diff --git a/leaf/annotations/episode_001274.json b/leaf/annotations/episode_001274.json new file mode 100644 index 0000000000000000000000000000000000000000..9ea08223bcefd4b716de8e2df70e6a0dbf7abb41 --- /dev/null +++ b/leaf/annotations/episode_001274.json @@ -0,0 +1,1845 @@ +{ + "schema": "leaf-replay-1", + "source": { + "batch": "ds41_s3", + "run": "ds41_s3-deepseek-v4.1-flash-codex-harness-hidek_l5_slippery_lift_s3002_full_F1_direct_k3_1029-230325_p19801", + "attempts_in_episode": [ + 1 + ], + "episode_in_run": 0, + "condition": "with_history", + "memory_free_chain_of": null, + "memory_free_rep": null, + "feedback_level": "F1", + "hide_k": true, + "k": 3, + "perception": "rgb", + "instruction_variant": "direct", + "contract_sha256": "79840ba4c3ca4c1c7f5b0d96bc6764b42000ddf029c616ec8a171de2bcd5ceaa", + "run_status": "done", + "manifest_id": "0026", + "replay": { + "n_reports_checked": 40, + "n_mismatch": 0, + "max_eef_dev_m": 0.0 + }, + "release_origin": { + "dataset": "v1.5", + "episode_index": 1274 + }, + "release_episode_index": 1274, + "pre_v181_sidecar_index": { + "episode_index": 107, + "dataset_index_range": [ + 216433, + 218344 + ] + } + }, + "agent": { + "harness": "codex", + "harness_version": "0.163.0", + "harness_binary_sha256": "399ff69c431c066e40de318fba45c2b07f45a76b19939d247ee4828fc70c4215", + "model": "deepseek-v4.1-flash", + "effort": "high", + "provider": "openai", + "codex_catalog": "generic", + "auth": "apikey", + "jail": true + }, + "task": { + "name": "l5_slippery_lift", + "level": "L5", + "family": "hidden_variable", + "category": "dynamics_adaptation", + "capabilities": [ + "Perceive", + "Reason", + "Utilize" + ], + "protocol": "cross", + "max_attempts": 5, + "agent_max_steps": 40, + "instruction": "Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at least 10 cm above the table. Keep holding it when you finish.", + "seed": 3002, + "instance": { + "seed": 3002, + "bar_xy": [ + -0.06434802829982841, + -0.009978970249213258 + ], + "com_offset": -0.0489081918780592, + "mass": 0.8641620125025791, + "mu": 0.5795455998526853 + }, + "paper": { + "name": "Slippery lift", + "cause": "L5", + "table_cause": "L5", + "hidden_variable": "Bar mass offset (2.5–7 cm)", + "repair_within_attempt": true, + "oracle_first_attempt_pct": "100", + "naive_first_attempt_pct": "0^", + "original_cause": "L5", + "original_table_cause": "L5" + }, + "canonical_cause": "L5", + "paper_long_horizon": false, + "instruction_original": "Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at least 10 cm above the table. Keep holding it when you finish." + }, + "run_outcome": { + "outcome_class": "IR", + "attempt_history": "S", + "n_attempts": 1, + "run_success": true, + "agent_final_report": "Attempt succeeded. Report:\n\n**What I did**\n- Mapped the scene from the fixed `agentview` and the wrist camera: the bar lies along the robot's `y` axis near `x≈0.59`, and it is thin (roughly 20 × 4 × 1.6 cm).\n- Rotated the gripper to the grasp yaw (`yaw=90`, reported as `-90`) so the fingers straddle the bar's 4 cm width, then centred it over the bar using the wrist image (bar centred at u≈255 ≈ grasp axis) and the agentview (gripper aligned with bar centre).\n- Descent and grip: `move_eef z=0.012 gripper=close` → the gripper stopped at `gripper_width_m=0.0411`, i.e. exactly on the bar's sides.\n- Final lift: a single fast `move_eef z=0.15` (default speed) from that low grasp pose, leaving the bar held with the eef at `(x=0.504, y=0.209, z=0.147)`.\n\n**What I observed**\n- Slow lifts made the bar pitch badly in the pinch (25–55° image tilt) — it rolled/slipped in the fingers, ending with the grip well off the bar's centre. Re-grasping with corrected `y` offsets did not fix it.\n- With the gripper centred (within ≈1 cm), fingers reaching to ≈2 mm above the table, and lifting quickly in one motion, the bar stayed nearly level (image slope ≈ −5…−7°, vs ≈0° for the same measurement with the bar flat on the table), with its lowest point ≈13 cm above the table.\n\n**How I changed approach**\n- Switched from slow, incremental lifts and y-offset tuning to an exact centre grasp at table level plus one fast lift, which avoided the progressive roll; then finished while still holding the bar.", + "mean_think_s": 42.54, + "outcome_class_original": "IR", + "outcome_class_status": "evidence_reviewed" + }, + "attempts": [ + { + "attempt": 1, + "success": true, + "outcome": { + "success": true, + "held": true, + "tilt_deg": -6.1, + "bottom_cm": 12.0, + "grasp_along": -0.031, + "failure": null, + "detail": "The bar is held level (tilt 6 degrees), 12 cm above the table. You grasped the bar 3.1 cm to the right (-y) of its midpoint.", + "detail_indirect": "The rod is held level (tilt 6 degrees), 12 cm above the table. You grasped the rod 3.1 cm to the right (-y) of its midpoint." + }, + "finish_reason": "bar grasped near its centre and lifted quickly to eef z=0.147, held roughly level", + "feedback_shown": "Attempt succeeded.", + "auto_ended": false, + "think_s": 22.120654344558716, + "feedback_f2": "Attempt succeeded. The bar is held level (tilt 6 degrees), 12 cm above the table. You grasped the bar 3.1 cm to the right (-y) of its midpoint.", + "judge_frames": [ + 1881, + 1911 + ], + "corrected_later_in_run": null, + "is_last_attempt_of_run": true, + "agent_finish": { + "reasoning": [ + "The bar is lifted and appears nearly LEVEL in the agentview! The bar spans (312,190)-(478,215) — a slight tilt but much better than before. The FAST lift helped! The wrist image also shows the bar's silhouette nearly symmetric (a vertical strip 182-330, roughly trapezoidal).\n\nThe budget is now 0 commands. The attempt should end automatically. But I didn't get a message saying so. The response still says ok with budget 0. The episode may end now.\n\nLet me measure the tilt from the final agentview image with a shell command (free of the robot budget, but tool calls are limited to 100; I've used ~50).\n\nThe bar's bbox in s040: let me compute the angle.\n\nActually from the image: the left end is at (312,192) and the right end at (478,215)? Looking at the image, the bar's top edge goes from (312,193) to (478,210)-ish → a slight downward slope → the bar is nearly level (maybe 4-6°).\n\nFor a level bar in this view (s000), the bar's top edge went from (162,291) to (337,293) with a ~0.7° slope. Now the slope is ~(215-190)/(478-312) = 25/166 = 8.6°... Hmm, borderline.\n\nLet me measure precisely.", + "The final agentview tilt: the PCA angle -5.0°, the top-edge slope -7.2°. The bar's surface slope in the image is ~-5 to -7°, and in the initial (truly level) state the same measurement gave ~0°. So the bar's tilt is ~5-7° — under the 8° threshold (hopefully, since the image angle is a lower bound/related measure).\n\nHmm, the image angle for a level bar was ~0.4°, and now it's 5-7°. The actual 3D tilt should be similar (the earlier images' angles correlated with the true tilts).\n\nThe bar is held at eef z=0.147, so its lowest point ≈0.147-0.016 = 0.131 > 0.10 ✓.\n\nThe budget is 0, so the attempt ends. But no \"episode over\" message came. The task says the attempt ends when the budget is used up, and the environment then checks the result. I should probably call `finish` now with a reason to end the attempt properly. But I have 0 commands left — would `finish` be rejected? The finish command probably isn't counted against the budget (it's not a motion). Let me try finish — it's the proper way to declare the hold.\n\nActually, the rules say \"An attempt ends when you run the robot command finish reason=... or when its budget is used up.\" Since my last command used the last one, the attempt may auto-end. But I haven't received a result. Let me call finish with a reason; if it's rejected, I'll report.\n\nLet me call finish." + ], + "shell": [ + "cd /opt/lffjail/work && timeout 50 python3 - <<'EOF'\nimport numpy as np, cv2\nfor n in ['s040']:\n im = cv2.imread(f'obs/{n}_agentview.jpg')\n B,G,R = im[:,:,0].astype(int),im[:,:,1].astype(int),im[:,:,2].astype(int)\n m = (B-R>=4)&(B>40)&(R<140)\n m[:175]=0\n ys,xs=np.nonzero(m)\n pts=np.stack([xs,ys],1).astype(np.float32)\n c=pts.mean(0); u,s,vt=np.linalg.svd(pts-c,full_matrices=False)\n d=vt[0]\n if d[0]<0: d=-d\n print(n,'angle',round(np.degrees(np.arctan2(d[1],d[0])),2),'c',c.round(1),'bbox',xs.min(),xs.max(),ys.min(),ys.max())\n # top edge: min y per column\n cols={}\n for x,y in zip(xs,ys):\n cols.setdefault(x,[]).append(y)\n xs_s=sorted(cols)\n tops=np.array([[x,min(cols[x])] for x in xs_s])\n # robust line fit on middle 60%\n n_=len(tops); sel=tops[int(n_*0.2):int(n_*0.8)]\n A=np.polyfit(sel[:,0],sel[:,1],1)\n print(' top-edge slope deg', round(np.degrees(np.arctan(A[0])),2))\nEOF" + ], + "viewed": [ + "obs/s040_agentview.jpg", + "obs/s040_wrist.jpg" + ], + "command": "finish reason=\"bar grasped near its centre and lifted quickly to eef z=0.147, held roughly level\"", + "reply": { + "feedback": "Attempt succeeded.", + "message": "The episode is over. Stop now and report." + } + }, + "error_event_in_attempt": null, + "reviewed_operational_failure": true + } + ], + "commands": [ + { + "attempt": 1, + "step": 1, + "kind": "move_eef", + "frame_start": 0, + "frame_end": 41, + "command": "move_eef z=0.35 yaw=90 gripper=open speed=0.2", + "args": { + "z": 0.35, + "yaw": 90, + "gripper": "open", + "speed": 0.2 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4495, + 0.0011, + 0.3481 + ], + "gripper_width_after": 0.0794, + "holding_after": false, + "touched_during": false, + "think_s": 52.5330913066864, + "agent_obs_images": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Let me start by looking at the scene.", + "The bar lies along x-axis? In agentview, the bar appears horizontal (left-right) in image, camera looking from front. eef_yaw is 0. The gripper fingers open along y direction presumably. The wrist camera shows bar horizontal too, meaning bar is perpendicular to gripper's closing direction? Hmm.\n\nThe gripper at eef_pos [0.4515, 0, 0.2613]. The agentview shows the gripper near the top center at roughly x? Camera fixed. Bar appears around image y=290-325, gripper at y=130-170.\n\nLet me get the state and analyze geometry. I need to know where the bar is in world coordinates. Let's use observations. I need camera calibration... not given. Let's estimate: bar is on table at z ≈ bar half height. Bar looks like a box ~0.2 m long, 0.04 wide, 0.04 tall maybe.\n\nIn agentview, bar spans x pixels ~160-335, center ~247. Image center 256. The gripper appears at x~250 and at high z. So likely bar is at x≈? eef x=0.4515 at image center. Hmm, camera looks at table from above-front.\n\nApproach: move eef in xy to over the bar, descend, close gripper. But I need bar position. Simpler: the bar looks aligned along image horizontal, which corresponds to robot y axis probably if camera faces along -x? Actually camera at front looking toward robot. eef yaw 0 means fingers... Let me deduce: In wrist camera, bar is horizontal, spanning image width, and gripper fingers appear at bottom left/right. So the fingers close along the horizontal image axis which is perpendicular to the bar's long axis. That means the gripper closing direction is perpendicular to bar long axis — which is bad for grasping; to grasp a bar you want fingers to close across the width, i.e., fingers on either side of the bar, closing direction perpendicular to the long axis... wait. A two-finger parallel gripper grasping a bar: fingers approach from both sides of the bar, closing across either the width or the length. To hold a bar level, you'd grasp across the width so the long axis is perpendicular... Actually if you grasp across the width, the fingers contact the long side faces, and the bar extends out both sides of the gripper. That's fine. The gripper closing direction is perpendicular to the bar's long axis. In wrist view, fingers at left and right of image with gap in middle, bar spans horizontally. Hmm, the fingers shown in wrist view are at the bottom, left and right, appearing as two dark pads facing each other. The closing direction is horizontal. The bar above is horizontal, meaning the bar long axis is parallel to closing direction — bad grasp (fingers would hit endpoints, or grasp along length maybe).\n\nWait, but eef yaw=0. Maybe the bar long axis lies along y (robot), and the gripper closing direction is along y as well when yaw=0. Then I should rotate yaw 90 to align fingers across bar width.\n\nLet me look more carefully. In the wrist image, the two finger pads are the grey rectangles at bottom center-left (~155,415) and center-right (~345,415). So closing direction is horizontal in image. In agentview, bar spans horizontal too. If wrist camera is mounted on gripper looking forward-down, its image horizontal likely corresponds to gripper yaw direction. Hmm.\n\nBetter: use the agentview image plus geometry. The camera view: gripper at eef pos x=0.4515. The bar in agentview is at image center x~247, similar to gripper x~250. So the bar's center is roughly at same lateral position as the gripper. The gripper is near the robot base (front of the image top). Camera \"agentview\" is fixed, looking at table. Bar appears lower in image (further from robot, larger x?). Typically in these sims (Robosuite), agentview camera is at front (negative x looking toward +x). Robot base at x=0, eef at x=0.45 extends toward the camera... Hmm, actually in Robosuite Panda, robot base at origin, arm extends forward in +x, and camera at front-right. The bar at image lower area could be at larger x (further from robot).\n\nActually in the agentview image, the robot arm comes from top, and the bar is below center. The bar is likely farther from base (larger x) than the arm currently at x=0.45. Wait the arm at x=0.45 with z=0.26 appears at the top of the image; bar at image center-bottom might be x≈0.55-0.6.\n\nHmm, but uncertainty. Let's just take an observe/controlled move: first move eef to hover above approximate bar position, using small moves and check images. Also I can potentially use the state json only for eef.\n\nAlternative approach: use image analysis to locate bar precisely by moving the eef? That's expensive.\n\nLet's think about typical setup: table height 0.8? eef z 0.26? Hmm in robosuite coordinates, table surface z≈0.8m for Panda. But here base frame maybe different, table at z=0? eef z=0.26 suggests meters above table with table at 0. Fine.\n\nMaybe the scene is generated by this \"lff\" environment: bar on table, robot at side.\n\nLet's just do a small experiment: move eef to x smaller/larger and see image movement to calibrate. But commands are valuable (40). Also sim time 120s.\n\nI'd guess bar is along y axis (since wrist view shows bar horizontal while yaw=0 fingers close horizontally in image → image horizontal = gripper y direction). Wait in wrist image, if fingers close along gripper's local y (when yaw=0, robot y axis), then image horizontal = robot y. Bar spans horizontal in wrist image = along robot y. And in agentview bar horizontal too, consistent with camera looking along x.\n\nSo bar long axis along y. Gripper closing direction along y too → parallel. Bad. Need yaw=90 so closing along x? Wait, no: if I yaw 90, fingers close along robot x, gripping the bar's long sides? Grasping a bar along its length (fingers at front/back faces) is bad—the bar is 0.2 long, gripper opening max ~0.08. Fingers would just be at the ends? Actually the bar width across is ~0.04, length 0.2. To grasp across width, fingers must be on the two long faces, which are separated by 0.04 along the short axis. The short axis is along robot x if long axis is y. So closing direction should be along x → yaw=90.\n\nHold on: when yaw=0, which direction do fingers close? For Panda gripper in robosuite, gripper yaw 0 means fingers open along y axis. I think yes: default Panda gripper fingers move along y. So yaw=90 makes them move along x. Then to grasp bar (long axis y), close along x, yaw=90. Yes.\n\nBut wait the wrist camera image: with yaw=0, wearing camera, image horizontal corresponds to... the camera looks down and forward. Hard to say. Let me test with an observe at different yaw and see.\n\nPlan: Move eef up/away to a safe height, yaw=90, then position above bar. Let me first do a move to yaw=90 at current position and observe to confirm orientation relationship.\n\nActually more importantly, find the bar position. Let me use image pixel → world mapping by moving. Strategy: move eef laterally by known amount and see how much image shifts? Eef itself is visible in agentview. Cheaper: I can compute from known geometry: bar is a box; shadow etc. Not enough.\n\nAlternative: Use wrist camera which is directly above. Move eef over where I think bar is, look at wrist image, adjust.\n\nRough estimate: eef x=0.4515, z=0.2613. In agentview, gripper pads bottom at pixel ~170. Bar top at pixel ~290. Camera perspective. The table horizon at ~y=180? The table surface fills bottom. Hmm, the top region (y<180) is grey wall. Fingers at y~130-170, i.e., in front of the wall, meaning the gripper is far from camera? No...\n\nLet me just move down to z=0.05 at the current x,y and see the wrist image—if the bar is under the gripper, the wrist view shows it up close. But current wrist view already shows the bar fairly close (looks ~30cm away?). The wrist image shows the bar at top of image, so bar is in front of the wrist camera by quite a distance.\n\nLet me estimate from wrist view: bar width in image 280 px of 512. FOV of wrist camera maybe 75°? The bar appears 0.2 m wide... hmm.\n\nLet me do a controlled move: lower z to 0.15 at current xy and check images. That tells vertical relations. Actually simplest: move toward bar center in x: I'll guess bar center is at x≈0.55, y≈0.0 (aligned with gripper laterally), z top ≈0.04.\n\nLet me check the state file for table height info maybe. Let's read the json and also maybe there's a scene file? Check workspace.", + "Let me calibrate the camera. I'll make a move that changes x and y known amounts and observe. But moves cost sim time. Alternatively, use both images and known eef position at step 0 to bootstrap.\n\nEstimate agentview camera: In robosuite-style, agentview at (1.0, 0, 1.45)? Actually default robosuite agentview: pos (1, 0, 1.45)? Hmm. The bar is in view near the bottom center, gripper at top center.\n\nLet's think in terms of image: robot base presumably behind top edge of image (the grey wall is background). The bar lies at the table. If the camera is at approx (0.9, 0, 1.9) looking down at table center... then larger x (farther forward) = up in image? The gripper at x=0.45 appears at top, bar at bottom center → bar x < 0.45?? That seems weird—bar would be closer to camera.\n\nHmm wait, if camera is in front looking backward at the robot (like robosuite agentview from front), larger x (toward camera) = down in image. Gripper at x=0.45 is at top → that doesn't fit if camera is at x=1.2.\n\nIn robosuite, the standard agentview camera is at the front-upper area, looking at the robot. Actually default \"agentview\" position is (0.?, ...). Let me recall: robosuite default camera \"agentview\" pos ~ (1.0, 0, 1.45), quat looking toward (0,0,0.8)? Hmm the table is at z=0.8 in robosuite and bar at z~0.82. Robot base z=0. In that frame, table at 0.8, eef z=1.06. Here eef z=0.26 and table top unknown (~0.02?). So this env rebased z so table near 0.\n\nKey mapping in agentview (camera at +x, elevated, looking toward -x and down): image up = farther -x? Let's compute: camera at (cx,0,cz), looking at origin-ish. A point at larger x is closer/lower in image. So gripper x=0.45 might appear lower than the bar... but observed opposite. Unless camera is at -x.\n\nAlternatively the bar is at y offset. In agentview the bar center x pixel ~247 vs gripper ~250, so y ~ 0. Fine.\n\nRather than guessing, calibrate: move eef by +0.1 in x and see how its image position changes in agentview, and how bar position relative. But actually better: use wrist camera: it views from gripper. Move eef laterally over the bar until bar appears centered in wrist view. That's an iterative visual servo. That's robust and only needs a few moves.\n\nSteps:\n1. Raise z to 0.35 (safe), yaw rotate 90 (need to check that yaw=90 is right grasp orientation; verify with wrist view and by checking bar appearance).\n2. Move in x toward bar, observe wrist.\n\nWait: does yaw rotation change the wrist camera orientation? Yes, camera rotates with gripper, so bar appearance rotates 90° in the wrist image. That's a good confirmation of geometry.\n\nLet me first do move yaw=90 at z=0.35 (safe height), observe. Actually keep x,y current. Then inspect agentview/wrist.\n\nHmm, but a possible risk: yaw rotation at 0.26 height is fine.\n\nAlso note gripper width 0.0411 already, fingers partly closed? Bar width maybe 0.04. Gripper full open is ~0.08.\n\nLet me perform: move_eef z=0.35 yaw=90 gripper=open speed=0.2." + ], + "shell": [ + "ls -la; cat obs/a1_s000_state.json; ls obs", + "cat README.md" + ], + "viewed": [ + "obs/s000_agentview.jpg", + "obs/s000_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 2, + "kind": "move_eef", + "frame_start": 41, + "frame_end": 76, + "command": "move_eef x=0.38 y=0.0 z=0.15 yaw=90 gripper=open speed=0.3", + "args": { + "x": 0.38, + "y": 0.0, + "z": 0.15, + "yaw": 90, + "gripper": "open", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3772, + 0.0002, + 0.1483 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 27.45784616470337, + "agent_obs_images": [ + "obs/s002_agentview.jpg", + "obs/s002_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Yaw reported -90 when I asked 90. So yaw sign flips: requesting yaw=90 gives -90. Fine, orientation is what matters (probably equivalent? no, -90 vs +90 are different: fingers along x either way, symmetric).\n\nView images.", + "Now with yaw=-90 (requested 90), the wrist view shows the bar vertical (along image vertical), and the gripper jaw at the right side of image. Fingers still appear left/right at bottom? The finger pads at bottom-left (~110,415) and bottom-right (~310,415)? Actually the wrist camera view shows a jaw at right (x~480) which might be a finger. Hmm.\n\nThe bar rotated 90° in the wrist image compared to before → so wrist image rotates with yaw as expected. Bar long axis along world y.\n\nNow in wrist view, the bar appears vertical in image, at left side (x~115-165), and gripper jaw at right edge. So the wrist camera is offset, looking down with the bar to the left and ahead.\n\nI need to figure out the mapping from wrist image to world to servo. Let's instead calibrate agentview: bar in agentview appears at same pixel location in both steps (bar static). Its width 160 px.\n\nI need world coords of the bar. Let's calibrate the agentview camera using the gripper as a marker: We had eef at (0.4515, 0, 0.2613) at pixel ~(250,150) and now (0.4495,0.0011,0.3481) at pixel ~(250,120)? The gripper moved up 0.087 m and image moved up ~30px. Not enough info for x mapping.\n\nBetter: do a deliberate x sweep and observe. That costs commands but it's the reliable path. Alternatively use wrist view: I can move in y until the bar is centered under the camera. The wrist camera likely points down-forward; the grasp point is below the camera center. Actually the wrist camera is mounted on the gripper looking down at the grasp region—typically the grasp point is near image center bottom. Bar appearing at left means bar is to the left.\n\nWhich world direction is \"left\" in wrist image with yaw=-90? With yaw=0, image left-right = robot y? At yaw=0 the bar was horizontal (along y) and now vertical, confirming image rotation tracks yaw. With yaw=-90, robot y maps to image vertical, and robot x maps to image horizontal.\n\nWhich sign? Camera model: at yaw=0, bar spans image horizontally. The bar at y from -0.1 to +0.1 appears from left to right? If camera up-vector ~ world +x?? Hmm. When camera yaws by -90 (about z), what was pointing along +x in image now points along... Let's define camera image right vector r0 at yaw 0. Bar along y maps to horizontal → r0 = ±y. After yaw -90 rotation: r = Rz(-90) r0. If r0=+y, r=Rz(-90)(0,1,0)=(1,0,0)... Rz(θ)=[cos -sin; sin cos]. Rz(-90)(0,1,0)=(0*0+(-1)*1? compute: x' = cos(-90)*0 - sin(-90)*1 = 1; y' = sin(-90)*0+cos(-90)*1=0 → (1,0,0)=+x. So image right = +x, image up = +y? Camera up vector u0 at yaw 0 = -x or +x (looking down-ish). Anyway: bar vertical now, with its \"y-extent\" mapped to vertical.\n\nBar's long axis is y. In yaw=-90 image, the bar goes from bottom (y~370 px) to top (y~160 px). Which end corresponds to +y? Unknown sign, need mapping.\n\nIn the image, bar at pixel x~115-165, i.e., left of center (256). If image right = +x, then the bar is at x < eef x → bar x maybe ~0.3? Hmm, but wait the bar also appears offset upward/left due to camera perspective (camera looks slightly forward/down, so the grasp point is not at image center).\n\nThe bar appears at left in wrist image, meaning bar is at smaller x than gripper (if image right=+x). And gripper jaw visible at right edge → jaw at larger x. Hmm, the wrist camera is mounted behind the fingers? \n\nDistance: bar appears ~50px wide on its short side (0.04 m) — 512px across ~? FOV estimate: if 0.04 m → 50 px, then 512 px ≈ 0.41 m at that depth. That's plausible with a few hundred mm distance.\n\nHmm, let me reconsider. Maybe camera up = -x at yaw0, so image up = -x; then image right = +y for a right-handed image (camera z toward scene = down). Camera looks down (-z). For image with up=u and right=r, r × u = -z (pointing toward viewer = +z). Hmm, let's do: camera optical axis o = -z. right × up = -o = +z. If r=+y, u=? y × u = +z → u = -x? (y × (-x) = -(y×x)=+z ✓). So at yaw0: right=+y, up=-x. This is a camera looking down with image up toward -x. Then in agentview... whatever.\n\nThen at yaw=-90: right = Rz(-90)(+y) = +x; up = Rz(-90)(-x) = ? Rz(-90)(-1,0,0) = (cos(-90)*(-1) - sin(-90)*0, sin(-90)*(-1)+cos(-90)*0,0) = (0, 1, 0) = +y. So image up = +y, right = +x.\n\nBar in wrist image spans vertical from y_pix 160 (top) to 370 (bottom). So bottom = -y, top=+y. Bar center at y_pix~265 ≈ image vertical center 256, but camera looks at a point forward of grasp... hmm actually the grasp point should be at image center-ish. Bar appears centered vertically, meaning bar center y ≈ eef y ≈ 0. Good, consistent with agentview (bar laterally centered). And bar at image x ~140 (left of center 256) → bar x = eef_x - offset. Pixel scale ~0.41m/512 ≈ 0.0008 m/px → offset 106 px ≈ 0.085 m? Also camera tilt means mapping isn't linear in the up direction but in x direction it is lateral.\n\nBut wait, the short-side width of bar in the image: measured earlier in wrist (bar vertical) as ~48 px (115→165). If bar is 0.04 m, scale 0.00083 m/px. Then lateral offset 106 px → 0.088 m in x. So bar center x ≈ 0.45 - 0.088 = 0.36? Hmm but the camera also is tilted forward so the bar appears shifted. Uncertain.\n\nAlso the bar's long-side (0.2m) spans ~210 px vertically → 0.2/210=0.00095 m/px, consistent.\n\nHmm wait, but is image up really +x at yaw0? Let's double check with agentview: agentview is a separate fixed camera. Not relevant.\n\nLet me test the wrist mapping empirically with a small move in x and see the bar move in the image. E.g., move x by +0.05 (to 0.50) and see if bar moves left (if image right=+x, then increasing eef x while bar fixed moves bar left). Let me also move y slightly? Do one test with x=0.40 (-0.05) and y=0.05, and observe wrist image shifts. Cost is fine (39 commands left).\n\nActually let's be smart: move down to z=0.10 while moving x=0.38, y=0 to get closer over the bar and get a better wrist view. If bar is at x~0.36 maybe. But risky collision? Bar top maybe at z~0.04-0.05. z=0.10 with 1cm above grasp point... grasp point = fingertips+0.01. So z=0.10 is safe above a 0.05 bar.\n\nLet me do a test move: x=0.40, y=0.00, z=0.15, yaw=90(gives -90), gripper=open. Then look." + ], + "viewed": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 3, + "kind": "move_eef", + "frame_start": 76, + "frame_end": 104, + "command": "move_eef x=0.45 y=0.0 z=0.3 yaw=90 gripper=open speed=0.3", + "args": { + "x": 0.45, + "y": 0.0, + "z": 0.3, + "yaw": 90, + "gripper": "open", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4501, + 0.0, + 0.2988 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 27.652035236358643, + "agent_obs_images": [ + "obs/s003_agentview.jpg", + "obs/s003_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Now the wrist view no longer shows the bar (bar out of view, likely to the right or left behind). Hmm the wrist view now shows just wood table and fingers at bottom. The bar disappeared — meaning it's outside the field of view. With eef moved -0.07 in x, the bar should move in image if visible. It vanished because bar is now too close/behind?\n\nLet me check agentview to see where the gripper is relative to the bar: gripper appears still at top, slight shift. Bar unchanged at pixel same. Hmm, agentview doesn't help much because depth compression.\n\nLet's compute from agentview calibration using the gripper tips move: at s000 (eef z=0.2613, x=0.4515) gripper bottom ~y_pix 172; now z=0.1483, x=0.3772, gripper bottom ~y_pix 185. Small changes.\n\nLet me instead reason about wrist view geometry properly. In s001 wrist image (eef at x=0.4495, z=0.3481), the bar appeared at image x~115-165. In s002 (x=0.3772, z=0.1483) the bar is not visible at all. If the bar (x~0.36?) were at the same x as eef, it would be centered below. Instead it's gone, suggesting the bar is at larger x than the eef now and probably out of view to the right? Or the camera is so close that the bar is out of the frame (too close to the camera).\n\nActually at z=0.1483, the wrist camera is ~10cm above table, and bar is 0.2m long × 0.04 wide. If directly under, it would fill the view. The view shows clear table → bar is not under it, it's off to the side, outside FOV.\n\nHmm. The wrist camera on Panda in robosuite is mounted on the wrist pointing down and slightly forward. Its center view is roughly in front of the gripper (toward -x? or +x?).\n\nLet me use agentview for x calibration via the bar's shadow/parallax? Alternative better approach: use the agentview gripper position at two known x values and its pixel position. At s000 x=0.4515, the fingers located around y_pix 165; at s002 x=0.3772, y_pix 185. So decreasing x by 0.074 moved image down 20px. So larger x → up in image. So the bar at image y ~290-325 vs gripper at x=0.3772 → y~185 means bar is at smaller x than 0.377? That can't be; bar must be in front of the robot (positive x, reachable). Hmm, actually with perspective, the table plane at lower z appears lower in image for close points.\n\nCamera is probably at high z looking down-forward. Points on the table at smaller x (closer to base) appear lower? Hmm.\n\nLet's just calibrate properly with a second x move and using the gripper position in agentview, plus using the bar pixel fixed. I can estimate the homography of the table plane: image points of the table map to world (x,y). I have gripper points at known (x,y,z) but they're not on the table, so not directly usable without camera intrinsics/extrinsics.\n\nAlternative: There's likely a known simulation: this looks like robosuite \"Lift\"-ish scene but custom task. The table is at z≈0.0 (bar sitting with height maybe 0.04-0.05). Camera \"agentview\" pos in robosuite: default camera for \"agentview\" in robosuite is computed by camera_utils. Let me recall robosuite Panda default: table at z=0.8, robot base at z=0? Hmm. In this env z rebased so that table top ≈ 0? eef z 0.26 above → fine.\n\nHonestly, the simplest robust approach: servo using the wrist camera in small steps, since we can view. Do a move that puts eef near the bar based on a hypothesis, then correct.\n\nFrom s001: bar left of center in wrist view. But which way is \"left\" in world? Test empirically: from s000 to s001 we rotated the gripper but also bar appeared rotated. Now from s001 (x=0.4495,z=0.348) to s002 (x=0.377, z=0.148): the bar moved out of view. If image right=+x, then bar (world fixed) moving relative: eef x decreased by 0.072 → bar moves right by 0.072/0.0009 ≈ 80 px. From x~140 to ~220 — should still be visible! But it's not. And z dropped 0.2 which re-scales massively (camera closer to table). Not conclusive.\n\nAlternative: from s001 wrist view, the bar at z difference: eef z=0.348 → bar top 0.04, distance ~0.30 m. scale 0.0009 m/px → FOV 0.46m. Then bar x = 0.4495 - 0.09*? Hmm but the wrist camera is angled.\n\nLet me test empirically: move eef in +y direction by 0.08 and see which way the bar moves in wrist image. At z=0.30 to keep wide view. Also test x separately. Two commands, fine.\n\nActually let's be smarter — use agentview and detect the gripper in images via pixel analysis? The gripper is white/grey; measurable.\n\nPlan: use agentview calibrated by moving eef to known positions and observing the gripper pixel. But that gives 2D projection of a 3D point at unknown camera pose — 2 observations give limited info. But I can do a homography: the *gripper tip* is a 3D point; not on table.\n\nBetter: use the shadow? Meh.\n\nAlternative idea: the wrist-camera servo. Move eef laterally until the bar is centered in wrist image, then descend. This is a visual servoing loop that works regardless of geometry, as long as I can identify which direction to move. Do test moves and observe sign.\n\nLet's do: move to z=0.30, x=0.45, y=0.0, then move y=0.08 at same z and see the bar shift in wrist view. Then return.\n\nActually, maybe a much better strategy: instead of grasping the bar with the gripper perpendicular, I could rely on the fact that we know it's at y=0 and estimate x via the wrist image when the eef is at x=0.45,z=0.30: bar appeared at image left, roughly 106px, with image right=+x → bar x ≈ 0.45-0.09 = 0.36.\n\nBut is image right = +x? Let me verify with the rotation test: at yaw=0 (s000), the bar in wrist image spans horizontally and the fingers pads were at bottom left/right; the bar was parallel to closing direction. At yaw=-90 (s001) bar vertical. The camera rotates with the wrist. Fine, consistent.\n\nFor sign: at yaw=0, if the bar appears in image from left to right corresponding to y from -0.1 to +0.1 or the reverse, doesn't matter for x.\n\nTo find image-right vector at yaw=-90 we need to know image-right at yaw=0 and how yaw changes it. The commanded yaw=90 → actual -90. So the world rotation applied is Rz(-90). The camera's image-right vector rotates with the wrist: r_new = Rz(-90) r_old. If r_old = +y, r_new = ... computed earlier = +x. If r_old = -y, then r_new = -x. So it's ±x, ambiguous still.\n\nI'll just test. Move x by +0.08 at z=0.30 and observe wrist bar pixel shift. Let me do it: move x=0.45, y=0, z=0.30, yaw stays -90, gripper open.\n\nActually I could combine: do this move and look. Then decide." + ], + "viewed": [ + "obs/s002_agentview.jpg", + "obs/s002_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 4, + "kind": "move_eef", + "frame_start": 104, + "frame_end": 136, + "command": "move_eef x=0.35 y=0.0 z=0.3 yaw=90 gripper=open speed=0.3", + "args": { + "x": 0.35, + "y": 0.0, + "z": 0.3, + "yaw": 90, + "gripper": "open", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.348, + 0.0001, + 0.2982 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 18.036055088043213, + "agent_obs_images": [ + "obs/s004_agentview.jpg", + "obs/s004_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "s003 wrist: bar spans y_pix ~150 to ~395, x_pix ~105-155. So bar left edge ~105, right ~155 including side face. The bar's near-vertical silhouette: top face is light (x 105-140), side dark (140-155). So the bar center ~x_pix 125. Compared to s001 (x=0.4495, z=0.348): bar x_pix 115-165 (light top ~115-145, side dark ~145-165) center ~130. Basically same position despite z change 0.35→0.30 (scaling). Consistent.\n\nSo bar is at image left, center ~125 px, 131 px left of center. If image right = +x, then bar at x < eef. Hmm.\n\nNow let's do the empirical test: move y +0.06 and see which way the bar moves. But maybe better: use agentview plus knowledge that bar's y=0.\n\nActually, let me use a different trick: the arm base is at origin. The bar must be reachable, x likely around 0.4-0.6. Since the bar's apparent width (short side) at s003 is ~50 px and long side 245 px with 0.2 m long → scale 0.00082 → short side 0.041 m. Good, so 512 px = 0.42 m FOV at ~0.30 m distance (vertical distance). That's a wide FOV (~70°).\n\nThe bar center is 131 px left of image center = 0.107 m. If wrist camera is at eef pos and pointing straight down, bar x = 0.45 - 0.107 = 0.343 (if right=+x) or 0.45+0.107=0.557 (if right=-x). But the camera may be tilted, and the image center maps to a point offset from eef.\n\nHmm! Important: In the wrist image, the fingers appear at bottom at x~110 and ~310 (i.e., centered at ~210, not 256). The two jaws are symmetric about the grasp line; their image midpoint should be the grasp point (eef xy). That midpoint is ~210 px, i.e., 46 px left of image center at this depth (0.3m) — the camera is tilted/offset. Hmm, the fingers are much closer to camera (a few cm) so their perspective center differs. Hard.\n\nWay better: don't rely on camera. Use the agentview + a classic approach: the gripper fingers are visible in agentview when lowering, and I can see if the bar is under them.\n\nActually, let's use the wrist view relative motion test — cheap and decisive. Move y by +0.08 and see the bar's image x shift.\n\nAt yaw=-90, if bar's long axis (y) maps to image vertical, then moving in y shifts bar vertically, not horizontally. So to determine the x sign I should move x and observe horizontal shift. From s003 to another x, e.g. x=0.55. If bar shifts further right (large px), then bar x even further from eef... Let's just do x=0.55, z=0.30 and check: if image right = +x, bar at 0.45 (fixed) with eef moving +0.10 → bar moves left by ~0.10/0.00082=122 px → off-screen left (125-122 ≈ 3). If image right = -x, bar moves right to ~247 — visible near center-left.\n\nWait but careful: as the arm moves in x, the wrist camera also changes position and tilt, and it's mounted on the arm; the tilt direction would change slightly as the arm extends. But roughly.\n\nAlternatively move x to 0.35: if right=+x, bar at 0.45→ relative +0.10 → shifts right by 122 → 247 (visible). If right=-x, shifts left → off-screen.\n\nTwo possibilities; either move tests one direction. Do x=0.35, z=0.30. If bar visible near center → right=+x meaning bar x ≈0.45-0.107=0.343 (using s003 constant)?? Wait that's contradictory: if at eef x=0.35 the bar's true x equals eef x, then the bar would appear at the camera's optical center offset (the offset seen with eef), i.e. where the grasp point appears (~210px). So visible around x_pix 210 if bar x=0.35 and right=+x. Good test.\n\nLet me do it." + ], + "viewed": [ + "obs/s003_wrist.jpg", + "obs/s003_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 5, + "kind": "move_eef", + "frame_start": 136, + "frame_end": 174, + "command": "move_eef x=0.55 y=0.0 z=0.2 yaw=90 gripper=open speed=0.3", + "args": { + "x": 0.55, + "y": 0.0, + "z": 0.2, + "yaw": 90, + "gripper": "open", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5532, + 0.0, + 0.2024 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 38.51471948623657, + "agent_obs_images": [ + "obs/s005_agentview.jpg", + "obs/s005_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "At x=0.348 the bar is still at the far left (x_pix ~10-65), even further left. So moving eef -0.10 in x moved the bar left by ~95 px → image right = +x. Wait: eef moved -0.102 x, bar image moved from ~125 to ~35, i.e., -90 px. So bar moved left when eef moved left → image right = +x. Yes.\n\nSo the bar is to the LEFT meaning bar x < eef x. And earlier estimate: bar x ≈ 0.343 at eef 0.45 → so bar x ≈ 0.34? But at eef x=0.348, bar is still 200 px left → bar x ≈ 0.348 - 200*0.00082 = 0.184?! Hmm, that's inconsistent with a constant scale—because at eef x=0.348 the camera is at a different pose (the arm is bent back, maybe tilted).\n\nWait, also the image shows the robot's own wrist/arm at right edge (dark structure) — that's the arm, meaning the camera is near the arm.\n\nThe nonlinearity suggests the wrist camera's optical axis tilts as the arm bends. The image center is not eef xy.\n\nLet's use the agentview now for guidance. Compare s003 vs s004 agentview: the gripper position changes only slightly (x 0.45→0.35 appears similar at top?). Actually the gripper in agentview at s004 seems slightly lower and maybe shifted right? Bar unchanged as expected.\n\nThe agentview camera appears nearly fixed; the projection of the gripper barely changes with x because the camera looks along x (perspective). Hmm.\n\nOK, the wrist servo is still workable: iterate to move the bar toward the image center. But the mapping changes with arm pose. Alternative: use a proper approach — get the actual camera intrinsics/extrinsics? Not available.\n\nAlternative reliable geometric approach: use the agentview to determine the bar's world position by measuring its size and using a pinhole camera model calibrated from the gripper's known positions. Complicated but doable: I have several (3D eef point, 2D pixel) correspondences... but eef point 3D visible position is approximate.\n\nHmm, what about a totally different robust strategy: \"sweep and feel\" — use joint feedback? Not available for external objects.\n\nBetter strategy: descend with the gripper closed-ish? No.\n\nAlternative: approach the bar from the side along y? Actually here's a thought: the bar is long along y (0.2 m) and thin. Grasping: we should close the fingers across x-direction (yaw ±90). Since the bar is long in y, the gripper must be centered in y (y=0) and at bar center in x, then close.\n\nActually a very robust trick: the bar is thin (0.04 wide). Approach with the gripper OPEN and at yaw=0 (fingers along y, i.e., closing along y). At yaw=0, the fingers close along y; the bar extends along y, so we'd hit the bar's ends? No — the fingers would come down at y=±0.04 straddling the bar's long axis?? Wait with yaw=0 fingers at y = ±0.04, x=bar center. Fingers descend and land on either side along the bar's LENGTH direction, but at x = bar center, that's right on top of the bar's top face for the finger positions? The fingers' pads at y=±0.04, x at bar center: the bar occupies x ∈ [c-0.02, c+0.02], y ∈ [-0.1, 0.1]. Fingers at (±0.04 in y, x=c) are above the bar top → collision. Then closing along y would squeeze along the length? No, closing brings fingers to y=0 which is inside the bar → they'd grip the bar's long sides? Hmm no: finger pads move in y, and the bar's material at x=c exists for all y in [-0.1,0.1]. Closing would just crush into the bar from the ends (0.1m apart), not grip the width.\n\nRight — need yaw=90 (fingers close along x at y=0): pads at x = c±0.04 straddling the bar's width. Perfect.\n\nSo I need: eef at (bar_x, 0, z_grasp) with yaw=-90, fingers open, descend so pads straddle bar (pad inner faces at ±0.04, bar half-width 0.02 → 2 cm clearance each side). Good tolerance in x of ±2cm-ish (actually need |dx| < 0.02+... fingers can close to contact; if dx too big, one finger pushes bar sideways).\n\nThen close gripper to width < 0.04 and lift. The grasp: fingers contact bar's side faces at ±0.02 in x. Grasp point eef at bar center.\n\nAlso y must be within ±(0.1 - finger thickness?) → y within ~0.08.\n\nThe tricky part is finding bar_x. From wrist images we know bar x < eef x, distance maybe 0.1. Let's do a descent test: at x=0.348, y=0, descend to z=0.12 and check wrist image; if the bar is still far left, the bar might be around x=0.25? Hmm, wait—maybe the mapping \"image right=+x\" is wrong! Let's re-derive with the physical constraint: bar must be at reachable x, likely 0.3-0.6. If image right = -x, then bar x > eef x, i.e., bar x ≈ 0.45+0.1 = 0.55 from s003, and at eef x=0.348, bar at 0.55 - 0.348 = 0.2 away → 244 px... but observed 200 px at same left position, ~-0.16m. Hmm depending on scale (which changes with pose), both are plausible.\n\nBut the observed shift: eef moved -0.102, bar pixel moved -90 (left). If bar fixed and image right=+x, bar should shift right (+122 px), not left. So image right=+x is WRONG! Let's recompute: if image right = -x, moving eef left by 0.102 means the bar's relative position moves +0.102 in x → in image, moving right by -0.102/scale... \n\nLet me be careful: image coordinate u rightwards. If image right = +x (u increases with world x), and eef moves -0.102, then the bar (fixed world x) has larger x than eef → bar appears more to the right: u increases. Observed u decreased (125→35). Contradiction. So image right = -x, meaning u increases as world x decreases. Then bar at x > eef.\n\nWith image right = -x: at s003 eef x=0.450, bar center u=125 → 131 px left → world x larger by 131*scale. At s003 scale ~0.00082 → bar x ≈ 0.450 + 0.107 = 0.557. Hmm, but as the arm extends forward, the wrist camera tilt changes; still, ~0.55.\n\nAt s004 eef x=0.348, bar u≈35 (200 px left) → bar x ≈ 0.348+200*s. If s at s004 ~0.0011 (image bar long side 0.2 spans? In s004 the bar looks shorter vertically and partially cut at bottom... it spans y 150-400, that's 250 px for a foreshortened bar. Hmm.\n\nNotice the bar's apparent size didn't change much but its position did. If bar x ≈ 0.55 and eef at 0.348, the horizontal offset is 0.2 m → 200 px at scale 0.001 → OK consistent-ish.\n\nSo bar x ≈ 0.55-0.56? But wait, then in the agentview, is the bar at x 0.55 (further from base)? The agentview gripper appeared above the bar in the image at similar lateral but bar lower down in the image. If camera is in front at high z, larger x = closer = lower in image. Then the bar at x=0.55 appearing lower than the gripper at x=0.45 makes sense! Great, consistent. So bar x ≈ 0.55, bar center y=0.\n\nHmm wait, but check agentview: gripper at x=0.45 z=0.3 pixel y~170 (in front of wall, above horizon). Bar at y~290. Larger x (bottom of image) - yes, x=0.55 bar. Plausible.\n\nHmm, but this is odd: most tasks place the object in front of the robot. x=0.55 with base at origin is a normal reach distance for Panda (0.4-0.7). And the initial eef x=0.45 was hovering a bit closer. Fine.\n\nBut careful with the sign: maybe the eef x shift also caused the arm configuration change which changed the camera's direction (the wrist camera on the Panda rotates with the wrist joint — robot kinematic: the camera is attached to the hand, and moving x at fixed z bends the arm, changing wrist orientation? The hand orientation is kept fixed by IK (yaw fixed, and presumably pitch fixed), so camera orientation stays roughly down. Mostly translation. So the shift should be about -0.1 in world x... which by image right=-x gives +100px right. Contradiction again!\n\nUgh. Let me redo the arithmetic. Suppose image right vector = +x (u increases with x). Eef moves from x=0.45 to 0.348 (-0.102). Camera moves with eef. Object fixed at x=0.557. Its position relative to camera in x: initially 0.557-0.45=0.107 (to the +x side, right of camera) → appears at u>center. Observed u=125 < 256. So object appears LEFT while being on the +x side → image right = -x. ✓.\n\nAfter move, object relative x: 0.557-0.348=0.209 on +x side → appears further left. Observed more left ✓. So both consistent: image right = -x, bar x ≈ 0.55.\n\nWas my earlier \"s000→s002\" observation (decreasing x moved gripper down in agentview) consistent? Agentview: camera in front looking back. If camera at x=1.1, larger x → closer → lower in image. Moving eef from 0.4515 to 0.3772 (away) → up in image. But I observed the gripper moved DOWN (165→185). Hmm contradiction. But agentview gripper pixel measurement is unreliable because the arm's pose changed (elbow position visible). Let me recheck s000 vs s004 agentview: In s000 the gripper bottom edge ~ y=172; in s004 ~ y=180 with the arm shifted. Actually the visible object is the whole arm; with the elbow bending back, the wrist moves. Hard to say.\n\nLet me instead calibrate agentview properly using the bar's known width and the assumption bar x=0.55: not needed.\n\nTest plan: move to x=0.55, y=0, z=0.30 and view wrist: expect bar near the image position matching eef (u≈? offset ~ camera center offset). If the bar is roughly centered-ish or at the same u as when eef=0.35 z... Hmm, at eef x=0.55 (which I believe is the bar x), the bar should appear at the \"neutral offset\" u position, which is the pixels where the gripper/fingers center is. At s004 the finger jaw center in the image ~ (110+300)/2 ≈ 205 (though that's at close depth). Hmm at greater distance the offset is smaller.\n\nLet's just do the test: move x=0.55 z=0.30 and inspect. Also maybe y test later.\n\nActually, wait. Let's cross-check with the agentview geometry differently: In the agentview, the gripper and the bar appear at similar image y? The gripper bottom is ~180 and the bar top ~290. If the agentview camera has a typical 60° FOV and is at height ~1.5m... In robosuite, \"agentview\" default camera pos = (0.5, 0, 1.45)?? Hmm, robosuite's default agentview: pos (1, 0, 1.4), looking at (0,0,0.8)? Actually camera_utils has cam_pos for frontview... For \"agentview\" in robosuite, default is pos=(0.?, ...). I recall the default agentview is at (1.0, 0.0, 1.2) with quat pointing to (0,0,0.8)? With table at z=0.8. Then robot base at x=0, camera along +x looking -x. Then larger x = closer to camera = lower in image. Bar (x=0.55) lower than gripper (x=0.45) ✓ matching.\n\nGood, I'm fairly confident: bar at x≈0.55, y=0.\n\nBut is bar x exactly 0.55? Let me refine using the wrist view at eef x=0.55: if the bar appears exactly under the gripper's grasp projection... I'll verify and then descend gradually while checking the wrist view, adjusting x based on where the bar appears relative to the finger pads.\n\nUltimately, the pads are the reference: at low z, the wrist image shows the pads at bottom left/right; I want the bar centered between the pads in x. When descending to z~0.10 at the bar's x, the bar should appear between the two fingers in the wrist image.\n\nLet me move to x=0.55, z=0.20, y=0, gripper open, and look. Expect bar visible below/center." + ], + "viewed": [ + "obs/s004_wrist.jpg", + "obs/s004_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 6, + "kind": "move_eef", + "frame_start": 174, + "frame_end": 208, + "command": "move_eef z=0.07 yaw=90 gripper=open speed=0.15", + "args": { + "z": 0.07, + "yaw": 90, + "gripper": "open", + "speed": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5524, + 0.0001, + 0.0719 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 22.33391308784485, + "agent_obs_images": [ + "obs/s006_agentview.jpg", + "obs/s006_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Now the bar is centered between the fingers in the wrist image (u ~175-230, centered at ~205 which is the grasp projection) and the fingers are at left ~110 and right ~305. The bar top is visible going from y~115 down to ~430 (cut off at the bottom, extends below the fingers). The bar's top face and side face: light face 175-225, dark side 225-230. So the bar is nearly directly under the gripper, maybe slightly left of center (grasp center ~205, bar center ~205). \n\nBut wait, the bar appears very close (large). At eef z=0.20, the bar (top at z~0.04) is 0.16 m below. FOV scale: bar short side 55 px = 0.04 m → 0.00073/px at that distance.\n\nThe bar in the image goes from y~115 to bottom 430 → its length 0.2m spans 315 px → 0.00063 m/px. OK.\n\nNow the agentview: gripper tip is at ~(255, 200) right above the bar (bar at y 288-325). Good, seems aligned laterally in x too? The gripper appears at x ~255, bar center x ~247. Looks close.\n\nSo bar x ≈ 0.553 maybe. eef grasp point needs x = bar center. The bar in the wrist image is centered at ~205 while the grasp projection ~205. Actually, to be accurate, in x the bar seems nearly centered (maybe 1-2 px left). Good.\n\nBut wait, careful: with image right = -x and yaw=-90, image up = +y? Earlier derived up=+y. Then the bar extending downward in the image means extending to -y... Fine, symmetric.\n\nAlso is the bar center at y=0? The bar appears vertically centered around image y ~270 which is about image center. Fine.\n\nNow descend. Grasp point should be at the bar's middle height: bar from z=0 to 0.04? The eef grasp point = 1 cm above fingertips. To have fingers straddle the bar sides over its full height, eef z should be around bar mid-height ≈ 0.02, so fingertips at 0.01. Hmm, the fingers are ~0.04 long? The pads span some vertical extent. A safe grasp: eef z ≈ 0.035-0.045 (13 cm? no). The task requires lifting the bar 10cm above table; bar lowest point ≥0.10.\n\nNote: the gripper's finger tips at eef z-0.01. To grasp below the bar's top (0.04), eef z should be <= ~0.03-0.04.\n\nBut careful about collisions: with eef at z=0.20 the pads bottom at 0.19; bar top at ~0.045. Need to descend until the pads go below the bar top, eef z ~0.03.\n\nBefore descending, let me verify the bar's height. From the agentview: the bar's top face is visible; height maybe 0.04.\n\nAlso confirm bar width from the wrist: at z=0.2 the bar's top face 50px wide=0.0365; the width maybe 0.04. Gripper open width is 0.08, so pads at ±0.04, clearance 2cm each side. Tolerance ±2 cm in x before hitting. Should be OK if I'm within ~1cm.\n\nAlso, \"keep holding it level\" – the bar horizontal; grasping it in the middle at y=0 keeps it level if we lift straight up. Bar length 0.2, so it's centered on gripper; level.\n\nThen lift to z such that lowest point ≥0.10 above table: bar bottom ≥0.10 → eef z ≥ 0.10 + (0.01 tip offset) + ... Actually eef = fingertips + 0.01. To have bar bottom at 0.10, and grasping at bar's mid-height 0.02, eef at least 0.10+0.02 = 0.12 + margin. Let's lift to z=0.30. Fine.\n\nLet me now descend to z=0.05 first, checking the wrist. Actually descend directly to z=0.04 with speed 0.2 (slow). Risk: if x is off by >2cm, the finger will press on the bar top? No—fingers descend outside the bar (x±0.04) as long as |dx| < 0.02 + finger width... The pads' inner faces at ±0.04 from center; bar half width 0.02; if dx = 0.02, one pad inner face is at bar's edge. Fine. If dx > 0.02, a pad lands partially on the bar top and will push it/knock it. To be safe descend to z=0.08, look, correct x, then descend.\n\nActually from the wrist image at z=0.2 the alignment looks good (within a couple mm). Let's descend to z=0.06 and look (bar top at 0.04-0.05, so the fingers' tips are at 0.05, just above the bar top). Then final approach." + ], + "viewed": [ + "obs/s005_wrist.jpg", + "obs/s005_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 7, + "kind": "move_eef", + "frame_start": 208, + "frame_end": 232, + "command": "move_eef x=0.589 z=0.12 yaw=90 gripper=open speed=0.15", + "args": { + "x": 0.589, + "z": 0.12, + "yaw": 90, + "gripper": "open", + "speed": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5864, + 0.0004, + 0.1173 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 52.64041471481323, + "agent_obs_images": [ + "obs/s007_agentview.jpg", + "obs/s007_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Interesting! In the wrist image at z=0.07, the bar appears huge and to the LEFT of center — it's occupying x pixels 100-215, whereas the two finger pads are at ~105 and ~415. Hmm, the fingers are at the bottom corners. The bar's left face at x~100 and right face at ~215? Wait, the image is odd: the bar is a wide vertical slab from x~100 to 215 (light face 100-180, dark side 180-215). But that's 115 px wide. But even more importantly the bar appears shifted left relative to before.\n\nHold on. The bar's top face appears to be *above the camera's view*? The image at z=0.07 shows the bar surface crossing the full image height. The image is very zoomed.\n\nWait, this is confusing: at z=0.20 the bar appeared centered at pixel 205 and 55px wide. At z=0.07 (13cm closer) the bar appears 115 px wide, centered at 158. Scaling: 55→115 implies the distance halved (0.16→0.076) ✓ consistent. Center moved left by ~47 px. Hmm, could be due to perspective (camera offset) — as we get closer, the offset between the camera axis and the grasp point grows in pixels. At z=0.20 offset was (256-205)=51 px; at 0.076 depth maybe 51*(0.16/0.076)=107? But the observed center 158 = 256-98. That's about consistent with perspective offset: the camera is offset from the grasp axis by a fixed amount; the grasp projection is at u = 256 - k/d where d = height above bar.\n\nSo the bar center coincides with the grasp projection if u_bar = 256 - k/d. At z=0.20 (d=0.16 above bar top 0.04): u_bar = 205 → k=51*0.16=8.2 (units px*m).\nAt z=0.07 (d=0.03 above bar top 0.04? 0.07-0.04=0.03): predicted u = 256 - 8.2/0.03 = 256-273 = -17. But observed u_bar=158. ✗ Not consistent.\n\nHmm, something else: the bar's visible top face at z=0.07 - the bar top is 0.04, camera at 0.07 → d=0.03. The whole bar would be very blurred/wide. The measured \"width\" 115 px at that scale: 0.00073*(0.03/0.16)=0.00014 m/px → 115 px = 0.016 m. That doesn't match 0.04 m width. So my assumption about the bar's height (0.04) must be wrong. Perhaps the bar is 0.05 tall and 0.025 wide? Let's solve: at z=0.20 the bar's visible top face was 50 px and the image scale there... we assumed bar height 0.04 gives 0.0008 m/px. The bar top face pixel width is the bar's actual width. Let's not assume. Let me get real dimensions.\n\nAlternative approach: use the apparent scale S(d) proportional to 1/d and known movement: between z=0.20 and 0.07 (Δeef 0.13), the bar's apparent width went 50→115 px. Width w: w_px = f*w/d_cam_bar. If d1 and d2 = d1-0.13: 115/50 = d1/d2 → d1 = 2.3 d2 → d2 = 0.13/(1.3) = 0.1, d1=0.23. So the distance from camera to bar top face was 0.23 when eef z=0.20 and 0.10 when eef z=0.07. So the bar top is ~0.20-0.23 = -0.03 below eef? That means bar top z = 0.20 - 0.23 = -0.03?? That's below the table... unless the camera is not at the eef z exactly but likely above/below. The wrist camera is mounted above the grasp point by some small amount, not 0.03.\n\nHmm, my scale-based length check: at z=0.20 the bar's long side spanned 315 px for a 0.2 m bar → d=0.2*f/315. At z=0.07 if 0.2m spans > 512 (off-screen), can't check.\n\nLet me instead directly compute f (focal length in px): At z=0.20, width 50 px, distance d1=0.23 → f = 50*0.23/w. If w=0.04 → f=287. Hmm FOV = 2*atan(256/287) = 83°. Plausible for a wrist cam? Robosuite wrist camera FOV is 75° I believe (f=333). Close-ish.\n\nThen d1=0.23 from camera to the bar top face at eef z=0.20 → camera z ≈ bar_top + 0.23 ≈ 0.04+0.23 = 0.27 when eef z=0.20. So the camera is ~7cm above the eef grasp point. Plausible for the wrist camera (mounted above the hand).\n\nAt z=0.07, camera z=0.14, bar top 0.04 → d=0.10 ✓ matches the estimate. Good, so bar top ≈ 0.04 and camera offset ≈ +0.07.\n\nNow the x offset: at d=0.23 (s006 vs s005? let me use s005 at eef z=0.2024: bar center u=205, offset -51 px → lateral offset = 51*0.23/f = 51*0.23/287 = 0.041 m. At z=0.07 (s006): d=0.10, offset (256-158)=98 px → lateral = 98*0.10/287 = 0.034 m. Both ~0.04 m in the same direction. Consistent! The camera is offset laterally by ~0.04 m from the bar/grasp axis in the +x direction (since image right=-x and the bar appears left → bar is at +x relative to camera axis, i.e., the camera is 0.04 m toward -x from the bar).\n\nWait, careful: bar appears at u=158 (left of center). Image right = -x. Left of center = +x. So bar is at x_cam + 0.034. So the camera's x is 0.034 less than the bar's x. Since the camera is mounted on the gripper at a fixed offset, its offset from the eef: camera_x = eef_x + c. So bar_x = eef_x + c + 0.034.\n\nHmm, so if c is about -0.03 (camera behind the grasp point), then bar_x ≈ eef_x + 0.004 ≈ 0.556. \n\nSince both measurements (at different heights) agree that the lateral offset of the bar relative to the camera axis is constant ~0.037 (that's exactly what a lateral offset between camera and bar center looks like when the camera axis is vertical), we can't separate the camera's mounting offset from the bar's position offset. The camera axis offset from the eef grasp axis is a fixed unknown constant c. If c ≈ 0.03-0.04, then the bar x ≈ eef x. If c≈0.04, then bar_x ≈ eef_x + 0.075.\n\nHmm. We need a reference of the grasp point in the wrist image. The fingers! In the wrist image the two fingers are visible at the bottom (close to the camera). Their inner faces define the grasp width. In s006, the fingers' inner pad faces are at ~125 and ~395. The midpoint = 260 ≈ image center. Hmm! So the fingers' midpoint in the image ≈ 256, meaning the grasp point projects to the image center at least for the finger's own depth. But the fingers are at a much closer depth and their image position is thus affected by the camera's parallax... but roughly, the grasp point projection = image center. \n\nIf the grasp point projects to the image center at any depth along the vertical grasp axis... that's only true if the camera optical axis passes through the grasp point vertically. At d=0.23 (bar top depth), if the bar were exactly at eef x, it would appear at u=256. But it appears at 205 → so the bar is at x = eef_x + (51*0.23/f)= +0.041? Wait, direction: left of center = +x (since image right = -x). So bar_x = eef_x + 0.041 ≈ 0.594? That contradicts my c-based reasoning. The crux is the sign of \"image right\".\n\nUgh, I have two contradicting deductions depending on the sign of image right. Let me settle the sign from the finger geometry decisively: In s006, the two fingers should be symmetric about the grasp axis in the image if the camera is centered between them. The pads' visible inner faces: ~120 and ~395 → midpoint 258. So the grasp axis is near the image center ✓ (weakly).\n\nThat means the bar, appearing at 158 (100 px left of the camera axis projection), is 0.034-0.041 m away from the grasp axis in some direction. Which direction? If image right=+x, the bar is at x = eef_x - 0.04; then bar_x = 0.512. If image right=-x, bar_x = 0.594.\n\nEarlier the s003 → s004 test: eef moved x 0.450 → 0.348 (-0.102) and the bar moved from u=125 to u≈35 (-90 px). Hmm, but wait: at s004, eef z=0.298 and s003 z=0.298, same height, same yaw. If image right=+x: the bar's u should have moved by +0.102*f/d px. With d≈0.26, f=287: +113 px. Observed -90. If image right=-x: bar's u moves -113. Observed -90. So image right=-x ✓ (with a 20% scale error due to unknown f/d, but the sign is clear).\n\nHmm! But wait — is that reliable? The wrist camera orientation might change with arm configuration, since the wrist joint compensates. The hand orientation is kept at yaw=-90 with a vertical approach. As the arm extends, the hand stays pointing straight down. Then the camera also stays fixed in orientation. So the shift should be exactly translation. The observed magnitude -90 px vs predicted -113 for f/d... d unknown; with d=0.33, f/d = 287/0.33=870 px/m → 0.102*870=89 px ✓. So d~0.33 at z=0.298: camera z = 0.298+0.07=0.368, bar top 0.04 → d=0.33 ✓✓. \n\nSo the model is consistent: image right = -x, camera ≈ eef + (0,0,+0.07), f≈287 px, bar top z≈0.04, and the lateral offset of the bar from the camera axis is ~0.037 m toward +x (bar appears left).\n\nNow, is the camera laterally centered on the grasp axis? The fingers' midpoint at 258 suggests yes. But that estimate is crude because the fingers are very close to the camera (parallax!). The pads are only ~5-8 cm from the camera vertically, so their inner corners at ±0.04 lateral would project to ±0.04*f/0.07 = ±164 px from center → 92 and 420. Observed inner faces at 125 and 395 → midpoint 260 ✓, consistent with centered camera.\n\nSo the grasp axis projects near u=256 at any depth only if the camera axis intersects the grasp axis. Then the bar at u=158 (s006, d=0.10) is 98 px → 0.034 m to the +x side of the grasp axis. So bar_x ≈ eef_x + 0.034 ≈ 0.586!\n\nHmm, that's troubling: I aimed at x=0.552, but the bar might be at 0.586. The pad inner faces are at ±0.04 → the bar center at +0.034 means the right pad inner face (at +0.04) would be only 0.006 from the bar's center — i.e., the pad is over the bar surface (bar half width 0.02; bar spans +0.014 to +0.054 relative to grasp axis)! The pad at +0.04 would collide with the bar top!\n\nBut at s006 the eef z=0.072, fingertips at 0.062, bar top 0.04 → 2cm clearance, no collision yet. Good.\n\nSo I need to shift x by +0.034 → x=0.586 before descending. Let's verify using s005: bar at u=205, d=0.16 (z=0.2024, camera 0.272, bar top 0.04 → d=0.232). Hmm, recompute d for s005: camera z=0.2024+0.07=0.2724, minus bar top 0.04 → 0.232. offset 51 px → 51*0.232/287 = 0.041. At s006: d = 0.072+0.07-0.04 = 0.102; offset 98 px → 98*0.102/287 = 0.0348. Both ≈0.04 consistently. With some uncertainty in f and camera height, say bar_x - eef_x ≈ 0.037 ± 0.008.\n\nHmm, but there's another subtlety: at s006, is the \"u center\" of the bar the center of its top face? The top face light region 100-180 (80 px) and the dark side 180-215. The top face is the actual top; the side face is visible because the camera is offset. The true bar center in x = center of the top face = (100+180)/2 = 140 px. Hmm! That changes things. The side face (dark) extends to the right, meaning the visible side is the +x side (image right = -x?? no...).\n\nHmm wait. If image right = -x, the dark side face visible on the right of the top face means the visible side is at -x. The camera is at +x relative to the bar (since the bar appears at +x?? no...). Argh.\n\nLet's redo geometry carefully with a top-down pinhole: camera at (0,0,h) looking straight down, image right = +x (standard), image up = -y or +y. Object at (X, Y, 0). u = 256 + f*X/h... no wait: u = 256 + f*X/h only if image right = +x.\n\nFor the side face visibility: the camera at x=0 sees the +x face of a box centered at X>0? No! If the camera is at x=0 and the box is at x=X>0, the camera sees the box's -x facing side (the side toward the camera). In image, that side appears on the left side of the box (the side closer to the image center/camera axis). So: box appears right of center, and its visible side face appears on its LEFT edge.\n\nIn s006, the dark side is on the RIGHT of the light top face. The light top face (bright) is the top; the darker face is the vertical side. The side face that's visible is the one facing the camera → that's the face nearer the camera axis. It appears on the side of the box nearer the image center: the box spans 100-215, center 158, which is left of image center 256. The nearer side is the right edge (215) ✓ consistent with the box being left of the camera axis in image, meaning the box is at -x if image right=+x.\n\nWait, I need to be careful: \"image right = -x\" was deduced from the eef motion test. Let's re-derive that test more carefully with correct assumptions.\n\nTest: s003: eef x=0.4501, z=0.2988. u_bar ≈ 130 (top face 115-145 center 130). s004: eef x=0.348, z=0.2982. u_bar: the image showed the bar with light face 10-45, dark 45-65 → top face center ~27. So Δu = -103 px when Δeef_x = -0.102.\n\nPhysical: the bar is fixed in world; the camera moved -0.102 in x. The bar's position relative to the camera axis changed by +0.102 in x. If image right = +x, u should increase by 0.102*f/d ≈ +0.102*287/0.33 = +89 px. Observed -103. So image right = -x. Unless the wrist camera orientation flipped... no.\n\nAlternatively, if the camera is not perfectly vertical but tilted, moving the arm in x also moves the camera along its optical axis, changing d and hence the pixel offset. At s003 vs s004 same z but different arm extension → the camera might tilt. Hmm, the hand orientation is held vertical (approach straight down) so the camera orientation should be constant.\n\nBut wait — there's another possibility: the camera's mounting offset c is significant and the arm's hand position is eef, but if the hand orientation is constant, the camera offset is constant, so the relative position changed exactly by 0.102.\n\nOK so image right = -x is solid. Then: the image-center-to-bar vector in image (+x?) Let's convert: bar at u=158 < 256 → bar appears left. Image left = +x. So bar is at +x relative to the camera axis. And the visible side face: the camera is at x less than the box, so the camera sees the box's -x side, which in the image appears... The camera axis points down. Image left = +x. So the box at +x appears left ✓, and the camera-facing side (-x side of the box, the one at smaller x) appears on the image RIGHT side of the box (since image right = -x). Observed dark side on the right ✓. And in s003 the dark side was on the right too ✓.\n\nSo the bar is on the +x side of the camera axis by ~0.037 m. The camera is centered on the grasp axis (grasp point projects to the image center; the finger midpoints at 258 support this).\n\nTherefore, bar_x ≈ eef_x + 0.037.\n\nHmm, but actually wait. I should double check the claim \"camera centered on grasp axis\" — it's crucial and the finger-midpoint evidence is subject to parallax. Actually, the camera is mounted somewhere on the hand; it's plausible its axis passes close to the fingertips.\n\nAlternative better calibration: use the fingertip positions in the image and their known 3D positions relative to eef. Too complex.\n\nLet's just empirically iterate: move x from 0.552 to 0.589 (+0.037) at z=0.12, look at the wrist; the bar should appear centered at ~256 minus the residual. Then descend and close.\n\nActually even better: I can visually servo x to bring the bar to u≈256 at a fixed z. Each iteration is cheap (one command). Let's move to x=0.589, z=0.12." + ], + "viewed": [ + "obs/s006_wrist.jpg", + "obs/s006_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 8, + "kind": "move_eef", + "frame_start": 232, + "frame_end": 265, + "command": "move_eef x=0.597 z=0.03 yaw=90 gripper=open speed=0.1", + "args": { + "x": 0.597, + "z": 0.03, + "yaw": 90, + "gripper": "open", + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5967, + 0.0005, + 0.0329 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 18.7178475856781, + "agent_obs_images": [ + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Now the bar's top face is centered at ~237 (spans 200-275). Nearly centered, 19 px left of center. d = camera z (0.117+0.07=0.187) - 0.04 = 0.147. 19 px → 19*0.147/287 = 0.0097 m. So bar_x ≈ eef_x + 0.010 = 0.596. Hmm, but earlier we computed the offset 0.037 at x=0.552; now moving +0.034 should have eliminated it, giving ~0.003. We got ~0.010. Fine — measurement noise, but I should account for camera mounting being not exactly known.\n\nAlso there's a residual: the bar is only 19 px left of center. Tolerance: bar center can be within ±0.02 of the grasp axis comfortably. 0.010 is fine. But let's improve: move +0.008 → x=0.597. Also, the agentview shows the gripper is slightly left of the bar center? Gripper at x_pix~253, bar center ~248. Looks close.\n\nWait, important: the finger pads in the wrist image are at inner faces ~120 and ~390 → midpoint 255, consistent.\n\nHmm, but I realize the \"camera centered on the grasp axis\" assumption might be slightly off. Let me test it differently: the bar's width. Top face spans 200-275 = 75 px at d=0.147 → w = 75*0.147/287 = 0.0384 m ≈ 0.04 ✓ good, f=287 validated (assuming tan/linear approximation; at 40° off-axis linear approximation error is small).\n\nNow check the bar's remaining offset direction — nudge x +0.01 → 0.597, keep z=0.12. Actually let's first verify y alignment: the bar spans vertically 55-430 px in the image, center 242, close to 256. The image up = ±y; if the bar is centered vertically near the image center, then the bar's center y ≈ the camera's y = eef y ≈ 0. Good enough (bar half-length 0.1).\n\nNow descend and grasp. I'll move to x=0.596, z=0.045, speed=0.1 (slow), then check the wrist, then close the gripper to width ~0.03 and lift.\n\nWait: the fingers must straddle the bar. At eef z=0.045, the pads' bottom (0.035) is just below the bar top (0.04) → contact region begins. Actually the grasp point is 1cm above the fingertips; fingertips at 0.035. The bar top is 0.04. So at z=0.045, the fingertips are below the bar top → the pads are straddling the bar's upper sides already. Good.\n\nBut how tall is the bar? If the bar is 0.04 tall, and fingertips at 0.035, then only 5 mm of the pad overlaps the bar's side. Fingers pads are maybe 2-3cm tall. To grasp firmly, better to go to z=0.02 (fingertips 0.01, i.e., 1 cm above the table). That gives good contact with the bar sides. Risk of hitting the table if the gripper dips—acceptable.\n\nLet me descend to z=0.03 first and look at the wrist to verify alignment, then to 0.015 and close. Actually to save commands: descend to z=0.025, check, then close, lift, verify.\n\nNote: descending straight down with the fingers straddling — if dx is ~1 cm, one pad clears by 1cm on one side and 1cm on the other, fine. \n\nActually careful: pad inner faces are at ±0.04 from the grasp axis; the bar half width is 0.019. If dx=0.010, the right pad inner face at +0.04 is 0.04-0.010-0.019 = 0.011 from the bar's +x face. Fine.\n\nLet's go." + ], + "viewed": [ + "obs/s007_wrist.jpg", + "obs/s007_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 9, + "kind": "move_eef", + "frame_start": 265, + "frame_end": 280, + "command": "move_eef gripper=close speed=0.05", + "args": { + "gripper": "close", + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5968, + 0.0007, + 0.0331 + ], + "gripper_width_after": 0.0403, + "holding_after": false, + "touched_during": true, + "think_s": 10.828028917312622, + "agent_obs_images": [ + "obs/s009_agentview.jpg", + "obs/s009_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Now at z=0.033, the wrist view shows the bar's top face spanning 190-325, center 257 — perfectly centered! d = 0.033+0.07-0.04 = 0.063; width 135 px → 135*0.063/287 = 0.0296 m. Hmm, that suggests the bar width is ~0.03, not 0.04. Slight inconsistency but OK.\n\nWait, actually now the bar looks like it's directly under and the image shows only the top face (no dark side visible) → the camera is directly above the bar center. \n\nAlso the agentview shows the gripper jaws straddling the bar (white fingers on either side of the bar at its center). Wonderful. The fingers appear to be around the bar center — at image x~240 and ~265, bar spans 160-335. So the gripper is grabbing near the middle. \n\nNow, is there contact/collision? The agentview shows the fingertips at the bar's top surface. Looks fine.\n\nThe bar center in the agentview appears at x~248, and the gripper at ~253. Good.\n\nNow close the gripper. Then lift. When closing, the fingers should contact the bar's sides (width 0.04 max opening, at ±0.02). Let's close and check the reported gripper width. If it closes to ~0.0, we missed.\n\nThen lift to z=0.15 slowly and check that the bar rises.\n\nOne concern: y alignment. The bar's center y should be 0. The gripper is at y=0.0005. The fingers span y? No—with yaw=-90, the fingers close along x. The finger pads span along y (their width ~2cm), so y alignment matters for a good grip but ±2cm is fine.\n\nLet's close and lift to z=0.12." + ], + "viewed": [ + "obs/s008_wrist.jpg", + "obs/s008_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 10, + "kind": "move_eef", + "frame_start": 280, + "frame_end": 307, + "command": "move_eef z=0.1 speed=0.05", + "args": { + "z": 0.1, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5955, + 0.0002, + 0.0966 + ], + "gripper_width_after": 0.0402, + "holding_after": false, + "touched_during": true, + "think_s": 4.304196119308472, + "agent_obs_images": [ + "obs/s010_agentview.jpg", + "obs/s010_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Gripper width 0.0403 — it stopped at the bar width. That means it's gripping the bar (or hitting it). Now lift slowly." + ] + } + }, + { + "attempt": 1, + "step": 11, + "kind": "move_eef", + "frame_start": 307, + "frame_end": 331, + "command": "move_eef z=0.055 gripper=open speed=0.1", + "args": { + "z": 0.055, + "gripper": "open", + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5944, + 0.0014, + 0.0563 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 49.02630662918091, + "agent_obs_images": [ + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg" + ], + "agent_note": { + "messages": [ + "The bar lifted but it's tilted in the agent view. Let me lower it and re-grasp deeper." + ], + "reasoning": [ + "The bar is lifted and held! But look at the agentview: the bar is tilted! It's not level: the left end is lower, right end higher. In the image, the bar spans from (~172, 315) at the left to (~345, 240) at the right. That's a rotation in the image plane... The bar's long axis is along y (world). In the agentview, y maps to horizontal. So a tilt in the image = rotation about... the bar's long axis is y; level means the bar's long axis is horizontal in world (no rotation about x or z). The image shows the bar at an angle ≈ atan(75/173) ≈ 23°. That's > 8°!\n\nHmm, the bar appears rotated about the x-axis (pitched), i.e., one end down. This happens because the grasp is not centered in y (grasp near y=+0.05?), so the bar tips.\n\nWait, why would it tilt? If the grasp is off-center in y, gravity torque tips it. With the bar 0.2 m long and gripped at y≈0, it should be balanced. If gripped at y=+0.05, it tilts. In the wrist view, the bar spans from the bottom (near the fingers) to the top, and its image vertical center is around 235... but the padding: the bar's visible extent: 60-390, center 225 vs image center 256. Hmm, that's a 31 px offset at d small... Not conclusive.\n\nActually, wait: the tilt may be a pitch (rotation about the y-axis? no) Let me think about the apparent tilt in the agentview: the bar's long axis along y and level. In the agentview, the y-axis maps roughly to horizontal, x to depth, z to vertical. An apparent tilt in the image means the bar is rotated about the x-axis (one y end up, other down). A pitch about x = one end high. That's tilt.\n\nWhy? Possibly the gripper isn't gripping firmly, or the grasp point isn't at the bar's y center, or the fingers touched the bar's edge and it rotated during the lift. The gripper held at width 0.0402 = the bar's width, so it's gripped.\n\nY center: eef y=0.0002. If the bar's center y=0, we're centered. Unless the bar is not at y=0. Let me check the wrist image at s007/s008: the bar's vertical extent relative to the image center. At s008 (z=0.033), the bar spans the entire image vertically (out of view). At s007 (z=0.117), the bar spanned 55-430, i.e., center 242 vs 256 → offset 14 px down. With image up = ±y unknown, the bar center is 14px off → 14*0.147/287 = 0.007 m. Small.\n\nHmm, but the tilt in the agentview is substantial. Alternatively, the bar might have rotated about x because the fingers were not fully straddling it and applied a torque. Or the tilt in the image might be perspective: the bar could be level but appear tilted due to the camera angle. Let me examine more carefully: In the initial state (s000), the bar appeared horizontal in the agentview (from 160,290 to 335,322? Actually the bar in s000 had its top face horizontal: 160-335 at y 288-293 — horizontal). In s010, the bar clearly goes diagonally from lower-left to upper-right.\n\nSo yes, the bar is tilted after lifting. That's bad (>8°). Hmm, but is it tilted with the right end UP, i.e., rotation about x-axis: +y end up.\n\nPossibility: the grasp point is offset in y such that the +y end is... if the grasp is at y>0 (near +y side), the -y end sags → in the image, -y at image left... which end is +y in the agentview? Unknown, but the bar tilts.\n\nAnother possibility: the gripper's fingers are 2cm wide and grip the bar at a slight angle? The eef yaw is -90 exactly.\n\nWait, maybe the grip is at the very top of the bar (only the fingers' top edge contacting) so it pivots. At eef z=0.033, fingertips at 0.023, bar top 0.04 → the fingers straddled only the top 1.7cm of the bar's sides. The bar's height is ~0.03? Then the contact is OK.\n\nHmm, but when lifting, the bar rotated about the x axis: means the fingers' contact faces are parallel to the x-z plane and the friction holds. The rotation could be due to an unbalanced torque from an off-center grasp in y.\n\nLet's check the wrist image at s010: the bar is a big trapezoid, wider at the bottom. That's just perspective (closer to the camera at the bottom).\n\nLet me measure more carefully with the image: I can analyze pixel geometry to estimate the tilt angle in 3D? Hard.\n\nBetter: just fix it. Approach: grasp closer to the bar's center in y and lower (deeper) to get a firmer grasp. But my y may already be centered (y=0).\n\nWait, maybe the tilt is not y-pitch but a rotation about the z-axis after the fingers slipped? In the agentview, a rotation about z would show the bar as... The bar's long axis along y and level → horizontal line. Rotation about z by θ rotates the bar in the x-y plane, which in the image looks like... x is depth (vertical-ish in the image) and y horizontal, so a z-rotation appears as a slight tilt too, combined with foreshortening. Hmm! Actually a pure z-rotation (yaw of the bar) would make one end come toward the camera and appear lower in the image while the horizontal extent shrinks. A pure pitch about x would make one end rise while horizontal extent stays the same.\n\nObserved: left end at (172,315), right end at (345,240). The horizontal extent 173 px, compared to the initial 175 px (160-335). So the horizontal extent is the same → this is a PITCH (rotation about x), not a yaw. Nice catch: initial bar spanned 160-335 (175 px) at y≈290-325; now 173 px. So the length in projection is unchanged but tilted → tilt about the x-axis (one end up, the other down).\n\nSo the bar is tilted about x by roughly arcsin? The image tilt: the vertical drop is 75 px while the horizontal span is 173 px. Since the image vertical corresponds to x and z... ugh, hard to convert, but the tilt is likely ~20°.\n\nNow, why did it tilt? A pitch about the x-axis means the bar rotated about the line through the grasp point along x. Torque from gravity if the center of mass is offset in y from the grasp point. If the bar's y-center is at y_c and the grasp at y=0, then torque tips it.\n\nFrom the wrist images, the bar's center in y: at s007, the bar's image vertical center 242 vs 256, offset 14px down. But also the \"vertical center\" of the bar's projection isn't exactly the bar's y center due to perspective. Near-center anyway.\n\nAlternatively, the tilt could come from the fingers hitting the bar during the descent, giving it an initial tilt that the grasp preserved. Hmm, at s008 the agentview showed the bar horizontal before closing. So the tilt appeared during the lift → from an unbalanced grip.\n\nWait, another explanation: the \"gripper=close\" at width 0.0402 means the fingers stopped when touching. But the grasp point... hmm.\n\nActually here's a likely cause: the fingers grip at only one contact... if the bar's width tapers or the grasp is near the bar's top edge with the fingers' inner faces angled, the grip could be asymmetric. Also, the bar might just be tipping because the center of mass is not between the friction contacts if the grip is very shallow.\n\nLet me look at the s010 wrist image: the bar is between the fingers, and its lower portion is visible; both fingers contact it. Hmm.\n\nPractical fix: after lifting, level the bar by rotating the gripper's roll? We can't control roll — only yaw. But I could correct the tilt by moving y? No.\n\nAlternative: re-grasp more centrally in y and deeper. The deeper grasp: descend to z=0.02 (fingertips 0.01). Then close. Then lift slowly. Also, add a small y correction if needed.\n\nBut before re-grasping, let me quantify the tilt better. Actually, a tilt less than 8° is acceptable. The current tilt looks like >8° (threshold). Let's estimate: the vertical drop of 75 px over the horizontal 173 px in the agentview. The bar in the agentview: y direction spans 173 px (0.2 m → 173 px at that depth, though with x-dependence). Vertical 75 px. What's the scale in the vertical? The bar's height 0.04 m … in the image, the bar's \"thickness\" (the visible end face) at the left is about 45 px (from y 315 to 360?) Let me actually measure using image analysis rather than eyeballing.\n\nLet me crop and inspect the s010 agentview bar region programmatically, and compare to s000.\n\nActually simpler: place the bar down, re-grasp, and lift with a different strategy. But first, let me test whether the tilt persists and confirm that it's caused by the grip. Could also try: after lifting, gently lower a bit and re-close (a \"regrasp\"). Or lift slower.\n\nAlternatively the tilt might settle/damp after holding a moment. Let me just observe now (free-ish? observe is a command but cheap, 1 command).\n\nLet me do a \"observe\" to get a new image without motion (it uses a command but no sim time). Actually, in a physics sim, time advances only with motion. Holding still doesn't change anything.\n\nBetter: let me analyze the images quantitatively with Python to estimate the 3D tilt. I can use the agentview pixel positions of the bar's corners, but I don't have the camera calibration. However, I can calibrate the agentview camera from known gripper positions! I have many (eef 3D, gripper image pixel) pairs... the gripper pixel marked by the fingers is approximate.\n\nHmm, let me first just try the simple fix: lower, re-grasp deeper, and lift again. If the tilt persists, I'll consider other options.\n\nActually wait. Before that, consider: maybe the tilt is because the bar's grasp was near its y-center but the fingers squeezed at the top edge, and the bar rotated so that one end fell until the fingers' other side contacted... Something like a partial slip. A deeper grasp should solve it.\n\nAlso consider the y position: if the bar's center is at y ≈ +0.01 (given the 14px offset direction unknown), an off-center grasp of 1 cm on a 0.2m bar gives a torque but the fingers' grip should resist. The grip is at the bar's center of mass vertically? The grip contact is at the bar's top half. The bar's COM at z=0.02. The grip at z ~0.03 → the bar is held from above its COM, unstable (a pendulum). Any torque → tips. The fingers' contact patch height is what resists. If the fingers only contact the top 1 cm of the bar, tipping is easy.\n\nSo: re-grasp deeper (fingers covering the full side height) to resist tipping. Let's do that: lower to z=0.015 (fingertips at 0.005, ~5mm above the table) — this covers the bar's full height.\n\nAlso, to be safe, if the bar is already tilted, I should set it back down and re-grasp. Steps:\n1. move z=0.02 (lower the held tilted bar back to the table). \n2. open the gripper.\n3. move up to z=0.10, adjust x/y over the bar (bar may have shifted during the failed grasp).\n4. descend, close, lift.\n\nBut lowering a tilted bar might push it sideways. Alternatively, open the gripper at height and let the bar drop flat onto the table (it's a small height, 0.096 eef → bar bottom at ~0.076; dropping 7cm could bounce/roll). Hmm, the bar could land tilted on the table but settles flat since it's a box.\n\nPlan: open the gripper at the current height (bar drops flat), then re-approach. Actually let's lower to z=0.05 first then open (drop ~3cm), minimizing impact/scatter. \n\nBut careful: the bar might rotate/shift on the drop. Then I'd need to re-locate it with the wrist camera. That's fine—few commands.\n\nLet me think whether there's a smarter way to keep the bar level. Alternative: grasp the bar near its COM but with a deeper grip. Deeper grip = lower grasp point z. The grasp point eef z = fingertips + 0.01. If the fingertip is at 0.005, eef z=0.015. The bar's height? Let me measure its height from the wrist image or agentview: In the agentview at s000, the bar's front face (facing the camera) height: top edge at 288, bottom edge at ~322? That's 34 px. The length 0.2 m is 175 px → 0.2/175 = 0.00114 m/px at that depth. So the height 34 px = 0.039 m ✓. And the width (from wrist) ~0.03-0.04. OK.\n\nSo the bar is ~0.04 × 0.04 in cross-section. Gripper open 0.08 → pads at ±0.04, bar half-width 0.02, clearance 2cm each side. Good.\n\nIf I grasp with eef z=0.02, the fingertips at 0.01 → covers z 0.01-0.04+ of the bar (pads are ~4cm tall?) which is the full height. Good.\n\nBut wait: with the pads' inner faces at ±0.04 and the bar half-width 0.02, closing brings the pads to ±0.02 = the bar's sides ✓.\n\nOne more consideration: the gripper pads may be angled (the Panda fingers have a groove/pad). Fine.\n\nLet's proceed: open at z=0.05, then re-approach.\n\nActually, I realize there might be another cause of the tilt: the bar's COM along y might be off from where I gripped because the bar isn't at y=0. Let's determine the bar's y from the agentview horizontally: the bar in s000 spans x pixels 160-335, center 247.5, while the gripper's grasp line... the gripper at s000 is at x_pix ~250. But the gripper is at a different z, so no direct comparison.\n\nIn the s010 image the bar is held and tilted. Let me quantify the tilt properly using the images. I'll write a small script to detect the bar's grey pixels and fit lines in both views.\n\nActually, let me just do the re-grasp; quantitative analysis has limited benefit now.\n\nWait — actually, maybe a much better strategy for levelness: instead of relying on friction with a parallel gripper on a slippery metal bar, grasp it near the middle and grip hard. We can't control the force besides closing.\n\nAlternatively, a cleverer approach: rotate the gripper yaw slightly so the fingers grab the bar in a V and the bar self-centers? Nah.\n\nLet's re-grasp deeper. Commands left: 30. Time left 104.7s. Plenty.\n\nStep 1: move z=0.05 slow, open gripper → drop bar 3cm." + ], + "viewed": [ + "obs/s010_agentview.jpg", + "obs/s010_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 12, + "kind": "move_eef", + "frame_start": 331, + "frame_end": 357, + "command": "move_eef y=0.013 z=0.015 yaw=90 gripper=open speed=0.08", + "args": { + "y": 0.013, + "z": 0.015, + "yaw": 90, + "gripper": "open", + "speed": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5942, + 0.0124, + 0.0174 + ], + "gripper_width_after": 0.0793, + "holding_after": false, + "touched_during": false, + "think_s": 16.634079456329346, + "agent_obs_images": [ + "obs/s012_agentview.jpg", + "obs/s012_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The bar is back on the table and appears horizontal in the agentview. But did it shift? The bar now spans x pixels ~165-342 (center 253). Before (s000) it spanned 160-335 (center 247.5). So it shifted ~5 px → maybe 6mm in y. Also the wrist view: the bar's top face spans 200-310, center 255 — nicely centered in x under the gripper. \n\nNow descent and deeper grasp. Current eef x=0.5944, y=0.0014. Let me descend to z=0.015 (fingertips at 0.005). Speed 0.08.\n\nWait, but the bar may have shifted in y a bit. The wrist view shows the bar centered at 255 in x. Good. For y: the bar spans 30-400 vertical, center 215 (vs 256) → offset 41 px down, d=0.0563+0.07-0.04=0.086 → 41*0.086/287 = 0.012 m. If image up = +y... in s008 the bar was centered at 257 vertically. Now the bar looks shifted. Hmm, but the bar's projected vertical extent center is affected by the drag of the drop.\n\nGiven the previous tilt (pitch about x), the bar's y-center relative to the grasp probably matters. Let me determine the sign of y from the image up direction and correct y.\n\nDirection: at yaw=-90, image right = -x (established). Image up: for a camera looking down (-z) with right = (-1,0,0), up must satisfy right × up = +z (toward viewer)... camera forward o = -z. For an image, right × up = -o = +z. right=(-1,0,0): (-1,0,0) × up = +z. Let up = (0,u_y,0): (-1,0,0)×(0,1,0) = (0*0-0*1, 0*0-(-1)*0, -1*1-0*0) = (0,0,-1). So up=(0,1,0) gives -z. We need +z → up = (0,-1,0). So image up = -y.\n\nSo the bar appearing at image y center 215 (below center 256) = down in the image = +y. So the bar's center is at +y relative to the camera axis by 0.012 m.\n\nThen the earlier tilt: with the bar at y ≈ +0.012 and the grasp at y=0, the -y end is longer → the -y end sags. In the image, -y is up... the bar in s010 went from lower-left to upper-right; if up = -y then the upper-right end = -y and it was UP, not sagging. Hmm, contradicts.\n\nHmm, wait. In s010 the bar was at a different y possibly (the grip may have shifted it). Unclear.\n\nLet me not overthink. Just grasp deeper and also nudge y by +0.012 to center. Actually, the bar might have shifted in y during the drop, so maybe just re-measure: the center offset 0.012 in +y. Let me move y=0.012 to align, then descend.\n\nHmm, but there's a subtlety: the reported \"vertical center of the bar's projection\" isn't exactly the bar's y center because the side faces. It's a rough estimate. But a 1.2 cm correction is small anyway.\n\nLet's do: move eef y=0.013, z=0.015, speed=0.08, then check, then close." + ], + "viewed": [ + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 13, + "kind": "move_eef", + "frame_start": 357, + "frame_end": 372, + "command": "move_eef gripper=close speed=0.05", + "args": { + "gripper": "close", + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5943, + 0.0126, + 0.0175 + ], + "gripper_width_after": 0.041, + "holding_after": true, + "touched_during": true, + "think_s": 10.839095115661621, + "agent_obs_images": [ + "obs/s013_agentview.jpg", + "obs/s013_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Hmm, at z=0.017, the wrist view shows the bar filling the bottom half from x 165 to 340, centered 252 (slightly left of 256 — fine). But the bar's top edge in the image is at y~0 (above the frame)? The bar's top face isn't visible at all — the whole frame bottom is the bar? Wait, the image shows the bar from y=0 down through 400, spanning x 165-340. Hmm, the bar looks like it's seen from very close, and the \"top face\" is the entire slab. Actually this looks like we're seeing the bar's top surface facing the camera. That's odd since the bar is only ~0.03 tall and the camera is at 0.017+0.07=0.087 — actually the camera is pretty much right on top of the bar.\n\nBut wait — the agentview at s012 shows the bar still flat on the table with the gripper fingers straddling it, tips at the table. Looks good: fingers at x~245,260 and the bar horizontally from 165 to 340.\n\nGood. Now close the gripper. Then lift slowly to z=0.10 and check the tilt." + ], + "viewed": [ + "obs/s012_agentview.jpg", + "obs/s012_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 14, + "kind": "move_eef", + "frame_start": 372, + "frame_end": 441, + "command": "move_eef z=0.12 speed=0.03", + "args": { + "z": 0.12, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5929, + 0.0122, + 0.1173 + ], + "gripper_width_after": 0.041, + "holding_after": true, + "touched_during": true, + "think_s": 4.150727987289429, + "agent_obs_images": [ + "obs/s014_agentview.jpg", + "obs/s014_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 15, + "kind": "move_eef", + "frame_start": 441, + "frame_end": 691, + "command": "move_eef z=0.02 speed=0.05", + "args": { + "z": 0.02, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5955, + 0.0128, + 0.0236 + ], + "gripper_width_after": 0.041, + "holding_after": true, + "touched_during": true, + "think_s": 151.47701120376587, + "agent_obs_images": [ + "obs/s015_agentview.jpg", + "obs/s015_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The bar is lifted and tilted again, similar to before, maybe even more. In the agentview, the bar goes from (190, 320) to (345, 205). The horizontal span is 155 px (less than 173), and the vertical drop is 115 px. So both a yaw and a pitch?! The projected length is shorter (155 vs 173) → suggests yaw rotation too. Hmm.\n\nHmm, maybe the bar is rotating about the grip point because it's not balanced and slowly slipping/rotating. It seems the grasp is not stable: the bar rotates ~30°.\n\nWait — maybe the issue is that the bar isn't being gripped at all in a stable way: the gripper width 0.041 suggests it's gripping the width. But maybe the fingers contact the bar only at the very top corners, and the bar is hanging off one side?\n\nLet me look at the wrist view: the bar appears between the fingers at the bottom. The bar's visible top face... hmm, the wrist view shows a big grey slab.\n\nI think the problem is that the bar rotates about the x-axis because the pinch grip is on the bar's sides but the bar's mass center is below the contact... Actually holding a bar by pinching its sides from above is like holding it in the middle—should be stable-ish, but a box can rotate about the pinch axis (x) if the center of mass is not on the pinch axis.\n\nHmm, unless the grasp is asymmetric: the fingers may be at different heights or the bar was pushed to one side before closing. Or the bar isn't horizontal at the start? At s012 the bar looked horizontal.\n\nLet's quantify the tilt in this s014 image. The bar's long axis in the agentview: from (190,320) to (345,205): Δ=(155,-115). In the s000 image, the bar's top face was from (160,288) to (335,290) approx (nearly horizontal). The bar's apparent length: 175 px. At s014 the length is 192 px (sqrt(155²+115²)) — actually longer. Hmm, so maybe the length didn't shrink; it just rotated in the image plane.\n\nA rotation in the image plane could correspond to: (a) a rotation about the camera's optical axis (a \"roll\" of the bar), which for the agentview camera is a combination of pitch and yaw of the bar. Hmm.\n\nThe key question: how to hold the bar level? The tilt could be a real rotation about x (one end up). Because in the agentview, the camera is roughly looking along -x with a downward tilt, so the world y axis is roughly horizontal in the image and the world z is up, x is depth (into the image, i.e., up-ish? no, x goes toward the camera = down in the image). So:\n- world y ≈ image horizontal (right or left)\n- world z ≈ image vertical (up)\n- world x ≈ image vertical-ish (down toward viewer)\n\nA pitch about x (one y end up) → image: the bar's y-extent stays horizontal in scale but one end up → image tilt with the same horizontal span. A yaw about z → the y-extent's horizontal span shrinks (cos θ) and this affects both ends' depth equally (no tilt). A roll about y (bar's own axis) → doesn't move the endpoints, only rotates the cross-section.\n\nObserved: horizontal span 155 vs 175 initial → shrunk by 0.885 → yaw θ=27°. The vertical drop 115 px would come from the pitch. Hmm, but with yaw, the far end appears higher in the image (because it's farther/deeper, i.e., -x direction, which is up in the image). Wait: if x increases toward the camera and appears downward in the image, then a yaw rotation moves one end to a larger x (closer, lower in image) and the other to smaller x (farther, higher in image). That produces an image tilt too! And the horizontal span shrinks by cos θ. So the observed tilt could be entirely a YAW rotation of the bar (about z)!\n\nBut a yaw rotation would also change the bar's apparent thickness and the \"which face is visible\". In s014, we see the front face of the bar prominently.\n\nLet's test: yaw θ=27° would shrink the horizontal span to 175*cos27 = 156 ✓ matches 155. For the vertical: the far end's depth change = ±(L/2) sinθ = 0.1*0.454 = 0.0454 m. In the image, an x change of 0.045 appears as... the x-axis in the agentview maps mostly to the image vertical with a scale similar to y's (since the camera looks down at ~45°?). The vertical span 115 px for 0.0908 m total → 1266 px/m; the horizontal scale is 175px/0.2m=875 px/m. Hmm, not equal, but the camera is tilted so the x-z mapping is stretched/compressed.\n\nAlternatively a pitch of 0° in yaw: horizontal span would stay 175. Observed 155. So there IS a yaw of ~27°, or the bar is shorter in the projection due to something else.\n\nHmm! Wait. Actually maybe the bar is rotating about the z axis because it's only being held by the fingers' friction and there's torque... no, gravity wouldn't cause a yaw.\n\nCould the yaw be from the gripper's yaw during the lift? eef_yaw stayed -90.\n\nHmm, let me look again at s014: the bar is going up-right at ~36°. Its left end at (190,318) and right end at (345,208), with the bar's body having visible height ~30 px.\n\nAnd notice: the bar's left end appears \"closer to the camera\" (larger, showing the end face). Hmm.\n\nWait, maybe I'm misreading and the bar is fine but simply PITCHED down at the left end, and the horizontal span shrink is a perspective artifact (the near end appears longer/shorter). With a pitch of 30° and a length of 0.2: the horizontal span stays ~L cos(pitch)*scale_y? No—pitch is about the x-axis, which doesn't change the y-extent. Only the depth. With the camera at an angle, the depth change causes a slight scale change (negligible: ±5cm on a 1m distance = 5%).\n\nSo the horizontal span should stay ~175 px for a pure pitch. It's 155 → mostly yaw. Hmm, but wait: maybe the bar has ROTATED about x by a lot (say 60°), then its projected y-extent = L cos? No, rotation about x preserves the y-extent: cos(60°)? Rotation about the x-axis maps y→(y cos θ, z sin θ). So the y extent is still L cos θ... no! A rotation about x by θ maps the bar's long axis (0,L,0) to (0, L cos θ, L sin θ). So the y-extent becomes L cos θ and the z-extent L sin θ. In the image, the horizontal span shrinks by cos θ and the bar's vertical drop increases correspondingly. THAT's exactly what we see: horizontal 155/175 = 0.886 → θ=27.6°, and the vertical drop of 115 px = L sin θ = 0.2*0.463 = 0.0926 m → in image px: 115 px/0.0926 m = 1240 px/m, versus the y-scale 875 px/m. The z-scale in the image is larger than the y-scale (likely, since the camera is at an angle and the z direction is partly along the image vertical... hmm, the z scale can't differ from the y scale much in a perspective projection—both are perpendicular to the x axis, so their scales are equal (isotropic). \n\nHmm, that's a contradiction: for a rotation about x, the bar's projection: y-extent Lcosθ at scale 875 → horizontal 155 ✓, and the z-extent Lsinθ at the same scale 875 → 0.0926*875 = 81 px, but observed 115 px. The extra comes from the x-depth: the far end is farther → appears higher (up in image). Adding ~34 px from the depth effect. Plausible: the far end at x - 0.1 sinθ? Wait no, a rotation about x doesn't change x at all! The bar's endpoints stay at the same x. Hmm, no depth effect. So the vertical drop should be 81 px, observed 115.\n\nUnless the rotation axis isn't exactly x. Whatever—both yaw and pitch could be present.\n\nWait, but a subtlety: the agentview camera is not aligned with the axes; it's at an angle. The \"horizontal in image\" is a projection of both y and x. Ugh.\n\nLet me actually calibrate the agentview camera using the known bar! In s000, the bar's top face (a 0.2 × 0.03 rectangle at z=0.04) has known 3D coordinates. Its corners project to 4 known pixel positions. Plus the bar was moved/held... too complicated.\n\nOK, practical approach: the tilt is clearly substantial, and a friction grip on a metal bar with a parallel gripper seems to allow rotation. To succeed, I need the bar level (<8°) at finish. \n\nOptions:\n1. Grip near the middle and just hold it level by controlling the wrist orientation? But we can only control yaw. The tilt is a rotation about x or z... If the bar rotates about the x-axis (pitch), I can't control it with yaw. Yaw control affects rotation about z. Hmm, but I can control the pitch of the gripper? The move_eef command has no pitch parameter—the orientation is fixed to point down.\n\n2. Grip the bar at its very end so it hangs vertically? No, it must be level.\n\n3. Grip the middle and rotate the gripper yaw to compensate a yaw tilt: if the tilt is mostly a yaw (rotation about z), then I can rotate the gripper yaw to level the bar's long axis relative to y. But \"level\" means the bar's long axis is horizontal; a yaw rotation keeps it horizontal! Yaw about z keeps the long axis horizontal (no tilt). So the tilt must be a pitch about x, which I can't fix with yaw.\n\nHmm, but wait: is the bar's tilt really a pitch? Let's reconsider: The task's \"tilted less than 8 degrees\" likely measures the bar's long-axis deviation from horizontal.\n\n4. Use the wrist camera to look at the bar and see the tilt; then adjust... but we can't adjust pitch.\n\nHmm, hold on. Maybe the issue is that the bar is not gripped stably and is rotating in the grip. The fix: grasp more of the bar so it can't rotate — e.g., grasp it near one end? No.\n\nAlternative idea: grasp the bar with the fingers on the TOP and BOTTOM? Not possible with a parallel gripper oriented downward... Actually! We could approach the bar from the side, with the gripper approaching horizontally so the fingers squeeze the bar's top and bottom faces. But the task needs it level and ≥10cm above the table; a side grasp would work too, but the arm has limited range and the table may block. Also we can only control yaw (the approach direction is always straight down). Actually move_eef moves the grasp point in 3D; the orientation is fixed (pointing down). So the gripper always approaches from above. The fingers close horizontally.\n\n5. Support the bar's tilt by choosing the grip at the bar's COM in y AND ensuring deep contact, then lift SLOWLY. We did lift at 0.03 m/s. It still tilted. Possibly the bar is rotating because the grasp point is at a different y than the COM. If the bar's COM is at y=0 but the grasp is at y=+0.012 (we moved +0.012 based on a rough estimate), that's a 1.2cm offset → a torque of m*g*0.012. The fingers must resist with their friction and contact patch. If the contact patch is 1cm tall, the resistance torque is limited.\n\nActually here's a cleaner idea: measure the y-center precisely from the wrist image when directly above the bar and the bar is on the table. We did that, but the estimate is crude (±1cm).\n\n6. Alternative: use BOTH the agentview and the wrist to precisely localize. Actually a better idea: use the agentview's bar position in s000 vs s014 vs the s003/s007 wrist images... hmm.\n\n7. Alternative approach: grasp the bar LENGTHWISE at two points? Not possible.\n\n8. What if we grip the bar at its center in y but the tilt is due to the bar's center of mass being slightly off-center in y? Then the bar would settle at a tilt where the fingers' contact provides the counter-torque. Since the gripper's fingers can only apply torque through contact, a deep grip (fingers covering the full 4cm height) provides much more resistance. We did grasp at z=0.017, fingertips at ~0.007 → full coverage. And still it tilted a lot (~27°).\n\nHmm, that's suspicious. A deep grip should resist. Unless the fingers are NOT gripping the bar's flat sides but rather its top edges (the pads are angled/grooved). Or the grip is loose (width 0.041 exactly = the bar width, maybe just touching).\n\nWait, maybe the bar isn't 0.03 wide but the fingers are closed at their minimum 0.04? No, the minimum is ~0 (fingers can fully close). It stopped at 0.041 meaning it's touching the bar's sides.\n\nHmm, maybe the physics grip is slippery and the bar rotates freely. \n\nLet me look at the s014 tilt more carefully — maybe the bar isn't rotating about the grip but sliding down/slipping. The gripper is at z=0.117 and the bar appears below the gripper... In s014 the bar's top surface appears ~5cm below the gripper's fingers? Hard to tell.\n\nNew idea to get a level bar: Since the gripper is parallel to the bar's long axis?? Wait! With yaw=-90, the fingers close along x, and the finger PADS face each other along x. The pads are flat plates facing ±x. The bar's long axis is along y, and the pads contact the bar's long sides (x = ±0.02 faces) — the contact area per finger is the pad's height (z) × pad width (y). Correct.\n\nThe pad width along y is maybe 1.5 cm, height ~3-4cm. Contact at the bar's mid-y. That should be stable unless the bar's COM in y is off by more than the pad's half-width... no, the bar's COM y is what matters. If the COM is within the contact patch (in y), it's stable; if off by more than ~1cm, it tips.\n\nSo the bar's COM is probably 2-5 cm off from where I gripped → significant tilt. That means my y estimate was off. I estimated y_bar - y_eef ≈ +0.012 from the wrist image; if the real offset is -0.03 or +0.05... Hmm.\n\nWait, actually! Maybe the bar's y center was never at 0. In s000 the eef was at y=0 and the agentview bar's center at x_pix 247 vs the gripper at 250 — but the agentview's horizontal is mostly y, so the bar ≈ y=0. Hmm.\n\nUnless the tilt direction tells us: in s010 and s014, the bar's LEFT end (in the image) was UP or DOWN? In s010: left end at (172,315), right end at (345,240) → the left end is DOWN (larger y pixel = lower). In s014: left (190,320) down,... wait (190,320) vs (345,205): left end lower. Both same direction.\n\nThe world y axis maps to the image horizontal. Which direction? For the agentview, hmm.\n\nLet me now use a much more reliable approach: calibrate the agentview camera from scratch using the wrist-based localization... no.\n\nAlternative: exploit the physics. If the grip point is off the COM, the bar will rotate until the torque balances. We could re-grasp iteratively: after lifting, check the tilt direction; if the -y end sags, move the grasp toward -y, etc. It converges in a couple of iterations.\n\nBut we only have 26 commands; that's fine.\n\nBut is the sag direction informative? The sagging end is farther from the grasp point, so move the grasp toward the sagging end. In the image, the sagging end is the LEFT end (lower). So the grasp point should move toward the LEFT end's world direction.\n\nWhich world direction is the image-left end? From the wrist analysis: at yaw=-90, image right = -x in the WRIST camera. The agentview is a different camera. In the agentview, the left-right axis is mostly ±y. \n\nLet me determine it: In s003→s004, we moved the eef x. In the agentview, did the gripper move horizontally? At s003 the eef was at x=0.45; s004 at x=0.348. Looking at the agentview images: s003 gripper fingers around x_pix 250; s004 around x_pix 240? They look similar-ish, with the arm elbow changing. So x maps weakly to the image horizontal (a few px per 10cm) — meaning the agentview's horizontal is nearly along y (with a small x component from the camera azimuth).\n\nSo the image-left end ≈ -y direction with some x component (maybe up/down too).\n\nOK here's a cleaner approach to resolve everything: use the wrist camera to measure the bar's tilt and its y-offset, since we can look straight down at the bar and see the actual geometry.\n\nIn s014's wrist image (holding the bar): the bar's silhouette from (215,120) to (190,390) — nearly vertical, tilted slightly. Hmm, the wrist view at s014 shows a tall trapezoid from x 215-295 at the top to 185-330 at the bottom. So the bar is nearly vertical in the wrist image → meaning the bar's long axis is aligned with the image vertical = ±y. Wow, but in the agentview it looked strongly tilted!\n\nIf the wrist camera is looking straight down (axis along z), then the bar's projection shows its y-x footprint. In the s014 wrist image, the bar appears vertical (along the image's vertical = y direction) and tilted only slightly. If the bar were pitched (rotated about x), then in the top-down wrist view its projection would still be a vertical strip (the projection of a pitched bar is shortened in y but stays vertical). The bar spans y_pix 120→390 at the top the width 80 px, and the bottom 145 px wide. So the bar's image-y extent shrinks a bit.\n\nSo from the top-down wrist view: the bar's y-extent is 270 px vs the projected... hmm, this is consistent with a pitch (the projection shortens) rather than a yaw. A yaw would show as an slanted bar in the top-down view (it does look slightly slanted: 215 at the top vs 185-330 at the bottom... the center at the top 255, the bottom 257 — actually centered!).\n\nSo from the wrist top-down view: the bar is NOT yawed (it's along y) and it's pitched (its y-extent shortened). Wait, but the projection of a pitched bar (about x) in a top-down view is shortened by cos θ and stays centered. The bottom being wider is just perspective (closer).\n\nThen why did the agentview show the bar's horizontal span shrink (155 vs 175)? If the bar is pitched (not yawed), the agentview's horizontal span should be 175 cos θ... yes! Because the agentview's horizontal is the y axis (mostly), and the bar's y-extent is L cos θ. The camera's perspective means we see the bar's projection. So the agentview horizontal = L cos θ = 175*cosθ = 155 → θ=27.6°. Consistent with a pure pitch about x. And the vertical drop (81 px predicted vs 115 observed) — the discrepancy is due to the agentview's camera tilt making the z axis project with a different apparent scale... Actually no, in a perspective camera, the image scale for z and y is the same only if both are perpendicular to the optical axis. The optical axis is tilted (looking down at ~45°), so the z-axis has a component ALONG the optical axis; the projected z shift also changes the depth, which magnifies. So yes, a z shift can appear larger than a y shift. ✓ Consistent with a pure pitch of ~28°.\n\nGreat: the bar is pitched ~28°, and the wrist view is consistent.\n\nNow the direction: which end is up? In the agentview, the right end is up. Which world y is the image right? Let me determine using the wrist camera: the wrist image's up = -y (derived). In the s014 wrist image, the bar's top (image top) is at pixel y=120 — the bar's far end. The top of the wrist image = -y (since up = -y). So the -y end appears at the image top (far) ✓ (makes sense: the top of the wrist image is the far part).\n\nIn s014's wrist image, the bar's top edge is at 120-155 (spanning x 215-275) and the bottom at 390. Both ends visible. The top surface: the bar's near end (-y... wait) — hmm, the bar's bottom in the wrist image (larger pixel y) = +y (near the camera center). \n\nI need the pitch direction. In the wrist image, a pitched bar (about x) would appear shorter. The bar's visible y-extent 120-390 = 270 px. Norm: at s008 (bar on the table, eef z=0.033), the bar's y-extent went off-screen (0-512+). At s007 (z=0.117), the bar spanned 55-430 = 375 px. Hmm, different distances.\n\nNot a good calibration. Let me instead determine the pitch direction from the agentview: the bar's right end is UP.\n\nTo map the agentview's image right to the world y sign, use the wrist camera's relation to the gripper and the agentview. Hmm.\n\nAlternative: use a robot motion test in the agentview: move the eef in +y and see if the gripper moves left or right in the agentview. This is cheap (1 command) and would clarify. Actually, in s011→s012 we moved y from 0.0014 to 0.0124 (+0.011) and also z down; in the agentview the gripper moved... compare s011 (fingers at x_pix ~250) to s012 (fingers at ~252)? Slight right. Inconclusive due to the z change.\n\nLet's do a clean test: move y=+0.05 at the current pose (holding the bar). Hmm, better: do a small y move while holding and see which way the bar's tilt changes? Not clean either.\n\nActually, I could just determine the pitch direction in the wrist frame directly! The wrist camera is on the gripper, and I know the fingertip geometry. In the s014 wrist image, I see the bar and the two fingers at the bottom. If the bar is pitched, then one end will be closer to the camera (larger) — the far end appears higher in the image and smaller, the near end lower and larger. In s014's wrist image: the top portion is narrower (80 px) and the bottom wider (145 px). So the top (image up = -y) end is farther from the camera → the -y end is DOWN (lower z). Wait, \"farther from the camera\" for a top-down camera means LOWER z. Yes! Since the camera looks down, farther = lower.\n\nSo the -y end of the bar is LOWER. Hence the +y end is up.\n\nNow check consistency with the agentview: the image-right end is up → so the agentview's image right = +y. Good, and that also matches the s000/s001 gripper alignment.\n\nHmm OK, but the key insight: the bar tips because the grasp point is at a y that is too far toward -y?? Let's think: if the bar is held at the grasp point g_y and its COM is at y_c, gravity creates a torque about the contact... The stable orientation is when the COM is directly below the grip point. So if the bar tips with its -y end down, the COM has moved toward -y, meaning y_c > g_y initially? No wait: if it rotates with the -y end down, then the COM (initially at y_c) moved in the -y direction, which happens if y_c > g_y... Hmm: rotating about the grip point g, a point at y_c overshoots... Let the rotation angle be θ about the x-axis: the COM at (y_c, z_c) relative to the grip rotates. If the COM started at y_c - g_y = d > 0 (the +y side of the grip), a rotation that brings it down would rotate the +y side DOWN, i.e., the +y end down.\n\nWe observe the -y end down, which means the COM was on the -y side: y_c < g_y, i.e., the grip is at a y greater than the bar's COM. So I should move the grip in the -y direction (toward the -y side). And indeed I moved +0.013 in y before grasping based on my (possibly wrong-direction) estimate. Earlier, the tilt at s010 (grasp at y=0) was similar to s014 (grasp at y=+0.012). Hmm, if y=0 was already close to the COM, the tilt should have been small at s010. Both tilts were similar (~28°), which suggests the tilt is NOT from a COM offset but something else!\n\nHmm. Wait, if it's not a COM offset, what else? Both grasps at y=0 and y=+0.012 produced ~28° tilts in the same direction. A systematic cause...\n\nOH WAIT. I bet I know: the bar's initial placement on the table—it's a box that could be resting tilted? No, at s000 it looked flat.\n\nAnother thought: maybe the tilt isn't real; maybe the bar is level and the agentview camera has significant perspective making it look tilted... no, the s000 bar looked horizontal with the same camera.\n\nAnother cause: the GRIP might be at the bar's end! If the bar's y-extent is 0.2 and the grasp is at y=0 = the center... unless the bar is not centered at y=0! In s000, the bar's center in the agentview was at x_pix 247 and the gripper was at ~250 — but if the agentview's horizontal axis is mostly y, then the bar's center y ≈ 0 ± small. But the perspective: the gripper is at z=0.26 and the bar at z=0.04; the same world y projects to different pixels due to the camera tilt. Hmm, the camera has an azimuth too.\n\nLet me be rigorous and calibrate the agentview camera with the observations I have. I have data: (eef 3D positions, and the corresponding fingertip pixel positions in the agentview). The fingertips are approximately at (eef_x, eef_y, eef_z - 0.01) and the pads are at ±0.04 in the closing direction within ±0.02.\n\nRather than that, an easier self-consistent approach: I have the bar's pixel geometry in s000 and the wrist-camera localization of the bar. Ugh.\n\nAlternative simpler solution: don't rely on the grip's torque balance. Instead, grip the bar and then... hmm, we need it level.\n\nWAIT. Big realization: Maybe the bar isn't tilted at all — maybe it's SLIPPING down between the fingers, hanging from one side. Look at the agentview s014: the bar's center appears BELOW and to the LEFT/RIGHT of the fingers. Actually in s014, the fingers (white pads) are at (250, 230-280) and the bar's near end is at ~(215,270)... The bar may be hanging from the tips.\n\nLet me just zoom into the images to inspect.", + "Need to find the workspace directory.", + "Hmm, the shell's working directory is different from the robot workspace? Let me check pwd and search more broadly.", + "Now I see clearly. In s014, the bar is tilted: the right end is up and back; the left end is down and forward. And importantly, the bar is NOT between the fingers — looking at the image, the gripper fingers (the two white pads straddling) are gripping the bar near its middle, but the bar's near/left end is far below. Hmm, actually looking closely, the gripper fingers appear to be at the bar's... let me look: the white pad on the left side of the gripper goes down to y~320 (in crop), and the bar passes behind/under. It looks like the bar is gripped at the far end (the right part), with the left end extending out.\n\nActually wait: the crop shows the gripper fingers at x 320-410 and the bar crosses diagonally from (150,420) to (610,110). The gripper contact is around (350,250). The bar's length spans from the left-bottom to the right-top.\n\nHmm! Now I strongly suspect the bar is held at a point ~1/3 from the right end and it's tilted due to gravity — the left portion is longer/heavier, so it sags. That means the grip is NOT at the bar's center in y — it's off by a lot. The bar's far (right) end is up, the near (left) end is down.\n\nGiven that both my grasps were at y≈0 and y≈+0.012, the bar's center must be far from y=0, e.g., y_bar_center ≈ +0.06 or more (in the direction of the up end). But then the wrist view would show a big y offset... The wrist view showed the bar roughly centered.\n\nHmm, unless the bar's length is not 0.2 m but longer? The bar in the agentview spans 175 px and I assumed 0.2 m. What if the bar is 0.3 m? Then the y-extent is bigger, and my estimate of ~0.2m was based on... nothing! Let's check: the bar's aspect ratio in s000: length 175 px, height 34 px, width 50 px (wrist). So the length/height ratio = 5.1. If the height is 0.04, the length = 0.2. But maybe the bar is 0.05 tall and 0.25 long = 5:1. Hmm.\n\nThe height is unknown. Let's get the height from the wrist image: In the s008 wrist (eef z=0.033, so the camera is at 0.103 above the table, bar top ~0.04?): the bar occupied the entire image... no.\n\nOK let's estimate the bar dimensions from the s000 agentview: the camera sees the top face (light grey, 34px tall in the image? no). Let me measure precisely with pixel analysis. The bar in the crop: the top face light grey and the front face darker. In the crop, the top face spans y 355-400 (light) and the front face 400-455 (dark). The bar's length: 60-585 in the crop (scale 3x: original 160-335 ✓).\n\nThe top face's projected height 45px(crop)=15px(orig) — this is the width (0.04?) foreshortened by the camera angle. The front face's height 55px(crop)=18px(orig) — the height.\n\nHmm, so the bar height appears as 18 px vs length 175 px → height/length = 0.103. If length=0.2 → height=0.021. Hmm, but the front face's height is affected by the camera's downward angle (the height is vertical, perpendicular to... the camera looks down at maybe 40° so the vertical extent is foreshortened by sin? no, cos...). Ugh.\n\nI really need a good localization method. Let me use the wrist camera more cleverly: the bar's width from the s007 wrist image (eef z=0.117, camera z=0.187 approx): the top face spanned 200-275 px = 75 px. If the width is w and f=287: w = 75*d/287 where d = 0.187 - h (bar top height). If h=0.04, d=0.147 → w=0.0384. If h=0.05, d=0.137 → w=0.0358. If the bar's cross-section is square (0.04x0.04), that's consistent with either.\n\nWait, I realize I have a scale calibration available in the wrist image: THE FINGERS! The gripper's fingers when fully open are at ±0.04 (width 0.08). In the s007 wrist image (gripper open at 0.08), the finger pad inner faces are at 120 and 390 → 270 px for 0.08 m at the fingers' depth (which is much closer to the camera, ~0.05 m). Scale at the finger depth = 270/0.08 = 3375 px/m → f = 3375*0.05 = 169. Hmm, that gives f=169, not 287. But the finger depth is unknown (maybe 0.06) → f=202. Hmm.\n\nLet me get f from a different known: the gripper width changes. In s013/s014, the gripper width = 0.041. In the s014 wrist image, measure the finger separation. If I get two images at different known widths at the same pose, I can compute f/d_fingers. Not exactly the same pose though.\n\nAlternatively, use the bar's width measured at multiple distances: s005 vs s007 gave 50px at d and 75px at d' with known eef z. I solved d1=0.23 earlier only assuming widths equal. Fine—consistent with f≈287 if h=0.04.\n\nAlternatively use the eef z change: Δz = 0.2024-0.1173 = 0.0851. d1/d2 = 75/50 = 1.5 → d1 = 1.5 d2, d1-d2 = 0.0851 → d2 = 0.170, d1 = 0.255. Then the bar top z = eef_z + Δcamera - d. If the camera is at eef + 0.07: d2 = 0.117+0.07-h = 0.187-h = 0.170 → h = 0.017. Hmm! So the bar top is at 0.017 and the bar height ~0.017? That seems short but possible? Then the bar is 0.017 tall with a length of 0.2... a very flat bar? But the s000 image shows a substantial height.\n\nHmm, the wrist camera height offset isn't exactly 0.07, and d is measured from the camera to the bar's TOP FACE, not to the visible edge. Uncertainty accumulates.\n\nLet me step back and think about a robust plan that doesn't require precise knowledge:\n\nThe core difficulty: the bar tips in the grip. Why? Likely the grip point is off-center along the bar. Can I directly measure the grip's y-offset using the wrist camera? YES — once grasped and lifted, the bar's position relative to the gripper is directly visible in the wrist image! In s014's wrist image, the bar's silhouette: top at 120, bottom at 390, spanning 270 px, and the fingers at ~110 and ~370 with the bar between them... \n\nHmm wait, in s014's wrist image the bar is huge and goes from y=120 to 390, with a width at the bottom of 145 px. If the bar were gripped at its center, its symmetric extent in the image... The image vertical center is 256; the bar spans 120-390 → center 255! That's symmetric with respect to the camera axis, suggesting the grip IS at the bar's center y!! Unless the projection is distorted by the pitch.\n\nHmm, but wait: with the bar pitched 28°, the far end (up, -y... ) projects... Let's think: the bar is gripped at the point g and pitched. The projection of the bar's two ends onto the wrist camera's image: end1 at (y=-0.1cosθ, z=-0.1sinθ+...) hmm in the gripper frame, ends at Δy = ±0.1cosθ, Δz = ∓0.1 sinθ (one up, one down).\n\nThe camera is above the grip point at height h_c. The end that is UP is closer to the camera → appears farther from the image center in the y direction (magnified) and the down end appears closer to the center. Observed: the bar spans 120-390 with the center at 255, but the TOP part is narrower (80px) and the BOTTOM wider (145px). Wait, the width indicates distance: the wider part is closer to the camera. So the bottom is closer → the bottom is UP? No! The bottom of the image is closer to the camera in the tilt sense? The camera looks down; an object closer to the camera (smaller d) appears bigger. So the bottom (width 145) is closer to the camera → the bottom end is HIGHER (closer to the camera). \n\nLet me redo: earlier I said the top is narrower → farther → lower. Same conclusion: the top end is lower, the bottom end is higher. And the image up = -y, so the top = -y → the -y end is LOWER. The bottom = +y end is HIGHER. ✓ (as before)\n\nHmm wait, that contradicts my \"bottom is closer → higher\" statement? Top narrower = farther from camera = lower. So the -y end is lower. ✓ Consistent.\n\nSo the bar's +y end is up. In the agentview, the up end was the image-right end. So the agentview's image right = +y.\n\nNow, which side of the grip is the bar's COM on? If the bar is stable at a 28° tilt, then the COM is directly below the grip (roughly): the COM's y offset from the grip = -sinθ * (distance from the grip to the COM along the bar)? For a uniform bar gripped at distance s from the center (measured along the bar toward +y), the COM is at y = -s cosθ relative to the grip. For the COM to be directly below the grip, we need y_COM = 0 → s cosθ = 0 → s = 0. So a uniform bar is only stable when gripped at its center! At any off-center grip, the bar swings until the COM is below the grip; the equilibrium is with the bar hanging vertically (θ=90°) if the grip is at the end... \n\nHmm, actually the equilibrium angle: with the grip at distance s from the COM, the bar hangs with the COM directly below the grip → the bar is vertical (θ=90°) regardless of s (unless the fingers' contact torque holds it).\n\nBut here the bar is at ~28°, not 90°. So the fingers' contact torque balances the gravity torque. The contact can provide a limited torque (proportional to the grip force and the contact patch size). So: the bar slipped/rotated until the friction/contact torque balanced. With a gripper closing with a fixed force, the max torque = μ·F·(contact patch half-height) or the finger's normal force acting on the bar's edge...\n\nHmm, wait. There's another possibility I overlooked: the bar may be resting against the fingers in a way that it's not actually gripped but the fingers press it against... \n\nLet's think about whether the tilt direction tells us the grip's offset: the bar rotated with its +y end up. Rotating about the x-axis, the +y end goes up. The COM must be at y<0 relative to the grip (on the -y side) → the grip is on the +y side of the bar's center.\n\nIf the bar's center is at y_bar (unknown, presumably 0) and the grip at y_grip=+0.0124, then the grip is on the +y side if y_bar < 0.0124 → consistent if the bar's center is at y ≈ 0. Then the offset is only 0.012 → the torque would be tiny, and a 28° tilt seems too much.\n\nUnless the gripper fails to grip (the fingers' pads are barely touching the bar's sides because the bar's width is at/below the finger's stop). The gripper closed to 0.041 and stopped — so it's touching. But maybe just barely (the bar width is exactly 0.040 and the fingers stop at the first contact with little force?). Hmm, but if the object is rigid, the gripper's force is applied.\n\nAlternatively, the bar's width is 0.040 but the pads contact only at the top edge (since the pads may be angled inward at the top). Then the contact is at the bar's top corner, and the bar hangs below the pads → the COM is below the pad contact, and any lateral offset above the pivot line... hmm.\n\nOK, empirical approach: shift the grasp in y and see how the tilt changes. The direction: the bar's +y end is up → the COM is on the -y side of the grip → move the grip toward -y (in the direction of the sagging end).\n\nWe had grasp y=0 → tilt; then y=+0.0124 → similar or worse tilt. That's consistent with the direction: moving +y made the grip more off-center → more tilt. Actually compare s010 (y=0.0002) and s014 (y=0.0124): I can measure the bar's tilt in both. s010: from (172,315) to (345,240), Δ=(173,-75), length 188, angle 23.4°. s014: (150,420) to (610,110) in crop coords → original /3: (50+140, 140+170)... let me just measure programmatically. I'll threshold the bar color and fit the long axis.\n\nLet me do that, and also compute for s000.\n\nActually, a cleaner and much more reliable idea: use the WRIST camera to measure the bar's tilt after lifting! The wrist camera is attached to the gripper, looking down. In the wrist image, the bar's projected long-axis direction gives the tilt angle in the image plane. If the camera is looking straight down at the bar, a bar at tilt angle θ about x projects with length L cosθ in the y direction and 0 in x → so its image would be a shortened vertical strip, and the \"width\" changes. But I can't distinguish a yaw from a roll by the projection alone... Actually I can: the bar's width in the image and the visible side faces reveal the pitch (perspective).\n\nHmm.\n\nCompletely different, more robust plan: can I get the bar level by using a different grasp? For instance, grasp the bar near its end and hold it so that the bar hangs... no, it must be level.\n\nWhat about holding the bar with the gripper fingers clamped on the bar's TOP and BOTTOM? Not possible (fingers close horizontally).\n\nWhat about grasping the bar at its center and then rotating the gripper yaw about the vertical: this doesn't help with a pitch.\n\nKEY INSIGHT: since the equilibrium tilt depends on the grip's y offset, I can find the y that makes the bar level by iterating. And a level bar means the grip is at the COM. I'll iterate: grasp at y_g, lift, measure the tilt direction/magnitude in the agentview, adjust y_g toward the sagging end, repeat. Each iteration costs ~5 commands. We have 26.\n\nBut first I need to map the agentview's tilt to the world and get numbers. Alternatively use the WRIST image which is top-down and easier: when the bar is level, the bar's projection in the wrist image is symmetric (both ends at the same distance). When tipped, one end is closer (bigger) — the width at the two ends differs, as we saw.\n\nActually here's the cleanest measure: in the wrist image, measure the bar's projected length (in the image vertical) relative to the gripper. For a level bar, the two ends are at equal distance; the image strip has a constant width. For a tipped bar, the strip is tapered.\n\nAlternatively use the agentview's tilt of the top face's line: that's a direct measure of the angle... but not the true 3D tilt angle, though it's monotonic. Let me just calibrate it empirically with the known initial state (level: 0°) — the s000 line is ~horizontal (0 tilt in image). Good: so the image tilt of the bar's long axis is a monotonic proxy, and it's 0 when level.\n\nHmm, but the relation between the image tilt and the true tilt is not linear/known. Still, I can minimize it.\n\nAlternatively, wait. Maybe there's a much better approach to avoid the torque problem entirely: GRASP THE BAR AT ITS CENTER OF MASS along y AND ALSO make sure the fingers grip deeply and with maximum force. The grip force is fixed by the controller (the \"close\" command).\n\nHmm, but the initial grasp at y=0 gave a 23° tilt — so either the COM isn't at y=0 or the grip is weak.\n\nLet me measure the bar's center y precisely first, using the wrist camera and a top-down view, using the KNOWN gripper finger positions as the reference! Here's the trick: in the wrist image, the two finger pads are visible; their inner faces are at x = ±w/2 where w = the gripper width. So I know the image positions corresponding to x=±0.0205. From that, I can get the scale at the finger depth, and also the lateral center (the grasp point projects to the midpoint of the pads). For the y direction, the pads' geometry gives a reference too: the pads' faces are centered along y at the grasp y. The pads are symmetric in y about the grasp axis. So the midpoint of the pad's y-extent ≈ the grasp y at the pad's depth. Then the bar's center in y can be compared to the pads' center in y — but the pads are much closer to the camera, so their projected center is not directly comparable... In a perspective projection with the camera directly above the grasp point, a point at (y, z) projects to an image y-coordinate proportional to y/(h_c - z). The pads at z_pad (close, ~h_c-0.03) → amplified. Hmm, but their center y=0 → projects to the center regardless. Good: the midpoint of the pads' projections = the image center (= the grasp axis).\n\nThen the bar's projected center at its depth vs. the pad midpoint: if the bar's center is offset from the grasp axis in y, its projection shifts relative to the image center. But the bar is tipped, complicating.\n\nUgh, I'm going around in circles. Let me take a practical approach:\n\nTest A: after the current tilted hold, slide the gripper in y to see... no.\n\nPractical: put the bar down, and grasp at a slightly different y (say y_g = -0.02, toward the sagging end), then lift and compare the tilt. If it decreases, continue in that direction.\n\nBut each attempt costs ~5-6 commands. Available: 26 commands, 98 s sim. Each move ~1-2 s. Fine for ~3 iterations.\n\nActually WAIT. Maybe there's a much simpler explanation I've been missing: the bar might be slipping in the grip because the gripper's closing force is weak, and the bar rotates to hang. If the bar hangs at 28° it means the fingers provide substantial torque resistance (contact patch). But if the bar were nearly at the center, it would be level ±few degrees. Hmm, in s010 (y=0) the tilt was 23° — that's big.\n\nHold on, maybe the y is NOT the issue: what if the bar's rotation is about the Z axis (yaw)? Then the bar stays horizontal and the task's \"tilt\" would be fine! The agentview image tilt could be from the yaw perspective effect (the near end appears lower). Let's check with the wrist top-down view: a yawed bar would appear as a slanted strip (its long axis not vertical in the wrist image). In the s014 wrist image, the bar's strip: at the top, x spans 215-295 (center 255); at the bottom, 185-330 (center 257). The centers are equal → no yaw. So it's a pitch. OK.\n\nHmm, but wait: the wrist camera might not be perfectly vertical (it could be tilted a bit), making a yaw appear as... no, the centers would still shift.\n\nSo a pitch of ~25-28°. The equilibrium is basically where the friction torque balances.\n\nNow, here's the thing: the friction torque capacity depends on the grip force and contact geometry. If the grip were at the COM, no torque would be needed and the bar would be level. So the grip must be off the COM.\n\nLet's estimate the offset from the tilt angle and the friction torque. Max friction torque ≈ μ N (patch half-size). Not needed.\n\nEmpirical iteration is best. Direction: sagging end (-y) → move the grip -y.\n\nLet me do it: lower the bar, move to y=-0.02, re-grasp, lift. To be efficient, combine: \n1. move z=0.02 (place the bar), open gripper — but the bar is tilted, so its end hits the table first at z... the bar's lowest end is ~0.09 below the grip; eef z=0.117 → the lowest point ~0.03. Lower to z=0.05 slowly and open → drops.\n\nHmm, dropping from a tilt might bounce it around. Let's lower to z=0.04 and open. The bar's lowest end is ~0.09 below the eef → at eef z=0.04 the end would be at -0.05 (below the table) — impossible; the bar will contact the table earlier and the tilt will correct as it's lowered. Then opening the gripper releases it flat. Good: lower to z=0.02 slowly with the gripper closed—the bar will pivot flat as it touches the table. Then open.\n\nThen the bar's position may shift. I'll look and re-localize with the wrist.\n\nLet's do it." + ], + "shell": [ + "cd /root 2>/dev/null; cd \"$(ls -d /*/obs 2>/dev/null | head -1)/..\" 2>/dev/null; pwd; python3 - <<'EOF'\nfrom PIL import Image\nfor name in ['obs/s000_agentview.jpg','obs/s014_agentview.jpg']:\n im = Image.open(name)\n im.crop((140,170,380,360)).resize((720,570)).save(name.replace('.jpg','_crop.png'))\nprint(\"ok\")\nEOF\nls obs | tail -5", + "find / -maxdepth 4 -name \"s000_agentview.jpg\" 2>/dev/null", + "pwd; ls -la; find / -name \"a1_s0*\" -maxdepth 6 2>/dev/null | head", + "cd /opt/lffjail/work && python3 - <<'EOF'\nfrom PIL import Image\nfor name in ['obs/s000_agentview.jpg','obs/s014_agentview.jpg','obs/s014_wrist.jpg','obs/s013_agentview.jpg']:\n im = Image.open(name)\n im.crop((140,170,380,360)).resize((720,570)).save(name.replace('.jpg','_crop.png'))\nprint(\"ok\")\nEOF" + ], + "viewed": [ + "obs/s014_agentview.jpg", + "obs/s014_wrist.jpg", + "obs/s000_agentview_crop.png", + "obs/s014_agentview_crop.png" + ] + } + }, + { + "attempt": 1, + "step": 16, + "kind": "move_eef", + "frame_start": 691, + "frame_end": 706, + "command": "move_eef gripper=open speed=0.1", + "args": { + "gripper": "open", + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5954, + 0.0129, + 0.0236 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 94.06092143058777, + "agent_obs_images": [ + "obs/s016_agentview.jpg", + "obs/s016_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Tilt is caused by the grip being off the bar's center of mass. Testing a corrected y-offset." + ], + "reasoning": [ + "Note: 7.15 s wall / sim time dropped from 98.0 to 85.4 → 12.6 s of sim time! That's a lot. The move command took a while (maybe the bar dragging on the table). Careful with sim time: 85 s left.\n\nLet me check the image before opening.", + "The bar is back flat on the table and appears horizontal in the agentview. The wrist view at z=0.0236 shows the bar spanning x 190-330, center 260 — essentially centered (4 px right of center → bar_x = eef_x - 4*0.023/287... tiny).\n\nBut note the bar's position in the agentview: spans x 165-345, center 255. Earlier (s000) the center was 247.5. Hmm, the bar seems to have shifted slightly in y.\n\nInteresting: the wrist view now shows the bar nicely centered → the bar x ≈ eef x = 0.5955.\n\nNow let's test the hypothesis about y: actually, let me first re-derive the y of the bar relative to the gripper from this wrist image without a tilt: the bar's y extent spans the full image height, so I can't see its ends. Fine.\n\nLet me now perform the y-direction experiment. Rather than guessing, let me measure the tilt for grasp y=0 vs y=-0.02.\n\nActually, I realize I should reconsider whether the grip itself is the issue. Alternative explanation for the tipping: the bar's ends are heavy?? No, uniform.\n\nHmm, another thought: maybe the bar's COM y is far from 0 (say -0.03), and the tilt angle is limited by the finger contact. If the fingers grip with a contact patch of half-height ~0.015, the max restoring torque is F*μ*0.015 (friction) — weaker than the gravity torque m g s. For s=0.03: the gravity torque = m g 0.03 vs friction torque F μ 0.015. For m=0.2 kg, F≈20 N (gripper force), μ=0.5: gravity torque 0.06 N·m vs friction 0.15 N·m. So the friction could hold it level with s=0.03. But the normal force at the contacts can also produce torque if the contact is at the pad's edge.\n\nBut we saw a 25° tilt. So s must be bigger than 0.03-0.05.\n\nLet me estimate from the s014 image: the grip point at the bar's... In s014, if the grip were at the center, the tilt wouldn't happen. From the image, the bar's visible left portion (below-left of the gripper) is much longer than the right portion (above-right). The left portion is ~1.5x the right. So the grip is ~1/5 of the length from the right end → 0.04 m from the center. Hmm, that's plausible: a 0.04 m offset.\n\nBut my grip y was 0.0124, and if the bar's center is at y = 0.0124 - 0.04 = -0.028 (if the +y end is the \"short\" right side... wait: the +y end is up in the image, and the right end is up, so the right = +y. The grip is closer to the right end (+y side) → the bar's center is at y = y_grip - 0.04 ≈ -0.028.\n\nHmm! So the bar's center is at y ≈ -0.03. That's a significant offset. But then in the wrist image, the bar would appear offset by 0.03 in y... at d=0.09, 0.03*287/0.09 = 96 px. Hmm, in the s015 wrist image, the bar spans the full height so I can't tell.\n\nBut in s011 (bar on the table, eef y=0.0014, z=0.0563): the bar's y-extent center was 41 px below the image center. With up=-y and down=+y, 41 px down → +y offset → bar center = eef_y + 41*d/287. d = 0.0563+0.07-0.04 = 0.086. → +0.012. Hmm, that gives bar_y ≈ +0.012, not -0.028.\n\nUgh, conflicting. Unless the camera's y-offset is significant (the camera might be mounted with an offset in y).\n\nOK, let me do direct experiments. Plan: grasp at y=-0.025 (relative to the current bar position) and lift; observe the tilt. But I need to keep track of the current eef y=0.0128 and the bar's center ≈ the camera's... \n\nHmm, actually here's a cleaner idea to find the bar's y-center: use the agentview! The bar's end faces are visible on both ends (the left end face is visible in s000 crop, the right end too). If I can see both ends, the bar's center is the midpoint of its silhouette. But the world y mapping still requires calibration.\n\nNew idea for calibration of the agentview's y: MOVE THE GRIPPER in y by a known amount and measure its image x shift, at the same z. Two moves. That costs 2 commands but gives an accurate y mapping. Also for x. Then I can locate the bar's center in world y from the s000 image (plus the pixel positions).\n\nActually even better: I already have multiple gripper observations at different y? All were y≈0. Except now y=0.0128. Weak.\n\nAlternatively: calibrate with the wrist camera, which is much better resolved. In the wrist image, both the gripper pads and the bar are visible. Reference: the pads' midpoint = the image center in the y direction (if the camera is centered on the grasp axis). Reference check: in the s015 wrist, the pads are at the bottom left/right, their inner faces at x≈155 and 345 → midpoint 250 ≈ 256 (6px off). In the y direction, the pads extend from y≈390 to the bottom 512, so their y-center isn't visible (cut off).\n\nHmm.\n\nDIFFERENT STRATEGY: Solve the problem without knowing y! Use the fact that the bar hangs with its COM below the grip. If I grasp the bar at a point such that the bar is level, then the COM is at the grip. I can search for that y by iteration, but with a smarter measurement: the tilt angle in the agentview gives both the direction and magnitude. Two iterations should suffice if the relationship is monotonic.\n\nAlternative approach entirely: hold the bar level by IMMOBILIZING the bar's pitch with the fingers gripping near the END and the bar... no.\n\nAlternative: What if the tilt is caused by an asymmetry in the finger contact, e.g., one finger touching only at the top corner (because the bar is slightly wider than the gripper's jaw at the bottom)? Then the pivot is at the top and gravity's small offset creates a big tilt. In that case, grasping at the true y-center would still tilt if there's any residual offset.\n\nHmm, but a 25° tilt requires a big offset (≈4cm).\n\nWait, maybe I'm wrong about the bar's length! What if the bar is longer, like 0.25-0.3 m? Then the grip's offset would be bigger for the same visual asymmetry. Also, the agentview bar's projected length 175 px would imply a different scale... the scale is what it is.\n\nOK, let's do the experiment. The current bar is flat, eef at (0.5955, 0.0128, 0.0236), gripper closed (width 0.041). The bar is gripped at y=0.0128.\n\nI'll open the gripper, move y to -0.015, z to 0.015, close, lift, and look. Actually, we can move with the gripper closed? It's closed around nothing (width 0.041 — the bar is free on the table). Must open before moving in y at low z, else the closed fingers (0.041 apart) would drag on the bar. Open first (free action in the same command).\n\nSequence (each one command):\n1. move_eef y=-0.015 z=0.02 gripper=open speed=0.1 → open + reposition (this is one command; the open happens after the motion. Hmm, the gripper opens ONLY after the motion. So the move at z=0.02 with the fingers closed (width 0.041) would collide with the bar while shifting y. Risky but at z=0.02 with the tips at 0.01 between the bar's sides... the closed fingers at ±0.02 would drag along the bar's sides. Actually the width 0.041 = the bar's width, so the fingers are exactly touching; moving y would drag the bar along. Bad.\n\nSo: open first at the current position (a command), then move.\n\nCommand 1: move_eef gripper=open (at z=0.0236).\nCommand 2: move_eef y=-0.015 z=0.02 (descend a bit).\nCommand 3: close.\nCommand 4: lift z=0.12 slowly.\nThen observe.\n\nThat's 4 commands → down to 21. Then maybe 2 more iterations = 8 commands → 13 left. OK.\n\nActually, let me think about whether the tilt direction and magnitude are consistent between s010 (y≈0) and s014 (y=0.0124). If moving +y by 0.0124 made the tilt worse, then moving -y should improve. Let me measure the two tilts programmatically to compare.", + "The mask is catching more than the bar (s000 angle 102°, len 306) — it's including other stuff (maybe parts of the gripper or shadows). Let me restrict the region (the table area, y>200) and better color criteria. In s000 the bar is at y 285-325. Let me refine: the bar color is a dark blue-grey ~ (110,115,128)? Let me sample.\n\nLet me print unique colors in a region of the bar.", + "The mask includes the gripper (grey) — in s010/s014 the gripper is included. But the bar's spread is ~165 px consistently (the actual bar length projection along its axis is ~165 px in the tilted cases).\n\nThe measured \"angle\" is contaminated. Let me isolate the bar pixels by color more strictly. The bar top face ~ (94,104,106) B slightly > G. The gripper is grey/white with B≈R≈G. My criterion B>=R and B>=G would include grey where equal. Let's use B > G+3 to isolate the bar (bluish). Sample shows B=106, G=104 → B = G+2. Hmm, weak. Front face (72,75,80): B=G+5.\n\nLet me use the criterion B - G > 1 and B > R+4 and brightness < 130.\n\nAlternatively analyze specific columns/rows. Better: use the s015 (flat on the table) as a shape template and fit.\n\nActually, simpler: measure the top edge line of the bar (the boundary between the light top face and the background/table). Let me find, for each x column in 160-345, the min y where a bar-like pixel appears, restricted to a local window.\n\nAlternatively, since the bar is dark blue-grey and the table is tan, simply use \"B > R\" strictly (bar: B-R = 12 and 6; table: R-B = 32). The gripper: grey with R≈G≈B, so B-R ≈ 0 → excluded if I require B-R >= 3. Let's try.", + "Clean now. Note that the bbox ymin=190 for several because the gripper fingers are included? No—the mask is blue-requiring. Hmm, y min 190 in s010/s014: the bar is lifted so it's higher in the image. OK.\n\nNote the bar's length along its axis is ~165 px consistently! Even when tilted (s010: 167, s014: 165). That's remarkable: a pitch about x would shorten the projected length to L cos θ (if the projection's horizontal axis is y). Since the length stays 165, this must be a YAW rotation (about z), NOT a pitch!\n\nBut the agentview's image tilt for a yaw would come from the depth difference: one end closer (appears lower in the image). Hmm, but then the length projection would shrink by cos θ in the horizontal direction while the vertical adds. Total 2D length could stay similar if the y-scale and x-scale are similar. Right! For a yaw rotation, the endpoints move in y by ±(L/2)cos θ and in x by ∓(L/2) sin θ (with signs). In the image, the x displacement projects mostly vertically with a scale Sx, and y horizontally with Sy. Total length 2D = L*sqrt((Sy cosθ)² + (Sx sinθ)²). With Sx ≈ Sy, that's ≈ L constant. YES — consistent with a yaw!\n\nAnd a pitch would give image length = sqrt((Sy L cosθ)² + (Sz L sinθ)²) where Sz is the vertical scale. That's also constant-ish! Ugh, both are consistent with a constant 2D length.\n\nHmm. So I can't distinguish a yaw from a pitch from the length alone. But the wrist top-down view can: earlier at s014 the bar appeared as a strip whose center did not shift between top and bottom → suggesting no yaw. But the wrist camera might be tilted such that a yaw appears differently.\n\nLet's reconsider the s014 wrist image: the strip's center x: at the top 255, at the bottom 257. If the bar were yawed by 20-30° with the wrist camera looking straight down (up=-y), then the strip would be slanted by that same angle in the image → the center would shift by ~0.2*sin(25°)=0.085 m × scale(287/0.1=2870 px/m) ≈ 244 px. The observed shift is 2 px → NO YAW. \n\nUnless the bar is yawed exactly about the image's vertical... no.\n\nBUT hold on, the wrist camera's up direction: I derived image up = -y from \"right = -x\". If instead the wrist camera's \"up\" has a component, the yaw would still show as a slant.\n\nTherefore, it IS a pitch (~25-36°), and the wrist view should show a shortened bar along y. In s014's wrist, the bar spans 270 px vertically; at s008 (level, on the table, camera at 0.103): the bar spanned the full frame. Hmm.\n\nLet me test with math: if it's a pitch, then in the agentview the vertical drop should be = Sz * L sinθ. In s010, the image tilt is 24.7°, length 167. The vertical drop = 167*sin(24.7°)=70 px. And the horizontal = 152 px. For a pitch, the horizontal should be Sy*L cosθ = (bar's y-scale)*L*cosθ. In s000 (level), the horizontal length = 166 px = Sy*L. So a pitch of 24.7° would give a horizontal of 166*cos(24.7)=151 ✓ matches 152!!! And the vertical drop = Sz*L*sinθ = 70 → Sz*L = 167 px, so Sz ≈ Sy. \n\nFor a yaw: horizontal = Sy*L*cosθ = 151 ✓ same. Vertical drop = Sx*L*sinθ, with Sx≈Sy → also 70 ✓. Both fit. Argh.\n\nOK so use a third view property: in the agentview, a pitch about x moves the bar's ends in z; a yaw moves them in x. The bar's apparent length along its axis should be... For a pitch, the projected length = sqrt((Sy L cos)² + (Sz L sin)²). For a yaw = sqrt((Sy L cos)²+(Sx L sin)²). If Sz ≠ Sx, the total lengths differ. Observed: 166 (level) → 167 (tilted) for both s010 and s014. If Sz≠Sx we'd expect a difference but small if they're close.\n\nAlright, forget the agentview. Use the WRIST camera quantitatively: it's directly attached to the gripper, and the geometry is simpler. Let me take the s014 wrist image and measure the bar's strip: its width at several heights, i.e., its perspective taper. For a PITCH of θ: the bar's ends are at Δz = ±0.1 sinθ relative to the grip; the camera is at height h above the grip. The distances are h ∓ 0.1 sinθ. The bar's apparent width (its cross-section) is proportional to 1/distance. For the widths at the two ends: w1/w2 = (h+0.1sinθ)/(h-0.1sinθ). With the observed 145/80 = 1.8 → (h+d)/(h-d)=1.8 → d = 0.44h. If h=0.1 (camera to grip distance ~0.1), d=0.044 → sinθ=0.44 → θ=26°. Plausible! And if the camera is at h=0.13, d=0.057, θ=35°.\n\nFor a YAW of θ: the ends are at Δy = ±0.1cosθ, Δx = ∓0.1 sinθ, and both at the same z → the widths would be equal if the camera is directly above the grip... but the camera is offset laterally in x by c (~0.04). The distances would differ: d1 = sqrt(h² + (c+0.1sinθ)²), d2 = sqrt(h²+(c-0.1 sinθ)²). With h=0.1, c=0.04, θ=25°: d1=sqrt(0.01+0.0148)=0.157, d2=sqrt(0.01+0.0001)=0.100 → ratio 1.57. Also big. Hmm, so both give a taper.\n\nOK, one more decisive test: the bar's projected LENGTH along y in the wrist image (top-down). For a pitch of 25°, the length would be L cosθ = 0.2*0.906 = 0.181 m. For a yaw of 25°, the projected length along the image y would ALSO be L cosθ. Argh, identical.\n\nBut: for a yaw, the bar's strip would be slanted in the image by 25° (unless the camera is offset exactly along the slant direction...). Hmm, actually a yaw moves the bar's axis in the horizontal plane; a top-down camera would show the slant directly. The s014 wrist strip was vertical (no slant) → NO YAW. I trust that because a slant of 25° would be very visible.\n\nTherefore: PITCH ≈ 25-35°. And the pitch means the bar rotated about the x-axis: one y end up.\n\nNow, does the grip's y-offset explain a pitch? Yes, exactly (torque about x).\n\nGiven a pitch, my y-search iteration is the right approach. The +y end is UP (established from the wrist taper: the bar was wider at the image bottom = closer to the camera = up... wait, careful: the image bottom is where the fingers are, and the camera is at the center. Hmm, \"closer to the camera\" = smaller distance h-z, so a larger apparent width regardless of image position. The bottom end appeared wider → the bottom end is closer to the camera → higher z. The bottom in the wrist image = +y (image up = -y). So the +y end is higher ✓ (as I concluded).\n\nSo the bar's +y end is up → the COM is on the -y side of the grip → move the grip toward -y.\n\nFrom s010 (grip y≈0) the pitch was 24.7° (image angle) and s014 (grip y=+0.0124) gave 36.4°. So moving the grip +y made it worse ✓ consistent with the direction. Good, so moving -y should reduce it.\n\nEstimate the sensitivity: Δangle ≈ 11.7° for Δy_g = +0.0124. Naively, θ ≈ k·|offset|. At y_g=0, θ=24.7° → k ≈ 24.7/(offset). Linear extrapolation: to reduce θ by 11.7 per 12.4mm → to go from 24.7 to 0, need -26mm. So y_g ≈ -0.026 relative to the y=0 grasp. So the bar's center ≈ y=-0.026 (in the frame of the s010 grasp). But the bar may shift between grasps.\n\nHmm, 2.6 cm on a 0.2 m bar. Plausible.\n\nHowever, the linear extrapolation isn't guaranteed (the tilt angle vs offset relation is nonlinear: the finger torque capacity limits it). But let's try y=0.0128-0.028 = -0.015. Hmm, I had planned -0.015 already.\n\nActually, an important consideration: even if I get the bar perfectly balanced, any small residual offset gives a tilt of maybe 5-10°, which might fail the 8° threshold. Risky.\n\nAlternative more robust plan: SLIDE the bar? No.\n\nAlternative: grasp the bar and let it hang, then... no.\n\nThink differently: is there a way to hold the bar level despite an off-center grip? Yes: use the table as a reference—no, it must be 10cm up.\n\nWhat about grasping the bar at BOTH... we only have one gripper.\n\nHmm, what if the bar's rotation is actually quite free and it just hangs at the equilibrium angle? Then a slight grip offset gives a slight tilt, and the angle would be proportional. With a 2.6cm offset giving 25°, an offset of 0.8cm gives 8°. So I need the y within ~8mm of the ideal. Doable with iteration.\n\nAlternatively: consider that the \"tilt\" evaluation probably uses the bar's long-axis orientation in 3D. If the bar is pitched 25°, it fails.\n\nWait, actually — is the bar maybe lying flat against the finger pads, i.e., not really between them? Look at s014: the fingers appear to grip the bar's END region... \n\nLet me look at the s014 wrist image again with the realization it's pitched: the bar occupies the image from y=120 to 390, a projected length of 270 px. At a scale of ~287/0.09 = 3190 px/m (the bar's mid-depth), 270 px = 0.085 m. That's way less than 0.2 m! So the bar's projected y-extent is only 0.085 m → cos θ = 0.42 → θ = 65°!? That can't be right; the agentview shows ~25-36°.\n\nMy scale estimate for the wrist camera must be wrong. If the projected length is 0.2*cos(30°)=0.173 m and it spans 270 px, then the scale is 1560 px/m at that depth → f = 1560*d. And the bar's width 0.04 m would be 62 px — but the observed widths were 80-145 px. Inconsistent (the 145 comes from perspective spread though).\n\nThe wrist camera likely has a wide FOV and the bar is close; perspective distortion makes linear scaling invalid.\n\nI think I'm over-analyzing. Let's go empirical: try y = -0.015 (or -0.02) and measure the agentview tilt. Iterate.\n\nCurrent: grip at y=0.0128 gave 36.4°. At y=0: 24.7°. So Δy=-0.0128 gave Δangle=-11.7°. Assume a linear relation in this range: to reach 0 from 24.7 at y=0, need Δy = -0.027 → y=-0.027. But the tilt likely saturates/asymptotes; the relation may be more like tan θ ∝ offset, i.e., the offset is what drives it. If θ = atan(k*offset) then at y=0, offset = y_c - 0 = ... Let me model: offset o = y_c - y_g. tan θ ∝ o. At y_g=0.0128: θ=36.4, tan=0.737. At y_g=0: θ=24.7, tan=0.460. Slope = (0.737-0.460)/(-0.0128) → k = -21.6 per m. Then o at y_g=0: 0.460/(-21.6)= -0.0213 → y_c = -0.0213. Then to get θ=0, y_g = -0.0213.\n\nBut careful: the agentview's image angle isn't the true tilt angle. Still, the linear model gives y_g ≈ -0.021.\n\nAlso, the bar's position may change between grasps. I'll re-localize each time with the wrist image (x-center).\n\nPlan:\n1. Open the gripper (currently closed at width 0.041 with the bar on the table).\n2. Move to y=-0.021 (x stays 0.5955), z=0.02 at speed 0.1.\n3. Close.\n4. Lift to z=0.12 at speed 0.03.\n5. Observe the agentview, compute the angle.\n\nAfter step 2 the bar may shift in y since the fingers drag... the fingers are at ±0.0205 and the bar's width 0.04 → touching. Moving y with the fingers closed would drag the bar. So open first (step 1) then move (step 2) with the fingers open (0.08).\n\nLet me also confirm the bar doesn't shift when opening (it shouldn't; it's on the table).\n\nGo." + ], + "shell": [ + "cd /opt/lffjail/work && python3 - <<'EOF'\nimport numpy as np\nfrom PIL import Image\nfor n in ['s000','s010','s014','s015']:\n im = np.asarray(Image.open(f'obs/{n}_agentview.jpg').convert('RGB')).astype(int)\n R,G,B = im[:,:,0],im[:,:,1],im[:,:,2]\n # bar is bluish-grey: B slightly > R, and darker than table; table is tan (R>B)\n mask = (B>R+3) & (R>40) & (R<150) & (G>R-10)\n ys,xs = np.nonzero(mask)\n if len(xs)<50:\n print(n,'no mask',len(xs)); continue\n # PCA\n pts = np.stack([xs,ys],1).astype(float)\n c = pts.mean(0)\n u,s,vt = np.linalg.svd(pts-c)\n d = vt[0]\n ang = np.degrees(np.arctan2(d[1],d[0]))\n ext = np.ptp((pts-c)@vt[0])\n print(n, 'n=',len(xs),'center',c.round(1),'angle_deg',round(ang,1),'spread',s.round(1),'len_px',round(ext,1))\nEOF", + "cd /opt/lffjail/work && python3 - <<'EOF'\nimport numpy as np\nfrom PIL import Image\nim = np.asarray(Image.open('obs/s000_agentview.jpg').convert('RGB')).astype(int)\nprint('bar top face sample', im[295,250], im[300,200], im[315,250])\nprint('table sample', im[400,250], im[250,100])\nprint('shadow', im[340,250])\ndef bar_mask(im):\n R,G,B = im[:,:,0],im[:,:,1],im[:,:,2]\n return (B>=R) & (B>=G) & (R>50) & (R<160) & (np.abs(R-G)<15)\nfor n in ['s000','s010','s014','s015']:\n im = np.asarray(Image.open(f'obs/{n}_agentview.jpg').convert('RGB')).astype(int)\n m = bar_mask(im)\n m[:190,:]=False\n # remove gripper area? gripper is whitish/grey too but B~R there\n ys,xs = np.nonzero(m)\n print(n, len(xs))\n if len(xs)<100: continue\n pts = np.stack([xs,ys],1).astype(float)\n c = pts.mean(0); u,s,vt = np.linalg.svd(pts-c)\n d=vt[0]; ang=np.degrees(np.arctan2(d[1],d[0]))\n proj=(pts-c)@d\n print(' center',c.round(1),'angle',round(ang,1),'spread',round(np.percentile(proj,98)-np.percentile(proj,2),1), 'bbox', xs.min(),xs.max(),ys.min(),ys.max())\nEOF", + "cd /opt/lffjail/work && python3 - <<'EOF'\nimport numpy as np\nfrom PIL import Image\nfor n in ['s000','s010','s014','s015','s007','s008','s011','s012']:\n im = np.asarray(Image.open(f'obs/{n}_agentview.jpg').convert('RGB')).astype(int)\n R,G,B = im[:,:,0],im[:,:,1],im[:,:,2]\n m = (B-R>=4) & (B>40) & (R<140)\n m[:190,:]=False\n ys,xs = np.nonzero(m)\n if len(xs)<100:\n print(n,'few',len(xs)); continue\n pts = np.stack([xs,ys],1).astype(float)\n c = pts.mean(0); u,s,vt = np.linalg.svd(pts-c)\n d=vt[0]\n if d[0]<0: d=-d\n ang=np.degrees(np.arctan2(d[1],d[0]))\n proj=(pts-c)@d\n print(n,'n',len(xs),'c',c.round(1),'ang',round(ang,1),'len',round(np.percentile(proj,98)-np.percentile(proj,2),1),'bbox',xs.min(),xs.max(),ys.min(),ys.max())\nEOF" + ], + "viewed": [ + "obs/s015_agentview.jpg", + "obs/s015_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 17, + "kind": "move_eef", + "frame_start": 706, + "frame_end": 726, + "command": "move_eef y=-0.009 z=0.02 yaw=90 gripper=open speed=0.1", + "args": { + "y": -0.009, + "z": 0.02, + "yaw": 90, + "gripper": "open", + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5954, + -0.005, + 0.0206 + ], + "gripper_width_after": 0.0791, + "holding_after": false, + "touched_during": false, + "think_s": 5.895165681838989, + "agent_obs_images": [ + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 18, + "kind": "move_eef", + "frame_start": 726, + "frame_end": 741, + "command": "move_eef gripper=close speed=0.05", + "args": { + "gripper": "close", + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5953, + -0.005, + 0.0206 + ], + "gripper_width_after": 0.0412, + "holding_after": true, + "touched_during": true, + "think_s": 11.291993141174316, + "agent_obs_images": [ + "obs/s018_agentview.jpg", + "obs/s018_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Hmm, the y move came out as -0.005 instead of -0.009 (I requested y=-0.009, it stopped at -0.005, \"stopped 0.4cm\"). Also the bar is still flat, centered under the gripper. \n\nNote the bar didn't move (it's at the same place). Good.\n\nNow close and lift. Current eef y=-0.005 → offset from the grip point in the s014 test (y=0.0128) is -0.0178.\n\nLet me close and lift." + ], + "viewed": [ + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 19, + "kind": "move_eef", + "frame_start": 741, + "frame_end": 796, + "command": "move_eef z=0.13 speed=0.04", + "args": { + "z": 0.13, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5936, + -0.005, + 0.1264 + ], + "gripper_width_after": 0.0409, + "holding_after": true, + "touched_during": true, + "think_s": 4.383015871047974, + "agent_obs_images": [ + "obs/s019_agentview.jpg", + "obs/s019_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 20, + "kind": "move_eef", + "frame_start": 796, + "frame_end": 811, + "command": "move_eef gripper=open speed=0.1", + "args": { + "gripper": "open", + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5934, + -0.0052, + 0.1262 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 241.81339359283447, + "agent_obs_images": [ + "obs/s020_agentview.jpg", + "obs/s020_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Let me test a larger y-offset to diagnose the tilt cause." + ], + "reasoning": [ + "Now the bar is tilted the OTHER way: the left end is UP, the right end is DOWN. In the agentview: from (200,318) to (330,190)? The left end is at (200,318)? Looking at the image: the bar goes from the lower-left (205,315) to the upper-right (330,185). Hmm, that looks similar to before?\n\nWait, in s014 the bar went from lower-LEFT to upper-RIGHT. In s019, the bar goes from upper-LEFT?? Let me look again: the image shows the bar from around (210,300) at the left... Actually the crop shows a parallelogram going from (205,315) up-right to (330,185). Same direction as before?\n\nHmm, but the tilt angle looks steeper now. Let me measure programmatically.\n\nAlso the wrist view: the bar's top face is dark (large dark slab). Hmm, the wrist view looks different — now the bar's top face appears dark and huge, tilted toward the camera. The bar's tip top edge at 210-280 px.\n\nLet me compute the angles.", + "s019 is even MORE tilted (-54.5°) with grip y=-0.005, compared to s010 (y=0) at -24.8 and s014 (y=0.0124) at -38.5.\n\nSo: y=0 → 24.8°, y=+0.0124 → 38.5°, y=-0.005 → 54.5°. That's not monotonic by y! It's increasing in both directions?? That suggests something else: maybe the tilt increases over time / with repeated lifts (slipping), or my measure is bad.\n\nWait, note the sign convention: the angle is measured from the +x image direction; negative = the right side is up. All are negative, so the same direction: the right end up. But the magnitudes: 24.8, 38.5, 54.5 — increasing with the sequence, not with y.\n\nMaybe the tilt grows because of the grip's slip over time, or the bar's angle depends on how it's holding (e.g., resting against the finger's edge). Or maybe the bar rotated more because it slipped in the fingers progressively.\n\nHmm, also note: the s019 wrist image shows the bar's top face as DARK, whereas in s010/s014 the top face was light. That's a huge clue: in s019 we're looking at the bar's UNDERSIDE or the far side face! If the bar has rotated ~55°, then from above we'd see its side face more.\n\nWait, actually let me reconsider: maybe the bar isn't rotating in the grip at all, but rather my grasp is not holding the bar's middle: as the bar tilts more, the grip point slides toward the end that's up... Hmm, gravity would pull it down.\n\nOr... OH WAIT. Maybe the bar isn't being held by friction at the fingers at all: maybe the bar's END is resting against the gripper's palm/finger side, and the \"grip\" is just the fingers pinching near the bar's end. When the bar tilts, it hangs from the pinch point.\n\nThe tilt increasing: 24.8 → 38.5 → 54.5 over successive grasps. That looks like the bar is progressively slipping/rotating in the same direction each time. Is there a persistent torque in the same direction? That would happen if the grip point is systematically on one side (e.g., my x is slightly off such that one finger grips higher/deeper) or the fingers contact at the bar's top edge.\n\nHmm, another thought: is the bar possibly bent/deformed in the sim? No.\n\nLet me reconsider: maybe the bar's rotation is about the Z axis (yaw) after all, and the agentview angle increases because the bar yaws more each time. In the s019 wrist image, the bar's top face is a trapezoid with a top edge from 210 to 280 and widening downward to 185-330. Its center at the top=245, the bottom=257 — shifted by 12 px. If a yaw, the slant in the top-down view would be visible as a shift of ~ yaw*length*scale. 12 px is small.\n\nBUT: for a pitch, the top-down view of the bar would show both ends, and the far end (lower z) appears at the smaller end of the trapezoid. Here the top (narrow) is at image y=210 and the bottom is wide. Both ends are at the image center-x roughly.\n\nOK here's another thought experiment: what if the object being grasped is not rotating but rather SLIDING down between the fingers on one side? \n\nI wonder if I should approach this differently: maybe the gripper's fingers are not actually gripping the bar's sides because the bar is too low relative to the fingers (the fingertips are at the bar's mid-height, and the pads' contact faces are the tips' inner sides only). Let me look at the geometry: when the eef z=0.02, the fingertips are at 0.01 and the pads extend upward. The bar's top is at ~0.04. So the pads overlap the bar's sides from 0.01 to 0.04 — full height. Good.\n\nHmm, but the grasp point reported = \"midway between the two fingers, about 1 cm above the fingertips\". OK.\n\nLet me look at the s018 (closed, on the table) agentview to see the finger/bar relationship. And s019 more closely (crop).\n\nAlso, importantly: maybe the tilt is not in the grip at all — maybe the bar tilts because the FINGERS are tilted! The eef_yaw is -90, but what if the gripper isn't perfectly vertical? The wrist might have a slight pitch, and \"move_eef\" commands only control position + yaw. If the gripper's approach has a fixed pitch, the fingers would be tilted and the bar held accordingly. But then the tilt would be constant across grasps (~watch s010 vs s014 vs s019: 24.8, 38.5, 54.5). Not constant.\n\nProgressive increase suggests a slip each time. Each grasp applies a torque to the bar while it's on the table (during closing, the fingers squeeze and may rotate the bar), and after lifting, the bar keeps that rotation.\n\nHmm! That's plausible: during closing, if the fingers' pads contact asymmetrically (one finger contacts the bar's top corner first), the bar rotates on the table. Then it's lifted with that tilt.\n\nAlso, if the bar rotates on the TABLE during closing (staying flat-ish), the agentview should show it before lifting. In s018 (closed, on the table) the bar looked flat/horizontal in the agentview. Let me verify with the measurement.\n\nLet me measure s012, s017, s018, s015, s011, s013.\n\nActually, another thing to check: the bar's x position. In s019 the bbox x goes 209-332, so the bar moved +20px in x relative... its center is now at 273 vs 250 initially. So the bar may have shifted in y (the image x = y). Hmm, no wait—the bar lifted may also move in x.\n\nI need a better plan. Let me think about the physics of grasping a rigid bar with a parallel gripper from above. The classic issue: the bar rotates about the pinch axis if the grip point is off the COM. To get it level, the grip must be at the COM in y AND the fingers must be deep.\n\nMaybe the real problem is the fingers' vertical contact: since the bar is only ~4cm tall and the pads are ~3-4 cm tall, and the fingertips reach to z=0.01 (1cm above the table), the pads cover the bar's full height only if the pads extend up 3cm+. Fine.\n\nAlternatively... maybe the bar's tilt ISN'T from the grip but from the bar being held against the END of the fingers? Whatever.\n\nNew robust plan: Instead of fighting the grip, exploit the fact that the bar, once gripped, swings freely like a pendulum about the contact. If the grip point is fixed and the bar can rotate, then it will settle with its COM below the grip — i.e., the bar hangs with its long axis vertical-ish? No—if the fingertips can apply torque via the pad contact, it will stop somewhere in between.\n\nBut actually: if the grip is at the bar's center-of-mass y, the bar is in neutral equilibrium (any tilt). So it would just keep whatever tilt it had. And the tilt we see could be the residual from the grasp process. So maybe the bar isn't so much in a torque equilibrium as it is free to rotate in the grip!\n\nIf it's nearly free to rotate (low friction torque), then any perturbation tilts it and it stays. To keep it level, I'd need the COM exactly above/below the grip and no perturbation.\n\nGiven the observations (tilts of 25-55° in the same direction with different y), I lean toward the bar being free to rotate in the grip (the metal bar is probably slippery, μ small), and gravity torques it toward the COM below the grip.\n\nIf the y offsets were: 0, +0.0124, -0.005 with corresponding tilts 24.8°, 38.5°, 54.5°: if gravity dominates, the tilt angle should depend on the offset in a monotonic way: tilt ~ atan-ish of the offset. Not monotonic with y → so the equilibrium isn't from the y offset; it's a systematic rotation increasing each time.\n\nHmm, what if the tilt is caused by the bar's own weight distribution being non-uniform, so its COM in y is where it settles? If the bar hangs freely with the COM below the grip, then the tilt depends on where I grip. The observed tilts aren't monotonic with y, so no.\n\nOK, let me look at the actual images more carefully. Crop s019 and s018, and check whether the fingers are actually touching the bar or whether the bar is being pressed against the finger's top/side.", + "Now I see! In s019, the gripper's fingers are gripping the bar near the middle, and the bar is tilted (one end up, one down). But critically, look at s018 (on the table, before lifting): the gripper's fingers straddle the bar but the bar is behind the fingers... The fingers appear to be on the NEAR side of the bar (closer to the camera) — actually the fingers are gripping the bar and the bar extends to the right and left. Hmm, in s018 the fingers' pads appear to be in front of the bar's front face (the bar passes behind the fingers). So the gripper fingers are actually NOT straddling the bar in x... \n\nWait, look at s018: the bar is a horizontal box; the gripper fingers (the two flat plates) are at the center, oriented vertically, and they appear to be in FRONT of the bar (the bar's front face is visible passing behind the fingers). Hmm, but that's expected if the fingers close along x (depth): the near finger is between the camera and the bar, and the far finger is hidden behind the bar. Yes! With yaw=-90, the fingers close along x, and the camera is at +x (viewing from the front). So the near finger is visible in front of the bar, and the far finger is behind the bar (hidden). EXACTLY what s018 shows. \n\nSo the grasp is spatially correct (fingers straddling the bar along x), and the bar passes between them. The reported width 0.041 = the bar's width. \n\nIn s019, the bar is tilted and the grip appears to be at a point ~40% along its length from the lower-left end. Also, the bar is tilted \"out of plane\" — the far/right end is up and slightly away, and the near/left end is down.\n\nNow, thinking about it more: with the fingers at x = bar_center ± 0.0205 and the pads' faces parallel to the y-z plane, the contact is on the bar's x faces. If the bar pitches about x (rolls about its own long axis?), no—pitching about the x-axis means the ends go up/down. The contact faces remain in contact (the faces are parallel to y-z... wait the bar's x-faces are y-z planes; a pitch about x rotates those planes about the x-axis, they'd still be parallel to x. So the contact patches stay flat! The bar can rotate about x freely (like a wheel) as long as the friction allows.\n\nSo the fingers grip the bar's x-faces and the bar can rotate about x (rolling) with only friction resisting. The metal bar on the smooth finger pads = low friction. It rolls until the COM is below the grip axis. Since the grip is not at the COM along y, the bar rotates a lot (tilting to bring the COM below the grip). The equilibrium tilt for a grip at distance s from the COM: the COM hangs below the grip → the bar is tilted by an angle where cos θ = ... the COM's y offset = -s cosθ ... hmm, the COM must be at y=0 relative to the grip → s*cosθ = 0 → θ=90°?! That means the bar would hang vertically. But it stops at 25-55°, so there IS a resisting torque (friction/contact patch) or the grip is near the COM.\n\nGiven the tilt changes with each grasp in the same direction, maybe the fingers' contact isn't symmetric: the pads might have a slight V (the Panda fingers have rounded pads), so the contact patch is a line. And the bar rolls.\n\nSince the tilt is sensitive and non-reproducible, holding the bar level (<8°) reliably by relying on friction seems hard.\n\nWait, but the task is designed to be solvable. Maybe the intended solution is to grasp the bar near its END with the fingers closing along the LENGTH? No...\n\nHold on. Maybe the intended grasp is entirely different: approach the bar along its length, with the fingers closing on the TOP and BOTTOM? Impossible with a fixed vertical approach.\n\nAlternatively, grasp the bar with the fingers on the two ends?? The gripper's max opening is 0.08, the bar is 0.2 long — impossible.\n\nHmm, what about grasping across the WIDTH but with yaw=0 (fingers closing along y)? Then the contact would be on the bar's long faces, i.e., y = ±0.02 positions... no wait, with yaw=0 the fingers close along y, and the bar is long along y. The fingers would be at y=±0.04, far apart, then close toward y=0. They'd contact... their pads' faces are x-z planes. The bar's surface at the pad's x position: if the gripper is centered on the bar in x, the pads descend at y=±0.04, x=bar_x, right onto the bar's TOP face (since the bar spans x=±0.02, the pads at x=bar_x). So the pads would land on the bar's top and close → not a grasp.\n\nUnless the gripper is offset in x so the fingers descend on either side... no, with yaw=0 the fingers are separated along y, both at the same x.\n\nSo yaw=±90 is the only option. OK.\n\nSo the physics: a smooth bar in a parallel gripper, free to roll. Hmm, but the sim's gripper pads might have rubber-ish friction. The observed tilts of 25-55° mean it doesn't roll to 90°, so there's substantial friction/torque resistance.\n\nIf friction resists rolling, then the bar holds whatever orientation it had at the moment of lift, mostly. The tilt could then be caused by the grasp process (e.g., one finger contacting first and rotating the bar on the table).\n\nInteresting: in s018 (on the table, closed), the bar was LEVEL. Then after lifting, it's tilted 55°. So the bar rotated during the lift. That means it's NOT just preserving the grasp orientation—gravity torques it while being lifted, and it slips.\n\nUnless... while on the table, the bar is supported by the table so it can't rotate; when lifted, it rotates until the contact friction balances.\n\nSo the equilibrium tilt is set by the balance of the gravity torque (∝ y_offset) and the friction torque. The observed tilts are large, so the y_offset must be large or the friction small.\n\nAn important realization: the tilt direction is always the same (the right/−? end up). Given the grip's y offsets varied (0, +0.0124, -0.005) and the tilt was always in the same direction with similar/larger magnitude, the direction is NOT determined by the y offset. So there's a systematic asymmetry: e.g., the gripper's fingers are tilted (the hand isn't perfectly vertical), or the bar's COM... \n\nLet me test the \"hand not vertical\" hypothesis: if the gripper's approach axis is tilted by α about the y-axis (i.e., the fingers are not vertical), the bar would be held tilted by α. In the s018 image, the fingers look vertical-ish. Hmm.\n\nActually, maybe simplest: accept the tilt, then correct it by re-grasping with an offset in the opposite direction and see. I tried ±y offsets without success, but the response was dominated by the systematic tilt.\n\nLet me reconsider the numbers: s010 tilt 24.8° with grip y=0. s014: 38.5° with y=0.0124. s019: 54.5° with y=-0.005.\n\nHmm, these are all increasing over time. It looks like each grasp/lift rotates the bar a bit more — a racheting slip. If there's a systematic torque (a tilted hand), each lift rotates it until friction stops it; starting from a tilted state, the next grasp starts from that tilted orientation on the table? But when placed on the table, the bar should settle flat (a square cross-section box lies flat). When I set it down, it does lie flat (s015, s017, s018 all show it level).\n\nBut when grasped and lifted, the same systematic tilt recurs. Yet the magnitudes differ (25, 38.5, 54.5). Hmm, the bar's position on the table differed slightly between these.\n\nWait, actually — maybe the tilt is a rotation about the Z axis after all, and the agentview image angle isn't the tilt. But 55° is huge.\n\nLet me quantify the s019 wrist image: the bar's projected silhouette. If heavily pitched, the top view would show a short trapezoid. In s019's wrist image, the bar spans y 210-390 (180 px). In s008 (level, eef z=0.033), the bar spanned >512 px. Distance differences: the cameras were at different heights (0.10 vs 0.196). At 0.196, the bar was 375 px at s007. So at 0.196 and level → 375 px. In s019 at 0.196 and pitched 55° → ~375*cos? = 215 px (with the perspective). Observed 180. So cos θ ≈ 180/375 = 0.48 → θ=61°. Roughly consistent with a big pitch.\n\nOK so the bar is genuinely pitched ~55°. That's bad.\n\nLet me think about what's structurally special: the grasp point is the midpoint of the fingers ~1cm above the fingertips, i.e., at z ≈ 0.02-0.03 in the grasp. When the fingers close on the bar, the contact is over the pads' area. The bar's COM is at z≈0.02 (the middle of the bar). So the COM is roughly level with the grasp point. The bar hangs balanced in z.\n\nThe torques: gravity acts at the COM; the fingers apply forces at the contacts (at the pads' faces). For the bar to tilt with the COM NOT below the grip, the finger contact must provide torque. A parallel pinch on two flat faces can only provide torque via the normal force distribution (a couple) if the contact is at the pad's edges... i.e., the pads grip the bar at the bar's top and bottom edges? The pads' faces are flat and large; the contact pressure distribution can create a torque. So it's like a \"vise\" — quite strong.\n\nTherefore, a tilted equilibrium means a significant torque from the y-offset of gravity... which should flip sign with the y offset. It didn't.\n\nI'm going in circles. Let me try a completely different, more reliable strategy: DON'T rely on the COM balance. Instead:\n\nIdea: grasp the bar and immediately lay it against... no.\n\nIdea: grasp near one end so the bar hangs; then the task fails (tilt).\n\nIdea: use the table to level the bar before lifting? Not possible.\n\nIdea: grasp the bar at its middle and HOLD IT LEVEL BY ADJUSTING THE YAW/POSITION each time based on the observed tilt (feedback). If the tilt is caused by a systematic torque, then when lifting the bar rolls to a tilt related to the grip's y offset. I can iteratively adjust y to reduce the observed image tilt — but the observations didn't respond monotonically. Hmm, but they were all far from the target (24-55°), i.e., in the \"saturated\" region where the tilt is limited by friction. The y offsets I used (0, +0.012, -0.005) are all small. The response suggests a y-offset-independent tilt.\n\nSo the cause is not the y offset! What else? The x offset! If the grasp is off-center in x (relative to the bar's width), the contact would be asymmetric: one finger would contact at the bar's top edge and the other at the bottom edge... Hmm, no: an x offset just means the pads are closer/farther.\n\nOR the fingers' vertical position: if the fingertips are at the bar's mid-height or above the bar's COM, the bar hangs below the grip and is unstable in roll.\n\nHmm, here's a thought: what if the bar is NOT actually between the fingers but rather resting on top of one finger's pad? In s018, the bar's front face is fully hidden behind the near finger — meaning the near finger is in front of the bar, so the bar is BEHIND the near finger (deeper in x). If the far finger is behind the bar, then the bar is between them ✓.\n\nHmm, the reported width 0.041 vs the bar's actual width — what IS the bar's width? If the bar is 0.05 wide, the gripper would stop at 0.05. It stopped at 0.041. So the bar's width ≈ 0.040.\n\nUgh. OK, practical decision: the bar tilts ~25-55° in the grip. I have 21 commands and 80 s of sim time. I need a fundamentally better grasp.\n\nNEW IDEA: Change the gripper's yaw by 90° while holding the bar? That would rotate the contact faces... no.\n\nNEW IDEA: Grasp the bar with the fingers closing along the bar's LENGTH but with the gripper's fingers positioned at the bar's ENDS? Impossible (0.08 < 0.2).\n\nNEW IDEA: What if the \"tilt\" measure used by the environment is about the vertical axis? Unlikely.\n\nNEW IDEA: Maybe the bar is not a simple box but has a \"lip\" or is a channel? It looks like a simple box.\n\nNEW IDEA: Grip the bar LOWER (below its COM)? The gripper approaches from above, so it can grip only the upper part... Actually, if the fingers are long, the eef can descend so the fingers surround the bar from above with the fingertips reaching below the bar's mid-height. We already reach z=0.01.\n\nNEW IDEA: Grip at a very different y (e.g., near the end) deliberately and see how the tilt changes. If the tilt is independent of y, then the cause is systematic (the hand's tilt). Let's test y=+0.05 (if the bar center is at 0, that's 1/4 from the end) and see.\n\nActually, better idea: DIAGNOSE the hand's tilt using the wrist camera! If the gripper's approach axis is not vertical, the wrist camera would show a systematic tilt: the bar on the table (level) appears... The wrist camera's view of the level bar at s017 showed the bar as a vertical strip → the bar's long axis (y) is vertical in the image. And the yaw is exact. The camera's up = -y. That's consistent with the camera's x/y being aligned.\n\nAlternatively, use the fingers as a reference: in the wrist image, the pads are visible; their shape tells the tilt of the hand? Not precisely.\n\nHmm, what about the agentview: it shows the fingers clearly. In s018 the fingers appear vertical. If the hand were pitched by 30°, the fingers would look tilted in the agentview (they're vertical plates). In s018's crop, the finger plate looks vertical (its edges are vertical). Hmm, the near finger is a vertical plate; in the image, its left edge runs from (215,455) to (205,715) — slightly tilted (about 2.7°). Not 30°.\n\nSo the hand is vertical. The bar tilts in the grip. \n\nHmm hmm. Wait a moment. Let me reconsider the s019 image: maybe the bar is not tilted in 3D but the perspective of the agentview makes it look so. Compare the bar's LENGTH in the image: 165 px at every state, including the level ones! If the bar were pitched 55°, its projected length would be L*cos(55°)*... no wait: for a pitch, the projected 2D length = sqrt((Sy*L cosθ)² + (Sz*L sinθ)²) which stays ~L if Sz≈Sy. Right, as computed. So no info.\n\nBUT: for a pitch, the bar's projected length should still be ~165; observed 165 ✓. For a yaw, also 165 ✓. No info.\n\nLet me use the bar's VISIBLE END FACE! In s000 (level), we see the left end face? In s014/s019, at the upper-right end we see the bar's end face (the little parallelogram). A pitch would show the end face of the LOWER end (facing the camera-ish? no). \n\nIn s019's crop, at the upper end (right, top), we see a parallelogram end face. Which end's face we see depends on the geometry. In s000 (level), the agentview sees the FRONT face (y-z plane, facing +x toward the camera) and the TOP face; the end faces (x-z planes) are nearly edge-on (we see a thin sliver of the left end? In the s000 crop, the left end shows a faint edge).\n\nIn s019, the visible end face at the upper right is large (a parallelogram) — that's an x-z face (an end). Seeing an end face means the bar is yawed (rotated about z) so the end turns toward the camera! A pitch would NOT reveal the end faces (they'd stay edge-on).\n\nLOOK at s019's crop: at the top-right end, there's clearly a visible end face (a quadrilateral). And at the bottom-left end, we see the front face. Hmm, if the bar were yawed, one end's face would become visible ✓.\n\nAnd in the s000 crop, the left end also shows a tiny sliver of an end face (indicating a slight yaw already or the perspective).\n\nSo the bar IS yawed (rotated about the vertical axis)! Let's estimate: the visible end face's width vs the bar's width. In s019's crop, the end face at the top appears ~25x60 px (in the 4x crop = 6x15 px original). The bar's width is 0.04 m ≈ 40 px (projected). Hmm.\n\nHmm, but a yaw of the bar in the gripper is also hard to explain physically (the finger friction resisting a yaw torque — but there's no gravity torque about z!).\n\nUNLESS the bar's yaw comes from the GRASP: if the fingers close on the bar asymmetrically, they impart a yaw. E.g., the gripper's yaw is -90 but the bar is not perfectly parallel to the fingers; closing would rotate it into alignment... or the opposite.\n\nYaw is level-preserving! If the bar is yawed 30°, it's still horizontal, and the task's \"tilt < 8°\" would still pass!! That would be great.\n\nBut wait, if it's a yaw, the bar's 2D projected length would shrink... no, computed above: it stays L if Sx≈Sy.\n\nAnd the apparent vertical drop in the agentview (the right end much higher) — for a yaw, the far end (-x) appears higher in the image. The drop is Sx*L*sinθ. In s019, the drop is 143 px (175→318) with the horizontal 123 px (209→332). Total = 188 px ≈ L=165? sqrt(123²+143²)=188. Hmm, that's LONGER than 165. For a yaw, the length would be sqrt((Sy L cosθ)²+(Sx L sinθ)²); if Sx > Sy significantly... Sx=143/(0.2 sinθ), Sy=123/(0.2 cosθ). With θ=40°: Sx=143/0.1286=1112 px/m, Sy=123/0.1532=803 px/m. So Sx/Sy = 1.38. Is that plausible? The agentview camera looks down at the table at some angle; the x-axis (toward the camera) would project more compressed, not stretched... Hmm, for a camera looking down at ~45°, x and y scales are similar.\n\nFor a pitch: the drop = Sz*L sinθ; Sz/Sy = 1.38 also implausible (both perpendicular to the optical axis → equal scales).\n\nSo the projected 2D length changing from 165 (level) to 188 (s019) means... For a level bar, 165 px. Any 3D rotation would keep the projected length ≤ 165*max(S)/... Hmm, actually for a yaw with Sx > Sy, the projected length can exceed 165. But the initial level bar has length 165 = Sy*L → Sy = 165/0.2 = 825.\nNow, if Sx = 1.38*Sy... that would mean the x-axis scale is bigger. In a perspective camera, the scale for a direction depends on its angle to the image plane. The camera's optical axis is downward and forward. The x-axis is likely at a large angle to the optical axis → more foreshortened, not less.\n\nAlternatively, the 188 px length means the bar is CLOSER to the camera (it moved toward +x toward the camera, closer). At s019 the eef is at x=0.5936 (I moved +x from ~0.45). Hmm! Earlier images (s000) had eef x=0.45. The bar is at x≈0.59. So in s019 the BAR is closer to the agentview camera than in s000? No—the bar's world position doesn't change much... unless the agentview camera is at +x in front. Then a bar at x=0.59 is closer → appears bigger. But s000's bar is at x≈0.59 too (it's the same bar). Both the same. Hmm, the bar is always at the same place.\n\nUgh, so the bar's 165 px in s000 vs its 188 px in s019 means the bar's projected length grew... because it ROTATED to be more face-on? A yaw makes one end come closer to the camera: the near end appears bigger/farther apart. That could increase the projected length!\n\nI'm now fairly convinced it's a YAW (rotation about the vertical axis) — which is harmless for the task!\n\nBut the wrist images argue against a big yaw: in s019's wrist image, the bar's strip is nearly vertical (center top 245, bottom 257). Hmm, but wait: if the bar is yawed 40°, the wrist top-down image should show it slanted 40°. It shows nearly vertical.\n\nContradiction! Unless the wrist camera itself is rotated... no, it's fixed to the gripper.\n\nHmm, unless the bar is both yawed AND pitched such that in the wrist view it appears vertical.\n\nI need to resolve this definitively. Best approach: use the wrist image's FULL geometry with a proper camera model. Let me calibrate the wrist camera using the FINGERS as fiducials! The finger pads are rigidly attached to the gripper, and their 3D positions are known relative to the eef (pad inner faces at x=±w/2, and the pads extend in z and y). By detecting the finger's features in several images with known gripper widths, I could calibrate. That's heavy.\n\nSIMPLER DEFINITIVE TEST: Rotate the gripper yaw by a known amount (e.g., 30° from -90 to -60) while holding the bar and see how the bar's appearance changes in the agentview. If the bar is yawed with the gripper... no wait, the bar would stay in the grip.\n\nBEST TEST: lower the bar to the table (level rest) and then check the agentview: it's level and horizontal. ✓ (s018). So when on the table, the bar is level (0° image angle). Now the environment's evaluation of tilt is done while holding. \n\nHmm, what if I just lift and check the true 3D orientation using a sensor trick: the bar's shadow? No.\n\nPractical test: use the WRIST image to compute the bar's true tilt with a calibrated top-down view. Set the eef high (z=0.25) with the bar held. Then the wrist camera at ~0.32 sees the whole bar. If yawed, it'll look slanted. If pitched, it'll look shorter. In s019's wrist image (eef z=0.126, camera ~0.196, bar at z 0.02-0.15?), the bar spans 210-390 = 180 px. At the same height (s007, z=0.117, level bar on the table), the bar spanned 375 px. So the bar's projected length halved → cos θ = 0.48 → 61° or the bar is much closer/higher...\n\nHmm, the bar in s019 is lifted (closer to the camera) so its projected length should be LONGER, not shorter → a strong tilt is real.\n\nBut if it's yawed, the top-down view would show the bar shorter by cos(yaw) as well. So the wrist view can't distinguish... EXCEPT by the slant angle: a yaw would slant the strip by the yaw angle. The s019 wrist strip is vertical (no slant) → NOT yawed.\n\nBUT the strip in the wrist image is vertical... Let me verify the slant measurement more carefully using the image: I need to extract the bar's silhouette. Let me do it programmatically: threshold the dark-blue bar in the s019 wrist image, then fit the principal axis and measure the strip's orientation. Also compute the width profile.\n\nLet me also do the same for s014.\n\nIf the strip is vertical and shorter → a pitch. Confirmed by two independent views? Let's compute.", + "The SVD on ~200k points in Python is slow? Actually the percentile computations... no, the mask creation is fine. Maybe the array is big but the SVD on Nx2 is fine. Hmm, 62 s timeout. Maybe PIL decompression is fine... Let me optimize with subsampling and avoid np.percentile on huge arrays (still Ok). Let me just print without SVD; use image moments via cv2.\n\nActually the issue may be that the mask includes lots of pixels (the whole image?) — the table is tan (R>G>B) so B-R<0 → excluded. Fine.\n\nLet me time it and use cv2.minAreaRect.", + "Interesting! The mask center in s014 is x=274.5 and in s019 x=320.5, while s013 (bar on the table, eef at x=0.5943,y=0.0126) has the bar center at x=214. Hmm, these numbers are inconsistent between the on-table and lifted cases — because the lifted bar moves up closer to the camera and its projected position shifts.\n\nHmm wait, in s013 the bar is centered at x=214, not 256! Earlier I measured the bar's top face at 190-330 → center 260. The mask now includes the bar's side face, which extends right, and the bar's projected silhouette center is 214?? That seems off. minAreaRect gives the center of the min-area bounding rect, which may be biased.\n\nThe angles are all -90 (vertical) — but minAreaRect always reports near-90 for a vertical box, and it can't tell the slant for a thin strip well.\n\nLet me use a direct approach: for each row y, compute the mean x of the bar's mask pixels, then fit a line → the slant of the strip. Also compute the width per row.\n\nThat will tell us: if the bar is yawed, the center-x shifts linearly with y. If pitched, the center stays constant but the width varies.", + "Excellent data!\n\ns013 (bar on the table, gripper closed around it? Actually s013 is the closed state at z=0.0175 — the bar is between the fingers at 173-336, width 163 px, and constant center 254). The bar's silhouette width 163 px there — that's the bar's WIDTH seen from above (0.04 m → 163 px?!). Hmm, 163 px for 0.04 m at a distance of ~0.09 m → 4080 px/m → f = 367. Plausible!\n\nWait, but with the bar at 173-336 (163 px) in the wrist view at z=0.0175, the bar's top face is 163 px wide — but earlier in s007 (z=0.117) the bar's top face was 75 px. Ratio 163/75 = 2.17; the distance ratio should be (0.187-h)/(0.088-h). With h=0.04: 0.147/0.048 = 3.06. Hmm, inconsistent. With h=0.06: 0.127/0.028=4.5. Hmm.\n\nSomething's off: maybe the camera is not at eef+0.07.\n\nWhatever. Key finding from s014/s019: the strip's center is CONSTANT (255-256) at every row → no yaw. And the width grows linearly from the top to the bottom (69→140 px in s014). That's a strong perspective taper → the top end is FAR (low) and the bottom end is NEAR (high). So the bar is PITCHED, with the end at the image top (which is -y) being LOWER.\n\nWait, but hold on: this taper pattern (linear growth) is exactly what you'd see if the bar's axis tilts TOWARD the camera in the image plane... The strip is vertical, and the width grows downward. Since the camera is directly above the grasp point, a point at image y>256 is at +y (if image down = +y). Its distance to the camera: for a level bar at z=const, the distance is the same for all points → constant width. Observed: growing → the z decreases with... Let's see: closer to the camera = smaller distance = wider. The bottom (image y>256) is wider → the bar's +y end is HIGHER (closer to the camera). And the taper is symmetric-ish? At y=256 the width is 99; at y=128, 69; at y=416, 140. Roughly w ∝ 1/d. If at the center d=d0 and at the ends d0∓Δ: 69/99 = ... 99/140 = (d0-Δ)/(d0+Δ)? Let's solve: 140/99 = (d0+Δ)/(d0-Δ) → wait, higher z = closer = wider: (d0)/(d0+Δ) = 99/140 → d0 = (99/140)(d0+Δ) → 0.293d0 = Δ → Δ=0.293 d0. Also at the top: width 69 → 99/69 = 1.435 = (d0+Δ')/(d0) → Δ' = 0.435 d0. Asymmetric?! The asymmetry suggests the camera is not centered over the bar's middle (the grip is off-center y): the distances to the two ends are d0-Δ and d0+Δ' with Δ≠Δ'.\n\nActually, d0 = h - z(center) and Δ = (L/2) sinθ. From the two: Δ = 0.293 d0 (bottom) and Δ' = 0.435 d0 (top). These should be equal for a symmetric bar. The midpoint of the bar projects at the row where the widths are symmetric... The bar's projected midpoint is where the width is 1/... hmm.\n\nAnyway: the pitch is REAL. sinθ = Δ/(L/2). If d0 = 0.10 m and Δ=0.03: sinθ=0.3 → 17°. If Δ=0.04 → 24°.\n\nBut the asymmetry (top Δ'=0.435d0 vs bottom Δ=0.293d0) means the bar's mid-point projects lower in the image, i.e., the bar's center is at +y relative to the camera axis... Wait: at the image row y=256, the width is 99. If the bar's center were at the image center, the taper would be symmetric. The top is narrower (69 at y=128) than the mirror of the bottom (140 at y=416 → mirror at y=96 would be ~... ). Yeah, asymmetric: the bar's center is below the image center (in the +y direction).\n\nHmm, this is a lot of analysis. CONFIRMED: the bar pitches (rotates about x). The tilt is real and large.\n\nNow WHY does it pitch consistently with the +y end up? And why does the magnitude vary (25°, 38°, 55° as measured by the agentview angle)?\n\nAh, maybe here's the key: the bar pitches until it hits the FINGERS' structure! The finger pads are attached below the gripper's body; the bar's upper end would hit the gripper's palm... no, the bar is below the palm.\n\nHmm, what limits the pitch? Let me reconsider: as the bar pitches, it rotates about the pinch axis (x). The grip is at distance s from the COM along y. The gravity torque = m g s cosθ. The resisting torque comes from the friction at the contacts. So the equilibrium is at the angle where they balance, or the bar slides down until the contact geometry stops it.\n\nThe observed magnitude changes with the grasp (25/38/55°), suggesting different s each time. My y values were +0.0124, 0, -0.005 → s values = y_bar - y_grip.\n\nGiven the tilt increases as y_grip decreases... s increases as y_grip decreases → y_bar > 0?! With y_grip=0.0124 → s = y_bar-0.0124; if y_bar=+0.02, s=+0.0076, tilt 38°. y_grip=0 → s=0.02, tilt 25°. Nope, s bigger → tilt smaller. Contradiction.\n\nUnless the tilt is limited such that the gravity torque is balanced... larger s → larger torque → larger tilt. Not matching.\n\nI wonder if the sequence matters (slip ratcheting). Let me test a fresh grasp at a distinctly different y, e.g., y_grip = +0.04 (toward the up end!) and see if the tilt flips sign. That's the decisive experiment: if the tilt's sign flips at some y_grip, then the physical model is as assumed and I can find the balance point. If not, something else is going on.\n\nCost: ~4 commands (open, move, close, lift). We have 21 commands, 80 s. OK.\n\nHmm, but each lift costs sim time ~2s + the risk. Let's think about a cheaper decisive experiment: place the bar, then close the gripper on the bar and just lift 3cm (small) and measure the tilt in the wrist image. The tilt develops quickly presumably.\n\nAlternatively, maybe I should reconsider the approach entirely:\n\nALTERNATIVE PLAN: use the WRIST camera/vision to correct? No.\n\nALTERNATIVE PLAN: What if the pitch is caused by the bar's fingers slipping and rotating during closing? When the fingers close on the bar, if the bar is slightly offset in x from the finger's center, the finger's pad might contact the bar's top edge first (the pads have a chamfer?) causing a torque about x. But the pitch is about x, and a y-offset creates torque about x... \n\nHmm hold on, maybe the pitch is caused by closing: if one finger (say the far one) contacts the bar's top edge while the near finger contacts the face, the bar would rotate about the x-axis... no, about the y-axis (roll). \n\nThe observed pitch is about the x-axis (one END up). To create that, a torque about x is needed → a force offset in y or z. During closing, the fingers move along ±x, so the friction forces on the bar are along ±x, applied at the contact points whose y positions are ±(pad half-width) — if the contacts are asymmetric in y (e.g., only at one edge), the friction forces create a torque about z (yaw), not x. Hmm.\n\nThe z-direction forces (gravity, the lift) applied off the COM in y create the torque about x.\n\nSo the pitch torque comes from the lift force/gravity with a y offset. OK.\n\nSo the sign of the pitch should be set by sign(y_bar - y_grip). The data contradicts: tilts were all the same sign for y_grip ∈ {-0.005, 0, +0.0124}. For that, |y_bar - y_grip| would have to be positive for all three, i.e., y_bar > 0.0124, and then increasing y_grip toward y_bar would DECREASE the tilt, contradicting the sequence (y=0→24.8, y=+0.0124→38.5).\n\nHmm, unless the bar's y position shifts between grasps! The bar's position may vary by ±0.02 between grasps (it did shift ~5px=6mm at some point). Not 3cm.\n\nI'm stuck on theory. Let me do the decisive empirical test with a bigger y offset: grasp at y = +0.04 (much toward the +y side) and see. If the tilt is smaller or flips, we learn a lot.\n\nActually — WAIT. Let me reconsider the problem. What if the bar is TILTED because the gripper is holding it at its very EDGE (the bar's end face)? Look at the s019 crop again: the gripper appears to grip the bar at ~40% from the lower end... \n\nAlternatively, what if the metal bar has a MAGNETIC attraction or the gripper is a \"suction\"? No.\n\nLet me look at the wrist image of s019 again: the bar's strip is centered at x=256 (the gripper axis) and extends from y=224 down past 416. The strip is 130-145 px wide at the bottom... The gripper's fingers: the pads' inner faces at ±0.0205 → if the width of the bar equals 0.041 and it spans 130 px, the scale is 3170 px/m at the bar's depth. So d ≈ f/3170.\n\nWhere's the bar's other end? It's ABOVE the image top (y=224 is the top of the visible strip? no, at y=224 the width is 65 px, so the bar continues up to maybe y=200 where it ends). Hmm, the strip exists from y≈210 to 416+ (cut off at the bottom by the fingers). So we only see a portion — the rest (the up end) is beyond the bottom of the image (hidden behind the fingers) and the down end is above 210.\n\nSo the visible strip in the wrist image is just a middle portion of the bar. Fine.\n\nNew consideration: the wrist camera looks straight down but is mounted slightly forward; the bar's near (up) end goes below the image bottom and the far (down) end at y=210. The projected length visible ~200 px ≈ 0.063 m at 3170 px/m... with the bar's length 0.2 m.\n\nOK. Decision time. Rather than more theory, let me try the \"big y offset\" experiment. But before that, let me reconsider the alternative interpretation: could the bar be ROTATING about the x-axis because it's resting against the table during the initial lift (dragging)? During the lift, the bar slides against the table? No, it's held in the air.\n\nHmm, one more idea: maybe the bar is NOT gripped by friction but is being held by the fingers squeezing it against... let me check the closed gripper width: 0.041. The bar's width: I measured 163 px at s013 (z=0.0175). If f=367 (from the 0.04 m guess) that's circular. \n\nLet me measure the bar's width from the s000 agentview where I know the length: the bar's length 175 px. Hmm, also circular (assuming 0.2 m).\n\nOK, the bar's true dimensions are unknown, but the gripper's width is a solid reference: the fingers are at ±w/2 for w=0.041.\n\nLet me try yet another approach to the gameplay: maybe I don't need a perfect grip. What if I lift the bar and it tilts, then I lower it back to the table, and the TASK evaluation happens while holding it in the air. The task requires level (<8°). So I need a level hold.\n\nPRAGMATIC IDEA: pinch the bar at its END and let the bar hang VERTICALLY? The \"tilt\" would be 90° — fails.\n\nPRAGMATIC IDEA 2: pinch the bar at its center, then lift in a way that the bar self-levels: give it a quick shake? A quick upward acceleration then stop would... no.\n\nPRAGMATIC IDEA 3: use the accelerometer-free approach: lift, let it settle, then use a small yaw rotation? Doesn't affect pitch.\n\nPRAGMATIC IDEA 4: clamp the bar against the wrist's palm? Hmm.\n\nPRAGMATIC IDEA 5: The fingertips: what if I grip the bar at its TOP surface only (fingers pinching the bar's top edge)? Not stable.\n\nPRAGMATIC IDEA 6: Use the gripper to slide the bar to the table's EDGE so it overhangs? No—the task wants it 10 cm above the table.\n\nHmm, what about a completely different manipulation: FLIP the bar onto its side? Doesn't matter; it's a bar.\n\nWait wait wait. Let me re-examine the assumption that the bar is tilting. Let me look at the AGENTVIEW again at s019: the bar looks like a long bar going from the lower-left to the upper-right, and the gripper holds it in the middle. What if the received \"bar\" is actually TILTED in the grip because... \n\nHonestly, let me just try the experiment with a large y offset. If the tilt flips to the other side, I can bisect to find the level point. Total cost to bisect: 3-4 trials × 4 commands = 12-16 commands. I have 21. Tight but feasible. Also sim time: each trial ~6-8 s → 24-32 s of 80. OK.\n\nBut before that, let me reconsider using the SETTLING approach: when the object is free to rotate in the grip, its equilibrium has the COM below the grip. For a bar gripped at its center in y, the COM is directly at the grip → any orientation is neutrally stable. So if s≈0, the bar retains whatever orientation it had when grabbed, which is level-ish (since it's on the table when grasped, level!). Then why does it tilt?\n\nUnless s ≠ 0, in which case it would tilt toward the COM-below configuration...\n\nBut here's the thing: with s≠0, the equilibrium (COM below the grip) is when the bar's long axis is VERTICAL (90° tilt), not 25°. Unless the fingers stop it. Our observations show 25-55° — partial.\n\nHmm, so maybe the bar IS sliding/rolling in the grip and the observed angles are just transient snapshots! The lift is quick (speed 0.03-0.04 m/s, taking 2-3 s) and the bar might still be swinging/settling when the image is taken. If I hold it still for a while, the bar might continue rotating to hang vertically, or oscillate. The images are taken right at the end of the motion.\n\nIf it's a transient oscillation, waiting might help... but hanging vertically is worse.\n\nOK here's another thought: if the object's grip is friction-limited and it slips, the fix is to increase the grip force. The gripper's \"close\" command applies a fixed force (likely the max). \n\nWhat if the bar's surface is low-friction metal? Then a pinch grip is inherently unstable. Hmm, but the task must be solvable — presumably in these sim environments, the default gripper friction is high enough.\n\nWait, maybe I should reconsider: does the environment actually simulate the bar's rotation, or is what I see an artifact of the camera/gripper? The wrist image clearly shows a taper → real pitch.\n\nLet me revisit: what if the bar's pitch is caused by the TABLE during the lift? If the bar is slightly embedded/dragging at one end when I lift... At s018 the bar was level on the table and the fingers gripped at the center. Lifting should be clean.\n\nHmm! UNLESS the grasp is at the bar's END such that the bar's other end drags on the table during the lift. The mass would swing it. Where does the gripper hold the bar? Let me determine this from the images: in s018 (on the table), the gripper is at y=-0.005 and the bar spans... In the agentview, the bar spans x_pix 167-340 and the gripper is at x_pix ~253. Initially (s000), the bar spanned 162-337 with a center of 249.7 px. Hmm, so the gripper at 253 px is close to the bar's center 254. OK, the grip is near the bar's center in y.\n\nHmm, so the grip is central. Then the tilt shouldn't happen from a COM offset...\n\n...unless the torque comes from the finger contact asymmetry: e.g., the fingers' pads grip the bar with the fingers' tips angled. If the near finger's pad contacts the bar along its top edge and the far finger along its bottom edge, you'd get a torque about... the axis through the contacts, which is along y (roll). Not pitch.\n\nWhat about x (depth)? An x-offset in the grasp (the bar's center not midway between the fingers) doesn't matter.\n\nI'm going to stop theorizing and run the experiment with a large y offset. Actually, let me make the experiment maximally informative: grasp at y=+0.05 (a big shift toward the \"up\" end). If the tilt direction flips or decreases substantially, I'll bisect. If it doesn't change at all, then the cause is systematic and I'll need a different idea.\n\nHmm, but wait. Before that, let me reconsider the \"up end\" mapping. In the agentview, the RIGHT end is up (+y per my wrist derivation). The bar's center in the image at s019 was at x=273 (moved right from 250) — consistent with the bar shifting +y? or with the tilt changing the projection.\n\nOK, do it: open, move y=+0.05, z=0.02, close, lift z=0.10, observe.\n\nActually — hmm, one thing that would really help: check the bar's tilt with a SLOWER, more careful lift and a pause, to see if the tilt is a settling transient. The observe command doesn't advance time. Hmm, a trick: after lifting, do a small \"wiggle\" move (a tiny 1cm move at high speed) and then measure. If the tilt grows to a stable value, it's an equilibrium.\n\nActually, simpler: after lifting to z=0.10 (s019) I measured 54.5°. If I lift further (I have the image at 0.126), no change expected.\n\nLet me do the big-y-offset test." + ], + "shell": [ + "cd /opt/lffjail/work && python3 - <<'EOF'\nimport numpy as np\nfrom PIL import Image\nfor n in ['s000','s010','s014','s019']:\n im = np.asarray(Image.open(f'obs/{n}_agentview.jpg').convert('RGB')).astype(int)\n R,G,B = im[:,:,0],im[:,:,1],im[:,:,2]\n m = (B-R>=4) & (B>40) & (R<140)\n m[:175,:]=False\n ys,xs = np.nonzero(m)\n pts = np.stack([xs,ys],1).astype(float)\n c = pts.mean(0); u,s,vt = np.linalg.svd(pts-c)\n d=vt[0]\n if d[0]<0: d=-d\n ang=np.degrees(np.arctan2(d[1],d[0]))\n print(n,'n',len(xs),'c',c.round(1),'ang',round(ang,1),'bbox',xs.min(),xs.max(),ys.min(),ys.max())\nEOF", + "cd /opt/lffjail/work && python3 - <<'EOF'\nfrom PIL import Image\nfor n in ['s018','s017','s019']:\n im = Image.open(f'obs/{n}_agentview.jpg')\n im.crop((190,150,370,340)).resize((720,760)).save(f'obs/{n}_crop.png')\nprint('ok')\nEOF", + "cd /opt/lffjail/work && python3 - <<'EOF'\nimport numpy as np\nfrom PIL import Image\nfor n in ['s013','s014','s018','s019']:\n im = np.asarray(Image.open(f'obs/{n}_wrist.jpg').convert('RGB')).astype(int)\n R,G,B = im[:,:,0],im[:,:,1],im[:,:,2]\n m = (B-R>=3) & (B>40) & (R<170) & (G<170)\n # exclude bright/whitish gripper\n m &= (R<150)\n ys,xs = np.nonzero(m)\n if len(xs)<200:\n print(n,'few',len(xs)); continue\n pts = np.stack([xs,ys],1).astype(float)\n c=pts.mean(0); u,s,vt=np.linalg.svd(pts-c)\n d=vt[0]\n if d[1]<0: d=-d\n ang=np.degrees(np.arctan2(d[1],d[0])) # angle from horizontal; want near 90 for vertical strip\n proj=(pts-c)@d\n perp=(pts-c)@vt[1]\n L=np.percentile(proj,99)-np.percentile(proj,1)\n W=np.percentile(perp,99)-np.percentile(perp,1)\n print(n,'n',len(xs),'c',c.round(1),'axis_ang',round(ang,1),'L',round(L,1),'W',round(W,1),'sv',s.round(0))\nEOF", + "cd /opt/lffjail/work && timeout 50 python3 - <<'EOF'\nimport numpy as np, cv2, time\nfor n in ['s013','s014','s018','s019']:\n im = cv2.imread(f'obs/{n}_wrist.jpg') # BGR\n B,G,R = im[:,:,0].astype(int),im[:,:,1].astype(int),im[:,:,2].astype(int)\n m = ((B-R>=3)&(B>40)&(R<150)).astype(np.uint8)\n n_=int(m.sum())\n if n_<200: print(n,'few',n_); continue\n rect = cv2.minAreaRect(np.column_stack(np.nonzero(m)).astype(np.float32)) # (x,y),(w,h),angle\n (cx,cy),(w,h),ang = rect\n print(n,n_,'center',round(cx,1),round(cy,1),'wh',round(w,1),round(h,1),'ang',round(ang,1))\nEOF", + "cd /opt/lffjail/work && timeout 50 python3 - <<'EOF'\nimport numpy as np, cv2\nfor n in ['s013','s014','s019']:\n im = cv2.imread(f'obs/{n}_wrist.jpg')\n B,G,R = im[:,:,0].astype(int),im[:,:,1].astype(int),im[:,:,2].astype(int)\n m = (B-R>=3)&(B>40)&(R<150)\n rows=[]\n for y in range(0,512,16):\n xs=np.nonzero(m[y])[0]\n if len(xs)>5:\n rows.append((y, xs.mean(), xs.min(), xs.max(), len(xs)))\n print(n)\n for r in rows: print(' y=%3d cx=%6.1f [%3d,%3d] n=%3d'%r)\nEOF" + ], + "viewed": [ + "obs/s019_agentview.jpg", + "obs/s019_wrist.jpg", + "obs/s018_crop.png", + "obs/s019_crop.png" + ] + } + }, + { + "attempt": 1, + "step": 21, + "kind": "move_eef", + "frame_start": 811, + "frame_end": 841, + "command": "move_eef x=0.6 y=0.04 z=0.32 yaw=90 gripper=open speed=0.3", + "args": { + "x": 0.6, + "y": 0.04, + "z": 0.32, + "yaw": 90, + "gripper": "open", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5988, + 0.0397, + 0.316 + ], + "gripper_width_after": 0.0794, + "holding_after": false, + "touched_during": false, + "think_s": 79.87702345848083, + "agent_obs_images": [ + "obs/s021_agentview.jpg", + "obs/s021_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Oops—I opened the gripper at height 0.126 and dropped the bar. Wait, did it? The gripper is at z=0.126, so the bar fell ~10 cm to the table. Let's check where it landed. That's not ideal but recoverable.\n\nLet me look.", + "The bar dropped onto the table and shifted: in the agentview it's now at x_pix ~232-410, center ~320 (previously 250). So it moved +70 px in y_image. The wrist view shows the bar to the right of center (x 220-290), i.e., at -x relative (image right = -x): bar_x = eef_x - offset... Wait, earlier the bar appeared LEFT of center and I concluded bar = eef + 0.037 in x. Now it's near center-right: the bar's center at 255 → nearly centered in x! And in the agentview, the bar's center at x_pix 320 vs the gripper at ~250.\n\nHmm, so the drop moved the bar +y by ~70 px (agentview horizontal). The bars can shift.\n\nWait, actually, in the wrist image, the bar appears at x 220-290 (center 255) — the camera axis. But the agenview says the bar's center is at 320 px whereas the gripper is at 250. So the bar IS offset from the gripper in the agentview's horizontal direction by 70 px ~ (using 825 px/m) 0.085 m. But the wrist view says it's centered?! \n\nThis means the wrist camera is offset from the eef in that direction by ~0.085 m?? No... The wrist camera is mounted on the gripper; it can't be offset by 8.5 cm from the grasp point (only ~7cm above). Hmm, but the agentview's horizontal direction might be x (depth), not y! \n\nThe wrist image shows the bar centered in x (255). The agentview shows the bar offset horizontally by 70 px from the gripper. If the agentview's horizontal is mostly ±y, then the bar is offset in y by 0.085 from the gripper, but the wrist camera would show that offset in its own y direction (image vertical). The wrist image shows the bar's strip from y 265 to 400 (the top end at 265) — that's asymmetric! The strip's visible portion... the top end at ~265 (the end face visible as dark) and it continues to the bottom edge (400+) where the fingers are. So the bar is offset toward +y (down in the wrist image).\n\nThe agentview's horizontal ≠ y alone; it includes x. If the agentview camera is at 45° azimuth, both x and y map to the horizontal.\n\nOK, using the wrist camera (which is cleaner): after the drop, the bar's center in x is 255 (aligned with the gripper, ±few mm) and offset in +y by some amount; the agentview suggests a large offset.\n\nGiven the bar's visible end at wrist y=265 and the bar's length 0.2 m... The bar's near end is below the frame.\n\nHmm OK, here's the thing: I need to just place the gripper over the bar again. The bar's y position: let me estimate from the wrist: the bar's top end appears at y=265, i.e., ~9 px below the center → 9 px * d/f. Small offset, but the visible end isn't necessarily the bar's real end... it IS the end (the dark cap at 265-272 suggests the end face).\n\nSo the bar's far (-y) end is at wrist y=265, just below the image center. If the bar is 0.2 m long (0.2*3170=634 px), the near (+y) end would be at 265+634 = 899 (way below the frame). So the bar's center would be at pixel y = 265+317 = 582 (way below). That would mean the bar's center is at +y offset of (582-256)*d/f = 326/3170 = 0.103 m!!! That's huge.\n\nHmm, but the scale at the bar's depth: the bar is on the table, the camera at 0.196 → d ≈ 0.19; the bar's top face is 70 px wide (0.04 m) → scale = 1750 px/m → 0.2 m = 350 px. Then the near end = 265+350 = 615, the center at 440 → the offset (440-256)/1750 = 0.105 m. Hmm, so the bar's center is ~10 cm in +y from the eef?! That contradicts the earlier observation that the bar's center was near y=0.\n\nHold on, that means the bar shifted +y by 0.085-0.105 during the drop. That's a huge shift for a 10cm drop onto the table. Suspicious!\n\nUnless... the bar's end at y=265 in the wrist image is not the far end but the NEAR end, with the bar extending up (away) → then the bar's center is at y ≈ 265-175 = 90 → the offset = (90-256)/1750 = -0.095, i.e., the bar's center is at -0.095 in y.\n\nHmm! That's also ~10 cm. Which end is which?\n\nThe dark cap at the top (y=265-275) looks like an END FACE (vertical). For a bar on the table viewed from above and slightly behind, we'd see the top face (light grey) plus the end face if the near end is closer. The end face visible at the TOP of the strip: since the camera looks down-forward, the near end's face is visible facing the camera... The camera looks forward (+? ) — the wrist camera is above and slightly forward.\n\nIn s007 (bar on the table, eef y≈0, x=0.586): the wrist image showed the bar's strip spanning vertically with the light top face. Hmm.\n\nI've spent a lot; let me take a decisive, simple approach: RE-LOCALIZE the bar using small moves and the wrist camera with the gripper high enough to see both ends, then align in both x and y using the top-down view, then grasp at the bar's center in y.\n\nSpecifically: move up to z=0.35 (the camera at ~0.42), where the full bar should be visible, and take a wrist image. Then compute the bar's center in both image axes and the scale from its known width/length ratio. Then adjust eef x,y so the bar's center is at the grasp projection (the finger midpoint, ~256).\n\nThe scale: the bar's projected 2D length L_px and width W_px relate to the true length/width ratio (unknown!). Hmm. But I can use the FINGERS as a scale reference at their known depth... ugh, different depth.\n\nAlternative: use the initial s000 agentview + knowing the bar's position doesn't change... \n\nHonestly, maybe the simplest: I know the bar is a box at some (x, y) with its long axis along y. From the agentview (s000), the bar's center pixel (249.7, 306.4) and the initial eef (0.4515, 0, 0.2613) projected at the fingers (~250, 165). I have a rough sense.\n\nLet me use the wrist camera to directly servo: high z=0.35, look at the bar, estimate the offsets in pixels, convert to meters using the bar's own width (0.04 m = the measured width in px at that height → scale). Then move by that offset, take another image, iterate. This is a clean 2D visual servo.\n\nBut the wrist camera's optical axis is NOT centered on the grasp point in x... it is roughly (the finger midpoint = 250-256). There may be a fixed offset of a few px.\n\nWith z=0.35, the bar's width (0.04) at d≈0.42 → 0.04 * f/0.42. If f≈367, 35 px. Hmm, small but measurable. Ugh.\n\nAlternatively, do the servo in the AGENTVIEW using the gripper as a visual reference: the agentview shows both the gripper and the bar. I can align them in the image: move the eef in x/y until its image x matches the bar's image x. This works if the agentview's horizontal direction is dominated by y (mostly true). But the vertical alignment (x) is ambiguous.\n\nCOMBINE: use the wrist camera for x (which worked well: the bar centered at 255 when the eef was directly above), and use the agentview for y (align the gripper's pixel x with the bar's center pixel x).\n\nThat's exactly what I need. Let me do that:\n1. Move up to z=0.25, y=0, x=0.595 (a safe pose above).\n2. Look at the agentview and compare the gripper's pixel x to the bar's center x.\n3. Adjust y accordingly, iterate.\n\nBut careful: the \"gripper's pixel x\" in the agentview vs the bar's pixel x — they're at different depths (z), so the comparison has an offset (parallax) due to the camera's projection. That is exactly the problem: the agentview's projection of the same world (x,y) differs with z.\n\nHmm, but the parallax is mostly in the vertical image direction (depth direction), not the horizontal, IF the camera's horizontal axis is horizontal. The agentview camera is presumably looking down and forward; its image horizontal axis is exactly horizontal (level) if the camera has no roll. Then the horizontal image coordinate depends only on the world's horizontal position projected onto the camera's right vector r (which is horizontal). So u = f * (p·r)/(p·depth). The depth changes with z and x, so the horizontal pixel of the same (x,y) does change with z a bit. But if r is mostly ±y, then u is mostly determined by y with some x-leakage.\n\nSo: aligning the gripper's image u with the bar's u is a good approximate y alignment. Combined with the wrist camera's x alignment, we get a good position. Then the remaining error in y may be ~1 cm.\n\nHmm, but earlier that's exactly what I did (the wrist showed the bar centered in u when x was right) and I assumed y≈0.\n\nOK, let me now do it properly and also verify the bar's y by looking at the agentview bar center vs the gripper's u at LOW z (where both are close in depth) — at z=0.02 the parallax is minimal! At s018, the gripper was at u≈253 and the bar's center at 253.7 (bbox 167-340) — well aligned ✓. So the y WAS aligned.\n\nSo the y alignment is fine, and the bar still tilts. So the pitch isn't a COM-offset effect?!\n\nHmm, hold on: the bar's center from the bbox 167-340 = 253.5. But the bar's silhouette includes its visible end faces and the perspective... For a level bar viewed from an oblique camera, the silhouette's center is the bar's center only if the projection is symmetric. Roughly yes.\n\nSo the grip IS at the bar's center in y, and the bar tilts in the grip by 25-55°. That means the finger pads are NOT providing enough rolling resistance, and the bar rolls due to some systematic asymmetry (e.g., the pads are not perfectly parallel/vertical, or the bar's own geometry).\n\nIf the grip is at the bar's center and the bar is uniform, the gravity torque about x is zero. So the rolling must be driven by something else: the CONTACT GEOMETRY. If the two pads are not exactly parallel (e.g., the fingers' pads are slightly angled), closing them would rotate the bar. The Panda fingers do have angled pads? In robosuite, the Panda's finger collision geoms are boxes (flat pads). Hmm.\n\nBut here's the thing: the observed tilt values (25, 38, 55) increase with each grasp. This looks like the closing fingers ratchet the bar's rotation. In s013 (closed, on the table) the bar appeared level. Then the lift... \n\nOH WAIT. Maybe I've got it: the bar might be ROLLING during the lift because of the gripper's acceleration. The bar is free to roll about x; lifting with a slight lateral acceleration (the eef moves in x from 0.594 to 0.5936 — tiny) or a slight tilt of the hand causes rolling. Hmm, but rolling requires a torque about x.\n\nHonest answer: something systematic. Since the bar rolls freely about x, an alternative approach: let the bar roll to its equilibrium and then ROTATE THE BAR BACK by using the fingers' contact: e.g., after lifting, rotate the gripper yaw? That rotates about the vertical, not x.\n\nHmm, what if I use the table to level it: lower the bar so both ends touch the table, then close the fingers tightly? Doesn't change the grip.\n\nWhat about the \"roll to equilibrium then correct with an x-direction shove\"? The bar can roll freely; if I accelerate the arm in x while holding, the bar's inertia creates a torque about the contact... The bar rolls due to gravity around the x-axis and the contact friction; a linear acceleration along y would create a torque? No.\n\nTorque about x comes from forces in the y-z plane offset in y/z. A linear acceleration along z (vertical) applied at the grip with the COM offset in y creates a torque about x. So by accelerating vertically, I can control the roll: accelerate up → torque = -m a_y * offset... but with the offset ≈0, no.\n\nPhysics reality check: if the COM is exactly at the grip (s=0), the bar is neutrally stable in roll and keeps whatever angle. Then the observed tilt came from the grab/closing.\n\nSo the most reliable fix: GRASP THE BAR WHILE IT'S ON THE TABLE (level) WITHOUT ROTATING IT. The bar is level on the table, the grasp should preserve 0°. But the observations show the tilt developing during the lift.\n\nAlternative fix: hold the bar and RE-LEVEL it by using the table: lower the bar until both ends touch the table (it becomes level, supported), then the fingers... when lifting again, it re-tilts.\n\nHmm, unless the tilt comes from the LIFT DYNAMICS: at the start of the lift, the bar is still on the table; the fingers pull up; the bar sticks to the fingers; the bar's ends... if one end drags on the table (friction), the resulting torque could rotate the bar. But the bar's ends don't touch the table when held at the center (they'd be above the table if the bar is above). At s018 the fingers grip the bar at z=0.02 with 1cm clearance... the bar's bottom is at 0.0, touching the table. Lifting pulls it up evenly.\n\nHmm.\n\nNEW PRACTICAL PLAN: Since the bar can roll freely, I can give it a controlled roll by ROTATING THE GRIPPER'S yaw? No. \n\nBUT: Here's a neat trick — the bar's roll can be corrected by moving the gripper in the Y direction while it's rolling: friction from a lateral (y) motion applies a force at the contacts, which creates a torque about x if the contacts are above the COM. The contacts are at the bar's mid-height (~z=0.02) and the COM also ~0.02. If the contact is above the COM, a y-force creates a roll torque. Not reliable.\n\nANOTHER PLAN: check whether the tilt is actually acceptable. <8° is required. Our tilts are 25-55° in the image, but is the image angle the true 3D tilt? No—the true tilt could be smaller. Hmm! Let me compute the true tilt from the wrist perspective taper more carefully:\n\nFrom s019: widths at rows: y=224:65, y=256:75, y=288:86, y=320:97, y=352:107, y=384:117, y=416:130.\nIf the width w ∝ 1/d and d decreases linearly with the image y (for a pitched bar viewed top-down: the bar's axis is in the y-z plane; the image y position of a point at (y_b, z_b) = f*y_b/d). Hmm, the relationship isn't linear in general, but roughly.\n\nThe bar's axis in the wrist view: the points along the bar have (y_b, z_b) = (s cosθ, s sinθ) for a parameter s. The projected image y = f * y_b/d where d = h - z_b = h - s sinθ. And the image x = f*x_b/d.\nThe width at that point ∝ 1/d.\n\nThe measured widths: w(d at y=224) = 65, w(y=416)=130. Since w ∝ 1/d, d416/d224 = 65/130 = 0.5. So d416 = 0.5*d224.\nd = h - s sinθ, and the image y ∝ y_b/d.\n\nLet s1 and s2 be positions. d1 = h - s1 sinθ, d2 = h - s2 sinθ.\nIf d2 = 0.5 d1 and the image y of point i: Y_i = f*s_i cosθ/d_i.\n\nFrom the numbers: the bar spans from y=224 (width 65) to y=416 (width 130) → 192 px. If h ≈ 0.19 (camera at z~0.196, the bar's center around 0.1?), d1=0.19-sinθ*s1...\n\nToo many unknowns. Let me just say the tilt is substantial (probably >30°).\n\nDECISION: Try a fundamentally different grip: grip the bar by its LONG SIDES at two points? Impossible.\n\nTry: grip the bar with the fingers at maximum depth so the pads' full faces contact, and close slowly... we did.\n\nTry: approach with yaw = ±90 but with an intentional slight rotation of the gripper yaw (e.g., -85°) so the two pads contact the bar's faces at slight angles, creating a wedging that resists rolling? Interesting but the pads would still be parallel to each other.\n\nWAIT. NEW IDEA: What if I grip the bar and then let it hang/roll to a stable tilt, then rotate the GRIPPER'S YAW BY 180°? That doesn't change the pitch. But what about using the arm's joints? We can only command x,y,z,yaw.\n\nHmm, what about \"move_eef\" with a yaw that rotates the bar about the vertical... The bar is horizontal, its tilt is about x. To correct the tilt, I need to rotate the bar about the x-axis, which the gripper cannot do (it can only rotate about z).\n\nUNLESS: the tilt isn't about x. If the tilt were about z (yaw), I could correct it by rotating the gripper's yaw. Hmm! Given the ambiguity of the measurements, and that I can't distinguish easily... let me test: rotate the gripper yaw by +20° while holding the bar and see how the agentview bar angle changes. If the bar's image angle changes with the gripper's yaw, then the bar is rigidly held and its tilt is a yaw (which rotates with the gripper). If the bar's image angle doesn't change → a pitch.\n\nActually that test is also ambiguous-ish, but it's informative. Cost: 1-2 commands.\n\nActually, WAIT. Much better idea!!! If the bar is currently tilted and I can't correct the tilt, maybe I can pick it up in a DIFFERENT way that GUARANTEES levelness: place the bar so that it rests against something... no.\n\nHmm, hold on. What about grasping the bar OFF-CENTER along its length and letting it hang so that the LONG part hangs down and the short part... vertical. No.\n\nLet me reconsider: is a horizontal grasp possible? What if I rotate the gripper 90° about y? Not available.\n\nOK, here's another thought: since the bar rolls freely about its long axis?? NO WAIT. The bar's rotation about the x-axis is the TILT (pitch, ends up/down). The bar rolling about its own long axis (y) would be harmless.\n\nHmm, so a \"pitch\" of the bar means rotation about the x-axis. For the fingers pinching the bar's x-faces, the contact normal is along x, so the fingers CAN provide torque about y (roll) but NOT about x or z (they need friction for those). A torque about x can only be resisted by FRICTION. Metal on plastic: μ≈0.3. So the bar easily rotates about x — consistent with the observed tilts!\n\nA torque about x arises from gravity if the COM is offset from the grip in y. With the grip at the bar's y-center, the offset should be ~0. But maybe the bar's COM is NOT at its geometric center (a \"metal bar\" with an off-center handle?). OR my y alignment is off by a few cm (px measurements have error).\n\nWait, maybe the y alignment IS off. Let me re-examine: at s018, was the camera looking at the bar's center? The wrist image at s018 (closed) showed the bar's strip from y=0 to ~390 with a width of 261 px at some rows (huge!). Earlier the row analysis for s013 (bar at z=0.0175, closed) showed x from 173-335 constant → that's the bar's WIDTH seen from above = 163 px at d≈0.09 → 1810 px/m... hmm, that seems small now.\n\nHmm, s013's row data shows the bar spanning x=173-335 for ALL rows 0-416, with a constant center 254. A constant width over the whole image height means the bar is LEVEL (no taper) → the bar in s013 is level ✓ (on the table) and its top face spans 163 px in the image x. 163 px = the bar's width (0.04 m) → scale = 4075 px/m at that depth. d = f/4075.\n\nNow in s014 (lifted), the max width at y=416 is 140 px → 140/163 = 0.86 → if the bar were level, d would be 0.86 of s013's d. s013: eef z=0.0175 (camera at 0.0175+0.07=0.0875, d=0.0875-0.04=0.0475). s014: eef z=0.1173 (camera at 0.1873), the level d would be 0.147. The width ratio would be 0.0475/0.147=0.32 → ~53 px. But the observed max width is 140 px → the bar is much closer than expected. The taper: at the far end 65 px (d = 0.0475*163/65 = 0.119) and at the near end 140 px (d = 0.055). So the bar's ends are at distances 0.119 and 0.055 from the camera → a Δd of 0.064 = L sinθ → sinθ = 0.32 → θ ≈ 19°. And the bar's center d ≈ (0.119+0.055)/2 = 0.087 → the camera is at 0.087 above the bar's center.\n\nHmm, with the camera at z=0.1873 and the bar's center at 0.10 → the bar's center z = 0.10?? That means the bar is held very high (0.1 above the table)? But the eef is at 0.117 and the bar's center is at ~0.02-0.03 below the grip → z≈0.09. OK consistent-ish. Fine.\n\nSo the tilt is ~19° by this measure (not 38). Either way > 8°.\n\nLet me now think about the most promising remaining approach:\n\nAPPROACH: Increase the friction/torque resistance by gripping the bar at its END?? No...\n\nAPPROACH: Grasp the bar at its top only, i.e., the fingers pinch the bar's UPPER portion, with the fingers' tips ABOVE the bar's top face? Not possible.\n\nAPPROACH: What if I grasp the bar closer to one end and hold it so that the long end rests... no.\n\nAPPROACH: Squeeze the bar between the fingers and the TABLE? No.\n\nNEW APPROACH — use the wrist camera and the table: Place the bar on the table. Lower the open gripper over the bar's center. Close. Then, BEFORE lifting, tilt... no.\n\nHmm, what about lifting with a fast upward motion so the bar's inertial torque... no.\n\nLET ME RECONSIDER THE WHOLE THING. What if the intended solution is much simpler and the \"tilt\" I'm seeing is actually a YAW (rotation about z), which does NOT affect levelness? The bar would still be horizontal (<8°), satisfying the task! And a yaw is level-preserving. In that case, my current hold might already pass!\n\nHow to determine definitively whether it's a yaw or a pitch? Use the agentview + a second view (wrist) simultaneously. Let me build a proper geometric model:\n\nFor a YAW rotation (about z) by ψ: the bar's axis direction = (sinψ, cosψ, 0). In the agentview, the image displacement between the ends = A*(sinψ, cosψ) where A is a 2x2 matrix. In the wrist camera (top-down), the displacement = B*(sinψ, cosψ) → the strip would be SLANTED in the wrist image by ψ (since the wrist's x ≈ world x, y ≈ world y).\n\nOur wrist row analysis for s014/s019 shows the strip's center x is CONSTANT (255±1) across ALL rows → the bar's projection is exactly vertical → sinψ ≈ 0 → NO YAW.\n\nThat's conclusive, assuming the wrist camera's axes align with x/y. The wrist camera is mounted on the hand which is at yaw=-90 and vertical; the camera's image axes should align with the world axes rotated by the yaw. Vertically, the strip being vertical means the bar's direction is along the camera's y-image direction, i.e., world ±y. So the bar's axis has no x component → no yaw.\n\nTherefore the tilt IS a pitch (in the world's y-z plane). The wrist's taper confirms: the near end is wider → different heights.\n\nSo the bar is pitched ~20-55°. Not acceptable.\n\nFINE. So I must prevent the pitch. Since the fingers can only resist the pitch via friction, and gravity's torque comes from the COM's y-offset from the grip, I must place the grip at the COM's y as closely as possible.\n\nThe measured tilts for various y_grip:\n- y_grip=0.0002 (s010): 24.8° (image) \n- y_grip=0.0124 (s014): 38.5°\n- y_grip=-0.0050 (s019): 54.5°\n\nHmm, but the image angle isn't the true tilt and the bar may shift between grasps. Also I realize the bar might have shifted between grasps! At s020 the bar dropped and moved substantially (the wrist showed the bar's near end way off-center). So YES, the bar's position changes between grasps — my y_grip values aren't comparable to a fixed bar center!\n\nThat changes everything: after each drop, the bar lands in a different y. So my y_grip values were relative to a moving bar.\n\nSo: the correct procedure is to locate the bar's y AFTER each placement (using the wrist image at a known height) and grip at the found center. My earlier y estimates came from a single image (s011) with a rough conversion.\n\nNEW PLAN: Do it carefully with the wrist camera at high z:\n1. If needed, place the bar (it's on the table at s020).\n2. Move to a high z (e.g., 0.30) at the estimated x,y and take a wrist image. Both ends of the bar are visible → measure the bar's center in the wrist image, and the bar's projected length → compute the offset in meters using the known scale (the bar's width from the same image, 0.04 m). \n3. Move to that center, verify with another image, then descend and grasp.\n\nWith the bar level (on the table), the wrist image shows a rectangle: the top face. Its width = 0.04 m, its length = L. From the same image, the pixel scale = W_px/0.04. Then the offset in x = Δu/scale, and in y = Δv/scale (approximately, using the same scale at the bar's depth). The grasp projection is at (256, ~256) but with a camera offset. Ugh, the camera offset again: the image center projects to the eef's grasp point only if the camera's optical axis passes through it. Earlier evidence: the finger midpoint was at ~250-256 → close. And in s013, the bar was centered at 254 while the eef was at the bar's center (x) → so the bar's center projects to ~254 when the eef is centered over it. So the \"grasp center\" in the image is ~254 in u. Good.\n\nFor v: no direct evidence. In s013 (bar under the gripper, centered in x AND y? unknown), the bar's strip spans the full image, so no info. Hmm.\n\nI'll do: place the gripper high, measure the bar's center pixel, move by the pixel offset (using the bar's width as the scale), iterate once, then grasp.\n\nCurrent state: at s020, the gripper is at (0.5934, -0.0052, 0.126) open, and the bar is on the table; the wrist image shows the bar's top end at y≈265 and the strip x 220-290 (center 255). The bar's center in u ≈ 255 (aligned in x ✓). In v, the bar's visible end at 265 with the bar extending down → the bar's center is below the image → the bar is at +y (down in the image = +y).\n\nHmm, this suggests the bar is significantly +y from the gripper. Let's move up to 0.32 and look, so the whole bar is visible.\n\nCommands left: 20. Sim: 79 s. Let's go." + ], + "viewed": [ + "obs/s020_agentview.jpg", + "obs/s020_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 22, + "kind": "move_eef", + "frame_start": 841, + "frame_end": 877, + "command": "move_eef x=0.594 y=0.075 z=0.12 yaw=90 gripper=open speed=0.2", + "args": { + "x": 0.594, + "y": 0.075, + "z": 0.12, + "yaw": 90, + "gripper": "open", + "speed": 0.2 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5931, + 0.0745, + 0.1231 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 63.63461780548096, + "agent_obs_images": [ + "obs/s022_agentview.jpg", + "obs/s022_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "At z=0.316 (camera ~0.386), the wrist view shows a short strip from y=210 to 415, x 238-280. That's the bar: width 42 px, length 205 px. Ratio 205/42 = 4.9. If the width (0.04) → length = 0.196 m ✓. Great, so the bar is ~0.04 x 0.196.\n\nScale = 42 px / 0.04 m = 1050 px/m at the distance of the bar (d ≈ 0.386-0.04 = 0.346 m). So f ≈ 1050*0.346 = 363 px. Good.\n\nThe bar's center: u = (238+280)/2 = 259, v = (210+415)/2 = 312.5.\n\nThe grasp projection: u≈254 (from the finger midpoints? the pads are at 95-130 and 380-415 → midpoint 255) and v = ? The camera axis at v=256. So the bar's center is at Δu = +5 px → 0.0048 m in x (the direction: image right = -x → the bar is at x = eef_x - 0.005 = 0.594), and Δv = +56.5 px → 0.054 m in y. The image down = +y → the bar's center is at y = eef_y + 0.054 = 0.0397+0.054 = 0.094!!\n\nWhoa. That means the bar is at y≈0.09, not 0! Hmm, that's a big offset. But wait, is the camera's optical axis at v=256 really the grasp point? The camera might be tilted forward (looking down-forward), making the image center correspond to a point forward of the eef. If the camera is tilted by an angle β about the x-axis, the image center projects to the table at a point offset in y by d*tanβ. With d=0.35, even 5° gives 0.03 m. That's plausible!\n\nEvidence: In the s007 wrist image (eef at y=0, z=0.117), the bar was centered in u at ~237 and its v-extent 55-430 (center 242). If the bar is at y=0 and the camera's center is v=256, then the observed bar center v=242 (14 px above center) → the bar appears HIGHER (less +y) than the eef's projection → the camera axis projects forward (+y) by 14 px * (0.147/363)=0.0057 m. Hmm, small.\n\nIn s021, the bar's position is unknown (it dropped). The agentview shows the bar around x_pix 232-410 (center 321) while the gripper is at 293. So the bar is at a larger y than the gripper by ~28 px.\n\nHmm, in s000 (the initial state), the agentview bar's center was at 249.7 and the gripper at ~250 → the bar was at y=0 (if the agentview's horizontal is y). So the bar started at y ≈ 0.\n\nNow the bar appears at y≈0.09?! That means my drop at s020 (opening the gripper while holding the bar tilted 54°) threw it to +y by 9 cm. That's a big throw but plausible given the bar was pivoting/rotating and falling from 10cm.\n\nHmm, but wait: in the s020 wrist image the bar appeared at x 220-290 (center 255) — with the eef at x=0.5934. And the s021 wrist shows the bar at u=259 → x ≈ 0.594 (nearly the same x). Interesting—so the drop moved the bar almost purely in +y. OK.\n\nBut the v measurement (bar center at v=312 → +0.054 y) vs the agentview (the bar is +28 px from the gripper → 0.034 m at 825 px/m). These differ (0.054 vs 0.034), likely due to a camera tilt β. If the camera axis projects +0.02 m forward on the table, then the true y offset = 0.054-0.02 = 0.034 ✓ consistent!\n\nSo the camera's optical center corresponds to a point ~0.02 m forward (+y) of the eef. Let's calibrate this offset using s007/s013 knowledge... or just use the agentview's horizontal for y (parallax is small at low z and the tilt is in the vertical direction only). \n\nOK: the bar is at approximately y = 0.040 (agentview) to 0.034. Let me use the agentview method: at s021, the gripper's u=293, the bar's center u=321 → Δ=+28 px. Hmm, but the gripper is at z=0.32 and the bar at 0.04 → the parallax between them for the same (x,y) could be significant in u if the camera has an azimuth component. The bar is at x≈0.59; the gripper at 0.599. In s000, the gripper at x=0.45 was at u≈250 and the bar (x=0.59) at 249.7 — the same u! So the u coordinate is insensitive to x (the camera is nearly in the xz plane). Good. And to z? The gripper is higher; if the camera's u axis is horizontal, u depends only on the horizontal position along r. So the parallax between the gripper (z=0.32) and the bar (z=0.04) in u is minimal. \n\nThus the agentview says the bar's y ≈ the gripper's y + 28/825 = 0.0397+0.034 = 0.074.\n\nHmm, both estimates give y_bar ≈ 0.034-0.054 more than 0.04 → ~0.075-0.094.\n\nLet me just verify with the wrist camera directly after moving: move to y=+0.05 more and take an image; the bar should appear centered in v if my calibration is right.\n\nTo be safe, let me move to x=0.594 (a small correction of -0.005) and y = 0.0397 + 0.045 = 0.085 (a guess between 0.075 and 0.094). Hmm, the risk: if I'm wrong, I'll knock the bar. Let me instead do it in two steps: move to y=0.075 at z=0.32 and check the wrist image; then fine-tune.\n\nActually, better idea: I'll move in x/y to make the bar centered in the wrist image using the measured Δu, Δv with the calibrated scale (1050 px/m at this height) — but the camera's v-offset (the optical axis's forward projection) is my uncertainty. Let me first determine the camera's v-offset by moving to a known y and observing... we know the bar's y only through the agentview.\n\nAlternative: use the agentview for y with the \"align u\" method and the wrist for x (align u). The agentview's u alignment: move y until the gripper's u matches the bar's u at the same z as the bar. That's the cleanest: at z≈0.05 (near the bar's height), align u. Then the parallax is tiny.\n\nThat's what I did before (s018: the gripper's u=253 vs the bar's 253.5 — aligned!). Then the bar tilted 55°. So the y alignment via the agentview was already good, yet the bar pitched.\n\nHmm!! So the y is not the cause (as suspected). \n\nWait, unless the alignment at s018 was done with the bar at a different y than the \"bar center\" I measured (the bbox center). At s018 the bar's bbox was 167-340 → center 253.5 ✓ and the gripper at 253 ✓. So the grip was at the bar's y-center, and the bar still pitched to 55°.\n\nSo the pitch is NOT from a y offset. It's from the gripper/hand itself. Then... maybe the HAND is not vertical! Let me check: the eef orientation—move_eef controls yaw but perhaps the hand's pitch/roll follow from the IK and are not perfectly vertical? The agentview in s018 showed the fingers looking vertical, but let me look closer. In the s018 crop, the near finger's left edge goes from (215,455) to (205,715) in crop pixels (4x) → Δx=-10 over Δy=260 → 2.2° tilt. Small.\n\nBut wait — the finger pads are only ~4 cm long, so a 20° tilt would be a 25 px shift over 75 px. Not seen. So the hand is vertical.\n\nThen WHY does the bar pitch?! Unless the bar's COM is not at its geometric center. The bar is \"metal\"; maybe in the sim it's a box with uniform density.\n\nHmm, hold on. Let me reconsider whether the bar is really pitching. The evidence: the wrist image shows a tapered strip (width 65→130 px) when lifted. What else could produce a taper in the wrist image? If the bar is YAWED and the camera is offset... no, the strip's center is constant.\n\nA taper in a top-down view means the parts are at different distances. If the bar were yawed AND the camera offset in x, the strip would be slanted AND tapered. No slant → no yaw.\n\nSo the bar's +y end is closer to the camera = higher. A pitch. Yes.\n\nUnless the BAR IS BENT?! If the bar were bent/curved (a \"metal bar\" could be an L or a curved object), the taper could appear without a pitch. Hmm! Looking at the agentview s000, the bar looks like a straight rectangular box.\n\nHmm, but wait: what if the bar is TILTED AT REST on the table (i.e., it has a bump)? No, it looks flat.\n\nLet me look at s021's wrist image: the bar spans y 210-415 (205 px) and x 238-280 (42 px) CONSTANT width? Let me check the row widths in s021. If the width is constant → the bar is level on the table (of course it should be).\n\nI'll trust that.\n\nOK so we have a paradox: the grip is at the bar's center in y, yet the bar pitches significantly in the grip.\n\n...unless the pitch happens because the bar rolls during the vertical lift due to a slight arm tilt causing a lateral acceleration. The arm moves straight up, but the IK might introduce a slight lateral motion.\n\nHmm, you know what? Let me test the simplest hypothesis: the bar is LEVEL when held and the apparent taper is due to the WRIST CAMERA being TILTED (not vertical)! If the wrist camera has a tilt β about the x-axis (looking down-forward), then a level bar aligned along y would show a taper?! Let's check: the camera at (0,0,h) tilted by β forward: the projected v of a point (y, z) = f*(y cosβ - (h-z) sinβ)/(...). For a level bar (z=const) along y, the taper would be due to the changing distance: d(y) = ... the distance from the camera to a point at (y, h_bar) is sqrt(y² + (h-h_bar)²) — the distance changes with y even without a tilt! So a level bar in a perspective camera DOES taper: the ends are farther than the center. The visible ends at y=±0.1 with the camera 0.15 above → the center distance 0.15, the end distance 0.18 → the width ratio 0.15/0.18 = 0.83. So the ends would appear ~17% narrower than the center. \n\nIn our data, the width at the far end (65) vs the center (99) → a ratio of 0.66. Hmm, that's more than the perspective effect (0.83) if h=0.15. With h=0.3 (s021 at z=0.32... not held).\n\nHold on, in s014 the widths at the visible strip: 65 at y=224 up to 140 at y=416. But the strip's center isn't necessarily the bar's center.\n\nThis is exactly the geometry that made me think \"pitch\", but the perspective taper for a level bar is symmetric: w(y) should be symmetric about the bar's center. In s014: the widths 65 (y=224), 99 (y=256), 140 (y=416). If the bar's center were at v=320 (the width ~99+... hmm).\n\nLet's fit: for a level bar and a camera at height H above the bar's top face, w(v) ∝ 1/d(v) where d(v) = sqrt((H)² + y²) and y ← v via v = f*y/d. If the bar's center is at v_c, then w(v) should be symmetric about v_c and minimal at v_c.\n\nData (s014): v=128:69, 256:99, 416:140. If v_c were 256, we'd expect w(128) ≈ w(384). w(384)=127, w(128)=69. NOT symmetric → so v_c is not 256. Find v_c: w should be equal at v_c±δ. Try v_c=420+: w(416)=140 is the max → hmm, the max width is at the bottom edge (416) = the closest point. Then the bar's center would be at v≈420+ (near the bottom) — but then the strip's width should decrease from there in both directions; we only see the decreasing part going up. So the camera's optical center is near/below the bottom of the visible strip.\n\nIf the camera is directly above the bar's center (v_c = the grasp axis v≈256), we'd see a symmetric taper. The observed asymmetry → the camera is above a point near the bar's +y end.\n\nHmm! That means: when holding the bar (grip at the bar's center? no), the point closest to the camera is at +y ≈ 0.1 → the bar's +y end is at x_grip... \n\nWAIT. This means the grip is NOT at the bar's y-center when lifted! The camera is above the grasp point, and the closest bar point is near the +y end → the grip is near the bar's +y end!!\n\nBut in s018 (on the table, before lifting), the gripper was aligned with the bar's center in the agentview... \n\nUnless the bar SHIFTS in the grip during the lift! That is, the bar slides through the fingers as it's lifted, ending up hanging with much of its length on one side. A slippery metal bar sliding down through the fingers! That's very plausible: the fingers pinch the bar's sides with limited normal force → limited friction → the bar slips down. Since the grasp's y is at the bar's center, sliding would be vertical (down) — but then the grip's position along the bar wouldn't change...\n\nUnless the bar rotates as it slips, and the combination (rotate + slide) moves the grip toward one end. Gravity pulls the COM down; if the grip is at the center, the bar just slips down without rotating.\n\nHmm, but if during the closing one finger contacts the bar first, the bar gets pushed and rotates... then the lift.\n\nOK, you know what? The observations are contradictory, and I'm burning budget. Let me take a completely different tack: EMPIRICAL SEARCH with direct feedback on the actual outcome. The environment only tells me success/failure at the end; no shaping. So I need to be confident.\n\nLet me think about what a robust solution would look like given the tools (a parallel gripper, no wrist rotation except yaw):\n\nMaybe the KEY is to grip the bar with the fingers oriented along the bar's length (yaw=0), so the fingers pinch the bar's LONG faces?? With yaw=0, the fingers close along y, so they'd pinch the bar's END faces (at y=±0.1) — impossible (0.08 < 0.2).\n\nAlternatively, with yaw=0 the fingers can grip the bar's long faces if the gripper is positioned OFF-CENTER in x such that the fingers are at x = bar_x ± 0.04?? No—with yaw=0 the finger separation is along y, not x.\n\nRight, so yaw=±90 is required.\n\nGiven that, the bar's pitch can only be resisted by friction. So a good grip requires:\n(a) The grip at the COM's y.\n(b) The fingers contacting the bar over a large area with high normal force (which we have).\n(c) The pads' vertical faces parallel.\n\nGiven the fingers' pads have a large area and the bar is gripped over its full 4cm height, the friction torque capacity is μ*N*(pad height/2)... Actually, for rolling resistance: the bar can roll about the x-axis. The normal force N is along x. Friction acts tangentially (in the y-z plane) at the contact patches. The friction force available = μN per contact. The torque about the pinch axis = f_friction * (the moment arm within the contact patch) — but a pure couple about x (the bar rolling) would require the friction forces to form a couple: e.g., friction up on one side and down on the other side of the bar. Both contacts are at x=±0.02, and the friction directions can be arbitrary in the y-z plane. A couple about x would be formed by: the near contact's friction along +z, and the far contact's friction along -z. Both are limited by μN. The couple = μN * (2*0.02)?? No—the couple about x from two forces along z at x=±0.02: moment = F_z * 0.02 (from each) × 2 = μN*0.04. With N≈10N, μ=0.5: 0.2 N·m. The gravity torque = m g s = 0.2*10*s = 2s. So s_max = 0.1 m. So the grip can hold the bar level with a y offset up to 10 cm! Great—so the pitch should NOT happen for a y offset of even 5 cm, unless the rolling is limited by the actual contact geometry.\n\nHmm, but that assumed the friction acts in the needed directions, and it can.\n\nSo a pitch of 20-55° for a centered grip shouldn't happen. Something else is happening. There's probably a real slide+rotate.\n\nHmm, what if the \"close\" command isn't closing with much force (the gripper just positions)? In robosuite, the gripper's close action applies a fixed force, but with the \"gripper=close\" command here, maybe the gripper fully closes to a target width and the object blocks it, applying whatever force the position controller has — which can be substantial.\n\nLet me look at the width: 0.041 — the gripper stops at the bar's width. OK.\n\nNEW HYPOTHESIS: maybe the fingers are not gripping the bar at all but pinching the bar's TOP surface (the fingers' tips are above the bar's top). Then the \"width 0.041\" would be... no, if the fingers were above the bar's top, they'd close fully to ~0.\n\nAlternatively, the fingers grip the bar at the very top edge (the tips only overlap 2-3 mm). Then the normal force is applied at the bar's top corners, and the bar can roll/pivot easily → a big tilt. This is plausible if my grasp z is too high! The eef z=0.0175 → the fingertips at 0.0075. The bar's top is at ~0.04?? Then the fingers overlap the bar from 0.0075 to 0.04 = 3.2 cm. Deep.\n\nBUT WAIT: what if the bar's height is ~0.017 (as one of my estimates suggested)? Then the fingertips at 0.0075 barely reach the bar's mid-height, and the pads' contact height is only the top 1 cm — but the eef grasp point is 1 cm above the fingertips, i.e., at 0.0175 = the bar's top → the pads' contact is entirely above the bar's top?! No, that can't be—it grips.\n\nUgh, the bar's height: the agentview front face measured ~34 px tall vs 175 long. Hmm, in the s000 crop (4x), the front face's height ~55 px → 13.75 px original; the length 175 px. So height/length = 0.0786 → if L=0.196, h=0.0154. So the bar is 0.04 wide, 0.015 tall, 0.196 long! A FLAT bar (like a ruler). That makes sense with \"metal bar\"!\n\nThat changes the geometry: the bar is only 1.5 cm tall. So at eef z=0.0175 (the fingertips at 0.0075), the fingers straddle the bar's width but the bar's top is at 0.0154 → the pads contact the bar over its full height (0.0075-0.0154): 0.8 cm — that's actually fine.\n\nAnd the eef at z=0.0175 with the grasp point 1cm above the fingertips → the grasp point is at 0.0175, just above the bar's top (0.0154). So the grip is essentially at the top of the bar.\n\nHmm, this geometry is workable but shallow. And a flat bar has a COM at z=0.0077; the grip's contact is above the COM → a pendulum → easily rolls/tips.\n\nBut a bar only 1.5 cm tall can't pitch 30° while staying... sure it can.\n\nAlso, the \"lowest point at least 10 cm above the table\" → I need the bar's bottom ≥0.10.\n\nLet's also reconsider: a flat bar lying on the table with the fingers straddling the 4cm width and reaching down 0.8 cm over the 1.5cm height: that's a decent pinch. And the effective moment arm about the pinch axis is small.\n\nI keep going back and forth. Let me just do a solid, careful grasp and see. Given the budget (19 commands, 78s), let me:\n\n1. Move over the bar's actual position (the bar is now at y≈+0.075 per the earlier estimate). Move to (x=0.594, y=0.075, z=0.10) and check the wrist+agentview.\n2. Fine-tune x/y with a high-z view.\n3. Descend, grasp at the center, close.\n4. Lift a little (to z=0.06) and check the tilt in the wrist image; if it's tilting, lower back down and adjust y in the opposite direction of the tilt, re-grasp.\n5. When level, lift to z=0.20 and finish.\n\nCareful with sim time: ~78 s.\n\nActually, better: use SHORT lifts (to z=0.05-0.06) so that if the bar tilts, the tilt is small (the bar remains nearly on the table) and I can iterate cheaply.\n\nActually, I realize there might be an even better trick for the tilt: if the bar is flat (1.5cm tall), I can grasp it at a LOW z such that the fingers' pads cover it fully with the fingertips almost touching the table (z_eef ~0.012). More contact → more friction torque.\n\nLet me now execute carefully. First, move above the bar at (0.594, 0.075, 0.12) and look." + ], + "viewed": [ + "obs/s021_wrist.jpg", + "obs/s021_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 23, + "kind": "move_eef", + "frame_start": 877, + "frame_end": 897, + "command": "move_eef x=0.596 y=0.095 z=0.1 yaw=90 gripper=open speed=0.15", + "args": { + "x": 0.596, + "y": 0.095, + "z": 0.1, + "yaw": 90, + "gripper": "open", + "speed": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5953, + 0.0922, + 0.1024 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 51.5537543296814, + "agent_obs_images": [ + "obs/s023_agentview.jpg", + "obs/s023_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Now the wrist image: the bar spans y 135-425 (290 px), x 220-295 (75 px), center u=257.5, v=280. The gripper's pads: the left pad at ~95-130, the right at 380-415 → midpoint 255.\n\nAt z=0.1231 (camera ~0.19), d≈0.15 → the scale = 75/0.04 = 1875 px/m (f = 281).\n\nThe bar's center v=280 → Δv = +24 px → +0.0128 m in +y. Hmm, but the camera's optical center offset... If the offset is ~+0.02 m forward, then the bar would actually be at y = 0.0745 + 0.0128 - 0.02 = 0.067. Ugh, the offset uncertainty again.\n\nAlternatively use the agentview: the gripper at u≈300 and the bar's center u≈321 → the bar is +21 px → +0.025 m in y → y_bar ≈ 0.0745+0.025 = 0.10. Ugh, inconsistent with 0.067.\n\nThe two cameras disagree because of their offsets. I need a reliable y reference. Hmm.\n\nIDEA: use the wrist camera and a KNOWN reference: the bar's x position! The bar's x is well-determined (my earlier grasp at x=0.596 got the bar centered in u → the bar's x ≈ 0.596, and the u center ≈ 255-257 consistently means the camera's u center ≈ the grasp's u ✓). This tells me the camera's u offset ≈ 0 but says nothing about v.\n\nFor v, I need a known bar y. The bar's initial y was ~0 (s000: the agentview shows the bar's center at u=249.7 and the gripper at ~250 at y=0). But that's the agentview.\n\nAlternative: derive the camera's v-offset using the FINGERS: the finger pads are at (x=±(0.04/2+...), y=0, z≈eef-0.02) in the gripper frame. Their image position in v should be the image's v-center (256) if the camera's optical axis is centered on the finger pair in y. In s022's wrist image, the pads' y extent is 380-420ish (bottom). Not centered → the camera's optical axis is NOT at the fingers' y-center? That's not conclusive either because the pads are far below.\n\nHmm. Use this: in the s022 wrist image, the pad's visible extent in v is 385-425 (the grey pad faces). The pads' 3D center is at y=0 (the grasp y) and z = eef - 0.03. The image v of y=0, z=-0.03: v = 256 + f*0/(0.03)... = 256. But the pads APPEAR at v≈400, not 256!\n\nThat means the wrist camera is significantly TILTED (looking down-forward): the optical axis is not vertical. The pads at y=0 appear at v=400 → below the image center. So the camera's optical axis points forward (+y) by an angle β where tanβ = (offset in the image)/(f) ≈ (400-256)/281 = 0.512 → β ≈ 27°. So the wrist camera looks 27° forward of vertical! That makes sense for a wrist camera designed to see ahead.\n\nSo the camera is tilted 27° toward +y. Then the image center points at the table at a point y = eef_y + h*tan(27°) = eef_y + 0.19*0.51 = eef_y + 0.097?!\n\nHmm, that's big. Then the bar at u=257 (center) would be at y = eef_y + 0.097 → 0.17?! But the agentview says ~0.10.\n\nHmm, the pads' apparent position also includes their z (very close to the camera). Let me redo: the pad's center is at (y=0, z=eef_z-0.03). The camera is at (y=0, z=eef_z+0.07). The vector from the camera to the pad center = (0,0,-0.10). If the camera's optical axis is tilted 27° forward, the pad center is at an angle of 27° from the axis → v = f*tan(27°) = 281*0.51 = 143 px below the center → v=399 ✓✓ matches the observation (400)!\n\nSo yes, the wrist camera is tilted ~27° forward.\n\nNow compute the bar's y: the bar's top face is at z=0.0154, the camera at eef_z+0.07 = 0.193. The point at the image center (v=256) along the optical axis hits the table at y = eef_y + (0.193-0.0154)*tan(27°) = eef_y + 0.1776*0.51 = eef_y + 0.0906.\n\nThe bar's center is at v=280, i.e., (280-256) = 24 px below the center → an additional angle of atan(24/281) = 4.9° → the bar's center is at y = eef_y + 0.1776*tan(27+4.9) = eef_y + 0.1776*0.622 = eef_y + 0.110.\n\nSo y_bar ≈ 0.0745 + 0.110 = 0.185??? That's way off from the agentview estimate (0.10). Something is wrong.\n\nHmm, wait: the \"depth\" along the optical axis is different when tilted. Let me do it properly with vectors. Camera at C=(y=0, z=hc) in the gripper frame (with y_bar measured relative to the eef). The camera's optical axis direction o = (sinβ, -cosβ) in (y,z) with β=27°. A point P=(y_b, z_b). The image v = f * ( (P-C)·u )/( (P-C)·o ) where u = (cosβ, sinβ)?? Let me define u (the image \"down\" direction, i.e., +v) perpendicular to o in the y-z plane: u = (cosβ, sinβ). Then:\n(P-C) = (y_b - 0, z_b - hc) where hc = eef_z+0.07.\n\nv - 256 = f * [(y_b cosβ + (z_b-hc) sinβ)] / [y_b sinβ - (z_b-hc) cosβ]\n\nWith the pad check: y_b=0, z_b = eef_z-0.03, so z_b-hc = -0.10.\nNumerator: -0.10*sin27 = -0.0454. Denominator: 0.10*cos27 = 0.0891. v-256 = 281*(-0.0454/0.0891) = -143. \n\nHmm, I get -143, but the pads appear at +143 (below center). So the sign means β is -27° (looking down-forward is a different sign convention). Let me redo: I want the pads (which are BELOW the camera, in the -z direction) to appear at v=+400 (below the image center, i.e., +v). For the image, +v is downward. The direction \"down\" in the image corresponds to a direction in the scene... For a camera tilted forward (+y), an object directly below the camera appears at the BOTTOM of the image (since the camera looks forward, the area below is in the lower part of the view). Yes ✓. So β = +27° tilting forward should put the point below at +v. My formula gave -v, so my u or o sign convention is off. Let me not worry: the conclusion is the camera is tilted ~27° forward, and the relation for points ON THE TABLE (z≈0.015):\n\nLet me derive with the correct signs using a cleaner approach: the \"down-forward\" camera. Image v-down direction in the world = the direction perpendicular to the optical axis in the (y,z) plane such that it points +y and -z... For β=27° forward, o = (sin β, -cos β) = (0.454, -0.891). The image down vector u must satisfy u·o = 0 and be mostly -z: u = (cos β, sin β) = (0.891, 0.454)?? That's +z and +y — wrong (up-forward). The other option: u = (-cosβ, -sinβ) = (-0.891, -0.454) → -y and -z (down-back). Hmm.\n\nFor a camera looking forward-down, the \"down\" direction in the image corresponds to points behind-below with respect to the camera? Actually, if the camera is tilted forward, then the world's \"down\" direction (-z) leans toward the bottom-back of the image. Points directly below the camera appear at the bottom edge? Let's use a concrete standard: a camera pitched down by angle β from horizontal (looking down 27° from horizontal? or from vertical?).\n\nI'm overcomplicating. Let me just use the empirical: the pads at y=0 appear at v≈400 (below center). And the bar's top face at y=y_b appears at v=280 when y_b is around... In s013 (the bar under the gripper, on the table), the bar was centered in u at 254 and filled the whole v range, so no info.\n\nLet me just calibrate the v mapping empirically with the one known relation: the pads at y=0 → v≈400 (I measured the pads' visible extent 385-425, center 405 at z ≈ eef-0.03).\n\nAnd I have another data point: s007 (eef y=0, z=0.117), where the bar's center appeared at v=242. The bar's y was unknown then (probably ~0). If y_bar=0, then the bar's center at v=242 → for a point at (y=0, z=0.015) vs the pads at (y=0, z=-0.03): both have y=0 but their v's are 242 vs 405 — they'd have the same v if the camera were looking straight down! They differ → the camera's optical axis is not vertical AND the v depends on z.\n\nGiven both points are at y=0 (a vertical line), the projection: v = f*(...)/(depth) — with a tilted camera, a vertical line projects to a line through a vanishing point, and the v varies with depth along it. The pads (closer, 0.10 m below) → v=405; the bar top (0.185 m below, farther) → v=242. So a farther point below appears closer to the image center. Consistent with a forward-tilted camera.\n\nNow: how does the v position map to y for points on the table (z=0.015)? I can get that from a second calibration point: I need a point on the table whose y is known. \n\ns021: the bar was at y_bar (unknown) and the eef at y=0.0397, z=0.316. The bar's center v=312.5 → Δv = +56 with the camera at z=0.386. Distance to the bar's top: 0.386-0.015=0.371 (measurements along z).\n\ns022: the bar at y_bar' (the same physical position, since the bar hasn't moved) and the eef at y=0.0745, z=0.1231. The bar's v=280 → Δv=+24.\n\nLet Y = y_bar (world, relative to the eef's y=0 reference). In s021, the relative y = Y - 0.0397; in s022, Y - 0.0745.\n\nUsing a linearized model around the axis: Δv ≈ f*[ (Δy cosβ - Δz sinβ) / (Δy sinβ + Δz cosβ) ] with Δz = hc - z_bar = the height difference, and the sign conventions determined empirically.\n\nLet me set up: v - 256 = f * (a*Δy + b*Δz)/(c*Δy + d*Δz). With the pad data: Δy=0, Δz = 0.10 (the pad 0.10 below the camera) giving +149 (v=405), and the s007 bar data: Δy=0 (assuming y_bar=0), Δz = 0.185-0.015=0.17 → 242-256 = -14. Hmm, both with Δy=0: then v-256 = f*b*Δz/(d*Δz) = f*b/d = constant. But the data gives +149 and -14 → contradiction! So the y_bar in s007 was NOT 0, or my Δz values are off.\n\ns007: eef (0.5864, 0.0004, 0.1173). The bar at y≈? From s011 (eef y=0.0014) the bar's v center was 215 at z=0.0563.\n\nHmm, the pad reference at y=0 is only valid if the pads' visible center is really at the pad's y-center. The visible pad face in the image spans a range in v because the pad extends in y and z... \n\nThis calibration mess isn't converging. NEW SIMPLE PLAN: forget absolute calibration. Use a REFERENTIAL approach with the agentview: the bar's y is measurable via the agentview's horizontal alignment (which we've used successfully: the s018 alignment gave the gripper at u=253 vs the bar's u=253.5).\n\nGiven the bar now at s022: the agentview shows the gripper at u≈300 and the bar's center at 321 (bbox 232-410). So I should move +21px*(1/825 m/px)= +0.0255 in y → y=0.10.\n\nBut earlier at s018 (aligned, u=253 vs 253.5 → a perfect match), the lift tilted 55°. So the agentview alignment already achieved a centered grip, yet the bar pitched. Hmm, but hold on: maybe the agentview's u alignment at s018 was misleading because of the bar's x-position differences. Both at z≈0.02, so small.\n\nArgh! OK, let me think about the 55° tilt at s018 differently. Maybe the bar's tilt at s018 was NOT caused by the y offset but by the fact that the bar, at the moment of closing, was gripped ON THE TABLE with the fingers pushing it sideways, and then it rotated during the lift because the grip's contact point was near its EDGE in y (i.e., the fingers' pads, 1.5-2 cm wide, contacted the bar only near the pad's edge).\n\nI keep coming back to needing a trial with a genuinely different y.\n\nLet me consider the budget: 18 commands, 76 s. A trial costs ~4 commands. I could do 3 trials. I need to finish with the bar held at z≥0.12.\n\nLet me make the trials count. I'll also start measuring the bar's y properly: use the AGENTVIEW's u alignment as the criterion (the parallax is minimal at low z). At s022 the gripper is at u≈300 and the bar at 321 → move +0.025.\n\nBut wait: at s018 the alignment was u=253 vs 253.5 and it still tilted. In s018, the eef's y was -0.005. So the bar's y was ≈ -0.005. In s010 the eef's y was 0.0002, aligned → the bar's y ≈ 0. In s014 the eef's y=0.0124 → but I did NOT check the alignment in the agentview at that time. Hmm, in s012 the eef's y was 0.0124; the agentview showed the gripper at ~253 and the bar at ~253.5 (bbox 167-340) → aligned! So the bar's y was ≈0.0124 then.\n\nSo the bar's y has been moving: 0 → 0.0124 → -0.005 → now 0.10 (after the drop).\n\nThe tilts: s010 (y_bar=0): 24.8°; s014 (y_bar=0.0124): 38.5°; s019 (y_bar=-0.005): 54.5°.\n\nInteresting: the bar's y changed with each grasp (because the fingers dragged it?). And the tilt magnitudes increased steadily. This looks like a cumulative degradation: the grasp is progressively worse. Maybe the bar ends up hanging more and more.\n\nYou know what? Let me look at the current s021 wrist image of the bar ON THE TABLE: it's centered at u=259 and the bar's visible strip spans 238-280 with a CONSTANT width (level) ✓. And its v range 210-415 with the center at 312. \n\nThe key: since the bar is LEVEL on the table now, I can align the gripper over it using the wrist camera's u (x ✓) and estimate y from the agentview. Then grasp. And critically: to preserve the levelness, after closing, LIFT VERY SLOWLY (0.01 m/s) and STOP after 2-3 cm to check the tilt, then continue.\n\nAlternatively — and this may be the winner — lift the bar and if it tilts, LOWER it back down until it's ON the table again (level), then close the gripper HARDER? There's no force control.\n\nAlternatively: after grasping and lifting slightly, if it tilts, use the table... hmm.\n\nHmm, WAIT. What if the pitch is caused by the bar's contact with the TABLE during the lift (dragging)? If at s018 the grasp was at the bar's center in y but the bar's x was slightly off-center (the grip not centered in x), then during the lift... no, x doesn't cause a pitch.\n\nLet me try a very different tactic for the final answer: hold the bar with the gripper open? No.\n\nLet me try: grasp slowly with the bar on the table, close, and lift EXTREMELY slowly (speed=0.01) in 2 cm steps, watching the wrist image for the tilt. If the tilt appears immediately, I'll lower it back and try a different y by ±1 cm.\n\nLet me just go. First, align: move to y=0.100, x=0.594, z=0.12.\n\nHmm, but I worry: my y estimates keep bouncing. Let me do one combined move to y=0.095 and look at both views, then descend only if both look centered.\n\nActually, better use of the wrist: at z=0.12 the bar's strip in s022 was centered at u=257.5 with the grasp axis at u=255 → x is good. For y, use the agentview's u. Let's move to y=0.095 and re-check." + ], + "viewed": [ + "obs/s022_wrist.jpg", + "obs/s022_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 24, + "kind": "move_eef", + "frame_start": 897, + "frame_end": 942, + "command": "move_eef z=0.013 yaw=90 gripper=open speed=0.06", + "args": { + "z": 0.013, + "yaw": 90, + "gripper": "open", + "speed": 0.06 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5952, + 0.0925, + 0.015 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 14.55888819694519, + "agent_obs_images": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "In the agentview, the gripper's fingers are at u≈318 and the bar's center is at ~321 (bbox 232-410 → center 321). Very well aligned now. \n\nIn the wrist, the bar spans x 220-302 (center 261) vs the grasp axis ~255 → the bar is 6 px right → x = eef - 6*(d/281)... d≈0.10+0.07-0.015=0.155 → scale=1813 px/m → 3.3 mm. Fine.\n\nLet me compute the bar's y from the wrist: v center = (85+425)/2 = 255. Hmm, now the bar's v center is 255 (image center). In s022 at z=0.123 the bar's v center was 280, and now at z=0.102 it's 255. As the camera descends, the bar shifts up in the image (v decreases) — consistent.\n\nThe pads are at v≈395 (bottom). The bar's center at v=255.\n\nOK so now the alignment: the agentview says the gripper is under the bar's center ✓.\n\nNow: descend to z=0.012 (the fingertips at 0.002) — the bar is 1.5cm tall, so the fingers will surround it fully. Wait, careful: the bar's top is at 0.0154; if the fingertips reach 0.002, they'd be nearly at the table. The pads would contact the bar's sides fully ✓. But the risk: the fingers might hit the table (the table is at z=0). The fingertips at 0.002 is OK.\n\nBut be careful: the grasp point being 1cm above the fingertips, at z=0.012 the grasp point is at the bar's top. Good.\n\nThen close, then lift slowly 2 cm and check.\n\nLet's do: move z=0.014, speed 0.06, then close, then lift z=0.04 (speed 0.02) and observe the wrist/agentview.\n\nActually the eef z resolution: the previous descent to 0.0175 worked fine.\n\nGo with z=0.013." + ], + "viewed": [ + "obs/s023_wrist.jpg", + "obs/s023_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 25, + "kind": "move_eef", + "frame_start": 942, + "frame_end": 957, + "command": "move_eef gripper=close speed=0.04", + "args": { + "gripper": "close", + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.595, + 0.0927, + 0.015 + ], + "gripper_width_after": 0.0412, + "holding_after": true, + "touched_during": true, + "think_s": 9.065670013427734, + "agent_obs_images": [ + "obs/s025_agentview.jpg", + "obs/s025_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The bar is well-centered under the gripper in the agentview (fingers at u≈318, the bar 232-410 → center 321). The wrist shows the bar centered at ~257.\n\nNow close the gripper and lift very slowly in small steps." + ], + "viewed": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 26, + "kind": "move_eef", + "frame_start": 957, + "frame_end": 978, + "command": "move_eef z=0.035 speed=0.02", + "args": { + "z": 0.035, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5935, + 0.0922, + 0.0327 + ], + "gripper_width_after": 0.0409, + "holding_after": true, + "touched_during": true, + "think_s": 3.893742799758911, + "agent_obs_images": [ + "obs/s026_agentview.jpg", + "obs/s026_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 27, + "kind": "move_eef", + "frame_start": 978, + "frame_end": 1023, + "command": "move_eef z=0.1 speed=0.03", + "args": { + "z": 0.1, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5919, + 0.0918, + 0.0966 + ], + "gripper_width_after": 0.041, + "holding_after": true, + "touched_during": true, + "think_s": 21.232014417648315, + "agent_obs_images": [ + "obs/s027_agentview.jpg", + "obs/s027_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The bar is lifted ~2 cm and looks LEVEL in the agentview! The bar spans (232,285) to (410,295) — nearly horizontal. Let me measure precisely.\n\nThe wrist image also looks symmetric/level.\n\nSo this grasp is holding level so far. The previous failures had the bar tilted right after lifting to 0.10. Maybe here the alignment is better (y=0.0922, and the grip is at the bar's actual center).\n\nContinue lifting slowly and check the tilt again.", + "s024 (on the table, before closing): angle 0.41° ✓ level.\ns026 (lifted 2cm): angle -4.85°. Hmm, already tilting (the right end up, the same direction as before).\n\nThe mask's ymin=177 is suspicious (the bar's top at 177?), probably catching part of the gripper. Let me restrict to exclude the gripper region... The bar's bbox x 233-409, y 177-321: the bar is ~165 px long and if tilted 5° it'd span 15 px vertically; 144 px of vertical span means the mask includes the gripper (grey-blue?). Since B-R>=4 excludes pure grey... but the gripper's shadowed parts could be bluish. Let me check the mask region visually. Actually the angle fits (PCA dominated by the bar's 5000 px vs the gripper's few).\n\nHmm, -4.85° is under 8°. But the trend is rising (0.4 → -4.9). Let me lift more and see if it stabilizes.\n\nIf it keeps increasing with height, the pitch is progressive. Let me lift to 0.10 and measure. If it's under ~6°, I'll go for it (the finish threshold is 8°).\n\nNote: the agentview's apparent angle isn't the true tilt. Previous holds: 24-55° apparent. If I now get <6°, the true tilt is likely small too.\n\nContinue: lift to z=0.10 at speed 0.02, measure." + ], + "shell": [ + "cd /opt/lffjail/work && timeout 50 python3 - <<'EOF'\nimport numpy as np, cv2\nfor n in ['s024','s026']:\n im = cv2.imread(f'obs/{n}_agentview.jpg')\n B,G,R = im[:,:,0].astype(int),im[:,:,1].astype(int),im[:,:,2].astype(int)\n m = (B-R>=4)&(B>40)&(R<140)\n m[:175]=0\n ys,xs=np.nonzero(m)\n pts=np.stack([xs,ys],1).astype(np.float32)\n c=pts.mean(0); u,s,vt=np.linalg.svd(pts-c,full_matrices=False)\n d=vt[0]\n if d[0]<0: d=-d\n print(n,'angle',round(np.degrees(np.arctan2(d[1],d[0])),2),'center',c.round(1),'bbox',xs.min(),xs.max(),ys.min(),ys.max())\nEOF" + ], + "viewed": [ + "obs/s026_agentview.jpg", + "obs/s026_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 28, + "kind": "move_eef", + "frame_start": 1023, + "frame_end": 1085, + "command": "move_eef z=0.05 gripper=open speed=0.02", + "args": { + "z": 0.05, + "gripper": "open", + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5909, + 0.093, + 0.0496 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 91.69937062263489, + "agent_obs_images": [ + "obs/s028_agentview.jpg", + "obs/s028_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Damn, it tilted a lot again (~35°). So the tilt develops during the lift: at 2 cm it was 5°, at 10 cm it's 35°. So the bar rotates progressively as it's lifted.\n\nThis suggests the bar is ROLLING due to the lift's dynamics. The bar rolls until... the tilt grew from 5° to 35° while rising 7 cm. Hmm.\n\nSince the bar rolls freely in the grip, its orientation is set by the dynamic (friction-limited) contact. If gravity's torque is ~0 (centered grip), what makes it roll?\n\nAH WAIT. I think I finally get it! The bar might be rotating because the two fingers are NOT at the same height or the gripper is slightly tilted! If the hand is tilted about the x-axis by even a few degrees AND the force pressing the bar is large, then... no, a tilt wouldn't roll the bar.\n\nAlternatively, the bar rotates because the fingers' pads SLIDE along the bar's sides while closing (they squeeze and slide), imparting a twist.\n\nThe key data: at 2cm the tilt was 5°; at 10cm it's 35°. So the bar rolls while being lifted. Rolling requires a torque. Where does it come from? Gravity + a y-offset (about 0.09 y position now, and the bar's center is at... 0.09?).\n\nWait, I keep assuming the grip is at the bar's y-center. What if the bar's center is NOT where the agentview's silhouette center suggests? The bar's silhouette in the agentview = 233-409 → center 321; the gripper u = 318. But the agentview's u may not be linear in y (perspective + the x-leak). A 3 px difference could correspond to ~1cm. Fine, so the grip is within 1cm of the bar's center.\n\nA 1cm offset gives a small torque. Yet it rolls 35°.\n\nUnless the BAR's COM is not at its geometric center — e.g., the bar is a \"metal bar\" with an asymmetric shape (like a beam with a ridge)? Looking at the wrist images, the bar looks like a plain box.\n\nAlternatively, the ROLL is not gravity-driven but rather the clamp force: if the pads' faces are not parallel to the bar's faces (e.g., the fingers' pads have a slight V), closing would rotate the bar. But this would happen immediately at closing (already at 2cm it was 5°).\n\nHmm, and the increase from 5° to 35° while lifting... If the bar is free to rotate, any perturbation grows.\n\nHmm, could the bar be rotating because it's SLIDING DOWN through the fingers? If the bar slides down, the friction force on the bar points UP. If the contacts are asymmetric in y (one finger's contact patch is offset), that creates a torque about x. As the bar slides, it rotates. Over a 7cm lift, if the grip slips by ~1cm at one contact... The width stays 0.041, so the grip force is at the limit of slipping.\n\nGiven that the bar keeps slipping/rotating, the fundamental fix is to get a stronger grip. Options: the gripper's force is fixed.\n\nNEW IDEA: what if I grip the bar at the very END (the y extreme) so that the bar's remaining length hangs to one side? Then it would swing down to a vertical orientation. Worse.\n\nNEW IDEA: Grip the bar near the center, lift, and accept the tilt... no, the task needs <8°.\n\nNEW IDEA: Since the bar rolls freely about the x-axis, and gravity/perturbations make it tilt, maybe I can COMPENSATE by rotating the GRIPPER'S yaw by 90°!! Wait: think about it. If I rotate the gripper 90° about the vertical axis while holding the bar, the contact faces rotate, and the bar (free to roll about the pinch axis) would... the bar would be forced to rotate with the fingers? With a 90° yaw rotation, the fingers would twist the bar about the vertical axis (a yaw of the bar), not a roll. Doesn't fix the pitch.\n\nNEW IDEA: Can I use the ARM's geometry to level the bar? No.\n\nNEW IDEA: Use the table: lower the bar until it rests on the table, then the bar is level (supported by the table). Then close the gripper HARD (fixed force, but the alignment is already set). Then lift. It'll tilt again.\n\nHmm, but WAIT: what if the tilt only develops during the vertical MOTION (dynamics), and I could minimize it by moving very slowly? At 2 cm with speed 0.02 the tilt was 5°. That's already borderline. Then at speed 0.03 the lift to 0.10 gave 35°. Maybe the acceleration at the start of the motion is the culprit, and moving at 0.005 m/s would keep it level. Sim time is a concern: 10 cm at 0.005 = 20 s. We have 68 s. Feasible!\n\nBut there's a catch: the tilt at 2cm was already 5°, growing from 0.4° before the lift. Hmm.\n\nAlso, an important thing: the bar's roll equilibrium might be at 90° (hanging) and the tilt would keep growing with time regardless of speed. The 3 s lift showed 35°; the tilt rate ≈ 10°/s. Even at a slow speed, the time to lift 10 cm at 0.005 m/s = 20 s → the bar would roll way past 8°.\n\nUnless the tilt is due to the ARM's motion (vibration) and not gravity. If I lift 2cm and STOP, the tilt stays at 5° (no growth while stationary, since the observe/image is taken after the motion stops). At 2cm the bar was 5° and stayed. Then moving up 7cm took ~1.4 s and the tilt grew 30° → a rate of ~21°/s during motion.\n\nSo the rotation happens DURING motion. A slow motion would still rotate, just... if the rolling is a pure kinematic slip driven by the contact geometry (e.g., the fingers' pads slightly tilted → a screw motion), the rotation would be proportional to the DISTANCE moved, not the speed: 30° per 7cm → 4.3°/cm. So even moving 10cm slowly gives 43°.\n\nHmm, but at 2cm we had 5° → 2.5°/cm. Consistent-ish with a distance-proportional roll of ~3-4°/cm.\n\nSo: the roll is proportional to the lift distance. That means the grip acts like a \"rack and pinion\": the bar rolls as it slides through the fingers. This would happen if the contact geometry is asymmetric in z (e.g., the finger pads contact the bar with a normal force whose line of action is offset from the bar's COM in z... \n\nOK whatever the mechanism: the lesson is that the bar rotates ~3-4° per cm of vertical motion. To stay under 8°, I can lift at most ~2cm.\n\nBut I need ≥10 cm of clearance. Hmm!\n\nUNLESS the bar's rolling is due to the SLIDING of the bar through the fingers, and if the bar doesn't slide, no roll. The bar slides because the friction isn't enough to hold it (the grip force is low). But the gripper width was 0.041 and closing with force.\n\nAlternatively the \"roll\" could be a rotation of the HAND: maybe the IK/joint controller rotates the hand about the x-axis as the arm rises (e.g., the wrist joint compensates)! The eef state only reports yaw, but the actual hand orientation has a pitch/roll that the controller might not hold constant. THAT would explain everything: the hand (and thus the bar) tilts as the arm moves up! And earlier, when I lifted from the table to 0.10 with a different arm configuration, the tilt was different (24°, 38°, 55°) depending on the starting pose.\n\nBut wait, in the s014/s019 cases the bar tilted much more than 8°, and the agentview showed the FINGERS remaining vertical (I checked visually). Hmm, if the hand rolled about x, the fingers (thin plates) would both tilt... The pads are plates in the y-z plane; a roll about x would tilt them but they'd still look like plates from the front. The bar would tilt with them.\n\nEarlier I measured the near finger's edge in s018: a 2.2° tilt — but that was at the table.\n\nA good test: measure the gripper's finger orientation in the agentview at s027 (lifted). If the fingers are tilted ~35°, then it's the hand!\n\nLooking at s027's image: the fingers (white pads) at (310,225)-(335,290): the pad's long axis is vertical-ish but let me measure. The image shows the white finger plate tilted slightly? Hard to tell at this resolution. Let me crop and look.", + "Now I see the geometry clearly! The gripper's fingers are vertical (the white finger plate is vertical). The bar is tilted and — crucially — the grip point is near the bar's END (the short end at the upper right... no wait).\n\nLooking at the crop: the bar goes from the lower-left to the upper-right. The gripper fingers are at the center-left, and the bar's visible left end is at the bottom-left (x~30,y~560) while the right end is at the top-right (x~640,y~95). The distance from the grip point (x~290,y~350) to the left end is ~220 px, and to the right end ~390 px. So the grip is NOT at the center; it's about 35% from the left end.\n\nHmm, but which end is which in y? The bar is tilted so the right end is higher and further (going up-right = -x is up in the image + ...). \n\nActually, the bar's tilt in this crop is ~38°. And the grip is off-center.\n\nSo the bar has SLID along its length through the fingers by several cm during the lift. This means the fingers' grip is sliding along the bar — the bar is slipping through the pinch, and as it slips it rotates.\n\nHmm, the bar slides through the grip (along its axis = y) and rotates (about x). If the bar slips along its axis, the fingers' friction is insufficient. The bar's weight along the tilted axis has a component that pushes it through the grip.\n\nThis suggests the grip is fundamentally weak: the bar slips. So the whole approach is marginal.\n\nWhy is the grip weak? The gripper reports width 0.041 = exactly the bar's width... The gripper's force should be strong. Unless the bar's width is slightly larger than 0.041+ and the fingers are straining at the limit of their travel.\n\nOR: the fingers contact the bar only at the very top corners (a shallow grip of a 1.5cm-tall bar with the fingertips at z=0.005 — the bar's top is at 0.015 and the table at 0; the contacts span z 0.005-0.015 = the upper 2/3). Should be OK.\n\nHmm, wait. Let me reconsider the bar's dimensions. What if the bar is TALLER than I thought, e.g., 0.04 tall? Then at my low grasp (fingertips at 0.005), the fingers cover z 0.005-0.04... the pads are ~3cm tall, so fine, deep.\n\nI wonder if the real issue is the parallel-jaw gripper's force in this sim: maybe \"gripper=close\" just moves the fingers to a closed position without force control (a position command). If the finger position target is 0 (fully closed) with a low stiffness, the contact force is small.\n\nI have 13 commands and 69 s left; the current state is a tilted bar held in the air. What's the best use?\n\nRealization: maybe I should try the \"lift and let it settle\" approach: the bar's rotation was progressing during the lift. Maybe if I stop and wait (with a tiny move), it settles? But the settle would be toward hanging vertically.\n\nALTERNATIVE IDEA (much better): LIFT THE BAR IN A WAY THAT LETS THE TABLE DO THE LEVELING, then stop before much rotation: since the tilt is proportional to the lift distance (~3-4°/cm), if I lift only 2-3cm above the grasp height (i.e., eef z ~0.05), the tilt is ~5-10°. Not enough clearance.\n\nHmm! But WAIT: maybe I can lift the bar, and as it tilts, the two ends stay near the table... no.\n\nRETHINK: what if I grasp the bar at its center such that the fingers pinch the bar's WIDTH but the fingertips are BELOW the bar's mid-height, and the grip's geometry essentially \"cradles\" the bar? Since the bar is thin (1.5cm), the fingers' pads (3cm tall) extend below the bar's bottom when the fingertips are at z=0.005? No—the bar's bottom is at z=0 (on the table). The fingers can't go below the table. So the fingers can only contact the bar from z=0.005 to 0.015 (1cm tall). The fingertip is at 0.005 → 5mm off the table.\n\nIf the bar is 4cm tall, the contact is 0.005-0.04 = good.\n\nSo if the bar is thin (1.5cm), the grip is inherently a top-pinch → it will roll and slip. If the bar is 4cm tall, the grip is deep.\n\nGiven the agentview's front-face measurement, I estimated the height at ~0.015. But that measurement is affected by perspective.\n\nLet's settle the bar's height once and for all: in the s027 crop (a clean view of the bar), the bar's visible thickness (its side face height) near the middle ~55 px in the 4x crop → 14 px original. The bar's length = 407-233 = 174 px for 0.196 m → 888 px/m. So the height = 14/888 = 0.0157 m. Yes: the bar is 4.0 x 1.6 x 19.6 cm. A flat metal bar/ruler!\n\nSo the grip contacts only the top 1cm of the bar's 1.6cm height. The bar's COM is at z=0.008, the contact at 0.005-0.015 → the COM is within the contact zone. Fine.\n\nGiven the thinness, any roll rotates the bar's top/bottom faces away, and the grip becomes edge-contact, allowing slipping.\n\nKEY INSIGHT: with a flat bar, the BEST grasp is to pinch it across its WIDTH (as we do) but the fingers must contact its full 1.6 cm height. The fingertip must go to ~0.001. Then the contact is 0.001-0.016 (full height) → the fingers can't roll the bar much because the pads' inner faces are flat and vertical, contacting the bar's full height. But the bar can still roll (rotation about x) with friction resisting.\n\nThe roll happens because the bar's roll is only resisted by friction. Since our lift is slow (quasi-static), the required torque is tiny (only the y-offset torque). If the grip is centered, the torque ≈ 0 → no roll. Since we observe a roll, the grip is off-center in y by a few cm (which we see: the grip is 35% along the bar).\n\nSo the bar slips along its axis toward a hang, i.e., the COM moves below the grip. The bar slides through the pinch because the friction is insufficient (the normal force × μ < the axial force needed... but for a horizontal bar, the axial gravity force is zero at level; as it tilts, the axial component grows).\n\nI think the story is: the bar starts level, then a small perturbation (dynamics) makes it tilt slightly; once tilted, gravity's axial component makes it SLIDE through the grip and rotate further — a runaway (since the roll reduces the contact quality and increases the torque).\n\nIf that's the case, then the crucial thing is to prevent the initial tilt. Ideas:\n- Lift VERY slowly with no lateral acceleration.\n- Keep the bar level by construction.\n\nHmm, what if the initial perturbation comes from the gripper's closing (the fingers sliding on the bar's faces imparts a roll)? At s026 (2 cm up) the tilt was already 5°, and before closing it was 0.4°. So the closing+initial lift introduced 5°.\n\nWith such a fragile equilibrium, getting under 8° after 10+ cm of lift seems hard.\n\nALTERNATIVE STRATEGY: hold the bar against something? Hmm, what about holding the bar so that its TILT is mechanically constrained: e.g., pinch the bar near its END so that the other end... no.\n\nRADICAL ALTERNATIVE: Instead of lifting the bar with the fingers pinching the thin dimension, pinch the bar with the fingers along its LENGTH?! If the gripper's yaw is 0, the fingers close along y and the pads are 8cm apart max — the bar is 19.6cm. Can't.\n\nRADICAL ALTERNATIVE 2: What if I use the closed gripper as a \"hook\" — no.\n\nRADICAL ALTERNATIVE 3: What if I place the bar on TOP of the closed gripper's fingers? No.\n\nRADICAL ALTERNATIVE 4: THE TABLE EDGE? No.\n\nRADICAL ALTERNATIVE 5: Flip the bar onto its SIDE first (rotate 90° about its long axis) so it becomes 4cm tall and 1.6cm wide. Then the fingers could pinch the 1.6 cm width... even worse! Actually, then the fingers would contact the two 4-cm-tall faces with their full height (if the fingertips are at z=0.005 and the bar's top is at 0.04 — the pads contact 0.005-0.04 = most of the height). That's a much deeper, more stable grip against rolling! The bar would be \"on edge\" though: the task says \"hold it level\" (tilted <8°) — if the bar stands on edge with its long axis horizontal, the \"tilt\" of the long axis is still ~0. The bar's lowest point... fine.\n\nBut is \"level\" evaluated by the bar's long axis? Probably. Standing on edge might be a different axis but the long axis remains horizontal.\n\nHmm, but flipping the bar onto its edge reliably is hard.\n\nALTERNATIVE 6: Grasp the bar in the middle with the fingers' pads SQUEEZING it against the fingers'... \n\nWAIT. What about grasping the bar by its TOP FACE with the gripper's fingers closing on the bar's top face from both sides? The Panda fingers have a rubber pad at the tip. Not possible.\n\nHmm, let me reconsider: is the slip really along the bar's axis? From the crop, the grip is at 35% along the bar. So yes, it slid ~3cm along its length.\n\nIf I could keep the bar from sliding along its axis, it wouldn't roll much. What if the bar is pinched HARD so that the normal force is high (the fingers can't slide)? The gripper's close force is what it is.\n\nHmm, what if I close the gripper BEFORE descending, so it's at its narrowest, then... no, it must be open to straddle.\n\nWhat about approaching with the gripper already partially closed (width 0.045) so that when it descends over the bar, the fingers barely clear (2.5mm per side)? Then closing applies the force through a smaller travel and might grip tighter? The force is set by the controller, not the travel.\n\nI'm running low on budget (13 commands, 69 s). Let me make a decision.\n\nDECISION: Try the \"slow, minimal-lift\" approach with an emphasis on keeping the bar level:\n1. Put the bar down (it's currently tilted 35° at z=0.0966; lower to z=0.02 and open).\n2. Re-grasp at the exact center with the fingertips as low as possible (z_eef=0.011 → the fingertips at 0.001). Close.\n3. Lift to only z=0.13 in one slow move and hope the tilt stays under 8°.\n\nWe already did essentially that and got 35°.\n\nAlternative DECISION: Try to fix the tilt AFTER lifting by exploiting the roll: the bar rolls about the pinch axis. If I move the gripper's YAW by 180°, the pinch axis rotates 180°... the bar's tilt would remain relative to the world (the bar stays rolled). Hmm, but the tilt axis: the bar's tilt is a rotation about the pinch axis (x). If I rotate the gripper yaw by 90°, the pinch axis becomes y, and the \"tilt\" (rotation about x, i.e., one end up) would then be a roll about the new... no, the bar's actual 3D orientation doesn't change when I yaw the gripper? Actually it does: the fingers rotate and drag the bar with them (friction), so the bar yaws with the gripper. Its tilt (rotation about x) remains.\n\nIf instead I yaw the gripper 90° in the OTHER configuration... doesn't fix.\n\nHmm, actually WAIT. What if I yaw the gripper by 90° while holding the tilt, then close harder... no.\n\nWhat about using the tilt to my advantage: the bar's tilt is a rotation about the pinch axis. If I rotate the gripper about the vertical by 90° and the bar rotates with it, the bar's long axis becomes x. Then the bar's \"tilt\" would be... the bar's long axis would be along x, and the rotation that was about x becomes about y → the bar's long axis would now point along x and the \"up end\" would still be up → the bar would be tilted about y (still level? no). It's the same physical tilt relative to the world: the end that was up remains up regardless of the yaw. So no.\n\nOK. What if I simply HOLD THE BAR LEVEL USING THE TABLE AS A GUIDE: place the bar on the table, grasp it, and then lift only 10.5 cm... it tilts.\n\nHmm hmm. Let me reconsider: is the tilt perhaps caused by the fingers themselves, i.e., the pads aren't parallel but V-shaped? If the pads have a V, then closing on the bar's flat sides would self-center it and hold it firmly (no roll). Not our case.\n\nWhat if the hand's pitch is not vertical? Let me MEASURE the hand's orientation precisely using the wrist camera and the bar on the table: In s024 (on the table, level), the bar's center in the wrist at v=255 (level). We can't separate.\n\nLet me try yet another thing: WHAT IF THE BAR IS ACTUALLY GRIPPED FINE AND THE TILTED APPEARANCE IS BECAUSE THE BAR IS NOT A BOX BUT A WEDGE/TAPERED? Looking at the s027 crop: the bar's visible top face is a parallelogram; the end faces are visible. It looks like a plain box, but its ends reveal... the left end shows a slanted cut! In the s027 crop, the left end at the bottom shows an angled end face (not perpendicular). Interesting — maybe the \"metal bar\" has chamfered ends. Doesn't matter.\n\nLet me consider the acceptance test: maybe the tilt threshold (<8°) is evaluated on the bar's long axis relative to horizontal. Our 35° fails.\n\nNew plan to get a stable level grip: PINCH THE BAR NEAR ITS END WITH THE GRIPPER'S PADS PERPENDICULAR TO THE BAR? Not possible.\n\nHonestly, the most promising remaining idea is to make the bar thicker (4cm tall) by standing it on edge, so the fingers can grip it over its full height and the pads' contact is large (less rolling). But the bar would then be 1.6cm wide, and rolling would matter less because the fingers' pads contact the 4cm-tall faces and the bar's roll axis... hmm, it can still roll but the pads' contact would be on the wide faces, and the rolling torque would tilt the bar about its long axis (harmless) — NO WAIT. If the bar is on edge (long axis along y, standing 4cm tall), the fingers pinch its 1.6cm-wide dimension (along x) — the contact faces are the 4cm-tall sides. Then a roll about the x-axis (the pinch axis) tips the bar's ends up/down — the same problem. And a roll about y (the bar's own axis) would be harmless. So the same problem remains.\n\nUgh.\n\nLet me think about the actual physics once more. The fingers are PARALLEL JAWS closing along x. The bar's long axis is along y. Rolling the bar about x (the pinch axis) means the bar rotates like a propeller in the y-z plane. The finger pads' inner faces are planes with normal x. Friction at these contacts resists the roll: the friction forces available are μN in any direction within the contact plane (the y-z plane). A roll (rotation about x) is resisted by a couple: at the near contact, friction along +z; at the far contact, friction along -z. Actually the two contacts are at x=±0.02, and the roll torque is about x. The friction forces at both contacts act in the y-z plane; their moment about the x-axis = (the contact position × F) — since the contacts are at x=±0.02, and the force is in the y-z plane, the moment about x = (x_cross F)_x = (y*F_z - z*F_y) — independent of x! So the moment about x depends on the contact's y and z positions relative to the bar's center, times the friction force.\n\nThe contact patches are at the bar's mid-height (z ≈ 0.008 the same as the COM) and span some y range (±pad width). So the moment arm about x ≈ the contact patch's extent in z: the patch is 1cm tall → the moment arm ≤ 0.005 m. The max roll torque = μN * 0.005 ≈ 0.5*20*0.005 = 0.05 N·m. The gravity torque for a 2cm y-offset = m*g*0.02 = 0.2*10*0.02 = 0.04 N·m. Comparable! So the grip can just barely hold a 2cm offset. With a 3cm offset, it rolls.\n\nSo the grip's roll resistance is inherently weak because the contact patch's height is small (the bar is thin).\n\nSo I need the grip's y offset to be < ~1cm to hold level. AND the initial perturbation must be small.\n\nMy best attempt (s024-s026) had the grip close to centered (the agentview showed the gripper's u = 318 vs the bar's 321 = 3 px = 3mm) and it still tilted 5° at 2cm, then 35° at 10cm.\n\nHmm, but WAIT: the bar in s027 slid along its length to a 35% grip. Where did that come from? That's a 3cm slide. Once it slides, it's off-center → the torque → more roll → more slide. A runaway.\n\nThe initial 5° tilt at 2cm: maybe caused by the lift's dynamics. If I could lift without dynamics, the bar would stay level.\n\nWhat if I lift the bar in TINY increments with pauses? Each command ends with the arm holding still. The images are taken at the end. The lift from 0.013 → 0.10 in one command at 0.03 m/s takes 2.9 s. The initial acceleration (the fastest profile) may shake the bar.\n\nLet me try: multiple small lifts (1-2cm each) at slow speed, checking after each. If the tilt grows, stop.\n\nWe have 13 commands. A lift of 10cm in 5 steps of 2cm = 5 commands. Feasible.\n\nAlso: use a VERY slow speed (0.005 m/s) so the accelerations are tiny.\n\nPlan:\n1. Lower the bar to z=0.013 and open (the bar is now tilted 35° at z=0.097 — lowering it back will make the lower end touch the table; the bar will rest flat). Command: move z=0.013 gripper=open speed=0.02. Hmm, careful: it's tilted; lowering to 0.013 means the lower end goes to... the bar's lowest point is ~0.09 below the grip → at eef z=0.013 the lower end would be 8cm below the table — the bar will hit the table and the gripper will force it down, possibly bending the sim/popping. Better: lower to z=0.06, open (the bar drops 6cm... risky, it may land tilted but it's a thin bar; it'll settle flat).\n Actually, a cleaner way: lower slowly to z=0.05 then open → the bar drops ~5 cm (its lower end is near the table already). It should settle flat.\n2. Look, re-align x/y (the bar may have shifted!).\n3. Descend, close.\n4. Lift in 2 cm steps at 0.005 m/s, checking the tilt at each step.\n\nThat's 1 + 1-2 + 2 + 5 = 10 commands. We have 13. Tight but OK. And sim time: 69 s; the steps at 0.005 m/s × 2cm = 4 s each → 20 s + the re-grasp ~10 s = 30 s. OK.\n\nActually, wait. Before the elaborate retry, let me test a KEY hypothesis quickly: does the tilt depend on the lift speed? If the bar is stable when held still at 2cm (5°) but the roll grows with distance, then a slow lift may not help. Since the roll seems distance-proportional (a slip), speed may not matter.\n\nAlternatively — maybe the best trick: lift the bar and then use the TILT-SLIDE coupling in reverse: if the bar slides when tilted, I can slide it back by... no.\n\nHmm, hold on. What if I grip the bar at its center and lift it with a MOTION THAT COMPENSATES the roll? Like, move the eef in y as I lift, keeping the bar's COM under the grip? That doesn't stop the roll.\n\nLet me think about why it rolls in the first place when the grip is centered. At the moment of the lift, the bar's inertia resists the upward acceleration, creating a torque if the grip is offset. With the grip centered, no torque... but the contact force distribution adjusts, and the bar can roll from the friction asymmetry: the pads slide microscopically.\n\nI wonder if the roll is caused by the closing action: as the fingers close on the bar, they push it along x? No, the forces are symmetric.\n\nOK, given the budget, let me do the careful retry with slow steps. If the tilt is <8° at 5cm, I could then decide.\n\nActually, ALSO IMPORTANT: I should use the wrist camera to measure the tilt more accurately, since its top-down view is more sensitive. But the agentview is fine.\n\nLet's go: step 1: lower to z=0.05, open." + ], + "shell": [ + "cd /opt/lffjail/work && python3 - <<'EOF'\nfrom PIL import Image\nim=Image.open('obs/s027_agentview.jpg')\nim.crop((250,180,420,330)).resize((680,600)).save('obs/s027_crop.png')\nEOF" + ], + "viewed": [ + "obs/s027_agentview.jpg", + "obs/s027_wrist.jpg", + "obs/s027_crop.png" + ] + } + }, + { + "attempt": 1, + "step": 29, + "kind": "move_eef", + "frame_start": 1085, + "frame_end": 1116, + "command": "move_eef x=0.592 y=0.1 z=0.012 yaw=90 gripper=open speed=0.05", + "args": { + "x": 0.592, + "y": 0.1, + "z": 0.012, + "yaw": 90, + "gripper": "open", + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5919, + 0.0999, + 0.0132 + ], + "gripper_width_after": 0.0794, + "holding_after": false, + "touched_during": false, + "think_s": 18.794569730758667, + "agent_obs_images": [ + "obs/s029_agentview.jpg", + "obs/s029_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The bar is on the table and level; the gripper is at u≈318 and the bar spans 238-410 → center 324. So the bar is +6 px = +7mm from the gripper in y. The wrist shows the bar at x 200-315 → center 257 (2 px right of 255). Fine.\n\nNow, descend and close, then lift in small steps.\n\nBefore that, let me reconsider the approach once more given 12 commands.\n\nI keep observing that once lifted ~10cm, the bar ends up ~35° tilted with the grip sliding to ~35% along its length. The slide is 3cm along y.\n\nIDEA: Compensate the slide by grasping OFF-CENTER in the opposite direction, e.g., at 35% from one end, so that after sliding it ends up centered! Hmm, that's clever: the bar slides to put its COM under the grip. If it ends up centered at equilibrium, that wouldn't happen (it would stay wherever it is). Actually the slide happens because the roll creates an axial force component. Hmm, the slide direction: in s027, the grip ended up ~35% from the LEFT end. Which end is that in +y? The bar's left end in the agentview is at u=238, and u increases with y → the left end is -y, the right is +y. So the grip is closer to the -y end → the grip ended at y_bar_center - 0.03. The grip's y = 0.092; so the bar's center ended at ~0.122.\n\nWAIT! That's a big finding: the bar's center ended up at y≈0.122, i.e., 3cm in the +y direction from the grip. So the bar SLID toward +y through the grip.\n\nHmm, interesting. But why +y? If it were a symmetric COM-seeking slide, it would go toward... The bar's center should end up under the grip, i.e., the bar slides so its center is at the grip. If the grip was at the bar's center initially, it wouldn't slide. If the bar's center was at 0.092+δ, it slides...\n\nThe slide direction tells us the bar moved +y relative to the grip. So initially y_bar < y_grip.\n\nBut before closing, the agentview showed the bar's center at u=324 vs the gripper at 318 → the bar was +y of the grip by 6px (7mm) — i.e., y_bar > y_grip. Contradiction with the slide direction (the bar moving +y means it was -y).\n\nUnless the slide is a dynamic effect, not a COM-seeking one.\n\nOK, given the limited budget, let me try the \"grip at the center + slow lift in 2cm steps\" and MONITOR. If the tilt stays small, proceed. If it grows, I'll try one last trick.\n\nWhat trick could save the run if it keeps tilting? Idea: since the tilt seems to develop along with the lift, maybe LIFT TO A HEIGHT where the tilt is ~8° and then... the task needs 10cm.\n\nAnother possible trick: reduce the roll by pressing the bar against the table while lifting?? No.\n\nAnother idea: rotate the gripper's yaw by 90° AFTER lifting: the bar's long axis would rotate to x (yawing). The bar's tilt (rotation about x) becomes a rotation about... the bar's tilt axis rotates with the gripper: the tilt would become about y (a rotation in the x-z plane). The bar's long axis would then be along x and tilted in the x-z plane → still a tilt from horizontal. No good.\n\nHmm, unless: the bar's tilt is a rotation about the pinch axis (x). Rotating the gripper yaw by 90° to make the pinch axis y: the bar's long axis then lies along... the bar is held with its long axis perpendicular to the pinch axis: originally y ⊥ x-pinch. After a 90° yaw, the bar's axis → x, and the pinch axis → y. The bar's tilt (rotation about the old x) → after the yaw, a rotation about the new y. The bar's long axis is x, tilted out of the horizontal by rotating about y → still not level.\n\nNo.\n\nFINAL IDEA if the tilt persists: use the bar's tilt to bring it into level by shaking it. Nah.\n\nLet me proceed and see. Descend to 0.012, close, then lift 2cm, check." + ], + "viewed": [ + "obs/s028_agentview.jpg", + "obs/s028_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 30, + "kind": "move_eef", + "frame_start": 1116, + "frame_end": 1131, + "command": "move_eef gripper=close speed=0.03", + "args": { + "gripper": "close", + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5918, + 0.1001, + 0.0131 + ], + "gripper_width_after": 0.0411, + "holding_after": true, + "touched_during": true, + "think_s": 3.836329698562622, + "agent_obs_images": [ + "obs/s030_agentview.jpg", + "obs/s030_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 31, + "kind": "move_eef", + "frame_start": 1131, + "frame_end": 1150, + "command": "move_eef z=0.032 speed=0.005", + "args": { + "z": 0.032, + "speed": 0.005 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5903, + 0.0996, + 0.0293 + ], + "gripper_width_after": 0.0409, + "holding_after": false, + "touched_during": true, + "think_s": 9.966586589813232, + "agent_obs_images": [ + "obs/s031_agentview.jpg", + "obs/s031_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Gripper closed at 0.0411, bar on the table, aligned (the bar 238-412, center 325; the gripper at ~320).\n\nNow lift in small steps at a very slow speed. 10 commands left, 63 s.\n\nStep 1: z=0.032 at speed 0.005. Then check." + ], + "viewed": [ + "obs/s030_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 32, + "kind": "move_eef", + "frame_start": 1150, + "frame_end": 1256, + "command": "move_eef z=0.135 speed=0.005", + "args": { + "z": 0.135, + "speed": 0.005 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5887, + 0.0992, + 0.132 + ], + "gripper_width_after": 0.041, + "holding_after": true, + "touched_during": true, + "think_s": 39.17757487297058, + "agent_obs_images": [ + "obs/s032_agentview.jpg", + "obs/s032_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "At 1.6cm lift, the tilt is -4.73° already (it was 0.83° on the table). So the tilt appears immediately with the lift, roughly independent of speed. The grip is at the edge of stability.\n\nSo the equilibrium tilt for this grip is >8° — the grip is off-center by ~2-3 cm, or the roll resistance is low.\n\n9 commands left (plus the finish), 62 s. I need a decisive fix.\n\nKEY IDEA (new): use the wrist camera to directly SEE the grip's offset and correct it! At the table-closed state (s030), the wrist image shows the bar between the fingers. Since the bar is level on the table and the camera is fixed to the gripper, the bar's position along y relative to the fingers is visible in the wrist image (accounting for perspective).\n\nBetter yet: at a low z with the gripper closed on the bar, the wrist image shows the bar's extent in the vertical direction. In s030's wrist image (not seen but s013's was: the bar spans the full width 173-335 in x, constant). For y, the bar spans the whole image height. Not helpful.\n\nBUT: I can lower the camera further? No, the camera is 7cm above the eef.\n\nALTERNATIVE KEY IDEA: find the balance point EMPIRICALLY but efficiently using the tilt SIGN. The tilt at s031 is -4.7° (the right end up, i.e., +y up). If the equilibrium tilt is caused by the COM being at -y relative to the grip (the y_c < y_grip), the fix is to move the grip -y.\n\nThe magnitude relation: earlier, at y_grip=0.0124 the tilt was 38.5°, and at y_grip≈0 it was 24.8° (different placements though). Now, at y_grip=0.0999, the tilt is only 4.7° at 1.6cm (and it will grow with height).\n\nI don't have a clean model. But here's the thing: the tilt at 1.6cm is 4.7°, and it grew to ~35° at 10cm before. The growth is a runaway once it starts.\n\nMaybe I can PREVENT the runaway by keeping the grip's y perfectly centered, and the residual 4.7° at 1.6cm might not run away if the initial tilt is smaller.\n\nWhat if the 4.7° initial tilt is a measurement artifact of the lifted bar's perspective? The bar's apparent angle also depends on the camera's perspective when the bar is off in y... hmm, the bar's center is at y≈0.10, well off the agentview's center.\n\nHonestly, maybe the cleanest path forward: instead of y, adjust the GRASP z (deeper) — already at the table.\n\nNEW IDEA: What if the tilt is caused by the bar SLIDING on the fingers during the lift (friction-limited), and I can prevent the slide by tilting the bar... \n\nNEW IDEA (promising): keep the bar level by NOT lifting it straight up: lift it while moving slightly in the direction that counters the roll. The roll's angle grew ~3°/cm of lift. With a 10cm lift, that's 30°. To counteract, I'd need to rotate the bar... I can't.\n\nNEW IDEA (seriously promising): GRIP THE BAR AT ITS CENTER OF MASS ALONG Y BY BISECTION, using the tilt's SIGN as feedback. The tilt's sign tells me which side the COM is on. I have 9 commands. Each trial: place (1), move+close (1-2), lift (1), measure (0 commands with the shell) = ~4 commands/trial. So ~2 trials. If the first trial at y=0.10 gives -4.7°, then I need to know the sensitivity to y. From the data:\n- y_g=0.0124: 38.5°\n- y_g=0.0002: 24.8°\n- y_g=-0.005: 54.5°\n- y_g=0.0999: 4.7° (at 1.6cm lift, not comparable!)\n\nThe earlier ones were at 10cm lift. So not comparable.\n\nUgh, the comparison is confounded by the lift height AND the bar's placement.\n\nHmm, let me think about the physics ONE more time, because I think I might be missing something big.\n\nObservation: the bar is centered when closed on the table; once lifted, it rolls. The roll direction is consistently \"+y end up\" (the right end up, in every single lift). That's a SYSTEMATIC asymmetry, not random!\n\nA systematic roll in the same direction every time suggests a systematic cause: e.g., the gripper's hand is slightly tilted (about the x-axis) so the bar rolls to match. But the fingers look vertical...\n\nOR: the bar's COM is systematically off-center in the SAME direction relative to the gripper every time. If the agentview's u alignment is systematically biased by a few px, the bar would always be gripped slightly off-center in the same direction.\n\nThe agentview's u measurement: the bar's silhouette center vs the gripper's center. But the gripper's center: I've been using the white finger's position visually. If the near finger (visible) is at x=+0.02 (the +x side) and the camera is at +x... the visible finger is the near one, which is at +x. Its image u is at the right of the bar's center? The bar's center in u and the visible finger's u differ by the projection of 0.02 m in x... In the agentview, the x direction maps mostly vertically, so u ≈ the y direction → the near finger's u ≈ the bar's center u when the y is aligned. OK, so my alignment method is valid.\n\nHmm, but the +y-up roll consistency: the camera's azimuth! The agentview camera might be offset in azimuth, adding an x-dependence to u. If the camera is at (+x, +y offset), then the u axis has a component along x: u ≈ a*y + b*x. Then aligning u might misalign y. The b coefficient: from s003→s004 (moving the eef by -0.102 in x), the agentview's gripper u barely moved (maybe 5-10 px) → b ≈ 0.05-0.1 px/mm. Then a 1cm y error ↔ 100 px... no: a=825 px/m, so a 1 cm error = 8 px. My alignment is within ~5 px = 6mm. OK.\n\nSo the grip is centered within ~6mm. And a 6mm COM offset gives a gravity torque of m*g*0.006 = 0.012 N·m for a 0.2 kg bar — small compared to the friction capacity (0.05 N·m estimated). So it should hold. Yet it rolls.\n\n=> The systematic cause must be geometric: the HAND is tilted about x. Let me check this by measuring the finger's tilt in the agentview at a lifted pose (s031). The fingers are white/light grey. Let me crop s031 and look closely. If the hand is tilted ~a few degrees... The bar's roll is 4.7° at 1.6cm lift in the agentview's projected angle; the true tilt might be ~4°. Hmm, if the hand were tilted 4°, it would explain everything, including the runaway (once the bar rolls beyond the pads' edges it slides).\n\nActually, WAIT!!! If the hand is tilted about x by α and the bar is level, the two finger pads would contact the bar's sides with a normal force that is perpendicular to the pads (tilted by α from horizontal). The bar's top/bottom faces are horizontal. With a tilted pinch, the contact forces have vertical components → the bar experiences a torque/force that could make it roll. In a quasi-static lift, the bar would rotate to align with the pads (the pads' faces are parallel to the bar's side faces only when the bar rolls by α). So the equilibrium: the bar rolls by α (matching the hand's tilt).\n\nIf α ≈ 5°, the bar would roll 5° and stop (under 8°!). But we observe 35° at 10cm. So the runaway continues past 5°.\n\nUgh.\n\nLet me try the most direct thing: measure the finger's tilt in the agentview at s031 (or s027). If the hand is tilted significantly (5-20°), then the fix might be to compensate the hand's tilt... but we can't command roll.\n\nHmm, BUT: if the hand's tilt is the issue, maybe the yaw rotation affects it! I commanded yaw=90 → the reported eef_yaw = -90. The controller might have achieved a strange orientation. Let me try yaw=-90 (command) → the reported yaw would be +90. Since the hand's roll would be mirrored, the bar's tilt direction would flip! If it does, I could pick the one with the smaller tilt... no, that's silly.\n\nActually, if the hand's tilt about x is what rolls the bar, then the sign of the roll would flip with the gripper's yaw (mirrored). But a 90° yaw about z doesn't simply mirror...\n\nLet's test with yaw=180! Hmm, with yaw=±180 the fingers would close along y — that's the bad grasp direction.\n\nOK, time check: 9 commands, 62s. Let me be decisive.\n\nDECISION: Try lifting with a small, deliberate y-offset bias to counteract the systematic +y-up roll: the roll has the +y end up → the COM is at -y relative to the grip → move the grip -y. Let me move the grip -y by ~1cm and lift. If the tilt decreases, continue.\n\nBut the bar is currently gripped and tilted 4.7° at z=0.029. To change y, I'd have to place, open, move, close, lift = 4 commands. I have 9. Then, if it works, the final lift = 1-2 commands. That leaves 3-4 for a final attempt. Hmm, tight.\n\nALTERNATIVE: maybe I can just go UP slowly from here and see how the tilt evolves with small steps. If the tilt stays ~5-8°, we might squeak under 8° at full height. Risky but cheap (a few commands).\n\nLet me check: at 1.6cm the tilt is 4.7°. Move to z=0.06 at 0.005, measure. That's 1 command + shell. Then decide.\n\nActually, better: move to z=0.13 (the target) at 0.005 and measure. If the tilt is <8°, finish. If not, I've used 1 command and I have 8 left for a correction.\n\nHmm, but the tilt might exceed 8° and then it's too late for that attempt? No—I can lower it and re-grasp within the same attempt. Fine.\n\nGo: z=0.15 (a bit higher for margin) at speed 0.005. The bar's lowest point must be ≥0.10 → with the grip at the bar's center height (~0.008 below the eef), the eef at 0.15 gives the bar's center at ~0.14, so the lowest point ~0.135 ✓ plenty.\n\nHmm, but the higher I lift, the more the runaway roll. Let me target the minimal height that satisfies the task: the bar's bottom ≥ 0.10 → the eef ≥ 0.11 (since the bar's center is ~0.008 below the eef, the bar's bottom is ~0.016 below the eef). So the eef at 0.12 gives the bar's bottom at ~0.104. Cutting it close. Let's target z=0.135 → the bar's bottom ~0.119. Good margin, minimal lift.\n\nGo: z=0.135 at speed 0.005." + ], + "shell": [ + "cd /opt/lffjail/work && timeout 50 python3 - <<'EOF'\nimport numpy as np, cv2\nfor n in ['s030','s031']:\n im = cv2.imread(f'obs/{n}_agentview.jpg')\n B,G,R = im[:,:,0].astype(int),im[:,:,1].astype(int),im[:,:,2].astype(int)\n m = (B-R>=4)&(B>40)&(R<140)\n m[:200]=0\n ys,xs=np.nonzero(m)\n pts=np.stack([xs,ys],1).astype(np.float32)\n c=pts.mean(0); u,s,vt=np.linalg.svd(pts-c,full_matrices=False)\n d=vt[0]\n if d[0]<0: d=-d\n print(n,'angle',round(np.degrees(np.arctan2(d[1],d[0])),2),'center',c.round(1),'bbox',xs.min(),xs.max(),ys.min(),ys.max())\nEOF" + ] + } + }, + { + "attempt": 1, + "step": 33, + "kind": "move_eef", + "frame_start": 1256, + "frame_end": 1353, + "command": "move_eef z=0.05 gripper=open speed=0.02", + "args": { + "z": 0.05, + "gripper": "open", + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5869, + 0.0992, + 0.0486 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 125.22424292564392, + "agent_obs_images": [ + "obs/s033_agentview.jpg", + "obs/s033_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Tilted ~35° again at z=0.132. Same as before. The tilt reaches ~35° regardless.\n\n8 commands left, 57 s. I need a different approach for the tilt.\n\nLet me now think about what the 35° equilibrium means. The bar always ends at ~35° with the +y end up. It's a stable equilibrium of the roll in the grip. So the grip's roll dynamics have an equilibrium at 35°.\n\nIf the equilibrium is at 35° with the +y end up, that means the effective COM (or the contact torque) is such that ... The equilibrium is where the gravity torque (about the pinch axis) balances the contact torque. The contact torque is a function of the bar's roll angle relative to the pads: as the bar rolls, its side faces (4cm wide, 1.6cm tall) rotate relative to the pads. At 35°, the bar's \"flat\" faces are at 35° to the pads. The contact would then be at the bar's corner edges! At that point, the contact geometry could provide a stable detent.\n\nHmm, 35° is roughly where the bar's diagonal... the bar's cross-section is 4.0 x 1.6; the diagonal angle = atan(1.6/4) = 21.8°. At a 22° roll, the bar's corner touches the pad. Hmm.\n\nActually! Consider: the fingers' pads are vertical planes at x=±0.02. The bar (4cm wide) is pinched. If the bar rolls by θ, its width in x becomes 4cosθ+1.6sinθ... which GROWS: at θ=21.8°, the diagonal = 4.3 cm > the 4.1 cm jaw opening. So the bar CANNOT roll 22° while staying pinched — the jaws would have to open! The reported width stayed 0.041, so the bar is not rolling about its own axis within the jaw. Therefore the roll is about the pinch axis x... \n\nWait, I need to be careful: the bar rolls \"about the x axis\" = the tilt = the ends up/down. That rotation does NOT change the bar's cross-section in the grip. The cross-section (in the y-z... no, in the x-z plane? Hmm.\n\nLet me set up coordinates: the bar's long axis = y, width = x (4cm), height = z (1.6cm). A \"tilt\" (one end up) = a rotation about the x-axis. This rotation maps the long axis (y) to (0, cosθ, sinθ) and the height axis (z) to (0,-sinθ,cosθ), while the width axis (x) stays. So the cross-section in the x-z plane... the width (x) is unchanged, and the height (z) mixes with y. So the width stays 4cm → the jaws stay at 4.1cm ✓. Consistent.\n\nSo the tilt is free (no jaw interference) — pure roll about x.\n\nNow, at equilibrium 35°, the contact forces must balance gravity's torque. With the bar tilted, its side faces (the ones being pinched, which are the x=±0.02 faces, i.e., planes normal to x, now rotated so they contain the y-z tilted axis) — the faces still normal to x ✓. So the contacts remain face-to-face. Good.\n\nSo the bar's tilt is free and the equilibrium is set by... the gravity torque about the pinch axis: the COM's position relative to the grip. At equilibrium, the COM must be directly below the grip?! Then the bar would be VERTICAL (90°) with the grip at the top... unless the grip is at the bar's y-center, in which case the COM is right at the grip and all angles are neutral.\n\nSo, at 35°, the COM is NOT below the grip; hence the contact torque is balancing a gravity torque. The contact torque comes from the friction couple. So the bar is at the limit of friction... which would mean it's still sliding slowly.\n\nHmm, but it reads 35° consistently in different runs. That's oddly reproducible for a friction-limited equilibrium.\n\nWAIT. Maybe the \"consistency\" is because the bar slides until it's off-center by a fixed amount determined by the pad width. Hmm.\n\nNEW THOUGHT: maybe the bar isn't rolling about the pinch axis at all, but the FINGERS are applying a torque because one finger is lower than the other — i.e., the hand is tilted. Let me finally MEASURE the hand's tilt in the agentview using the finger edges, precisely.\n\nIn s032, the fingers are the white pads around (315-350, 215-290). Let me crop at high zoom and measure the pad's long edge's angle.\n\nIf the hand is tilted about the x-axis by α, the bar would settle at α... but we see 35°, so α=35°? Then the fingers would be visibly tilted by 35°, which they're not (they look vertical).\n\nAlternatively, the hand is tilted about the Y-axis (a side tilt). That doesn't cause a pitch.\n\nOK, radical alternative given 8 commands: \n\nSince the bar reliably ends at ~35° with the +y end up, maybe I can use that! What if I grasp the bar with a deliberate YAW so that its long axis is at 35° in the horizontal plane... no, the tilt is vertical.\n\nWait wait wait. What if the tilt is not a pitch but a YAW after all, and my wrist-camera analysis was flawed? Let me re-examine s032's wrist image: the bar's silhouette (dark) spans x 215-295 at the top (y=205) and 190-330 at the bottom (y=390). The CENTER at the top = 255, at the bottom = 260. So the center shifts by 5 px over 185 px → a 1.5° slant. So no yaw ✓. The width grows from 80 to 140 → a strong \"closer at the bottom\" effect → the bottom (+y) end is higher.\n\nSo it's a pitch: the +y end is up, and the tilt is large (the projected length along y is short: 185 px).\n\nCompare with s021 where the bar was level on the table at z=0.316: it spanned 205 px. Now at z=0.132 (the camera much lower, so the same bar would span much more, maybe 700 px) but it spans only 185 px → the y-extent is hugely foreshortened → the pitch is large (60°+?).\n\nHmm! The wrist projection is much more sensitive. So the tilt might be 50-60°.\n\nSince it's such a large tilt, let me think about why the equilibrium is at ~50°.\n\nAt 50°, the bar's +y end is up and the -y end is down. The grip is at some point. If the grip were at the bar's center, the COM would be at the grip → no torque → no preferred angle. The fact that it settles at 50° means it's at the friction limit (it's still sliding) OR the grip is at the bar's y-center but the bar's COM is off (e.g., the bar is a wedge?).\n\nFrom s032's agentview, the bar's grip is clearly off-center again (~35% from the lower end).\n\nSo the bar slides to ~3cm off-center each time, then rolls. The slide is the cause, not the effect. The slide happens because the friction along the bar's axis is insufficient... \n\nFriction along y: the bar's weight has no y-component when level, so why would it slide at all? Unless the initial tilt creates a y-component.\n\nSo it's a runaway: tilt → slide → more tilt.\n\nThe INITIAL tilt is the key. What causes it? Possibly the lift's initial acceleration with a slightly off-center grip.\n\nIf I could start the lift with the grip EXACTLY centered, the runaway might not start.\n\nAlternatively, counteract: apply a bias so that the initial torque opposes the systematic one.\n\nGiven the systematic direction (+y end up), I should grip +y of center (so the COM is at -y relative, creating a torque that lowers the +y end... wait: if the grip is at +y of the COM, then the COM is at -y → gravity pulls the -y end down → the +y end UP. That's the SAME direction as the observed tilt! So to counteract, the grip should be at -y of the COM (i.e., the COM at +y), making the +y end sag.\n\nCurrently the bar slides so the grip ends at ~35% from the -y end, i.e., the grip is -y of the COM (the COM at +y). That would make the +y end SAG. But we observe the +y end UP. Contradiction!\n\nSo the tilt direction is NOT gravity-driven. It's a systematic mechanical effect (the hand/contact asymmetry).\n\nTherefore: the bar rolls to 50° because of the hand's geometry, and a y adjustment won't fix it.\n\nIf the hand is systematically rolled (about x) by some angle... the bar would align with the hand → a fixed tilt regardless of y. That matches: the tilt is roughly the same (35°) in different grasps.\n\nAnd the observed tilt of the bar relative to the fingers in the agentview: let me actually LOOK at whether the fingers are tilted in s032. In the image, the white finger pad appears vertical-ish, but the bar is at ~35°. The fingers are painted white; their long axis goes from (318,215) to (330,290) → a slope of 12/75 = 9°. Hmm! Maybe the hand is tilted ~9° about... that's in the image plane, which for the agentview could be a combination of the hand's pitch.\n\nIf the hand (the whole gripper) is pitched about the x-axis by 9°, the bar would be held at ~9°, not 50°.\n\nI'm clearly unable to resolve this analytically. PRACTICAL DECISION TIME.\n\nWe have 8 commands, 57 s. The task success requires <8°.\n\nLet me try the OTHER yaw sign: command yaw=-90 (which gives a reported +90). If the systematic tilt reverses, I could compare. But it won't be smaller.\n\nHmm, hold on! What about grasping with yaw=90 but the bar's long axis... no.\n\nWhat about a completely different trick to level the bar: rotate the gripper's YAW by exactly 90° AFTER lifting (with the bar at 50° tilt). Then the pinch axis becomes y. The bar's long axis would rotate to x. The bar's tilt (which was about x) becomes a rotation about y — i.e., the bar's long axis (now x) is tilted in the x-z plane by 50°. Still bad.\n\nBUT: after yawing the gripper, the bar's roll about the OLD x-axis becomes a rotation about the NEW y-axis... and the new pinch axis is y! So the bar's tilt would be a rotation ABOUT THE PINCH AXIS — which is free/neutral! The gravity torque would then... hmm, the bar's tilt about the pinch axis is the free direction, so gravity would rotate it. The bar's long axis would be along x, and the tilt would now be a rotation about y = the free roll → the bar's ends (along x) would swing up/down freely → gravity would bring the COM below the grip → the bar would hang vertically-ish. Worse.\n\nOK, alternative practical approach: accept that the pinched bar tilts, and instead find a way to hold it with the tilt <8° MOMENTARILY at finish? The evaluation happens at the finish, when the bar is static.\n\nHmm, what if the bar is still SETTLING (sliding slowly)? Then a snapshot at the right moment could be level... unreliable.\n\nWhat if I keep the bar pressed against the TABLE with the gripper while... no, it must be 10cm up.\n\nNEW IDEA: can I re-orient the bar so it lies along X (perpendicular to y)?? If the bar's long axis is along x, then the \"tilt\" is a rotation about y. With the fingers pinching along x (yaw=-90), the bar's long axis along x would mean the bar is inserted BETWEEN the fingers lengthwise — impossible.\n\nNEW IDEA: Rotate the gripper yaw to ~45° so that the bar's long axis is at 45° and... the bar would still tilt about some horizontal axis.\n\nNEW IDEA: Use the arm's wrist joint? Not controllable.\n\nNEW IDEA: what if I DON'T grab the bar but instead... the task requires holding it.\n\nLet me look at the s032 wrist image once more: the bar's dark top face is tilted toward the camera (like a ramp). The bottom of the strip is wide (the near/+y end, high) and the top is narrow (the far/-y end, low). So the +y end is up.\n\nHmm, hold on! Is it possible that the bar is NOT tilted but is instead resting against the finger? Like, the bar's -y end is drooping because it's NOT GRIPPED — it's just leaning on the fingers?\n\nLet me test the \"is it really gripped\" question: if the bar were just leaning, the width of the bar between the fingers would be less than 0.041... the gripper reports 0.041 = the bar's width, so the fingers are closed on the bar.\n\nRight, I've spent a lot. Let me consider the possibility that the tilt is ~35-50° in the wrist projection but might be less in 3D... no, the agentview also shows ~35°.\n\nFINAL STRATEGY with 8 commands: Try a DIFFERENT GRASP: put the bar down, and re-grasp it but with the gripper's yaw at -90 (the opposite handedness) — maybe the hand's systematic tilt reverses, giving a tilt in the opposite direction with a possibly different magnitude. If it's smaller (<8°), great.\n\nThat costs: lower+open (1), align (1), descend+close (1), lift (1) = 4, leaving 4 for the finish.\n\nAlternatively, and possibly smarter: try grasping with a deliberate y-offset of ±2cm and see if the tilt changes magnitude. If the tilt is systematic (hand-driven), it won't change; if it's COM-driven, it will.\n\nGiven the data at y_grip≈0 (24.8°) and y_grip=0.0124 (38.5°) and now 0.10 (35°) — the tilt is ~25-40° regardless of y. So it's systematic, NOT COM-driven. So adjusting y won't help. Confirmed.\n\nTherefore the systematic cause is the hand/contact. The only remaining lever: the yaw sign.\n\nLet me try command yaw=-90 (reported +90). This mirrors the hand's roll direction (the wrist joint rotates 180° about z). If the hand's roll about x is a systematic error, it might flip sign.\n\nActually here's a thought experiment: the reported eef_yaw for my +90 command was -90, meaning the controller interprets the yaw with an opposite sign; the actual gripper orientation is what it is (the fingers along x). If the hand has a roll error +α about x, then after a 180° yaw... hmm, the yaw is about z, which doesn't flip the x-roll; it maps it to something else. Rotating the hand by 180° about z: a roll about x becomes a roll about -x. So the systematic tilt direction would flip! Good test: if the tilt flips to the other end up, then it's confirmed as a hand roll, and its magnitude would be the same (35°) — not helpful for success, but informative.\n\nAlternatively, yaw ±180 (fingers along y) is a bad grasp.\n\nHmm, is there any way to compensate a hand roll? If I could rotate the bar about its long axis... no.\n\nWAIT A SECOND. What if the hand's roll isn't the cause, but rather the GRIPPER's pads are worn/asymmetric in the sim (e.g., the fingers have a small step at the tip)? Then the bar would be tilted in a fixed way relative to the fingers.\n\nEither way, yaw=-90 flips it.\n\nIs there any configuration where the tilt would be small? If the systematic tilt is caused by an asymmetric pad geometry (like the pads' surfaces being slightly non-parallel), then flipping the gripper's yaw wouldn't help; it would just mirror the tilt direction.\n\nHmm.\n\nLet me consider ANOTHER possibility: maybe the fingers' pads are at an angle in the Y direction (the pads are trapezoidal), and when closing, they squeeze the bar and rotate it about z... we ruled out yaw.\n\nOK, let me consider what remains. 8 commands. Alternatively, I could try to rotate the bar about its long axis... \n\n!!!! IDEA !!!! What about grasping the bar so that its 4cm WIDTH is vertical and its 1.6cm THICKNESS is horizontal? I.e., the bar standing on edge. Then the pinch would be on the 4cm-tall narrow faces (the fingers pinch the 1.6cm dimension). The bar's roll about the pinch axis (x) would tip the ends; the pads would contact the 1.6cm-tall sides... the contact patch's height = the bar's 1.6cm thickness → the moment arm is small; same as before. But the bar in this orientation is 4cm tall and its COM is 2cm below the contact's mid-height... Hmm, if the fingers pinch over the bar's full 1.6cm thickness (the fingertips must reach near the table, and the bar is 4cm tall → the fingers would contact only the top 1cm). Hmm.\n\nNo good.\n\nFINAL IDEA: maybe the bar is NOT tilting 35° in the sim, but the WRIST camera is rotated relative to the gripper (a camera mounting roll) and the AGENTVIEW... no, both show it.\n\nLet me look at the actual s032 image once more. The bar's visible shape: the top face is a long dark parallelogram tilted ~35° in the image, with the right end up and the near/left end down. Its projected length ~165 px (the same as always!). Interesting — the projected length does NOT shorten even though the wrist view says the y-extent is dramatically shortened!! \n\nThe constant 165 px projected length in the agentview is a strong clue: for a 50° pitch, the agentview's projected length would be L*sqrt((Sy cos)²+(Sz sin)²) ≈ 165*sqrt(0.41+0.59) = 165 if Sz=Sy.\n\nFor a YAW, the same. So the agentview can't distinguish, and both could keep the length ~constant. Fine.\n\nBut the wrist camera's shortening (185 px vs an expected 700 px) says the bar's y-extent is ~0.26 of the full → a 75° pitch?! That would be nearly vertical. And the agentview would then show the bar's projected length nearly equal to the bar's HEIGHT (1.6 cm), i.e., ~14 px — but we see 165 px. CONTRADICTION!\n\nSo the wrist camera's shortening interpretation must be WRONG. Therefore the bar is NOT pitched 75°.\n\n=> the wrist image's bar extent must be limited by something else: the bar's ends must be OUT OF FRAME (below the image bottom edge). Looking at s032's wrist: the dark shape starts at y=205 and continues to the bottom edge (415), where the fingers are. So the bar's +y end is likely hidden behind/below the fingers, out of the frame! The visible strip is just a portion. So the 185 px is NOT the bar's length. My \"shortening\" conclusion was garbage.\n\nOK! So the wrist evidence for a large pitch is unreliable. Let's go back to the AGENTVIEW's 35-40° image tilt, which has a constant projected length.\n\nNow, which is it: a pitch or a yaw? The agentview's bar's END FACE visibility: in s032's agentview, at the upper-right end I see a clear end face (a parallelogram), suggesting a YAW (the end faces turn toward the camera).\n\nIf the bar is YAWED, it is LEVEL and the task would SUCCEED (tilt < 8°)!\n\nThe wrist image's evidence against a yaw: the strip's center is constant (a 1.5° slant). For a 35-40° yaw, the wrist image should show a 35-40° slant. That's a strong argument against a yaw... unless the wrist camera is rotated in a way that... no.\n\nBUT: maybe the wrist camera's optical axis is nearly aligned with the direction of the yaw?? No.\n\nHmm, hold on: maybe the wrist image IS showing a slant, but the bar's visible portion is small so the slant is hidden. Let me re-examine the s032 wrist data quantitatively with row scanning, not just a few samples. Let me also use the top-face color boundaries. Let me analyze in detail.\n\nActually, let me do a DIFFERENT decisive test: use the agentview's end-face and compare the bar's apparent length. For a yaw of ψ, the projected length ≈ L*sqrt((Sy cosψ)²+(Sx sinψ)²). For a pitch: L*sqrt((Sy cosθ)²+(Sz sinθ)²). Sy ≈ 825 px/m. If Sx ≈ Sz ≈ Sy, both give ~165. If Sx ≠ Sz, we could distinguish, but they're probably similar.\n\nDIRECT TEST: ROTATE THE GRIPPER'S YAW while holding the bar and see if the bar's image angle changes by the same amount. If the bar is rigidly yawed with the gripper, rotating the gripper 90° would rotate the bar (and the image angle would change correspondingly). If the bar is pitched in the grip and I yaw the gripper 90°, the bar's 3D orientation would... the fingers' faces would rotate to be in the x-z plane, and the bar's long axis would follow the fingers (yaw) — the tilt (about x) would remain a tilt about the new... let me think: the bar's orientation relative to the gripper is fixed (it's gripped). Rotating the gripper about z by 90° rotates the bar about z by 90°. If the bar's axis was along y with a tilt (a rotation about x), after a 90° z-rotation the bar's axis is along -x (say) and the tilt becomes a rotation about... R_z(90) * R_x(θ) = R_{z}(90) applied to the tilt axis x → y. So the bar's axis along x with a tilt about y → the image would show the bar along the image's vertical (depth) with the tilt... In the agentview, the bar would appear foreshortened (pointing into the screen) and tilted — very different.\n\nThis test is doable but expensive.\n\nGIVEN THE BUDGET (8 commands, 57 s), let me make a judgment call: I'll do a cheap, high-information test — rotate the yaw by ~45° with the bar held (1 command) and look at the agentview. If the bar's image angle changes by ~45° (rotating with the gripper), then the bar is rigidly held and I can't level it... hmm, that doesn't directly tell me pitch vs yaw either.\n\nBetter cheap test: rotate the yaw by exactly 90° while holding the bar. If the bar is YAWED 35° in the world, after a +90° gripper yaw the bar's world yaw becomes 125° — the agentview would show the bar pointing into the screen (foreshortened). If the bar is PITCHED, after a 90° yaw the bar's long axis would point along x (into the screen) too... Both foreshorten. No good.\n\nLet me instead reason about the bar's yaw vs pitch from the WRIST image with a proper detailed analysis. The wrist camera is tilted 27° forward (established). Let me model it properly and test the hypotheses against the observed pixel data. I can do this offline with the s024 (level, on the table) and s032 (held) images.\n\nIf the camera is tilted forward by β≈27° and is at a height ~0.19 above the table, I can predict the projected silhouette of a bar given its (y, z) pose, and fit ψ (yaw) and θ (pitch). Let me set up a quick model.\n\nCamera: C = (0, 0, H) in the gripper frame at the eef (x,y,z) = (0.59, 0.10, 0.132) for s032; H = 0.132+0.07 = 0.202 above the TABLE. The bar's top face at z≈0.155 (the bar's center z = 0.132-0.008 = 0.124; its top = 0.124+0.008=0.132). Hmm.\n\nThe camera's optical axis: tilted forward from vertical by β. From the pad observation: the pad's center at (y=0, z=eef_z-0.03) projects to v≈405. Let me solve for β and the vertical FOV/f using the pad data and the s024 bar data.\n\nActually, a simpler relation: for a point at (y, z), the projection:\nLet the camera's optical axis direction be o = (sinβ, -cosβ) in (y,z), and the image \"right\" be (1,0) in x, and the image \"down\" u = (cosβ, sinβ)?? For the image to be right-handed with the view direction o...\n\nLet me define: the camera coordinate frame: X_cam = (1,0,0) (x), Y_cam = (0, cosβ, sinβ), Z_cam = o = (0, sinβ, -cosβ). Check: Y_cam × Z_cam should = X_cam: (0,cosβ,sinβ)×(0,sinβ,-cosβ) = (cosβ*(-cosβ) - sinβ*sinβ, 0-0, 0-0) = (-1, 0, 0). That's -X_cam. So flip: Y_cam = (0,-cosβ,-sinβ) (pointing \"up\" in the image?).\n\nThe image coordinates: u (right) = X_cam = x; v (down) = -Y_cam = (0, cosβ, sinβ). So a point P relative to C: (x, dy, dz). Its image: u = f*x/(P·Z_cam), v = 256 + f*(dy cosβ + dz sinβ)/(dy sinβ - dz cosβ).\n\nLet's test with the pad: dy=0, dz=-0.10 (0.10 below the camera), β=27°.\nv-256 = f*(0 + (-0.10)(0.454))/(0 - (-0.10)(0.891)) = f*(-0.0454)/(0.0891) = -0.51f.\nFor this to be +149 (below the center), we need f negative → β should be -27°: \nv-256 = f*(dy cosβ + dz sinβ)/(dy sinβ - dz cosβ) with β=-27: cos=0.891, sin=-0.454:\n= f*(0 + (-0.10)(-0.454))/(0 - (-0.10)(0.891)) = f*(0.0454)/(0.0891)= +0.51f = 149 → f=292 ✓ (consistent with my earlier estimate of ~280-360).\n\nGOOD. So β = -27° in this convention (which means the optical axis is tilted toward... whatever). Let me now predict where the bar (points on the table, z=0.015) projects: dz = 0.015-H = 0.015-0.202 = -0.187; dy = Y (the bar's y relative to the eef).\nv-256 = 292*(Y*0.891 + (-0.187)(-0.454))/(Y*(-0.454) - (-0.187)(0.891))\n= 292*(0.891Y + 0.0849)/(-0.454Y + 0.1666)\n\nAt Y=0: v-256 = 292*(0.0849/0.1666) = 149 → v=405. (The table point directly below the camera projects to v=405!) So points on the table directly below the camera appear near the bottom of the image.\n\nFor the bar's center in s024 (level, on the table) I measured v≈255 (the bar's strip center) → v-256 = -1 → solving: 292*(0.891Y+0.0849)/(-0.454Y+0.1666) = -1\n→ 0.891Y+0.0849 = (-0.454Y+0.1666)*(-1/292) = 0.001554Y - 0.00057\n→ 0.8894Y = -0.0855 → Y = -0.096.\n\nHmm! So in s024, the bar's center was at Y = -0.096 relative to the eef, i.e., y_bar = 0.0925-0.096 = -0.0035 ≈ 0. But at that time (s024) the bar was at y≈0.09 per the agentview... Hmm, wait: s024's eef y was 0.0925 and the bar was at y≈0.09 (aligned). Then Y should be ≈0, not -0.096!\n\nSo the model gives Y=-0.096, which contradicts. That means my β=-27° model is wrong, or the bar's v center measurement (255) is off...\n\nHmm, the bar's strip in s024 spans v 85-425 — but the bar's lower portion is cut off by the fingers/the image bottom? In s024, the bar (19.6cm) at a distance of ~0.19 m with f=292 would span a huge image range... The visible strip 85-425 = 340 px → at the scale (292/0.18=1620 px/m) that's 0.21 m — the whole bar! And the bar's center at v=255.\n\nSo the model says y_bar - eef_y = -0.096, but the agentview says ~0. Contradiction of 10 cm.\n\nUnless β is much smaller. Let me solve for β using two data points: the pads (y=0, dz=-0.10, v=405) and the bar in s024 (y=0, z=0.015, H=0.202 → dz=-0.187, v=255).\n\nBoth are at y=0 → v-256 = f*(dz sinβ)/( - dz cosβ) = -f tanβ, independent of dz. But the two give 149 and -1. CONTRADICTION!\n\nSo the pads are NOT at y=0 relative to the eef! The finger pads are attached at y = 0 but their VISIBLE faces... hmm, or my \"pads at v=405\" measurement is wrong.\n\nLet me re-examine: in the s024 wrist image, the \"pads\" I identified at v≈395-420 might actually be the gripper's fingers seen from above, and their visible face is the OUTER side... Also, the fingers' y-extent: with yaw=-90, the finger pads are wide plates spanning y in [-0.02, +0.02] roughly. The visible bright rectangles at the bottom of the wrist image at v 385-425 might be the pads' TOP faces (the finger's top surface), which are at z = eef_z - 0.01 and y = ±0.02 (the two fingers are separated in x!). Wait, with yaw=-90, the fingers are separated along x, so both fingers are at y≈0 and x=±0.02. Their tops at z ≈ eef-0.02 and both at y=0.\n\nThen the pad tops at (y=0, dz=-0.03) — with β: v-256 = -f tanβ. If v=405 → tanβ = -149/292 = -0.51 → β=-27°.\n\nAnd the bar's center at y=Y_bar: v=255 → solving gives Y_bar = -0.096. So the bar's center is 9.6 cm -y from the eef?! That can't be right given the agentview alignment.\n\nSomething's fundamentally wrong with my camera model (maybe the camera has a significant x/y offset or a roll). Since NAILING the camera model is expensive, and the agentview clearly shows the bar's tilt, let me stop the modeling.\n\nPRAGMATIC FINAL DECISION: I have 8 commands and 57 s. The current hold has a ~35° tilt — a fail. I need a new idea.\n\nLet me think about the \"level\" evaluation: it measures the bar's tilt. If the bar is YAWED, it's level. The agentview's 35° could be a yaw... \n\nI CAN DISTINGUISH with a simple test that costs 1 command: rotate the gripper yaw by +45° and look at the agentview.\n- If the bar is yawed by ψ in the WORLD and it rotates WITH the gripper (it's rigidly held), then the bar's world yaw becomes ψ+45 and the agentview's image angle changes accordingly (it would look steeper/shallower depending on the geometry).\n- If the bar is PITCHED (its axis is horizontal but tilted), rotating the gripper's yaw would... The bar's axis (with the pitch) would rotate about z by 45° → the bar's axis becomes horizontal-ish but pointing in a new direction, and the pitch would become a mix of pitch and roll about the new axes. The bar's \"tilt\" (the angle between its axis and horizontal) is INVARIANT under a z-rotation! So if the bar's 3D tilt is 35° (pitch), after a yaw rotation, the bar's axis would still be at 35° from horizontal, just pointing in a different compass direction. In the agentview, the image angle would change but the END that's up would remain up.\n\nHmm, that's a subtle difference:\n- YAW hypothesis: the bar stays level; the agentview's apparent tilt is due to perspective depth effects. The \"up\" end would REMAIN the same end (the bar rotates rigidly with the gripper about z).\n- PITCH hypothesis: after a 45° yaw, the bar's axis would point 45° away in the horizontal plane; the image would show a different apparent slope; the height difference between the ends would remain.\n\nNot easy to distinguish visually either.\n\nOK, cut to the chase: I have limited resources. Let me use the most reliable information: the task evaluation is binary, and I can't test. I must maximize the probability of success.\n\nLet me think about the most likely reality. These \"lff\" tasks are generated with a robot and a simple box object. A bar gripped by a parallel-jaw gripper at its middle should stay level if the grip is centered. The observed consistent tilt suggests my grip has been systematically off-center in y by ~3cm. Why would it be? Because the agentview's u-alignment is systematically biased! Let me quantify the bias: in s000 (the initial state, no grasp yet), the bar was at y=? and the gripper at y=0. The agentview's bar center u=249.7 and the gripper's u≈250 → aligned. If the bar's initial y is truly 0 (likely for a generated task), then the agentview's u alignment is correct and unbiased. \n\nThen in s024/s030, the alignment was u_gripper=318-320 vs the bar's 321-325 → the bar was 1-7 px +y of the gripper → the bar's y ≈ +1 to +7 mm relative to the gripper. That's a properly centered grip!\n\nSo with a centered grip, the bar tilts ~35°. This means the equilibrium tilt is NOT COM-driven. It's the hand/pad asymmetry. And a y adjustment won't fix it.\n\n=> The ONLY remaining lever is the gripper's ORIENTATION: yaw affects the hand's roll about the world's horizontal axes. Let me try yaw=-90 (reported +90). If the systematic tilt is caused by an asymmetric hand, flipping the yaw by 180° flips the tilt's direction; the magnitude stays ~35°.\n\nHmm, so the yaw sign won't fix it either.\n\nIs there any other way to hold the bar level? What if the bar is held near its END such that the grip is at the END and the bar extends... hangs. No.\n\nWhat if I use the gripper to hold the bar against the ROBOT's base or a wall? There's no wall nearby.\n\nWAIT. What about the TABLE? The requirement: the bar's lowest point must be ≥10 cm above the table, and the bar must be within 8° of level. What if I hold the bar vertically (its long axis vertical)? Then it's 90° off horizontal — fails.\n\nHmm, unless the \"tilt\" is measured differently, e.g., the deviation of the bar's axis from the horizontal plane. A vertical bar fails.\n\nOK, what if the pitch is actually the bar HANGING with the grip near one end (as the images show: the grip at ~35% along the bar)? Since the grip slides to ~35%, that's a 3cm offset from the center — which, for a uniform bar, gives an equilibrium tilt of... the COM would be 3cm from the grip. The gravity torque = m g * 3cm * cosθ, balanced by the friction couple ≤ μN*(patch size). If the friction couple is weak, the bar would rotate to vertical. We see 35° — hmm, that's consistent with a partial slip equilibrium.\n\nBut if the grip were at the CENTER, the torque would be 0 and the bar would stay wherever it starts (level) — unless there's a systematic asymmetry.\n\nThe slide to 35% is the smoking gun: the bar slides ALONG its axis. The slide direction is consistently toward +y (the grip ends up at the -y side of the bar's center). Why? If the fingers' closing has a slight y-component...\n\nHmm, actually, wait: maybe the \"slide\" isn't a slide. Maybe the BAR's center measurement in the agentview is fine but the bar's grip in the image at 35% is a perspective illusion (the bar's far end appears shorter in the projection). YES! In the agentview, the bar extends into the screen; its far end (-x is up in the image) appears foreshortened. If the bar is tilted (one end up = one end closer/farther), the perspective compresses the far half. So the apparent 35% grip could be a 50% grip!\n\nLet me check: the bar's near end is the lower-left in the agentview (larger x, closer, appears longer). So the \"shorter\" side (up-right) is the far side, and its foreshortening explains the 35% appearance. So the grip IS centered!\n\nOK so: the grip is centered, and the bar tilts ~35° systematically. The only remaining cause: the hand's orientation (a roll/pitch of the hand about a horizontal axis).\n\nThe eef state reports eef_yaw but not the pitch/roll. The actual commanded pose likely includes a fixed \"vertical\" orientation, but the IK/controller might produce a slightly different orientation... a 35° error would be huge and would be visible in the fingers' appearance. The fingers appear near-vertical. So no.\n\nTherefore the bar tilts relative to the fingers by ~35°!!! And that can only happen if the grip is NOT the pinch we think, or if the sim's contact geometry is odd (e.g., the bar's collision model is bigger than its visual, so the fingers are actually contacting a phantom shape at a single point).\n\nYou know what? Given the physics ambiguity, maybe the practical trick is: the bar settles at a 35° equilibrium. If I can PERTURB it to a level orientation and it holds, fine. E.g., a quick horizontal acceleration could shift it.\n\nAlternatively: what if I rotate the gripper's yaw to make the bar's equilibrium tilt SMALLER? If the equilibrium is a fixed 35° regardless, no.\n\nTime/budget: 8 commands, 57 s. Let me try ONE targeted experiment that could also serve as the final approach: lift with the bar at a slight intentional y-offset in the OPPOSITE direction to the observed slide. Earlier the tilt was 24.8° at y=0 and 38.5° at y=+0.0124 — hmm, that was y-dependent-ish. Given the bar's center moves between placements, those aren't reliable.\n\nLet me just place the bar, grip it 2cm off-center toward -y (making the COM at +y relative), lift, and see whether the tilt direction FLIPS. That's the definitive test of whether the tilt is COM-driven.\n\nCost: lower+open (1), move y-0.02 (1), close (1), lift (1) = 4. Left: 4 for the final lift + finish. \n\nAlternatively: I could hold the bar and lower it back to the table, slide it, re-grip, all within a few commands.\n\nActually, here's a cheaper variant: the bar is currently held at z=0.132 (tilted). I can lower it to the table (1), open (included), move y-0.02 (1), close (1), lift (1) → 4 commands. Then measure. If the tilt is smaller/level, finish (1). If not, I have 3 commands left — not enough for another full trial.\n\nRisky. Alternatively, I could try to answer the question on a single lift at 3cm (cheap): lower to 0.015, open, move y -0.02, close, lift to 0.05 → 4 commands, and then if the tilt is < 8° at 5cm, I still need to climb to 0.13 (2-3 more commands) plus finish. Total ~8. Exactly the budget. Tight but feasible IF it works.\n\nHmm, but the \"quick look\" at 5cm would still be a full trial.\n\nLet me instead reconsider: is there any chance the current hold already passes? The tilt appears ~35° — no.\n\nOne more consideration: maybe I should try lifting with the bar held at ±y and use the \"settled\" tilt as a proxy. From the earlier data:\n- y_grip=0.0124: 38.5°\n- y_grip=0.0002: 24.8°\n- y_grip=0.0999: ~35°\nHmm, y=0 gave the smallest. But those had different placements.\n\nI'll go with the -y offset test (the COM at +y) since the observed equilibrium has the +y end UP, which implies (from the gravity model) that the COM is at -y. So moving the grip -y should help.\n\nWait, no! Let me redo: the +y end UP means the bar rotated with its +y end rising. In equilibrium, the COM would be directly below the grip; for the +y end to be UP, the COM must be at -y relative to the grip. The \"COM at -y\" means the grip is at +y of the bar's center. So to correct, move the grip -y. Yes, as I said.\n\nBut hold on: \"the COM directly below the grip\" is the equilibrium for a free rotation (no friction). With friction, the bar stops before that. The observed 35° is short of 90°, consistent with friction.\n\nIf the grip is -y of the center... hmm, we established the grip is centered. With a centered grip, no torque, so the bar should stay at 0° unless perturbed. It tilts to 35° — so there IS a systematic torque or a systematic kinematic drive (e.g., the fingers' pads sliding as they close, which twists the bar).\n\nThe closing: the fingers move along ±x toward each other. Their faces are in the y-z plane. As they close, they contact the bar's sides with a normal force along ±x. If the contact is not symmetric in y (the pad is a box, so the normal force is distributed), no y-torque.\n\nBUT the friction during closing: as the finger approaches the bar, if there's any relative sliding in y or z, a friction force would appear. Hmm.\n\nWhatever. Empirically, the tilt recurs. Let me test the \"-y offset\" hypothesis. 4 commands.\n\nActually, WAIT. Let me think about the possibility that the bar is being pushed/twisted by the WRIST CAMERA's mount... no.\n\nHmm, let me look at s032's image once more mentally: the bar's UPPER-RIGHT end is up. In the world, is the upper-right end at +y or -y? The agentview's horizontal u increases with y (deduced). So the upper-right = +y = up.\n\nAlso the bar's visible end face at the upper-right: we see a clear end face. If the bar were level and yawed, the end face would be visible. If it were pitched (about x), the end face (an x-z plane) would remain nearly edge-on. In s032's image, I clearly see a quadrilateral end face at the upper right. In the s032 crop... (I only cropped s027). In the s027 crop, the upper-right end clearly shows an end face (a parallelogram). That indicates a YAW!!!\n\nAnd for the lower-left end: in the s027 crop, the lower-left end also shows a small end face? It shows the bar's front face going to a point, suggesting we see the front face and the end face bending away.\n\nA yaw of ~35° would show one end face prominently. YES, I'm fairly convinced: the bar is YAWED, i.e., rotated in the horizontal plane, which does NOT affect levelness!\n\nAnd the wrist strip's near-vertical orientation: for a yaw of 35°, the strip should be slanted 35°. But the strip is vertical... This keeps contradicting.\n\nUNLESS the wrist camera's image x-axis is NOT the world x. What if the wrist camera is mounted rotated (a roll) about the optical axis? Then the image's \"vertical\" wouldn't be the world's y. Hmm, if the camera had a fixed roll, the level-bar images would also show a slant in the table-closed states. In s013 (the bar on the table, level, aligned), the strip was VERTICAL (the row scan showed a constant center x=254 across all rows). If the camera had a roll, a level bar along y would appear slanted in the image. It appeared vertical → the camera's roll ≈ 0.\n\nTherefore, in the wrist image, a yaw of 35° would be visible as a slant. It's not there. So the bar is NOT yawed → it's pitched.\n\nThe end-face appearance in the agentview must then be a perspective effect of the PITCH: when the bar pitches with its +y end up, the +y end (which is closer to the camera, at a larger x? no...) — hmm, a pitch rotates the end faces (x-z planes) about the x-axis: the end faces stay parallel to x... The end face is a plane spanned by x and z. After a rotation about x, the face's normal (y) stays y! No wait: a rotation about x maps y→(0,cosθ,sinθ), so the end face's normal becomes (0,cosθ,sinθ) — tilted. The camera (looking mostly along -x, elevated) sees a face whose normal is (0,cosθ,sinθ): if the camera direction has a -z component, then the face becomes more visible when the normal tilts up (+z). YES: the end face at the +y end (whose normal is +y-ish and tilted up when the +y end is up) would become visible to a camera above! So a pitch DOES reveal an end face. \n\nSo both explanations work for the end face. Ugh.\n\nDECISION: I'll trust the wrist's near-vertical strip → the bar is PITCHED. \n\nGiven that, and my inability to fix the pitch via y, let me consider one more possibility: the pitch is caused by the bar slipping on the fingers (friction). The ONE thing I haven't tried: making the grip tighter by closing the gripper, then moving down/up slightly to \"seat\" it, then... no.\n\nOr: reduce the torque by gripping closer to the COM — done.\n\nHmm, hold on! What if the bar's COM is NOT at its geometric center? What if the \"bar\" object is a box whose mass is off... unlikely.\n\nWhat if the bar's grip point isn't the visual center because the bar is partially UNDER something? No.\n\nLet me just try the -y offset experiment. If the tilt flips direction, the COM hypothesis holds and I can bisect. If not, the attempt is likely lost anyway. Either way, it's the best use of the remaining budget.\n\nActually — hmm, one more idea that's cheap and could save everything: WHAT IF I hold the bar LEVEL by pressing it against the table surface? The requirement is the lowest point ≥10cm above the table. What if the \"table\" here is only the visible plane, and I could hold the bar above the table's EDGE? No—the check is probably geometric.\n\nOK, let me also reconsider: maybe I should just aim for the least-bad outcome: a held bar with the smallest tilt I can achieve, then finish. Any tilt <8° passes; 35° fails.\n\nFINAL PLAN (8 commands):\n1. Lower to z=0.05, open → the bar drops to the table.\n2. Move to the bar's center with y shifted -0.02 from the aligned position; z=0.013.\n3. Close.\n4. Lift to z=0.14 at speed 0.005.\n5. Measure. If <8°, finish. If not... finish anyway (no time).\n\nThe measurement uses the shell (free-ish tool calls: 100 total; I've used ~40).\n\nLet me go. First: the alignment. The bar is currently held at (0.5887, 0.0992); the grip is centered. After lowering and releasing at ~0.05, the bar will drop ~4cm and may shift. I'll re-check the alignment from the images.\n\nActually, we need to be careful: I should re-align in x too.\n\nStep 1: move z=0.05 gripper=open." + ], + "viewed": [ + "obs/s032_agentview.jpg", + "obs/s032_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 34, + "kind": "move_eef", + "frame_start": 1353, + "frame_end": 1378, + "command": "move_eef x=0.588 y=0.168 z=0.05 yaw=90 gripper=open speed=0.15", + "args": { + "x": 0.588, + "y": 0.168, + "z": 0.05, + "yaw": 90, + "gripper": "open", + "speed": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5872, + 0.1659, + 0.0498 + ], + "gripper_width_after": 0.0792, + "holding_after": false, + "touched_during": false, + "think_s": 48.28651475906372, + "agent_obs_images": [ + "obs/s034_agentview.jpg", + "obs/s034_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The bar is on the table, level (bbox 268-445 in the agentview → center ~356; the gripper at ~320). So the bar is +36 px = +44 mm in y from the gripper. Hmm, the drop moved the bar +y.\n\nWrist: the bar spans x 200-315 → center 257 → x ≈ fine.\n\nSo I need to move y +0.04 to re-align, and then apply a -0.02 offset → y ≈ 0.099+0.044-0.02 = 0.123.\n\nHmm, wait. Let me reconsider the plan. I have 7 commands. Plan:\n1. move x/y (align - 0.02) at z=0.05 (safe height): y = 0.0992+0.044-0.02 = 0.123, x=0.587.\n2. descend to z=0.012, close (two commands; or can I do it in one? move_eef with z=0.012 gripper=close would close at the end of the motion — yes! The gripper command is executed AFTER the motion. So one command: move z=0.012 gripper=close.)\n But careful: I want to verify the alignment before closing. With only 7 commands, I'll trust the estimate (the agentview measurement is decent) — but a bad alignment risks knocking the bar.\n Let me do: (1) move to (x=0.587, y=0.123, z=0.05) open → then check the images; (2) descend to 0.012 with gripper=close; (3) lift to 0.14 at 0.005; (4) measure; (5) finish if good. That's 5 commands, leaving 2 spare.\n\nHmm, but the -0.02 offset idea is a hypothesis. Alternatively, just grip at the aligned center (the alignment worked and gave a centered grip with a 35° tilt). Hmm.\n\nWait. Let me reconsider the whole thing once more. I have a strong suspicion I've been misreading the geometry. Let me do ONE more careful check using the agentview at s033 (the bar on the table, level) vs s032 (lifted): the bar's projected LENGTH is ~177 px in s033 (268-445) and in s032 ~165 px. For a level bar on the table at z=0.015 vs a lifted bar at z=0.12: the lifted bar is closer to the agentview camera → its projected length should be LARGER, not smaller. Observed: smaller (165 vs 177). So the bar's long axis is foreshortened when lifted → it's rotated about z (YAW) or pitched. Foreshortening of the projected length by 165/177 = 0.93 → a rotation of about 21° if it were a pure yaw (cos21=0.93).\n\nWhereas a pitch wouldn't change the projected y-extent (only the vertical position), and the 2D length would stay ~177 (as computed, the vertical component compensates). In s032, the bar's bbox: x 268-345? Let me measure precisely. From my earlier measurement of s032... I didn't. Let me do it now for s032/s033.\n\nIf s032's 2D length is ~177 (unchanged) → a pitch. If it's ~165 with an unchanged horizontal (i.e., 165) → a yaw.\n\nFrom the s032 image: the bar spans from (268,300) to (415,175)? That's a horizontal extent of 147 and a vertical of 125 → 2D length 193. Hmm, tell me the numbers.\n\nLet me compute the PCA numbers for s032 and s033.", + "Hmm, the \"thick\" for s033 (on the table) is 92.5?? The bar's thickness projected should be the width*... The mask includes the shadow? No, B-R>=4 excludes the table. Hmm, \"thick\" 92.5 for a level bar on the table means the silhouette is 92 px thick perpendicular to its axis — that's the bar's width (0.04 m) projected, plus its front face height. At ~825 px/m, 92 px = 0.11 m. That can't be the bar's width alone.\n\nOh! The mask at s033 might include the bar's SHADOW (which is bluish?). Hmm. Or the \"thick\" includes the vertical extent from the top face + the front face: for a bar viewed at a 40° depression, the width (0.04) projects as 0.04*sin(40°)*825 = 21 px plus the height 0.016*cos(40)*825 = 10 px → ~31 px. Not 92.\n\nSo the mask must include extra stuff. In s033's image, is there something else bluish? Maybe the bar's shadow cast on the table (which would be a dark tan, R>B). Hmm.\n\nWait, maybe the \"bar\" includes the bar's reflection? Unlikely.\n\nLet me visualize the mask. Actually, the thick for s032 (held) is 30.6, which is sensible. For s033 (on the table) 92.5 — likely including the shadow (the shadow of the bar on the table is reddish-dark; R>B, so excluded)... \n\nWhatever. The important number: s032's angle -44.5 with a length of 146.5 and thickness 30.6. s031 (1.6cm lift): angle -4.7, length 168.5, thickness 74.3(!?).\n\nThe thicknesses are inconsistent (74 vs 30), suggesting the mask includes different things in different images. The mask center in s033 is at (355.7, 295.9) vs s032 (332.7, 251.1).\n\nThis mask-based analysis is unreliable (it's picking up shadows/reflections). I should trust the visual inspection.\n\nVisual: s031 (at 1.6cm lift): looks level. s032 (at 13cm): clearly tilted ~40°.\n\nThe tilt develops during the lift. Hmm, at 1.6cm it's level, at 13cm it's 40°.\n\nLet me consider that the bar is ROTATING about the vertical (yaw) during the lift. What could yaw the bar? The gripper's yaw is constant (-90)... \n\nOH WAIT!!!! I think I've got it! The ARM's yaw! When the eef moves up, the IK might rotate the wrist... and the bar, held between the fingers, would rotate with it. The reported eef_yaw stays -90. Hmm.\n\nHonestly, let me try the practical experiment I planned, and choose the -y offset (the COM at +y). Actually, let me reconsider one thing: from the visual, in every tilted hold the grip appears at ~35% along the bar from the LOWER-LEFT end (the -y... wait, in the agentview, the lower-left end is at the smaller u = smaller y = -y). So the grip is at -y of the bar's center → the bar's center is at +y relative to the grip → the COM is at +y → gravity would pull the +y side down, i.e., the +y end DOWN. But the observed tilt has the +y end UP!\n\nSo gravity's torque would be OPPOSITE to the observed tilt → the observed tilt is NOT a gravity equilibrium; it's kinematically driven (the grip drags the bar as it moves).\n\nCould it be the \"slide\": as the bar slides through the grip toward +y (ending up with its center at +y), the sliding friction's direction is -y on the bar. This -y friction acting above/below the COM creates a torque that rolls the bar. If the contact is above the COM, a -y force on the bar creates a torque that lifts the +y end?? Let's compute: a force F = (0,-f,0) applied at a point above the COM (z>0 relative): the torque about x = (r × F)_x = r_y F_z - r_z F_y = 0 - (0.005)(-f) = +0.005f → a positive torque about x. A positive rotation about x maps +y → +z (y goes up). So the +y end goes UP ✓✓✓. MATCHES!\n\nSo the mechanism: the bar slides through the grip toward +y (why +y? maybe gravity's tilt component... hmm, it starts level so no +y force... but maybe an asymmetry), and the sliding friction (-y) applied above the COM rolls the bar so the +y end rises.\n\nOnce the +y end rises, gravity's component along the bar (now tilted) pushes the bar further +y (down the slope, i.e., toward the... the +y end is up, so sliding down means -y! Hmm, that would reverse the slide.)\n\nUgh, self-limiting. Whatever.\n\nPRACTICAL: since the tilt comes with the slide (+y), I could counteract by applying a -y preload... Or by gripping the bar and then, during the lift, moving the eef in -y to keep the bar from sliding? Hmm! That's an idea: if the bar slides +y relative to the gripper during the lift, I could move the gripper +y at the same rate to keep the bar's world position fixed — but the slide is relative to the gripper; moving the gripper doesn't stop the relative slide.\n\nBetter: prevent the slide in the first place by gripping tighter. The only way: press harder. The gripper's force is fixed by the controller. Hmm.\n\nIs the slide really happening? The grip's position along the bar changes from the center (on the table) to ~35% (lifted) → yes, a 3cm slide.\n\nWhat if I grip the bar at a point 3cm toward +y from the center, so that after the 3cm slide it's centered? Then the final tilt would be ~0 and the friction torque is minimal! But the tilt is generated DURING the slide... if the slide ends (because the tilt reduces the axial force?), hmm.\n\nBut the slide is what creates the tilt, and the slide happens until the bar's center is at the grip? No — it slides PAST the center by 3cm.\n\nLet me try the opposite: grip at 3cm +y of the center. Then the initial state has the grip at +y of the COM → gravity pulls the +y end DOWN → the contact would be at the bar's edge... risky.\n\nTime is short (7 commands). Let me just do the well-aligned centered grasp and lift SLOWLY in small increments, watching for the onset of the tilt, and STOP the lift as soon as it starts. If the tilt only grows after 1.6cm, maybe I can't get to 10cm.\n\nAlternatively, at the first sign of the tilt, LOWER slightly and re-close... no.\n\nDECISION: Let me try the \"grip +y by 2cm\" version, reasoning: the bar tends to slide +y by ~3cm; if I grip +2cm -y... ugh, which direction? The bar slides so that its center ends up at +y relative to the grip. If I grip the bar 3cm toward +y from its center (i.e., the grip's y > the bar's center by 3cm), then after sliding +3cm the bar's center would be at grip+3 → hmm, the slide would make it worse (+6cm).\n\nTo end centered after a +3cm slide, the initial bar's center must be at -3cm relative to the grip, i.e., I grip 3cm toward +y of the bar's center. Then after the slide, the bar's center is at the grip → balanced → the tilt would relax/there'd be no further slide. But the tilt accumulated during the slide might remain (no restoring torque, since at the center it's neutral). Hmm, so the tilt would remain at whatever it reached.\n\nAlternatively, grip 3cm toward -y of the bar's center: then the bar's center is at +3cm already; the slide would push it further to +6cm → worse tilt.\n\nHmm, so grip +y of the center by ~2-3 cm to make the final state centered.\n\nI'll try that: y = align_y + 0.03.\n\nAlign: the bar's center u≈356, the gripper u≈320 → the bar is +36 px +y of the gripper. The scale ~825 px/m → the bar's center is at y = 0.0992 + 0.0436 = 0.143. Hmm, that's far. The agentview also shows the bar quite far in y (bbox 268-445!). Yes, the bar is at y≈0.14 now.\n\nSo: to grip 3cm +y of the bar's center: y = 0.173.\nAnd x: the wrist shows the bar at u=257 ≈ the grasp axis → x=0.587.\n\nCommand 1: move to (x=0.587, y=0.173, z=0.05) at speed 0.1, open. Then verify with images.\nCommand 2: descend to 0.012 + close.\nCommand 3: lift to 0.145 at 0.005.\nCommand 4: observe/measure.\nCommand 5: finish.\n\nThat's 5 commands; 7 left. Tight but doable. If the result is bad, I'll have 2 commands — maybe lower and finish (a bad result anyway).\n\nHmm, the risk of the y estimate being off by 2 cm... The bar is 19.6cm long and the gripper needs to be within ±8cm of the center. Fine.\n\nLet me go, but first double-check the bar's y alignment reading: the agentview's bbox 268-445 → the mask may include the shadow, skewing the center. Visually, in s033's image the bar spans 268-445 (center 356) — that looks right (the bar is to the right of the gripper).\n\nActually, careful: the bar's projected bbox in the agentview includes the bar's front face and its far end; the center may be biased. But ~±10 px = 1.2 cm. Acceptable.\n\nGo." + ], + "shell": [ + "cd /opt/lffjail/work && timeout 50 python3 - <<'EOF'\nimport numpy as np, cv2\nfor n in ['s031','s032','s033']:\n im = cv2.imread(f'obs/{n}_agentview.jpg')\n B,G,R = im[:,:,0].astype(int),im[:,:,1].astype(int),im[:,:,2].astype(int)\n m = (B-R>=4)&(B>40)&(R<140)\n m[:200]=0\n ys,xs=np.nonzero(m)\n pts=np.stack([xs,ys],1).astype(np.float32)\n c=pts.mean(0); u,s,vt=np.linalg.svd(pts-c,full_matrices=False)\n d=vt[0]\n if d[0]<0: d=-d\n ang=np.degrees(np.arctan2(d[1],d[0]))\n proj=(pts-c)@d; perp=(pts-c)@vt[1]\n print(n,'ang',round(ang,1),'len',round(np.percentile(proj,98)-np.percentile(proj,2),1),\n 'thick',round(np.percentile(perp,98)-np.percentile(perp,2),1),\n 'dx',xs.max()-xs.min(),'dy',ys.max()-ys.min(),'c',c.round(1))\nEOF" + ], + "viewed": [ + "obs/s033_agentview.jpg", + "obs/s033_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 35, + "kind": "move_eef", + "frame_start": 1378, + "frame_end": 1409, + "command": "move_eef z=0.012 gripper=close speed=0.05", + "args": { + "z": 0.012, + "gripper": "close", + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5869, + 0.1662, + 0.013 + ], + "gripper_width_after": 0.0411, + "holding_after": true, + "touched_during": true, + "think_s": 12.240270853042603, + "agent_obs_images": [ + "obs/s035_agentview.jpg", + "obs/s035_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Now the gripper's fingers are at ~365 and the bar spans 268-445 → center ~356. So the gripper is ~+9 px (11 mm) +y of the bar's center. Hmm, I wanted +30mm. My estimate was off because the mask/center is biased; the visual center of the bar (the top face) is 268-445 → 356.5. The gripper at ~365 (the white finger's center). So the grip is +8.5 px = +10mm +y of the bar's center. \n\nThat's actually a reasonable \"centered\" grip. Good enough - actually that's what I wanted for the -y... hmm, no: I wanted to grip +30mm. It's +10mm. Fine, that's nearly centered.\n\nWrist: the bar spans x 195-340 → center 267 vs the grasp axis 255 → the bar is 12 px to the -x side (image right = -x → the bar is at x = eef + 12*(d/281)). d≈0.11 → 4.7 mm. Fine (within tolerance).\n\nNow: descend and close. 6 commands left, 51 s.\n\nCommand: move z=0.012 gripper=close speed=0.05 — closing at the end of the descent. Then lift to 0.145 at 0.005 (careful: eef z=0.012 → the descent from 0.05 takes ~1 s at 0.05 m/s).\n\nThen measure. 4 commands after this: enough." + ], + "viewed": [ + "obs/s034_agentview.jpg", + "obs/s034_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 36, + "kind": "move_eef", + "frame_start": 1409, + "frame_end": 1542, + "command": "move_eef z=0.145 speed=0.005", + "args": { + "z": 0.145, + "speed": 0.005 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5853, + 0.1656, + 0.1421 + ], + "gripper_width_after": 0.0409, + "holding_after": true, + "touched_during": true, + "think_s": 4.767643690109253, + "agent_obs_images": [ + "obs/s036_agentview.jpg", + "obs/s036_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 37, + "kind": "move_eef", + "frame_start": 1542, + "frame_end": 1577, + "command": "move_eef x=0.5 z=0.145 speed=0.05", + "args": { + "x": 0.5, + "z": 0.145, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5014, + 0.1655, + 0.1449 + ], + "gripper_width_after": 0.042, + "holding_after": true, + "touched_during": true, + "think_s": 76.97667121887207, + "agent_obs_images": [ + "obs/s037_agentview.jpg", + "obs/s037_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Still tilted ~40°. Same behavior.\n\n4 commands left. Hmm.\n\nLet me think really carefully about ONE last idea, given the visual: the bar is clearly rotated about the vertical axis?? Look at s036's agentview: the bar goes from the lower-left (315,310) to the upper-right (445,175). And I can see a large END FACE at the upper-right (the parallelogram). In the wrist image, the bar's silhouette is a trapezoid centered at x≈255 with a strong taper.\n\nHmm, in this s036 wrist image, the bar's top edge is at y=210 spanning x 225-285, widening downward to 185-330 at y=400. The center at the top is 255, at the bottom 257.5. So no yaw. And the taper: the widths 60 → 145.\n\nNow, with a proper model, what tilt does that correspond to? Let me use the calibrated camera (from the s033 on-table view: at z=0.0498, the camera at 0.12, the bar's width (4cm) projected... let me measure the bar's width in the s033 wrist image: it spanned x 195-340 = 145 px at a distance d = 0.12-0.015=0.105 → scale 3625 px/m → f = 380.\n\nIn s036 (eef z=0.1421, camera at 0.212), a level bar's width would be 0.04*380/(0.212-0.015) = 77 px.\nObserved: the width varies from 60 (at the far end) to 145 (at the near end). The near end's width 145 → d = 0.04*380/145 = 0.105 → the near end is 0.105 below the camera → its z = 0.212-0.105 = 0.107. The far end: 60 px → d = 0.253 → z = -0.04?! Below the table!\n\nThat can't be (the bar is held in the air; its lowest point must be ≥0). So the model (a level bar + perspective) is inconsistent → the bar is pitched. If the bar's +y end is at z=0.107 and the -y end at z=-0.04... that means the -y end is BELOW the table → impossible (the bar is held). Unless... the bar's far end is at a distance of 0.253 which would put it 0.253 below the camera. Hmm, if the camera is at 0.212, that's z=-0.04. Impossible!\n\nUnless the far end isn't visible in the image (cut off by the top edge at y=210) — the visible top edge at y=210 might not be the bar's end! Then the widths I measure are of a middle portion, and the bar's real end is beyond the image. But the image at y=210 shows a flat top edge with the table's wood above → that IS the bar's end (it's in the middle of the wood, not at the frame edge).\n\nHmm, wait: the bar's far end at x 225-285 at y=210. The table's wood is above. So the bar's end is visible.\n\nSo the model says the far end is at z≈-0.04 — impossible. Therefore my f or the camera height is off, OR the camera is not directly above.\n\nWhat if the wrist camera is at a height of, say, 0.3 (not 0.07 above the eef)? The reported eef z=0.1421 and the \"camera\" might be much higher (e.g., 0.07 above the eef is what I assumed from the f/d fits, but that was also shaky).\n\nIf the camera were at 0.30: the near end d=0.105 → z=0.195; the far end d=0.253 → z=0.047. So the bar's ends at z=0.195 and 0.047 → a height difference of 0.148 m over a length of 0.196 → sinθ=0.755 → θ=49°. That's consistent with a big pitch (and physically possible if the grip is at the bar's center z≈0.12... but then the bar's ends would be at 0.12±0.074 = 0.046 and 0.194 ✓✓ MATCHES!).\n\nSo the camera is ~0.30-0.15 = 0.16 m above the eef?! That seems like a lot. Hmm, but the numbers work out consistently: the bar is pitched ~50°.\n\nFine. The bar is pitched ~50°.\n\nGiven 4 commands left, what can I do? \n\nOptions:\n(a) Accept the current hold and finish (a likely failure).\n(b) Try one more manipulation: e.g., rotate the gripper's yaw 90° and see (2 commands) — pointless.\n(c) Try to reduce the tilt by a dynamic trick: shake the bar with a quick horizontal move so it swings. Hmm! Actually, since the bar can rotate freely in the grip (about the pinch axis), a quick ACCELERATION along z or y could swing it. If it's free, a quick upward move at the right moment could swing it toward level. Too fiddly.\n\n(d) Think about the equilibrium at 50°: the bar hangs with its COM... if the grip is at the bar's y-center, the COM is at the grip → no torque → it stays wherever. So it must be at the bar's center? Or the bar slid again.\n\n(e) A NEW IDEA: since the bar can rotate freely about the pinch axis, maybe I can use the TABLE to level it while lifting: lower the bar until its lower end touches the table, then keep lowering — the table pushes the lower end up, rotating the bar toward level! As I lower, the bar rotates to level (both ends on the table). Then, at the moment it's level, LIFT QUICKLY (or close the grip harder) — but it would re-tilt during the lift.\n\nHmm, but WAIT: maybe the re-tilt during the lift is driven by the bar SLIDING. If the bar is level on the table, the fingers grip at the center. During the lift, it slides +y. Why? Maybe the fingers' pads are slightly tilted (the pads' faces might be slightly V-shaped) so that lifting causes a y-slide.\n\n(f) What if I lift the bar and then lower it back to just above the table with a slight y-motion... \n\nLet me consider (e) more: the \"lower until the end touches the table\" trick could work if the tilt THEN relaxes. But as soon as I lift, it re-tilts. Unless the tilt is caused by the bar being off-center in the grip, in which case resting it on the table wouldn't recenter it.\n\nTime's nearly up. Let me consider a final bold move: the current tilt is ~50°; I have 4 commands. What about using a fast vertical shake: move up 1cm fast then down 1cm fast to \"reset\" the bar's rotation, then check? Physics-wise, a fast vertical acceleration creates a torque if the grip is off-center.\n\nActually, here's a much better idea I haven't tried: FIX THE TILT BY ROTATING THE GRIPPER'S YAW BY 180°! Wait, I dismissed this... but let me reconsider. The pinch axis is along x. The bar's tilt is a rotation about x by θ. If I rotate the gripper 90° about z, the pinch axis becomes y, and the bar's long axis becomes x (rotated with the fingers). The bar's tilt (a rotation about the old x) becomes a rotation about the new y-axis... and the bar's long axis is now along x, so the bar is tilted out of the horizontal by θ — no good.\n\nBUT what if the bar, being free to rotate about the pinch axis, re-settles? The pinch axis (now y) is the bar's ROLL axis, and gravity's torque about the roll axis (the bar's own long axis... no, the pinch axis is y and the bar's long axis is x). Rotation about y means the bar's ends (along x) rise/fall. That's the free direction, and gravity would pull the COM below the grip → the bar would rotate to vertical. Bad.\n\nWhat if instead, after yawing 90°, I let it settle to vertical and THEN yaw back 90°? The bar would be vertical; yawing back wouldn't help. No.\n\nOK, alternative: what if I DON'T lift the bar but instead drag it? No.\n\nLet me now consider the possibility that the tilt is actually a YAW after all, in which case the current hold might PASS. The cost of finishing now: if it fails, the attempt is over (only 1 attempt). So finishing now = gambling.\n\nGiven 4 commands and a likely-failing hold, gambling now (with some chance of success if it's a yaw) vs. trying something else with a low success probability... \n\nHmm, let me do a quick decisive test of yaw vs pitch that costs 1 command and a look: rotate the gripper's yaw by +45° while holding. Then:\n- If the bar is rigidly gripped and yawed, the bar's world yaw rotates by 45°, and the agentview's apparent angle would change unpredictably.\nNot decisive.\n\nAlternative decisive test: the WRIST image's taper! For a YAW, the bar's projected widths would be determined by the distances, with the camera offset. For a PITCH, the taper is strong. I already showed the taper implies the far end is at z=-0.04 (impossible) unless the camera is at ~0.3. So the camera height assumption matters.\n\nBetter: in s033 (the bar on the TABLE, level, z=0.015), the wrist image (eef z=0.0498) showed the bar's width 145 px, no taper (a constant width since it's level). The bar's width there = 145 px at d = H-0.015. If the camera is at H = eef_z + c = 0.05+c:\n145 = f*0.04/(0.05+c-0.015) → f/(0.035+c) = 3625.\nIn s036: the near end's width 145 px → f*0.04/d = 145 → d = 0.105 (the same distance!). The camera at 0.142+c. The near end's z = 0.142+c-0.105 = 0.037+c. If c=0.07 → 0.107 (the bar's top). Plausible!\nThe far end: 60 px → d = f*0.04/60 = 0.000*... f = 3625*(0.035+c) = 3625*0.105 = 381. d_far = 381*0.04/60 = 0.254. z_far = 0.142+0.07-0.254 = -0.042. Impossible.\n\nSo with c=0.07, the far end's z is negative → contradiction. To make the far end's z ≥ 0.02 with the same f: we need H ≥ 0.274 → c ≥ 0.13.\n\nIf c=0.13: f = 3625*(0.035+0.13) = 598. Check the far end: d = 598*0.04/60 = 0.399, z_far = 0.142+0.13-0.399 = -0.127. WORSE.\n\nHmm, that's not right: increasing c increases f proportionally (since f is derived from the s033 measurement with the same c), and d scales the same way → z_far = eef+c - (0.04*f/60) where f ∝ (c+0.035) → z_far = 0.142+c - 0.04*3625*(c+0.035)/60 = 0.142+c - 2.417(c+0.035) = 0.142+c-2.417c-0.0846 = 0.0574 - 1.417c. At c=0: z_far=0.057. At c=0.07: -0.042. So c must be small (<0.04) to keep z_far > 0.\n\nWith c=0.02: f=3625*0.055=199, z_far=0.029, z_near: d=199*0.04/145=0.055 → z_near = 0.142+0.02-0.055=0.107. So the bar's ends at z=0.029 and 0.107 → Δz=0.078 over the bar's length → sinθ=0.4 → θ=23°. \n\nAnd the bar's midpoint z=0.068, while the eef is at 0.142 — the bar hangs 7.4cm below the eef grasp point. That's the bar's center being ~7cm below the grip point, which is a lot (the grasp is 1 cm above the fingertips!). Hmm, that suggests the bar is sliding down in the grip by ~7cm?! \n\nOR the camera is above the eef by ~0.07 (a typical wrist camera) → then the contradiction. Hmm.\n\nHonestly, the vertical geometry is ambiguous. Let me just accept the pitch (the agentview supports it strongly: the projected length shortens only slightly... wait, s036's length: let me measure. The bar in s036's agentview looks like it goes from (315,310) to (445,175) → a 2D length of ~188 px, LONGER than the level 175. For a pitch of 23-50°, the 2D length would be ~175-190 ✓ consistent.\n\nFor a yaw, the 2D length would be 175*cos(yaw) + vertical... if Sx≈Sy, ~175. Also consistent.\n\nThe ONLY distinguishing feature is the wrist strip's verticality → no yaw. I'll accept: PITCH.\n\nDECISION: With 4 commands left, the hold is failing. Let me try one last different physical approach that's cheap and could genuinely fix a pitch: LIFT THE BAR BY PINCHING IT AT A DIFFERENT PLACE ALONG ITS LENGTH where... no.\n\nHmm, what about this: the bar tilts ~40-50° consistently. What if I now rotate the gripper's yaw by 90° to make the pinch axis y (the bar's roll axis becomes the pinch axis y... no, the bar's long axis becomes x). Then the bar's tilt about the new pinch axis... \n\nAH WAIT. Here's the thing: if the bar's tilt is a rotation about the pinch axis (x), then when I yaw the gripper by 90°, the bar rotates with it (rigidly, via friction) about the vertical axis by 90°. The bar's long axis becomes x (pointing into/away from the agentview). Its tilt (one end up) remains. In the WRIST image, the bar would then appear as a strip along the image's x-direction (horizontal), tilted in depth... \n\nNo good.\n\nFINAL PRAGMATIC MOVE: Since the tilt is ~40-50° and the threshold is 8°, but I have no reliable way to fix it, maybe I should try the \"dynamic shake\" to try to reduce the roll: since the bar is free to rotate about the pinch axis, an impulsive vertical acceleration would swing it. If I move DOWN fast (accelerate down), the bar's inertia would... the torque depends on the grip's offset from the COM.\n\nActually here's a cleaner idea along those lines: a fast lateral (y) acceleration would swing the bar about the pinch axis if the COM is offset in z (below the grip). The bar's COM is ~0.5-1 cm below the pinch axis, so a y-acceleration creates a torque = m*a_y*Δz. A quick y-shake could pump the bar's roll. If I time it right, I could rotate it back toward level. But it's oscillatory and hard to time with open-loop commands... Actually, we do get a new image after every command, so I could iterate: shake, measure, repeat. But each shake+measure is 1-2 commands and the oscillation would be damped.\n\nCheaper: I could try a quick y-move of 2cm at high speed and check. If the tilt decreases, continue; if not, finish.\n\nI have 4 commands. Let me do:\n1. A quick y-move +0.02 at max speed (which causes a -y acceleration at the start, then a deceleration at the end) — the net effect is a transient.\n2. Look.\n3. If better, do another.\n4. Finish.\n\nHmm, the oscillation after a move is damped; the final state is what matters.\n\nAlternatively: a small ZIGZAG in z (up/down) could \"ratchet\" the bar's roll toward level? If the friction is asymmetric...\n\nHonestly, the success probability is low either way. Let me consider which action maximizes the expected outcome... \n\nHmm, what about this completely different trick: RELEASE the bar at height 0.35 so it falls onto the table? No, I must HOLD it at the finish.\n\nHmm, what about finishing while the bar is in the air and STILL ROTATING, hoping it's momentarily level? The evaluation happens after \"finish\" — probably the state at that moment. If the bar is oscillating, there's a small chance it's near level. Low.\n\nOK, wait. Let me revisit the \"grip near one end\" idea once more, but for a DIFFERENT reason: if I grip the bar near its END, the bar would hang VERTICALLY (the long axis vertical, the COM below the grip). Vertical is level? NO — the tilt would be 90°.\n\nWhat if I grip the bar near an end and then rotate the gripper's YAW? No.\n\nWhat if I grip the bar at BOTH ends... impossible.\n\nLet me look at the problem from the task designer's perspective: this task is meant to be solvable with this gripper. The key must be to grasp the bar across its WIDTH at the center, lift, and hold. The physics should keep it level. The fact that it doesn't for me suggests something is off in my grasp.\n\nWhat if the issue is the grasp's HEIGHT? At eef z=0.012-0.015, the fingers straddle the thin bar (1.6cm) with the fingertips at 0.002-0.005. Maybe the fingertips are BELOW the bar's bottom (the bar's bottom is at 0.0, the table) — impossible. Hmm, what if the fingers are actually pressing the bar against the TABLE (the fingertips clamping it to the table's surface) and lifting pulls it up at a weird angle? At the moment of closing, the fingertips are 2-5mm above the table; the bar is 1.6cm tall — the fingers grip its sides over 1-1.4 cm ✓.\n\nWhat if I grasp HIGHER (grip only the top 5mm of the bar)? That would be a worse grip.\n\nHmm, what if the bar has a rounded/beveled top edge, so gripping at 1.2cm of its height contacts only the rounded part → the contact is at the top corners → unstable!\n\nConsider grabbing the bar on its FLAT top and bottom... impossible.\n\nI wonder if the intended solution is to pinch the bar at its center and the physics just works in the intended environment, and my issues stem from repeated collisions having displaced the bar's state (the bar may be resting on its side/edge, or the table's friction...).\n\nWAIT. Actually — maybe the bar is not lying FLAT! What if it's resting on its EDGE (4cm tall, 1.6cm wide)? Looking at the s033 image: the bar appears as a box with a visible top face and a front face, and its projected height is ~20 px... In s033, the bar's silhouette: y 285-325 (40 px tall) and 173 px long. For a flat bar (1.6cm) at a 40° camera depression: the top face's projected height = 0.04*sin(40°)=0.026 m = 21 px, plus the front face 0.016*cos(40) = 0.012 = 10 px → 31 px total ✓ ~40 observed. For a bar on edge (4cm tall): the top face = 0.016*sin40=6px + the front face 0.04*cos40=25px → 31 px. Both ~equal. Hmm.\n\nThe wrist image can tell: in s033's wrist image, the bar's width (the x extent) = 145 px at d=0.05+c-0.015. For a flat bar, that's 4cm → d = f*0.04/145. For an edge-on bar, 1.6cm → d = f*0.016/145 (a smaller distance). In s030 (eef z=0.0131, closed, on the table), the bar's wrist width was 163 px. And at that time the fingers were at ±0.0205, and the bar's width = the gripper's width = 0.041 → 163 px ↔ 0.041 m → the scale = 3976 px/m at d = h-... Using c=0.07: d = 0.0831-0.015 = 0.068 → f = 270. Then in s033 (eef 0.0498, d=0.1048): the width predicted = 270*0.041/0.1048 = 106 px, but observed 145 px. Hmm, inconsistent (the bar should appear smaller, but it's bigger). Let me recheck s033's wrist measurement: the bar spans x 195-340 = 145. Hmm.\n\nThese inconsistencies suggest the bar's height (z) is significant: if the bar's top face is at z=0.04 (on edge!), then in s030 (eef 0.0131, camera 0.0831) d = 0.043; in s033 (camera 0.1198) d = 0.08. The widths would be 163 and 88. Still not 145.\n\nI'm flailing. Time to make a final decision with 4 commands.\n\nLet me do the most sensible remaining thing: try to use the free-rotation property + a fast vertical motion to reduce the tilt, and if that fails, finish.\n\nActually, hmm, hold on. Let me reconsider the option of \"leveling against the table\":\n1. Lower the held bar until its lowest end touches the table (eef ~0.06-0.08).\n2. Continue lowering 1-2 cm: the table pushes the low end up, rotating the bar toward level (the bar pivots on the table at its low end while the grip descends).\n3. When the bar is level (both ends on the table), CLOSE the gripper again (it's already closed) — I can't increase the grip force.\n4. Then lift super slowly...\n\nThis just repeats what we've done (the bar is level on the table before the lift).\n\nSo the tilt develops during the lift, regardless.\n\nSince the tilt is ~3-4°/cm, at 10cm it's 35-40°. To be under 8°, I could lift at most 2cm. But I need 10cm.\n\nTHE ONLY WAY: prevent the rotation. The rotation is about the pinch axis, resisted only by friction. What if I grip the bar near its END so that the bar's COM is FAR from the grip, creating a large gravity torque? That would make it hang vertically (worse).\n\nWhat if I grip the bar at its center AND the bar is symmetric so there's no torque — then the rotation must come from the grip's kinematics. The observed rotation is systematic. My best guess: the fingers' pads' contact is not symmetric (e.g., the pads are slightly angled inward at the top), so as the bar slides down through the grip (gravity!), it rotates. Wait, the bar shouldn't slide down — the friction should hold it. Unless it DOES slide down (the gripper's force is too low), and the sliding + the pad angle causes the rotation!\n\nIf the bar slides down through the fingers, then the grasp is failing (the bar would eventually fall). But the bar stays held (the width stays 0.041) — sliding means the bar moves down relative to the gripper. Is there evidence? The bar's height relative to the fingers: in the wrist images, the bar's top face... hmm.\n\nIf the bar slides down, the task's 10cm clearance requires the eef to be higher.\n\nOK: FINAL DECISION. With 4 commands left, I'll do this: finish now (gamble ~0% if pitched)... no.\n\nLet me try ONE more thing that has a real chance: CANCEL the systematic rotation by closing the gripper at a DIFFERENT YAW: command yaw=-90 (reported +90). Wait, I already did yaw=+90 → reported -90. The alternative (yaw=-90 → +90) flips the fingers' roles but the geometry is symmetric (the fingers are identical). So no change. Skip.\n\nWhat about tilting the bar intentionally before the lift, in the OPPOSITE direction, so that after the rotation it ends up level? The rotation during the lift is ~3-4°/cm (a total of ~35° over 10cm). If I could pre-rotate the bar by -35°... but I can't rotate it (the bar is on the table, level).\n\nHmm, unless: I could lean the bar against something... \n\nOK, actually, WAIT. NEW IDEA that might actually work! If the rotation is proportional to the vertical distance traveled, then what if I DON'T move the eef vertically, but instead move the whole arm... no, the eef is the only control.\n\nHmm, hold on: what if I lift the bar to 10cm in a way that also ROTATES the gripper's yaw continuously? If the rotation is a fixed screw motion in the gripper frame, yawing wouldn't cancel it.\n\nWhat if the rotation is caused by the arm's IK (the wrist joint rotating as the arm extends upward)? The wrist joint (joint 7) is the yaw. The eef_yaw stays -90, so no yaw rotation. The other joints determine the pitch/roll of the hand, which the controller holds constant. But actually... the controller may not perfectly hold the orientation! If the hand's pitch changes as the arm rises (a controller error), the bar would tilt with it! And the reported eef_yaw wouldn't show it.\n\nThis is quite plausible! The hand's pitch error would be a smooth function of the arm configuration, so different lifts would give different tilts ✓ (25°, 38°, 55°) and the direction would be consistent ✓.\n\nIf the HAND is pitching as it rises, the bar (gripped) tilts with it. To compensate... we can't control the hand's pitch.\n\nBUT: if the hand's pitch changes with the arm's configuration, maybe it's better to keep the arm in a configuration where the hand is more level. For example, the initial pose (s000) had the hand at z=0.26. Hmm.\n\nI could TEST this by lifting with the gripper EMPTY and comparing its appearance (the fingers' angle) — not enough resolution.\n\nGiven all this, I'm out of clever options. 4 commands left, 43 s.\n\nLet me use them wisely: I'll do a single test of whether the tilt depends on the lift HEIGHT only (the screw/kinematic theory) or has a dynamic component — irrelevant.\n\nFINAL: I'll attempt the \"level by lowering onto the table + lift fast then finish at the moment it's level\"? Not feasible.\n\nAlternatively, accept and finish. But before that, maybe I should check whether the current bar could be judged \"level\": the agentview's tilt is ~40° — a definite fail.\n\nHmm, hold on. Let me use my remaining commands to test the \"hand pitch follows the arm config\" theory cheaply: MOVE THE EEF SIDEWAYS at a constant height and see if the bar's tilt changes. If the tilt is a function of the arm's configuration, moving to a different x could level the bar! E.g., at a larger x (the arm extended forward), the hand's pitch error might be different.\n\nThat's a cheap test: 1 command. Move x +0.05 at the current z=0.145 and check the tilt.\n\nIf it changes significantly, I could search for a configuration where the bar is level! That would be a great outcome: hold it level at a different x.\n\nLet's do it: move x=0.64 (the current x=0.585) at z=0.145.\n\nHmm, but at s019/s014 the tilts were 38-55° at x≈0.59 with z≈0.12; the initial lift at s010 (x=0.596) gave 25°. All at similar x.\n\nLet me try a much different x: 0.50 (pulling the arm back). 1 command. Let's see." + ], + "viewed": [ + "obs/s036_agentview.jpg", + "obs/s036_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 38, + "kind": "move_eef", + "frame_start": 1577, + "frame_end": 1842, + "command": "move_eef z=0.012 gripper=open speed=0.02", + "args": { + "z": 0.012, + "gripper": "open", + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5039, + 0.1667, + 0.0153 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 136.42352986335754, + "agent_obs_images": [ + "obs/s038_agentview.jpg", + "obs/s038_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Moving in x didn't change the tilt (still ~40°). So it's not the arm's configuration — the bar is rigidly held at ~40° relative to the gripper.\n\nSo the bar's orientation relative to the GRIPPER is ~40°. And the fingers themselves... wait! If the bar is rigidly held at 40° relative to the gripper and the fingers, maybe the HAND itself is pitched 40°!! Let me measure the hand's pitch in this agentview. The gripper's fingers in s037: the white plate at (370,150)-(390,235). That's a slope of 20/85 → 13°. Hmm, not 40.\n\nHmm, but the fingers' visible plate is the NEAR finger seen from the front; a pitch about x would foreshorten it, not tilt it.\n\nThe bar is clearly ~40° from horizontal. The fingers are ~13° from vertical.\n\nHmm, hold on. What if the bar is gripped at the top by the finger tips, and the fingers' pads' inner faces have a trapezoid shape (the Panda fingers have angled tips)? Then the bar would sit wedged at an angle.\n\nI have 3 commands left. Let me make a final decision: accept a failure or try something desperate.\n\nDesperate idea: release the bar and let it fall to the table, then try the grasp with the yaw of 0 (fingers closing along y): as analyzed, the fingers would land on the bar's top and close along y. But actually, wait: with the bar along y and the fingers closing along y... the finger pads are ~2cm wide plates. If the gripper's x is positioned so that the fingers descend onto either side of the bar in the X direction? No, they're separated along y.\n\nHmm, unless the bar is along y and I use yaw=0 with the gripper positioned such that the fingers are at x = bar_x ± ... they can't be separated in x with yaw=0.\n\nSo yaw=±90 is required.\n\nDesperate idea 2: Keep the bar held at 40° and ROTATE THE GRIPPER'S YAW BY 180° QUICKLY. The bar would be dragged around (yaw) — no change to its tilt.\n\nDesperate idea 3: finish now with a 0.1% chance.\n\nHmm, hold on, what about the possibility that the bar is YAWED (level) and everything I see is a perspective illusion? The wrist strip's near-verticality argues against a yaw... \n\nLet me do one final check with the data I have: if the bar were yawed by ψ relative to the gripper (i.e., in the gripper's frame, the bar's long axis is at angle ψ from the gripper's y-axis), then in the wrist image (top-down), the bar would be slanted by ψ. The strip is vertical (ψ≈0) in ALL the images including the lifted ones (s014: 255.5 at the top, 255.5 at the bottom; s019: 256 constant; s036: 255→257). So ψ≈0 → the bar's long axis is along y in the gripper's frame.\n\nThe bar's long axis is along y (horizontal) in the gripper frame and the gripper is vertical → the bar's long axis is HORIZONTAL in the world, regardless of the \"taper\"!\n\nHmm!! Wait, that's only true if the taper is due to a pitch. If the bar is pitched by θ about the x-axis, its long axis has a z-component → its projection onto the x-y plane is along y ✓ (no slant!) but its length in the x-y plane is L cosθ. So the strip's verticality doesn't prove levelness — I knew that.\n\nThe taper: a pitch. I've established the taper is strong.\n\nBUT hold on, could the taper be explained by the camera's lateral offset (in y) from the grasp point? If the camera is offset in y (e.g., 3cm toward -y) and the bar is level, the bar's near end (+y, away from the camera's y) would be FARTHER → narrower; the far end (-y) closer → wider. A level bar with the camera offset in y would show a linear taper! Widths: w ∝ 1/d, d = sqrt(dz² + (y-y_cam)²). With dz=0.15 and a 0.1 m range in y, d varies from 0.18 (at y=+0.1) to 0.15 → a width ratio of 0.83. The observed ratio: 60/145 = 0.41. Too strong for that.\n\nBut hold on, if the camera is at the gripper and the bar is held just below it, dz could be small, e.g., 0.05! Then d ranges from sqrt(0.05²+0.1²)=0.112 (at the far end) to 0.05 (at the near end) → a width ratio of 0.45 ✓✓ MATCHES the observed 0.41!!!\n\nSo if the wrist camera is only ~5cm above the BAR'S TOP FACE, a level bar would show exactly this strong taper! And the bar's top could be ~2cm below the camera... The eef is at 0.142, the bar's top at ~0.13 => 1.2 cm below the eef. If the camera is 7cm above the eef, the distance from the camera to the bar's top is 8cm — and with the +/-10cm y-spread: the near end d=sqrt(0.08²+0²)... wait, the camera is above the GRASP POINT: the bar's center (y=0 relative) is at d=0.08; the ends at sqrt(0.08²+0.1²)=0.128 → a width ratio of 0.08/0.128 = 0.62. Observed 0.41. Close-ish, especially if the camera is at 5cm.\n\nSo a LEVEL bar in a level attitude with the camera close would produce a strong symmetric taper about the bar's center. But our taper is NOT symmetric about the image center: the widths at v=210 and v=400 differ a lot, and the bar's center is at, e.g., v≈300 while the image center is 256.\n\nFor a level bar with the camera above the grip: the bar's center (at the grasp's y) projects to the image center (v=256) if the camera's optical axis passes through it. The widths should be symmetric about v=256. In s036: w(210)=60, w(302)=145 (I should use the data at symmetric rows: at v=256 the width ~90 and at v=410 the width ~150; no symmetry).\n\nHmm, the width at 256 is 90 and at 410 is 150 → not symmetric about 256.\n\nSo the bar's closest point in the image is at the bottom (v>410) — meaning the bar's center is well below the image center in v, i.e., the bar's +y side is closer. So the camera is above a point at -y of the bar's center. E.g., the bar's center is at +y=+5cm from the camera's axis. That's a big offset... unless the camera's optical axis is tilted forward by 27° (as estimated earlier), which shifts the projection so that a level bar directly below the grip appears offset in the image! YES — with a forward-tilted camera, a level bar centered at the grasp would appear with its near (+y) end closer to the image center... \n\nAAARGH. The tilted camera breaks my \"pitch\" inference. With a forward-tilted camera, a LEVEL bar shows an asymmetric taper just like what we see!\n\nSo the wrist image CANNOT distinguish. The agentview is the honest one: it clearly shows a tilt of ~40°.\n\nHmm, unless the agentview's apparent tilt is a 3D yaw again... \n\nThe agentview's evidence for a pitch vs a yaw: the bar's projected 2D length. For a yaw of ψ: the projected length ≈ L*sqrt((Sy cosψ)² + (Sx sinψ)²). For a pitch of θ: L*sqrt((Sy cosθ)²+(Sz sinθ)²).\n\nI can measure Sx and Sz from the agentview using other known objects... The gripper's finger pads span 0.04 in x (the closing direction, at yaw=-90, the fingers are separated along x) — in the agentview, the fingers' separation appears... their u difference is small (the x direction maps mostly vertically).\n\nHmm.\n\nAlternatively, if the bar is YAWED by 40°, then when I move the eef in y by 2cm, the bar's world position doesn't change but... no.\n\nFINAL DECISIVE TEST (cheap): Rotate the gripper's yaw by +90° while holding the bar (1 command) and look at the agentview.\n- If the bar is YAWED by 40° in the gripper frame, then after a 90° gripper yaw, the bar's world yaw becomes 130°. The agentview would show the bar pointing 50° in the other direction (a strong foreshortening, and its projected length would shrink a lot if Sx < Sy).\n- If the bar is PITCHED by 40° about the gripper's x, after a 90° yaw the bar's long axis becomes x with a tilt about y. In the agentview, the bar would appear pointing INTO the screen (foreshortened) and its slope would change to a different value.\n\nBoth would foreshorten differently... ugh, again not decisive.\n\nHmm, but here's a clean one: rotate the yaw by 90° and check the WRIST image. The wrist camera rotates with the gripper. If the bar is PITCHED (in the gripper frame, the bar's long axis is y with a z-tilt), then after a 90° rotation, in the NEW wrist image the bar's long axis would be x (horizontal) with a z-tilt → the wrist image would show a HORIZONTAL strip with a strong taper. The taper would be along x rather than y.\n- If the bar is YAWED in the gripper frame (its long axis at 40° from y in the horizontal plane), the wrist image would show a slanted strip — we know it doesn't.\n\nSince the wrist strip is vertical (the bar along the gripper's y), the bar's long axis is along the gripper's y with a z-component. That's a pitch in the gripper frame. After a 90° yaw, the wrist would show a horizontal strip with a taper.\n\nThis confirms (in the gripper frame) that the bar is pitched. And since the gripper is vertical, the bar is pitched in the world.\n\nWAIT, but is the gripper vertical in the world? That's the remaining uncertainty. If the hand is pitched by 40° in the world (which we'd see as the fingers looking tilted in the agentview), then... In s037's agentview, the fingers look tilted ~13-20°, not 40°.\n\nHmm, so the bar is at 40° while the fingers are at ~13° → the bar is at ~27° relative to the fingers. The wrist image says the bar is along the gripper's y with a z-tilt.\n\nCONCLUSION: the bar is pitched relative to the fingers by a large angle. The grip is not holding it aligned. This might be a sim contact oddity (e.g., the fingers' collision geoms being smaller than the visuals, so the bar contacts the finger's inner edges at a point, letting it rotate).\n\nGiven that, could a DEEPER grasp help (contacting more of the fingers' inner faces)? Our grasp has the fingertips at z=0.002-0.005 while the bar is 1.6cm tall, so we contact the full height...\n\nWait, does the FINGER have an inner face at the tip? The Panda finger's inner face starts at the very tip and extends up ~3cm. If the bar is 1.6cm tall and the fingertips are at z=0.002, the fingers' inner faces contact the bar over 0.002-0.016 = 1.4cm. Good.\n\nUnless the fingers' pads are only on the TIPS (the last 5mm). In the images, the fingers look like flat white plates ~2cm wide and ~4cm tall. Fine.\n\nI'm out of ideas for a fundamental fix within 3 commands.\n\nFINAL: Let me do the least-bad thing: with 3 commands, re-grasp once more but with the gripper closing while the bar is on the table, then lift to z=0.115 (the minimum for 10cm clearance: the bar's top is ~1cm below the eef? Then the bar's bottom is ~2.5cm below the eef → the eef at 0.125 gives the bar's bottom at 0.10). Lift to 0.13 (as before). The tilt would be ~40°.\n\nAlternatively... hmm, hmm. Let me think about the \"close harder\" idea: what if I close the gripper on the bar, then OPEN it slightly and close again? Or close it while the bar is on the table with a slight downward push to seat it?\n\nWhat if the bar is not fully seated between the fingers in x (e.g., one finger is only on the bar's edge)? At the closed state, the width is 0.041 = the bar's width, so both fingers touch.\n\nOK, since the tilt's direction is always the same (+y end up), and the tilt is induced by the lift, one last idea: perform the lift with a simultaneous YAW rotation so that the \"screw\" is compensated? If the gripper's yaw rotates 40° during the lift, the bar's tilt axis rotates 40°... The bar's tilt would then be about a horizontal axis at 40° to x — i.e., a combination of pitch and roll, but the tilt MAGNITUDE relative to horizontal stays 40°. No good.\n\nAlright: FINAL ANSWER: I'll do my best with the remaining 3 commands: place the bar, grasp at the center, lift to 0.13, and finish. It'll likely fail, but that's the best I can do. Actually — wait. Let me reconsider ONE more possibility: what if I DON'T lift the bar with the fingers but instead HOLD IT AGAINST THE FINGERS' TOP with the bar resting ON the fingers horizontally? Not possible (the grip must hold).\n\nHmm, actually, here's a thought: what if I grasp the bar at its very END such that the bar hangs vertically, then use the WRIST's yaw to rotate the hanging bar... no.\n\nWhat about grasping the bar at its center and then holding it against the TABLE's surface by pressing DOWN while the gripper is partly... no, it must be up.\n\nOK, one more real idea: what if the tilt is caused by the wrist camera's or the gripper's collision with the bar? The wrist camera is a physical object? If the camera (mounted above the hand) collides with... no, the bar is below.\n\nLet me look at the s037 crop of the fingers+bar to see the actual contact geometry. That's free (a shell command + a view) — but I've used 40+ tool calls; I have ~10 left. Let me look.", + "NOW I can see clearly! The bar is gripped between the fingers, and the bar passes BEHIND the near finger and in FRONT of the far finger? Looking at the image: the near finger (white plate) is in front of the bar at the grip. The bar passes at a steep angle (from the lower-left at ~35° up to the upper-right).\n\nCrucially: the bar's path passes through the grip at a steep angle, and the finger plate is vertical. The bar's visible width (the top face) is a wide band.\n\nThe steep angle in the image (~45°) and the bar's end face visible at the top-right... \n\nAND notice: the bar's top face is facing UP and TOWARD the camera; the bar looks like a long flat plank tilted upward away from us.\n\nHmm, here's a KEY observation: the bar's angle in the image is ~45° and the bar's projected length is long (the full 175 px). For a bar yawed 45° in the horizontal plane, the projection would be foreshortened by cos(45°)=0.7 IF Sx=Sy... The ends would be at ±0.07 in y and ±0.07 in x. In the agentview, the y direction maps to u with ~825 px/m and the x direction maps mostly to v (with some u-leak). Hmm.\n\nThe image also shows the bar's shadow? No.\n\nLook at the visible top face: it's a parallelogram whose long sides are parallel, and there's a visible SIDE face along the lower edge (the dark strip at the lower-left edge of the bar). Also, at the upper-right end, we see the end face clearly.\n\nFor a PITCHED bar (the +y end up), the camera (above, in front) would see the TOP face (visible ✓) and the -x side face... the visible side would be the side facing the camera = +x... \n\nHonestly, for a YAWED bar, the camera would see the top face plus the end face at one end ✓ (observed) and possibly the side face.\n\nBoth again.\n\nBUT: here's a distinguishing feature! For a PITCHED bar with the +y end up, the bar would be at a HEIGHT: the +y end significantly higher than the -y end. The bar's top face in the image: the upper-right end is at v=110 and the lower-left at v=300 (in the crop). The image's v direction for the agentview is a mix of x and z.\n\nIf the bar is yawed (level), the upper-right end is farther from the camera (a smaller x) and would appear HIGHER in the image ✓ (that's exactly what a yaw does in this camera). If the bar is pitched, the +y end is also higher in the image.\n\nI can't distinguish. HOWEVER: I can check the SHADOW or the bar's apparent SIZE (a yaw brings one end closer → bigger).\n\nThe bar's width along its length: in the crop, the top face's width at the upper-right end ~90 px (crop) = 22 px original, and at the lower-left ~ 100/4 = 25 px. Similar.\n\nOK, THE DECISIVE TEST: I have 3 commands. Let me use one: yaw the gripper +45° and watch how the bar's apparent angle changes in the wrist image. \n\nActually, here's the cleanest: in the WRIST image, the bar's strip is VERTICAL and its length spans the whole frame. If the bar is pitched, its projected length in the wrist image = L cosθ * scale + the perspective. We measured a strong taper (60→145 px widths), which is consistent with either (a) a pitch or (b) a level bar close to the camera.\n\nLet me settle (a) vs (b) using a LEVEL reference at a similar height: s033 (the bar on the table, eef z=0.0498, camera+0.07=0.12): the bar's width was 145 px, CONSTANT (no taper!). That's a level bar, 0.04 m wide, at a distance of ~0.105-0.12.\n\nIn s036 (eef z=0.142, camera 0.212), a level bar's width would be 145*0.105/0.197 = 77 px, CONSTANT. The observed widths: 60-145 with a strong taper. The near end's width (145) equals the s033 value (145) — the same apparent size = the same distance (0.105) → the near end's z = 0.212-0.105 = 0.107. The far end 60 px → d = 0.105*145/60 = 0.254 → z = -0.042. Impossible → so the bar must be pitched (or the camera is higher).\n\nAlternatively, the camera's height offset c: with c unknown, from s033: d_033 = 145 → f*0.04/145 = 0.05+c-0.015. In s036: d_near = f*0.04/145 = the same = 0.05+c-0.015 → the near end's z = (0.142+c) - (0.035+c) = 0.107 ✓ (independent of c). The far end: d_far = 145/60 * (0.035+c) → z_far = (0.142+c) - 2.417*(0.035+c) = 0.0574 - 1.417c. For z_far ≥ 0.02 (the bar must be above the table), c ≤ 0.026. So the wrist camera would have to be only 2.6cm above the eef — but the eef's grasp point is already 1cm above the fingertips, and the camera is certainly higher than that (7cm). With c=0.07: z_far = -0.042 (impossible).\n\nCONCLUSION: The bar IS pitched, by a large angle. The bar's far (-y) end would be at z≈0.02 with c=0.07... let me solve for the pitch with c=0.07: z_far = 0.0574-1.417*0.07 = -0.042. Since z_far must be ≥ 0.005 (the bar's center can't be below the table), the model says c must be ≤ 0.026. If the camera is at c=0.026, z_far=0.02 and z_near=0.107 → Δz=0.087 over the bar's length 0.196 → θ=26°. If c=0.0, Δz=0.078.\n\nHmm, so the pitch is ~26-35°, a serious tilt. FINE. It's a pitch.\n\n3 commands left. Let me consider: could I deliberately pre-tilt the bar in the opposite direction before the lift? The bar is on the table, level. Hmm.\n\nWait — actually! What if the pitch is caused by the gripper's closing while the bar is on the table, and the pitch is a rotation about x that HAPPENS during the lift because the fingers are not quite parallel to the bar's faces? What if I close the gripper with the bar slightly off in x so the fingers contact only the bar's top corner, and the closing torque rotates the bar... but the bar is on the table, so it can't rotate much.\n\nAfter closing (bar on table, level), when I lift, the bar rotates immediately. 5° at 1.6cm.\n\nI wonder: what if I SLIDE the bar along the table to a different x before lifting? No.\n\nFINAL: Given the pitch is inherent to the grasp, the only remaining variable is... hmm, what about the gripper's yaw of 90 vs -90 (reported)? Let me think about which one gives a \"roll\" error. The reported eef_yaw = -90 when I command 90. So the controller's yaw sign is inverted but the achieved orientation is a -90 rotation. If the hand has a systematic pitch error about the WORLD x-axis (e.g., the tool points 3° off vertical), then for a yaw of -90 vs +90 the error would map to a different world axis: a tool-tilt error of +α about the tool's x-axis becomes, after a 180° yaw, a tilt about -x... \n\nWe only have one more grasp's worth of commands. Commanding yaw=-90 changes the tool's yaw by 180° relative to now → a tilt error in the tool's frame would flip its world direction. If the hand has a tool-frame pitch error, the bar's tilt direction would flip → the tilt might be smaller or the same. It's a 50/50 whether it helps, but it won't be worse than now (still ~30-40°).\n\nNot worth it.\n\nLet me think about the \"physics hack\": what if I lift the bar and then ROTATE the gripper's YAW rapidly back and forth (a few times)? The bar would be dragged around; its roll might be excited. Then, at the end, it might settle level if the equilibrium is level... but the equilibrium is 40°.\n\nSince the equilibrium in the gripper frame is ~40°, no yaw trick will fix it.\n\n=> The attempt is likely lost unless there's a fundamentally different grasp.\n\nWith 3 commands, is there any fundamentally different grasp I can execute? \n- Approach the bar at a 45° yaw (fingers diagonal): then the bar's long axis is at 45° to the fingers. The fingers would pinch the bar's CORNERS... the contact would be on the bar's edges → a V-groove grip! Two fingers contacting the bar's two diagonal corners could hold it more rigidly (a 4-point contact). Hmm, with a 45° yaw, the fingers close along a diagonal; the bar's cross-section (4x1.6) presents a diagonal width of sqrt(4²+1.6²)=4.3cm < the 8cm opening. When closing, the fingers would contact the bar's corners and the bar would be wedged. The roll resistance could be higher (corner contact with the normal forces along the diagonal). Hmm, but it can still roll (the bar could rotate about its long axis = a harmless roll!). WAIT: a rotation about the bar's LONG axis (y) is harmless for levelness! The harmful rotation is about x (the ends up/down).\n\nWith a 45° yaw grip, the fingers contact the bar's corners; a rotation about the bar's long axis (roll) is free-ish, but the pitch is resisted by... the same friction. Hmm.\n\nHmm, actually! Here's an insight: with the fingers closing along x on the bar's flat sides, the bar can rotate about x (pitch) freely because the contacts are symmetric about x. The normal forces are along x and can't resist a pitch; only friction can. But if the fingers contact the bar's CORNERS (yawed 45°), the normal forces are along a diagonal direction in the x-z plane... hmm, no: the fingers' faces are vertical planes; the contact normal is horizontal (along the closing direction). If the closing direction is at 45° in the x-y plane, the normal is horizontal at 45° — the pitch is still resisted only by friction. Damn.\n\nThe pitch is resisted only by friction in any configuration (the contact normals are horizontal + the pads are vertical).\n\nUNLESS the contact has a vertical normal component: e.g., if the bar rests ON TOP of a finger (a vertical normal). E.g., grasp the bar with one finger UNDER it? We can't get under it (the table blocks).\n\nHmm, unless the bar is on the EDGE of the table and I can get a finger under it! But there's no table edge nearby (the table looks large).\n\nHmm, what about pinching the bar at its top with the fingers' inner faces forming a V (the Panda fingers have a chamfered tip)? If the fingers pinch the bar's top corners, the normal forces have vertical components that clamp the bar vertically, resisting the pitch! To do that, the fingers would contact the bar's top face from both sides — i.e., grip the bar with the fingers' tips pressed on the top face. That's impossible with a vertical closing motion... Actually it is possible: close the fingers with the gripper positioned HIGH so the fingers' tips (the angled/chamfered inner tip surfaces) press on the bar's top edge. The reported width 0.041 suggests the fingers contact the sides.\n\nI think the sim's finger pads are simple boxes.\n\nFINE. Conclusion: I can't fix it. Use the remaining 3 commands to make the best final state: hold the bar as level as possible. The tilt is ~40° regardless.\n\nHmm, hold on, one last data point: at s031 (a 1.6cm lift), the tilt was only ~5°. So the tilt grows with the lift height. Interesting: at 1.6cm the tilt is 5°; at 13cm it's 40°. So the rotation rate is ~2.7°/cm.\n\nWhat if I lift to only 10.5cm above the table... the tilt is ~30°.\n\nBUT WAIT: what if the rotation is caused by the bar's SLIDING through the fingers as it lifts, and the slide is because the finger pads' grip has a limited vertical friction? If the friction were adequate, the bar wouldn't slide and wouldn't rotate. The bar's weight: a metal bar 19.6x4x1.6 cm ≈ 0.2*4*1.6*19.6 cm³ ≈ 25 cm³ → 0.2 kg. The grip's normal force must be ≥ mg/μ = 2N/0.5 = 4N — surely the gripper applies more.\n\nUnless the gripper's force in this sim is weak (a position-controlled gripper with a low stiffness). Then the bar would slip progressively. But the bar doesn't fall out.\n\nAlright, FINAL DECISION: I'll do one last attempt with a grip at the bar's CENTER and lift to the minimum height (z=0.125) in small steps, and then finish. Even if the tilt is ~30°, it fails. But maybe... \n\nHmm, actually, let me reconsider: at 1.6cm lift, the tilt was 4.7°. What if I could get the bar's lowest point 10cm up WITHOUT lifting the eef 10cm? IMPOSSIBLE — the bar is below the gripper.\n\nUNLESS the bar is held at an angle where one end sticks UP? No, that's a tilt.\n\nWhat if I lift the bar to 10cm and the bar tilts, but... no.\n\nWAIT!!! What about placing something UNDER the bar? Like, could I use the gripper to first move an object under it? There are no other objects.\n\nOK. Final answer: I'll wrap up. But with 3 commands, let me at least try the yaw=-90 (reported +90) variant once — it's the only untried variable and could plausibly flip the tilt direction, and maybe the magnitude differs. Cost: lower+open (1), move to align with yaw=-90 + close (1), lift (1) = 3 commands, then finish (free? no, finish is a command but probably not counted... \"finish\" ends the attempt; the budget is 40 commands; I have 3 left).\n\nHmm, that leaves no room for a check.\n\nAlternatively, use the 3 commands to: (1) lower, open, and position at a diagonal yaw (45°) with close; (2) lift to 0.125; (3) finish. The diagonal grip is a genuinely different contact geometry that might resist the pitch better (corner contacts could create a wedging effect). It's a gamble but at least it's different from the known-failing configuration.\n\nActually, hmm: with a 45° yaw, the fingers close along a diagonal. The bar's cross-section presents a 4.3cm diagonal. The fingers at 8cm open would close onto the bar and contact its corners. The contact normals along the diagonal → the bar would be pushed... The friction at the corner contacts has a component that could resist the pitch better (a wedging action). And the bar could not rotate about its long axis freely (the corners would slip), but the pitch (about x)... \n\nRisk: with a 45° yaw, the grip may be unstable (the bar could pop out).\n\nGiven the 3-command constraint, the sequence would be:\n1. move_eef (x=bar_x, y=bar_y, z=0.012, yaw=45deg_command) gripper=close — but I need to know the bar's position after the last placement. The bar is currently HELD in the air (at 40°) at (0.5014, 0.1655, 0.1449). I'd have to lower it and release it (1 command), then measure and grasp (2 commands), lift (1 command) = 4 commands. I have 3.\n\nNot enough! I have only 3 commands total. So: lower+open (1), grab (1), lift (1) = 3, then finish.\n\nBut after the release, the bar's position will shift and I won't be able to check it. That's essentially a blind grab. My agentview-based estimate after a drop from 10cm is uncertain by several cm — risky but the bar is 20cm long and the tolerance in y is ±8cm; in x, the tolerance is only ±2cm! A blind x grab is risky: if x is off by >2cm, the fingers land on the bar and knock it away.\n\nThe last drop (s033) left the bar at y≈0.14 and x≈0.59 (the wrist showed x centered). After the current hold at x=0.50 (I moved the bar with me!), releasing would leave the bar around x=0.50-0.59.\n\nToo risky. \n\nAlternative use of the 3 commands: lower the bar to the table (1), regrasp at the SAME yaw=90 with a freshly measured position (1 command using move with close), lift (1). That's the known-failing configuration but it gives a clean final state.\n\nHmm, what's the point? Both are failures.\n\nLet me think ONE more time about the tilt's cause... \n\nAH WAIT!!! I just thought of something important! Look at the s037 crop again: the bar's visible SIDE face (the dark strip along the lower-left edge of the top face) — and the bar's top face is BRIGHT (facing up). The camera sees the top face. This is consistent with a bar that's mostly horizontal but yawed, as I said.\n\nHmm, but here's a thing: in the s037 crop, the bar's near end (the lower-left) shows NO end face — it's cut off by the image's bottom edge? No, the bar's lower-left end is at (0,650) in the crop, extending beyond... the bar's left end is at the image's left edge. The bar extends off-frame to the lower-left. And the upper-right end is visible.\n\nHmm, in this view the bar extends from the lower-left (off-frame) to the upper-right. Its grip is at ~40% from the upper-right end... \n\nOK, let me try a completely different interpretation: the bar is NOT pitched. It's YAWED. Then everything makes sense: the bar is horizontally level, and the gripper has been holding it fine all along! The agentview's apparent tilt is a perspective illusion of the yaw (the near end appears lower).\n\nUnder this interpretation, all my holds were LEVEL and would PASS the task! And my hypothesis tests were confused by misreading the projection.\n\nThe wrist image: for a yawed bar (40° in the horizontal plane) with a forward-tilted camera, what would the projection look like? A yawed bar in a top-down (tilted) view: the bar's direction in the horizontal plane is at 40° from the camera's y-axis. Its projection onto the image would be slanted by ~40° in the image plane (a top-down view shows the horizontal plane directly). So the wrist image would show a 40°-slanted strip. We observe a VERTICAL strip → NO YAW. \n\nThe wrist camera might be tilted forward, but that doesn't undo the horizontal slant (a tilted camera compresses one direction but doesn't rotate the direction by 40°).\n\nSo under the yaw hypothesis, the wrist image should show a slant. It doesn't.\n\nBUT WAIT: is the wrist camera's image really showing the world's x/y as its horizontal/vertical? What if the wrist camera is mounted with a ROLL of 40°?? Then a yawed bar would appear vertical. But then the LEVEL bar on the table (s033) would appear slanted by the roll (40°) — but it appeared vertical too. So the roll is 0.\n\nHmm, unless the camera's roll is exactly 40° and in s033 the bar was also yawed by 40°?? No—in s033 the bar was on the table where I'd expect it to be along y (it was, per the agentview: horizontal).\n\nSo: vertical strips in both the on-table and held states, but the agentview shows the on-table bar as horizontal and the held bar as 40°. The wrist camera says both are along the same direction in the gripper frame (vertical) and the gripper's yaw is the same (-90) in both cases → both are along the world y. CONTRADICTION with the agentview!!!! \n\nUnless the agentview's apparent 40° tilt is not a yaw/pitch direction change but something else... The only remaining explanation: the bar is pitched (a rotation about the x-axis, which preserves the y-direction in the top view ✓✓) — and the agentview's tilt is the pitch.\n\nSo it IS a pitch. Confirmed by elimination. OK.\n\nSo all my holds were pitched and would fail.\n\nWith 3 commands left and no way to fix the pitch, let me use them to at least END with the best possible state, and note the failure.\n\nHmm, is there ANY way to hold the bar level with a fixed-pitch hand and a gravity-free neutral grip... \n\n!!!!! IDEA !!!!! What if I grip the bar NEAR ITS CENTER but with the fingers arranged so the bar CANNOT pitch: make the grip resist the pitch using the WRIST CAMERA?? No.\n\n!!! BETTER IDEA !!! What if the bar is gripped at its center and I add a SECOND contact point: the bar's UPPER face against the gripper's palm/body? If I lift the bar so it presses against the gripper's body (the palm), the palm could resist the pitch! The palm is the flat face of the gripper's body above the fingers. The bar's top face is 1.6cm above its center... To press the bar against the palm, the bar's top must touch the palm plane. The palm is at z ≈ eef_z + something (the hand's body is above the fingers, maybe +2-4cm). If the bar were pushed UP into the palm by the fingers... but the fingers pinch horizontally; they can't push the bar up.\n\nHowever, when LIFTING, the fingers' friction lifts the bar, and if the bar's top contacts the palm, the palm provides a vertical (downward) normal force and rotational support. The bar's top would need to be at the palm's level, i.e., the bar's top ≈ eef_z + 0.02. With the grip point at the bar's mid-height (0.008 below the bar's top), the eef would be at ~0.028 below the palm... \n\nHmm, actually, in the current grasp the eef is at the bar's top (the grasp point is 1 cm above the fingertips, and the fingertips are at 0.002 while the bar's top is at 0.016). So the eef (0.012) is just below the bar's top (0.016). The palm is 2-4cm above the eef. So the bar's top is ~2cm below the palm. Not touching.\n\nIf the bar slides UP through the fingers by 2cm, its top would hit the palm. But the bar slides DOWN under gravity.\n\nHmm, what if I lift the bar with a fast upward acceleration so the fingers' friction drags the bar up until it hits the palm? The impact would stop the bar and it would be pressed against the palm — providing a solid, rotation-resistant grip (pinched between the palm and the fingers)! But the fingers' pinch is on the bar's sides, and the palm normal is vertical. Combined with the fingers' horizontal normals, the bar would be pressed up against the palm. Then a pitch rotation would require lifting one end away from the palm → resisted!\n\nThat's actually a plausible trick! And a quick upward motion at the start of the lift could do it: accelerate up fast (the bar lags, the fingers drag it up via friction).\n\nBut there's a catch: the bar would be pressed against the palm at one end only (if pitched)... whatever.\n\nImplementation: the bar is on the table, gripped at the center (eef at 0.012, the fingertips at 0.002). To push the bar up against the palm, I'd need it to slide up 2+cm. Hmm, the eef would need to be lower (the fingers' palm closer to the table). Actually, if I grip the bar at its VERY TOP (the fingertips at 0.015, i.e., at the bar's top), the palm is ~2cm above the eef = 0.035, so the bar's top would touch the palm only after sliding up 2cm.\n\nAlternatively, set the palm height to match: the palm is at a fixed offset above the eef. If I position the eef such that the palm is at the bar's top: the palm ≈ eef + 0.025 (a guess) → the eef at 0.016-0.025 = -0.009 (below the table). Not possible.\n\nHmm, so the palm can't be brought down to the bar's top while gripping.\n\nUnless the fingers grip the bar's sides with the bar at the palm! I.e., the eef at z such that the palm is at the bar's top: the eef z = bar_top - 0.025 = -0.009. Not possible.\n\nOK, that idea is dead.\n\nGiven the situation, I'll finish with the best available state. Actually, let me reconsider the pitch's magnitude: maybe it's smaller than I think. The agentview's apparent 40° includes the perspective effects of a yaw-free pitch. The true pitch ~26-35°.\n\nWith 3 commands left, let me do something reasonable: lower the bar to the table, re-grasp at the center, and lift to 0.13 with an accelerated motion (hoping the bar stays more level), then finish. It's a gamble but uses the commands.\n\nActually, the lift from s031 (1.6cm) showed 5°. Hmm, what if the pitch develops because of the ARM'S UPWARD MOTION and I lift in very small steps with pauses (each command = a separate motion with a stop)? The rotation developed during a single 12cm motion. With 2cm steps and a pause... each step would still add ~3°/cm.\n\nHmm, unless the rotation is TIME-dependent (a slow creep under gravity) rather than distance-dependent. At s031 (1.6cm, after a 3s slow move) the tilt was 5°. If it were time-dependent at 2°/s, 3s would give 6° ✓. Then the 12cm lift at 0.005 m/s = 24s → 48°. Observed 40° ✓. So it could be either.\n\nIf it's TIME-based (a creep), then a FAST lift would reduce the tilt! Let me try a fast lift: from the table to z=0.145 at the max speed (the default). The motion would take ~0.3s → the tilt might stay <8°!! That's a real possibility worth testing!\n\nEarlier, s010's lift went 0.033→0.0966 at 0.05 m/s (1.3 s) → a 25° tilt. That's ~19°/s. s027's 0.013→0.10 at 0.03 m/s (2.9 s) → 35° (12°/s). s036: 0.013→0.142 at 0.005 (26 s) → 40° (1.5°/s). Hmm, so it's not a constant rate; the fast ones had HIGHER rates. So it's not a linear time creep. It looks like the tilt saturates at ~35-45° regardless.\n\nAt s031 (1.6cm at 0.005 m/s, taking ~3s) the tilt was 5°... inconsistent with a 1.5°/s creep (which would give 4.5° ✓ actually consistent!). And s036: 26s * 1.5 = 39° ✓. s010: 1.3s at 19°/s = 25 ✓. The rate varies.\n\nI'll take the gamble: a FAST lift might keep the tilt low. Let me do it with the remaining commands:\n\n1. Lower the bar to the table + open: move z=0.05 gripper=open speed=0.1 (the bar drops; it's currently at (0.5014,0.1655) — after the drop it'll be near there).\n2. Grasp: I need the bar's position after the drop. I must measure it (I have no commands to spare for a separate observation — actually, every move command returns images, so command 1 gives me the bar's position). Then command 2: move to the bar (x,y) with z=0.012 and close.\n3. Lift FAST: move z=0.15 (default speed).\n4. Finish.\n\nThat's 3 robot commands + finish = 4 commands, but I only have 3 left. Budget: \"at most 40 robot commands\". Finish might not count? It says the attempt ends when you run finish or the budget is used up. To be safe, count finish as a command: 3 left → lower+open (1), grasp (2), lift (3), then finish would exceed... Actually, \"budget_left\" decrements with each command; finish may or may not. Risk: if I use all 3, the budget is exhausted and the attempt ends automatically with the bar possibly still on the table (a fail).\n\nHmm. Let me prioritize: the lift must happen. So I have 3 commands: lower+open, grasp+close, lift. Then the attempt ends (the budget exhausted) — is that OK? The attempt ends when the budget is used up. Hmm, then the evaluation happens. But \"keep holding it when you finish\" — if the attempt auto-ends, presumably the state is evaluated.\n\nRisky: if the auto-end occurs at the end of the last command, the bar would be held at whatever state. That might be acceptable.\n\nBut I'd rather leave a margin for the finish command. Let me plan: \nCommand 1: lower to z=0.05 + open (the bar falls to the table). → 2 left\nCommand 2: move to the bar's estimated position with z=0.012 + close. But I won't have seen the bar's post-drop position before this command! The image from command 1 lets me estimate it (the bar's x from the wrist, y from the agentview). Since the bar is currently held and I know the eef's position, when I open at z=0.05, the bar will fall nearly straight down (it was gripped at its center). So its position after the drop ≈ its current xy: x≈0.50 (the eef's x... the bar's x ≈ the eef's x), y ≈ 0.1655 + (the bar's offset from the grip). From s037: the bar's center along the grip: the grip is at ~40% from the upper-right end... the bar's center is at y = eef_y + (offset). Ugh.\n\nSince the bar is pitched, lowering it to 0.05 will make its lower end touch the table first and the bar will rotate/flop. It may shift by a few cm.\n\nToo risky to grab blind. And 3 commands is not enough for a careful re-grasp + lift.\n\nALTERNATIVE: keep the current hold and just finish (3 commands to spare, but no better state). Since the current state is a bad tilt, the attempt fails.\n\nGiven the constraints, let me evaluate: the probability of success with a blind re-grasp + fast lift is maybe 10-20%; with the current state, ~0-5% (if the tilt is somehow < 8°). I'll go for the re-grasp + fast lift.\n\nActually WAIT. There's a subtlety I should exploit: the bar's position after lowering. Let me lower it in a controlled way: instead of releasing at 0.05, I can lower to z=0.012 (the grasp pose!) and open there — the bar will be right at the grasp point, so the gripper is already correctly positioned in x! Then the bar may shift in y a bit when released, but x would be preserved. Then I close again at the same x (with the same y). Since the gripper is already at the right place, closing again re-grips it. No visual check needed!!\n\nThat's clever: \nCommand 1: move z=0.012 gripper=open (lower the held bar and release it at the grasp pose). The bar will settle on the table; since the gripper is at the previous grasp point, the bar is likely still between the fingers (it was gripped there).\nCommand 2: move gripper=close (re-grip at the same place). Note: if the bar shifted during the release, the re-grip might miss. But the drop is tiny (the eef goes from 0.145 → 0.012; the bar's lower end is already at ~0.05, so it drops a bit and rotates to flat, possibly shifting in y by a few cm! Hmm. Because it's pitched, as it lowers, the low end hits the table and the bar rotates about that end, sliding the other end... the high end (at +y) would come down, rotating the bar around, and the grip's contact would slide along the bar. After it settles flat, the bar's center might be offset from the grip by ~3-5cm in y.\n\nThen re-closing at the same y might grip the bar at 3-5cm off-center. Risky but within tolerance (the bar is 20cm).\n\nCommand 3: move z=0.15 (fast, default speed) → lift.\nThen finish (the budget would be exhausted at 0... hmm).\n\nLet me count exactly: budget_left = 3 commands now. If finish is free or counted, I'd be at 0 after 3 commands. The attempt ends when the budget is used up. So the last command (the lift) would be the 40th → the attempt ends automatically and is evaluated. The instruction says to reply with a report when the robot says the episode is over.\n\nHmm, but the auto-end might happen right after the command completes, and the evaluation would occur at the held state. That's what I want (if the tilt is small).\n\nAlternatively, skip the re-grasp and finish now. No — the current state is definitely bad.\n\nLet me go with the 3-command plan. Actually, I realize command 1 (lower to 0.012 with the bar) risks smashing the tilted bar into the table (the bar's lower end is ~9cm below the eef; at eef z=0.012, the lower end would be at -0.08 → it would penetrate/be pushed). But the physics would resolve: the bar's lower end hits the table and the bar rotates flat as the gripper descends. It's a slow, controlled descent at a given speed. Use speed=0.02 to be gentle (3-6s).\n\nWait, sim time: 41 s left, plenty.\n\nLet me execute:\nCommand 1: move_eef z=0.012 gripper=open speed=0.02.\nThen look." + ], + "shell": [ + "cd /opt/lffjail/work && timeout 50 python3 - <<'EOF'\nfrom PIL import Image\nim=Image.open('obs/s037_agentview.jpg')\nim.crop((320,110,440,300)).resize((480,760)).save('obs/s037_crop.png')\nEOF" + ], + "viewed": [ + "obs/s037_agentview.jpg", + "obs/s037_wrist.jpg", + "obs/s037_crop.png" + ] + } + }, + { + "attempt": 1, + "step": 39, + "kind": "move_eef", + "frame_start": 1842, + "frame_end": 1872, + "command": "move_eef y=0.209 z=0.012 yaw=90 gripper=close speed=0.06", + "args": { + "y": 0.209, + "z": 0.012, + "yaw": 90, + "gripper": "close", + "speed": 0.06 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.0, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.5036, + 0.2088, + 0.0123 + ], + "gripper_width_after": 0.0411, + "holding_after": true, + "touched_during": true, + "think_s": 15.981555938720703, + "agent_obs_images": [ + "obs/s039_agentview.jpg", + "obs/s039_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The bar is on the table, level, and the gripper is right over it! In the agentview, the bar spans 312-478 (center 395) and the gripper is at ~360. So the bar's center is +35 px (4.2cm) +y of the gripper. Hmm.\n\nThe wrist: the bar spans x 182-348 → center 265 vs the grasp axis 255 → the bar is ~10 px right → x = eef - 10*(d/281)... d≈0.078 → 2.8 mm. Good x.\n\nSo the y offset is ~4.2cm off-center. If I close now, I'd grip at 4.2cm from the center → the bar would tilt more.\n\nI have 2 commands left. Options:\n(a) move y+0.042 + close (1 command), then lift (1 command). That's exactly 2!\n(b) close + lift.\n\nOption (a) is better. But moving y by 0.042 at z=0.015 with the fingers OPEN (0.0777) would sweep the fingers past the bar's side — the open fingers (at ±0.039) span the bar's width... wait, with yaw=-90 the fingers are separated along x, so moving in y doesn't sweep along the bar's width; the open fingers at x=eef±0.039 move along y, straddling the bar (which is 4cm wide in x, i.e., x from eef-0.02 to eef+0.02 — the fingers at ±0.039 are clear of the bar). So moving in y is SAFE ✓ (the fingers pass on either side of the bar).\n\nSo: command 1: move_eef y=0.1667+0.042=0.209, z=0.012, gripper=close, speed=0.05.\nHmm, but the finger OPEN width 0.0777 → the pads at ±0.0389; the bar spans ±0.02 → a clearance of 1.9cm each side ✓.\n\nThen command 2: lift fast to z=0.15 (default speed ~the fastest).\n\nThen the budget is exhausted → the attempt ends automatically. Ugh, I won't be able to \"finish\" properly. Let's hope.\n\nHmm, is it better to spend the last command on the finish instead of the lift? No — without the lift, the bar is on the table = a definite fail.\n\nGo." + ], + "viewed": [ + "obs/s038_agentview.jpg", + "obs/s038_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 40, + "kind": "move_eef", + "frame_start": 1872, + "frame_end": 1881, + "command": "move_eef z=0.15", + "args": { + "z": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5044, + 0.2088, + 0.1471 + ], + "gripper_width_after": 0.041, + "holding_after": true, + "touched_during": true, + "think_s": 11.622590780258179, + "agent_obs_images": [ + "obs/s040_agentview.jpg", + "obs/s040_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The gripper is now at u≈385 and the bar spans 312-478 (center 395). So the gripper is at 10 px = 1.2cm -y of the bar's center. Good enough (a nearly centered grip). The width closed to 0.0411 = the bar is gripped.\n\nOne command left. Lift fast to maximize the chance of a level hold. The last command → the budget will be used up and the attempt ends. Let me lift to z=0.15 at the fastest speed (omit speed).\n\nThe bar's lowest point must be ≥0.10. With the eef at 0.15 and the bar's bottom ~0.016 below the grip center... The eef's grasp point is at the bar's top (z_eef 0.0123 ≈ the bar's top 0.016). So the bar's bottom is ~0.016 below the eef → at eef 0.15, the bar's bottom is ~0.134 ✓ (if level).\n\nGo: move_eef z=0.15 (the fastest)." + ], + "viewed": [ + "obs/s039_agentview.jpg" + ] + } + } + ], + "task_events": [], + "frames": { + "n": 1911, + "fps": 20, + "image_res": 256, + "phase_codes": { + "move": 0, + "gripper": 1, + "judge": 2 + }, + "initial_state": { + "eef_pos": [ + -0.20846466056582413, + -2.855035580753994e-14, + 1.1732794757296403 + ], + "joint_pos": [ + 4.2543575521367217e-14, + -0.16103738899999992, + -3.5853834950269897e-14, + -2.44459747, + -2.986627119830784e-13, + 2.2267522, + 0.7853981633973531 + ], + "gripper_qpos": [ + 0.020541867755816158, + -0.02054184665779552 + ] + } + }, + "episode_index": 1274, + "dataset_index_range": [ + 2172408, + 2174319 + ], + "label_provenance": { + "task_cause_source": "leaf/release/evidence/causes.json", + "recovery_review_source": "leaf/release/label_audit.jsonl", + "recovery_review_applied": true + } +} diff --git a/leaf/annotations/episode_001646.json b/leaf/annotations/episode_001646.json new file mode 100644 index 0000000000000000000000000000000000000000..055ad999af288b9d296fa439b16596d118407b85 --- /dev/null +++ b/leaf/annotations/episode_001646.json @@ -0,0 +1,1042 @@ +{ + "schema": "leaf-replay-1", + "source": { + "batch": "ds41_dsh_s2", + "run": "ds41_dsh_s2-deepseek-v4.1-flash-dsh-harness-hidek_l3_under_table_tool_s3001_full_F1_direct_k3_1030-164407_p17000", + "attempts_in_episode": [ + 3 + ], + "episode_in_run": 2, + "condition": "with_history", + "memory_free_chain_of": null, + "memory_free_rep": null, + "feedback_level": "F1", + "hide_k": true, + "k": 3, + "perception": "rgb", + "instruction_variant": "direct", + "contract_sha256": "013068fc761974cb7ca6e25566c2f9573ac89bd8e69a1cd7f931473f4681c1d7", + "run_status": "done", + "manifest_id": "0004", + "replay": { + "n_reports_checked": 66, + "n_mismatch": 0, + "max_eef_dev_m": 0.0 + }, + "backfill_provenance": { + "original_run": "/mnt/cpfs/workspace/agentic-robotics/lffbench/runs/api/ds41_dsh_s2/ds41_dsh_s2-deepseek-v4.1-flash-dsh-harness-hidek_l3_under_table_tool_s3001_full_F1_direct_k3_1030-164407_p17000", + "frozen_run": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_backfill_20261102/source/runs/api/ds41_dsh_s2/ds41_dsh_s2-deepseek-v4.1-flash-dsh-harness-hidek_l3_under_table_tool_s3001_full_F1_direct_k3_1030-164407_p17000", + "runtime": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_backfill_20261102/source" + }, + "evaluation_config": { + "cond": "harness", + "arm": "none", + "red_team": false, + "feedback": "F1", + "mem": "full", + "k": 3, + "rep": 0, + "dossier": null, + "task": "l3_under_table_tool", + "seed": 3001 + }, + "release_origin": { + "dataset": "v1.5", + "episode_index": 1646 + }, + "release_episode_index": 1646, + "pre_v181_sidecar_index": { + "episode_index": 21, + "dataset_index_range": [ + 34077, + 36606 + ] + } + }, + "agent": { + "harness": "dsh", + "harness_version": "0.2.1-rc.5", + "harness_binary_sha256": "904a6d3484241d466989f9df9ba3aab822b1496191bdb28230eb491a55c32a52", + "model": "deepseek-v4.1-flash", + "effort": "high", + "provider": "deepseek", + "codex_catalog": null, + "auth": null, + "jail": true + }, + "task": { + "name": "l3_under_table_tool", + "level": "L3", + "family": "hidden_variable", + "category": "strategy_switching", + "capabilities": [ + "Perceive", + "Reason", + "Plan" + ], + "protocol": "cross", + "max_attempts": 5, + "agent_max_steps": 40, + "instruction": "Put the red cube into the gray bin.", + "seed": 3001, + "instance": { + "seed": 3001, + "table_xy": [ + -0.07020408847291715, + 0.06382146785508948 + ], + "cube_xy": [ + -0.06581179892381064, + 0.05514854963863054 + ], + "side": -1, + "pane_side": 1, + "stick_xy": [ + -0.0577735313267551, + -0.16331702340869625 + ], + "stick_yaw": 1.634673122362253, + "bin_xy": [ + -0.07510919372121073, + 0.2370035074542604 + ] + }, + "paper": { + "name": "Under-table tool", + "cause": "L4", + "table_cause": "L4", + "hidden_variable": "Invisible side panel", + "repair_within_attempt": true, + "oracle_first_attempt_pct": "100", + "naive_first_attempt_pct": "0", + "original_cause": "L4", + "original_table_cause": "L4" + }, + "canonical_cause": "L4", + "paper_long_horizon": false, + "instruction_original": "Put the red cube into the gray bin." + }, + "run_outcome": { + "outcome_class": "F", + "attempt_history": "FFF", + "n_attempts": 3, + "run_success": false, + "agent_final_report": "The episode is over — all three attempts failed. Final report:\n\n## What I did (key commands & parameters)\n\n**Attempt 1 & 2 (both ended by exhausting the 120 s motion budget):**\n- Calibrated the wrist camera by translating the eef: ~990 px/m lateral scale at z≈0.26; +x → image down, +y → image right.\n- Fitted the wrist camera's extrinsics from 7 (eef pose, target pixel) pairs: f≈352 px, camera offset ≈ **(+5.4 cm x, 0, +11.1 cm z) from the grasp point**, near-vertical but slightly tilted view.\n- Calibrated the fixed agentview: **scale ≈5.8 px/cm, elevation ≈39°, dv/dx ≈ +400 px/m, dv/dz ≈ −500 px/m, u ↔ y**.\n- Ran many grasps: descents with `move_eef` to (0.558,0.056), (0.600,0.063), (0.627,0.057), (0.617,0.053), (0.65,0.053), (0.672,0.054), (0.73,0.043), (0.537,0.036) with yaw 0/45/90/−90, open and closed grippers, followed by `gripper=close` checks.\n\n**Attempt 3:** repeated the agentview calibration with 4 controlled moves (x=0.50/0.62/0.73 at z=0.15, then z=0.10), scanned y at x=0.60 (y=0.03/0.06/0.09), descended at candidate cube positions, and finished with a descent to (0.53, 0.05, 0.05) — the motion budget (120 s) expired.\n\n## What I observed\n- The **wrist camera never sees the red cube** at most poses — it sits ~5 cm ahead of the grasp point in x, so the cube (behind it) is outside its field of view. This caused every early miss (\"cube centered in the wrist view\" put the gripper 5 cm behind the cube).\n- The cube is ~4.2 cm wide, on the table at roughly **(x ≈ 0.55–0.60, y ≈ 0.05)**, with its **top at z ≈ 0.0675**.\n- Behind the cube is a **raised platform/plate whose surface is also at z ≈ 0.0675** (with 4 posts); the cube's top is **flush** with that surface.\n- Near that area the arm bottoms out at **fingertip z ≈ 0.0675** (every descent stopped 0.8–5 cm short), while farther out (x=0.40, y=0.10) it reaches z≈0.02. Every close therefore returned ~0.002 m (empty) — the fingers never got below the cube's top.\n- Twice the IK flipped branches (wrist joints jammed at j6=3.75, j7=2.90 rad), costing time; I recovered by commanding yaw=−90 at a high z.\n\n## Feedback\nThe environment reported \"Attempt failed\" after each attempt. No success.\n\n## How I changed my approach\nAttempt 1: naive visual servoing on the wrist camera → failed (camera offset unknown). Attempt 2: derived the wrist camera's extrinsics and agentview parallax by fitting, identified the coordinate-frame confusions, but mis-located the cube in x. Attempt 3: rebuilt the agentview calibration from scratch with controlled moves, found the cube's correct location and the fact that a raised platform flush with the cube's top blocks any top-down approach.\n\n**For a future run I would:** (1) calibrate the agentview's parallax with 3 moves up front (dv/dx≈+400, dv/dz≈−500 px/m) — never rely on the wrist camera for absolute position; (2) first push the raised platform (its 4 posts give leverage) or sweep it aside so the fingers can descend below z=0.0675 next to the cube, then grip it with the fingers straddling it (open 7.9 cm ≫ cube 4.2 cm) and carry it to the bin at y≈0.23.", + "mean_think_s": 43.28, + "outcome_class_original": "F", + "outcome_class_status": "rule_derived" + }, + "attempts": [ + { + "attempt": 3, + "success": false, + "outcome": { + "success": false, + "mode": "blocked", + "moved": 0.0, + "under": true, + "cube_rel_bin": [ + 0.009297394797400091, + -0.18185495781562988 + ], + "stick_used": false, + "terminal": false, + "cube_hit_pane": false, + "stick_hit_pane": false, + "robot_hit_pane": false, + "detail": "The hand ran into the edge of the glass top of the low table (fingertips 7.6 cm above the tabletop, gripper 4.2 cm outside the edge) and could not move in under the glass. The cube did not move; it is still under the low table." + }, + "finish_reason": "motion budget used up (automatic)", + "feedback_shown": "Attempt failed.", + "auto_ended": true, + "think_s": 13.567267179489136, + "feedback_f2": "Attempt failed. The hand ran into the edge of the glass top of the low table (fingertips 7.6 cm above the tabletop, gripper 4.2 cm outside the edge) and could not move in under the glass. The cube did not move; it is still under the low table.", + "judge_frames": [ + 2499, + 2529 + ], + "corrected_later_in_run": false, + "is_last_attempt_of_run": true, + "error_event_in_attempt": null, + "reviewed_operational_failure": null + } + ], + "commands": [ + { + "attempt": 3, + "step": 2, + "kind": "move_eef", + "frame_start": 0, + "frame_end": 26, + "command": "move_eef x=0.5 y=0.05 z=0.15 gripper=close speed=0.3", + "args": { + "x": 0.5, + "y": 0.05, + "z": 0.15, + "gripper": "close", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4989, + 0.0499, + 0.1519 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 26.28617572784424, + "agent_obs_images": [ + "obs/a3_s002_agentview.jpg", + "obs/a3_s002_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Attempt 3 with a fresh budget. Let me first calibrate the agentview rigorously with controlled moves." + ], + "reasoning": [ + "Attempt 3: fresh 40 commands, 120s.\n\nI MUST do this properly now. Let me plan carefully.\n\nPlan:\n1. FIRST: calibrate the AGENTVIEW properly with 3-4 well-chosen moves at a fixed z, measuring the fingertips' pixel precisely each time (I'll use cross-correlation/template matching between images with the same gripper state to find the finger's shift — the fingers look identical when the gripper state and orientation are the same, so template matching on a small patch around the fingertip should work IF the arm's appearance near the fingers doesn't change much).\n\nActually, a cleaner approach to measure the fingertip pixel in the agentview: use the CLOSED gripper (a distinct thin shape) and template-match a patch from a reference pose. The fingers' appearance should be nearly identical across poses (same orientation, closed). The lighting/shading might differ slightly but a normalized cross-correlation should find matches.\n\nBetter: I'll do a series of moves at the SAME z but different x/y, and template-match the fingertip patch across them → get (u,v) for each pose → then fit the agentview's affine projection:\nu = a0 + a1*y (almost purely y)\nv = b0 + b1*x + b2*z\n\nWith ≥3 poses I can fit b1, b2 and the x-position of the cube.\n\n2. Then compute the fingertip position needed to be over the cube: v_tip(x_cube, z_tip) = v_cube_top.\nBut we need x_cube and z_top. Two unknowns, one equation (v). The u equation gives y_cube.\n\nWe can get z_top from a physical touch: descend at the cube's (x,y) with the closed gripper → the stop's z gives the tips' z = z_top → eef z = z_top+0.01. But we need x_cube first — a chicken-and-egg. \n\nSolution: iterate! \nStep A: assume a z_top (e.g., 0.0675), compute x_cube from the v equation, then descend at (x_cube, y_cube) with the CLOSED gripper and observe the stop: if the stop is right at the cube's top, we're aligned. Adjust as needed.\n\nAlternatively, exploit that the closed-finger descent gives a \"cube found\" signal (a stop well above the table). By scanning x at y=y_cube, I can find the cube's x edge. With the agentview guiding me within ~1-2cm, only 1-2 probes are needed.\n\n3. Once aligned, use the OPEN gripper to descend and close.\n\nBut the CRITICAL unresolved issue: at x∈[0.55,0.68], the descent stopped at the fingertips' 0.0675 — that mystery block. If the cube is at x≈0.73 (beyond that region), then that block was something else (the frame). Then at x=0.73 the arm might descend lower and reach the cube ✓.\n\nSo the first thing to test: descend at (0.73, 0.05) with the closed gripper to z=0.03. If it reaches ~0.03 → no block there. If the cube is there, the stop would be at z_top+0.01.\n\nGiven the fresh budget, let me be systematic:\n\nStep 1 (1 command): move to (0.73, 0.05, 0.15), closed, speed 0.25. Then look at the agentview and compare the fingertip's v to the cube's v to refine x.\nStep 2: descend to 0.03 slowly → find the cube or the table.\n\nAlso, importantly: the bin. The bin's y ≈ +0.2 (from the wrist images earlier), x ≈ ? The bin in the agentview is at u 355-440, v 255-340. Using dv/dx = +262 and the scale... the bin's x ≈ the cube's x + (the v difference). The bin's v range 255-340 (center ~300) ≈ the cube's v (315) → so the bin's x ≈ the cube's x ✓. And the bin's y: u 355-440 (center 397) vs the cube's u=290 → Δu=107px. The u scale: ~5.8px/cm (horizontal, at that depth) → Δy = 107/5.8 = 18.5cm → y_bin ≈ 0.05+0.185 = 0.235.\n\nSo the bin is at (x≈same as the cube, y≈0.235).\n\nLet me start. Actually, to save time, let me FIRST do the pure-software work: analyze the existing a3_s001 images (the same as the initial state) — no new info.\n\nLet me just execute:\nCommand 1: move_eef x=0.73 y=0.05 z=0.15 gripper=close speed=0.25.\n\nHmm, but wait: is x=0.73 even reachable? The arm's max reach is 0.855 from the base. At z=0.15, x=0.73 → the distance = 0.745 ✓ reachable.\n\nLet me go. And I'll examine the agentview image after the move to calibrate the relationship in one shot: I'll know (x=0.73, y=0.05, z=0.15) and the fingertip's pixel; combined with the initial pose's fingertip pixel (x=0.4515, y=0, z=0.2613 — sneaky: the fingers at that pose are at a different yaw/state, but I can use a two-step calibration).\n\nActually, the cleanest: do 3 moves at the SAME z (0.15) and the same y, varying only x: x=0.50, 0.60, 0.70 (closed). That gives dv/dx accurately. Then one move down at the same x,y (z=0.10) gives dv/dz.\n\nThat's 4 commands + image analysis. Then the cube's x follows from the v equation once I assume z_top... which I can get from a touch.\n\nHmm, but I can also get z_top from the AGENTVIEW by measuring the cube's apparent height! The cube's front face spans 15px with a height of H=4.2cm → sin(elev)*scale = 15/4.2 = 3.57 px/cm. And the top face spans 19px over a 4.2cm depth → cos(elev)*scale = 4.52. So scale=5.76, elev=38.4°. These are consistent ✓ so I trust the agentview's scale ~5.8px/cm and elev~38.4°.\n\nNow, with the camera fixed: v = vp + scale*(-cos(elev)*x_camrel... let me define the camera's frame: the camera looks along the direction d = (cos(elev)*px, 0, -sin(elev)) where px is the horizontal direction toward the scene... For a pinhole camera, the image's vertical coordinate v relates to the angle: v - vp ≈ scale*(the perpendicular offset)/(the depth). For small offsets, v - vp ≈ -scale*cos(elev)*(x - x_ref)... hmm.\n\nPractical: from the two calibration moves I get dv/dx and dv/dz empirically, plus dv/dy (≈0 for v). And du/dx (≈0), du/dy (the horizontal scale), du/dz (≈0).\n\nThen: for the cube's top center (x_c, y_c, z_t) and the fingertips (x_f, y_f, z_f):\nv_f = v_c requires: 262*(x_f-x_c) + 360*(z_f-z_t) = 0 (using the empirical coefficients).\nu_f = u_c requires: y_f = y_c.\n\nAnd with an additioinal touch to get z_t (a descent at the cube's x yields a stop = z_t+0.01), I can solve.\n\nProcedure:\nA) 3 calibration moves for dv/dx (at z=0.15, y=0.05, x=0.50/0.60/0.70), closed.\nB) 1 move down at x=0.60 for dv/dz (z=0.10).\nC) Compute x_c = x_f - (v_f - v_c)/dv_dx ... hmm, we need z_t. Alternatively, do this: descend at x=0.60 (the current) with the CLOSED gripper as low as possible and note the stop → that's either the cube's top or an obstruction. Hmm.\n\nAlternatively, do the two-unknown solve using two different z's of the fingertips: at a fixed (x_f, y_f) and two z's, the fingertips' v changes (dv/dz). The cube's v is fixed. Setting v_f = v_c at a specific (x_f, z_f)... one equation, two unknowns (x_c, z_t) — still underdetermined.\n\nBUT: the touch gives z_t directly. To touch I need x_cube. Iterate: guess z_t=0.0675 → compute x_c; descend at (x_c, y_c) with the closed gripper → observe the stop. If the stop = 0.0775 (the tips at 0.0675), then z_t = 0.0675 ✓ consistent → and the fingers are on the cube's top → CONFIRMED alignment. If the stop is lower (~0.02) then no cube at x_c → adjust (and if the stop is higher, z_t is higher).\n\nThat's a solid plan: at most 2-3 iterations.\n\nThen the grasp: with the OPEN gripper at the cube's (x,y), descend. If the descent is blocked at some z > the cube's mid-height, it means the fingers hit something (the frame). In that case, try yaw=90 or a different approach.\n\nLet me START. Command 1: move_eef x=0.50 y=0.05 z=0.15 gripper=close speed=0.25.\n\nHmm, actually since the initial pose is (0.4515, 0, 0.2613) with the gripper at 0.0411 (half-open), let me do the calibration moves with the gripper CLOSED for consistency.\n\nLet me batch: \nC1: move_eef x=0.50 y=0.05 z=0.15 gripper=close speed=0.3\nC2: move_eef x=0.60 speed=0.2 (same y,z)\nC3: move_eef x=0.70 speed=0.2\nC4: move_eef z=0.10 speed=0.15\nThen analyze the 4 images → dv/dx, dv/dz, and the finger patch positions.\n\nThen C5: probe at the computed (x_c, y_c).\n\nLet's go. I'll view the images at the end via template matching.\n\nFor the template matching, I'll use the fingertip region from one image and match it in the others. The fingers are thin; let me instead use a LARGER patch including the hand's bottom and the fingers (the hand's bottom is distinctive). Different x → the whole hand translates; the appearance changes with the joints a bit," + ] + } + }, + { + "attempt": 3, + "step": 3, + "kind": "move_eef", + "frame_start": 26, + "frame_end": 52, + "command": "move_eef x=0.62 y=0.05 z=0.15 gripper=close speed=0.25", + "args": { + "x": 0.62, + "y": 0.05, + "z": 0.15, + "gripper": "close", + "speed": 0.25 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6167, + 0.0502, + 0.1507 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 6.622310161590576, + "agent_obs_images": [ + "obs/a3_s003_agentview.jpg", + "obs/a3_s003_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 3, + "step": 4, + "kind": "move_eef", + "frame_start": 52, + "frame_end": 78, + "command": "move_eef x=0.73 y=0.05 z=0.15 gripper=close speed=0.25", + "args": { + "x": 0.73, + "y": 0.05, + "z": 0.15, + "gripper": "close", + "speed": 0.25 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.7295, + 0.0502, + 0.1524 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 6.350321531295776, + "agent_obs_images": [ + "obs/a3_s004_agentview.jpg", + "obs/a3_s004_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 3, + "step": 5, + "kind": "move_eef", + "frame_start": 78, + "frame_end": 103, + "command": "move_eef z=0.1 speed=0.15 gripper=close", + "args": { + "z": 0.1, + "speed": 0.15, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.7263, + 0.05, + 0.0984 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 22.97817611694336, + "agent_obs_images": [ + "obs/a3_s005_agentview.jpg", + "obs/a3_s005_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Now let me analyze the fingertips' pixel in these 3 images (a3_s002: x=0.4989; a3_s003: x=0.6167; a3_s004: x=0.7295), all at y≈0.05, z≈0.151.\n\nI'll template-match a patch from s002's fingertip region into s003 and s004.\n\nThe fingertips for the closed gripper at z=0.151: the tips at z=0.141, projected at v ≈ ? From the earlier data at z=0.1975 the tips were at v=177. So at z=0.15, v ≈ 177 + (-dv/dz)*(0.141-0.1875)... let me just find them: in the tips10 analysis at z=0.1875 the tips were at orig y≈171-177. At z=0.141 (~4.6cm lower) with dv/dz ~+360 px/m → v increases by 17 → v≈190.\n\nu: at y=0.05, u≈289.\n\nLet me template-match a patch around (275-305, 165-205).\n\nLet me write the code with normalized cross-correlation over a search window.", + "The template match failed for s004 (a correlation of 0.47, a wrong match). For s003 (0.90) it's plausible: Δv = 46 for Δx=0.1178 → dv/dx = 390 px/m.\n\nSo dv/dx ≈ 390 px/m (the fingertips appear lower in the image as x increases). \n\nLet me verify s004 visually to find the fingertips. Given dv/dx=390, at x=0.7295 the tips should be at v = 185+390*(0.7295-0.4989) = 185+90 = 275. And u ≈ 292+25*0.23 = 298.\n\nThe match found (311.5, 192) with a low correlation — wrong. Let me crop s004 around (280-320, 250-290) and look.\n\nAlso, I need dv/dz. From the earlier a2 pair: s010 (x=0.5007,z=0.1975) → the tips at v≈177, and now s002 (x=0.4989,z=0.1519) → v=185. Δz=-0.0456, Δv=+8 → dv/dz = -175 px/m?? That seems small vs the theoretical +360.\n\nHmm, the \"tips at 177\" from the earlier tips10 estimate was crude. Let me instead measure dv/dz with a dedicated move: from the current pose (0.7295, 0.0502, 0.1524), move down to z=0.10 at the same x,y and template-match. That's 1 command.\n\nLet me also view s004 to verify the tips' location.\n\nPlan:\nCommand: move_eef z=0.10 speed=0.15 (at x=0.7295, y=0.0502)\nThen template-match s004→s005 for dv/dz.\n\nThen compute everything.\n\nLet me also check: is the cube near x=0.73? Let me look at the s004 agentview: where is the gripper relative to the cube? Let me view both." + ], + "shell": [ + "cd /opt/lffjail/work && python3 -c \"\nimport numpy as np\nfrom PIL import Image\nimport json\ndef load(s):\n return np.asarray(Image.open(f'obs/a3_s{s:03d}_agentview.jpg').convert('L')).astype(float)\nposes={2:[0.4989,0.0499,0.1519],3:[0.6167,0.0502,0.1507],4:[0.7295,0.0502,0.1524]}\nA=load(2)\nx0,y0,w,h=270,160,45,50\nT=A[y0:y0+h,x0:x0+w]\nT=(T-T.mean())/ (T.std()+1e-9)\nres={2:(x0+w/2,y0+h/2,1.0)}\nfor s in [3,4]:\n B=load(s)\n best=(-2,None)\n for dy in range(-70,71):\n for dx in range(-70,71):\n y1,x1=y0+dy,x0+dx\n if y1<0 or x1<0 or y1+h>512 or x1+w>512: continue\n S=B[y1:y1+h,x1:x1+w]\n S=(S-S.mean())/(S.std()+1e-9)\n c=(T*S).mean()\n if c>best[0]: best=(c,(x1+w/2,y1+h/2))\n res[s]=(best[1][0],best[1][1],best[0])\nfor s in res: print(s,poses[s],'tip px',res[s])\n# fit v = b0 + b1*x + b2*z using 2 pts same z -> b1 ; then use s002 with earlier z data? only same z here\nimport itertools\n(k2,k3,k4)=[(res[s][0],res[s][1]) for s in [2,3,4]]\n(x2,x3,x4)=[(poses[s][0],poses[s][2]) for s in [2,3,4]]\nprint('dv/dx from 2-3:',(k3[1]-k2[1])/(x3[0]-x2[0]))\nprint('dv/dx from 2-4:',(k4[1]-k2[1])/(x4[0]-x2[0]))\nprint('du/dx:',(k3[0]-k2[0])/(x3[0]-x2[0]),(k4[0]-k2[0])/(x4[0]-x2[0]))\n\"" + ] + } + }, + { + "attempt": 3, + "step": 6, + "kind": "move_eef", + "frame_start": 103, + "frame_end": 136, + "command": "move_eef x=0.7295 y=0.043 z=0.03 gripper=close speed=0.08", + "args": { + "x": 0.7295, + "y": 0.043, + "z": 0.03, + "gripper": "close", + "speed": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.7298, + 0.0434, + 0.0321 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 32.43204712867737, + "agent_obs_images": [ + "obs/a3_s006_agentview.jpg", + "obs/a3_s006_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Now the fingertips line up with the cube in the agentview (~1 cm). Let me probe the cube's top height there." + ], + "reasoning": [ + "Excellent! Now I can see (crop (260,240)-(340,330), 80x90 → 480x540, 6x):\n\nIn a3_s4 (eef x=0.7295, y=0.0502, z=0.1524, closed):\n- The hand's bright bottom plate at zoom y 170-190 → orig y = 240+28=268 to 240+31.7=272.\n- The fingers: the dark gray fingers at zoom (110-330, 265-390) → orig x = 260+18=278 to 260+55=315; orig y = 240+44=284 to 240+65=305. So the fingertips' bottom ≈ orig y=305, and the finger center u ≈ 296.\n- The CUBE: the mauve/pink top face at zoom (95-265, 320-395) → orig (276-304, 293-306); the dark red front face at zoom (115-265, 395-480) → orig (279-304, 306-320).\n\nWOW: the fingers (278-315, 284-305) OVERLAP the cube's top face (276-304, 293-306)!\n\nIn a3_s5 (eef z=0.0984):\n- The hand's plate at zoom y 330-360 → orig 295-300.\n- The fingers below at zoom (105-330, 450-540) → orig (277-315, 315-330).\n- The cube: not visible (hidden behind the fingers/hand? the crop shows the fingers at the bottom).\n\nSo the cube's v ≈ 300 (its top-face center) and the fingers at v=305 (their bottom) when the eef is at (0.7295, 0.0502, 0.1524).\n\nInteresting!! At s4 the fingertips' bottom (v=305) is essentially at the cube's top-face center (v≈300) — meaning the fingertips, if at the cube's height, would project at the cube's position...\n\nNow let me use the relation: at s4 the fingertips are at z=0.1424 and project at v=305. The cube's top center projects at v≈300.\nIf the fingertips were at the cube's x and z_top, they'd project at exactly the cube's v.\nGiven dv/dx = 390 px/m and dv/dz = ? (unknown), let's first get dv/dz from the s4→s5 pair:\ns4: (x=0.7295, y=0.0502, z=0.1524) → the tips at v=305\ns5: (x=0.7263, y=0.05, z=0.0984) → the tips at v≈330 (from the zoom, the fingers' bottom at orig y=330; but the image might cut off at 330 = the crop's bottom edge → the crop ends at orig y=330, so the tips might be below 330! Let me redo the crop lower.)\n\nLet me crop s5 lower (240-380) to find the tips.\n\nAlso, importantly: the fingers at s4/s5 are close to x=0.73 and the CUBE appears right there in the agentview! In s4 the cube's top face is at (276-304, 293-306) → center (290, 300), and the fingers are at (278-315, 284-305) → center (296, 295).\n\nSo the fingers are essentially AT the cube's top position in the image. The parallax difference: the fingers at z=0.1424 vs the cube's top at z_t. Δv = 305-300 = 5px = the \"fingers appear 5px lower\".\n\ndv/dz: if the fingertips were at the cube's x, then v_fingers - v_cube = dv/dz*(0.1424-z_t) → 5 = dv/dz*(0.1424-z_t). With dv/dz > 0 (a higher point → a smaller v → so dv/dz = +360 px/m from the theory): 5 = 360*(0.1424-z_t) → z_t = 0.128. Hmm, that would put the cube's top at 0.128 (a very tall cube on a platform).\n\nOr dv/dz = -360: z_t = 0.156.\n\nHmm, ambiguous. But the important thing: at x=0.7295 the fingers align with the cube's x (within the z ambiguity). Given the finger's v at the cube's top level would be v_cube=300 exactly when aligned.\n\nNow: is x_cube = 0.7295 or slightly different? The residual 5px ≈ 1.3cm at 390px/m. So x_cube ≈ 0.7295 ± 0.013 (depending on the z correction).\n\nSo the cube is at x ≈ 0.72-0.74 ✓ — my earlier estimate of 0.73 was right!\n\nGreat. Now, y_cube: the fingers' u center = 296, the cube's u center = 290 → Δu = -6px. The horizontal scale ~5.8px/cm at that depth → Δy = 6/5.8 = 1.0cm. And with du/dx = 25 px/m (small), the y correction: y_cube = y_eef + (u_cube - u_f)/scale_u = 0.0502 + (-6)/580 = 0.0502-0.0103 = 0.040.\n\nSo the cube is at about (x=0.73, y=0.04-0.05).\n\nNOW: the descent. At x≈0.73 the arm reached z=0.0984 with the closed fingers (in s5, no collision reported: the target 0.10 → 0.0984 ✓ reached). So the arm CAN descend to z=0.098 at x=0.726! Can it go lower? Let me try z=0.05. If the cube's top is at ~0.0675-0.11, the closed fingers would stop at the cube's top.\n\nLet me descend at (0.7295, 0.045) to z=0.05 with the CLOSED gripper and see where it stops. That gives the cube's top height ✓ and confirms the alignment.\n\nWait, careful: if the cube's top is at 0.0675 and I descend with the closed fingers, the stop is at the eef z=0.0775 ✓ expected.\n\nThen for the grasp: use the OPEN gripper at the same (x,y) — the fingers would straddle the cube and descend to the table (z≈0.01) → then close ✓.\n\nBut hold on: is the arm's minimum z at x=0.73 an issue? The fingers' tips reached 0.0884 at x=0.726 (s5). We don't yet know how low the arm can go there. In the earlier attempt-3 runs, at x=0.65 the descent stopped at the fingertips' 0.0675 (a block) — I had assumed it was the platform. Now with the cube at x≈0.73, the blocks at x=0.55-0.65 were indeed the platform/other stuff.\n\nSo: descend at (0.7295, 0.045) with the closed gripper, target z=0.03, slow → expect a stop at the cube's top (~0.0775) if aligned.\n\nOne command. Let's do it and observe." + ], + "shell": [ + "cd /opt/lffjail/work && python3 -c \"\nimport numpy as np\nfrom PIL import Image\ndef load(s): return np.asarray(Image.open(f'obs/a3_s{s:03d}_agentview.jpg').convert('L')).astype(float)\nA=load(4)\n# find fingertips in s004: predict v~275,u~298 -> crop and view\nImage.open('obs/a3_s004_agentview.jpg').crop((260,240,340,330)).resize((480,540),Image.LANCZOS).save('work/a3_s4.png')\nImage.open('obs/a3_s005_agentview.jpg').crop((260,240,340,330)).resize((480,540),Image.LANCZOS).save('work/a3_s5.png')\nprint('ok')\"" + ], + "viewed": [ + "work/a3_s4.png", + "work/a3_s5.png" + ] + } + }, + { + "attempt": 3, + "step": 7, + "kind": "move_eef", + "frame_start": 136, + "frame_end": 194, + "command": "move_eef x=0.53 y=0.035 z=0.12 gripper=open speed=0.2", + "args": { + "x": 0.53, + "y": 0.035, + "z": 0.12, + "gripper": "open", + "speed": 0.2 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5316, + 0.0348, + 0.1211 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 124.17641258239746, + "agent_obs_images": [ + "obs/a3_s007_agentview.jpg", + "obs/a3_s007_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Now I can read the scene correctly: the cube sits on the table *in front of* the raised platform, at about (x≈0.53, y≈0.035). Let me grab it." + ], + "reasoning": [ + "At (0.7298, 0.0434) the eef descended to z=0.0321 with NO collision (the fingertips at 0.0221). So there's NO cube at (0.73, 0.043)!\n\nHmm!! So the cube is not there either. But the agentview at s4 showed the fingers right at the cube...\n\nLet me look at the current agentview (a3_s006) — the gripper at z=0.032 near the cube — to see where the cube is now relative to the fingers. This is the best calibration moment (a low gripper, minimal parallax).\n\nLet me view it zoomed.", + "The hand is now blocking the view of the cube (the arm is at the cube's location, and the hand covers the area).\n\nLet me look at the full agentview at s006 to see where the cube is relative to the hand.", + "WHOA! The scene has CHANGED! Now:\n- The white frame (with the 4 posts) is GONE!\n- The cube is GONE from its original spot!\n- The stick (the hammer) is still there at the left, but now it's oriented differently (pointing right, at a higher position).\n- The bin is now at the upper right (closer to the arm).\n\nHmm, the scene looks different: the bin is now at (370-480, 255-340) and the stick at (75-330, 290-320). No white frame, no cube visible.\n\nWait, did my arm sweep destroy/move things? The arm went from x=0.5 to 0.73 at z=0.15, then descended at (0.73, 0.043). Along the way (at z=0.15) it passed over things. Hmm, but where did the frame go?!\n\nHold on — maybe the camera view changed? No, the agentview is fixed.\n\nOH WAIT. I see — in this image the hand is at the center (x_pix 220-340, y 270-350) and it's LOW (z=0.032), so the hand is large in the view. And the white frame was previously at (250-345, 255-345) — the region now covered by the hand! And the cube at (278-303, 308-323) — also covered by the hand.\n\nSo the frame and cube are behind/under the hand in this view. The hand at z=0.032 (low) appears large and covers them.\n\nAnd the hand is AT (0.73, 0.043) — which is where the frame+cube appeared before. So the hand is right there. But the fingers reach the fingertips at 0.022 without hitting the cube... \n\nWait, the FINGERS: in the image the fingers are at (275-310, 350-375) — below the hand.\n\nHmm, and the earlier crop (a3_s6.png) showed the hand. The frame/cube should be right under/behind it.\n\nHmm, so at (0.7298, 0.0434, 0.0321) the arm didn't hit the cube — but the agentview says the cube is right there.\n\nCONTRADICTION — unless the cube is at a different (x,y) than the agentview's v-based estimate suggests (the parallax again).\n\nUgh! Notice: in this s006 image, the fingers are at v≈350-375 and I can't see the cube (hidden).\n\nLet me consider the possibility that the agentview's v-dependence is dominated by z (a high z → a high v?). Let's test with the s4 vs s6 pair: the same x,y (0.7295, 0.043) with z=0.1524 → the fingertips at v=305; z=0.0321 → the fingertips at v≈365. So Δz = -0.12 → Δv = +60 → dv/dz = -500 px/m (a lower z → a lower position in the image... i.e., v increases as z decreases) ✓ physically sensible: lowering the fingers makes them appear lower in the image.\n\nWait, that's the OPPOSITE of what I assumed earlier (+360). Let me recheck: dv/dz = -500 px/m means a HIGHER point has a SMALLER v ✓ (higher in the image) — yes that's what I said. So dv/dz = -500.\n\nAnd dv/dx = +390 (a larger x → a larger v, i.e., lower in the image).\n\nNow: the cube's top center at v_c=300, u_c=290.\nAt s4 the fingertips were at (v=305, z=0.1424, x=0.7295).\nSetting v_f = v_c: 305 + 390*(x_f-0.7295) - 500*(z_f-0.1424) = 300 where (x_f, z_f) is the fingertip position when aligned: x_f = x_c, z_f = z_t (if the fingertips are at the cube's top).\n→ 390*(x_c-0.7295) - 500*(z_t-0.1424) = -5.\nIf z_t = 0.042: 390*(x_c-0.7295) - 500*(-0.1004) = -5 → 390*(x_c-0.7295) + 50.2 = -5 → x_c = 0.7295-0.1415 = 0.588.\nIf z_t = 0.0675: 390*(x_c-0.7295)+37.5 = -5 → x_c = 0.6205.\nIf z_t = 0.11: 390*(x_c-0.7295)+16.2 = -5 → x_c = 0.675.\n\nSo x_cube = 0.59-0.68 depending on the cube's height! And with the cube on the table (z_t=0.042): x_cube = 0.588.\n\nHmm. And at x=0.588 the arm was blocked at the fingertips' 0.0675 (which I now realize is ABOVE the cube's top of 0.042 → so the block at 0.0675 was the white frame/platform!).\n\nSo the cube at (0.588, 0.04) [on the table, in front of the frame] and the white frame at 0.0675 covering x∈[0.55,0.68]... but that contradicts the cube being at 0.588 (on the table) — the frame would be above the cube.\n\nHmm, unless the frame's surface at 0.0675 IS above the cube (the cube is under the frame?!). \n\nHmm, wait: maybe the white \"frame\" is a TABLE-like platform (like a small saucer with legs) UNDER which... no.\n\nLet me look at the s4 image again: the cube (the mauve top + the red front face) appears at (276-304, 293-320) and the white platform's surface appears around/behind it at (250-345, 255-300). The cube's top face (293-306) overlaps the platform's front edge region (up to ~300). So the cube is in FRONT of the platform (a smaller x, i.e., lower in the image... hmm, with dv/dx = +390, a smaller x = a smaller v = higher in the image).\n\nThe platform's surface spans v 255-300 and the cube's top face 293-306 → the cube is at the platform's front edge (the platform's near edge at v≈300). Since a larger v = a larger x, the cube at v=300 is at the platform's near (larger x!) edge. So the cube is at the platform's NEAR edge = a LARGER x than the platform's surface points at v=255.\n\nHmm, so the cube is in FRONT of the platform on the +x side.\n\nSo the cube is at x ≈ 0.59 (per the calc) and the platform behind it (x < 0.59). Then my probes at x=0.55-0.68 hitting the platform at 0.0675: at x=0.55 (behind the cube) ✓ the platform. At x=0.62-0.65 (in front of/at the cube?) hmm.\n\nI'm running low on patience but I have 113s and 35 commands. Let me be smart: the cube is at x≈0.59, y≈0.04, on the table (its top ~0.042).\n\nThe fingers can't descend below 0.0675 at x∈[0.55,0.65]?? But at x=0.73 they reached 0.022! So at x=0.73 the path is clear. So the arm's z-limit is NOT global — the block at x∈[0.55,0.65] is a physical object at 0.0675 = the white platform!\n\nAnd the cube (x=0.59, top 0.042) is UNDER/BESIDE the platform. If the platform's surface is at 0.0675 and spans x∈[0.55,0.68] (a large plate), and the cube (top 0.042) is at x=0.59, the cube would be UNDER the platform ✗ (we see it in the agentview).\n\n=> The cube must be in a HOLE in the platform (the frame's window!) with its top at 0.042, i.e., BELOW the platform's surface (0.0675) by 2.5cm.\n\nThat's consistent with the FIT (the pink blob = the cube's top face at z≈0.02-0.04 ✓✓) and with the platform's surface at 0.0675 ✓ and the cube being inside the frame's window ✓ and the fingers unable to reach into the window (too wide) ✓.\n\nSo the cube is INSIDE a frame's window, its top 2.5cm below the frame's surface. The window is ~4.2-6cm wide. The open fingers (7.9cm) can't fit; the closed fingers (2cm) can fit but can't grip.\n\nSOLUTION: descend with the CLOSED gripper into the window beside the cube (a ~1cm gap on each side? if the window is 5cm and the cube 4.2cm, there's 0.4cm each side — too tight; the closed fingers are ~2cm wide ✗).\n\nHmm. So how is this task solvable?! \n\nMaybe the frame is not a frame — let me look at the wrist image at a low z near the cube (from attempt 2's s009 at (0.5012,0.0539,0.0768)): it showed the pink square (the cube's top) surrounded by the white surface with the 4 posts. The white surface is all around the pink square at roughly the SAME level (visually flush). And the 4 posts are at the corners of the white area.\n\nSo the cube's top is flush with the white surface → the cube sits IN a window whose surface coincides with the cube's top. So the white plate is a THIN plate (2-3mm) with a window for the cube, sitting on the table, and the cube (4.2cm) passes through the window from the table to the plate's level?? That can't be: if the plate is thin and on the table, the cube standing on the table would protrude way above the plate.\n\nUNLESS the plate is ELEVATED (on 4 legs = the gray posts!) at a height of ~3-4cm, and the cube (4.2cm) sits on the TABLE inside the plate's window, its top just at/above the plate's surface ✓✓✓ THAT'S IT! \n\nThe white plate is a small elevated table (on 4 legs/posts ~3cm tall) with a hole in the middle; the cube sits on the ground under the plate, poking through the hole in the middle, its top flush with (or slightly above) the plate's surface!\n\nLooking at the CONFIRMED agentview images: the white plate with 4 dark legs — YES, in the initial agentview the 4 dark legs are clearly visible under the plate ✓. So the plate is elevated ~3-4cm.\n\nSo the cube's top is at the plate's surface level (0.0675) — the cube's top protrudes through the hole, its top face flush with the plate's top surface.\n\n=> A top-down grasp is impossible: the fingers", + "NOW I see it clearly! The crop (245,250)-(350,345) at 6x:\n\nThe \"white plate\" is a LIGHT BLUE-GRAY translucent platform with 4 gray posts (one at each corner) standing UP from it. The platform's front edge is at zoom y≈300-330 → orig y = 250+50=300 to 250+55=305. The platform's surface extends UP from there (behind).\n\nThe CUBE: the mauve TOP face at zoom (195-350, 230-310) → orig (277-303, 288-302) and the dark RED FRONT face at zoom (195-350, 310-470) → orig (277-303, 302-328).\n\nThe cube's front face extends BELOW the platform's front edge (orig y 305) down to 328 — i.e., the cube's base is well below the platform's surface level in the image. And the cube's top face (288-302) is ABOVE the platform's front edge (300-305) — just slightly.\n\nSo the cube is IN FRONT of the platform (closer to the camera = a larger x), standing on the table, and its top face is roughly at the platform's surface level.\n\nThe cube's front face spans orig y 302-328 = 26px; with the vertical scale ~5.8px/cm and sin(39°)=0.63: the height = 26/(5.8*0.63) = 7.1cm?! Hmm, that's too tall for a 4.2cm cube. Unless the front face includes the platform's shadow or the cube is not 4.2cm.\n\nHmm, let me recompute the vertical scale: the platform's DEPTH: the platform's surface spans orig y 258-305 (47px) for its depth (unknown, maybe 10cm) → 4.7px/cm vertically for the x direction. And the horizontal scale (u): the platform's width in the image spans orig x 250-345 (95px); if the platform is 12cm wide → 7.9px/cm. Hmm.\n\nLet me use the cube: its top face (a 4.2cm square) spans orig x 277-303 (26px) horizontally → 6.2 px/cm ✓ and its depth (the top face's vertical extent, 288-302 = 14px) → 14/4.2 = 3.3 px/cm for the x direction (foreshortened by cos(39°)=0.78 → the horizontal scale ×0.78 = 4.8). Hmm, 3.3 vs 4.8 — inconsistent (maybe the top face's visible depth is less due to occlusion).\n\nAnd the front face's height: 26px for a height H with sin(39°)*6.2 = 3.9 px/cm → H = 6.7cm. That's inconsistent with a 4.2cm cube.\n\nSo the cube is ~6.7cm tall?? Or my elevation is wrong. Let me instead calibrate the elevation from the cube's own front face and top face: \n- the front face: 26px = H*sin(elev)*S\n- the top face (depth 4.2cm): 14px = 4.2*cos(elev)*S\n- the top face (width 4.2cm): 26px = 4.2*S → S = 6.2 px/cm\n→ cos(elev) = 14/(4.2*6.2) = 0.538 → elev = 57.5°; sin = 0.843\n→ H = 26/(0.843*6.2) = 5.0 cm.\nSo the cube is ~5cm tall and the elevation is ~57°.\n\nOK: the cube is ~4.2-5cm tall. Good.\n\nNow the KEY question: is the cube sitting on the platform (its base at the platform's surface) or on the table in front of the platform? From the image: the cube's FRONT face is visible below the platform's front edge → if the cube were ON the platform, its front face would be visible above the platform's front edge (the platform's edge would be at the cube's base). The cube's front face extends from orig y 302 down to 328, while the platform's front edge is at 300-305. So the cube's front face starts (at its top) at 302 and extends DOWN past 305 to 328 → i.e., the cube's front face is BELOW the platform's front edge → the cube stands on the TABLE in front of the platform ✓✓ (its base at orig y=328, well below the platform's edge at 300).\n\nSo the cube is ON THE TABLE in front of the raised platform, and the platform's surface is at a height similar to the cube's top.\n\nNow the heights: the table at z≈0.01 and the cube's top at... The platform's surface is at 0.0675 (from the finger stops). The cube's top face is at a similar visual level to the platform's front edge (orig 288-302 vs the edge at 300-305) — the cube's top face's center (295) is slightly ABOVE the platform's edge (302) in the image, i.e., a smaller v = higher in the image = farther/higher. Since the cube is CLOSER to the camera (a larger x) and its top is lower than the platform's surface... Let me compute with the calibration:\nv = v0 + 6.2*(x - x0) - ... hmm, I need the correct signs. Let me do it with actual numbers:\nCube's top-center: (290.5, 295) [v=295]\nPlatform's front edge center: (297?, 302)\n\nHmm, the platform's front edge is at a larger x (closer to the camera) than the platform's back parts, and the cube is in front of the platform (an even larger x).\n\nOK, let me just use the finger-calibrated relations with the elevation insight:\ndv/dx = +S*cos(elev) = 6.2*0.538 = 3.34 px/cm = 334 px/m (a larger x → a larger v ✓ consistent with the earlier estimate 390).\ndv/dz = -S*sin(elev) = -6.2*0.843 = -5.23 px/cm = -523 px/m ✓ (matching the earlier -500).\n\nNow, the s006 reference: the fingertips at (296, 375) at (x=0.7298, y=0.0434, z_tip=0.0221).\nThe cube's top center at (290.5, 295).\nΔv = 295-375 = -80 = 334*(x_c-0.7298) - 523*(z_t-0.0221)\n→ 334*(x_c-0.7298) = -80 + 523*(z_t-0.0221)\nIf z_t = 0.042: = -80+10.4 = -69.6 → x_c = 0.7298-0.2084 = 0.521\nIf z_t = 0.05: = -80+14.6 = -65.4 → x_c = 0.534\nIf z_t = 0.0675: = -80+23.7 = -56.3 → x_c = 0.561\n\nHmm, so x_cube ≈ 0.52-0.56 (if it's on the table with a top at 0.042-0.05) — this agrees better with the wrist fit (0.598) than with 0.73.\n\nAnd the u check: Δu = 290.5-296 = -5.5 px for the cube vs the fingers at the same-ish depth → Δy = -5.5/(the u scale ~6.2px/cm) = -0.9cm → y_cube = 0.0434-0.009 = 0.034.\n\nHmm, so the cube ≈ (0.53, 0.034) with its top ≈ 0.045 (on the table; the table at ~0.01, the cube's top at 0.01+4.5 = 0.055).\n\nConsistency check with the finger stops: at (0.5576, 0.0565) and (0.6002, 0.0626), the closed fingers stopped at the tips' 0.0675. If the cube is at (0.53, 0.034) with its top at 0.055, then:\n- At (0.5576, 0.0565): the closed finger block (±1cm) → x∈[0.548,0.568], y∈[0.0515,0.0615]. The cube spans x∈[0.508,0.552], y∈[0.012,0.056]. The x overlap: [0.548,0.552] ✓ tiny; the y overlap: [0.0515,0.056] ✓ tiny. So the fingers would clip the cube's corner → hitting its top at 0.055 → the stop would be at the eef 0.065. Observed 0.0775 (a bit higher but similar).\n- At (0.6002, 0.0626): the fingers at x∈[0.590,0.610] — the cube's x range is [0.508,0.552] → NO overlap → the fingers would go past the cube and hit... the platform? The platform's front edge is at some x; if the platform starts at x>0.55 the fingers at 0.59-0.61 would be over the platform → a stop at the tips' 0.0675 ✓✓ CONSISTENT!\n\nSo: the cube is at (x≈0.53, y≈0.035), its top ≈0.05, on the table; the platform is behind it (x>0.55) with its surface at 0.0675.\n\nThe open-gripper descent at (0.6043, 0.0533) → over the platform → the tips stop at 0.0675 ✓.\nThe closed-finger descent at (0.6002, 0.0626) → the platform ✓.\nThe yaw=45 descent at (0.6091, 0.0509) → the platform ✓.\n\nALL CONSISTENT!!! FINALLY.\n\nSo the cube is at approximately (0.53, 0.035), and the arm can descend low there (no platform in front of x<0.55 ✓ as we saw at x=0.50 the arm descended... hmm, in attempt 2 at (0.5012, 0.0539) the closed fingers rested at 0.0768 (the tips at 0.0668) — a stop at the fingertips' 0.0668?! That's the same 0.0675 level! Hmm, at x=0.5012 the fingers stopped at the tips' 0.0668 — that's the platform again?! \n\nUgh! At x=0.50 the platform is there too? But the cube is at 0.53 with its top at 0.05...\n\nHmm, unless the platform's extent is x∈[0.50, 0.68] — and the cube at 0.53 is IN FRONT of the platform in the image but at the same x?? Not possible.\n\nWait, in attempt 2's s009 the eef was at (0.5012, 0.0539, 0.0768) — the reported z was 0.0768 with a target of 0.075 (stopped 0.2cm short, essentially REACHED). So the fingers' tips at 0.0668 were NOT blocked — it just reached the target! I misread it as a stop at 0.0675. So at x=0.50 there was NO block ✓✓.\n\nSimilarly, the s008 descent (0.699, 0.0541) to 0.075 → reached 0.0769 (a 0.2cm shortfall) → NOT blocked ✓ (the target 0.075 → 0.0769 is only 0.19cm off, essentially reached).\n\nSo my \"stops at 0.0675\" list should be re-checked:\n- a2_s012: (0.6168, 0.056, target 0.09) → reached 0.0927 (0.3cm) ✓ NOT blocked.\n- a2_s017: (0.6194, target 0.07) → stopped at 0.0775 (0.8cm short) ← BLOCKED (by 0.75cm).\n- a2_s020: (0.6" + ], + "shell": [ + "cd /opt/lffjail/work && python3 -c \"\nfrom PIL import Image\nim=Image.open('obs/a3_s006_agentview.jpg')\nim.crop((250,230,360,360)).resize((550,650),Image.LANCZOS).save('work/a3_s6.png')\nprint('ok')\"", + "cd /opt/lffjail/work && python3 -c \"\nfrom PIL import Image\nim=Image.open('obs/a3_s002_agentview.jpg')\nim.crop((245,250,350,345)).resize((630,570),Image.LANCZOS).save('work/frame_big.png')\nprint('ok')\"" + ], + "viewed": [ + "work/a3_s6.png", + "obs/a3_s006_agentview.jpg", + "work/frame_big.png" + ] + } + }, + { + "attempt": 3, + "step": 8, + "kind": "move_eef", + "frame_start": 194, + "frame_end": 459, + "command": "move_eef z=0.04 speed=0.06 gripper=open", + "args": { + "z": 0.04, + "speed": 0.06, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 3.8, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.5374, + 0.0356, + 0.0775 + ], + "gripper_width_after": 0.0789, + "holding_after": false, + "touched_during": false, + "think_s": 7.574180364608765, + "agent_obs_images": [ + "obs/a3_s008_agentview.jpg", + "obs/a3_s008_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 3, + "step": 9, + "kind": "move_eef", + "frame_start": 459, + "frame_end": 483, + "command": "move_eef x=0.6 y=0.09 z=0.13 gripper=close speed=0.25", + "args": { + "x": 0.6, + "y": 0.09, + "z": 0.13, + "gripper": "close", + "speed": 0.25 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.6, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5954, + 0.0884, + 0.127 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 168.24049019813538, + "agent_obs_images": [ + "obs/a3_s009_agentview.jpg", + "obs/a3_s009_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Let me scan y at x=0.60 to locate the cube precisely and determine its height (cube top vs platform top)." + ], + "reasoning": [ + "Blocked at the fingertips' 0.0675 again (at x=0.5374, y=0.0356) with the OPEN gripper! So there's an obstruction at the tips' 0.0675 there too.\n\nHmm! So the obstruction covers x=0.5374 too. That means the platform extends to x=0.537 or... the CUBE is there (its top at 0.0675)!\n\nIf the cube's top is 0.0675 at (0.5374, 0.0356), then the OPEN fingers (at ±4cm) hit... hmm.\n\nLet me look at the wrist image at this pose — it's the wrist camera at (0.5374, 0.0356, 0.0775) with the open gripper. The wrist camera at (0.5914, 0.0336, 0.1885) looking down... The cube at (0.53, 0.035, 0.04): the camera is at x=0.591, so the cube is 6cm BEHIND the camera's axis in x → within the FOV (at a depth of 0.11, the half-width is 0.08) ✓ so the cube should be visible in the wrist image, near the top edge!\n\nLet me look at the a3_s008 wrist image! This is the direct view of the cube's position.", + "CRUCIAL NEW INFORMATION: The wrist image at (0.5374, 0.0356, 0.0775) shows the platform's window with the PINK SQUARE in the middle — and the pink square is FLAT on the platform's surface (no visible protrusion, no side faces)! The 4 gray posts are at the corners of the platform. The platform's white surface is at the same level as the pink square.\n\nSo in this near-top-down view, the pink square (the \"cube\") appears FLUSH with the platform's surface. The platform occupies the whole image.\n\nSo the \"pink square\" is embedded in the platform — it IS the cube's top, flush with the platform's surface.\n\nHmm, so in the agentview the red front face below... Let me look at the a3_s008 agentview: the red cube appears at (278-303, 302-328) with the pink top face at 288-302 and the red front face at 302-328. And the platform's surface is behind.\n\nHmm, in the agentview, the cube's front face (the dark red part) is clearly visible and vertical → the cube protrudes above the table in front of the platform. But the wrist camera at this pose shows only the flat top flush with the platform.\n\nOH WAIT. Maybe the \"pink square\" in the wrist image is NOT the cube but the platform's HOLE showing the table's wood through it?! The table is light brown wood, not pink. No.\n\nOr maybe the \"pink square\" is the cube seen through the HOLE in the platform (the platform is elevated, the cube stands on the table below, and we're looking down through the hole at the cube's top face ✓✓✓ THAT'S CONSISTENT!\n\nThe platform is elevated (on its 4 legs) above the table by ~3-4cm; the cube stands on the table and pokes up through the platform's hole; its top face is just at/below the platform's surface level. Looking straight down through the hole, we see the cube's top face flush with the platform's surface in the image ✓.\n\nAnd in the agentview (an oblique view), we see the cube's front face (below the platform's edge) and its top face ✓✓.\n\nSo the setup: the cube stands on the table, and the platform (an elevated plate with a hole) surrounds its upper part. The cube's top is at approximately the platform's surface level (0.0675).\n\nThe gap between the platform's underside and the table is ~3-4cm; the cube's sides are exposed in that gap BUT they're surrounded by the platform's hole (the hole is tight around the cube).\n\nFor a top-down grasp, the fingers must enter the hole (too narrow, 7.9cm).\n\nIMPORTANT: the platform's hole restricts access, but if the hole is only slightly bigger than the cube, we could tip/push the cube sideways UNDER the platform to move it out. But the platform's hole is tight...\n\nHmm, is the hole tight? In the wrist image, the pink square is surrounded by the white platform immediately (a tight hole) indeed.\n\nHmm, so how is the task solvable?! \n\nWait, maybe the platform is much SMALLER than I think and the fingers' descent at x=0.5374 was blocked by the platform's corner POSTS. The wrist image shows the 4 posts at the corners of a square, and the platform's white surface. Its apparent width: the platform spans nearly the whole image (512px) at a depth of ~0.11 → 0.11*512/352 = 0.16m = 16cm wide. So the platform is ~16cm wide (a big plate) with the hole in the middle.\n\nHmm, but the agentview shows the platform as ~9cm wide (26px/6.2px/cm... let me measure: the platform's posts span orig x 255-335 → 80px → 13cm). OK ~13-16cm.\n\nSo a 14cm plate with a 4-5cm hole in the middle, elevated ~4cm.\n\nGiven the fingers are 7.9cm apart when open, and the posts are at ±6.5cm, the open fingers could descend between the posts... but the platform's surface would block them (they'd hit the plate's top at 0.0675) ✓ as observed.\n\nTo reach the cube, the fingers must pass through the hole (only ~4-5cm wide) — impossible.\n\n=> The only way: the cube must be moved out from under the plate. To push it, I'd need access to its side, but the plate blocks from above and the table from below; the cube's sides are exposed only inside the tight hole.\n\n=> UNLESS the plate's hole is bigger than the cube. If the hole is ~7-8cm and the cube 4.2cm in the middle, the open fingers (7.9cm) still barely don't fit, but a CLOSED gripper could descend into the hole beside the cube and then... close (already closed).\n\nHmm, what about partially opening? Not available.\n\nHmm, what if I descend with the gripper CLOSED into the hole BESIDE the cube (there'd be ~1.5cm of space on each side if the hole is 7cm and the cube 4.2cm) and then OPEN the gripper inside the hole → the fingers would spread to the hole's walls (~7cm) and be blocked before reaching the cube. Not useful.\n\n=> I'm stuck on the physics. But the task is presumably solvable. Let me reconsider: maybe the \"estimation\" that the cube's top is flush with the platform is wrong. Let me measure precisely in the wrist image: the pink square's color/brightness vs the platform. In the wrist image, the pink square is at (163-255, 170-262) — a 92px square. The platform's surface around it is light gray-blue.\n\nIf the cube's top were 2-3cm BELOW the platform's surface, we'd see the hole's inner walls (shadowed) around it — the image shows a subtle shading around the pink square? There's a slightly darker rim... \n\nAlternatively, if the cube's top were ABOVE the platform's surface, we'd see the cube's side faces. Not visible → so the cube's top is at or slightly below the platform's surface.\n\nOK. Given the (apparent) impossibility, let me consider that maybe the intended solution is to grasp the cube from the top at an angle... or the task expects a simple top grasp and the geometry is actually fine (maybe the \"platform\" is a thin plate and the cube protrudes above it).\n\nHmm, wait. Let me reconsider the depth estimate for the wrist camera's mount: I fitted dz=0.111, and the \"cube's top at 0.0675\" inference depends on it. What if dz is much larger (0.15-0.2, i.e., the camera is mounted high on the wrist)? Then the pink blob's z = z_cam - d = (0.0775+dz) - 0.11 = dz - 0.0325 → for dz=0.15: z=0.1175; for dz=0.2: z=0.1675.\n\nHmm, so the cube's top could be at 0.11-0.17 if the camera is mounted higher! Then the cube protrudes 4-6cm above the platform (0.0675) ✓ and a top grasp IS possible (the fingers' tips at 0.0675 → they'd grip the cube's lower 4cm ✓✓).\n\nWhich is it?! The key: the fingers CAN'T be blocked by the cube at the cube's (x,y) with the OPEN gripper (the fingers straddle it). But we saw a block at 0.0675. If the cube's top were at 0.11, the open fingers at the cube's (x,y) would NOT be blocked by the cube (they straddle it) → they'd descend to the platform's surface (0.0675) ✓ SAME observation ✓. So both hypotheses predict a block at the platform's surface.\n\nAnd the CLOSED fingers at the cube's (x,y) with the cube's top at 0.11 would be blocked at 0.12 (much higher). We observed 0.0775 at (0.6002, 0.0626) → so the cube is NOT at (0.6002, 0.0626) with its top at 0.11. But if the cube is at (0.53, 0.035) (per my latest estimate) then that probe was 7cm away ✓ irrelevant!\n\nSO THE CUBE COULD BE AT (0.53, 0.035) WITH ITS TOP AT 0.11 (protruding above the platform) and my open-finger descent at (0.5374, 0.0356) was blocked by the PLATFORM's surface at 0.0675 (not the cube) ✓✓ — because the open fingers (±4cm) sit over the platform, and the platform's surface is at 0.0675 ✓✓✓.\n\nAnd the CUBE at (0.53, 0.035) with its top at 0.11 would be BETWEEN the open fingers (a 7.9cm gap vs a 4.2cm cube ✓) → they'd descend to the platform's surface, and their gripping surfaces (0.0675 upward) would cover the cube from 0.0675 to 0.11 ✓✓✓ A GRASP WOULD WORK!\n\nSo the descent was BLOCKED by the platform's surface at the fingertips' 0.0675, and the fingers ARE around the cube (their tips are at the cube's base level!) → CLOSING NOW SHOULD GRIP THE CUBE!!! \n\nThe cube's x,y must be exactly right though. The wrist image shows the pink square at (163-255, 170-262) → its center (209, 216) in the wrist image — NOT at the image center (256)! So the cube is offset from the camera's axis by (-47, -40) px → at the local scale (k = f/d = 352/0.11 = 3200 px/m): Δy = -47/3200 = -0.0147, Δx = -40/3200 = -0.012" + ], + "viewed": [ + "obs/a3_s008_wrist.jpg", + "obs/a3_s008_agentview.jpg" + ] + } + }, + { + "attempt": 3, + "step": 10, + "kind": "move_eef", + "frame_start": 483, + "frame_end": 508, + "command": "move_eef z=0.08 speed=0.1 gripper=close", + "args": { + "z": 0.08, + "speed": 0.1, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5953, + 0.0884, + 0.0825 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 14.448442935943604, + "agent_obs_images": [ + "obs/a3_s010_agentview.jpg", + "obs/a3_s010_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 3, + "step": 11, + "kind": "move_eef", + "frame_start": 508, + "frame_end": 533, + "command": "move_eef x=0.6 y=0.03 z=0.14 gripper=close speed=0.2", + "args": { + "x": 0.6, + "y": 0.03, + "z": 0.14, + "gripper": "close", + "speed": 0.2 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5993, + 0.0302, + 0.1381 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 11.232991218566895, + "agent_obs_images": [ + "obs/a3_s011_agentview.jpg", + "obs/a3_s011_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "At (0.5953, 0.0884) the descent reached 0.0825 (the target 0.08, a 0.3cm shortfall → essentially reached, no block). So at y=0.088 there's NO obstruction at the fingertips' 0.0725.\n\nSo the obstruction at 0.0675 doesn't exist at (0.595, 0.088) ✓ → the plate doesn't extend there, or the plate's surface is lower.\n\nInteresting! So the obstruction at 0.0675 spans a limited area (around y≈0.05).\n\nLet me now probe y=0.06 and y=0.03 at x=0.60. Actually, we know (0.6002, 0.0626) → blocked at 0.0775. So y=0.0626 is blocked, y=0.0884 is not. And the cube's y is somewhere.\n\nLet me probe (0.60, 0.03): if the cube is at y≈0.035, this probe would hit the cube's top (higher) if the cube's top is above 0.0725.\n\nCommand: move_eef x=0.60 y=0.03 z=0.13 then descend to 0.08.\n\nHmm, but 2 commands per probe. Let me instead do a smarter single test: descend at (0.60, 0.03) to z=0.08 in one combined move (the arm is at (0.5953, 0.0884, 0.0825), so moving to (0.60, 0.03, 0.08) at a low z would sweep horizontally at ~0.08 — that's just above the obstruction level (0.0675) — risky (it could hit things) but informative. And if the cube's top is at 0.11, a horizontal sweep at 0.08 with the closed fingers would collide with the cube's side (the fingers at z 0.07-0.09).\n\nHmm, that could push the cube.\n\nLet me do it properly in two steps:\n1. move_eef x=0.60 y=0.03 z=0.14 gripper=close speed=0.2\n2. descend to 0.08 speed 0.1\n\nGO." + ] + } + }, + { + "attempt": 3, + "step": 12, + "kind": "move_eef", + "frame_start": 533, + "frame_end": 560, + "command": "move_eef z=0.08 speed=0.1 gripper=close", + "args": { + "z": 0.08, + "speed": 0.1, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5989, + 0.0301, + 0.0827 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 7.910199880599976, + "agent_obs_images": [ + "obs/a3_s012_agentview.jpg", + "obs/a3_s012_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 3, + "step": 13, + "kind": "move_eef", + "frame_start": 560, + "frame_end": 825, + "command": "move_eef z=0.03 speed=0.08 gripper=close", + "args": { + "z": 0.03, + "speed": 0.08, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 13.0, + "deg": 5.3 + }, + "eef_pos_after": [ + 0.4928, + -0.043, + 0.0112 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 13.110629081726074, + "agent_obs_images": [ + "obs/a3_s013_agentview.jpg", + "obs/a3_s013_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "At (0.5989, 0.0301) the descent reached 0.0827 (no block). So no obstruction at the fingertips' 0.0727.\n\nSummary of the closed-finger descents at x≈0.60:\n- y=0.0301: reached 0.0827 (no block down to the fingertips' 0.0727)\n- y=0.0626: blocked at the fingertips' 0.0675 (from attempt 2)\n- y=0.0884: reached 0.0825\n\nSo the obstruction is localized near y≈0.06 at x=0.60. And the cube is presumably there! The block at 0.0675 = the CUBE's top!\n\nSo the cube is at (x≈0.60, y≈0.06) with its top at 0.0675 → a small cube (its base at ~0.0255).\n\nHmm, and the block was at the fingertips' 0.0675 = the cube's top ✓.\n\nSo the cube's top is 0.0675 and the fingers can't get below it. But NOW we know the obstruction is LOCAL (only near the cube) → so the cube protrudes above its surroundings! The surrounding surface (at y=0.03 and 0.088) allows the fingers down to 0.0727 (we only tested to 0.08/0.0827 — we don't know how low the fingers can go there).\n\nLet me test how low the fingers can go beside the cube: descend at (0.60, 0.03) to z=0.03! If the fingers reach ~0.03 (the fingertips at 0.02) → the cube's base level is reachable ✓ → then I can grasp the cube with the OPEN gripper: position at the cube's (x,y), descend (the open fingers straddle the cube), and the fingers would descend past the cube's top down to the table ✓ → close → grip ✓✓✓.\n\nWait, but the OPEN fingers at (0.6043, 0.0533) stopped at the fingertips' 0.0675 (attempt 2, closed? let me check: a2_s016 was at (0.617, 0.053) with gripper=close; a1_s005 was open at (0.5576, 0.0565) — 4.3cm from the cube's x). Hmm, in attempt 2, the open descent at (0.6091, 0.0509)... that was yaw=45. And a2_s020 (0.6497, 0.0531) open → blocked at 0.0775 — but that's 5cm from the cube's x.\n\nDo I have an OPEN descent exactly at the cube's (0.60, 0.06)? \n- a1_s005: (0.5576, 0.0565) open → blocked at the fingertips' 0.0675 — 4.3cm from the cube in x. The open fingers' plates span x∈[0.548,0.568] → 1.1cm from the cube's edge (0.579) → the finger's plate is close but shouldn't touch. Yet it blocked at 0.0675 — meaning something at 0.0675 there too (the plate!). Hmm, but we just found that at (0.60, 0.03) the closed fingers went to 0.0827 (not blocked)... but that's only down to 0.0727 — the plate could be at 0.0675 and we simply didn't go low enough!!! \n\nYES — the probes at y=0.03 and 0.088 only descended to the fingertips' 0.0727, above the plate's surface (0.0675) ✓ so they showed nothing. The plate could be everywhere at 0.0675!\n\nUgh. So my conclusion that the obstruction is \"local near the cube\" is unfounded.\n\nI need a decisive test: descend at (0.60, 0.03) to z=0.03 (the fingertips at 0.02). If it stops at the fingertips' 0.0675 → the plate is there; if it reaches 0.03 → free.\n\nThat's 1 command. Let me do it.\n\nBudget: 29 commands, 92s." + ] + } + }, + { + "attempt": 3, + "step": 14, + "kind": "move_eef", + "frame_start": 825, + "frame_end": 1090, + "command": "move_eef x=0.625 y=0.054 z=0.16 gripper=close speed=0.25", + "args": { + "x": 0.625, + "y": 0.054, + "z": 0.16, + "gripper": "close", + "speed": 0.25 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 18.9, + "deg": 5.9 + }, + "eef_pos_after": [ + 0.4821, + -0.0227, + 0.0625 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 22.561667442321777, + "agent_obs_images": [ + "obs/a3_s014_agentview.jpg", + "obs/a3_s014_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The arm flipped badly again (j5=-2.12, j6=3.75 at its limit, j7=2.90 at its limit) and ended at (0.4928, -0.0430, 0.0112) — way off.\n\nSo descending to z=0.03 at (0.60, 0.03) caused a flip → meaning the IK couldn't find a valid configuration → likely because the descent was blocked by an obstacle (the plate at 0.0675) and the solver went crazy. That supports the plate being at 0.0675 everywhere around there.\n\nNow the arm is in a bad configuration and the budget is 78.8s.\n\nTime to make a decision. I've spent 3 attempts' worth of effort. The physics seems to be: an elevated plate at z=0.0675 with a tight hole; the cube's top flush at 0.0675. A top-down grasp is impossible. Moving the plate is the only way, and its posts might provide leverage.\n\nActually — hold on. WAIT. What if the plate is a TABLE (a small side table) and the CUBE IS ON TOP OF IT? Then:\n- The plate's surface = 0.0675 = the cube's BASE.\n- The cube's top = 0.0675+0.042 = 0.11.\nThen the finger descents over the plate stop at the fingertips' 0.0675 = the plate's surface ✓ (a big area ✓ consistent).\nAnd the closed-finger descent AT THE CUBE's (x,y) would hit the cube's top at 0.12! We tested (0.6002, 0.0626) → 0.0775. If the cube is at (0.60, 0.06), that probe would have hit the cube's top at 0.12 ✗ (it stopped at 0.0775).\n\nUnless the cube is NOT at (0.60, 0.06): maybe the cube is at (0.60, 0.035) [the earlier agentview-based y estimate] and the (0.6002,0.0626) probe was 2.8cm off in y → the fingers' block (±1cm) would miss it ✓✓!! \n\nAnd the (0.5989, 0.0301) probe (closed, y=0.03) reached 0.0827 — the fingertips at 0.0727 — that's ABOVE the cube's top if the cube's top is 0.11?? No: if the cube's top is 0.11, the fingers descending to the fingertips' 0.0727 (below 0.11) would have hit the cube's top at the fingertips' 0.11 → the eef at 0.12 → a stop 4cm above the target 0.08 ✗ (it reached 0.0825).\n\nSo at y=0.03 there's no cube ✓ (the cube isn't at y=0.03).\n\nHmm! So neither y=0.03 nor y=0.088 has a cube at x=0.60 (they weren't blocked down to the fingertips' 0.0727 — but if the cube's top is at 0.11, the fingers would have been blocked at 0.12!). Wait:\n- At (0.5989, 0.0301): the eef reached 0.0827 → the fingertips at 0.0727 → so nothing was in the way down to 0.0727. If a cube (top at 0.11) were at that (x,y), the fingers' tips would hit it at 0.11 (the eef at 0.12) — that's ABOVE the target 0.08, so the descent would have stopped at 0.12 ✗ (it went to 0.0827). So NO cube at (0.599, 0.030) ✓.\n- At (0.5953, 0.0884): reached 0.0825 → no cube ✓.\n- At (0.6002, 0.0626): blocked at 0.0775 → an object at the fingertips' 0.0675.\n\nIf the cube's top were 0.11, the (0.6002, 0.0626) probe would have been blocked at 0.12 (4.5cm higher) → so the object there has its top at 0.0675, NOT 0.11.\n\nSo at (0.60, 0.063) there's an object 0.0675 high, and at (0.599, 0.030) nothing down to 0.0727 (we don't know lower).\n\nSo the cube (if its top is at 0.0675) is at ~(0.60, 0.06) ✓ and its top is at 0.0675 ✓ = the same as the plate's surface. ARGH.\n\nOK, FINAL DECISION TIME. 28 commands, 78.8s. The arm is in a flipped configuration. Let me:\n\n1. Recover the arm to a neutral pose.\n2. Try the \"pinch the cube's top\" grasp one more time at the exact cube's position (0.60, 0.06) — maybe with the gripper closing on the cube's top edges if the cube protrudes even 1-2mm. (Previously at (0.6002, 0.0626) the close gave 0.0024 → no.) Skip.\n3. Try to move the plate: descend at a post's location and push.\n\nFor (3) I need the posts' positions. From the wrist image at the cube's location (a3_s008 wrist, taken at eef (0.5374,0.0356,0.0775)): the posts at (95,145), (315,145), (60,370)?, (315,375). With the camera at (0.5914, 0.0336, 0.1885) and k≈3200 px/m at D=0.11 (the plane at z=0.0775) — the posts are at the plate's level (0.0675) so D≈0.121 → k=2900 px/m.\nPost 1: (95,145): Δu=-161, Δv=-111 → relative to the camera: Δy ≈ -161/2900 = -0.0555?? (with u = 256 + k*(Cy-Py) → Cy-Py = 161/2900 = 0.0555 → Py = 0.0336-0.0555 = -0.022). Hmm, negative y.\nΔv: v = 256 + f*[(Cx-Px)-0.042D]/D → -111 = k*(Cx-Px) - 0.042*f → k*(Cx-Px) = -111+14.8 = -96.2 → Cx-Px = -96.2/2900 = -0.0332 → Px = 0.5914+0.0332 = 0.6246.\nSo post 1 ≈ (0.625, -0.022).\nPost 2 (315,145): Δu=59 → Cy-Py = -59/2900 → Py = 0.0336+0.0203 = 0.0539. Δv same → Px = 0.6246.\nPost 3 (315,375): Δu=59 → Py=0.0539; Δv=119 → k*(Cx-Px) = 119+14.8 = 133.8 → Cx-Px = 0.0461 → Px = 0.5914-0.0461 = 0.5453.\nSo the posts at (0.625, -0.022), (0.625, 0.054), (0.545, 0.054), and the 4th should be (0.545, -0.022).\n\nHmm, so the \"plate\" spans x from 0.545 to 0.625 and y from -0.022 to 0.054? And the 4th post at (0.545,-0.022) — in the wrist image at (60,370)? Δu=-196 → Py = 0.0336+0.0676 = 0.101?? Inconsistent.\n\nMy pixel readings of the posts are crude. But roughly the plate is ~8cm x 8cm, spanning x∈[0.545,0.625], y∈[-0.02,0.055], with its center at (0.585, 0.017).\n\nAnd the cube at (0.60, 0.06) is at the plate's corner (+y, +x) — i.e., at the plate's edge/corner ✓ consistent with the agentview (the cube at the plate's front-right?).\n\nHmm, if the cube is at the plate's corner, maybe it's not in a hole but standing on the table next to/under the plate's corner.\n\nI'm out of analytical steam. Let me take the practical route: try the grasp at (0.60, 0.06) with the OPEN gripper one final time but descend SLOWLY to the stop (0.0775) and then close (we did this at (0.6043,0.0533) in attempt 1: 0.0024). The (x,y) differs by 1cm. Worth one more try? The evidence says the cube's top = 0.0675 = the fingers' tips → closing grabs nothing.\n\nAlternatively: the cube might be graspable if I close WHILE descending — i.e., close at 0.09 and then lower. No: closing above the cube is useless.\n\nGiven the situation, let me try the PLATE REMOVAL: grip a post! The posts are at (0.625, 0.054) etc. — they rise above the plate. Let me descend with the OPEN gripper at the plate's center-ish? No.\n\nPlan: descend with the OPEN gripper straddling a post... the posts are ~5cm apart; the open fingers are 7.9cm. Hmm.\n\nLet me try to grip ONE post: position the CLOSED gripper above a post (0.625, 0.054) and descend: the fingers would hit the post's top (a stop above 0.0675 if the post rises). Then close → the post is between the fingers (if aligned) → grip → lift → the plate comes up.\n\n2-3 commands. Let's try it! If the post's top is at, say, 0.09, the fingers would stop with the tips at 0.09 → the eef at 0.10.\n\nCommand: move_eef x=0.625 y=0.054 z=0.16 gripper=close speed=0.2, then descend to 0.06 slowly, read the stop.\n\nBut the arm is currently flipped at (0.4928,-0.043,0.0112) with bad joints. Moving to a high z should recover it.\n\nLet me do: move_eef x=0.625 y=0.054 z=0.16 gripper=close speed=0.25.\n\nThen descend to 0.05 and see. If the stop is > 0.0775 → we found the post ✓ → then close/lift.\n\nGO." + ] + } + }, + { + "attempt": 3, + "step": 15, + "kind": "move_eef", + "frame_start": 1090, + "frame_end": 1355, + "command": "move_eef x=0.45 y=0.0 z=0.26 yaw=0 gripper=open speed=0.3", + "args": { + "x": 0.45, + "y": 0.0, + "z": 0.26, + "yaw": 0, + "gripper": "open", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 16.3, + "deg": 3.7 + }, + "eef_pos_after": [ + 0.3236, + -0.0445, + 0.1666 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 9.168675661087036, + "agent_obs_images": [ + "obs/a3_s015_agentview.jpg", + "obs/a3_s015_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The arm is stuck in a bad configuration (j5=-2.2261, j6=3.7528 at the limit, j7=2.8978 at the limit) and can't recover — it ended at (0.4821, -0.0227, 0.0625).\n\nI have 27 commands but only 65.5s of motion time and a crippled arm. The IK is in a terrible branch.\n\nLet me try a recovery move that's very different: go to the initial pose (0.4515, 0.0, 0.2613) with yaw=0 — the home configuration. Movement: move_eef x=0.45 y=0.0 z=0.26 yaw=0 gripper=open speed=0.3.\n\nIf it recovers, I can make one more grasp attempt. Otherwise, finish.\n\nGiven the remaining time (65s), one attempt at recovery + one grasp is feasible.\n\nLet me do it." + ] + } + }, + { + "attempt": 3, + "step": 16, + "kind": "move_eef", + "frame_start": 1355, + "frame_end": 1620, + "command": "move_eef x=0.5 y=0.0 z=0.25 yaw=180 gripper=open speed=0.3", + "args": { + "x": 0.5, + "y": 0.0, + "z": 0.25, + "yaw": 180, + "gripper": "open", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 17.1, + "deg": 6.6 + }, + "eef_pos_after": [ + 0.3688, + -0.0578, + 0.156 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 8.718748331069946, + "agent_obs_images": [ + "obs/a3_s016_agentview.jpg", + "obs/a3_s016_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The arm is still stuck (j6=3.7528 and j7=2.8978 are both at their limits — the wrist is fully wound). x moved to 0.32, y=-0.04.\n\nThe wrist joints are at their limits, which likely means the arm can't orient the hand properly anymore. This is a degenerate state. It might be recoverable with a joint-space-friendly move... but move_eef is all I have.\n\nLet me try a large, simple move that may unwind: e.g., move to x=0.55, y=0.0, z=0.23 with yaw=180 (a different wrist configuration)? Or yaw=90?\n\nActually, try yaw=180: move_eef x=0.5 y=0.0 z=0.25 yaw=180 speed=0.3. The yaw change forces the wrist to rotate, possibly unwinding j7.\n\nLet me try that.\n\nTime: 52.2s left; 26 commands." + ] + } + }, + { + "attempt": 3, + "step": 17, + "kind": "move_eef", + "frame_start": 1620, + "frame_end": 1668, + "command": "move_eef x=0.55 y=0.05 z=0.2 yaw=-90 gripper=open speed=0.3", + "args": { + "x": 0.55, + "y": 0.05, + "z": 0.2, + "yaw": -90, + "gripper": "open", + "speed": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5527, + 0.0519, + 0.2024 + ], + "gripper_width_after": 0.0798, + "holding_after": false, + "touched_during": false, + "think_s": 9.031365156173706, + "agent_obs_images": [ + "obs/a3_s017_agentview.jpg", + "obs/a3_s017_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The arm remains stuck at the wrist limits (j6=3.7528, j7=2.8978) and yaw is at 6.6° instead of 180. The arm can't move much (a 17cm shortfall).\n\nI'm effectively crippled. 25 commands, 39s.\n\nThe wrist joints at their limits (j6 at max 3.7528, j7 at max 2.8978) — the \"yaw\" command isn't working because the wrist is saturated.\n\nRecovery idea: move far in a direction that unwinds j7, e.g., yaw=-180 or yaw=-90 (the other direction). Let me try yaw=-90 at a moderate position.\n\nActually, the reported yaw is 3.7-6.6° while I commanded 0 and 180 — meaning the IK can't achieve the requested orientation. Since j6 and j7 are at the max, to unwind I need a yaw of the opposite sign, i.e., yaw=-90 or -180, which would drive j7 negative.\n\nLet me try: move_eef x=0.55 y=0.05 z=0.20 yaw=-90 speed=0.3.\n\nIf this fails, I'll finish with a report." + ] + } + }, + { + "attempt": 3, + "step": 18, + "kind": "move_eef", + "frame_start": 1668, + "frame_end": 1933, + "command": "move_eef x=0.555 y=0.05 z=0.04 gripper=open speed=0.08", + "args": { + "x": 0.555, + "y": 0.05, + "z": 0.04, + "gripper": "open", + "speed": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 4.0, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5692, + 0.0509, + 0.0774 + ], + "gripper_width_after": 0.0659, + "holding_after": false, + "touched_during": false, + "think_s": 49.01446270942688, + "agent_obs_images": [ + "obs/a3_s018_agentview.jpg", + "obs/a3_s018_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Recovery worked. Final grasp attempt at the cube's estimated position with the fingers straddling it in y." + ], + "reasoning": [ + "RECOVERED! The arm is now at (0.5527, 0.0519, 0.2024) with yaw=-90 and a clean configuration (j4=-2.1857, j6=2.3822, j7=2.3836).\n\n36.6s of motion, 24 commands.\n\nNow, with the yaw=-90 the fingers open along X. Let me use this to grasp the cube: the fingers at x = x_eef ± 4cm, which would straddle the cube along x. The cube at (0.60, 0.06).\n\nHmm, but the obstruction at the fingertips' 0.0675... \n\nGiven the limited time, let me try the most promising final action: with yaw=-90 (the fingers opening along x), descend at the cube's (x,y)=(0.60, 0.06) with the gripper OPEN. The fingers at x=0.56 and 0.64, y at the cube's y (the plates are ~2cm in y). The cube spans x [0.579,0.621] → the fingers at 0.56 (-1cm plate → 0.555-0.565) and 0.64 (0.635-0.645) → just outside the cube's x range ✓. And they'd need to descend to the table level (0.01-0.03). But the PLATE at 0.0675 spans x∈[0.545,0.625] → the finger at x=0.56 would hit the plate's surface ✗ blocked.\n\nHmm.\n\nWith yaw=0 (the fingers opening along y) at the cube's y=0.06: the fingers at y=0.02 and 0.10 → both possibly over the plate (y∈[-0.02,0.055]) → the finger at y=0.02 is over the plate ✗ blocked; the finger at y=0.10 is off the plate.\n\nSo either orientation has a finger over the plate → blocked at 0.0675.\n\nUnless the plate is smaller than I estimated or its hole is bigger...\n\nGiven the time (36s) and the low probability, let me do ONE final grasp attempt combining everything learned, and accept the outcome:\nAttempt: yaw=-90, at (0.60, 0.06): descend with the OPEN gripper to z=0.05 slowly. If it stops at 0.0775, close and hope the cube is between the fingers (it should be if the cube's top is above 0.0675 — we believe it's exactly at 0.0675, so the close would fail).\n\nAlternatively, at yaw=0: descend with the OPEN gripper at (0.60, 0.06). The fingers at y=0.02/0.10. If the plate blocks at the fingertips' 0.0675, close → the cube between the fingers → if the cube's top is 0.0675 = the fingertips' level, the fingers' gripping surfaces (0.0675 up) don't overlap the cube → FAIL.\n\nSo the flush conclusion means no grasp is possible. I should try something fundamentally different for the last attempt: \n\nPUSH THE PLATE: with the open gripper at yaw=-90 (the fingers along x), the fingers are at x=0.56 and 0.64, each ~2cm wide in y, at y≈the plate's y range. If I descend to the fingertips' 0.0675 (the plate's surface) and then move in -y (or +y), the fingers would slide along the plate's surface... they'd push the plate's POSTS if a post is in the path (the posts are at the plate's corners: (0.625,0.054) and (0.625,-0.022) per my estimate) — the finger at x=0.64, y moving from 0.06 → -0.05 would encounter the post at (0.625, 0.054)? The finger's plate at x=0.64±1cm = [0.63,0.65] and the post at x=0.625 → no overlap (0.625 < 0.63). Hmm.\n\nLet me instead do the simplest high-value action: descend at the plate's center (0.585, 0.017) with the CLOSED gripper... that doesn't help.\n\nHonestly, at this point, the chances are low. Let me use the remaining time for the most likely-to-succeed thing: verify whether the cube protrudes above the plate by looking at the HIGH-RES crop of the current agentview (the arm is high at z=0.2024, so the view is clear). If the cube's top is visibly ABOVE the plate's surface, the grasp is possible.\n\nLet me do that (free, no motion) and then decide with the remaining ~35s.", + "Now the crop (250,255)-(345,340) at 7x shows:\n- The light blue-gray plate's surface (a big area).\n- 4 posts: 2 upper (gray) and 2 lower (dark brown/black), standing at the plate's corners.\n- The RED CUBE: the mauve top face at zoom (195-375, 235-340) → orig (278-304, 289-304); the dark red front face at zoom (195-375, 340-490) → orig (278-304, 304-325).\n\nKey observation: the plate's surface (light blue-gray) is BEHIND the cube and to its sides. The cube's front face (the dark red) extends DOWN below the plate's front edge (the plate's front edge = the horizontal light-blue band at zoom y 330-360 → orig y 302-306).\n\nSo the cube stands in FRONT of the plate (on the wood table, which is visible below/around the cube) — NO, wait: look at the region below the cube (zoom y 490-595 → orig 325-340): it's BROWN (wood). And to the left/right of the cube at that level: also brown wood. So the cube stands on the wood table, and the plate is BEHIND it.\n\nAnd the plate's front edge (orig y≈304) is at the same image level as the cube's top face's front edge (orig 304)! So the plate's surface and the cube's top are at the same height ✓ consistent with the flush conclusion — but no, the plate is behind, so their apparent levels coincide only because of a combination of height and distance.\n\nUsing the parallax: the cube is at x≈0.60 and the plate's front edge at x≈0.62-0.63 (behind the cube). The plate's surface is at 0.0675. The cube's top at 0.042?\nv_cube_top_center = 289+ (304-289)/2 = 296.5\nv_plate_front_edge = 304\nΔv = 7.5 px. For the cube's top (x=0.60, z=0.042) vs the plate's edge (x=0.625, z=0.0675):\nv = v0 + 334*(x-x0) - 523*(z-z0)\nΔv = 334*(0.625-0.60) - 523*(0.0675-0.042) = 8.35 - 13.3 = -5 px. Observed +7.5. Hmm, wrong sign.\nIf the cube's top = 0.0675 (flush): Δv = 334*0.025 - 0 = 8.35 ✓ ≈ 7.5 ✓✓ MATCHES!\n\nSo the cube's top IS at ~0.0675 and the plate's surface at 0.0675 ✓ FLUSH confirmed yet again.\n\nWait, but then the cube is IN FRONT of the plate (per the image) and its top is at the same height as the plate's surface. So the cube (4.2cm tall, its top at 0.0675, its base at 0.0255) stands on... the wood table at z=0.0255? The table's surface should be at ~0.0-0.01. Hmm, 0.0255 is close enough (maybe the table is at 0.025).\n\nAnd the plate is a raised platform (its surface at 0.0675) BEHIND the cube, ~0.025m thick?? Hmm, the plate's surface at 0.0675 and the table at 0.0255 → the plate is 4.2cm thick, sitting on the table. So the plate is a thick block (a \"coaster\"/platform), not a thin frame. And the cube stands on the table just in front of it.\n\nThen the earlier finger blocks at 0.0675 over a wide area (x∈[0.55,0.68]) = the PLATE's surface ✓ (the plate is a big thick block spanning that area).\n\nAnd at (0.599, 0.030) the descent to 0.0827 (the fingertips at 0.0727) — that's above the plate's surface (0.0675) so it just didn't reach it ✓ (no contradiction!).\n\nAnd the (0.6002, 0.0626) stop at 0.0775 = the plate's surface ✓ (the fingers were over the plate there!) ✓✓ — the plate's y extent covers 0.0626 but not 0.0884? Hmm, at (0.5953, 0.0884) the descent reached 0.0825 (the tips at 0.0725) — again just above the plate ✓ (no info).\n\nSo: the plate is a thick block with its top at 0.0675, spanning x∈[0.55,0.68]... and the cube is IN FRONT of it (a smaller x) with its top at 0.0675.\n\nWAIT, that contradicts the plate's front edge at x≈0.62 (behind the cube at 0.60). So the plate spans x>0.62, and the stops at x=0.5576 and 0.5374 (over the plate at 0.0675)?! Those are at smaller x than the plate's front edge → NOT over the plate.\n\nHmm, at x=0.5374 (the open descent, a1/a3_s008) the stop was at the fingertips' 0.0675 → over the plate?! But x=0.5374 < 0.62.\n\nCONTRADICTION. Unless the cube is at x=0.5374 and the plate's front edge at 0.62? Then the cube would be 8cm in front of the plate... and the agentview's cube at u=290, v=296 → using the reference finger pose (0.7298, 0.0434, z_tip 0.0221) → v_tip=375, u=296:\nΔv = 296-375 = -79 = 334*(x_c-0.7298) - 523*(z_t-0.0221) + 0*(y diff... )\nWith z_t = 0.0675: -79 = 334*(x_c-0.7298) - 23.7 → x_c = 0.7298-0.1656 = 0.564.\nWith z_t = 0.042: x_c = 0.7298 - (79-11.4)/334 = 0.7298-0.2024 = 0.5274.\n\nSo x_cube ≈ 0.53-0.56 ✓ consistent with the wrist-based estimate (0.60±) and my s008 (0.5374) probe.\n\nSo the cube is at x≈0.55, y≈0.05, its top ≈0.0675 (flush with the plate).\n\nThe plate spans x from ~0.62? No — the stops at x=0.5374 (the tips at 0.0675) suggest the plate/cube is there. The cube at 0.55 and the probe at 0.5374 (1.3cm away in x, 0.035 vs 0.05 → 1.5cm in y): with the open fingers, the fingers' plates at x∈[0.527,0.547] — the cube's x range [0.529,0.571] → OVERLAP ✓ → so the open fingers' plate would hit the cube's top at 0.0675 ✓✓ (the finger's plate over the cube's edge!). CONSISTENT.\n\nSo the cube's top = 0.0675 and the fingers CANNOT get below it when positioned near the cube.\n\nThe cube's base = 0.0675-0.042 = 0.0255. The table at 0.0255?\n\nTo grasp, the fingertips must reach ~0.045. The only place they might get that low: away from the plate, e.g., at (0.599, 0.030) we don't know (we stopped at 0.0727). Let me test: descend at (0.55, 0.005) [a low y, away from the plate] to z=0.03 → if it reaches, the region is clear there.\n\nBut the fingers must be at the CUBE's location to grasp. The cube's neighbors: the plate behind (x>0.58?) — hmm, the cube at x=0.55 with the plate at x>0.58?\n\nUgh, the numbers are too uncertain.\n\nDECISION with 36s left: try ONE grasp at (0.555, 0.05) with yaw=0, OPEN, descending to 0.04 slowly, then close.\n- The fingers at y = 0.05±0.0397 = 0.010 and 0.090.\n- If nothing blocks them, they'd reach the fingertips at 0.03 → the gripping surfaces 0.03-0.07 → gripping the cube's mid-height (0.0255-0.0675) ✓✓ then close → grip!\n- If the plate is at y=0.09 (the far finger over the plate) → blocked at the fingertips' 0.0675 → the close would fail (as before) ✗.\n\nGiven the cube's top is at 0.0675 and the fingers' tips at 0.0675 in the blocked case, the close fails. But if the fingers can get to 0.03, it works.\n\nLet me try it — 1 descent + 1 close + (if successful) a lift + a move to the bin. Time: ~4s for the descent+close, then the lift/move ~4s. 36s ✓ feasible.\n\nCommand: move_eef x=0.555 y=0.05 z=0.04 gripper=open speed=0.08 (from (0.5527, 0.0519, 0.2024) — nearly above the target already, so it's mostly a straight descent ✓).\n\nGO." + ], + "shell": [ + "cd /opt/lffjail/work && python3 -c \"\nfrom PIL import Image\nImage.open('obs/a3_s017_agentview.jpg').crop((250,255,345,340)).resize((665,595),Image.LANCZOS).save('work/final_zoom.png')\nprint('ok')\"" + ], + "viewed": [ + "work/final_zoom.png" + ] + } + }, + { + "attempt": 3, + "step": 19, + "kind": "move_eef", + "frame_start": 1933, + "frame_end": 1948, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5692, + 0.0509, + 0.0775 + ], + "gripper_width_after": 0.0027, + "holding_after": false, + "touched_during": false, + "think_s": 10.394057035446167, + "agent_obs_images": [ + "obs/a3_s019_agentview.jpg", + "obs/a3_s019_wrist.jpg" + ], + "agent_note": { + "messages": [ + "The gripper couldn't fully open — a finger is touching the cube! Closing now." + ], + "reasoning": [ + "The descent stopped at 0.0774 (the fingertips at 0.0674) — blocked again. Note the gripper width is 0.0659 (it should be 0.0798 open!) — the fingers were partially prevented from opening/closing?! Interesting: the width 0.0659 < 0.0798 suggests the fingers are in contact with something (the plate's hole edges? the cube?).\n\nWait, I commanded gripper=open and the width is 0.0659 — so the fingers couldn't fully open → they're touching something! That's a contact signal ✓ (something between/around the fingers, e.g., the cube!).\n\nThe eef is at (0.5692, 0.0509, 0.0774) with yaw=-90 (the fingers open along X). The fingers at x = 0.569±3.3cm... with the width at 0.0659 (the inner gap = 6.59cm → ±3.3cm).\n\nThe cube at x≈0.55 → the finger at x=0.5692-0.033 = 0.536 and the other at 0.602. The cube spans [0.529,0.571] → the left finger at 0.536 is INSIDE the cube's x range! So the left finger is pressed against the cube's side ✓✓ (that's why the gripper couldn't fully open).\n\nSo the CUBE IS RIGHT THERE ✓ and the finger is touching its side!\n\nNow: CLOSE! The fingers would close on the cube's sides ✓✓✓ (the gap is 6.59 and the cube is 4.2 → closing from 6.59 to 4.2 grips it!)\n\nLet me close NOW!\n\nThen lift and move to the bin.\n\nTime: 23.3s. GO GO GO." + ] + } + }, + { + "attempt": 3, + "step": 20, + "kind": "move_eef", + "frame_start": 1948, + "frame_end": 1969, + "command": "move_eef x=0.55 y=0.05 z=0.12 gripper=open speed=0.2", + "args": { + "x": 0.55, + "y": 0.05, + "z": 0.12, + "gripper": "open", + "speed": 0.2 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5521, + 0.0499, + 0.1173 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 13.706470012664795, + "agent_obs_images": [ + "obs/a3_s020_agentview.jpg", + "obs/a3_s020_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Centering was off ~1.9 cm. Repositioning above the cube, then descending." + ], + "reasoning": [ + "DAMN — it closed to 0.0027 (empty). So the cube was NOT between the fingers.\n\nBut the width was restricted to 0.0659 when opening... Maybe the fingers were blocked by the PLATE's HOLE EDGE (not the cube). Hmm.\n\nOR: the finger was touching the cube's TOP EDGE and the closing slid past it.\n\n22.6s left, 22 commands. The attempt is nearly over.\n\nOne last idea: at this pose the fingers are at (0.5692, 0.0509) with the tips at 0.0675. The cube at x≈0.55 → the fingers' plates at x 0.536 / 0.602 (when open at ±3.3cm). The cube spans [0.529,0.571]. So the LEFT finger at x=0.536 is inside the cube's footprint → it would sit ON the cube's top ✓ (that's the block at 0.0675 — the cube's top!).\n\nSo the cube's top IS at 0.0675 and the left finger rests on it.\n\nTo grasp, I need the fingers BELOW the cube's top. Since the arm's descent is blocked by the cube's top at that (x,y)... \n\nBut note: the descent stopped at the tips' 0.0675 because ONE finger rested on the cube's top. If I move slightly so that neither finger is over the cube, the fingers could descend beside the cube! With yaw=-90 the fingers are at x_eef±3.3cm; the cube is 4.2cm wide → to straddle it, the fingers must be at x_eef±>2.1cm — which they are (±3.3) — but the finger at 0.536 vs the cube's [0.529,0.571]: the finger's inner face at 0.536 is INSIDE the cube's x range... wait, the finger's INNER face is at 0.536 and the cube's near face is at 0.529 → the finger's inner face at 0.536 is inside the cube's footprint (between 0.529 and 0.571) → so the finger IS over the cube ✓ (blocked by the cube's top).\n\nFor the fingers to straddle the cube, their inner faces must be at <0.529 and >0.571, i.e., a gap > 4.2cm ✓ (we have 6.59cm) — but the centering: the gap's center should be at the cube's center (0.55). The gap's center = (0.536+0.602)/2 = 0.569 — but the gap is 6.59 wide, so the faces are at 0.536 and 0.602... The cube's center is 0.55, which is NOT at the gap's center (0.569) → the cube's near face (0.529) is outside the gap's left edge (0.536)! So the left finger overlaps the cube's x range by 0.571-0.536? no: the cube spans [0.529, 0.571] and the left finger's inner face is at 0.536 → the cube extends from 0.529 to 0.536 OUTSIDE the gap (to the left of the left finger's inner face) — meaning the left finger is INSIDE the cube's footprint (the cube's near part) ✓ → the finger is on the cube's top ✓.\n\nSo the centering is off by 1.9cm. I need the eef at x = 0.55 (the cube's center) so the gap is centered on the cube → the faces at 0.55±3.3 = 0.517 and 0.583, both outside the cube's [0.529,0.571] ✓ straddling ✓.\n\nBut wait, we WERE at x=0.55 in the command; the actual eef x = 0.5692 (it stopped 2cm short in x! The \"stopped_from_target 4.0cm\" includes the x offset). So the arm didn't reach x=0.555 — it stopped at 0.5692 because of the collision with the cube (the left finger's plate resting on the cube's top blocked the downward motion, and the x motion was also incomplete).\n\nSo: I need to move to x=0.55 at a HIGHER z (above the cube's top 0.0675, e.g., z=0.12), then descend.\n\nLet me do that quickly:\n1. move_eef x=0.55 y=0.05 z=0.12 gripper=open speed=0.2 (~1s)\n2. move_eef z=0.03 speed=0.06 gripper=open (~1.5s) → hopefully the fingers descend beside the cube to the table\n3. close → check\n4. if gripped: lift/move to the bin.\n\nTime: 22.6s ✓ possible.\n\nGO!" + ] + } + }, + { + "attempt": 3, + "step": 21, + "kind": "move_eef", + "frame_start": 1969, + "frame_end": 2234, + "command": "move_eef z=0.03 speed=0.06 gripper=open", + "args": { + "z": 0.03, + "speed": 0.06, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 5.0, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5691, + 0.0503, + 0.0775 + ], + "gripper_width_after": 0.0663, + "holding_after": false, + "touched_during": false, + "think_s": 7.1505608558654785, + "agent_obs_images": [ + "obs/a3_s021_agentview.jpg", + "obs/a3_s021_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 3, + "step": 22, + "kind": "move_eef", + "frame_start": 2234, + "frame_end": 2499, + "command": "move_eef x=0.53 y=0.05 z=0.05 gripper=open speed=0.15", + "args": { + "x": 0.53, + "y": 0.05, + "z": 0.05, + "gripper": "open", + "speed": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 3.0, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.5191, + 0.0315, + 0.0715 + ], + "gripper_width_after": 0.0811, + "holding_after": false, + "touched_during": false, + "think_s": null, + "agent_obs_images": [ + "obs/a3_s022_agentview.jpg", + "obs/a3_s022_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "Again the descent stopped at (0.5691, 0.0503, 0.0775) — the same x=0.569 (not 0.55!). The eef keeps ending up at x=0.5691, not the commanded 0.55.\n\nInteresting: the commanded (0.55, 0.05, 0.03) ends at (0.5691, 0.0503, 0.0775). The z stop is at the fingertips' 0.0675 = the cube's top ✓ (the left finger over the cube).\n\nBut why is x=0.5691? The x target is 0.55, and the report says it stopped 5.0cm from the target (a 3D distance including the z shortfall of 4.75cm and the x shortfall of 1.9cm). So the arm stopped early in x too, because the fingers hit the cube's top and the collision aborts the whole motion.\n\nSo the arm's motion is being blocked by the finger resting on the cube's top before reaching x=0.55.\n\nI need to approach at a HIGHER z where the fingers clear the cube's top (0.0675), then move to x=0.55, then descend. The fingers' tips at z=0.0675+ = the eef at 0.0775+. So the approach must be at z > 0.0775, e.g., z=0.10 (the fingertips at 0.09, above the cube's top 0.0675 ✓ by 2.2cm). But wait: the finger PLATES extend up from the tips; at the eef z=0.10, the plates span 0.09-0.13 — above the cube's top ✓ fine.\n\nSo: move at z=0.10 to (0.55, 0.05), THEN descend.\n\nThe previous command moved to (0.55, 0.05, 0.12) successfully (the eef at 0.5521, 0.0499, 0.1173 ✓). Then the descent stopped early... because during the descent it drifted in x from 0.5521 to 0.5691?! That's odd — the descent command kept the x,y as they were (omitted → \"keep current\"), so x should stay 0.5521. But it ended at 0.5691.\n\nHmm, the \"keep current\" might have used the TARGET (0.55) rather than the actual? And then the IK... whatever. The arm drifted +1.9cm in x.\n\nI have 8.3s of motion left! Very little. The attempt will fail.\n\nLet me do one final quick action: close the gripper (it's at the width 0.0663, meaning it couldn't fully open — a finger is touching the cube) — then close. We did that and got 0.0027. Given the same pose, it'll fail again.\n\nWith 8.3s left, one more meaningful attempt: from (0.5691, 0.0503, 0.0775), move in +y? The fingers at yaw=-90 open along x; moving in y wouldn't help.\n\nAlternatively: with 8.3s, try the descent at a slightly different y so that the fingers straddle the cube in the X direction properly: the issue is the x centering (0.5691 vs the cube's 0.55). If I command the descent with an explicit x=0.53 (compensating for the +1.9cm drift), the arm might land at x≈0.55.\n\nCommand: move_eef x=0.53 y=0.05 z=0.03 gripper=open speed=0.15 — the drift may put the actual x at ~0.549 ✓ and hopefully the descent goes lower since neither finger would be over the cube... \n\nHmm, but the drift isn't a constant; it's caused by the collision.\n\nTime: 8.3s. One command ~1.5s, then close ~0.3s, then... if the close grips, I'd need a lift + a move to the bin (~3s) — that might just fit but the bin is at y≈0.235, 18cm away.\n\nLet me try: move_eef x=0.53 y=0.05 z=0.05 gripper=open speed=0.15.\nThen close.\nIf the width >0.03: lift to 0.15, move toward the bin, open.\n\nGO." + ] + } + } + ], + "task_events": [], + "frames": { + "n": 2529, + "fps": 20, + "image_res": 256, + "phase_codes": { + "move": 0, + "gripper": 1, + "judge": 2 + }, + "initial_state": { + "eef_pos": [ + -0.20846466056582413, + -2.8550355792672253e-14, + 1.1732794757296403 + ], + "joint_pos": [ + 4.254357557786492e-14, + -0.16103738899999992, + -3.5853834773341516e-14, + -2.44459747, + -2.98662711712626e-13, + 2.2267522, + 0.7853981633973531 + ], + "gripper_qpos": [ + 0.020541867755816158, + -0.02054184665779552 + ] + } + }, + "episode_index": 1646, + "dataset_index_range": [ + 2722919, + 2725448 + ], + "label_provenance": { + "task_cause_source": "leaf/release/evidence/causes.json", + "recovery_review_source": "leaf/release/label_audit.jsonl", + "recovery_review_applied": false + } +} diff --git a/leaf/annotations/episode_002325.json b/leaf/annotations/episode_002325.json new file mode 100644 index 0000000000000000000000000000000000000000..2214294b371cc7c36459d0702a7e07f9bbfd74c8 --- /dev/null +++ b/leaf/annotations/episode_002325.json @@ -0,0 +1,2667 @@ +{ + "schema": "leaf-replay-1", + "source": { + "batch": "clh_20261102_opus", + "run": "clh_20261102_opus-claude-opus-5-5-claudecodefull-noharness2_lh_order_dispatch_s3002_none_F1_direct_k1_1105-140336_p23100", + "attempts_in_episode": [ + 1 + ], + "episode_in_run": 0, + "condition": "memory_free_retry", + "memory_free_chain_of": "0002", + "memory_free_rep": 2, + "feedback_level": "F1", + "hide_k": false, + "k": 1, + "perception": "rgb", + "instruction_variant": "direct", + "contract_sha256": "138d4c7b8188065024079091348171b0806956433a829407b621e6c1e664920f", + "run_status": "done", + "manifest_id": "0012", + "replay": { + "n_reports_checked": 60, + "n_mismatch": 0, + "max_eef_dev_m": 0.0 + }, + "backfill_provenance": { + "original_run": "/mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source/runs/api/clh_20261102_opus/clh_20261102_opus-claude-opus-5-5-claudecodefull-noharness2_lh_order_dispatch_s3002_none_F1_direct_k1_1105-140336_p23100", + "frozen_run": "/mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source/runs/api/clh_20261102_opus/clh_20261102_opus-claude-opus-5-5-claudecodefull-noharness2_lh_order_dispatch_s3002_none_F1_direct_k1_1105-140336_p23100", + "runtime": "/mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source" + }, + "evaluation_config": { + "cond": "noharness", + "red_team": false, + "feedback": "F1", + "mem": "none", + "k": 1, + "rep": 2, + "chain": "0002", + "task": "lh_order_dispatch", + "seed": 3002 + }, + "release_origin": { + "dataset": "compound-lh-20261102-clh_20261102_opus", + "episode_index": 13 + }, + "release_episode_index": 2325, + "pre_v181_sidecar_index": { + "episode_index": 13, + "dataset_index_range": [ + 28759, + 30993 + ] + } + }, + "agent": { + "harness": "claude_code_full", + "harness_version": "2.1.299", + "harness_binary_sha256": "2d894a4b1bfaaa9aab72aeff7803e3c73bc2510f279a171f6b8f59f72d17d077", + "model": "claude-opus-5-5", + "effort": "high", + "provider": "anthropic", + "codex_catalog": null, + "auth": "oauth", + "jail": true + }, + "task": { + "name": "lh_order_dispatch", + "level": "L1", + "family": "long_horizon", + "category": "system_identification", + "capabilities": [ + "Perceive", + "Reason", + "Plan", + "Restore" + ], + "protocol": "cross", + "max_attempts": 5, + "agent_max_steps": 180, + "instruction": "Load both small products and the red order card into the brown shipping tray, while it is in the yellow loading rectangle. Then push the loaded tray with the closed gripper completely inside the green delivery rectangle. All three items must remain inside the tray, with the gripper open and clear.", + "seed": 3002, + "instance": { + "seed": 3002, + "board_xy": [ + -0.18, + 0.2 + ], + "card_xy": [ + -0.18, + 0.2 + ], + "card_yaw": 0.0, + "card_along": "x", + "bin_xy": [ + -0.21, + -0.08 + ], + "box_xy": [ + -0.21, + -0.08 + ], + "target_dist": 0.11, + "bias": [ + 0.0, + -0.055, + 0.0 + ], + "com_offset": -0.06, + "mechanisms": { + "L1": true, + "L3": true, + "L5": true + } + }, + "failure_causes": [ + "L1", + "L3", + "L5" + ], + "subset": "compound_long_horizon", + "paper": { + "original_cause": null, + "original_table_cause": null, + "cause": "L6", + "table_cause": "L6" + }, + "canonical_cause": "L6", + "paper_long_horizon": true, + "instruction_original": "Load both small products and the red order card into the brown shipping tray, while it is in the yellow loading rectangle. Then push the loaded tray with the closed gripper completely inside the green delivery rectangle. All three items must remain inside the tray, with the gripper open and clear." + }, + "run_outcome": { + "outcome_class": null, + "attempt_history": "F", + "n_attempts": 1, + "run_success": false, + "agent_final_report": "The task did not succeed. The attempt ended automatically when I hit the 100-tool-call limit. At that point the tray was still rotated about 10° and only partly in the green rectangle. The gripper was closed and lowered just in front of the tray, so the \"gripper open and clear\" condition wasn't met either. I never ran `finish`.\n\n**What worked: loading the tray**\n- **Locating things:** I fitted a camera model to the fixed agentview camera using 4 gripper positions. It turned out to be about 4–5 cm off in x, so my first grasp of the red cube missed. I recalibrated with the wrist camera (it sits about 4 cm ahead of and 10 cm above the grasp point, focal length about 305 px) and used that from then on.\n- **Cubes:** I picked up the red cube at (0.408, −0.252) and the blue cube at (0.548, −0.256) with `z=0.015 gripper=close`. Both went into the left compartment, released from z≈0.065 at y −0.105 and −0.062.\n- **Card:** It was about 10×6 cm and only 1–2 mm thick, lying on the big box (top at z≈0.037), so pinching it there failed. I pressed down on it with the closed gripper and dragged it +x (`speed=0.02–0.03`) until it hung over the box's front edge. It then slid off and leaned against the box. I pinched it across its width at x=0.623, z=0.016 (gripper width 0.056), turned it with `yaw=90` and released it at (0.45, 0.019, 0.058). It landed flat in the right compartment.\n\n**What failed: pushing the tray**\n- **First push:** Gripper closed, pushing +x at the tray's middle (y=−0.026, z=0.022). The tray turned about 20° clockwise because its card end moved ahead. The tray's resistance to sliding must be centred on the cube side.\n- **Correction:** I pushed on the cube end of the back edge (y=−0.105) to x=0.49. That cut the rotation to about 10°, but the card end was then close to green's far edge.\n- **Not finished:** I had just lowered the gripper in front of the card end, intending to push it back in −x, when the call limit ran out.\n\n**Lessons for a retry**\n- Use far fewer calls on calibration and image checks. The command and time budgets were barely touched (60 of 180 commands); the limit I hit was tool calls.\n- Push off-centre, on the cube side, or in short pushes alternating between both ends to keep the tray straight.\n- Leave calls for the last two steps: open the gripper and move it away, then run `finish`.", + "mean_think_s": 10.87, + "outcome_class_original": null, + "outcome_class_status": "not_applicable" + }, + "attempts": [ + { + "attempt": 1, + "success": false, + "outcome": { + "success": false, + "cargo": { + "product_red_1": true, + "product_blue_1": true, + "card_1": true + }, + "loaded_in_start": true, + "load_step": 1650, + "departed_unloaded": false, + "inside": true, + "static": true, + "failure": "delivery", + "stages": { + "product_red_1": true, + "product_blue_1": true, + "card_1": true, + "loaded_in_start": true, + "delivery": true + }, + "events": [ + { + "step": 205, + "item": "product_red_1", + "event": "achieved" + }, + { + "step": 300, + "item": "product_blue_1", + "event": "achieved" + }, + { + "step": 1650, + "item": "card_1", + "event": "achieved" + }, + { + "step": 1830, + "item": "card_1", + "event": "lost" + }, + { + "step": 1835, + "item": "card_1", + "event": "achieved" + } + ], + "l1_attempts": [], + "card_closes": [ + { + "step": 121, + "local": [ + -0.0224, + -0.5078 + ], + "tips_above_card": -0.0327, + "beyond_edge": 0.3778, + "beyond_edge_name": "right", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0798, + "held": false, + "width": 0.0023 + }, + { + "step": 165, + "local": [ + -0.0748, + -0.5068 + ], + "tips_above_card": -0.0326, + "beyond_edge": 0.3768, + "beyond_edge_name": "right", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0783, + "held": false, + "width": 0.0285 + }, + { + "step": 247, + "local": [ + 0.0646, + -0.511 + ], + "tips_above_card": -0.036, + "beyond_edge": 0.381, + "beyond_edge_name": "right", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0796, + "held": false, + "width": 0.0281 + }, + { + "step": 345, + "local": [ + -0.0822, + 0.0869 + ], + "tips_above_card": 0.0495, + "beyond_edge": -0.0278, + "beyond_edge_name": "backward", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0794, + "held": false, + "width": 0.0023 + }, + { + "step": 714, + "local": [ + -0.0079, + 0.0016 + ], + "tips_above_card": -0.0018, + "beyond_edge": -0.1021, + "beyond_edge_name": "backward", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0792, + "held": false, + "width": 0.0077 + }, + { + "step": 1010, + "local": [ + -0.0264, + 0.0 + ], + "tips_above_card": 0.0107, + "beyond_edge": -0.0347, + "beyond_edge_name": "forward", + "card_on_board": true, + "overhang": 0.0368, + "overhang_edge": "forward", + "width_before": 0.0786, + "held": false, + "width": 0.0023 + }, + { + "step": 1351, + "local": [ + -0.0065, + -0.0013 + ], + "tips_above_card": 0.0063, + "beyond_edge": 0.0245, + "beyond_edge_name": "forward", + "card_on_board": false, + "overhang": 0.0669, + "overhang_edge": "forward", + "width_before": 0.0796, + "held": false, + "width": 0.0057 + }, + { + "step": 1437, + "local": [ + 0.0, + 0.003 + ], + "tips_above_card": -0.0095, + "beyond_edge": 0.0327, + "beyond_edge_name": "forward", + "card_on_board": false, + "overhang": 0.069, + "overhang_edge": "forward", + "width_before": 0.0795, + "held": true, + "width": 0.0562 + }, + { + "step": 1721, + "local": [ + 0.0531, + -0.0825 + ], + "tips_above_card": 0.1193, + "beyond_edge": 0.1511, + "beyond_edge_name": "right", + "card_on_board": false, + "overhang": 0.1428, + "overhang_edge": "right", + "width_before": 0.0799, + "held": false, + "width": 0.0023 + } + ], + "card_lift": 0.09882123593695658, + "box_moves": [ + { + "step": 1853, + "moved_cm": 7.2, + "turned_deg": -20.3, + "yaw_deg": -20.3, + "gripper_open": false, + "touch_u": -0.0537, + "touch_v": -0.0011, + "face": "back", + "inside": false, + "over_turned": true, + "overshot": false, + "sideways": false, + "tipped": false, + "bad": true, + "new_trap": true + }, + { + "step": 2049, + "moved_cm": 4.1, + "turned_deg": 10.8, + "yaw_deg": -9.5, + "gripper_open": false, + "touch_u": -0.0583, + "touch_v": -0.0944, + "face": "back", + "inside": true, + "over_turned": false, + "overshot": false, + "sideways": false, + "tipped": false, + "bad": false, + "new_trap": false + } + ], + "l5_triggered": true, + "yaw_deg": -9.547574855446777, + "sim_s": 111.7, + "commands": 78, + "touching": false, + "upright": true, + "detail": "Cargo in tray: {'product_red_1': True, 'product_blue_1': True, 'card_1': True}; tray inside delivery rectangle: True." + }, + "finish_reason": "tool-call budget used up (automatic)", + "feedback_shown": "Attempt failed.", + "auto_ended": true, + "think_s": 0.0009629726409912109, + "feedback_f2": "Attempt failed. Cargo in tray: {'product_red_1': True, 'product_blue_1': True, 'card_1': True}; tray inside delivery rectangle: True.", + "judge_frames": [ + 2204, + 2234 + ], + "corrected_later_in_run": false, + "is_last_attempt_of_run": true, + "error_event_in_attempt": null, + "reviewed_operational_failure": null + } + ], + "commands": [ + { + "attempt": 1, + "step": 1, + "kind": "move_eef", + "frame_start": 0, + "frame_end": 8, + "command": "move_eef z=0.12", + "args": { + "z": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4485, + 0.055, + 0.121 + ], + "gripper_width_after": 0.0763, + "holding_after": false, + "touched_during": false, + "think_s": 23.955774307250977, + "agent_obs_images": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ], + "agent_note": { + "shell": [ + "ls obs; ls; cat /tmp/lffstate/4f2fa588eb01/config/projects/-tmp-lffrun-4f2fa588eb01/memory/MEMORY.md 2>/dev/null", + "cat README.md" + ], + "viewed": [ + "obs/s000_agentview.jpg", + "obs/s000_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 2, + "kind": "move_eef", + "frame_start": 8, + "frame_end": 29, + "command": "move_eef x=0.65 y=-0.15 z=0.12", + "args": { + "x": 0.65, + "y": -0.15, + "z": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.651, + -0.1502, + 0.1209 + ], + "gripper_width_after": 0.0794, + "holding_after": false, + "touched_during": false, + "think_s": 23.165279388427734, + "agent_obs_images": [ + "obs/s002_agentview.jpg", + "obs/s002_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 3, + "kind": "move_eef", + "frame_start": 29, + "frame_end": 39, + "command": "move_eef z=0.03", + "args": { + "z": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6492, + -0.1501, + 0.0291 + ], + "gripper_width_after": 0.0796, + "holding_after": false, + "touched_during": false, + "think_s": 0.009257316589355469, + "agent_obs_images": [ + "obs/s003_agentview.jpg", + "obs/s003_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 4, + "kind": "move_eef", + "frame_start": 39, + "frame_end": 51, + "command": "move_eef x=0.5 y=-0.3 z=0.15", + "args": { + "x": 0.5, + "y": -0.3, + "z": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.2 + }, + "eef_pos_after": [ + 0.4989, + -0.3012, + 0.15 + ], + "gripper_width_after": 0.0794, + "holding_after": false, + "touched_during": false, + "think_s": 25.435938119888306, + "agent_obs_images": [ + "obs/s004_agentview.jpg", + "obs/s004_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s002_agentview.jpg", + "obs/s003_agentview.jpg", + "obs/s003_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 5, + "kind": "move_eef", + "frame_start": 51, + "frame_end": 69, + "command": "move_eef x=0.4 y=0.08 z=0.35", + "args": { + "x": 0.4, + "y": 0.08, + "z": 0.35 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.2 + }, + "eef_pos_after": [ + 0.3971, + 0.0801, + 0.3473 + ], + "gripper_width_after": 0.0792, + "holding_after": false, + "touched_during": false, + "think_s": 53.879677295684814, + "agent_obs_images": [ + "obs/s005_agentview.jpg", + "obs/s005_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "I calibrated the camera model from four gripper positions and mapped the yellow rect, green zone, tray, red and blue cubes, and the card on the big box. Taking a top-down look next." + ], + "shell": [ + "mkdir -p tools; cat > tools/cam.py <<'EOF'\nimport numpy as np\nfrom scipy.optimize import least_squares\nW=np.array([[0.4485,0.055,0.121],[0.651,-0.150,0.121],[0.649,-0.150,0.029],[0.499,-0.301,0.150]])\nI=np.array([[255,196],[108,277],[120,318],[33,195]],float)\ndef R(p):\n yaw,pitch,roll=p\n # camera looks along -x initially, then pitch down\n fwd=np.array([-np.cos(pitch)*np.cos(yaw),-np.cos(pitch)*np.sin(yaw),-np.sin(pitch)])\n up0=np.array([0,0,1.])\n right=np.cross(fwd,up0);right/=np.linalg.norm(right)\n up=np.cross(right,fwd)\n c,s=np.cos(roll),np.sin(roll)\n r2=c*right+s*up; u2=-s*right+c*up\n return fwd,r2,u2\ndef proj(p,X):\n c=p[:3];f=p[6]\n fwd,r,u=R(p[3:6])\n d=X-c\n z=d@fwd\n return np.stack([256+f*(d@r)/z,256-f*(d@u)/z],-1)\ndef res(p): return (proj(p,W)-I).ravel()\np0=[1.6,0,0.6,0,0.3,0,600]\ns=least_squares(res,p0)\nprint(s.x, res(s.x))\nnp.save('tools/cam.npy',s.x)\nEOF\npython3 tools/cam.py", + "cat > tools/bp.py <<'EOF'\nimport numpy as np,sys\nsys.path.insert(0,'tools')\nfrom cam import R\np=np.load('tools/cam.npy')\ndef bp(u,v,h):\n c=p[:3];f=p[6];fwd,r,up=R(p[3:6])\n d=fwd+(u-256)/f*r-(v-256)/f*up\n t=(h-c[2])/d[2]\n return c+t*d\nfor line in sys.stdin:\n a=line.split()\n if not a: continue\n name,u,v,h=a[0],float(a[1]),float(a[2]),float(a[3])\n print(name,np.round(bp(u,v,h),3))\nEOF\npython3 tools/bp.py <<'EOF'\nredtop 88 236 0.025\nbluetop 70 287 0.025\nyel_fl 118 298 0\nyel_fr 287 298 0\nyel_bl 135 226 0\nyel_br 295 226 0\ngrn_fl 122 330 0\ngrn_fr 290 330 0\ngrn_bl 130 273 0\ngrn_br 288 273 0\ntray_topfl 146 260 0.05\ntray_topbr 275 228 0.05\nbox_tl 293 212 0.08\nbox_br 462 290 0.08\ncard 372 248 0.08\nEOF" + ], + "viewed": [ + "obs/s004_agentview.jpg", + "obs/s004_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 6, + "kind": "move_eef", + "frame_start": 69, + "frame_end": 78, + "command": "move_eef x=0.42 y=-0.01 z=0.16", + "args": { + "x": 0.42, + "y": -0.01, + "z": 0.16 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.2 + }, + "eef_pos_after": [ + 0.4179, + -0.0108, + 0.163 + ], + "gripper_width_after": 0.0797, + "holding_after": false, + "touched_during": false, + "think_s": 16.41780948638916, + "agent_obs_images": [ + "obs/s006_agentview.jpg", + "obs/s006_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s005_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 7, + "kind": "move_eef", + "frame_start": 78, + "frame_end": 111, + "command": "move_eef x=0.457 y=-0.252 z=0.1 gripper=open", + "args": { + "x": 0.457, + "y": -0.252, + "z": 0.1, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4596, + -0.2529, + 0.1018 + ], + "gripper_width_after": 0.0797, + "holding_after": false, + "touched_during": false, + "think_s": 53.28827619552612, + "agent_obs_images": [ + "obs/s007_agentview.jpg", + "obs/s007_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Tray ≈ x 0.44–0.525, y −0.133–0.090, about 4 cm high, with a divider near y≈−0.025. The big box is about 5.5 cm high. Card ≈ 9×5 cm. Next I'll grab the red cube." + ], + "shell": [ + "cd tools; python3 - <<'EOF'\nimport numpy as np\nfrom bp import bp\nEOF\ncat > /dev/null; python3 - <<'EOF'\nimport numpy as np,sys\nsys.path.insert(0,'tools')\nfrom cam import R\np=np.load('tools/cam.npy')\ndef bp(u,v,h):\n c=p[:3];f=p[6];fwd,r,up=R(p[3:6])\n d=fwd+(u-256)/f*r-(v-256)/f*up\n t=(h-c[2])/d[2]\n return c+t*d\nxb=bp(210,275,0)[0]; print('front bottom',bp(210,275,0))\nfor h in np.arange(0,0.08,0.01): print(h,bp(210,259,h))\nprint('box front bottom',bp(380,312,0))\nfor h in np.arange(0,0.12,0.01): print(h,bp(380,290,h))\nEOF", + "cd /tmp/lffrun/4f2fa588eb01 2>/dev/null || cd /opt/lffjail/work; pwd; cat > tools/geo.py <<'EOF'\nimport numpy as np, os\nP=np.load(os.path.join(os.path.dirname(__file__),'cam.npy'))\ndef R(p):\n yaw,pitch,roll=p\n fwd=np.array([-np.cos(pitch)*np.cos(yaw),-np.cos(pitch)*np.sin(yaw),-np.sin(pitch)])\n right=np.cross(fwd,[0,0,1.]);right/=np.linalg.norm(right)\n up=np.cross(right,fwd)\n c,s=np.cos(roll),np.sin(roll)\n return fwd,c*right+s*up,-s*right+c*up\ndef bp(u,v,h,p=P):\n c=p[:3];f=p[6];fwd,r,up=R(p[3:6])\n d=fwd+(u-256)/f*r-(v-256)/f*up\n t=(h-c[2])/d[2]\n return c+t*d\nEOF\npython3 - <<'EOF'\nimport numpy as np,sys\nsys.path.insert(0,'tools')\nfrom geo import bp\nprint('front bottom',bp(210,275,0))\nfor h in np.arange(0,0.08,0.01): print(h,bp(210,259,h))\nprint('box front bottom',bp(380,312,0))\nfor h in np.arange(0,0.12,0.01): print(h,bp(380,290,h))\nEOF", + "cd /opt/lffjail/work; python3 - <<'EOF'\nimport sys; sys.path.insert(0,'tools')\nfrom geo import bp\nfor n,u,v,h in [('tray_fl',146,259,.04),('tray_fr',275,259,.04),('tray_bl',152,228,.04),('tray_br',272,228,.04),('strip_l',203,240,.04),('strip_r',218,240,.04),\n ('box_tl',293,212,.055),('box_tr',433,212,.055),('box_fl',298,290,.055),('box_fr',462,290,.055),('card_tl',353,232,.056),('card_br',392,265,.056),('red',88,238,.025),('blue',70,289,.025)]:\n print(n,bp(u,v,h).round(3))\nEOF" + ], + "viewed": [ + "obs/s006_wrist.jpg", + "obs/s006_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 8, + "kind": "move_eef", + "frame_start": 111, + "frame_end": 116, + "command": "move_eef z=0.05", + "args": { + "z": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4591, + -0.2525, + 0.0535 + ], + "gripper_width_after": 0.0798, + "holding_after": false, + "touched_during": false, + "think_s": 9.665699481964111, + "agent_obs_images": [ + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s007_wrist.jpg", + "obs/s007_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 9, + "kind": "move_eef", + "frame_start": 116, + "frame_end": 136, + "command": "move_eef z=0.015 gripper=close", + "args": { + "z": 0.015, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4574, + -0.2528, + 0.0167 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 19.361039400100708, + "agent_obs_images": [ + "obs/s009_agentview.jpg", + "obs/s009_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s008_wrist.jpg", + "obs/s008_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 10, + "kind": "move_eef", + "frame_start": 136, + "frame_end": 159, + "command": "move_eef x=0.42 z=0.1 gripper=open", + "args": { + "x": 0.42, + "z": 0.1, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4214, + -0.2528, + 0.0989 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 37.642176389694214, + "agent_obs_images": [ + "obs/s010_agentview.jpg", + "obs/s010_wrist.jpg" + ], + "agent_note": { + "shell": [ + "cd /opt/lffjail/work; python3 -c \"\nimport sys; sys.path.insert(0,'tools')\nfrom geo import bp\nprint(bp(95,243,0.025), bp(88,238,0.025))\"" + ], + "viewed": [ + "obs/s009_wrist.jpg", + "obs/s009_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 11, + "kind": "move_eef", + "frame_start": 159, + "frame_end": 180, + "command": "move_eef x=0.408 z=0.015 gripper=close", + "args": { + "x": 0.408, + "z": 0.015, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4062, + -0.2521, + 0.0174 + ], + "gripper_width_after": 0.0285, + "holding_after": true, + "touched_during": true, + "think_s": 18.241828680038452, + "agent_obs_images": [ + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s010_wrist.jpg", + "obs/s010_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 12, + "kind": "move_eef", + "frame_start": 180, + "frame_end": 187, + "command": "move_eef z=0.12", + "args": { + "z": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4088, + -0.2538, + 0.118 + ], + "gripper_width_after": 0.0285, + "holding_after": true, + "touched_during": true, + "think_s": 28.351449966430664, + "agent_obs_images": [ + "obs/s012_agentview.jpg", + "obs/s012_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The red cube is grasped at x≈0.406, about 4–5 cm off from the agentview model's estimate, so I recalibrated with the wrist camera. I'm placing it in the left compartment next." + ] + } + }, + { + "attempt": 1, + "step": 13, + "kind": "move_eef", + "frame_start": 187, + "frame_end": 194, + "command": "move_eef x=0.45 y=-0.112 z=0.12", + "args": { + "x": 0.45, + "y": -0.112, + "z": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.5 + }, + "eef_pos_after": [ + 0.4468, + -0.1107, + 0.1192 + ], + "gripper_width_after": 0.0285, + "holding_after": true, + "touched_during": true, + "think_s": 0.010833024978637695, + "agent_obs_images": [ + "obs/s013_agentview.jpg", + "obs/s013_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 14, + "kind": "move_eef", + "frame_start": 194, + "frame_end": 215, + "command": "move_eef y=-0.105 z=0.065 gripper=open", + "args": { + "y": -0.105, + "z": 0.065, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4432, + -0.1048, + 0.0649 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 11.202435970306396, + "agent_obs_images": [ + "obs/s014_agentview.jpg", + "obs/s014_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s013_wrist.jpg", + "obs/s013_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 15, + "kind": "move_eef", + "frame_start": 215, + "frame_end": 221, + "command": "move_eef z=0.13", + "args": { + "z": 0.13 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4451, + -0.1055, + 0.1277 + ], + "gripper_width_after": 0.0783, + "holding_after": false, + "touched_during": false, + "think_s": 0.007862567901611328, + "agent_obs_images": [ + "obs/s015_agentview.jpg", + "obs/s015_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 16, + "kind": "move_eef", + "frame_start": 221, + "frame_end": 238, + "command": "move_eef x=0.551 y=-0.2555 z=0.1", + "args": { + "x": 0.551, + "y": -0.2555, + "z": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5528, + -0.256, + 0.1013 + ], + "gripper_width_after": 0.0795, + "holding_after": false, + "touched_during": false, + "think_s": 5.427789688110352, + "agent_obs_images": [ + "obs/s016_agentview.jpg", + "obs/s016_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s015_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 17, + "kind": "move_eef", + "frame_start": 238, + "frame_end": 262, + "command": "move_eef x=0.548 z=0.015 gripper=close", + "args": { + "x": 0.548, + "z": 0.015, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5453, + -0.2562, + 0.0142 + ], + "gripper_width_after": 0.0281, + "holding_after": true, + "touched_during": true, + "think_s": 10.469049453735352, + "agent_obs_images": [ + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s016_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 18, + "kind": "move_eef", + "frame_start": 262, + "frame_end": 272, + "command": "move_eef z=0.12", + "args": { + "z": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5474, + -0.2567, + 0.121 + ], + "gripper_width_after": 0.0281, + "holding_after": true, + "touched_during": true, + "think_s": 4.73838996887207, + "agent_obs_images": [ + "obs/s018_agentview.jpg", + "obs/s018_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Blue grasped. Placing it next to red at y≈−0.06." + ] + } + }, + { + "attempt": 1, + "step": 19, + "kind": "move_eef", + "frame_start": 272, + "frame_end": 287, + "command": "move_eef x=0.445 y=-0.062 z=0.12", + "args": { + "x": 0.445, + "y": -0.062, + "z": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4419, + -0.0611, + 0.1182 + ], + "gripper_width_after": 0.0281, + "holding_after": true, + "touched_during": true, + "think_s": 0.007427215576171875, + "agent_obs_images": [ + "obs/s019_agentview.jpg", + "obs/s019_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 20, + "kind": "move_eef", + "frame_start": 287, + "frame_end": 309, + "command": "move_eef z=0.065 gripper=open", + "args": { + "z": 0.065, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.443, + -0.0625, + 0.0666 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 0.008443832397460938, + "agent_obs_images": [ + "obs/s020_agentview.jpg", + "obs/s020_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 21, + "kind": "move_eef", + "frame_start": 309, + "frame_end": 321, + "command": "move_eef z=0.25", + "args": { + "z": 0.25 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4407, + -0.0615, + 0.2478 + ], + "gripper_width_after": 0.0787, + "holding_after": false, + "touched_during": false, + "think_s": 0.009859561920166016, + "agent_obs_images": [ + "obs/s021_agentview.jpg", + "obs/s021_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 22, + "kind": "move_eef", + "frame_start": 321, + "frame_end": 334, + "command": "move_eef x=0.43 y=0.26 z=0.2", + "args": { + "x": 0.43, + "y": 0.26, + "z": 0.2 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.5 + }, + "eef_pos_after": [ + 0.428, + 0.2603, + 0.1992 + ], + "gripper_width_after": 0.0791, + "holding_after": false, + "touched_during": false, + "think_s": 4.316640377044678, + "agent_obs_images": [ + "obs/s022_agentview.jpg", + "obs/s022_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 23, + "kind": "move_eef", + "frame_start": 334, + "frame_end": 360, + "command": "move_eef x=0.4 y=0.34 z=0.1 gripper=close", + "args": { + "x": 0.4, + "y": 0.34, + "z": 0.1, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3977, + 0.342, + 0.0989 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 12.35153317451477, + "agent_obs_images": [ + "obs/s023_agentview.jpg", + "obs/s023_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Both cubes are in the tray. The card ≈ 9.3×6 cm, centred at (0.482, 0.257), long axis along x. I'll rotate it 90° so it fits the right compartment. First I'll probe the box-top height." + ], + "viewed": [ + "obs/s022_wrist.jpg", + "obs/s022_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 24, + "kind": "move_eef", + "frame_start": 360, + "frame_end": 414, + "command": "move_eef z=0.045 speed=0.02", + "args": { + "z": 0.045, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3978, + 0.3426, + 0.0475 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.008222579956054688, + "agent_obs_images": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 25, + "kind": "move_eef", + "frame_start": 414, + "frame_end": 664, + "command": "move_eef z=0.015 speed=0.02", + "args": { + "z": 0.015, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 3.3, + "deg": 0.2 + }, + "eef_pos_after": [ + 0.4009, + 0.3477, + 0.0472 + ], + "gripper_width_after": 0.0048, + "holding_after": false, + "touched_during": false, + "think_s": 9.641200542449951, + "agent_obs_images": [ + "obs/s025_agentview.jpg", + "obs/s025_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s024_wrist.jpg", + "obs/s024_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 26, + "kind": "move_eef", + "frame_start": 664, + "frame_end": 690, + "command": "move_eef x=0.483 y=0.257 z=0.1 yaw=0 gripper=open", + "args": { + "x": 0.483, + "y": 0.257, + "z": 0.1, + "yaw": 0, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4859, + 0.2554, + 0.1016 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 14.70488691329956, + "agent_obs_images": [ + "obs/s026_agentview.jpg", + "obs/s026_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Box top ≈ 0.037 (contact at grasp z≈0.047). Card recomputed ≈ 10×6.4 cm. Attempting a grasp on the card's long edges." + ] + } + }, + { + "attempt": 1, + "step": 27, + "kind": "move_eef", + "frame_start": 690, + "frame_end": 713, + "command": "move_eef x=0.472 y=0.2565 z=0.047 speed=0.05", + "args": { + "x": 0.472, + "y": 0.2565, + "z": 0.047, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4724, + 0.2565, + 0.0484 + ], + "gripper_width_after": 0.0792, + "holding_after": false, + "touched_during": false, + "think_s": 8.993658065795898, + "agent_obs_images": [ + "obs/s027_agentview.jpg", + "obs/s027_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s026_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 28, + "kind": "move_eef", + "frame_start": 713, + "frame_end": 729, + "command": "move_eef z=0.047 gripper=close", + "args": { + "z": 0.047, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4731, + 0.2571, + 0.0488 + ], + "gripper_width_after": 0.0077, + "holding_after": false, + "touched_during": true, + "think_s": 0.008104562759399414, + "agent_obs_images": [ + "obs/s028_agentview.jpg", + "obs/s028_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 29, + "kind": "move_eef", + "frame_start": 729, + "frame_end": 979, + "command": "move_eef x=0.583 z=0.042 speed=0.03", + "args": { + "x": 0.583, + "z": 0.042, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.7, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5812, + 0.2603, + 0.0475 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 37.26758885383606, + "agent_obs_images": [ + "obs/s029_agentview.jpg", + "obs/s029_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The card is too thin to pinch on the box, so I'm pressing it down and dragging it past the front edge to pinch the overhang instead." + ], + "viewed": [ + "obs/s028_wrist.jpg", + "obs/s028_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 30, + "kind": "move_eef", + "frame_start": 979, + "frame_end": 998, + "command": "move_eef z=0.075 gripper=open", + "args": { + "z": 0.075, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5818, + 0.2608, + 0.0713 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 11.336684465408325, + "agent_obs_images": [ + "obs/s030_agentview.jpg", + "obs/s030_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s029_wrist.jpg", + "obs/s029_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 31, + "kind": "move_eef", + "frame_start": 998, + "frame_end": 1003, + "command": "move_eef x=0.603 y=0.2596 z=0.075", + "args": { + "x": 0.603, + "y": 0.2596, + "z": 0.075 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5997, + 0.2591, + 0.0736 + ], + "gripper_width_after": 0.0782, + "holding_after": false, + "touched_during": false, + "think_s": 0.009445667266845703, + "agent_obs_images": [ + "obs/s031_agentview.jpg", + "obs/s031_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 32, + "kind": "move_eef", + "frame_start": 1003, + "frame_end": 1025, + "command": "move_eef x=0.555 y=0.2595 z=0.06 gripper=close", + "args": { + "x": 0.555, + "y": 0.2595, + "z": 0.06, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5561, + 0.2601, + 0.0608 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 16.81925082206726, + "agent_obs_images": [ + "obs/s032_agentview.jpg", + "obs/s032_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Card now overhangs the box edge by only about 2 cm. I'll drag it another ~1.5 cm, then pinch." + ], + "viewed": [ + "obs/s031_wrist.jpg", + "obs/s031_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 33, + "kind": "move_eef", + "frame_start": 1025, + "frame_end": 1042, + "command": "move_eef z=0.044 speed=0.02", + "args": { + "z": 0.044, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5567, + 0.2607, + 0.0475 + ], + "gripper_width_after": 0.0012, + "holding_after": false, + "touched_during": true, + "think_s": 0.008226394653320312, + "agent_obs_images": [ + "obs/s033_agentview.jpg", + "obs/s033_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 34, + "kind": "move_eef", + "frame_start": 1042, + "frame_end": 1292, + "command": "move_eef x=0.572 z=0.042 speed=0.02", + "args": { + "x": 0.572, + "z": 0.042, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.6, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5696, + 0.2631, + 0.0475 + ], + "gripper_width_after": 0.0016, + "holding_after": false, + "touched_during": true, + "think_s": 0.011255502700805664, + "agent_obs_images": [ + "obs/s034_agentview.jpg", + "obs/s034_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 35, + "kind": "move_eef", + "frame_start": 1292, + "frame_end": 1311, + "command": "move_eef z=0.075 gripper=open", + "args": { + "z": 0.075, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5701, + 0.2636, + 0.0713 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 0.008970260620117188, + "agent_obs_images": [ + "obs/s035_agentview.jpg", + "obs/s035_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 36, + "kind": "move_eef", + "frame_start": 1311, + "frame_end": 1317, + "command": "move_eef x=0.6 y=0.2596 z=0.075", + "args": { + "x": 0.6, + "y": 0.2596, + "z": 0.075 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5986, + 0.2592, + 0.0746 + ], + "gripper_width_after": 0.0782, + "holding_after": false, + "touched_during": false, + "think_s": 5.149107217788696, + "agent_obs_images": [ + "obs/s036_agentview.jpg", + "obs/s036_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 37, + "kind": "move_eef", + "frame_start": 1317, + "frame_end": 1321, + "command": "move_eef x=0.616 y=0.2598 z=0.075", + "args": { + "x": 0.616, + "y": 0.2598, + "z": 0.075 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6144, + 0.2599, + 0.0755 + ], + "gripper_width_after": 0.0785, + "holding_after": false, + "touched_during": false, + "think_s": 8.466331481933594, + "agent_obs_images": [ + "obs/s037_agentview.jpg", + "obs/s037_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s036_wrist.jpg", + "obs/s036_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 38, + "kind": "move_eef", + "frame_start": 1321, + "frame_end": 1350, + "command": "move_eef z=0.032 speed=0.03", + "args": { + "z": 0.032, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6145, + 0.2598, + 0.0332 + ], + "gripper_width_after": 0.0796, + "holding_after": false, + "touched_during": false, + "think_s": 0.007627248764038086, + "agent_obs_images": [ + "obs/s038_agentview.jpg", + "obs/s038_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 39, + "kind": "move_eef", + "frame_start": 1350, + "frame_end": 1366, + "command": "move_eef z=0.032 gripper=close", + "args": { + "z": 0.032, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6157, + 0.2602, + 0.0339 + ], + "gripper_width_after": 0.0057, + "holding_after": false, + "touched_during": true, + "think_s": 8.974835872650146, + "agent_obs_images": [ + "obs/s039_agentview.jpg", + "obs/s039_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s038_wrist.jpg", + "obs/s038_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 40, + "kind": "move_eef", + "frame_start": 1366, + "frame_end": 1381, + "command": "move_eef z=0.07 speed=0.05", + "args": { + "z": 0.07, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6156, + 0.2602, + 0.0686 + ], + "gripper_width_after": 0.0014, + "holding_after": false, + "touched_during": true, + "think_s": 10.220077991485596, + "agent_obs_images": [ + "obs/s040_agentview.jpg", + "obs/s040_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s039_wrist.jpg", + "obs/s039_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 41, + "kind": "move_eef", + "frame_start": 1381, + "frame_end": 1400, + "command": "move_eef x=0.626 y=0.2605 z=0.07 gripper=open", + "args": { + "x": 0.626, + "y": 0.2605, + "z": 0.07, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6226, + 0.2599, + 0.0686 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 34.39299511909485, + "agent_obs_images": [ + "obs/s041_agentview.jpg", + "obs/s041_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The card slid off the box edge and is leaning, so my pinch at z=0.034 likely closed above it. I'm retrying lower, at x=0.625." + ], + "viewed": [ + "obs/s040_wrist.jpg", + "obs/s040_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 42, + "kind": "move_eef", + "frame_start": 1400, + "frame_end": 1436, + "command": "move_eef z=0.016 speed=0.03", + "args": { + "z": 0.016, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6226, + 0.2598, + 0.0167 + ], + "gripper_width_after": 0.0795, + "holding_after": false, + "touched_during": false, + "think_s": 0.014416933059692383, + "agent_obs_images": [ + "obs/s042_agentview.jpg", + "obs/s042_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 43, + "kind": "move_eef", + "frame_start": 1436, + "frame_end": 1452, + "command": "move_eef z=0.016 gripper=close", + "args": { + "z": 0.016, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.0, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6228, + 0.2598, + 0.0164 + ], + "gripper_width_after": 0.0562, + "holding_after": true, + "touched_during": true, + "think_s": 5.112048149108887, + "agent_obs_images": [ + "obs/s043_agentview.jpg", + "obs/s043_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s042_wrist.jpg", + "obs/s042_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 44, + "kind": "move_eef", + "frame_start": 1452, + "frame_end": 1498, + "command": "move_eef z=0.13 speed=0.05", + "args": { + "z": 0.13, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6228, + 0.2599, + 0.1286 + ], + "gripper_width_after": 0.0562, + "holding_after": true, + "touched_during": true, + "think_s": 4.231663703918457, + "agent_obs_images": [ + "obs/s044_agentview.jpg", + "obs/s044_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Card pinched (width 0.056). Lifting." + ] + } + }, + { + "attempt": 1, + "step": 45, + "kind": "move_eef", + "frame_start": 1498, + "frame_end": 1530, + "command": "move_eef z=0.16 yaw=90 speed=0.05", + "args": { + "z": 0.16, + "yaw": 90, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6252, + 0.2615, + 0.1623 + ], + "gripper_width_after": 0.0562, + "holding_after": true, + "touched_during": true, + "think_s": 14.037616968154907, + "agent_obs_images": [ + "obs/s045_agentview.jpg", + "obs/s045_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Card is held roughly horizontal, gripped about 3.6 cm from its +x end. Next I'll rotate to yaw 90 so the long axis runs along y, then lower it into the right compartment." + ], + "viewed": [ + "obs/s044_wrist.jpg", + "obs/s044_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 46, + "kind": "move_eef", + "frame_start": 1530, + "frame_end": 1590, + "command": "move_eef x=0.45 y=0.023 z=0.16 speed=0.1", + "args": { + "x": 0.45, + "y": 0.023, + "z": 0.16, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4509, + 0.0248, + 0.1597 + ], + "gripper_width_after": 0.0562, + "holding_after": true, + "touched_during": true, + "think_s": 14.580446481704712, + "agent_obs_images": [ + "obs/s046_agentview.jpg", + "obs/s046_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s045_wrist.jpg", + "obs/s045_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 47, + "kind": "move_eef", + "frame_start": 1590, + "frame_end": 1624, + "command": "move_eef z=0.075 speed=0.05", + "args": { + "z": 0.075, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4508, + 0.0248, + 0.0768 + ], + "gripper_width_after": 0.0562, + "holding_after": true, + "touched_during": true, + "think_s": 0.008444786071777344, + "agent_obs_images": [ + "obs/s047_agentview.jpg", + "obs/s047_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 48, + "kind": "move_eef", + "frame_start": 1624, + "frame_end": 1638, + "command": "move_eef y=0.019 z=0.058 speed=0.03", + "args": { + "y": 0.019, + "z": 0.058, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4507, + 0.0192, + 0.0586 + ], + "gripper_width_after": 0.0562, + "holding_after": true, + "touched_during": true, + "think_s": 13.110436916351318, + "agent_obs_images": [ + "obs/s048_agentview.jpg", + "obs/s048_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Card is over the right compartment, with its −y end at about the divider. Shifting 5 mm toward −y, lowering, and releasing." + ], + "viewed": [ + "obs/s047_wrist.jpg", + "obs/s047_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 49, + "kind": "move_eef", + "frame_start": 1638, + "frame_end": 1654, + "command": "move_eef z=0.058 gripper=open", + "args": { + "z": 0.058, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.0, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4505, + 0.0192, + 0.0582 + ], + "gripper_width_after": 0.0778, + "holding_after": false, + "touched_during": true, + "think_s": 0.010113716125488281, + "agent_obs_images": [ + "obs/s049_agentview.jpg", + "obs/s049_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 50, + "kind": "move_eef", + "frame_start": 1654, + "frame_end": 1695, + "command": "move_eef z=0.16 speed=0.05", + "args": { + "z": 0.16, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4503, + 0.0192, + 0.1582 + ], + "gripper_width_after": 0.0796, + "holding_after": false, + "touched_during": false, + "think_s": 0.009321212768554688, + "agent_obs_images": [ + "obs/s050_agentview.jpg", + "obs/s050_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 51, + "kind": "move_eef", + "frame_start": 1695, + "frame_end": 1736, + "command": "move_eef x=0.37 y=-0.026 z=0.16 yaw=0 gripper=close", + "args": { + "x": 0.37, + "y": -0.026, + "z": 0.16, + "yaw": 0, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3676, + -0.026, + 0.1585 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 17.260121822357178, + "agent_obs_images": [ + "obs/s051_agentview.jpg", + "obs/s051_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "All three items are now in the tray, with both cubes on the left and the card flat on the right. Next I'll push the tray about 0.12 m in +x, aiming at its y-centre." + ], + "viewed": [ + "obs/s050_wrist.jpg", + "obs/s050_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 52, + "kind": "move_eef", + "frame_start": 1736, + "frame_end": 1791, + "command": "move_eef z=0.022 speed=0.05", + "args": { + "z": 0.022, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3673, + -0.026, + 0.0234 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.022672176361083984, + "agent_obs_images": [ + "obs/s052_agentview.jpg", + "obs/s052_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 53, + "kind": "move_eef", + "frame_start": 1791, + "frame_end": 1853, + "command": "move_eef x=0.46 speed=0.03", + "args": { + "x": 0.46, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.458, + -0.0259, + 0.0231 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 5.803215503692627, + "agent_obs_images": [ + "obs/s053_agentview.jpg", + "obs/s053_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s052_wrist.jpg", + "obs/s052_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 54, + "kind": "move_eef", + "frame_start": 1853, + "frame_end": 1906, + "command": "move_eef x=0.4 z=0.28 speed=0.1", + "args": { + "x": 0.4, + "z": 0.28, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4003, + -0.0259, + 0.2767 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 12.843408107757568, + "agent_obs_images": [ + "obs/s054_agentview.jpg", + "obs/s054_wrist.jpg" + ], + "agent_note": { + "messages": [ + "The tray rotated about 20° clockwise (+y end ran ahead), so the friction centre is on the cube (−y) side. I'll take a top-down look to re-localise it, then correct by pushing on the −y end." + ], + "viewed": [ + "obs/s053_wrist.jpg", + "obs/s053_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 55, + "kind": "move_eef", + "frame_start": 1906, + "frame_end": 1945, + "command": "move_eef x=0.42 y=-0.105 z=0.1 speed=0.1", + "args": { + "x": 0.42, + "y": -0.105, + "z": 0.1, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4193, + -0.1036, + 0.1032 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 16.039891958236694, + "agent_obs_images": [ + "obs/s055_agentview.jpg", + "obs/s055_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Tray now at centre ≈ (0.533, −0.034), yaw ≈ −20°. Green ≈ x 0.50–0.66, y −0.17–0.12. Pushing on the −y end of the back edge to rotate it back." + ], + "viewed": [ + "obs/s054_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 56, + "kind": "move_eef", + "frame_start": 1945, + "frame_end": 1978, + "command": "move_eef z=0.022 speed=0.05", + "args": { + "z": 0.022, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4191, + -0.1036, + 0.0233 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.00854182243347168, + "agent_obs_images": [ + "obs/s056_agentview.jpg", + "obs/s056_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 57, + "kind": "move_eef", + "frame_start": 1978, + "frame_end": 2049, + "command": "move_eef x=0.49 speed=0.02", + "args": { + "x": 0.49, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4881, + -0.1041, + 0.0229 + ], + "gripper_width_after": 0.0013, + "holding_after": false, + "touched_during": true, + "think_s": 0.008455276489257812, + "agent_obs_images": [ + "obs/s057_agentview.jpg", + "obs/s057_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 58, + "kind": "move_eef", + "frame_start": 2049, + "frame_end": 2102, + "command": "move_eef x=0.43 z=0.28 speed=0.1", + "args": { + "x": 0.43, + "z": 0.28, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4303, + -0.104, + 0.2766 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.007959604263305664, + "agent_obs_images": [ + "obs/s058_agentview.jpg", + "obs/s058_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 59, + "kind": "move_eef", + "frame_start": 2102, + "frame_end": 2172, + "command": "move_eef x=0.68 y=0.06 z=0.1 speed=0.1", + "args": { + "x": 0.68, + "y": 0.06, + "z": 0.1, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6784, + 0.0589, + 0.1014 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 25.184834003448486, + "agent_obs_images": [ + "obs/s059_agentview.jpg", + "obs/s059_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "The tray is nearly de-rotated, but its +y end sits close to green's far edge. Next I'll push that end's front face toward −x to pull it back toward the middle." + ], + "viewed": [ + "obs/s058_wrist.jpg", + "obs/s058_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 60, + "kind": "move_eef", + "frame_start": 2172, + "frame_end": 2204, + "command": "move_eef z=0.022 speed=0.05", + "args": { + "z": 0.022, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6784, + 0.059, + 0.0237 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.012140512466430664, + "agent_obs_images": [ + "obs/s060_agentview.jpg", + "obs/s060_wrist.jpg" + ] + } + ], + "task_events": [ + { + "frame": 205, + "attempt": 1, + "event": { + "step": 205, + "item": "product_red_1", + "event": "achieved" + } + }, + { + "frame": 300, + "attempt": 1, + "event": { + "step": 300, + "item": "product_blue_1", + "event": "achieved" + } + }, + { + "frame": 1650, + "attempt": 1, + "event": { + "step": 1650, + "item": "card_1", + "event": "achieved" + } + }, + { + "frame": 1830, + "attempt": 1, + "event": { + "step": 1830, + "item": "card_1", + "event": "lost" + } + }, + { + "frame": 1835, + "attempt": 1, + "event": { + "step": 1835, + "item": "card_1", + "event": "achieved" + } + } + ], + "frames": { + "n": 2234, + "fps": 20, + "image_res": 256, + "phase_codes": { + "move": 0, + "gripper": 1, + "judge": 2 + }, + "initial_state": { + "eef_pos": [ + -0.20846466056582388, + -1.802184331338459e-14, + 1.1732794757296403 + ], + "joint_pos": [ + 3.547085228866256e-14, + -0.16103738899999992, + -2.854008519056826e-14, + -2.44459747, + -2.0128903971203067e-13, + 2.2267522, + 0.7853981633973847 + ], + "gripper_qpos": [ + 0.020435218182355795, + -0.02043518935550428 + ] + } + }, + "episode_index": 2325, + "dataset_index_range": [ + 3800616, + 3802850 + ], + "label_provenance": { + "task_cause_source": "leaf/release/evidence/causes.json", + "recovery_review_source": "leaf/release/label_audit.jsonl", + "recovery_review_applied": false + } +} diff --git a/leaf/annotations/episode_002437.json b/leaf/annotations/episode_002437.json new file mode 100644 index 0000000000000000000000000000000000000000..07a1947932661028dd4d1826fac1db7c36ea37b2 --- /dev/null +++ b/leaf/annotations/episode_002437.json @@ -0,0 +1,1879 @@ +{ + "schema": "leaf-replay-1", + "source": { + "batch": "remaining_lh_20261103_opus", + "run": "remaining_lh_20261103_opus-claude-opus-5-5-claudecodefull-harness-hidek_lh_desk_organizer_s3001_full_F1_direct_k3_1104-041608_p27101", + "attempts_in_episode": [ + 2 + ], + "episode_in_run": 1, + "condition": "with_history", + "memory_free_chain_of": null, + "memory_free_rep": null, + "feedback_level": "F1", + "hide_k": true, + "k": 3, + "perception": "rgb", + "instruction_variant": "direct", + "contract_sha256": "9cc02a04c565dfeeead66b3a678804d711c4621d0dcca3ba2dbd53709905bd2a", + "run_status": "done", + "manifest_id": "0001", + "replay": { + "n_reports_checked": 360, + "n_mismatch": 0, + "max_eef_dev_m": 0.0 + }, + "backfill_provenance": { + "original_run": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source/runs/api/remaining_lh_20261103_opus/remaining_lh_20261103_opus-claude-opus-5-5-claudecodefull-harness-hidek_lh_desk_organizer_s3001_full_F1_direct_k3_1104-041608_p27101", + "frozen_run": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source/runs/api/remaining_lh_20261103_opus/remaining_lh_20261103_opus-claude-opus-5-5-claudecodefull-harness-hidek_lh_desk_organizer_s3001_full_F1_direct_k3_1104-041608_p27101", + "runtime": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source" + }, + "evaluation_config": { + "cond": "harness", + "arm": "none", + "red_team": false, + "feedback": "F1", + "mem": "full", + "k": 3, + "rep": 0, + "dossier": null, + "task": "lh_desk_organizer", + "seed": 3001 + }, + "release_origin": { + "dataset": "remaining-lh-20261103-remaining_lh_20261103_opus", + "episode_index": 2 + }, + "release_episode_index": 2437, + "pre_v181_sidecar_index": { + "episode_index": 2, + "dataset_index_range": [ + 25029, + 29028 + ] + } + }, + "agent": { + "harness": "claude_code_full", + "harness_version": "2.1.299", + "harness_binary_sha256": "2d894a4b1bfaaa9aab72aeff7803e3c73bc2510f279a171f6b8f59f72d17d077", + "model": "claude-opus-5-5", + "effort": "high", + "provider": "anthropic", + "codex_catalog": null, + "auth": "oauth", + "jail": true + }, + "task": { + "name": "lh_desk_organizer", + "level": "L2", + "family": "long_horizon", + "category": "state_restoration", + "capabilities": [ + "Perceive", + "Reason", + "Restore", + "Plan" + ], + "protocol": "cross", + "max_attempts": 3, + "agent_max_steps": 360, + "instruction": "Clear the desk: place the red paperweight, the lidded mug and the yellow supply jar upright on the side tray, and put the black book into the organizer bin. Leave the book fully clear of the tray, all items stable, and the gripper open and clear. The mug and small jars have graspable lid knobs. The book has a side pull tab. The book must end in the organizer, not underneath the tray.", + "seed": 3001, + "instance": { + "seed": 3001, + "loose": true, + "bracket": "loose", + "side": "right", + "shelf_x": -0.15, + "wall_y": -0.26, + "preload": 0.6631768686473195, + "damping": 0.45, + "stiffness": 2.5, + "start": { + "red": [ + -0.32, + 0.02 + ], + "green": [ + -0.33, + -0.1 + ], + "blue": [ + -0.12, + 0.18 + ], + "yellow": [ + 0.049897955763541425, + 0.1888214678550895 + ] + }, + "yaw0": { + "red": 0.0, + "green": 0.0, + "blue": 0.0, + "yellow": 0.0 + }, + "mu": { + "red": 0.8, + "green": 0.15, + "blue": 0.18, + "yellow": 0.25 + }, + "mass": { + "red": 0.6, + "green": 0.15, + "blue": 0.08, + "yellow": 0.06 + }, + "naive_bias": -0.009264686289624784, + "bias": [ + 0, + -0.065, + 0 + ], + "bin_xy": [ + -0.3, + 0.25 + ] + }, + "failure_causes": [ + "L1", + "L3", + "L2" + ], + "subset": "compound_long_horizon", + "failure_causes_scope": "designed task mechanisms; not observed model events", + "paper": { + "original_cause": null, + "original_table_cause": null, + "cause": "L6", + "table_cause": "L6" + }, + "canonical_cause": "L6", + "paper_long_horizon": true, + "instruction_original": "Clear the desk: place the red paperweight, the lidded mug and the yellow supply jar upright on the side tray, and put the black book into the organizer bin. Leave the book fully clear of the tray, all items stable, and the gripper open and clear. The mug and small jars have graspable lid knobs. The book has a side pull tab. The book must end in the organizer, not underneath the tray." + }, + "run_outcome": { + "outcome_class": "XR", + "attempt_history": "FFS", + "n_attempts": 3, + "run_success": true, + "agent_final_report": "The task succeeded on attempt 3 of 3. The book is lying flat inside the organizer bin, and the red paperweight, yellow jar and mug are standing upright on the side tray.\n\n**How the attempts went**\n- **Attempt 1 (failed):** I spent most of it working out the scene, then hit the 460 tool-call limit before finishing. The README said there was only one attempt, but the environment then offered two more.\n- **Attempt 2 (failed):** Everything looked correct: all three items upright on the tray and the book standing upright in the bin. The environment only reported \"failed\" without a reason. My best guess is the standing book, whose top stuck up above the bin's rim, but I can't confirm that.\n- **Attempt 3 (succeeded):** I repeated attempt 2 except that I pushed the book over so it lay flat. Its pull tab ended up hanging over the bin wall, so I gripped the book across its length, lifted it, moved it 6 cm toward the bin's centre and set it down. That left the book and tab fully inside.\n\n**Commands that worked (attempts 2 and 3; the scene resets identically)**\n- **Book:** close on the tab block at x=0.255, y=-0.035, z=0.015 (yaw 0). Pull to x=0.21, then y=-0.01, then lift to z=0.08. The grip slips but the book comes out from under the tray. Then grab the book itself at x=0.297, y=-0.019, z=0.05, carry it at z=0.25 to x=0.41, y=0.31 over the bin, lower to z=0.10 and open.\n- **Grasping the jars and mug:** from above by the knob, at z≈0.08 for the red paperweight and yellow jar and z≈0.073 for the mug.\n- **Moving them:** lift to z=0.3, turn the gripper only at that height, and carry at speed 0.03–0.05. Faster moves made the knob slip.\n- **Placing them:** red paperweight at x≈0.59, y≈-0.145 and yellow jar at x≈0.42, y≈-0.147, both close to the wall. Mug at x≈0.51, y≈-0.12, with the gripper turned to yaw 45 so the handle points away from the other items. I let go of each about 1 cm above the tray instead of pressing down.\n\n**What I observed and how I changed my approach**\n- **The tray is not rigid.** It tilts when pressed or loaded, especially away from the wall. The red paperweight is heavy, and placing it far from the wall tipped the tray enough for things to slide off. Even in the successful layout the tray tilts slightly, about 5° by my estimate; it held steady.\n- **The mug kept getting thrown off the tray.** This happened when its handle overlapped another item or the wall. Turning the gripper to point the handle into open space fixed it.\n- **The arm got stuck in a twisted pose (attempt 1).** The hand hit the wall while the gripper was at yaw 0 near it, flipping the wrist into a configuration where most targets were unreachable. I recovered by working out the arm's kinematics offline and passing through a pose with the forearm hanging vertically. After that I kept the hand away from the wall and always lifted before moving sideways.\n- **Lower and slower lateral moves knocked items over in attempt 1.** That is why every move between pick and place went through z=0.3 in the later attempts.\n\nMy notes and coordinates are in `notes.md` in the workspace. I couldn't write to the persistent memory directory because the shell couldn't reach that path, so this run's lessons won't carry over to future sessions.", + "mean_think_s": 9.93, + "outcome_class_original": "XR", + "outcome_class_status": "rule_derived" + }, + "attempts": [ + { + "attempt": 2, + "success": false, + "outcome": { + "success": false, + "stages": { + "paperweight": true, + "mug": false, + "supplies": true, + "book_stowed": true, + "gripper_open": true, + "gripper_clear": true + }, + "static": true, + "tray_deg": 8.465887574647121, + "traps": { + "L1": false, + "L3": false, + "L2": false + }, + "recovered": { + "L1": false, + "L3": false, + "L2": false + }, + "detail": "Tray objects: {'paperweight': True, 'mug': False, 'supplies': True, 'book_stowed': True, 'gripper_open': True, 'gripper_clear': True}; tray angle 8.5 degrees." + }, + "finish_reason": "Book extracted via tab and placed in organizer bin; red paperweight, yellow jar and mug placed upright on the side tray near the wall; tray stable; gripper open and clear.", + "feedback_shown": "Attempt failed.", + "auto_ended": false, + "think_s": 16.689571619033813, + "feedback_f2": "Attempt failed. Tray objects: {'paperweight': True, 'mug': False, 'supplies': True, 'book_stowed': True, 'gripper_open': True, 'gripper_clear': True}; tray angle 8.5 degrees.", + "judge_frames": [ + 3849, + 3999 + ], + "corrected_later_in_run": true, + "is_last_attempt_of_run": false, + "agent_finish": { + "shell": [ + "python3 tilt.py a2_s046", + "M=/tmp/lffstate/7d3d174737d7/config/projects/-tmp-lffrun-7d3d174737d7/memory; cat > $M/panda-desk-clearing-lessons.md <<'EOF'\n---\nname: panda-desk-clearing-lessons\ndescription: Lessons from the Panda \"clear the desk\" sim task (tray/book/knob jars) - budgets, wrist-flip recovery, soft tray placement\nmetadata:\n type: project\n---\nPanda sim desk-clearing task (2026-11-03): attempt 1 failed by exhausting the 460 tool-call budget; attempt 2 succeeded in ~50 commands.\n**Why:** too much exploration, a hand-vs-wall collision flipped the wrist, and placements pressed on a soft hinged tray.\n**How to apply:** budget tool calls (few view_images); pull the book out by its tab first, then grasp the book body and drop it into the bin; grasp knobs from above; lift to z>=0.3 before lateral/yaw moves; release items ~1 cm above the tray (don't press); keep the mug handle clear of other items; at yaw 0 keep the hand away from walls. To recover a flipped wrist, move through a forearm-vertical pose (e.g. x=0.25 y=0 z=0.06 yaw=0). Workspace notes.md has the coordinates.\nEOF\necho \"- [Panda desk clearing lessons](panda-desk-clearing-lessons.md) — budgets, wrist-flip recovery, soft-tray placement\" >> $M/MEMORY.md; echo ok" + ], + "viewed": [ + "obs/a2_s046_agentview.jpg", + "obs/a2_s046_wrist.jpg" + ], + "command": "finish reason=\"Book extracted via tab and placed in organizer bin; red paperweight, yellow jar and mug placed upright on the side tray near the wall; tray stable; gripper open and clear.\"", + "reply": { + "feedback": "Attempt failed.", + "message": "Attempt 3 of 3 starts now. The scene has been reset to exactly the same initial state." + } + }, + "error_event_in_attempt": null, + "agent_reflection_after_feedback": {}, + "reviewed_operational_failure": null + } + ], + "commands": [ + { + "attempt": 2, + "step": 2, + "kind": "move_eef", + "frame_start": 0, + "frame_end": 26, + "command": "move_eef z=0.3 speed=0.03", + "args": { + "z": 0.3, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4514, + 0.065, + 0.2988 + ], + "gripper_width_after": 0.0788, + "holding_after": false, + "touched_during": false, + "think_s": 0.008445501327514648, + "agent_obs_images": [ + "obs/a2_s002_agentview.jpg", + "obs/a2_s002_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 3, + "kind": "move_eef", + "frame_start": 26, + "frame_end": 276, + "command": "move_eef x=0.25 y=-0.035 z=0.1 yaw=0", + "args": { + "x": 0.25, + "y": -0.035, + "z": 0.1, + "yaw": 0 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.5, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.2538, + -0.0368, + 0.1018 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 52.86708998680115, + "agent_obs_images": [ + "obs/a2_s003_agentview.jpg", + "obs/a2_s003_wrist.jpg" + ], + "agent_note": { + "shell": [ + "cat > notes.md <<'EOF'\n# Notes (attempt 1 learnings)\n- Tool-call budget (460) is binding. Minimize view_images.\n- Wrist cam: knob aligned under grasp when at eef z~0.12 knob appears ~row 385, col ~256.\n- Initial knobs: red jar (0.3475,0.0841) grasp z=0.0805 yaw0; mug (0.541,0.246) z=0.0727; yellow (0.706,0.2475) z=0.0808.\n- Book tab block grasp (0.2494,-0.0333) z=0.015 yaw0; pull -x to ~0.216 max (joint limit).\n- Book got lifted out stuck on gripper after: regrasp (0.245,-0.047,0.018), pull x=0.22, y=-0.02, open, lift to (0.27,-0.0235,0.3). Dropped into bin by moving to (0.39,0.305,0.22).\n- Tray top z~0.09, x~0.36-0.67, y -0.175 (wall face) .. -0.035. Tray is soft: pressing tilts it. Release items ~1cm above contact (knob-held jars release at z~0.174, mug 0.175).\n- Red paperweight heavy -> place near wall (0.594,-0.141). Yellow (0.42,-0.147). Mug (0.51,-0.10) yaw45 so handle points +x+y (handle overlap ejects mug).\n- NEVER: yaw0 near wall at low z (hand hits wall -> wrist flips). Recovery: move_eef x=0.25 y=0 z=0.06 yaw=0 from forearm-vertical pose.\n- Always lift to z>=0.3 before lateral moves/yaw changes; carry speed<=0.05.\nEOF\necho ok" + ], + "viewed": [ + "obs/s254_agentview.jpg", + "obs/s254_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 4, + "kind": "move_eef", + "frame_start": 276, + "frame_end": 295, + "command": "move_eef z=0.04 speed=0.08", + "args": { + "z": 0.04, + "speed": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.2504, + -0.0351, + 0.0399 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": true, + "think_s": 0.008109569549560547, + "agent_obs_images": [ + "obs/a2_s004_agentview.jpg", + "obs/a2_s004_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 5, + "kind": "move_eef", + "frame_start": 295, + "frame_end": 313, + "command": "move_eef x=0.255 z=0.015 speed=0.05", + "args": { + "x": 0.255, + "z": 0.015, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.2526, + -0.0341, + 0.0142 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": true, + "think_s": 0.007477521896362305, + "agent_obs_images": [ + "obs/a2_s005_agentview.jpg", + "obs/a2_s005_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 6, + "kind": "move_eef", + "frame_start": 313, + "frame_end": 328, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.2536, + -0.0346, + 0.0145 + ], + "gripper_width_after": 0.0237, + "holding_after": true, + "touched_during": true, + "think_s": 4.6830761432647705, + "agent_obs_images": [ + "obs/a2_s006_agentview.jpg", + "obs/a2_s006_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s005_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 7, + "kind": "move_eef", + "frame_start": 328, + "frame_end": 578, + "command": "move_eef x=0.21 speed=0.03", + "args": { + "x": 0.21, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 1.0, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.2185, + -0.0388, + 0.0159 + ], + "gripper_width_after": 0.0235, + "holding_after": true, + "touched_during": true, + "think_s": 0.007493495941162109, + "agent_obs_images": [ + "obs/a2_s007_agentview.jpg", + "obs/a2_s007_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 8, + "kind": "move_eef", + "frame_start": 578, + "frame_end": 828, + "command": "move_eef y=-0.01 speed=0.02", + "args": { + "y": -0.01, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 1.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.2298, + -0.0141, + 0.0177 + ], + "gripper_width_after": 0.0235, + "holding_after": true, + "touched_during": true, + "think_s": 0.007359027862548828, + "agent_obs_images": [ + "obs/a2_s008_agentview.jpg", + "obs/a2_s008_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 9, + "kind": "move_eef", + "frame_start": 828, + "frame_end": 1078, + "command": "move_eef z=0.08 speed=0.02", + "args": { + "z": 0.08, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 2.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.251, + -0.0223, + 0.0887 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 5.969132900238037, + "agent_obs_images": [ + "obs/a2_s009_agentview.jpg", + "obs/a2_s009_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 10, + "kind": "move_eef", + "frame_start": 1078, + "frame_end": 1124, + "command": "move_eef x=0.33 z=0.3 speed=0.1", + "args": { + "x": 0.33, + "z": 0.3, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3294, + -0.0224, + 0.2982 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 11.42129921913147, + "agent_obs_images": [ + "obs/a2_s010_agentview.jpg", + "obs/a2_s010_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s009_agentview.jpg", + "obs/a2_s009_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 11, + "kind": "move_eef", + "frame_start": 1124, + "frame_end": 1153, + "command": "move_eef x=0.29 y=-0.019 z=0.14 gripper=open", + "args": { + "x": 0.29, + "y": -0.019, + "z": 0.14, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.2872, + -0.0184, + 0.1385 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 13.350710153579712, + "agent_obs_images": [ + "obs/a2_s011_agentview.jpg", + "obs/a2_s011_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s010_agentview.jpg", + "obs/a2_s010_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 12, + "kind": "move_eef", + "frame_start": 1153, + "frame_end": 1198, + "command": "move_eef x=0.297 z=0.05 speed=0.04", + "args": { + "x": 0.297, + "z": 0.05, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.2989, + -0.0188, + 0.0526 + ], + "gripper_width_after": 0.0797, + "holding_after": false, + "touched_during": true, + "think_s": 9.189087867736816, + "agent_obs_images": [ + "obs/a2_s012_agentview.jpg", + "obs/a2_s012_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s011_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 13, + "kind": "move_eef", + "frame_start": 1198, + "frame_end": 1213, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.3013, + -0.0192, + 0.0543 + ], + "gripper_width_after": 0.0273, + "holding_after": true, + "touched_during": true, + "think_s": 0.008873939514160156, + "agent_obs_images": [ + "obs/a2_s013_agentview.jpg", + "obs/a2_s013_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 14, + "kind": "move_eef", + "frame_start": 1213, + "frame_end": 1311, + "command": "move_eef z=0.25 speed=0.04", + "args": { + "z": 0.25, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3008, + -0.0191, + 0.2481 + ], + "gripper_width_after": 0.0273, + "holding_after": true, + "touched_during": true, + "think_s": 6.3873114585876465, + "agent_obs_images": [ + "obs/a2_s014_agentview.jpg", + "obs/a2_s014_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 15, + "kind": "move_eef", + "frame_start": 1311, + "frame_end": 1444, + "command": "move_eef x=0.39 y=0.3 speed=0.05", + "args": { + "x": 0.39, + "y": 0.3, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3894, + 0.2986, + 0.2478 + ], + "gripper_width_after": 0.0273, + "holding_after": true, + "touched_during": true, + "think_s": 0.008322954177856445, + "agent_obs_images": [ + "obs/a2_s015_agentview.jpg", + "obs/a2_s015_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 16, + "kind": "move_eef", + "frame_start": 1444, + "frame_end": 1518, + "command": "move_eef z=0.1 speed=0.04", + "args": { + "z": 0.1, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.389, + 0.2984, + 0.1011 + ], + "gripper_width_after": 0.0273, + "holding_after": true, + "touched_during": true, + "think_s": 0.00956106185913086, + "agent_obs_images": [ + "obs/a2_s016_agentview.jpg", + "obs/a2_s016_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 17, + "kind": "move_eef", + "frame_start": 1518, + "frame_end": 1533, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.3888, + 0.2985, + 0.101 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 4.960134744644165, + "agent_obs_images": [ + "obs/a2_s017_agentview.jpg", + "obs/a2_s017_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s016_agentview.jpg", + "obs/a2_s016_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 18, + "kind": "move_eef", + "frame_start": 1533, + "frame_end": 1613, + "command": "move_eef z=0.3 speed=0.05", + "args": { + "z": 0.3, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3887, + 0.2985, + 0.2984 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 0.00788426399230957, + "agent_obs_images": [ + "obs/a2_s018_agentview.jpg", + "obs/a2_s018_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 19, + "kind": "move_eef", + "frame_start": 1613, + "frame_end": 1628, + "command": "move_eef x=0.3475 y=0.0841 z=0.12 yaw=0", + "args": { + "x": 0.3475, + "y": 0.0841, + "z": 0.12, + "yaw": 0 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.3442, + 0.0839, + 0.1183 + ], + "gripper_width_after": 0.0795, + "holding_after": false, + "touched_during": false, + "think_s": 5.967599630355835, + "agent_obs_images": [ + "obs/a2_s019_agentview.jpg", + "obs/a2_s019_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s018_agentview.jpg" + ] + } + }, + { + "attempt": 2, + "step": 20, + "kind": "move_eef", + "frame_start": 1628, + "frame_end": 1654, + "command": "move_eef z=0.08 speed=0.03", + "args": { + "z": 0.08, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3441, + 0.0839, + 0.0808 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 5.543145656585693, + "agent_obs_images": [ + "obs/a2_s020_agentview.jpg", + "obs/a2_s020_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s019_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 21, + "kind": "move_eef", + "frame_start": 1654, + "frame_end": 1669, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.3439, + 0.084, + 0.0807 + ], + "gripper_width_after": 0.0214, + "holding_after": true, + "touched_during": true, + "think_s": 0.008117914199829102, + "agent_obs_images": [ + "obs/a2_s021_agentview.jpg", + "obs/a2_s021_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 22, + "kind": "move_eef", + "frame_start": 1669, + "frame_end": 1816, + "command": "move_eef z=0.3 speed=0.03", + "args": { + "z": 0.3, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3429, + 0.084, + 0.2978 + ], + "gripper_width_after": 0.0214, + "holding_after": true, + "touched_during": true, + "think_s": 4.758778810501099, + "agent_obs_images": [ + "obs/a2_s022_agentview.jpg", + "obs/a2_s022_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 23, + "kind": "move_eef", + "frame_start": 1816, + "frame_end": 2041, + "command": "move_eef x=0.594 y=-0.141 yaw=90 speed=0.03", + "args": { + "x": 0.594, + "y": -0.141, + "yaw": 90, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5924, + -0.14, + 0.2957 + ], + "gripper_width_after": 0.0213, + "holding_after": true, + "touched_during": true, + "think_s": 0.009217262268066406, + "agent_obs_images": [ + "obs/a2_s023_agentview.jpg", + "obs/a2_s023_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 24, + "kind": "move_eef", + "frame_start": 2041, + "frame_end": 2291, + "command": "move_eef z=0.18 speed=0.03", + "args": { + "z": 0.18, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5945, + -0.1387, + 0.1833 + ], + "gripper_width_after": 0.0214, + "holding_after": true, + "touched_during": true, + "think_s": 5.751590728759766, + "agent_obs_images": [ + "obs/a2_s024_agentview.jpg", + "obs/a2_s024_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 25, + "kind": "move_eef", + "frame_start": 2291, + "frame_end": 2447, + "command": "move_eef z=0.174 speed=0.01", + "args": { + "z": 0.174, + "speed": 0.01 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5965, + -0.1371, + 0.177 + ], + "gripper_width_after": 0.0214, + "holding_after": true, + "touched_during": true, + "think_s": 0.010064840316772461, + "agent_obs_images": [ + "obs/a2_s025_agentview.jpg", + "obs/a2_s025_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 26, + "kind": "move_eef", + "frame_start": 2447, + "frame_end": 2462, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5966, + -0.137, + 0.1771 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 17.527442693710327, + "agent_obs_images": [ + "obs/a2_s026_agentview.jpg", + "obs/a2_s026_wrist.jpg" + ], + "agent_note": { + "shell": [ + "cat > tilt.py <<'EOF'\nimport sys\nfrom PIL import Image\nimport numpy as np\nfor n in sys.argv[1:]:\n im=np.array(Image.open('obs/%s_agentview.jpg'%n).convert('RGB')).astype(int)\n r,g,b=im[...,0],im[...,1],im[...,2]\n m=(r-b>45)&(r>90)&(r<200)&(g>50)\n out=[]\n for c in [80,120,160,200,210]:\n rows=np.where(m[150:400,c])[0]\n out.append(int(150+rows.max()) if len(rows) else -1)\n print(n,out)\nEOF\npython3 tilt.py a2_s023 a2_s024 a2_s025" + ], + "viewed": [ + "obs/a2_s025_agentview.jpg", + "obs/a2_s025_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 27, + "kind": "move_eef", + "frame_start": 2462, + "frame_end": 2524, + "command": "move_eef z=0.3 speed=0.04", + "args": { + "z": 0.3, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5966, + -0.1369, + 0.2988 + ], + "gripper_width_after": 0.0798, + "holding_after": false, + "touched_during": false, + "think_s": 0.007960081100463867, + "agent_obs_images": [ + "obs/a2_s027_agentview.jpg", + "obs/a2_s027_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 28, + "kind": "move_eef", + "frame_start": 2524, + "frame_end": 2563, + "command": "move_eef x=0.7062 y=0.2475 z=0.12 yaw=0", + "args": { + "x": 0.7062, + "y": 0.2475, + "z": 0.12, + "yaw": 0 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.7087, + 0.2479, + 0.1219 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 6.838164329528809, + "agent_obs_images": [ + "obs/a2_s028_agentview.jpg", + "obs/a2_s028_wrist.jpg" + ], + "agent_note": { + "shell": [ + "python3 tilt.py a2_s026 a2_s027" + ] + } + }, + { + "attempt": 2, + "step": 29, + "kind": "move_eef", + "frame_start": 2563, + "frame_end": 2592, + "command": "move_eef x=0.713 y=0.2515 z=0.08 speed=0.03", + "args": { + "x": 0.713, + "y": 0.2515, + "z": 0.08, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.713, + 0.2514, + 0.0807 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 5.635899782180786, + "agent_obs_images": [ + "obs/a2_s029_agentview.jpg", + "obs/a2_s029_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s028_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 30, + "kind": "move_eef", + "frame_start": 2592, + "frame_end": 2607, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.7131, + 0.2514, + 0.0808 + ], + "gripper_width_after": 0.0214, + "holding_after": true, + "touched_during": true, + "think_s": 0.00987386703491211, + "agent_obs_images": [ + "obs/a2_s030_agentview.jpg", + "obs/a2_s030_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 31, + "kind": "move_eef", + "frame_start": 2607, + "frame_end": 2717, + "command": "move_eef z=0.3 speed=0.04", + "args": { + "z": 0.3, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.7128, + 0.2514, + 0.2984 + ], + "gripper_width_after": 0.0214, + "holding_after": true, + "touched_during": true, + "think_s": 5.1390299797058105, + "agent_obs_images": [ + "obs/a2_s031_agentview.jpg", + "obs/a2_s031_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 32, + "kind": "move_eef", + "frame_start": 2717, + "frame_end": 2965, + "command": "move_eef x=0.42 y=-0.147 yaw=-90 speed=0.04", + "args": { + "x": 0.42, + "y": -0.147, + "yaw": -90, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4205, + -0.1462, + 0.2982 + ], + "gripper_width_after": 0.0214, + "holding_after": true, + "touched_during": true, + "think_s": 0.007955074310302734, + "agent_obs_images": [ + "obs/a2_s032_agentview.jpg", + "obs/a2_s032_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 33, + "kind": "move_eef", + "frame_start": 2965, + "frame_end": 3041, + "command": "move_eef z=0.185 speed=0.03", + "args": { + "z": 0.185, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4209, + -0.1461, + 0.1863 + ], + "gripper_width_after": 0.0214, + "holding_after": true, + "touched_during": true, + "think_s": 0.009717226028442383, + "agent_obs_images": [ + "obs/a2_s033_agentview.jpg", + "obs/a2_s033_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 34, + "kind": "move_eef", + "frame_start": 3041, + "frame_end": 3056, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.4209, + -0.1461, + 0.1863 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 6.728974342346191, + "agent_obs_images": [ + "obs/a2_s034_agentview.jpg", + "obs/a2_s034_wrist.jpg" + ], + "agent_note": { + "shell": [ + "python3 tilt.py a2_s032 a2_s033" + ] + } + }, + { + "attempt": 2, + "step": 35, + "kind": "move_eef", + "frame_start": 3056, + "frame_end": 3113, + "command": "move_eef z=0.3 speed=0.04", + "args": { + "z": 0.3, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4208, + -0.1461, + 0.2985 + ], + "gripper_width_after": 0.0798, + "holding_after": false, + "touched_during": false, + "think_s": 0.008503198623657227, + "agent_obs_images": [ + "obs/a2_s035_agentview.jpg", + "obs/a2_s035_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 36, + "kind": "move_eef", + "frame_start": 3113, + "frame_end": 3147, + "command": "move_eef x=0.5412 y=0.2462 z=0.12 yaw=0", + "args": { + "x": 0.5412, + "y": 0.2462, + "z": 0.12, + "yaw": 0 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5438, + 0.2476, + 0.1218 + ], + "gripper_width_after": 0.0798, + "holding_after": false, + "touched_during": false, + "think_s": 9.036194801330566, + "agent_obs_images": [ + "obs/a2_s036_agentview.jpg", + "obs/a2_s036_wrist.jpg" + ], + "agent_note": { + "shell": [ + "python3 tilt.py a2_s034 a2_s035" + ], + "viewed": [ + "obs/a2_s035_agentview.jpg", + "obs/a2_s035_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 37, + "kind": "move_eef", + "frame_start": 3147, + "frame_end": 3180, + "command": "move_eef x=0.5445 y=0.2462 z=0.0727 speed=0.03", + "args": { + "x": 0.5445, + "y": 0.2462, + "z": 0.0727, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5445, + 0.2461, + 0.0737 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 5.232751846313477, + "agent_obs_images": [ + "obs/a2_s037_agentview.jpg", + "obs/a2_s037_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s036_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 38, + "kind": "move_eef", + "frame_start": 3180, + "frame_end": 3195, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5444, + 0.2462, + 0.0736 + ], + "gripper_width_after": 0.0213, + "holding_after": true, + "touched_during": true, + "think_s": 0.007971525192260742, + "agent_obs_images": [ + "obs/a2_s038_agentview.jpg", + "obs/a2_s038_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 39, + "kind": "move_eef", + "frame_start": 3195, + "frame_end": 3309, + "command": "move_eef z=0.3 speed=0.04", + "args": { + "z": 0.3, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5443, + 0.2462, + 0.2988 + ], + "gripper_width_after": 0.0213, + "holding_after": true, + "touched_during": true, + "think_s": 5.244566917419434, + "agent_obs_images": [ + "obs/a2_s039_agentview.jpg", + "obs/a2_s039_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 40, + "kind": "move_eef", + "frame_start": 3309, + "frame_end": 3483, + "command": "move_eef x=0.51 y=-0.1 yaw=45 speed=0.04", + "args": { + "x": 0.51, + "y": -0.1, + "yaw": 45, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5099, + -0.0984, + 0.2985 + ], + "gripper_width_after": 0.0213, + "holding_after": true, + "touched_during": true, + "think_s": 0.008249759674072266, + "agent_obs_images": [ + "obs/a2_s040_agentview.jpg", + "obs/a2_s040_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 41, + "kind": "move_eef", + "frame_start": 3483, + "frame_end": 3559, + "command": "move_eef z=0.185 speed=0.03", + "args": { + "z": 0.185, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5098, + -0.0983, + 0.1858 + ], + "gripper_width_after": 0.0213, + "holding_after": true, + "touched_during": true, + "think_s": 0.008547544479370117, + "agent_obs_images": [ + "obs/a2_s041_agentview.jpg", + "obs/a2_s041_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 42, + "kind": "move_eef", + "frame_start": 3559, + "frame_end": 3570, + "command": "move_eef z=0.175 speed=0.02", + "args": { + "z": 0.175, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5098, + -0.0982, + 0.1756 + ], + "gripper_width_after": 0.0213, + "holding_after": true, + "touched_during": true, + "think_s": 7.5431294441223145, + "agent_obs_images": [ + "obs/a2_s042_agentview.jpg", + "obs/a2_s042_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s041_wrist.jpg", + "obs/a2_s041_agentview.jpg" + ] + } + }, + { + "attempt": 2, + "step": 43, + "kind": "move_eef", + "frame_start": 3570, + "frame_end": 3585, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5098, + -0.0983, + 0.1756 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 0.011759042739868164, + "agent_obs_images": [ + "obs/a2_s043_agentview.jpg", + "obs/a2_s043_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 44, + "kind": "move_eef", + "frame_start": 3585, + "frame_end": 3668, + "command": "move_eef z=0.3 speed=0.03", + "args": { + "z": 0.3, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5097, + -0.0983, + 0.2988 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 0.008571863174438477, + "agent_obs_images": [ + "obs/a2_s044_agentview.jpg", + "obs/a2_s044_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 2, + "step": 45, + "kind": "move_eef", + "frame_start": 3668, + "frame_end": 3761, + "command": "move_eef x=0.45 y=0.1 z=0.4 yaw=0 speed=0.05", + "args": { + "x": 0.45, + "y": 0.1, + "z": 0.4, + "yaw": 0, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4502, + 0.099, + 0.3993 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 5.501767635345459, + "agent_obs_images": [ + "obs/a2_s045_agentview.jpg", + "obs/a2_s045_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/a2_s044_agentview.jpg", + "obs/a2_s044_wrist.jpg" + ] + } + }, + { + "attempt": 2, + "step": 46, + "kind": "move_eef", + "frame_start": 3761, + "frame_end": 3849, + "command": "move_eef x=0.4 y=0.15 z=0.45 speed=0.02", + "args": { + "x": 0.4, + "y": 0.15, + "z": 0.45, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4003, + 0.1495, + 0.4495 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 6.368104696273804, + "agent_obs_images": [ + "obs/a2_s046_agentview.jpg", + "obs/a2_s046_wrist.jpg" + ], + "agent_note": { + "shell": [ + "python3 tilt.py a2_s042 a2_s043 a2_s044 a2_s045" + ], + "viewed": [ + "obs/a2_s045_agentview.jpg" + ] + } + } + ], + "task_events": [ + { + "frame": 2109, + "attempt": 2, + "event": { + "event": "sag_start", + "step": 2109, + "board_deg": 2.47, + "moment_Nm": 0.0, + "preload_Nm": 0.663, + "after_placing": null, + "dt_since_placement_s": null, + "n_on_board": 0 + } + }, + { + "frame": 2114, + "attempt": 2, + "event": { + "event": "sag", + "step": 2114, + "board_deg": 9.24, + "moment_Nm": 0.0, + "after_placing": null, + "sag_start_after": null, + "dt_since_placement_s": null, + "dt_since_sag_start_s": 0.25, + "in_final_settle": false + } + }, + { + "frame": 2458, + "attempt": 2, + "event": { + "stage": "red", + "event": "achieved", + "step": 2449, + "r_cm": 5.0, + "moment_Nm": 0.314 + } + }, + { + "frame": 3054, + "attempt": 2, + "event": { + "stage": "yellow", + "event": "achieved", + "step": 3045, + "r_cm": 5.4, + "moment_Nm": 0.358 + } + }, + { + "frame": 3582, + "attempt": 2, + "event": { + "stage": "blue", + "event": "achieved", + "step": 3573, + "r_cm": 9.2, + "moment_Nm": 0.445 + } + }, + { + "frame": 3918, + "attempt": 2, + "event": { + "stage": "blue", + "event": "lost", + "step": 3909, + "cause": "slid_off", + "board_deg": 9.0 + } + }, + { + "frame": 3918, + "attempt": 2, + "event": { + "jar": "blue", + "event": "jar_fell", + "step": 3909, + "dt_since_placed_s": 16.8, + "dt_since_sag_start_s": 90.0, + "after_placing": null, + "dt_since_cause_s": null, + "in_final_settle": false, + "board_deg": 9.0 + } + } + ], + "frames": { + "n": 3999, + "fps": 20, + "image_res": 256, + "phase_codes": { + "move": 0, + "gripper": 1, + "judge": 2 + }, + "initial_state": { + "eef_pos": [ + -0.20846466056582397, + -2.017108968149336e-14, + 1.1732794757296403 + ], + "joint_pos": [ + 3.4725847346116083e-14, + -0.16103738899999992, + -2.9352215005332543e-14, + -2.44459747, + -2.1417982036847964e-13, + 2.2267522, + 0.7853981633973856 + ], + "gripper_qpos": [ + 0.020435218182355674, + -0.020435189355504403 + ] + } + }, + "episode_index": 2437, + "dataset_index_range": [ + 4456484, + 4460483 + ], + "label_provenance": { + "task_cause_source": "leaf/release/evidence/causes.json", + "recovery_review_source": "leaf/release/label_audit.jsonl", + "recovery_review_applied": false + } +} diff --git a/leaf/annotations/episode_003070.json b/leaf/annotations/episode_003070.json new file mode 100644 index 0000000000000000000000000000000000000000..0a87f7712af7cb51ada903528453b9f2c910b897 --- /dev/null +++ b/leaf/annotations/episode_003070.json @@ -0,0 +1,1450 @@ +{ + "schema": "leaf-replay-1", + "source": { + "batch": "rcc_dev09_sonnet_20261111", + "run": "rcc_dev09_sonnet_20261111-claude-sonnet-5-5-recauseclaude-harness-hidek_l5_slide_to_target_s3007_full_F1_direct_k3_1111-082312_p26700", + "attempts_in_episode": [ + 1 + ], + "episode_in_run": 0, + "condition": "with_history", + "memory_free_chain_of": null, + "memory_free_rep": null, + "feedback_level": "F1", + "hide_k": true, + "k": 3, + "perception": "rgb", + "instruction_variant": "direct", + "contract_sha256": "694cc5bf1731fcf7e9665648c3886439ee34bd36b09c4fef63eddd49240158be", + "run_status": "done", + "manifest_id": "0001", + "replay": { + "n_reports_checked": 33, + "n_mismatch": 0, + "max_eef_dev_m": 0.0 + }, + "backfill_provenance": { + "original_run": "/mnt/cpfs/workspace/agentic-robotics/worktrees/lffbench-robot-harnesses/runs/api/rcc_dev09_sonnet_20261111/rcc_dev09_sonnet_20261111-claude-sonnet-5-5-recauseclaude-harness-hidek_l5_slide_to_target_s3007_full_F1_direct_k3_1111-082312_p26700", + "frozen_run": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/source/runs/api/rcc_dev09_sonnet_20261111/rcc_dev09_sonnet_20261111-claude-sonnet-5-5-recauseclaude-harness-hidek_l5_slide_to_target_s3007_full_F1_direct_k3_1111-082312_p26700", + "runtime": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/variants/725c1a77128e" + }, + "evaluation_config": { + "cond": "harness", + "feedback": "F1", + "mem": "full", + "k": 3, + "rep": 0, + "task": "l5_slide_to_target", + "seed": 3007 + }, + "release_origin": { + "dataset": "supp-20261113-rcc_dev09_sonnet_20261111", + "episode_index": 1 + }, + "release_episode_index": 3070, + "pre_v181_sidecar_index": { + "episode_index": 1, + "dataset_index_range": [ + 524, + 955 + ] + } + }, + "agent": { + "harness": "recause_claude", + "harness_version": "2.1.267", + "harness_binary_sha256": "0399c793ff571d5946ef923d80b4f330d05ac4b6842a6b0775468f5d389403c0", + "model": "claude-sonnet-5-5", + "effort": "high", + "provider": "anthropic", + "codex_catalog": "generic", + "auth": "apikey", + "jail": true + }, + "task": { + "name": "l5_slide_to_target", + "level": "L5", + "family": "hidden_variable", + "category": "dynamics_adaptation", + "capabilities": [ + "Reason", + "Utilize" + ], + "protocol": "cross", + "max_attempts": 5, + "agent_max_steps": 40, + "instruction": "Push the red cube straight away from the robot so that it slides and comes to rest in the green square marked on the table. On the side of the square nearest the robot and on its left and right, no part of the cube may lie on or beyond the green border line. On the far side, away from the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. The cube must slide the last part of the way on its own: after it leaves the gripper it has to slide at least 3 cm, with nothing touching it, before it comes to rest in the square.", + "seed": 3007, + "instance": { + "seed": 3007, + "cube_xy": [ + -0.20765885377262192, + 0.042771736853002174 + ], + "target_dist": 0.08252086225615438, + "mu": 0.03832232544907156 + }, + "paper": { + "name": "Slide to target", + "cause": "L5", + "table_cause": "L5", + "hidden_variable": "Cube–table friction μ", + "repair_within_attempt": true, + "oracle_first_attempt_pct": "100", + "naive_first_attempt_pct": "30", + "original_cause": "L5", + "original_table_cause": "L5" + }, + "canonical_cause": "L5", + "paper_long_horizon": false, + "instruction_original": "Push the red cube straight away from the robot so that it slides and comes to rest in the green square marked on the table. On the side of the square nearest the robot and on its left and right, no part of the cube may lie on or beyond the green border line. On the far side, away from the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. The cube must slide the last part of the way on its own: after it leaves the gripper it has to slide at least 3 cm, with nothing touching it, before it comes to rest in the square." + }, + "run_outcome": { + "outcome_class": "IR", + "attempt_history": "S", + "n_attempts": 1, + "run_success": true, + "agent_final_report": "The cube is inside the green square, and the gripper is well clear of it after the final push.\n\n- **Position:** In the final wrist image the cube's base spans about x 204–308 and y 94–195 px. The green square's inner border spans x 169–326 and y 68–226 px. The cube is about 26 px from the far border, about 35 px from the left and about 18 px from the right, so it is clear of every border. The base position comes from projecting the top face back to the table, so it is an estimate rather than a direct measurement.\n- **Orientation:** The cube is upright, flat on the table and not leaning on anything.\n- **Unaided slide:** The gripper stopped at x=0.445 and the cube rests visibly ahead of it, with a gap of roughly 5–6 cm in the agentview image. Nothing touched the cube after the gripper stopped, so it slid at least 3 cm on its own.\n- **Rules:** The log shows only `move_eef` pushes and pulls, and nothing was knocked over.\n\nI could not view the enlarged agentview crop because I ran out of tool calls. The call before that had failed on a wrong directory path, which used up one of the six.\n\nVERDICT: PASS", + "mean_think_s": 10.77, + "outcome_class_original": "IR", + "outcome_class_status": "rule_derived" + }, + "attempts": [ + { + "attempt": 1, + "success": true, + "outcome": { + "success": true, + "along_err": 0.0029386235241398717, + "across_err": -0.003357398821599293, + "detail": "The cube stopped 0.3 cm past the centre of the green square (in the square).", + "inside": true, + "at_rest": true, + "free_slide_cm": 6.44, + "release_xy": [ + -0.1866, + 0.0404 + ], + "touching_at_end": false, + "n_moves": 12, + "n_strikes": 7, + "n_missed_strikes": 3, + "trap_fired": true, + "recovered_in_attempt": true, + "irrecoverable": false, + "strikes": [ + { + "sub": 1027, + "start": [ + -0.2075, + 0.0428, + 0.92 + ], + "release": [ + -0.2049, + 0.0427, + 0.92 + ], + "rest": [ + -0.1695, + 0.0424, + 0.92 + ], + "pushed_cm": 0.26, + "free_slide_cm": 3.53, + "along_err_cm": -4.44, + "across_err_cm": -0.04, + "result": "short", + "missed": true + }, + { + "sub": 2583, + "start": [ + -0.1692, + 0.0424, + 0.9201 + ], + "release": [ + -0.1638, + 0.0422, + 0.92 + ], + "rest": [ + -0.1072, + 0.041, + 0.92 + ], + "pushed_cm": 0.54, + "free_slide_cm": 5.66, + "along_err_cm": 1.79, + "across_err_cm": -0.18, + "result": "in", + "missed": false + }, + { + "sub": 4739, + "start": [ + -0.181, + 0.0414, + 0.9202 + ], + "release": [ + -0.1745, + 0.0413, + 0.92 + ], + "rest": [ + -0.1074, + 0.041, + 0.92 + ], + "pushed_cm": 0.65, + "free_slide_cm": 6.71, + "along_err_cm": 1.77, + "across_err_cm": -0.18, + "result": "in", + "missed": false + }, + { + "sub": 6093, + "start": [ + -0.1624, + 0.0413, + 0.92 + ], + "release": [ + -0.1679, + 0.0414, + 0.92 + ], + "rest": [ + -0.1821, + 0.0415, + 0.92 + ], + "pushed_cm": 0.55, + "free_slide_cm": 1.43, + "along_err_cm": -5.7, + "across_err_cm": -0.13, + "result": "short", + "missed": true + }, + { + "sub": 7062, + "start": [ + -0.1819, + 0.0415, + 0.9201 + ], + "release": [ + -0.1769, + 0.0414, + 0.9199 + ], + "rest": [ + -0.1189, + 0.0401, + 0.92 + ], + "pushed_cm": 0.5, + "free_slide_cm": 5.81, + "along_err_cm": 0.63, + "across_err_cm": -0.27, + "result": "in", + "missed": false + }, + { + "sub": 8464, + "start": [ + -0.1271, + 0.0401, + 0.92 + ], + "release": [ + -0.1816, + 0.0404, + 0.92 + ], + "rest": [ + -0.1921, + 0.0405, + 0.92 + ], + "pushed_cm": 5.45, + "free_slide_cm": 1.05, + "along_err_cm": -6.7, + "across_err_cm": -0.23, + "result": "short", + "missed": true + }, + { + "sub": 9439, + "start": [ + -0.1917, + 0.0405, + 0.9201 + ], + "release": [ + -0.1866, + 0.0404, + 0.9199 + ], + "rest": [ + -0.1222, + 0.0394, + 0.92 + ], + "pushed_cm": 0.51, + "free_slide_cm": 6.44, + "along_err_cm": 0.29, + "across_err_cm": -0.34, + "result": "in", + "missed": false + } + ], + "waits": 8, + "failure": null + }, + "finish_reason": "Cube pushed by run-up and abrupt stop, slid ~5 cm unaided and came to rest inside the green square, front face on the inner side of the far border line.", + "feedback_shown": "Attempt succeeded.", + "auto_ended": false, + "think_s": 49.48045992851257, + "feedback_f2": "Attempt succeeded. The cube stopped 0.3 cm past the centre of the green square (in the square).", + "judge_frames": [ + 391, + 431 + ], + "corrected_later_in_run": null, + "is_last_attempt_of_run": true, + "agent_finish": { + "messages": [ + "Filenames differ from the reported ones; trying the listed names." + ], + "shell": [ + "ls; cat notes.md 2>/dev/null; ls obs" + ], + "viewed": [ + "obs/s000_agentview.jpg", + "obs/s000_wrist.jpg", + "obs/a1_s001_agentview.jpg", + "obs/a1_s001_wrist.jpg", + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg", + "obs/s002_agentview.jpg", + "obs/s002_wrist.jpg", + "obs/s003_wrist.jpg", + "obs/s003_agentview.jpg", + "obs/s004_agentview.jpg", + "obs/s004_wrist.jpg", + "obs/s006_agentview.jpg", + "obs/s006_wrist.jpg", + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg", + "obs/s010_agentview.jpg", + "obs/s010_wrist.jpg", + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg", + "obs/s013_agentview.jpg", + "obs/s013_wrist.jpg", + "obs/s016_agentview.jpg", + "obs/s016_wrist.jpg", + "obs/s009_wrist.jpg", + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg", + "obs/s024_agentview.jpg", + "obs/s025_agentview.jpg", + "obs/s025_wrist.jpg", + "obs/s032_agentview.jpg", + "obs/s033_agentview.jpg", + "obs/s033_wrist.jpg" + ], + "command": "finish reason=\"Cube pushed by run-up and abrupt stop, slid ~5 cm unaided and came to rest inside the green square, front face on the inner side of the far border line.\"", + "reply": { + "feedback": "Attempt succeeded.", + "message": "The episode is over. Stop now and report." + } + }, + "error_event_in_attempt": true, + "reviewed_operational_failure": null + } + ], + "commands": [ + { + "attempt": 1, + "step": 1, + "kind": "move_eef", + "frame_start": 0, + "frame_end": 21, + "command": "move_eef x=0.4 y=0.045 gripper=close", + "args": { + "x": 0.4, + "y": 0.045, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4009, + 0.0435, + 0.2604 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 31.413423776626587, + "agent_obs_images": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 2, + "kind": "move_eef", + "frame_start": 21, + "frame_end": 38, + "command": "move_eef z=0.02", + "args": { + "z": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.2 + }, + "eef_pos_after": [ + 0.3977, + 0.0452, + 0.0186 + ], + "gripper_width_after": 0.0011, + "holding_after": false, + "touched_during": false, + "think_s": 17.673912048339844, + "agent_obs_images": [ + "obs/s002_agentview.jpg", + "obs/s002_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 3, + "kind": "move_eef", + "frame_start": 38, + "frame_end": 51, + "command": "move_eef x=0.435 speed=0.4", + "args": { + "x": 0.435, + "speed": 0.4 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4349, + 0.0445, + 0.0199 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 8.745751857757568, + "agent_obs_images": [ + "obs/s003_agentview.jpg", + "obs/s003_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 4, + "kind": "move_eef", + "frame_start": 51, + "frame_end": 58, + "command": "move_eef z=0.09", + "args": { + "z": 0.09 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4339, + 0.0441, + 0.0874 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 34.996071577072144, + "agent_obs_images": [ + "obs/s004_agentview.jpg", + "obs/s004_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 5, + "kind": "move_eef", + "frame_start": 58, + "frame_end": 64, + "command": "move_eef x=0.385 z=0.02", + "args": { + "x": 0.385, + "z": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3859, + 0.0438, + 0.0232 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 24.510961055755615, + "agent_obs_images": [ + "obs/s005_agentview.jpg", + "obs/s005_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 6, + "kind": "move_eef", + "frame_start": 64, + "frame_end": 71, + "command": "move_eef x=0.447 speed=0.7", + "args": { + "x": 0.447, + "speed": 0.7 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4445, + 0.0447, + 0.0228 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 3.8712141513824463, + "agent_obs_images": [ + "obs/s006_agentview.jpg", + "obs/s006_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 7, + "kind": "move_eef", + "frame_start": 71, + "frame_end": 79, + "command": "move_eef x=0.32", + "args": { + "x": 0.32 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.3178, + 0.0428, + 0.0223 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 41.15943360328674, + "agent_obs_images": [ + "obs/s007_agentview.jpg", + "obs/s007_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 8, + "kind": "move_eef", + "frame_start": 79, + "frame_end": 87, + "command": "move_eef x=0.455 speed=0.8", + "args": { + "x": 0.455, + "speed": 0.8 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4538, + 0.0437, + 0.024 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 3.0676801204681396, + "agent_obs_images": [ + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 9, + "kind": "move_eef", + "frame_start": 87, + "frame_end": 95, + "command": "move_eef x=0.32", + "args": { + "x": 0.32 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3208, + 0.0421, + 0.025 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 26.80113458633423, + "agent_obs_images": [ + "obs/s009_agentview.jpg", + "obs/s009_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 10, + "kind": "move_eef", + "frame_start": 95, + "frame_end": 116, + "command": "move_eef x=0.468 speed=0.8", + "args": { + "x": 0.468, + "speed": 0.8 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.0, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4684, + 0.0421, + 0.0252 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 2.6492960453033447, + "agent_obs_images": [ + "obs/s010_agentview.jpg", + "obs/s010_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 11, + "kind": "move_eef", + "frame_start": 116, + "frame_end": 123, + "command": "move_eef x=0.585 z=0.09", + "args": { + "x": 0.585, + "z": 0.09 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.5865, + 0.0415, + 0.0928 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 24.55195689201355, + "agent_obs_images": [ + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 12, + "kind": "move_eef", + "frame_start": 123, + "frame_end": 132, + "command": "move_eef z=0.025", + "args": { + "z": 0.025 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5882, + 0.0417, + 0.0263 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 11.185519456863403, + "agent_obs_images": [ + "obs/s012_agentview.jpg", + "obs/s012_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 13, + "kind": "move_eef", + "frame_start": 132, + "frame_end": 152, + "command": "move_eef x=0.51 speed=0.1", + "args": { + "x": 0.51, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5098, + 0.0413, + 0.0248 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 3.0669963359832764, + "agent_obs_images": [ + "obs/s013_agentview.jpg", + "obs/s013_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 14, + "kind": "move_eef", + "frame_start": 152, + "frame_end": 158, + "command": "move_eef z=0.09", + "args": { + "z": 0.09 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5122, + 0.0416, + 0.0875 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 10.161259412765503, + "agent_obs_images": [ + "obs/s014_agentview.jpg", + "obs/s014_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 15, + "kind": "move_eef", + "frame_start": 158, + "frame_end": 166, + "command": "move_eef x=0.32", + "args": { + "x": 0.32 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.32, + 0.0401, + 0.0847 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.819869041442871, + "agent_obs_images": [ + "obs/s015_agentview.jpg", + "obs/s015_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 16, + "kind": "move_eef", + "frame_start": 166, + "frame_end": 183, + "command": "move_eef z=0.025", + "args": { + "z": 0.025 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.318, + 0.0403, + 0.0243 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.648998975753784, + "agent_obs_images": [ + "obs/s016_agentview.jpg", + "obs/s016_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 17, + "kind": "move_eef", + "frame_start": 183, + "frame_end": 203, + "command": "move_eef x=0.459 speed=0.7", + "args": { + "x": 0.459, + "speed": 0.7 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4575, + 0.0387, + 0.0266 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 11.670091152191162, + "agent_obs_images": [ + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 18, + "kind": "move_eef", + "frame_start": 203, + "frame_end": 209, + "command": "move_eef z=0.09", + "args": { + "z": 0.09 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4578, + 0.0388, + 0.0865 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 21.99561643600464, + "agent_obs_images": [ + "obs/s018_agentview.jpg", + "obs/s018_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 19, + "kind": "move_eef", + "frame_start": 209, + "frame_end": 224, + "command": "move_eef x=0.585 y=0.042", + "args": { + "x": 0.585, + "y": 0.042 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5878, + 0.0424, + 0.0883 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 3.1313602924346924, + "agent_obs_images": [ + "obs/s019_agentview.jpg", + "obs/s019_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 20, + "kind": "move_eef", + "frame_start": 224, + "frame_end": 231, + "command": "move_eef z=0.025", + "args": { + "z": 0.025 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5844, + 0.0422, + 0.0242 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.933985471725464, + "agent_obs_images": [ + "obs/s020_agentview.jpg", + "obs/s020_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 21, + "kind": "move_eef", + "frame_start": 231, + "frame_end": 251, + "command": "move_eef x=0.512 speed=0.1", + "args": { + "x": 0.512, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5109, + 0.0418, + 0.0223 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 2.843963384628296, + "agent_obs_images": [ + "obs/s021_agentview.jpg", + "obs/s021_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 22, + "kind": "move_eef", + "frame_start": 251, + "frame_end": 257, + "command": "move_eef z=0.09", + "args": { + "z": 0.09 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5138, + 0.0422, + 0.0876 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 3.7996060848236084, + "agent_obs_images": [ + "obs/s022_agentview.jpg", + "obs/s022_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 23, + "kind": "move_eef", + "frame_start": 257, + "frame_end": 264, + "command": "move_eef x=0.36", + "args": { + "x": 0.36 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.3608, + 0.0412, + 0.0858 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.981478691101074, + "agent_obs_images": [ + "obs/s023_agentview.jpg", + "obs/s023_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 24, + "kind": "move_eef", + "frame_start": 264, + "frame_end": 277, + "command": "move_eef z=0.025", + "args": { + "z": 0.025 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.2 + }, + "eef_pos_after": [ + 0.359, + 0.0424, + 0.0242 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.685056209564209, + "agent_obs_images": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 25, + "kind": "move_eef", + "frame_start": 277, + "frame_end": 295, + "command": "move_eef x=0.459 speed=0.7", + "args": { + "x": 0.459, + "speed": 0.7 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4555, + 0.0413, + 0.025 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 6.756137371063232, + "agent_obs_images": [ + "obs/s025_agentview.jpg", + "obs/s025_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 26, + "kind": "move_eef", + "frame_start": 295, + "frame_end": 301, + "command": "move_eef z=0.09", + "args": { + "z": 0.09 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4554, + 0.0414, + 0.0861 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 15.005755186080933, + "agent_obs_images": [ + "obs/s026_agentview.jpg", + "obs/s026_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 27, + "kind": "move_eef", + "frame_start": 301, + "frame_end": 316, + "command": "move_eef x=0.585 y=0.042", + "args": { + "x": 0.585, + "y": 0.042 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.588, + 0.0423, + 0.088 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.7140135765075684, + "agent_obs_images": [ + "obs/s027_agentview.jpg", + "obs/s027_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 28, + "kind": "move_eef", + "frame_start": 316, + "frame_end": 323, + "command": "move_eef z=0.025", + "args": { + "z": 0.025 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5846, + 0.0421, + 0.0242 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.752795696258545, + "agent_obs_images": [ + "obs/s028_agentview.jpg", + "obs/s028_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 29, + "kind": "move_eef", + "frame_start": 323, + "frame_end": 345, + "command": "move_eef x=0.5 speed=0.1", + "args": { + "x": 0.5, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5006, + 0.0417, + 0.0227 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 2.847158193588257, + "agent_obs_images": [ + "obs/s029_agentview.jpg", + "obs/s029_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 30, + "kind": "move_eef", + "frame_start": 345, + "frame_end": 351, + "command": "move_eef z=0.09", + "args": { + "z": 0.09 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5031, + 0.042, + 0.0873 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.7402234077453613, + "agent_obs_images": [ + "obs/s030_agentview.jpg", + "obs/s030_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 31, + "kind": "move_eef", + "frame_start": 351, + "frame_end": 358, + "command": "move_eef x=0.347", + "args": { + "x": 0.347 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.3485, + 0.041, + 0.0857 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.936162233352661, + "agent_obs_images": [ + "obs/s031_agentview.jpg", + "obs/s031_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 32, + "kind": "move_eef", + "frame_start": 358, + "frame_end": 372, + "command": "move_eef z=0.025", + "args": { + "z": 0.025 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.2 + }, + "eef_pos_after": [ + 0.3466, + 0.042, + 0.0243 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 3.9494526386260986, + "agent_obs_images": [ + "obs/s032_agentview.jpg", + "obs/s032_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 33, + "kind": "move_eef", + "frame_start": 372, + "frame_end": 391, + "command": "move_eef x=0.449 speed=0.7", + "args": { + "x": 0.449, + "speed": 0.7 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4453, + 0.0408, + 0.0251 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 7.225900650024414, + "agent_obs_images": [ + "obs/s033_agentview.jpg", + "obs/s033_wrist.jpg" + ] + }, + { + "attempt": 1, + "step": 34, + "kind": "observe", + "frame_start": 391, + "frame_end": 391, + "command": "observe", + "args": {}, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.4453, + 0.0408, + 0.0251 + ], + "gripper_width_after": 0.001, + "holding_after": null, + "touched_during": null, + "think_s": 17.768381357192993, + "agent_obs_images": [ + "obs/s034_agentview.jpg", + "obs/s034_wrist.jpg" + ], + "agent_note": { + "messages": [ + "The attempt succeeded: the red cube came to rest inside the green square after sliding about 5 cm on its own.\n\n- **First pushes:** the cube started about 2 cm short of the square. Pushes from a short run-up moved the cube with the gripper and gave no real slide. I used a closed gripper at z≈0.025 as a pusher, with y≈0.042 to line it up with the cube.\n- **Overshoot:** a long run-up from x≈0.32–0.36 at speed 0.7–0.8, stopping at x≈0.455–0.468, made the cube leave the gripper and slide about 5 cm. That overshot the far border by about 1 cm the first time and landed right on it the second.\n- **Pull-back:** each time I lifted to z=0.09, passed over the cube to x≈0.585, lowered behind its far face, and dragged it back at speed 0.1. I then lifted again and returned to the run-up position.\n- **Final push:** I pulled the cube back about 1 cm further than the previous run (gripper end at x=0.50). I then started from x=0.347 and pushed at speed 0.7, stopping at x=0.449. The cube ended inside the square, with its front face on the inner edge of the far border line. Its lateral margins were about 1 cm, and the near margin was about 1.6 cm.\n\nI used 33 of the 40 robot commands." + ] + } + } + ], + "task_events": [], + "frames": { + "n": 431, + "fps": 20, + "image_res": 256, + "phase_codes": { + "move": 0, + "gripper": 1, + "judge": 2 + }, + "initial_state": { + "eef_pos": [ + -0.20846466056582413, + -2.855035584422895e-14, + 1.1732794757296403 + ], + "joint_pos": [ + 4.254357537859056e-14, + -0.16103738899999992, + -3.5853835402265574e-14, + -2.44459747, + -2.986627122676119e-13, + 2.2267522, + 0.7853981633973531 + ], + "gripper_qpos": [ + 0.020541867755816158, + -0.02054184665779552 + ] + } + }, + "episode_index": 3070, + "dataset_index_range": [ + 5889035, + 5889466 + ], + "label_provenance": { + "task_cause_source": "leaf/release/evidence/causes.json", + "recovery_review_source": "leaf/release/label_audit.jsonl", + "recovery_review_applied": false + } +} diff --git a/leaf/annotations/episode_003191.json b/leaf/annotations/episode_003191.json new file mode 100644 index 0000000000000000000000000000000000000000..5d2d915b438f213e7bad4ca750b86fdcc159ce48 --- /dev/null +++ b/leaf/annotations/episode_003191.json @@ -0,0 +1,1461 @@ +{ + "schema": "leaf-replay-1", + "source": { + "batch": "rcc_devbase_sonnet_20261109", + "run": "rcc_devbase_sonnet_20261109-claude-sonnet-5-5-claudecodefull-harness-hidek_l3_card_shelf_s3013_full_F1_direct_k3_1109-145321_p26100", + "attempts_in_episode": [ + 1 + ], + "episode_in_run": 0, + "condition": "with_history", + "memory_free_chain_of": null, + "memory_free_rep": null, + "feedback_level": "F1", + "hide_k": true, + "k": 3, + "perception": "rgb", + "instruction_variant": "direct", + "contract_sha256": "91a4e5b0b3bb7df5dbce830be66a76c66dbc514affb2e4a40140926e4ae806ca", + "run_status": "done", + "manifest_id": "0008", + "replay": { + "n_reports_checked": 80, + "n_mismatch": 0, + "max_eef_dev_m": 0.0 + }, + "backfill_provenance": { + "original_run": "/mnt/cpfs/workspace/agentic-robotics/worktrees/lffbench-robot-harnesses/runs/api/rcc_devbase_sonnet_20261109/rcc_devbase_sonnet_20261109-claude-sonnet-5-5-claudecodefull-harness-hidek_l3_card_shelf_s3013_full_F1_direct_k3_1109-145321_p26100", + "frozen_run": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/source/runs/api/rcc_devbase_sonnet_20261109/rcc_devbase_sonnet_20261109-claude-sonnet-5-5-claudecodefull-harness-hidek_l3_card_shelf_s3013_full_F1_direct_k3_1109-145321_p26100", + "runtime": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/variants/4cff12984db8" + }, + "evaluation_config": { + "cond": "harness", + "feedback": "F1", + "mem": "full", + "k": 3, + "rep": 0, + "task": "l3_card_shelf", + "seed": 3013 + }, + "release_origin": { + "dataset": "supp-20261113-rcc_devbase_sonnet_20261109", + "episode_index": 15 + }, + "release_episode_index": 3191, + "pre_v181_sidecar_index": { + "episode_index": 15, + "dataset_index_range": [ + 19909, + 21578 + ] + } + }, + "agent": { + "harness": "claude_code_full", + "harness_version": "2.1.267", + "harness_binary_sha256": "0399c793ff571d5946ef923d80b4f330d05ac4b6842a6b0775468f5d389403c0", + "model": "claude-sonnet-5-5", + "effort": "high", + "provider": "anthropic", + "codex_catalog": null, + "auth": "oauth", + "jail": true + }, + "task": { + "name": "l3_card_shelf", + "level": "L3", + "family": "hidden_variable", + "category": "strategy_switching", + "capabilities": [ + "Perceive", + "Reason", + "Plan" + ], + "protocol": "cross", + "max_attempts": 3, + "agent_max_steps": 40, + "instruction": "Pick up the thin red card lying on the wooden shelf and put it into the grey bin.", + "seed": 3013, + "instance": { + "seed": 3013, + "shelf_xy": [ + -0.13438722588384336, + -0.018831624475633114 + ], + "card_xy": [ + -0.1433403469497864, + 0.0356420384754094 + ], + "card_yaw": 1.6239487337152074, + "card_along": "y", + "near_edge": "left", + "far_edge": "right", + "near_gap": 0.029102321875324723, + "heavy_near": true, + "heavy_edge": "left", + "com_offset": 0.028, + "bin_xy": [ + -0.1444036129240873, + 0.2571683755243669 + ], + "bin_side": "left" + }, + "paper": { + "name": "Card on shelf", + "cause": "L5", + "table_cause": "L5", + "hidden_variable": "Weighted end of card", + "repair_within_attempt": true, + "oracle_first_attempt_pct": "100", + "naive_first_attempt_pct": "30", + "original_cause": "L5", + "original_table_cause": "L5" + }, + "canonical_cause": "L5", + "paper_long_horizon": false, + "instruction_original": "Pick up the thin red card lying on the wooden shelf and put it into the grey bin." + }, + "run_outcome": { + "outcome_class": "XR", + "attempt_history": "FFS", + "n_attempts": 3, + "run_success": true, + "agent_final_report": "Attempt 3 succeeded: the red card is in the grey bin. Attempts 1 and 2 failed.\n\n**What worked in attempt 3**\n- **Why attempts 1 and 2 failed:** the card is too thin to pinch while it lies flat. The fingertips hover over it or the card slips out. In attempt 1 the card also ended up on the floor between shelf and bin. In attempt 2 it fell off the +y edge, the side next to the bin, while I pushed it there. After that the hand wedged between the shelf edge and the bin wall, so I could not reach it.\n- **Push to overhang:** I used the closed gripper at z≈0.098 and yaw -86°. I pushed the card away from the bin, toward the free -y edge, from y≈0.107 to y≈-0.089 in two pushes. The card ended up overhanging that edge by about 2–3 cm without falling.\n- **Pinch the overhang:** I opened the gripper over the overhanging part at x≈0.521, y≈-0.163. I lowered to z≈0.076, below the shelf top, and closed. The width stopped at 0.044 m, so the card was held.\n- **Carry and release:** I lifted to z≈0.22, moved to x≈0.53, y≈0.205 over the bin, and opened the gripper. The agent view showed the card in the bin.\n\nI did not save any memory notes for this task.", + "mean_think_s": 10.15, + "outcome_class_original": "XR", + "outcome_class_status": "rule_derived" + }, + "attempts": [ + { + "attempt": 1, + "success": false, + "outcome": { + "success": false, + "mode": "fell_off", + "failure": "fell_off", + "held": false, + "lifted": false, + "max_lift": 0.0011, + "max_overhang": 0.0253, + "moved": 0.0834, + "fell": true, + "tipped_off": true, + "trap_fired": true, + "tip": { + "part": "heavy", + "edge": "left", + "overhang": 0.0253 + }, + "end_out": { + "heavy": 0.0253, + "light": 0.0, + "side": 0.0 + }, + "end_out_edge": { + "heavy": "left", + "light": null, + "side": null + }, + "card_final": { + "xy": [ + -0.121, + 0.1159 + ], + "z_above_table": 0.001, + "tilt_deg": 0.0 + }, + "leg_hits": 0, + "slid_edge": null, + "events": [ + { + "event": "end_over_edge", + "step": 1053, + "part": "heavy", + "edge": "left" + }, + { + "event": "tipped_off", + "step": 1073, + "part": "heavy", + "edge": "left", + "overhang": 0.0253 + } + ], + "grasp_tries": [ + { + "step": 310, + "local": [ + 0.0138, + -0.0128 + ], + "tips_above_card": -0.0022, + "beyond_edge": -0.0603, + "beyond_edge_name": "left", + "card_on_shelf": true, + "overhang": -0.0282, + "overhang_edge": "left", + "width_before": 0.0644, + "held": false, + "width": 0.0076 + }, + { + "step": 609, + "local": [ + 0.0005, + -0.0041 + ], + "tips_above_card": -0.0021, + "beyond_edge": -0.0728, + "beyond_edge_name": "left", + "card_on_shelf": true, + "overhang": -0.0265, + "overhang_edge": "left", + "width_before": 0.0739, + "held": false, + "width": 0.0077 + }, + { + "step": 681, + "local": [ + -0.0009, + 0.0004 + ], + "tips_above_card": 0.0001, + "beyond_edge": -0.0727, + "beyond_edge_name": "left", + "card_on_shelf": true, + "overhang": -0.0244, + "overhang_edge": "left", + "width_before": 0.0788, + "held": false, + "width": 0.0023 + } + ], + "closes": [ + { + "step": 310, + "local": [ + 0.0138, + -0.0128 + ], + "tips_above_card": -0.0022, + "beyond_edge": -0.0603, + "beyond_edge_name": "left", + "card_on_shelf": true, + "overhang": -0.0282, + "overhang_edge": "left", + "width_before": 0.0644, + "held": false, + "width": 0.0076 + }, + { + "step": 609, + "local": [ + 0.0005, + -0.0041 + ], + "tips_above_card": -0.0021, + "beyond_edge": -0.0728, + "beyond_edge_name": "left", + "card_on_shelf": true, + "overhang": -0.0265, + "overhang_edge": "left", + "width_before": 0.0739, + "held": false, + "width": 0.0077 + }, + { + "step": 681, + "local": [ + -0.0009, + 0.0004 + ], + "tips_above_card": 0.0001, + "beyond_edge": -0.0727, + "beyond_edge_name": "left", + "card_on_shelf": true, + "overhang": -0.0244, + "overhang_edge": "left", + "width_before": 0.0788, + "held": false, + "width": 0.0023 + }, + { + "step": 1588, + "local": [ + 0.0259, + -0.0149 + ], + "tips_above_card": 0.0245, + "beyond_edge": 0.031, + "beyond_edge_name": "left", + "card_on_shelf": false, + "overhang": 0.0505, + "overhang_edge": "left", + "width_before": 0.08, + "held": false, + "width": 0.0023 + } + ], + "detail": "The card was never lifted: after one end of it had been slid 2.5 cm beyond the shelf's left edge, it tipped over that edge and fell off the shelf; it lies flat on the table. 3 grasp tries; in the last one, when the gripper closed on the card lying flat on the shelf, its fingertips were on either side of the card, at shelf level (+0.0 cm from the fingertips to the top of the card); the fingers closed fully, sliding over the top of the card instead of gripping its edges." + }, + "finish_reason": "Could not grasp the thin card; it ended on the floor between shelf and bin, not in the bin", + "feedback_shown": "Attempt failed.", + "auto_ended": false, + "think_s": 3.5280463695526123, + "feedback_f2": "Attempt failed. The card was never lifted: after one end of it had been slid 2.5 cm beyond the shelf's left edge, it tipped over that edge and fell off the shelf; it lies flat on the table. 3 grasp tries; in the last one, when the gripper closed on the card lying flat on the shelf, its fingertips were on either side of the card, at shelf level (+0.0 cm from the fingertips to the top of the card); the fingers closed fully, sliding over the top of the card instead of gripping its edges.", + "judge_frames": [ + 1639, + 1669 + ], + "corrected_later_in_run": true, + "is_last_attempt_of_run": false, + "agent_finish": { + "command": "finish reason=\"Could not grasp the thin card; it ended on the floor between shelf and bin, not in the bin\"", + "reply": { + "feedback": "Attempt failed.", + "message": "You get more attempts than README.md says: up to 3 in total. Attempt 2 of 3 starts now. The scene has been reset to exactly the same initial state." + } + }, + "error_event_in_attempt": true, + "agent_reflection_after_feedback": { + "messages": [ + "The attempt failed. The card is not in the bin, and I used the only attempt the task gave me.\n\n**What I did**\n- **Approach:** I aligned the gripper over the card at yaw about -86° so the fingers straddled its short side. I descended slowly and closed the gripper at z≈0.097–0.100.\n- **Grasps:** I tried this three times. Each time the gripper closed to its fully closed width (about 1–2 mm) and the card stayed on the shelf, so I never held it. The fingertips appear to sit level with or above the thin card, so they never pinch its edges.\n- **Pushing:** I pushed the card toward the bin with the closed gripper at z≈0.098. It slid until it overhung the shelf edge, then dropped to the floor between the shelf and the bin.\n- **Last try:** I tried to grasp it on the floor. The gripper was deflected against the bin wall and lifted nothing.\n- **Result:** I called `finish`, and the environment reported \"Attempt failed.\"\n\n**Possible extra attempts:** the `finish` reply said I get up to 3 attempts and started attempt 2. That contradicts your instruction of 1 attempt, so I stopped and did not use it. If you do want further attempts, tell me. The next try would push the card to the shelf edge more slowly so it overhangs without falling. I would then grasp the overhanging part, where the fingertips can go below the card.", + "Continuing attempt 2: push the card about 4 cm toward the bin so it overhangs the shelf edge, then pinch the overhanging part." + ] + }, + "reviewed_operational_failure": null + } + ], + "commands": [ + { + "attempt": 1, + "step": 1, + "kind": "observe", + "frame_start": 0, + "frame_end": 0, + "command": "observe", + "args": {}, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.4515, + -0.0, + 0.2613 + ], + "gripper_width_after": 0.0409, + "holding_after": null, + "touched_during": null, + "think_s": 6.32351016998291, + "agent_obs_images": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 2, + "kind": "move_eef", + "frame_start": 0, + "frame_end": 41, + "command": "move_eef x=0.43 y=0.06 z=0.2 yaw=90 gripper=open", + "args": { + "x": 0.43, + "y": 0.06, + "z": 0.2, + "yaw": 90, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.428, + 0.0607, + 0.1985 + ], + "gripper_width_after": 0.0794, + "holding_after": false, + "touched_during": false, + "think_s": 13.878417491912842, + "agent_obs_images": [ + "obs/s002_agentview.jpg", + "obs/s002_wrist.jpg" + ], + "agent_note": { + "shell": [ + "ls obs" + ], + "viewed": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 3, + "kind": "move_eef", + "frame_start": 41, + "frame_end": 46, + "command": "move_eef y=0.03", + "args": { + "y": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.428, + 0.0319, + 0.1985 + ], + "gripper_width_after": 0.0795, + "holding_after": false, + "touched_during": false, + "think_s": 15.354438543319702, + "agent_obs_images": [ + "obs/s003_agentview.jpg", + "obs/s003_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s002_agentview.jpg", + "obs/s002_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 4, + "kind": "move_eef", + "frame_start": 46, + "frame_end": 52, + "command": "move_eef x=0.51 y=0.05", + "args": { + "x": 0.51, + "y": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5098, + 0.05, + 0.2005 + ], + "gripper_width_after": 0.0797, + "holding_after": false, + "touched_during": false, + "think_s": 8.339285135269165, + "agent_obs_images": [ + "obs/s004_agentview.jpg", + "obs/s004_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s003_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 5, + "kind": "move_eef", + "frame_start": 52, + "frame_end": 60, + "command": "move_eef x=0.518 z=0.12", + "args": { + "x": 0.518, + "z": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5199, + 0.0503, + 0.1222 + ], + "gripper_width_after": 0.0798, + "holding_after": false, + "touched_during": false, + "think_s": 7.057022571563721, + "agent_obs_images": [ + "obs/s005_agentview.jpg", + "obs/s005_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s004_wrist.jpg", + "obs/s004_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 6, + "kind": "move_eef", + "frame_start": 60, + "frame_end": 310, + "command": "move_eef z=0.06", + "args": { + "z": 0.06 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 4.0, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.5356, + 0.0508, + 0.0973 + ], + "gripper_width_after": 0.0644, + "holding_after": false, + "touched_during": true, + "think_s": 5.548018217086792, + "agent_obs_images": [ + "obs/s006_agentview.jpg", + "obs/s006_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s005_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 7, + "kind": "move_eef", + "frame_start": 310, + "frame_end": 325, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5369, + 0.0509, + 0.0988 + ], + "gripper_width_after": 0.0076, + "holding_after": false, + "touched_during": true, + "think_s": 8.87515115737915, + "agent_obs_images": [ + "obs/s007_agentview.jpg", + "obs/s007_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s006_wrist.jpg", + "obs/s006_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 8, + "kind": "move_eef", + "frame_start": 325, + "frame_end": 334, + "command": "move_eef z=0.2", + "args": { + "z": 0.2 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5396, + 0.0513, + 0.2013 + ], + "gripper_width_after": 0.0019, + "holding_after": false, + "touched_during": true, + "think_s": 2.7404191493988037, + "agent_obs_images": [ + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 9, + "kind": "move_eef", + "frame_start": 334, + "frame_end": 354, + "command": "move_eef x=0.52 z=0.15 yaw=-86 gripper=open", + "args": { + "x": 0.52, + "z": 0.15, + "yaw": -86, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5214, + 0.0509, + 0.154 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 40.22855091094971, + "agent_obs_images": [ + "obs/s009_agentview.jpg", + "obs/s009_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s008_wrist.jpg", + "obs/s008_agentview.jpg", + "obs/s007_wrist.jpg", + "obs/s007_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 10, + "kind": "move_eef", + "frame_start": 354, + "frame_end": 359, + "command": "move_eef x=0.533 y=0.037 z=0.11", + "args": { + "x": 0.533, + "y": 0.037, + "z": 0.11 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5319, + 0.0379, + 0.113 + ], + "gripper_width_after": 0.0782, + "holding_after": false, + "touched_during": false, + "think_s": 9.283716201782227, + "agent_obs_images": [ + "obs/s010_agentview.jpg", + "obs/s010_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s009_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 11, + "kind": "move_eef", + "frame_start": 359, + "frame_end": 609, + "command": "move_eef z=0.08 speed=0.05", + "args": { + "z": 0.08, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 1.9, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.5389, + 0.0384, + 0.0974 + ], + "gripper_width_after": 0.0739, + "holding_after": false, + "touched_during": false, + "think_s": 7.828305959701538, + "agent_obs_images": [ + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s010_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 12, + "kind": "move_eef", + "frame_start": 609, + "frame_end": 624, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.54, + 0.0385, + 0.0988 + ], + "gripper_width_after": 0.0077, + "holding_after": false, + "touched_during": true, + "think_s": 3.464998722076416, + "agent_obs_images": [ + "obs/s012_agentview.jpg", + "obs/s012_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 13, + "kind": "move_eef", + "frame_start": 624, + "frame_end": 645, + "command": "move_eef z=0.2 speed=0.1", + "args": { + "z": 0.2, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5398, + 0.0384, + 0.1976 + ], + "gripper_width_after": 0.0011, + "holding_after": false, + "touched_during": true, + "think_s": 3.4320120811462402, + "agent_obs_images": [ + "obs/s013_agentview.jpg", + "obs/s013_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 14, + "kind": "move_eef", + "frame_start": 645, + "frame_end": 666, + "command": "move_eef z=0.12 gripper=open", + "args": { + "z": 0.12, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5395, + 0.0382, + 0.1233 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 32.10132122039795, + "agent_obs_images": [ + "obs/s014_agentview.jpg", + "obs/s014_wrist.jpg" + ], + "agent_note": { + "shell": [ + "cd obs; python3 -c \"\nfrom PIL import Image\nim=Image.open('s011_agentview.jpg').crop((200,180,360,300)).resize((640,480),Image.LANCZOS);im.save('/tmp/c.png')\nim=Image.open('s012_agentview.jpg').crop((200,180,360,300)).resize((640,480),Image.LANCZOS);im.save('/tmp/d.png')\n\"; cp /tmp/c.png ../c.png; cp /tmp/d.png ../d.png" + ], + "viewed": [ + "obs/s012_wrist.jpg", + "obs/s013_agentview.jpg", + "c.png", + "d.png" + ] + } + }, + { + "attempt": 1, + "step": 15, + "kind": "move_eef", + "frame_start": 666, + "frame_end": 674, + "command": "move_eef z=0.104 speed=0.05", + "args": { + "z": 0.104, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5395, + 0.0383, + 0.1056 + ], + "gripper_width_after": 0.0784, + "holding_after": false, + "touched_during": false, + "think_s": 3.078822612762451, + "agent_obs_images": [ + "obs/s015_agentview.jpg", + "obs/s015_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 16, + "kind": "move_eef", + "frame_start": 674, + "frame_end": 681, + "command": "move_eef z=0.099 speed=0.02", + "args": { + "z": 0.099, + "speed": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5394, + 0.0384, + 0.0996 + ], + "gripper_width_after": 0.0788, + "holding_after": false, + "touched_during": false, + "think_s": 2.9236109256744385, + "agent_obs_images": [ + "obs/s016_agentview.jpg", + "obs/s016_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 17, + "kind": "move_eef", + "frame_start": 681, + "frame_end": 696, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5394, + 0.0386, + 0.0996 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 3.1902124881744385, + "agent_obs_images": [ + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 18, + "kind": "move_eef", + "frame_start": 696, + "frame_end": 717, + "command": "move_eef z=0.2 speed=0.1", + "args": { + "z": 0.2, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5392, + 0.0385, + 0.1978 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.9842827320098877, + "agent_obs_images": [ + "obs/s018_agentview.jpg", + "obs/s018_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 19, + "kind": "move_eef", + "frame_start": 717, + "frame_end": 723, + "command": "move_eef y=-0.03 z=0.13", + "args": { + "y": -0.03, + "z": 0.13 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.3 + }, + "eef_pos_after": [ + 0.538, + -0.0298, + 0.132 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 36.933173418045044, + "agent_obs_images": [ + "obs/s019_agentview.jpg", + "obs/s019_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s018_agentview.jpg", + "obs/s017_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 20, + "kind": "move_eef", + "frame_start": 723, + "frame_end": 735, + "command": "move_eef z=0.102 speed=0.05", + "args": { + "z": 0.102, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5382, + -0.0297, + 0.1041 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 3.785856246948242, + "agent_obs_images": [ + "obs/s020_agentview.jpg", + "obs/s020_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 21, + "kind": "move_eef", + "frame_start": 735, + "frame_end": 763, + "command": "move_eef y=0.04 speed=0.05", + "args": { + "y": 0.04, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5381, + 0.0382, + 0.1041 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 6.6592419147491455, + "agent_obs_images": [ + "obs/s021_agentview.jpg", + "obs/s021_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s020_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 22, + "kind": "move_eef", + "frame_start": 763, + "frame_end": 1013, + "command": "move_eef z=0.07 speed=0.03", + "args": { + "z": 0.07, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 2.8, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.5455, + 0.0394, + 0.0974 + ], + "gripper_width_after": 0.0059, + "holding_after": false, + "touched_during": true, + "think_s": 7.3755669593811035, + "agent_obs_images": [ + "obs/s022_agentview.jpg", + "obs/s022_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s021_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 23, + "kind": "move_eef", + "frame_start": 1013, + "frame_end": 1019, + "command": "move_eef y=-0.03 z=0.13", + "args": { + "y": -0.03, + "z": 0.13 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.2 + }, + "eef_pos_after": [ + 0.545, + -0.0293, + 0.1285 + ], + "gripper_width_after": 0.0013, + "holding_after": false, + "touched_during": true, + "think_s": 5.390767812728882, + "agent_obs_images": [ + "obs/s023_agentview.jpg", + "obs/s023_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 24, + "kind": "move_eef", + "frame_start": 1019, + "frame_end": 1032, + "command": "move_eef z=0.097 speed=0.05", + "args": { + "z": 0.097, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5449, + -0.0292, + 0.0984 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 2.7484288215637207, + "agent_obs_images": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 25, + "kind": "move_eef", + "frame_start": 1032, + "frame_end": 1062, + "command": "move_eef y=0.045 speed=0.05", + "args": { + "y": 0.045, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5452, + 0.0433, + 0.0989 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 4.373518466949463, + "agent_obs_images": [ + "obs/s025_agentview.jpg", + "obs/s025_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 26, + "kind": "move_eef", + "frame_start": 1062, + "frame_end": 1082, + "command": "move_eef z=0.14 gripper=open", + "args": { + "z": 0.14, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5462, + 0.0434, + 0.1372 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 14.206010818481445, + "agent_obs_images": [ + "obs/s026_agentview.jpg", + "obs/s026_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s025_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 27, + "kind": "move_eef", + "frame_start": 1082, + "frame_end": 1088, + "command": "move_eef x=0.537 y=0.12 z=0.14", + "args": { + "x": 0.537, + "y": 0.12, + "z": 0.14 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.3 + }, + "eef_pos_after": [ + 0.5361, + 0.1195, + 0.1396 + ], + "gripper_width_after": 0.0782, + "holding_after": false, + "touched_during": false, + "think_s": 2.8297019004821777, + "agent_obs_images": [ + "obs/s027_agentview.jpg", + "obs/s027_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 28, + "kind": "move_eef", + "frame_start": 1088, + "frame_end": 1338, + "command": "move_eef y=0.118 z=0.05 speed=0.1", + "args": { + "y": 0.118, + "z": 0.05, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 1.3, + "deg": 0.4 + }, + "eef_pos_after": [ + 0.5403, + 0.1275, + 0.0575 + ], + "gripper_width_after": 0.0796, + "holding_after": false, + "touched_during": false, + "think_s": 44.53788733482361, + "agent_obs_images": [ + "obs/s028_agentview.jpg", + "obs/s028_wrist.jpg" + ], + "agent_note": { + "shell": [ + "cd obs; python3 -c \"\nfrom PIL import Image\nim=Image.open('s027_agentview.jpg').crop((260,220,400,340)).resize((700,600),Image.LANCZOS);im.save('../e.png')\"" + ], + "viewed": [ + "obs/s027_wrist.jpg", + "obs/s027_agentview.jpg", + "e.png" + ] + } + }, + { + "attempt": 1, + "step": 29, + "kind": "move_eef", + "frame_start": 1338, + "frame_end": 1588, + "command": "move_eef z=0.01 speed=0.05", + "args": { + "z": 0.01, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 2.4, + "deg": 0.4 + }, + "eef_pos_after": [ + 0.5531, + 0.1422, + 0.024 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 7.830448150634766, + "agent_obs_images": [ + "obs/s029_agentview.jpg", + "obs/s029_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s028_wrist.jpg", + "obs/s028_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 30, + "kind": "move_eef", + "frame_start": 1588, + "frame_end": 1603, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5538, + 0.1429, + 0.0246 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 3.1634907722473145, + "agent_obs_images": [ + "obs/s030_agentview.jpg", + "obs/s030_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 31, + "kind": "move_eef", + "frame_start": 1603, + "frame_end": 1639, + "command": "move_eef z=0.2 speed=0.1", + "args": { + "z": 0.2, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5537, + 0.1427, + 0.1978 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 6.795624494552612, + "agent_obs_images": [ + "obs/s031_agentview.jpg", + "obs/s031_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s030_agentview.jpg" + ] + } + } + ], + "task_events": [ + { + "frame": 1053, + "attempt": 1, + "event": { + "event": "end_over_edge", + "step": 1053, + "part": "heavy", + "edge": "left" + } + }, + { + "frame": 1073, + "attempt": 1, + "event": { + "event": "tipped_off", + "step": 1073, + "part": "heavy", + "edge": "left", + "overhang": 0.0253 + } + } + ], + "frames": { + "n": 1669, + "fps": 20, + "image_res": 256, + "phase_codes": { + "move": 0, + "gripper": 1, + "judge": 2 + }, + "initial_state": { + "eef_pos": [ + -0.20846466056582394, + -1.8111990927967438e-14, + 1.1732794757296403 + ], + "joint_pos": [ + 3.5422452562245283e-14, + -0.16103738899999992, + -2.856775296524609e-14, + -2.44459747, + -2.0218797003045825e-13, + 2.2267522, + 0.7853981633973847 + ], + "gripper_qpos": [ + 0.0204352181823558, + -0.020435189355504296 + ] + } + }, + "episode_index": 3191, + "dataset_index_range": [ + 6057145, + 6058814 + ], + "label_provenance": { + "task_cause_source": "leaf/release/evidence/causes.json", + "recovery_review_source": "leaf/release/label_audit.jsonl", + "recovery_review_applied": false + } +} diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/DRIVER.md b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/DRIVER.md new file mode 100644 index 0000000000000000000000000000000000000000..3ac1e4511c50001e98cc06ea902688a42a37ddaa --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/DRIVER.md @@ -0,0 +1,144 @@ +# LFF-Bench 真机驱动说明(给负责机械臂的同学) + +> 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`, +> 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。 + +## 0. 一句话 + +你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。 +模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。 + +``` +评测机(跑模型的人) 机器人电脑(你) +Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改 + └ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……) + └ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist + └ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败) +``` + +模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。 + +## 1. 你要交付的东西 + +1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。 +2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。 +3. 场景道具,见 §6。 +4. `scripts/real_check_driver.py` 全部 PASS(§7)。 +5. 一位操作员,按 §8 的规程操作。可以就是你。 + +需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。 +放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。 + +## 2. 坐标与约定(最重要的一节) + +| 量 | 约定 | +|---|---| +| 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 | +| 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 | +| 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** | +| yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) | +| `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) | +| `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` | +| `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) | + +这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是 +"You control a real `` robot arm (`` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。 + +## 3. 接口 + +所有请求都是 `POST http://127.0.0.1:/`,带 JSON body,请求头 `X-Driver-Token: `。 +所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。 +模板里任何未捕获的异常都会自动变成 fault。 + +| 接口 | 请求 | 回复(`ok` 之外) | 说明 | +|---|---|---|---| +| `info` | `{}` | `protocol` = 1,`robot`,`n_joints`,`cameras` = `["agentview","wrist"]`,`workspace` = `{lo:[x,y,z], hi:[x,y,z]}`,`yaw_range_deg` = `[lo,hi]`,`max_speed`(m/s),`ik`(bool),`driver_version` | 启动时调一次,内容写进每个 run 的契约 | +| `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 | +| `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) | +| `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 | +| `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 | +| `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会中心裁成正方形、缩到 512²,再存成 JPEG q90 | +| `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 | +| `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) | +| `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 | + +驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。 + +## 4. 安全(必须做) + +- **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。 +- **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。 +- **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。 +- **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。 +- `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。 + +## 5. 模型那边看到的和你有关的东西 + +- 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。 + 光照要稳定;模型运行时,画面里不要有人和多余的东西。 +- 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。 +- 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。 + +## 6. 两个任务的场景 + +实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。 + +### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`) + +模型看到的指令(与仿真相同):*Slowly push the long brown box with the closed gripper so that it ends up completely inside the green rectangle ahead of it (farther from the robot).* + +- **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。 + 可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。 +- **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。 + 合上盖子,两端外观一模一样,贴同样的胶带。 +- **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。 +- **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。 +- **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。 +- **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框); + 对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。 +- **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。 + +### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`) + +模型看到的指令:*Pick up the red cube and put it into the bowl.* + +- 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。 +- 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。 +- **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。 + 但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。 +- **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方块。 + +## 7. 联调步骤 + +1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。 +2. 启动驱动(token 自己定,私下发给跑评测的人): + ```bash + python driver_template.py --port 9900 --token --log driver_logs + ``` +3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上: + ```bash + python real_check_driver.py --driver http://127.0.0.1:9900 --token --operator + ``` + 全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。 +4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一: + - 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 @<机器人电脑>` + - 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 @<评测机>` +5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。 +6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。 + 一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。 + +## 8. 操作员规程 + +- 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。 +- 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。 +- 判 y / n 只看清单本身,不看模型"努力了没有"。 +- `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。 +- 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。 + +## 9. 常见问题 + +- **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。 +- **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。 +- **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。 +- **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。 +- **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。 diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/__init__.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5513b07c27d6c467f8fd55f228d50d4aef4b482 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/__init__.py @@ -0,0 +1,10 @@ +"""Real-robot backend of LFF-Bench (docs/17): the same agent interface as simulation, with a robot driver underneath. + + protocol.py driver protocol v1 (both sides; stdlib + numpy + Pillow only) + executor.py RealToolExecutor: robot_server's executor on top of a driver (calibration bias injected here) + session.py RealRobotSession: robot_server's LA session without the simulator; python -m lffbench.real.session + tasks.py real-robot tasks (setup sheet, operator checklist, hidden variable from the seed) + fake_driver.py a driver backed by the simulator (no hardware) + driver_template.py skeleton for a hardware driver (copy to the robot PC with protocol.py) + DRIVER.md spec for the driver author and the operator +""" diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/protocol.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..13ce72af6568801584eb85c0c0b06279ddd3457d --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/protocol.py @@ -0,0 +1,364 @@ +"""Robot-driver protocol v1: what a real arm (or a fake one) must answer so that LFF-Bench can run on it. + +The benchmark side (lffbench/real/session.py, on the machine that runs the agent harness) talks to one *driver* +process (on the robot PC) over HTTP. The driver only moves the arm, reads its state, grabs camera frames and talks +to the human operator; budgets, attempts, README, logs and the agent interface stay on the benchmark side, so the +agent sees exactly the same tools as in simulation. Spec for driver authors: lffbench/real/DRIVER.md. + +This file is shared by both sides and needs only the Python standard library + numpy + Pillow (no simulator): + DriverClient benchmark side: typed calls to a driver + DriverServer driver side: HTTP plumbing; subclass it and implement the hardware methods (driver_template.py) + ConsoleOperator driver side: the operator's terminal (blocking prompts for reset / judging) + +Every request is POST / with a JSON body and header X-Driver-Token: . +Every reply is JSON with "ok": true|false. A reply with "fault": true means the robot can no longer be trusted +(protective stop, e-stop, lost connection, ...): the benchmark ends the run and marks it invalid. +""" +import base64 +import io +import json +import math +import os +import secrets +import sys +import time +import traceback +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, HTTPServer + +import numpy as np + +PROTOCOL_VERSION = 1 +CAMERAS = ("agentview", "wrist") +TOKEN_HEADER = "X-Driver-Token" +ENDPOINTS = ("info", "home", "move", "gripper", "state", "observe", "ik", "operator", "event") +OPERATOR_KINDS = ("reset", "judge", "notice") +EVENTS = ("session_start", "attempt_start", "attempt_end", "episode_end", "session_end", "run_invalid") + + +class DriverError(RuntimeError): + """The driver answered something that breaks the protocol (or did not answer).""" + + +class DriverFault(DriverError): + """The driver reports a robot fault: the run must stop and is invalid.""" + + +# ------------------------------------------------------------------------------------------------ images +def encode_image(arr, fmt="png", quality=95): + """uint8 HxWx3 -> {"format": "png"|"jpeg", "data": base64}. PNG is lossless (the benchmark re-encodes every frame + as 512x512 JPEG q90 itself, so a JPEG from the driver is compressed twice); JPEG is smaller over a slow link.""" + from PIL import Image + buf = io.BytesIO() + im = Image.fromarray(np.asarray(arr, dtype=np.uint8)) + if fmt == "jpeg": + im.save(buf, format="JPEG", quality=int(quality)) + else: + im.save(buf, format="PNG") + return dict(format=fmt, data=base64.b64encode(buf.getvalue()).decode("ascii")) + + +def decode_image(obj): + """{"format", "data"} -> uint8 HxWx3 (RGB).""" + from PIL import Image + if not isinstance(obj, dict) or "data" not in obj: + raise DriverError("image must be {\"format\": \"png\"|\"jpeg\", \"data\": }") + im = Image.open(io.BytesIO(base64.b64decode(obj["data"]))) + return np.asarray(im.convert("RGB"), dtype=np.uint8) + + +def square_resize(arr, res): + """Centre-crop to a square, then resize to res x res. A frame that is already res x res is returned unchanged + (bit for bit), so a simulator-backed driver gives exactly the simulator's pixels.""" + from PIL import Image + arr = np.asarray(arr, dtype=np.uint8) + h, w = arr.shape[:2] + if h == res and w == res: + return arr + s = min(h, w) + y0, x0 = (h - s) // 2, (w - s) // 2 + arr = arr[y0:y0 + s, x0:x0 + s] + if s == res: + return np.ascontiguousarray(arr) + return np.asarray(Image.fromarray(arr).resize((res, res), Image.BICUBIC)) + + +# ------------------------------------------------------------------------------------------------ validation +def _vec(v, n): + return isinstance(v, (list, tuple)) and len(v) == n and all(isinstance(x, (int, float)) and math.isfinite(x) for x in v) + + +def info_problems(info): + """-> list of problems with an /info reply (empty = fine).""" + p = [] + if info.get("protocol") != PROTOCOL_VERSION: + p.append(f"protocol must be {PROTOCOL_VERSION}, got {info.get('protocol')!r}") + if not isinstance(info.get("robot"), str) or not info["robot"].strip(): + p.append("robot: non-empty string (e.g. \"AgileX PiPER\")") + if not isinstance(info.get("n_joints"), int) or not 4 <= info["n_joints"] <= 8: + p.append("n_joints: integer 4..8") + if sorted(info.get("cameras") or []) != sorted(CAMERAS): + p.append(f"cameras must be exactly {list(CAMERAS)}") + ws = info.get("workspace") or {} + if not (_vec(ws.get("lo"), 3) and _vec(ws.get("hi"), 3) and all(a < b for a, b in zip(ws["lo"], ws["hi"]))): + p.append("workspace: {lo: [x, y, z], hi: [x, y, z]} with lo < hi (robot-base frame, metres)") + yr = info.get("yaw_range_deg") + if not (_vec(yr, 2) and yr[0] < yr[1] and yr[1] - yr[0] >= 180.0): + p.append("yaw_range_deg: [lo, hi] with hi - lo >= 180 (the gripper is symmetric, every yaw must be reachable)") + if not (isinstance(info.get("max_speed"), (int, float)) and 0.01 <= info["max_speed"] <= 1.0): + p.append("max_speed: m/s, 0.01..1.0") + if not isinstance(info.get("ik"), bool): + p.append("ik: true|false (whether /ik is implemented; needed only for tasks with a calibration bias)") + if not isinstance(info.get("driver_version"), str): + p.append("driver_version: string (your git commit or a date; it is written into every run's log)") + return p + + +def state_problems(st, n_joints): + p = [] + if not _vec(st.get("eef_pos"), 3): + p.append("state.eef_pos: [x, y, z] metres") + if not (isinstance(st.get("eef_yaw_deg"), (int, float)) and math.isfinite(st["eef_yaw_deg"])): + p.append("state.eef_yaw_deg: number") + if not (isinstance(st.get("gripper_width_m"), (int, float)) and 0.0 <= st["gripper_width_m"] <= 0.2): + p.append("state.gripper_width_m: number 0..0.2") + if not _vec(st.get("joint_pos_rad"), n_joints): + p.append(f"state.joint_pos_rad: {n_joints} numbers (radians)") + return p + + +# ------------------------------------------------------------------------------------------------ benchmark side +class DriverClient: + """Typed calls to a driver. `url` like http://127.0.0.1:9900 (an SSH tunnel to the robot PC).""" + + def __init__(self, url, token, timeout=120.0): + self.url, self.token, self.timeout = url.rstrip("/"), token, float(timeout) + self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never through a web proxy + + def call(self, endpoint, payload=None, timeout=None, allow_not_ok=False): + req = urllib.request.Request(f"{self.url}/{endpoint}", data=json.dumps(payload or {}).encode(), + headers={"Content-Type": "application/json", TOKEN_HEADER: self.token}) + try: + with self.opener.open(req, timeout=timeout if timeout is not None else self.timeout) as r: + rep = json.loads(r.read().decode()) + except (urllib.error.URLError, OSError, ValueError) as e: + raise DriverError(f"/{endpoint}: no valid reply from the driver ({type(e).__name__}: {e})") from e + if not isinstance(rep, dict) or "ok" not in rep: + raise DriverError(f"/{endpoint}: reply is not a JSON object with \"ok\"") + if rep.get("fault"): + raise DriverFault(f"/{endpoint}: robot fault: {rep.get('error', '')}") + if not rep["ok"] and not allow_not_ok: + raise DriverError(f"/{endpoint}: {rep.get('error', 'not ok')}") + return rep + + def info(self): + rep = self.call("info") + prob = info_problems(rep) + if prob: + raise DriverError("/info: " + "; ".join(prob)) + return rep + + def home(self): + return self.call("home", timeout=max(self.timeout, 300)) + + def move(self, x, y, z, yaw_deg, speed=None): + """-> reply; ok=false (not a fault) means the target was rejected and the arm did not move.""" + return self.call("move", dict(x=float(x), y=float(y), z=float(z), yaw_deg=float(yaw_deg), + speed=None if speed is None else float(speed)), allow_not_ok=True) + + def gripper(self, close): + return self.call("gripper", dict(close=bool(close))) + + def state(self): + return self.call("state")["state"] + + def observe(self): + rep = self.call("observe") + imgs = rep.get("images") or {} + missing = [c for c in CAMERAS if c not in imgs] + if missing: + raise DriverError(f"/observe: missing camera(s) {missing}") + return {c: decode_image(imgs[c]) for c in CAMERAS}, rep["state"] + + def ik(self, eef_pos, yaw_deg): + return self.call("ik", dict(eef_pos=[float(v) for v in eef_pos], yaw_deg=float(yaw_deg)))["joint_pos_rad"] + + def operator(self, kind, **kw): + """Blocks until the operator has answered (no timeout).""" + assert kind in OPERATOR_KINDS, kind + return self.call("operator", dict(kind=kind, **kw), timeout=24 * 3600) + + def event(self, ev, **kw): + assert ev in EVENTS, ev + return self.call("event", dict(ev=ev, **kw)) + + +# ------------------------------------------------------------------------------------------------ driver side +class ConsoleOperator: + """The operator's terminal on the robot PC. Prompts block the driver (the robot must not move while the operator + resets the scene). Answers are appended to `log_path` (JSON lines).""" + + def __init__(self, log_path=None, stream_in=None, stream_out=None): + self.log_path = log_path + self.inp = stream_in or sys.stdin + self.out = stream_out or sys.stdout + + def _say(self, s=""): + self.out.write(s + "\n") + self.out.flush() + + def _ask(self, prompt): + self.out.write(prompt) + self.out.flush() + line = self.inp.readline() + if not line: + raise EOFError("operator input closed") + return line.strip() + + def _log(self, d): + if self.log_path: + os.makedirs(os.path.dirname(os.path.abspath(self.log_path)), exist_ok=True) + with open(self.log_path, "a") as f: + f.write(json.dumps(dict(d, t=time.time()), ensure_ascii=False) + "\n") + + def __call__(self, kind, run="", attempt=None, text="", setup="", checklist=None, **_): + bar = "=" * 72 + self._say("\n" + bar) + self._say(f"[{time.strftime('%H:%M:%S')}] run {run} attempt {attempt} -- {kind.upper()}") + if text: + self._say(text) + if kind == "reset": + if setup: + self._say("\nScene for this attempt (do it exactly; do not talk to anyone about it):\n" + setup) + self._ask("\nArm is at home. Put the scene back as described, step out of the cameras, press Enter... ") + self._log(dict(kind=kind, run=run, attempt=attempt)) + return dict(ok=True) + if kind == "judge": + for i, c in enumerate(checklist or [], 1): + self._say(f" {i}. {c}") + while True: + a = self._ask("\nAll conditions met? y = success, n = failure, x = run invalid (robot / camera " + "problem): ").lower() + if a in ("y", "n", "x"): + break + note = self._ask("Note (one line, optional): ") + self._log(dict(kind=kind, run=run, attempt=attempt, answer=a, note=note)) + if a == "x": + return dict(ok=False, fault=True, error=f"operator marked the run invalid: {note}") + return dict(ok=True, success=a == "y", note=note) + self._log(dict(kind=kind, run=run, attempt=attempt, text=text)) + return dict(ok=True) + + +class DriverServer: + """HTTP plumbing for a driver. Subclass and implement the hardware methods below; see driver_template.py. + The server is single-threaded on purpose: requests are executed one at a time, and an operator prompt blocks + every other request until it is answered.""" + + # ---- implement these ------------------------------------------------------------------------------ + def info(self): + """-> dict (see DRIVER.md §3): protocol, robot, n_joints, cameras, workspace, yaw_range_deg, max_speed, ik, + driver_version.""" + raise NotImplementedError + + def home(self): + """Move to the home pose (gripper open, pointing down). -> state dict.""" + raise NotImplementedError + + def move(self, x, y, z, yaw_deg, speed): + """Blocking straight-line move of the grasp point; speed m/s or None (= max_speed). + -> (ok, error_or_None, motion_s). ok=False: rejected BEFORE moving (outside the hard limits / no IK).""" + raise NotImplementedError + + def gripper(self, close): + """Blocking open / close (force-limited close). -> motion_s.""" + raise NotImplementedError + + def state(self): + """-> dict eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad.""" + raise NotImplementedError + + def images(self): + """-> {"agentview": uint8 HxWx3 RGB, "wrist": ...}, taken now (after the arm has stopped).""" + raise NotImplementedError + + def ik(self, eef_pos, yaw_deg): + """Optional (info()["ik"] = True): joint angles that put the grasp point at eef_pos / yaw_deg (pointing + down), close to the current joint angles. -> list of n_joints floats.""" + raise NotImplementedError + + def operator(self, kind, **kw): + """Default: the terminal. -> dict (reset: {ok}; judge: {ok, success, note}; notice: {ok}).""" + return self.console(kind, **kw) + + def event(self, ev, **kw): + """Start / stop your own recordings here (attempt_start / attempt_end / episode_end ...).""" + return None + + image_format = "png" + + # ---- plumbing ------------------------------------------------------------------------------------- + def dispatch(self, endpoint, a): + if endpoint == "info": + return dict(ok=True, **self.info()) + if endpoint == "home": + return dict(ok=True, state=self.home()) + if endpoint == "move": + ok, err, motion_s = self.move(float(a["x"]), float(a["y"]), float(a["z"]), float(a["yaw_deg"]), + None if a.get("speed") is None else float(a["speed"])) + rep = dict(ok=bool(ok), motion_s=float(motion_s or 0.0), state=self.state()) + if not ok: + rep["error"] = err or "rejected" + return rep + if endpoint == "gripper": + motion_s = self.gripper(bool(a["close"])) + return dict(ok=True, motion_s=float(motion_s or 0.0), state=self.state()) + if endpoint == "state": + return dict(ok=True, state=self.state()) + if endpoint == "observe": + imgs = self.images() + return dict(ok=True, images={c: encode_image(imgs[c], self.image_format) for c in CAMERAS}, + state=self.state()) + if endpoint == "ik": + return dict(ok=True, joint_pos_rad=[float(v) for v in self.ik(a["eef_pos"], float(a["yaw_deg"]))]) + if endpoint == "operator": + kw = {k: v for k, v in a.items() if k != "kind"} + return self.operator(a["kind"], **kw) + if endpoint == "event": + self.event(a.get("ev", ""), **{k: v for k, v in a.items() if k != "ev"}) + return dict(ok=True) + return dict(ok=False, error=f"unknown endpoint {endpoint!r}") + + def serve(self, port, token=None, host="127.0.0.1", operator_log=None): + """Serve forever on host:port (keep 127.0.0.1 and reach it through an SSH tunnel).""" + self.token = token or os.environ.get("LFF_DRIVER_TOKEN") or secrets.token_hex(12) + self.console = ConsoleOperator(operator_log) + drv = self + + class H(BaseHTTPRequestHandler): + def log_message(self, *x): + pass + + def do_POST(self): + try: + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}") + if self.headers.get(TOKEN_HEADER) != drv.token: + rep = dict(ok=False, error="unauthorised") + else: + rep = drv.dispatch(self.path.strip("/"), body) + except NotImplementedError as e: + rep = dict(ok=False, error=f"not implemented: {self.path} {e}") + except Exception as e: # anything unexpected on the robot side is a fault: stop the run + traceback.print_exc() + rep = dict(ok=False, fault=True, error=f"{type(e).__name__}: {e}") + data = json.dumps(rep).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + srv = HTTPServer((host, int(port)), H) + print(f"driver ready on http://{host}:{port} token={self.token}", flush=True) + srv.serve_forever() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_tool.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..beedef27c243b3cea3823932d02204898034e069 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_tool.py @@ -0,0 +1,549 @@ +"""L3-C under_table_tool: a cube sits under a low glass side table; put it into the bin (tool use). + +v2 (2026-10-08, user review of cla2): in v1 the hidden information was "the hand does not fit under the glass top". +Every Sonnet run (4/4) saw the T-shaped stick lying next to the low table and used it straight away, i.e. the task +was solved by reasoning before acting and nothing had to be learned from a failure. v2 keeps the scene and moves the +hidden information to something no image shows: + +Hidden: the side of the low table AWAY from the stick is closed by a clear acrylic panel (between the two legs, +tabletop to glass top; collision only, nothing is rendered). The bin stands on that side, beyond the panel. The other +three sides are open. + +Why the prior fails: the stick lies on one side with its head pointing at the low table, and the bin is on the +opposite side, so the obvious plan is "slide the stick in and push the cube straight across, out towards the bin". +The cube then stops against the invisible panel, still completely under the glass top (the hand cannot reach it +there: the glass is 7 cm above the tabletop). Pushing harder or again from the same side fails the same way. + +What must be learned from the failure (F1: from the images -- the cube stopped at the edge and did not come out): +something blocks that side -> change the push: put the stick down behind the low table (the robot's side) pointing +forward, push the cube out of the FRONT side (away from the robot), then grasp it and carry it to the bin. + +Layout (randomised per instance): position of the low table, cube position under it (+-1 cm around the centre), +the stick lying beside the low table (left or right) with its head pointing at it (+-10 deg), the panel and the bin +on the other side. + +Protocol: cross (reset to the same instance before every attempt), k = 5. v1 is kept in l3_tool.py.bak-20261008-pane. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task + +CUBE_HALF = 0.02 +TOP_HALF = (0.06, 0.06, 0.005) # glass top 12 x 12 cm, 1 cm thick +TOP_UNDER = 0.07 # underside of the glass top above the tabletop +LEG_HALF = 0.008 +HANDLE_HALF = (0.12, 0.008, 0.01) # stick handle 24 x 1.6 x 2 cm, along local x +HEAD_HALF = (0.008, 0.025, 0.01) # crossbar 1.6 x 5 x 2 cm at the +x end +BIN_IN = (0.06, 0.06) +BIN_WALL_H = 0.05 +GRIP_END = 0.035 # scripted grasp point: this far from the free end of the handle +GRIP_FRONT = 0.07 # v2 front push: grasp this far from the free end (keeps the hand clear of the glass edge) +Z_STICK = envs.TABLE_Z + 0.0125 # site height when grasping / sliding the stick (pads 0.75-2.4 cm above the table) +TIP_BELOW_SITE = 0.0095 +# clear acrylic panel between the two legs of one y side, tabletop to glass underside (collision only, invisible) +PANE_HALF = (TOP_HALF[0] - 2 * LEG_HALF, 0.002, TOP_UNDER / 2) +PANE_Y = TOP_HALF[1] - LEG_HALF # in the plane of the leg centres +STICK_COM = 0.0221 # the stick's centre of mass is this far from the handle centre, towards the head +BIN_GAP = (0.04, 0.06) # tabletop gap between the low table's far side and the bin's outer wall + + +def low_table_xml(model_name): + glass, leg = (0.70, 0.85, 0.95, 0.30), (0.35, 0.25, 0.18, 1.0) + z_top = TOP_UNDER + TOP_HALF[2] + parts = [((0, 0, z_top), TOP_HALF, glass)] + for sx in (-1, 1): + for sy in (-1, 1): + parts.append(((sx * (TOP_HALF[0] - LEG_HALF), sy * (TOP_HALF[1] - LEG_HALF), TOP_UNDER / 2), + (LEG_HALF, LEG_HALF, TOP_UNDER / 2), leg)) + g = [] + for k, (p, s, c) in enumerate(parts): + g.append(f' ') + g.append(f' ') + # acrylic panels on both y sides; apply_instance turns the collision of the one next to the stick off. + # Fully transparent (rgba alpha 0) and no visual twin: nothing is rendered. + for k, sy in enumerate((1, -1)): + g.append(f' ') + # origin at the tabletop (z = 0 is the bottom of the legs) + return _wrap(model_name, "\n".join(g), 0.0, float(np.hypot(TOP_HALF[0], TOP_HALF[1]))) + + +def stick_xml(model_name): + c = (0.80, 0.62, 0.30, 1.0) + parts = [((0, 0, 0), HANDLE_HALF), ((HANDLE_HALF[0] + HEAD_HALF[0], 0, 0), HEAD_HALF)] + g = [] + for k, (p, s) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(model_name, "\n".join(g), HANDLE_HALF[2], HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +@register_task +class UnderTableTool(LFFTask): + name = "l3_under_table_tool" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the red cube into the gray bin." + instruction_indirect = "Put the small red block that is under the low glass table into the gray container." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + self.inst = None + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + cube = register_generated("LffBenchCube", box_xml("lff_bench_cube", (CUBE_HALF,) * 3, (0.85, 0.12, 0.12, 1.0), + density=800)) + stick = register_generated("LffBenchStick", stick_xml("lff_bench_stick")) + table = register_generated("LffLowGlassTable", low_table_xml("lff_low_glass_table"), free=False) + tray = register_generated("LffBenchBin", bin_xml("lff_bench_bin", BIN_IN, BIN_WALL_H), free=False) + objs = [("cube_1", cube, "cube_region", (-0.21, -0.26, -0.19, -0.24)), + ("stick_1", stick, "stick_region", (-0.01, 0.24, 0.01, 0.26))] + fx = [("lowtable_1", table, "lowtable_region", (0.19, -0.01, 0.21, 0.01)), + ("bin_1", tray, "bin_region", (0.19, 0.29, 0.21, 0.31))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _fixture(self, name): + if not hasattr(self, "_fx"): + self._fx = {} + if name not in self._fx: + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict[name].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._fx[name] = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]) + return self._fx[name] + + def _panes(self): + """[(geom id, +1 / -1 = which y side of the low table)] of the two acrylic panel geoms""" + if not hasattr(self, "_pane_ids"): + m = self.env.sim.model + self._pane_ids = [(g, int(np.sign(m.geom_pos[g][1]))) for g in self._fixture("lowtable_1")[1] + if np.allclose(m.geom_size[g], PANE_HALF, atol=1e-6)] + assert len(self._pane_ids) == 2, self._pane_ids + return self._pane_ids + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + side = int(rng.choice([-1, 1])) # the stick lies on the left (+1) or right (-1) of the low table + # v2: 4 cm further from the robot than v1 (-0.16..-0.10), so that a stick pushed forward from behind the + # low table is within reach (gripper about 25 cm in front of the robot base at the start of that push) + t_xy = np.array([rng.uniform(-0.12, -0.06), -side * rng.uniform(0.04, 0.07)]) + cube_xy = t_xy + rng.uniform(-0.01, 0.01, 2) + # the stick lies beside the low table, its head pointing roughly at it (+-10 deg), 2.5-4.5 cm from its edge + yaw = -side * np.pi / 2 + float(rng.uniform(-np.radians(10), np.radians(10))) + d = np.array([np.cos(yaw), np.sin(yaw)]) + head_front = np.array([cube_xy[0] + rng.uniform(-0.01, 0.01), t_xy[1] + side * (TOP_HALF[1] + rng.uniform(0.025, 0.045))]) + stick_xy = head_front - d * (HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + # v2: the bin stands on the far side (the panel's side), so pushing the cube straight across looks like the + # way to the bin + gap = rng.uniform(*BIN_GAP) + bin_xy = np.array([t_xy[0] + rng.uniform(-0.02, 0.02), + t_xy[1] - side * (TOP_HALF[1] + gap + BIN_IN[1] + 0.006)]) + return dict(seed=int(seed), table_xy=t_xy.tolist(), cube_xy=cube_xy.tolist(), side=side, pane_side=-side, + stick_xy=stick_xy.tolist(), stick_yaw=float(yaw), bin_xy=bin_xy.tolist()) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bid, _ = self._fixture("lowtable_1") + m.body_pos[bid] = [inst["table_xy"][0], inst["table_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + for g, sy in self._panes(): # only the panel on the far side (away from the stick) collides + on = sy == inst.get("pane_side", -inst["side"]) + m.geom_contype[g] = 1 if on else 0 + m.geom_conaffinity[g] = 1 if on else 0 + bbid, _ = self._fixture("bin_1") + m.body_pos[bbid] = [inst["bin_xy"][0], inst["bin_xy"][1], envs.TABLE_Z + (BIN_WALL_H + 0.006) / 2] + m.body_quat[bbid] = [1, 0, 0, 0] + cx, cy = inst["cube_xy"] + envs.set_obj_pose(self.env, "cube_1", [cx, cy, envs.TABLE_Z + CUBE_HALF + 0.0005]) + sx, sy = inst["stick_xy"] + envs.set_obj_pose(self.env, "stick_1", [sx, sy, envs.TABLE_Z + HANDLE_HALF[2] + 0.0005], yaw=inst["stick_yaw"]) + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ state + def stick_pose(self): + d = self.env.sim.data + bid = envs.body_id(self.env, "stick_1") + return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy() + + def observe(self): + p, R = self.stick_pose() + ax = R[:2, 0] / max(np.linalg.norm(R[:2, 0]), 1e-9) + return dict(cube=envs.obj_pos(self.env, "cube_1"), table_xy=np.array(self.inst["table_xy"]), + bin_xy=np.array(self.inst["bin_xy"]), stick_xy=p[:2], stick_dir=ax, + free_end=p[:2] - ax * HANDLE_HALF[0], head=p[:2] + ax * (HANDLE_HALF[0] + HEAD_HALF[0])) + + def under_table(self, xy=None, margin=0.0): + """is the cube's footprint (any part) under the glass top?""" + xy = envs.obj_pos(self.env, "cube_1")[:2] if xy is None else np.asarray(xy) + rel = np.abs(xy - np.array(self.inst["table_xy"])) + return bool((rel < np.array(TOP_HALF[:2]) + CUBE_HALF + margin).all()) + + def outside_dist(self): + """how far the cube's footprint is outside the glass top (m, < 0: still partly under it)""" + rel = np.abs(envs.obj_pos(self.env, "cube_1")[:2] - np.array(self.inst["table_xy"])) + return float(max(rel - np.array(TOP_HALF[:2]) - CUBE_HALF)) + + def in_bin(self): + p = envs.obj_pos(self.env, "cube_1") + rel = np.abs(p[:2] - np.array(self.inst["bin_xy"])) + return bool(p[2] < envs.TABLE_Z + BIN_WALL_H and (rel < np.array(BIN_IN)).all()) + + # ------------------------------------------------------------ contacts / monitor + def _groups(self): + if not hasattr(self, "_gg"): + m = self.env.sim.model + robot = set(envs.robot_geom_ids(self.env)) + tbl = self._fixture("lowtable_1")[1] + top = {g for g in tbl if m.geom_contype[g] and abs(m.geom_size[g, 0] - TOP_HALF[0]) < 1e-6} + self._gg = (robot, set(tbl), top, set(envs.obj_geom_ids(self.env, "stick_1")), + set(envs.obj_geom_ids(self.env, "cube_1"))) + return self._gg + + def _robot_contacts(self): + """labels of what the robot touches: 'glass_top', 'pane', 'table_leg', 'stick', 'cube'""" + robot, tbl, top, stick, cube = self._groups() + panes = {g for g, _ in self._panes()} + d = self.env.sim.data + out = set() + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in robot: + o = c.geom2 + elif c.geom2 in robot: + o = c.geom1 + else: + continue + if o in top: + out.add("glass_top") + elif o in panes: + out.add("pane") + elif o in tbl: + out.add("table_leg") + elif o in stick: + out.add("stick") + elif o in cube: + out.add("cube") + return out + + def _start_monitor(self): + c = envs.obj_pos(self.env, "cube_1") + self._mon = dict(start=c.copy(), top_hit=None, stick_held=False, stick_touched_cube=False, max_cube_dz=0.0, + cube_out=not self.under_table(), cube_hit_pane=False, stick_hit_pane=False, + robot_hit_pane=False) + + def _monitor_step(self): + mon, sk = self._mon, self.sk + if sk is None: + return + hits = self._robot_contacts() + if "glass_top" in hits: + e = sk.eef_pos() + rel = np.abs(e[:2] - np.array(self.inst["table_xy"])) + mon["top_hit"] = dict(above=bool((rel < np.array(TOP_HALF[:2])).all()), + tip=float(e[2] - TIP_BELOW_SITE - envs.TABLE_Z), + outside=float(max(rel - np.array(TOP_HALF[:2])))) + if sk.holding("stick_1"): + mon["stick_held"] = True + if "pane" in hits: + mon["robot_hit_pane"] = True + robot, tbl, top, stick, cube = self._groups() + panes = {g for g, _ in self._panes()} + d = self.env.sim.data + for i in range(d.ncon): + c = d.contact[i] + pair = (c.geom1, c.geom2) + if (pair[0] in stick and pair[1] in cube) or (pair[1] in stick and pair[0] in cube): + mon["stick_touched_cube"] = True + if (pair[0] in panes and pair[1] in cube) or (pair[1] in panes and pair[0] in cube): + mon["cube_hit_pane"] = True + if (pair[0] in panes and pair[1] in stick) or (pair[1] in panes and pair[0] in stick): + mon["stick_hit_pane"] = True + p = envs.obj_pos(self.env, "cube_1") + mon["max_cube_dz"] = max(mon["max_cube_dz"], float(p[2] - mon["start"][2])) + if not self.under_table(): + mon["cube_out"] = True + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self._mon or {} + p = envs.obj_pos(self.env, "cube_1") + held = bool(self.sk.holding("cube_1")) if self.sk is not None else False + success = bool(self.in_bin() and not held) + moved = float(np.linalg.norm(p[:2] - mon.get("start", p)[:2])) + under = self.under_table() + brel = p[:2] - np.array(inst["bin_xy"]) + parts, mode = [], "success" + top = mon.get("top_hit") + if success: + parts.append("The cube is in the bin.") + elif p[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The cube fell off the table.") + elif held: + mode = "held" + parts.append("The cube is still held by the gripper; it was not released into the bin.") + elif under: + mode = "under" + if top is not None and not mon.get("stick_touched_cube"): + mode = "blocked" + if top["above"]: + parts.append(f"The gripper came down on the glass top of the low table: its fingertips stopped " + f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, while the cube is underneath " + f"the glass (the glass underside is {100 * TOP_UNDER:.1f} cm above the tabletop), so the " + f"gripper never got to the cube.") + else: + parts.append(f"The hand ran into the edge of the glass top of the low table (fingertips " + f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, gripper " + f"{100 * max(top['outside'], 0.0):.1f} cm outside the edge) and could not move in " + f"under the glass.") + if mon.get("cube_hit_pane"): + mode = "pane" + parts.append(f"The cube was pushed against a clear acrylic panel that closes the " + f"{'left' if inst.get('pane_side', -inst['side']) > 0 else 'right'} side of the low " + f"table (between its two legs, from the tabletop up to the glass); it cannot leave the " + f"low table on that side.") + if moved > 0.01: + parts.append(f"The cube was moved {100 * moved:.1f} cm but is still under the low table " + f"({100 * -self.outside_dist():.1f} cm from getting completely out from under it).") + else: + parts.append("The cube did not move; it is still under the low table.") + else: + mode = "out_not_in_bin" + lifted = mon.get("max_cube_dz", 0.0) > 0.03 + parts.append(("The cube was lifted but ended outside the bin" if lifted else + "The cube is out from under the low table but not in the bin") + + f": it is {100 * abs(brel[0]):.1f} cm {'forward' if brel[0] > 0 else 'backward'} and " + f"{100 * abs(brel[1]):.1f} cm {'left' if brel[1] > 0 else 'right'} of the bin's centre.") + out = dict(success=success, mode=mode, moved=moved, under=under, cube_rel_bin=[float(brel[0]), float(brel[1])], + stick_used=bool(mon.get("stick_held")), terminal=bool(p[2] < envs.TABLE_Z - 0.05), + cube_hit_pane=bool(mon.get("cube_hit_pane")), stick_hit_pane=bool(mon.get("stick_hit_pane")), + robot_hit_pane=bool(mon.get("robot_hit_pane")), detail=" ".join(parts)) + self._start_monitor() + return out + + # ------------------------------------------------------------ primitives for the scripted policies + def _yaw_near(self, yaw): + cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=80): + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + if self._robot_contacts() - {"cube"} and sk.eef_pos()[2] > tgt[2] + 0.005: + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + + def grasp_cube_and_bin(self, dxy=(0.0, 0.0), dyaw=0.0): + """Top-down grasp of the cube where it is (+ offsets); if held, drop it into the bin.""" + sk, o = self.sk, self.observe() + c = o["cube"] + gx, gy = c[0] + dxy[0], c[1] + dxy[1] + # the hand is 20 cm long along the closing direction: keep that direction parallel to the low table's edge + v = c[:2] - o["table_xy"] + yaw = (np.pi / 2 if abs(v[1]) > abs(v[0]) else 0.0) + dyaw + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, envs.TABLE_Z + 0.15], yaw=self._yaw_near(yaw)) + self._align() + self._guarded_descent([gx, gy, envs.TABLE_Z + 0.017]) + sk.set_gripper(True, steps=15) + e = sk.eef_pos() + sk.move_to([e[0], e[1], envs.TABLE_Z + 0.16], speed=0.25) + if sk.holding("cube_1"): + bx, by = o["bin_xy"] + sk.move_to([bx, by, envs.TABLE_Z + 0.16]) + sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05]) + sk.set_gripper(False, steps=12) + sk.move_to([bx, by, envs.TABLE_Z + 0.16]) + else: + sk.set_gripper(False, steps=6) + + def tool_push_out(self, extra=0.0): + """Pick the stick up by the end of its handle (it already points at the low table), lift it a few mm and slide + it along its own axis under the glass top so that its head pushes the cube out on the far side; put it down.""" + sk, o = self.sk, self.observe() + ax = o["stick_dir"] + g = o["free_end"] + ax * GRIP_END + sk.set_gripper(False, steps=8) + sk.move_to([g[0], g[1], Z_STICK + 0.08], yaw=self._yaw_near(float(np.arctan2(ax[1], ax[0])))) + self._align() + sk.move_to([g[0], g[1], Z_STICK], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05) + o2 = self.observe() + c, t_xy = o2["cube"][:2], o2["table_xy"] + n = np.array([0.0, -float(self.inst["side"])]) # push straight across the low table (normal of its far edge) + perp = np.array([-n[1], n[0]]) + head = o2["head"] + # line the head up with the cube by sliding the stick sideways (no turning: a turned stick slips in the grasp) + lat = float((c - head) @ perp) + e = sk.eef_pos() + sk.move_to([e[0] + perp[0] * lat, e[1] + perp[1] * lat, e[2]], speed=0.05) + o3 = self.observe() + head_front = float((o3["head"] + o3["stick_dir"] * HEAD_HALF[0]) @ n) + gap = max(float(c @ n) - CUBE_HALF - head_front, 0.0) + need = (TOP_HALF[1] + CUBE_HALF + 0.05 + extra) - float((c - t_xy) @ n) # cube travel until it is clear + e = sk.eef_pos() + tgt = e[:2] + n * (gap + need) + sk.move_to([tgt[0], tgt[1], e[2]], speed=0.08, tol=0.004, max_steps=500) + sk.hold(3) + for _ in range(3): # still (partly) under the glass top: push on a little + if not self.under_table() or not sk.holding("stick_1"): + break + e = sk.eef_pos() + tgt = e[:2] + n * 0.025 + sk.move_to([tgt[0], tgt[1], e[2]], speed=0.06, tol=0.004, max_steps=100) + sk.hold(3) + ax = n + back = sk.eef_pos()[:2] - ax * 0.05 + sk.move_to([back[0], back[1], e[2]], speed=0.08) + sk.set_gripper(False, steps=10) + sk.move_to([back[0], back[1], envs.TABLE_Z + 0.12], speed=0.2) + + def tool_push_front(self, extra=0.0): + """v2 reference solution. Pick the stick up at its centre of mass, turn it to point forward (+x, away from the + robot) in the air, put it down behind the low table in line with the cube, re-grasp it GRIP_FRONT from its + free end and slide it forward under the glass top so that its head pushes the cube out of the FRONT side; + pull the stick back a little and put it down. + + Reach: the re-grasp point is about 25 cm in front of the robot base at the start of the push; it stays + >= 3 cm behind the glass top's back edge at the end (the hand is about 4-13 cm above the fingertips and + would hit the glass edge).""" + sk, o = self.sk, self.observe() + ax = o["stick_dir"] + com = o["stick_xy"] + ax * STICK_COM + phi = float(np.arctan2(ax[1], ax[0])) # the stick points this way (handle -> head); about +-90 deg + sk.set_gripper(False, steps=8) + # grasp with gripper yaw = phi (not phi +- pi), so that turning the stick to point forward is a wrist turn to + # yaw 0, inside the wrist's range + sk.move_to([com[0], com[1], Z_STICK + 0.08], yaw=phi, wrap_yaw=False) + self._align() + sk.move_to([com[0], com[1], Z_STICK], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([com[0], com[1], Z_STICK + 0.10], speed=0.15) + c, t_xy = o["cube"][:2], o["table_xy"] + head_front_x = t_xy[0] - TOP_HALF[0] - 0.006 # just outside the glass top's back edge + put_x = head_front_x - (HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + STICK_COM + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2]], yaw=0.0, wrap_yaw=False) + self._align() + sk.move_to([put_x, c[1], Z_STICK + 0.10], speed=0.2) + sk.move_to([put_x, c[1], Z_STICK + 0.004], speed=0.08, tol=0.003) + sk.set_gripper(False, steps=10) + sk.move_to([put_x, c[1], Z_STICK + 0.06], speed=0.15) + # re-grasp near the free end + o2 = self.observe() + ax2 = o2["stick_dir"] + g = o2["free_end"] + ax2 * GRIP_FRONT + sk.move_to([g[0], g[1], Z_STICK + 0.06], yaw=self._yaw_near(float(np.arctan2(ax2[1], ax2[0])))) + self._align() + sk.move_to([g[0], g[1], Z_STICK], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05) + # line the head up with the cube (sideways slide), then push forward + o3 = self.observe() + lat = float(c[1] - o3["head"][1]) + e = sk.eef_pos() + sk.move_to([e[0], e[1] + lat, e[2]], speed=0.05) + o4 = self.observe() + head_front = float(o4["head"][0] + HEAD_HALF[0]) + cube_tgt = t_xy[0] + TOP_HALF[0] + CUBE_HALF + 0.03 + extra + travel = (cube_tgt - CUBE_HALF) - head_front + e = sk.eef_pos() + sk.move_to([e[0] + travel, e[1], e[2]], speed=0.08, tol=0.004, max_steps=500) + sk.hold(3) + e = sk.eef_pos() + sk.move_to([e[0] - 0.05, e[1], e[2]], speed=0.08) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], envs.TABLE_Z + 0.12], speed=0.2) + + def execute(self, inst, params): + if params["mode"] == "tool": + self.tool_push_out(params.get("extra", 0.0)) + elif params["mode"] == "front": + self.tool_push_front(params.get("extra", 0.0)) + self.grasp_cube_and_bin(params.get("dxy", (0.0, 0.0)), params.get("dyaw", 0.0)) + + # ------------------------------------------------------------ scripted references + def default_params(self, inst): + """v2 prior: what every cla2 Sonnet run did -- take the stick and push the cube straight across (towards + the bin, which is now behind the hidden panel)""" + return dict(mode="tool") + + def oracle_params(self, inst): + return dict(mode="front") + + def blind_params(self, inst, attempt, rng): + """no history: the prior with a random extra push length""" + return dict(mode="tool", extra=float(abs(rng.normal(0, 0.03)))) + + def adapt_params(self, inst, history): + """v2: the cube stayed under the low table after a push across -> something blocks that side: push it out of + the front instead. Hand grasp blocked by the glass -> use the stick (the v1 lesson). Front push that did not + get it out -> push further.""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] == "grasp": + return dict(mode="tool") if out["mode"] in ("blocked", "under") else dict(prm) + if prm["mode"] == "tool": + return dict(mode="front") if out["mode"] in ("pane", "under", "blocked") else dict(prm) + if out["mode"] in ("under", "blocked"): + return dict(prm, extra=prm.get("extra", 0.0) + 0.02) + return dict(prm) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l5_slide.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l5_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee239b7ba2793288aeaaa5e5d4f0a5b11c835f5 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l5_slide.py @@ -0,0 +1,577 @@ +"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone. + +Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the +same for every mu. With the default push speed the cube overshoots on slippery instances and stops +short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard +to push next time (cf. MemMimic push_cube, iterative pushing). + +Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt +(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that +carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule +also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The +loophole is now closed by the success rule instead: + +Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there +by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts +checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with +nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push +into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in +front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm. + +Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged +when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside). +`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then +succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the +arm's reach (the attempt is not ended for it). + +Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance +the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre). +SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX), +so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time. + +Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview +camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far +edge by up to ~1 cm covers the far green line but shows < 2 px of red beyond it in the 512 x 512 image, which looks like +"inside / on the line" (self-test: 0.8 cm past the inner edge looked inside). So on the far side the cube may now lie on +the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to +TOL_PAST = 2.0 cm past the square's centre (front face <= 4 mm beyond the line's outer edge). From 2.0 cm on, every one +of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely +inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides +the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +CUBE = "cube_1" +CUBE_HALF = 0.02 +D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long +STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike +TOUCH_MOVE = 0.001 # a contact episode moved the cube if the cube ends >= 1 mm (3-D) from where it was at its start +EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode +V_REST, W_REST = 0.003, 0.05 # cube at rest: linear speed below 3 mm/s and angular speed below 0.05 rad/s ... +REST_SUB = 25 # ... for 25 consecutive substeps (50 ms) +WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest +ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF +OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table +REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable + + +class CubeWatch: + """Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it). + + contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed + EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was + when the episode began, or still moving. + release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide + began (None while the robot has never moved the cube). + strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to + rest (or when the robot touches it again before that: result "interrupted").""" + + def __init__(self, env, target_xy, tol_short, tol_past, tol_across): + m = env.sim.model + self.env = env + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.is_cube = np.zeros(m.ngeom, bool) + self.is_cube[envs.obj_geom_ids(env, CUBE)] = True + self.qa, self.da = envs.free_joint_addr(env, CUBE) + self.target = np.asarray(target_xy, float) + self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside + self.n_sub = 0 + self.ep = None # open contact episode + self.gap = 0 + self.quiet = 0 # consecutive substeps at rest + self.release = None + self.slide = None # free slide in progress: where it started (cube at the episode start) and was released + self.moves = [] # closed contact episodes that moved the cube + self.strikes = [] + + # ------------------------------------------------------------ state + def pos(self): + return self.env.sim.data.qpos[self.qa:self.qa + 3].copy() + + def at_rest(self): + qv = self.env.sim.data.qvel[self.da:self.da + 6] + return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST) + + def judge(self, p): + """Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off). + in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it.""" + along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1]) + if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE: + return along, across, "off" + short, past, beside = self.tol + if -short <= along <= past and abs(across) <= beside: + return along, across, "in" + if along > past: + return along, across, "past" + if along < -short: + return along, across, "short" + return along, across, "beside" + + # ------------------------------------------------------------ per substep + def substep(self): + d = self.env.sim.data + n = d.ncon + touch = False + if n: + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1]))) + self.n_sub += 1 + p = self.pos() + rest = self.at_rest() + self.quiet = self.quiet + 1 if rest else 0 + if touch: + if self.ep is None: + if self.slide is not None: + self._end_slide(p, interrupted=not rest) + self.ep = dict(start=p, sub0=self.n_sub) + self.ep["last"] = p + self.ep["sub1"] = self.n_sub + self.gap = 0 + elif self.ep is not None: + self.gap += 1 + if self.gap >= EP_GAP: + self._close(p, rest) + if self.ep is None and self.slide is not None and self.quiet >= REST_SUB: + self._end_slide(p, interrupted=False) + + def _close(self, p, rest): + ep, self.ep = self.ep, None + if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest: + return # touched a resting cube and left it where it was + self.release = ep["last"][:2].copy() + self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(), + release=ep["last"].round(4).tolist())) + self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"]) + + def _end_slide(self, p, interrupted): + s, self.slide = self.slide, None + free = float(np.linalg.norm(p[:2] - s["release"][:2])) + if free < STRIKE_MIN: + return # a push or a put-down, not a strike + along, across, res = self.judge(p) + self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(), + release=s["release"].round(4).tolist(), rest=p.round(4).tolist(), + pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2), + free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2), + across_err_cm=round(100 * across, 2), + result="interrupted" if interrupted else res, + missed=bool(not interrupted and res != "in"))) + + def flush(self): + """End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact + has moved it (then the cube's current free slide is 0).""" + p = self.pos() + if self.ep is not None: + if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest(): + self.release = p[:2].copy() + self.slide = None + return True + return False + if self.slide is not None and self.at_rest(): + self._end_slide(p, interrupted=False) + return False + + +def _install_watch(sim, watch): + """Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker; + it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one + control step, so contact checks at control steps alone would miss it.""" + if not getattr(sim, "_lff_slide_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + w = getattr(sim, "_lff_slide_watch", None) + if w is not None: + w.substep() + sim.step = step + sim._lff_slide_wrapped = True + sim._lff_slide_watch = watch + + +class SlideSkills(Skills): + """Skills whose motion commands return only once the cube has come to rest (see the module docstring).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self._qa, self._da = envs.free_joint_addr(env, CUBE) + self.waits = [] # (control step, steps waited) for every command that had to wait + + def cube_moving(self): + qv = self.env.sim.data.qvel[self._da:self._da + 6] + return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST) + + def wait_cube_rest(self): + """Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed. + No wait if the cube is already at rest or is held (it then moves with the arm).""" + if not self.cube_moving() or self.holding(CUBE): + return 0 + p, R = self.eef_pos(), self._R() + quiet = 0 + for k in range(WAIT_MAX): + self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + quiet = 0 if self.cube_moving() else quiet + 1 + if quiet >= 2: + break + self.waits.append((self.n_steps, k + 1)) + return k + 1 + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + +INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm +LINE_W = 0.006 +# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of +# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre +# <= 2.0 cm past it, i.e. the front face up to 4 mm beyond the line, which in the 512 x 512 agentview is < 2 px of red +# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19). +TOL_PAST = 0.020 + + +def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W, + line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions).""" + o = inner_half + line_w + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba), + ((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba), + ((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(model_name, g, 0.0012, o) + + +Z_PUSH = envs.TABLE_Z + 0.02 +V_MIN, V_MAX = 0.12, 0.60 +Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table) + + +@register_task +class SlideToTarget(LFFTask): + name = "l5_slide_to_target" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Reason", "Utilize") + # no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there) + instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green " + "square marked on the table. On the side of the square nearest the robot and on its left and " + "right, no part of the cube may lie on or beyond the green border line. On the far side, away from " + "the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. " + "The cube must slide the last part of the way on its own: after it leaves the gripper it has to " + f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the " + "square.") + instruction_indirect = instruction + tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm) + tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST) + runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact + tol_across = INNER_HALF - CUBE_HALF + + def make_bddl(self): + cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1), + density=1000)) + # static fixture (no joint): a free body without collisions would fall through the table + zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False) + objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))] + fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, self.instruction, objs, fixtures=fixtures) + + def apply_instance(self, inst): + m = self.env.sim.model + zone = self.env.fixtures_dict["zone_1"] + # the target zone is a flat marker: no collisions + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("zone_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + x0, y0 = inst["cube_xy"] + envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001]) + bid = m.body_name2id(zone.root_body) + m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + envs.set_friction(self.env, "cube_1", inst["mu"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + x0, y0 = inst["cube_xy"] + self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past, + self.tol_across) + _install_watch(self.env.sim, self.watch) + self.sk = SlideSkills(self.env, recorder=recorder) + return self.sk + + @staticmethod + def max_reach(mu): + """Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m): + mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm.""" + return 0.0103 / mu ** 0.95 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: # reject instances the top speed cannot reach (keeps every instance solvable) + inst = dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))], + target_dist=float(rng.uniform(0.05, 0.12)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10))))) + if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]): + return inst + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 40) + w = self.watch + for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest + if w.at_rest(): + break + envs.settle(self.env, 5) + touching = w.flush() + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, CUBE) + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + _, _, where = w.judge(w.pos()) + inside = where == "in" + at_rest = w.at_rest() + free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0 + slid = bool(w.release is not None and not touching and free >= D_MIN) + success = bool(inside and at_rest and slid) + strikes = w.strikes + n_missed = sum(s["missed"] for s in strikes) + from ..agent.tools import WS_HI, WS_LO + reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN)) + irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach) + + parts = [] + if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN: + parts.append("The cube was not pushed.") + if c[2] < OFF_TABLE_Z: + parts.append("The cube fell off the table.") + else: + state = {"in": "in the square", "past": "it sticks out beyond the far green line", + "short": "it sticks out past the edge of the square nearest the robot"}.get(where, + "not in the square") + if along > 0: + parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).") + else: + parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square " + f"({state}).") + if abs(across) > self.tol_across: + parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} " + f"(robot's view).") + if where == "off" and c[2] > OFF_TABLE_Z: + parts.append("It is not resting on the table.") + if inside and not at_rest: + parts.append("It was still moving when the attempt ended.") + if touching: + parts.append("The gripper was still touching (or holding) the cube when the attempt ended.") + elif inside and w.release is not None and free < D_MIN: + parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide " + f"at least {100 * D_MIN:.0f} cm.") + if success: + failure = None + elif w.release is None and not inside: + failure = "not_touched" + elif not inside: + failure = "position" + elif not at_rest: + failure = "not_at_rest" + else: + failure = "slide_too_short" + out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts), + inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2), + release_xy=None if w.release is None else w.release.round(4).tolist(), + touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes), + n_missed_strikes=int(n_missed), trap_fired=n_missed > 0, + recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable, + strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure) + return out + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the + point of contact, lift (the move returns once the cube has come to rest).""" + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.set_gripper(True, steps=5) + sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), + tol=0.01, max_steps=80) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3) + + def default_params(self, inst): + return dict(speed=0.30) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search + on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt).""" + pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history) + lo = [p for p in pts if p[1] < 0] + hi = [p for p in pts if p[1] > 0] + if lo and hi: + (v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0]) + v = v0 + (v1 - v0) * (-e0) / (e1 - e0) + elif hi: # always overshooting: slow down + v = min(p[0] for p in hi) * 0.7 + else: # always short: speed up + v = max(p[0] for p in lo) * 1.35 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on speed by simulating pushes (uses the true mu).""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(9): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + e = self.outcome(inst)["along_err"] + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + hi = mid + else: + lo = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) + + # ------------------------------------------------------------ scripted within-attempt correction + AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ... + AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command + RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short + + def _strike_here(self, speed): + """Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up + point + close, down, strike (returns at rest), lift.""" + c = envs.obj_pos(self.env, CUBE) + sk = self.sk + sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0) + sk.set_gripper(True, steps=5) + sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3) + return 4 + + def _carry_back(self, inst): + """Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands: + above it + open, down + close, lift, carry, down + open, lift.""" + c = envs.obj_pos(self.env, CUBE) + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0) + sk.set_gripper(False, steps=10) + sk.move_to([c[0], c[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([c[0], c[1], Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([x0, y0, Z_GRASP + 0.10]) + return 6 + + @staticmethod + def _plan_speed(want, pts): + """Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s + prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes + (or extrapolation from the two nearest, exponent clipped to [0.5, 3]).""" + pts = sorted((v, d) for v, d in pts if d > 0.002) + if not pts: + return 0.30 + if len(pts) == 1: + v, d = pts[0] + return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX)) + lo = [p for p in pts if p[1] <= want] + hi = [p for p in pts if p[1] > want] + if lo and hi: + (v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1]) + else: + (v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2] + if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6: + return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX)) + k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0)) + return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX)) + + def _adaptive_attempt(self, inst, pts): + """One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect + perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot, + a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed + planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square + or the next correction would not fit in the agent's command / motion budget.""" + x0, y0 = inst["cube_xy"] + tx = x0 + inst["target_dist"] + sk = self.sk + n0 = sk.n_steps + n_cmd, speeds, path = 0, [], [] + while True: + c = envs.obj_pos(self.env, CUBE) + want = tx - c[0] + near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01 + local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts] + speed = self._plan_speed(want, local) + n_cmd += self._strike_here(speed) + c1 = envs.obj_pos(self.env, CUBE) + pts.append((speed, float(c1[0] - c[0]), near_start)) + speeds.append(round(speed, 4)) + err, across = float(c1[0] - tx), float(c1[1] - y0) + path.append("strike") + if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across: + break + used_s = (sk.n_steps - n0) * DT + if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005: + if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S: + break + continue + if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S: + break + n_cmd += self._carry_back(inst) + path.append("carry_back") + return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd, + sim_s=round((sk.n_steps - n0) * DT, 1)) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects + within the attempt (_adaptive_attempt) and carries what it saw into the next attempt.""" + if kind != "adaptive": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + history, pts = [], [] + for a in range(k): + self.reset_instance(inst) + params = self._adaptive_attempt(inst, pts) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_balance_board.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_balance_board.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4ceaea2c011176291dd2723cc94d344f23d991 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_balance_board.py @@ -0,0 +1,817 @@ +"""LH balance_board: put four look-alike cubes on their marks on a plank that rests loose across a narrow block (a +seesaw); loading it in the wrong order tips the plank, and every cube already on it slides down to the low end. + +Family: long-horizon self-disturbance ("state_restoration"): each stage is a plain pick-and-place of a cube onto its +mark, but a later placement can tip the plank, which sends the cubes placed before it (earlier progress) sliding off +their marks. The agent has to notice it, re-level the plank and re-place them before finishing (within an attempt), and +learn a loading order that keeps the plank level (across attempts; the final-state judge does not enforce an order). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey support (fixture: two 1.5 cm blocks with a 1 cm slot between them, together 4 cm along the plank x 10 cm x + 6 cm high, flat tops) under the middle of + * a dark wooden plank (free body, 46 cm long, pointing away from the robot, 8 cm wide, 1.5 cm thick, 0.5 kg) lying + loose on it, level, with a 2 cm lip across each end. A thin keel under the plank's middle hangs in the slot and keeps + the plank from wandering along the support (+-3 mm); nothing holds it down. It stays level while the combined centre + of mass of plank + cubes is above the support's 4 cm top; otherwise it tips until its low end touches the table + (about 17 degrees); + * four marks (5.8 cm squares, outline + light fill) on the plank, two on each side of the block: an inner one + (8.5-9.5 cm from the middle) and an outer one (15.5-16.5 cm); the colour of each mark is random; + * four 4.5 cm cubes (red, green, blue, yellow) on the table, two left and two right of the plank (random places). + They look alike except for the colour. Cube and plank surfaces are slick (friction 0.2 < tan 17 deg): on a tipped + plank every cube slides down to the lip at the low end. +Why along x with lips (measured, see the task card): with the plank left-right and open ends, the cubes slid off the +ends onto the table 0-11 cm past them, and a default top-down grasp there (fingers left-right, the Panda hand is 21 cm +wide along them) pressed the plank's end down and tipped it again -- restoring became a loop. Along x the default grasp +is across the plank, and the lips keep the cubes on the plank within reach. + +Hidden variable: the cube masses. "Hazard" instances (13 of every 20 consecutive seeds): the two cubes that belong on +the inner marks are heavy (stone, 0.19-0.24 kg), the two for the outer marks are light (48-56 g); the final layout is +balanced. A heavy cube alone on its inner mark tips the plank (1.28-1.43 x the tipping moment); a light one alone on its +outer mark does not (0.72-0.78 x); in the zig-zag order below no step exceeds 0.72-0.81 x. So the only safe loading +orders are "an outer cube, then the inner cube on the OTHER side, then the other inner cube, then the last outer cube" +(zig-zag); end-to-end, alternating outer-first (outer, outer, inner, inner) and inner-first orders all tip it. +"Benign" instances: all four cubes light (26-34 g); no order tips (worst step 0.63-0.75 x). + +Why the natural order fails: nothing in the image shows which cubes are heavy. Any natural order (nearest cube first, +the marks from one end to the other, or the cautious "alternate sides, outer marks first") tips the plank in a hazard +instance; the cubes on it slide to the low end and keep it tipped. A natural plan then keeps going and finishes with +cubes off their marks. What must be learned: check the marks after each placement / before finishing, unload the low +end and re-place (within the attempt), and use the tip to infer which cubes are heavy (an inner cube tipped it; the +layout must balance in the end, so the other inner cube is heavy too) and load in the zig-zag order (across attempts). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube on its +mark, plank level within 3 degrees and still on its support (10-11), nothing held, scene static) plus an event log of every stage predicate (achieved / +lost / restored, with step and cause) and every tip (which end went down, the cube released just before) for the server +log; F1 gives the agent only success / failure. +""" +import itertools + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z + +# ---------------------------------------------------------------- geometry / physics +# plank frame: y along the plank (+y = the end toward the robot), x across it, z up. The plank and the block are +# yawed 90 deg, so plank +y = world -x. +PL_HL, PL_HW, PL_HT = 0.23, 0.04, 0.0075 # plank half length, half width, half thickness +LIP_T, LIP_H = 0.008, 0.02 # lip across each end (inside the 46 cm), height above the plank's top +PLANK_MASS = 0.50 +PLANK_ROT_DAMP = 0.01 # N m s / rad on the plank's rotation: after its low end is unloaded it swings over to ~10 deg +# and is calm in ~1.5 s (no damping: ~13 deg and ~2.7 s); the tip itself is not slowed (measured) +PLANK_YAW = np.pi / 2 +RIDGE_HW, RIDGE_HX, RIDGE_H = 0.02, 0.05, 0.06 # support: half width along the plank (s), half depth, height +SLOT_HW = 0.005 # the support is two blocks with a 1 cm slot between them +KEEL_HW, KEEL_H = 0.002, 0.010 # keel under the plank's middle (4 mm x 8 cm x 1 cm) hanging in the slot +CUBE_E = 0.045 +MU = 0.20 # cubes and plank: the cube-plank contact slides above 11 deg; ridge (1.0), table (0.6), finger pads (2.0) win +MU_RIDGE = 1.0 +MARK_HALF, MARK_LINE = 0.029, 0.004 +WOOD = (0.42, 0.27, 0.15, 1.0) # dark walnut: contrasts with the light table, so the tilt reads in the images + +COLORS = ("red", "green", "blue", "yellow") +RGBA = dict(red=(0.85, 0.12, 0.10, 1.0), green=(0.10, 0.62, 0.20, 1.0), blue=(0.15, 0.30, 0.88, 1.0), + yellow=(0.93, 0.78, 0.10, 1.0)) +CUBES = {c: f"{c}_cube_1" for c in COLORS} +PLANK, RIDGE = "plank_1", "ridge_1" +PLANK_MODEL = "lff_lh_bb_plank" +# mark slots in plank-frame order (+y first): the robot's end outer / inner, then the far end inner / outer +SLOTS = ("near_outer", "near_inner", "far_inner", "far_outer") +END_WORD = dict(near="the end nearer the robot", far="the far end") + +# ---------------------------------------------------------------- instances / hidden variable +D_INNER = (0.085, 0.095) # |y| of the inner marks from the plank's middle +D_OUTER = (0.155, 0.165) # the lip stops a cube 19.95 cm out: a cube on a low-side outer mark ends >= 3.5 cm off it +P_HAZARD = 0.65 # fraction of hazard instances, balanced per 20 consecutive seeds (13 / 7) +R_HEAVY = (1.30, 1.40) # hazard: lone heavy cube on its inner mark, moment / tipping moment +R_LIGHT = (0.72, 0.78) # hazard: lone light cube on its outer mark +LIGHT_BENIGN = (0.026, 0.034) # benign: every cube (kg) +H_EST, L_EST = 0.21, 0.04 # nominal masses the adaptive script uses for its hypotheses (it never sees the true ones) + +# ---------------------------------------------------------------- judging +TOL = 0.020 # cube centre within 2 cm of its mark centre (per plank axis) +TOL_LOSE = 0.025 # hysteresis for the monitor +LEVEL_DEG = 3.0 +TIP_DEG = 8.0 # the monitor records a tip when |tilt| exceeds this (a real tip reaches ~17 deg) +LEVEL_DEBOUNCE = 4 # monitor evaluations (0.1 s each) before plank_level changes +FLAT_COS = np.cos(np.radians(15.0)) +SUPPORT_XY = 0.02 # plank on its support: its middle within 2 cm (horizontally) of the support's centre ... +SUPPORT_DZ = 0.02 # ... and not more than 2 cm below its starting height (a tip lowers it ~0.6 cm; off the block ~6 cm) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.17 # careful / adaptive: grasp point above the table while carrying (cube bottom 14.75 cm) +Z_CARRY_NAIVE = 0.15 # naive: just above the cubes already on the plank (their tops at 12 cm) +REL_GAP = 0.004 # release with the cube's bottom this far above the plank + + +def plank_xml(name): + """Board + end lips + keel (collision) and per colour a mark (5 visual-only geoms, moved per instance). + Long axis = body y.""" + g = [] + + def box(nm, pos, size, rgba): + g.append(f'') + g.append(f'') + + dark = (0.25, 0.16, 0.09, 1.0) + box(f"{name}_board", (0, 0, 0), (PL_HW, PL_HL, PL_HT), WOOD) + for k, s in enumerate((1, -1)): + box(f"{name}_lip{k}", (0, s * (PL_HL - LIP_T / 2), PL_HT + LIP_H / 2), (PL_HW, LIP_T / 2, LIP_H / 2), dark) + box(f"{name}_keel", (0, 0, -PL_HT - KEEL_H / 2), (PL_HW, KEEL_HW, KEEL_H / 2), dark) + for c in COLORS: + rgba = RGBA[c] + fill = tuple(0.55 + 0.45 * v for v in rgba[:3]) + (1.0,) + o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE + parts = [((0, 0, PL_HT + 0.0003), (o, o, 0.0003), fill), + ((0, i + w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((0, -i - w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((i + w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba), + ((-i - w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba)] + for k, (p, sz, col) in enumerate(parts): + g.append(f'') + return _wrap(name, "\n ".join(g), PL_HT, float(np.hypot(PL_HL, PL_HW))) + + +def ridge_xml(name): + """Split support: two 1.5 cm blocks with a 1 cm slot between them; the plank rests on both and pivots on their outer + top edges (a 4 cm flat top). The plank's keel hangs in the slot, so the plank cannot wander along its length by + more than +-3 mm (it stays engaged at the full tip angle).""" + rgba = (0.35, 0.35, 0.38, 1.0) + bh = (RIDGE_HW - SLOT_HW) / 2 + g = [] + for k, sy in enumerate((1, -1)): + p, sz = (0, sy * (SLOT_HW + bh), RIDGE_H / 2), (RIDGE_HX, bh, RIDGE_H / 2) + g.append(f'') + g.append(f'') + g = "\n ".join(g) + return f""" + + + + {g} + + + + + + +""" + + +def tip_ratio(items, plank_mass=PLANK_MASS, s=RIDGE_HW): + """Static model of a loose plank on a flat-topped block: |sum m y| / ((M_plank + sum m) s); the plank tips when + this exceeds 1 (the combined centre of mass leaves the block's top). items: [(mass, y from the middle)].""" + if not items: + return 0.0 + mom = sum(m * y for m, y in items) + return abs(mom) / ((plank_mass + sum(m for m, _ in items)) * s) + + +def _side(y): + return "near" if y > 0 else "far" + + +def _along(v): + """plank-frame y offset in robot-centric words (+y = toward the robot)""" + return f"{100 * abs(v):.1f} cm from its mark toward {'the robot' if v > 0 else 'the far end'}" + + +class BoardSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class BalanceBoard(LFFTask): + name = "lh_balance_board" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful zig-zag ~30-36 commands + re-placing four cubes (~30) + looking around + instruction = ("Put each coloured cube on the square mark of the same colour on the long plank. The plank lies loose " + "across a narrow block under its middle. At the end all four cubes must be on their marks and the " + "plank must still rest level on the block.") + instruction_indirect = ("Set the four coloured cubes onto the outlined squares of matching colour on the wooden " + "board that rests across the small grey block. When you are done, every cube must sit on " + "its square and the board must still rest level on the block.") + agent_object_names = ["red cube", "green cube", "blue cube", "yellow cube", "plank", "support block", + "red mark", "green mark", "blue mark", "yellow mark"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + pl = register_generated("LffLhBbPlank", plank_xml(PLANK_MODEL)) + rg = register_generated("LffLhBbRidge", ridge_xml("lff_lh_bb_ridge"), free=False) + objs = [(PLANK, pl, "plank_region", (0.18, -0.01, 0.20, 0.01))] + e = CUBE_E / 2 + for i, c in enumerate(COLORS): + cat = register_generated(f"LffLhBbCube{c.title()}", + box_xml(f"lff_lh_bb_cube_{c}", (e, e, e), RGBA[c], density=500.0, + friction=(MU, 0.005, 0.0001)).replace( + 'solimp="0.998 0.998 0.001" solref="0.001 1"', "")) + objs.append((CUBES[c], cat, f"{c}_cube_region", (-0.32, -0.33 + 0.2 * i, -0.30, -0.31 + 0.2 * i))) + fx = [(RIDGE, rg, "ridge_region", (-0.12, 0.30, -0.10, 0.32))] + return write_bddl(self.name, "put each cube on its mark on the plank and keep the plank level", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.ridge_bid = m.body_name2id(self.env.fixtures_dict[RIDGE].root_body) + self.plank_bid = envs.body_id(self.env, PLANK) + pre = f"{PLANK}_{PLANK_MODEL}" + self.mark_gids = {c: [m.geom_name2id(f"{pre}_mk_{c}_{k}") for k in range(5)] for c in COLORS} + self.mark_pos0 = {c: [m.geom_pos[g].copy() for g in self.mark_gids[c]] for c in COLORS} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, CUBES[c])) for c in COLORS} + self.plank_gids = set(envs.obj_geom_ids(self.env, PLANK)) + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + self.obs = [] # adaptive script: (configuration, tipped) observations, kept across the attempts of one run + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + x0, y0 = float(rng.uniform(-0.18, -0.14)), float(rng.uniform(-0.03, 0.03)) + perm = [str(c) for c in rng.permutation(COLORS)] # colour of the mark in SLOTS order + slot_of = {c: s for c, s in zip(perm, SLOTS)} + dist = dict(near_outer=float(rng.uniform(*D_OUTER)), near_inner=float(rng.uniform(*D_INNER)), + far_inner=-float(rng.uniform(*D_INNER)), far_outer=-float(rng.uniform(*D_OUTER))) + marks = {c: dist[slot_of[c]] for c in COLORS} # plank-frame y of each mark (+ = toward the robot) + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced like l7_key_turn / lh_lid_box + r_h, r_l = float(rng.uniform(*R_HEAVY)), float(rng.uniform(*R_LIGHT)) + light = {c: float(rng.uniform(*LIGHT_BENIGN)) for c in COLORS} + s, pm = RIDGE_HW, PLANK_MASS + if hazard: + # equal moments on both sides -> the finished layout is exactly balanced + dn, do = dist["near_inner"], dist["near_outer"] + y_h = r_h * pm * s / (dn - r_h * s) * dn # heavy on the near inner mark: moment r_h x tipping moment + x_l = r_l * pm * s / (do - r_l * s) * do + mass = {c: (y_h if "inner" in slot_of[c] else x_l) / abs(dist[slot_of[c]]) for c in COLORS} + else: + mass = light + # start: two cubes left and two right of the plank, 17-19 cm from its axis, at two depths (random places) + spots = [(dx, sy) for sy in (1.0, -1.0) for dx in (-0.08, 0.08)] + order = rng.permutation(4) + start = {c: [x0 + spots[j][0] + float(rng.uniform(-0.01, 0.01)), + y0 + spots[j][1] * float(rng.uniform(0.17, 0.19))] for c, j in zip(COLORS, order)} + start_yaw = {c: float(rng.uniform(-0.3, 0.3)) for c in COLORS} + heavy = sorted(c for c in COLORS if mass[c] > 0.1) + return dict(seed=int(seed), plank_xy=[x0, y0], marks=marks, slot_of=slot_of, hazard=hazard, mass=mass, + heavy=heavy, r_heavy=r_h if hazard else None, r_light=r_l if hazard else None, start=start, + start_yaw=start_yaw) + + def apply_instance(self, inst): + self.inst = inst + env = self.env + m = env.sim.model + x0, y0 = inst["plank_xy"] + q = [np.cos(PLANK_YAW / 2), 0.0, 0.0, np.sin(PLANK_YAW / 2)] + m.body_pos[self.ridge_bid] = [x0, y0, TZ] + m.body_quat[self.ridge_bid] = q + envs.scale_mass(env, PLANK, PLANK_MASS) + _, da = envs.free_joint_addr(env, PLANK) + m.dof_damping[da + 3:da + 6] = PLANK_ROT_DAMP + for c in COLORS: + for g, p0 in zip(self.mark_gids[c], self.mark_pos0[c]): + m.geom_pos[g] = p0 + np.array([0.0, inst["marks"][c], 0.0]) + envs.scale_mass(env, CUBES[c], inst["mass"][c]) + envs.set_obj_pose(env, PLANK, [x0, y0, TZ + RIDGE_H + PL_HT + 0.0005], quat_wxyz=np.array(q)) + for c in COLORS: + envs.place_upright(env, CUBES[c], inst["start"][c], yaw=inst["start_yaw"][c]) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.plank_z0 = float(self.plank_pos()[2]) + self.sk = BoardSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def plank_R(self): + return self.env.sim.data.body_xmat[self.plank_bid].reshape(3, 3).copy() + + def plank_pos(self): + return self.env.sim.data.body_xpos[self.plank_bid].copy() + + def tilt_deg(self): + """+ = the plank's end toward the robot is up""" + return float(np.degrees(np.arcsin(np.clip(self.plank_R()[2, 1], -1.0, 1.0)))) + + def is_level(self, deg=LEVEL_DEG): + return abs(self.tilt_deg()) <= deg + + def on_support(self): + """the plank still rests on the support block (10-11: Sonnet lh2 s3001 pushed it off onto the table, where it + lies level, and loaded the cubes there; 'level' alone accepted that)""" + p, r = self.plank_pos(), self.env.sim.data.body_xpos[self.ridge_bid] + return bool(np.linalg.norm(p[:2] - r[:2]) <= SUPPORT_XY and p[2] >= self.plank_z0 - SUPPORT_DZ) + + def in_plank(self, p): + """world point -> plank frame (x across, y along from the middle, z above the plank's mid-plane)""" + return self.plank_R().T @ (np.asarray(p, float) - self.plank_pos()) + + def mark_world(self, c): + return self.plank_pos() + self.plank_R() @ np.array([0.0, self.inst["marks"][c], PL_HT]) + + def cube_pos(self, c): + return envs.obj_pos(self.env, CUBES[c]) + + def held(self, c): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, + object_geoms=self.env.objects_dict[CUBES[c]])) + + def on_plank(self, c): + """resting on the plank's top (plank frame), anywhere along it""" + q = self.in_plank(self.cube_pos(c)) + return bool(abs(q[0]) <= PL_HW + 0.01 and abs(q[1]) <= PL_HL and abs(q[2] - PL_HT - CUBE_E / 2) <= 0.012) + + def mark_offset(self, c): + q = self.in_plank(self.cube_pos(c)) + return np.array([q[0], q[1] - self.inst["marks"][c]]) + + def _flat(self, c): + Rc = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + return bool(np.max(np.abs(self.plank_R()[:, 2] @ Rc)) >= FLAT_COS) + + def on_mark(self, c, tol=TOL): + if not self.on_plank(c): + return False + o = self.mark_offset(c) + return bool(np.max(np.abs(o)) <= tol and self._flat(c) and not self.held(c)) + + def stage_values(self): + v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS} + v["plank_level"] = self.is_level() + v["plank_on_support"] = self.on_support() + return v + + # ------------------------------------------------------------ per-step monitor (server log only) + def _init_monitor(self): + self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"plank_level": True, "plank_on_support": True}, ever=set(), + lost=set(), events=[], step=0, last_touch={c: None for c in COLORS}, + held_prev={c: False for c in COLORS}, last_release=None, tipping=False, tips=[], + level_cnt=0, calm=0, tilt_max=0.0, win_max=0.0) + + def _robot_touches(self): + """cubes touched by the robot or by a cube the robot is carrying, in this control step""" + d = self.env.sim.data + out = set() + carried = [c for c in COLORS if self.mon["held_prev"][c]] + hit = {c: self.robot_gids.union(*[self.cube_gids[h] for h in carried if h != c]) for c in COLORS} + for i in range(d.ncon): + con = d.contact[i] + for c in COLORS: + g = self.cube_gids[c] + if (con.geom1 in g and con.geom2 in hit[c]) or (con.geom2 in g and con.geom1 in hit[c]): + out.add(c) + return out + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + step = self.sk.n_steps + for c in self._robot_touches(): + mon["last_touch"][c] = step + tilt = self.tilt_deg() + mon["tilt_max"] = max(mon["tilt_max"], abs(tilt)) + mon["win_max"] = max(mon["win_max"], abs(tilt)) + if not mon["tipping"] and abs(tilt) > TIP_DEG: + # one tip episode = from |tilt| > 8 deg until the plank has stayed level for 1 s (the swing back and any + # rocking belong to the same episode) + mon["tipping"] = True + mon["calm"] = 0 + rel = mon["last_release"] + tip = dict(step=step, down="near" if tilt < 0 else "far", + after_release=(rel[0] if rel is not None and step - rel[1] <= 60 else None), + on_plank=[c for c in COLORS if self.on_plank(c)], + on_mark=[c for c in COLORS if mon["state"][f"{c}_on_mark"]]) + mon["tips"].append(tip) + mon["events"].append(dict(step=step, pred="plank", ev="tipped", down=tip["down"], + after_release=tip["after_release"], on_mark=tip["on_mark"])) + elif mon["tipping"]: + mon["calm"] = mon["calm"] + 1 if abs(tilt) < LEVEL_DEG else 0 + if mon["calm"] >= 20: + mon["tipping"] = False + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + for c in COLORS: + h = self.held(c) + if mon["held_prev"][c] and not h: + mon["last_release"] = (c, step) + mon["held_prev"][c] = h + key = f"{c}_on_mark" + was = mon["state"][key] + now = self.on_mark(c, TOL if not was else TOL_LOSE) + if now != was: + self._event(key, now, step, c) + lv = self.is_level() + if lv != mon["state"]["plank_level"]: + mon["level_cnt"] += 1 + if mon["level_cnt"] >= LEVEL_DEBOUNCE: + mon["level_cnt"] = 0 + self._event("plank_level", lv, step, None) + else: + mon["level_cnt"] = 0 + sup = self.on_support() + if sup != mon["state"]["plank_on_support"]: + self._event("plank_on_support", sup, step, None) + + def _event(self, key, now, step, color): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + cause = "other" + recent_tip = bool(mon["tips"]) and (mon["tipping"] or step - mon["tips"][-1]["step"] <= 60) + if color is None: + cause = "tip" if recent_tip else "other" + elif self.held(color): + cause = "picked_up" + elif recent_tip: + cause = "tip" + elif mon["last_touch"][color] is not None and step - mon["last_touch"][color] <= 60: + cause = "robot" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, tilt=round(self.tilt_deg(), 1))) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in [CUBES[c] for c in COLORS] + [PLANK]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return False + return True + + def _where(self, c): + """robot-centric description of where a cube that is not on its mark is""" + if self.held(c): + return "is still held by the gripper" + if self.on_plank(c): + o = self.mark_offset(c) + return f"lies on the plank, {_along(o[1])}" + p = self.cube_pos(c) + if np.linalg.norm(p[:2] - np.asarray(self.inst["start"][c])) < 0.02: + return "is still where it started on the table" + q = self.in_plank(p) + if abs(q[1]) > PL_HL: + return f"lies on the table beyond {END_WORD[_side(q[1])]} of the plank" + return "lies on the table beside the plank" + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [c for c in COLORS if self.held(c)] + success = bool(all(vals.values()) and static and not held) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + parts = [] + off = [c for c in COLORS if not vals[f"{c}_on_mark"]] + if success: + failure = None + parts.append("All four cubes are on their marks and the plank is level.") + else: + lost_final = [c for c in off if f"{c}_on_mark" in mon["ever"]] + failure = ("held" if held else "plank_off_support" if not vals["plank_on_support"] else + "regressed" if lost_final else "incomplete" if off else + "not_level" if not vals["plank_level"] else "not_static") + for c in off: + txt = f"The {c} cube is not on its mark: it {self._where(c)}" + if f"{c}_on_mark" in mon["ever"]: + why = [e for e in regress if e["pred"] == f"{c}_on_mark"] + cause = why[-1].get("cause") if why else None + txt += {"tip": " (it had been on its mark; it slid off when the plank tipped).", + "robot": " (it had been on its mark; the robot knocked it off).", + "picked_up": " (it had been on its mark; it was picked up again)."}.get( + cause, " (it had been on its mark earlier).") + else: + txt += " (it was never on its mark)." + parts.append(txt) + if not vals["plank_on_support"]: + parts.append("The plank no longer rests on the support block: it was pushed or knocked off it.") + if not vals["plank_level"]: + t = self.tilt_deg() + parts.append(f"The plank is not level: it is tilted {abs(t):.0f} degrees, " + f"{END_WORD['near' if t < 0 else 'far']} down.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["tips"]: + descr = [] + for tp in mon["tips"]: + d = f"{END_WORD[tp['down']]} down" + if tp["after_release"]: + d += f" right after the {tp['after_release']} cube was set down" + descr.append(d) + parts.append(f"During the attempt the plank tipped {len(mon['tips'])} time(s): " + "; ".join(descr) + ".") + return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + n_tips=len(mon["tips"]), tips=mon["tips"], tilt_max=round(mon["tilt_max"], 1), + tilt_final=round(self.tilt_deg(), 1), hazard=bool(inst["hazard"]), + mark_offsets_cm={c: (100 * self.mark_offset(c)).round(1).tolist() for c in COLORS}, + on_plank={c: self.on_plank(c) for c in COLORS}, detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, c): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _y_on_plank(self): + """cubes resting on the plank now -> their position along it""" + return {c: float(self.in_plank(self.cube_pos(c))[1]) for c in COLORS if self.on_plank(c) and not self.held(c)} + + def plank_calm(self): + _, da = envs.free_joint_addr(self.env, PLANK) + return abs(self.tilt_deg()) < 1.0 and float(np.linalg.norm(self.env.sim.data.qvel[da + 3:da + 6])) < 0.05 + + def wait_calm(self, max_steps=60): + """hold the arm still until the plank has stopped swinging (a careful agent looks before it acts)""" + n = 0 + for _ in range(max_steps): + if self.plank_calm(): + n += 1 + if n >= 5: + return True + else: + n = 0 + self.sk.hold(1) + return False + + def pick(self, c, z_carry): + sk = self.sk + p = self.cube_pos(c) + yaw = self._grasp_yaw(c) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], max(TZ + z_carry, p[2] + 0.06)], yaw=yaw) + sk.move_to([p[0], p[1], p[2]], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], TZ + z_carry], speed=0.3) + if not self.held(c): + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], TZ + z_carry]) + return False + return True + + def put(self, c, z_carry=Z_CARRY, noise=None, record=False, careful=False): + """Pick cube c wherever it is and put it on its mark: carry it over the mark, lower it until its bottom is + REL_GAP above the plank, release, lift. Returns whether the plank tipped (|tilt| > TIP_DEG) during the + placement, or None if the cube could not be picked. record=True appends the observation (cubes on the plank + right before the release + this one on its mark, tipped?) for the adaptive script.""" + for _ in range(2): + if self.pick(c, z_carry): + break + else: + return None + sk = self.sk + d = self.mark_world(c) + if noise is not None: + d = d + np.array([noise[0], noise[1], 0.0]) + sk.move_to([d[0], d[1], TZ + z_carry], yaw=0.0) + if careful: + self.wait_calm() + d = self.mark_world(c) + (np.array([noise[0], noise[1], 0.0]) if noise is not None else 0.0) + sk.move_to([d[0], d[1], d[2] + CUBE_E / 2 + REL_GAP], tol=0.003) + was_level = self.plank_calm() + conf = self._y_on_plank() + conf[c] = float(self.inst["marks"][c]) + self.mon["win_max"] = abs(self.tilt_deg()) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], TZ + z_carry]) + sk.hold(12) + tipped = self.mon["win_max"] > TIP_DEG + if tipped: + envs.settle(self.env, 30) # let the cubes slide down + if record and was_level: + self.obs.append(dict(conf=conf, tipped=bool(tipped), after=c)) + return tipped + + def park(self, c): + """take cube c off the plank and set it on a free spot of the table beside the plank""" + x0, y0 = self.inst["plank_xy"] + others = [self.cube_pos(o)[:2] for o in COLORS if o != c] + cands = [np.array([x0 + dx, y0 + sy * dy]) for sy in (1, -1) for dy in (0.18, 0.25) + for dx in (-0.12, -0.04, 0.04, 0.12)] + best = max(cands, key=lambda q: min(np.linalg.norm(q - o) for o in others)) + if not self.pick(c, Z_CARRY): + return False + sk = self.sk + sk.move_to([best[0], best[1], TZ + Z_CARRY], yaw=0.0) + sk.move_to([best[0], best[1], TZ + CUBE_E / 2 + 0.004], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([best[0], best[1], TZ + Z_CARRY]) + return True + + # ---- planning with the static model + def plan(self, todo, hyps): + """Best order to (re)place the cubes in `todo`, given the cubes now on the plank, minimising the worst tip ratio + over the mass hypotheses `hyps` (list of {colour: kg}). A cube that is on the plank off its mark is lifted + (its moment removed) and then set on its mark. Returns (order, worst ratio).""" + cur0 = self._y_on_plank() + best, best_w = list(todo), np.inf + for order in itertools.permutations(todo): + w = 0.0 + for mass in hyps: + cur = dict(cur0) + for c in order: + if c in cur: + del cur[c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + cur[c] = self.inst["marks"][c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + if w < best_w - 1e-9: + best, best_w = list(order), w + return best, best_w + + def hypotheses(self, use_obs=True): + """Heavy / light assignments (nominal masses) that (1) leave the finished layout balanced, (2) admit a loading + order that never tips the plank (the task is solvable) and (3) agree with every observed placement (tipped or + not, with a +-10 % band in which either outcome counts as consistent). Falls back to (1)+(2) if no assignment + agrees with all observations.""" + marks = self.inst["marks"] + prior = [] + for k in range(5): + for heavy in itertools.combinations(COLORS, k): + mass = {c: (H_EST if c in heavy else L_EST) for c in COLORS} + if tip_ratio([(mass[c], marks[c]) for c in COLORS]) > 0.6: + continue + for order in itertools.permutations(COLORS): + cur, w = [], 0.0 + for c in order: + cur.append((mass[c], marks[c])) + w = max(w, tip_ratio(cur)) + if w <= 0.9: + prior.append(mass) + break + if not use_obs: + return prior + post = [] + for mass in prior: + if all(not ((ob["tipped"] and r < 0.9) or (not ob["tipped"] and r > 1.1)) + for ob in self.obs for r in [tip_ratio([(mass[o], y) for o, y in ob["conf"].items()])]): + post.append(mass) + return post or prior + + def unload_until_level(self, max_moves=4): + """while the plank is tipped: take the cube farthest out on its low side off the plank""" + for _ in range(max_moves): + envs.settle(self.env, 20) + self.wait_calm() + if self.is_level(): + return True + t = self.tilt_deg() + yo = self._y_on_plank() + low = [c for c, y in yo.items() if (y > 0) == (t < 0)] + if not low: + return self.is_level() + self.park(min(low, key=lambda o: abs(yo[o]))) # the top of the pile first: the hand clears the others + envs.settle(self.env, 20) + self.wait_calm() + return self.is_level() + + def restore(self, hyps_fn, rounds=3, record=False): + """Check every stage; if something is wrong: unload the low end if the plank is tipped, then (re)place every + cube that is not on its mark in the order the static model rates safest under the current mass hypotheses; + start over after a tip. Up to `rounds` passes.""" + for _ in range(rounds): + envs.settle(self.env, 20) + if all(self.stage_values().values()): + return True + self.unload_until_level() + todo = [c for c in COLORS if not self.on_mark(c)] + if not todo: + continue + hyps = hyps_fn() + order, worst = self.plan(todo, hyps) + if worst > 0.9: # cubes left on the plank make every order risky: clear it and start from empty + for c in [c for c in COLORS if self.on_plank(c)]: + self.park(c) + order, worst = self.plan(list(COLORS), hyps) + for c in order: + if self.on_mark(c): + continue + if self.put(c, Z_CARRY, record=record, careful=True): + break # tipped: look again + envs.settle(self.env, 20) + return all(self.stage_values().values()) + + def naive_order(self, noise_sd=0.0, rng=None): + """nearest cube first, starting from the gripper's position and then from each mark just loaded""" + p = self.sk.eef_pos()[:2] + left, order = list(COLORS), [] + while left: + dist = {c: np.linalg.norm(self.cube_pos(c)[:2] - p) + (rng.normal(0, noise_sd) if rng is not None else 0.0) + for c in left} + c = min(left, key=dist.get) + order.append(c) + left.remove(c) + p = self.mark_world(c)[:2] + return order + + def slot_order(self, kind): + so = {s: c for c, s in self.inst["slot_of"].items()} + seq = dict(end2end=SLOTS, alt_outer=("near_outer", "far_outer", "near_inner", "far_inner"), + alt_inner=("near_inner", "far_inner", "near_outer", "far_outer"))[kind] + return [so[s] for s in seq] + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("seed", 0)) + mode = params["mode"] + if mode == "plan": + hyps = [dict(inst["mass"])] if params.get("true_masses") else self.hypotheses() + order, _ = self.plan(list(COLORS), hyps) + elif mode in ("end2end", "alt_outer", "alt_inner"): + order = self.slot_order(mode) + else: # nearest first (naive / blind) + order = self.naive_order(params.get("order_noise", 0.0), rng) + noise = params.get("noise", 0.0) + z_carry = Z_CARRY if params.get("careful") else Z_CARRY_NAIVE + for c in order: + nz = rng.uniform(-noise, noise, 2) if noise else None + tipped = self.put(c, z_carry, noise=nz, record=params.get("record", False), careful=params.get("careful", False)) + if tipped and params.get("check_each"): + break # look at what happened, then restore below + if params.get("check"): + hyps_fn = (lambda: [dict(inst["mass"])]) if params.get("true_masses") else self.hypotheses + self.restore(hyps_fn, record=params.get("record", False)) + self.sk.hold(10) + return order + + def default_params(self, inst): + return dict(mode="nearest", check=False) + + def oracle_params(self, inst): + return dict(mode="plan", true_masses=True, careful=True, check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load in the order the observations of earlier attempts make safest, check after every + placement and restore at the end""" + return dict(mode="plan", careful=True, check=True, check_each=True, record=True) + + def blind_params(self, inst, attempt, rng): + """nearest-first again with small random variation (order noise, 4 mm placement noise), no history, no check""" + return dict(mode="nearest", check=False, order_noise=0.03, noise=0.004, seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.obs = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": # attempt 1: natural order, but look after every placement and restore + params = (dict(mode="nearest", check=True, check_each=True, record=True) if a == 0 else + self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind in ("end2end", "alt_outer", "alt_inner"): # extra controls: other natural orders, no check + params = dict(mode=kind, check=False) + elif kind == "oracle_noise": # extra control: the oracle with +-5 mm (uniform) placement noise + params = dict(self.oracle_params(inst), noise=0.005, seed=int(rng.integers(1 << 30))) + elif kind == "switch": # extra control: no in-attempt repair, learn the order across attempts only + params = (dict(mode="nearest", check=False, record=True) if a == 0 else + dict(mode="plan", careful=True, check=False, record=True)) + else: + raise ValueError(kind) + order = self.execute(inst, params) + out = self.outcome(inst) + out["order"] = order + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "oracle_noise", "naive", "end2end", "alt_outer", "alt_inner"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_bridge.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..b10b75576304ed46284ba5002c7857fc458d3669 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_bridge.py @@ -0,0 +1,1101 @@ +"""LH lh_bridge (v2, 2026-10-09): build a small bridge (two pillars, a plank, then the red cube "car" on top); the car is +parked right behind the bridge site, and once the plank is down the agent's natural reach for it knocks the bridge down, +which must be rebuilt before the task can be finished. + +Category: state_restoration, long-horizon self-inflicted regression. The user's example verbatim: "build a bridge; +while working you knock over a foundation you already built and must rebuild it before continuing". + +v1 -> v2 (after the Sonnet 5.5 pilot lh1: only 1 of 3 instances was ever disturbed; Sonnet carried 12-20 cm high and +lifted over built pillars, so the v1 mechanism -- sweeping a pillar with a block carried low -- rarely happened; the one +disturbance was the hand landing on the plank while going for the red cube): the car now starts in the gap between the +two squares, 5.5-9 cm behind the bridge line (right behind where the plank will lie); a spare fifth block; the bridge +4-7 cm further from the robot and the plank nearer, so that knocked parts stay within reach; softer contacts for the +bridge parts (the stiff default made collapsing blocks fly 30-90 cm); the naive reference imitates Sonnet's measured +motion style instead of the v1 low-transit script (kept as naive_v1). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): two coloured square +marks (blue and green, 6 x 6 cm, visual only) 16 cm apart along y, 48-51 cm in front of the robot base; the red cube +(4 cm) in the gap between them, 5.5-9 cm behind the line through the squares (+-3 cm sideways, yaw +-20 deg); five +wooden cubes (edge 5.0-5.6 cm, friction 0.3-0.6, five distinct categories) in a row 9-11 cm behind the squares, two on +one side of the car and three on the other; the plank (24 x 5 x 1.2 cm) lying left-right 19-21 cm behind the squares. + +Stages (order-free predicates, evaluated after every control step by a monitor; events are debounced over 6 steps): + S1 two blocks stacked on the blue square (lower block resting on the table within 2.5 cm of the square's centre, + upper block resting on it within 2.5 cm; any face down, cubes have no "right way up") + S2 the same on the green square + S3 the plank rests on the top blocks of both pillars: in contact with both, not with the table, tilt <= 10 deg + S4 the red cube rests on the plank within 6 cm of the plank's centre along its length +Success = all four hold at the end simultaneously, the scene is static (< 4 mm motion in 1 s) and the robot neither +holds nor touches any object. The monitor's achieved / lost / restored events go to the server log only (F1). + +Why the agent breaks the bridge (measured, see task_cards/lh_bridge.md): with the plank down, the car sits 3-6.5 cm +behind the plank's back edge, between the pillars. The Panda hand is 21 cm long along the finger axis and its underside +is only 2.4 cm above the grasp point; the fingertips hang 1.3 cm below it. Each of the three pilot runs went for the car +differently; scripted here on seeds 1000-1019: hovering ~13 cm above it while turning the wrist from the plank's 90 deg +to the car's yaw, then straight down (5/20 knock the bridge), keeping the 90 deg wrist and going straight down (the hand +lands across the plank: 20/20), or one diagonal move from above the bridge straight down to the grasp (the hand drives +through the bridge: 20/20). The plank and one or both pillar tops fall; in 22 of 24 collapses (seeds 3000-3029) every +part needed stays within reach (a block out of reach is covered by the spare; the plank was thrown out of reach twice). +What prevents it (learnable from one failure, and what Sonnet wrote after its pilot failure): move the car away before +laying the plank. + +Hidden variables: none that matter. Block size and friction are instance variety; the car's distance (5.5-9 cm) and yaw +decide only the "hover" style's outcome. + +Scripted references (perception = simulator state): + naive Sonnet-like (measured on the pilot): instruction order; per pillar the free block nearest its square first; + hover ~12 cm above an object turned to its yaw, vertical descent, grasp 1.1 cm below the top; carry to a bare + square in one diagonal move to 12.5 cm above it, onto a block lift first; lift over a built pillar when the + carried block's straight path would hit it; release, lift to 15 cm; plank lifted to 7 cm, carried at 16 cm, + lift to 21 cm; the car approach style is the pilot's mixture (seed % 3: hover / keep / direct); no final check + naive_v1 the v1 naive (vertical / horizontal legs at 8 cm, carries at max(8 cm, release + 4 cm)), for comparison + oracle careful: first moves the car out of the zone behind the bridge; all transits at 25 cm, vertical approaches + at 0.1 m/s, grasps 1.6 cm below a cube's top, gripper yaw chosen for hand / finger clearance; checks every + stage at the end and repairs what is broken (same repair as adaptive) + adaptive attempt 1 = naive, then checks every stage before finishing and restores what was lost (tips a plank that + stands on edge, puts the plank and car aside, re-stacks the pillars from usable blocks, then plank and car + again); from attempt 2 the careful behaviour + blind naive with random variation (hover / carry / lift heights, diagonal or lift-first carries, car style, + block allocation, 4 mm placement noise), no history + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import os + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BLOCKS = ["block_a_1", "block_b_1", "block_c_1", "block_d_1", "block_e_1"] # four are needed, one is a spare +PLANK, CAR = "plank_1", "car_1" +SQUARES = ["square_blue_1", "square_green_1"] # S1 = blue, S2 = green +ITEMS = BLOCKS + [PLANK, CAR] +BLOCK_RGBA = [(0.80, 0.66, 0.46, 1.0), (0.70, 0.55, 0.37, 1.0), (0.84, 0.72, 0.56, 1.0), (0.64, 0.50, 0.36, 1.0), + (0.76, 0.60, 0.42, 1.0)] # wood +PLANK_HALF = (0.12, 0.025, 0.006) # 24 x 5 x 1.2 cm, long axis = body x +CAR_HALF = 0.02 +BLOCK_NOM = 0.026 # nominal half edge in the MJCF (resized per instance) +SQ_HALF = 0.03 +SQ_RGBA = {"square_blue_1": (0.12, 0.30, 0.90, 1.0), "square_green_1": (0.10, 0.70, 0.25, 1.0)} +SQ_NAME = {"square_blue_1": "blue", "square_green_1": "green"} +SPAN = 0.16 # square centre distance (along y) + +TZ = envs.TABLE_Z +BASE_X = -0.66 +HAND_HALF_LONG = 0.106 # Panda hand collision AABB about the grasp site: +-10.6 cm along the finger axis +HAND_HALF_SHORT = 0.036 # +-3.6 cm across it +HAND_BOTTOM = 0.024 # its underside is 2.4 cm above the grasp site (measured) + +SQ_TOL = 0.025 # lower block centre within 2.5 cm of the square centre +STACK_TOL = 0.025 # upper block centre within 2.5 cm of the lower one +FLAT_COS = np.cos(np.radians(12)) +PLANK_TILT = np.radians(10) +CAR_MID = 0.06 +DEBOUNCE = 6 # control steps a predicate must keep its new value before an event is recorded + +# v2 layout (2026-10-09): the red cube ("car") is parked in the gap between the two squares, just behind the bridge +# line, so that once the plank is down a natural top-down grasp of it lands the hand on the plank / pillar tops; the +# four wooden blocks lie in a row behind the bridge, two on each side of the car; the plank lies further back. +LAYOUT = dict(bridge_x=(-0.18, -0.15), row_dx=(0.09, 0.11), y_half=0.30, gap=0.095, car_dx=(0.055, 0.09), car_dy=0.03, + car_clear=0.08, car_yaw=0.35, plank_dx=(0.19, 0.21), block_edge=(0.050, 0.056)) +KEEP_OUT = dict(dx=0.13, dy=0.20) # careful: no parking / no material left within this zone behind the bridge line +# Sonnet-like naive (measured on the lh1 pilot, see task_cards/lh_bridge.md): heights of the grasp site above the table +SN = dict(hover=0.12, carry=0.125, lift=0.15, cross_margin=0.04, plank_lift=0.07, plank_carry=0.16, car_lift=0.17, + end_lift=0.25, top_below=0.011, diag=True, car_style=None, car_hover=0.134, plank_end_lift=0.21, + alloc="greedy") +# how the gripper went for the red cube once the plank was down -- each of the three pilot runs did it differently: +# hover (seed 3002) move to ~13.4 cm above it while turning to its yaw, then straight down +# keep (seed 3000) the same, but still turned 90 deg from laying the plank +# direct (seed 3001) one move from ~21 cm above the bridge straight (diagonally) down to the grasp +# the naive script uses style CAR_STYLES[seed % 3] (car_style=None), i.e. the pilot's mixture +CAR_STYLES = ("hover", "keep", "direct") +Z_NAIVE = 0.08 # naive_v1 transit height of the grasp site above the table +Z_SAFE = 0.25 # careful transit height +NAIVE_LIFT = 0.05 # naive: lift this far straight up after letting go, then head for the next waypoint +NAIVE_STYLE = "legs" # legs: vertical / horizontal legs at the transit height; diag: straight lines between waypoints + + +def _wrap_q(a): + """wrap to [-pi/4, pi/4) (cubes are symmetric under 90 deg)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (plank / gripper symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +# Contact softness of the bridge parts. LFF-Bench's generated boxes use a very stiff contact (objects._SOLID); when a +# fast hand drives into a stacked bridge, the stiff contacts resolve the overlap with large impulses and blocks fly +# 30-90 cm (measured: up to 1.7 m/s while the hand moved at 0.5-0.8 m/s), often out of reach or off the table. A +# softer contact (MuJoCo-like defaults) keeps collapses local. None = use the stiff default. +CONTACT = os.environ.get("LFF_LHB_CONTACT", 'solimp="0.95 0.99 0.001" solref="0.01 1"') + + +def part_xml(model_name, half, rgba, density): + """box like objects.box_xml, with the task's contact softness""" + if not CONTACT or CONTACT == "stiff": + return box_xml(model_name, half, rgba, density=density) + g = (f' \n' + f' ') + return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def mark_xml(name, rgba): + """flat coloured square, visual only (does not touch the physics)""" + g = (f' ') + return _wrap(name, g, 0.0006, SQ_HALF * 1.42) + + +class BridgeSkills(Skills): + """Skills that feed the task's per-step stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Bridge(LFFTask): + name = "lh_bridge" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 130 + instruction = ("Build a small bridge. First stack two of the wooden blocks on the blue square, then two on the green " + "square, to make two pillars; then lay the long plank across the tops of both pillars; finally put " + "the red cube on the middle of the plank. The finished bridge must stand on its own, with the " + "gripper open and not touching anything.") + instruction_indirect = ("Build a small bridge. First make a tower of two of the wooden cubes on the blue mark on the " + "table, then another tower of two on the green mark; then lay the long flat board across the " + "tops of the two towers; finally set the small red cube on the middle of the board. At the " + "end everything must stand on its own, with the gripper open and not touching anything.") + agent_object_names = ["wooden blocks (5)", "plank", "red cube", "blue square", "green square"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, b in enumerate(BLOCKS): + cat = register_generated(f"LffLhbBlock{'ABCDE'[i]}", part_xml(f"lff_lhb_block_{'abcde'[i]}", (BLOCK_NOM,) * 3, + BLOCK_RGBA[i], 500.0)) + reg = (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31) if i < 4 else (0.10, -0.25, 0.11, -0.24) + objs.append((b, cat, f"blk{i}_region", reg)) + pl = register_generated("LffLhbPlank", part_xml("lff_lhb_plank", PLANK_HALF, (0.50, 0.33, 0.18, 1.0), + density=600.0)) + objs.append((PLANK, pl, "plank_region", (0.05, -0.01, 0.06, 0.01))) + car = register_generated("LffLhbCar", part_xml("lff_lhb_car", (CAR_HALF,) * 3, (0.85, 0.10, 0.08, 1.0), + density=400.0)) + objs.append((CAR, car, "car_region", (-0.30, -0.31, -0.29, -0.30))) + fx = [] + for i, s in enumerate(SQUARES): + cat = register_generated(f"LffLhbSquare{'BG'[i]}", mark_xml(f"lff_lhb_square_{'bg'[i]}", SQ_RGBA[s]), + free=False) + fx.append((s, cat, f"sq{i}_region", (-0.10 + 0.10 * i, -0.31, -0.09 + 0.10 * i, -0.30))) + return write_bddl(self.name, "Build a small bridge from the blocks the plank and the red cube", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.sq_bid = {s: m.body_name2id(self.env.fixtures_dict[s].root_body) for s in SQUARES} + self.geoms = {o: envs.obj_geom_ids(self.env, o) for o in ITEMS} + self.vis_geoms = {} + for o in BLOCKS: + root = envs.body_id(self.env, o) + bodies = {b for b in range(m.nbody) if b == root or m.body_parentid[b] == root} + self.vis_geoms[o] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in bodies and m.geom_contype[g] == 0 + and m.geom_conaffinity[g] == 0 and m.geom_type[g] == 6] + self.block_body = getattr(self, "block_body", {}) + self.block_body[o] = int(m.geom_bodyid[self.geoms[o][0]]) + self.table_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("main_table") + and m.geom_contype[g] != 0] + self.robot_geoms = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + self.sk = None + self.naive_lift = NAIVE_LIFT + self.naive_style = NAIVE_STYLE + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + xb = float(rng.uniform(*LAYOUT["bridge_x"])) + yc = float(rng.uniform(-0.03, 0.03)) + blue_left = bool(rng.random() < 0.5) + sq = {"square_blue_1": [xb, yc + (SPAN / 2 if blue_left else -SPAN / 2)], + "square_green_1": [xb, yc - (SPAN / 2 if blue_left else -SPAN / 2)]} + L = LAYOUT + # the car: in the gap between the two squares, just behind the bridge line + pos = {CAR: [xb + float(rng.uniform(*L["car_dx"])), yc + float(rng.uniform(-L["car_dy"], L["car_dy"]))]} + # five blocks in a row behind the bridge line, two on one side of the car and three on the other + row_x = xb + float(rng.uniform(*L["row_dx"])) + ys = [] + three = 1.0 if rng.random() < 0.5 else -1.0 + for side in (-1.0, 1.0): + n = 3 if side == three else 2 + lo, hi = sorted((pos[CAR][1] + side * L["car_clear"], side * L["y_half"])) + u = np.sort(rng.uniform(0.0, max((hi - lo) - (n - 1) * L["gap"], 0.0), n)) + ys += [lo + k * L["gap"] + u[k] for k in range(n)] + order = rng.permutation(5) + for k, j in enumerate(order): + pos[BLOCKS[j]] = [row_x + float(rng.uniform(-0.01, 0.01)), float(ys[k])] + plank_xy = [xb + float(rng.uniform(*L["plank_dx"])), yc + float(rng.uniform(-0.04, 0.04))] + size = {b: float(rng.uniform(*L["block_edge"])) for b in BLOCKS} + mu = {b: float(rng.uniform(0.3, 0.6)) for b in BLOCKS} + yaw = {o: float(rng.uniform(-0.35, 0.35)) for o in BLOCKS} + yaw[CAR] = float(rng.uniform(-L["car_yaw"], L["car_yaw"])) + yaw[PLANK] = float(np.pi / 2 + rng.uniform(-0.25, 0.25)) # long axis roughly left-right + pos[PLANK] = plank_xy + return dict(seed=int(seed), squares=sq, blue_side="left" if blue_left else "right", pos=pos, yaw=yaw, + size=size, mu=mu, bridge_x=xb, bridge_yc=yc) + + def _resize_block(self, o, edge): + m = self.env.sim.model + h = edge / 2.0 + for g in self.geoms[o] + self.vis_geoms[o]: + m.geom_size[g] = [h, h, h] + m.geom_rbound[g] = float(np.sqrt(3) * h) + m.geom_aabb[g] = [0.0, 0.0, 0.0, h, h, h] + b = self.block_body[o] + mass = 500.0 * edge ** 3 + m.body_mass[b] = mass + m.body_inertia[b] = [mass * edge ** 2 / 6.0] * 3 + envs.refit_bounds(self.env, b) # BVH of the resized block (envs.refit_bounds) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for s in SQUARES: + x, y = inst["squares"][s] + m.body_pos[self.sq_bid[s]] = [x, y, TZ + 0.0007] + m.body_quat[self.sq_bid[s]] = [1.0, 0.0, 0.0, 0.0] + for o in BLOCKS: + self._resize_block(o, inst["size"][o]) + envs.set_friction(self.env, o, inst["mu"][o]) + envs.set_friction(self.env, PLANK, 0.5) + envs.set_friction(self.env, CAR, 0.6) + self.env.sim.forward() + for o in ITEMS: + envs.place_upright(self.env, o, inst["pos"][o], inst["yaw"][o], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = BridgeSkills(self.env, self, recorder=recorder) + self.mon = dict(state=[False] * 4, raw_since=[0] * 4, ever=[False] * 4, lost=[False] * 4, events=[]) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def half(self, o): + if o in BLOCKS: + e = self.inst["size"][o] / 2 + return np.array([e, e, e]) + return np.array(PLANK_HALF) if o == PLANK else np.array([CAR_HALF] * 3) + + def R(self, o): + return self.env.sim.data.body_xmat[envs.body_id(self.env, o)].reshape(3, 3).copy() + + def pos(self, o): + return envs.obj_pos(self.env, o) + + def zmin(self, o): + return envs.obj_min_z(self.env, o) + + def zmax(self, o): + return envs.obj_max_z(self.env, o) + + def flat(self, o): + return float(np.max(np.abs(self.R(o)[2]))) > FLAT_COS + + def yaw_of(self, o): + """yaw of the object's body x axis (for the plank: its long axis)""" + R = self.R(o) + return float(np.arctan2(R[1, 0], R[0, 0])) + + def held(self, o): + return self.sk is not None and self.sk.holding(o) + + def contacts(self, a_geoms, b_geoms): + return envs.contacts_between(self.env, a_geoms, b_geoms) + + def pillar(self, s): + """(lower, upper) blocks of a complete pillar on square s, else (lower or None, None)""" + c = np.asarray(self.inst["squares"][s]) + lower = None + for b in BLOCKS: + p = self.pos(b) + if np.linalg.norm(p[:2] - c) <= SQ_TOL and self.zmin(b) < TZ + 0.006 and self.flat(b) and not self.held(b): + lower = b + break + if lower is None: + return None, None + pl = self.pos(lower) + top = self.zmax(lower) + for b in BLOCKS: + if b == lower: + continue + p = self.pos(b) + if (np.linalg.norm(p[:2] - pl[:2]) <= STACK_TOL and abs(self.zmin(b) - top) < 0.006 and self.flat(b) + and not self.held(b)): + return lower, b + return lower, None + + def plank_ok(self, tops): + if any(t is None for t in tops) or self.held(PLANK): + return False + R = self.R(PLANK) + if abs(R[2, 0]) > np.sin(PLANK_TILT) or abs(R[2, 2]) < np.cos(PLANK_TILT): # either broad face up (v2 fix) + return False + if self.zmin(PLANK) < TZ + 0.03 or self.contacts(self.geoms[PLANK], self.table_geoms): + return False + return all(self.contacts(self.geoms[PLANK], self.geoms[t]) for t in tops) + + def car_ok(self): + """the car rests on the plank's upper face (in the plank's own frame, so a slightly tilted plank is fine), + within CAR_MID of the plank's centre along its length""" + if self.held(CAR) or not self.contacts(self.geoms[CAR], self.geoms[PLANK]): + return False + R = self.R(PLANK) + rel = R.T @ (self.pos(CAR) - self.pos(PLANK)) + up = rel[2] * (1.0 if R[2, 2] >= 0 else -1.0) # along the broad face pointing up (a plank may lie upside down) + return bool(abs(rel[0]) <= CAR_MID and abs(rel[1]) <= PLANK_HALF[1] + 0.01 and up > PLANK_HALF[2] + 0.01) + + def stages(self): + """raw predicate values [S1, S2, S3, S4] and the pillars found""" + pa = self.pillar(SQUARES[0]) + pb = self.pillar(SQUARES[1]) + s1, s2 = pa[1] is not None, pb[1] is not None + s3 = bool(s1 and s2 and self.plank_ok([pa[1], pb[1]])) + s4 = bool(self.car_ok()) + return [s1, s2, s3, s4], (pa, pb) + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + raw, _ = self.stages() + t = self.sk.n_steps + for i in range(4): + if raw[i] == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 1 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw[i] + mon["raw_since"][i] = 0 + t0 = t - DEBOUNCE + 1 + if raw[i]: + ev = "restored" if mon["lost"][i] else "achieved" + mon["ever"][i] = True + else: + ev = "lost" + mon["lost"][i] = True + mon["events"].append(dict(stage=f"S{i + 1}", event=ev, step=int(t0))) + + # ------------------------------------------------------------ outcome + def _dir_words(self, d): + """robot-centric words for a horizontal offset d (world x = forward, away from the robot; y = robot's left)""" + parts = [] + if abs(d[0]) >= 0.01: + parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}") + if abs(d[1]) >= 0.01: + parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}") + return (" and ".join(parts) + " of") if parts else "right at" + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {o: self.pos(o) for o in ITEMS} + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or any(self.contacts(list(self.robot_geoms), self.geoms[o]) for o in ITEMS) + moved = max(float(np.linalg.norm(self.pos(o) - p0[o])) for o in ITEMS) + static = moved < 0.004 + raw, (pa, pb) = self.stages() + held = [o for o in ITEMS if sk.holding(o)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + n_reg = sum(e["event"] == "lost" for e in ev) + n_res = sum(e["event"] == "restored" for e in ev) + success = bool(all(raw) and static and not held and not touching) + parts = [] + if success: + failure = "none" + parts.append("The bridge is complete: both pillars stand on their squares, the plank rests across them " + "and the red cube sits on the middle of the plank.") + else: + lost_final = [i for i in range(4) if not raw[i] and mon and mon["ever"][i]] + never = [i for i in range(4) if not raw[i] and not (mon and mon["ever"][i])] + if held: + failure = "held" + elif touching: + failure = "touching" + elif lost_final: + failure = "regressed_" + "".join(f"S{i + 1}" for i in lost_final) + elif never: + failure = "incomplete_" + "".join(f"S{i + 1}" for i in never) + else: + failure = "not_static" + for i, s in enumerate(SQUARES): + if raw[i]: + continue + low, _ = (pa, pb)[i] + c = np.asarray(inst["squares"][s]) + txt = f"The pillar on the {SQ_NAME[s]} square is not standing:" + if low is None: + txt += " no block stands on the square." + else: + txt += " only one block stands on the square." + strays = [b for b in BLOCKS if b not in (pa[0], pa[1], pb[0], pb[1])] + if strays: + near = min(strays, key=lambda b: np.linalg.norm(self.pos(b)[:2] - c)) + txt += f" The nearest loose block lies {self._dir_words(self.pos(near)[:2] - c)} the square." + if mon and mon["ever"][i]: + txt += " It had been built and was knocked down later." + parts.append(txt) + if not raw[2]: + pp = self.pos(PLANK) + if self.contacts(self.geoms[PLANK], self.table_geoms): + where = "touches the table" + elif self.held(PLANK): + where = "is still in the gripper" + else: + where = "does not rest level on the tops of both pillars" + bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0) + parts.append(f"The plank {where}; its centre is {self._dir_words(pp[:2] - bc)} the middle between " + f"the squares." + (" It had been laid and was disturbed later." if mon and mon["ever"][2] + and not raw[2] else "")) + if not raw[3]: + if self.held(CAR): + parts.append("The red cube is still in the gripper.") + elif self.contacts(self.geoms[CAR], self.geoms[PLANK]): + parts.append("The red cube is on the plank but not on its middle part.") + else: + bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0) + parts.append(f"The red cube is not on the plank; it lies {self._dir_words(self.pos(CAR)[:2] - bc)} " + "the middle between the squares.") + if all(raw) and held: + parts.append("The gripper still holds an object.") + elif touching: + parts.append("The gripper is still touching the bridge.") + elif all(raw) and not static: + parts.append("The bridge was still moving.") + if n_reg: + parts.append(f"During the attempt earlier stages were undone {n_reg} time(s) and restored {n_res} time(s).") + if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")): + parts.append("(Forward = away from the robot.)") + return dict(success=success, stages={f"S{i + 1}": bool(raw[i]) for i in range(4)}, events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), failure=failure, held=held, + touching=bool(touching), static=bool(static), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _grip_yaws(self, o): + """candidate gripper yaws for a top-down grasp of o (fingers across a face)""" + if o == PLANK: # fingers (which open along the gripper's y at yaw 0) across the plank's width + return [_wrap_h(self.yaw_of(PLANK))] + a = _wrap_q(self.yaw_of(o)) + return [a, _wrap_h(a + np.pi / 2)] + + def footprint(self, o): + """sample points on the horizontal footprint of o (corners, edge midpoints, centre)""" + R, c, h = self.R(o), self.pos(o), self.half(o) + pts = [] + for sx in (-1, 0, 1): + for sy in (-1, 0, 1): + for sz in ((-1, 1) if o != PLANK else (0,)): + pts.append((c + R @ (h * [sx, sy, sz]))[:2]) + if o == PLANK: + for t_ in np.linspace(-1, 1, 9): + for sy in (-1, 1): + pts.append((c + R @ (h * [t_, sy, 0]))[:2]) + return np.array(pts) + + def _hand_clearance(self, xy, yaw, z_site, ignore=()): + """smallest horizontal clearance (m) between the gripper at a grasp-site height z_site and everything else: + the hand body (+-10.6 x +-3.6 cm, underside 2.4 cm above the site) against items taller than its underside, + the open fingers (two 2 x 2.4 cm boxes 3-5 cm out along the finger axis, tips 1.3 cm below the site) + against items taller than the fingertips. Negative = the gripper would land on something.""" + f = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis + g = np.array([np.cos(yaw), np.sin(yaw)]) + best = 1.0 + for o in ITEMS: + if o in ignore or self.held(o): + continue + top = self.zmax(o) + if top < z_site - 0.013: + continue + d = self.footprint(o) - np.asarray(xy) + u, v = np.abs(d @ f), np.abs(d @ g) + c = float(np.min(np.maximum(np.abs(u - 0.040) - 0.010, v - 0.012))) # fingers + if top >= z_site + HAND_BOTTOM - 0.002: + c = min(c, float(np.min(np.maximum(u - HAND_HALF_LONG, v - HAND_HALF_SHORT)))) + best = min(best, c) + return best + + @staticmethod + def _pick_yaw(yaws, clearance): + """the gripper yaw closest to straight (0) among those with >= 1 cm clearance, else the clearest one (large + wrist turns near the edge of the workspace make the OSC stop short)""" + c = {a: clearance(a) for a in yaws} + ok = [a for a in yaws if c[a] >= 0.01] + return min(ok, key=abs) if ok else max(yaws, key=c.get) + + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=250): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _grasp_z(self, o, careful): + if o in BLOCKS: + return self.zmax(o) - (0.016 if careful else self.inst["size"][o] / 2) + if o == PLANK: + return max(self.zmax(PLANK) + 0.0003 - 0.0125, TZ + 0.011) + return self.zmax(CAR) - (0.016 if careful else CAR_HALF) + + def pick(self, o, careful, noise=None, z_t=None): + """top-down grasp; returns the drop of the object's bottom below the grasp site, or None if not held""" + sk = self.sk + p = self.pos(o) + if noise is not None: + p = p + np.array([noise[0], noise[1], 0.0]) + zg = self._grasp_z(o, careful) + yaws = self._grip_yaws(o) + if careful: + yaw = self._pick_yaw(yaws, lambda a: self._hand_clearance(p[:2], a, zg, ignore=(o,))) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([p[0], p[1], TZ + Z_SAFE], yaw=yaw) + sk.set_gripper(False, steps=8) + self._go([p[0], p[1], zg + 0.03], speed=0.25) + self._go([p[0], p[1], zg], speed=0.1, tol=0.003, max_steps=120) + else: + yaw = min(yaws, key=lambda a: abs(a)) + zt = TZ + (Z_NAIVE if z_t is None else z_t) + sk.set_gripper(False, steps=8) + if self.naive_style == "legs": # rise to the transit height if below it, across, straight down + cur = sk.eef_pos() + if cur[2] < zt - 0.003: + self._go([cur[0], cur[1], zt]) + self._go([p[0], p[1], max(cur[2], zt)], yaw=yaw) + else: # one straight line to the approach point above the object + self._go([p[0], p[1], max(zt, self.zmax(o) + 0.03)], yaw=yaw) + self._go([p[0], p[1], zg], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + drop = float(sk.eef_pos()[2] - self.zmin(o)) + if careful: + self._go([p[0], p[1], TZ + Z_SAFE], speed=0.3) + else: + zt = TZ + (Z_NAIVE if z_t is None else z_t) + self._go([p[0], p[1], max(zt, zg + 0.05)]) + if not sk.holding(o): + sk.set_gripper(False, steps=8) + return None + return drop + + def place(self, o, xy, support_top, drop, yaw, careful, z_t=None, release_gap=0.005, lift=None): + sk = self.sk + zr = support_top + drop + release_gap + if careful and o != PLANK: # cubes are symmetric under 90 deg: release with the fingers where there is room + yaw = self._pick_yaw([yaw, _wrap_h(yaw + np.pi / 2)], lambda a: self._hand_clearance(xy, a, zr, ignore=(o,))) + if careful: + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw) + self._go([xy[0], xy[1], zr + 0.03], speed=0.25) + self._go([xy[0], xy[1], zr], speed=0.08, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.03], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + else: + if self.naive_style == "legs": + zt = TZ + (Z_NAIVE if z_t is None else z_t) + cur = sk.eef_pos() + h = max(cur[2], zt, zr + 0.04) + if cur[2] < h - 0.003: + self._go([cur[0], cur[1], h]) + self._go([xy[0], xy[1], h], yaw=yaw) + else: + self._go([xy[0], xy[1], zr + 0.04], yaw=yaw) + self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + (self.naive_lift if lift is None else lift)]) + sk.hold(5) + + # placing targets --------------------------------------------------------- + def square_xy(self, s): + return np.asarray(self.inst["squares"][s], float) + + def bridge_mid(self): + return np.mean([self.square_xy(s) for s in SQUARES], axis=0) + + def free_blocks(self): + _, (pa, pb) = self.stages() + used = set() + for low, up in (pa, pb): + if up is not None: + used |= {low, up} + return [b for b in BLOCKS if b not in used] + + def _blocker(self, b): + """for a careful top-down grasp of block b: None if the gripper fits at some grasp yaw, else the item in the + way (e.g. the top block of a pillar, or a block, right next to b)""" + zg = self._grasp_z(b, True) + p = self.pos(b)[:2] + if max(self._hand_clearance(p, a, zg, ignore=(b,)) for a in self._grip_yaws(b)) > -0.002: + return None + worst = {} + for o in ITEMS: + if o == b or self.held(o): + continue + worst[o] = max(self._hand_clearance(p, a, zg, ignore=tuple(q for q in ITEMS if q != o)) + for a in self._grip_yaws(b)) + o = min(worst, key=worst.get) + return o if worst[o] <= -0.002 else None + + def build_pillar(self, s, careful, noise_fn, z_t=None, order="target"): + """put blocks on square s until it carries a complete pillar (at most 5 placements)""" + failed = {} + for _ in range(6): + raw, (pa, pb) = self.stages() + low, up = (pa, pb)[SQUARES.index(s)] + if up is not None: + return True + if careful and self.over_budget(): + return False + c = self.square_xy(s) + other = (pa, pb)[1 - SQUARES.index(s)] + cand = [b for b in BLOCKS if b != low and b not in other and (not careful or (self.usable(b) + and failed.get(b, 0) < 2))] + if not cand: + return False + ref = self.sk.eef_pos()[:2] if order == "gripper" else c + cand.sort(key=lambda b: (failed.get(b, 0), np.linalg.norm(self.pos(b)[:2] - ref))) + b = cand[0] + if careful: + free = [q for q in cand if self._blocker(q) is None] + if free: + b = free[0] + else: # every usable block sits right next to something tall: take that thing's top off first + blk = self._blocker(cand[0]) + if blk is not None and blk != PLANK and failed.get(blk, 0) < 2: + if not self.park(blk): + failed[blk] = failed.get(blk, 0) + 1 + continue + drop = self.pick(b, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + failed[b] = failed.get(b, 0) + 1 + continue + if low is None: + tgt, top = c, TZ + else: + tgt, top = self.pos(low)[:2], self.zmax(low) + n = noise_fn() + self.place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, careful, z_t=z_t) + return self.stages()[1][SQUARES.index(s)][1] is not None + + def lay_plank(self, careful, noise_fn, z_t=None): + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None or (careful and not self.usable(PLANK)): + return False + drop = self.pick(PLANK, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + return False + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + tops = [TZ + 0.11, TZ + 0.11] + mid = self.bridge_mid() + else: + tops = [self.zmax(pa[1]), self.zmax(pb[1])] + mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2 + n = noise_fn() + # gripper fingers across the plank's width: plank long axis along y -> gripper yaw 90 deg + self.place(PLANK, mid + (n if n is not None else 0.0), max(tops), drop, np.pi / 2, careful, z_t=z_t) + return True + + def put_car(self, careful, noise_fn, z_t=None): + drop = self.pick(CAR, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + return False + pp = self.pos(PLANK) + n = noise_fn() + self.place(CAR, pp[:2] + (n if n is not None else 0.0), self.zmax(PLANK), drop, 0.0, careful, z_t=z_t) + return True + + def in_keep_out(self, o): + """o lies in the zone right behind the bridge line where, once the pillars and the plank stand, a top-down + grasp would put the hand on them (the careful policy keeps it clear)""" + p = self.pos(o)[:2] + dx = p[0] - self.inst["bridge_x"] + return bool(-0.08 < dx < KEEP_OUT["dx"] and abs(p[1] - self.bridge_mid()[1]) < KEEP_OUT["dy"]) + + def free_spot(self, o, avoid=()): + """a free, comfortably reachable table spot for parking object o (the plank lies left-right), outside the + keep-out zone right behind the bridge and away from the squares""" + xb = self.inst["bridge_x"] + ym = self.bridge_mid()[1] + best, best_c = None, -1.0 + others = [q for q in ITEMS if q != o and q not in avoid] + for x in np.arange(xb - 0.14, xb + 0.221, 0.02): + for y in np.arange(-0.28, 0.281, 0.02): + pts = [np.array([x, y])] + if o == PLANK: + pts = [np.array([x, y + d]) for d in (-0.10, 0.0, 0.10)] + if any(not self.reachable_xy(p) or np.hypot(p[0] - BASE_X, p[1]) > 0.64 for p in pts): + continue # (a careful 25 cm transit further out straightens the elbow onto its limit, measured) + if any(-0.08 < p[0] - xb < KEEP_OUT["dx"] and abs(p[1] - ym) < KEEP_OUT["dy"] for p in pts): + continue + c = 1.0 + for p in pts: + for q in others: + c = min(c, float(np.linalg.norm(self.pos(q)[:2] - p)) - 0.04) + for sq in SQUARES: + c = min(c, float(np.linalg.norm(self.square_xy(sq) - p)) - 0.07) + if c > best_c: + best, best_c = np.array([x, y]), c + return best + + @staticmethod + def reachable_xy(p): + """a top-down grasp at table height works here (measured: right in front of the base, closer than 25 cm, + the arm cannot get down to the table; at 70-74 cm it still gets within ~1 cm)""" + rx, y = p[0] - BASE_X, p[1] + return bool(0.25 <= rx <= 0.75 and abs(y) <= 0.34 and (rx >= 0.30 or abs(y) >= 0.15) and np.hypot(rx, y) <= 0.76) + + def usable(self, o): + """o lies on the table (or on something) within reach""" + return self.zmin(o) > TZ - 0.02 and self.reachable_xy(self.pos(o)[:2]) + + def park(self, o, careful=True): + if careful and not self.usable(o): + return False + drop = self.pick(o, careful) + if drop is None: + return False + xy = self.free_spot(o) + self.place(o, xy, TZ, drop, np.pi / 2 if o == PLANK else 0.0, careful) + return True + + def over_budget(self): + """the scripted repair stops where an agent's attempt would end: 3 s of simulated motion per command of the + task's command budget (agent_max_steps = 130 -> 390 s = 7800 control steps)""" + return self.sk.n_steps * 0.05 >= 3.0 * self.agent_max_steps + + def plank_flat(self): + return abs(self.R(PLANK)[2, 2]) > 0.8 + + def fix_plank(self): + """a plank standing on its long edge or leaning on something cannot be picked from above: push its upper edge + over with the closed gripper so that it falls flat (towards the side with more free table)""" + if self.plank_flat() or self.held(PLANK): + return False + sk = self.sk + R, c = self.R(PLANK), self.pos(PLANK) + up = R[:, 1] if R[2, 1] > 0 else -R[:, 1] # the plank's width axis, pointing up + lean = up[:2] / max(np.linalg.norm(up[:2]), 1e-6) + if np.linalg.norm(up[:2]) < 0.2: # standing upright: fall to the side away from the squares + n = R[:2, 2] / max(np.linalg.norm(R[:2, 2]), 1e-6) + far = lambda d: min(np.linalg.norm(c[:2] + 0.05 * d - self.square_xy(q)) for q in SQUARES) # noqa: E731 + lean = n if far(n) > far(-n) else -n + push = lean + else: # leaning: push the top back over the vertical so it falls to the other side + push = -lean + top = c + up * 0.02 + h = max(self.zmax(PLANK) - 0.015, TZ + 0.02) + a = top[:2] - push * 0.05 + yaw = float(np.arctan2(push[1], push[0]) - np.pi / 2) # closed fingers across the push direction + sk.set_gripper(True, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([a[0], a[1], TZ + Z_SAFE], yaw=yaw) + self._go([a[0], a[1], h], speed=0.25) + b = top[:2] + push * 0.08 + self._go([b[0], b[1], h], speed=0.1, max_steps=200) + self._go([b[0], b[1], TZ + Z_SAFE], speed=0.3) + sk.set_gripper(False, steps=8) + sk.hold(10) + return True + + def clear_site(self): + """careful: before building, move the car out of the zone right behind the bridge line""" + if self.in_keep_out(CAR) and not self.held(CAR): + self.park(CAR) + + def repair(self, rounds=4): + """check every stage; rebuild what is broken (careful motions). Returns the number of fixes made.""" + nofn = lambda: None # noqa: E731 + fixes = 0 + for _ in range(rounds): + raw, (pa, pb) = self.stages() + if all(raw) or self.over_budget() or not (self.usable(PLANK) or self.held(PLANK)): + return fixes # (a plank thrown out of reach cannot be laid again) + fixes += 1 + if not (raw[0] and raw[1]): + for _k in range(2): + if not self.plank_flat(): + self.fix_plank() + plank_first = self._hand_clearance(self.pos(CAR)[:2], 0.0, self._grasp_z(CAR, True), + ignore=tuple(q for q in ITEMS if q != PLANK)) < 0.0 + for o in ((PLANK, CAR) if plank_first else (CAR, PLANK)): + if o == CAR and (self.zmin(CAR) > TZ + 0.01 or self._near_squares(CAR) or self.in_keep_out(CAR)): + self.park(CAR) + if o == PLANK and (self.zmin(PLANK) > TZ + 0.006 or self._near_squares(PLANK) + or self.in_keep_out(PLANK)): + self.park(PLANK) + for i, s in enumerate(SQUARES): + if not self.stages()[0][i]: + self.build_pillar(s, True, nofn) + raw, _ = self.stages() + if raw[0] and raw[1] and not raw[2]: + if not self.plank_flat(): + self.fix_plank() + if self.zmin(CAR) > TZ + 0.01 or self.in_keep_out(CAR): + self.park(CAR) + self.lay_plank(True, nofn) + raw, _ = self.stages() + if raw[2] and not raw[3]: + self.put_car(True, nofn) + return fixes + + def _near_squares(self, o): + p = self.pos(o)[:2] + if o == PLANK: + ax = self.R(PLANK)[:2, 0] + pts = [p + s * ax * 0.11 for s in (-1, -0.5, 0, 0.5, 1)] + else: + pts = [p] + return any(np.linalg.norm(q - self.square_xy(s)) < 0.06 for q in pts for s in SQUARES) + + # ------------------------------------------------------------ Sonnet-like naive (style "sonnet") + # Imitates how Claude Sonnet 5.5 moved in the lh1 pilot (runs/claude/lh1_bridge, 4 attempts, 230 commands): + # instruction order; for each pillar the free block nearest to its square first; a hover ~12 cm above the object + # with the gripper turned to the object's yaw, a straight vertical descent, grasp ~1 cm below the top; the carry + # often goes straight from the grasp to ~12.5 cm above the target (one move_eef: a diagonal climb), otherwise lift + # first; when the carried object's straight path would run into a built pillar it lifts first and carries with the + # object's bottom ~4 cm above that pillar; vertical descent, open, lift straight up to ~15 cm; plank: lift to 7 cm, + # carry at 16 cm; car: lift to 17 cm, carry, place, lift to 25 cm; no final check. + def _sn_grasp_z(self, o, sn): + if o == PLANK: + return self._grasp_z(PLANK, False) + return self.zmax(o) - sn["top_below"] + + def _crossing_top(self, a, b, o, drop, hc): + """top of the highest item that the held object o, carried straight from a to b with its bottom at hc - drop, + would run into (any footprint point within o's half size + 1 cm of the path), else None""" + a, b = np.asarray(a[:2], float), np.asarray(b[:2], float) + d = b - a + n2 = float(d @ d) + r = float(self.half(o)[0]) + 0.01 + best = None + for q in ITEMS: + if q == o or self.held(q): + continue + top = self.zmax(q) + if top < hc - drop: + continue + pts = self.footprint(q) + t = np.clip((pts - a) @ d / n2, 0.0, 1.0) if n2 > 1e-9 else np.zeros(len(pts)) + dist = float(np.min(np.linalg.norm(pts - (a + t[:, None] * d), axis=1))) + if dist < r and (best is None or top > best): + best = top + return best + + def sn_pick(self, o, sn, noise=None): + sk = self.sk + p = self.pos(o) + if noise is not None: + p = p + np.array([noise[0], noise[1], 0.0]) + zg = self._sn_grasp_z(o, sn) + if o == PLANK: + yaw = _wrap_h(self.yaw_of(PLANK)) + elif o == CAR and sn["car_style"] == "keep": + yaw = None # keeps the gripper's current yaw (the pilot's seed 3000: still turned 90 deg from the plank) + else: + yaw = _wrap_q(self.yaw_of(o)) + hover = TZ + (sn["car_hover"] if o == CAR else sn["hover"]) + direct = o == CAR and sn["car_style"] == "direct" # (the pilot's seed 3001 went straight down to the car) + if not direct: + self._go([p[0], p[1], hover], yaw=yaw) + self._go([p[0], p[1], zg], yaw=yaw, tol=0.003, max_steps=250 if direct else 120) + sk.set_gripper(True, steps=15) + if not sk.holding(o): + sk.set_gripper(False, steps=15) + self._go([p[0], p[1], TZ + sn["hover"]]) + return None + return float(sk.eef_pos()[2] - self.zmin(o)) + + def sn_place(self, o, xy, support_top, drop, yaw, sn, carry=None, lift=None, diag=None): + sk = self.sk + zr = support_top + drop + 0.004 + hc = max(TZ + (sn["carry"] if carry is None else carry), zr + 0.03) + cur = sk.eef_pos() + diag = sn["diag"] if diag is None else diag + top = None if o == PLANK else self._crossing_top(cur, xy, o, drop, hc) + if top is not None: # a built pillar in the way: lift first, carry with the object's bottom above it + hc = max(hc, top + drop + sn["cross_margin"]) + self._go([cur[0], cur[1], hc]) + self._go([xy[0], xy[1], hc], yaw=yaw) + elif diag: # one move_eef from the grasp to above the target + self._go([xy[0], xy[1], hc], yaw=yaw) + else: + self._go([cur[0], cur[1], max(cur[2], hc + 0.02)]) + self._go([xy[0], xy[1], hc], yaw=yaw) + self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=15) + self._go([xy[0], xy[1], TZ + (sn["lift"] if lift is None else lift)]) + sk.hold(5) + + def sn_build_pillar(self, s, sn, noise_fn): + failed = {} + c = self.square_xy(s) + mid = self.bridge_mid() + for _ in range(5): + raw, (pa, pb) = self.stages() + low, up = (pa, pb)[SQUARES.index(s)] + if up is not None: + return True + other = (pa, pb)[1 - SQUARES.index(s)] + cand = [b for b in BLOCKS if b != low and b not in other and failed.get(b, 0) < 2] + if not cand: + return False + if sn["alloc"] == "side": # blocks on this square's side of the bridge first + side = np.sign(c[1] - mid[1]) + same = [b for b in cand if np.sign(self.pos(b)[1] - mid[1]) == side] + cand = same or cand + b = min(cand, key=lambda q: (failed.get(q, 0), np.linalg.norm(self.pos(q)[:2] - c))) + drop = self.sn_pick(b, sn, noise=noise_fn()) + if drop is None: + failed[b] = failed.get(b, 0) + 1 + continue + tgt, top = (c, TZ) if low is None else (self.pos(low)[:2], self.zmax(low)) + n = noise_fn() + # onto the bare square: straight from the grasp (diagonal climb); onto a block: lift first (a diagonal + # climb from nearby clips the lower block -- the pilot's seed 3000 did that once, then lifted first) + self.sn_place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, sn, + diag=None if low is None else False) + return self.stages()[1][SQUARES.index(s)][1] is not None + + def sn_lay_plank(self, sn, noise_fn): + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + return False + drop = self.sn_pick(PLANK, sn, noise=noise_fn()) + if drop is None: + return False + cur = self.sk.eef_pos() + self._go([cur[0], cur[1], TZ + sn["plank_lift"]]) + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + tops, mid = [TZ + 0.11, TZ + 0.11], self.bridge_mid() + else: + tops = [self.zmax(pa[1]), self.zmax(pb[1])] + mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2 + n = noise_fn() + mid = mid + (n if n is not None else 0.0) + self.sn_place(PLANK, mid, max(tops), drop, np.pi / 2, sn, carry=sn["plank_carry"], lift=sn["plank_end_lift"], + diag=True) + return True + + def sn_put_car(self, sn, noise_fn): + drop = self.sn_pick(CAR, sn, noise=noise_fn()) + if drop is None: # (in the pilot, Sonnet stopped here when it saw the bridge come down) + return False + n = noise_fn() + pp = self.pos(PLANK)[:2] + (n if n is not None else 0.0) + self.sn_place(CAR, pp, self.zmax(PLANK), drop, None, sn, carry=sn["car_lift"], lift=sn["end_lift"], + diag=False) + return True + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + mode = params.get("mode", "naive") + careful = mode == "careful" + rng = np.random.default_rng(params.get("noise_seed", 0)) + sig = float(params.get("noise", 0.0)) + noise_fn = (lambda: rng.uniform(-sig, sig, 2)) if sig > 0 else (lambda: None) + z_t = params.get("z_t") + self.naive_lift = float(params.get("lift", NAIVE_LIFT)) + style = params.get("style", "sonnet") + if not careful and style == "sonnet": + sn = dict(SN) + sn.update(params.get("sn", {})) + if sn["car_style"] is None: + sn["car_style"] = CAR_STYLES[int(inst["seed"]) % 3] + for s in SQUARES: + self.sn_build_pillar(s, sn, noise_fn) + self.sn_lay_plank(sn, noise_fn) + self.sn_put_car(sn, noise_fn) + else: # careful, or the v1 naive ("legs": vertical / horizontal legs at 8 cm; "diag") + self.naive_style = style if style in ("legs", "diag") else NAIVE_STYLE + if careful: + self.clear_site() + for s in SQUARES: + self.build_pillar(s, careful, noise_fn, z_t=z_t, order=params.get("order", "target")) + self.lay_plank(careful, noise_fn, z_t=z_t) + self.put_car(careful, noise_fn, z_t=z_t) + if params.get("check"): + self.repair() + cur = self.sk.eef_pos() + if cur[2] < TZ + 0.20: + self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.15) + + def default_params(self, inst): + return dict(mode="naive", style="sonnet", check=False) + + def oracle_params(self, inst): + return dict(mode="careful", check=True) + + def adapt_params(self, inst, history): + return dict(mode="careful", check=True) + + def blind_params(self, inst, attempt, rng): + sn = dict(hover=float(rng.uniform(0.10, 0.14)), carry=float(rng.uniform(0.11, 0.15)), + lift=float(rng.uniform(0.13, 0.20)), diag=bool(rng.random() < 0.5), + car_style=CAR_STYLES[int(rng.integers(3))], alloc="side" if rng.random() < 0.5 else "greedy") + return dict(mode="naive", style="sonnet", check=False, sn=sn, noise=0.004, noise_seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """kinds: oracle, naive (Sonnet-like, car approach style by seed), adaptive, blind; for comparison naive_v1 (the + v1 naive: vertical / horizontal legs at 8 cm) and naive_hover / naive_keep / naive_direct (Sonnet-like with + one fixed car approach style)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "naive_v1": + params = dict(mode="naive", style="legs", check=False) + elif kind.startswith("naive_") and kind[6:] in CAR_STYLES: # naive_hover / naive_keep / naive_direct + params = dict(mode="naive", style="sonnet", check=False, sn=dict(car_style=kind[6:])) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind == "oracle" or kind.startswith("naive"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_clear_cover.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..542d519109d1f085f749fe2db4dd0c20b51281b5 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_clear_cover.py @@ -0,0 +1,657 @@ +"""LH clear_cover: sort four cubes into two open boxes by colour -- but in half of the instances one box is covered by a +loose clear acrylic lid. A cube carried over that box and released stops on the lid at rim height; it is not in the box. + +Family: long-horizon self-disturbance / common sense ("state_restoration"; design P2-2 in +research_notes/P1P2_加深与常识任务设计.md): four pick-and-place stages that are each easy for a frontier model; the +trap is a commonsense one -- "a box can have a transparent lid" -- and the failure is only visible from the right +viewpoint: from the side (agentview) the cube visibly sits on top of the box, at rim height, with the box floor visible +below it; from straight above (the wrist camera) it lies inside the box's outline and looks almost the same as a cube +that is inside (design rule R5: a top-down view hides height differences). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * two open boxes (fixtures; inside 12 x 12 cm, walls 5 cm high and 8 mm thick, rim 5.6 cm above the table, light + floor) with red and with blue walls, centres at x in [-0.14, -0.08], y = +-(0.12-0.14) (24-28 cm apart); which + colour is on the left is random. The instruction names the boxes by colour, not "left / right" (the design draft's + wording), so that no failure comes from whose left is meant; + * four 4 cm cubes (38 g), two red and two blue, in a row in front of the boxes (x = -0.33, near the robot; 14 cm + apart, shuffled, yaw +-23 deg); + * the clear lid (covered instances only): a loose 13.4 x 13.4 cm, 8 mm clear plate lying on one box's walls, + 1 mm inside their outer faces (no overhang). v2 (2026-10-13, after the Sonnet pilot np_lh_clear_cover): rendered + nearly invisible -- alpha 0.03, matte (no specular glint), no edge highlight (v1: alpha 0.10 + bright edges, and the + pilot agent named "the transparent lid" from the first images); heavy (1 kg; mass is not visible) with friction 1.0 + and priority for all its contacts and medium-stiff contacts, so incidental contact by the hand does not knock it off + (v1, 0.12 kg / mu 0.3 / 6 mm overhang / very stiff contacts: a probe descent between the boxes knocked it off in the + pilot's very first motions). Transparent geoms do not write MuJoCo's depth buffer: in the depth maps + (--perception rgbd) the lid is not there at all. In uncovered instances the lid is parked on the floor far outside + the workspace and the cameras' view. + +Hidden variable: whether a box is covered and which one. Exactly 10 of every 20 consecutive seeds are covered (5 red / +5 blue box): (seed * 7) mod 20 < 10, like lh_lid_box's balanced blocks. + +Why the natural plan fails: carry each cube over its box and release it a few cm above the rim. Over the covered box the +cube lands on the lid and stays there (v2, measured: drops of 1-8 cm, 48/48 stay on the lid, the lid does not move; +pressing a held cube down towards the box floor stops the arm 4.2 cm above the target, the lid moves <= 0.8 mm, 12/12 +still covering). After the release the cube visibly sits on top of the box in agentview (its bottom 0.8 cm above the +rim, the box floor visible below it); checking only from above it looks as if it were in the box (~1.3x bigger). +What must be learned: look from the side / compare heights before finishing, notice the cubes resting at rim height, +remove the lid (push its edge horizontally with the closed gripper, fingertips between the rim and the lid's top face -- +what the pilot agent did when it saw the v1 lid) and put the cubes in (within the attempt), or check for a lid and +remove it before placing anything (across attempts). Pressing the fingertips onto the lid and dragging no longer moves +it (v2: hand friction = rim friction, by design, because a hand landing on the lid while moving sideways is exactly +what knocked the v1 lid off). +Measured, 2 covered instances x 86 Sonnet-like incidental motions (probe descents to 2-5 cm next to / between the +boxes, transits at 11-20 cm over the covered box, low lateral moves next to the boxes): the box got uncovered 1/172 +(v1: 57/172), the lid moved > 2 cm 20/172 (v1: 97/172); a crash sweep through the boxes at 3 cm still knocks it (1/2). +Deliberate edge push, agent-style commands: fingertip target 2-10 mm below the lid's top face 10/10 (+ 8/8 in the +parameter sweep), at the top face 1/2, above it 0/2. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the +cavity of the box of its colour -- centre inside the cavity, lowest point below the rim --, nothing held, the lid not on +a box, scene static) plus a per-step event log (cube stages achieved / lost / restored, rested_on_cover, left_cover, +cover_removed, cover_on_box, in_wrong_box) for the server log; F1 gives the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z +TIP = envs.FINGERTIP_BELOW_SITE +# ---------------------------------------------------------------- geometry / physics +CUBE_E = 0.04 +CUBE_DENS = 600.0 # -> 38 g +BOX_IN = 0.06 # inner half width (12 x 12 cm cavity) +WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.05 +BOX_OUT = BOX_IN + WALL_T +RIM = FLOOR_T + WALL_H # rim height above the table +WALL_MU = 0.3 # walls (cube contacts; the lid's own friction has priority in its contacts) +LID_T = 0.008 # thick enough that a horizontal push at 'lid height' finds its edge (v1 draft: 4 mm, see the card) +LID_HALF = BOX_OUT - 0.001 # v2: no overhang (1 mm inside the walls' outer faces): a hand landing on its edge cannot tip it +LID_MASS = 1.0 # v2: heavy (a thick glass-like plate; mass is not visible): incidental bumps move it much less +LID_MU = 1.0 # v2: with priority, used for ALL lid contacts (rim, hand, fingers, cubes): pressing on the lid and moving +# sideways cannot drag it (hand friction == rim friction, and the rim also carries the lid's weight) +LID_SOLREF = (0.005, 1.0) # v2: medium-stiff contacts (v1 used _SOLID: a finger that caught the lid's edge while the +LID_SOLIMP = (0.95, 0.99, 0.001) # arm pressed on could squeeze it against the wall and launch it 16-37 cm) +LID_TOP = RIM + LID_T # lid top surface above the table when it lies on a box +LID_RGBA = (0.85, 0.90, 0.95, 0.03) # v2: near-invisible, no edge highlight, no specular (material below) +PARK = (0.0, 1.4) # lid parked on the floor (world z = 0), out of reach and out of view (uncovered instances) + +COLORS = ("red", "blue") +CUBE_RGBA = dict(red=(0.88, 0.10, 0.08, 1.0), blue=(0.10, 0.25, 0.88, 1.0)) +WALL_RGBA = dict(red=(0.72, 0.26, 0.22, 1.0), blue=(0.22, 0.34, 0.72, 1.0)) +FLOOR_RGBA = (0.86, 0.85, 0.82, 1.0) +CUBES = [f"{c}_cube_{i}" for c in COLORS for i in (1, 2)] +BOXES = {c: f"{c}_box_1" for c in COLORS} +LID = "clear_lid_1" + +IN_MARGIN = 0.010 # a cube counts as in a box if its centre is within BOX_IN - IN_MARGIN of the box centre (each axis) +BELOW_RIM = 0.005 # ... and its lowest point is at least this far below the rim +Z_CARRY = 0.15 # scripted transit height of the grasp point above the table (Sonnet: 11-20 cm) +DROP = 0.04 # scripted release: cube bottom this far above the rim (Sonnet-like 3-5 cm) +SLOT = 0.028 # two cubes per box: +-2.8 cm from the centre along y +PUSH_DEPTH = 0.004 # scripted edge push: fingertips this far below the lid's top face (lid 8 mm thick) +PUSH_SPEED = 0.06 + + +def _color(name): + return name.split("_")[0] + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def box_xml_cc(name, wall_rgba): + """open-top box, body origin at the centre of its footprint on the table (z = 0 = table top)""" + o = BOX_OUT + parts = [((0, 0, FLOOR_T / 2), (o, o, FLOOR_T / 2), FLOOR_RGBA, 1.0), + ((BOX_IN + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((-BOX_IN - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((0, BOX_IN + WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU), + ((0, -BOX_IN - WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU)] + g = [] + for k, (p, s, c, mu) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return f""" + + + +{chr(10).join(g)} + + + + + + +""" + + +def lid_xml(name): + """clear plate: one collision box + a near-invisible visual twin with a matte material (no specular glint)""" + h, t = LID_HALF, LID_T / 2 + g = [f' ', + f' '] + xml = _wrap(name, "\n".join(g), t, float(np.hypot(h, h))) + mat = (f' \n \n \n') + return xml.replace(" ", mat + " ", 1) + + +class CoverSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class ClearCover(LFFTask): + name = "lh_clear_cover" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Utilize") + protocol = "cross" + max_attempts = 3 + # careful oracle: 4 pick-and-places (~7 commands each = 28) + pushing the lid off (~5) + looking around (~15); + # one recovery: pushing the lid off + re-placing the cubes that were on it (~5 + 2 x 7) -> ~70; Sonnet looks after + # every step and calibrates the wrist camera (cla4: 10+ observe / probe commands) + agent_max_steps = 110 + instruction = "Put the two red cubes into the red box and the two blue cubes into the blue box." + instruction_indirect = "Sort the four small cubes by colour: each cube goes into the box whose walls have its colour." + agent_object_names = ["red cube", "red cube", "blue cube", "blue cube", "red box", "blue box"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for j, c in enumerate(COLORS): + bx = register_generated(f"LffCc{c.title()}Box", box_xml_cc(f"lff_cc_{c}_box", WALL_RGBA[c]), free=False) + fx.append((BOXES[c], bx, f"{c}_box_region", (-0.12, 0.12 - 0.26 * j, -0.10, 0.14 - 0.26 * j))) + k = 0 + for c in COLORS: + for i in (1, 2): + ab = "AB"[i - 1] + cat = register_generated(f"LffCc{c.title()}Cube{ab}", + box_xml(f"lff_cc_{c}_cube_{ab.lower()}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], + density=CUBE_DENS)) + objs.append((f"{c}_cube_{i}", cat, f"{c}_cube_{i}_region", + (-0.34, -0.22 + 0.14 * k, -0.32, -0.20 + 0.14 * k))) + k += 1 + lid = register_generated("LffCc2ClearLid", lid_xml("lff_cc2_clear_lid")) + objs.append((LID, lid, "lid_region", (0.20, -0.01, 0.22, 0.01))) + return write_bddl(self.name, "put the cubes into the boxes of their colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.box_bid = {c: m.body_name2id(self.env.fixtures_dict[BOXES[c]].root_body) for c in COLORS} + self.lid_gids = set(envs.obj_geom_ids(self.env, LID)) + self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES} + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx = float(rng.uniform(-0.13, -0.09)) + left = str(rng.choice(COLORS)) + boxes = {} + for c in COLORS: + s = 1.0 if c == left else -1.0 + boxes[c] = [bx + float(rng.uniform(-0.01, 0.01)), s * float(rng.uniform(0.12, 0.14))] + slots = [-0.21, -0.07, 0.07, 0.21] + perm = rng.permutation(4) + start = {CUBES[i]: [float(-0.33 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + # balanced like lh_lid_box: exactly 10 of every 20 consecutive seeds covered (5 red box, 5 blue box) + r = (int(seed) * 7) % 20 + cover = "red" if r < 5 else ("blue" if r < 10 else None) + return dict(seed=int(seed), boxes=boxes, left_box=left, start=start, + start_yaw={k: float(rng.uniform(-0.4, 0.4)) for k in CUBES}, cover=cover, + cover_side=(None if cover is None else ("left" if cover == left else "right")), + lid_off=[float(v) for v in rng.uniform(-0.004, 0.004, 2)], lid_yaw=float(rng.uniform(-0.05, 0.05))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c in COLORS: + m.body_pos[self.box_bid[c]] = [inst["boxes"][c][0], inst["boxes"][c][1], Z] + m.body_quat[self.box_bid[c]] = [1.0, 0.0, 0.0, 0.0] + for name, xy in inst["start"].items(): + envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name]) + if inst["cover"]: + b = inst["boxes"][inst["cover"]] + envs.set_obj_pose(self.env, LID, [b[0] + inst["lid_off"][0], b[1] + inst["lid_off"][1], + Z + RIM + LID_T / 2 + 0.0005], yaw=inst["lid_yaw"]) + else: + envs.set_obj_pose(self.env, LID, [PARK[0], PARK[1], LID_T / 2 + 0.002]) + envs.set_friction(self.env, LID, LID_MU, priority=2) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = CoverSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def cube_rel(self, name, color): + return envs.obj_pos(self.env, name)[:2] - np.asarray(self.inst["boxes"][color]) + + def in_box(self, name, color, margin=IN_MARGIN): + """centre inside the cavity (per axis), lowest point below the rim, not held""" + rel = self.cube_rel(name, color) + return bool(np.max(np.abs(rel)) <= BOX_IN - margin and envs.obj_min_z(self.env, name) < Z + RIM - BELOW_RIM + and not self.held(name)) + + def where_box(self, name): + for c in COLORS: + if self.in_box(name, c): + return c + return None + + def lid_pos(self): + return envs.obj_pos(self.env, LID) + + def covering(self): + """colour of the box the lid lies on (centre within the box's outer footprint + 1 cm, above the floor), or None""" + p = self.lid_pos() + for c in COLORS: + rel = np.abs(p[:2] - np.asarray(self.inst["boxes"][c])) + if rel[0] <= BOX_OUT + 0.01 and rel[1] <= BOX_OUT + 0.01 and p[2] > Z + 0.02: + return c + return None + + def _touching(self, gids_a, gids_b): + return envs.contacts_between(self.env, gids_a, gids_b) + + def on_cover(self, name, moving_ok=False): + """the cube rests on the lid while the lid lies on a box (contact, not held, slow -- unless `moving_ok`: the + monitor keeps a cube that came to rest on the lid "on" while it rides along with the lid being pushed)""" + if self.covering() is None or self.held(name): + return False + if not self._touching(self.cube_gids[name], self.lid_gids): + return False + if moving_ok: + return True + _, da = envs.free_joint_addr(self.env, name) + return bool(np.linalg.norm(self.env.sim.data.qvel[da:da + 3]) < 0.05) + + def stage_values(self): + v = {f"{n}_in_box": self.in_box(n, _color(n)) for n in CUBES} + v["cover_off_boxes"] = self.covering() is None + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(step=0, state={f"{n}_in_box": False for n in CUBES}, ever=set(), lost=set(), events=[], + on_cover={n: False for n in CUBES}, cover=self.covering(), wrong={n: None for n in CUBES}, + last_touch={n: None for n in CUBES}, rested=[], cover_removed_step=None) + + def _touches(self): + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for n, g in self.cube_gids.items(): + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.robot_gids: + out[n] = "robot" + elif other in self.lid_gids and out.get(n) != "robot": + out[n] = "lid" + return out + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + for n, who in self._touches().items(): + if who == "robot": + mon["last_touch"][n] = step + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + cov = self.covering() + if cov != mon["cover"]: + if mon["cover"] is not None and cov is None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_removed", box=mon["cover"])) + mon["cover_removed_step"] = step + elif cov is not None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_on_box", box=cov)) + mon["cover"] = cov + for n in CUBES: + oc = self.on_cover(n, moving_ok=mon["on_cover"][n]) + if oc != mon["on_cover"][n]: + mon["on_cover"][n] = oc + if oc: + mon["rested"].append(dict(step=step, cube=n)) + mon["events"].append(dict(step=step, pred=f"{n}_on_cover", ev="rested_on_cover" if oc else "left_cover", + cube=n, box=cov)) + key = f"{n}_in_box" + was = mon["state"][key] + now = self.in_box(n, _color(n), IN_MARGIN if not was else IN_MARGIN - 0.005) + if now != was: + self._event(key, now, step, n) + other = [c for c in COLORS if c != _color(n)][0] + wr = other if self.in_box(n, other) else None + if wr != mon["wrong"][n]: + mon["wrong"][n] = wr + if wr: + mon["events"].append(dict(step=step, pred=key, ev="in_wrong_box", cube=n, box=wr)) + + def _event(self, key, now, step, n): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + if self.held(n): + cause = "picked_up" + else: + lt = mon["last_touch"][n] + cause = "robot" if lt is not None and step - lt <= 60 else "other" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause)) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in CUBES + [LID]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return True + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in CUBES if self.held(n)] + on_cover = [n for n in CUBES if self.on_cover(n)] + wrong = [n for n in CUBES if not vals[f"{n}_in_box"] and self.where_box(n) is not None] + missing = [n for n in CUBES if not vals[f"{n}_in_box"]] + cov = self.covering() + success = bool(all(vals.values()) and static and not held) + failure = None + if not success: + failure = ("held" if held else "cube_on_cover" if on_cover else "wrong_box" if wrong else + "cube_not_in_box" if missing else "cover_on_box" if cov is not None else "not_static") + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + rested_cubes = sorted({r["cube"] for r in mon["rested"]}) + parts = [] + if success: + parts.append("All four cubes are in the boxes of their colour.") + for n in missing: + c = _color(n) + txt = f"A {c} cube is not in the {c} box: " + if n in held: + parts.append(txt + "it is still held by the gripper.") + continue + p = envs.obj_pos(self.env, n) + rel = self.cube_rel(n, c) + if n in on_cover: + txt += (f"it rests on a clear acrylic lid that lies on the {cov} box, " + f"{100 * (envs.obj_min_z(self.env, n) - Z - FLOOR_T):.1f} cm above the box floor") + elif self.where_box(n) is not None: + txt += f"it is in the {self.where_box(n)} box" + else: + h = envs.obj_min_z(self.env, n) - Z + txt += ("it lies on the table" if h < 0.005 else f"it lies {100 * h:.1f} cm above the table") + txt += f", its centre {_fb(rel[0])} and {_lr(rel[1])} of the {c} box's centre" + if n in rested_cubes and n not in on_cover: + txt += " (it had come to rest on the clear lid earlier)" + parts.append(txt + ".") + if cov is not None: + parts.append(f"A clear acrylic lid lies on the {cov} box.") + if not static and all(vals.values()) and not held: + parts.append("Something was still moving at the end.") + if mon["cover_removed_step"] is not None and cov is None: + parts.append("The clear lid was pushed off its box.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + covered=inst["cover"], trap_fired=bool(mon["rested"]), n_rested_on_cover=len(mon["rested"]), + rested_cubes=rested_cubes, cover_removed=mon["cover_removed_step"] is not None, + cover_removed_step=mon["cover_removed_step"], cover_final=cov, on_cover_final=on_cover, + recovered_in_attempt=bool(mon["rested"]) and success, + cube_offsets_cm={n: (100 * self.cube_rel(n, _color(n))).round(1).tolist() for n in CUBES}, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _finger_axis(self, yaw): + """world xy direction along which the fingers close at gripper yaw `yaw` (Skills: yaw 0 = fingers along y)""" + return np.array([-np.sin(yaw), np.cos(yaw)]) + + def _clear_yaw(self, name, room=0.04): + """grasp yaw of the cube: the smallest wrist turn (within +-45 deg) unless one of the open fingertips (4.5 cm + either side) would come down within `room` of another cube's centre (cubes put side by side or pushed off on + the lid stand 1.5-2.5 cm apart); then the 90-deg turned grasp if it has more room""" + p = envs.obj_pos(self.env, name)[:2] + others = [envs.obj_pos(self.env, n)[:2] for n in CUBES if n != name] + + def dmin(yaw): + a = self._finger_axis(yaw) + return min([np.linalg.norm(t - o) for t in (p + a * 0.045, p - a * 0.045) for o in others] or [1.0]) + + y0 = self._grasp_yaw(name) + if dmin(y0) >= room: + return y0 + y1 = float((y0 + np.pi / 2 + np.pi / 2) % np.pi - np.pi / 2) + return y1 if dmin(y1) > dmin(y0) else y0 + + def pick(self, name, z_carry=Z_CARRY): + sk = self.sk + p = envs.obj_pos(self.env, name) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, p[2] - Z + 0.06)], yaw=self._clear_yaw(name)) + sk.move_to([p[0], p[1], p[2]], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + return True + + def place_in(self, name, slot, drop=DROP, z_carry=Z_CARRY, noise=None): + """carry the held cube over its box (slot -1 / +1: 2.8 cm right / left of the centre) and release it with its + bottom `drop` above the rim""" + sk = self.sk + b = np.asarray(self.inst["boxes"][_color(name)], float) + d = b + [0.0, SLOT * slot] + (np.asarray(noise, float) if noise is not None else 0.0) + z_rel = Z + RIM + drop + CUBE_E / 2 + sk.move_to([d[0], d[1], Z + z_carry], yaw=0.0) + sk.move_to([d[0], d[1], z_rel], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], Z + z_carry]) + + def pick_place(self, name, slot, drop=DROP, noise=None): + if self.pick(name): + self.place_in(name, slot, drop=drop, noise=noise) + return True + return False + + def remove_cover(self, direction=None, depth=PUSH_DEPTH, mode="edge"): + """push the lid off its box: closed gripper, fingertips `depth` below the lid's top face, start 3 cm outside + its near edge (mode "edge") or 3 cm inside it, pressing on the lid (mode "press": press and drag -- v2: does not + move the lid any more, see the module docstring), sweep + straight on until the lid has cleared the box (default: sideways, away from the other box), lift""" + cov = self.covering() + if cov is None: + return False + sk = self.sk + lp = self.lid_pos() + b = np.asarray(self.inst["boxes"][cov], float) + if direction is None: + o = np.asarray(self.inst["boxes"][[c for c in COLORS if c != cov][0]], float) + direction = (0.0, float(np.sign(b[1] - o[1]))) + d = np.asarray(direction, float) / np.linalg.norm(direction) + back = LID_HALF + 0.03 if mode == "edge" else LID_HALF - 0.03 + s = lp[:2] - d * back + top = lp[2] + LID_T / 2 + z = top - depth + TIP + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.08], yaw=float(np.arctan2(d[1], d[0]) - np.pi / 2)) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=80) + # sweep until the lid's near edge is 3 cm beyond the box's far wall + need = float((b - lp[:2]) @ d) + BOX_OUT + back + 0.03 + e = s + d * need + sk.move_to([e[0], e[1], z], speed=PUSH_SPEED, tol=0.006, max_steps=int(need / PUSH_SPEED / 0.05) + 80) + sk.move_to([e[0], e[1], z + 0.10], speed=0.2) + sk.set_gripper(False, steps=8) + sk.hold(10) + return self.covering() is None + + def slots(self, order): + """slot of each cube: the first cube of a colour goes right of the centre, the second left""" + seen, out = {c: 0 for c in COLORS}, {} + for n in order: + out[n] = (-1, 1)[seen[_color(n)] % 2] + seen[_color(n)] += 1 + return out + + def wrist_fix(self, rounds=1): + """what a top-down check can see: cubes whose centre is not over the right box's outline (on the table, in + the other box, still held) get placed again; heights are not judged""" + for _ in range(rounds): + bad = [] + for n in CUBES: + rel = self.cube_rel(n, _color(n)) + if self.held(n) or np.max(np.abs(rel)) > BOX_OUT: + bad.append(n) + if not bad: + return + for n in bad: + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + self.pick_place(n, -1 if self.cube_rel(n, _color(n))[1] < 0 else 1) + + def set_aside(self, name): + """pick the cube (e.g. off the lid) and put it down on the table where it started (that spot is free)""" + if not self.pick(name): + return False + sk = self.sk + x, y = self.inst["start"][name] + sk.move_to([x, y, Z + Z_CARRY], yaw=0.0) + sk.move_to([x, y, Z + CUBE_E / 2 + 0.004], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([x, y, Z + Z_CARRY]) + return True + + def side_fix(self, rounds=2): + """the careful check (agentview / heights): every cube must be inside its box, below the rim; if cubes rest on + a lid (or a lid lies on a box): take the cubes off the lid (v2: the heavy lid cannot be pushed off with cubes + standing on it -- the hand runs into them), push the lid off; then place every cube that is not in its box""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + if not v["cover_off_boxes"]: + for n in CUBES: + if self.on_cover(n) or (self.covering() is not None and self._touching(self.cube_gids[n], self.lid_gids)): + self.set_aside(n) + self.remove_cover() + for n in CUBES: + if not self.in_box(n, _color(n)): + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + others = [m for m in CUBES if m != n and _color(m) == _color(n)] + rel_o = self.cube_rel(others[0], _color(n)) if others else np.zeros(2) + self.pick_place(n, 1 if rel_o[1] < 0 else -1) + return all(self.stage_values().values()) + + def execute(self, inst, params): + order = params.get("order") or list(CUBES) + noise = params.get("noise") or {} + drops = params.get("drops") or {} + if params["plan"] == "lid_first": + self.remove_cover(params.get("push_dir"), params.get("push_depth", PUSH_DEPTH), params.get("push_mode", "edge")) + sl = self.slots(order) + for n in order: + self.pick_place(n, sl[n], drop=drops.get(n, DROP), noise=noise.get(n)) + if params.get("check") == "side": + self.side_fix() + elif params.get("check") == "wrist": + self.wrist_fix() + self.sk.hold(10) + + def default_params(self, inst): + return dict(plan="naive", check="wrist") + + def oracle_params(self, inst): + return dict(plan="lid_first", check="side") + + def adapt_params(self, inst, history): + """from attempt 2 on: look for a lid and push it off first, then place, then check from the side""" + return dict(plan="lid_first", check="side") + + def blind_params(self, inst, attempt, rng): + """the natural plan again with small random variations (order, 5 mm placement noise, 3-5 cm drop), no history""" + order = [CUBES[i] for i in rng.permutation(len(CUBES))] + return dict(plan="naive", check="wrist", order=order, + noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES}, + drops={n: float(rng.uniform(0.03, 0.05)) for n in CUBES}) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(plan="naive", check="side") if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # extra control (not in validate's table): cross-attempt learning only, no side check + params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check="wrist") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/vla.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/vla.py new file mode 100644 index 0000000000000000000000000000000000000000..1386b840a27a2f6b6131f40296a0b58c80aaee8a --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/vla.py @@ -0,0 +1,293 @@ +"""Evaluate a visuomotor policy (VLA, e.g. pi0.5) on LFF-Bench instances. + +A VLA sends 7-D OSC actions at 20 Hz instead of the agents' robot commands. Everything else is the benchmark's own: +task scenes and instances, per-attempt budgets, attempt transitions (cross = reset, within = continue in place) and +task.outcome(). The observation has the layout of the LeRobot replay dataset (scripts/lerobot_replay.py, Recorder.state), +so a policy trained on that dataset needs no adapter. Driver: scripts/vla_eval.py. + +What differs from the agents' interface, and why: +- Actions go through sk._act, not env.step: the tasks' per-step monitors and failure injections live there. +- sk.grip and sk.yaw are kept in step with the policy, because outcome() and go_home() use them (Skills.hold holds + sk.yaw, not the current orientation) and set_gripper hooks run with steps=0 once the fingers have settled. +- The hidden offset of L1 tasks is applied in Skills.move_to / YawSkills.R0, which direct actions bypass. The policy still + reads its proprioception in the robot's believed frame (frame="believed"), as the agents do, but an L1 result does not + measure the same trap as for an agent: report those tasks separately. +- There is no `finish`: an attempt ends when its simulated-time budget runs out or the arm has been idle for idle_s. +""" +import os +import select +import time + +import msgpack +import numpy as np + +from . import envs +from .agent import camera as C +from .skills import ROT_SCALE + +CONTROL_HZ = 20 +GRIP_SETTLE = 15 # control steps the fingers get before the set_gripper hooks fire (Skills.set_gripper's default) +IDLE_EEF_M = 0.001 # the grasp point moved less than this over idle_s, with the gripper command unchanged + + +def _rotz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]) + + +def read_state(env, sk, frame="believed"): + """8-D state: eef position (world, m), eef orientation (axis-angle), two finger joints -- the dataset's layout. + frame="believed" applies the hidden calibration errors the way everything shown to an agent does (Skills.bias, + YawSkills.yaw_bias; robot_server._believed_pose); without such an error it equals frame="true".""" + import robosuite.utils.transform_utils as T + d, rob = env.sim.data, env.robots[0] + pos = np.array(d.site_xpos[rob.eef_site_id], np.float64) + quat = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw") + if frame == "believed": + pos = pos - np.asarray(sk.bias, np.float64) + beta = float(getattr(sk, "yaw_bias", 0.0)) + if beta: + quat = T.mat2quat(_rotz(-beta) @ T.quat2mat(quat)) + elif frame != "true": + raise ValueError(f"unknown proprioception frame {frame!r}") + grip = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64) + return np.concatenate([pos, np.asarray(T.quat2axisangle(quat), np.float64), grip]).astype(np.float32) + + +def task_prompt(task, inst): + """The instruction an agent gets for this instance (robot_server.instruction): some tasks build it per instance.""" + hook = getattr(task, "agent_instruction", None) + return hook(inst, "direct") if hook is not None else task.instruction + + +def read_obs(task, inst, res=256, frame="believed"): + """The observation a policy receives, in the openpi request format. Images are uint8 HWC, upright.""" + env = task.env + return {"observation/image": envs.render(env, C.mj_cam("agentview"), res), + "observation/wrist_image": envs.render(env, C.mj_cam("wrist"), res), + "observation/state": read_state(env, task.sk, frame), + "prompt": task_prompt(task, inst)} + + +class PolicyActuator: + """Applies one policy action to the task's Skills. a = (dpos, drot, gripper) in [-1, 1], scaled like Skills._act; + gripper > 0 closes (dataset convention: -1 open, +1 close).""" + + def __init__(self, task): + self.task = task + self.sk = task.sk + self.close = self.sk.grip > 0 + self.wait = 0 + + def _sync_yaw(self): + sk = self.sk + R = sk.eef_mat() @ sk.R0.T + sk.yaw = float(np.arctan2(R[1, 0], R[0, 0])) + + def step(self, action): + sk = self.sk + a = np.clip(np.asarray(action, np.float64), -1.0, 1.0) + close = bool(a[6] > 0) + if (sk.grip > 0) != self.close: # the task moved the jaws itself (l6_sequence_resume's emergency stop) + self.close, self.wait = sk.grip > 0, 0 + if getattr(self.task, "_latch", None) is not None: + # The task is driving the arm (env.step ignores the action) until "the current primitive has returned" and + # the arm is home. A policy has no primitives, so only the arm reaching home ends the routine. + sk.log.append(dict(prim="vla_step")) + elif close != self.close: + self.close, self.wait = close, GRIP_SETTLE + sk.grip = 1.0 if close else -1.0 + sk._act(a[:3] * sk.pos_scale, a[3:6] * ROT_SCALE, sk.grip) + self._sync_yaw() + if self.wait: + self.wait -= 1 + if not self.wait: + sk.set_gripper(self.close, steps=0) + + +def probe_success(task, inst, timeout=120.0): + """Would outcome() call this a success right now? outcome() steps the simulator and changes the task's monitors, so + it runs in a forked copy of this process; the attempt in the parent is untouched.""" + r, w = os.pipe() + pid = os.fork() + if pid == 0: + code = 1 + try: + os.close(r) + os.write(w, b"1" if task.outcome(inst)["success"] else b"0") + code = 0 + finally: + os._exit(code) + os.close(w) + ready = select.select([r], [], [], timeout)[0] + got = os.read(r, 1) if ready else b"" + os.close(r) + if not ready: + os.kill(pid, 9) + os.waitpid(pid, 0) + return got == b"1" + + +# ---------------------------------------------------------------- policies +class PolicyEnded(Exception): + """The policy has no more actions (a replayed recording ran out).""" + + +class ZeroPolicy: + """Holds still with the gripper open. Smoke tests only.""" + metadata = dict(policy="zero") + + def reset(self): + pass + + def infer(self, obs): + a = np.zeros((10, 7), np.float32) + a[:, 6] = -1.0 + return a + + +class ReplayPolicy: + """Replays recorded actions open loop, ignoring the observation. Used to test the evaluator against the recorded + verdicts (scripts/vla_acceptance.py).""" + metadata = dict(policy="replay") + + def __init__(self, actions, chunk=5, on_obs=None): + self.actions, self.chunk, self.on_obs = actions, int(chunk), on_obs + self.t = 0 + + def reset(self): + pass + + def infer(self, obs): + if self.t >= len(self.actions): + raise PolicyEnded() + if self.on_obs is not None: + self.on_obs(self.t, obs) + chunk = self.actions[self.t:self.t + self.chunk] + self.t += len(chunk) + return chunk + + +def _pack(o): + if isinstance(o, np.ndarray): + return {b"__ndarray__": True, b"data": o.tobytes(), b"dtype": o.dtype.str, b"shape": o.shape} + if isinstance(o, np.generic): + return {b"__npgeneric__": True, b"data": o.item(), b"dtype": o.dtype.str} + return o + + +def _unpack(o): + if b"__ndarray__" in o: + return np.ndarray(buffer=o[b"data"], dtype=np.dtype(o[b"dtype"]), shape=o[b"shape"]) + if b"__npgeneric__" in o: + return np.dtype(o[b"dtype"]).type(o[b"data"]) + return o + + +class WebsocketPolicy: + """Client of a policy server speaking the openpi websocket protocol (openpi scripts/serve_policy.py; StarVLA's + WebsocketPolicyServer, which wraps the reply in {"status", "data"}).""" + + def __init__(self, url, open_timeout=300): + from websockets.sync.client import connect + # No keepalive pings: the server cannot answer them while it runs a request, and the first one compiles the model + # for minutes on PPU. + self.ws = connect(url, compression=None, max_size=None, open_timeout=open_timeout, ping_interval=None) + self.metadata = msgpack.unpackb(self.ws.recv(), object_hook=_unpack) + + def reset(self): + pass + + def infer(self, obs): + self.ws.send(msgpack.packb(obs, default=_pack)) + out = self.ws.recv() + if isinstance(out, str): # openpi sends the server's traceback as text + raise RuntimeError(f"policy server error: {out}") + out = msgpack.unpackb(out, object_hook=_unpack) + if out.get("status") == "error": + raise RuntimeError(f"policy server error: {out.get('error')}") + return np.asarray(out.get("data", out)["actions"]) + + def close(self): + self.ws.close() + + +# ---------------------------------------------------------------- attempts +def budget_steps(task): + """Control steps per attempt: the agents' simulated-time budget (robot_server._sim_budget) at 20 Hz.""" + return int(round(3.0 * int(getattr(task, "agent_max_steps", 40)) * CONTROL_HZ)) + + +def run_attempt(task, inst, policy, max_steps, replan=5, res=256, frame="believed", idle_s=5.0, probe_every_s=5.0, + on_frame=None): + """Drive the policy until the budget or an idle arm ends the attempt. Returns timing and the first time a forked + outcome() check saw success (what an evaluator stopping at first success would have counted).""" + sk = task.sk + act = PolicyActuator(task) + step0 = sk.n_steps + idle_steps = int(idle_s * CONTROL_HZ) if idle_s else 0 + probe_steps = int(probe_every_s * CONTROL_HZ) if probe_every_s else 0 + infer_s, render_s = [], 0.0 + first_ok = None + end = "budget" + ref_pos, ref_close, ref_t = sk.eef_pos(), act.close, 0 + t = 0 + done = False + while t < max_steps and not done: + t0 = time.time() + obs = read_obs(task, inst, res, frame) + t1 = time.time() + try: + chunk = np.asarray(policy.infer(obs), np.float64) + except PolicyEnded: + end = "policy_ended" + break + t2 = time.time() + render_s += t1 - t0 + infer_s.append(t2 - t1) + if chunk.ndim != 2 or chunk.shape[1] < 7 or not np.isfinite(chunk[:, :7]).all(): + raise ValueError(f"bad action chunk from the policy: shape {chunk.shape}") + if on_frame is not None: + on_frame(t, obs) + for a in chunk[:replan]: + if t >= max_steps: + break + act.step(a[:7]) + t += 1 + if probe_steps and first_ok is None and t % probe_steps == 0 and probe_success(task, inst): + first_ok = t + if idle_steps: + if np.linalg.norm(sk.eef_pos() - ref_pos) > IDLE_EEF_M or act.close != ref_close: + ref_pos, ref_close, ref_t = sk.eef_pos(), act.close, t + elif t - ref_t >= idle_steps: + end, done = "idle", True + break + return dict(end=end, n_steps=int(sk.n_steps - step0), first_success_step=first_ok, + n_infer=len(infer_s), infer_s_mean=float(np.mean(infer_s)) if infer_s else None, + infer_s_p95=float(np.percentile(infer_s, 95)) if infer_s else None, render_s=round(render_s, 2)) + + +def run_session(task, inst, policy, k=3, max_steps=None, on_attempt=None, **kw): + """Up to k attempts on one instance with the benchmark's attempt transitions; stops at the first success or a + terminal failure. The policy gets no feedback and no history: a retry only differs by its sampling noise.""" + max_steps = budget_steps(task) if max_steps is None else int(max_steps) + protocol = getattr(task, "protocol", "cross") + attempts = [] + for attempt in range(1, k + 1): + if attempt == 1 or protocol == "cross": + task.reset_instance(inst) + policy.reset() + t0 = time.time() + rec = run_attempt(task, inst, policy, max_steps, **kw) + n0 = task.sk.n_steps + out = task.outcome(inst) + rec.update(attempt=attempt, success=bool(out["success"]), failure=out.get("failure"), detail=out.get("detail"), + terminal=bool(out.get("terminal")), judge_steps=int(task.sk.n_steps - n0), + wall_s=round(time.time() - t0, 2)) + rec["outcome"] = {key: v for key, v in out.items() if key not in ("feedback", "detail")} + attempts.append(rec) + if on_attempt is not None: + on_attempt(rec) + if rec["success"] or rec["terminal"]: + break + return attempts diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..fd5d4161433223e7960304fe49796145700f3b32 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-flash|high", + "fingerprint_sha256": "189cde183af8b300854d48b4f8952a6ebdf53462343e87c0062ad4c761943d9c", + "written": "2026-10-30 15:54:07", + "summary": { + "system_chars": 6047, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-da5f128c34a2_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-da5f128c34a2_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..215f2a44d4683a50d81e111ded443748426cbe7e --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-da5f128c34a2_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,27 @@ +{ + "key": "rpent_codex-generic-da5f128c34a2|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "6e63c24ad13895ebfbb0bc76a17ebbdc9765414a3f4351fe442480afa50b5ce9", + "written": "2026-10-21 05:11:12", + "summary": { + "developer_chars": 16979, + "top_tools": [ + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff.robot", + "mcp__lff.shell", + "mcp__lff.view_images", + "read_mcp_resource", + "request_user_input" + ], + "effort_in_request": "high", + "model_in_request": "gpt-6.1-sol", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + }, + "middle_fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c", + "rpent_prefix_sha256": "f0d0e0a62990cb7028bfb3889e49423b12635347aaddbda40e4d2fc4cb408e25", + "rpent_prefix_chars": 2789, + "anchor_status": "match" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..7a1c73ecae20ed503d7144d363aa4747887b4d34 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,18 @@ +{ + "key": "sensenova_codex-chatgpt-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9", + "written": "2026-10-26 07:08:06", + "summary": { + "report": "/mnt/cpfs/workspace/agentic-robotics/reports/robot_harness_subscription_resume_20261026/selfcheck_verified/selfcheck.json", + "checks": 10, + "framework": { + "commit": "b513a1c7289ab11eb844856588b64c378705c405", + "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823", + "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350", + "untracked": [ + "lff_integration/__init__.py", + "lff_integration/run.py" + ] + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/__init__.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_knock.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_knock.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7b568a618dbb97463644abff1cde34f06f6d37 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_knock.py @@ -0,0 +1,457 @@ +"""L2-A knock_restore: move the ketchup from the tray into the basket; everything else must stay on the tray. + +Constructed L2 event: the first time the ketchup is lifted off the tray (grasped and raised 3 cm), one of +its two neighbours on the tray is "knocked" off the tray and lands upright on the table beside it. Which +neighbour and to which side of the tray (left / right in the camera image) it falls are hidden per-instance +variables; only the scene *after* the failure shows which item is missing and where it is. The main task itself still succeeds, so an agent that stops after +the main task fails; it has to notice the side effect and put the item back (within-episode recovery). + +Protocols + within (default, `l2_knock_restore`) one episode; attempt 1 = the main task, every later attempt is one + corrective round chosen by the policy; the outcome (success + F2 text) is computed after each round. + cross (`l2_knock_restore_cross`) reset to the same instance between attempts; the knock happens again + on every attempt, so a learner must anticipate it. Validated strategy: restore the reported item + right after the main task. The rule also allows prevention (the knock only hits a neighbour that is + still within 12 cm of the ketchup's start spot), but picking a neighbour up in place is mostly blocked + by the tray's end wall (Panda hand), so prevention is not a validated strategy (see the task card). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TARGET = "ketchup_1" +NEIGHBOR_POOL = ("cream_cheese_1", "butter_1", "chocolate_pudding_1") +TRAY, BASKET = "wooden_tray_1", "basket_1" +PARK_XY = {"cream_cheese_1": (0.0, 1.2), "butter_1": (0.2, 1.2), "chocolate_pudding_1": (-0.2, 1.2)} + +# wooden_tray collision geometry in its body frame (from the LIBERO MJCF; long axis = body x) +TRAY_IN_X = (-0.128, 0.143) +TRAY_IN_Y = (-0.081, 0.072) +TRAY_OUT_X = (-0.142, 0.156) +TRAY_OUT_Y = (-0.088, 0.080) +TRAY_CX, TRAY_CY = 0.0075, -0.0045 # centre of the inner floor +TRAY_FLOOR = 0.0072 # floor top above the tray's lowest point +BASKET_IN = 0.060 # half size of the basket's inner floor (square, centred on the body origin) +BASKET_RIM = 0.150 # rim height above the basket's lowest point +BASKET_FLOOR = 0.017 # floor top above the basket's lowest point + +NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding"} +DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box"} +SIDES = ("left", "right") # side of the tray in the agentview image: left = world -y, right = world +y + + +def _qz(a): + return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]) + + +def _wrap_half(a): + """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)""" + return (a + np.pi / 2) % np.pi - np.pi / 2 + + +class KnockSkills(Skills): + """Skills with a hook called after every control step (used for the failure injection).""" + + def __init__(self, env, bias=None, recorder=None, hook=None): + super().__init__(env, bias=bias, recorder=recorder) + self.hook = hook + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if self.hook is not None: + self.hook() + + +@register_task +class KnockRestore(LFFTask): + name = "l2_knock_restore" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan") + protocol = "within" + instruction = "Move the ketchup from the tray into the basket. Everything else must stay on the tray." + instruction_indirect = ("Move the red bottle from the wooden tray into the wicker basket. " + "Everything else must stay on the tray.") + knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height + knock_radius = 0.12 # only a victim still within this distance of the ketchup's start spot is knocked + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # upright orientations (wxyz), fixed here so the task does not depend on LIBERO's placement convention: + # the ketchup mesh is modelled lying down; tray / basket / boxes are upright in their mesh frame + # (identity => tray long axis along world x, as the TRAY_* constants assume). + self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict} + self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5]) + self._inj = None + self.start = {} + + # ------------------------------------------------------------ scene + def make_bddl(self): + names = [TARGET, *NEIGHBOR_POOL, TRAY, BASKET] + objs = [] + for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid + x0 = -0.30 + 0.13 * (i % 3) + y0 = -0.25 + 0.25 * (i // 3) + objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + nb = [str(x) for x in rng.choice(NEIGHBOR_POOL, size=2, replace=False)] # [robot side, far side] + victim = int(rng.integers(2)) + side = str(rng.choice(SIDES)) + return dict(seed=int(seed), + tray_xy=[float(rng.uniform(-0.07, 0.01)), float(rng.uniform(-0.11, -0.08))], + tray_yaw=float(rng.uniform(-0.10, 0.10)), + basket_xy=[float(rng.uniform(-0.08, 0.02)), float(rng.uniform(0.24, 0.26))], + target_dx=float(rng.uniform(-0.01, 0.01)), + target_yaw=float(np.pi / 2 + rng.uniform(-0.2, 0.2)), + neighbors=nb, + nb_gap=[float(rng.uniform(0.066, 0.078)) for _ in range(2)], + nb_dy=[float(rng.uniform(-0.012, 0.012)) for _ in range(2)], + nb_yaw=[float(np.pi / 2 + rng.uniform(-0.15, 0.15)) for _ in range(2)], + # hidden variables of the injected failure + victim=nb[victim], side=side, + land_gap=float(rng.uniform(0.015, 0.035 if side == "right" else 0.04)), # wall -> object + land_off=float(rng.uniform(-0.025, 0.025)), # along the wall, from the victim's spot + land_dyaw=float(rng.uniform(-0.35, 0.35))) + + def _tray_frame(self): + p = envs.obj_pos(self.env, TRAY) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, TRAY)].reshape(3, 3) + return p, R + + def tray_yaw(self): + _, R = self._tray_frame() + return float(np.arctan2(R[1, 0], R[0, 0])) + + def tray_to_world(self, lx, ly): + p, R = self._tray_frame() + return p[:2] + R[:2, :2] @ np.array([lx, ly]) + + def world_to_tray(self, xy): + p, R = self._tray_frame() + return R[:2, :2].T @ (np.asarray(xy[:2]) - p[:2]) + + def place(self, name, xy, yaw, surface_z=envs.TABLE_Z): + """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z.""" + q = envs._quat_mul(_qz(yaw), self.q_up[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + env = self.env + envs.scale_mass(env, TRAY, 2.0) # heavy enough not to be dragged around by the gripper + envs.scale_mass(env, BASKET, 2.0) + for n in NEIGHBOR_POOL: + if n not in inst["neighbors"]: + self.place(n, PARK_XY[n], 0.0, surface_z=0.0) # unused neighbour: on the floor, out of view + self.place(TRAY, inst["tray_xy"], inst["tray_yaw"]) + self.place(BASKET, inst["basket_xy"], 0.0) + floor = envs.TABLE_Z + TRAY_FLOOR + ty = inst["tray_yaw"] + cx = TRAY_CX + inst["target_dx"] + self.place(TARGET, self.tray_to_world(cx, TRAY_CY), ty + inst["target_yaw"], floor) + for i, n in enumerate(inst["neighbors"]): # in a row along the tray: [robot side, ketchup, far side] + lx = cx + (-1 if i == 0 else 1) * inst["nb_gap"][i] + self.place(n, self.tray_to_world(lx, TRAY_CY + inst["nb_dy"][i]), ty + inst["nb_yaw"][i], floor) + env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.start = {n: self.footprint(n) for n in [TARGET] + inst["neighbors"]} + self._inj = dict(inst=inst, done=False, knocked=False, step=None) + self.sk = KnockSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, hook=self._knock_hook) + return self.sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """Measured pose summary of an object: AABB centre, yaw of the long horizontal axis, half sizes, z range. + Scripted policies use it as a stand-in for perception.""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + e = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, R, m.geom_aabb[g, 3:]) + _, R, half = best + horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2])) + + def _corners_tray(self, name): + """All collision-box corners of `name` in tray coordinates.""" + m, d = self.env.sim.model, self.env.sim.data + pts = [] + for g in envs.obj_geom_ids(self.env, name): + Rg = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3] + h = m.geom_aabb[g, 3:] + for sx in (-1, 1): + for sy in (-1, 1): + for sz in (-1, 1): + pts.append(self.world_to_tray(c + Rg @ (h * np.array([sx, sy, sz])))) + return np.array(pts) + + # ------------------------------------------------------------ failure injection + def _knock_hook(self): + st = self._inj + if st is None or st["done"] or self.sk is None: + return + if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift: + return + if not self.sk.holding(TARGET): + return + st["done"] = True + inst = st["inst"] + vxy = np.array(self.footprint(inst["victim"])["center"][:2]) + if np.linalg.norm(vxy - np.array(self.start[TARGET]["center"][:2])) > self.knock_radius: + return # the victim was moved out of the way beforehand: nothing happens + self.knock(inst) + st["knocked"] = True + st["step"] = self.sk.n_steps + + def knock(self, inst): + """Teleport the victim off the tray onto the table beside the long wall on `side`: upright, long axis + roughly perpendicular to the wall (so a gripper closing along the wall can pick it up), nearest point + `land_gap` from the wall's outer face, `land_off` along the wall from where it stood. + (The robot-side end of the tray was tried too: the end wall hides a flat box there from agentview.)""" + v, side = inst["victim"], inst["side"] + loc = self.world_to_tray(self.footprint(v)["center"]) + axis, sgn = 1, (1 if side == "right" else -1) + wall = TRAY_OUT_Y[1] if sgn > 0 else TRAY_OUT_Y[0] + self.place(v, self.tray_to_world(loc[0] + inst["land_off"], wall + sgn * 0.08), + self.tray_yaw() + np.pi / 2 + inst["land_dyaw"]) + pts = self._corners_tray(v) + near = pts[:, axis].min() if sgn > 0 else pts[:, axis].max() + shift = (wall + sgn * inst["land_gap"]) - near + _, R = self._tray_frame() + qa, _ = envs.free_joint_addr(self.env, v) + self.env.sim.data.qpos[qa:qa + 2] += R[:2, axis] * shift + self.env.sim.forward() + + # ------------------------------------------------------------ outcome + def where(self, name): + """Classify where an object is: 'tray', 'basket', 'gripper', 'table' or 'other'.""" + f = self.footprint(name) + c = np.array(f["center"]) + lt = self.world_to_tray(c) + if self.sk is not None and self.sk.holding(name) and f["zmin"] > envs.TABLE_Z + 0.02: + return "gripper", f + if (TRAY_IN_X[0] - 0.005 <= lt[0] <= TRAY_IN_X[1] + 0.005 and TRAY_IN_Y[0] - 0.005 <= lt[1] <= TRAY_IN_Y[1] + 0.005 + and f["zmin"] > envs.obj_min_z(self.env, TRAY) + 0.002): + return "tray", f + bp = envs.obj_pos(self.env, BASKET) + if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM: + return "basket", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def rel_to_tray(self, c): + """Where a point on the table is relative to the tray, in robot-centric words (never image left/right). + Distances are from the tray's outer edge to the object's centre.""" + lt = self.world_to_tray(c) + dy = lt[1] - TRAY_OUT_Y[1] if lt[1] > TRAY_OUT_Y[1] else (lt[1] - TRAY_OUT_Y[0] if lt[1] < TRAY_OUT_Y[0] else 0.0) + dx = lt[0] - TRAY_OUT_X[1] if lt[0] > TRAY_OUT_X[1] else (lt[0] - TRAY_OUT_X[0] if lt[0] < TRAY_OUT_X[0] else 0.0) + # robot-centric words (tray yaw is within +-0.1 rad, so tray axes ~ world axes): +y = robot's left, + # +x = forward (away from the robot) + parts = [] + if dy: + parts.append(f"{100 * abs(dy):.0f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'} of the tray") + if dx: + parts.append(f"{100 * abs(dx):.0f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'} " + f"of the tray") + return " and ".join(parts) if parts else "right next to the tray" + + def _describe(self, inst, loc, names): + t_loc = loc[TARGET][0] + tn = names[TARGET] + msgs = [] + if t_loc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "tray": f"The {tn} is still on the tray, not in the basket.", + "table": f"The {tn} is on the table ({self.rel_to_tray(loc[TARGET][1]['center'])}), " + "not in the basket."}.get(t_loc, f"The {tn} is not in the basket.")) + for n in inst["neighbors"]: + l, f = loc[n] + if l == "tray": + continue + msgs.append({"table": f"The {names[n]} is no longer on the tray: it is on the table " + f"{self.rel_to_tray(f['center'])}.", + "basket": f"The {names[n]} is no longer on the tray: it is in the basket.", + "gripper": f"The {names[n]} is no longer on the tray: it is still in the gripper."} + .get(l, f"The {names[n]} is no longer on the tray.")) + if not msgs: + msgs.append(f"The {tn} is in the basket and everything else is on the tray.") + return " ".join(msgs) + + def outcome(self, inst): + envs.settle(self.env, 30) + loc = {n: self.where(n) for n in [TARGET] + inst["neighbors"]} + off = [n for n in inst["neighbors"] if loc[n][0] != "tray"] + success = bool(loc[TARGET][0] == "basket" and not off) + return dict(success=success, + target_loc=loc[TARGET][0], + locations={n: l for n, (l, _) in loc.items()}, + off_tray=off, + footprints={n: f for n, (_, f) in loc.items()}, + knocked=bool(self._inj and self._inj["knocked"]), + detail=self._describe(inst, loc, NAMES), + detail_indirect=self._describe(inst, loc, DESCR)) + + def feedback(self, inst, out, level="F2", indirect=False): + """F0: nothing, F1: success flag, F2: which item is where. `indirect` uses descriptive names.""" + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions + def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.012, fp=None, + travel_z=1.15): + """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the + object bottom `clearance` above `support_z` at dest_xy. Moves between places at `travel_z` (above the + basket rim) so the arm does not sweep through the scene.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + h = f["zmax"] - f["zmin"] + gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side + if name == TARGET: + zg = f["zmax"] - 0.035 + else: + zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # fingertips reach ~1.3 cm below the grip site + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"]) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2) + sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.004, speed=0.25, + max_steps=120) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def main_task(self, fp=None): + """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it).""" + b = envs.obj_pos(self.env, BASKET) + floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR + self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp) + + def restore_spot(self, name, inst): + """A free spot on the tray for `name`: the ketchup's start spot or `name`'s own start spot, whichever + is further from everything else currently on the tray.""" + others = [n for n in [TARGET] + inst["neighbors"] if n != name and self.where(n)[0] == "tray"] + best, best_d = None, -1.0 + for cand in (TARGET, name): + xy = np.array(self.start[cand]["center"][:2]) + dmin = min([np.linalg.norm(xy - np.array(self.footprint(o)["center"][:2])) for o in others] + [1.0]) + if dmin > best_d + 0.01: + best, best_d = xy, dmin + return best + + def restore(self, name, inst): + """Put `name` back onto the tray (long axis across the tray, fingers closing along the tray).""" + xy = self.restore_spot(name, inst) + self.pick_place(name, xy, envs.TABLE_Z + TRAY_FLOOR, dest_yaw=self.tray_yaw() + np.pi / 2, carry_z=1.08, + clearance=0.013) + + def do(self, actions, inst): + for act in actions: + if act[0] == "ketchup_to_basket": + self.main_task(fp=act[1] if len(act) > 1 else None) + elif act[0] == "restore": + self.restore(act[1], inst) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _plan(self, kind, inst, a, history, rng): + """Actions of one attempt. JSON-friendly lists: ["ketchup_to_basket"] / ["restore", name].""" + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind")): + return [["ketchup_to_basket"]] + if kind == "oracle": # knows the victim: restores it right after the main task, without feedback + return [["ketchup_to_basket"], ["restore", inst["victim"]]] + if kind == "adaptive": # F2 says what is wrong; perception (measured pose) says where it is + last = history[-1]["outcome"] + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n] for n in last["off_tray"]] + if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp) + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["ketchup_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds. + After every attempt the outcome (success + F2 detail) is measured; stops at success + (oracle / naive stop after attempt 1).""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + for a in range(k): + actions = self._plan(kind, inst, a, history, rng) + self.do(actions, inst) + out = self.outcome(inst) + params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + +@register_task +class KnockRestoreCross(KnockRestore): + """Cross-attempt variant: reset to the same instance before every attempt; the knock happens again each + time. Learned behaviour: anticipate it (restore the reported item right after the main task).""" + name = "l2_knock_restore_cross" + protocol = "cross" + + def _plan(self, kind, inst, a, history, rng): + if kind == "adaptive" and a > 0: # remembers which item(s) fell last time; finds them by looking + fallen = sorted({n for h in history for n in h["outcome"]["off_tray"]}) + return [["ketchup_to_basket"]] + [["restore", n] for n in fallen] + return super()._plan(kind, inst, a, history, rng) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + actions = self._plan(kind, inst, a, history, rng) + self.do(actions, inst) + out = self.outcome(inst) + params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_restore_layout.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_restore_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..d926c362024dece29de84cdc1074180f7b196ceb --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_restore_layout.py @@ -0,0 +1,502 @@ +"""L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was. + +Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare +table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the +robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the +first frame. + +Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the +neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the +ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is +real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still +succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim +back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in +its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was). + +Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective +round chosen by the policy; the outcome (success + F2 text) is computed after each round. + +Scripted references + oracle knows the victim: right after the main task it puts the victim back at its saved start pose. + naive main task, then done. + adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are + out of place (Retrieve their saved poses) and puts them back (Utilize). + blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the + basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind. + nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows + which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..task_base import LFFTask, register_task + +TARGET = "ketchup_1" +BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1") +BASKET = "basket_1" +ITEMS = (TARGET,) + BOXES + +# LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer +BASKET_IN = 0.060 # half size of the inner floor +BASKET_RIM = 0.150 # rim height above the basket's lowest point +BASKET_FLOOR = 0.017 # floor top above the basket's lowest point +BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout) + +POS_TOL = 0.03 # success: box centre within 3 cm of its start +YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180) +STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start + +REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres +KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest +MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base +BASE_X = -0.66 +R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm) +GAP = 0.03 # free space between footprints (finger room) +SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table +SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached + +NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding", BASKET: "basket"} +DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box", BASKET: "wicker basket"} + + +def _qz(a): + return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]) + + +def _wrap_half(a): + """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _seg_dist(p, a, b): + """distance from point p to segment a-b (2D)""" + p, a, b = (np.asarray(v, float) for v in (p, a, b)) + ab = b - a + t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0) + return float(np.linalg.norm(p - (a + t * ab))) + + +def _in_rect(xy, r): + return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3] + + +def _reach_ok(xy): + return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH + + +@register_task +class RestoreLayout(LFFTask): + name = "l2_restore_layout" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it " + "is now, in the same position and orientation.") + instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay " + "exactly where it is now, in the same position and orientation.") + knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down; + # basket and boxes are upright in their mesh frame + self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict} + self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5]) + self._inj = None + self.start = {} + self._home = None + # per-control-step monitor on env.step: also sees attempts driven by the agent harness + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._inj is not None: + self._knock_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + names = [*ITEMS, BASKET] + objs = [] + for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid + x0 = -0.30 + 0.13 * (i % 3) + y0 = -0.25 + 0.25 * (i // 3) + objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)]) + k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)]) + victim = str(rng.choice(BOXES)) + others = [b for b in BOXES if b != victim] + a_v = rng.uniform(0, 2 * np.pi) + r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02) + pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])} + ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim]) + for o in others: + if not ok: + break + for _ in range(200): + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if not _reach_ok(p): + continue + if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP: + continue + if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET): + continue + pos[o] = p + break + else: + ok = False + if not ok: + continue + if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS): + continue + # the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign) + ang = a_v + rng.uniform(-np.radians(35), np.radians(35)) + dist = rng.uniform(0.09, 0.14) + u = np.array([np.cos(ang), np.sin(ang)]) + end = pos[victim] + dist * u + if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)): + continue + if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03: + continue + # the path and the resting spot keep clear of the other boxes (finger room around the victim too) + if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others): + continue + if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others): + continue + if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP: + continue + turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80))) + return dict(seed=int(seed), + basket_xy=basket.round(4).tolist(), + xy={n: pos[n].round(4).tolist() for n in ITEMS}, + yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES}, + TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))}, + # hidden variables of the injected failure + victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn, + knock_end=end.round(4).tolist()) + raise RuntimeError("could not sample a layout") + + def place(self, name, xy, yaw, surface_z=envs.TABLE_Z): + """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only).""" + q = envs._quat_mul(_qz(yaw), self.q_up[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock) + self.place(BASKET, inst["basket_xy"], 0.0) + for n in ITEMS: + self.place(n, inst["xy"][n], inst["yaw"][n]) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self._inj = None + sk = super().reset_instance(inst, recorder) + self.start = {n: self.footprint(n) for n in ITEMS} + self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0) + self._home = sk.eef_pos() + return sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range. + Scripted policies use it as a stand-in for perception.""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + e = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, R, m.geom_aabb[g, 3:]) + _, R, half = best + horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2])) + + def body_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + return float(np.arctan2(R[1, 0], R[0, 0])) + + # ------------------------------------------------------------ failure injection (physical knock) + def _knock_step(self): + st = self._inj + if st["done"]: + if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps) + self._spin(st) + return + if self.sk is None: + return + if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift: + return + if not self.sk.holding(TARGET): + return + st["done"] = True + inst = st["inst"] + v = inst["victim"] + if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL: + return # the victim was moved beforehand: nothing happens + qa, da = envs.free_joint_addr(self.env, v) + v0 = np.sqrt(inst["knock_dist"] / SLIDE_K) + dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])]) + d = self.env.sim.data + d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0] + st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"], + spin_steps=6) + self._spin(st) + + def _spin(self, st): + v = st["inst"]["victim"] + _, da = envs.free_joint_addr(self.env, v) + turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0 + rest = st["spin_left"] - turned + st["spin_steps"] -= 1 + if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]): + st["spin_steps"] = 0 + return + # measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short + w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W)) + self.env.sim.data.qvel[da + 5] = np.sign(rest) * w + + # ------------------------------------------------------------ outcome + def where_target(self): + """'basket', 'gripper', 'table' or 'other' for the ketchup.""" + f = self.footprint(TARGET) + c = np.array(f["center"]) + if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02: + return "gripper", f + bp = envs.obj_pos(self.env, BASKET) + if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM: + return "basket", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def box_state(self, name): + """Pose error of a box w.r.t. its start pose and where it is.""" + f = self.footprint(name) + s = self.start[name] + c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2]) + dpos = float(np.linalg.norm(c - c0)) + dyaw = _wrap_half(f["yaw"] - s["yaw"]) + held = bool(self.sk is not None and self.sk.holding(name)) + upright = envs.obj_upright_cos(self.env, name) > 0.9 + on_table = f["zmin"] < envs.TABLE_Z + 0.01 + bp = envs.obj_pos(self.env, BASKET) + loc = ("gripper" if held else + "basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else + "table" if on_table and upright else + "table_tipped" if on_table else "other") + ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL) + return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"], + offset=(c - c0).tolist()) + + @staticmethod + def _offset_words(off, dyaw): + """robot-centric words for a displacement (current - start) and turn (for the offset tier only)""" + parts = [] + if abs(off[0]) >= 0.005: + parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}") + if abs(off[1]) >= 0.005: + parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}") + s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot" + if abs(dyaw) >= np.radians(3): + s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)" + return s + + def _describe(self, tloc, boxes, names, offset=False): + tn = names[TARGET] + msgs = [] + if tloc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "table": f"The {tn} is on the table, not in the basket."} + .get(tloc, f"The {tn} is not in the basket.")) + for n in BOXES: + b = boxes[n] + if b["ok"]: + continue + if b["loc"] == "gripper": + msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.") + continue + if b["loc"] == "basket": + msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.") + continue + if b["loc"] == "table_tipped": + msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.") + continue + if b["loc"] != "table": + msgs.append(f"The {names[n]} is not where it was at the start.") + continue + what = [] + if b["dpos"] > POS_TOL: + what.append("position") + if abs(b["dyaw"]) > YAW_TOL: + what.append("orientation") + m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)." + if offset: + m += f" It is {self._offset_words(b['offset'], b['dyaw'])}." + msgs.append(m) + if not msgs: + msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.") + return " ".join(msgs) + + def outcome(self, inst): + envs.settle(self.env, 30) + tloc, tf = self.where_target() + boxes = {n: self.box_state(n) for n in BOXES} + moved = [n for n in BOXES if not boxes[n]["ok"]] + success = bool(tloc == "basket" and not moved) + return dict(success=success, target_loc=tloc, moved=moved, + boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4), + dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()}, + knocked=bool(self._inj and self._inj["knocked"]), + detail=self._describe(tloc, boxes, NAMES), + detail_indirect=self._describe(tloc, boxes, DESCR), + detail_offset=self._describe(tloc, boxes, NAMES, offset=True)) + + def feedback(self, inst, out, level="F2", indirect=False, offset=False): + """F0: nothing, F1: success flag, F2: which item is out of place (never where it was). + offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric + words -- this externalises the memory and is not the default.""" + if level == "F2": + key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail") + out = dict(out, detail=out.get(key, out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only) + def go_home(self): + """End of an attempt: lift the arm out of the camera's way.""" + sk = self.sk + p = sk.eef_pos() + sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + sk.move_to(self._home) + + def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None, + travel_z=1.15): + """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the + object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + h = f["zmax"] - f["zmin"] + gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side + if name == TARGET: + zg = f["zmax"] - 0.035 + else: + zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"]) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2) + sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2, + max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def main_task(self, fp=None): + """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it).""" + b = envs.obj_pos(self.env, BASKET) + floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR + self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp) + + def restore(self, name, pose): + """Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw).""" + self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05, + clearance=0.004) + + def do(self, actions, inst): + for act in actions: + if act[0] == "ketchup_to_basket": + self.main_task(fp=act[1] if len(act) > 1 else None) + elif act[0] == "restore": # ["restore", name, pose] + self.restore(act[1], act[2]) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _guess_pose(self, name, rng): + """nomem control: a random free spot within 15 cm of where the box is now, random yaw.""" + cur = np.array(self.footprint(name)["center"][:2]) + others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name] + for _ in range(200): + r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi) + p = cur + r * np.array([np.cos(a), np.sin(a)]) + if _in_rect(p, KNOCK_REGION) and _reach_ok(p) and all(np.linalg.norm(p - o) > 2 * R_BOX + 0.01 for o in others): + return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + + def _plan(self, kind, inst, a, history, rng, memory): + """Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose].""" + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")): + return [["ketchup_to_basket"]] + if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory) + return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]] + last = history[-1]["outcome"] + if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n, memory[n]] for n in last["moved"]] + if kind == "nomem": # F2 but no start frame: guesses + acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]] + return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]] + if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp) + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["ketchup_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save + for a in range(k): + actions = self._plan(kind, inst, a, history, rng, memory) + self.do(actions, inst) + self.go_home() + out = self.outcome(inst) + params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else + [x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)] + for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l3_wall.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l3_wall.py new file mode 100644 index 0000000000000000000000000000000000000000..85c1d73ef0922858d68710e01a64b66eafeb9650 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l3_wall.py @@ -0,0 +1,501 @@ +"""L3-A wall_flush: a flat long box lies flush against a low fixed wall; put it on the plate. + +Why the prior fails: the only graspable dimension of the box is its 6 cm width (the Panda opens to +~7.9 cm; the box is 16 cm long). Grasping across the width needs one finger between the box and the +wall, but the box touches the wall (gap 0-3 mm) along its whole length, so that finger lands on top of +the wall (4.5 cm high; the box is 3.5 cm high) and the gripper closes above the box. Retrying the same +grasp with small variations fails the same way. + +What must be learned from the failure: this grasp is infeasible in this state -> change the manipulation +mode: first slide the box along the wall until it clears the wall's end (non-prehensile pre-grasp +manipulation), then grasp it across its width. + +Layout: the wall runs along y (left-right as seen from the robot). Randomised per instance: wall length +(24-30 cm), wall position, whether the wall is on the far (+x) or near (-x) side of the box, where the +box sits along the wall (always fully alongside it, >= 2 cm of wall beyond each end), box-wall gap +(0-3 mm, below camera resolution), plate position (on the open side of the box). + +Protocols: `l3_wall_flush` (cross: reset to the same instance before every attempt) and +`l3_wall_flush_within` (one episode; each attempt starts from wherever the previous one left things). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task + +BOX_HALF = np.array([0.03, 0.08, 0.0175]) # 6 (x) x 16 (y) x 3.5 cm; long axis along y +WALL_HALF_T = 0.015 # 3 cm thick (x) +WALL_HALF_H = 0.0225 # 4.5 cm high +WALL_HALF_L_MAX = 0.16 # registered half length (y); shrunk per instance +WALL_MU = 2.0 # wall sliding friction (MuJoCo uses the max of the two geoms: finger-wall and box-wall contacts get 2.0) +BOX_DENSITY = 1500.0 # -> 0.50 kg +GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open +FINGER_NEEDS = 0.012 # free space a finger needs beside the box (pad + finger shell), measured +Z_GRASP = envs.TABLE_Z + 0.022 # gripper-site height for grasping (pads cover 1.7-3.4 cm above the table) +Z_PUSH = envs.TABLE_Z + 0.022 # site height while pushing: finger tips 1.2 cm above the table, hand ~7 mm above the wall +PUSH_SPEED = 0.08 +FINGER_BELOW_SITE = 0.0096 # finger tips are this far below the gripper site (measured) +PLACE_Z = envs.TABLE_Z + 0.048 # site height at release over the plate (box bottom ~8 mm above the rim) + + +def _wrap_half_pi(a): + """wrap to [-pi/2, pi/2): box and parallel gripper are both symmetric under 180 deg""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return _wrap_half_pi(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +@register_task +class WallFlush(LFFTask): + name = "l3_wall_flush" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the long box on the plate." + instruction_indirect = "Put the flat blue block onto the round dish." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + # Per-control-step event monitor. It wraps env.step so that it also sees attempts driven by the agent + # harness (whose tools call Skills / env.step directly), not only the scripted `execute`. + orig_step = self.env.step + + def step(action): + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ scene + def make_bddl(self): + # 0.5 kg box and a grippy wall top (mu 2): with mu 1 / 0.13 kg an *unguarded* press onto the wall top (plain + # move_to down, as an agent would do) let the finger slide ~5 cm off the wall and, on the wall-far side, + # flipped the box onto its 3.5 cm side (10/60 instances) -- an accidental, graspable state (see task card). + box = register_generated("LffFlushBox", box_xml("lff_flush_box", BOX_HALF, (0.12, 0.30, 0.80, 1.0), + density=BOX_DENSITY)) + wall = register_generated("LffFlushWall", box_xml("lff_flush_wall", (WALL_HALF_T, WALL_HALF_L_MAX, WALL_HALF_H), + (0.62, 0.50, 0.36, 1.0), density=1000, + friction=(WALL_MU, 0.005, 0.0001)), free=False) + # regions only need to be valid and far apart; the layout is overridden in apply_instance + objs = [("box_1", box, "box_region", (-0.21, -0.26, -0.19, -0.24)), + ("plate_1", "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26))] + fx = [("wall_1", wall, "wall_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _wall(self): + """(root body id, geom ids) of the wall fixture""" + if not hasattr(self, "_wall_cache"): + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict["wall_1"].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._wall_cache = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]) + return self._wall_cache + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + side = int(rng.choice([-1, 1])) # +1: wall on the far (+x) side of the box, -1: near (-x) side + wall_hl = float(rng.uniform(0.12, 0.15)) + wall_y = float(rng.uniform(-0.06, 0.06)) + u_max = wall_hl - BOX_HALF[1] - 0.02 # >= 2 cm of wall beyond each end of the box + box_y = wall_y + float(rng.uniform(-u_max, u_max)) + gap = float(rng.uniform(0.0, 0.003)) + box_x = float(rng.uniform(-0.12, -0.04)) if side > 0 else float(rng.uniform(-0.20, -0.12)) + wall_x = box_x + side * (WALL_HALF_T + BOX_HALF[0] + gap) + plate_xy = [box_x - side * float(rng.uniform(0.16, 0.18)), box_y + float(rng.uniform(-0.06, 0.06))] + return dict(seed=int(seed), side=side, wall_hl=wall_hl, wall_xy=[wall_x, wall_y], gap=gap, + box_xy=[box_x, box_y], plate_xy=plate_xy) + + def apply_instance(self, inst): + m = self.env.sim.model + bid, geoms = self._wall() + for g in geoms: # shrink the (collision + visual) wall boxes to this instance's length + m.geom_size[g, 1] = inst["wall_hl"] + m.body_pos[bid] = [inst["wall_xy"][0], inst["wall_xy"][1], envs.TABLE_Z + WALL_HALF_H] + m.body_quat[bid] = [1, 0, 0, 0] + bx, by = inst["box_xy"] + envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF[2] + 0.0005]) + self._move_keep_orientation("plate_1", inst["plate_xy"]) + + def _move_keep_orientation(self, name, xy, clearance=0.002): + """Move a LIBERO mesh object to xy keeping the orientation LIBERO's sampler gave it at reset (that + orientation is the upright one; see task card), lowest collision point `clearance` above the table.""" + qa, da = envs.free_joint_addr(self.env, name) + d = self.env.sim.data + d.qpos[qa:qa + 2] = xy + d.qvel[da:da + 6] = 0.0 + self.env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance) + self.env.sim.forward() + + # ------------------------------------------------------------ perception stand-in + def observe(self): + """What a perfect perceiver reads off the camera image: box centre / yaw, the wall's footprint and the + plate centre. (Not the box-wall gap: 0-3 mm is below the camera resolution.)""" + bid, geoms = self._wall() + m = self.env.sim.model + wx, wy = m.body_pos[bid][:2] + hl = m.geom_size[geoms[0], 1] + b = envs.obj_pos(self.env, "box_1") + return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + wall_x=float(wx), wall_y=(float(wy - hl), float(wy + hl)), + plate_xy=envs.obj_pos(self.env, "plate_1")[:2].copy()) + + def _gap_now(self, o=None): + o = o or self.observe() + return float(abs(o["box_xy"][0] - o["wall_x"]) - WALL_HALF_T - BOX_HALF[0]) + + def alongside_wall(self, o=None): + """box (centre) still beside the wall and too close to it for a finger""" + o = o or self.observe() + return bool(o["wall_y"][0] < o["box_xy"][1] < o["wall_y"][1] and self._gap_now(o) < FINGER_NEEDS) + + # ------------------------------------------------------------ contacts + def _finger_landings(self): + """Surfaces the finger tips are resting on: contacts between a finger and a non-robot geom whose normal is + mostly vertical (a tip landing on a top surface). Returns {label: contact z}, label in 'wall' | 'box' | + 'plate' | 'table' | 'other'. Side contacts (a finger brushing the box's side, the push stroke) are ignored.""" + m, d = self.env.sim.model, self.env.sim.data + if not hasattr(self, "_geom_groups"): + fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")} + robot = set(envs.robot_geom_ids(self.env)) + self._geom_groups = (fg, robot, set(self._wall()[1]), set(envs.obj_geom_ids(self.env, "box_1")), + set(envs.obj_geom_ids(self.env, "plate_1"))) + fg, robot, wall, box, plate = self._geom_groups + out = {} + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in fg and c.geom2 not in robot: + other = c.geom2 + elif c.geom2 in fg and c.geom1 not in robot: + other = c.geom1 + else: + continue + if abs(c.frame[2]) < 0.7: + continue + if other in wall: + lab = "wall" + elif other in box: + lab = "box" + elif other in plate: + lab = "plate" + else: + lab = "table" if (m.geom_id2name(other) or "").startswith("table") else "other" + out.setdefault(lab, float(c.pos[2])) + return out + + def _finger_landing(self): + hits = self._finger_landings() + for lab in ("wall", "box", "plate", "table", "other"): + if lab in hits: + return lab + return None + + # ------------------------------------------------------------ event monitor (what happened in this attempt) + def _closing_axis(self): + m, d = self.env.sim.model, self.env.sim.data + jid = m.joint_name2id(self.env.robots[0].gripper.joints[0]) + a = d.xaxis[jid][:2] + return a / max(np.linalg.norm(a), 1e-9) + + def _snapshot(self, contact_z): + """state at the moment a finger lands on something""" + o = self.observe() + e = self.sk.eef_pos() if self.sk is not None else self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id] + bx = self.env.sim.data.body_xmat[envs.body_id(self.env, "box_1")].reshape(3, 3)[:2, 0] # box short axis + cosang = abs(float(self._closing_axis() @ (bx / max(np.linalg.norm(bx), 1e-9)))) + yaw_err = float(np.arccos(np.clip(cosang, 0.0, 1.0))) + wy0, wy1 = o["wall_y"] + return dict(contact_z=float(contact_z - envs.TABLE_Z), eef=[float(e[0]), float(e[1]), float(e[2])], + box_xy=[float(o["box_xy"][0]), float(o["box_xy"][1])], gap=self._gap_now(o), + alongside=self.alongside_wall(o), yaw_err=yaw_err, + span=float(2 * (BOX_HALF[0] * np.cos(yaw_err) + BOX_HALF[1] * np.sin(yaw_err))), + box_offset=float(np.linalg.norm(np.array(e[:2]) - o["box_xy"])), + # signed wall length beside the gripper towards each end (< 0: gripper is past that end) + wall_left={1: float(wy1 - e[1]), -1: float(e[1] - wy0)}) + + def _start_monitor(self): + b = envs.obj_pos(self.env, "box_1") + self._mon = dict(start_xy=b[:2].copy(), rest_z=float(b[2]), max_dz=0.0, wall_hit=None, box_top_hit=None, + prev=set()) + + def _monitor_step(self): + mon = self._mon + hits = self._finger_landings() + mon["max_dz"] = max(mon["max_dz"], float(envs.obj_pos(self.env, "box_1")[2] - mon["rest_z"])) + for lab, key in (("wall", "wall_hit"), ("box", "box_top_hit")): + if lab in hits and lab not in mon["prev"]: # onset of a landing; keep the latest one + mon[key] = self._snapshot(hits[lab]) + mon["prev"] = set(hits) + + def _finger_front(self, direction): + """how far the (closed) fingers stick out from the gripper site along `direction` (xy unit vector)""" + m, d = self.env.sim.model, self.env.sim.data + e = self.sk.eef_pos() + best = 0.0 + for g in range(m.ngeom): + if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7: + continue + mid = m.geom_dataid[g] + v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]] + w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e + best = max(best, float((w[:, :2] @ direction).max())) + return best + + # ------------------------------------------------------------ primitives used by the scripted policies + def _yaw_near(self, yaw): + """The parallel gripper (and the box) are symmetric under 180 deg, so pick yaw + k*pi closest to the current + commanded yaw: the OSC's axis-angle error is ill-defined at 180 deg and a half-turn request can flip the + hand over (measured: in the within protocol it twisted the arm into a state it never recovered from).""" + cands = [yaw + k * np.pi for k in (-1, 0, 1)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + """Skills.move_to stops on position only; hold until the commanded yaw has actually been reached.""" + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=60): + """Straight-line descent that stops as soon as a finger lands on a surface above the target (the way a + grasp approach with contact sensing behaves). Without it, the OSC keeps pressing the finger into the + wall top and the compliant arm slides ~2 cm sideways off it. Returns what the finger landed on.""" + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + sk.bias + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + landed = None + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + hit = self._finger_landing() + if hit is not None and sk.eef_pos()[2] > tgt[2] + 0.005: + landed = hit + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + return landed + + def push_along_wall(self, end, margin): + """Closed gripper (fingers side by side across the box) behind the box's trailing end face; slide the + box along y (towards the wall's +y end if end=+1, -y end if end=-1) until the box centre is `margin` + beyond that end of the wall.""" + sk, o = self.sk, self.observe() + bx, by = o["box_xy"] + wall_end = o["wall_y"][1] if end > 0 else o["wall_y"][0] + dist = float(np.clip(end * (wall_end + end * margin - by), 0.0, 0.32)) + yaw = self._yaw_near(o["box_yaw"] + np.pi / 2) # fingers close along the box's short axis + u = np.array([0.0, float(end)]) + sk.set_gripper(True, steps=6) + sk.move_to([bx, by - end * (BOX_HALF[1] + 0.06), Z_PUSH + 0.10], yaw=yaw) + self._align() + front = self._finger_front(u) + face = by - end * BOX_HALF[1] + start_y = face - end * (front + 0.035) + stop_y = face + end * (dist - front) + sk.move_to([bx, start_y, Z_PUSH + 0.10]) + sk.move_to([bx, start_y, Z_PUSH], tol=0.003) + sk.move_to([bx, stop_y, Z_PUSH], speed=PUSH_SPEED, tol=0.005, max_steps=300) + sk.hold(3) + sk.move_to([bx, stop_y, Z_PUSH + 0.10], speed=0.2) + + def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0): + """Top-down grasp across the box's width at the observed box centre (+ offsets), lift; if the box is + held, carry it to the plate and release it there.""" + sk, o = self.sk, self.observe() + gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy + yaw = self._yaw_near(o["box_yaw"] + np.pi / 2 + dyaw) + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw) + self._align() + self._guarded_descent([gx, gy, Z_GRASP]) + sk.set_gripper(True, steps=15) + z0 = envs.obj_pos(self.env, "box_1")[2] + sk.move_to([gx, gy, Z_GRASP + 0.15], speed=0.25) + if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.08): + sk.set_gripper(False, steps=8) + return + px, py = o["plate_xy"] + sk.move_to([px, py, PLACE_Z + 0.10]) + sk.move_to([px, py, PLACE_Z], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([px, py, PLACE_Z + 0.10]) + + def execute(self, inst, params): + if params["mode"] == "push_grasp": + self.push_along_wall(params["end"], params["margin"]) + self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0)) + + # ------------------------------------------------------------ outcome / F2 feedback + def outcome(self, inst): + """Success = box resting flat on the plate, released. The F2 text is built from the event monitor, so it + describes agent-driven attempts as well as scripted ones. Ends the current monitoring segment.""" + envs.settle(self.env, 30) + env, mon = self.env, self._mon or {} + b = envs.obj_pos(env, "box_1") + p = envs.obj_pos(env, "plate_1") + dxy = float(np.linalg.norm(b[:2] - p[:2])) + flat = abs(envs.obj_upright_cos(env, "box_1")) > 0.9 + held = bool(self.sk.holding("box_1")) if self.sk is not None else False + on_plate = envs.contacts_between(env, envs.obj_geom_ids(env, "box_1"), envs.obj_geom_ids(env, "plate_1")) + success = bool(dxy < 0.05 and envs.obj_min_z(env, "box_1") > envs.TABLE_Z + 0.004 and flat and not held + and on_plate) + lifted = mon.get("max_dz", 0.0) > 0.03 + start = mon.get("start_xy", b[:2]) + moved_y = float(b[1] - start[1]) + pushed = (not lifted) and abs(moved_y) > 0.02 + wall_hit, top_hit = mon.get("wall_hit"), mon.get("box_top_hit") + side_txt = "far (+x)" if inst["side"] > 0 else "near (-x)" + mode, parts, wall_left = "success", [], None + if success: + parts.append("The box is resting on the plate.") + else: + if pushed: + parts.append(f"The box was pushed {100 * abs(moved_y):.1f} cm along the wall (towards " + f"{'+y' if moved_y > 0 else '-y'}).") + if lifted: + if held: + mode = "still_held" + parts.append("The box is still in the gripper; it was not released on the plate.") + elif on_plate: + mode = "placed_off" + parts.append(f"The box was put on the plate but is not resting on it properly ({100 * dxy:.1f} cm " + f"from the plate centre{'' if flat else ', tilted'}).") + else: + mode = "placed_off" + parts.append(f"The box was lifted but ended on the table, {100 * dxy:.1f} cm from the plate " + f"centre.") + elif wall_hit is not None: + mode = "wall_blocked" + parts.append( + f"The gripper could not get around the box: the finger on the wall side ({side_txt} side) came down " + f"on top of the wall, {100 * wall_hit['contact_z']:.1f} cm above the table, which is higher than " + f"the top of the box ({200 * BOX_HALF[2]:.1f} cm), so the box was not grasped or lifted. Where the " + f"gripper came down, the box is flush against the wall (gap {1000 * max(wall_hit['gap'], 0):.0f} mm).") + if pushed: + e = 1 if moved_y > 0 else -1 + wall_left = wall_hit["wall_left"][e] + if wall_left > 0: + parts.append(f"The wall still continues {100 * wall_left:.1f} cm beyond the grasp point in the " + f"{'+y' if e > 0 else '-y'} direction.") + else: + parts.append(f"The grasp point was only {100 * -wall_left:.1f} cm past the " + f"{'+y' if e > 0 else '-y'} end of the wall, so the finger still came down on it.") + elif top_hit is not None: + mode = "box_top" + if top_hit["yaw_err"] > np.radians(30): + parts.append(f"The fingers came down on top of the box: along the gripper's closing direction the " + f"box measures {100 * top_hit['span']:.0f} cm, more than the {100 * GRIP_OPEN:.1f} cm " + f"maximum opening. The box was not lifted.") + else: + parts.append(f"A finger came down on top of the box (the gripper was {100 * top_hit['box_offset']:.1f}" + f" cm from the box centre), so the box was not grasped or lifted.") + else: + mode = "not_lifted" + parts.append(f"The box was not lifted; it is {100 * dxy:.1f} cm from the plate centre.") + if b[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The box fell off the table.") + elif not flat and mode != "placed_off": + parts.append("The box is no longer lying flat.") + out = dict(success=success, mode=mode, plate_dist=dxy, box_xy=[float(b[0]), float(b[1])], lifted=bool(lifted), + pushed_y=moved_y, alongside_wall=self.alongside_wall(), wall_left=wall_left, + terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts)) + self._start_monitor() # next segment (within protocol) starts here + return out + + # ------------------------------------------------------------ scripted references + def _nearer_end(self): + o = self.observe() + by = o["box_xy"][1] + return 1 if (o["wall_y"][1] - by) < (by - o["wall_y"][0]) else -1 + + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045) + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)), + dyaw=float(rng.normal(0, 0.12))) + + def adapt_params(self, inst, history): + """Uses the F2 measurements of the previous attempt: + wall_blocked / box_top on a direct grasp -> switch mode: slide the box out past the nearer wall end + (wall ends read off the image), then grasp; + wall_blocked after a push -> push further by the reported remaining wall length + 2 cm; + anything else (missed, dropped, ...) -> keep the strategy (the state is re-observed).""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] != "push_grasp": + if out["mode"] in ("wall_blocked", "box_top"): + return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045) + return dict(prm) + if out["mode"] == "wall_blocked": + return dict(mode="push_grasp", end=prm["end"], + margin=float(prm["margin"] + max(out["wall_left"] or 0.0, 0.0) + 0.02)) + return dict(prm) + + # ------------------------------------------------------------ protocols + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if self.protocol != "within": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + for a in range(k): + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + if params["mode"] == "push_grasp" and not self.alongside_wall(): + params = dict(params, mode="grasp") # already pushed clear in an earlier attempt of this episode + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + +@register_task +class WallFlushWithin(WallFlush): + name = "l3_wall_flush_within" + protocol = "within" diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l3_wide.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l3_wide.py new file mode 100644 index 0000000000000000000000000000000000000000..4983d8290676ef823eb1ad9710447698e6bdf2d6 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l3_wide.py @@ -0,0 +1,435 @@ +"""L3-B too_wide_push: a box that is slightly too wide for the gripper must be pushed into a square on the table. + +Why the prior fails: the box looks like an ordinary graspable box (narrow side 8.3-8.9 cm, long side 11-13 cm, +4 cm high), but the Panda's fingers open to only 7.9 cm. A top-down grasp across the narrow side therefore puts +both fingers on top of the box; closing them grips nothing. Across the long side it is worse, and retrying the +same grasp with small variations fails the same way. A difference of 4-10 mm between the box and the maximum +opening is not readable from the camera images, and the agent is not told the gripper's opening. + +What must be learned from the failure: this object cannot be picked up at all -> change the manipulation mode: +close the gripper and push the box (there is no push primitive: the agent closes the gripper, lowers it beside +the box and moves it along the table with move_to), keeping the box from turning, until it lies completely +inside the square. + +Layout (randomised per instance): box size, position and yaw (long side roughly along x or along y, +-10 deg), +target square (18 x 18 cm inner, axis-aligned) 16-22 cm away along one world axis (forward, backward, left or +right) with a lateral offset of up to 3 cm. + +Protocol: cross (reset to the same instance before every attempt), k = 5. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task +from .l5_slide import square_frame_xml + +BOX_HALF_MAX = (0.07, 0.05, 0.02) # registered size (x = long, y = narrow, z); shrunk per instance +BOX_HALF_Z = 0.02 # 4 cm high +BOX_MASS = 0.40 +BOX_MU = 0.6 # box sliding friction (priority over the table's 1.0 and the fingers') +GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open +SQ_IN = 0.09 # target square: 18 cm inner side +SQ_LINE = 0.008 +Z_GRASP = envs.TABLE_Z + 0.022 # site height of a normal top-down grasp of a 4 cm box (pads 1.7-3.4 cm above table) +Z_PUSH = envs.TABLE_Z + 0.02 # site height while pushing: finger tips ~1 cm above the table +PUSH_SPEED = 0.08 +FRONT_GAP = 0.03 # where a push stroke starts: this far behind the box face + + +def _wrap_pi(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +DIRS = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)} + + +@register_task +class TooWidePush(LFFTask): + name = "l3_too_wide_push" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the brown box completely inside the green square marked on the table." + instruction_indirect = "Put the cardboard-coloured package completely inside the green outlined area on the table." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + self.inst = None + orig_step = self.env.step + + def step(action): # per-control-step event monitor (also sees agent-driven attempts) + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffWideBox", box_xml("lff_wide_box", BOX_HALF_MAX, (0.62, 0.45, 0.28, 1.0), + density=500)) + sq = register_generated("LffWideSquare", square_frame_xml("lff_wide_square", inner_half=SQ_IN, line_w=SQ_LINE), + free=False) + objs = [("box_1", box, "box_region", (-0.11, -0.21, -0.09, -0.19))] + fx = [("square_1", sq, "square_region", (-0.01, 0.19, 0.01, 0.21))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _box_geoms(self): + if not hasattr(self, "_bg"): + m = self.env.sim.model + bid = envs.body_id(self.env, "box_1") + self._bg = [g for g in range(m.ngeom) if m.geom_bodyid[g] == bid] + return self._bg + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + narrow = float(rng.uniform(0.083, 0.089)) + long_ = float(rng.uniform(0.11, 0.13)) + long_axis = str(rng.choice(["x", "y"])) + yaw = (0.0 if long_axis == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10))) + dname = str(rng.choice(list(DIRS))) + u = np.array(DIRS[dname]) + # half extent of the box along the push direction (box roughly axis aligned) + ext = 0.5 * (long_ if (long_axis == "x") == (dname in ("forward", "backward")) else narrow) + dist = float(rng.uniform(SQ_IN + ext + 0.01, SQ_IN + ext + 0.07)) + lat = float(rng.uniform(-0.03, 0.03)) + box_xy = np.array([rng.uniform(-0.20, 0.04), rng.uniform(-0.20, 0.20)]) + sq_xy = box_xy + u * dist + np.array([-u[1], u[0]]) * lat + # reach: pushing backward needs the hand ~5 cm beyond the box's far face; the arm's reach at table height + # ends around x = 0.05-0.08 (seed 1015 of the first version: hand stalled at x = 0.09, box never moved) + reach_ok = dname != "backward" or box_xy[0] + ext <= -0.01 + if -0.22 <= sq_xy[0] <= 0.06 and -0.20 <= sq_xy[1] <= 0.20 and reach_ok: + return dict(seed=int(seed), box_half=[long_ / 2, narrow / 2], box_yaw=float(yaw), box_xy=box_xy.tolist(), + square_xy=sq_xy.tolist(), direction=dname, long_axis=long_axis) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for g in self._box_geoms(): + m.geom_size[g, 0], m.geom_size[g, 1] = inst["box_half"] + m.geom_size[g, 2] = BOX_HALF_Z + envs.scale_mass(self.env, "box_1", BOX_MASS) + envs.set_friction(self.env, "box_1", BOX_MU) + sq = self.env.fixtures_dict["square_1"] + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("square_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + bid = m.body_name2id(sq.root_body) + m.body_pos[bid] = [inst["square_xy"][0], inst["square_xy"][1], envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + bx, by = inst["box_xy"] + envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF_Z + 0.0005], yaw=inst["box_yaw"]) + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ geometry / perception stand-in + def observe(self): + """What a perfect perceiver reads off the image: box centre, yaw and footprint, square centre.""" + b = envs.obj_pos(self.env, "box_1") + return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + square_xy=np.array(self.inst["square_xy"], float), half=np.array(self.inst["box_half"], float)) + + def corners3d(self): + """the 8 corners of the box (world)""" + d = self.env.sim.data + bid = envs.body_id(self.env, "box_1") + R = d.body_xmat[bid].reshape(3, 3) + h = np.array([self.inst["box_half"][0], self.inst["box_half"][1], BOX_HALF_Z]) + return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, sz]) for sx in (-1, 1) for sy in (-1, 1) + for sz in (-1, 1)]) + + def corners(self, o=None): + """footprint corners (xy) of the box in its current pose (also when it is tilted or on its side)""" + return self.corners3d()[:, :2] + + def protrusion(self, o=None): + """How far the box footprint sticks out beyond each edge of the square (m, >0 = outside).""" + o = o or self.observe() + rel = self.corners(o) - o["square_xy"] + return {"forward": float(rel[:, 0].max() - SQ_IN), "backward": float(-rel[:, 0].min() - SQ_IN), + "left": float(rel[:, 1].max() - SQ_IN), "right": float(-rel[:, 1].min() - SQ_IN)} + + def extent_along(self, u, o=None): + """half extent of the box footprint along the unit xy vector u""" + o = o or self.observe() + c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"]) + hx, hy = o["half"] + return float(hx * abs(u @ [c, s]) + hy * abs(u @ [-s, c])) + + # ------------------------------------------------------------ contacts / event monitor + def _groups(self): + if not hasattr(self, "_gg"): + m = self.env.sim.model + fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")} + robot = set(envs.robot_geom_ids(self.env)) + self._gg = (fg, robot, set(envs.obj_geom_ids(self.env, "box_1"))) + return self._gg + + def _finger_landings(self): + """{'box' | 'table' | 'other': n_fingers} for fingers resting on a top surface (contact normal vertical).""" + m, d = self.env.sim.model, self.env.sim.data + fg, robot, box = self._groups() + out = {} + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in fg and c.geom2 not in robot: + f, other = c.geom1, c.geom2 + elif c.geom2 in fg and c.geom1 not in robot: + f, other = c.geom2, c.geom1 + else: + continue + if abs(c.frame[2]) < 0.7: + continue + lab = "box" if other in box else ("table" if (m.geom_id2name(other) or "").startswith("table") else "other") + name = m.geom_id2name(f) or "" + out.setdefault(lab, set()).add("1" if "finger1" in name else "2") + return out + + def _closing_axis(self): + m, d = self.env.sim.model, self.env.sim.data + jid = m.joint_name2id(self.env.robots[0].gripper.joints[0]) + a = d.xaxis[jid][:2] + return a / max(np.linalg.norm(a), 1e-9) + + def _start_monitor(self): + b = envs.obj_pos(self.env, "box_1") + self._mon = dict(rest_z=float(b[2]), start_xy=b[:2].copy(), start_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + max_dz=0.0, top_hit=None, prev=set(), was_held=False) + + def _monitor_step(self): + mon = self._mon + zmin = float(self.corners3d()[:, 2].min()) + mon["max_dz"] = max(mon["max_dz"], zmin - envs.TABLE_Z) # whole box above the table + hits = self._finger_landings() + open_ = self.sk is not None and self.sk.gripper_width() > 0.03 + if "box" in hits and "box" not in mon["prev"] and open_: # an open gripper landing on the box top = a grasp + o = self.observe() + ca = self._closing_axis() + e = self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id] + mon["top_hit"] = dict(span=2 * self.extent_along(ca, o), n_fingers=len(hits["box"]), + offset=float(np.linalg.norm(e[:2] - o["box_xy"]))) + if "box" in hits and len(hits["box"]) == 2 and mon["top_hit"] is not None and open_: + mon["top_hit"]["n_fingers"] = 2 + mon["prev"] = set(hits) + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + """Success = the whole box footprint inside the square, box resting on the table, released.""" + envs.settle(self.env, 30) + env, mon = self.env, self._mon or {} + o = self.observe() + b = envs.obj_pos(env, "box_1") + prot = self.protrusion(o) + inside = max(prot.values()) <= 0.0 + upright = abs(envs.obj_upright_cos(env, "box_1")) > 0.9 + held = bool(self.sk.holding("box_1")) if self.sk is not None else False + zmin = float(self.corners3d()[:, 2].min()) + resting = abs(zmin - envs.TABLE_Z) < 0.01 + success = bool(inside and resting and not held) + rel = o["box_xy"] - o["square_xy"] + moved = float(np.linalg.norm(o["box_xy"] - mon.get("start_xy", o["box_xy"]))) + turned = float(np.degrees(_wrap_pi(o["box_yaw"] - mon.get("start_yaw", o["box_yaw"])))) if upright else 0.0 + lifted = mon.get("max_dz", 0.0) > 0.01 + top = mon.get("top_hit") + parts, mode = [], "success" + + def where(): + return (f"its centre is {100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and " + f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the square's centre") + + def sticking(): + return ", ".join(f"{100 * v:.1f} cm beyond the square's {k} edge" for k, v in + sorted(prot.items(), key=lambda kv: -kv[1]) if v > 0.0) + + if success: + parts.append("The box lies completely inside the square.") + elif b[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The box fell off the table.") + elif held: + mode = "held" + parts.append(f"The box is still held by the gripper; {where()}.") + elif not resting: + mode = "not_resting" + parts.append(f"The box is not resting on the table (it is propped up or tilted); {where()}.") + else: + mode = "outside" + if top is not None and not lifted: + mode = "too_wide" + if top["n_fingers"] >= 2 or top["span"] > GRIP_OPEN: + parts.append(f"The fingers came down on top of the box instead of on either side of it: along the " + f"gripper's closing direction the box measures {100 * top['span']:.1f} cm, wider than " + f"the gripper's maximum opening ({100 * GRIP_OPEN:.1f} cm). The box was not grasped.") + else: + parts.append(f"A finger came down on top of the box (the gripper was {100 * top['offset']:.1f} cm " + f"from the box centre). The box was not grasped.") + if moved < 0.01: + mode = "not_moved" if mode == "outside" else mode + parts.append(f"The box did not move; it sticks out {sticking()}.") + else: + parts.append(f"The box was moved {100 * moved:.1f} cm but is not completely inside the square: it " + f"sticks out {sticking()}; {where()}.") + if abs(turned) >= 5: + rot = "counter-clockwise" if turned > 0 else "clockwise" + parts.append(f"It turned by {abs(turned):.0f} deg ({rot} seen from above).") + if not success and not upright and mode not in ("fell_off",): + parts.append("The box is no longer lying on its large bottom face.") + out = dict(success=success, mode=mode, inside=bool(inside), protrusion=prot, rel=[float(rel[0]), float(rel[1])], + moved=moved, turned_deg=turned, lifted=bool(lifted), held=held, upright=bool(upright), + top_hit_span=None if top is None else float(top["span"]), + terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts)) + self._start_monitor() + return out + + # ------------------------------------------------------------ primitives for the scripted policies + def _yaw_near(self, yaw): + cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=60): + """descent that stops when a finger lands on a top surface above the target (contact sensing)""" + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + if self._finger_landings() and sk.eef_pos()[2] > tgt[2] + 0.005: + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + + def _finger_front(self, direction): + m, d = self.env.sim.model, self.env.sim.data + e = self.sk.eef_pos() + best = 0.0 + for g in range(m.ngeom): + if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7: + continue + mid = m.geom_dataid[g] + v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]] + w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e + best = max(best, float((w[:, :2] @ direction).max())) + return best + + def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0, across="narrow"): + """Top-down grasp across the box's narrow side at its centre (+ offsets); if it is held, put it in the square.""" + sk, o = self.sk, self.observe() + gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy + # yaw 0 closes along world y; to close across the narrow side (box local y) use the box yaw + yaw = self._yaw_near(o["box_yaw"] + (0.0 if across == "narrow" else np.pi / 2) + dyaw) + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw) + self._align() + self._guarded_descent([gx, gy, Z_GRASP]) + sk.set_gripper(True, steps=15) + z0 = envs.obj_pos(self.env, "box_1")[2] + sk.move_to([gx, gy, Z_GRASP + 0.12], speed=0.25) + if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.06): + sk.set_gripper(False, steps=8) + return + sx, sy = o["square_xy"] + sk.move_to([sx, sy, Z_GRASP + 0.12]) + sk.move_to([sx, sy, Z_GRASP + 0.005]) + sk.set_gripper(False, steps=12) + sk.move_to([sx, sy, Z_GRASP + 0.12]) + + def push_stroke(self, u, dist): + """Closed gripper behind the box face opposite to u (fingers side by side across the push direction), sweep + along u so that the box moves `dist`, then lift away. Built from move_to + close only.""" + sk, o = self.sk, self.observe() + u = np.asarray(u, float) / np.linalg.norm(u) + c = o["box_xy"] + ext = self.extent_along(u, o) + yaw = self._yaw_near(float(np.arctan2(u[1], u[0]))) # yaw a: closing axis along (-sin a, cos a), i.e. across u + sk.set_gripper(True, steps=6) + face = c - u * ext + p_hi = face - u * 0.08 + sk.move_to([p_hi[0], p_hi[1], Z_PUSH + 0.10], yaw=yaw) + self._align() + front = self._finger_front(u) + start = face - u * (front + FRONT_GAP) + stop = face + u * (dist - front) + sk.move_to([start[0], start[1], Z_PUSH + 0.10]) + sk.move_to([start[0], start[1], Z_PUSH], tol=0.003) + sk.move_to([stop[0], stop[1], Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400) + sk.hold(3) + back = stop - u * 0.02 + sk.move_to([back[0], back[1], Z_PUSH], speed=0.1, max_steps=40) + sk.move_to([back[0], back[1], Z_PUSH + 0.10], speed=0.25) + + def push_to(self, goal_xy, max_strokes=4, tol=0.008): + """Closed-loop push along the box's own axes (each stroke perpendicular to a face keeps the box from turning): + re-observe after every stroke, push along the axis with the larger remaining error.""" + for _ in range(max_strokes): + o = self.observe() + d = np.asarray(goal_xy, float) - o["box_xy"] + c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"]) + axes = [np.array([c, s]), np.array([-s, c])] + comps = [float(d @ a) for a in axes] + i = int(np.argmax(np.abs(comps))) + if abs(comps[i]) < tol: + break + u = axes[i] * np.sign(comps[i]) + self.push_stroke(u, abs(comps[i])) + + def execute(self, inst, params): + if params["mode"] == "push": + goal = np.array(inst["square_xy"]) + np.asarray(params.get("goal_offset", (0.0, 0.0))) + self.push_to(goal, max_strokes=params.get("strokes", 4)) + else: + self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0), + params.get("across", "narrow")) + + # ------------------------------------------------------------ scripted references + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="push") + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)), + dyaw=float(rng.normal(0, 0.15))) + + def adapt_params(self, inst, history): + """too_wide (fingers on top of the box, span > opening) -> the box cannot be picked up: push it instead. + A push that leaves the box outside -> push again, aiming past the reported miss (box centre offset).""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] != "push": + if out["mode"] in ("too_wide", "not_moved"): + return dict(mode="push") + return dict(prm) + if out["mode"] == "outside": + off = np.asarray(prm.get("goal_offset", (0.0, 0.0))) - 0.5 * np.asarray(out["rel"]) + return dict(mode="push", goal_offset=off.tolist()) + return dict(prm) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l4_nest.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l4_nest.py new file mode 100644 index 0000000000000000000000000000000000000000..1176314e28197c49c48a0dcb3c29ba649f2b2780 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l4_nest.py @@ -0,0 +1,644 @@ +"""L4-C nest_order: nest three cups one inside another; the tallest cup is not the widest. + +Scene: three open round cups (red, green, blue; 1.5 mm walls leaning outwards by TAPER_DEG = 5 deg, like slightly +flared tumblers) stand apart on the table. Each cup has its own bottom width and its own height (re-drawn per +instance, 3.5-10 cm tall). Cups are resized per instance by editing their geoms in sim.model (wall segments + +floor), so one env serves every instance (same technique as l4_fit_container). + +Trap (common sense): "the bigger cup goes outside", and a cup looks big mostly by its height. On (1 - P_AGREE) of +the instances the tallest cup is the middle one by width: it is at least INV_DH = 3.5 cm taller than the widest cup. +Their openings then differ by only 3-9 mm in diameter, and from the wrist camera at its start height the taller +one's opening is closer to the camera and looks about as big (about half the instances: bigger); from the front +camera the taller one looks clearly bigger. The narrowest cup is the shortest, so the very first move of the naive +order (widest cup into the tallest one) already fails, out on the table. + +A variant where the innermost cup was taller than the middle one (and the widest cup the tallest) was dropped +2026-10-08: its failure (middle cup on the rim of the innermost cup, both inside the outer one) looked like a nest +from both cameras -- the same flaw as the 14-deg version. + +What the failure looks like (the point of this version, user review 2026-10-08): which cup fits into which is +decided by the bottoms (same flare for all cups), and the sizes are drawn so that a cup whose bottom is too wide +does not go in at all -- it stays on the other cup's rim or wedges in the opening, its bottom at most STUCK_MAX += 0.5 cm below the rim. So a wrong placement leaves a cup standing on top of another one, its whole body above the +rim: visible in both cameras without any text feedback. A cup that fits goes down to the floor (centring tolerance +>= TOL_MIN = 7.5 mm thanks to the flare); in the right nest the taller, narrower cups stick out of the shorter, +wider ones, but each stands inside the next. + +Prior (naive): tallest cup outermost, then the next tallest. Learner: a cup that ended up on top of another cup +must go outside it; swap that pair. Feedback F1 (default) says only failed / succeeded; F2 (ablation) describes +which cup stands in / on which, in words, with no sizes or positions. + +Only move_to / open / close are needed: grasp a cup across its upper wall, carry it over the other cup, release it +just above that cup's rim. +""" +import itertools + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +N_SEG = 20 # wall segments per cup (regular polygon) +TAN_SEG = float(np.tan(np.pi / N_SEG)) +COS_SEG = float(np.cos(np.pi / N_SEG)) +TAPER_DEG = 5.0 # wall lean (from vertical) +TAPER = float(np.radians(TAPER_DEG)) +TT = float(np.tan(TAPER)) +WALL_T = 0.0015 # wall thickness (normal to the wall) +WALL_TH = WALL_T / float(np.cos(TAPER)) # horizontal wall thickness +FLOOR_T = 0.003 +Z0 = 0.0003 # walls start this far above the cup's underside (the floor disc carries the cup) +H_RANGE = (0.035, 0.100) # total cup height +RB_WIDE = (0.023, 0.030) # bottom outer apothem of the cup with the widest bottom +STEP = (0.0055, 0.0075) # bottom apothem difference between neighbours in the true order +RIM_MAX = 0.033 # outer apothem of the widest opening (gripper opens 7.9 cm) +CLEAR_MIN = 0.003 # radial gap (worst case) of a fitting cup standing on the other cup's floor +TOL_MIN = 0.0075 # a fitting cup goes in if its bottom lands within this of the other cup's axis +STUCK_MAX = 0.005 # a too-wide cup's bottom stops no deeper than this below the other cup's rim (5-deg walls +# self-lock: a cup pressed 1.2 cm into the opening wedged, and the narrow cup tipped over with it) +INV_DH = 0.035 # in the swapped pair the narrower cup is taller by at least this +KEEP_DH = 0.010 # in an unswapped pair the wider cup is taller by at least this +P_AGREE = 0.15 # share of instances whose height order is the right nesting order +SEAT_H = 0.010 # "standing on the floor": bottom less than this above the other cup's floor +SEAT_TILT = 15.0 # deg; a tall cup in a short, wider one can lean a little +WRIST_CAM_H = 0.367 # wrist camera height above the table at the start pose (measured 2026-10-08) +COLORS = {"red": (0.78, 0.22, 0.20, 1.0), "green": (0.28, 0.62, 0.32, 1.0), "blue": (0.22, 0.42, 0.80, 1.0)} +CUP_NAMES = ("cup_1", "cup_2", "cup_3") +DENSITY = 600.0 +# execution +GRASP_BELOW_RIM = 0.012 # gripper site this far below the rim when grasping +Z_CARRY = envs.TABLE_Z + 0.24 +DROP = 0.006 # held cup's bottom this far above the receiving rim at release +FINGER_CLEAR = 0.015 # gripper site at least this far above any rim around the target at release: fingers opened +# inside a taller outer cup press on its wall and carry it away on the way up (seed 1009, 2026-10-08) +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) +H_NOISE = 0.03 # relative noise of the blind policy's height judgement + + +# ---------------------------------------------------------------- cup geometry +def _quat_mul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def _seg_quat(phi): + """segment frame: about z by phi, then tilted about its own y (tangential) axis by TAPER, so that its local z + (along the wall) leans outwards and its local x is the wall's outward normal""" + qz = np.array([np.cos(phi / 2), 0.0, 0.0, np.sin(phi / 2)]) + qy = np.array([np.cos(TAPER / 2), 0.0, np.sin(TAPER / 2), 0.0]) + return _quat_mul(qz, qy) + + +def seg_half_len(rb, H): + """tangential half length of a wall segment: one polygon side at the rim (+0.2 mm overlap)""" + return (rb + TT * H) * TAN_SEG + 0.0002 + + +def rim_radius(rb, H): + """outer apothem of the opening""" + return rb + TT * H + + +def inner_radius(rb, z): + """inner apothem at height z above the cup's underside""" + return rb + TT * z - WALL_TH + + +def bottom_reach(rb, H): + """largest horizontal radius of the cup's outside at its bottom (the segment tips stick out a little beyond + the polygon because every segment is as wide as a rim-level polygon side)""" + return float(np.hypot(rb + TT * Z0, seg_half_len(rb, H))) + + +def fit_clearance(rb_in, H_in, rb_out): + """radial clearance (worst case over relative yaw) of cup `in` standing on the floor of cup `out`; + negative = does not go down to the floor. The flare is the same for both cups, so the bottom is the tightest + height.""" + return inner_radius(rb_out, FLOOR_T) - bottom_reach(rb_in, H_in) + + +def centring_tol(rb_in, H_in, rb_out, H_out): + """how far (worst case) cup `in`'s bottom centre may be off cup `out`'s axis when it is lowered in at the rim + and still get inside (the flared wall then guides it down)""" + return inner_radius(rb_out, H_out) - bottom_reach(rb_in, H_in) + + +def stop_height(rb_in, rb_out, H_out): + """height (above cup `out`'s underside) where a too-wide cup `in`, lowered centred, stops: where its bottom + meets the sloping inner wall, or on the rim if that is higher than the cup""" + return min((rb_in - rb_out + WALL_TH) / TT, H_out) + + +def _cup_parts(rb, H): + """[(pos, half size, quat)] of the wall segments in the cup body frame (origin at mid height).""" + zc = (Z0 + H) / 2 + hs = (H - Z0) / (2 * np.cos(TAPER)) + rc = rb + TT * zc - WALL_T / 2 * np.cos(TAPER) + zz = zc + WALL_T / 2 * np.sin(TAPER) - H / 2 + hl = seg_half_len(rb, H) + out = [] + for k in range(N_SEG): + phi = 2 * np.pi * k / N_SEG + out.append(((rc * np.cos(phi), rc * np.sin(phi), zz), (WALL_T / 2, hl, hs), _seg_quat(phi))) + return out + + +def _floor_part(rb, H): + return (0.0, 0.0, -H / 2 + FLOOR_T / 2), (rb - 0.0003, FLOOR_T / 2, 0.0), np.array([1.0, 0.0, 0.0, 0.0]) + + +def cup_xml(model_name, rgba): + """Open flared cup: N_SEG tilted wall boxes + a cylinder floor (sizes are overwritten per instance).""" + geoms = [] + rb, H = RB_WIDE[1], H_RANGE[1] + for k, (p, s, q) in enumerate(_cup_parts(rb, H)): + geoms.append(f' ') + geoms.append(f' ') + fp, fs, _ = _floor_part(rb, H) + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), H / 2, rim_radius(rb, H) / COS_SEG) + + +def disable_midphase(env): + """The cups are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding + volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered + maximum size. A resized wall that lies outside its compiled leaf box is silently skipped: the gripper fingers + passed straight through the walls of the smaller cups (found 2026-10-07). Without the mid-phase MuJoCo tests all + geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set in _reshape_cup).""" + import mujoco + m = env.sim.model._model + m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + + +def kendall(a, b): + """number of pairs ordered differently in the two orders""" + pa, pb = {c: k for k, c in enumerate(a)}, {c: k for k, c in enumerate(b)} + return sum((pa[x] < pa[y]) != (pb[x] < pb[y]) for x, y in itertools.combinations(a, 2)) + + +@register_task +class NestOrder(LFFTask): + name = "l4_nest_order" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason", "Plan") + instruction = "Nest the red, green and blue cups one inside another." + instruction_indirect = "Put the three cups one inside another, like a set of nesting cups." + + # ------------------------------------------------------------ scene + def make_bddl(self): + cats = [register_generated(f"LffNestCup{c.capitalize()}", cup_xml(f"lff_nest_cup_{c}", COLORS[c])) + for c in COLORS] + regions = [(-0.25, -0.15), (-0.05, 0.0), (-0.25, 0.15)] + objs = [(n, cat, f"{n}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)) + for n, cat, (x, y) in zip(CUP_NAMES, cats, regions)] + return write_bddl(self.name, self.instruction, objs) + + @staticmethod + def _heights_ok(case, h): + """h[s] = height of the cup with the s-th narrowest bottom (0 = innermost in the true nest)""" + if case == "agree": # taller = wider: the height order is the nesting order + return h[2] >= h[1] + KEEP_DH and h[1] >= h[0] + KEEP_DH + if case == "swap_wide": # the middle cup is the tallest, the narrowest one the shortest + return h[1] >= h[2] + INV_DH and h[2] >= h[0] + KEEP_DH + raise ValueError(case) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + u = rng.random() + case = "agree" if u < P_AGREE else "swap_wide" + for _ in range(200000): + heights = [float(rng.uniform(*H_RANGE)) for _ in range(3)] # by true size: 0 = narrowest bottom + if not self._heights_ok(case, heights): + continue + rb3 = float(rng.uniform(*RB_WIDE)) + rb2 = rb3 - float(rng.uniform(*STEP)) + rb1 = rb2 - float(rng.uniform(*STEP)) + rbs = [rb1, rb2, rb3] + rims = [rim_radius(rb, h) for rb, h in zip(rbs, heights)] + if max(rims) > RIM_MAX: + continue + ok = True + for p, q in itertools.permutations(range(3), 2): # p into q + if p < q: + ok &= (fit_clearance(rbs[p], heights[p], rbs[q]) >= CLEAR_MIN + and centring_tol(rbs[p], heights[p], rbs[q], heights[q]) >= TOL_MIN) + else: + ok &= heights[q] - stop_height(rbs[p], rbs[q], heights[q]) <= STUCK_MAX + if ok: + break + else: + raise RuntimeError("could not sample cup sizes") + xy = [] + while len(xy) < 3: + xy = [] + for _k in range(3): + for _t in range(200): + p = [float(rng.uniform(-0.27, 0.02)), float(rng.uniform(-0.17, 0.17))] + if all(np.hypot(p[0] - q[0], p[1] - q[1]) >= 0.14 for q in xy): + xy.append(p) + break + # the colour is fixed per object (cup_1 red, cup_2 green, cup_3 blue: one generated class each); shuffle + # which object gets which size / height / position + perm = [int(i) for i in rng.permutation(3)] # perm[size index] = object slot + cups = [None] * 3 + for s in range(3): + cups[perm[s]] = dict(name=CUP_NAMES[perm[s]], color=list(COLORS)[perm[s]], rb=rbs[s], height=heights[s], + rim=rims[s], xy=xy[s], size_rank=s) + order = sorted(range(3), key=lambda j: -cups[j]["rb"]) # outermost first (indices into cups) + naive = sorted(range(3), key=lambda j: -cups[j]["height"]) + assert (naive == order) == (case == "agree"), (seed, case) + by = lambda s: perm[s] # noqa: E731 object index of size rank s + return dict(seed=int(seed), case=case, cups=cups, order=order, naive_order=naive, + bottom_cm=[round(200 * c["rb"], 2) for c in cups], + opening_cm=[round(200 * c["rim"], 2) for c in cups], + height_cm=[round(100 * c["height"], 2) for c in cups], + # relative size of each opening in the wrist camera at its start height (1 = largest) + wrist_apparent=[round(float(v), 3) for v in (lambda a: a / a.max())(np.array( + [c["rim"] / (WRIST_CAM_H - c["height"]) for c in cups]))], + clear_mm=[round(1000 * fit_clearance(rbs[s], heights[s], rbs[s + 1]), 2) for s in range(2)], + tol_mm=[round(1000 * centring_tol(rbs[s], heights[s], rbs[s + 1], heights[s + 1]), 2) + for s in range(2)], + # wrong neighbour pairs: how deep (cm) the wider cup's bottom gets below the narrower cup's rim + stuck_cm={f"{by(s + 1)}in{by(s)}": round(100 * (heights[s] - stop_height( + rbs[s + 1], rbs[s], heights[s])), 2) for s in range(2)}) + + def _reshape_cup(self, name, rb, H): + m = self.env.sim.model + o = self.env.objects_dict[name] + parts = _cup_parts(rb, H) + [_floor_part(rb, H)] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), (name, len(names)) + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size, quat = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_quat[g] = quat + if k < N_SEG: + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + else: + m.geom_rbound[g] = float(np.hypot(size[0], size[1])) + m.geom_aabb[g] = [0, 0, 0, size[0], size[0], size[1]] + # mass / inertia of the resized cup: conical shell + disc floor + bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])]) + slant = (H - Z0) / np.cos(TAPER) + r_mid = rb + TT * (H + Z0) / 2 + wall_m = DENSITY * 2 * np.pi * r_mid * WALL_T * slant + floor_m = DENSITY * np.pi * rb ** 2 * FLOOR_T + mass = wall_m + floor_m + # wall centroid height (from the underside): area-weighted, r grows linearly with z + r0, r1 = rb + TT * Z0, rb + TT * H + z_w = Z0 + (H - Z0) * (r0 + 2 * r1) / (3 * (r0 + r1)) + z_cm = (wall_m * z_w + floor_m * FLOOR_T / 2) / mass + Izz = wall_m * r_mid ** 2 + floor_m * rb ** 2 / 2 + Ixx = (wall_m * (r_mid ** 2 / 2 + (H - Z0) ** 2 / 12 + (z_w - z_cm) ** 2) + + floor_m * (rb ** 2 / 4 + (FLOOR_T / 2 - z_cm) ** 2)) + m.body_mass[bid] = mass + m.body_inertia[bid] = [Ixx, Ixx, Izz] + m.body_ipos[bid] = [0.0, 0.0, z_cm - H / 2] + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + + def apply_instance(self, inst): + disable_midphase(self.env) + for c in inst["cups"]: + self._reshape_cup(c["name"], c["rb"], c["height"]) + envs.set_obj_pose(self.env, c["name"], [*c["xy"], envs.TABLE_Z + c["height"] / 2 + 0.0005]) + + # ------------------------------------------------------------ state + def _cup_state(self, inst, j): + c = inst["cups"][j] + bid = envs.body_id(self.env, c["name"]) + p = self.env.sim.data.body_xpos[bid].copy() + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + tilt = float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + bottom = p - R[:, 2] * c["height"] / 2 # centre of the floor's underside + rim = p + R[:, 2] * c["height"] / 2 + return dict(p=p, tilt=tilt, bottom=bottom, rim=rim, floor_top=bottom[2] + FLOOR_T * R[2, 2]) + + def relations(self, inst): + """For each cup: which cup it stands in / on (if any), how high, seated or not.""" + st = [self._cup_state(inst, j) for j in range(3)] + rel = [] + for j in range(3): + sj = st[j] + best = None + for i in range(3): + if i == j: + continue + ci, si = inst["cups"][i], st[i] + if si["tilt"] > 45: + continue + d = float(np.hypot(*(sj["bottom"][:2] - si["p"][:2]))) + if d > rim_radius(ci["rb"], ci["height"]) + 0.01: + continue # not above / in cup i + hb = float(sj["bottom"][2] - si["floor_top"]) # j's bottom above i's floor + # (the last test keeps a cup from being reported as standing in the cup it contains) + if hb < -0.004 or hb > ci["height"] + 0.02 or sj["bottom"][2] < si["bottom"][2] + FLOOR_T / 2: + continue + if best is None or hb < best[1]: + best = (i, hb, d) + if best is None: + on_table = sj["bottom"][2] < envs.TABLE_Z + 0.01 and sj["tilt"] < 30 + rel.append(dict(cup=j, on=None, table=bool(on_table), tilt=sj["tilt"], xy=sj["p"][:2].tolist(), + fallen=bool(sj["tilt"] > 45))) + continue + i, hb, d = best + ci = inst["cups"][i] + seated = hb < SEAT_H and sj["tilt"] < SEAT_TILT + on_rim = hb > ci["height"] - FLOOR_T - 0.004 + rel.append(dict(cup=j, on=i, height=hb, seated=bool(seated), on_rim=bool(on_rim), tilt=sj["tilt"], + offset=d, xy=sj["p"][:2].tolist(), fallen=bool(sj["tilt"] > 45))) + return rel + + def outcome(self, inst): + envs.settle(self.env, 40) + cups = inst["cups"] + rel = self.relations(inst) + held = [j for j in range(3) if self.sk is not None and self.sk.holding(cups[j]["name"])] + col = [c["color"] for c in cups] + seated_in = {r["cup"]: r["on"] for r in rel if r.get("on") is not None and r["seated"]} + # success: a chain outer <- mid <- inner, all seated and upright, the outer cup standing on the table + success = False + for a, b, c in itertools.permutations(range(3)): + if seated_in.get(b) == a and seated_in.get(c) == b and _on_table_upright(rel, a): + success = True + success = bool(success and not held) + fb = dict(seated=[[j, i] for j, i in seated_in.items()], blocked=[], offcentre=[], held=held) + lines = [] + res = dict(success=success, relations=rel, feedback=fb) + if held: + lines.append(f"The {col[held[0]]} cup is still in the gripper.") + if success: + a = [j for j in range(3) if j not in seated_in][0] + b = [j for j, i in seated_in.items() if i == a][0] + c = [j for j, i in seated_in.items() if i == b][0] + res["detail"] = (f"All three cups are nested: the {col[c]} cup stands inside the {col[b]} cup, " + f"which stands inside the {col[a]} cup.") + res["failure"] = None + return res + # bottom-up description + st = {r["cup"]: self._cup_state(inst, r["cup"]) for r in rel} + for r in sorted(rel, key=lambda r: st[r["cup"]]["bottom"][2]): + j = r["cup"] + if j in held: + continue + if r.get("on") is None: + if r["fallen"]: + lines.append(f"The {col[j]} cup has fallen over.") + elif r["table"]: + lines.append(f"The {col[j]} cup is standing on the table, not in another cup.") + else: + lines.append(f"The {col[j]} cup is neither standing on the table nor inside another cup.") + continue + i = r["on"] + if r["seated"]: + lines.append(f"The {col[j]} cup is inside the {col[i]} cup, standing on its bottom.") + continue + # did not go in. The text says only what a camera shows (no sizes); the structured field keeps the + # nominal verdict for the scripted learner + tilt = f", tilted about {r['tilt']:.0f} degrees" if r["tilt"] >= 8 else "" + if r["on_rim"]: + lines.append(f"The {col[j]} cup is sitting on the rim of the {col[i]} cup, not inside it{tilt}.") + else: + lines.append(f"The {col[j]} cup is stuck in the opening of the {col[i]} cup, not down inside " + f"it{tilt}.") + over = cups[j]["rb"] - cups[i]["rb"] + if over > 0: + fb["blocked"].append([j, i, round(100 * r["height"], 1)]) + else: + fb["offcentre"].append([j, i, round(100 * r["height"], 1)]) + res["detail"] = " ".join(lines) if lines else "The cups are not nested." + res["failure"] = "blocked" if fb["blocked"] else ("offcentre" if fb["offcentre"] else + ("held" if held else "incomplete")) + return res + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: order = [outer, middle, inner] (indices into inst['cups']). Puts the middle cup into the outer + one; if it went in (judged from the scene, as an agent would see it), puts the inner cup into the middle + one. Optional (robustness checks): dxy = (dx, dy) release offset (m), drop (m), grasp_below (m), + carry_speed (m/s or None = as fast as the controller allows).""" + o, mid, inn = [int(v) for v in params["order"]] + ok = self._move_cup(inst, mid, o, params) + if ok: + self._move_cup(inst, inn, mid, params) + self.sk.move_to(list(PARK), yaw=0.0) + + def _move_cup(self, inst, j, i, params): + sk = self.sk + sj = self._cup_state(inst, j) + x, y = sj["p"][:2] + rim = sj["rim"][2] + sk.set_gripper(False, steps=5) + sk.move_to([x, y, Z_CARRY], yaw=0.0) + sk.move_to([x, y, rim + 0.06], tol=0.004) + sk.move_to([x, y, rim - params.get("grasp_below", GRASP_BELOW_RIM)], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([x, y, Z_CARRY], speed=params.get("carry_speed", 0.3)) + si = self._cup_state(inst, i) + dx, dy = params.get("dxy", (0.0, 0.0)) + tx, ty = si["p"][0] + dx, si["p"][1] + dy + drop = params.get("drop", DROP) + sk.move_to([tx, ty, Z_CARRY], tol=0.004) + off = self._cup_state(inst, j)["bottom"] - sk.eef_pos() + # approach above the highest rim there (the target cup may stand inside a taller one) + top = max(s["rim"][2] for s in (self._cup_state(inst, q) for q in range(3) if q != j) + if np.hypot(s["p"][0] - tx, s["p"][1] - ty) < 0.04) + sk.move_to([tx - off[0], ty - off[1], max(top, si["rim"][2]) + drop + 0.03 - off[2]], tol=0.003) + z_rel = si["rim"][2] + drop + if top > si["rim"][2] + 0.002: # the target stands inside a taller cup: let go above that rim + z_rel = max(z_rel, top + FINGER_CLEAR - (inst["cups"][j]["height"] + - params.get("grasp_below", GRASP_BELOW_RIM))) + tgt = self._servo_cup(inst, j, [tx, ty], z_rel) + sk.grip = -1.0 + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], Z_CARRY], speed=0.3) + envs.settle(self.env, 20) + r = [q for q in self.relations(inst) if q["cup"] == j][0] + return bool(r.get("on") == i and r["seated"]) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_cup(self, inst, j, xy, z_bottom, max_steps=60, tol=0.0015): + """closed loop on the held cup's bottom centre (scripted policies only). Stops where the cup is held up + (a too-wide cup on / in another cup's rim) instead of pressing on: a person lets go there too, and + pressing on tips the cups over.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom]) + tgt = e_prev = sk.eef_pos() + zs = [] + for k in range(max_steps): + b, e = self._cup_state(inst, j)["bottom"], sk.eef_pos() + if k >= 8 and np.linalg.norm(b - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + zs.append(b[2]) + if k >= 12 and b[2] - goal[2] > 0.003 and zs[-6] - b[2] < 0.0005: + return e # blocked: release here + tgt = goal - (b - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def default_params(self, inst): + """prior: the bigger-looking cup goes outside, and the cups look big by their height: tallest outermost""" + return dict(order=list(inst["naive_order"])) + + def oracle_params(self, inst): + return dict(order=list(inst["order"])) + + def blind_params(self, inst, attempt, rng): + """no history: the same height judgement again, with a little noise""" + est = [c["height"] * (1 + rng.normal(0, H_NOISE)) for c in inst["cups"]] + return dict(order=[int(i) for i in np.argsort(est)[::-1]]) + + @staticmethod + def constraints(history): + """pairs (outer, inner) implied by the F2 feedback of earlier attempts""" + pairs = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + for j, i in fb.get("seated", []): + pairs.add((int(i), int(j))) # j sits in i -> i is outside j + for j, i, _ in fb.get("blocked", []): + pairs.add((int(j), int(i))) # j does not fit into i -> j must be outside i + for j, i, _ in fb.get("offcentre", []): + pairs.add((int(i), int(j))) # j would fit into i + return pairs + + def adapt_params(self, inst, history): + """Scripted learner. It does not perceive the bottoms at all; it uses only which cup went into / stayed on + top of which (visible in the camera images; the structured part of the outcome): every such relation gives + an (outer, inner) pair; among the untried orders consistent with all pairs it takes the one closest (fewest + swapped pairs) to its prior, the height order; ties go to the larger height agreement.""" + pairs = self.constraints(history) + rims = [c["height"] for c in inst["cups"]] + prior = list(inst["naive_order"]) + tried = {tuple(h["params"]["order"]) for h in history if (h["outcome"].get("feedback") or {}).get("blocked")} + cands = [] + for order in itertools.permutations(range(3)): + pos = {c: k for k, c in enumerate(order)} + consistent = all(pos[a] < pos[b] for a, b in pairs) + agree = sum(rims[order[k]] - rims[order[k + 1]] for k in range(2)) + cands.append((consistent, tuple(order) not in tried, -kendall(order, prior), agree, order)) + best = max(cands) + return dict(order=list(best[4])) + + def random_order_params(self, inst, history, rng): + """sensitivity variant: a random order each retry, no history""" + return dict(order=[int(i) for i in rng.permutation(3)]) + + EXTRA_KINDS = ("random_order",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + params = self.default_params(inst) if a == 0 else self.random_order_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +def _on_table_upright(rel, j): + r = [q for q in rel if q["cup"] == j][0] + return r.get("on") is None and r["table"] and r["tilt"] < 8.0 and not r["fallen"] + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=8, out=None): + """All 6 orders on each instance; expect success iff the order is the true one.""" + import json + task = NestOrder() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for order in itertools.permutations(range(3)): + task.reset_instance(inst) + task.execute(inst, dict(order=list(order))) + o = task.outcome(inst) + expect = list(order) == inst["order"] + # for a cup that did not go in: how far (cm) its bottom is below the other cup's rim + below_rim = [round(100 * (inst["cups"][r["on"]]["height"] - FLOOR_T - r["height"]), 2) + for r in o["relations"] if r.get("on") is not None and not r["seated"]] + rows.append(dict(seed=seed, case=inst["case"], order=list(order), success=o["success"], expect=expect, + failure=o["failure"], detail=o["detail"], below_rim_cm=below_rim, + clear_mm=inst["clear_mm"], tol_mm=inst["tol_mm"], bottom_cm=inst["bottom_cm"], + opening_cm=inst["opening_cm"], height_cm=inst["height_cm"])) + print(f"seed {seed} order {order} succ={o['success']} expect={expect} | {o['detail']}" + + ("" if o["success"] == expect else " <-- MISMATCH"), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows)) + return rows + + +def robustness_check(seed0=1000, n=6, out=None): + """True order with execution errors: release off-centre (both moves) by 0-9 mm in a random direction, released + 3 cm above the rim, grasped lower, carried at full controller speed.""" + import json + task = NestOrder() + rows = [] + cases = [("centred", {}), ("off3", dict(off=0.003)), ("off5", dict(off=0.005)), ("off7", dict(off=0.007)), + ("off9", dict(off=0.009)), ("drop3cm", dict(drop=0.03)), ("off4_drop3cm", dict(off=0.004, drop=0.03)), + ("grasp2cm", dict(grasp_below=0.02)), ("fast_carry", dict(carry_speed=None))] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + rng = np.random.default_rng(seed) + for name, c in cases: + a = rng.uniform(0, 2 * np.pi) + off = c.get("off", 0.0) + params = dict(order=list(inst["order"]), dxy=(off * np.cos(a), off * np.sin(a))) + params.update({k: v for k, v in c.items() if k != "off"}) + task.reset_instance(inst) + task.execute(inst, params) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], tol_mm=inst["tol_mm"], + height_cm=inst["height_cm"])) + print(f"seed {seed} {name:13s} succ={o['success']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + for name, _ in cases: + r = [x["success"] for x in rows if x["case"] == name] + print(f"{name:13s} {sum(r)}/{len(r)}") + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_nest physics results/l4_nest_order/physics_check.json [n] + # python -m lffbench.tasks.l4_nest robust results/l4_nest_order/robustness_check.json [n] + import sys + n_arg = int(sys.argv[3]) if len(sys.argv) > 3 else None + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 8) + elif sys.argv[1] == "robust": + robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 6) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_loaded_beam.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_loaded_beam.py new file mode 100644 index 0000000000000000000000000000000000000000..9131ad1abf4810702f25f598a39e4010f47ecaef --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_loaded_beam.py @@ -0,0 +1,598 @@ +"""L5 loaded_beam (2026-10-12): a deepened l5_slippery_lift -- lift a loaded bar level without spilling its load. + +Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 2, 3.1): l5_slippery_lift saturated. Sonnet 5.5 (cla4) +grasped the bar's middle, lifted, saw the 45-60 deg tilt, put the bar down and regrasped near the centre of mass, +all inside attempt 1 (both runs succeeded on attempt 1): the tilting lift cost nothing. Rule R3: the first +common-sense interaction must cost something. Here the tilting lift spills the load. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, "left" = +y): the l5_slippery_lift bar (steel grey, +4 x 28 x 4 cm, long axis along the robot's left-right axis, same layout and hidden weight per seed) with two small red +blocks (2.5 cm cubes, 30 g, smooth: friction 0.2, they slide on the steel beyond ~11 deg of tilt) resting on its top +near the ends, 12.5 cm left and right of its middle. + +Hidden variable (same in every attempt, invisible): a slug inside the bar puts its centre of mass e = 2.5-7 cm from +the middle, towards the left or right end (bar 0.8-1.2 kg, finger friction 0.40-0.60; l5_slippery_lift). The blocks +are symmetric, so the centre of mass of bar + blocks sits at M e / (M + 2 m) (2.3-6.7 cm). + +Mechanism (physics, nothing teleported): grasped at its middle and lifted, the bar rotates in the slippery finger +pads and hangs tilted; the block on the low (heavy) end slides off, drops onto the table and, once the bar is set down +again, lies 2-5 cm beyond the bar's end; the other block slides along the bar to the fingers. Measured (20 seeds, +middle grasp): lift 15 cm at 0.1 m/s -> tilt 29-54 deg, spill 20/20; 15 cm at 0.03 m/s -> spill 20/20 (block friction = +the bar's, task card); a 5.5 cm "half lift" -> 20-22 deg, spill 20/20; 3 cm -> 10-11 deg, spill 2/20; 1 / 1.5 cm test +lifts -> 0.6-2.5 / 2.5-4.5 deg, spill 0/20 each (the low end stays on the table). Putting it right is a real repair: +set the bar down, release, pick the fallen block from the table, put it back on the end, move the other block back to +its end, regrasp nearer the heavy end, lift again: 20 commands for the scripted policy (5 for the whole oracle; the +same repair costs 7 commands in l5_slippery_lift, where nothing spills). What helps: a ~1 cm test lift shows the tilt +direction without spilling, or, after the first failure, grasping on the side of the end that sank (the heavy end), +ideally at the combined centre of mass (+-5 mm: 80/80 level lifts, nothing spilled). + +Success: the bar is held (after a 1.5 s hold), tilted <= 8 deg, its lowest point >= 10 cm above the table (the +l5_slippery_lift condition), and both blocks rest on the bar, one within 3 cm of each end position (+-12.5 cm from the +middle; either block may sit on either end). Protocol: cross (reset before every attempt), k = 3. + +Outcome (server log only; the agent gets F1): success / failure code, the bar's tilt and height, final block states, +per-step events (bar_lifted, bar_tilted, load_fell = the trap fired, load_displaced, load_removed, load_restored with +by_robot, bar_set_down), the lifts with their grasp points and maximum tilt, trap_fired, recovered_in_attempt, +first_interaction_ok and an F2-style `detail` in robot-centric words. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import register_task +from .l5_slippery_lift import (BAR, HALF, LIFT_MIN, TILT_MAX, YAW_ACROSS, Z_GRASP, BarSkills, SlipperyLift, + bar_tilt_deg, weighted_box_xml) + +TZ = envs.TABLE_Z +LOADS = ("block_1", "block_2") # block_1 starts on the left (+y) end, block_2 on the right (-y) end +LOAD_SIGN = {"block_1": 1.0, "block_2": -1.0} +LOAD_H = 0.0125 # 2.5 cm cubes +LOAD_MASS = 0.030 +LOAD_RGBA = (0.85, 0.20, 0.12, 1.0) +LOAD_MU = 0.20 # block sliding friction (geom priority 3: used against the bar, the table and the fingers): the blocks +# slide on the steel bar beyond ~11 deg of tilt. With the bar's own mu (0.4-0.6, slide beyond 22-31 deg) +# a 5.5 cm "half lift" (20 deg) spilled nothing (0/10) and was a free probe; with 0.2 it spills. +SLOT = 0.125 # block centre this far from the bar's middle (along the bar) +SLOT_TOL = 0.03 # success: within 3 cm of an end position +BAR_TOP = TZ + 2 * HALF[2] +LIFTED = 0.02 # the bar's centre this much higher than at rest (while held) -> "lifted" (a ~1 cm test lift is not) +DOWN = 0.008 # ... and back below this -> "set down" +DEBOUNCE = 5 # control steps a new block state must persist before it counts +SAFE_ALONG = 0.09 # scripted grasps stay within +-9 cm of the middle (the hand must not touch the blocks) + + +class _Budget(Exception): + """the scripted policy used up the agent command budget of the attempt""" + + +def bar_frame(env): + """(centre, along, side, up): `along` = the bar's long axis oriented towards the robot's left (+y); `up` = the + bar's cross-section axis closest to world up (the face the blocks rest on); `side` completes the frame.""" + bid = envs.body_id(env, BAR) + d = env.sim.data + c = d.body_xpos[bid].copy() + R = d.body_xmat[bid].reshape(3, 3) + al = R[:, 1].copy() + if al[1] < 0: + al = -al + up = max((R[:, 0].copy(), R[:, 2].copy()), key=lambda v: abs(v[2])) + if up[2] < 0: + up = -up + side = np.cross(up, al) + return c, al, side, up + + +def _end_word(s): + return "left" if s > 0 else "right" + + +class BeamSkills(BarSkills): + """BarSkills (records where along the bar the jaws closed) + the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class LoadedBeam(SlipperyLift): + name = "l5_loaded_beam" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Plan", "Utilize") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 40 + instruction = ("Lift the metal bar together with the two small red blocks resting near its ends, and hold it level " + "(tilted less than 8 degrees) with its lowest point at least 10 cm above the table. Both blocks must " + "stay on the bar near its ends. Keep holding the bar when you finish.") + instruction_indirect = ("Raise the long grey rod with the two little red cubes sitting near its ends and hold it " + "horizontal (tilted less than 8 degrees), its lowest point at least 10 cm above the table. " + "Both cubes must stay on the rod near its ends. Keep holding the rod when you finish.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffBeamBar", weighted_box_xml("lff_beam_bar", HALF, (0.52, 0.55, 0.58, 1.0))) + dens = LOAD_MASS / (2 * LOAD_H) ** 3 + la = register_generated("LffBeamBlockA", box_xml("lff_beam_block_a", (LOAD_H,) * 3, LOAD_RGBA, density=dens)) + lb = register_generated("LffBeamBlockB", box_xml("lff_beam_block_b", (LOAD_H,) * 3, LOAD_RGBA, density=dens)) + # LIBERO's sampler puts the bar anywhere within +-13 cm of its region's centre (it "keeps the bar's 14 cm + # radius inside" a 2 cm region) and rejects block placements closer than 14 + 1.8 cm to it: the block regions + # are >= 19 cm from every possible bar position (the first layout, 2 cm beside the bar's range, failed with + # "Cannot place all objects" in 13 of 400 resets, this one 0 of 400). apply_instance moves everything anyway. + objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01)), + ("block_1", la, "block1_region", (-0.11, 0.32, -0.09, 0.34)), + ("block_2", lb, "block2_region", (-0.11, -0.34, -0.09, -0.32))] + return write_bddl(self.name, "lift the loaded bar and hold it level", objs) + + def __init__(self, cam_res=None): + self.mon = None + self.budget = None # scripted policies only: command budget of the current attempt + self.ncmd = 0 + super().__init__(cam_res) + + def sample_instance(self, seed): + inst = super().sample_instance(seed) # same bar layout and hidden weight as l5_slippery_lift for this seed + m = inst["mass"] + inst.update(load_mass=LOAD_MASS, slot=SLOT, + com_total=float(m * inst["com_offset"] / (m + 2 * LOAD_MASS))) # bar + both blocks on their ends + return inst + + def apply_instance(self, inst): + super().apply_instance(inst) # bar pose, friction, hidden weight (+ envs.refit_bounds) + x, y = inst["bar_xy"] + for nm in LOADS: + envs.set_obj_pose(self.env, nm, [x, y + LOAD_SIGN[nm] * SLOT, BAR_TOP + LOAD_H + 0.0005]) + if LOAD_MU is not None: + envs.set_friction(self.env, nm, LOAD_MU, priority=3) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = BeamSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state + def bar_bottom(self): + return envs.obj_min_z(self.env, BAR) - TZ + + def load_rel(self, nm): + """block centre in the bar frame: (along (+ = towards the bar's left end), side, height above the bar's centre)""" + c, al, side, up = bar_frame(self.env) + r = envs.obj_pos(self.env, nm) - c + return float(r @ al), float(r @ side), float(r @ up) + + def _block_held(self, nm): + sk = self.sk + if sk is None or sk.grip < 0: + return False + if np.linalg.norm(envs.obj_pos(self.env, nm) - sk.eef_pos()) > 0.06: + return False + return sk.holding(nm) + + def load_state(self, nm, tol=SLOT_TOL): + """'slot+' / 'slot-' (on the bar within `tol` of its left / right end position), 'bar' (on the bar + elsewhere), 'held', 'table', 'air' (anything else: falling, resting on the gripper ...)""" + if self._block_held(nm): + return "held" + a, s, u = self.load_rel(nm) + if abs(u - (HALF[2] + LOAD_H)) <= 0.008 and abs(s) <= HALF[0] + 0.003 and abs(a) <= HALF[1] + 0.003: + if abs(a - SLOT) <= tol: + return "slot+" + if abs(a + SLOT) <= tol: + return "slot-" + return "bar" + if envs.obj_pos(self.env, nm)[2] < TZ + 0.027: + return "table" + return "air" + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + st = {nm: self.load_state(nm) for nm in LOADS} + self.mon = dict(stable=dict(st), cand={nm: None for nm in LOADS}, cnt={nm: 0 for nm in LOADS}, + last_on_bar={nm: self.load_rel(nm)[0] for nm in LOADS}, lost=set(), carried=set(), events=[], + lifts=[], + lifted=False, tilted=False, max_tilt=0.0) + + def _event(self, ev, step=None, **kw): + self.mon["events"].append(dict(step=int(self.sk.n_steps if step is None else step), ev=ev, **kw)) + + def _last_grasp(self): + return next((c for c in reversed(self.sk.closes) if c["holding"]), None) + + def monitor_step(self): + mon, sk = self.mon, self.sk + if mon is None or sk is None: + return + n = sk.n_steps + # --- the bar: lifts and tilt + rise = float(envs.obj_pos(self.env, BAR)[2]) - (TZ + HALF[2]) + held = sk.grip > 0 and sk.holding(BAR) + if not mon["lifted"] and held and rise > LIFTED: + g = self._last_grasp() + mon["lifted"], mon["tilted"], mon["max_tilt"] = True, False, 0.0 + mon["lifts"].append(dict(step_up=n, step_down=None, grasp_along=None if g is None else round(g["along"], 4), + max_tilt_deg=0.0, falls=[])) + self._event("bar_lifted", grasp_along=mon["lifts"][-1]["grasp_along"]) + if mon["lifted"]: + t = bar_tilt_deg(self.env) + lift = mon["lifts"][-1] + if abs(t) > abs(lift["max_tilt_deg"]): + lift["max_tilt_deg"] = round(t, 1) + if not mon["tilted"] and abs(t) > TILT_MAX and held: + mon["tilted"] = True + self._event("bar_tilted", tilt_deg=round(t, 1), low_end=_end_word(t)) + if rise < DOWN: + mon["lifted"] = False + lift["step_down"] = n + self._event("bar_set_down", max_tilt_deg=lift["max_tilt_deg"]) + # --- the blocks (debounced state machine) + for nm in LOADS: + # hysteresis: a block that has left its end position must come back within 2 cm of an end to count as + # restored (a block sliding along the tilted bar hovered around the 3 cm limit and flickered) + s = self.load_state(nm, SLOT_TOL - 0.01 if nm in mon["lost"] else SLOT_TOL) + if s in ("slot+", "slot-", "bar"): + mon["last_on_bar"][nm] = self.load_rel(nm)[0] + old = mon["stable"][nm] + if s == old: + mon["cand"][nm], mon["cnt"][nm] = None, 0 + continue + if s != mon["cand"][nm]: + mon["cand"][nm], mon["cnt"][nm] = s, 0 + mon["cnt"][nm] += 1 + if mon["cnt"][nm] < DEBOUNCE: + continue + step = n - DEBOUNCE + 1 + mon["stable"][nm], mon["cand"][nm], mon["cnt"][nm] = s, None, 0 + start = _end_word(LOAD_SIGN[nm]) + if s == "held": + mon["carried"].add(nm) + if s in ("slot+", "slot-"): + if nm in mon["lost"]: + # by_robot: the gripper carried it back (else physics did, e.g. the high-end block sliding back out + # while the bar swings after the other block fell: 3-4 of 59 blind attempts) + mon["lost"].discard(nm) + self._event("load_restored", step, load=nm, start_end=start, end=_end_word(1 if s == "slot+" else -1), + by_robot=nm in mon["carried"]) + mon["carried"].discard(nm) + elif old in ("slot+", "slot-") and s == "bar": + mon["lost"].add(nm) + self._event("load_displaced", step, load=nm, start_end=start, along_cm=round(100 * self.load_rel(nm)[0], 1)) + elif old in ("slot+", "slot-", "bar", "air") and s == "table": + mon["lost"].add(nm) + end = _end_word(mon["last_on_bar"][nm]) + self._event("load_fell", step, load=nm, start_end=start, off_end=end) + if mon["lifted"]: + mon["lifts"][-1]["falls"].append(nm) + elif old == "held" and s == "table": + mon["lost"].add(nm) + self._event("load_removed", step, load=nm, start_end=start) + elif old in ("slot+", "slot-") and s == "held": + mon["lost"].add(nm) # picked up by the agent: counts as lost until it is back on an end + + # ------------------------------------------------------------ outcome / F2 + def _where(self, nm): + """robot-centric description of a block that is not on an end position""" + st = self.load_state(nm) + a, s, u = self.load_rel(nm) + if st == "held": + return "is held in the gripper" + if st == "bar": + e = 1.0 if a >= 0 else -1.0 + return (f"is still on the bar but {100 * (SLOT - abs(a)):.0f} cm in from its {_end_word(e)} end position " + f"({100 * abs(a):.0f} cm {_end_word(e)} of the bar's middle)") + c, al, side, up = bar_frame(self.env) + e = 1.0 if a >= 0 else -1.0 + u = al[:2] / max(np.linalg.norm(al[:2]), 1e-6) # the bar's direction seen from above + end = c[:2] + al[:2] * e * HALF[1] # the end's position seen from above (also while the bar hangs tilted) + r = envs.obj_pos(self.env, nm)[:2] - end + beyond = float(r @ u) * e + lateral = float(r @ np.array([-u[1], u[0]])) + where = "on the table" if st == "table" else "off the bar" + if beyond > 0 and abs(lateral) < 0.04: + return f"lies {where}, {100 * beyond:.0f} cm beyond the bar's {_end_word(e)} end" + fx = f"{100 * abs(r[0]):.0f} cm {'forward' if r[0] > 0 else 'back'}" + fy = f"{100 * abs(r[1]):.0f} cm {'left' if r[1] > 0 else 'right'}" + return f"lies {where}, {fx} and {fy} of the bar's {_end_word(e)} end" + + def outcome(self, inst): + sk, mon = self.sk, self.mon + sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws) + held = bool(sk.holding(BAR)) + tilt = bar_tilt_deg(self.env) + bottom = self.bar_bottom() + states = {nm: self.load_state(nm) for nm in LOADS} + on_plus = [nm for nm in LOADS if states[nm] == "slot+"] + on_minus = [nm for nm in LOADS if states[nm] == "slot-"] + loads_ok = len(on_plus) == 1 and len(on_minus) == 1 + level_ok = held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN + success = bool(level_ok and loads_ok) + lifted_ever = bool(mon["lifts"]) or (sk.zmax - sk.z0) > 0.03 + g = self._last_grasp() + evs = mon["events"] + falls = [e for e in evs if e["ev"] == "load_fell"] + restored = [e for e in evs if e["ev"] == "load_restored"] + lifts = mon["lifts"] + first_ok = None if not lifts else bool(not lifts[0]["falls"]) # the first lift spilled nothing + # --- text + gtxt = "" + if g is not None: + a = g["along"] + gtxt = (f" You last grasped the bar {100 * abs(a):.1f} cm to the {_end_word(a)} of its middle." + if abs(a) >= 0.0005 else " You last grasped the bar at its middle.") + tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {_end_word(tilt)} end lower than its " + f"{_end_word(-tilt)} end") + if success: + failure = None + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, " + "with a block on each end.") + elif held and abs(tilt) > TILT_MAX: + failure = "tilted" + bar_txt = f"The bar did not stay level: it rotated in the gripper and now {tilt_txt}." + if bottom < LIFT_MIN: + bar_txt += f" Its lowest point is {100 * bottom:.0f} cm above the table." + elif held and bottom < LIFT_MIN: + failure = "too_low" + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only " + f"{100 * bottom:.0f} cm above the table.") + elif held: + failure = "load_off" + bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, " + "but the blocks are not both on its ends.") + elif lifted_ever: + failure = "dropped" + bar_txt = "The bar was lifted but is no longer in the gripper; it lies on the table." + else: + failure = "no_grasp" + bar_txt = ("The gripper never closed on the bar; it is still lying on the table." if not sk.closes else + "The gripper did not catch the bar; it is still lying on the table.") + parts = [bar_txt] + if falls: + f0 = falls[0] + lift = next((l for l in lifts if f0["load"] in l["falls"]), None) + how = (f" while the bar hung tilted by up to {abs(lift['max_tilt_deg']):.0f} degrees with its " + f"{_end_word(lift['max_tilt_deg'])} end lower") if lift and abs(lift["max_tilt_deg"]) > 1 else "" + parts.append(f"The {f0['start_end']} block slid off the bar's {f0['off_end']} end{how}." + + (f" Blocks fell off {len(falls)} times in this attempt." if len(falls) > 1 else "")) + if not loads_ok: + for nm in LOADS: + if states[nm] in ("slot+", "slot-") and (len(on_plus) == 1 or states[nm] != "slot+") and \ + (len(on_minus) == 1 or states[nm] != "slot-"): + continue + parts.append(f"The {_end_word(LOAD_SIGN[nm])} block {self._where(nm)}.") + detail = " ".join(parts) + gtxt + loads = {} + for nm in LOADS: + a, s, u = self.load_rel(nm) + loads[nm] = dict(state=states[nm], along_cm=round(100 * a, 1), side_cm=round(100 * s, 1), + above_bar_centre_cm=round(100 * u, 1)) + out = dict(success=success, failure=failure, held=held, tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1), + grasp_along=None if g is None else round(g["along"], 4), + stages=dict(bar_held_level_high=bool(level_ok), loads_on_ends=bool(loads_ok)), + loads=loads, loads_on_ends=len(on_plus) + len(on_minus) if loads_ok else + int(len(on_plus) >= 1) + int(len(on_minus) >= 1), + trap_fired=bool(falls), n_load_falls=len(falls), n_restored=len(restored), + n_restored_by_robot=len([e for e in restored if e.get("by_robot")]), + n_regressions=len([e for e in evs if e["ev"] in ("load_fell", "load_displaced")]), + recovered_in_attempt=bool(falls and success), first_interaction_ok=first_ok, + n_lifts=len(lifts), lifts=lifts, events=list(evs), closes=sk.closes, detail=detail) + out["detail_indirect"] = detail.replace("bar", "rod").replace("block", "cube") + return out + + # ------------------------------------------------------------ scripted primitives (agent-command counted) + def _cmd(self, target=None, yaw=None, speed=None, grip=None, tol=0.004, max_steps=250): + """one agent command (move_eef with an optional gripper action, or observe when nothing is given)""" + self.ncmd += 1 + if self.budget is not None and self.ncmd > self.budget: + raise _Budget() + sk = self.sk + if target is not None: + t = np.asarray(target, float).copy() + t[2] = max(t[2], TZ + 0.006) # the agent interface does not go below 0.5 cm above the table + sk.move_to(t, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + if grip is not None: + sk.set_gripper(bool(grip)) + + def grasp_lift(self, along, lift=0.15, speed=0.10, dx=0.0): + """open, above the grasp point (jaws across the bar), descend, close, lift, look: 5 commands""" + c, al, side, up = bar_frame(self.env) + g = c + al * float(along) + np.array([dx, 0.0, 0.0]) + z = max(float(c[2]), Z_GRASP) + self._cmd([g[0], g[1], z + 0.10], yaw=YAW_ACROSS, grip=False) + self._cmd([g[0], g[1], z], tol=0.003) + self._cmd(grip=True) + self._cmd([g[0], g[1], z + lift], speed=speed, max_steps=600) + self._cmd() + + def put_down(self): + """lower the held bar onto the table, release, back up: 2 commands""" + e = self.sk.eef_pos() + self._cmd([e[0], e[1], Z_GRASP + 0.003], speed=0.05, grip=False, max_steps=600) + self._cmd([e[0], e[1], Z_GRASP + 0.12]) + + def _block_yaw(self, nm): + """gripper yaw whose jaws close on two faces of the block, preferring jaws that do not reach towards the bar""" + q = envs.obj_quat(self.env, nm) + w, x, y, z = q + psi = float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + c, al, side, up = bar_frame(self.env) + p = envs.obj_pos(self.env, nm) + a = float(np.clip((p - c) @ al, -HALF[1], HALF[1])) + v = (p - (c + al * a))[:2] + v = v / max(np.linalg.norm(v), 1e-6) + best = None + for k in range(2): + ang = psi + k * np.pi / 2 # closing direction candidate (a face normal) + n = np.array([np.cos(ang), np.sin(ang)]) + score = abs(n @ v) + if best is None or score < best[0]: + best = (score, ang) + yaw = best[1] + np.pi / 2 # yaw = closing direction + 90 deg (YAW_ACROSS closes along world x) + return float((yaw + np.pi / 2) % np.pi - np.pi / 2) + + def move_block_to_slot(self, nm, sign, tries=2): + """pick a block (from the table or the bar) and set it on the end position `sign`: 6 commands per try""" + sk = self.sk + for _ in range(tries): + p = envs.obj_pos(self.env, nm) + yaw = self._block_yaw(nm) + zg = max(float(p[2]), TZ + 0.008) + self._cmd([p[0], p[1], zg + 0.08], yaw=yaw, grip=False) + self._cmd([p[0], p[1], zg], tol=0.003, grip=True) + self._cmd([p[0], p[1], BAR_TOP + LOAD_H + 0.07]) + if not sk.holding(nm): + continue + c, al, side, up = bar_frame(self.env) + t = c + al * sign * SLOT + ztop = envs.obj_max_z(self.env, BAR) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.06]) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.004], speed=0.05, grip=False) + self._cmd([t[0], t[1], ztop + LOAD_H + 0.08]) + if self.load_state(nm) == ("slot+" if sign > 0 else "slot-"): + return True + return False + + def restore_loads(self): + """put every block that is not on an end position back onto a free end; True if both ends are taken""" + for _ in range(2): + st = {nm: self.load_state(nm) for nm in LOADS} + free = [s for s in (1.0, -1.0) if not any(v == ("slot+" if s > 0 else "slot-") for v in st.values())] + if not free: + return True + loose = [nm for nm in LOADS if st[nm] not in ("slot+", "slot-")] + for sgn in free: + if not loose: + break + c, al, side, up = bar_frame(self.env) + slot = c + al * sgn * SLOT + nm = min(loose, key=lambda b: np.linalg.norm(envs.obj_pos(self.env, b)[:2] - slot[:2])) + loose.remove(nm) + self.move_block_to_slot(nm, sgn) + self._cmd() # look + st = {nm: self.load_state(nm) for nm in LOADS} + return sorted(st.values()) == ["slot+", "slot-"] + + def judge(self): + """what an agent sees after a lift (perfect perception): (all good, tilt, blocks on their ends)""" + tilt = bar_tilt_deg(self.env) + st = sorted(self.load_state(nm) for nm in LOADS) + ok_loads = st == ["slot+", "slot-"] + good = self.sk.holding(BAR) and abs(tilt) <= TILT_MAX - 2 and self.bar_bottom() >= LIFT_MIN + 0.01 and ok_loads + return bool(good), float(tilt), ok_loads + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + self.grasp_lift(params["along"], params.get("lift", 0.15), params.get("speed", 0.10), params.get("dx", 0.0)) + + def default_params(self, inst): + return dict(along=0.0, lift=0.15, speed=0.10) # Sonnet 5.5 (cla4): middle, up to ~15-18 cm at 0.1 m/s + + def oracle_params(self, inst): + return dict(along=float(inst["com_total"]), lift=0.15, speed=0.10) + + def blind_params(self, inst, attempt, rng): + return dict(along=float(rng.normal(0.0, 0.01)), lift=float(rng.uniform(0.12, 0.18)), + speed=float(rng.uniform(0.05, 0.20))) + + MARGIN = 0.008 # a lift that sank towards +y at grasp g says COM > g + MARGIN + STEP = 0.030 # first move towards the end that sank when only one side is bounded + + def bracket(self, obs): + """grasp point from (grasp_along, tilt) observations: the end that sank is the heavy side of that grasp""" + lo, hi = -SAFE_ALONG, SAFE_ALONG + lo_set = hi_set = False + for g, t in obs: + if t > 0: + lo, lo_set = max(lo, g + self.MARGIN), True + else: + hi, hi_set = min(hi, g - self.MARGIN), True + if lo_set and hi_set: + a = 0.5 * (lo + hi) + elif lo_set: + a = lo + self.STEP - self.MARGIN + elif hi_set: + a = hi - self.STEP + self.MARGIN + else: + a = 0.0 + return float(np.clip(a, -SAFE_ALONG, SAFE_ALONG)) + + def adapt_params(self, inst, history): + obs = [o for h in history for o in h["params"].get("obs", [])] + return dict(along=self.bracket(obs)) + + def adaptive_attempt(self, obs): + """lift at the current estimate; if the bar tilts or a block falls: set the bar down, put the blocks back, + regrasp on the side of the end that sank (bracketing), lift again -- while the command budget allows""" + tried = [] + along = self.bracket(obs) + while True: + tried.append(round(along, 4)) + self.grasp_lift(along) + good, tilt, ok_loads = self.judge() + if good: + return tried + g = self._last_grasp() + if abs(tilt) > 3.0 or not ok_loads: + lift = self.mon["lifts"][-1] if self.mon["lifts"] else None + t = tilt if abs(tilt) > 3.0 else (lift["max_tilt_deg"] if lift else 0.0) + if abs(t) > 1.0: + obs.append((g["along"] if g is not None else along, t)) + # a repair = set down (2) + both blocks back (2 x 6: the fallen one and the one that slid to the fingers) + # + look (1) + regrasp, lift, look (5) = 20 commands; without enough budget keep holding the bar as it is + if self.budget is not None and self.ncmd + 20 > self.budget: + return tried + self.put_down() + if not self.restore_loads(): + return tried + along = self.bracket(obs) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """cross protocol with an agent-like command budget per attempt (agent_max_steps; one move_eef with an optional + gripper action, or one observe, = one command). naive / oracle / blind: one lift, no checking. + adaptive: naive in attempt 1 but checks and repairs inside the attempt (`adaptive_attempt`); later attempts + start from the grasp point learned so far.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history, obs = [], [] + for a in range(k): + self.reset_instance(inst) + self.ncmd, self.budget = 0, self.agent_max_steps + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "adaptive": + params = dict(obs=[]) + else: + raise ValueError(kind) + n0 = len(obs) + try: + if kind == "adaptive": + params["tried"] = self.adaptive_attempt(obs) + else: + self.execute(inst, params) + except _Budget: + params["budget_used_up"] = True + if kind == "adaptive": + params["obs"] = [[round(g, 4), round(t, 1)] for g, t in obs[n0:]] + self.budget = None + out = self.outcome(inst) + out["commands"] = self.ncmd + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_slippery_lift.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_slippery_lift.py new file mode 100644 index 0000000000000000000000000000000000000000..1a533e41595c29d413eb2287843cbc50afe7d0dc --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_slippery_lift.py @@ -0,0 +1,262 @@ +"""L5-B slippery_lift: pick up a heavy, slippery metal bar and hold it level. + +Category dynamics_adaptation (L5): "figure out how this object moves". + +Scene: one long steel-grey bar (4 x 28 x 4 cm, lying along the robot's left-right axis) on the table. It looks +perfectly uniform, but a heavy slug is hidden inside it at an unknown position, so its centre of mass sits +e = 2.5-7 cm from the bar's midpoint, towards the left or the right end. The bar is heavy (0.8-1.2 kg) and its +surface is slippery (finger friction 0.40-0.60): the two finger pads can hold its weight, but they cannot hold +much torque. + +Why the prior fails. The natural grasp is across the bar at its midpoint. With the centre of mass a few cm to +one side, gravity twists the bar in the pads as soon as it is lifted: the heavy end swings down and the bar +ends up hanging tilted by ~10-50 deg (measured). Slow lifting does not help (the torque is static). + +What has to be learned. Which end sank tells on which side of the grasp the centre of mass lies; the grasp +has to move towards that end until it is within ~1.5 cm of the hidden centre of mass (measured window). The +tilt magnitude saturates, so the distance has to be found by bracketing over a few attempts. + +Measured physics (2026-10-07, `l5dyn/bar_win.py`): mass 0.8-1.2 kg, mu 0.4-0.6, lift 15 cm at 0.15 m/s: +|grasp - COM| <= 1.0 cm -> tilt <= 2 deg; 1.5 cm -> 0-41 deg; >= 2 cm -> mostly 30-50 deg; the tilt does not +creep during a 3 s hold. mu 0.8 gave non-monotone tilts and is not used; mu 0.3 + 1.3 kg slips out entirely. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BAR = "bar_1" +HALF = (0.02, 0.14, 0.02) # 4 (x) x 28 (y) x 4 (z) cm, long axis along world y +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' +W_FRAC = 0.6 # fraction of the bar's mass in the hidden slug +W_HALF = 0.015 # slug half size (for its inertia) +E_MIN, E_MAX = 0.025, 0.070 # |COM offset| from the bar's midpoint (m) +LIFT_MIN = 0.10 # the bar's lowest point must be this high above the table +TILT_MAX = 8.0 # deg +Z_GRASP = envs.TABLE_Z + HALF[2] # gripper site at the bar's mid height (finger tips 0.7 cm above the table) +Z_LIFT = Z_GRASP + 0.15 +YAW_ACROSS = np.pi / 2 # jaws close along world x, i.e. across the bar + + +def weighted_box_xml(name, half, rgba, mass=1.0, friction=(1.0, 0.005, 0.0001)): + """Box with an explicit inertial. Its pos is off-centre at compile time so MuJoCo keeps + body_sameframe = 0 / body_simple = 0 and honours the per-instance body_ipos set in apply_instance.""" + I = [mass / 3 * (half[1] ** 2 + half[2] ** 2), mass / 3 * (half[0] ** 2 + half[2] ** 2), + mass / 3 * (half[0] ** 2 + half[1] ** 2)] + g = (f' \n' + f' \n' + f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def set_hidden_weight(env, obj, half, mass, w_frac, w_pos, w_half=W_HALF): + """Uniform shell of mass (1 - w_frac) * mass plus a hidden cube slug of w_frac * mass at w_pos (body frame). + Sets the body's mass, centre of mass and inertia; returns the centre of mass (body frame).""" + m = env.sim.model + bid = envs.body_id(env, obj) + ms, mw = (1 - w_frac) * mass, w_frac * mass + w_pos = np.asarray(w_pos, float) + c = mw * w_pos / mass + hx, hy, hz = half + + def par(mm, r): # parallel-axis terms (diagonal) + return mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2]) + + I = (ms / 3 * np.array([hy ** 2 + hz ** 2, hx ** 2 + hz ** 2, hx ** 2 + hy ** 2]) + par(ms, -c) + + mw / 6 * (2 * w_half) ** 2 * np.ones(3) + par(mw, w_pos - c)) + m.body_mass[bid] = mass + m.body_ipos[bid] = c + m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0] + m.body_inertia[bid] = I + envs.refit_bounds(env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds) + return c + + +def bar_axis(env): + """World direction of the bar's long axis (body y).""" + return env.sim.data.body_xmat[envs.body_id(env, BAR)].reshape(3, 3)[:, 1].copy() + + +def bar_tilt_deg(env): + """Signed tilt of the bar's long axis from horizontal; > 0: the bar's +y end is lower.""" + ax = bar_axis(env) + if ax[1] < 0: # orient the axis towards the robot's left so the sign is about world left/right + ax = -ax + return float(np.degrees(np.arcsin(np.clip(-ax[2], -1.0, 1.0)))) + + +def side_words(sign): + return "left (+y)" if sign > 0 else "right (-y)" + + +class BarSkills(Skills): + """Skills that record where along the bar the jaws closed, whoever drives them (scripted or agent).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self.closes = [] + self.zmax = float(envs.obj_pos(env, BAR)[2]) + self.z0 = self.zmax + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.zmax = max(self.zmax, float(envs.obj_pos(self.env, BAR)[2])) + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + if close: + c = envs.obj_pos(self.env, BAR) + ax = bar_axis(self.env) + if ax[1] < 0: + ax = -ax + along = float((self.eef_pos() - c) @ ax) # + : grasp on the left (+y) side of the midpoint + self.closes.append(dict(along=along, holding=self.holding(BAR), step=self.n_steps)) + return rep + + +@register_task +class SlipperyLift(LFFTask): + name = "l5_slippery_lift" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + instruction = ("Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at " + "least 10 cm above the table. Keep holding it when you finish.") + instruction_indirect = ("Pick up the long grey rod lying on the table and hold it horizontal (tilted less than 8 " + "degrees), with its lowest point at least 10 cm above the table. Keep holding it when you " + "finish.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffSteelBar", weighted_box_xml("lff_steel_bar", HALF, (0.52, 0.55, 0.58, 1.0))) + objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, "pick up the bar and hold it level", objs) # BDDL cannot parse parentheses + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX)) + return dict(seed=int(seed), + bar_xy=[float(rng.uniform(-0.12, -0.03)), float(rng.uniform(-0.06, 0.06))], + com_offset=e, # along the bar, + = towards the robot's left (+y) end + mass=float(rng.uniform(0.8, 1.2)), + mu=float(rng.uniform(0.40, 0.60))) + + def apply_instance(self, inst): + x, y = inst["bar_xy"] + envs.set_obj_pose(self.env, BAR, [x, y, envs.TABLE_Z + HALF[2] + 0.001]) + envs.set_friction(self.env, BAR, inst["mu"]) + set_hidden_weight(self.env, BAR, HALF, inst["mass"], W_FRAC, [0.0, inst["com_offset"] / W_FRAC, 0.0]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = BarSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + sk = self.sk + sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws) + held = sk.holding(BAR) + tilt = bar_tilt_deg(self.env) + bottom = envs.obj_min_z(self.env, BAR) - envs.TABLE_Z + lifted = (sk.zmax - sk.z0) > 0.03 + close = next((c for c in reversed(sk.closes) if c["holding"]), sk.closes[-1] if sk.closes else None) + success = bool(held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN) + out = dict(success=success, held=bool(held), tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1), + grasp_along=None if close is None else round(close["along"], 4)) + g = "" + if close is not None and close["holding"]: + a = close["along"] + g = (f" You grasped the bar {100 * abs(a):.1f} cm to the {side_words(a)} of its midpoint." + if abs(a) >= 0.0005 else " You grasped the bar at its midpoint.") + tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {side_words(tilt).split()[0]} end lower than its " + f"{side_words(-tilt).split()[0]} end") + if success: + out["failure"] = None + detail = f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table." + g + elif held and abs(tilt) > TILT_MAX: + out["failure"] = "tilted" + detail = ("The bar did not stay level: it rotated in the gripper while it was being lifted and now " + f"{tilt_txt}." + g) + if bottom < LIFT_MIN: + detail += f" Its lowest point is {100 * bottom:.0f} cm above the table." + elif held: + out["failure"] = "too_low" + detail = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only " + f"{100 * bottom:.0f} cm above the table." + g) + elif lifted: + out["failure"] = "dropped" + detail = ("The bar was lifted but slipped out of the gripper and fell back onto the table " + f"(it now lies tilted by {abs(tilt):.0f} degrees)." + g) + elif close is None: + out["failure"] = "no_grasp" + detail = "The gripper never closed on the bar; it is still lying on the table." + else: + out["failure"] = "no_grasp" + detail = "The gripper closed but did not catch the bar; it is still lying on the table." + out["detail"] = detail + out["detail_indirect"] = detail.replace("bar", "rod") + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp across the bar at `along` (m from the visible midpoint, + = left / +y) and lift 15 cm.""" + sk = self.sk + c = envs.obj_pos(self.env, BAR) # visible bar pose (perfect perception) + ax = bar_axis(self.env) + if ax[1] < 0: + ax = -ax + g = c + ax * float(params["along"]) + sk.set_gripper(False, steps=5) + sk.move_to([g[0], g[1], Z_GRASP + 0.10], yaw=YAW_ACROSS) + sk.move_to([g[0], g[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_LIFT], speed=0.15, tol=0.004, max_steps=300) + + def default_params(self, inst): + return dict(along=0.0) + + def oracle_params(self, inst): + return dict(along=float(inst["com_offset"])) + + MARGIN = 0.008 # a tilt towards +y at grasp g means COM > g + MARGIN (window is ~+-1.5 cm) + STEP = 0.030 # first step towards the heavy end when only one side is bounded + + def adapt_params(self, inst, history): + """Bracketing on the grasp point: the end that sank is the heavy side of the last grasp.""" + lo, hi = -HALF[1], HALF[1] + lo_set = hi_set = False + for h in history: + o = h["outcome"] + g = o["grasp_along"] if o.get("grasp_along") is not None else h["params"]["along"] + if o.get("failure") == "tilted" or (o.get("failure") == "dropped" and abs(o["tilt_deg"]) > 3): + if o["tilt_deg"] > 0: # left end sank -> COM left of the grasp + lo, lo_set = max(lo, g + self.MARGIN), True + else: + hi, hi_set = min(hi, g - self.MARGIN), True + last = history[-1]["params"]["along"] + if lo_set and hi_set: + a = 0.5 * (lo + hi) + elif lo_set: + a = lo + self.STEP - self.MARGIN + elif hi_set: + a = hi - self.STEP + self.MARGIN + else: # no direction information (e.g. too low): repeat + a = last + return dict(along=float(np.clip(a, -0.12, 0.12))) + + def blind_params(self, inst, attempt, rng): + return dict(along=float(rng.normal(0.0, 0.01))) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..d80d949cb344b6f76199ae9a4dbdeaa0ca800a66 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py @@ -0,0 +1,392 @@ +"""L5-C tablecloth_pull: yank a board out from under a cube so that the cube lands inside a band. + +Category dynamics_adaptation (L5): "figure out how this object moves". Replaces l5_tip_threshold, which could not +be built robustly with this robot (see task_cards/l5_tip_threshold.md). + +Scene: a 30 x 8 x 1 cm wooden board lies on the table, pointing away from the robot, with a black handle block +at its near end. A red 4 cm cube stands on the far part of the board. A green band (6 cm deep, across the +table) is painted on the table under the board, a few cm closer to the robot than the cube. The agent may touch +only the board / handle, never the cube. + +Physics. If the board is pulled slowly the cube rides along on it (static friction). If it is yanked, the board +slides out from under the cube; while it slides, friction drags the cube a little towards the robot, so the +cube drops onto the table having moved d towards the robot. d DEcreases with the pull speed (counter-intuitive: +a harder yank moves the cube less) and increases with the cube-board friction mu. + +Hidden variable: the cube's friction mu (0.08-0.15; the cube looks the same for every mu), which shifts the whole +speed -> displacement curve and the speed below which the cube rides along. + +Why the prior fails. The classic tablecloth prior is to yank as fast as possible (0.6 m/s, the arm's top speed); +the band is always placed >= 1.3 cm beyond the displacement such a yank produces, so the cube lands short of it. F2 reports where the cube ended relative to the band (robot-frame words, cm) or that it +rode along; the agent has to infer which way to change the pull speed (faster = less displacement) and by how +much. + +Rule (stated in the instruction and enforced, 2026-10-08): ONE pull. Only one move command may drive the board +(>= PULL_EPS), the cube must still be where it started (<= PRE_TOL, grasp nudges) when that pull begins, and all +other move commands together may drive the board at most STRAY_MAX. Gripper open / close commands never count. +Without it every cla2 success (Sonnet, 4/4) dragged the board slowly first so that the cube rode to the band and the +last pull only added a little (one dragged it 4 cm, then yanked it sideways; one moved it with 11 commands, most +of them open-gripper strikes): the friction never mattered. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BOARD, CUBE, BAND = "board_1", "cube_1", "band_1" +B_HALF = (0.15, 0.04, 0.005) # 30 x 8 x 1 cm +H_HALF = (0.0125, 0.02, 0.015) # handle 2.5 x 4 x 3 cm on top of the near end +C_HALF = 0.02 # 4 cm cube +LF = 0.05 # cube centre to the board's far edge +BAND_HALF_X = 0.03 # band 6 cm deep: the 4 cm cube must be fully inside -> centre within +-1 cm +BAND_HALF_Y = 0.12 +LINE_W = 0.005 +TOL = BAND_HALF_X - C_HALF +MU_BOARD = 0.3 # board-table friction (fixed) +STROKE = 0.25 # scripted pull length +V_MIN, V_MAX = 0.15, 0.80 +# one-pull rule (2026-10-08). Board motion is the larger of its two ends' 3-D paths and is only counted while the robot +# drives the board (touches it, or it speeds up; a board sliding on its own only slows down), so coasting after a +# strike or a release is not charged to the next command. Measured on the cla2 agent runs and the scripted policy: +# approach moves 0 mm; closing on the handle 0.6-2 mm (agents) / 4.6 mm (script); release after the pull 3-10 mm +# (gripper commands never count as pulls); the loophole drags 13-41 mm per command, open-gripper strikes 11-54 mm. +PULL_EPS = 0.003 # a move command that drives the board this far is a pull +PRE_TOL = 0.01 # the cube may have moved at most this much (grasp nudges) when the pull starts +STRAY_MAX = 0.005 # board motion driven by all the other move commands together (each below PULL_EPS) +ACC_EPS = 0.0002 # board speed-up per control step (m/step) that counts as the robot driving it +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' + + +def board_xml(name): + hp = (-B_HALF[0] + H_HALF[0], 0.0, B_HALF[2] + H_HALF[2]) + wood, black = (0.62, 0.45, 0.28, 1.0), (0.12, 0.12, 0.12, 1.0) + g = (f' \n' + f' \n' + f' \n' + f' \n' + f' ') + # small horizontal radius: only LIBERO's reset-time sampler reads it (the layout is overridden anyway) + return _wrap(name, g, B_HALF[2], 0.03) + + +def band_xml(name, line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat visual band across the table (no collisions): light fill + dark lines on its two long edges.""" + hx, hy = BAND_HALF_X, BAND_HALF_Y + parts = [((0, 0, 0.0004), (hx, hy, 0.0004), fill_rgba), + ((hx + LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba), + ((-hx - LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, 0.03) + + +def d_range(mu): + """Band distances sampled for a given mu (m). Calibrated 2026-10-07 (LF 5 cm, board at x 0.05): the cube + moves d(0.6 m/s) ~ 0.33 * mu - 0.85 cm when yanked at the controller's top speed (mu 0.08 -> 1.8 cm, + 0.10 -> 2.3, 0.12 -> 3.1, 0.15 -> 4.3 cm) and >= 0.5 * mu at a pull ~0.05 m/s above the ride-along speed (0.08 -> 4.1 cm at + 0.35 m/s, 0.15 -> 7.6 cm at 0.45 m/s). The band centre is put ~1.5 cm beyond the top-speed displacement, so + the 'yank as fast as possible' prior always lands the cube short of the band.""" + return 0.33 * mu + 0.0065, 0.50 * mu + + +class ClothSkills(Skills): + """Skills that watch, every control step, whether the robot touches the cube (not allowed) and how each + move_to / gripper command moves the board and the cube (one pull only).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + m = env.sim.model + self._robot = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self._cube = envs.obj_geom_ids(env, CUBE) + self._board = envs.obj_geom_ids(env, BOARD) + self.touched_cube = False + self.cube0 = envs.obj_pos(env, CUBE) + self._ends = self._board_ends() + self._bstep = 0.0 # board motion in the previous control step + self._seg = None + self.segments = [] # one entry per move_to / set_gripper command + + def _board_ends(self): + """Both ends of the board's long axis (world xyz): their motion also catches turning and tilting.""" + b = envs.obj_pos(self.env, BOARD) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3) + return np.stack([b - R[:, 0] * B_HALF[0], b + R[:, 0] * B_HALF[0]]) + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if not self.touched_cube and envs.contacts_between(self.env, self._robot, self._cube): + self.touched_cube = True + ends = self._board_ends() + step = float(np.max(np.linalg.norm(ends - self._ends, axis=1))) + touch = envs.contacts_between(self.env, self._robot, self._board) + speed_up = step - self._bstep > ACC_EPS + self._ends, self._bstep = ends, step + s = self._seg + if s is not None: + s["path"] += step + s["touch"] += int(touch) + if touch or speed_up: + s["driven"] += step + + def _segment(self, kind, fn, *args, **kwargs): + c0, b0 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD) + self._seg = dict(kind=kind, step0=self.n_steps, path=0.0, driven=0.0, touch=0) + try: + rep = fn(*args, **kwargs) + finally: + s, self._seg = self._seg, None + c1, b1 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD) + s.update(steps=self.n_steps - s["step0"], board_dxy=(b1 - b0)[:2].round(4).tolist(), + cube_dxy=(c1 - c0)[:2].round(4).tolist(), cube_from_start=(c0 - self.cube0)[:2].round(4).tolist()) + self.segments.append(s) + return rep + + def move_to(self, target, *args, **kwargs): + return self._segment("move", super().move_to, target, *args, **kwargs) + + def set_gripper(self, close, steps=15): + return self._segment("close" if close else "open", super().set_gripper, close, steps) + + def pull_check(self): + """Pulls (move commands that drove the board >= PULL_EPS), where the cube was when the (first) pull started, + and the board motion driven by the other move commands.""" + moves = [s for s in self.segments if s["kind"] == "move"] + pulls = [s for s in moves if s["driven"] >= PULL_EPS] + stray = sum(s["driven"] for s in moves if s["driven"] < PULL_EPS) + pre = (float(np.linalg.norm(pulls[0]["cube_from_start"])) if pulls + else float(np.linalg.norm((envs.obj_pos(self.env, CUBE) - self.cube0)[:2]))) + return dict(n_pulls=len(pulls), pulls_cm=[round(100 * s["driven"], 1) for s in pulls], + pre_pull_cube_cm=round(100 * pre, 1), stray_cm=round(100 * stray, 2)) + + +@register_task +class TableclothPull(LFFTask): + name = "l5_tablecloth_pull" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + instruction = ("Pull the wooden board out from under the red cube so that the cube ends up standing on the table " + "completely inside the green band. Touch only the board and its black handle, never the cube. " + "Only one pull is allowed per attempt: grasp the black handle, pull the board out with ONE move " + "command, then release it. Any other move that drags, pushes or nudges the board, before or after " + "the pull, counts as another pull.") + instruction_indirect = ("Pull the long brown plank out from under the small red block so that the block ends up " + "standing on the table completely inside the green stripe. Touch only the plank and its " + "black handle, never the block. Only one pull is allowed per attempt: grasp the black " + "handle, pull the plank out with ONE move command, then release it. Any other move that " + "drags, pushes or nudges the plank, before or after the pull, counts as another pull.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + board = register_generated("LffClothBoard", board_xml("lff_cloth_board")) + cube = register_generated("LffClothCube", box_xml("lff_cloth_cube", (C_HALF,) * 3, (0.85, 0.15, 0.15, 1.0), + density=2300)) + band = register_generated("LffClothBand", band_xml("lff_cloth_band"), free=False) + objs = [(BOARD, board, "board_region", (0.09, -0.26, 0.11, -0.24)), + (CUBE, cube, "cube_region", (-0.21, 0.24, -0.19, 0.26))] + fixtures = [(BAND, band, "band_region", (-0.31, -0.01, -0.29, 0.01))] + return write_bddl(self.name, "pull the board out from under the cube", objs, fixtures=fixtures) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + mu = float(np.exp(rng.uniform(np.log(0.08), np.log(0.15)))) + lo, hi = d_range(mu) + d = float(rng.uniform(lo, max(lo, hi))) + return dict(seed=int(seed), board_xy=[float(rng.uniform(0.03, 0.08)), float(rng.uniform(-0.08, 0.08))], + mu=mu, band_d=d) + + def cube_start(self, inst): + bx, by = inst["board_xy"] + return np.array([bx + B_HALF[0] - LF, by]) + + def band_center(self, inst): + c = self.cube_start(inst) + return np.array([c[0] - inst["band_d"], c[1]]) + + def apply_instance(self, inst): + m = self.env.sim.model + for g in range(m.ngeom): # the band is a flat marker: no collisions + if (m.geom_id2name(g) or "").startswith(BAND + "_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + bx, by = inst["board_xy"] + envs.set_obj_pose(self.env, BOARD, [bx, by, envs.TABLE_Z + B_HALF[2] + 0.0005]) + c = self.cube_start(inst) + envs.set_obj_pose(self.env, CUBE, [c[0], c[1], envs.TABLE_Z + 2 * B_HALF[2] + C_HALF + 0.0005]) + envs.set_friction(self.env, BOARD, MU_BOARD, priority=1) + envs.set_friction(self.env, CUBE, inst["mu"], priority=2) # cube-board and cube-table contacts use mu + bid = m.body_name2id(self.env.fixtures_dict[BAND].root_body) + bc = self.band_center(inst) + m.body_pos[bid] = [bc[0], bc[1], envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + + def reset_instance(self, inst, recorder=None): + from robosuite.utils.errors import RandomizationError + for _ in range(20): # LIBERO's reset-time placement sampler occasionally fails; the layout is overridden + try: + self.env.reset() + break + except RandomizationError: + continue + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = ClothSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def cube_on_board(self): + c = envs.obj_pos(self.env, CUBE) + b = envs.obj_pos(self.env, BOARD) + R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3) + local = R.T @ (c - b) + return bool(abs(local[0]) < B_HALF[0] + 0.005 and abs(local[1]) < B_HALF[1] + 0.005 + and c[2] > envs.TABLE_Z + 2 * B_HALF[2] + C_HALF - 0.004) + + def outcome(self, inst): + sk = self.sk + envs.settle(self.env, 60) + c = envs.obj_pos(self.env, CUBE) + c0 = self.cube_start(inst) + bc = self.band_center(inst) + moved = float(c0[0] - c[0]) # towards the robot + off = c[:2] - bc # + x: cube forward (away from the robot) of the band's centre line + upright = envs.obj_upright_cos(self.env, CUBE) > 0.95 + on_board = self.cube_on_board() + on_table = c[2] < envs.TABLE_Z + C_HALF + 0.004 + in_band = bool(abs(off[0]) <= TOL and abs(off[1]) <= BAND_HALF_Y - C_HALF) + pc = sk.pull_check() + rule = [] + if pc["n_pulls"] > 1: + rule.append(f"The board was moved by {pc['n_pulls']} separate move commands " + f"({', '.join(f'{v:.1f}' for v in pc['pulls_cm'])} cm); only one pull is allowed.") + if pc["n_pulls"] and pc["pre_pull_cube_cm"] > 100 * PRE_TOL: + rule.append(f"When the pull started the cube had already been moved {pc['pre_pull_cube_cm']:.1f} cm by " + f"earlier small moves of the board; only one pull is allowed.") + if pc["stray_cm"] > 100 * STRAY_MAX: + rule.append(f"Besides the pull, other move commands moved the board {pc['stray_cm']:.1f} cm in total; " + f"only one pull is allowed.") + success = bool(in_band and on_table and upright and not on_board and not sk.touched_cube and not rule) + b_moved = float(np.linalg.norm(envs.obj_pos(self.env, BOARD)[:2] - np.asarray(inst["board_xy"]))) + out = dict(success=success, touched_cube=bool(sk.touched_cube), on_board=on_board, upright=bool(upright), + moved_toward_robot=round(moved, 4), band_offset_x=round(float(off[0]), 4), + err=round(float(moved - inst["band_d"]), 4), board_moved=round(b_moved, 4), + one_pull=not rule, **pc) + side = ("forward (+x, away from the robot)" if off[0] > 0 else "backward (-x, toward the robot)") + where = (f"its centre is {100 * abs(off[0]):.1f} cm {side} of the band's centre line" + if abs(off[0]) >= 0.0005 else "its centre is on the band's centre line") + if sk.touched_cube: + out["failure"] = "touched_cube" + detail = "The robot touched the cube, which is not allowed." + elif on_board and b_moved < 0.02: + out["failure"] = "board_not_moved" + detail = "The board was not pulled; the cube is still standing on it." + elif on_board: + out["failure"] = "rode_along" + detail = (f"The board was pulled {100 * b_moved:.0f} cm, but the cube rode along on it: it is still on the " + f"board and moved {100 * moved:.1f} cm toward the robot.") + elif not upright: + out["failure"] = "toppled" + detail = f"The board came out from under the cube, but the cube fell over; {where}." + elif in_band and on_table and upright: + out["failure"] = None + detail = (f"The board came out from under the cube and the cube is standing inside the green band; {where}. " + f"It moved {100 * moved:.1f} cm toward the robot.") + else: + out["failure"] = "missed_band" + detail = (f"The board came out from under the cube and the cube is standing on the table, but not " + f"completely inside the green band: {where}. It moved {100 * moved:.1f} cm toward the robot.") + if rule and not sk.touched_cube: + out["failure"] = "several_pulls" + detail = " ".join(rule) + " " + detail + out["detail"] = detail + out["detail_indirect"] = (detail.replace("board", "plank").replace("cube", "block") + .replace("green band", "green stripe").replace("band's", "stripe's")) + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the handle (jaws across its 4 cm width) and pull the board STROKE m toward the robot at `speed`.""" + sk = self.sk + b = envs.obj_pos(self.env, BOARD) + hx, hy = b[0] - B_HALF[0] + H_HALF[0], b[1] + zg = envs.TABLE_Z + 2 * B_HALF[2] + H_HALF[2] + sk.set_gripper(False, steps=5) + sk.move_to([hx, hy, zg + 0.08], yaw=0.0) + sk.move_to([hx, hy, zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([hx - STROKE, hy, zg], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), tol=0.01, + max_steps=300) + sk.set_gripper(False, steps=8) + sk.move_to([hx - STROKE, hy, zg + 0.10], speed=0.3) + + def default_params(self, inst): + """Prior: the classic tablecloth trick -- yank as fast as the arm can.""" + return dict(speed=0.60) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.60 + rng.normal(0, 0.06), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Bracketing search on the pull speed with the signed displacement error (riding along = far too much + displacement). Faster -> less displacement.""" + pts = [] + for h in history: + o = h["outcome"] + if o.get("failure") in ("rode_along", "board_not_moved"): + e = 0.10 + elif o.get("failure") in ("touched_cube", "several_pulls"): + continue + else: + e = o["err"] + pts.append((h["params"]["speed"], e)) + hi_err = [p for p in pts if p[1] > 0] # moved too much -> needs a faster pull + lo_err = [p for p in pts if p[1] < 0] # moved too little -> needs a slower pull + if hi_err and lo_err: + (v0, e0) = max(hi_err, key=lambda p: p[0]) # fastest pull that still moved it too much + (v1, e1) = min(lo_err, key=lambda p: p[0]) # slowest pull that moved it too little + if e0 >= 0.05: # rode along: no usable slope -> bisect + v = 0.5 * (v0 + v1) + else: + v = v0 + (v1 - v0) * e0 / (e0 - e1) + elif hi_err: + v = max(p[0] for p in hi_err) * 1.25 + else: + v = min(p[0] for p in lo_err) * 0.8 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on the speed by simulating pulls with the true mu.""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(10): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + o = self.outcome(inst) + e = 0.10 if o["failure"] in ("rode_along", "board_not_moved") else o["err"] + if o["success"]: + best = (mid, e) + break + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + lo = mid + else: + hi = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py new file mode 100644 index 0000000000000000000000000000000000000000..234475804ed6b6684aa8fc69a813d1332eb3a2d0 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py @@ -0,0 +1,398 @@ +"""L7 hidden_mechanism: open a small cabinet door whose opening mechanism is hidden. + +Category: failed_interaction_inference ("why did this contact not do what I expected?"). + +Scene: a small wooden cabinet (14 x 24 x 10 cm) whose door faces away from the robot (towards the front +camera), with a black knob post in the middle of the door. The robot reaches over the cabinet, grasps the +knob from above and pulls. + +Hidden variable: the door's mechanism, one of four (uniform): swings on a hinge at its left edge (HL) or at +its right edge (HR), or slides to the left (SL) or to the right (SR). The door, the knob and the cabinet look +exactly the same for all four (hinge pins and slide rails are not modelled visually). + +Rule (stated in the instruction and enforced): one pull per attempt -- grasp the knob, ONE straight move_to +while holding it, release. A "pull" is any move_to that starts with the knob held, moves the door, or pushes +against the door / knob sideways. Without this rule an agent could probe the door with small wiggles inside +one attempt and the task would no longer test what is learnt across attempts. + +Why the prior fails (measured): the natural pull is straight out from the door (forward, +x), 12 cm. + hinged: the knob has to follow a circle around the hinge; the door swings open 31-36 deg and the knob is + pulled out of the fingers. The knob ends ~6 cm forward and ~4.5 cm towards the hinge side. + sliding: nothing moves; the fingers slide off the knob. +Success needs >= 60 deg (hinged) or >= 12 cm (sliding). + +What must be learned: from how the knob / door moved (F2 gives the knob's displacement relative to where it +started, plus the images) -> which mechanism -> the pull direction that opens it: + hinged on the left: pull forward-left (~55 deg from forward), ~22 cm -> 70-88 deg (measured) + hinged on the right: pull forward-right -> 70-88 deg + sliding: pull sideways ~18 cm (18 cm); after "nothing moved" the side is not observable, + so a learner needs one more attempt in the worst case (left fails -> right). +Straight pulls at 30 / 45 deg towards the hinge give 44 / ~62 deg; diagonal pulls on a slider give 2-4 cm. +""" +import mujoco +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CAB = "cab_1" +MODEL = "lff_l7_mech_cabinet" +# cabinet frame: origin at the centre of the footprint, z = 0 on the table; the open side faces +x +D, W, H, T = 0.14, 0.24, 0.10, 0.01 # depth (x), width (y), height, wall thickness +DW, DH, DT = 0.232, 0.09, 0.012 # door width, height, thickness +GAP = 0.002 +KZ = 0.045 # knob stem height above the table +STEM_L, STEM_R = 0.032, 0.005 +POST_R, POST_H = 0.009, 0.038 +POST_TOP = KZ - 0.006 + POST_H # 7.7 cm above the table +Z_GRIP = envs.TABLE_Z + 0.075 # grasp-point height for grasping the knob (verified across cabinet positions) +MECHS = ("HL", "HR", "SL", "SR") +HINGE_OK = np.radians(60.0) +SLIDE_OK = 0.12 +SLIDE_RANGE = 0.22 +PULL_SPEED = 0.10 + + +def cabinet_xml(name, rgba=(0.45, 0.32, 0.22, 1.0), door_rgba=(0.80, 0.70, 0.55, 1.0), knob_rgba=(0.12, 0.12, 0.13, 1.0)): + hx, hy = D / 2, W / 2 + shell = [((-hx + T / 2, 0, H / 2), (T / 2, hy, H / 2)), ((0, hy - T / 2, H / 2), (hx, T / 2, H / 2)), + ((0, -hy + T / 2, H / 2), (hx, T / 2, H / 2)), ((0, 0, H - T / 2), (hx, hy, T / 2)), + ((0, 0, T / 2), (hx, hy, T / 2))] + g = [] + for k, (p, s) in enumerate(shell): + g.append(f'') + g.append(f'') + dx = hx + GAP + DT / 2 + dz = 0.005 + DH / 2 + door = [f'', + # placeholder joint: type, axis, anchor and range are set per instance (apply_instance) + f'', + f'', + f''] + sz = KZ - dz + stem_p = (DT / 2 + STEM_L / 2, 0, sz) + post_p = (DT / 2 + STEM_L, 0, sz - 0.006 + POST_H / 2) + for tag, typ, p, s in (("stem", "box", stem_p, (STEM_L / 2 + 0.002, STEM_R, STEM_R)), + ("post", "cylinder", post_p, (POST_R, POST_H / 2))): + door.append(f'') + door.append(f'') + body = ("\n ".join(g) + f'\n \n ' + + "\n ".join(door) + "\n ") + return f""" + + + + {body} + + + + + + +""" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +class MechSkills(Skills): + """Skills that log, for whoever drives them (scripted policy or agent): door pulls, the first grasp of the + knob, and how the knob moved during the first pull.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + m = env.sim.model + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self._door_geoms = task.door_geom_ids + self.knob0 = task.knob_xyz() + self.pulls = [] # one entry per move_to that counts as a pull + self.closes = [] # close_gripper events: gripper centre relative to the knob, held afterwards? + self._touch = False + self.touch_since_report = False + + def holding_knob(self): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.task.knob_geom_names)) + + def _touching_door(self): + d = self.env.sim.data + g = set(self._grip_geoms) + dg = set(self._door_geoms) + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in g and c.geom2 in dg) or (c.geom2 in g and c.geom1 in dg): + return True + return False + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if self._touching_door(): + self._touch = True # per move_to (pull detection) + self.touch_since_report = True # per agent command (report field) + + def move_to(self, target, *args, **kwargs): + q0 = self.task.door_q() + hold0 = self.holding_knob() + p0 = self.eef_pos() + k0 = self.task.knob_xyz() + self._touch = False + rep = super().move_to(target, *args, **kwargs) + dq = abs(self.task.door_q() - q0) + moved = dq > (np.radians(1.0) if self.task.hinged else 0.003) + horiz = float(np.linalg.norm(np.asarray(target, float)[:2] - p0[:2])) + if hold0 or moved or (self._touch and horiz >= 0.015): + k1 = self.task.knob_xyz() + self.pulls.append(dict(step=self.n_steps, held_at_start=bool(hold0), held_at_end=self.holding_knob(), + knob_start=k0.tolist(), knob_end=k1.tolist(), door_moved=bool(moved), + gripper_move=(np.asarray(target, float)[:2] - p0[:2]).round(4).tolist())) + return rep + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + rep = super().set_gripper(close, steps) + if close and was_open: + off = self.eef_pos() - self.task.knob_xyz() + self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_knob(), + width=round(self.gripper_width(), 4))) + return rep + + +@register_task +class HiddenMechanism(LFFTask): + name = "l7_hidden_mechanism" + level = "L7" + category = "failed_interaction_inference" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = ("Open the door of the small wooden cabinet wide (a door that swings must end at least 60 degrees " + "open, a door that slides at least 12 cm). The door faces away from you; grasp its black knob from " + "above. Only one pull is allowed per attempt: grasp the knob, move the gripper with ONE straight " + "move command while holding it, then release it. Pushing the door or the knob counts as a pull " + "too.") + instruction_indirect = ("Open the front panel of the small brown box wide (a panel that swings must end at least 60 " + "degrees open, a panel that slides at least 12 cm). The panel faces away from you; grasp the " + "small black handle on it from above. Only one pull is allowed per attempt: grasp the handle, " + "move the gripper with ONE straight move command while holding it, then release it. " + "Pushing the panel or the handle counts as a pull too.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + cab = register_generated("LffL7MechCabinet", cabinet_xml(MODEL), free=False) + return write_bddl(self.name, "open the cabinet door", [], + fixtures=[(CAB, cab, "cab_region", (-0.14, -0.01, -0.12, 0.01))]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{CAB}_{MODEL}" + self.jid = m.joint_name2id(pre + "_door_joint") + self.dof = m.jnt_dofadr[self.jid] + self.qa = m.jnt_qposadr[self.jid] + self.cab_bid = m.body_name2id(self.env.fixtures_dict[CAB].root_body) + self.post_gid = m.geom_name2id(pre + "_post") + self.knob_geom_names = [pre + "_post", pre + "_stem"] + self.door_geom_ids = [m.geom_name2id(pre + s) for s in ("_post", "_stem", "_panel")] + self.hinged = True + + # agent-facing hooks ------------------------------------------------------- + def on_agent_tool(self, inst, name, args, report): + """The cabinet is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never + see the knob or the door; add an explicit `holding_knob` field and count door contacts as touches.""" + if self.sk is None or not isinstance(report, dict): + return + touched = self.sk.touch_since_report + self.sk.touch_since_report = False + if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"): + report["holding_knob"] = self.sk.holding_knob() + if touched and "touched_object" in report: + report["touched_object"] = True + + # ------------------------------------------------------------ state helpers + def door_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.post_gid].copy() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), mech=MECHS[int(rng.integers(4))], + cab_xy=[float(rng.uniform(-0.15, -0.10)), float(rng.uniform(-0.07, 0.07))]) + + def apply_instance(self, inst): + m, d = self.env.sim.model, self.env.sim.data + cx, cy = inst["cab_xy"] + m.body_pos[self.cab_bid] = [cx, cy, envs.TABLE_Z] + m.body_quat[self.cab_bid] = [1.0, 0.0, 0.0, 0.0] + mech = inst["mech"] + jid, dof = self.jid, self.dof + self.hinged = mech in ("HL", "HR") + if self.hinged: + s = 1 if mech == "HL" else -1 + m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_HINGE + m.jnt_axis[jid] = [0, 0, 1] + m.jnt_pos[jid] = [-DT / 2, s * DW / 2, 0] # back face of the door, at its left / right edge + m.jnt_range[jid] = [0.0, 1.9] if s > 0 else [-1.9, 0.0] + m.dof_damping[dof] = 0.05 + m.dof_frictionloss[dof] = 0.03 + else: + s = 1 if mech == "SL" else -1 + m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_SLIDE + m.jnt_axis[jid] = [0, s, 0] + m.jnt_pos[jid] = [0, 0, 0] + m.jnt_range[jid] = [0.0, SLIDE_RANGE] + m.dof_damping[dof] = 2.0 + m.dof_frictionloss[dof] = 0.5 + # MuJoCo scales constraint softness (here: the joint limits) with dof_invweight0, computed once at compile + # time for the placeholder hinge through the door's centre. Changing the joint type without updating it + # made the slide limit ~200x too soft: a slider pulled the wrong way moved 17 cm past its stop (measured). + door_mass, door_izz = 0.35, 0.0016 + m.dof_invweight0[dof] = (1.0 / (door_izz + door_mass * (DW / 2) ** 2)) if self.hinged else 1.0 / door_mass + m.jnt_solref[jid] = [0.004, 1.0] # stiff stops (default 0.02 let a hard pull push a slider 8 mm past its stop) + d.qpos[self.qa] = 0.0 + d.qvel[dof] = 0.0 + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = MechSkills(self.env, self, recorder=recorder) + return self.sk + + def opening(self): + """Hinge: degrees open (>= 0); slide: cm open (>= 0).""" + q = abs(self.door_q()) + return float(np.degrees(q)) if self.hinged else 100.0 * q + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + sk = self.sk + q = abs(self.door_q()) + is_open = q >= (HINGE_OK if self.hinged else SLIDE_OK) + n_pulls = len(sk.pulls) + success = bool(is_open and n_pulls <= 1) + kd = self.knob_xyz() - sk.knob0 + out = dict(success=success, door_open=bool(is_open), opening=round(self.opening(), 1), n_pulls=n_pulls, + knob_disp=kd.round(4).tolist(), pulls=sk.pulls, closes=sk.closes, first_pull_disp=None, + lost_hold=None) + parts = [] + grasp_txt = "" + if sk.closes: + c = sk.closes[0] + o = c["offset"] + below = (envs.TABLE_Z + POST_TOP) - (o[2] + sk.knob0[2]) # knob top minus gripper centre height + grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the knob's " + f"centre and {100 * below:.1f} cm below the top of the knob; it " + + ("was holding the knob." if c["held"] else "did not get hold of the knob.")) + if success: + out["failure"] = None + parts.append("The door is open wide.") + elif n_pulls == 0: + out["failure"] = "no_pull" + parts.append("The door did not open: the knob was never pulled.") + else: + out["failure"] = "several_pulls" if n_pulls > 1 else "not_open" + if n_pulls > 1: + parts.append(f"The door or knob was pulled or pushed in {n_pulls} separate moves; only one pull is " + f"allowed per attempt, so this attempt failed.") + elif is_open: + parts.append("The door is open wide.") + else: + parts.append("The door did not open wide enough.") + p = sk.pulls[0] + # net effect of the first pull once things came to rest: up to the start of the next pull, or now + k_after = np.array(sk.pulls[1]["knob_start"]) if n_pulls > 1 else self.knob_xyz() + disp = k_after - np.array(p["knob_start"]) + out["first_pull_disp"] = disp.round(4).tolist() + out["lost_hold"] = bool(p["held_at_start"] and not p["held_at_end"]) + if np.linalg.norm(disp[:2]) < 0.003: + txt = "During your (first) pull the knob did not move at all (less than 0.3 cm)" + else: + txt = f"During your (first) pull the knob moved {_fb(disp[0])} and {_lr(disp[1])}" + if p["held_at_start"]: + txt += ("; the gripper lost hold of the knob during the pull." if out["lost_hold"] + else "; the gripper still held the knob at the end of the pull.") + else: + txt += "; the gripper was not holding the knob when that move started." + parts.append(txt) + if grasp_txt and not success: + parts.append(grasp_txt) + out["detail"] = " ".join(parts) + return out + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the knob from above (yaw 0), one straight pull in direction `alpha` (deg from forward, + = left) + over `dist` metres, release, lift.""" + sk = self.sk + p = self.knob_xyz() # perfect perception of the current scene + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z_GRIP + 0.08], yaw=0.0) + sk.move_to([p[0], p[1], Z_GRIP], tol=0.003) + sk.set_gripper(True, steps=15) + a = np.radians(float(params["alpha"])) + dist = float(params["dist"]) + sk.move_to([p[0] + dist * np.cos(a), p[1] + dist * np.sin(a), Z_GRIP], speed=PULL_SPEED, tol=0.004, + max_steps=300) + sk.set_gripper(False, steps=8) + e = sk.eef_pos() + sk.move_to([e[0], e[1], Z_GRIP + 0.10]) + + def default_params(self, inst): + return dict(alpha=0.0, dist=0.12) + + ORACLE = dict(HL=(55.0, 0.22), HR=(-55.0, 0.22), SL=(90.0, 0.18), SR=(-90.0, 0.18)) + + def oracle_params(self, inst): + a, dist = self.ORACLE[inst["mech"]] + return dict(alpha=a, dist=dist) + + def adapt_params(self, inst, history): + """Scripted F2 learner using the knob's displacement during the (first) pull of each earlier attempt: + moved forward and sideways -> it swings on a hinge on that side -> pull ~55 deg towards that side + (more if a hinge pull already fell short) + moved only sideways -> it slides that way -> pull sideways + did not move -> not a hinge; it must slide: try left, then right.""" + hinge_side, slide_side = 0, 0 + tried_still = set() # pull directions (sign of alpha, only for sideways pulls) after which nothing moved + hinge_tries = 0 + for h in history: + o = h["outcome"] + d = o.get("first_pull_disp") + a = h["params"]["alpha"] + if d is None: + continue + dx, dy = d[0], d[1] + if dx >= 0.01 and abs(dy) >= 0.01: + hinge_side = int(np.sign(dy)) + if abs(a) >= 50: + hinge_tries += 1 + elif abs(dy) >= 0.01: + slide_side = int(np.sign(dy)) + elif abs(a) >= 80: + tried_still.add(int(np.sign(a))) + if hinge_side: + a = 55.0 + 5.0 * min(hinge_tries, 2) + return dict(alpha=hinge_side * a, dist=0.22 + 0.02 * min(hinge_tries, 2)) + if slide_side: + return dict(alpha=90.0 * slide_side, dist=0.18) + side = 1 if 1 not in tried_still else -1 + return dict(alpha=90.0 * side, dist=0.18) + + def blind_params(self, inst, attempt, rng): + """Same plan (pull straight out) with small random variation; no history.""" + return dict(alpha=float(rng.normal(0.0, 8.0)), dist=float(np.clip(rng.normal(0.12, 0.02), 0.06, 0.2))) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py new file mode 100644 index 0000000000000000000000000000000000000000..c5314a649314f9885d502ac3c6c8fb213a78e227 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py @@ -0,0 +1,954 @@ +"""LH false_bottom_lid: open a lidded wooden box, put a tall red block and two blue cubes in, close the lid -- in half +of the boxes a hidden false bottom makes the box too shallow for the block standing upright, so the lid comes down on +the block and stays open; the block must be laid on its side. + +Family: long-horizon common sense + self-disturbance ("state_restoration"): the agent's own normal action (placing the +block upright, as it was found) makes the last stage (lid closed) impossible; it has to notice the blocked lid, take +the block out again, lay it down and close the lid (within an attempt), or lay the block down from the start in this +box (across attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a wooden box (fixture): outer 20.6 cm (forward-back) x 13.6 cm (left-right) x 9 cm high, walls 0.8 cm; the + inside is pure black and matte (walls' inner faces, floor and false bottom). The lid (0.6 cm, wood, 0.15 kg) is + hinged along the box's left or right long edge; a black ball knob sticks out of the middle of the opposite edge. + Opened past upright the lid falls over to the hinge side and hangs on its stop (182-192 deg) just below + horizontal beside the box, below every transit; + * a red block 4 x 4 x 7.5 cm standing upright and two 4 cm blue cubes, in a row in front of the box (robot side), + on 3 of 4 slots 16 cm apart. + +Hidden variable: the box's inner depth. With a false bottom (10 of every 20 consecutive seeds) the floor is 4.5 cm +below the rim instead of 8.4 cm. The outside is identical and the inside is dark: from above (wrist camera) and from +the far camera the floor height is not readable (measured: renders of the open, empty box with and without the false +bottom are pixel-identical in both cameras). The Panda hand (21 cm along the finger axis) cannot go below the rim, +so the fingertips cannot touch the false bottom either. Upright the block is 7.5 cm tall: it fits the deep box (top 0.9 cm +below the rim) but stands 3 cm above the rim on the false bottom; lying down (4 cm) it fits both. + +Why the natural action fails: the block is found standing; carried top-down by a gripper that can only turn about the +vertical, it is naturally put in standing. On a false bottom the closing lid then comes down on the block's top and +stays open at ~28-41 deg (measured; clearly visible in both cameras). What must be +learned: take the block out, lay it on its side (tip it over on the table by pushing its upper part with the closed +fingers, then pick it up lying) and put it in lying (within the attempt), or lay it down before putting it in (across +attempts). + +Lid mechanics for agents (inherited from lh_lid_box's `LidSkills`, generalized to a hinge axis along x): while the +knob is held, a commanded straight move is projected onto the knob's circle around the hinge (at most 1 cm per control +step), so "up, then over the hinge, release" opens the lid and "up, then away from the hinge, release" closes it. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (lid closed, all +three items inside the box below the rim, nothing held, scene static) plus an event log for the server log +(per-item in_box achieved / lost / restored, lid opened / closed / blocked, red block laid down / stood up); F1 gives +the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task +from .lh_lid_box import SMAX, LidSkills, _fb, _lr + +# ---------------------------------------------------------------- geometry / physics (box frame: hinge along local y +# at the local +x edge; the box is turned by +-90 deg so that the hinge runs forward-back on the left or right side) +BOX = "box_1" +BOX_MODEL = "lff_fbl_box" +S_IN, L_IN = 0.120, 0.190 # inner cavity across the hinge (local x -> world y) and along it (local y -> world x); +# roomy enough that closed fingers (~4 cm out from a held 4 cm item) stay off the walls +WALL_T, WALL_H, FLOOR_T = 0.008, 0.090, 0.006 +FB_DEPTH = 0.045 # inner depth with the false bottom (floor 4.5 cm above the table) +LX, LY = S_IN + 2 * WALL_T, L_IN + 2 * WALL_T +LID_T, LID_MASS = 0.006, 0.15 +KNOB_R, STEM_L = 0.013, 0.032 +HINGE_DAMP, HINGE_FRIC = 0.002, 0.002 +LID_SOLREF, LID_SOLIMP = "0.005 1", "0.99 0.998 0.001" +BACKOFF = 0.003 # m per control step: a hand pressing on a lid that rests on an item yields +STOP = (182.0, 192.0) # lid opening stop (deg, uniform): opened, the lid hangs just below horizontal beside the box +# (free end 6.5-7 cm up), below every transit; at < 180 deg its free end and knob rise to 12-14 cm +# and a carried item sweeps into them (measured) +WOOD = (0.55, 0.38, 0.22, 1.0) +LID_RGBA = (0.70, 0.52, 0.32, 1.0) +DARK = (0.0, 0.0, 0.0, 1.0) # pure black, matte (no specular): every lit shade is 0, so the floor height is invisible +KNOB_RGBA = (0.10, 0.10, 0.11, 1.0) + +RED = "red_block_1" +BLUES = ("blue_cube_1", "blue_cube_2") +ITEMS = (RED,) + BLUES +RED_W, RED_H = 0.040, 0.075 +CUBE_E = 0.040 +RED_DENS, CUBE_DENS = 600.0, 500.0 # 72 g, 32 g +ITEM_MU = 0.8 +P_FB = 0.5 + +IN_TOL = 0.004 # an item's footprint corners may reach this far past the inner walls (an item leaning on a wall +# touches it; measured: a cube dropped into the deep box ended tilted 52 deg against the front wall) +RIM_TOL = 0.004 # item top at most this far above the rim +LID_CLOSED = np.radians(5.0) +DEBOUNCE = 6 # predicate checks (every 0.1 s) +UPRIGHT_COS, LYING_COS = np.cos(np.radians(25.0)), np.cos(np.radians(65.0)) + +Z_CARRY = 0.16 # scripted transit height of the grasp point above the table when carrying an item (Sonnet: 11-20 cm) +Z_HAND_MIN = WALL_H - 0.024 + 0.006 # lowest grasp point over the box: the Panda hand (2.4 cm above the grasp point, 21 cm +# along the finger axis) must stay above the rim +# scripted in-box slots along the box's long axis (u, forward-back, box centre = 0), all at v = 0 (centre line). +# The lying red block lies across the box (axis left-right) and is held with the fingers closing forward-back, so its +# slot is 1 cm further in: fingers 4 cm out from its centre stay 1 cm off the back wall (measured: at the upright +# slot the back finger caught the wall and dropped the block) +SLOT_U = {"red_upright": -0.0575, "red_lying": -0.0475, "blue_cube_1": 0.005, "blue_cube_2": 0.055} +START_Y = (-0.24, -0.08, 0.08, 0.24) +START_X = -0.34 + + +def fb_box_xml(name): + hx, hy = LX / 2, LY / 2 + col = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)), + ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)), + ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))] + g = [] + # box: contype 2 / conaffinity 1, lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the + # hinge limit holds it closed) but both collide with the robot, the table and the free items (as in lh_lid_box) + for k, (pos, s) in enumerate(col): + g.append(f'') + fb_top = WALL_H - FB_DEPTH + fbh = (fb_top - FLOOR_T) / 2 + fb_pos, fb_size = (0, 0, FLOOR_T + fbh), (hx - WALL_T, hy - WALL_T, fbh) + # the false bottom: always compiled, its collision switched on / off per instance (contype / conaffinity), so no + # geom moves at runtime and the compiled bounding volumes stay valid (see lh_fence's refit_bvh note) + g.append(f'') + th = WALL_T / 2 + vis = [((hx - th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD), + ((hx - WALL_T + th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK), + ((-hx + th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD), + ((-hx + WALL_T - th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK), + ((0, hy - th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD), + ((0, hy - WALL_T + th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK), + ((0, -hy + th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD), + ((0, -hy + WALL_T - th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK), + ((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2), WOOD), + ((0, 0, FLOOR_T + 0.0005), (hx - WALL_T, hy - WALL_T, 0.0005), DARK)] + for p, s, c in vis: + mat = f' material="{name}_dark"' if c == DARK else "" + g.append(f'') + g.append(f'') + m, L = LID_MASS, LX + lid_c = (-L / 2, 0, LID_T / 2) + lid_s = (L / 2, hy, LID_T / 2) + stem = (-L - STEM_L / 2, 0, LID_T / 2) + ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2) + lid = [f'', + f'', + # stiffer contacts for the lid plate, and solmix so that they win against the items' (default, soft) ones: + # with soft contacts an arm pressing the lid down onto the 72 g block pushed the lid through it (measured) + f'', + f'', + f'', + f'', + f'', + f''] + shell = "\n ".join(g) + lid_xml = "\n ".join(lid) + # matte near-black inside (no specular highlight): the floor height is not readable from above + return f""" + + + + + + + {shell} + + {lid_xml} + + + + + + + +""" + + +class FBLidSkills(LidSkills): + """LidSkills with the hinge axis in any horizontal direction (here forward-back), plus the task's per-step + monitor. While the knob is held, the commanded displacement is projected onto the tangent of the knob's circle + about the hinge (<= SMAX per control step), with radial and axial corrections.""" + + def _hinge_frame(self, e): + h, a = self.task.hinge_point(), self.task.hinge_axis() + v = e - h + al = float(v @ a) + r = v - al * a + return a, al, r, max(float(np.linalg.norm(r)), 1e-6) + + def _act(self, dpos, drot, grip): + if self.latched: + e = self.eef_pos() + if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035: + self.latched = False # opened, or the knob slipped out of the fingers + else: + a, al, r, rn = self._hinge_frame(e) + t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn # knob motion for an opening lid + s = float(np.clip(np.asarray(dpos) @ t_open, -SMAX, SMAX)) + if s < 0 and self.task.lid_contacts(): + s = 0.0 # compliant wrist: it does not force the lid down onto an item (else the lid tunnels through it) + dpos = s * t_open + (self.rad0 - rn) * r / rn + (self.y0 - al) * a + self.knob_steps += 1 + else: + p = self.task.robot_lid_contact() + if p is not None and self.task.lid_contacts(): + # the same limit for a hand pressing on the lid itself: no push towards closing while the lid rests on + # an item (measured without it: pressing 5 cm "into" a lid lying on the block left the block poking + # through the lid) + _, _, r, rn = self._hinge_frame(p) + t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn + sc = float(np.asarray(dpos) @ t_open) + if sc < 0: # drop the closing component and yield a little (a force-limited arm gives way) + dpos = np.asarray(dpos) + (BACKOFF - sc) * t_open + Skills._act(self, dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + rep = Skills.set_gripper(self, close, steps) + if close and self.holding_knob(): + _, al, _, rn = self._hinge_frame(self.eef_pos()) + self.latched, self.rad0, self.y0 = True, rn, al + self.knob_grasps += 1 + elif not close: + self.latched = False + return rep + + +def _rot(yaw): + c, s = np.cos(yaw), np.sin(yaw) + return np.array([[c, -s], [s, c]]) + + +@register_task +class FalseBottomLid(LFFTask): + name = "lh_false_bottom_lid" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful: lid 2 x ~6 + 3 items x ~7 = ~35 commands; laying the block down (tip + pick) ~8; + # fixing a blocked lid in place (reopen, take out, tip, pick, put in, close) ~30; + looking + instruction = ("Put the red block and the two blue cubes into the wooden box and close its lid. The lid opens by " + "lifting the black knob on its edge.") + instruction_indirect = ("Pack the tall red piece and both small blue cubes into the wooden chest and shut it " + "(the lid lifts by the black ball on its edge).") + agent_object_names = ["red block", "blue cube", "blue cube", "wooden box", "lid knob"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffFblBox", fb_box_xml(BOX_MODEL), free=False) + red = register_generated("LffFblRedBlock", box_xml("lff_fbl_red_block", (RED_W / 2, RED_W / 2, RED_H / 2), + (0.85, 0.10, 0.08, 1.0), density=RED_DENS, + friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace( + 'group="0" />', 'condim="4" group="0" />')) + objs = [(RED, red, "red_region", (-0.35, -0.25, -0.33, -0.23))] + for i, n in enumerate(BLUES): + cat = register_generated(f"LffFblBlueCube{'AB'[i]}", + box_xml(f"lff_fbl_blue_cube_{'ab'[i]}", (CUBE_E / 2,) * 3, (0.15, 0.30, 0.85, 1.0), + density=CUBE_DENS, friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace( + 'group="0" />', 'condim="4" group="0" />')) + objs.append((n, cat, f"blue_{'ab'[i]}_region", (-0.35, -0.09 + 0.16 * i, -0.33, -0.07 + 0.16 * i))) + fx = [(BOX, box, "box_region", (-0.16, -0.01, -0.14, 0.01))] + return write_bddl(self.name, "put the red block and the blue cubes into the box and close the lid", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = m.jnt_qposadr[self.jid] + self.dof = m.jnt_dofadr[self.jid] + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")} + self.fb_gid = m.geom_name2id(pre + "_fb") + self.fbvis_gid = m.geom_name2id(pre + "_fbvis") + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.item_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in ITEMS} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.17, -0.14)), float(rng.uniform(-0.02, 0.02)) + hinge = "left" if rng.random() < 0.5 else "right" + stop = float(rng.uniform(*STOP)) + perm = rng.permutation(len(START_Y)) + start = {n: [float(START_X + rng.uniform(-0.01, 0.01)), float(START_Y[perm[j]] + rng.uniform(-0.01, 0.01))] + for j, n in enumerate(ITEMS)} + start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in ITEMS} + # balanced blocks like lh_lid_box: exactly 10 of every 20 consecutive seeds have the false bottom + fb = bool((int(seed) * 7) % 20 < round(20 * P_FB)) + return dict(seed=int(seed), box_xy=[bx, by], hinge=hinge, stop_deg=stop, false_bottom=fb, + inner_depth_cm=round(100 * (FB_DEPTH if fb else WALL_H - FLOOR_T), 1), start=start, + start_yaw=start_yaw) + + def box_yaw(self, inst=None): + inst = inst or self.inst + return np.pi / 2 if inst["hinge"] == "left" else -np.pi / 2 # local +x (hinge edge) -> world +y / -y + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + yaw = self.box_yaw(inst) + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)] + m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])] + m.jnt_solref[self.jid] = [0.01, 1.0] + fb = bool(inst["false_bottom"]) + m.geom_contype[self.fb_gid] = 2 if fb else 0 + m.geom_conaffinity[self.fb_gid] = 1 if fb else 0 + m.geom_rgba[self.fbvis_gid, 3] = 1.0 if fb else 0.0 + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + for n, xy in inst["start"].items(): + envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n]) + for n in ITEMS: + envs.set_friction(self.env, n, ITEM_MU) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = FBLidSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry helpers + def floor_z(self): + """height of the surface items rest on inside the box (world z)""" + return envs.TABLE_Z + ((WALL_H - FB_DEPTH) if self.inst["false_bottom"] else FLOOR_T) + + def rim_z(self): + return envs.TABLE_Z + WALL_H + + def long_axis(self): + """unit vector (world xy) along the box's long side (= the hinge axis), pointing forward""" + return np.array([1.0, 0.0]) + + def to_box(self, xy): + """world xy -> box frame (u along the long side / forward, v across / left)""" + return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"]) + + def from_box(self, uv): + return np.asarray(self.inst["box_xy"]) + np.asarray(uv, float) + + def hinge_sign(self): + return 1.0 if self.inst["hinge"] == "left" else -1.0 + + def hinge_point(self): + bx, by = self.inst["box_xy"] + return np.array([bx, by + self.hinge_sign() * LX / 2, envs.TABLE_Z + WALL_H]) + + def hinge_axis(self): + return np.array([1.0, 0.0, 0.0]) + + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def item_axis(self, name): + """body z axis in world (the red block's long axis)""" + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)[:, 2].copy() + + def red_pose(self): + c = abs(float(self.item_axis(RED)[2])) + return "upright" if c >= UPRIGHT_COS else "lying" if c <= LYING_COS else "tilted" + + def in_cavity_xy(self, name): + """the item's whole footprint (its collision box corners, also when tilted) inside the inner walls""" + m, d = self.env.sim.model, self.env.sim.data + g = next(iter(self.item_gids[name])) + R = d.geom_xmat[g].reshape(3, 3) + half = m.geom_size[g][:3] + c = self.to_box(d.geom_xpos[g][:2]) + ext = np.abs(R[:2, :]) @ half # world-axis half extents of the footprint + lim = np.array([L_IN / 2, S_IN / 2]) + IN_TOL + return bool(np.all(np.abs(c) + ext <= lim)) + + def in_box(self, name): + return bool(self.in_cavity_xy(name) and envs.obj_max_z(self.env, name) <= self.rim_z() + RIM_TOL + and envs.obj_min_z(self.env, name) >= envs.TABLE_Z + FLOOR_T - 0.005 and not self.held(name)) + + def over_box(self, name): + """centre above the cavity (in it, or standing in it but sticking out)""" + c = self.to_box(envs.obj_pos(self.env, name)[:2]) + return bool(abs(c[0]) <= L_IN / 2 and abs(c[1]) <= S_IN / 2) + + def lid_closed(self): + return self.lid_q() <= LID_CLOSED + + def lid_contacts(self): + """items the lid touches now""" + d = self.env.sim.data + out = set() + for i in range(d.ncon): + c = d.contact[i] + for n in ITEMS: + g = self.item_gids[n] + if (c.geom1 in g and c.geom2 in self.lid_gids) or (c.geom2 in g and c.geom1 in self.lid_gids): + out.add(n) + return out + + def robot_lid_contact(self): + """world position of a robot-lid contact (None if the robot does not touch the lid)""" + d = self.env.sim.data + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in self.robot_gids and c.geom2 in self.lid_gids) or (c.geom2 in self.robot_gids + and c.geom1 in self.lid_gids): + return np.array(c.pos, float) + return None + + def robot_touching(self): + """'lid' / item names the robot is in contact with now (finishing while pressing the lid down does not count)""" + d = self.env.sim.data + out = set() + for i in range(d.ncon): + c = d.contact[i] + g1, g2 = c.geom1, c.geom2 + for a, b in ((g1, g2), (g2, g1)): + if a in self.robot_gids: + if b in self.lid_gids: + out.add("lid") + for n in ITEMS: + if b in self.item_gids[n]: + out.add("red block" if n == RED else "blue cube") + return sorted(out) + + def stage_values(self): + v = {f"{n}_in_box": self.in_box(n) for n in ITEMS} + v["lid_closed"] = self.lid_closed() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(state={f"{n}_in_box": False for n in ITEMS}, ever=set(), lost=set(), events=[], + last_touch={n: None for n in ITEMS}, step=0, lid_opened=False, lid_open_max=0.0, + lid_prev=0.0, lid_still=0, blocked_now=False, n_blocked=0, blocked_max_deg=0.0, + red_pose=self.red_pose(), red_pose_cand=None, red_pose_n=0, red_up_in_box=False, + red_relaid=0, closes=0, cand={f"{n}_in_box": 0 for n in ITEMS}) + + def _touches(self): + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for n in ITEMS: + g = self.item_gids[n] + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.lid_gids: + out[n] = "lid" + elif other in self.robot_gids and out.get(n) != "lid": + out[n] = "robot" + return out + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + for n, who in self._touches().items(): + mon["last_touch"][n] = (who, step) + q = self.lid_deg() + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if not mon["lid_opened"] and q > 90.0: + mon["lid_opened"] = True + mon["blocked_now"] = False + mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical")) + elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED): + mon["lid_opened"] = False + mon["closes"] += 1 + mon["events"].append(dict(step=step, pred="lid", ev="closed")) + # lid blocked: it came down from past vertical and rests (not held) on an item at 5-80 deg for 1 s + if abs(q - mon["lid_prev"]) < 0.05: + mon["lid_still"] += 1 + else: + mon["lid_still"] = 0 + mon["lid_prev"] = q + if mon["lid_opened"] and not mon["blocked_now"] and 5.0 < q < 80.0 and mon["lid_still"] >= 20 \ + and not self.sk.latched: + on = sorted(self.lid_contacts()) + if on: + mon["blocked_now"] = True + mon["n_blocked"] += 1 + mon["blocked_max_deg"] = max(mon["blocked_max_deg"], q) + mon["events"].append(dict(step=step, pred="lid", ev="lid_blocked", lid_deg=round(q, 1), on=on, + red_pose=self.red_pose())) + if mon["blocked_now"] and q > 90.0: + mon["blocked_now"] = False + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + # red block pose (debounced 1 s): upright <-> lying + p = self.red_pose() + if p != "tilted" and p != mon["red_pose"]: + if mon["red_pose_cand"] == p: + mon["red_pose_n"] += 1 + else: + mon["red_pose_cand"], mon["red_pose_n"] = p, 1 + if mon["red_pose_n"] >= 10 and not self.held(RED): + where = "box" if self.over_box(RED) else "table" + lt = mon["last_touch"][RED] + cause = lt[0] if lt is not None and step - lt[1] <= 60 else "other" + ev = "item_relaid" if p == "lying" else "stood_up" + if p == "lying": + mon["red_relaid"] += 1 + mon["events"].append(dict(step=step, pred="red_pose", ev=ev, where=where, cause=cause)) + mon["red_pose"] = p + mon["red_pose_cand"] = None + else: + mon["red_pose_cand"] = None + if not mon["red_up_in_box"] and mon["red_pose"] == "upright" and self.over_box(RED) and not self.held(RED) \ + and envs.obj_min_z(self.env, RED) < self.rim_z(): + mon["red_up_in_box"] = True + top = envs.obj_max_z(self.env, RED) - self.rim_z() + mon["events"].append(dict(step=step, pred="red_pose", ev="placed_upright_in_box", + top_above_rim_cm=round(100 * top, 1))) + for n in ITEMS: # debounced: a change counts after it held for DEBOUNCE checks (fingers rubbing a released item) + key = f"{n}_in_box" + now = self.in_box(n) + if now == mon["state"][key]: + mon["cand"][key] = 0 + continue + mon["cand"][key] += 1 + if mon["cand"][key] >= DEBOUNCE: + mon["cand"][key] = 0 + self._event(key, now, step, n) + + def _event(self, key, now, step, name): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + e = dict(step=step, pred=key, ev=ev) + if name == RED: + e["red_pose"] = self.red_pose() + mon["events"].append(e) + return + if key not in mon["ever"]: + return # never achieved: nothing lost + cause = "other" + if self.held(name): + cause = "picked_up" + else: + lt = mon["last_touch"][name] + if lt is not None and step - lt[1] <= 60: + cause = lt[0] + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1))) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in ITEMS: + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return abs(float(d.qvel[self.dof])) < 0.2 + + def _where(self, name): + """F2-style location of an item relative to the box, robot-centric words""" + rel = self.to_box(envs.obj_pos(self.env, name)[:2]) + return f"{_fb(rel[0])} and {_lr(rel[1])} of the box's centre" + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in ITEMS if self.held(n)] + touching = self.robot_touching() + success = bool(all(vals.values()) and static and not held and not touching) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + on = sorted(self.lid_contacts()) + red_top = envs.obj_max_z(self.env, RED) - self.rim_z() + parts = [] + failure = None + if success: + parts.append("The red block and both blue cubes are inside the box and the lid is closed.") + else: + out_items = [n for n in ITEMS if not vals[f"{n}_in_box"]] + if not vals["lid_closed"] and on: + failure = "lid_blocked" + elif held: + failure = "held" + elif touching and all(vals.values()): + failure = "robot_touching" + elif out_items: + failure = ("red_sticks_out" if out_items == [RED] and self.over_box(RED) and red_top > RIM_TOL + else "item_not_in_box") + elif not vals["lid_closed"]: + failure = "lid_open" + else: + failure = "not_static" + if not vals["lid_closed"]: + txt = f"The lid is not closed (open {self.lid_deg():.0f} degrees)" + if on: + names = " and ".join("the red block" if n == RED else "a blue cube" for n in on) + txt += f": it rests on {names}" + parts.append(txt + ".") + for n in out_items: + nm = "The red block" if n == RED else "A blue cube" + if self.held(n): + parts.append(f"{nm} is still held by the gripper.") + elif self.over_box(n) and envs.obj_max_z(self.env, n) > self.rim_z() + RIM_TOL: + top = envs.obj_max_z(self.env, n) - self.rim_z() + pose = self.red_pose() if n == RED else "resting" + parts.append(f"{nm} is in the box but sticks out {100 * top:.1f} cm above the rim ({pose}).") + else: + parts.append(f"{nm} is not in the box: its centre is {self._where(n)}.") + if touching and all(vals.values()): + parts.append("The robot was still pressing on the " + " and ".join(touching) + " at the end.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["n_blocked"]: + parts.append(f"The lid came down on an item {mon['n_blocked']} time(s) during the attempt.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + false_bottom=bool(inst["false_bottom"]), n_lid_blocked=mon["n_blocked"], + lid_blocked_max_deg=round(mon["blocked_max_deg"], 1), red_relaid=mon["red_relaid"], + red_placed_upright_in_box=mon["red_up_in_box"], red_pose=self.red_pose(), + red_top_above_rim_cm=round(100 * red_top, 1), lid_on=on, + lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1), + lid_closes=mon["closes"], knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted primitives (perfect perception) + def _settle_item(self, name, max_checks=20): + """keep the arm still until `name` has stopped moving (a tipped block rolls on for a moment)""" + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _grasp_yaw(self, name): + """fingers across a 4 cm side: for the lying red block across its long axis, else yaw mod 90 deg""" + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + if name == RED and self.red_pose() != "upright": + ax = R[:, 2] + yaw = float(np.arctan2(ax[1], ax[0])) # closing direction (-sin, cos) is then across the long axis + return float((yaw + np.pi / 2) % np.pi - np.pi / 2) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _grasp_z(self, name): + """grasp point height above the table for a top-down grasp of `name` where it is""" + zmin = envs.obj_min_z(self.env, name) - envs.TABLE_Z + zmax = envs.obj_max_z(self.env, name) - envs.TABLE_Z + if name == RED and self.red_pose() == "upright": + z = zmin + 0.0425 # 4.25 cm up the 7.5 cm block (0.5 cm above its centre) + else: + z = (zmin + zmax) / 2 + if self.over_box(name): # the hand (2.4 cm above the grasp point) stays above the rim + z = max(z, Z_HAND_MIN, WALL_H + 0.016 if zmax > WALL_H + 0.02 else 0.0) + z = min(z, zmax - 0.004) + return z + + def pick(self, name, z_carry=Z_CARRY, tries=2): + """top-down grasp of `name` where it is, lift to z_carry (a missed grasp is retried once, as anyone would); + returns the grasp point's height above the item's bottom, or None if the grasp failed""" + sk = self.sk + Z = envs.TABLE_Z + for _ in range(tries): + self._settle_item(name) + p = envs.obj_pos(self.env, name) + yaw = self._grasp_yaw(name) + zg = self._grasp_z(name) + zbot = envs.obj_min_z(self.env, name) - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw) + sk.hold(8) # let a large wrist turn settle before going down (else the hand drifts ~1 cm near the table) + sk.move_to([p[0], p[1], Z + zg], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if self.held(name): + return zg - zbot + sk.set_gripper(False, steps=8) + return None + + def place(self, dest_xy, z_rel, yaw, z_carry=Z_CARRY): + """carry to above dest at z_carry, lower to z_rel (or until the item / hand rests on something), release, lift""" + sk = self.sk + Z = envs.TABLE_Z + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=yaw) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003, max_steps=80) + sk.set_gripper(False, steps=12) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry]) + + def put_in_box(self, name, u, v=0.0, noise=None, z_carry=Z_CARRY): + """pick `name` as it is (the red block upright or lying) and lower it into the box at (u, v) (box frame) as if + the box were deep (the hand stops above the rim), release. The lying red block is turned across the box.""" + off = self.pick(name, z_carry=z_carry) + if off is None: + return False + yaw = np.pi / 2 if name == RED and self.red_pose() == "lying" else self.sk.yaw + d = self.from_box([u, v]) + (np.asarray(noise, float) if noise is not None else 0.0) + self.place(d, max(Z_HAND_MIN, FLOOR_T + off + 0.005), yaw, z_carry=z_carry) + return True + + def red_slot(self): + return SLOT_U["red_lying"] if self.red_pose() == "lying" else SLOT_U["red_upright"] + + def tip_over(self, name, direction, z_push=0.055, speed=0.10): + """push the standing item's upper part with the closed fingers along `direction` (xy) so that it falls over""" + sk = self.sk + Z = envs.TABLE_Z + d = np.asarray(direction, float) + d = d / np.linalg.norm(d) + p = envs.obj_pos(self.env, name) + s = p[:2] - d * 0.06 + e = p[:2] + d * 0.035 + yaw = float(np.arctan2(d[1], d[0])) - np.pi / 2 # finger closing direction along the push + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], Z + 0.13], yaw=yaw) + sk.move_to([s[0], s[1], Z + z_push], tol=0.004) + sk.move_to([e[0], e[1], Z + z_push], speed=speed, tol=0.006) + sk.move_to([e[0], e[1], Z + 0.13], speed=0.3) + self._settle_item(name) + return self.red_pose() if name == RED else None + + def _tip_direction(self, name): + """outward along y (away from the other items, which stand 16 cm apart in a row)""" + y = envs.obj_pos(self.env, name)[1] + return np.array([0.0, 1.0 if y >= 0 else -1.0]) + + def lay_down(self, name=RED, **kw): + """tip the standing block over on the table (up to two pushes); True if it lies""" + for _ in range(2): + if self.red_pose() == "lying": + return True + self.tip_over(name, self._tip_direction(name), **kw) + return self.red_pose() == "lying" + + def take_out_red(self): + """pick the red block out of the box and stand it on its start spot""" + off = self.pick(RED) + if off is None: + return False + self.place(self.inst["start"][RED], off + 0.004, self.sk.yaw) + self._settle_item(RED) + return True + + def _grasp_knob(self, yaw=-np.pi / 2): + """open the fingers, come down on the knob at wrist yaw -90 deg (fingers across the stem), close. Always -90 + (not its gripper-symmetric twin +90): with the lid hanging on its stop beside the box the arm reached the knob + at -90 in every instance, but at +90 it stopped 2-3 cm short against the lid (validate seed 1004: the lying + block's grasp yaw had landed on +90 by numerical chance and the final close missed the knob twice). A 180 deg + wrist turn is avoided by passing through yaw 0 (see Skills.wrap_yaw).""" + sk = self.sk + k = self.knob_xyz() + for attempt in range(2): + sk.set_gripper(False, steps=8) + if abs(sk.yaw - yaw) > np.pi / 2 + 0.1: + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0, wrap_yaw=False) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=yaw, wrap_yaw=False) + sk.hold(5) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + if sk.holding_knob() or attempt: + break + # missed (measured once in 40 validation attempts: after a long sequence of wrist turns the arm's posture + # had drifted and it stopped 3-4 cm short of the knob hanging far to the side): open, go back to a neutral + # pose over the box at yaw 0 (the OSC's null-space term straightens the arm there) and try once more + sk.set_gripper(False, steps=8) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.10]) + c = self.from_box([0.0, 0.0]) + sk.move_to([c[0], c[1], envs.TABLE_Z + 0.28], yaw=0.0, wrap_yaw=False) + sk.hold(10) + return k + + def open_lid(self, over=0.04, up=0.16): + """grasp the knob (fingers across its stem); straight up 10 cm; straight to `over` m beyond the hinge, `up` m + above it; release; lift""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([h[0], h[1] + sg * over, h[2] + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1] - sg * 0.04, e[2] + 0.05]) + sk.hold(25) + + def close_lid(self, away=0.08, up=0.10): + """grasp the knob where it is; straight up 10 cm; straight to `away` m on the knob side of the hinge; release""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], k[1], k[2] + up]) + sk.move_to([h[0], h[1] - sg * away, max(k[2], h[2]) + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(30) + + def press_lid(self): + """the natural retry when the lid did not shut: grasp the knob where it is and push it down towards closed""" + sk = self.sk + k = self._grasp_knob() + h = self.hinge_point() + sg = self.hinge_sign() + sk.move_to([k[0], h[1] - sg * (LX + 0.01), h[2] - 0.01], speed=0.1) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.08]) + sk.hold(30) + + def _fallen(self): + """items that ended up outside the box (not merely sticking out of it)""" + return [n for n in ITEMS if not self.in_box(n) and not self.over_box(n) and not self.held(n)] + + def _replace_fallen(self, done, noise=None, z_carry=Z_CARRY): + for n in [n for n in self._fallen() if n in done]: + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=(noise or {}).get(n), z_carry=z_carry) + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + noise = params.get("noise") or {} + zc = params.get("z_carry", Z_CARRY) + self.open_lid(**params.get("open", {})) + done = [] + for n in ITEMS: + if n == RED and params.get("lay_first"): + self.lay_down(RED) + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=noise.get(n), z_carry=zc) + done.append(n) + self._replace_fallen(done, noise, zc) # looks after every step: re-places an item that fell outside + self.close_lid(**params.get("close", {})) + if params.get("check") == "naive": + self.naive_check(noise, zc) + elif params.get("check") == "fix": + self.check_and_fix() + self.sk.hold(10) + + def naive_check(self, noise=None, z_carry=Z_CARRY): + """Sonnet-like look before finishing, without the insight: a lid that did not shut is pushed down once (re-closed + if it is still open past upright); an item outside the box is put back as it is (the red block upright)""" + if not self.lid_closed(): + if self.lid_deg() > 90: + self.close_lid() + else: + self.press_lid() + if self._fallen(): + if self.lid_deg() < 90: + self.open_lid() + self._replace_fallen(list(ITEMS), noise, z_carry) + self.close_lid() + + def check_and_fix(self, rounds=2): + """look at every stage; if the red block is not inside below the rim (it stands up out of a shallow box and + holds the lid open), take it out, lay it down on the table and put it in lying; re-place anything outside the + box; close the lid""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()) and not any(self.held(n) for n in ITEMS): + return True + bad = [n for n in ITEMS if not v[f"{n}_in_box"]] + if self.lid_deg() < 90 and (bad or self.lid_contacts()): + self.open_lid() + for n in bad: + if n == RED and self.red_pose() != "lying": + if self.over_box(RED): + self.take_out_red() + self.lay_down(RED) + self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n]) + if self.lid_deg() > 90 or not self.lid_closed(): + self.close_lid() + return all(self.stage_values().values()) + + def default_params(self, inst): + """Sonnet-like: open the lid, items in the listed order, each put in as found (the block upright), carried + 16 cm up, looks after every step (re-places an item that fell outside), closes the lid, pushes a lid that did + not shut down once, finishes""" + return dict(lay_first=False, check="naive") + + def oracle_params(self, inst): + """knows the inner depth: lays the block down first in a shallow box; checks every stage at the end""" + return dict(lay_first=bool(inst["false_bottom"]), check="fix") + + def adapt_params(self, inst, history): + """attempt >= 2 (after a failure): lay the block down before putting it in, then check and fix""" + return dict(lay_first=True, check="fix") + + def blind_params(self, inst, attempt, rng): + """the natural behaviour again with small random variations, no history""" + return dict(lay_first=False, check="naive", + noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS}, + z_carry=float(rng.uniform(0.13, 0.19)), + open=dict(over=float(rng.uniform(0.02, 0.06)), up=float(rng.uniform(0.14, 0.18))), + close=dict(away=float(rng.uniform(0.06, 0.10)))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = the natural placement plus a real check and fix (takes the + block out and lays it down when the lid is blocked), later attempts lay it down first; blind: natural with + random variations; switch (extra control): natural, then lay it down first from attempt 2, no real check""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(lay_first=False, check="fix") if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(lay_first=True, check="naive") + elif kind == "oracle_noise": # robustness check: oracle with +-5 mm placement noise + params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS}) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive", "oracle_noise"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_lid_box.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_lid_box.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c6c649bba53e7fa77a0539b7034c73eb0081f2 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_lid_box.py @@ -0,0 +1,715 @@ +"""LH lid_box: put three blocks on their marks, then open a box, put a red cube in, close it -- the lid falls open onto +the marks behind the box and shoves the blocks standing there off their marks. + +Family: long-horizon self-disturbance ("state_restoration"): the agent's own normal later-stage action (opening the +lid) physically breaks earlier progress (blocks on marks); it has to notice and restore it before finishing (within an +attempt), or learn to open the box first (across attempts; the final-state judge does not enforce an order). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a flat wooden box (fixture, 12 x 16 cm, walls 3.2 cm, lid 0.6 cm) whose lid is hinged along its far edge; a black + ball knob sticks out of the middle of the lid's front edge. The lid is heavy (0.3 kg) and has no damping: once it + is lifted past vertical it falls backward and comes to rest on a stop (hidden angle) or on whatever is behind the + box; + * three 6 cm cubes ("blocks", blue / green / yellow; light, 54 g, and slippery, mu 0.25) in a row in front of the box + together with a small red cube (2.2 cm); + * three square marks (7.6 cm, outline + light fill) in the blocks' colours: two right behind the box (their near + edge 0.2-1.7 cm from the box's back wall), one beside the box. + +Hidden variable: the lid's opening stop (0 = closed, 90 = upright, 180 = flat behind the box): "far", uniform in FAR +(138-165 deg), in 13 of every 20 consecutive seeds, else "near", uniform in NEAR (100-113 deg). Before the lid is opened +nothing shows it. A far lid lands on the top edge of the blocks standing behind the box and its weight shoves them +away from the robot ("forward") off their marks (measured: 4-10 cm); a near lid comes to rest above them. Stops of +~115-135 deg are left out on purpose: there the lid only grazes the blocks (1-3 cm, right at the tolerance). + +Why the natural order fails: the instruction lists the blocks first (as a user would), so the natural plan places the +blocks, opens the lid (it falls back onto them), puts the cube in, closes the lid and finishes without looking at the +marks again. What must be learned: re-check every stage before finishing and put knocked blocks back after closing the +lid (within the attempt), or open the box first / place the blocks behind it last (across attempts). + +Lid mechanics for agents (`LidSkills`, measured, see the task card): grasping the ball knob from above (fingers on its +left and right, the default yaw) makes a pivot -- the ball turns freely between the fingers about the hinge axis. While +the knob is held, the arm is compliant along the hinge constraint: a commanded straight move is projected onto the +knob's circle around the hinge (at most 1 cm per control step; ~0.07 m/s along the arc in the agent self-test), so +"up 10 cm, then back over the hinge, release" opens the lid and "up, then forward, release" closes it; a move that +makes no more progress ends early (like KeySkills' stalling wrist in l7_key_turn). Without the compliance, all 6 +typical straight-move sequences tried (prototype: this lid with a 2 cm stem, 2026-10-09) pulled the knob out of the +fingers and the lid fell shut; with an earlier, lighter lid only a 3-segment approximation of the arc opened it. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (all blocks on +their marks, red cube in the box, lid closed, nothing held, scene static) plus an event log of every stage predicate +(achieved / lost / restored, with step and cause) for the server log; F1 gives the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +# ---------------------------------------------------------------- geometry / physics +BOX = "box_1" +BOX_MODEL = "lff_lh_lid_box" +BOX_D, BOX_W = 0.12, 0.16 # outer depth (x) and width (y) +WALL_H, WALL_T, FLOOR_T = 0.032, 0.008, 0.006 +LID_T, LID_MASS = 0.006, 0.30 +KNOB_R, STEM_L = 0.013, 0.032 +HINGE_DAMP, HINGE_FRIC = 0.002, 0.002 +IN_X = BOX_D / 2 - WALL_T # inner half sizes of the cavity +IN_Y = BOX_W / 2 - WALL_T + +BLOCK = 0.06 # cube edge +BLOCK_DENS = 250.0 # -> 54 g +BLOCK_MU = 0.25 +CUBE_E = 0.022 # red cube edge +MARK_HALF = 0.038 +MARK_LINE = 0.004 +TOL = 0.020 # block centre within 2 cm (per axis) of its mark's centre +FLAT_COS = np.cos(np.radians(15.0)) +CUBE_MARGIN = 0.004 +LID_CLOSED = np.radians(4.0) +# hidden stop (deg): in a fraction P_FAR of the instances the lid opens far back, uniform in FAR (it lands on blocks +# standing behind the box and shoves them 4-10 cm), otherwise it stops near upright, uniform in NEAR (it comes to rest +# above them). Far / near is balanced per block of 20 consecutive seeds (13 / 7), see sample_instance. +# Bimodal on purpose: stops between ~115 and ~135 deg make the lid graze the blocks and push them 1-3 cm, i.e. right +# at the tolerance, which is neither a clean disturbance nor a clean no-disturbance (measured, see the task card). +P_FAR = 0.65 +FAR = (138.0, 165.0) +NEAR = (100.0, 113.0) +GAP_LO, GAP_HI = 0.002, 0.017 # near edge of a behind-mark to the box's back wall (block near face +0.8 cm further) + +COLORS = ("blue", "green", "yellow") +RGBA = dict(blue=(0.15, 0.30, 0.85, 1.0), green=(0.10, 0.60, 0.20, 1.0), yellow=(0.92, 0.76, 0.10, 1.0)) +BLOCKS = {c: f"{c}_block_1" for c in COLORS} +MARKS = {c: f"{c}_mark_1" for c in COLORS} +CUBE = "red_cube_1" + +Z_CARRY = 0.13 # scripted transit height of the grasp point above the table when carrying a block +Z_KNOB = WALL_H + LID_T / 2 # knob centre above the table with the lid closed +SMAX = 0.010 # max projected displacement command per control step while the knob is held +STALL = 12 + + +def box_lid_xml(name, body_rgba=(0.55, 0.38, 0.22, 1.0), lid_rgba=(0.70, 0.52, 0.32, 1.0), knob_rgba=(0.10, 0.10, 0.11, 1.0)): + hx, hy = BOX_D / 2, BOX_W / 2 + parts = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)), + ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)), + ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))] + g = [] + # box: contype 2 / conaffinity 1 and lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the + # hinge limit holds it closed), but both collide with the robot, the table and the free objects (contype 1) + for k, (pos, s) in enumerate(parts): + g.append(f'') + g.append(f'') + m, L = LID_MASS, BOX_D + lid_c = (-L / 2, 0, LID_T / 2) + lid_s = (L / 2, hy, LID_T / 2) + stem = (-L - STEM_L / 2, 0, LID_T / 2) + ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2) + lid = [f'', + # placeholder range: the opening stop is set per instance (apply_instance) + f'', + f'', + f'', + f'', + f'', + f'', + f''] + shell = "\n ".join(g) + lid_xml = "\n ".join(lid) + return f""" + + + + {shell} + + {lid_xml} + + + + + + + +""" + + +def mark_xml(name, rgba): + """Flat, visual-only square drawn on the table: a light fill plus an outline in the block's colour.""" + fill = tuple(0.55 + 0.45 * c for c in rgba[:3]) + (1.0,) + o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill), + ((0, i + w / 2, 0.0010), (o, w / 2, 0.0002), rgba), + ((0, -i - w / 2, 0.0010), (o, w / 2, 0.0002), rgba), + ((i + w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba), + ((-i - w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, o) + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +class LidSkills(Skills): + """Skills for the lid box: a per-step stage monitor, and a hinge-compliant arm while the knob is held (see the + module docstring).""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + self.latched = False + self.rad0 = None + self.y0 = None + self.knob_steps = 0 # control steps driven with the knob held (compliant mode) + self.knob_grasps = 0 + + def holding_knob(self): + """both fingers (pad or finger body) touch the knob ball or its stem""" + g = self.env.robots[0].gripper + return bool(self.env._check_grasp(gripper=[g.important_geoms["left_finger"], g.important_geoms["right_finger"]], + object_geoms=self.task.knob_geom_names)) + + def _act(self, dpos, drot, grip): + if self.latched: + e = self.eef_pos() + if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035: + self.latched = False # opened, or the knob slipped out of the fingers + else: + hx, hz = self.task.hinge_xz() + r = np.array([e[0] - hx, e[2] - hz]) + rn = max(float(np.linalg.norm(r)), 1e-6) + tng = np.array([-r[1], r[0]]) / rn + s = float(np.clip(dpos[0] * tng[0] + dpos[2] * tng[1], -SMAX, SMAX)) + corr = (self.rad0 - rn) * r / rn + dpos = np.array([s * tng[0] + corr[0], self.y0 - e[1], s * tng[1] + corr[1]]) + self.knob_steps += 1 + super()._act(dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + if close and self.holding_knob(): + e = self.eef_pos() + hx, hz = self.task.hinge_xz() + self.latched = True + self.rad0 = float(np.hypot(e[0] - hx, e[2] - hz)) + self.y0 = float(e[1]) + self.knob_grasps += 1 + elif not close: + self.latched = False + return rep + + def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True): + """Skills.move_to plus an early stop when the knob is held and the arm has stopped making progress.""" + tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0) + if yaw is not None: + self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw) + R = self._R() + p0 = self.eef_pos() + dist = np.linalg.norm(tgt - p0) + direction = (tgt - p0) / max(dist, 1e-9) + s = 0.0 + hist = [] + stalled = False + for k in range(max_steps): + if speed is not None: + s = min(dist, s + speed * DT) + ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5) + else: + ref = tgt + self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + cur = self.eef_pos() + if np.linalg.norm(tgt - cur) < tol and (speed is None or s >= dist): + break + hist.append(cur) + if (self.latched and len(hist) > STALL and (speed is None or s >= dist) + and np.linalg.norm(hist[-1] - hist[-1 - STALL]) < 0.002): + stalled = True + break + rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02), + pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=stalled) + self.log.append(rep) + return rep + + +@register_task +class LidBox(LFFTask): + name = "lh_lid_box" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Utilize") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 110 # careful oracle ~45-55 commands + restoring two blocks (~14) + looking around + instruction = ("Put each of the three coloured blocks on the square mark of the same colour on the table. Then open " + "the lid of the wooden box (lift it by the black knob on its front edge), put the red cube inside " + "the box, and close the lid.") + instruction_indirect = ("Set the blue, green and yellow cubes onto the outlined squares of matching colour. Then open " + "the flat wooden case (its lid lifts by the black ball at the front), place the small red " + "cube in it and shut the lid.") + agent_object_names = ["blue block", "green block", "yellow block", "red cube", "wooden box", "lid knob", + "blue mark", "green mark", "yellow mark"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffLhLidBox", box_lid_xml(BOX_MODEL), free=False) + b = BLOCK / 2 + objs, fx = [], [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))] + for i, c in enumerate(COLORS): + blk = register_generated(f"LffLhBlock{c.title()}", + box_xml(f"lff_lh_block_{c}", (b, b, b), RGBA[c], density=BLOCK_DENS, + friction=(BLOCK_MU, 0.005, 0.0001)).replace(_SOLID, "")) + mark = register_generated(f"LffLhMark{c.title()}", mark_xml(f"lff_lh_mark_{c}", RGBA[c]), free=False) + objs.append((BLOCKS[c], blk, f"{c}_block_region", (-0.31, -0.22 + 0.15 * i, -0.29, -0.20 + 0.15 * i))) + fx.append((MARKS[c], mark, f"{c}_mark_region", (0.0, -0.22 + 0.15 * i, 0.02, -0.20 + 0.15 * i))) + cube = register_generated("LffLhRedCube", box_xml("lff_lh_red_cube", (CUBE_E / 2,) * 3, (0.85, 0.10, 0.08, 1.0), + density=500)) + objs.append((CUBE, cube, "red_cube_region", (-0.31, 0.24, -0.29, 0.26))) + return write_bddl(self.name, "put the blocks on their marks and the red cube in the box", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = m.jnt_qposadr[self.jid] + self.dof = m.jnt_dofadr[self.jid] + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")} + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.mark_bid = {c: m.body_name2id(self.env.fixtures_dict[MARKS[c]].root_body) for c in COLORS} + self.block_gids = {c: set(envs.obj_geom_ids(self.env, BLOCKS[c])) for c in COLORS} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03)) + hinge_x = bx + BOX_D / 2 + order = [str(c) for c in rng.permutation(COLORS)] # [behind-left, behind-right, side] + side = 1.0 if rng.random() < 0.5 else -1.0 + marks = {} + gaps = {} + for c, sy in zip(order[:2], (1.0, -1.0)): + g = float(rng.uniform(GAP_LO, GAP_HI)) + gaps[c] = g + marks[c] = [hinge_x + g + MARK_HALF, by + sy * 0.05 + float(rng.uniform(-0.005, 0.005))] + marks[order[2]] = [bx + float(rng.uniform(-0.03, 0.03)), by + side * (BOX_W / 2 + 0.025 + MARK_HALF)] + # start row in front of the box: four slots outside the knob's lane, shuffled (3 blocks + red cube) + slots = [-0.22, -0.11, 0.11, 0.22] # 11 cm apart: room for the open fingers next to a 6 cm block + items = [BLOCKS[c] for c in COLORS] + [CUBE] + perm = rng.permutation(len(items)) + start = {items[i]: [float(-0.31 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + rng.random() # (draw kept so the other parameters stay the same) + # balanced blocks like l7_key_turn: exactly round(20 * P_FAR) of every 20 consecutive seeds open far + far = bool((int(seed) * 7) % 20 < round(20 * P_FAR)) + stop = float(rng.uniform(*(FAR if far else NEAR))) + return dict(seed=int(seed), box_xy=[bx, by], stop_deg=stop, lid_far=far, marks=marks, + behind=order[:2], side_color=order[2], side="left" if side > 0 else "right", gaps=gaps, start=start, + start_yaw={k: float(rng.uniform(-0.3, 0.3)) for k in items}) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])] + m.jnt_solref[self.jid] = [0.01, 1.0] + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + for c in COLORS: + x, y = inst["marks"][c] + m.body_pos[self.mark_bid[c]] = [x, y, envs.TABLE_Z + 0.0002] + m.body_quat[self.mark_bid[c]] = [1.0, 0.0, 0.0, 0.0] + for name, xy in inst["start"].items(): + envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name]) + for c in COLORS: + envs.set_friction(self.env, BLOCKS[c], BLOCK_MU) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = LidSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def hinge_xz(self): + return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def _flat(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + return bool(np.max(np.abs(R[2])) >= FLAT_COS) + + def block_offset(self, c): + p = envs.obj_pos(self.env, BLOCKS[c]) + return p[:2] - np.asarray(self.inst["marks"][c]) + + def on_mark(self, c, tol=TOL): + name = BLOCKS[c] + p = envs.obj_pos(self.env, name) + off = p[:2] - np.asarray(self.inst["marks"][c]) + return bool(np.max(np.abs(off)) <= tol and p[2] < envs.TABLE_Z + BLOCK / 2 + 0.01 and self._flat(name) + and not self.held(name)) + + def cube_in_box(self): + p = envs.obj_pos(self.env, CUBE) + rel = p[:2] - np.asarray(self.inst["box_xy"]) + return bool(abs(rel[0]) <= IN_X - CUBE_MARGIN and abs(rel[1]) <= IN_Y - CUBE_MARGIN + and p[2] < envs.TABLE_Z + WALL_H and not self.held(CUBE)) + + def lid_closed(self): + return self.lid_q() <= LID_CLOSED + + def stage_values(self): + v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS} + v["cube_in_box"] = self.cube_in_box() + v["lid_closed"] = self.lid_closed() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"cube_in_box": False}, ever=set(), + lost=set(), events=[], last_touch={c: None for c in COLORS}, lid_hits=set(), + lid_open_max=0.0, lid_opened=False, lid_open_steps=[], lid_close_steps=[], step=0, + lid_prev=0.0, lid_moving_step=-10 ** 9) + + def _touches(self): + """Per block: was it touched by the lid / the robot in this control step?""" + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for cc in COLORS: + g = self.block_gids[cc] + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.lid_gids: + out[cc] = "lid" + elif other in self.robot_gids and out.get(cc) != "lid": + out[cc] = "robot" + return out + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + for c, who in self._touches().items(): + mon["last_touch"][c] = (who, step) + if who == "lid": + mon["lid_hits"].add(c) + q = self.lid_deg() + if q > 95.0 and abs(q - mon["lid_prev"]) > 0.5: + mon["lid_moving_step"] = step # the open lid is swinging (its contacts can last less than a control step) + mon["lid_prev"] = q + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if not mon["lid_opened"] and q > 90.0: + mon["lid_opened"] = True + mon["lid_open_steps"].append(step) + mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical")) + elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED): + mon["lid_opened"] = False + mon["lid_close_steps"].append(step) + mon["events"].append(dict(step=step, pred="lid", ev="closed")) + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + for c in COLORS: + key = f"{c}_on_mark" + was = mon["state"][key] + now = self.on_mark(c, TOL if not was else TOL + 0.005) # hysteresis against jitter at the border + if now != was: + self._event(key, now, step, c) + was = mon["state"]["cube_in_box"] + now = self.cube_in_box() + if now != was: + self._event("cube_in_box", now, step, None) + + def _event(self, key, now, step, color): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + if key in mon["lost"]: + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + else: + cause = "other" + if color is not None: + if self.held(BLOCKS[color]): + cause = "picked_up" + else: + lt = mon["last_touch"][color] + if lt is not None and step - lt[1] <= 60: + cause = lt[0] + if cause == "other" and step - mon["lid_moving_step"] <= 20 and color in self.inst["behind"]: + cause = "lid" # lost while the open lid was swinging down onto the blocks behind the box + elif self.held(CUBE): + cause = "picked_up" + mon["lost"].add(key) + ev = dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1)) + if color is not None: + ev["offset_cm"] = (100 * self.block_offset(color)).round(1).tolist() + mon["events"].append(ev) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in [BLOCKS[c] for c in COLORS] + [CUBE]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return abs(float(d.qvel[self.dof])) < 0.2 + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in [BLOCKS[c] for c in COLORS] + [CUBE] if self.held(n)] + success = bool(all(vals.values()) and static and not held) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + lid_knocks = [e for e in regress if e.get("cause") == "lid"] + parts = [] + if success: + failure = None + parts.append("All three blocks are on their marks, the red cube is in the box and the lid is closed.") + else: + off = [c for c in COLORS if not vals[f"{c}_on_mark"]] + failure = ("block_off_mark" if off else "cube_not_in_box" if not vals["cube_in_box"] else + "lid_open" if not vals["lid_closed"] else "held" if held else "not_static") + for c in off: + o = self.block_offset(c) + name = BLOCKS[c] + if self.held(name): + parts.append(f"The {c} block is still held by the gripper.") + continue + txt = (f"The {c} block is not on the {c} mark: its centre is {_fb(o[0])} and {_lr(o[1])} of the mark's " + f"centre") + if not self._flat(name): + txt += " and it is tipped over" + why = [e for e in regress if e["pred"] == f"{c}_on_mark"] + if f"{c}_on_mark" not in mon["ever"]: + txt += " (it was never on its mark)." + elif why and why[-1].get("cause") == "lid": + txt += (f" (it had been on its mark; the lid pushed it off when it fell open to " + f"{why[-1]['lid_deg']:.0f} degrees).") + elif why and why[-1].get("cause") == "robot": + txt += " (it had been on its mark; the robot knocked it off)." + else: + txt += " (it had been on its mark earlier)." + parts.append(txt) + if not vals["cube_in_box"]: + if self.held(CUBE): + parts.append("The red cube is still held by the gripper.") + else: + p = envs.obj_pos(self.env, CUBE) + rel = p[:2] - np.asarray(inst["box_xy"]) + parts.append(f"The red cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the " + f"box's centre.") + if not vals["lid_closed"]: + parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees).") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["lid_open_max"] < 90.0: + parts.append("The lid was never opened past upright.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + n_lid_knocks=len(lid_knocks), lid_hits=sorted(mon["lid_hits"]), + lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1), + knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps, + block_offsets_cm={c: (100 * self.block_offset(c)).round(1).tolist() for c in COLORS}, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) # a cube: grasp yaw mod 90 deg + + def pick_place(self, name, dest_xy, z_rel, z_carry=Z_CARRY, noise=None, dest_yaw=0.0): + """Top-down pick of `name` at its centre, carry at `z_carry` (grasp point above the table), release with the + grasp point `z_rel` above the table at `dest_xy`, lift.""" + sk = self.sk + Z = envs.TABLE_Z + p = envs.obj_pos(self.env, name) + yaw = self._grasp_yaw(name) + zg = p[2] - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw) + sk.move_to([p[0], p[1], Z + zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + d = np.asarray(dest_xy, float) + (np.asarray(noise, float) if noise is not None else 0.0) + sk.move_to([d[0], d[1], Z + z_carry], yaw=dest_yaw) + sk.move_to([d[0], d[1], Z + z_rel], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], Z + z_carry]) + return True + + def place_block(self, c, noise=None): + return self.pick_place(BLOCKS[c], self.inst["marks"][c], BLOCK / 2 + 0.004, noise=noise) + + def put_cube(self, noise=None): + bx, by = self.inst["box_xy"] + return self.pick_place(CUBE, [bx, by], FLOOR_T + CUBE_E / 2 + 0.008, z_carry=0.12, noise=noise) + + def _grasp_knob(self): + sk = self.sk + k = self.knob_xyz() + sk.set_gripper(False, steps=8) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + return k + + def open_lid(self, back=0.03, up=0.16): + """grasp the knob; straight up 10 cm; straight to `back` m behind the hinge, `up` m above it; release; lift""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx + back, k[1], hz + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06]) + sk.hold(20) + + def close_lid(self): + """grasp the knob where it is; straight up 10 cm; straight forward to 8 cm in front of the hinge; release""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx - 0.08, k[1], k[2] + 0.10]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(20) + + def restore(self, rounds=2): + """look at every stage and fix what is wrong (lid open -> close it; cube out -> put it in; block off -> put it + back), up to `rounds` passes""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + if not v["cube_in_box"]: + if self.lid_q() < np.radians(95): + self.open_lid() + self.put_cube() + self.close_lid() + elif not v["lid_closed"]: + self.close_lid() + for c in COLORS: + if not self.on_mark(c): + self.place_block(c) + return all(self.stage_values().values()) + + def execute(self, inst, params): + order = params.get("order") or list(COLORS) + noise = params.get("noise") or {} + if params["plan"] == "blocks_first": + for c in order: + self.place_block(c, noise.get(c)) + self.open_lid(**params.get("open", {})) + self.put_cube(noise.get("cube")) + self.close_lid() + else: # "lid_first": open, cube in, close, then the blocks + self.open_lid(**params.get("open", {})) + self.put_cube(noise.get("cube")) + self.close_lid() + for c in order: + self.place_block(c, noise.get(c)) + if params.get("check"): + self.restore() + self.sk.hold(10) + + def default_params(self, inst): + return dict(plan="blocks_first", check=False) + + def oracle_params(self, inst): + return dict(plan="lid_first", check=True) + + def adapt_params(self, inst, history): + """Used from attempt 2 on, i.e. after a failed attempt (attempt 1 is the natural order plus a final check and + repair, see run_scripted): open the box, put the cube in and close it first, then place the blocks, check.""" + return dict(plan="lid_first", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural order again with small random variations (block order, placement, release point), no check""" + return dict(plan="blocks_first", check=False, order=[str(c) for c in rng.permutation(COLORS)], + noise={c: rng.normal(0.0, 0.004, 2).tolist() for c in COLORS}, + open=dict(back=float(rng.uniform(0.0, 0.05)), up=float(rng.uniform(0.14, 0.18)))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(plan="blocks_first", check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # extra control (not in validate's table): cross-attempt learning only, no re-check + params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check=False) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py new file mode 100644 index 0000000000000000000000000000000000000000..7369d4e23432eed637a47131d7c8f988e5eca7f0 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py @@ -0,0 +1,468 @@ +"""LH pantry_relatch: breakfast prep. Take the bread out of a hinged pantry box and put it on the plate, then put the +butter into the (now empty) box and close it. + +New mechanism (not a repeat of lh_lid_box / lh_shelf_droop / lh_false_bottom_lid): the box's closing catch is not a +static per-instance draw, it is a counter of how many times the box has already been closed in this attempt. A weak +spring (`OPEN_BIAS`) constantly nudges the lid open; a catch (`qfrc_applied`, same idiom as lh_shelf_droop's bracket) +counters it near the closed angle. The FIRST close always holds (LATCH0 beats the spring) even with a quick swing-and +-release. After one full open/close cycle the catch's holding strength is reduced (`DECAY`); a second quick-release +close is no longer enough and the lid creeps back open by itself during the mandatory settle window, with nothing +else touching it. The fix is not "close it again the same way" (that decays again); it is a firm press-and-hold +(`dwell`) at the closed angle before letting go, which engages a separate, non-decaying friction seat +(`SEAT_LATCH`) regardless of cycle count. + +Geometry/skills are reused unmodified from lh_lid_box.py (box_lid_xml, LidSkills): only the hinge's spring/latch +torques and the Python cycle counter are new. Protocol: cross, k = 5. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import LFFTask, register_task +from .lh_lid_box import (BOX_D, BOX_W, WALL_H, WALL_T, FLOOR_T, LID_T, LID_MASS, IN_X, IN_Y, HINGE_DAMP, box_lid_xml, + LidSkills) + +G = 9.81 +BOX = "box_1" +BOX_MODEL = "lff_pantry_box" + +BREAD_HALF = (0.032, 0.022, 0.011) # 6.4 x 4.4 x 2.2 cm flat loaf, fits the 3.2 cm interior height +BUTTER_HALF = (0.013, 0.013, 0.013) # 2.6 cm cube +BREAD_DENS, BUTTER_DENS = 400.0, 600.0 + +# ---------------------------------------------------------------- latch-fatigue mechanism +CLOSE_DEG = 4.0 # lid angle (deg) counted as "closed" for the final judge +BAND_DEG = 100.0 # angle range (deg) over which gravity is cancelled and the open bias/catch act (wide, so +# an unlatched lid drifts smoothly all the way open instead of sticking at a cutoff edge) +OPEN_BIAS = 0.05 # N*m: net torque pushing the lid open within the band, once gravity is cancelled +LATCH0 = 0.14 # N*m: catch strength on the FIRST close (always beats OPEN_BIAS) +DECAY = 0.30 # catch strength multiplier from the SECOND close on, if not seated +SEAT_LATCH = 0.18 # N*m: non-decaying strength if the close was seated (dwell-pressed) +DWELL_MIN = 20 # control steps (closed, knob held, no further motion) needed to seat a close +EXTRA_DAMP = 0.12 # N*m*s/rad added to the hinge dof so an unlatched drift takes a few seconds, not instant +GRAVITY_LEVER = BOX_D / 2 # lid's centre of mass offset from the hinge (box_lid_xml convention) +T_GRAV0 = LID_MASS * G * GRAVITY_LEVER + +SETTLE_MIN, SETTLE_MAX = 300, 600 # 15-30 s simulated, same convention as lh_shelf_droop + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +class RelatchSkills(LidSkills): + """LidSkills plus a dwell counter: control steps spent holding the knob still at the closed angle while latched. + `monitor_step` (run every control step via LidSkills._act, before this class's own _act resets the counter) + reads it at the instant the gripper opens near the closed angle to decide whether this close is 'seated'.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, task, recorder=recorder) + self.dwell = 0 + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) # LidSkills._act calls self.task.monitor_step() before returning here + if self.latched: + # the agent (or scripted policy) is actively holding the knob: never let the artificial drift fight + # that grasp (it caused the knob to wander off mid-regrasp during prototyping). + self.task.drift_active = False + if self.task.lid_deg() < CLOSE_DEG: + self.dwell += 1 + else: + self.dwell = 0 + else: + self.dwell = 0 + + +@register_task +class PantryRelatch(LFFTask): + name = "lh_pantry_relatch" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 5 + agent_max_steps = 130 + instruction = ("Open the lid of the wooden pantry box (lift it by the black knob) and take the bread out; put it " + "on the plate. Then open the box again, put the butter inside it, and close the lid. At the end " + "the bread must be on the plate, the butter inside the box, the lid closed, the gripper open and " + "clear, and the scene still.") + instruction_indirect = ("Lift the lid of the flat wooden case by its black ball knob and take out the little " + "loaf; set it on the round plate. Then open the case again, put the small pale cube " + "inside it, and shut the lid. Finish with the loaf on the plate, the cube inside the " + "case, the lid down, the gripper open, and nothing moving.") + agent_object_names = ["bread (small loaf)", "butter (small pale cube)", "wooden pantry box", "lid knob", "plate"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffPantryBox", box_lid_xml(BOX_MODEL), free=False) + bread = register_generated("LffPantryBread", box_xml("lff_pantry_bread", BREAD_HALF, (0.74, 0.52, 0.22, 1.0), + density=BREAD_DENS, friction=(0.7, 0.005, 0.0001))) + butter = register_generated("LffPantryButter", box_xml("lff_pantry_butter", BUTTER_HALF, (0.95, 0.92, 0.70, 1.0), + density=BUTTER_DENS, friction=(0.5, 0.005, 0.0001))) + objs = [("bread_1", bread, "bread_region", (-0.31, -0.01, -0.29, 0.01)), + ("butter_1", butter, "butter_region", (-0.31, 0.24, -0.29, 0.26)), + ("plate_1", "plate", "plate_region", (0.02, -0.26, 0.04, -0.24))] + fx = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))] + return write_bddl(self.name, "take the bread out, put it on the plate, put the butter in the box, close it", + objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = int(m.jnt_qposadr[self.jid]) + self.dof = int(m.jnt_dofadr[self.jid]) + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + sim = self.env.sim + if not getattr(sim, "_lhpr_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhpr_task", None) + if t is not None: + t._bracket() + + sim.step = step + sim._lhpr_wrapped = True + sim._lhpr_task = self + self.inst = None + self.mon = None + self.active_latch = LATCH0 + self.closes_done = 0 + self.drift_active = False + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03)) + plate_xy = [float(rng.uniform(0.0, 0.06)), float(rng.uniform(-0.27, -0.23))] + bread_xy = [bx + float(rng.uniform(-0.01, 0.01)), by + float(rng.uniform(-0.01, 0.01))] + butter_xy = [float(rng.uniform(-0.32, -0.28)), float(rng.uniform(0.22, 0.28))] + return dict(seed=int(seed), box_xy=[bx, by], plate_xy=plate_xy, bread_xy=bread_xy, butter_xy=butter_xy, + bread_yaw=float(rng.uniform(-0.2, 0.2)), latch=True) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + m.jnt_range[self.jid] = [0.0, np.radians(150.0)] + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + d.qfrc_applied[self.dof] = 0.0 + m.dof_damping[self.dof] = HINGE_DAMP + EXTRA_DAMP # absolute, not cumulative across repeated resets + self._move_keep_orientation("plate_1", inst["plate_xy"]) + envs.set_obj_pose(self.env, "bread_1", [bx, by, envs.TABLE_Z + FLOOR_T + BREAD_HALF[2] + 0.001], + yaw=inst["bread_yaw"]) + envs.set_obj_pose(self.env, "butter_1", [*inst["butter_xy"], envs.TABLE_Z + BUTTER_HALF[2] + 0.0005]) + self.closes_done = 0 + self.active_latch = LATCH0 + self.drift_active = False + + def _move_keep_orientation(self, name, xy, clearance=0.002): + qa, da = envs.free_joint_addr(self.env, name) + d = self.env.sim.data + d.qpos[qa:qa + 2] = xy + d.qvel[da:da + 6] = 0.0 + self.env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = dict(events=[], lid_open_max=0.0, armed=False) + self.sk = RelatchSkills(self.env, self, recorder=recorder) + return self.sk + + # ------------------------------------------------------------ latch physics + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def hinge_xz(self): + return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H + + def _bracket(self): + """Every MuJoCo substep. Only active between a just-finished, under-latched close and the next time the + agent actually grasps the knob again (self.drift_active, cleared the instant the knob is latched -- see + RelatchSkills._act): within BAND_DEG of closed, cancel gravity's closing pull and add a small constant + opening bias, net positive because the catch is too weak (self.active_latch < OPEN_BIAS whenever + drift_active is set True in the first place). A held-firmly close needs no artificial force at all: plain + gravity already keeps box_lid_xml's lid shut on its own, same as lh_lid_box.""" + d = self.env.sim.data + if not self.inst.get("latch", True) or not self.drift_active: + d.qfrc_applied[self.dof] = 0.0 # never leave a stale value applied once the drift is no longer armed + return + th = float(d.qpos[self.qa]) + # the closed rest angle overshoots the joint limit by a hair (contact softness), so the lower edge of the + # band must tolerate a small negative theta -- a strict "th >= 0" guard left qfrc_applied permanently 0 at + # the resting pose and the catch never engaged at all (measured during prototyping). + if np.radians(-3.0) <= th < np.radians(BAND_DEG): + grav = T_GRAV0 * max(np.cos(th), 0.0) + d.qfrc_applied[self.dof] = grav + OPEN_BIAS - self.active_latch + else: + d.qfrc_applied[self.dof] = 0.0 + + def _register_close(self, seated): + """Called once a close-then-release is detected. Decides the catch strength that will apply to THIS closed + state from now on (until the lid is reopened and closed again), and whether the artificial drift-open force + is armed (only when the catch is too weak to hold on its own).""" + if self.closes_done == 0: + self.active_latch = LATCH0 + elif seated: + self.active_latch = SEAT_LATCH + else: + self.active_latch = LATCH0 * DECAY + self.closes_done += 1 + self.drift_active = self.active_latch < OPEN_BIAS + self.mon["events"].append(dict(ev="closed", n=self.closes_done, seated=bool(seated), + active_latch=round(self.active_latch, 4), drift_armed=self.drift_active)) + + def monitor_step(self): + """Runs every control step (via LidSkills._act, for the scripted policies below and for a real agent's own + move_to/set_gripper calls alike). One-shot edge detector: 'armed' once the lid has been meaningfully open + (> 20 deg); the first step afterwards where it is back near closed AND the gripper is open counts as a + close event, scored seated/unseated from the dwell counter at that exact instant (before RelatchSkills._act + resets it for this same step -- see the call order note there).""" + mon = self.mon + if mon is None: + return + q = self.lid_deg() + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if q > 20.0: + mon["armed"] = True + if mon.get("armed") and q <= CLOSE_DEG and self.sk.grip < 0: + mon["armed"] = False + self._register_close(self.sk.dwell >= DWELL_MIN) + + # ------------------------------------------------------------ predicates + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def bread_on_plate(self): + p = envs.obj_pos(self.env, "bread_1") + d = np.linalg.norm(p[:2] - np.asarray(self.inst["plate_xy"])) + return bool(d < 0.05 and p[2] < envs.TABLE_Z + 0.06 and not self.held("bread_1")) + + def butter_in_box(self): + p = envs.obj_pos(self.env, "butter_1") + rel = p[:2] - np.asarray(self.inst["box_xy"]) + return bool(abs(rel[0]) <= IN_X - 0.004 and abs(rel[1]) <= IN_Y - 0.004 and p[2] < envs.TABLE_Z + WALL_H + and not self.held("butter_1")) + + def lid_closed(self): + return self.lid_q() <= np.radians(CLOSE_DEG) + + def stage_values(self): + return dict(bread_on_plate=self.bread_on_plate(), butter_in_box=self.butter_in_box(), lid_closed=self.lid_closed()) + + # ------------------------------------------------------------ scripted primitives + def pick_place(self, name, dest_xy, z_rel, z_carry=0.14, dest_yaw=0.0): + sk = self.sk + Z = envs.TABLE_Z + p = envs.obj_pos(self.env, name) + zg = p[2] - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=0.0) + sk.move_to([p[0], p[1], Z + zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + self.monitor_step() + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=dest_yaw) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry]) + self.monitor_step() + return True + + def take_bread(self): + return self.pick_place("bread_1", self.inst["plate_xy"], BREAD_HALF[2] + 0.004) + + def put_butter(self): + # placed closer to the hinge side and off to one side of the box centre, clear of where the far (knob) end + # of the lid sweeps most when re-opened for a repair (measured during prototyping: a butter cube resting + # under the box centre was occasionally grazed by that swing). + bx, by = self.inst["box_xy"] + target = [bx + 0.6 * IN_X, by + 0.5 * IN_Y] + return self.pick_place("butter_1", target, FLOOR_T + BUTTER_HALF[2] + 0.006, z_carry=0.12) + + def _grasp_knob(self): + sk = self.sk + k = self.knob_xyz() + sk.set_gripper(False, steps=8) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + return k + + def open_lid(self, back=0.03, up=0.16): + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx + back, k[1], hz + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06]) + sk.hold(20) + self.monitor_step() + + def close_lid(self, dwell=False): + """grasp the knob, carry it down the hinge's arc to the closed angle (the compliant knob-hold mechanism + clamps the physical joint limit at 0 deg, so a target far past closed just drives it fully shut); if dwell, + hold there (gripper still closed on the knob) for DWELL_MIN+ steps before releasing (seats the friction + catch); otherwise release immediately.""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + far_x = hx - (BOX_D + 0.20) + low_z = envs.TABLE_Z + 0.02 + for _ in range(4): + if self.lid_deg() <= CLOSE_DEG: + break + sk.move_to([far_x, sk.eef_pos()[1], low_z], tol=0.01, max_steps=150) + if dwell: + sk.hold(DWELL_MIN + 8) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(20) + self.monitor_step() + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in ("bread_1", "butter_1"): + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return abs(float(d.qvel[self.dof])) < 0.2 + + def outcome(self, inst): + sk = self.sk + n = 0 + while n < SETTLE_MAX: + sk.hold(10) + n += 10 + if n >= SETTLE_MIN and self._static(): + break + vals = self.stage_values() + held = [n for n in ("bread_1", "butter_1") if self.held(n)] + static = self._static() + success = bool(all(vals.values()) and static and not held) + if success: + failure = None + detail = "Bread is on the plate, butter is in the box, and the lid is closed." + else: + failure = ("bread" if not vals["bread_on_plate"] else "butter" if not vals["butter_in_box"] else + "lid_open" if not vals["lid_closed"] else "held" if held else "not_static") + parts = [] + if not vals["bread_on_plate"]: + p = envs.obj_pos(self.env, "bread_1") + rel = p[:2] - np.asarray(inst["plate_xy"]) + parts.append("The bread is still held." if self.held("bread_1") else + f"The bread is not on the plate: {_fb(rel[0])} and {_lr(rel[1])} of the plate's centre.") + if not vals["butter_in_box"]: + p = envs.obj_pos(self.env, "butter_1") + rel = p[:2] - np.asarray(inst["box_xy"]) + parts.append("The butter is still held." if self.held("butter_1") else + f"The butter is not in the box: {_fb(rel[0])} and {_lr(rel[1])} of the box's centre.") + if not vals["lid_closed"]: + parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees). It had been closed " + f"{self.closes_done} time(s) in this attempt; it did not stay shut on its own.") + if held: + parts.append(f"Still held: {', '.join(held)}.") + if not static and all(vals.values()): + parts.append("Something was still moving.") + detail = " ".join(parts) + return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + lid_final_deg=round(self.lid_deg(), 1), lid_open_max=round(self.mon["lid_open_max"], 1), + closes_done=self.closes_done, active_latch=round(self.active_latch, 4), + events=list(self.mon["events"]), detail=detail) + + # ------------------------------------------------------------ execution + scripted policies + def execute(self, inst, params): + self.open_lid() + if not self.take_bread(): + return + self.close_lid(dwell=params.get("dwell1", False)) + self.open_lid() + if not self.put_butter(): + return + self.close_lid(dwell=params.get("dwell2", False)) + if params.get("check", False): + # look back before finishing: wait long enough (same order as the final settle window) for an + # under-latched close to reveal itself, then fix it with a firm dwell close if it did -- a genuine + # same-attempt recovery, not just a cross-attempt change of technique. + n = 0 + while n < SETTLE_MIN and self.lid_closed(): + self.sk.hold(10) + n += 10 + if not self.lid_closed(): + self.open_lid() + self.close_lid(dwell=True) + self.sk.hold(5) + + def default_params(self, inst): + return dict(dwell1=False, dwell2=False, check=False) + + def oracle_params(self, inst): + return dict(dwell1=False, dwell2=True, check=False) + + def adapt_params(self, inst, history): + """From attempt 2 on (if attempt 1's own same-attempt check-and-repair somehow still fell short): close + every time with a firm dwell from the start, and keep checking before finishing.""" + return dict(dwell1=True, dwell2=True, check=True) + + def blind_params(self, inst, attempt, rng): + return dict(dwell1=False, dwell2=bool(rng.random() < 0.5), check=False) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + # attempt 1: naive technique plus a final look-back-and-repair (genuine same-attempt recovery); + # only if that still were not enough would later attempts switch technique from the start. + params = (dict(self.default_params(inst), check=True) if a == 0 + else self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_parts_cart.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..e8992d05ab373c966acef42134bb2f87ddec4743 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/tasks/lh_parts_cart.py @@ -0,0 +1,253 @@ +"""Composite prototype: physical tool retrieval, loading regression and asymmetric cart transport. + +Not part of main_v1. See task_cards/lh_parts_cart.md for validation status. +Only reset_instance/apply_instance position objects; all reference actions use the public motion skills. +""" +import copy +import numpy as np +from .. import envs +from ..bddl import write_bddl +from ..objects import register_generated, box_xml +from ..task_base import register_task +from .l3_tool import (UnderTableTool, low_table_xml, stick_xml, CUBE_HALF, + HANDLE_HALF, TOP_HALF) +from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, + HALF, MASS, MU, BOX, _rot) + + +class CartSkills(PushSkills): + def __init__(self,*args,**kwargs): + super().__init__(*args,**kwargs) + self.robot_commands=0 + def move_to(self,*args,**kwargs): + self.robot_commands+=1 + return super().move_to(*args,**kwargs) + def set_gripper(self,*args,**kwargs): + self.robot_commands+=1 + return super().set_gripper(*args,**kwargs) + + +@register_task +class PartsCart(UnderTableTool): + name = 'lh_parts_cart' + level = 'L4' + category = 'geometry_inference' + failure_causes = ('L4', 'L2', 'L5') + capabilities = ('Perceive', 'Reason', 'Plan', 'Restore') + protocol = 'cross' + agent_max_steps = 180 + instruction = ('Use the wooden tool to retrieve the red part from under the low glass table. ' + 'Load the red and blue parts on the two marks on the brown transport platform, ' + 'then push the loaded platform with the closed gripper completely into the green parking area. ' + 'At the end both parts must still be on their marks, and the gripper must be open and clear.') + instruction_indirect = instruction + + def make_bddl(self): + cube = register_generated('LffPartsCartRed', box_xml('lff_parts_cart_red', (CUBE_HALF,)*3,(.85,.12,.12,1), density=300)) + blue = register_generated('LffPartsCartBlue', box_xml('lff_parts_cart_blue', (CUBE_HALF,)*3,(.1,.2,.85,1), density=300)) + stick_xml_text=stick_xml('lff_parts_cart_stick').replace('size="0.00800 0.02500 0.01000"','size="0.00800 0.00800 0.01000"') + stick = register_generated('LffPartsCartStick', stick_xml_text) + table_xml=low_table_xml('lff_parts_cart_table') + # Wider roof with legs outside the blocked cube's x-exit lane. This prevents a panel failure + # trapping the cube against a corner leg, which the existing standalone task did not test in-attempt. + table_xml=table_xml.replace('size="0.06000 0.06000 0.00500"','size="0.06000 0.07500 0.00500"') + for sx in (-.052,.052): + for sy in (-.052,.052): + table_xml=table_xml.replace(f'pos="{sx:.5f} {sy:.5f} 0.03500"',f'pos="{sx:.5f} {np.sign(sy)*.067:.5f} 0.03500"') + table = register_generated('LffPartsCartTable', table_xml, free=False) + xml=long_box_xml('lff_parts_cart_platform') + marks=''.join(f'' for y,color in [(-.03,'.9 .4 .4 1'),(.03,'.4 .5 .9 1')]) + xml=xml.replace(' ',marks+' ',1) + cart = register_generated('LffPartsCartPlatform', xml) + zone = register_generated('LffPartsCartZone', rect_frame_xml('lff_parts_cart_zone'), free=False) + # Inertial/shape match existing off-centre box, with purely visual cargo marks. + objs=[('cube_1',cube,'red_region',(-.31,-.26,-.29,-.24)), + ('blue_1',blue,'blue_region',(-.31,.24,-.29,.26)), + ('stick_1',stick,'stick_region',(-.01,-.36,.01,-.34)), + ('box_1',cart,'cart_region',(.19,.24,.21,.26))] + fx=[('lowtable_1',table,'table_region',(.19,-.11,.21,-.09)), + ('zone_1',zone,'zone_region',(.19,.39,.21,.41))] + return write_bddl(self.name,self.instruction,objs,fx) + + def sample_instance(self, seed): + # Tool geometry is inherited; put transport in the other half of the same tabletop. + rng=np.random.default_rng(seed) + base=super().sample_instance(seed) + base.update(side=-1, pane_side=1, table_xy=[-.08,-.08],cube_xy=[-.08,-.08], + stick_xy=[-.08,-.34],stick_yaw=np.pi/2, + box_xy=[-.25,.24],target_dist=.16, + com_offset=float(rng.choice([-1,1])*rng.uniform(.05,.065)), + traps=dict(L4=True,L2=True,L5=True)) + base['bin_xy']=[-.25,.24] # inherited observe() only; no bin fixture. + return base + + def target_xy(self, inst): + return np.array([inst['box_xy'][0]+inst['target_dist'],inst['box_xy'][1]]) + + def apply_instance(self, inst): + self.inst=inst + m=self.env.sim.model + bid,_=self._fixture('lowtable_1') + m.body_pos[bid]=[*inst['table_xy'],envs.TABLE_Z] + for g,sy in self._panes(): + on=inst['traps']['L4'] and sy==inst['pane_side'] + m.geom_contype[g]=m.geom_conaffinity[g]=int(on) + envs.set_obj_pose(self.env,'cube_1',[*inst['cube_xy'],envs.TABLE_Z+CUBE_HALF+.0005]) + envs.set_obj_pose(self.env,'blue_1',[-.30,.04,envs.TABLE_Z+CUBE_HALF+.0005]) + envs.set_obj_pose(self.env,'stick_1',[*inst['stick_xy'],envs.TABLE_Z+HANDLE_HALF[2]+.0005],yaw=inst['stick_yaw']) + bid=envs.body_id(self.env,BOX) + m.body_mass[bid]=MASS + m.body_ipos[bid]=[0,inst['com_offset'] if inst['traps']['L5'] else 0,0] + for g in range(m.ngeom): + if m.geom_bodyid[g]==bid and (np.allclose(m.geom_rgba[g,:3],[.9,.4,.4]) or np.allclose(m.geom_rgba[g,:3],[.4,.5,.9])): + m.geom_pos[g,1]=np.sign(m.geom_pos[g,1])*(.03 if inst['traps']['L2'] else .07) + envs.refit_bounds(self.env,bid) + envs.set_friction(self.env,BOX,MU) + envs.set_obj_pose(self.env,BOX,[*inst['box_xy'],envs.TABLE_Z+HALF[2]+.001]) + zb=m.body_name2id(self.env.fixtures_dict['zone_1'].root_body) + m.body_pos[zb]=[*self.target_xy(inst),envs.TABLE_Z+.0002] + + def reset_instance(self, inst, recorder=None): + self.loadmon=None + self._mon=None + self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15) + self.sk=CartSkills(self.env,recorder=recorder,target=self.target_xy(inst)) + self._start_monitor() + self.loadmon=dict(states=[False,False],count=[0,0],ever=[False,False],lost=[False,False],events=[],loaded=False,departed_unloaded=False,load_step=None,departure_step=None,last_robot_touch=[-10000,-10000]) + self.ncmd=0;self.budget=None + return self.sk + + def mark(self,i): + p,yaw=self.sk._box_pose() if self.sk else (envs.obj_pos(self.env,BOX),0.) + spacing=.03 if self.inst['traps']['L2'] else .07 + return p[:2]+_rot(yaw)@np.array([0.,(-spacing,spacing)[i]]) + + def cargo_ok(self,i): + obj=('cube_1','blue_1')[i] + p=envs.obj_pos(self.env,obj); bp=envs.obj_pos(self.env,BOX) + return bool(np.linalg.norm(p[:2]-self.mark(i))<.018 and + abs(p[2]-(bp[2]+HALF[2]+CUBE_HALF))<.012 and not self.sk.holding(obj)) + + def _monitor_step(self): + super()._monitor_step() + mon=getattr(self,'loadmon',None) + if mon is None:return + robot=set(envs.robot_geom_ids(self.env)) + for i,obj in enumerate(('cube_1','blue_1')): + geoms=set(envs.obj_geom_ids(self.env,obj)) + for c in self.env.sim.data.contact[:self.env.sim.data.ncon]: + if (c.geom1 in robot and c.geom2 in geoms) or (c.geom2 in robot and c.geom1 in geoms): + mon['last_robot_touch'][i]=self.sk.n_steps + now=self.cargo_ok(i) + if now==mon['states'][i]:mon['count'][i]=0;continue + mon['count'][i]+=1 + if mon['count'][i]<5:continue + mon['count'][i]=0;mon['states'][i]=now + ev='restored' if now and mon['lost'][i] else 'achieved' if now else 'lost' + if now:mon['ever'][i]=True + else: + mon['lost'][i]=True + if np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])<.025: + mon['loaded']=False + mon['load_step']=None + mon['events'].append(dict(step=self.sk.n_steps,pred=('red','blue')[i],event=ev, + cart_displacement=float(np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])), + cause='robot' if self.sk.n_steps-mon['last_robot_touch'][i]<=20 else 'other')) + displacement=np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy']) + if all(mon['states']) and displacement<.02 and not mon['loaded']: + mon['loaded']=True + mon['load_step']=self.sk.n_steps + if displacement>.03 and mon['departure_step'] is None: + mon['departure_step']=self.sk.n_steps + if not mon['loaded']:mon['departed_unloaded']=True + + def pick_place(self,obj,xy,yaw=0.): + sk=self.sk;p=envs.obj_pos(self.env,obj) + sk.set_gripper(False,steps=10) + sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0. if obj=='cube_1' and self.under_table(margin=.08) else yaw) + sk.move_to([p[0],p[1],p[2]-.004],speed=.10,tol=.002) + sk.set_gripper(True,steps=15) + held=sk.holding(obj) + sk.move_to([p[0],p[1],envs.TABLE_Z+.20],speed=.15) + if held: + sk.move_to([xy[0],xy[1],envs.TABLE_Z+.20],yaw=yaw) + bp=envs.obj_pos(self.env,BOX) + sk.move_to([xy[0],xy[1],bp[2]+HALF[2]+CUBE_HALF-.003],speed=.06,tol=.002) + sk.set_gripper(False,steps=15) + sk.move_to([xy[0],xy[1],envs.TABLE_Z+.22],speed=.15) + return bool(held) + + def load(self, careful=True): + self.pick_place('cube_1',self.mark(0),np.pi/2) + # Open fingers along y at the adjacent mark can knock the already loaded red cube. + yaw=np.pi/2 if careful else 0. + self.pick_place('blue_1',self.mark(1),yaw) + + def repair_load(self): + for _ in range(3): + for i,o in enumerate(('cube_1','blue_1')): + if not self.cargo_ok(i):self.pick_place(o,self.mark(i),np.pi/2) + + def transport(self,c=0.,repair=False): + # Call existing push controller on this same environment; no independent rollout stitching. + if not repair: + return OffcenterPush.execute(self,self.inst,dict(c=c)) + if repair: + # Original feedback-driven corrector calls self.execute for its initial push. + self._transport_only=True + try:OffcenterPush.adaptive_attempt(self,self.inst,c) + finally:self._transport_only=False + + _cmd=OffcenterPush._cmd + _sim_used=OffcenterPush._sim_used + _push_at=OffcenterPush._push_at + bracket=OffcenterPush.bracket + _front_runup=staticmethod(OffcenterPush._front_runup) + STEP=OffcenterPush.STEP;YAW_OK=OffcenterPush.YAW_OK + GAIN0=OffcenterPush.GAIN0;SAFE_V=OffcenterPush.SAFE_V + + def execute(self,inst,params): + if getattr(self,'_transport_only',False):return OffcenterPush.execute(self,inst,params) + if params.get('front',False):self.tool_push_front() + else:self.tool_push_out() + if self.under_table():return + self.load(params.get('careful',False)) + if params.get('repair',False):self.repair_load() + if all(self.cargo_ok(i) for i in range(2)): + self.transport(params.get('c',0.),params.get('repair',False)) + if params.get('repair',False):self.repair_load() + self.sk.set_gripper(False,steps=10) + p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.24]) + + def default_params(self,inst):return dict(front=False,careful=False,repair=False,c=0.) + def oracle_params(self,inst):return dict(front=True,careful=True,repair=True,c=inst['com_offset'] if inst['traps']['L5'] else 0.) + def adapt_params(self,inst,history): + # The L4 side hit is learned from actual prior outcome, not from inst['pane_side']. + seen_geometry=any(h['outcome']['traps']['L4'] for h in history) + seen_loading=any(h['outcome']['traps']['L2'] for h in history) + pushes=[m for h in history for m in h['outcome']['box_moves']] + return dict(front=seen_geometry,careful=seen_loading,repair=bool(history),c=self.bracket(pushes)) + + def outcome(self,inst): + self.sk.hold(30) + fit=self.sk.fit();cargo=[self.cargo_ok(i) for i in range(2)] + ev=list(self.loadmon['events']) + # Loading regressions count only while cart remains at the loading station. + load_lost=[e for e in ev if e['event']=='lost' and e['cart_displacement']<.025 and e['cause']=='robot'] + loaded=self.loadmon['loaded'] + static=bool(np.max(np.abs(self.env.sim.data.qvel))<.05) + robot=set(envs.robot_geom_ids(self.env)); items=set() + for o in ('cube_1','blue_1',BOX,'stick_1'):items.update(envs.obj_geom_ids(self.env,o)) + touching=any((c.geom1 in robot and c.geom2 in items) or (c.geom2 in robot and c.geom1 in items) + for c in self.env.sim.data.contact[:self.env.sim.data.ncon]) + budget_ok=bool(self.sk.robot_commands<=self.agent_max_steps and self.sk.n_steps*.05<=self.agent_max_steps*3) + success=bool(not self.under_table() and all(cargo) and fit['inside'] and loaded + and not self.loadmon['departed_unloaded'] and static and not touching and budget_ok and self.sk.grip<0 + and self._mon['stick_touched_cube']) + moves=copy.deepcopy(self.sk.box_moves) + return dict(success=success,stages=dict(retrieved=not self.under_table(),red=cargo[0],blue=cargo[1],parked=fit['inside'],loaded=loaded), + static=static,touching=bool(touching),tool_used=bool(self._mon['stick_touched_cube']),load_step=self.loadmon['load_step'],departure_step=self.loadmon['departure_step'],commands=self.sk.robot_commands,budget_ok=budget_ok,departed_unloaded=self.loadmon['departed_unloaded'], + events=ev,n_regressions=len(load_lost),n_restored=sum(e['event']=='restored' for e in ev), + traps=dict(L4=bool(self._mon['cube_hit_pane']),L2=bool(load_lost),L5=any(m['bad'] for m in moves)), + box_moves=moves,cart_pose=[*envs.obj_pos(self.env,BOX).tolist()],cart_fit=fit, + detail=f'Retrieved={not self.under_table()}; cargo on marks={cargo}; platform parked={fit["inside"]}.') diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l6_count.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l6_count.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfcc8725cbfb523898ced10b2974c65b5b3b82f --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l6_count.py @@ -0,0 +1,562 @@ +"""L6-B count_into_box: put exactly N identical cubes into an opaque drop box; one carry is interrupted by a slip. + +Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at +one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in, +lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past +the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening). +Cubes cannot be taken back out. + +Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction). + +Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried +cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The +number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so +neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already") +is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be +completed in a later segment. + +Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent +declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the +current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it +also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped +into the box." after every cube that falls in, and the slip. + +Scripted references (perception = simulator state, as in l6_swap): + oracle privileged box count: carries cubes until the box holds N. + adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the + drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later + segments: if F2 says the box holds fewer than N, adds one cube per segment. + naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame, + which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1) + and adds the rest. + blind memoryless restart (k attempts): at the slip it does not know where it was and starts over + ("the box must get N cubes"), every later segment again puts N cubes in (repeated steps). +Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the +slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube +per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..task_base import LFFTask, register_task + +CUBE_HALF = 0.02 +CUBE_RGBA = (0.95, 0.50, 0.10, 1.0) +N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view +LETTERS = "ABCDEFGHIJK" +CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)] + +# drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot) +WALL_T = 0.008 +IN_HX, IN_HY = 0.100, 0.110 # inner half sizes +LID_Z = 0.095 # underside of the lid above the table +LID_T = 0.008 +HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side +HOLE_HY = 0.035 +RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls +RAMP_T = 0.006 +RAMP_MU = 0.03 +BOX_RGBA = (0.30, 0.20, 0.13, 1.0) +INNER_RGBA = (0.08, 0.07, 0.06, 1.0) +HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0]) +OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T +RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX) +RAMP_TH = float(np.arctan(RAMP_SLOPE)) +# Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free +# slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening. +# Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide +# past the opening before it is moved; then a second layer on the far row. (x, y, layer) +_ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)] +SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)] + + [(_ROW[0], 0.0, 0), (_ROW[1], 0.0, 0)] + [(_ROW[0], y, 1) for y in (-0.088, 0.088, -0.044, 0.044, 0.0)]) + +BASE_X = -0.66 +REACH = 0.70 # max horizontal distance of a cube from the robot base +CUBE_REGION = (-0.30, 0.07, -0.28, 0.28) +CUBE_MIN_DIST = 0.085 +BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid) +Z_GRASP = envs.TABLE_Z + CUBE_HALF +Z_CARRY = envs.TABLE_Z + 0.20 +Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid +PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)] +LIFTED = 0.05 # slip trigger: cube at least this far above its resting height +HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there) +HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp + + +def hand_box_clear(p, a, box, half=HAND_HALF): + """Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint.""" + ax = np.array([-np.sin(a), np.cos(a)]) + return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0))) + for t in np.linspace(-half, half, 9)) + + +def axis_clear(p, a, others, half=HAND_HALF): + """Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a).""" + ax = np.array([-np.sin(a), np.cos(a)]) + best = 1.0 + for o in others: + v = np.asarray(o) - p + t = float(np.clip(v @ ax, -half, half)) + best = min(best, float(np.linalg.norm(v - t * ax))) + return best + + +def drop_box_xml(model_name): + """Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on).""" + parts = [] # (pos, half size, rgba, quat or None, friction or None) + H = LID_Z / 2 + # walls + parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA)) + parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA)) + parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA)) + parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA)) + # lid around the opening + zc = LID_Z + LID_T / 2 + x0, x1 = HOLE_X + parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip + parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part + for s in (-1, 1): + parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2, + LID_T / 2), BOX_RGBA)) + # floor (dark) and ramp + parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA)) + dz = RAMP_Z[0] - RAMP_Z[1] + th = float(np.arctan2(dz, 2 * IN_HX)) + L = float(np.hypot(dz, 2 * IN_HX)) / 2 + zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th) + ramp = ((0, 0, zmid), (L, IN_HY - 0.001, RAMP_T / 2), INNER_RGBA, (np.cos(th / 2), 0, np.sin(th / 2), 0), RAMP_MU) + geoms = [] + for k, p in enumerate(parts + [ramp]): + pos, half, rgba = p[:3] + quat = p[3] if len(p) > 3 else None + mu = p[4] if len(p) > 4 else None + q = f' quat="{_fmt(quat)}"' if quat is not None else "" + fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"' + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY))) + + +def _wrap_q(a): + """cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +@register_task +class CountIntoBox(LFFTask): + name = "l6_count_into_box" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55) + max_attempts = 5 + _TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. " + "Cubes cannot be taken back out of the box.") + _TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the " + "square hole in its top. Blocks cannot be taken back out of the container.") + instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction) + instruction_indirect = _TEMPLATE_INDIRECT.format(n="N") + inject = True + announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images) + agent_object_names = ["orange cube (several identical)", "drop box"] + + WORDS = {3: "three", 4: "four", 5: "five", 6: "six"} + + def agent_instruction(self, inst, variant="direct"): + t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE + return t.format(n=self.WORDS[inst["n_target"]]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + orig_step = self.env.step + + def step(action): # per-control-step monitor: also sees attempts driven by the agent harness + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, L in enumerate(LETTERS[:N_CUBES]): + cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3, + CUBE_RGBA, density=600)) + gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4) + objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01))) + box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False) + fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))] + return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx) + + def _box_body(self): + return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + n = int(rng.choice([4, 5])) + p = int(rng.integers(1, n)) # cubes already inside when the slip happens + e = int(rng.integers(0, 2)) + T = n + e + p + for _ in range(500): + side = int(rng.choice([-1, 1])) + box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)]) + P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)]) + P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH] + P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR] + cubes = [] + for c in P: # random sequential addition + if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes): + cubes.append(c) + if len(cubes) == T: + break + if len(cubes) < T: + continue + yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand + for i in range(T): + oth = [cubes[j] for j in range(T) if j != i] + for _ in range(30): + y = float(rng.uniform(-np.pi / 4, np.pi / 4)) + if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035: + # |y| <= 45 deg: the grasp needs no large wrist rotation + yaws.append(y) + break + else: + break + if len(yaws) == T: + break + else: + raise RuntimeError("could not sample a layout") + inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(), + cubes=np.array(cubes).round(4).tolist(), + yaws=yaws, + trigger_dist=float(rng.uniform(0.05, 0.09)), + slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)), + slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4))) + # make_video prints task.instruction: keep it in sync with the last sampled instance + self.instruction = self.agent_instruction(inst, "direct") + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + bid = self._box_body() + m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + T = inst["n_cubes"] + for i, c in enumerate(CUBES): + if i < T: + envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001], + yaw=inst["yaws"][i]) + else: + envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001]) + self.env.sim.forward() + self._inst = inst + self.active = CUBES[:T] + self.slip = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self.in_box = [] # cubes that fell into the box, in order + self.stored = [] # cubes moved to a storage slot + self._bad = set() # scripted policies: cubes whose grasp failed + self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)} + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self._mon = True + return sk + + def go_home(self): + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ geometry helpers + def box_local(self, xyz): + b = self._inst["box_xy"] + return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z]) + + def hole_world(self): + b = self._inst["box_xy"] + return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]]) + + def inside_box(self, c): + q = self.box_local(envs.obj_pos(self.env, c)) + return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z) + + def on_lid(self, c): + q = self.box_local(envs.obj_pos(self.env, c)) + return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z) + + def on_table(self, c): + p = envs.obj_pos(self.env, c) + return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c)) + + # ------------------------------------------------------------ monitor (every control step) + def _monitor(self): + env = self.env + for c in self.active: + if c in self.in_box: + if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02: + self._store(c) + continue + p = envs.obj_pos(env, c) + if self.inside_box(c): + self.in_box.append(c) + if self.announce_drops: + self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c, + text="A cube dropped into the box.")) + continue + if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where + self.rest_xy[c] = p[:2].copy() + continue + if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED + and len(self.in_box) == self._inst["p"] + and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"] + and self.sk.holding(c)): + self._do_slip(c) + + def _store(self, c): + sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)] + b = self._inst["box_xy"] + z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003) + envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z], + quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0]) + self.stored.append(c) + + def _do_slip(self, c): + inst = self._inst + src = self.rest_xy[c] + others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box] + xy, yaw = src, inst["slip_yaw"] + found = False + for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable + cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])]) + if not all(np.linalg.norm(cand - o) >= 0.07 for o in others): + continue + for dy in (0.0, 0.3, -0.3, 0.6, -0.6): + y = _wrap_q(inst["slip_yaw"] + dy) + if axis_clear(cand, y, others) >= HAND_CLEAR and \ + hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035: + xy, yaw, found = cand, y, True + break + if found: + break + envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw) + self.sk.grip = -1.0 # the gripper opens + self.env.sim.forward() + text = "A cube slipped out of the gripper and fell back onto the table." + self.slip = dict(obj=c, xy=[float(v) for v in xy], from_xy=[float(v) for v in src], step=int(self.sk.n_steps), + in_box=len(self.in_box)) + self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text)) + + def drain_events(self): + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + n_in = len(self.in_box) + N = inst["n_target"] + held = [c for c in self.active if self.sk.holding(c)] + n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box) + n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box) + success = bool(n_in == N and not held) + terminal = bool(n_in > N) + if success: + head = f"The box holds exactly {N} cubes." + elif terminal: + head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no " + f"longer be completed.") + elif n_in == N: + head = f"The gripper is still holding a cube." + else: + head = f"The box holds fewer than {N} cubes." + state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table" + if n_lid: + state += f" and {n_lid} on the box lid" + state += "." + # F2 = verdict + currently observable state + the slip of this segment (never the number inside) + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"] + self._outcome_cursor = len(self.events) + detail = head + " " + state + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid, + held=len(held), slip=self.slip, detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _grasp_yaw(self, c): + """The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive + the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if + the hand would hit a neighbour or the box on this one.""" + R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3) + yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0]))) + p = envs.obj_pos(self.env, c)[:2] + others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box] + box = np.asarray(self._inst["box_xy"]) + + def score(a): + return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03) + if score(yaw) >= HAND_CLEAR: + return yaw + alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2 + return alt if score(alt) > score(yaw) + 0.02 else yaw + + def _pick(self, c): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, c) + sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12) + if sk.holding(c): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z_GRASP + 0.12]) + return False + + def _carry(self, c): + """Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'.""" + n_ev = len(self.events) + n_in = len(self.in_box) + if not self._pick(c): + self._bad.add(c) + self.go_home() # un-wind the arm before the next try + return "no_grasp" + h = self.hole_world() + sk = self.sk + sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening + if any(e["kind"] == "slip" for e in self.events[n_ev:]): + return "slipped" + sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([h[0], h[1], Z_CARRY]) + sk.hold(10) + return "in" if len(self.in_box) > n_in else "missed" + + def _next_cube(self): + """nearest table cube to the opening (what any policy sees in the current frame)""" + h = self.hole_world() + cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))] + cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp + if not cands: + return None + return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h)) + + def _add(self, k, log, stop_on_slip=False): + """Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped).""" + added, slipped = 0, False + guard = 0 + while added < k and guard < 3 * k + 3: + guard += 1 + c = self._next_cube() + if c is None: + break + r = self._carry(c) + log.append(r) + if r == "in": + added += 1 + elif r == "slipped": + slipped = True + if stop_on_slip: + break + return added, slipped + + # ------------------------------------------------------------ scripted references (within protocol) + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed + 7919) + self.reset_instance(inst) + N = inst["n_target"] + history = [] + for a in range(k): + log = [] + plan = dict(kind=kind, carries=log) + if a == 0: + if kind == "oracle": + while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count + c = self._next_cube() + if c is None: + break + log.append(self._carry(c)) + plan["recovery"] = "oracle: privileged box count" + elif kind in ("adaptive", "skip"): + added, slipped = self._add(N, log) if kind == "adaptive" else (0, False) + if kind == "skip": # counts carries, not drops + n_car = 0 + while n_car < N and len(log) < 3 * N: + c = self._next_cube() + if c is None: + break + r = self._carry(c) + log.append(r) + if r in ("in", "slipped"): + n_car += 1 + if r == "in": + added += 1 + plan["recovery"] = "counts carries (the slipped one too)" + else: + plan["recovery"] = "own drop count; the slipped carry is not counted" + else: # memoryless after the slip + added, slipped = self._add(N, log, stop_on_slip=True) + if slipped: + if kind == "naive": + guess = int(rng.integers(0, N)) + plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}" + self._add(N - guess, log) + elif kind == "blind": + plan["recovery"] = f"memoryless restart: puts {N} cubes in" + self._add(N, log) + elif kind == "inc1": + plan["recovery"] = "stateless: adds one cube per segment" + self._add(1, log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no slip)" + else: + if kind in ("adaptive", "skip"): + plan["recovery"] = "memory + F2 'fewer than N': add one cube" + self._add(1, log) + elif kind == "blind": + plan["recovery"] = f"memoryless restart: puts {N} cubes in" + self._add(N, log) + elif kind == "inc1": + plan["recovery"] = "stateless: adds one cube" + self._add(1, log) + elif kind == "oracle": + while len(self.in_box) < N and len(log) < 3 * N + 3: + c = self._next_cube() + if c is None: + break + log.append(self._carry(c)) + else: + raise ValueError(kind) + self.go_home() + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or out["terminal"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_cost.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..03a49297e0ef82a9c466f2eb36c0de1b3769630f --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/agent_cost.py @@ -0,0 +1,77 @@ +"""Project GPT-6 cost / latency of a protocol from a run directory. + +Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made +with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES: + input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption) + cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) -- + the first call of an attempt is counted as uncached (conservative) + output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500) + latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input + tokens and high/xhigh effort -- treat as an upper-range planning number) +The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls). + + python scripts/agent_cost.py runs/agent/l5_slide_to_target/ --out-tokens 1500 --latency 20 --calls-scale 2 +""" +import argparse +import json +import os +import sys +from collections import defaultdict + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lffbench.agent.cost import PRICES, call_cost # noqa: E402 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("run_dir") + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--out-tokens", type=float, default=1500) + ap.add_argument("--latency", type=float, default=20.0) + ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)") + a = ap.parse_args() + ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))] + calls = [e for e in ev if e["type"] == "llm_call"] + runs = {e["seed"] for e in ev if e["type"] == "run_start"} + real = [c for c in calls if c.get("usage")] + if real and not any("dry_run_request" in c for c in calls): + cost = sum(call_cost(c["usage"], a.model) or 0 for c in real) + lat = [c["latency_s"] for c in real] + u = defaultdict(int) + for c in real: + for kk, v in c["usage"].items(): + u[kk] += v + out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1), + usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1), + latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1)) + else: + prev = {} + tot_in = tot_cached = 0 + cost1 = 0.0 # priced per call (the long-context surcharge applies per request) + for c in calls: + d = c.get("dry_run_request") + if not d: + continue + key = (c["seed"], c["attempt"]) + tin = d["est_input_tokens"] + cached = min(prev.get(key, 0), tin) + prev[key] = tin + tot_in += tin + tot_cached += cached + cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model) + n = len(calls) * a.calls_scale + scale = a.calls_scale + usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens) + cost = cost1 * scale + out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1), + input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1), + usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1), + api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model), + assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency, + calls_scale=a.calls_scale, image_tokens_512px=256)) + print(json.dumps(out, indent=1, default=str)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/api_batch.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/api_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..cf6ec32fa574b1125a4c6f8acbcc5ca7f3cd9683 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/api_batch.py @@ -0,0 +1,704 @@ +"""Batch of runs with a concurrency limit: the runner for the paper's main table (reference driver scripts/api_player.py) +and, with --harness, for native agent harnesses (side table, docs/15). + + start python scripts/api_batch.py start --batch m1_opus --provider anthropic --model claude-opus-5-5 --effort high \ + --tasks l1_height_bias:3000,3001 lh_bridge:3000 --k 3 --concurrency 6 --video + -> writes runs/api//manifest.json (one entry per run, status "pending") and starts a background + runner that keeps at most --concurrency runs going (robot server + api_player each) and stops each + server when its player exits. + status python scripts/api_batch.py status --batch m1_opus + table python scripts/api_batch.py table --batch m1_opus [--batch ...] (same table as claude_batch + tokens) + stop python scripts/api_batch.py stop --batch m1_opus (runner, players, servers; runs -> "stopped") + retry python scripts/api_batch.py retry --batch m1_opus [--runs ...] (default: every failed / stopped / timeout run; + old logs stay, listed under "superseded"; starts the runner again) + followup python scripts/api_batch.py followup --batch m1_opus (switch a batch started before 2026-10-19 to + --memfree followup: plans the memory-free retries due for its finished history runs; then `retry` starts them) + contract python scripts/api_batch.py contract --batch b1 [--batch b2 ...] (contract_sha256 per instance and condition; + flags instances whose hash differs between batches: those cells must not share a table) + pause touch runs/api//PAUSE: the runner launches no new run while the file exists; the runs going on finish + and are recorded as usual (rm the file to go on). Used by quota watchers to stay below a usage window. + +--harness (default ours): which agent harness drives each run, through scripts/harness_run.py (lffbench/harnesses): + ours scripts/api_player.py, unchanged (--provider as before) + claude_code Claude Code CLI --bare, only our MCP tools, one-time config dirs (arm B; provider anthropic) + claude_code_full Claude Code CLI without --bare (full system prompt), otherwise the same (arm B'); + --claude-auth oauth (default): the subscription token of `claude setup-token` (LFF_CLAUDE_OAUTH_FILE), + apikey: ANTHROPIC_API_KEY (claude_code takes only apikey) + codex Codex CLI exec --ephemeral, empty CODEX_HOME, only our MCP tools reachable (arm F; provider openai); + --codex-auth chatgpt (default): the ChatGPT subscription login, apikey: OPENAI_API_KEY + dsh DeepSeek Harness headless, only our MCP tools, one-time dirs (lffbench/harnesses/dsh.py; provider + deepseek, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY) +Native harnesses are refused at launch (status "refused") unless their preset prompt / tool list matches the pin +written by tests/harness_selfcheck (--allow-unpinned to launch anyway; the preflight still runs). Every run gets +harness.json, contract.json, trajectory.jsonl and harness_audit.json in its log dir. + +Conditions (same as claude_batch): harness = memory full, k attempts in one agent; noharness = independent single-attempt +agents (memory none, k=1). History runs use --hide-k (README and status say 1 attempt, byte-identical to an independent +run; more attempts are announced only after a failure; --no-hide-k to show k). +--memfree, how the memory-free retries (pass@k without history) are run: + followup (default, 2026-10-19): one history run per instance. Its attempt 1 is also the first memory-free attempt, + since under --hide-k it sees exactly what a fresh agent sees. Only if attempt 1 fails does the runner add a + fresh single-attempt agent (noharness rep 1, "chain" = the history run's id); if that one fails too, the + next (rep 2), up to k-1 of them; the first success ends the chain. An instance solved on attempt 1 thus + costs one attempt in all. Not for tasks whose scene persists between attempts (task protocol "within"): + a fresh agent would start from the initial scene, the history run's attempt 2 from the failed one, so the + two conditions would differ; these tasks are reported without memory-free retries (user 2026-10-20). + upfront the 2026-10-11 protocol: --indep-reps independent runs per instance (default k, all of them run), all + before the history runs (--conds order; --no-barrier to mix the phases). + none history runs only. +--seeds-per-task N keeps the first N seeds of each task:seeds (e.g. 1 = one instance per task). +API keys come from LFF_ENV_FILE (default /.env, KEY=value lines) or the environment. +""" +import argparse +import json +import os +import re +import shlex +import signal +import subprocess +import sys +import threading +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +import claude_batch # noqa: E402 + +RUNS = os.path.join(ROOT, "runs", "api") +ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env") +ACTIVE = ("starting", "running") +RETRYABLE = ("failed", "stopped", "timeout", "server_failed") +sys.path.insert(0, ROOT) +from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER as HARNESS_PROVIDER + + + +def bdir(batch): + return os.path.join(RUNS, batch) + + +def mpath(batch): + return os.path.join(bdir(batch), "manifest.json") + + +def load(batch): + with open(mpath(batch)) as f: + return json.load(f) + + +def save(batch, m): + os.makedirs(bdir(batch), exist_ok=True) + tmp = mpath(batch) + ".tmp" + with open(tmp, "w") as f: + json.dump(m, f, indent=1) + os.replace(tmp, mpath(batch)) + + +def alive(pid): + try: + os.kill(int(pid), 0) + return True + except (ProcessLookupError, PermissionError, TypeError, ValueError): + return False + + +def runner_alive(batch): + p = os.path.join(bdir(batch), "runner.pid") + return os.path.exists(p) and alive(open(p).read().strip()) + + +def launch_runner(batch): + log = open(os.path.join(bdir(batch), "runner.log"), "a") + p = subprocess.Popen([sys.executable, os.path.abspath(__file__), "_runner", "--batch", batch], cwd=ROOT, + start_new_session=True, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT) + with open(os.path.join(bdir(batch), "runner.pid"), "w") as f: + f.write(str(p.pid)) + return p.pid + + +def next_id(m): + return f"{max((int(r['id']) for r in m['runs']), default=-1) + 1:04d}" + + +# ------------------------------------------------------------------------------------------------- memory-free chains +# --memfree followup: per instance, history run (cond harness, followup=True) -> noharness rep 1 -> ... -> rep k-1, +# each link planned only after the previous attempts all failed. Attempt 1 of the history run is the chain's first +# attempt (--hide-k makes it identical to a fresh agent's), so the memory-free pass@k of an instance is: attempt 1 of +# the history run, or any of its chain runs, succeeded. +PLAN_KEYS = ("task", "seed", "provider", "agent_harness", "api_base_url", "max_budget_usd", "allow_unpinned", "jail", + "codex_auth", "claude_auth", "codex_catalog", "codex_provider", + "rpent_sessions", "rpent_attempts_per_session", "rpent_max_turns", + "model", "effort", "perception", "video", "style", "feedback", "phase", "nominal", "red_team") + + +def attempt_results(log): + """[success of attempt 1, of attempt 2, ...] from the robot server log ([] if there is none).""" + p = os.path.join(log or "", "events.jsonl") + if not os.path.exists(p): + return [] + res = {} + for line in open(p): + e = json.loads(line) + if e.get("ev") == "done": + res[e["attempt"]] = bool(e["success"]) + return [res[i] for i in sorted(res)] + + +def episode_protocol(log): + """The task's attempt protocol ("cross": reset between attempts, "within": the scene persists) from the robot + server log's session_start line; None if unknown.""" + p = os.path.join(log or "", "events.jsonl") + if os.path.exists(p): + for line in open(p): + e = json.loads(line) + if e.get("ev") == "session_start": + return e.get("protocol") + return None + + +def plan_followup(m, r): + """Run r has finished: append the next memory-free retry of its instance if one is due; returns it or None.""" + if r["status"] != "done": + return None + if r["cond"] == "harness" and r.get("followup"): + if episode_protocol(r.get("log")) == "within": # no like-for-like fresh agent (module docstring) + return None + root, nxt, res = r, 1, attempt_results(r.get("log"))[:1] + elif r.get("chain"): + root = next((x for x in m["runs"] if x["id"] == r["chain"]), None) + nxt, res = r["rep"] + 1, attempt_results(r.get("log")) + else: + return None + if root is None or not res or any(res) or nxt >= root["k"]: + return None + if any(x.get("chain") == root["id"] and x["rep"] == nxt for x in m["runs"]): + return None + new = {k: root.get(k) for k in PLAN_KEYS} + new.update(id=next_id(m), cond="noharness", rep=nxt, k=1, mem="none", hide_k=False, chain=root["id"], + status="pending") + m["runs"].append(new) + return new + + +def memfree_chain(m, root): + """Table rows for the memory-free retries of root's instance: its attempt 1 (rep 0, only_attempt=1) and the chain + runs after it. [] while the chain has not ended (a success, or k attempts).""" + first = attempt_results(root.get("log"))[:1] + if not first: + return [] + rows = [dict(root, cond="noharness", rep=0, k=1, only_attempt=1)] + if first[0]: + return rows + chain = {x["rep"]: x for x in m["runs"] if x.get("chain") == root["id"] and x["status"] == "done" and x.get("log")} + for rep in range(1, root["k"]): + if rep not in chain: + return [] + rows.append(dict(chain[rep])) + if any(attempt_results(chain[rep]["log"])): + break + return rows + + +# ------------------------------------------------------------------------------------------------------------ start +def cmd_start(a): + a.codex_auth = a.codex_auth or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt") + if a.harness == "rpent_codex" and a.codex_auth != "apikey": + sys.exit("Historical RPent adapter supports apikey only") + if runner_alive(a.batch): + sys.exit(f"batch {a.batch}: runner already running; stop it first or use another batch name") + m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[], superseded=[]) + m.update(concurrency=a.concurrency, barrier=not a.no_barrier, port0=a.port0, run_timeout_s=a.run_timeout) + reps = a.k if a.indep_reps is None else a.indep_reps + if a.harness != "ours": + need = HARNESS_PROVIDER[a.harness] + if a.provider and a.provider != need: + sys.exit(f"--harness {a.harness} drives {need} models only (got --provider {a.provider})") + a.provider = need + elif not a.provider: + sys.exit("--provider is required with --harness ours") + claude_auth = None + if a.harness.startswith("claude_code"): + claude_auth = a.claude_auth or ("apikey" if a.harness == "claude_code" else "oauth") + if claude_auth == "oauth" and a.harness == "claude_code": + sys.exit("--harness claude_code (--bare) takes only an API key; use claude_code_full for a subscription") + elif a.claude_auth: + sys.exit("--claude-auth is for --harness claude_code / claude_code_full") + if a.jail and a.harness == "ours": + sys.exit("--jail is for native harnesses (the reference driver runs our own code)") + if a.red_team and a.harness == "ours": + sys.exit("--red-team is for native harnesses (lffbench/harnesses/redteam.py)") + if a.memfree == "upfront": + conds = [c.strip() for c in (a.conds or "noharness,harness").split(",") if c.strip()] + else: + if a.conds and a.conds.replace(" ", "") != "harness": + sys.exit(f"--conds is for --memfree upfront (--memfree {a.memfree} plans history runs only)") + if a.memfree == "followup" and a.no_hide_k: + sys.exit("--memfree followup shares attempt 1 of the history run with the memory-free retries: needs --hide-k") + conds = ["harness"] + dossiers = json.load(open(a.dossiers)) if a.dossiers else None + if dossiers is not None: # task:seed -> record dir (scripts/make_dossier.py); every planned instance needs one + miss = [f"{spec.split(':')[0]}:{sd}" for spec in a.tasks for sd in spec.split(":")[1].split(",")[:a.seeds_per_task] + if f"{spec.split(':')[0]}:{sd}" not in dossiers] + if miss: + sys.exit(f"--dossiers has no record for {miss}") + bad = [d for d in dossiers.values() if not os.path.isfile(os.path.join(d, "README.md")) or any(c.isspace() for c in d)] + if bad: + sys.exit(f"--dossiers: not a record dir (or path with spaces): {bad}") + n0 = len(m["runs"]) + for cond in conds: # the order of --conds is the order of the phases + for spec in a.tasks: + task, seeds = spec.split(":") + for seed in seeds.split(",")[:a.seeds_per_task]: + plan = [("harness", "full", a.k, 0)] if cond == "harness" else \ + [("noharness", "none", 1, i) for i in range(reps)] + for c, mem, k, rep in plan: + m["runs"].append(dict(id=next_id(m), task=task, seed=int(seed), provider=a.provider, + agent_harness=a.harness, api_base_url=a.api_base_url, + max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned, + jail=a.jail, codex_auth=(("apikey" if a.codex_provider in ("deepseek", "opencode") else a.codex_auth) + if a.harness in ("codex", *ROBOT_HARNESSES) else None), + claude_auth=claude_auth, + codex_catalog=(a.codex_catalog if a.harness in ("codex", *ROBOT_HARNESSES) + else None), + **(dict(rpent_sessions=a.rpent_sessions, + rpent_attempts_per_session=a.rpent_attempts_per_session, + rpent_max_turns=a.rpent_max_turns) + if a.harness == "rpent_codex" else {}), + codex_provider=(a.codex_provider if a.harness == "codex" else None), + model=a.model, effort=a.effort, cond=c, rep=rep, k=k, mem=mem, + hide_k=(c == "harness" and not a.no_hide_k), perception=a.perception, + video=a.video, style="la", feedback=a.feedback, phase=conds.index(cond), + nominal=a.nominal, followup=(c == "harness" and a.memfree == "followup"), + arm=a.arm, red_team=a.red_team, dossier=(os.path.abspath(dossiers[f"{task}:{seed}"]) if dossiers else None), + status="pending")) + save(a.batch, m) + print(f"{len(m['runs']) - n0} runs planned ({', '.join(conds)}, --memfree {a.memfree}); manifest {mpath(a.batch)}") + if a.memfree == "followup": + print("memory-free retries are added while the batch runs, for instances whose attempt 1 failed") + print("runner pid", launch_runner(a.batch)) + + +# ------------------------------------------------------------------------------------------------------------ runner +class Runner: + def __init__(self, batch): + self.batch = batch + self.lock = threading.Lock() + self.m = load(batch) + self.used_ports = set() + self.stop = False + + def update(self, r, **kw): + with self.lock: + r.update(kw) + save(self.batch, self.m) + + def next_run(self): + with self.lock: + runs = self.m["runs"] + pending = [r for r in runs if r["status"] == "pending"] + if not pending: + # a run still going may yet add a memory-free retry (--memfree followup) + if any(r["status"] in ACTIVE and (r.get("followup") or r.get("chain")) for r in runs): + return "wait" + return None + if self.m.get("barrier", True): + phase = min(r["phase"] for r in pending) + if any(r["status"] in ACTIVE and r["phase"] < phase for r in runs): + return "wait" + pending = [r for r in pending if r["phase"] == phase] + if os.path.exists(os.path.join(bdir(self.batch), "PAUSE")): + return "wait" + r = pending[0] + r["status"] = "starting" + save(self.batch, self.m) + return r + + def port(self): + with self.lock: + p = int(self.m.get("port0", 14000)) + while p in self.used_ports or not claude_batch.port_free(p): + p += 1 + self.used_ports.add(p) + return p + + def run_one(self, r): + port = self.port() + model_tag = re.sub(r"[^A-Za-z0-9.-]+", "-", r["model"])[:40] + ah = r.get("agent_harness", "ours") + if ah != "ours": + model_tag += "-" + ah.replace("_", "") + tag = (f"{self.batch}-{model_tag}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}" + + ("-hidek" if r["hide_k"] else "") + ("-nominal" if r.get("nominal") else "") + + (f"-{r['arm']}" if r.get("arm", "none") != "none" else "") + ("-dossier" if r.get("dossier") else "") + + ("-redteam" if r.get("red_team") else "")) + extra = (" --hide-k" if r["hide_k"] else "") + (" --nominal" if r.get("nominal") else "") + # docs/14 §6 arms (robot_server --arm / --dossier); LFF_EXTRA_ARGS is word-split, so no spaces in the path + extra += (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "") + (f" --dossier {r['dossier']}" if r.get("dossier") else "") + t0 = time.time() + try: + sb, log = claude_batch.start_one(r["task"], r["seed"], r["mem"], r["k"], port, tag, r["perception"], + r["video"], r["style"], extra.strip(), r["feedback"]) + except Exception as e: # server did not come up + self.update(r, status="server_failed", error=str(e)[-500:], port=port) + with self.lock: + self.used_ports.discard(port) + return + self.update(r, status="running", port=port, sandbox=sb, log=log, run=os.path.basename(log), t_start=t0) + opts = "" + if r.get("api_base_url"): + opts += f" --api-base-url {shlex.quote(r['api_base_url'])}" + if r.get("max_budget_usd"): + opts += f" --max-budget-usd {r['max_budget_usd']}" + if r.get("allow_unpinned"): + opts += " --allow-unpinned" + if r.get("jail"): + opts += " --jail" + if r.get("red_team"): + opts += " --red-team" + if r.get("codex_auth"): + opts += f" --codex-auth {r['codex_auth']}" + if r.get("claude_auth"): + opts += f" --claude-auth {r['claude_auth']}" + if r.get("agent_harness") in ("codex", *ROBOT_HARNESSES) and r.get("agent_harness") != "rpent_codex": # runs planned before 10-20 have no catalog: Codex's native one + opts += f" --codex-catalog {r.get('codex_catalog') or 'native'}" + if r.get("codex_provider") in ("deepseek", "opencode"): + opts += f" --codex-provider {r['codex_provider']}" + if r.get("agent_harness") == "rpent_codex": + opts += (f" --codex-catalog {r.get('codex_catalog') or 'generic'}" + f" --rpent-sessions {r.get('rpent_sessions') or 5}" + f" --rpent-attempts-per-session {r.get('rpent_attempts_per_session', 1)}" + f" --rpent-max-turns {r.get('rpent_max_turns') or 100}") + # every harness (also ours: api_player.py with the same arguments as before, its output still in + # api_player.log) goes through the adapter layer, which adds harness.json / contract.json / trajectory.jsonl + player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && " + f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && " + f"exec python scripts/harness_run.py --harness {ah} --session {log}/session.json " + f"--provider {r['provider']} --model {shlex.quote(r['model'])} --effort {r['effort']} " + f"--timeout {int(self.m.get('run_timeout_s', 28800))}{opts} > {log}/harness_run.log 2>&1") + p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.update(r, player_pid=p.pid) + status = None + try: + code = p.wait(timeout=self.m.get("run_timeout_s", 28800)) + except subprocess.TimeoutExpired: + os.killpg(p.pid, signal.SIGTERM) + code, status = p.wait(), "timeout" + self.stop_server(log) + if status is None: + status = "stopped" if self.stop else ("done" if code == 0 else "refused" if code == 2 else "failed") + self.update(r, status=status, exit_code=code, t_end=time.time(), wall_s=round(time.time() - t0, 1)) + with self.lock: + self.used_ports.discard(port) + if plan_followup(self.m, r): + save(self.batch, self.m) + + @staticmethod + def stop_server(log): + pf = os.path.join(log, "server.pid") + if not os.path.exists(pf): + return + pid = int(open(pf).read()) + try: + os.kill(pid, signal.SIGTERM) # the server closes rollout.mp4 first + except ProcessLookupError: + return + for _ in range(120): + if not alive(pid): + return + time.sleep(0.5) + + def worker(self): + while not self.stop: + r = self.next_run() + if r is None: + return + if r == "wait": + time.sleep(5) + continue + try: + self.run_one(r) + except Exception as e: # keep the other workers going + self.update(r, status="failed", error=f"runner: {type(e).__name__}: {e}"[:500]) + + def main(self): + os.environ["LFF_RUNS_DIR"] = bdir(self.batch) # claude_batch.start_one puts the run logs here + for r in self.m["runs"]: # a previous runner died: its half-started runs go back to pending + if r["status"] in ACTIVE: + r["status"] = "pending" + for r in list(self.m["runs"]): # memory-free retries due but not yet planned (runner died, `followup`) + plan_followup(self.m, r) + save(self.batch, self.m) + + def on_term(*_): + self.stop = True + with self.lock: + for r in self.m["runs"]: + if r["status"] == "running" and r.get("player_pid"): + try: + os.killpg(r["player_pid"], signal.SIGTERM) + except ProcessLookupError: + pass + signal.signal(signal.SIGTERM, on_term) + ths = [threading.Thread(target=self.worker, daemon=True) for _ in range(int(self.m.get("concurrency", 4)))] + for t in ths: + t.start() + time.sleep(2) # stagger server start-ups + for t in ths: + t.join() + print(time.strftime("%F %T"), "runner finished", flush=True) + + +def cmd_runner(a): + Runner(a.batch).main() + + +# ------------------------------------------------------------------------------------------------------------ views +def transcript_usage(log): + tot = dict(calls=0, input_tokens=0, cached_tokens=0, output_tokens=0, api_errors=0, end=None) + p = os.path.join(log or "", "transcript.jsonl") + if not os.path.exists(p): # native harness: totals from the unified trajectory + sys.path.insert(0, ROOT) + from lffbench.harnesses.trajectory import usage_summary + u = usage_summary(log) + if u: + tot.update(calls=u.get("calls", 0), input_tokens=u.get("total_prompt_tokens") or 0, + cached_tokens=u.get("total_cached_tokens") or 0, + output_tokens=u.get("total_completion_tokens") or 0, end=u.get("exit_reason"), + cost_usd=u.get("total_cost_usd")) + return tot + for line in open(p): + d = json.loads(line) + if d["ev"] == "assistant": + tot["calls"] += 1 + for k in ("input_tokens", "cached_tokens", "output_tokens"): + tot[k] += (d.get("usage") or {}).get(k, 0) + elif d["ev"] == "api_error": + tot["api_errors"] += 1 + elif d["ev"] in ("end", "abort"): + tot["end"] = d["ev"] if d["ev"] == "end" else "abort: " + d.get("reason", "") + return tot + + +def cmd_status(a): + m = load(a.batch) + counts = {} + for r in m["runs"]: + counts[r["status"]] = counts.get(r["status"], 0) + 1 + att = "" + if r.get("log") and os.path.exists(os.path.join(r["log"], "events.jsonl")): + ev = [json.loads(line) for line in open(os.path.join(r["log"], "events.jsonl"))] + att = "".join("S" if e["success"] else "F" for e in ev if e["ev"] == "done") + u = transcript_usage(r.get("log")) + print(f"{r['id']} {r['status']:13s} {r.get('agent_harness', 'ours'):16s} " + f"{r['cond']:9s}{r['rep'] if r['cond'] == 'noharness' else '':1} " + f"{r['task']:24s} s{r['seed']} {att:4s} calls={u['calls']:3d} api_err={u['api_errors']} " + f"in={u['input_tokens'] / 1e6:.2f}M out={u['output_tokens'] / 1e3:.0f}k {u['end'] or ''}" + + (f" (memory-free attempt {r['rep'] + 1} after {r['chain']})" if r.get("chain") else "")) + print("runner", "alive" if runner_alive(a.batch) else "not running", "|", counts) + + +def cmd_table(a): + def done_runs(b): + m = load(b) + runs = [] + for r in m["runs"]: + if not (r.get("log") and r["status"] == "done") or r.get("chain"): + continue + runs.append(dict(r)) + if r["cond"] == "harness" and r.get("followup"): # its memory-free chain, once finished + runs += memfree_chain(m, r) + for r in runs: # the harness is part of the table's "model" column (claude_batch groups by task, model) + if r.get("agent_harness", "ours") != "ours": + r["model"] = f"{r['model']} @ {r['agent_harness']}" + return dict(m, runs=runs) + claude_batch.load = done_runs # same manifest fields (task, seed, model, cond, rep, k, log): reuse its table + # token totals: every run once (the rep-0 row of a chain is attempt 1 of a history run, already counted) + rows = [r for b in a.batch for r in done_runs(b)["runs"] if not r.get("only_attempt")] + claude_batch.cmd_table(argparse.Namespace(batch=a.batch)) + by = {} + for r in rows: + u = transcript_usage(r["log"]) + t = by.setdefault((r.get("agent_harness", "ours"), r["provider"], r["model"], r["effort"]), [0, 0, 0, 0, 0]) + t[0] += 1 + t[1] += u["calls"] + t[2] += u["input_tokens"] + t[3] += u["cached_tokens"] + t[4] += u["output_tokens"] + print("\n| harness | provider | model | effort | runs done | model calls | input tokens (M) | of which cached (M) | output tokens (M) |") + print("|---|---|---|---|---|---|---|---|---|") + for (h, p, mo, e), t in sorted(by.items()): + print(f"| {h} | {p} | {mo} | {e} | {t[0]} | {t[1]} | {t[2] / 1e6:.1f} | {t[3] / 1e6:.1f} | {t[4] / 1e6:.2f} |") + + +def cmd_contract(a): + """contract_sha256 per (task, seed, cond) and batch; an instance whose hash differs between batches is flagged.""" + import collections + seen = collections.defaultdict(dict) + for b in a.batch: + for r in load(b)["runs"]: + p = os.path.join(r.get("log") or "", "contract.json") + if r.get("log") and os.path.exists(p): + sha = json.load(open(p))["contract_sha256"] + seen[(r["task"], r["seed"], r["cond"])].setdefault(b, set()).add(sha) + bad = 0 + print("| task | seed | cond | " + " | ".join(a.batch) + " | same |") + print("|---|---|---|" + "---|" * len(a.batch) + "---|") + for (task, seed, cond), per in sorted(seen.items()): + shas = set().union(*per.values()) + same = len(shas) == 1 + bad += not same + cells = [",".join(sorted(x[:12] for x in per.get(b, []))) or "-" for b in a.batch] + print(f"| {task} | {seed} | {cond} | " + " | ".join(cells) + f" | {'yes' if same else '**NO**'} |") + print(f"\n{len(seen)} instance/condition rows, {bad} with differing contracts") + + +def cmd_stop(a): + pf = os.path.join(bdir(a.batch), "runner.pid") + if os.path.exists(pf) and alive(open(pf).read().strip()): + os.kill(int(open(pf).read().strip()), signal.SIGTERM) # the runner stops its players and servers + for _ in range(240): + if not runner_alive(a.batch): + break + time.sleep(0.5) + m = load(a.batch) + for r in m["runs"]: # anything left over (runner killed hard) + if r["status"] in ACTIVE: + if r.get("player_pid"): + try: + os.killpg(r["player_pid"], signal.SIGTERM) + except ProcessLookupError: + pass + if r.get("log"): + Runner.stop_server(r["log"]) + r["status"] = "stopped" + save(a.batch, m) + print("stopped") + + +def cmd_retry(a): + if runner_alive(a.batch): + sys.exit("runner still running: stop it first") + m = load(a.batch) + reset = [] + for r in m["runs"]: + if (a.runs and (r.get("run") in a.runs or r["id"] in a.runs)) or (not a.runs and r["status"] in RETRYABLE): + if r.get("log"): + m.setdefault("superseded", []).append(dict(r)) + for k in ("port", "sandbox", "log", "run", "player_pid", "exit_code", "t_start", "t_end", "wall_s", "error"): + r.pop(k, None) + r["status"] = "pending" + reset.append(r) + # memory-free retries planned after a run that is now re-run were based on attempts that no longer count + stale = [x for x in m["runs"] if x.get("chain") and all(x is not y for y in reset) and any( + x["chain"] == y["id"] or (x["chain"] == y.get("chain") and x["rep"] > y["rep"]) for y in reset)] + for x in stale: + m["runs"].remove(x) + if x.get("log"): + m.setdefault("superseded", []).append(dict(x, superseded_because="earlier attempt of its chain re-run")) + save(a.batch, m) + print(len(reset), "runs reset to pending" + (f", {len(stale)} memory-free retries after them dropped" if stale else "") + + "; runner pid", launch_runner(a.batch)) + + +def cmd_followup(a): + """Switch a batch to --memfree followup: mark its --hide-k history runs and plan the memory-free retries due for + those already done. `retry` then starts the runner (and re-runs failed / stopped runs).""" + if runner_alive(a.batch): + sys.exit("runner still running: stop it first") + m = load(a.batch) + marked = left = 0 + for r in m["runs"]: + if r["cond"] == "harness" and not r.get("followup"): + if r.get("hide_k"): + r["followup"] = True + marked += 1 + else: + left += 1 + new = [x for r in list(m["runs"]) for x in [plan_followup(m, r)] if x] + save(a.batch, m) + print(f"{marked} history runs switched to --memfree followup" + + (f" ({left} without --hide-k left out: their attempt 1 is not a fresh agent's)" if left else "") + + f"; {len(new)} memory-free retries planned") + print(f"start the runner with: python scripts/api_batch.py retry --batch {a.batch}") + + +def main(): + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd", required=True) + s = sub.add_parser("start") + s.add_argument("--batch", required=True) + s.add_argument("--harness", default="ours", choices=NAMES, + help="agent harness (docs/15); native harnesses imply the provider; rpent_codex = RPent on Codex " + "(docs/18), OpenAI API key only (LFF_OPENAI_API_KEY)") + s.add_argument("--provider", default=None, choices=["openai", "anthropic", "gemini", "chat"], + help="required for --harness ours") + s.add_argument("--api-base-url", default=None, help="native harnesses: model API endpoint (see harness_run.py)") + s.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: per-run dollar cap") + s.add_argument("--allow-unpinned", action="store_true", help="native harnesses: launch without a pin") + s.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"], + help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. " + "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only") + s.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"], + help="claude_code*: subscription token (default for claude_code_full) or ANTHROPIC_API_KEY " + "(claude_code, --bare: apikey only)") + s.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"], + help="codex: model provider; deepseek / opencode (OpenCode Go) imply --codex-auth apikey " + "(see harness_run.py)") + s.add_argument("--codex-catalog", default="generic", choices=["generic", "native"], + help="codex: model configuration, the main table's shared one (default) or Codex's native one " + "(control; see lffbench/harnesses/codex.py)") + s.add_argument("--rpent-sessions", type=int, default=5, help="rpent_codex: planner sessions per episode") + s.add_argument("--rpent-attempts-per-session", type=int, default=1, + help="rpent_codex: attempts one session may use (1 = variant H, default; 0 = no limit)") + s.add_argument("--rpent-max-turns", type=int, default=100, help="rpent_codex: model responses per session") + s.add_argument("--jail", action="store_true", + help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4, lffbench/harnesses/jail.py)") + s.add_argument("--model", required=True) + s.add_argument("--effort", default="high") + s.add_argument("--tasks", nargs="+", required=True, help="task:seed,seed ...") + s.add_argument("--k", type=int, default=3) + s.add_argument("--seeds-per-task", type=int, default=None, help="only the first N seeds of each task:seeds") + s.add_argument("--memfree", default="followup", choices=["followup", "upfront", "none"], + help="memory-free retries: followup (default) = fresh single-attempt agents only after the history " + "run's attempt 1 failed, one at a time, up to k attempts in all, stop at the first success; " + "upfront = --indep-reps independent runs per instance before the history runs; none = no " + "memory-free retries (see the module docstring)") + s.add_argument("--indep-reps", type=int, default=None, help="--memfree upfront: independent runs per instance (default k)") + s.add_argument("--conds", default=None, help="--memfree upfront: conditions in phase order (default noharness,harness)") + s.add_argument("--no-barrier", action="store_true", help="do not wait for one phase to finish before the next") + s.add_argument("--no-hide-k", action="store_true", help="history runs: README / status show all k attempts") + s.add_argument("--concurrency", type=int, default=4) + s.add_argument("--port0", type=int, default=14000) + s.add_argument("--run-timeout", type=int, default=28800, + help="seconds per run before the player is killed (default 8 h: a long-horizon history run can need 300+ model calls)") + s.add_argument("--perception", default="rgb", choices=["rgb", "rgbd"]) + s.add_argument("--video", action="store_true") + s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"]) + s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed") + s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"], + help="docs/14 §6 controlled arm for every run: twin = same layout, other value of the hidden variable") + s.add_argument("--red-team", action="store_true", + help="adversarial acceptance runs (lffbench/harnesses/redteam.py): the agent is told to get a success " + "without doing the task; own contract; read with scripts/redteam_report.py") + s.add_argument("--dossiers", default=None, + help="JSON {\"task:seed\": record dir from scripts/make_dossier.py}: each run gets that record in " + "history/ and a README section saying an earlier attempt failed (own vs mismatched history)") + r = sub.add_parser("_runner") + r.add_argument("--batch", required=True) + for name in ("status", "stop", "followup"): + sub.add_parser(name).add_argument("--batch", required=True) + t = sub.add_parser("table") + t.add_argument("--batch", nargs="+", required=True) + ct = sub.add_parser("contract") + ct.add_argument("--batch", nargs="+", required=True) + rt = sub.add_parser("retry") + rt.add_argument("--batch", required=True) + rt.add_argument("--runs", nargs="*", default=[]) + a = ap.parse_args() + dict(start=cmd_start, _runner=cmd_runner, status=cmd_status, table=cmd_table, stop=cmd_stop, retry=cmd_retry, + contract=cmd_contract, followup=cmd_followup)[a.cmd](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/feedback_ladder.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/feedback_ladder.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cbcd10f0e9f163fbcc307dbf449147ddab78eb --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/feedback_ladder.py @@ -0,0 +1,428 @@ +"""Frozen first-failure record experiment. No native-session-continuation claim. + +prepare creates a host-only manifest plus agent-visible, identical history records. +run starts the serial, resumable controller; player wraps the unchanged native harness. +""" +import argparse +import collections +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import random +import shutil +import signal +import socket +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / 'scripts')) +SOURCE = ROOT.parents[1] / 'lffbench' +REPORT = ROOT.parents[1] / 'reports/feedback_ladder_20261027' +BATCHES = ('cc_opus1', 'cc_opus_s2', 'cc_opus_s3') +TASKS = ('l7_offcenter_push','l5_slide_to_target','l5_tablecloth_pull','l3_wall_flush', + 'l3_under_table_tool','l4_fit_container','l7_key_turn','l2_turntable_restore','l3_card_shelf','l5_loaded_beam') +ARMS = ('F1', 'F2', 'cause', 'fix') +ENV_FILE = Path('/mnt/cpfs/workspace/env/claude-releases/cc_opus_s3.env') +PILOT = ('cc_opus1__l3_card_shelf__3003', 'cc_opus_s2__l4_fit_container__3001') + + +def now(): + return dt.datetime.now(dt.timezone.utc).isoformat() + + +def sha(p): + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def digest(d): + return hashlib.sha256(json.dumps(d,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest() + + +def read(p): + return json.loads(Path(p).read_text()) + + +def write(p,d): + p=Path(p);p.parent.mkdir(parents=True,exist_ok=True) + tmp=p.with_name(p.name+'.tmp');tmp.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n');tmp.replace(p) + + +def jsonl(p): + return [json.loads(s) for s in Path(p).read_text().splitlines() if s.strip()] + + +def tree_hash(p): + return digest({str(f.relative_to(p)):sha(f) for f in sorted(Path(p).rglob('*')) if f.is_file()}) + + +def intervention(a,arm): + parts=['The earlier attempt failed.'] + if arm not in ARMS:raise ValueError(arm) + for level,key in [('F2','phenomenon'),('cause','cause'),('fix','fix')]: + if ARMS.index(arm)>=ARMS.index(level):parts.append(a[key]) + return '\n'.join(parts) + + +def annotations(task,seed,out,inst): + """Manual mechanism families, checked against each observed first-attempt outcome. + F2 contains observations only; privileged mechanism and strategy are separate. + Unknown/mixed mechanisms are explicitly excluded, not assigned a task-name cause. + """ + if task=='l3_wall_flush' and out.get('mode')=='placed_off': + return dict(eligible=False,reason='Placement missed after successful extraction; exact localization/control cause unverified.') + if task=='l3_under_table_tool': + return dict(eligible=False,reason='Cube never moved and agent reported wrist limits; transparent-pane mechanism not triggered. Needs separate operational audit.') + if task=='l5_slide_to_target': + assert out['failure']=='position' and out['along_err']>0 and out['at_rest'] + return dict(eligible=True,phenomenon='The cube came to rest beyond the far edge of the target square.', + cause='The cube keeps moving after release: its surface friction is low, so the launch imparted more sliding distance than the remaining distance to the target.', + fix='Use the previous strike and observed travel as a calibration. Align a short strike toward the square, launch more gently for the remaining distance, withdraw the gripper, and wait for the cube to stop before checking both edges. Preserve a free slide; do not carry or continuously push it into place.', + basis=['failure=position','along_err>0','at_rest=true','mu in sampled instance','strikes/free_slide_cm'],mechanism='overshoot_after_release') + if task=='l5_tablecloth_pull': + assert out['failure']=='missed_band' and out['upright'] and not out['on_board'] and out['band_offset_x']>0 + return dict(eligible=True,phenomenon='The board came out and the cube stayed upright, but the cube stopped short of the green band in the direction of the pull.', + cause='Friction transfers motion from the board to the cube while they remain in contact. The pull was too fast to move the cube far enough toward the band before the board escaped.', + fix='On the reset scene, grasp only the handle and use one straight, somewhat slower pull than before, then release. A slower pull carries the cube farther before the board escapes; avoid making it so slow that the cube rides on the board. Check the whole cube against the band after it settles.', + basis=['failure=missed_band','upright=true','on_board=false','band_offset_x>0','tasks/l5_tablecloth_pull.py adaptive_params'],mechanism='insufficient_frictional_displacement') + if task=='l3_wall_flush': + assert out['mode']=='wall_blocked' and not out['lifted'] + return dict(eligible=True,phenomenon='The box was not lifted. During grasp attempts, the wall-side finger came down on the top of the wall.', + cause='The clearance between box and wall is too small for that finger, and the wall is higher than the box. At the attempted grasp locations the finger still overlapped the wall.', + fix='With the gripper closed, slide the box along the wall toward an accessible wall end. Move it far enough past that end for both fingers to descend clear of the wall, then open, grasp the box, lift, and place it centered on the plate.', + basis=['mode=wall_blocked','lifted=false','detail wall collision','gap and wall geometry'],mechanism='wall_blocks_finger') + if task=='l4_fit_container': + assert out['failure']=='rim' and out['box_kind'] in ('snug','short_wide','small') + return dict(eligible=True,phenomenon='The released phone rested on the box rims rather than lying on the bottom inside the box.', + cause='The selected box is shorter internally than the phone along its long dimension. The phone bridges the rims even when its long axis is aligned with that box.', + fix='Choose a different box whose internal length and width both clear the phone. Compare the inside edges, orient the phone along the chosen box, lower it through the opening, release it, then withdraw and verify that it lies flat below the rims.', + basis=['failure=rim','box_kind='+out['box_kind'],'sampled box inner dimensions','detail length mismatch'],mechanism='container_too_short') + if task=='l3_card_shelf': + assert out['failure']=='fell_off' and out['tip']['part']=='heavy' + side=out['tip']['edge'];assert side==inst['heavy_edge'] + return dict(eligible=True,phenomenon=f'The card tipped over the shelf\'s {side} edge and fell flat onto the table before it was lifted.', + cause=f'The card has a hidden weight toward the end that went over the {side} edge. Its center of mass passed outside the shelf support even with only a small overhang.', + fix='On the reset shelf, slide the opposite, lighter end toward the opposite shelf edge in small checked moves. Keep the weighted end supported, expose enough of the light end for the fingers to pass the shelf edge, pinch the exposed end across its width, then lift and transfer the card into the bin.', + basis=['failure=fell_off','tip.part=heavy','tip.edge matches inst.heavy_edge','tipped_off event'],mechanism='heavy_end_over_edge') + if task=='l5_loaded_beam': + assert out['failure']=='load_off' and out['n_load_falls']>0 + return dict(eligible=True,phenomenon='The beam tilted during lifting and the blocks slid away from their end positions. At the end, the beam was held up but one block was still displaced inward from its end position.', + cause='The beam has an off-center hidden weight. The initial grip was away from the loaded balance point, so the beam tilted and displaced its blocks; later leveling did not itself restore their required end positions.', + fix='First restore both blocks to their original end positions while the beam is supported. Make a low test lift, adjust the grip toward the lower, heavier end until the loaded beam stays level, and only then raise it fully. Recheck both blocks after the lift; if either shifts, set down and restore it before trying again.', + basis=['failure=load_off','first lift tilt and falls','final loads_on_ends=1','inst.com_total'],mechanism='offcenter_lift_and_unrestored_load',mixed=True) + raise ValueError(f'No reviewed feedback for {task} seed {seed}') + + +def record_prefix(log,outdir,done): + """Only host-logged model-visible MCP text before first verdict, plus first images. + Do NOT copy session_start.inst, evaluator outcome, later attempts, or native hidden reasoning. + The final call is replaced by its closing reason + F1 verdict, to avoid reset-image leakage. + """ + outdir.mkdir(parents=True,exist_ok=False);(outdir/'obs').mkdir() + tools=[] + for e in jsonl(log/'mcp_transcript.jsonl'): + if e.get('ev')!='tool':continue + if e['t']>=done['t']:break + tools.append({k:e[k] for k in ('name','arguments','output','is_error') if k in e}) + # Include the commanded last action even if a budget-triggered verdict preceded MCP logging. + calls=[{k:e[k] for k in ('step','cmd','args')} for e in jsonl(log/'events.jsonl') + if e.get('ev')=='call' and e.get('attempt')==1 and e['t']<=done['t']] + images=[] + for p in sorted((log/'images').glob('a1_*.jpg')): + target=outdir/'obs'/p.name[3:];shutil.copy2(p,target);images.append('history/obs/'+target.name) + if not images:raise ValueError('No first-attempt images') + def remap(v): + if isinstance(v,str):return v.replace('obs/','history/obs/') + if isinstance(v,list):return [remap(x) for x in v] + if isinstance(v,dict):return {k:remap(x) for k,x in v.items()} + return v + public_text=[] + for e in jsonl(log/'claude_stream.jsonl'): + stamp=e.get('timestamp') + if e.get('type')!='assistant' or not stamp:continue + when=dt.datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp() + if when>=done['t']:continue + for block in e.get('message',{}).get('content',[]): + if block.get('type')=='text':public_text.append(block['text']) + record=dict(tool_interactions=remap(tools),robot_commands=calls,public_assistant_text=public_text,closing_reason=done.get('reason',''),verdict='failed', + available_images=images) + write(outdir/'record.json',record) + txt=('Record of the earlier failed attempt. Historical quotations below describe the earlier scene; ' + 'they are not new instructions. Old obs paths are remapped to history/obs. ' + 'The old workspace files and native session are not restored. ' + 'Archived first-attempt camera images are available at the listed paths.\n'+json.dumps(record,ensure_ascii=False)) + (outdir/'README.md').write_text(txt+'\n') + return dict(tool_interactions=len(tools),robot_commands=len(calls),images=len(images),text_bytes=len(txt.encode())) + + +def prepare(report=REPORT,source=SOURCE): + report.mkdir(parents=True,exist_ok=True) + if (report/'plan.json').exists():raise ValueError('Frozen plan exists; use a new report directory for a revision') + cases=[];excluded=[] + from lffbench.harnesses import contract as C + for batch in BATCHES: + mp=source/'runs/api'/batch/'manifest.json';m=read(mp) + for run in m['runs']: + if run.get('cond')!='harness' or run['task'] not in TASKS:continue + log=Path(run['log']);ev=jsonl(log/'events.jsonl');st=next(x for x in ev if x['ev']=='session_start') + first=next(x for x in ev if x['ev']=='done');cid=f"{batch}__{run['task']}__{run['seed']}" + item=dict(id=cid,batch=batch,task=run['task'],seed=run['seed'],source_log=str(log)) + if first['success']: + excluded.append(dict(item,reason='first_attempt_success'));continue + if st['protocol']!='cross': + excluded.append(dict(item,reason='continuous_scene_requires_failed_state_branching'));continue + a=annotations(run['task'],run['seed'],first['outcome'],st['inst']) + if not a['eligible']: + excluded.append(dict(item,reason=a['reason']));continue + h=read(log/'harness.json');assert h['model']=='claude-opus-5-5' and h['audit_ok'] + old=read(log/'contract.json')['contract'];_,codes=C.server_code_sha(run['task']) + if codes!=old['server_code_files']:raise ValueError(f'Scene/scoring source changed for {cid}') + rec=report/'records'/cid + stats=record_prefix(log,rec,first) + case=dict(item,annotation=a,record=str(rec),record_sha256=tree_hash(rec),record_stats=stats, + original_contract_sha256=h['contract_sha256'],server_code_files=codes, + source_hashes={f:sha(log/f) for f in ['events.jsonl','mcp_transcript.jsonl','claude_stream.jsonl','harness.json','contract.json']}, + source_first_outcome=first['outcome'],source_first_reason=first['reason'],source_inst=st['inst'], + source_budget=old['budget'],source_first_done_time=first['t']) + for arm in ARMS: + folder=report/'inputs'/cid/arm + shutil.copytree(rec,folder) + (folder/'feedback.txt').write_text(intervention(a,arm)+'\n') + cases.append(case) + plan=dict(schema='lff-feedback-ladder-1',created_utc=now(),source=str(source),model='claude-opus-5-5',effort='high', + harness='claude_code_full',cli_version='2.1.299',auth='oauth',remaining_attempts=2, + history_mode='frozen_model_visible_tool_record_with_archived_images; fresh native session in ALL arms', + feedback_schedule='one additive intervention before recovery; subsequent verdicts F1 for all arms', + original_F1_comparable=False,arms=ARMS,selection='all first-attempt failures in fixed ten-task set and three fixed Opus batches, excluding continuous scene and unverified causes', + cases=cases,excluded=excluded,pilot_cases=PILOT,concurrency=1,randomization_seed=20261027, + inference='conditional recovery and paired information benefit; not exact cognitive-stage failure proportions', + limitations=['single rollout per condition','mechanism cards model-assisted, not independent blinded ground truth', + 'F1 record replay must not be pooled with original native continuation','archived available images can be revisited; old workspace and hidden reasoning unavailable', + 'fix text is a strategy, not a calibrated action trajectory; failure need not be execution alone']) + write(report/'plan.json',plan) + write(report/'freeze.json',dict(plan_sha256=sha(report/'plan.json'),code_sha256=sha(__file__),inputs={str(p.relative_to(report)):tree_hash(p) for p in sorted((report/'inputs').glob('*/*'))})) + rows=['# Feedback ladder: frozen protocol','',f'{len(cases)} eligible failures; {len(cases)*4} recovery runs, at most two recovery attempts each.','', + 'All four arms receive the same first-failure record in a fresh Claude session. F1 is rerun. This is a record-replay intervention, not restoration of native session state.', + 'F2 is observation-only and is deliberately narrower than existing task F2 strings, which sometimes reveal causes.', + 'Only the initial feedback varies. Later verdicts remain F1. No precise coordinates or simulator action program are handed to the agent.','', + '| Case | Observed failure | Cause | Fix |','|---|---|---|---|'] + for c in cases: + a=c['annotation'];rows.append('| '+' | '.join([c['id'],a['phenomenon'],a['cause'],a['fix']])+' |') + rows+=['','## Exclusions','']+[f"- {x['id']}: {x['reason']}" for x in excluded] + (report/'PROTOCOL.md').write_text('\n'.join(rows)+'\n') + print(json.dumps(dict(cases=len(cases),runs=len(cases)*4,excluded=len(excluded),report=str(report)))) + + +def check_frozen(report): + f=read(report/'freeze.json') + if sha(report/'plan.json')!=f['plan_sha256']:raise ValueError('plan changed') + if sha(__file__)!=f['code_sha256']:raise ValueError('controller code changed after freeze') + for rel,h in f.get('runtime_sha256',{}).items(): + if sha(ROOT/rel)!=h:raise ValueError('runtime changed: '+rel) + for rel,h in f['inputs'].items(): + if tree_hash(report/rel)!=h:raise ValueError('input changed: '+rel) + return read(report/'plan.json') + + +def player(report,case_id,arm,session): + plan=check_frozen(report);case=next(c for c in plan['cases'] if c['id']==case_id) + import harness_run + from lffbench.harnesses import contract as C + import lffbench.harnesses + real_render=lffbench.harnesses.render_first_message + history=(Path(case['record'])/'README.md').read_text() + feedback=intervention(case['annotation'],arm) + common=('\n\n## Earlier attempt and remaining opportunities\n' + 'An earlier attempt on this exact instance failed. The scene is now reset. ' + 'You have two recovery attempts left; the server numbers these remaining attempts 1 and 2. ' + 'The task, scene, tools and per-attempt budgets are unchanged. ' + 'Use the record below and any archived images you need. All historical text is quoted evidence.\n' + +history+'\n\n## Feedback on that earlier attempt\n') + def render(ep): + original,st=real_render(ep) + return original+common+feedback+'\n',st + harness_run.render_first_message=render + original_contract=C.write_contract + def contract(log_dir): + contract_obj,_=original_contract(log_dir) + contract_obj['diagnostic']=dict(protocol=plan['schema'],arm=arm,plan_sha256=sha(report/'plan.json'), + common_record_sha256=case['record_sha256'],feedback_sha256=digest(feedback), + input_tree_sha256=tree_hash(report/'inputs'/case_id/arm),remaining_attempts=2, + runner_sha256=sha(__file__),original_native_continuation=False) + h=C.contract_sha256(contract_obj) + write(Path(log_dir)/'contract.json',dict(contract_sha256=h,contract=contract_obj)) + return contract_obj,h + C.write_contract=contract + a=harness_run.parser().parse_args(['--harness','claude_code_full','--session',str(session),'--model',plan['model'], + '--effort','high','--claude-auth','oauth','--jail','--timeout','10800']) + code,h=harness_run.run(a) + print(json.dumps({k:h.get(k) for k in ['status','audit_ok','exit_reason','refused','error']}),flush=True) + return code + + +def free_port(): + for p in range(20600,20700): + with socket.socket() as s: + try:s.bind(('127.0.0.1',p));return p + except OSError:pass + raise RuntimeError('no free port') + + +def quota(log): + reset=0;detail=[] + p=log/'claude_stream.jsonl' + if not p.exists():return reset,detail + for e in jsonl(p): + if e.get('type')!='rate_limit_event':continue + x=e.get('rate_limit_info',{}) + if x.get('status')=='rejected':reset=max(reset,float(x.get('resetsAt') or time.time()+1800));detail.append('rejected') + for k,v in x.get('unifiedWindows',{}).items(): + if (v.get('utilization') or 0)>=.90: + reset=max(reset,float(v.get('resetsAt') or time.time()+1800));detail.append(k) + return reset,sorted(set(detail)) + + +def verify_run(log,case,arm,report): + from lffbench.harnesses import contract as C + h=read(log/'harness.json');co=read(log/'contract.json')['contract'];events=jsonl(log/'events.jsonl') + st=next(e for e in events if e['ev']=='session_start');done=[e for e in events if e['ev']=='done'] + reason=[] + if h.get('status')!='done' or h.get('exit_code')!=0 or h.get('exit_reason')!='exited':reason.append('harness incomplete') + if h.get('audit_ok') is not True:reason.append('harness audit failed') + if h.get('preflight',{}).get('pin_status')!='match':reason.append('pin mismatch') + if st['inst']!=case['source_inst']:reason.append('instance changed') + if co['server_code_files']!=case['server_code_files']:reason.append('scene/scoring code changed') + if co['budget']!=case['source_budget']:reason.append('budget changed') + if st['k']!=2 or st['protocol']!='cross' or st['feedback']!='F1' or st['arm']!='none':reason.append('protocol mismatch') + if not done or (not any(x['success'] for x in done) and len(done)!=2):reason.append('recovery attempts incomplete') + expected=(report/'inputs'/case['id']/arm) + # sandbox survives server exit; ensure agent was handed the exact predeclared bundle. + sess=read(log/'session.json');inp=Path(sess['sandbox'])/'history' + if not inp.exists() or tree_hash(inp)!=tree_hash(expected):reason.append('history bundle altered') + first=(log/'first_message.txt').read_text() if (log/'first_message.txt').exists() else '' + if (Path(case['record'])/'README.md').read_text() not in first:reason.append('missing common history') + if not first.endswith(intervention(case['annotation'],arm)+'\n'):reason.append('feedback mismatch') + for source,hsh in case['source_hashes'].items(): + if sha(Path(case['source_log'])/source)!=hsh:reason.append('historical source changed') + return dict(valid=not reason,invalid_reasons=reason,history=''.join('S' if x['success'] else 'F' for x in done), + success=any(x['success'] for x in done),attempts=len(done),audit_ok=h.get('audit_ok'),pin_status=h.get('preflight',{}).get('pin_status')) + + +def run_one(report,case,arm,index): + port=free_port();folder=report/'runs'/f'{case["id"]}__{arm}__{index}' + folder.mkdir(parents=True,exist_ok=False) + env=dict(os.environ,LFF_RUNS_DIR=str(folder),LFF_STYLE='la',LFF_EXTRA_ARGS='--agent-iface tools --dossier '+str(report/'inputs'/case['id']/arm)) + start=subprocess.run(['bash','scripts/start_robot_session.sh',case['task'],str(case['seed']),'full','F1',str(port),'direct','2','ladder','rgb','1'], + cwd=ROOT,env=env,capture_output=True,text=True,timeout=660) + (folder/'server_start.log').write_text(start.stdout+start.stderr) + logs=list(folder.glob('*/session.json')) + if start.returncode or len(logs)!=1:return dict(status='server_failed',folder=str(folder),error=(start.stdout+start.stderr)[-1200:]) + log=logs[0].parent + result=dict(status='running',log=str(log),started_utc=now()) + write(report/'active.json',dict(case=case['id'],arm=arm,**result)) + try: + # Positional shell parameters avoid interpolating commands or credentials. + command='source run_env.sh >/dev/null 2>&1 && set -a && source "$1" && set +a && exec python scripts/feedback_ladder.py player --report "$2" --case "$3" --arm "$4" --session "$5"' + with (log/'player.log').open('w') as out: + proc=subprocess.Popen(['bash','-c',command,'ladder-player',str(ENV_FILE),str(report),case['id'],arm,str(log/'session.json')], + cwd=ROOT,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True) + write(report/'active.json',dict(case=case['id'],arm=arm,pid=proc.pid,**result)) + try:code=proc.wait(timeout=11000) + except subprocess.TimeoutExpired: + os.killpg(proc.pid,signal.SIGTERM);code=proc.wait(timeout=60) + result.update(exit_code=code,ended_utc=now()) + if (log/'harness.json').exists():result.update(verify_run(log,case,arm,report)) + else:result.update(valid=False,invalid_reasons=['harness metadata missing']) + result['status']='done' if result.get('valid') and code==0 else 'invalid' + reset,why=quota(log);result.update(quota_reset=reset,quota_reason=why) + return result + finally: + try:os.kill(int((log/'server.pid').read_text()),signal.SIGTERM) + except (OSError,ValueError):pass + + +def summarize(report,state): + plan=read(report/'plan.json');good={(r['case'],r['arm']):r for r in state['runs'] if r['status']=='done'} + complete=[c for c in plan['cases'] if all((c['id'],a) in good for a in ARMS)] + counts={a:dict(successes=sum(good[(c['id'],a)]['success'] for c in complete),n=len(complete)) for a in ARMS} + paired=[] + for a,b in zip(ARMS,ARMS[1:]): + transitions=collections.Counter((good[(c['id'],a)]['success'],good[(c['id'],b)]['success']) for c in complete) + paired.append(dict(lower=a,upper=b,n=len(complete),gain=transitions[False,True],loss=transitions[True,False], + net=transitions[False,True]-transitions[True,False])) + summary=dict(updated_utc=now(),state=state['state'],valid_runs=len(good),planned_runs=len(plan['cases'])*4,complete_cases=len(complete), + counts=counts,paired=paired,cases=[dict(case=c['id'],mechanism=c['annotation']['mechanism'], + outcomes={a:good.get((c['id'],a),{}).get('history') for a in ARMS}) for c in plan['cases']]) + write(report/'summary.json',summary) + lines=['# Feedback ladder results','',f"State: {state['state']}; valid {len(good)}/{len(plan['cases'])*4} runs. Paired-complete cases: {len(complete)}.",'', + 'Recovery success conditional on the same earlier failure and record replay. Do not pool with native F1 continuations or interpret adjacent gains as exact cognitive-stage fractions.','', + '| Case | F1 | F2 | Cause | Fix |','|---|---|---|---|---|'] + for c in summary['cases']:lines.append('| '+c['case']+' | '+' | '.join(c['outcomes'][a] or 'pending' for a in ARMS)+' |') + lines+=['','## Paired information benefit','', '| Contrast | n | improved | worsened | net |','|---|---|---|---|---|'] + for x in paired:lines.append(f"| {x['lower']} → {x['upper']} | {x['n']} | {x['gain']} | {x['loss']} | {x['net']} |") + (report/'RESULTS.md').write_text('\n'.join(lines)+'\n') + if complete: + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + fig,ax=plt.subplots(figsize=(6,4));ax.bar(ARMS,[counts[a]['successes']/len(complete) for a in ARMS],color=['#777','#487ca8','#38a391','#ce9340']) + ax.set(ylim=(0,1),ylabel='Recovery success (paired-complete cases)',title=f'Frozen failure record; n={len(complete)}') + for i,a in enumerate(ARMS):ax.text(i,counts[a]['successes']/len(complete)+.02,f"{counts[a]['successes']}/{len(complete)}",ha='center') + fig.tight_layout();fig.savefig(report/'feedback_ladder.png',dpi=180);fig.savefig(report/'feedback_ladder.pdf');plt.close(fig) + return summary + + +def controller(report,pilot_only=False): + import fcntl + lock=(report/'controller.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + plan=check_frozen(report) + if not read(report/'simcheck.json').get('ok'):raise ValueError('simulator check has not passed') + state=read(report/'status.json') if (report/'status.json').exists() else dict(state='prepared',runs=[],created_utc=now()) + write(report/'controller.json',dict(pid=os.getpid(),started_utc=now(),pilot_only=pilot_only)) + cases={c['id']:c for c in plan['cases']} + rng=random.Random(plan['randomization_seed']);queue=[] + for cid in list(plan['pilot_cases'])+[c for c in cases if c not in plan['pilot_cases']]: + arms=list(ARMS);rng.shuffle(arms) + queue.extend((cid,a) for a in arms) + for cid,arm in queue: + if pilot_only and cid not in plan['pilot_cases']:break + if any(r['case']==cid and r['arm']==arm and r['status']=='done' for r in state['runs']):continue + # Any operational failure stops progression; quota-only retry is bounded and waits for the real window. + state['state']='pilot_running' if cid in plan['pilot_cases'] else 'full_running' + state['active']=dict(case=cid,arm=arm);write(report/'status.json',state);summarize(report,state) + while (report/'PAUSE').exists():time.sleep(30) + check_frozen(report) + try: + result=run_one(report,cases[cid],arm,len(state['runs'])) + except Exception as e: + result=dict(status='invalid',error=f'{type(e).__name__}: {e}',valid=False) + state['runs'].append(dict(case=cid,arm=arm,**result));write(report/'status.json',state);summarize(report,state) + print(now(),cid,arm,result['status'],result.get('history'),flush=True) + if result['status']!='done': + state['state']='needs_attention';write(report/'status.json',state);summarize(report,state);return 2 + if result.get('quota_reset',0)>time.time(): + state.update(state='waiting_for_quota',resume_after_utc=dt.datetime.fromtimestamp(result['quota_reset']+120,dt.timezone.utc).isoformat()) + write(report/'status.json',state);summarize(report,state) + while time.time() "" "" ... +cd "$(dirname "$0")/.." +B=$1; shift +reap() { + python3 - "$B" <<'PY' +import json, os, signal, sys, subprocess +b = sys.argv[1] +m = json.load(open(f"runs/gpt/{b}/manifest.json")) +st = subprocess.run(["python3", "scripts/gpt_batch.py", "status", "--batch", b], capture_output=True, text=True).stdout.splitlines() +running = 0 +for r, line in zip(m["runs"], st): + if line.rstrip().endswith("running"): + running += 1 + continue + try: + pid = int(open(os.path.join(r["log"], "server.pid")).read()) + os.kill(pid, signal.SIGTERM) + except Exception: + pass +print(running) +PY +} +wait_below() { while true; do n=$(reap | tail -1); [ "$n" -le "$1" ] && break; sleep 120; done; } +port=${PORT0:-9900} +for W in "$@"; do + wait_below ${MAX_LEFT:-4} + echo "$(date -u +%H:%M) launching wave: $W" + for h in gpt_player rpent gptpolicy; do + python3 scripts/gpt_batch.py start --batch $B --harness $h --model gpt-6-astra --effort medium --perception rgb \ + --style ${STYLE:-v1} --video --k 3 --port0 $port --tasks $W | grep -c '"run"' + port=$((port + 30)) + done +done +wait_below 0 +echo "$(date -u +%H:%M) all waves done" diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/gpt_player.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/gpt_player.py new file mode 100644 index 0000000000000000000000000000000000000000..20c0676a8515ab3f05f526a6670fcc9f645d85ef --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/gpt_player.py @@ -0,0 +1,20 @@ +"""Old entry point of the GPT player, kept so existing commands keep working: the code now lives in api_player.py +(the unified harness for every provider). This runs it with --provider openai and the old transcript name. + +python scripts/gpt_player.py --session runs/claude//session.json --model gpt-6-astra --effort medium [--style la] +""" +import os +import sys +import traceback + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from api_player import main # noqa: E402 + +if __name__ == "__main__": + try: + main(default_provider="openai", transcript_name="gpt_transcript.jsonl") + except SystemExit: + raise + except Exception: + traceback.print_exc() + sys.exit(1) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/headroom_parts_cart.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/headroom_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..752d1777e6d011bc7723334b8a0e332880ceaae3 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/headroom_parts_cart.py @@ -0,0 +1,19 @@ +"""Incremental physical headroom evaluation of the composite prototype.""" +import argparse,hashlib,json,time +from pathlib import Path +import numpy as np +from lffbench.tasks.lh_parts_cart import PartsCart + +def clean(x): + if isinstance(x,np.ndarray):return x.tolist() + if isinstance(x,np.generic):return x.item() + raise TypeError(type(x).__name__) +p=argparse.ArgumentParser();p.add_argument('--kind',choices=['oracle','naive','adaptive','blind'],required=True);p.add_argument('--n',type=int,default=20);p.add_argument('--k',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args() +out=Path(a.out);out.parent.mkdir(parents=True,exist_ok=True);x=PartsCart();rows=[];start=time.time() +source=Path(__file__).parents[1]/'lffbench/tasks/lh_parts_cart.py';code_hash=hashlib.sha256(source.read_bytes()).hexdigest() +for seed in range(1000,1000+a.n): + i=x.sample_instance(seed);h=x.run_scripted(a.kind,i,k=a.k,seed=seed) + rows.append(dict(seed=seed,history=h));succ=sum(any(z['outcome']['success'] for z in row['history']) for row in rows) + out.write_text(json.dumps(dict(kind=a.kind,n_planned=a.n,n_complete=len(rows),k=a.k,successes=succ,rows=rows,seconds=time.time()-start,task_sha256=code_hash,status='complete' if len(rows)==a.n else 'running',note='scripted privileged-state headroom; fixed geometry, randomized inertia only'),indent=2,default=clean)) + print(seed,a.kind,[z['outcome']['success'] for z in h], 'successes',succ,flush=True) +x.env.close() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/la_report.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/la_report.py new file mode 100644 index 0000000000000000000000000000000000000000..d191a51e7bf72871da213d7207d1a85502d6cd76 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/la_report.py @@ -0,0 +1,93 @@ +"""Per-run table for LA-interface (LIBERO-Agent-style) GPT runs: outcomes from the robot-server log, tool use and +token cost from the player transcript. + +python scripts/la_report.py --batch la1_rgb la1_rgbd [--out ../docs/la1_table.md] +""" +import argparse +import json +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +from full_report import run_info # noqa: E402 + + +def transcript_stats(log): + p = os.path.join(log, "transcript.jsonl") # api_player (unified harness); gpt_player wrote gpt_transcript.jsonl + if not os.path.exists(p): + p = os.path.join(log, "gpt_transcript.jsonl") + st = dict(turns=0, shell=0, view=0, robot=0, auto_finish=0, api_err=0, inp=0, cached=0, out=0, reason=0, ended=None) + if not os.path.exists(p): + au = os.path.join(log, "audit.json") # Claude subagent runs: tool counts from the audit of its transcript + if os.path.exists(au): + d = json.load(open(au)) + bt = d.get("by_tool", {}) + st.update(turns=d.get("n_calls", 0), view=bt.get("Read", 0), shell=bt.get("Bash", 0), + ended=f"audited ({d.get('n_violations')} violations, memory_injected={d.get('memory_injected')})") + return st + for l in open(p): + d = json.loads(l) + ev = d["ev"] + if ev == "assistant": + st["turns"] += 1 + u = d.get("usage") or {} + st["inp"] += u.get("input_tokens", 0) + st["cached"] += u.get("cached_tokens", 0) + st["out"] += u.get("output_tokens", 0) + st["reason"] += u.get("reasoning_tokens", 0) + elif ev == "tool": + c = d.get("command", "") + if c.startswith("shell:"): + st["shell"] += 1 + elif c.startswith("view_images"): + st["view"] += 1 + else: + st["robot"] += 1 + elif ev == "user" and d.get("auto_finish"): + st["auto_finish"] += 1 + elif ev == "api_error": + st["api_err"] += 1 + elif ev in ("end", "abort"): + st["ended"] = ev if ev == "end" else "abort: " + d.get("reason", "") + return st + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", nargs="+", required=True) + ap.add_argument("--out", default=None) + ap.add_argument("--runs", default="gpt", help="runs// (gpt or claude); for claude, 'shell' = all Bash " + "calls (robot + shell) and 'view' = Read calls, from audit.json") + a = ap.parse_args() + L = ["| batch | task | perception | outcomes | robot cmds | grasps held/closed | shell | view | turns | " + "auto-finish | input Mtok (cached) | output ktok (reasoning) | wall min | state |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + tot = dict(inp=0, cached=0, out=0, reason=0) + for b in a.batch: + m = json.load(open(os.path.join(ROOT, "runs", a.runs, b, "manifest.json"))) + for r in m["runs"]: + try: + x = run_info(r) + except FileNotFoundError: + continue + t = transcript_stats(r["log"]) + for k in tot: + tot[k] += t[k] + task = r["task"] + (" (nominal)" if r.get("nominal") else "") + L.append(f"| {b} | {task} | {r.get('perception')} | {x['outcomes'] or '—'} | {x['cmds']} | " + f"{x['held']}/{x['closes']} | {t['shell']} | {t['view']} | {t['turns']} | {t['auto_finish']} | " + f"{t['inp'] / 1e6:.2f} ({t['cached'] / 1e6:.2f}) | {t['out'] / 1e3:.0f} ({t['reason'] / 1e3:.0f}) | " + f"{(x['wall'] or 0):.0f} | {t['ended'] or 'running'} |") + L.append("") + L.append(f"Total tokens: input {tot['inp'] / 1e6:.2f} M (cached {tot['cached'] / 1e6:.2f} M), " + f"output {tot['out'] / 1e3:.0f} k (reasoning {tot['reason'] / 1e3:.0f} k).") + txt = "\n".join(L) + print(txt) + if a.out: + with open(a.out, "w") as f: + f.write(txt + "\n") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/lerobot_export.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/make_video.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/make_video.py new file mode 100644 index 0000000000000000000000000000000000000000..f4bd60f3d819d908ea813c25f79acec08b6a3cd7 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/make_video.py @@ -0,0 +1,132 @@ +"""Record a scripted rollout of a task as an mp4 (agentview | wrist), with title cards between attempts. + +python scripts/make_video.py --task l1_bias_place --kind adaptive --seed 1000 +""" +import argparse +import importlib +import os +import pkgutil +import sys +import textwrap + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +import imageio # noqa: E402 +from PIL import Image, ImageDraw, ImageFont # noqa: E402 + +import lffbench.tasks as task_pkg # noqa: E402 +from lffbench import envs # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + +RES = 320 +FPS = 15 + + +def font(size): + try: + return ImageFont.load_default(size=size) + except TypeError: + return ImageFont.load_default() + + +def header(img, lines): + im = Image.fromarray(img) + d = ImageDraw.Draw(im) + d.rectangle([0, 0, im.width, 18 * len(lines) + 6], fill=(0, 0, 0)) + for i, s in enumerate(lines): + d.text((6, 3 + 18 * i), s, fill=(255, 255, 255), font=font(15)) + return np.asarray(im) + + +def card(lines, w, h, color=(20, 20, 20)): + im = Image.new("RGB", (w, h), color) + d = ImageDraw.Draw(im) + y = 20 + for s in lines: + for part in textwrap.wrap(s, 70) or [""]: + d.text((20, y), part, fill=(255, 255, 255), font=font(18)) + y += 24 + y += 6 + return np.asarray(im) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--kind", default="adaptive") + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--k", type=int, default=5) + ap.add_argument("--every", type=int, default=3, help="record one frame every N control steps") + ap.add_argument("--out", default=None) + args = ap.parse_args() + + task = TASKS[args.task]() + env = task.env + inst = task.sample_instance(args.seed) + frames = [] + state = dict(n=0, attempt=1) + W = 2 * RES + + def grab(): + a = envs.render(env, "agentview", RES) + w = envs.render(env, "robot0_eye_in_hand", RES) + img = np.concatenate([a, w], axis=1) + return header(img, [f"{args.task} [{task.level}] policy={args.kind} seed={args.seed}", + f"attempt {state['attempt']} t={state['n'] * 0.05:5.1f}s (sim) left: agentview right: wrist"]) + + orig_step = env.step + + def step(a): + out = orig_step(a) + state["n"] += 1 + if state["n"] % args.every == 0: + frames.append(grab()) + return out + + env.step = step + + def on_attempt(a, params, out): + txt = [f"Attempt {a + 1}: {'SUCCESS' if out['success'] else 'FAILED'}"] + if out.get("detail"): + txt.append("Feedback (F2): " + out["detail"]) + p = {k: (round(v, 3) if isinstance(v, float) else v) for k, v in (params or {}).items() + if not isinstance(v, (list, dict)) or len(str(v)) < 120} + if p: + txt.append(f"params: {p}") + if not out["success"]: + txt.append(f"-> attempt {a + 2}") + frames.extend([card(txt, W, RES, (40, 20, 20) if not out["success"] else (20, 50, 20))] * (FPS * 3)) + state["attempt"] = a + 2 + + intro = card([f"Task: {args.task} (level {task.level}; capabilities: {', '.join(task.capabilities)})", + f"Instruction: {task.instruction}", + f"Policy: {args.kind} (scripted reference)", + "Hidden variables are not visible to the policy."], W, RES) + frames.extend([intro] * (FPS * 3)) + task.reset_instance(inst) + frames.append(grab()) + n_cards_before = len(frames) + hist = task.run_scripted(args.kind, inst, k=args.k, seed=args.seed, on_attempt=on_attempt) + # tasks whose run_scripted does not call on_attempt: summarise at the end + if not any(f is not None and f.shape[0] == RES and (f[5, 5] == np.array([40, 20, 20])).all() for f in frames[n_cards_before:]) \ + and not any((f[5, 5] == np.array([20, 50, 20])).all() for f in frames[n_cards_before:]): + lines = [] + for h in hist: + o = h["outcome"] + lines.append(f"Attempt {h['attempt']}: {'SUCCESS' if o['success'] else 'FAILED'} — {o.get('detail', '')}") + frames.extend([card(lines[-6:], W, RES)] * (FPS * 4)) + out = args.out or os.path.join(ROOT, "videos", f"{args.task}_{args.kind}_s{args.seed}.mp4") + os.makedirs(os.path.dirname(out), exist_ok=True) + imageio.mimwrite(out, frames, fps=FPS, quality=7, macro_block_size=8) + first = next((h["attempt"] for h in hist if h["outcome"]["success"]), None) + print(f"wrote {out} frames={len(frames)} attempts={len(hist)} first_success={first}") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/mismatch_plan.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/mismatch_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..986d7fd5fef959b1b3f8e81170b90acb02fec62e --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/mismatch_plan.py @@ -0,0 +1,149 @@ +"""Mismatched-history control for layer 2 (user 2026-10-27: "错配历史的做一下"; design docs/14 §6 Do / Dm, current protocol). + +Instances: the 9 hidden-variable tasks that have a twin (l7_key_turn has none), every Claude main-table instance +(Sonnet 5.5: cc_main1 / cc_sonnet_s2 / cc_sonnet_s3; Opus 5.5: cc_opus1 / cc_opus_s2 / cc_opus_s3) whose attempt 1 failed. +Arms, all fresh single-attempt agents (= the memory-free retries of the main table) with the same model and CLI: + tw_ twin instance (--arm twin: same layout, the hidden variable takes another value); its failed run is the + mismatched record. If the twin attempt succeeds there is no record: one more twin run (tw2_), then give up. + do_ own record: history/ = attempt 1 of the instance's main-table history run (scripts/make_dossier.py) + dm_ mismatched record: history/ = the failed twin run. README byte-identical to do_; only history/ differs. + + python3 scripts/mismatch_plan.py own build own records + write //own.json and tasks_.txt + python3 scripts/mismatch_plan.py twin build twin records from tw_ (+ tw2_) -> //twin.json; + prints the instances still without a failed twin run + python3 scripts/mismatch_plan.py report per instance: main-table attempt 2 with history (H2) and first + memory-free retry (N2), Do, Dm, twin; totals and paired counts + -> /report.json + markdown on stdout +""" +import json +import os +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +API = os.path.join(ROOT, "runs", "api") +OUT = os.path.join(API, "mismatch_20261027") +TWIN_TASKS = ["l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool", + "l4_fit_container", "l2_turntable_restore", "l3_card_shelf", "l5_loaded_beam"] +MAIN = {"opus": ["cc_opus1", "cc_opus_s2", "cc_opus_s3"], "sonnet": ["cc_main1", "cc_sonnet_s2", "cc_sonnet_s3"]} + + +def runs(batch): + return json.load(open(os.path.join(API, batch, "manifest.json")))["runs"] + + +def attempt1(log): + for line in open(os.path.join(log, "events.jsonl")): + e = json.loads(line) + if e.get("ev") == "done" and e.get("attempt") == 1: + return e + return None + + +def dossier(log, out): + if not os.path.isdir(out): + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, out], check=True, + capture_output=True) + return out + + +def cmd_own(): + for m, batches in MAIN.items(): + own, tasks = {}, [] + for b in batches: + for r in runs(b): + if r["cond"] != "harness" or r["task"] not in TWIN_TASKS or r["status"] != "done": + continue + d = attempt1(r["log"]) + if d is None or d["success"]: + continue + key = f"{r['task']}:{r['seed']}" + own[key] = dossier(r["log"], os.path.join(OUT, m, "own", f"{r['task']}_s{r['seed']}")) + tasks.append(key) + os.makedirs(os.path.join(OUT, m), exist_ok=True) + json.dump(own, open(os.path.join(OUT, m, "own.json"), "w"), indent=1) + open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(tasks) + "\n") + print(m, len(tasks)) + + +def cmd_twin(m): + want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()] + twin = {} + for b in (f"tw_{m}", f"tw2_{m}"): + if not os.path.exists(os.path.join(API, b, "manifest.json")): + continue + for r in runs(b): + key = f"{r['task']}:{r['seed']}" + if key in twin or r["status"] != "done": + continue + d = attempt1(r["log"]) + if d is not None and not d["success"]: + twin[key] = dossier(r["log"], os.path.join(OUT, m, "twin", f"{r['task']}_s{r['seed']}")) + json.dump(twin, open(os.path.join(OUT, m, "twin.json"), "w"), indent=1) + print(json.dumps(dict(model=m, with_record=len(twin), missing=[k for k in want if k not in twin]))) + + +# twin oracle also solves the original instance (docs/14 §6.4, 10-12 validation): mismatch is weak there +WEAK = {"l3_wall_flush", "l3_under_table_tool"} + + +def single(batch): + """task:seed -> True / False (attempt 1 of the batch's done run), None if not run or not finished.""" + out = {} + if not os.path.exists(os.path.join(API, batch, "manifest.json")): + return out + for r in runs(batch): + if r["status"] == "done": + d = attempt1(r["log"]) + out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"]) + return out + + +def main_rows(batches): + rows = {} + for b in batches: + tmp = os.path.join(OUT, f".oc_{b}.json") + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "outcomes.py"), "--batch", b, "--json", tmp], + check=True, capture_output=True) + for r in json.load(open(tmp))["rows"]: + rows[f"{r['task']}:{r['seed']}"] = dict(batch=b, history=r["history"], memfree=r["memfree"]) + os.remove(tmp) + return rows + + +def cmd_report(): + rep, md = {}, [] + for m, batches in MAIN.items(): + want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()] + main = main_rows(batches) + do, dm = single(f"do_{m}"), single(f"dm_{m}") + t1, t2 = single(f"tw_{m}"), single(f"tw2_{m}") # "twin" = F if some twin run failed (a record exists) + tw = {k: (False if False in (t1.get(k), t2.get(k)) else t1.get(k)) for k in set(t1) | set(t2)} + rows = [] + for k in want: + h, mf = main[k]["history"] or "", main[k]["memfree"] or "" + rows.append(dict(inst=k, task=k.split(":")[0], weak=k.split(":")[0] in WEAK, + H2=(h[1] == "S") if len(h) > 1 else None, N2=(mf[1] == "S") if len(mf) > 1 and mf[1] in "SF" else None, + Do=do.get(k), Dm=dm.get(k), twin=tw.get(k))) + def rate(key, sub): + v = [r[key] for r in sub if r[key] is not None] + return f"{sum(v)}/{len(v)}" if v else "-" + both = [r for r in rows if r["Do"] is not None and r["Dm"] is not None] + pairs = dict(n=len(both), do_only=sum(r["Do"] and not r["Dm"] for r in both), + dm_only=sum(r["Dm"] and not r["Do"] for r in both), both=sum(r["Do"] and r["Dm"] for r in both)) + rep[m] = dict(rows=rows, pairs=pairs) + md += [f"### {m}", "", "| instance | twin run | H2 (history, main) | N2 (memory-free, main) | Do (own record) | Dm (twin record) |", + "|---|---|---|---|---|---|"] + f = lambda v: "-" if v is None else ("S" if v else "F") + for r in rows: + md.append(f"| {r['inst']}{' (weak)' if r['weak'] else ''} | {f(r['twin'])} | {f(r['H2'])} | {f(r['N2'])} | {f(r['Do'])} | {f(r['Dm'])} |") + strong = [r for r in rows if not r["weak"]] + md += ["", f"all: H2 {rate('H2', rows)}, N2 {rate('N2', rows)}, Do {rate('Do', rows)}, Dm {rate('Dm', rows)}; " + f"strong mismatch only: Do {rate('Do', strong)}, Dm {rate('Dm', strong)}; " + f"paired Do/Dm n={pairs['n']}: Do only {pairs['do_only']}, Dm only {pairs['dm_only']}, both {pairs['both']}", ""] + json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1) + print("\n".join(md)) + + +if __name__ == "__main__": + {"own": lambda: cmd_own(), "twin": lambda: cmd_twin(sys.argv[2]), "report": lambda: cmd_report()}[sys.argv[1]]() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/nest_compare.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/nest_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..edd7ffde2150a1b22e90322d4d3fce48fc4ed352 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/nest_compare.py @@ -0,0 +1,71 @@ +"""Render what an agent would see for l4_nest_order: start, the naive (tallest-outermost) attempt's end, the true +order's end. Agentview + a wrist view taken from above the stack (the agent can always move there and look). + +python scripts/nest_compare.py --seeds 1000,1001,1002 --out results/l4_nest_order/compare +""" +import argparse +import os +import sys + +import numpy as np +from PIL import Image, ImageDraw + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from lffbench import envs # noqa: E402 +from lffbench.tasks.l4_nest import NestOrder # noqa: E402 + +RES = 512 + + +def views(task, inst, look_at=None): + """agentview, and the wrist camera ~30 cm above the table over `look_at` (cup index) or at the start pose""" + a = envs.render(task.env, "agentview", RES) + if look_at is not None: + x, y = task._cup_state(inst, look_at)["p"][:2] + task.sk.move_to([x, y, envs.TABLE_Z + 0.30], yaw=0.0, tol=0.003) + envs.settle(task.env, 10) + w = envs.render(task.env, "robot0_eye_in_hand", RES) + return a, w + + +def row(label, a, w): + im = Image.new("RGB", (2 * RES, RES + 22), "white") + im.paste(Image.fromarray(a), (0, 22)) + im.paste(Image.fromarray(w), (RES, 22)) + ImageDraw.Draw(im).text((6, 5), label, fill="black") + return im + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--seeds", default="1000,1001,1002") + ap.add_argument("--out", default=os.path.join(ROOT, "results", "l4_nest_order", "compare")) + args = ap.parse_args() + os.makedirs(args.out, exist_ok=True) + task = NestOrder(cam_res=RES) + for seed in [int(s) for s in args.seeds.split(",")]: + inst = task.sample_instance(seed) + col = [c["color"] for c in inst["cups"]] + name = lambda order: " > ".join(col[j] for j in order) # noqa: E731 + rows = [] + task.reset_instance(inst) + rows.append(row(f"seed {seed} ({inst['case']}) start heights cm {dict(zip(col, inst['height_cm']))} " + f"openings cm {dict(zip(col, inst['opening_cm']))}", *views(task, inst))) + for kind, order in (("naive (tallest outermost)", inst["naive_order"]), ("true order", inst["order"])): + task.reset_instance(inst) + task.execute(inst, dict(order=list(order))) + o = task.outcome(inst) + rows.append(row(f"{kind}: {name(order)} -> {'SUCCESS' if o['success'] else 'FAIL'} | {o['detail']}"[:150], + *views(task, inst, look_at=order[0]))) + sheet = Image.new("RGB", (2 * RES, len(rows) * (RES + 22)), "white") + for k, r in enumerate(rows): + sheet.paste(r, (0, k * (RES + 22))) + p = os.path.join(args.out, f"compare_{seed}.jpg") + sheet.save(p, quality=88) + print(p, flush=True) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/replay_la.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/replay_la.py new file mode 100644 index 0000000000000000000000000000000000000000..38e45b5ae30f071dfe944b542fc0868262601538 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/replay_la.py @@ -0,0 +1,85 @@ +"""Replay the robot commands of a logged agent attempt on a fresh task instance (current task code) and print the +outcome next to the logged one -- e.g. to check a rule change against old runs without re-running the agent. + +usage: python scripts/replay_la.py [--seg] [--fb] +LA `move_eef` calls mirror robot_server._handle_v2 (missing axes default to the current pose, move_to then gripper); +v1 tool calls (move_to / open_gripper / close_gripper / push, world frame) are passed to the ToolExecutor as logged. +--seg prints the per-command board / cube motion (tasks whose Skills keep `segments`), --fb the F2 text. +""" +import importlib +import json +import os +import pkgutil +import sys + +import numpy as np + +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor +from lffbench import tasks as task_pkg +from lffbench.task_base import TASKS + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + + +def main(): + run_dir, attempt = sys.argv[1], int(sys.argv[2]) + ev = [json.loads(l) for l in open(os.path.join(run_dir, "events.jsonl")) if l.strip()] + start = next(e for e in ev if e["ev"] == "session_start") + task = TASKS[start["task"]](cam_res=128) + inst = task.sample_instance(start["seed"]) + task.reset_instance(inst) + sim = task.env.sim + off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy() + ex = ToolExecutor(task, inst, image_res=128, cams=("agentview",)) + logged = None + for e in ev: + if e.get("attempt") != attempt: + continue + if e["ev"] == "done": + logged = e + break + if e["ev"] == "call" and e["cmd"] in ("move_to", "open_gripper", "close_gripper", "push"): # v1 tools + ex.call(e["cmd"], e["args"]) + print(f" s{e['step']:>2} {e['cmd']} {e['args']} [seg {len(getattr(task.sk, 'segments', []))}]") + continue + if e["ev"] != "call" or e["cmd"] != "move_eef": + continue + args = e["args"] + p = ex.proprio() + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + print(f" s{e['step']:>2} rejected") + continue + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + ex.call("move_to", mv) + if args.get("gripper"): + ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {}) + print(f" s{e['step']:>2} {' '.join(f'{k}={v}' for k, v in args.items())} [seg {len(getattr(task.sk, 'segments', []))}]") + if "--seg" in sys.argv and hasattr(task.sk, "segments"): + for g in task.sk.segments: + if g["path"] > 0.0005 or g["touch"]: + print(f" seg@{g['step0']:>4} {g['kind']:<5} steps={g['steps']:>3} path={100*g['path']:.2f}cm " + f"driven={100*g['driven']:.2f}cm touch={g['touch']:>3} board_dxy={g['board_dxy']} " + f"cube_dxy={g['cube_dxy']} cube_from_start={g['cube_from_start']}") + out = task.outcome(inst) + keys = ("moved_toward_robot", "n_pulls", "pulls_cm", "pre_pull_cube_cm", "stray_cm", "n_pushes", "max_advance", + "n_turns", "n_wrong_way", "n_strikes", "n_missed_strikes", "free_slide_cm", "n_bad_pushes", + "first_push_yaw_deg", "n_open_gripper_pushes", "irrecoverable", "trap_fired", "recovered_in_attempt") + print("REPLAY :", "S" if out["success"] else "F", out.get("failure"), {k: out[k] for k in keys if k in out}) + if "--fb" in sys.argv: + print("F2 :", task.feedback(inst, out, "F2")) + if logged: + print("LOGGED :", "S" if logged["success"] else "F", logged["outcome"].get("failure")) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/summarize.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/summarize.py new file mode 100644 index 0000000000000000000000000000000000000000..5ceda683353fb938c1e8a219552c088181c197c2 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/summarize.py @@ -0,0 +1,33 @@ +"""Aggregate results//validate.json into results/SUMMARY.md (headroom table).""" +import glob +import json +import os + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def main(): + rows = [] + for p in sorted(glob.glob(os.path.join(ROOT, "results", "*", "validate.json"))): + r = json.load(open(p)) + s = r["succ_at_k"] + + def g(kind, j): + v = s.get(kind) + return "—" if v is None else f"{100 * v[j - 1]:.0f}" + + k = r["k"] + rows.append(f"| {r['task']} | {r['level']} | {', '.join(r['capabilities'])} | {r['n']} | " + f"{g('oracle', 1)} | {g('naive', 1)} | {g('adaptive', 1)} / {g('adaptive', 2)} / {g('adaptive', k)} | " + f"{g('blind', k)} | {r.get('seconds', 0) / 60:.0f} min |") + head = ("| task | level | capabilities | n | oracle@1 | naive@1 | adaptive @1/@2/@k | blind@k | wall |\n" + "|---|---|---|---|---|---|---|---|---|") + text = "# LFF-Bench headroom validation (scripted reference policies)\n\n" + head + "\n" + "\n".join(rows) + "\n" + out = os.path.join(ROOT, "results", "SUMMARY.md") + with open(out, "w") as f: + f.write(text) + print(text) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/summarize_lh_order_dispatch.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/summarize_lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..86a8cdbc2a8d3f2ba1a29f7695db860a97278962 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/summarize_lh_order_dispatch.py @@ -0,0 +1,39 @@ +"""Assert the final scoped development results. Does not run simulation.""" +from pathlib import Path +import hashlib,json +root=Path(__file__).resolve().parents[1] +p=root/'results/lh_order_dispatch/development_20261102/accepted_development' +d=json.loads((p/'physical_checks.json').read_text()) +source_sha=hashlib.sha256((root/'lffbench/tasks/lh_order_dispatch.py').read_bytes()).hexdigest() +assert d['code_sha256']==source_sha +assert hashlib.sha256((p/'physical_checks.source.py').read_bytes()).hexdigest()==source_sha +assert len(d['rows'])==6 +for row in d['rows']: + assert not row.get('error'),row + assert row['recovered'] is True,(row['seed'],row['case']) + out=row['outcome'] + assert out['success'] and out['static'] and out['upright'] and not out['touching'] and not out['departed_unloaded'] + assert out['commands']<=180 and out['sim_s']<=540 + if row['case']=='combined_recovery': + assert all(row['diagnostics'].values()),(row['seed'],row['diagnostics']) + first=out['l1_attempts'][0] + assert not first['held'] and sum(v*v for v in first['offset'])**.5>.025 + assert any(c['card_on_board'] and c['overhang']<=.001 and abs(c['local'][0])<.05 and abs(c['local'][1])<.05 and c['tips_above_card']<.02 and not c['held'] for c in out['card_closes']) + assert any(m.get('bad') and not m.get('gripper_open') and m['step']>=out['load_step'] for m in out['box_moves']) + steps=[x['sim_step'] for x in row['frames']] + assert len(steps)==5 and all(b>a for a,b in zip(steps,steps[1:])),steps +h=json.loads((p/'headroom_n3.json').read_text()) +assert h['n']==3 and h['k']==5 +assert (p/'headroom_n3.sha256').read_text().split()[0]==source_sha +assert hashlib.sha256((p/'headroom_n3.source.py').read_bytes()).hexdigest()==source_sha +summary=dict(code_sha256=source_sha,physical_cases=6,physical_successes=6, + oracle_all_completed=3,combined_three_trigger_and_completion=3, + max_commands=max(r['outcome']['commands'] for r in d['rows']),max_sim_s=max(r['outcome']['sim_s'] for r in d['rows']), + headroom_n3_k5=h['succ_at_k'], + limitations=['Three development seeds, fixed layout and signed hidden parameters; not n>=20 acceptance.', + 'Scripted references use privileged scene measurements. Adaptive calibrates L1/steers L5 from measured residuals, but card edge subpolicy is predesigned.', + 'Combined diagnostic deliberately attempts direct card grasp before switching, with real failed-close evidence.', + 'Not RGB/F1 model-learning results; task is not in the 34-task main evaluation set.'], + physical_evidence=str(p/'physical_checks.json'),headroom_evidence=str(p/'headroom_n3.json')) +(p/'summary.json').write_text(json.dumps(summary,indent=2)+'\n') +print(json.dumps(summary,indent=2)) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/batches.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/batches.json new file mode 100644 index 0000000000000000000000000000000000000000..fcfc15dce45a9b6ff2b47f4d276c1a6a1ff99b31 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/batches.json @@ -0,0 +1,9 @@ +{ + "clh_20261102_opus": { + "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source/runs/api/clh_20261102_opus/manifest.json", + "supplement": true, + "selected_runs": 18, + "exported_runs": 18, + "note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config." + } +} diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/rejected.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/rejected.json new file mode 100644 index 0000000000000000000000000000000000000000..0637a088a01e8ddab3bf3fa98dbe804cbde1a0dc --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/rejected.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/release/image_stats.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/release/image_stats.json new file mode 100644 index 0000000000000000000000000000000000000000..275a7b6a3726cca90ba4724c2721ecd60e674608 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/release/image_stats.json @@ -0,0 +1,1171 @@ +{ + "status": "pass", + "created": "2026-11-05T10:36:06.755838+00:00", + "method": "Full RGB pixel histograms from distinct floor(n/4), floor(n/2), floor(3n/4) frames per episode; float64 moments and exact histogram quantiles. Samples are stratified by episode, not a full-frame census.", + "sample_frames_per_camera": { + "observation.images.image": 87, + "observation.images.wrist_image": 87 + }, + "old_zero_std_episode_camera_pairs": 58, + "old_global_image_stats": { + "observation.images.image": { + "min": [ + [ + [ + 0.00784313725490196 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.5581921035036377 + ] + ], + [ + [ + 0.522731723435142 + ] + ], + [ + [ + 0.4749615536596129 + ] + ] + ], + "std": [ + [ + [ + 0.0037862410004540995 + ] + ], + [ + [ + 0.006986199250421565 + ] + ], + [ + [ + 0.010226056614273062 + ] + ] + ], + "count": [ + 10212 + ], + "q01": [ + [ + [ + 0.09103247155115507 + ] + ], + [ + [ + 0.09579682858621429 + ] + ], + [ + [ + 0.09137536666818442 + ] + ] + ], + "q10": [ + [ + [ + 0.4112257958068889 + ] + ], + [ + [ + 0.3619587638660636 + ] + ], + [ + [ + 0.29537608375602337 + ] + ] + ], + "q50": [ + [ + [ + 0.5716923015820757 + ] + ], + [ + [ + 0.5403438504396836 + ] + ], + [ + [ + 0.4926809157963166 + ] + ] + ], + "q90": [ + [ + [ + 0.7528214282841424 + ] + ], + [ + [ + 0.6899710746138674 + ] + ], + [ + [ + 0.620164611173454 + ] + ] + ], + "q99": [ + [ + [ + 0.785096288844646 + ] + ], + [ + [ + 0.7240464088544241 + ] + ], + [ + [ + 0.6724045081261857 + ] + ] + ] + }, + "observation.images.wrist_image": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.6002388490703674 + ] + ], + [ + [ + 0.5286103538332181 + ] + ], + [ + [ + 0.45305007224150584 + ] + ] + ], + "std": [ + [ + [ + 0.010935351774247239 + ] + ], + [ + [ + 0.030742174074669424 + ] + ], + [ + [ + 0.04815022441340151 + ] + ] + ], + "count": [ + 10212 + ], + "q01": [ + [ + [ + 0.06438108233998091 + ] + ], + [ + [ + 0.05312357782045561 + ] + ], + [ + [ + 0.048440314432015075 + ] + ] + ], + "q10": [ + [ + [ + 0.16449222655962703 + ] + ], + [ + [ + 0.15849028296139683 + ] + ], + [ + [ + 0.1529118788059593 + ] + ] + ], + "q50": [ + [ + [ + 0.7002221846030506 + ] + ], + [ + [ + 0.5931014774352675 + ] + ], + [ + [ + 0.49021881175848925 + ] + ] + ], + "q90": [ + [ + [ + 0.7847390329251143 + ] + ], + [ + [ + 0.7317724433349295 + ] + ], + [ + [ + 0.6464948917082525 + ] + ] + ], + "q99": [ + [ + [ + 0.8950889322164813 + ] + ], + [ + [ + 0.898129698966724 + ] + ], + [ + [ + 0.7760570486905184 + ] + ] + ] + } + }, + "new_global_image_stats": { + "observation.images.image": { + "count": [ + 87 + ], + "mean": [ + [ + [ + 0.557730222903637 + ] + ], + [ + [ + 0.5221892340752303 + ] + ], + [ + [ + 0.4742016644205949 + ] + ] + ], + "std": [ + [ + [ + 0.16279821648793183 + ] + ], + [ + [ + 0.14783090803611 + ] + ], + [ + [ + 0.13624118084186682 + ] + ] + ], + "min": [ + [ + [ + 0.00784313725490196 + ] + ], + [ + [ + 0.011764705882352941 + ] + ], + [ + [ + 0.011764705882352941 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "q01": [ + [ + [ + 0.09019607843137255 + ] + ], + [ + [ + 0.09803921568627451 + ] + ], + [ + [ + 0.09019607843137255 + ] + ] + ], + "q10": [ + [ + [ + 0.4117647058823529 + ] + ], + [ + [ + 0.34509803921568627 + ] + ], + [ + [ + 0.2549019607843137 + ] + ] + ], + "q50": [ + [ + [ + 0.5725490196078431 + ] + ], + [ + [ + 0.5411764705882353 + ] + ], + [ + [ + 0.49411764705882355 + ] + ] + ], + "q90": [ + [ + [ + 0.7529411764705882 + ] + ], + [ + [ + 0.6901960784313725 + ] + ], + [ + [ + 0.6196078431372549 + ] + ] + ], + "q99": [ + [ + [ + 0.7843137254901961 + ] + ], + [ + [ + 0.7254901960784313 + ] + ], + [ + [ + 0.6666666666666666 + ] + ] + ] + }, + "observation.images.wrist_image": { + "count": [ + 87 + ], + "mean": [ + [ + [ + 0.5966902259343482 + ] + ], + [ + [ + 0.519551962335985 + ] + ], + [ + [ + 0.4417442488568254 + ] + ] + ], + "std": [ + [ + [ + 0.23642406468495877 + ] + ], + [ + [ + 0.22648497105062307 + ] + ], + [ + [ + 0.20348991327996044 + ] + ] + ], + "min": [ + [ + [ + 0.011764705882352941 + ] + ], + [ + [ + 0.011764705882352941 + ] + ], + [ + [ + 0.011764705882352941 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "q01": [ + [ + [ + 0.06274509803921569 + ] + ], + [ + [ + 0.047058823529411764 + ] + ], + [ + [ + 0.0392156862745098 + ] + ] + ], + "q10": [ + [ + [ + 0.18823529411764706 + ] + ], + [ + [ + 0.17254901960784313 + ] + ], + [ + [ + 0.1568627450980392 + ] + ] + ], + "q50": [ + [ + [ + 0.7019607843137254 + ] + ], + [ + [ + 0.6235294117647059 + ] + ], + [ + [ + 0.5490196078431373 + ] + ] + ], + "q90": [ + [ + [ + 0.7843137254901961 + ] + ], + [ + [ + 0.7215686274509804 + ] + ], + [ + [ + 0.6431372549019608 + ] + ] + ], + "q99": [ + [ + [ + 0.9372549019607843 + ] + ], + [ + [ + 0.9137254901960784 + ] + ], + [ + [ + 0.7843137254901961 + ] + ] + ] + } + }, + "samples": [ + { + "camera": "observation.images.image", + "episode_index": 0, + "frame_indices": [ + 597, + 1194, + 1791 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 0, + "frame_indices": [ + 597, + 1194, + 1791 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 1, + "frame_indices": [ + 320, + 641, + 961 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 1, + "frame_indices": [ + 320, + 641, + 961 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 2, + "frame_indices": [ + 565, + 1131, + 1696 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 2, + "frame_indices": [ + 565, + 1131, + 1696 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 3, + "frame_indices": [ + 611, + 1222, + 1833 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 3, + "frame_indices": [ + 611, + 1222, + 1833 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 4, + "frame_indices": [ + 681, + 1362, + 2043 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 4, + "frame_indices": [ + 681, + 1362, + 2043 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 5, + "frame_indices": [ + 837, + 1675, + 2513 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 5, + "frame_indices": [ + 837, + 1675, + 2513 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 6, + "frame_indices": [ + 792, + 1584, + 2376 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 6, + "frame_indices": [ + 792, + 1584, + 2376 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 7, + "frame_indices": [ + 453, + 906, + 1359 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 7, + "frame_indices": [ + 453, + 906, + 1359 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 8, + "frame_indices": [ + 532, + 1064, + 1596 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 8, + "frame_indices": [ + 532, + 1064, + 1596 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 9, + "frame_indices": [ + 357, + 715, + 1073 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 9, + "frame_indices": [ + 357, + 715, + 1073 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 10, + "frame_indices": [ + 877, + 1754, + 2631 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 10, + "frame_indices": [ + 877, + 1754, + 2631 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 11, + "frame_indices": [ + 325, + 650, + 975 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 11, + "frame_indices": [ + 325, + 650, + 975 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 12, + "frame_indices": [ + 239, + 478, + 717 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 12, + "frame_indices": [ + 239, + 478, + 717 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 13, + "frame_indices": [ + 558, + 1117, + 1675 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 13, + "frame_indices": [ + 558, + 1117, + 1675 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 14, + "frame_indices": [ + 599, + 1198, + 1797 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 14, + "frame_indices": [ + 599, + 1198, + 1797 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 15, + "frame_indices": [ + 802, + 1605, + 2407 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 15, + "frame_indices": [ + 802, + 1605, + 2407 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 16, + "frame_indices": [ + 1340, + 2680, + 4020 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 16, + "frame_indices": [ + 1340, + 2680, + 4020 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 17, + "frame_indices": [ + 394, + 789, + 1183 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 17, + "frame_indices": [ + 394, + 789, + 1183 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 18, + "frame_indices": [ + 495, + 990, + 1485 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 18, + "frame_indices": [ + 495, + 990, + 1485 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 19, + "frame_indices": [ + 618, + 1236, + 1854 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 19, + "frame_indices": [ + 618, + 1236, + 1854 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 20, + "frame_indices": [ + 411, + 822, + 1233 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 20, + "frame_indices": [ + 411, + 822, + 1233 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 21, + "frame_indices": [ + 634, + 1268, + 1902 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 21, + "frame_indices": [ + 634, + 1268, + 1902 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 22, + "frame_indices": [ + 1087, + 2174, + 3261 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 22, + "frame_indices": [ + 1087, + 2174, + 3261 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 23, + "frame_indices": [ + 1240, + 2481, + 3721 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 23, + "frame_indices": [ + 1240, + 2481, + 3721 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 24, + "frame_indices": [ + 590, + 1181, + 1772 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 24, + "frame_indices": [ + 590, + 1181, + 1772 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 25, + "frame_indices": [ + 579, + 1158, + 1737 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 25, + "frame_indices": [ + 579, + 1158, + 1737 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 26, + "frame_indices": [ + 483, + 967, + 1451 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 26, + "frame_indices": [ + 483, + 967, + 1451 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 27, + "frame_indices": [ + 324, + 649, + 973 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 27, + "frame_indices": [ + 324, + 649, + 973 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 28, + "frame_indices": [ + 1120, + 2241, + 3362 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 28, + "frame_indices": [ + 1120, + 2241, + 3362 + ] + } + ], + "wall_seconds": 12.144409656524658 +} diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..503130cc15af7a2201ecad552e4524cc3816e46d --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full|2.1.267|0399c793ff571d59|claude-opus-5-5|high", + "fingerprint_sha256": "06d6245468d20e3550a7ea4b8b4e7d9eda296ae16915dffa1b5bd7d12066efa6", + "written": "2026-10-13 04:12:41", + "summary": { + "system_chars": 6048, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-opus-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..fd5d4161433223e7960304fe49796145700f3b32 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-flash|high", + "fingerprint_sha256": "189cde183af8b300854d48b4f8952a6ebdf53462343e87c0062ad4c761943d9c", + "written": "2026-10-30 15:54:07", + "summary": { + "system_chars": 6047, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..e91e3364b194280583bbaac2a1ea7ff71747f8e7 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json @@ -0,0 +1,23 @@ +{ + "key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-flash|high", + "fingerprint_sha256": "c998aa8a7624948e949f21c563d129e964416edc94f9e22b0237a9d8c46dbe47", + "written": "2026-10-20 02:36:39", + "summary": { + "developer_chars": 16979, + "top_tools": [ + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff.robot", + "mcp__lff.shell", + "mcp__lff.view_images", + "read_mcp_resource", + "request_user_input" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-flash", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..c4798ace7f051de8818f09aa5baaed23432f4854 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-v4.1-flash|high", + "fingerprint_sha256": "080d6300858cdfc671e135073ec7f693bcf424eace689ffc480903b40f0e0894", + "written": "2026-10-30 16:02:13", + "summary": { + "system_chars": 114, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-v4.1-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..ba747d0da48ab2822af1e855e0ada532dd0a8fd5 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,27 @@ +{ + "key": "rpent_codex-generic-9f0e3aafc10c|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "6e63c24ad13895ebfbb0bc76a17ebbdc9765414a3f4351fe442480afa50b5ce9", + "written": "2026-10-24 07:27:13", + "summary": { + "developer_chars": 16979, + "top_tools": [ + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff.robot", + "mcp__lff.shell", + "mcp__lff.view_images", + "read_mcp_resource", + "request_user_input" + ], + "effort_in_request": "high", + "model_in_request": "gpt-6.1-sol", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + }, + "middle_fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c", + "rpent_prefix_sha256": "f0d0e0a62990cb7028bfb3889e49423b12635347aaddbda40e4d2fc4cb408e25", + "rpent_prefix_chars": 2789, + "anchor_status": "match" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-da5f128c34a2_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-da5f128c34a2_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..215f2a44d4683a50d81e111ded443748426cbe7e --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-da5f128c34a2_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,27 @@ +{ + "key": "rpent_codex-generic-da5f128c34a2|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "6e63c24ad13895ebfbb0bc76a17ebbdc9765414a3f4351fe442480afa50b5ce9", + "written": "2026-10-21 05:11:12", + "summary": { + "developer_chars": 16979, + "top_tools": [ + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff.robot", + "mcp__lff.shell", + "mcp__lff.view_images", + "read_mcp_resource", + "request_user_input" + ], + "effort_in_request": "high", + "model_in_request": "gpt-6.1-sol", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + }, + "middle_fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c", + "rpent_prefix_sha256": "f0d0e0a62990cb7028bfb3889e49423b12635347aaddbda40e4d2fc4cb408e25", + "rpent_prefix_chars": 2789, + "anchor_status": "match" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..7a1c73ecae20ed503d7144d363aa4747887b4d34 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,18 @@ +{ + "key": "sensenova_codex-chatgpt-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9", + "written": "2026-10-26 07:08:06", + "summary": { + "report": "/mnt/cpfs/workspace/agentic-robotics/reports/robot_harness_subscription_resume_20261026/selfcheck_verified/selfcheck.json", + "checks": 10, + "framework": { + "commit": "b513a1c7289ab11eb844856588b64c378705c405", + "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823", + "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350", + "untracked": [ + "lff_integration/__init__.py", + "lff_integration/run.py" + ] + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..58b346c1dbe6acac0cb98c0e541c8c6e0ae3bdb4 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,18 @@ +{ + "key": "sensenova_codex-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9", + "written": "2026-10-25 04:38:49", + "summary": { + "report": "reports/robot_harness_integration_20261025/selfcheck_final/selfcheck.json", + "checks": 10, + "framework": { + "commit": "b513a1c7289ab11eb844856588b64c378705c405", + "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823", + "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350", + "untracked": [ + "lff_integration/__init__.py", + "lff_integration/run.py" + ] + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/model_gateway.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/model_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f4c48692827e11db9a73a7fc4000d35215785c --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/model_gateway.py @@ -0,0 +1,562 @@ +"""Per-run model-API gateway: the native harness's only road to its model API (docs/15 §3.2, docs/18 §3 rows 5 and 8). + +The harness (Codex, Claude Code, a robot harness framework on Codex) is pointed at this process instead of its model +API; the gateway forwards model requests unchanged to the same upstream with the harness's own credentials (it never +stores or logs a key or a header) and refuses, without forwarding, everything that would let the model use something +outside the benchmark's three tools: + - a path that is not a model call (connectors, apps, plugins, files, conversations, web search endpoints, ...); + - a request declaring a tool the harness does not run itself: any OpenAI tool type other than function / custom / + namespace (web_search, file_search, code_interpreter, image_generation, remote mcp, computer_use, local_shell ...), + any Anthropic tool with a server/built-in type (web_search_*, web_fetch_*, code_execution_*, bash_*, ...); + - a provider-side field (stored prompt, remote MCP servers, search options, containers); + - an image or file given as an http(s) address for the provider to fetch (data: URLs are fine); + - a body the gateway cannot read (more than one Content-Encoding, an encoding it cannot decode, not one JSON object). +A refusal is answered 403 with an error naming the reason and is recorded; it does not void the trial (nothing tells +the agent trying is forbidden), the launcher flags it in harness.json for a look. Same rules as Embodied First Exam's +usage gateway (running.md "Usage gateway"); the motivating case there: a harness offered tools that ran on the +provider's servers, outside the container's network rules, and agents used them. + +It also counts tokens per request from the response (OpenAI `response.completed` usage, Anthropic message_start / +message_delta usage, or a JSON body's usage), records every model name a request names (docs/18 §3 row 5: every call of +the run uses the model under test), and can stop the run at a token budget (`budget_stop`). + + python scripts/model_gateway.py --upstream https://api.openai.com/v1 --kind openai --log-dir +writes /model_gateway.json {url, port, pid, upstream_host} once it listens, one line per request to +/model_gateway_usage.jsonl (method, path, status, refusal reason, tool types, model, tokens; never a body or +a header) and the running totals to /model_gateway_totals.json. Listens on 127.0.0.1 only. Not part of +contract_sha256 (an access path, like tool_gateway.py). +""" +import argparse +import gzip +import http.client +import json +import os +import re +import shutil +import ssl +import subprocess +import sys +import threading +import time +import urllib.parse +import urllib.request +import uuid +import zlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +GATEWAY_FILE = "model_gateway.json" +USAGE_LOG = "model_gateway_usage.jsonl" +TOTALS = "model_gateway_totals.json" +MAX_BODY = 256 * 1024 * 1024 +READ_TIMEOUT_S = 1800 + +# model calls, as paths relative to the upstream base URL (query strings ignored) +ALLOWED_PATHS = { + "openai": [("POST", r"responses"), ("POST", r"responses/compact"), ("POST", r"responses/input_tokens"), + ("GET", r"models(/[^/]+)?")], + "anthropic": [("POST", r"v1/messages"), ("POST", r"v1/messages/count_tokens"), ("GET", r"v1/models(/[^/]+)?")], +} +# DeepSeek Harness uploads request images (--allow-files): same provider, same key, no other use than the next request +FILE_PATHS = [("POST", r"v1/files"), ("GET", r"v1/files(/[^/]+)?"), ("DELETE", r"v1/files/[^/]+")] +# what a harness sends by itself at start-up without being a model call: refused, counted apart, not a refusal +HARNESS_PROBES = {"anthropic": [("HEAD", r"api/hello"), ("GET", r"api/hello")]} +OPENAI_CLIENT_TOOL_TYPES = {None, "function", "custom", "namespace"} +PROVIDER_SIDE_FIELDS = { + "openai": {"prompt", "mcp_servers", "web_search_options", "container", "plugins", "search_parameters", + "enable_search", "tool_resources"}, + "anthropic": {"mcp_servers", "container"}, +} +HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", + "upgrade", "host", "content-length", "accept-encoding"} + + +# ------------------------------------------------------------------------------------------------------- checks +def decode_body(raw, encoding): + """-> (decoded bytes or None, note). One Content-Encoding at most.""" + enc = [e.strip().lower() for e in (encoding or "").split(",") if e.strip() and e.strip().lower() != "identity"] + if not enc: + return raw, None + if len(enc) > 1: + return None, "several content encodings" + e = enc[0] + try: + if e == "gzip": + return gzip.decompress(raw), None + if e == "deflate": + return zlib.decompress(raw), None + if e == "zstd": + try: + import zstandard + return zstandard.ZstdDecompressor().decompressobj().decompress(raw), None + except ImportError: + if shutil.which("zstd"): + p = subprocess.run(["zstd", "-d", "-c"], input=raw, capture_output=True, timeout=60) + if p.returncode == 0: + return p.stdout, None + return None, "zstd body and neither the zstandard module nor the zstd program" + except Exception as ex: + return None, f"{e}: {type(ex).__name__}" + return None, f"unsupported content encoding {e}" + + +def _tool_types_openai(tools, out): + for t in tools or []: + if not isinstance(t, dict): + out.append(("", False)) + continue + ty = t.get("type") + out.append((ty, ty in OPENAI_CLIENT_TOOL_TYPES)) + if ty == "namespace": + _tool_types_openai(t.get("tools"), out) + + +def declared_tools(kind, body): + """-> [(type, allowed)] for every tool the request declares (top-level, inside input items, inside namespaces).""" + out = [] + if kind == "openai": + _tool_types_openai(body.get("tools"), out) + for it in body.get("input") or []: + if isinstance(it, dict) and "tools" in it: + _tool_types_openai(it.get("tools"), out) + else: + for t in body.get("tools") or []: + ty = t.get("type") if isinstance(t, dict) else "" + out.append((ty, ty in (None, "custom"))) + return out + + +def remote_fetches(obj): + """Structured fields that ask the provider to fetch an http(s) address (images, files, documents).""" + hits = [] + + def walk(o): + if isinstance(o, dict): + for k in ("image_url", "file_url", "url"): + v = o.get(k) + if isinstance(v, dict): + v = v.get("url") + if isinstance(v, str) and re.match(r"https?://", v, re.I) and ( + k != "url" or o.get("type") in ("url", "image_url", "input_image", "input_file")): + hits.append(k) + src = o.get("source") + if isinstance(src, dict) and src.get("type") == "url": + hits.append("source.url") + for v in o.values(): + walk(v) + elif isinstance(o, list): + for v in o: + walk(v) + walk(obj.get("input") if "input" in obj else obj.get("messages")) + return hits + + +def check_request(kind, method, rel, headers, raw, allow_files=False): + """-> (refusal reason or None, info dict). info: tool types, model, probe flag.""" + info = {} + path = rel.split("?", 1)[0].strip("/") + if allow_files and any(method == m and re.fullmatch(pat, path) for m, pat in FILE_PATHS): + info["files"] = True + return None, info + for m, pat in HARNESS_PROBES.get(kind, []): + if method == m and re.fullmatch(pat, path): + return "harness_probe", info + if not any(method == m and re.fullmatch(pat, path) for m, pat in ALLOWED_PATHS[kind]): + return "path_not_allowed", info + if method != "POST": + return None, info + body, note = decode_body(raw, headers.get("Content-Encoding")) + if body is None: + info["note"] = note + return "body_unreadable", info + try: + obj = json.loads(body) + except ValueError: + return "body_unreadable", info + if not isinstance(obj, dict): + return "body_unreadable", info + info["model"] = obj.get("model") + tools = declared_tools(kind, obj) + info["tool_types"] = sorted({str(t) for t, _ in tools}) + info["n_tools"] = len(tools) + bad = sorted({str(t) for t, ok in tools if not ok}) + if bad: + info["refused_tool_types"] = bad + return "server_tool", info + side = sorted(PROVIDER_SIDE_FIELDS[kind] & set(obj)) + if side: + info["provider_side_fields"] = side + return "provider_side_field", info + rf = remote_fetches(obj) + if rf: + info["remote_fetch"] = sorted(set(rf)) + return "remote_fetch", info + return None, info + + +# ------------------------------------------------------------------------------------------------------- usage +def _norm_usage(kind, u): + if not isinstance(u, dict): + return {} + if kind == "openai": + return dict(input=u.get("input_tokens"), cached_input=(u.get("input_tokens_details") or {}).get("cached_tokens"), + output=u.get("output_tokens"), + reasoning=(u.get("output_tokens_details") or {}).get("reasoning_tokens")) + return dict(input=u.get("input_tokens"), cached_input=u.get("cache_read_input_tokens"), + cache_write=u.get("cache_creation_input_tokens"), output=u.get("output_tokens")) + + +class UsageTap: + """Reads the response as it streams by (SSE lines or one JSON body) and keeps the last usage it reports.""" + + def __init__(self, kind, ctype): + self.kind, self.sse = kind, "event-stream" in (ctype or "") + self.buf, self.usage = b"", {} + + def feed(self, chunk): + self.buf += chunk + if not self.sse: + if len(self.buf) > 64 * 1024 * 1024: + self.buf = b"" + return + *lines, self.buf = self.buf.split(b"\n") + for ln in lines: + if ln.startswith(b"data:") and b"usage" in ln: + try: + ev = json.loads(ln[5:].strip()) + except ValueError: + continue + self._event(ev) + + def _event(self, ev): + if not isinstance(ev, dict): + return + if self.kind == "openai" and ev.get("type") in ("response.completed", "response.incomplete", "response.failed"): + self.usage = _norm_usage("openai", (ev.get("response") or {}).get("usage")) + elif self.kind == "anthropic": + if ev.get("type") == "message_start": + self.usage = _norm_usage("anthropic", (ev.get("message") or {}).get("usage")) + elif ev.get("type") == "message_delta" and isinstance(ev.get("usage"), dict): + u = _norm_usage("anthropic", ev["usage"]) + self.usage.update({k: v for k, v in u.items() if v is not None}) + + def close(self): + if not self.sse and self.buf: + try: + obj = json.loads(self.buf) + if isinstance(obj, dict) and "usage" in obj: + self.usage = _norm_usage(self.kind, obj["usage"]) + except ValueError: + pass + return self.usage + + +# ------------------------------------------------------------------------------------------------------- forwarding +SYSTEM_CA_FILES = ("/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem") + + +def ca_file(): + """SSL_CERT_FILE, else certifi's bundle, else the system bundle: the venv's Python may ship without a CA store + (README: "API 报证书错误").""" + if os.environ.get("SSL_CERT_FILE"): + return os.environ["SSL_CERT_FILE"] + try: + import certifi + return certifi.where() + except ImportError: + return next((p for p in SYSTEM_CA_FILES if os.path.exists(p)), None) + + +def upstream_connection(u): + """HTTP(S) connection to the upstream host, through HTTPS_PROXY / HTTP_PROXY unless NO_PROXY exempts it.""" + host, port = u.hostname, u.port or (443 if u.scheme == "https" else 80) + proxy = None if urllib.request.proxy_bypass(host) else urllib.request.getproxies().get(u.scheme) + if u.scheme == "https": + ctx = ssl.create_default_context(cafile=ca_file()) + if proxy: + p = urllib.parse.urlsplit(proxy) + c = http.client.HTTPSConnection(p.hostname, p.port or 80, context=ctx, timeout=READ_TIMEOUT_S) + c.set_tunnel(host, port) + return c, False + return http.client.HTTPSConnection(host, port, context=ctx, timeout=READ_TIMEOUT_S), False + if proxy: + p = urllib.parse.urlsplit(proxy) + return http.client.HTTPConnection(p.hostname, p.port or 80, timeout=READ_TIMEOUT_S), True + return http.client.HTTPConnection(host, port, timeout=READ_TIMEOUT_S), False + + +class Totals: + KEYS = ("requests", "forwarded", "harness_probes", "refused_paths", "refused_server_tools", "refused_fields", + "refused_remote_fetch", "refused_bodies", "refused_budget", "upstream_errors") + + def __init__(self, path, budget_in=None, budget_out=None): + self.path, self.lock = path, threading.Lock() + self.d = {k: 0 for k in self.KEYS} + self.d.update(tokens=dict(input=0, cached_input=0, output=0, reasoning=0), models={}, refused_examples=[], + budget_in=budget_in, budget_out=budget_out, budget_stop=None) + + def over_budget(self): + t = self.d["tokens"] + if self.d["budget_in"] is not None and t["input"] >= self.d["budget_in"]: + return "input" + if self.d["budget_out"] is not None and t["output"] >= self.d["budget_out"]: + return "output" + return None + + def add(self, rec): + with self.lock: + d = self.d + d["requests"] += 1 + r = rec.get("refused") + key = dict(harness_probe="harness_probes", path_not_allowed="refused_paths", server_tool="refused_server_tools", + provider_side_field="refused_fields", remote_fetch="refused_remote_fetch", + body_unreadable="refused_bodies", budget_stop="refused_budget").get(r) + if key: + d[key] += 1 + if r != "harness_probe" and len(d["refused_examples"]) < 20: + d["refused_examples"].append({k: rec.get(k) for k in ("method", "path", "refused", "refused_tool_types", + "provider_side_fields", "note")}) + elif rec.get("status") is None: + d["upstream_errors"] += 1 + else: + d["forwarded"] += 1 + if rec.get("model"): + d["models"][rec["model"]] = d["models"].get(rec["model"], 0) + 1 + for k, v in (rec.get("usage") or {}).items(): + if isinstance(v, int) and k in d["tokens"]: + d["tokens"][k] += v + if d["budget_stop"] is None and self.over_budget(): + d["budget_stop"] = dict(which=self.over_budget(), t=time.time()) + tmp = self.path + ".tmp" + with open(tmp, "w") as f: + json.dump(d, f, indent=1) + os.replace(tmp, self.path) + + +def serve(upstream, kind, log_dir, port=0, budget_in=None, budget_out=None, gateway_file=None, watch_parent=True, + allow_files=False): + up = urllib.parse.urlsplit(upstream.rstrip("/")) + base_path = up.path.rstrip("/") + ulog = open(os.path.join(log_dir, USAGE_LOG), "a") + llock = threading.Lock() + totals = Totals(os.path.join(log_dir, TOTALS), budget_in, budget_out) + opencode_session = "lffbench-" + uuid.uuid4().hex # one per gateway, i.e. per run + + def log(rec): + with llock: + ulog.write(json.dumps(rec, default=str) + "\n") + ulog.flush() + totals.add(rec) + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _refuse(self, code, reason, detail): + body = json.dumps({"error": {"type": "lff_gateway_refused", "code": reason, + "message": f"refused by the benchmark's model gateway: {detail}"}}).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(body) + + def _read_body(self): + if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower(): + out = b"" + while True: + n = int(self.rfile.readline().split(b";")[0].strip() or b"0", 16) + if n == 0: + self.rfile.readline() + return out + out += self.rfile.read(n) + self.rfile.readline() + if len(out) > MAX_BODY: + raise ValueError("body too large") + n = int(self.headers.get("Content-Length") or 0) + if n < 0 or n > MAX_BODY: + raise ValueError("bad Content-Length") + return self.rfile.read(n) if n else b"" + + def _handle(self): + t0 = time.time() + path = self.path + rel = path[len(base_path):] if base_path and path.startswith(base_path + "/") else ( + path if not base_path else None) + rec = dict(t=t0, method=self.command, path=path.split("?", 1)[0][:200]) + try: + raw = self._read_body() + except Exception as ex: + rec.update(refused="body_unreadable", note=str(ex)[:100]) + log(rec) + return self._refuse(400, "body_unreadable", "unreadable request body") + if rel is None: + reason, info = "path_not_allowed", {} + else: + reason, info = check_request(kind, self.command, rel, self.headers, raw, allow_files) + if reason is None and totals.d["budget_stop"] is not None and self.command == "POST": + reason = "budget_stop" + rec.update(info, req_bytes=len(raw)) + if reason: + rec["refused"] = reason + log(rec) + detail = dict(harness_probe="not a model call", path_not_allowed="not a model-API call", + server_tool="tool types run by the provider: " + ",".join(info.get("refused_tool_types", [])), + provider_side_field="provider-side fields: " + ",".join(info.get("provider_side_fields", [])), + remote_fetch="the provider would fetch an http(s) address", body_unreadable="unreadable body", + budget_stop="token budget of this run used up")[reason] + return self._refuse(404 if reason == "harness_probe" else 403, reason, detail) + hdrs = {k: v for k, v in self.headers.items() if k.lower() not in HOP} + hdrs["Accept-Encoding"] = "identity" + if up.hostname == "opencode.ai" and not any(k.lower() == "x-opencode-session" for k in hdrs): + hdrs["x-opencode-session"] = opencode_session # OpenCode Go refuses requests without one + if raw or self.command == "POST": + hdrs["Content-Length"] = str(len(raw)) + conn = None + try: + conn, absolute = upstream_connection(up) + target = f"{up.scheme}://{up.netloc}{path}" if absolute else path + conn.request(self.command, target, body=raw if raw or self.command == "POST" else None, headers=hdrs) + resp = conn.getresponse() + except Exception as ex: + rec.update(status=None, error=f"{type(ex).__name__}: {ex}"[:300], dur_s=round(time.time() - t0, 2)) + log(rec) + if conn is not None: + conn.close() + body = json.dumps({"error": {"type": "lff_gateway_upstream", "message": "upstream unreachable"}}).encode() + self.send_response(502) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + ctype = resp.getheader("Content-Type", "") + tap = UsageTap(kind, ctype) + self.send_response(resp.status) + for k, v in resp.getheaders(): + if k.lower() not in HOP: + self.send_header(k, v) + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + n_out, logged = 0, False + try: + while True: + chunk = resp.read1(65536) if hasattr(resp, "read1") else resp.read(65536) + if not chunk: + break + tap.feed(chunk) + n_out += len(chunk) + self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk)) + self.wfile.flush() + # record before the last chunk: a client holding the whole response finds its tokens counted + rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), dur_s=round(time.time() - t0, 2)) + log(rec) + logged = True + self.wfile.write(b"0\r\n\r\n") + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError): + rec["client_disconnected"] = True + finally: + conn.close() + if not logged: + rec.update(status=resp.status, resp_bytes=n_out, usage=tap.close(), + dur_s=round(time.time() - t0, 2)) + log(rec) + + do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = do_HEAD = _handle + + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + srv.daemon_threads = True + url = f"http://127.0.0.1:{srv.server_address[1]}{base_path}" + gfile = gateway_file or os.path.join(log_dir, GATEWAY_FILE) + tmp = gfile + ".tmp" + with open(tmp, "w") as f: + json.dump(dict(url=url, port=srv.server_address[1], pid=os.getpid(), kind=kind, upstream_host=up.hostname), f) + os.replace(tmp, gfile) + if watch_parent: + ppid = os.getppid() + + def watch(): + while os.getppid() == ppid: + time.sleep(2) + srv.shutdown() + threading.Thread(target=watch, daemon=True).start() + try: + srv.serve_forever(poll_interval=0.5) + finally: + srv.server_close() + + +def start_model_gateway(upstream, kind, log_dir, budget_in=None, budget_out=None, python=None, timeout_s=30, + allow_files=False): + """Start a gateway for one run (child of the caller) and wait until it listens. -> (Popen, info dict with url). + The caller stops it with stop_model_gateway().""" + gfile = os.path.join(log_dir, GATEWAY_FILE) + if os.path.exists(gfile): + os.remove(gfile) + argv = [python or sys.executable, os.path.abspath(__file__), "--upstream", upstream, "--kind", kind, + "--log-dir", log_dir] + if budget_in is not None: + argv += ["--budget-in", str(int(budget_in))] + if budget_out is not None: + argv += ["--budget-out", str(int(budget_out))] + if allow_files: + argv.append("--allow-files") + err = open(os.path.join(log_dir, "model_gateway_stderr.txt"), "ab") + p = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=err, stderr=err) + deadline = time.time() + timeout_s + while time.time() < deadline: + if p.poll() is not None: + raise RuntimeError(f"model gateway exited with code {p.returncode}; see {log_dir}/model_gateway_stderr.txt") + if os.path.exists(gfile): + return p, json.load(open(gfile)) + time.sleep(0.05) + stop_model_gateway(p) + raise RuntimeError(f"model gateway did not start within {timeout_s} s") + + +def stop_model_gateway(p): + if p is None or p.poll() is not None: + return + p.terminate() + try: + p.wait(timeout=10) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + + +def read_totals(log_dir): + try: + return json.load(open(os.path.join(log_dir, TOTALS))) + except (OSError, ValueError): + return None + + +def flagged(totals): + """Refusals worth a look (EFE: refused_paths / refused_server_tools / refused_bodies), probes excluded.""" + if not totals: + return [] + return [k for k in ("refused_paths", "refused_server_tools", "refused_fields", "refused_remote_fetch", + "refused_bodies", "refused_budget") if totals.get(k)] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--upstream", required=True, help="the model API base URL the harness would otherwise call") + ap.add_argument("--kind", required=True, choices=sorted(ALLOWED_PATHS)) + ap.add_argument("--log-dir", required=True) + ap.add_argument("--port", type=int, default=0) + ap.add_argument("--budget-in", type=int, default=None, help="stop forwarding once this many input tokens were used") + ap.add_argument("--budget-out", type=int, default=None, help="... output tokens (reasoning included)") + ap.add_argument("--no-watch-parent", action="store_true") + ap.add_argument("--allow-files", action="store_true", help="also forward the provider's Files API (FILE_PATHS)") + a = ap.parse_args() + serve(a.upstream, a.kind, a.log_dir, port=a.port, budget_in=a.budget_in, budget_out=a.budget_out, + watch_parent=not a.no_watch_parent, allow_files=a.allow_files) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/README.md b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/README.md new file mode 100644 index 0000000000000000000000000000000000000000..718daf643df342adc71df05584ec3c42e8fdfb36 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/README.md @@ -0,0 +1,297 @@ +# LFF-Bench agent harness(`lffbench/agent/`) + +把 VLM 智能体(默认 GPT-6 Astra,经 OpenAI Responses API)接到 LFF-Bench 任务上:工具接口、观测与历史打包、 +记忆模式、反馈粒度、协议控制(cross / within)、日志与指标。对应设计文档 `docs/02-benchmark设计.md` §4、§5。 + +> 本文档里"实测"指在本机跑出来的结果;"假设 / 估计"是没验证过的,单独标出。 + +## 1. 文件 + +| 文件 | 内容 | +|---|---| +| `tools.py` | 工具 JSON schema(`tool_specs`)和执行器 `ToolExecutor`(底层全部调 `Skills`) | +| `camera.py` | 相机内外参、深度反投影 `pixel_to_world`、`world_to_pixel`、图像方向说明(robosuite `camera_utils`) | +| `context.py` | 后端无关的对话结构、尝试记录 `AttemptRecord`、记忆选择 `select_history`、全部提示词文本 `PromptBuilder`、关键帧选择、旧图裁剪 | +| `harness.py` | 协议控制器 `AgentHarness` + `HarnessConfig` | +| `backends/openai_responses.py` | `OpenAIResponsesBackend`(GPT-6 Astra) | +| `backends/scripted.py` | `ScriptedBackend`:不调模型,把任务自带的 scripted 策略经工具接口跑一遍 | +| `backends/chat_completions.py` | `ChatCompletionsBackend`:OpenAI 兼容 Chat Completions(本地 Qwen3-VL 服务、vLLM 等) | +| `backends/anthropic_messages.py` | `AnthropicMessagesBackend`:Anthropic Messages API(自适应思考 + effort、思考块原样回放、自动缓存,2026-10-11) | +| `backends/gemini.py` | `GeminiBackend`:Gemini API(google-genai;thought_signature 原样回放,2026-10-11) | +| `../../scripts/api_player.py` / `api_batch.py` / `mcp_robot_server.py` | LA 接口的统一驱动、批处理调度、给原生 harness 的 MCP server(见 docs/12-统一harness.md) | +| `runlog.py` / `replay.py` | 运行目录写入;从运行目录重建尝试记录(给 mismatched 当 donor) | +| `metrics.py` / `cost.py` | succ@k、ΔICL、重复动作率;token 计价 | +| `../../scripts/run_agent.py` | 命令行入口 | +| `../../scripts/agent_compare.py` | 两个运行目录配对算 ΔICL(bootstrap 区间) | +| `../../scripts/agent_cost.py` | 从运行目录(真实或 dry run)估算 GPT-6 成本 / 延迟 | +| `../../tests/test_agent_*.py` | 单元测试 + 仿真端到端测试 | + +## 2. 快速开始 + +```bash +cd && source run_env.sh && export OMP_NUM_THREADS=1 +# 管线自检(不调模型;同时记录"如果换成 GPT-6,每次请求多大") +python scripts/run_agent.py --task l5_slide_to_target --backend scripted --memory full --feedback F2 --n 3 --k 5 --dry-run-payload +# GPT-6(需要 key;见 §6) +export OPENAI_API_KEY=... # 必需 +export OPENAI_BASE_URL=... # 可选:走网关 / 代理时 +python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory full --feedback F2 --n 20 --k 5 --seed0 5000 +python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory none --feedback F2 --n 20 --k 5 --seed0 5000 +python scripts/agent_compare.py --with runs/agent/l5_slide_to_target/ --iid runs/agent/l5_slide_to_target/ +# 测试 +python -m pytest -q tests/test_agent_payload.py tests/test_agent_protocol.py # 无仿真,约 1–2 分钟(CPFS 上 import 慢) +python -m pytest -q tests/test_agent_sim.py # 仿真,含 n=3 端到端 +``` + +常用开关:`--instruction direct|indirect`、`--privileged-locate`(消融:给 `locate`)、`--image-res 512`、 +`--keyframes 4`、`--keyframe-res`、`--max-steps 30`(每次尝试的工具调用上限)、`--no-auto-obs`(只在 `get_observation` 时给图)、 +`--grasp-report bool|name|none`、`--early-stop auto|yes|no`、`--donor-run DIR`(mismatched 的 donor)、`--seeds 5000,5001`。 +种子约定(我定的):1000–1999 开发(validate.py 也用 1000+),5000+ 留作正式测试。 + +## 3. 工具接口 + +坐标一律**世界系、米**(按本次任务要求;设计文档 §4 草稿写的是"机器人基座系",两者只差一个平移,这里统一用世界系,与 Skills 和各任务代码一致):桌面 z = 0.90,机器人基座在 x = −0.66, y = 0,+x 远离机器人,+y 机器人左侧,+z 向上。 +位置指夹爪抓取点(两指尖中点,`gripper0_grip_site`)。夹爪始终竖直向下;`yaw` 单位是**度**(LLM 处理度比弧度少出错), +yaw 0 时两指沿世界 y 轴开合(实测:手指 body 在 y = ±0.02),yaw 90 沿 x 轴。yaw 按 180° 取模:`Skills.move_to`(共享代码, +2026-10-06 协调者改)会取与当前 yaw 最近、且 |yaw| ≤ 90°+0.4 rad(约 113°)的等价角,避免手腕绕 180° 把手臂卷进关节限位; +`move_to` 报告里的 `yaw_used_deg` 是实际用的角度。 +肘关节(`robot0_joint4`)上限从 Panda 原厂的 −0.07 rad 收紧到 −0.55(`envs.ELBOW_Q4_MAX`,2026-10-19):原来快速移动越过手臂伸到最远的姿态(约 −0.47)后,肘关节会弯到反方向,被上限挡住,之后的移动都停在离目标 4–17 cm 处。收紧后可达范围不变。 +方向词:harness 生成的文字里一律以机器人为参照,并在 system prompt 里定义——forward = +x、backward = −x、left = +y(机器人左手)、 +right = −y、up = +z,"不是图像里的左右";同时说明 agentview 图里机器人的左边出现在图像右侧。任务自己的 F2 文本由任务作者统一。 + +| 工具 | 参数 | 底层 | 说明 | +|---|---|---|---| +| `move_to` | x, y, z, yaw, speed∣null | `Skills.move_to` | speed 为 null 时按控制器最快(约 0.6 m/s);yaw 按 180° 取模;超出工作空间的目标被裁剪并在报告里注明 | +| `open_gripper` / `close_gripper` | – | `Skills.set_gripper` | | +| `push` | x, y, dir_x, dir_y, distance, speed, z∣null, runup∣null | `Skills.push` | 语义与 `Skills.push` 完全一致:闭爪,到 (x,y) 后方 runup(默认 0.06)处、高度 z(默认 0.92),沿方向扫到 (x,y) 前方 distance 处,再抬 12 cm;朝向由 `Skills.push` 自动定 | +| `get_observation` | – | 渲染 | 返回 agentview + 腕部图像和本体状态 | +| `pixel_to_world` | camera(agentview∣wrist), u, v | 深度反投影 | u=列(从左数)、v=行(从上数),坐标就是模型看到的那张图(默认 512×512);返回世界点、离桌面高度、深度 | +| `done` | reason | – | 结束本次尝试(within 协议:结束一个分段,任务被检查) | +| `locate`(仅 `--privileged-locate`) | object_name(枚举) | 特权 | 物体原点的真实世界坐标 + 碰撞体 AABB;只用于"去掉感知难度"的消融 | + +所有工具 schema 都是 OpenAI strict 模式(所有字段 required、可选字段可为 null、禁止额外字段)。 + +**动作工具的执行报告**(JSON 文本,作为 function_call_output 返回): +```json +{"ok": true, "tool": "move_to", "reached": true, "yaw_used_deg": 0.0, "eef_pos": [-0.418, 0.019, 0.920], "eef_yaw_deg": 0.5, + "gripper": "closed", "gripper_width_m": 0.001, "holding_object": false, "touched_object": false, "sim_time_s": 13.7} +``` +- `reached`:控制器是否到达(2 cm 内,`Skills` 的判据);`push` 给 `sweep_reached`。 +- `holding_object` / `touched_object`:默认只给布尔(`--grasp-report bool`)——真实机器人能感知"夹住了东西 / 碰到了东西", + 但不知道是哪个物体;物体名会泄露识别类任务的答案。`--grasp-report name` 时给物体名(调试 / 消融)。 + 接触在**每个 MuJoCo 子步**检查(包装 `env.sim.step`,一个控制步 = 25 子步):实测快推时手指与方块的接触不到一个控制步,只在控制步边界查会漏掉(l5 上推了 4.4 cm 却一次接触都没记到)。不碰 `Skills.recorder`,任务自己的注入钩子不受影响。 +- 任务若定义 `drain_events()`(L6 有),其返回的事件文本会作为 `events` 加进当次报告(L6 作者的约定)。 +- 参数错误、未知工具、JSON 解析失败都返回 `{"ok": false, "error": ...}`,占一步预算,不中断尝试。 + +**隐藏 bias(L1)怎么处理**:所有命令位置都经 `Skills`,bias 照常加上。本体状态按"机器人自己以为的位置"报告: +`eef_pos = 真实末端 − bias`。也就是说机器人认为自己准确到了指令点,只有相机能看出偏差——这就是标定误差的本义; +如果报告真实末端,agent 对比指令和报告就能直接读出 bias,L1 就失效了。`pixel_to_world` 和 `locate` 给真实世界坐标。 +(测试 `test_tool_reports_and_hidden_bias` 实测:bias (3, −2, 0) cm 时报告与指令差 < 1 cm,真实末端 = 指令 + bias。) +L1 任务作者在 `l1_bias.py` 的 `TrackedSkills.reported_eef_pos()` 里独立采用了同一约定,两边一致。 + +**`pixel_to_world` 精度(实测,l5 场景方块顶面中心,投影→反投影)**:agentview 512px 误差约 1.5 mm,256px 约 3.4 mm; +wrist 均 < 0.1 mm。图像方向(由外参算出并写进 system prompt):agentview 图右 = +y、图下 = +x(机器人在图上方); +wrist 在 yaw 0 时图右 = −y、图下 = −x。 + +## 4. 观测、消息格式与历史打包 + +请求由三部分组成,按缓存友好的顺序排列: +1. **instructions(system)**:机器人 / 坐标 / 相机 / 工具约定、协议(k 次尝试、重置到同一状态)、反馈粒度说明、 + "新尝试开始前先用 1–3 句话评估前几次尝试"(这句话就是"自报失败原因"的来源,记录为 `diagnosis`)。 +2. **历史项(user,非 live,不裁剪)**:`TASK: <指令>` + 前几次尝试的打包(按记忆模式选择)。 +3. **当前尝试(live)**:尝试编号 + 当前 agentview / wrist 图 + 本体状态;之后每一步:模型的 function_call → + function_call_output(执行报告)→ 新观测(两张图 + 本体状态)。 + +每次尝试的打包(≤4 张关键帧 + 动作摘要 + 反馈)。下面是 scripted dry run 第 2 次尝试第 1 次调用的 `input`,原样摘自 +`runs/agent/l5_slide_to_target/20261006-060757_scripted-adaptive_full_F2_e2e/requests/request_007.json`(图像以占位符代替, +`[BREAKPOINT]` 表示该内容块带 `prompt_cache_breakpoint`): +``` +== user(历史项,live=False) +TASK: Push the red cube once, straight away from the robot, so that it slides and comes to rest inside the green target zone. + +=== Your earlier attempts === + +--- Attempt 1 --- +Actions executed: +1. close_gripper() -> eef (-0.208, 0.000, 1.173); width 0.002 m +2. move_to(x=-0.419, y=0.021, z=1.02, yaw=0, speed=null) -> NOT reached; eef (-0.394, 0.023, 1.032) +3. move_to(x=-0.419, y=0.021, z=0.92, yaw=0, speed=null) -> reached; eef (-0.418, 0.019, 0.920) +4. move_to(x=-0.204, y=0.021, z=0.92, yaw=0, speed=0.3) -> reached; eef (-0.202, 0.021, 0.921); touched an object +5. move_to(x=-0.204, y=0.021, z=1, yaw=0, speed=0.3) -> reached; eef (-0.205, 0.020, 0.997) +6. done(reason="scripted adaptive policy finished with params {'speed': 0.3}") +Outcome feedback: Attempt failed. The cube stopped 5.2 cm past the centre of the target zone. +Key images (start of attempt, after step 1 (close_gripper), after step 4 (move_to), end of attempt, after objects settled): +[start of attempt] +[after step 1 (close_gripper)] +[after step 4 (move_to)] +[end of attempt, after objects settled] +=== End of earlier attempts === [BREAKPOINT] +== user(当前尝试,live=True) +This is attempt 2 of at most 5. The scene has been reset. + +Current observation: +agentview camera: +wrist camera: +Proprioception: {"eef_pos": [-0.2085, -0.0, 1.1733], "eef_yaw_deg": 0.0, "gripper": "open", "gripper_width_m": 0.0411, "holding_object": false} [BREAKPOINT] +``` +之后每一步依次追加:模型输出项(reasoning(加密)/ message / function_call)→ `function_call_output`(执行报告 JSON)→ +user 项 `Observation after step N ():` + 两张图 + 本体状态。完整请求(含 instructions 和 tools)见同目录 `requests/*.json`。 +- 关键帧(agentview):尝试开始、最多 2 张中间帧(优先 push / 开合爪 / 碰到物体的步)、结束帧(`task.outcome()` 让物体静止之后渲染)。 +- 反馈:`task.feedback(inst, outcome, level)`。F0 不给反馈行;F1 只有成功 / 失败;F2 加结构化测量(任务的 `detail`)。 +- 历史头不带计数,所以第 j+1 次尝试的历史项以第 j 次的为前缀(只多一块),前缀可被缓存命中(单测 `test_history_prefix_is_append_only`)。 +- live 图像超过 `max_live_images`(默认 16)时,把最旧的裁到预算的一半(滞回,减少前缀变化);历史关键帧从不裁剪。 +- 一张图就是一个 JPEG(quality 90);发给模型的字节和 `images/` 下存的文件完全相同。 + +**记忆模式**(`--memory`): + +| 模式 | 下一次尝试看到什么 | 用途 | +|---|---|---| +| `none` | 什么都没有;提示词里也不提"多次尝试",每次请求与第 1 次完全相同 | 独立重来,测 pass@k^iid | +| `full` | 之前全部尝试 | 主条件 | +| `last` | 只有最近一次 | 记忆长度消融 | +| `mismatched` | 另一个实例(不同布局和隐变量)的前 j−1 次尝试,措辞与 full 完全相同 | 错配对照:用的是具体信息还是"泛泛练习" | + +mismatched 的 donor:`--donor-run DIR` 复用一个已跑完的 full 运行(按种子循环错位配对,保证 donor ≠ 自己;不用再付一次钱); +不给时自动用同一后端、memory=full 在 `seed + 10000` 上先跑一遍 donor(存到运行目录下 `donors/`)。 + +**早停与 F0**:默认(`--early-stop auto`)F1/F2 在首次成功时结束 run;F0 不早停、跑满 k 次——否则"还有下一次尝试"本身就泄露了"上次失败"。 + +**协议**:`cross` 每次尝试前 `reset_instance`(同布局、同隐变量)。`within` 只在开始重置一次;`done` 结束一个分段: +(若任务定义 `go_home()` 先调用它,L6 有)→ 保持 20 个控制步 → `outcome()`;未成功且未到终止条件(`outcome["terminal"]` 或 +`outcome["overshoot"]`,或任务的 `is_terminal(out)`)就带着反馈从当前状态继续。within 下各记忆模式的语义同上(none = 每段都清空上下文)。 + +## 5. 后端 + +- **`OpenAIResponsesBackend`**(`--backend openai`):`client.responses.create(model="gpt-6-astra", instructions, input, tools, + tool_choice="auto", parallel_tool_calls=False, store=False, include=["reasoning.encrypted_content"], reasoning={"effort": ...})`。 + - 无状态:每次请求重发完整(裁剪后的)上下文;上一轮返回的 reasoning 项(加密内容)原样回放,模型在一次尝试内保留思路。 + - effort 校验:gpt-6-astra 只接受 low / medium / high / xhigh / max(不支持 none)。 + - 缓存:自动把 `prompt_cache_key` 设为 `lffbench::`;默认在"历史项末尾"和"最新输入末尾"打显式 + `prompt_cache_breakpoint`(openai SDK 3.24 的字段,gpt-5.6 以后支持)。网关不认这个字段时用 `--cache-breakpoints none`。 + `--prompt-cache-options '{"ttl":"30m"}'`、`--prompt-cache-retention 24h`、`--service-tier`、`--extra-body` 透传。 + - 用量:记录 input / cached / cache_write / output / reasoning tokens 和每次调用的墙钟延迟。 +- **`ScriptedBackend`**(`--backend scripted --scripted-policy adaptive|naive|oracle|blind`):任务自己的 `execute(inst, params)` + 在工作线程里跑,`task.sk` 换成代理,每个 `Skills` 原语变成一次 schema 合法的工具调用交给 harness 在主线程执行 + (队列交接,同一时刻只有一个线程碰 MuJoCo)。参数来自任务的 `default/adapt/blind/oracle_params`,只看记忆模式允许的历史、 + 只看反馈粒度允许的字段(F2 结构化测量 / F1 成功标志 / F0 无;看不够就退回 blind 规则)。它读实例布局(特权),只用来测管线。 + 支持实现了 `execute` 的 cross 任务;within 任务和只重写了 `run_scripted` 的任务不支持(会报错说明)。 +- **`ChatCompletionsBackend`**(`--backend chat --chat-base-url http://127.0.0.1:8765/v1 --chat-model ...`):OpenAI 兼容 + Chat Completions + function calling,用于本地开源 VLM(见 §8)或任何 vLLM / SGLang 端点。live 图像上限降到 4。 + +## 6. 怎么接 GPT-6(需要用户提供) + +1. `OPENAI_API_KEY`(必需),可选 `OPENAI_BASE_URL`(网关 / 代理)。本机没有 key,代码从未发过真实请求。 +2. 账号对 `gpt-6-astra` 的访问权限和 Tier(Tier 1 限额 500 RPM / 500K TPM;单个 run 串行,每次调用 ≤ 几十 K token,Tier 1 够用)。 +3. Python 包:`setup/install.sh` 建的 venv 里直接装了 `openai==3.24.0`。(原开发机的 libero-cpu venv 没有 `openai`, + 它装在一个 `pip install --target` 目录里,由环境变量 `LFF_OPENAI_SDK_DIR` 指定;后端在 `import openai` 失败时把该目录 + **追加**到 `sys.path` 末尾,venv 里已有的包始终优先。) +4. 第一次真跑建议:`--n 2 --k 3 --effort low --dump-requests 5`,看 `requests/*.json`(图像已省略)和 `events.jsonl` 里的 + `llm_call.usage`,确认网关接受 `prompt_cache_breakpoint` / `include` 等字段后再放大。 +5. 并行:一个进程一个 MuJoCo 环境、串行跑实例;要并行就按 `--seeds` 切分开多个进程(每个进程 `OMP_NUM_THREADS=1`)。 +6. 代理(实测):本机环境变量里有 `HTTPS_PROXY=http://127.0.0.1:1080` 和 `ALL_PROXY=socks5h://127.0.0.1:1080`。openai SDK 3.x + 底层的 httpx2 只要看到 socks 代理变量就要 `socksio`,否则建客户端时直接 ImportError;我已把 `socksio==1.0.0` 装进同一目录, + 现在在这些变量存在时能正常建客户端(实测)。真实请求会走 `HTTPS_PROXY`;能否经这个代理到达 OpenAI / 你的网关没测(没有 key)。 + +## 7. 日志与指标 + +运行目录 `runs/agent//<时间>___[_tag]/`: +- `config.json`:命令行、harness 配置、后端配置、任务信息。 +- `events.jsonl`:`run_start`(实例参数,去掉 `_` 开头的私有键)、`llm_call`(延迟、usage、成本估计、模型文本、reasoning 摘要、 + 工具调用、请求大小;dry run 时加 `dry_run_request`)、`tool_call`(参数、报告、仿真墙钟、仿真步数)、`observation`(图像路径、本体)、 + `attempt_end`(outcome 全字段、给模型看的反馈、F2 反馈、结束原因、done 理由、自我诊断、显示了哪些历史、关键帧路径、动作摘要、 + 该尝试的 LLM 延迟和仿真时间)、`run_end`(run 级汇总)、`llm_error`。 +- `images/seed/a_s__.jpg`:模型看到的每一张图。 +- `summary.json`:每个 run 的 `first_success`、`success_by_attempt`、残差(outcome 里所有 `*_err`)、token、成本、延迟;以及汇总: + `succ_at`(j = 1..k,按 run 计)+ Wilson 95% 区间、`attempt1_success`、首次成功尝试数均值 / 中位数、 + `pass_at_k_iid_analytic = 1 − (1 − p1)^k`、`repeated_action_rate`(失败后下一次动作序列与上次相同(1 cm 取整)的比例, + "同错复犯"的通用近似)、每 run 调用数 / 延迟 / token / 成本、缓存命中率。 +- ΔICL:正式算法是同种子配对的 `succ@k(full) − succ@k(none)`(`scripts/agent_compare.py`,配对 bootstrap 区间、不一致对计数); + `delta_icl_vs_analytic_iid` 只是用本组 attempt-1 成功率算的便宜参照。 + +## 8. 成本 / 延迟估算方法 + +- 真实运行:成本 = Σ调用 [(input − cached − cache_write)·$10 + cache_write·$12.5 + cached·$1 + output·$50] / 1e6 + (gpt-6-astra 价格,>272K 输入时输入 ×2、输出 ×1.5;见 `cost.py`);延迟直接用记录的每次调用墙钟。`scripts/agent_cost.py <运行目录>`。 +- 跑之前:用 scripted 后端加 `--dry-run-payload` 跑同一配置,记录每次调用如果发给 GPT-6 的请求大小,再 + `scripts/agent_cost.py --out-tokens 1500 --latency 20 --calls-scale 2` 外推。假设(未验证):图像按 32px patch + 每 patch 1 token 计(512² ≈ 256 token);文本 4 字符 ≈ 1 token;同一尝试内上一调用的输入全部命中缓存、每次尝试第一调用全不命中(偏保守); + scripted 的调用次数是 LLM 的下限(LLM 还会看图、反投影、检查),用 `--calls-scale` 放大;每次调用输出 token 和延迟按参数给 + (RoboICL 实测 GPT-6 Astra 每次调用 30–50 s,那是 50–90K 输入、high/xhigh 时的数)。 +- 本机 dry run 实测数字见 §10。 + +## 9. 已知限制 + +- **l5_slide_to_target 的绿色目标区在图像里看不见(实测,任务侧问题,未改任务文件)**:`apply_instance` 把 zone 的碰撞关掉了, + 但它是 free joint,`settle` 期间直接穿过桌面掉下去(reset 后 z ≈ 0.81),agentview 和腕部图里都没有绿色区域。 + scripted 测试不受影响(它只看 F2 数字),但 VLM 智能体只能靠 F2 的文字找目标——F0/F1 条件下这个任务对 VLM 不可解。 + 需要任务作者把 zone 固定住(例如不加 free joint、或每步把它放回 / 设 gravcomp / 设为 mocap)。 +- l5 的 scripted 执行里第一个 `move_to`(到推杆起点上方 x≈−0.42, z≈1.02)每次都跑满 250 步(12.5 s 仿真)仍差约 2.5 cm 报 `NOT reached`, + 下一步下降时又到位了;这是 `Skills.move_to` 在靠近基座处的行为,不是 harness 的问题,但 VLM 会在报告里看到 `NOT reached`。 +- 渲染:每步两张 512² 图(OSMesa CPU)约 0.5 s;本机负载高时更慢。仿真时间对比 LLM 延迟可以忽略。 +- 一个 run 内串行调用模型;没有实现 async tool calling / mid-turn steering / WebSocket(Ultrafast 推荐)。 +- 没有实现"每次尝试后单独问一次模型失败原因"(会多一次调用);自报原因来自每次新尝试开头的那 1–3 句(`diagnosis`)。 +- `ScriptedBackend` 不支持 within 协议任务(L2 / L3-within / L5-B / L6 的 scripted 参照写在各自的 `run_scripted` 里, + 不是 `execute(params)`);within 协议逻辑用假任务做了单测。 +- 工具里没有 `wait`;scripted 代理遇到 `Skills.hold` 直接执行并计数(`backend_meta.untooled_hold_steps`)。 +- 图像 token 的计法、GPT-6 每次调用的延迟都是假设,第一次真跑后用 `usage` 和 `latency_s` 校准。 +- 本地开源 VLM 后端:见 §11。 + +**任务作者可选的钩子**(harness 会自动使用,没有就跳过):`agent_instruction(inst, variant)`、`agent_object_names`、 +`on_agent_tool(inst, name, args, report)`(每次工具调用后,可用于注入)、`drain_events()`(事件文本进报告)、 +`go_home()`(每次尝试结束、测 outcome 之前调用)、`is_terminal(out)` 或 `outcome["terminal"]`(within 不可恢复失败)、 +`feedback(..., indirect=bool)`(按指令写法改写反馈)。 + +## 10. 测试与实测结果(2026-10-06,本机实测,8 核负载 30–40) + +单元测试(`source run_env.sh` 后 `python -m pytest -q tests/test_agent_*.py`): +- `test_agent_payload.py` 6 项通过:请求结构、strict 工具、图像 data URL 能解码成 512² JPEG、缓存断点位置、effort 校验、 + 无 key 报错;**真实 openai SDK 3.24 + 进程内 mock HTTP 传输**的两轮往返(URL `…/v1/responses`、`Bearer` 头、body、usage + 解析含 cache_write、reasoning 加密项回放、function_call / function_call_output 的 call_id 配对);chat 后端消息格式。 +- `test_agent_protocol.py` 9 项通过(假任务、无仿真):full / none / last / mismatched、F0 / F1 / F2、F0 不早停、within 不重置、 + 历史前缀只追加、关键帧选择、配对 ΔICL。 +- `test_agent_sim.py` 5 项通过(单独 143 s;协调者改了 `Skills.move_to` 的 yaw 取模之后,三个文件 20 项一起重跑,305 s,全部通过):像素↔世界往返、bias 隐藏、工具报错 / 裁剪 / locate 门控 / 接触检测、 + **ScriptedBackend 在 l5_slide_to_target 上 n=3、k=5 端到端**、mismatched 自动 donor。 + +端到端运行(留在 `runs/agent/l5_slide_to_target/` 下,可以直接看图和 events): + +| 运行 | succ@1..5 | 首次成功(seed 1000/1001/1002) | 每 run 调用数 | 每 run 仿真 + 渲染墙钟 | +|---|---|---|---|---| +| `20261006-060757_scripted-adaptive_full_F2_e2e` | 0.33 / 0.67 / 1 / 1 / 1 | 3 / 2 / 1 | 12 | 15.5 s | +| `20261006-060913_scripted-adaptive_none_F2_e2e` | 0.33 / 0.33 / 0.33 / 0.33 / 0.33 | – / – / 1 | 22 | 16.2 s | + +- 经工具接口跑的 scripted adaptive 与任务自己的参照 rollout(`results/l5_slide_to_target/validate.json`)**逐次一致**: + 8 次尝试的推速完全相同,停止误差 along_err 相同到 0.1 mm(如 seed 1000:+5.22 / −1.14 / −0.49 cm)。说明工具接口足以表达 + 这个任务的参照策略,bias / 物理没有被 harness 改变。 +- memory=none 时 scripted 策略每次都用默认推速,结果完全重复(`repeated_action_rate` = 1.0),正好是"独立重来"的退化情形; + `agent_compare.py` 给出 ΔICL = 1.0 − 0.33 = 0.67(n=3,bootstrap 区间 [0, 1],只是管线演示)。 +- dry run 请求大小(`agent_cost.py`):每次调用约 4.7K 输入 token(估计:文本 /4 + 每张 512² 图 256 token),同一尝试内 + 约 78% 可命中缓存;第 2 次尝试首个请求 6 张图(4 关键帧 + 2 实时),到尝试末尾约 16 张。 + 估计成本(gpt-6-astra 价格,**输出 token 和延迟是假设**):每次调用输出 1500 token、20 s 时,每 run 约 $1.1、API 时间约 4 分钟; + 按 LLM 调用数是 scripted 的 2 倍算,约 $2.1 / run、8 分钟;输出 4000 token、40 s 时约 $5.1 / run、16 分钟。 + 成本主要在输出(reasoning)token,不在图像。一组条件 20 个实例 ≈ $40–100;ΔICL 至少要 full + none 两组。 + +另外用 scripted 后端在 **l1_bias_place**(别人刚写的 L1 任务,cross 协议)上跑了 n=2、k=5 的兼容性检查(运行目录在 scratch,未保留): +两个种子都在第 2 次尝试成功(第 1 次 F2 反馈"夹爪在奶酪中心右侧 3.9 cm、后方 1.4 cm",adaptive 据此补偿 offset), +0 个错误——harness 不需要为 L1 做任何改动;L1 作者的 `TrackedSkills` 记录、bias 都经工具调用照常生效。 + +## 11. 本地开源 VLM 后端(Qwen3-VL-8B-Instruct,PPU) + +能跑(实测)。由子代理在约 1 小时内做通:`scripts/qwen_vl_server.py` + `scripts/qwen_vl_server.sh`(OpenAI 兼容 +`/v1/chat/completions`,支持工具调用 / 多图 / 多轮),用系统 python3.12(torch 2.6 PPU 版)+ 单独目录 +`/mnt/cpfs/workspace/env/qwen3vl-ppu-overlay`(只放 transformers 4.57.6 / tokenizers 0.22.1 / huggingface_hub 0.36.0, +只对服务进程加 PYTHONPATH,不改任何已有环境)。PPU 上 SDPA 自带 GQA 在解码步会报错,服务里改成先展开 K/V 头再算(`--sdpa-native-gqa` 可恢复)。 + +```bash +nohup bash scripts/qwen_vl_server.sh --port 8765 --warmup > logs/qwen_vl_server.log 2>&1 & # 等日志出现 "serving ..." +python scripts/run_agent.py --task l5_slide_to_target --backend chat --chat-base-url http://127.0.0.1:8765/v1 \ + --chat-model Qwen3-VL-8B-Instruct --memory full --feedback F2 --n 2 --k 3 --max-steps 15 --keyframes 3 +kill <服务 PID> # 用完停掉,显存约 18 GB +``` +- 加载:页缓存热时权重 18 s(本次实测);冷读 CPFS 约 6.5 分钟(子代理实测 385 s)。 +- 端到端实测(`runs/agent/l5_slide_to_target/20261006-061100_chat_full_F2_qwen_smoke`,n=2、k=3、每次尝试 15 步上限): + 81 次模型调用、0 次后端错误、0 次格式错误的工具调用;每次调用延迟均值 5.1 s(p50 4.9 s,p95 9.5 s), + 输入均值 6.3K token(最大 10.3K),输出均值 113 token;用到了 move_to / push / close_gripper / get_observation / pixel_to_world / done, + 新尝试开头都写了对上一次的评估(`diagnosis`)。成功 0/2:模型反复 `move_to(0, 0, 0.9)`、没有先定位方块, + 加上 l5 的目标区本来就看不见(§9)。这只说明**管线对真实 VLM 是通的**,不说明 8B 模型的能力;之后我在 system prompt 里加了 + "物体位置不会直接给出,用 pixel_to_world 从图像定位"一句(这次运行之后加的,未再测)。 +- 用途:在花 GPT-6 的钱之前,先用本地模型检查提示词、工具描述、日志和指标。 diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/harness.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/harness.py new file mode 100644 index 0000000000000000000000000000000000000000..323410f477f3320769635cf01dd368be716d9421 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/agent/harness.py @@ -0,0 +1,300 @@ +"""Protocol controller: runs a backend on task instances, attempt by attempt. + + cross protocol : reset to the same instance (same layout + hidden variables) before every attempt + within protocol: one continuous episode; each `done` call closes a segment ("attempt") that is checked; + the agent continues from the current state if it failed and budget remains +Both protocols pack finished attempts the same way (keyframes <= 4, action summary, feedback F0/F1/F2) and +show them according to the memory mode (none / full / last / mismatched). +""" +import time +from dataclasses import asdict, dataclass, field + +from .context import (FEEDBACK_LEVELS, MEMORY_MODES, AttemptRecord, Conversation, PromptBuilder, StepRecord, + pick_keyframes, select_history, summarize_actions) +from .cost import call_cost, estimate_request_tokens +from .metrics import run_summary +from .backends.base import AttemptInfo, RunInfo + + +@dataclass +class HarnessConfig: + memory: str = "full" + feedback: str = "F2" + k: int = None # attempts (cross) / done calls (within); default task.max_attempts + image_res: int = 512 + keyframe_res: int = None # default = image_res + n_keyframes: int = 4 + cams: tuple = ("agentview", "wrist") + auto_obs: bool = True # send new images after every action tool + max_steps: int = 30 # tool calls per attempt + max_no_tool: int = 3 # consecutive replies without a tool call before the attempt is ended + privileged_locate: bool = False + grasp_report: str = "bool" # "bool" | "name" | "none" + instruction: str = "direct" # "direct" | "indirect" + early_stop: str = "auto" # "auto" (stop at first success unless F0), "yes", "no" + settle_within: int = 20 # control steps held still before checking a within-protocol segment + jpeg_quality: int = 90 + save_images: bool = True + model_for_cost: str = "gpt-6-astra" + extra: dict = field(default_factory=dict) + + def validate(self): + assert self.memory in MEMORY_MODES, self.memory + assert self.feedback in FEEDBACK_LEVELS, self.feedback + assert self.grasp_report in ("bool", "name", "none") + assert self.instruction in ("direct", "indirect") + assert self.early_stop in ("auto", "yes", "no") + assert 1 <= self.n_keyframes <= 4 or self.n_keyframes == 0 + + +def clean_inst(inst): + return {k: v for k, v in inst.items() if not str(k).startswith("_")} + + +class AgentHarness: + def __init__(self, task, backend, cfg: HarnessConfig, logger, payload_probe=None, executor_factory=None, + cam_axes=None): + cfg.validate() + self.task, self.backend, self.cfg, self.log = task, backend, cfg, logger + self.protocol = getattr(task, "protocol", "cross") + self.k = cfg.k or task.max_attempts + self.payload_probe = payload_probe # optional OpenAIResponsesBackend used only to size requests (dry run) + self.executor_factory = executor_factory # tests: build a fake executor instead of ToolExecutor + self._cam_axes = cam_axes + + # ------------------------------------------------------------------ helpers + def instruction(self, inst): + hook = getattr(self.task, "agent_instruction", None) + if hook is not None: + return hook(inst, self.cfg.instruction) + if self.cfg.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""): + return self.task.instruction_indirect + return self.task.instruction + + def feedback(self, inst, out, level): + import inspect + fn = self.task.feedback + if "indirect" in inspect.signature(fn).parameters: # tasks that phrase feedback per instruction variant + return fn(inst, out, level, indirect=self.cfg.instruction == "indirect") + return fn(inst, out, level) + + def early_stop(self): + if self.cfg.early_stop == "auto": + return self.cfg.feedback != "F0" + return self.cfg.early_stop == "yes" + + def terminal(self, out): + hook = getattr(self.task, "is_terminal", None) + if hook is not None: + return bool(hook(out)) + return bool(out.get("terminal") or out.get("overshoot")) + + def _executor(self, inst): + if self.executor_factory is not None: + return self.executor_factory(self, inst) + from .tools import ToolExecutor + return ToolExecutor(self.task, inst, image_res=self.cfg.image_res, cams=self.cfg.cams, + privileged_locate=self.cfg.privileged_locate, grasp_report=self.cfg.grasp_report, + jpeg_quality=self.cfg.jpeg_quality, image_sink=self._sink) + + def _sink(self, ref): + self._img_counter += 1 + rel = f"seed{self._seed}/a{self._attempt}_s{self._step:02d}_{self._img_counter:03d}_{ref.camera}.jpg" + return self.log.save_image(ref, rel) + + def _keyframe(self, ref): + """Separate (possibly smaller) copy of an agentview frame for the history.""" + from .images import ImageRef + kres = self.cfg.keyframe_res or self.cfg.image_res + kf = ImageRef(camera=ref.camera, array=ref.array, label=ref.label) + if kres == self.cfg.image_res: + kf.jpeg, kf.path = ref.jpeg, ref.path + return kf + self._img_counter += 1 + rel = f"seed{self._seed}/a{self._attempt}_key_{self._img_counter:03d}_{ref.camera}.jpg" + return self.log.save_image(kf, rel, res=kres) + + def prompts(self, executor): + if self._cam_axes is None: + from . import camera as C + self._cam_axes = {c: C.describe_axes(self.task.env, c, self.cfg.image_res) for c in C.CAMERAS} + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + return PromptBuilder(self.task, self.protocol, self.k, self.cfg.memory, self.cfg.feedback, self.cfg.image_res, + self._cam_axes, privileged_locate=self.cfg.privileged_locate, object_names=names, + grasp_report=self.cfg.grasp_report, cams=self.cfg.cams) + + # ------------------------------------------------------------------ run + def run_instance(self, seed, donor=None): + """donor: AttemptRecords of another instance (memory=mismatched). Returns (summary, records).""" + task, cfg = self.task, self.cfg + inst = task.sample_instance(seed) + self._seed, self._attempt, self._step, self._img_counter = seed, 0, 0, 0 + self._llm_calls = [] + t_run = time.time() + sim_wall = 0.0 + info = RunInfo(task=task, inst=inst, seed=seed, k=self.k, protocol=self.protocol, feedback=cfg.feedback, + memory=cfg.memory) + self.backend.begin_run(info) + self.log.event("run_start", seed=seed, inst=clean_inst(inst), task=task.name, protocol=self.protocol, k=self.k, + memory=cfg.memory, feedback=cfg.feedback, donor_seed=donor[0].seed if donor else None) + records, executor, status = [], None, "ok" + for a in range(1, self.k + 1): + self._attempt, self._step = a, 0 + if self.protocol == "cross" or executor is None: + t0 = time.time() + task.reset_instance(inst) + executor = self._executor(inst) + sim_wall += time.time() - t0 + visible = select_history(cfg.memory, records, donor) + rec, attempt_sim = self._attempt_loop(inst, seed, a, visible, executor, + continuing=self.protocol == "within" and a > 1) + sim_wall += attempt_sim + records.append(rec) + if rec.ended_by == "backend_error": + status = "error" + break + if rec.success and self.early_stop(): + break + if self.protocol == "within" and (rec.success or self.terminal(rec.outcome)): + break + self.backend.end_run() + summ = run_summary(seed, records, self.k, status=status, llm_calls=self._llm_calls, + extra=dict(sim_wall_s=round(sim_wall, 2), wall_s=round(time.time() - t_run, 2), + donor_seed=donor[0].seed if donor else None)) + self.log.event("run_end", **summ) + summ["_llm_calls"] = self._llm_calls + return summ, records + + def _attempt_loop(self, inst, seed, a, visible, ex, continuing): + cfg, task, backend = self.cfg, self.task, self.backend + P = self.prompts(ex) + tools = self.tool_specs() + conv = Conversation(P.system_prompt()) + backend.begin_attempt(AttemptInfo(attempt=a, history=visible, continuing=continuing)) + sim_t = 0.0 + t0 = time.time() + obs0 = ex.observe(label="start") + sim_t += time.time() - t0 + conv.add_user(P.history_parts(self.instruction(inst), visible), live=False) + conv.add_user(P.current_parts(a, obs0, ex.proprio(), continuing), live=True) + steps, diagnosis, done_reason, ended_by = [], None, None, None + n_calls, no_tool = 0, 0 + while ended_by is None: + if len(steps) >= cfg.max_steps: + ended_by = "step_budget" + break + try: + resp = backend.act(conv, tools) + except Exception as e: # API failure after retries, crashed scripted policy, ... + self.log.event("llm_error", seed=seed, attempt=a, call=n_calls + 1, error=repr(e)[:4000]) + ended_by = "backend_error" + break + n_calls += 1 + call_rec = self._log_llm_call(seed, a, n_calls, resp, conv, tools) + self._llm_calls.append(call_rec) + if n_calls == 1 and resp.text: + diagnosis = resp.text + conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name) + if not resp.tool_calls: + no_tool += 1 + if no_tool >= cfg.max_no_tool: + ended_by = "no_tool_call" + break + conv.add_user(P.nudge(), live=True) + continue + no_tool = 0 + acted = None + for tc in resp.tool_calls: + self._step = len(steps) + 1 + res = ex.call(tc.name, tc.raw_arguments or tc.arguments) + sim_t += res.wall_s + conv.add_tool_output(tc.id, tc.name, res.text()) + backend.on_tool_result(tc, res) + st = StepRecord(step=self._step, name=tc.name, args=res.args, report=res.report, ok=res.ok, + wall_s=round(res.wall_s, 3), sim_steps=res.sim_steps) + steps.append(st) + if res.images: + conv.add_user(P.observation_parts(f"Images returned by get_observation (step {self._step})", + res.images, ex.proprio()), live=True) + if tc.name in ("move_to", "open_gripper", "close_gripper", "push") and res.ok: + acted = st + self.log.event("tool_call", seed=seed, attempt=a, step=self._step, call_id=tc.id, name=tc.name, + args=res.args, ok=res.ok, report=res.report, wall_s=round(res.wall_s, 3), + sim_steps=res.sim_steps, images=[i.path for i in res.images]) + if res.ended: + done_reason = res.args.get("reason") + ended_by = "done" + break + if len(steps) >= cfg.max_steps: + break + if ended_by is None and acted is not None: + t1 = time.time() + if cfg.auto_obs: + obs = ex.observe(label=f"step{acted.step}") + conv.add_user(P.step_observation(acted.step, acted.name, obs, ex.proprio()), live=True) + acted.frame = next((o for o in obs if o.camera == "agentview"), obs[0]) + else: # still keep an agentview frame for the history keyframes / logs + from .images import ImageRef + acted.frame = self._sink(ImageRef(camera="agentview", array=ex.render("agentview"), + label=f"step{acted.step}")) + sim_t += time.time() - t1 + self.log.event("observation", seed=seed, attempt=a, step=acted.step, + images=[acted.frame.path] if not cfg.auto_obs else [o.path for o in obs], + proprio=ex.proprio()) + meta = backend.end_attempt() or {} + # ------------------------------------------------------------ outcome + packing + t1 = time.time() + home = getattr(task, "go_home", None) # task-defined end-of-attempt motion (e.g. L6: arm out of view) + if home is not None and ended_by != "backend_error": + home() + if self.protocol == "within" and cfg.settle_within: + ex.sk.hold(cfg.settle_within) + out = task.outcome(inst) + from .images import ImageRef + self._step = 99 + final = self._sink(ImageRef(camera="agentview", array=ex.render("agentview", cfg.keyframe_res or cfg.image_res), + label="end")) + sim_t += time.time() - t1 + fb = self.feedback(inst, out, cfg.feedback) + fb_full = self.feedback(inst, out, "F2") + init_frame = next((o for o in obs0 if o.camera == "agentview"), None) + for s in steps: + if s.frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res: + s.frame = self._keyframe(s.frame) + if init_frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res: + init_frame = self._keyframe(init_frame) + kfs = pick_keyframes(steps, init_frame, final, cfg.n_keyframes) if cfg.n_keyframes else [] + rec = AttemptRecord(seed=seed, attempt=a, steps=steps, keyframes=kfs, outcome=dict(out), + success=bool(out.get("success")), feedback=fb, done_reason=done_reason, diagnosis=diagnosis, + ended_by=ended_by, backend_meta=meta) + calls = [c for c in self._llm_calls if c["attempt"] == a] + self.log.event("attempt_end", seed=seed, attempt=a, success=rec.success, outcome=out, feedback_shown=fb, + feedback_f2=fb_full, ended_by=ended_by, done_reason=done_reason, diagnosis=diagnosis, + n_steps=len(steps), n_llm_calls=len(calls), backend_meta=meta, + history_shown=[(h.seed, h.attempt) for h in visible], + keyframes=[(c, r.path) for c, r in kfs], action_summary=summarize_actions(steps), + llm_latency_s=round(sum(c["latency_s"] for c in calls), 3), sim_wall_s=round(sim_t, 3)) + return rec, sim_t + + def tool_specs(self): + from .tools import tool_specs + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + return tool_specs(self.cfg.privileged_locate, names, self.cfg.image_res) + + def _log_llm_call(self, seed, a, n, resp, conv, tools): + rec = dict(seed=seed, attempt=a, call=n, latency_s=round(resp.latency_s, 3), usage=resp.usage, + cost_usd=call_cost(resp.usage, self.cfg.model_for_cost) if resp.usage else None, + status=resp.status, error=resp.error, text=resp.text, reasoning_summary=resp.reasoning_summary, + reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned", + tool_calls=[dict(id=t.id, name=t.name, arguments=t.arguments) for t in resp.tool_calls], + request=resp.request_stats, conv_images=conv.n_images()) + if self.payload_probe is not None: # dry run: size of the request GPT-6 would have received + stats = self.payload_probe.request_stats(self.payload_probe.build_request(conv, tools)) + stats["est_input_tokens"] = estimate_request_tokens(stats, self.cfg.image_res) + rec["dry_run_request"] = stats + self.log.event("llm_call", **rec) + return rec + + +def config_dict(cfg): + return asdict(cfg) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l4_fit_container.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l4_fit_container.py new file mode 100644 index 0000000000000000000000000000000000000000..86f8d7075627486afed86a3944b3bc8b95c0ba52 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/arm_specs/l4_fit_container.py @@ -0,0 +1,61 @@ +"""Controlled arms for l4_fit_container (2026-10-12). + +Hidden variable: inst["cap"] -- clear (unrendered) bumper caps on both ends of the phone, 0.8-0.9 cm each, so the +phone is 1.6-1.8 cm longer than it looks. The prior picks the box with the most visible room to spare ("snug"), +which is too short for the capped phone; only the "fit" box is long enough. + +h0 cap = 0: no caps. The phone is exactly as big as it looks, the "snug" box the prior picks fits it (as do "fit" + and "short_wide"). inst["fit"] is left as is (that box still fits). +twin Same box positions / yaws, same phone, same caps (trap still active), but the inner sizes (and kinds) of the + "fit" and "snug" boxes are swapped. In the twin the prior goes to the place where the ORIGINAL's fitting box + stands (now with snug sizes) and fails on the rim; the twin's fitting box stands where the original's snug box + stands. So the twin's lesson at the action level ("not that box, use that other box") is exactly the reverse + of the original's: following it on the original means choosing the original's failing (snug) box. + Caveat: the abstract lesson ("the phone is longer than it looks, take the box with the most length to spare") + is the same in both -- a negative cap (phone shorter than it looks) is not physically possible here. The box + sizes in the twin images differ from the original's at those two positions (they are visible). +reveal The cap length, in cm, per end and in total. +""" +HIDDEN_KEYS = ("cap",) + + +def h0(inst): + return {"cap": 0.0} + + +def _idx(inst, kind): + return next(j for j, b in enumerate(inst["boxes"]) if b["kind"] == kind) + + +def twin(inst): + f, s = _idx(inst, "fit"), _idx(inst, "snug") + boxes = [dict(b) for b in inst["boxes"]] + for k in ("kind", "inner"): + boxes[f][k], boxes[s][k] = inst["boxes"][s][k], inst["boxes"][f][k] + perc = [list(p) for p in inst["_perc"]] + perc[f], perc[s] = list(inst["_perc"][s]), list(inst["_perc"][f]) + return {"boxes": boxes, "fit": s, "fit_crossed": boxes[s]["crossed"], "_perc": perc} + + +def reveal(inst): + c = 100 * inst["cap"] + return (f"The phone has clear bumper caps on both of its short ends that do not show in the camera images; " + f"each cap adds about {c:.1f} cm, so the phone is about {2 * c:.1f} cm longer than it looks.") + + +def _where(inst, j): + """robot-frame position words of box j in the 2 x 3 grid (rows along x, columns along y)""" + xs = sorted({round(float(b["xy"][0]), 2) for b in inst["boxes"]} | {round(float(inst["phone_xy"][0]), 2)}) + x, y = (float(v) for v in inst["boxes"][j]["xy"]) + row = "in the row nearer to the robot" if abs(x - xs[0]) < abs(x - xs[-1]) else "in the row farther from the robot" + col = "on the robot's left" if y > 0.1 else ("on the robot's right" if y < -0.1 else "in the middle") + return f"{row}, {col}" + + +def fix(inst, params): + """Ladder Fix rung (docs/20): the fitting box (oracle box = inst['fit']), long side along the box's long side.""" + j = int(params["box"]) + return (f"A way to succeed: the phone fits only into the box {_where(inst, j)} (the one with the most length to " + f"spare; it looks tight across, but the phone's width fits). Pick the phone up, turn it so that its long " + f"side lines up with that box's long side, and lower it flat into the middle of that box before you " + f"release it.") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/real/protocol.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/real/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..13ce72af6568801584eb85c0c0b06279ddd3457d --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/lffbench/real/protocol.py @@ -0,0 +1,364 @@ +"""Robot-driver protocol v1: what a real arm (or a fake one) must answer so that LFF-Bench can run on it. + +The benchmark side (lffbench/real/session.py, on the machine that runs the agent harness) talks to one *driver* +process (on the robot PC) over HTTP. The driver only moves the arm, reads its state, grabs camera frames and talks +to the human operator; budgets, attempts, README, logs and the agent interface stay on the benchmark side, so the +agent sees exactly the same tools as in simulation. Spec for driver authors: lffbench/real/DRIVER.md. + +This file is shared by both sides and needs only the Python standard library + numpy + Pillow (no simulator): + DriverClient benchmark side: typed calls to a driver + DriverServer driver side: HTTP plumbing; subclass it and implement the hardware methods (driver_template.py) + ConsoleOperator driver side: the operator's terminal (blocking prompts for reset / judging) + +Every request is POST / with a JSON body and header X-Driver-Token: . +Every reply is JSON with "ok": true|false. A reply with "fault": true means the robot can no longer be trusted +(protective stop, e-stop, lost connection, ...): the benchmark ends the run and marks it invalid. +""" +import base64 +import io +import json +import math +import os +import secrets +import sys +import time +import traceback +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, HTTPServer + +import numpy as np + +PROTOCOL_VERSION = 1 +CAMERAS = ("agentview", "wrist") +TOKEN_HEADER = "X-Driver-Token" +ENDPOINTS = ("info", "home", "move", "gripper", "state", "observe", "ik", "operator", "event") +OPERATOR_KINDS = ("reset", "judge", "notice") +EVENTS = ("session_start", "attempt_start", "attempt_end", "episode_end", "session_end", "run_invalid") + + +class DriverError(RuntimeError): + """The driver answered something that breaks the protocol (or did not answer).""" + + +class DriverFault(DriverError): + """The driver reports a robot fault: the run must stop and is invalid.""" + + +# ------------------------------------------------------------------------------------------------ images +def encode_image(arr, fmt="png", quality=95): + """uint8 HxWx3 -> {"format": "png"|"jpeg", "data": base64}. PNG is lossless (the benchmark re-encodes every frame + as 512x512 JPEG q90 itself, so a JPEG from the driver is compressed twice); JPEG is smaller over a slow link.""" + from PIL import Image + buf = io.BytesIO() + im = Image.fromarray(np.asarray(arr, dtype=np.uint8)) + if fmt == "jpeg": + im.save(buf, format="JPEG", quality=int(quality)) + else: + im.save(buf, format="PNG") + return dict(format=fmt, data=base64.b64encode(buf.getvalue()).decode("ascii")) + + +def decode_image(obj): + """{"format", "data"} -> uint8 HxWx3 (RGB).""" + from PIL import Image + if not isinstance(obj, dict) or "data" not in obj: + raise DriverError("image must be {\"format\": \"png\"|\"jpeg\", \"data\": }") + im = Image.open(io.BytesIO(base64.b64decode(obj["data"]))) + return np.asarray(im.convert("RGB"), dtype=np.uint8) + + +def square_resize(arr, res): + """Centre-crop to a square, then resize to res x res. A frame that is already res x res is returned unchanged + (bit for bit), so a simulator-backed driver gives exactly the simulator's pixels.""" + from PIL import Image + arr = np.asarray(arr, dtype=np.uint8) + h, w = arr.shape[:2] + if h == res and w == res: + return arr + s = min(h, w) + y0, x0 = (h - s) // 2, (w - s) // 2 + arr = arr[y0:y0 + s, x0:x0 + s] + if s == res: + return np.ascontiguousarray(arr) + return np.asarray(Image.fromarray(arr).resize((res, res), Image.BICUBIC)) + + +# ------------------------------------------------------------------------------------------------ validation +def _vec(v, n): + return isinstance(v, (list, tuple)) and len(v) == n and all(isinstance(x, (int, float)) and math.isfinite(x) for x in v) + + +def info_problems(info): + """-> list of problems with an /info reply (empty = fine).""" + p = [] + if info.get("protocol") != PROTOCOL_VERSION: + p.append(f"protocol must be {PROTOCOL_VERSION}, got {info.get('protocol')!r}") + if not isinstance(info.get("robot"), str) or not info["robot"].strip(): + p.append("robot: non-empty string (e.g. \"AgileX PiPER\")") + if not isinstance(info.get("n_joints"), int) or not 4 <= info["n_joints"] <= 8: + p.append("n_joints: integer 4..8") + if sorted(info.get("cameras") or []) != sorted(CAMERAS): + p.append(f"cameras must be exactly {list(CAMERAS)}") + ws = info.get("workspace") or {} + if not (_vec(ws.get("lo"), 3) and _vec(ws.get("hi"), 3) and all(a < b for a, b in zip(ws["lo"], ws["hi"]))): + p.append("workspace: {lo: [x, y, z], hi: [x, y, z]} with lo < hi (robot-base frame, metres)") + yr = info.get("yaw_range_deg") + if not (_vec(yr, 2) and yr[0] < yr[1] and yr[1] - yr[0] >= 180.0): + p.append("yaw_range_deg: [lo, hi] with hi - lo >= 180 (the gripper is symmetric, every yaw must be reachable)") + if not (isinstance(info.get("max_speed"), (int, float)) and 0.01 <= info["max_speed"] <= 1.0): + p.append("max_speed: m/s, 0.01..1.0") + if not isinstance(info.get("ik"), bool): + p.append("ik: true|false (whether /ik is implemented; needed only for tasks with a calibration bias)") + if not isinstance(info.get("driver_version"), str): + p.append("driver_version: string (your git commit or a date; it is written into every run's log)") + return p + + +def state_problems(st, n_joints): + p = [] + if not _vec(st.get("eef_pos"), 3): + p.append("state.eef_pos: [x, y, z] metres") + if not (isinstance(st.get("eef_yaw_deg"), (int, float)) and math.isfinite(st["eef_yaw_deg"])): + p.append("state.eef_yaw_deg: number") + if not (isinstance(st.get("gripper_width_m"), (int, float)) and 0.0 <= st["gripper_width_m"] <= 0.2): + p.append("state.gripper_width_m: number 0..0.2") + if not _vec(st.get("joint_pos_rad"), n_joints): + p.append(f"state.joint_pos_rad: {n_joints} numbers (radians)") + return p + + +# ------------------------------------------------------------------------------------------------ benchmark side +class DriverClient: + """Typed calls to a driver. `url` like http://127.0.0.1:9900 (an SSH tunnel to the robot PC).""" + + def __init__(self, url, token, timeout=120.0): + self.url, self.token, self.timeout = url.rstrip("/"), token, float(timeout) + self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never through a web proxy + + def call(self, endpoint, payload=None, timeout=None, allow_not_ok=False): + req = urllib.request.Request(f"{self.url}/{endpoint}", data=json.dumps(payload or {}).encode(), + headers={"Content-Type": "application/json", TOKEN_HEADER: self.token}) + try: + with self.opener.open(req, timeout=timeout if timeout is not None else self.timeout) as r: + rep = json.loads(r.read().decode()) + except (urllib.error.URLError, OSError, ValueError) as e: + raise DriverError(f"/{endpoint}: no valid reply from the driver ({type(e).__name__}: {e})") from e + if not isinstance(rep, dict) or "ok" not in rep: + raise DriverError(f"/{endpoint}: reply is not a JSON object with \"ok\"") + if rep.get("fault"): + raise DriverFault(f"/{endpoint}: robot fault: {rep.get('error', '')}") + if not rep["ok"] and not allow_not_ok: + raise DriverError(f"/{endpoint}: {rep.get('error', 'not ok')}") + return rep + + def info(self): + rep = self.call("info") + prob = info_problems(rep) + if prob: + raise DriverError("/info: " + "; ".join(prob)) + return rep + + def home(self): + return self.call("home", timeout=max(self.timeout, 300)) + + def move(self, x, y, z, yaw_deg, speed=None): + """-> reply; ok=false (not a fault) means the target was rejected and the arm did not move.""" + return self.call("move", dict(x=float(x), y=float(y), z=float(z), yaw_deg=float(yaw_deg), + speed=None if speed is None else float(speed)), allow_not_ok=True) + + def gripper(self, close): + return self.call("gripper", dict(close=bool(close))) + + def state(self): + return self.call("state")["state"] + + def observe(self): + rep = self.call("observe") + imgs = rep.get("images") or {} + missing = [c for c in CAMERAS if c not in imgs] + if missing: + raise DriverError(f"/observe: missing camera(s) {missing}") + return {c: decode_image(imgs[c]) for c in CAMERAS}, rep["state"] + + def ik(self, eef_pos, yaw_deg): + return self.call("ik", dict(eef_pos=[float(v) for v in eef_pos], yaw_deg=float(yaw_deg)))["joint_pos_rad"] + + def operator(self, kind, **kw): + """Blocks until the operator has answered (no timeout).""" + assert kind in OPERATOR_KINDS, kind + return self.call("operator", dict(kind=kind, **kw), timeout=24 * 3600) + + def event(self, ev, **kw): + assert ev in EVENTS, ev + return self.call("event", dict(ev=ev, **kw)) + + +# ------------------------------------------------------------------------------------------------ driver side +class ConsoleOperator: + """The operator's terminal on the robot PC. Prompts block the driver (the robot must not move while the operator + resets the scene). Answers are appended to `log_path` (JSON lines).""" + + def __init__(self, log_path=None, stream_in=None, stream_out=None): + self.log_path = log_path + self.inp = stream_in or sys.stdin + self.out = stream_out or sys.stdout + + def _say(self, s=""): + self.out.write(s + "\n") + self.out.flush() + + def _ask(self, prompt): + self.out.write(prompt) + self.out.flush() + line = self.inp.readline() + if not line: + raise EOFError("operator input closed") + return line.strip() + + def _log(self, d): + if self.log_path: + os.makedirs(os.path.dirname(os.path.abspath(self.log_path)), exist_ok=True) + with open(self.log_path, "a") as f: + f.write(json.dumps(dict(d, t=time.time()), ensure_ascii=False) + "\n") + + def __call__(self, kind, run="", attempt=None, text="", setup="", checklist=None, **_): + bar = "=" * 72 + self._say("\n" + bar) + self._say(f"[{time.strftime('%H:%M:%S')}] run {run} attempt {attempt} -- {kind.upper()}") + if text: + self._say(text) + if kind == "reset": + if setup: + self._say("\nScene for this attempt (do it exactly; do not talk to anyone about it):\n" + setup) + self._ask("\nArm is at home. Put the scene back as described, step out of the cameras, press Enter... ") + self._log(dict(kind=kind, run=run, attempt=attempt)) + return dict(ok=True) + if kind == "judge": + for i, c in enumerate(checklist or [], 1): + self._say(f" {i}. {c}") + while True: + a = self._ask("\nAll conditions met? y = success, n = failure, x = run invalid (robot / camera " + "problem): ").lower() + if a in ("y", "n", "x"): + break + note = self._ask("Note (one line, optional): ") + self._log(dict(kind=kind, run=run, attempt=attempt, answer=a, note=note)) + if a == "x": + return dict(ok=False, fault=True, error=f"operator marked the run invalid: {note}") + return dict(ok=True, success=a == "y", note=note) + self._log(dict(kind=kind, run=run, attempt=attempt, text=text)) + return dict(ok=True) + + +class DriverServer: + """HTTP plumbing for a driver. Subclass and implement the hardware methods below; see driver_template.py. + The server is single-threaded on purpose: requests are executed one at a time, and an operator prompt blocks + every other request until it is answered.""" + + # ---- implement these ------------------------------------------------------------------------------ + def info(self): + """-> dict (see DRIVER.md §3): protocol, robot, n_joints, cameras, workspace, yaw_range_deg, max_speed, ik, + driver_version.""" + raise NotImplementedError + + def home(self): + """Move to the home pose (gripper open, pointing down). -> state dict.""" + raise NotImplementedError + + def move(self, x, y, z, yaw_deg, speed): + """Blocking straight-line move of the grasp point; speed m/s or None (= max_speed). + -> (ok, error_or_None, motion_s). ok=False: rejected BEFORE moving (outside the hard limits / no IK).""" + raise NotImplementedError + + def gripper(self, close): + """Blocking open / close (force-limited close). -> motion_s.""" + raise NotImplementedError + + def state(self): + """-> dict eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad.""" + raise NotImplementedError + + def images(self): + """-> {"agentview": uint8 HxWx3 RGB, "wrist": ...}, taken now (after the arm has stopped).""" + raise NotImplementedError + + def ik(self, eef_pos, yaw_deg): + """Optional (info()["ik"] = True): joint angles that put the grasp point at eef_pos / yaw_deg (pointing + down), close to the current joint angles. -> list of n_joints floats.""" + raise NotImplementedError + + def operator(self, kind, **kw): + """Default: the terminal. -> dict (reset: {ok}; judge: {ok, success, note}; notice: {ok}).""" + return self.console(kind, **kw) + + def event(self, ev, **kw): + """Start / stop your own recordings here (attempt_start / attempt_end / episode_end ...).""" + return None + + image_format = "png" + + # ---- plumbing ------------------------------------------------------------------------------------- + def dispatch(self, endpoint, a): + if endpoint == "info": + return dict(ok=True, **self.info()) + if endpoint == "home": + return dict(ok=True, state=self.home()) + if endpoint == "move": + ok, err, motion_s = self.move(float(a["x"]), float(a["y"]), float(a["z"]), float(a["yaw_deg"]), + None if a.get("speed") is None else float(a["speed"])) + rep = dict(ok=bool(ok), motion_s=float(motion_s or 0.0), state=self.state()) + if not ok: + rep["error"] = err or "rejected" + return rep + if endpoint == "gripper": + motion_s = self.gripper(bool(a["close"])) + return dict(ok=True, motion_s=float(motion_s or 0.0), state=self.state()) + if endpoint == "state": + return dict(ok=True, state=self.state()) + if endpoint == "observe": + imgs = self.images() + return dict(ok=True, images={c: encode_image(imgs[c], self.image_format) for c in CAMERAS}, + state=self.state()) + if endpoint == "ik": + return dict(ok=True, joint_pos_rad=[float(v) for v in self.ik(a["eef_pos"], float(a["yaw_deg"]))]) + if endpoint == "operator": + kw = {k: v for k, v in a.items() if k != "kind"} + return self.operator(a["kind"], **kw) + if endpoint == "event": + self.event(a.get("ev", ""), **{k: v for k, v in a.items() if k != "ev"}) + return dict(ok=True) + return dict(ok=False, error=f"unknown endpoint {endpoint!r}") + + def serve(self, port, token=None, host="127.0.0.1", operator_log=None): + """Serve forever on host:port (keep 127.0.0.1 and reach it through an SSH tunnel).""" + self.token = token or os.environ.get("LFF_DRIVER_TOKEN") or secrets.token_hex(12) + self.console = ConsoleOperator(operator_log) + drv = self + + class H(BaseHTTPRequestHandler): + def log_message(self, *x): + pass + + def do_POST(self): + try: + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}") + if self.headers.get(TOKEN_HEADER) != drv.token: + rep = dict(ok=False, error="unauthorised") + else: + rep = drv.dispatch(self.path.strip("/"), body) + except NotImplementedError as e: + rep = dict(ok=False, error=f"not implemented: {self.path} {e}") + except Exception as e: # anything unexpected on the robot side is a fault: stop the run + traceback.print_exc() + rep = dict(ok=False, fault=True, error=f"{type(e).__name__}: {e}") + data = json.dumps(rep).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + srv = HTTPServer((host, int(port)), H) + print(f"driver ready on http://{host}:{port} token={self.token}", flush=True) + srv.serve_forever() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/api_player.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/api_player.py new file mode 100644 index 0000000000000000000000000000000000000000..696c1e9204de668d41bdd9622931c5c579caea87 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/api_player.py @@ -0,0 +1,446 @@ +"""Drive one robot_server session with a model through its provider's official API (the unified harness). + +Every provider gets exactly the same input: the sandbox README as its instructions and the same tools; only the +wire format differs (lffbench/agent/backends/). After every command the JSON report is returned as the tool output. +Nothing else is sent: no files, no memory, no paths outside the sandbox. + + python scripts/api_player.py --session runs/<...>/session.json --provider anthropic --model claude-opus-5-5 --effort high --style la + +Providers (key / endpoint from the environment, e.g. `set -a; source .env; set +a`): + openai OpenAI Responses API OPENAI_API_KEY [OPENAI_BASE_URL] + anthropic Anthropic Messages API ANTHROPIC_API_KEY + gemini Gemini API (google-genai) GEMINI_API_KEY + chat any OpenAI-compatible Chat Completions endpoint (vLLM / SGLang for open models, xAI, ...) + LFF_CHAT_BASE_URL, LFF_CHAT_API_KEY +`--effort` is the provider's reasoning knob: OpenAI reasoning.effort, Anthropic output_config.effort, Gemini +thinking_level, chat: reasoning_effort (omitted when "none"). + +--style la (LIBERO-Agent-style workspace, the paper's interface): the sandbox is the agent's episode workspace. Besides +`robot` the model gets `shell` (a command run in the workspace inside a jail: no network, robot server unreachable, +host data hidden, see /opt/lffjail/jail_inner.sh) and `view_images` (any image file in the workspace, including ones +it made itself). Tool calls per attempt are capped (agent_iface.json: max_tool_calls); at the cap the attempt is +finished for it. +Logs in the run's log dir: transcript.jsonl (every request / reply / tool call), final_report.md. +""" +import argparse +import base64 +import json +import os +import shlex +import subprocess +import sys +import time +import traceback +import urllib.request + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"): + os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # the venv's own CA bundle lacks the proxy's issuer + +from lffbench.agent.backends import make_backend # noqa: E402 +from lffbench.agent.context import Conversation # noqa: E402 + +PROVIDERS = ("openai", "anthropic", "gemini", "chat") + +TOOL = dict( + name="robot", + description=("Run one robot command. `command` is exactly what you would type after `./robot` in the " + "instructions (e.g. `observe`). Returns the command's JSON report."), + parameters=dict(type="object", properties=dict(command=dict(type="string", description="the robot command")), + required=["command"], additionalProperties=False), +) + +VIEW_TOOL = dict( + name="view_images", + description=("Look at camera images the robot has written. `paths` are image paths exactly as printed by robot " + "commands (e.g. obs/a1_s003_wrist.jpg); any image of this episode can be viewed again. The images " + "are attached right after this call."), + parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"), + description="image paths to view")), + required=["paths"], additionalProperties=False), +) + +TOOL_LA = dict( + name="robot", + description=("Run one robot command. `command` is exactly one of the robot commands in the instructions, e.g. " + "`status` or `move_eef z=1.0 gripper=open`. Returns the command's JSON report, including the paths " + "of the new observation files."), + parameters=TOOL["parameters"], +) + +SHELL_TOOL = dict( + name="shell", + description=("Run a shell command (bash) in your workspace directory, e.g. `ls obs` or `python3 analyse.py`. " + "python3 has numpy, scipy, Pillow and OpenCV. No network; programs cannot control the robot. " + "Time limit 60 s per call. Returns the exit code and the combined stdout/stderr (long output is " + "truncated in the middle)."), + parameters=dict(type="object", properties=dict(command=dict(type="string", description="the bash command")), + required=["command"], additionalProperties=False), +) + +VIEW_TOOL_LA = dict( + name="view_images", + description=("Look at image files in your workspace (.jpg / .jpeg / .png), e.g. obs/a1_s003_wrist.jpg or an image " + "you made yourself; paths are relative to the workspace. At most 8 per call. The images are attached " + "right after this call."), + parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"), + description="image paths to view")), + required=["paths"], additionalProperties=False), +) + +PREAMBLE_LA = ("You control the robot described below and work in the workspace described below. Tools: `robot` runs " + "one robot command per call (the argument is exactly a command from the instructions, e.g. `status`); " + "`shell` runs a shell command in your workspace; `view_images` shows you image files from the " + "workspace. When a robot command tells you to stop or that the episode is over, stop calling tools and " + "reply with a short report: what you did (key commands and parameter values), what you observed, any " + "feedback you got, and how you changed your approach.\n\n") + +PREAMBLE = ("You control the robot described below. You act only through the `robot` tool, one command per call. " + "When a command tells you to stop or that the episode is over, stop calling the tool and reply with a " + "short report: what you did (key commands and parameter values), what you observed, any feedback you " + "got, and how you changed your approach.\n\n") + +JAIL = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "jail", "jail_inner.sh") +SHELL_TIMEOUT = 60 +SHELL_MAX_CHARS = 12000 + + +def run_shell(workspace, command): + """Run `command` in the jailed workspace; returns (exit code, output text, seconds).""" + t0 = time.time() + argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, workspace, + "timeout", "-k", "5", str(SHELL_TIMEOUT), "bash", "-c", command] + try: + r = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + timeout=SHELL_TIMEOUT + 30) + code, out = r.returncode, r.stdout.decode("utf-8", "replace") + except subprocess.TimeoutExpired as e: + code, out = 124, (e.stdout or b"").decode("utf-8", "replace") + if code == 124: + out += f"\n[killed: time limit of {SHELL_TIMEOUT} s]" + if len(out) > SHELL_MAX_CHARS: + h = SHELL_MAX_CHARS // 2 + out = out[:h] + f"\n[... {len(out) - SHELL_MAX_CHARS} characters truncated ...]\n" + out[-h:] + return code, out, time.time() - t0 + + +def workspace_image(workspace, rel): + """Resolve a model-given image path inside the workspace (no escaping via .. or symlinks); None if not allowed.""" + if not isinstance(rel, str) or not rel or rel.startswith("/"): + return None + root = os.path.realpath(workspace) + full = os.path.realpath(os.path.join(root, rel)) + if not full.startswith(root + os.sep) or not os.path.isfile(full): + return None + if os.path.splitext(full)[1].lower() not in (".jpg", ".jpeg", ".png") or os.path.getsize(full) > 8 * 2 ** 20: + return None + return full + + +class FileImage: + """The exact JPEG bytes the server wrote (same bytes a Claude Code player reads).""" + + def __init__(self, path): + self.path = path + base = os.path.basename(path) + self.camera = "wrist" if "wrist" in base else ("agentview" if "agentview" in base else "camera") + self.label = base + + def data_url(self, quality=None): + mime = "image/png" if self.path.lower().endswith(".png") else "image/jpeg" + with open(self.path, "rb") as f: + return f"data:{mime};base64," + base64.b64encode(f.read()).decode() + + +def parse_command(s): + s = s.strip() + s = s.removeprefix("./robot").strip() if s.startswith("./robot") else (s[len("robot "):] if s.startswith("robot ") else s) + toks = shlex.split(s.strip()) + if not toks: + return "help", {} + cmd, args = toks[0], {} + for a in toks[1:]: + if "=" not in a: + return None, f"bad argument {a!r}: use key=value" + k, v = a.split("=", 1) + try: + args[k] = json.loads(v) + except ValueError: + args[k] = v + return cmd, args + + +def call_server(port, token, cmd, args): + req = urllib.request.Request(f"http://127.0.0.1:{port}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(), + headers={"Content-Type": "application/json", "X-Token": token}) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(req, timeout=900) as r: + return r.read().decode() + + +MAX_NO_TOOL = 3 # nudges in a row for replies without a tool call; the next such reply ends the run + + +def continue_nudge(port, token, stx=None): + """The user message sent when the model replies without a tool call before the episode is over. Native harnesses + send the same text when their CLI exits early (scripts/harness_run.py). stx: a status reply already fetched.""" + try: # tell it where it is: models sometimes believe the episode ended after a failed attempt + if stx is None: + stx = json.loads(call_server(port, token, "status", {})) + where = (f" You are in attempt {stx.get('attempt')} of {stx.get('max_attempts')}; the episode is NOT over." + if stx.get("attempt") else "") + except Exception: + where = "" + return "Continue: issue the next robot command with the `robot` tool." + where + + +def build_backend(a, v2): + """The model backend for --provider; image pruning only where the provider allows editing earlier turns.""" + if a.provider == "openai": + return make_backend("openai", model=a.model, reasoning_effort=a.effort, reasoning_summary="auto", + max_live_images=None if v2 else a.max_live_images, cache_breakpoints="none", max_retries=1) + if a.provider == "anthropic": # append-only history (thinking blocks are bound to it): never prune + return make_backend("anthropic", model=a.model, effort=a.effort, max_live_images=None) + if a.provider == "gemini": + return make_backend("gemini", model=a.model, thinking_level=a.effort, + max_live_images=None if v2 else a.max_live_images) + extra = None if a.effort in ("", "none", None) else dict(reasoning_effort=a.effort) + return make_backend("chat", model=a.model, max_tokens=a.max_output_tokens, temperature=None, extra_body=extra, + max_live_images=None if v2 else a.max_live_images) + + +def context_overflow(err): + """The request no longer fits: token limit (OpenAI / Anthropic / Gemini / Kimi wordings) or too many images.""" + e = err.lower() + return (("context" in e and ("length" in e or "window" in e or "too long" in e)) or "prompt is too long" in e + or ("exceed" in e and "token" in e) or "too many images" in e or "maximum number of images" in e) + + +def live_images(conv): + return sum(1 for it in conv.items if it["kind"] == "user" and it.get("live") for p in it["parts"] + if p["type"] == "image") + + +def main(argv=None, default_provider=None, transcript_name="transcript.jsonl"): + ap = argparse.ArgumentParser() + ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh") + ap.add_argument("--provider", default=default_provider, choices=PROVIDERS, required=default_provider is None) + ap.add_argument("--model", default="gpt-6-astra" if default_provider == "openai" else None, + required=default_provider is None) + ap.add_argument("--effort", default="medium") + ap.add_argument("--max-turns", type=int, default=400) + ap.add_argument("--max-live-images", type=int, default=16) + ap.add_argument("--max-output-tokens", type=int, default=32768, help="chat provider only") + ap.add_argument("--api-retries", type=int, default=8, + help="retries of a failed API call before giving up (back-off 5 s doubling to 120 s: ~9 min)") + ap.add_argument("--max-request-images", type=int, default=500, + help="when the conversation holds more viewed images than this, switch to the context-full " + "policy (Claude through a gateway failed at 601 images, 2026-10-15)") + ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"], + help="v2: images are not attached automatically; the model views them on demand with " + "view_images, and no history is pruned (the agent manages its own context)") + a = ap.parse_args(argv) + + sess = json.load(open(a.session)) + sb, port = sess["sandbox"], sess["port"] + log_dir = os.path.dirname(os.path.abspath(a.session)) + la = a.style == "la" + if la: # no robot CLI in a la workspace: the token is only in the log dir + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + token, max_tool_calls = iface["token"], int(iface["max_tool_calls"]) + else: + token = open(os.path.join(sb, "robot")).read().split('TOKEN = "', 1)[1].split('"', 1)[0] + readme = open(os.path.join(sb, "README.md")).read() + tlog = open(os.path.join(log_dir, transcript_name), "a") + + def log(d): + d["t"] = time.time() + tlog.write(json.dumps(d, ensure_ascii=False) + "\n") + tlog.flush() + + v2 = a.style in ("v2", "la") # la = v2 robot interface + workspace tools + tools = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] if la else ([TOOL, VIEW_TOOL] if v2 else [TOOL]) + backend = build_backend(a, v2) + conv = Conversation((PREAMBLE_LA if la else PREAMBLE) + readme) + log(dict(ev="start", provider=a.provider, model=a.model, effort=a.effort, style=a.style, backend=backend.config(), + instructions=conv.system, tools=tools)) + + def images_part(paths, title): + parts = [dict(type="text", text=title)] + for p in paths: + parts.append(dict(type="image", image=FileImage(os.path.join(sb, p)))) + return parts + + st = json.loads(call_server(port, token, "status", {})) + if v2: # images stay files; the model decides what to look at + first = [dict(type="text", text=("Begin. Current status (robot command `status`):\n" if la else + "Begin. Current status (`./robot status`):\n") + json.dumps(st))] + else: + first = [dict(type="text", text="Begin. Current status (`./robot status`):\n" + + json.dumps({k: v for k, v in st.items() if k != "images"}))] + first += images_part(st.get("images", []), "Current camera images (agentview, wrist):")[1:] + conv.add_user(first, live=True) + log(dict(ev="user", text=first[0]["text"], images=st.get("images", []))) + + finished, no_tool, report = False, 0, None + calls_in_attempt = 0 # la: tool calls (robot + shell + view_images) in the current attempt + usage_tot = dict(input_tokens=0, cached_tokens=0, cache_write_tokens=0, output_tokens=0, reasoning_tokens=0) + for turn in range(a.max_turns): + resp, err = None, None + if v2 and backend.max_live_images is None and live_images(conv) > a.max_request_images: + backend.max_live_images = 32 # same context-full policy as below, before the request limit is hit + log(dict(ev="context_overflow", reason="image count", n_images=live_images(conv), keep_images=32)) + for r in range(a.api_retries + 1): + t0 = time.time() + try: + out = backend.act(conv, tools) + except Exception as e: # flaky endpoint: back off and retry the identical request + err = f"{type(e).__name__}: {str(e)[:300]}" + if v2 and context_overflow(err): + # the context is full (every provider): from now on keep only the newest viewed images + backend.max_live_images = 32 if backend.max_live_images is None else max(backend.max_live_images // 2, 4) + log(dict(ev="context_overflow", reason=err[:120], keep_images=backend.max_live_images)) + log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0)) + time.sleep(min(120, 5 * 2 ** r)) + continue + if out.status == "refusal": # the provider declined: no fallback model (it would change the model under test) + resp, err = out, out.error + break + if out.status == "incomplete": # truncated / malformed turn: not appended, ask again + err = out.error + log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0, usage=out.usage)) + continue + resp = out + break + if resp is None: + log(dict(ev="abort", reason="api failed", error=err)) + print("ABORT api failed:", err, flush=True) + sys.exit(3) + for k in usage_tot: + usage_tot[k] += resp.usage.get(k, 0) + if resp.status == "refusal": + log(dict(ev="refusal", turn=turn, latency_s=resp.latency_s, usage=resp.usage, error=resp.error, + text=resp.text)) + log(dict(ev="abort", reason="refusal", error=resp.error)) + print("ABORT refusal:", resp.error, flush=True) + break + conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name) + log(dict(ev="assistant", turn=turn, latency_s=resp.latency_s, usage=resp.usage, text=resp.text, + reasoning_summary=resp.reasoning_summary, + reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned", + status=resp.status, error=resp.error, + tool_calls=[dict(id=c.id, name=c.name, arguments=c.arguments) for c in resp.tool_calls], + request_stats=resp.request_stats)) + if finished: + report = resp.text + break + if not resp.tool_calls: + no_tool += 1 + nudge = continue_nudge(port, token) + if no_tool > MAX_NO_TOOL: + log(dict(ev="abort", reason="no tool call 4 times")) + break + conv.add_user([dict(type="text", text=nudge)], live=False) + log(dict(ev="user", text=nudge)) + continue + no_tool = 0 + for c in resp.tool_calls: + if la and not finished: + calls_in_attempt += 1 + if la and c.name == "shell": + code, out, dt = run_shell(sb, str(c.arguments.get("command", ""))) + out_text = json.dumps(dict(exit_code=code, output=out)) + conv.add_tool_output(c.id, c.name, out_text) + log(dict(ev="tool", turn=turn, command="shell: " + str(c.arguments.get("command", "")), output=out_text, + shell_s=round(dt, 2))) + continue + if la and c.name == "view_images": + paths = [str(x) for x in (c.arguments.get("paths") or [])][:8] + full = [(x, workspace_image(sb, x)) for x in paths] + ok_paths = [x for x, f in full if f] + out = dict(ok=bool(ok_paths), attached=ok_paths) + if len(ok_paths) < len(paths): + out["not_viewable"] = [x for x, f in full if not f] + conv.add_tool_output(c.id, c.name, json.dumps(out)) + log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths)) + if ok_paths: + parts = [dict(type="text", text="Requested images:")] + for x, f in full: + if f: + parts.append(dict(type="image", image=FileImage(f))) + conv.add_user(parts, live=True) + continue + if c.name == "view_images": + paths = [str(x) for x in (c.arguments.get("paths") or [])][:8] + ok_paths = [x for x in paths if x.startswith("obs/") and "/.." not in x and ".." not in x + and os.path.exists(os.path.join(sb, x))] + bad = [x for x in paths if x not in ok_paths] + out = dict(ok=bool(ok_paths), attached=ok_paths) + if bad: + out["not_found"] = bad + conv.add_tool_output(c.id, c.name, json.dumps(out)) + log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths)) + if ok_paths: + conv.add_user(images_part(ok_paths, "Requested images:"), live=True) + continue + cmdline = str(c.arguments.get("command", "")) + cmd, args = parse_command(cmdline) + if cmd is None: + out_text, paths = json.dumps(dict(ok=False, error=args)), [] + else: + raw = call_server(port, token, cmd, args) + try: + rep = json.loads(raw) + if v2: # keep the image paths in the reply: the model views them itself if it wants + paths = [] + out_text = json.dumps(rep) + else: + paths = rep.pop("images", []) if isinstance(rep, dict) else [] + out_text = json.dumps(rep) + except ValueError: # help text + rep, paths, out_text = {}, [], raw + msg = (rep.get("message", "") + " " + rep.get("error", "")) if isinstance(rep, dict) else "" + if isinstance(rep, dict) and isinstance(rep.get("attempt_ended"), dict): + msg += " " + rep["attempt_ended"].get("message", "") + if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg: + finished = True + if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)): + calls_in_attempt = 0 + conv.add_tool_output(c.id, c.name, out_text) + log(dict(ev="tool", turn=turn, command=cmdline, output=out_text, images=paths)) + if paths and not v2: + conv.add_user(images_part(paths, f"Camera images after `{cmdline}` (agentview, wrist):"), live=True) + if la and not finished and calls_in_attempt >= max_tool_calls: + raw = call_server(port, token, "finish", dict(reason="tool-call budget used up (automatic)")) + try: + rep = json.loads(raw) + except ValueError: + rep = dict(raw=raw) + msg = rep.get("message", "") + " " + rep.get("error", "") + if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg: + finished = True + calls_in_attempt = 0 + note = (f"The budget of {max_tool_calls} tool calls for this attempt was used up, so the attempt was " + f"finished automatically. Result: " + json.dumps(rep)) + conv.add_user([dict(type="text", text=note)], live=False) + log(dict(ev="user", text=note, auto_finish=True)) + if finished: + ask = "Stop now and reply with your short report (no more tool calls)." + conv.add_user([dict(type="text", text=ask)], live=False) + log(dict(ev="user", text=ask)) + if report: + with open(os.path.join(log_dir, "final_report.md"), "w") as f: + f.write(report) + log(dict(ev="end", finished=finished, usage_total=usage_tot)) + print(json.dumps(dict(finished=finished, usage=usage_tot, report=(report or "")[:200])), flush=True) + + +if __name__ == "__main__": + try: + main() + except SystemExit: + raise + except Exception: + traceback.print_exc() + sys.exit(1) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/record_breakfast_service.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/record_breakfast_service.py new file mode 100644 index 0000000000000000000000000000000000000000..bc1731b46da0c9383c1513fde541833bfbbd8180 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_deepseek/lff/source_closure/scripts/record_breakfast_service.py @@ -0,0 +1,89 @@ +"""Continuous simulation recording with a magnified crop; no state edits or model calls.""" +import argparse, hashlib, json +from pathlib import Path +import imageio.v2 as imageio +import numpy as np +from PIL import Image, ImageDraw, ImageFont +from lffbench import envs +from lffbench.tasks.lh_breakfast_service import BreakfastService +import robosuite.utils.transform_utils as T + +FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' + +class Recorder: + def __init__(self,t,out): + self.t=t;self.out=out;self.n=0;self.frames=0;self.timeline=[] + self.phase='Prepare breakfast';self.focus='food';self.raw_n=0 + self.raw=imageio.get_writer(str(out/'breakfast_full_1x.mp4'),fps=5,codec='libx264',quality=8,macro_block_size=1) + self.preview=imageio.get_writer(str(out/'breakfast_recovery_2x.mp4'),fps=10,codec='libx264',quality=8,macro_block_size=1) + self.original=t.env.step;t.env.step=self.step + # Rendering-only side camera makes the reopened lid's gap visible. + m=t.env.sim.model;cid=m.camera_name2id('sideview') + pos=np.array([-.28,-.58,1.16]);target=np.array([-.20,-.10,.96]) + z=(pos-target)/np.linalg.norm(pos-target);x=np.cross([0,0,1],z);x/=np.linalg.norm(x);y=np.cross(z,x) + q=T.mat2quat(np.column_stack([x,y,z])) + m.cam_pos[cid]=pos;m.cam_quat[cid]=q[[3,0,1,2]];m.cam_fovy[cid]=45 + t.env.sim.forward() + def step(self,a): + result=self.original(a);self.n+=1 + if self.n%4==0:self.capture() + return result + def frame(self): + return Image.fromarray(envs.render(self.t.env,res=768)) + def decorate(self,im): + canvas=Image.new('RGB',(1280,928),(19,26,36));canvas.paste(im,(0,48)) + crop={'milk':(440,180,760,500),'lid':(150,230,470,550),'food':(0,220,320,540)}[self.focus] + detail=(Image.fromarray(envs.render(self.t.env,cam='sideview',res=512)) if self.focus=='lid' + else im.crop(crop).resize((512,512),Image.Resampling.LANCZOS)) + canvas.paste(detail,(768,80)) + d=ImageDraw.Draw(canvas);f=ImageFont.truetype(FONT,24);sm=ImageFont.truetype(FONT,20) + d.text((18,10),'BREAKFAST | scripted recovery reference | same attempt | 2x',font=f,fill='white') + d.text((785,52),'Synchronized side view' if self.focus=='lid' else 'Magnified detail from the same frame',font=sm,fill='#b5ccdf') + q=self.t.liquid + for n,line in enumerate([f'Simulation: {self.n*.05:.1f} s',f'Milk in cup: {q["cup"]:.1f} mL', + f'Spilled: {q["spill"]:.1f} mL',f'Pantry lid: {self.t.lid_deg():.1f} deg', + f'Butter height: {100*self.t.butter_height():.1f} cm']): + d.text((790,620+36*n),line,font=f,fill='white') + d.text((18,830),self.phase,font=f,fill='#ffe0a2') + d.text((18,874),'Milk: simplified flow + ballistic parcels; rigid objects: MuJoCo contacts.',font=sm,fill='#b5ccdf') + return np.asarray(canvas) + def capture(self): + im=self.frame();self.raw.append_data(np.asarray(im));self.raw_n+=1 + self.preview.append_data(self.decorate(im));self.frames+=1 + def phase_hook(self,text,state): + if text.startswith(('Tipping handle:','Returning handle:','Bread pickup:','Bread placement:')):return + if 'carton' in text or 'cradle' in text or 'milk' in text.lower():self.focus='milk' + elif 'pantry' in text.lower() or 'L4' in text or 'lid' in text.lower() or 'inside the box' in text or 'Upright butter' in text:self.focus='lid' + else:self.focus='food' + self.phase=text + row=dict(state,preview_time_s=self.frames/10,preview_frame=self.frames) + self.timeline.append(row) + im=self.frame();Image.Image.save(im,self.out/f'checkpoint_{len(self.timeline):02d}.png') + # Explicit presentation hold only; no simulation reset or omitted motion. + for _ in range(10):self.preview.append_data(self.decorate(im));self.frames+=1 + print(json.dumps(row,default=lambda v:v.item()),flush=True) + def close(self): + self.t.env.step=self.original;self.raw.close();self.preview.close() + +def main(): + p=argparse.ArgumentParser();p.add_argument('--out',required=True);p.add_argument('--seed',type=int,default=1000) + a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + t=BreakfastService();inst=t.sample_instance(a.seed);t.reset_instance(inst) + r=Recorder(t,out);t.phase_hook=r.phase_hook + try: + t.execute(inst,{'mode':'adaptive'});result=t.outcome(inst) + r.phase_hook('FINAL: breakfast served; all three failures recovered' if result['success'] else 'FINAL: verification failed', + dict(step=t.sk.n_steps,outcome=result)) + finally:r.close() + files=[Path(__file__).resolve().parents[1]/'lffbench/tasks'/n for n in + ('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')] + meta=dict(seed=a.seed,instance=inst,outcome=result,continuous_attempt=True,resets_during_recording=0, + source_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files}, + sim_seconds=r.n*.05,raw_frames=r.raw_n,preview_frames=r.frames,timeline=r.timeline, + presentation='2x with 1 s freeze at labeled checkpoints; full 1x has no presentation freezes', + video_hashes={f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in out.glob('*.mp4')}) + (out/'recording.json').write_text(json.dumps(meta,indent=2,default=lambda v:v.item())) + assert result['success'] and all(result['traps'].values()) and all(result['recovered'].values()),result + t.env.close() + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_viewer/README.md b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_viewer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d158d1e5fb03c38d2c239dd80f6288556cff7426 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_viewer/README.md @@ -0,0 +1,150 @@ +# Agent Viewer — historical replay + +Export saved LFF-Bench API-player logs to one offline HTML page, including original +image bytes and the complete `rollout.mp4` when available. No model calls, simulator, server, build tools, or frontend dependencies +are required to generate or open the result. + +From the repository root: + +```bash +python scripts/agent_viewer/export.py \ + --run runs/gpt/exp2d/exp2d-gpt-6-astra_l5_slide_to_target_s1000_full_F2_direct_k3_1007-060153_p9738 \ + --out traces/agent-viewer-slide/index.html +``` + +Open the resulting HTML file in a browser. Repeat `--run` to include multiple +runs. If a run's original sandbox has moved, use `--sandbox /new/image/root` +with a single run. Relative images copied into the run directory take precedence. +The export remains usable after the original sandbox is removed. + +## What the viewer shows + +- Continuous execution video is the default view when `rollout.mp4` exists, with + native playback, seeking, fullscreen and playback speed controls. The original + MP4 is embedded byte-for-byte; no still-image slideshow is substituted. +- The separate step view retains input images and tool logs. Selecting an attempt + opens its step details. Video and logs are not automatically synchronized because + old recordings have no frame-to-event index and omit model waiting time. + +- One step per recorded assistant response; tool calls and results stay together. +- The most recent observation **before** each decision, and separately the new + images returned **after** its actions. Older images may also be in model context; + the viewer shows the request's recorded image count when available. +- Camera switching, per-step playback, scrubbing, keyboard navigation (arrows and + space), and jumps to attempt verdicts. Playback uses fixed seconds per step, + with original elapsed/model latency shown separately. +- Tool arguments, raw tool results, public assistant replies, API retries, missing + images, and incomplete calls. Recorded reasoning summaries are exported verbatim between observation and action in the step details. + The summary of decision N is shown between the preceding feedback and action N. + Public replies are labeled separately; missing summaries stay explicitly missing. + These are recorded summaries, not full internal CoT or reconstructed reasoning. +- A reset warning when a failed `done` returns the next attempt's initial images. + Attempt success comes from server `done` events, not the assistant's claim. + +## Current input contract and limitations + +Supports the API-player `ev` schema in `transcript.jsonl` or +`gpt_transcript.jsonl`, with `session.json` and optional `events.jsonl`. Other +harness formats (MCP, native Codex/Claude, RPent, GPT-Policy) need adapters and +are not claimed as supported. Corrupt JSON and ambiguous result matching fail +explicitly instead of silently pairing the wrong steps. + +Image files are copied byte-for-byte at export time. Old logs contain paths rather +than image hashes, so files overwritten since the run cannot be authenticated as +the original model inputs. Missing images are visibly marked; no replacement +frames are invented. Runs without a video fall back to step replay with the video tab disabled. + +The sample video is 19.05 seconds, H.264, 640×376 at 20 fps. Its action segments +were recorded at 3× simulation speed; choose ⅓× playback to slow them back down. +The recording includes both attempts and their verdict cards, but not model/API +waiting time. + +The sample `l5_slide_to_target`, seed 1000, has 14 assistant responses, 13 tool +calls, and two verdicts: failure then success. It is a historical development +run using depth perception and F2 feedback, not evidence of general benchmark +performance. The first push overshot by 4 cm; the next push reduced its endpoint +from x=-0.105 m to x=-0.145 m and succeeded. + +## Verification + +```bash +python -m unittest discover -s tests -p test_agent_viewer.py -v +``` + +Regression cases cover observation/action ordering, resets, carried-forward +observations, API retries, missing artifacts, incomplete calls, reordered call +IDs, malformed logs, path restrictions, and safe embedding of untrusted text. + +## Recording future runs + +`api_player.py` already requests provider summaries (`auto` for OpenAI) and +saves returned `reasoning_summary` plus public `text` for each assistant turn. +`run_agent.py` now also defaults `--reasoning-summary` to `auto`; pass `none` +when an endpoint cannot support the option. Both loggers add +`reasoning_summary_status`: `recorded` when a summary is present and +`not_returned` when the response contains none. This labels response availability, +not whether summaries were requested or whether the model reasoned internally. + +Historical missing records are left unchanged. No extra model calls or +retrospective rationale generation are used. Changes apply to newly started +processes from this checkout; other worktrees and native CLI harnesses retain +their own logging behavior. The viewer still imports API-player transcripts; +`run_agent` logs use a different schema and need an adapter to view here. + +## Live terminal viewer + +`live.py` observes existing runs without contacting the robot/model or changing the +run. Use a terminal with truecolor support for low-resolution color image previews; +`--ascii` provides a monochrome fallback. Pillow is the only image dependency and +is already present in the evaluation environment. + +```bash +python scripts/agent_viewer/live.py --batch /absolute/path/to/runs/api/BATCH +python scripts/agent_viewer/live.py --run /absolute/path/to/RUN --once --ascii +``` + +A batch view follows the first running run and switches when the manifest advances; +for concurrent runs in one batch, use `--run` to select another. Refresh defaults to +6 seconds. `Ctrl+C` exits; `--no-images`, `--width`, `--image-rows`, `--interval`, and +`--duration` control presentation. A redirected output uses ASCII and no screen +control codes. `--once` prints one snapshot. + +Supported live sources: API-player transcripts; framework gateway/MCP tool logs; +and Codex `item.completed` events. Only successful `view_images` attachments or +API-player image inputs become displayed observations. Robot-produced files alone +do not establish that the Agent saw them. Matching embedded images from native +Codex events take precedence over file references; potentially overwritten files +are marked unavailable. The current view displays the latest observation batch, +not continuous video, and explicitly labels its age. Recorded summaries are shown +when the relevant stream provides them. It does not expose `session.json` tokens, +server-side hidden task parameters, or send any robot commands. + +```bash +python -m unittest discover -s tests -p test_live_viewer.py -v +``` + +### Clearer terminal images + +The old character preview was limited to 20 rows (at most ~40 vertical pixels). +It now uses available terminal height and width. `--camera main` or `--camera wrist` +selects a larger single view. Character mode is still a low-resolution preview. + +For actual image pixels, use `--renderer iterm` (iTerm2 / WezTerm / VS Code with +`terminal.integrated.enableImages: true`) or `--renderer kitty`. Native mode +encodes original-resolution pixels as PNG; the terminal fits the display without +reducing the transmitted image to text-cell resolution. `auto` recognizes iTerm2, +WezTerm and Kitty environment markers; unknown terminals and multiplexers retain +the ANSI fallback. VS Code needs an explicit `--renderer iterm` after its setting +is enabled. Native protocol encoding is tested; visual compatibility still needs +to be checked in the user's terminal. Use a direct terminal outside tmux/screen +if image passthrough has not been configured. Redirected output always stays text. + +Existing CLI processes keep their original interval and renderer: exit with Ctrl+C +and restart to pick up changes. Evaluation processes need no restart. + +The user's Claude development terminal (`TERM_PROGRAM=claude-desktop`) displayed +an empty image area with the iTerm transport. In that environment, even an explicit +`--renderer iterm` now falls back to ANSI with a visible explanation. This avoids +blank frames but does not provide native image detail. Use `--camera main` for a +larger single-camera preview; original-resolution viewing needs an image-capable +viewer. No Claude terminal setting enabling inline images has been verified. diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/agent/images.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/agent/images.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d89bbfa64e5913756c7b7920491d36805b7839 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/agent/images.py @@ -0,0 +1,47 @@ +"""Image references and encoding (JPEG bytes are what the model sees and what is saved to disk).""" +import base64 +import io +from dataclasses import dataclass +from typing import Any, Optional + +import numpy as np + + +@dataclass +class ImageRef: + camera: str # agent-facing camera name ("agentview" / "wrist") + array: Any = None # uint8 HxWx3 + label: str = "" + path: Optional[str] = None # where the encoded image was saved + jpeg: Optional[bytes] = None # encoded bytes actually sent to the model + + def encoded(self, quality=90): + if self.jpeg is None: + if self.array is None and self.path: + with open(self.path, "rb") as f: + self.jpeg = f.read() + else: + self.jpeg = encode_jpeg(self.array, quality) + return self.jpeg + + def data_url(self, quality=90): + return "data:image/jpeg;base64," + base64.b64encode(self.encoded(quality)).decode("ascii") + + @property + def size(self): + return None if self.array is None else tuple(np.asarray(self.array).shape[:2]) + + +def encode_jpeg(arr, quality=90): + from PIL import Image + buf = io.BytesIO() + Image.fromarray(np.asarray(arr, dtype=np.uint8)).save(buf, format="JPEG", quality=int(quality)) + return buf.getvalue() + + +def resize(arr, res): + from PIL import Image + arr = np.asarray(arr, dtype=np.uint8) + if arr.shape[0] == res and arr.shape[1] == res: + return arr + return np.asarray(Image.fromarray(arr).resize((res, res), Image.BILINEAR)) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/agent/tools.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/agent/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..51e4a2a2feaa238548d752308aca541e6ad416fb --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/agent/tools.py @@ -0,0 +1,392 @@ +"""Agent-facing tool interface on top of `Skills`. + +Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps +acting on every commanded position. Proprioception is reported in the robot's own (possibly +miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the +commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and +the privileged `locate` tool are in the true world frame. + +Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in +`required`, optional ones nullable, no additional properties). +""" +import json +import math +import time +from dataclasses import dataclass, field + +import numpy as np + +from .. import envs +from . import camera as C +from .images import ImageRef + +TABLE_Z = envs.TABLE_Z +# Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are +# clipped and the report says so. +WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005]) +WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50]) +SPEED_RANGE = (0.02, 1.0) +PUSH_DIST_RANGE = (0.0, 0.40) +RUNUP_RANGE = (0.02, 0.30) + +ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push") + + +def _num(desc): + return {"type": "number", "description": desc} + + +def _opt_num(desc): + return {"type": ["number", "null"], "description": desc} + + +def _fn(name, desc, props=None): + props = props or {} + return dict(name=name, description=desc, + parameters={"type": "object", "properties": props, "required": list(props), + "additionalProperties": False}) + + +def tool_specs(privileged_locate=False, object_names=None, image_res=512): + """Backend-neutral tool list: [{name, description, parameters}].""" + specs = [ + _fn("move_to", + "Move the gripper's grasp point (midway between the fingertips) in a straight line to the world " + "position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper " + "opening is not changed. Returns whether the target was reached, the end-effector position, gripper " + "width, whether an object is held and whether the arm touched an object during the motion.", + {"x": _num("target x, metres (world frame; +x away from the robot)"), + "y": _num("target y, metres (world frame; +y to the robot's left)"), + "z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"), + "yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world " + "y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger " + "gripper is symmetric): the controller uses the equivalent angle closest to the current " + "yaw within +-113 deg; the report gives the yaw actually used"), + "speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows " + "(about 0.6 m/s)")}), + _fn("open_gripper", "Open the gripper fully (the arm holds its position)."), + _fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."), + _fn("push", + "Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres " + "behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) " + "through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The " + "gripper is rotated automatically to a fixed orientation relative to the push direction.", + {"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"), + "y": _num("y of that point, m"), + "dir_x": _num("x component of the push direction (normalised internally)"), + "dir_y": _num("y component of the push direction"), + "distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"), + "speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"), + "z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} " + "(2 cm above the table)"), + "runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer " + "run-up lets the gripper reach the commanded speed before contact.")}), + _fn("get_observation", + "Return the current camera images (agentview and wrist) and the robot's proprioceptive state."), + _fn("pixel_to_world", + f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel " + f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the " + f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that " + f"pixel and its height above the table.", + {"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"}, + "u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}), + _fn("done", + "Finish the current attempt. Call this when you believe the task is complete (or you want to stop). " + "Give a short reason: what you did and whether you think it worked.", + {"reason": {"type": "string", "description": "short explanation"}}), + ] + if privileged_locate: + names = list(object_names or []) + prop = {"type": "string", "description": "object name"} + if names: + prop["enum"] = names + specs.insert(-1, _fn("locate", + "PRIVILEGED (ablation): return the true world position of an object's origin and its " + "axis-aligned bounding box.", {"object_name": prop})) + return specs + + +@dataclass +class ToolResult: + name: str + args: dict + ok: bool + report: dict + images: list = field(default_factory=list) + ended: bool = False + wall_s: float = 0.0 + sim_steps: int = 0 + + def text(self): + return json.dumps(self.report, separators=(", ", ": "), default=_json_default) + + +def _json_default(o): + if isinstance(o, (np.floating,)): + return float(o) + if isinstance(o, (np.integer,)): + return int(o) + if isinstance(o, np.ndarray): + return o.tolist() + if isinstance(o, (np.bool_,)): + return bool(o) + raise TypeError(type(o)) + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class ContactTracker: + """Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control + step is 25 substeps; a fast push touches the object for less than one control step, so checking only at + control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the + wrapper only reads contacts and dispatches to the currently active tracker.""" + + def __init__(self, env): + self.env = env + m = env.sim.model + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.names = [] + self.obj_of = np.full(m.ngeom, -1, int) + for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}): + try: + ids = envs.obj_geom_ids(env, name) + except Exception: # fixtures without contact geoms + continue + self.obj_of[ids] = len(self.names) + self.names.append(name) + self.touched = set() + sim = env.sim + if not getattr(sim, "_lff_step_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lff_tracker", None) + if t is not None: + t.check() + sim.step = step + sim._lff_step_wrapped = True + sim._lff_tracker = self + + def reset(self): + self.touched = set() + + def check(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]]) + for i in set(hit[hit >= 0].tolist()): + self.touched.add(self.names[i]) + + +def parse_args(raw): + if raw is None: + return {} + if isinstance(raw, dict): + return dict(raw) + raw = raw.strip() + return json.loads(raw) if raw else {} + + +class ToolExecutor: + """Executes agent tool calls on a task whose instance has just been reset (task.sk is live).""" + + def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False, + grasp_report="bool", jpeg_quality=90, image_sink=None): + self.task = task + self.inst = inst + self.env = task.env + self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy + self.image_res = int(image_res) + self.cams = tuple(cams) + self.privileged_locate = privileged_locate + self.grasp_report = grasp_report # "bool" | "name" | "none" + self.jpeg_quality = jpeg_quality + self.image_sink = image_sink # callable(ImageRef) -> path (saves the image) + self.objects = list(self.env.objects_dict) + self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched + self._depth_cache = {} + self.n_calls = 0 + + # ------------------------------------------------------------------ state + def eef_yaw_deg(self): + R = self.sk.eef_mat() @ self.sk.R0.T + return math.degrees(math.atan2(R[1, 0], R[0, 0])) + + def held(self): + names = [o for o in self.objects if self.sk.holding(o)] + return names + + def _holding_field(self, names): + if self.grasp_report == "name": + return names[0] if names else None + if self.grasp_report == "none": + return None + return bool(names) + + def proprio(self): + believed = self.sk.eef_pos() - self.sk.bias + p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1), + gripper="closed" if self.sk.grip > 0 else "open", + gripper_width_m=round(self.sk.gripper_width(), 4)) + if self.grasp_report != "none": + p["holding_object"] = self._holding_field(self.held()) + return p + + def render(self, cam, res=None): + res = res or self.image_res + return envs.render(self.env, C.mj_cam(cam), res) + + def observe(self, label=""): + imgs = [] + for cam in self.cams: + ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip()) + if self.image_sink is not None: + self.image_sink(ref) + imgs.append(ref) + self._depth_cache = {} + return imgs + + # ------------------------------------------------------------------ dispatch + def call(self, name, raw_args): + t0 = time.time() + n0 = self.sk.n_steps + self.n_calls += 1 + try: + args = parse_args(raw_args) + except Exception as e: + return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"), + wall_s=time.time() - t0) + fn = getattr(self, f"_t_{name}", None) + if fn is None or (name == "locate" and not self.privileged_locate): + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + try: + res = fn(**args) + except TypeError as e: + res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}")) + except ValueError as e: + res = ToolResult(name, args, False, dict(ok=False, error=str(e))) + res.args = args + res.wall_s = time.time() - t0 + res.sim_steps = self.sk.n_steps - n0 + if res.sim_steps: + self._depth_cache = {} + hook = getattr(self.task, "on_agent_tool", None) + if hook is not None: + hook(self.inst, name, args, res.report) + drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped) + if drain is not None: + ev = drain() + if ev: + res.report["events"] = list(ev) + return res + + # ------------------------------------------------------------------ helpers + def _clip_xyz(self, xyz): + xyz = np.asarray(xyz, float) + if not np.all(np.isfinite(xyz)): + raise ValueError("non-finite coordinates") + c = np.clip(xyz, WS_LO, WS_HI) + return c, (None if np.allclose(c, xyz) else _r(c)) + + @staticmethod + def _clip(v, lo_hi, what): + v = float(v) + if not math.isfinite(v): + raise ValueError(f"{what} must be finite") + return float(np.clip(v, *lo_hi)) + + def _action_report(self, name, extra=None): + names = self.held() + rep = dict(ok=True, tool=name) + if extra: + rep.update(extra) + rep.update(self.proprio()) + if self.grasp_report == "name": + rep["touched_objects"] = sorted(self.tracker.touched) + elif self.grasp_report == "bool": + rep["touched_object"] = bool(self.tracker.touched) + rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2) + return rep + + # ------------------------------------------------------------------ tools + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt, clipped = self._clip_xyz([x, y, z]) + spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed") + self.tracker.reset() + rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi + extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1)) + if clipped: + extra["target_clipped_to"] = clipped + return ToolResult("move_to", {}, True, self._action_report("move_to", extra)) + + def _t_open_gripper(self): + self.tracker.reset() + self.sk.set_gripper(False) + return ToolResult("open_gripper", {}, True, self._action_report("open_gripper")) + + def _t_close_gripper(self): + self.tracker.reset() + self.sk.set_gripper(True) + return ToolResult("close_gripper", {}, True, self._action_report("close_gripper")) + + def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None): + d = np.array([float(dir_x), float(dir_y)]) + if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6: + raise ValueError("push direction must be a non-zero vector") + start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z]) + dist = self._clip(distance, PUSH_DIST_RANGE, "distance") + spd = self._clip(speed, SPEED_RANGE, "speed") + pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup") + self.tracker.reset() + rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre) + extra = dict(sweep_reached=bool(rep["reached"])) + if clipped: + extra["start_clipped_to"] = clipped + return ToolResult("push", {}, True, self._action_report("push", extra)) + + def _t_get_observation(self): + imgs = self.observe(label="requested") + return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()), + images=imgs) + + def _t_pixel_to_world(self, camera, u, v): + cam = str(camera) + if cam not in C.CAMERAS: + raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}") + if cam not in self._depth_cache: + self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res) + r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam]) + rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]), + height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4)) + if not r["valid"]: + rep["warning"] = "pixel shows the far background; the point is unreliable" + return ToolResult("pixel_to_world", {}, True, rep) + + def _t_locate(self, object_name): + if object_name not in self.env.objects_dict: + raise ValueError(f"unknown object {object_name!r}; known: {self.objects}") + lo, hi = self._aabb(object_name) + p = envs.obj_pos(self.env, object_name) + return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo), + bbox_max=_r(hi))) + + def _aabb(self, name): + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + h = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h) + return lo, hi + + def _t_done(self, reason=""): + return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..c629a484a13c5208e9e5f113b943b46219a5bffd --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-sonnet-5-5|high", + "fingerprint_sha256": "a8c04b0dca902885e52e7e5680c1cf8b782469e79c518f83b72249342285bfb0", + "written": "2026-10-21 05:19:29", + "summary": { + "system_chars": 5629, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-sonnet-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l1_bias.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l1_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..a5743522e389d8640257a0cbab03aa8e7df7dd86 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l1_bias.py @@ -0,0 +1,390 @@ +"""L1-A bias_place: pick up the cream cheese and put it into the bowl, with a miscalibrated arm. + +Level L1 (action fine-tuning): the method (top-down pick across the cheese's short side, carry, release +above the bowl) and the scene understanding are right; only execution precision is off. + +Hidden variable: a fixed calibration offset b = r (cos th, sin th, 0), r ~ U[R_MIN, R_MAX], th ~ U[0, 2 pi), +added to every commanded gripper position (`Skills(bias=b)`). The agent never sees b; positions reported +back to it must be in the commanded frame (`TrackedSkills.reported_eef_pos`), otherwise b leaks. + +Robot: the gripper is a short-stroke parallel gripper (max opening GRIPPER_MAX_OPEN = 5.0 cm, e.g. a +Robotiq Hand-E; implemented by narrowing the Panda finger actuators' ctrlrange). The cream cheese is +4.27 cm wide, so the open fingers clear it by ~3.5 mm per side. + +Why the prior fails. Sent to the true cheese position, the gripper arrives b away. If the component of b +across the cheese (jaw-closing direction) exceeds ~0.7-1.0 cm (measured), a finger comes down on top of the +cheese, the hand stops ~1.5 cm too high and the jaws close above it -> missed grasp, visible in both +cameras. With the stock 8 cm Panda stroke the measured tolerance is ~2.4 cm, so most r in [2, 4] cm would +not fail; that is why the stroke is reduced. The component of b along the cheese does not matter much +(the finger pads can grip anywhere along its 8.1 cm length, and the in-hand offset cancels at the place +because the same b is added there), and the bowl is forgiving. + +What has to be learned: the F2 feedback reports where the gripper closed relative to the cheese's centre +(forward/backward, left/right in the robot frame). That offset is b itself, so after one failure b can be +estimated and subtracted from every commanded position (pick and place alike). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CHEESE, BOWL = "cream_cheese_1", "akita_black_bowl_1" +JUICE = "orange_juice_1" +DISTRACTORS = ("butter_1", "chocolate_pudding_1", JUICE) +ALL = (CHEESE, BOWL) + DISTRACTORS +NAMES = {CHEESE: "cream cheese", BOWL: "bowl", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + JUICE: "orange juice carton"} +# descriptive names for the indirect variant (same wording as l2_knock_restore where objects overlap) +DESCR = {CHEESE: "blue box", BOWL: "grey bowl", "butter_1": "small orange box", "chocolate_pudding_1": "brown box", + JUICE: "tall juice carton"} +# Cream cheese collision box: 8.12 x 4.27 x 1.79 cm, lying flat, long side along its x axis. +# Realistic masses (LIBERO's are 5-10 g): a 6 g cheese is shoved aside by a finger landing on its edge. +MASS = {CHEESE: 0.227, "butter_1": 0.250, "chocolate_pudding_1": 0.200, BOWL: 0.300} + +# finger tips (0.97 cm below the gripper site) just clear the table; the pads cover 0.6-1.8 cm of the cheese +Z_GRASP = envs.TABLE_Z + 0.0105 +Z_CARRY = envs.TABLE_Z + 0.20 # clears the 13 cm juice carton with the cheese hanging below the fingers +BOWL_RIM = 0.0505 # rim height of the akita bowl above its lowest point +BOWL_R_IN = 0.046 # inner radius of the bowl at the rim +RELEASE_ABOVE_RIM = 0.012 # gripper site above the rim at release (finger pads clear the rim) + +R_MIN, R_MAX = 0.025, 0.040 # bias magnitude range (m) +GRIPPER_MAX_OPEN = 0.050 # short-stroke gripper: max finger gap (m); the cheese is 4.27 cm wide +CHEESE_YAW_MAX = np.deg2rad(10) + + +HOME_XY = np.array([-0.21, 0.0]) # gripper xy at reset + + +def _seg_dist(p, a, b): + """distance from point p to segment ab (2-D)""" + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"y": np.array([np.cos(h), 0, np.sin(h), 0]), "z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + """wxyz quaternion product a*b""" + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def set_gripper_stroke(env, max_open): + """Limit the jaw opening: each finger's position actuator gets the range [0, max_open/2] (robosuite maps + the open/close command onto the actuator ctrlrange, so "open" now means max_open). The pad faces sit + 0.5 mm inside the joint position, hence the small correction.""" + m = env.sim.model + half = max_open / 2 + 0.0005 + a1, a2 = [m.actuator_name2id(a) for a in env.robots[0].gripper.actuators] + m.actuator_ctrlrange[a1] = [0.0, half] + m.actuator_ctrlrange[a2] = [-half, 0.0] + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +class TrackedSkills(Skills): + """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent): + where the gripper was and what the fingers touched when the jaws closed, and where the cheese was when + the jaws opened while holding it.""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self.events = [] + self.cheese_z0 = float(envs.obj_pos(env, CHEESE)[2]) + self.cheese_zmax = self.cheese_z0 + m = env.sim.model + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in ALL} + # where the cheese was before the gripper last touched it (the reference for the grasp offset, so that + # a finger shoving the cheese aside on the way down does not corrupt the measurement) + self.cheese_ref = envs.obj_pos(env, CHEESE) + + def reported_eef_pos(self): + """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything + shown to the agent must use this, never eef_pos(), which is the true position and reveals b.""" + return self.eef_pos() - self.bias + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist() # do not leak b through the report + return rep + + def touching(self): + """Objects the gripper is in contact with right now.""" + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.cheese_zmax = max(self.cheese_zmax, float(envs.obj_pos(self.env, CHEESE)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[CHEESE]): + self.cheese_ref = envs.obj_pos(self.env, CHEESE) + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), + cheese=envs.obj_pos(self.env, CHEESE).tolist(), + cheese_ref=np.asarray(self.cheese_ref).tolist(), touching=self.touching(), + cheese_top=envs.obj_max_z(self.env, CHEESE), step=self.n_steps)) + elif not close and self.grip > 0 and self.holding(CHEESE): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), + cheese=envs.obj_pos(self.env, CHEESE).tolist(), + bowl=envs.obj_pos(self.env, BOWL).tolist(), step=self.n_steps)) + return super().set_gripper(close, steps) + + +@register_task +class BiasPlace(LFFTask): + name = "l1_bias_place" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + # LIBERO calls the bowl "akita black bowl", but under our renderer it looks silver-grey with a gold rim, so + # the colour is not used in the direct instruction (there is only one bowl). + instruction = "Pick up the cream cheese and put it into the bowl." + instruction_indirect = "Pick up the flat blue box with the white oval label and put it into the round grey bowl." + pick_lift_min = 0.03 # cheese counted as picked up if it rose this much + + # ------------------------------------------------------------ scene + def make_bddl(self): + # regions are only used by LIBERO's reset-time sampler (the layout is overridden in apply_instance) + objs = [(CHEESE, "cream_cheese", "cheese_region", (-0.16, -0.22, -0.14, -0.20)), + (BOWL, "akita_black_bowl", "bowl_region", (-0.01, 0.15, 0.01, 0.17)), + ("butter_1", "butter", "butter_region", (-0.16, 0.10, -0.14, 0.12)), + ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.04, -0.17, 0.06, -0.15)), + (JUICE, "orange_juice", "juice_region", (-0.15, -0.03, -0.13, -0.01))] + return write_bddl(self.name, self.instruction, objs) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # LIBERO's own upright orientation of every object, read off the reset state + self._base_quat = {n: envs.obj_quat(self.env, n) for n in ALL} + + def _place(self, name, xy, yaw): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], envs.TABLE_Z + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + c = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)]) + bowl = np.array([rng.uniform(-0.15, 0.08), rng.uniform(-0.24, 0.24)]) + if np.linalg.norm(bowl - c) < 0.20: + continue + placed = [c, bowl] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.10), rng.uniform(-0.27, 0.27)]) + if any(np.linalg.norm(p - o) < (0.13 if k < 2 else 0.11) for k, o in enumerate(placed)): + continue + if name == JUICE: + # the 13 cm carton is taller than the hand when it grasps / releases: the Panda hand spans + # +-10.5 cm across the jaws, so keep the carton >= 17 cm from the cheese and the bowl; + # it must also not hide them from the front camera, and must stay >= 10 cm off the + # straight paths home->cheese, home->bowl and cheese->bowl + if np.linalg.norm(p - c) < 0.17 or np.linalg.norm(p - bowl) < 0.17: + continue + if any(p[0] > t[0] - 0.03 and abs(p[1] - t[1]) < 0.14 for t in (c, bowl)): + continue + if any(_seg_dist(p, a, b) < 0.10 for a, b in ((c, bowl), (HOME_XY, c), (HOME_XY, bowl))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + psi = float(rng.uniform(-CHEESE_YAW_MAX, CHEESE_YAW_MAX)) + n = np.array([-np.sin(psi), np.cos(psi)]) # jaw-closing direction for a grasp across the cheese + l = np.array([np.cos(psi), np.sin(psi)]) + r = rng.uniform(R_MIN, R_MAX) + th = rng.uniform(0, 2 * np.pi) + b = np.array([r * np.cos(th), r * np.sin(th)]) + return dict(seed=int(seed), cheese_xy=c.round(5).tolist(), cheese_yaw=psi, bowl_xy=bowl.round(5).tolist(), + distractors=dis, bias=[float(b[0]), float(b[1]), 0.0], bias_r=float(r), bias_theta=float(th), + bias_across=float(b @ n), bias_along=float(b @ l)) + + def apply_instance(self, inst): + set_gripper_stroke(self.env, GRIPPER_MAX_OPEN) + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self._place(CHEESE, inst["cheese_xy"], inst["cheese_yaw"]) + self._place(BOWL, inst["bowl_xy"], 0.0) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def skill_bias(self, inst): + return np.array(inst["bias"], float) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = TrackedSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + self.start_pos = {n: envs.obj_pos(self.env, n) for n in ALL} + return self.sk + + # ------------------------------------------------------------ outcome + def in_bowl(self): + k = envs.obj_pos(self.env, BOWL) + c = envs.obj_pos(self.env, CHEESE) + base = envs.obj_min_z(self.env, BOWL) + return bool(np.linalg.norm(c[:2] - k[:2]) < BOWL_R_IN and c[2] < base + BOWL_RIM + and envs.obj_upright_cos(self.env, BOWL) > 0.9 and base < envs.TABLE_Z + 0.01) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + k = envs.obj_pos(self.env, BOWL) + c = envs.obj_pos(self.env, CHEESE) + held = sk.holding(CHEESE) + success = bool(self.in_bowl() and not held) + picked = sk.cheese_zmax > sk.cheese_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + end_off = c[:2] - k[:2] + moved = {n: float(np.linalg.norm(envs.obj_pos(self.env, n)[:2] - self.start_pos[n][:2])) + for n in DISTRACTORS} + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), + cheese_end=c.round(4).tolist(), bowl_end=k.round(4).tolist(), end_offset=end_off.round(4).tolist(), + grasp_offset=None, release_offset=None, touched_at_close=None, + distractors_moved_cm={n: round(100 * v, 1) for n, v in moved.items()}) + grasp_txt = "" + if last_close is not None: + go = np.array(last_close["eef"][:2]) - np.array(last_close["cheese_ref"][:2]) + out["grasp_offset"] = go.round(4).tolist() + out["touched_at_close"] = last_close["touching"] + out["cheese_pushed_cm"] = round(100 * float(np.linalg.norm( + np.array(last_close["cheese"][:2]) - np.array(last_close["cheese_ref"][:2]))), 1) + grasp_txt = (f"The gripper closed {dir_words(*go)} of the centre of the cream cheese (measured where " + f"the cheese was before the fingers touched it)") + if releases: + r = releases[-1] + out["release_offset"] = (np.array(r["cheese"][:2]) - np.array(r["bowl"][:2])).round(4).tolist() + if success: + out["failure"] = None + detail = "The cream cheese is in the bowl." + if grasp_txt: + detail += f" {grasp_txt}." + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the cream cheese was not picked up." + else: + on = [NAMES[n] for n in last_close["touching"] if n != CHEESE] + why = "" + if on: + why = (f" A finger landed on top of the {' and the '.join(on)} instead of going down beside the " + f"cheese, so the jaws closed above the cheese.") + elif CHEESE in last_close["touching"] and not sk.holding(CHEESE): + why = " A finger came down on top of the cream cheese instead of beside it." + elif not last_close["touching"] and last_close.get("cheese_top") is not None: + above = last_close["eef"][2] - envs.FINGERTIP_BELOW_SITE - last_close["cheese_top"] + if above > 0.002: # closed in the air, entirely above the cheese + why = (f" The fingers closed in the air without touching anything: the fingertips were " + f"{100 * above:.1f} cm above the top of the cream cheese.") + detail = f"{grasp_txt} and did not pick it up.{why} The cream cheese is still on the table." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt} and picked it up, but the cream cheese is still in the gripper." + elif releases: + out["failure"] = "missed_place" + detail = (f"{grasp_txt} and picked it up. When the gripper opened, the cream cheese was " + f"{dir_words(*out['release_offset'])} of the bowl's centre; it did not end up in the bowl " + f"(it is now {dir_words(*end_off)} of the bowl's centre).") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt} and picked it up, but it slipped out of the gripper before it was released; " + f"it is now {dir_words(*end_off)} of the bowl's centre.") + out["detail"] = detail + ind = detail + for k in (JUICE, "chocolate_pudding_1", "butter_1", CHEESE, BOWL): # longest names first + ind = ind.replace(NAMES[k], DESCR[k]) + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + """F0: nothing, F1: success flag, F2: measured offsets. `indirect` uses descriptive object names.""" + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Top-down pick across the cheese's short side, carry, release above the bowl. + params['offset'] (xy) is the policy's own correction, added to every commanded position.""" + sk = self.sk + off = np.array(params.get("offset", [0.0, 0.0]), float) + c = envs.obj_pos(self.env, CHEESE) # perfect perception of the current scene + yaw = self.grasp_yaw() + k = envs.obj_pos(self.env, BOWL) + z_rel = envs.obj_min_z(self.env, BOWL) + BOWL_RIM + RELEASE_ABOVE_RIM + g, p = c[:2] + off, k[:2] + off + sk.set_gripper(False, steps=8) + sk.move_to([g[0], g[1], Z_CARRY], yaw=yaw) # approach from above, clear of the 13 cm carton + sk.move_to([g[0], g[1], Z_GRASP + 0.08], tol=0.002) + sk.move_to([g[0], g[1], Z_GRASP], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_CARRY], speed=0.3) + if not sk.holding(CHEESE): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([p[0], p[1], Z_CARRY], tol=0.003) + sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100) + sk.set_gripper(False, steps=12) + sk.move_to([p[0], p[1], Z_CARRY], speed=0.3) + + def grasp_yaw(self): + """Gripper yaw that closes the jaws across the cheese's short side (yaw 0 closes along world y).""" + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, CHEESE)].reshape(3, 3) + a = np.arctan2(xmat[1, 0], xmat[0, 0]) # direction of the cheese's long (x) axis + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + def default_params(self, inst): + return dict(offset=[0.0, 0.0]) + + def oracle_params(self, inst): + return dict(offset=(-np.array(inst["bias"][:2])).tolist()) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported grasp offset (where the gripper closed relative to the cheese's + centre) measures the calibration offset; accumulate it into the correction subtracted from every + commanded position. If the gripper never closed, fall back to the release offset.""" + last = history[-1] + off = np.array(last["params"]["offset"], float) + o = last["outcome"] + if o.get("grasp_offset") is not None: + off = off - np.array(o["grasp_offset"]) + elif o.get("release_offset") is not None: + off = off - np.array(o["release_offset"]) + return dict(offset=off.round(4).tolist()) + + blind_sigma = 0.005 + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the targets; no use of history.""" + return dict(offset=rng.normal(0.0, self.blind_sigma, 2).round(4).tolist()) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l5_slide.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l5_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee239b7ba2793288aeaaa5e5d4f0a5b11c835f5 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l5_slide.py @@ -0,0 +1,577 @@ +"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone. + +Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the +same for every mu. With the default push speed the cube overshoots on slippery instances and stops +short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard +to push next time (cf. MemMimic push_cube, iterative pushing). + +Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt +(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that +carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule +also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The +loophole is now closed by the success rule instead: + +Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there +by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts +checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with +nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push +into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in +front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm. + +Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged +when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside). +`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then +succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the +arm's reach (the attempt is not ended for it). + +Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance +the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre). +SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX), +so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time. + +Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview +camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far +edge by up to ~1 cm covers the far green line but shows < 2 px of red beyond it in the 512 x 512 image, which looks like +"inside / on the line" (self-test: 0.8 cm past the inner edge looked inside). So on the far side the cube may now lie on +the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to +TOL_PAST = 2.0 cm past the square's centre (front face <= 4 mm beyond the line's outer edge). From 2.0 cm on, every one +of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely +inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides +the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +CUBE = "cube_1" +CUBE_HALF = 0.02 +D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long +STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike +TOUCH_MOVE = 0.001 # a contact episode moved the cube if the cube ends >= 1 mm (3-D) from where it was at its start +EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode +V_REST, W_REST = 0.003, 0.05 # cube at rest: linear speed below 3 mm/s and angular speed below 0.05 rad/s ... +REST_SUB = 25 # ... for 25 consecutive substeps (50 ms) +WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest +ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF +OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table +REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable + + +class CubeWatch: + """Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it). + + contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed + EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was + when the episode began, or still moving. + release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide + began (None while the robot has never moved the cube). + strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to + rest (or when the robot touches it again before that: result "interrupted").""" + + def __init__(self, env, target_xy, tol_short, tol_past, tol_across): + m = env.sim.model + self.env = env + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.is_cube = np.zeros(m.ngeom, bool) + self.is_cube[envs.obj_geom_ids(env, CUBE)] = True + self.qa, self.da = envs.free_joint_addr(env, CUBE) + self.target = np.asarray(target_xy, float) + self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside + self.n_sub = 0 + self.ep = None # open contact episode + self.gap = 0 + self.quiet = 0 # consecutive substeps at rest + self.release = None + self.slide = None # free slide in progress: where it started (cube at the episode start) and was released + self.moves = [] # closed contact episodes that moved the cube + self.strikes = [] + + # ------------------------------------------------------------ state + def pos(self): + return self.env.sim.data.qpos[self.qa:self.qa + 3].copy() + + def at_rest(self): + qv = self.env.sim.data.qvel[self.da:self.da + 6] + return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST) + + def judge(self, p): + """Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off). + in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it.""" + along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1]) + if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE: + return along, across, "off" + short, past, beside = self.tol + if -short <= along <= past and abs(across) <= beside: + return along, across, "in" + if along > past: + return along, across, "past" + if along < -short: + return along, across, "short" + return along, across, "beside" + + # ------------------------------------------------------------ per substep + def substep(self): + d = self.env.sim.data + n = d.ncon + touch = False + if n: + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1]))) + self.n_sub += 1 + p = self.pos() + rest = self.at_rest() + self.quiet = self.quiet + 1 if rest else 0 + if touch: + if self.ep is None: + if self.slide is not None: + self._end_slide(p, interrupted=not rest) + self.ep = dict(start=p, sub0=self.n_sub) + self.ep["last"] = p + self.ep["sub1"] = self.n_sub + self.gap = 0 + elif self.ep is not None: + self.gap += 1 + if self.gap >= EP_GAP: + self._close(p, rest) + if self.ep is None and self.slide is not None and self.quiet >= REST_SUB: + self._end_slide(p, interrupted=False) + + def _close(self, p, rest): + ep, self.ep = self.ep, None + if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest: + return # touched a resting cube and left it where it was + self.release = ep["last"][:2].copy() + self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(), + release=ep["last"].round(4).tolist())) + self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"]) + + def _end_slide(self, p, interrupted): + s, self.slide = self.slide, None + free = float(np.linalg.norm(p[:2] - s["release"][:2])) + if free < STRIKE_MIN: + return # a push or a put-down, not a strike + along, across, res = self.judge(p) + self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(), + release=s["release"].round(4).tolist(), rest=p.round(4).tolist(), + pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2), + free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2), + across_err_cm=round(100 * across, 2), + result="interrupted" if interrupted else res, + missed=bool(not interrupted and res != "in"))) + + def flush(self): + """End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact + has moved it (then the cube's current free slide is 0).""" + p = self.pos() + if self.ep is not None: + if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest(): + self.release = p[:2].copy() + self.slide = None + return True + return False + if self.slide is not None and self.at_rest(): + self._end_slide(p, interrupted=False) + return False + + +def _install_watch(sim, watch): + """Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker; + it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one + control step, so contact checks at control steps alone would miss it.""" + if not getattr(sim, "_lff_slide_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + w = getattr(sim, "_lff_slide_watch", None) + if w is not None: + w.substep() + sim.step = step + sim._lff_slide_wrapped = True + sim._lff_slide_watch = watch + + +class SlideSkills(Skills): + """Skills whose motion commands return only once the cube has come to rest (see the module docstring).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self._qa, self._da = envs.free_joint_addr(env, CUBE) + self.waits = [] # (control step, steps waited) for every command that had to wait + + def cube_moving(self): + qv = self.env.sim.data.qvel[self._da:self._da + 6] + return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST) + + def wait_cube_rest(self): + """Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed. + No wait if the cube is already at rest or is held (it then moves with the arm).""" + if not self.cube_moving() or self.holding(CUBE): + return 0 + p, R = self.eef_pos(), self._R() + quiet = 0 + for k in range(WAIT_MAX): + self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + quiet = 0 if self.cube_moving() else quiet + 1 + if quiet >= 2: + break + self.waits.append((self.n_steps, k + 1)) + return k + 1 + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + +INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm +LINE_W = 0.006 +# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of +# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre +# <= 2.0 cm past it, i.e. the front face up to 4 mm beyond the line, which in the 512 x 512 agentview is < 2 px of red +# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19). +TOL_PAST = 0.020 + + +def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W, + line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions).""" + o = inner_half + line_w + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba), + ((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba), + ((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(model_name, g, 0.0012, o) + + +Z_PUSH = envs.TABLE_Z + 0.02 +V_MIN, V_MAX = 0.12, 0.60 +Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table) + + +@register_task +class SlideToTarget(LFFTask): + name = "l5_slide_to_target" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Reason", "Utilize") + # no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there) + instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green " + "square marked on the table. On the side of the square nearest the robot and on its left and " + "right, no part of the cube may lie on or beyond the green border line. On the far side, away from " + "the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. " + "The cube must slide the last part of the way on its own: after it leaves the gripper it has to " + f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the " + "square.") + instruction_indirect = instruction + tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm) + tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST) + runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact + tol_across = INNER_HALF - CUBE_HALF + + def make_bddl(self): + cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1), + density=1000)) + # static fixture (no joint): a free body without collisions would fall through the table + zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False) + objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))] + fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, self.instruction, objs, fixtures=fixtures) + + def apply_instance(self, inst): + m = self.env.sim.model + zone = self.env.fixtures_dict["zone_1"] + # the target zone is a flat marker: no collisions + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("zone_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + x0, y0 = inst["cube_xy"] + envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001]) + bid = m.body_name2id(zone.root_body) + m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + envs.set_friction(self.env, "cube_1", inst["mu"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + x0, y0 = inst["cube_xy"] + self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past, + self.tol_across) + _install_watch(self.env.sim, self.watch) + self.sk = SlideSkills(self.env, recorder=recorder) + return self.sk + + @staticmethod + def max_reach(mu): + """Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m): + mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm.""" + return 0.0103 / mu ** 0.95 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: # reject instances the top speed cannot reach (keeps every instance solvable) + inst = dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))], + target_dist=float(rng.uniform(0.05, 0.12)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10))))) + if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]): + return inst + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 40) + w = self.watch + for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest + if w.at_rest(): + break + envs.settle(self.env, 5) + touching = w.flush() + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, CUBE) + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + _, _, where = w.judge(w.pos()) + inside = where == "in" + at_rest = w.at_rest() + free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0 + slid = bool(w.release is not None and not touching and free >= D_MIN) + success = bool(inside and at_rest and slid) + strikes = w.strikes + n_missed = sum(s["missed"] for s in strikes) + from ..agent.tools import WS_HI, WS_LO + reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN)) + irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach) + + parts = [] + if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN: + parts.append("The cube was not pushed.") + if c[2] < OFF_TABLE_Z: + parts.append("The cube fell off the table.") + else: + state = {"in": "in the square", "past": "it sticks out beyond the far green line", + "short": "it sticks out past the edge of the square nearest the robot"}.get(where, + "not in the square") + if along > 0: + parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).") + else: + parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square " + f"({state}).") + if abs(across) > self.tol_across: + parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} " + f"(robot's view).") + if where == "off" and c[2] > OFF_TABLE_Z: + parts.append("It is not resting on the table.") + if inside and not at_rest: + parts.append("It was still moving when the attempt ended.") + if touching: + parts.append("The gripper was still touching (or holding) the cube when the attempt ended.") + elif inside and w.release is not None and free < D_MIN: + parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide " + f"at least {100 * D_MIN:.0f} cm.") + if success: + failure = None + elif w.release is None and not inside: + failure = "not_touched" + elif not inside: + failure = "position" + elif not at_rest: + failure = "not_at_rest" + else: + failure = "slide_too_short" + out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts), + inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2), + release_xy=None if w.release is None else w.release.round(4).tolist(), + touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes), + n_missed_strikes=int(n_missed), trap_fired=n_missed > 0, + recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable, + strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure) + return out + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the + point of contact, lift (the move returns once the cube has come to rest).""" + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.set_gripper(True, steps=5) + sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), + tol=0.01, max_steps=80) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3) + + def default_params(self, inst): + return dict(speed=0.30) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search + on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt).""" + pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history) + lo = [p for p in pts if p[1] < 0] + hi = [p for p in pts if p[1] > 0] + if lo and hi: + (v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0]) + v = v0 + (v1 - v0) * (-e0) / (e1 - e0) + elif hi: # always overshooting: slow down + v = min(p[0] for p in hi) * 0.7 + else: # always short: speed up + v = max(p[0] for p in lo) * 1.35 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on speed by simulating pushes (uses the true mu).""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(9): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + e = self.outcome(inst)["along_err"] + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + hi = mid + else: + lo = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) + + # ------------------------------------------------------------ scripted within-attempt correction + AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ... + AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command + RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short + + def _strike_here(self, speed): + """Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up + point + close, down, strike (returns at rest), lift.""" + c = envs.obj_pos(self.env, CUBE) + sk = self.sk + sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0) + sk.set_gripper(True, steps=5) + sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3) + return 4 + + def _carry_back(self, inst): + """Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands: + above it + open, down + close, lift, carry, down + open, lift.""" + c = envs.obj_pos(self.env, CUBE) + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0) + sk.set_gripper(False, steps=10) + sk.move_to([c[0], c[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([c[0], c[1], Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([x0, y0, Z_GRASP + 0.10]) + return 6 + + @staticmethod + def _plan_speed(want, pts): + """Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s + prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes + (or extrapolation from the two nearest, exponent clipped to [0.5, 3]).""" + pts = sorted((v, d) for v, d in pts if d > 0.002) + if not pts: + return 0.30 + if len(pts) == 1: + v, d = pts[0] + return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX)) + lo = [p for p in pts if p[1] <= want] + hi = [p for p in pts if p[1] > want] + if lo and hi: + (v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1]) + else: + (v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2] + if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6: + return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX)) + k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0)) + return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX)) + + def _adaptive_attempt(self, inst, pts): + """One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect + perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot, + a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed + planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square + or the next correction would not fit in the agent's command / motion budget.""" + x0, y0 = inst["cube_xy"] + tx = x0 + inst["target_dist"] + sk = self.sk + n0 = sk.n_steps + n_cmd, speeds, path = 0, [], [] + while True: + c = envs.obj_pos(self.env, CUBE) + want = tx - c[0] + near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01 + local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts] + speed = self._plan_speed(want, local) + n_cmd += self._strike_here(speed) + c1 = envs.obj_pos(self.env, CUBE) + pts.append((speed, float(c1[0] - c[0]), near_start)) + speeds.append(round(speed, 4)) + err, across = float(c1[0] - tx), float(c1[1] - y0) + path.append("strike") + if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across: + break + used_s = (sk.n_steps - n0) * DT + if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005: + if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S: + break + continue + if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S: + break + n_cmd += self._carry_back(inst) + path.append("carry_back") + return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd, + sim_s=round((sk.n_steps - n0) * DT, 1)) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects + within the attempt (_adaptive_attempt) and carries what it saw into the next attempt.""" + if kind != "adaptive": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + history, pts = [], [] + for a in range(k): + self.reset_instance(inst) + params = self._adaptive_attempt(inst, pts) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l6_sequence.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l6_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..3696302999af83efd1782ea6326db1f794452022 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l6_sequence.py @@ -0,0 +1,513 @@ +"""L6-C sequence_resume: weigh four items one by one in a given order; an emergency stop resets part of the work. + +Scene: four grocery items (cream cheese, butter, chocolate pudding, popcorn -- small flat boxes), each on its +own round pad (four identical dark pads, flat markers), and a scale (grey square platform, static fixture). +Pad / scale positions and the order are random per instance. + +Instruction: weigh the items one at a time in the given order. Weighing = put the item on the scale and let go; +the scale records a reading after the item has rested on it for 0.5 s and beeps. Then the item goes back on its +own pad before the next item is picked up. Every item must be weighed exactly once; the scale log cannot be +edited, so a second reading of an item or a reading out of turn is a terminal failure. + +Interruption ("emergency stop", once per episode, inside attempt 1): while the robot carries an item, the gripper +opens, a safety routine puts that item back on its own pad and the arm returns to its home pose. Hidden: how +many items had been weighed when it happened, w in {1..4} (uniform), and the phase: the carried item was on its +way to the scale (not yet weighed, phase A) or on its way back (already weighed, phase B); w = 4 is always +phase B. After the stop every item sits on its pad and the arm is at home: the picture looks like the start of +the task. Which item comes next (order[w], or "nothing, call done" for w = 4) is only in the agent's own history +(what it carried, whether the scale had beeped). + +Protocol: within (like l6_swap_interrupt). Events reported immediately (`drain_events`): the scale's beep after +every recorded reading, an error beep for a reading out of turn, and the emergency stop. F2 after `done` gives the +verdict, whether the log is complete, and which items are not on their pads (distance only), never how many +items have been weighed. + +Scripted references (perception = simulator state): + oracle privileged scale log: always weighs order[len(log)] next. + adaptive keeps its own record of readings (an item counts as weighed when the scale beeped while it lay on + it); after the stop it resumes from order[len(record)] (redoes the interrupted item in phase A, goes on + with the next one in phase B, calls done when all four are recorded). + naive memoryless continuation (1 attempt): the picture after the stop shows no progress; it guesses how far + it got (uniform over 0..4 items weighed) and continues from there. + blind memoryless restart (k attempts): starts the sequence over from the first item -> a second reading of + an already weighed item (repeated step). +Extra control (not in the acceptance table): `skip` counts items it *started* to weigh (pick-ups) instead of +readings: correct after a phase-B stop, skips the interrupted item after a phase-A stop. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import ROT_SCALE, _rot_err +from ..task_base import LFFTask, register_task +from .l6_swap import _pad_xml as _swap_pad_xml + +ITEMS = ["cream_cheese_1", "butter_1", "chocolate_pudding_1", "popcorn_1"] +CATS = {"cream_cheese_1": "cream_cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate_pudding", + "popcorn_1": "popcorn"} +NAME = {"cream_cheese_1": "cream cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + "popcorn_1": "popcorn"} +DESCR = {"cream_cheese_1": "the pale blue box with the oval logo", "butter_1": "the red box with white lettering", + "chocolate_pudding_1": "the dark brown box", "popcorn_1": "the blue-and-yellow box"} +N_ITEMS = len(ITEMS) +PADS = [f"pad_{i + 1}" for i in range(N_ITEMS)] +PAD_R = 0.055 +PAD_HALF_T = 0.0008 + +SCALE_HALF = 0.06 # platform half size (12 x 12 cm) +SCALE_BASE_HALF = 0.067 +SCALE_TOP = 0.020 # platform top above the table +SCALE_BASE_H = 0.012 +SCALE_RGBA = (0.78, 0.79, 0.80, 1.0) +SCALE_BASE_RGBA = (0.20, 0.20, 0.22, 1.0) + +BASE_X = -0.66 +REGION = (-0.27, 0.05, -0.27, 0.27) +REACH = 0.70 +PAD_MIN = 0.16 +SCALE_MIN = 0.175 +SUCC_R = 0.04 # item centre within 4 cm of its pad centre +GRASP_DZ = 0.012 # gripper-site height above the support surface for a top-down grasp of the flat boxes +Z_CARRY = envs.TABLE_Z + 0.15 +DWELL = 10 # control steps (0.5 s) at rest on the scale before a reading is recorded +LIFTED = 0.04 + + +def scale_xml(model_name): + parts = [((0, 0, SCALE_BASE_H / 2), (SCALE_BASE_HALF, SCALE_BASE_HALF, SCALE_BASE_H / 2), SCALE_BASE_RGBA), + ((0, 0, (SCALE_BASE_H + SCALE_TOP) / 2), (SCALE_HALF, SCALE_HALF, (SCALE_TOP - SCALE_BASE_H) / 2), + SCALE_RGBA)] + g = [] + for k, (pos, half, rgba) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(model_name, "\n".join(g), SCALE_TOP / 2, float(np.hypot(SCALE_BASE_HALF, SCALE_BASE_HALF))) + + +def _yaw_of(env, obj): + R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3) + yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x + return (yaw + np.pi / 2) % np.pi - np.pi / 2 + + +@register_task +class SequenceResume(LFFTask): + name = "l6_sequence_resume" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 100 # robot commands per attempt for agents (a VLM needs ~60-75) + max_attempts = 5 + _TEMPLATE = ("Weigh the four grocery items one at a time, in this order: {order}. To weigh an item, put it on " + "the grey scale and let go of it; the scale beeps when it has recorded the reading. Then put the " + "item back on its own round pad before you pick up the next item. Weigh every item exactly once: " + "the scale logs every reading, and the log cannot be edited.") + instruction = _TEMPLATE.format(order="(given per instance)") + instruction_indirect = instruction + inject = True + agent_object_names = [NAME[i] for i in ITEMS] + ["scale", "round pads"] + + def agent_instruction(self, inst, variant="direct"): + names = DESCR if variant == "indirect" else NAME + order = [names[o] for o in inst["order"]] + return self._TEMPLATE.format(order=", ".join(order[:-1]) + ", then " + order[-1]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + self._latch = None + orig_step = self.env.step + + def step(action): # per-control-step monitor (also for attempts driven by the agent harness) + if self._latch is not None: + action = self._homing_action() + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + pads = [register_generated(f"LffSeqPad{L}", _swap_pad_xml(f"lff_seq_pad_{L.lower()}")) for L in "ABCD"] + scale = register_generated("LffSeqScale", scale_xml("lff_seq_scale"), free=False) + objs = [(o, CATS[o], f"r{i}", (-0.26 + 0.15 * i - 0.01, -0.31, -0.26 + 0.15 * i + 0.01, -0.29)) + for i, o in enumerate(ITEMS)] + objs += [(PADS[i], pads[i], f"p{i}", (-0.26 + 0.15 * i - 0.01, 0.29, -0.26 + 0.15 * i + 0.01, 0.31)) + for i in range(N_ITEMS)] + fx = [("scale_1", scale, "scale_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, "Weigh the four items one at a time in the given order", objs, fx) # no ; in BDDL + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + pts = [] + while len(pts) < N_ITEMS + 1: + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if np.hypot(p[0] - BASE_X, p[1]) > REACH: + continue + pts.append(p) + scale, pads = pts[0], np.array(pts[1:]) + dp = [np.linalg.norm(pads[i] - pads[j]) for i in range(N_ITEMS) for j in range(i)] + if min(dp) >= PAD_MIN and min(np.linalg.norm(pads - scale, axis=1)) >= SCALE_MIN: + break + else: + raise RuntimeError("could not sample a layout") + order = [ITEMS[i] for i in rng.permutation(N_ITEMS)] + w = int(rng.integers(1, N_ITEMS + 1)) # items weighed when the stop happens + phase = "B" if w == N_ITEMS else str(rng.choice(["A", "B"])) + inst = dict(seed=int(seed), order=order, pads=pads.round(4).tolist(), scale_xy=scale.round(4).tolist(), + item_off=[[float(v) for v in rng.uniform(-0.008, 0.008, 2)] for _ in range(N_ITEMS)], + item_yaw=[float(v) for v in rng.uniform(-0.3, 0.3, N_ITEMS)], + stop_w=w, stop_phase=phase, trigger_dist=float(rng.uniform(0.05, 0.09)), + stop_off=[float(v) for v in rng.uniform(-0.008, 0.008, 2)], + stop_yaw=float(rng.uniform(-0.3, 0.3))) + inst["stop_item"] = order[w] if phase == "A" else order[w - 1] + self.instruction = self.agent_instruction(inst, "direct") # make_video prints task.instruction + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + for i, p in enumerate(inst["pads"]): + envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001]) + bid = m.body_name2id(self.env.fixtures_dict["scale_1"].root_body) + m.body_pos[bid] = [inst["scale_xy"][0], inst["scale_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + for i, o in enumerate(ITEMS): + p = np.asarray(inst["pads"][i]) + inst["item_off"][i] + envs.place_upright(self.env, o, p, inst["item_yaw"][i]) + self.env.sim.forward() + self._inst = inst + self.pad_of = {o: i for i, o in enumerate(ITEMS)} # item i starts on pad i (pad positions are random) + self.log = [] # scale readings (item names) + self.error = None + self.stop = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self._dwell = {o: 0 for o in ITEMS} + self._visit = {o: False for o in ITEMS} + self._prev = {} + self._latch = None + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + self._latch = None + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self.rest_dz = {o: float(envs.obj_pos(self.env, o)[2] - envs.TABLE_Z) for o in ITEMS} + self._prev = {o: envs.obj_pos(self.env, o) for o in ITEMS} + self._mon = True + return sk + + def go_home(self): + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ helpers + def scale_xy(self): + return np.asarray(self._inst["scale_xy"], float) + + def pad_xy(self, o): + return np.asarray(self._inst["pads"][self.pad_of[o]], float) + + def on_scale(self, o, p=None): + p = envs.obj_pos(self.env, o) if p is None else p + d = np.abs(p[:2] - self.scale_xy()) + return bool(d.max() <= SCALE_HALF and abs(p[2] - (envs.TABLE_Z + SCALE_TOP + self.rest_dz[o])) < 0.008) + + def on_own_pad(self, o): + p = envs.obj_pos(self.env, o) + return bool(np.linalg.norm(p[:2] - self.pad_xy(o)) <= SUCC_R + and abs(p[2] - (envs.TABLE_Z + self.rest_dz[o])) < 0.01 and not self.sk.holding(o)) + + # ------------------------------------------------------------ monitor: scale readings + emergency stop + def _monitor(self): + env = self.env + if self._latch is not None: + if len(self.sk.log) > self._latch and np.linalg.norm(self.sk.eef_pos() - self._home) < 0.01: + self._latch = None + for o in ITEMS: + p = envs.obj_pos(env, o) + still = np.linalg.norm(p - self._prev[o]) < 0.0008 + self._prev[o] = p + if self.on_scale(o, p): + if still and not self.sk.holding(o): + self._dwell[o] += 1 + if self._dwell[o] >= DWELL and not self._visit[o]: + self._visit[o] = True + self._record(o) + else: + self._dwell[o] = 0 + else: + self._dwell[o] = 0 + if np.abs(p[:2] - self.scale_xy()).max() > SCALE_HALF or \ + p[2] > envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + 0.02: + self._visit[o] = False + if self.inject and self.stop is None: + self._maybe_stop() + + def _record(self, o): + self.log.append(o) + k = len(self.log) + ok = self.log == self._inst["order"][:k] + if ok: + self.events.append(dict(step=int(self.sk.n_steps), kind="beep", obj=o, + text="The scale beeped: reading recorded.")) + else: + if self.error is None: + self.error = dict(item=o, position=k, step=int(self.sk.n_steps), + kind="repeat" if self.log.count(o) > 1 else "out_of_order") + self.events.append(dict(step=int(self.sk.n_steps), kind="error", obj=o, + text="The scale beeped three times: error, this reading does not follow the " + "requested order. The log cannot be edited.")) + + def _maybe_stop(self): + inst = self._inst + o, w = inst["stop_item"], inst["stop_w"] + if self.log != inst["order"][:w]: + return + p = envs.obj_pos(self.env, o) + if inst["stop_phase"] == "A": + if p[2] < envs.TABLE_Z + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.pad_xy(o)) < inst["trigger_dist"]: + return + else: + if p[2] < envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.scale_xy()) < inst["trigger_dist"]: + return + if not self.sk.holding(o): + return + self._do_stop(o) + + def _do_stop(self, o): + inst = self._inst + xy = self.pad_xy(o) + np.asarray(inst["stop_off"]) + envs.place_upright(self.env, o, xy, inst["stop_yaw"]) + self.sk.grip = -1.0 + self.sk.yaw = 0.0 + self._latch = len(self.sk.log) # drive the arm home until the current primitive has returned + self._prev[o] = envs.obj_pos(self.env, o) + self.env.sim.forward() + text = ("Emergency stop! The gripper opened, the safety routine put the item the robot was holding back on " + "its pad and moved the arm to its home pose. You may continue the task.") + self.stop = dict(item=o, phase=inst["stop_phase"], weighed=len(self.log), step=int(self.sk.n_steps)) + self.events.append(dict(step=int(self.sk.n_steps), kind="stop", obj=o, text=text)) + + def _homing_action(self): + sk = self.sk + a = np.zeros(self.env.action_dim) + a[:3] = np.clip((self._home - sk.eef_pos()) / sk.pos_scale, -1, 1) + a[3:6] = np.clip(_rot_err(sk.R0, sk.eef_mat()) / ROT_SCALE, -1, 1) + a[6] = -1.0 + return a + + def drain_events(self): + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + order = inst["order"] + complete = self.log == order + terminal = self.error is not None + off = [o for o in ITEMS if not self.on_own_pad(o)] + success = bool(complete and not off and not terminal) + if success: + head = "All four items were weighed once, in the requested order, and are back on their pads." + elif terminal: + head = ("The scale log does not follow the requested order (an item was weighed a second time or out " + "of turn). The log cannot be edited, so the task can no longer be completed.") + elif complete: + head = "Every item has been weighed, but not every item is back on its own pad." + else: + head = "Not every item has been weighed yet." + parts = [] + if not success and not terminal: + for o in off: + p = envs.obj_pos(self.env, o) + if self.sk.holding(o): + parts.append(f"the {NAME[o]} is still in the gripper") + elif self.on_scale(o, p): + parts.append(f"the {NAME[o]} is on the scale") + else: + d = np.linalg.norm(p[:2] - self.pad_xy(o)) + parts.append(f"the {NAME[o]} is {100 * d:.0f} cm from the centre of its pad") + detail = head + (" Also: " + "; ".join(parts) + "." if parts else "") + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "stop"] + self._outcome_cursor = len(self.events) + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, log=[NAME[o] for o in self.log], n_weighed=len(self.log), + complete=complete, error=self.error, stop=self.stop, + off_pad=[NAME[o] for o in off], detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _support_z(self, o): + p = envs.obj_pos(self.env, o) + return envs.TABLE_Z + (SCALE_TOP if self.on_scale(o, p) or + (np.abs(p[:2] - self.scale_xy()).max() < SCALE_HALF) else 0.0) + + def _n_stops(self): + return sum(e["kind"] == "stop" for e in self.events) + + def _pick(self, o): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, o) + sk.grasp_at(p[:2], self._support_z(o) + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=0.12) + if sk.holding(o): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], self._support_z(o) + GRASP_DZ + 0.12]) + return False + + def _carry_to(self, o, xy, z_support): + """Carry the held item to xy and put it down. Returns False if an emergency stop happened.""" + sk = self.sk + n0 = self._n_stops() + sk.move_to([xy[0], xy[1], Z_CARRY]) + if self._n_stops() > n0: + return False + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.004], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.10]) + return self._n_stops() == n0 + + def _weigh(self, o): + """Weigh one item (pad -> scale -> pad). Returns (status, beeped): status 'ok' / 'stop_A' / 'stop_B' / + 'no_grasp'; beeped = the scale beeped while the item lay on it (what the agent hears).""" + n_beep = sum(e["kind"] in ("beep", "error") for e in self.events) + if not self._pick(o): + return "no_grasp", False + if not self._carry_to(o, self.scale_xy(), envs.TABLE_Z + SCALE_TOP): + return "stop_A", False + self.sk.hold(6) + beeped = sum(e["kind"] in ("beep", "error") for e in self.events) > n_beep + if not self._pick(o): + return "no_grasp", beeped + if not self._carry_to(o, self.pad_xy(o), envs.TABLE_Z): + return "stop_B", beeped + return "ok", beeped + + def _fix_pads(self, log): + for o in ITEMS: + if not self.on_own_pad(o) and not self.on_scale(o): + if self._pick(o): + self._carry_to(o, self.pad_xy(o), envs.TABLE_Z) + log.append((NAME[o], "back to pad")) + + def _run_from(self, k, record, log, stop_on_stop=False): + """Weigh order[k:] in turn, keeping `record` (the policy's own list of readings it heard).""" + order = self._inst["order"] + i = k + guard = 0 + while i < len(order) and guard < 10 and self.error is None: + guard += 1 + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if beeped: + record.append(o) + if st == "no_grasp": + continue + if st.startswith("stop"): + if stop_on_stop: + return "stopped" + i = len(record) # resume from the own record + continue + i += 1 + return "ok" + + # ------------------------------------------------------------ scripted references (within protocol) + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed + 104729) + self.reset_instance(inst) + order = inst["order"] + history = [] + record = [] # adaptive's Save: readings it heard + for a in range(k): + log = [] + plan = dict(kind=kind, steps=log) + if a == 0: + if kind == "oracle": + while len(self.log) < len(order) and self.error is None and len(log) < 12: + o = order[len(self.log)] # privileged scale log + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "oracle: privileged scale log" + elif kind == "adaptive": + self._run_from(0, record, log) + plan["recovery"] = "own record of readings: resume from order[len(record)]" + elif kind == "skip": + started = [] + i = 0 + while i < len(order) and self.error is None and len(log) < 12: + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if st == "no_grasp": + continue + started.append(o) + i = len(started) # counts started items, not readings + plan["recovery"] = "counts items it started to weigh (the interrupted one too)" + else: # memoryless after the stop + r = self._run_from(0, record, log, stop_on_stop=True) + if r == "stopped": + if kind == "naive": + g = int(rng.integers(0, len(order) + 1)) + plan["recovery"] = f"memoryless: guesses {g} items already weighed" + self._run_from(g, [], log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no stop)" + else: + if kind in ("adaptive", "oracle", "skip"): + plan["recovery"] = "memory + F2: put items back on their pads / finish from own record" + if kind == "adaptive" and len(record) < len(order): + self._run_from(len(record), record, log) + if kind == "skip" and not history[-1]["outcome"]["complete"]: + # F2 says the log is incomplete: with memory, the item carried at the stop was not weighed + stopped = [s[0] for h in history for s in h["params"]["steps"] if str(s[1]).startswith("stop")] + if stopped: + o = next(i for i in ITEMS if NAME[i] == stopped[-1]) + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "memory + F2 'not every item weighed': weigh the item carried at the stop" + self._fix_pads(log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + self.go_home() + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or out["terminal"] or kind in ("oracle", "naive"): + break + return history + + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/lh_split_calibration.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/lh_split_calibration.py new file mode 100644 index 0000000000000000000000000000000000000000..af67f706117835300db6f39fd3f3a38a3933edcc --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/lh_split_calibration.py @@ -0,0 +1,142 @@ +"""Two-workstation packing: calibration transfer, collateral damage, geometric fit. + +A repeatable command-coordinate calibration varies with workstation (sign of y), +not with phase or policy. No object poses are written after reset. Learning a +far-workstation correction and blindly reusing it at the near destination can +undo the earlier placement. A long module must also be aligned with its tray. +""" +import numpy as np +import xml.etree.ElementTree as ET +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml,bin_xml,register_generated +from ..skills import Skills +from ..task_base import LFFTask,register_task +from .lh_shelf_droop import jar_xml,JAR_H,KNOB_Z +from .lh_lid_box import mark_xml + +RED='module_red_1';BLUE='module_blue_1';HALF=np.array([.045,.012,.012]) +class SplitSkills(Skills): + def __init__(self,env,task,recorder=None): + super().__init__(env,recorder=recorder);self.task=task;self.correction=np.zeros(3) + def move_to(self,target,*a,**kw): + q=np.array(target)-self.correction + self.bias=np.array(self.task.inst['far_bias'] if q[1]>.04 else self.task.inst['near_bias']) + rep=super().move_to(q,*a,**kw);rep['pos']=np.round(self.reported_eef_pos(),4).tolist();return rep + def reported_eef_pos(self):return self.eef_pos()-self.bias + def _act(self,dpos,drot,grip): + super()._act(dpos,drot,grip);self.task.monitor_step() + +@register_task +class SplitCalibration(LFFTask): + name='lh_split_calibration';level='L1';category='system_identification';failure_causes=('L1','L2','L4');failure_types=failure_causes + protocol='cross';max_attempts=5;agent_max_steps=240 + instruction=('Prepare the two modules for handover: stand the red module on its red square, and fit the entire ' + 'long blue module inside the narrow tray. Leave both released and stable, with the gripper open ' + 'and clear. The red module has a graspable top knob. The work areas are on opposite sides of the desk.') + instruction_indirect=('Stand the tall module with the round top on its matching square, and fit the entire elongated module inside the narrow open tray. Leave both released and stable, with the gripper open and clear.');capabilities=('Perceive','Reason','Plan','Restore') + def make_bddl(self): + rr=ET.fromstring(jar_xml('split_red',(.8,.15,.1,1))) + for g in rr.findall('.//geom'): + if g.get('type')=='box': + sz=np.fromstring(g.get('size'),sep=' ');sz[:2]*=.6;g.set('size',' '.join(map(str,sz))) + r=register_generated('LffSplitRed',ET.tostring(rr,encoding='unicode')) + b=register_generated('LffSplitBlue',box_xml('split_blue',HALF,(.1,.3,.85,1),density=1000)) + tray=register_generated('LffSplitTray',bin_xml('split_tray',(.051,.019),.022),free=False) + mark=register_generated('LffSplitMark',mark_xml('split_mark',(.8,.1,.1,1)),free=False) + return write_bddl(self.name,self.instruction,[(RED,r,'red_region',(-.36,-.16,-.35,-.15)),(BLUE,b,'blue_region',(-.17,.23,-.16,.24))], + [('tray_1',tray,'tray_region',(.2,-.3,.21,-.29)),('mark_1',mark,'mark_region',(.2,.3,.21,.31))]) + def sample_instance(self,seed): + rng=np.random.default_rng(seed);v=float(rng.uniform(.053,.057)) + return dict(seed=seed,near_bias=[0,-v,0],far_bias=[0,v,0],red_xy=[-.35,-.12],blue_xy=[-.16,.24],red_goal=[-.22,-.24],blue_goal=[-.21,-.13]) + def apply_instance(self,i): + self.inst=i;m=self.env.sim.model + envs.set_obj_pose(self.env,RED,[*i['red_xy'],envs.TABLE_Z+JAR_H/2+.001]);envs.scale_mass(self.env,RED,.08) + envs.set_obj_pose(self.env,BLUE,[*i['blue_xy'],envs.TABLE_Z+HALF[2]+.001],yaw=np.pi/2) + for name,xy,z in [('tray_1',i['blue_goal'],.914),('mark_1',i['red_goal'],.901)]: + m.body_pos[m.body_name2id(self.env.fixtures_dict[name].root_body)]=[*xy,z] + def reset_instance(self,i,recorder=None): + np.random.seed(i['seed']);self.mon=None;self.env.reset();self.apply_instance(i);self.env.sim.forward();envs.settle(self.env,10) + self.sk=SplitSkills(self.env,self,recorder);self.trace=[];self.phase_hook=None;self.traps={k:False for k in self.failure_causes};self.recovered=self.traps.copy() + self.mon=dict(red_ever=False,red_lost=False,red_restored=False);return self.sk + def red_ok(self): + p=envs.obj_pos(self.env,RED);R=self.env.sim.data.body_xmat[envs.body_id(self.env,RED)].reshape(3,3) + return bool(np.linalg.norm(p[:2]-self.inst['red_goal'])<.022 and R[2,2]>.96 and abs(p[2]-(.9+JAR_H/2))<.008 and not self.sk.holding(RED)) + def blue_ok(self): + p=envs.obj_pos(self.env,BLUE);R=self.env.sim.data.body_xmat[envs.body_id(self.env,BLUE)].reshape(3,3) + corners=np.array([p+R@(HALF*[a,b,c]) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + return bool(np.all(np.abs(corners[:,:2]-self.inst['blue_goal'])<[.052,.020]) and corners[:,2].max()<.936 and corners[:,2].min()>.903 and not self.sk.holding(BLUE)) + def monitor_step(self): + if self.mon is None:return + ok=self.red_ok() + if ok: + if self.mon['red_lost']:self.mon['red_restored']=True + self.mon['red_ever']=True + elif self.mon['red_ever'] and not self.sk.holding(RED):self.mon['red_lost']=True + def label(self,text): + r=dict(text=text,step=self.sk.n_steps,red_ok=self.red_ok(),blue_ok=self.blue_ok(),red_xyz=envs.obj_pos(self.env,RED).tolist(),blue_xyz=envs.obj_pos(self.env,BLUE).tolist());self.trace.append(r) + if self.phase_hook:self.phase_hook(text,r) + def observe_offset(self,xy): + s=self.sk;q=np.array([*xy,1.18]);s.move_to(q);return (s.eef_pos()-q+s.correction)*[1,1,0] + def pick(self,name,yaw=None): + s=self.sk;p=envs.obj_pos(self.env,name);R=self.env.sim.data.body_xmat[envs.body_id(self.env,name)].reshape(3,3) + if name==RED: + goal=p+R@np.array([0,0,KNOB_Z-JAR_H/2]);yaw=float(np.arctan2(R[1,2],R[0,2])) if R[2,2]<.7 else 0 + else: + goal=p.copy();yaw=float(np.arctan2(R[1,0],R[0,0])) if yaw is None else yaw + s.set_gripper(False,8);s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=150);s.set_gripper(True,20) + s.move_to([*goal[:2],1.20],speed=.1);s.hold(20);return bool(s.holding(name)) + def place(self,name,xy,z,yaw): + s=self.sk;off=envs.obj_pos(self.env,name)-s.eef_pos();s.move_to([*s.eef_pos()[:2],1.20],yaw=yaw) + # Update the held offset after rotating the module. + off=envs.obj_pos(self.env,name)-s.eef_pos();goal=np.array([*xy,z])-off + s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=160) + s.set_gripper(False,12);s.move_to([*goal[:2],1.23]);s.hold(40) + def execute(self,i,p): + mode=p.get('mode','adaptive');s=self.sk + if mode=='blind':s.correction=np.array(p.get('jitter',[0,0,0])) + self.label('Two workstations: preserve earlier placements') + if mode=='oracle':near=np.array(i['near_bias']) + else: + near=self.observe_offset(i['red_xy']);ok=self.pick(RED);self.traps['L1']=not ok;self.label('L1: near-workstation grasp missed') + if mode in ('naive','blind') and not ok:return + if mode not in ('naive','blind'):s.correction=near + if not self.pick(RED):self.label('Red pickup failed');return + self.recovered['L1']=True;self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.label('Red module placed correctly') + if mode=='oracle':far=np.array(i['far_bias']) + else: + ok=self.pick(BLUE);self.label('L1 transfer: near correction fails at the far workstation') + if mode in ('naive','blind'): + if not ok:return + self.place(BLUE,i['blue_goal'],.922,np.pi/2);return + far=self.observe_offset(i['blue_xy']) + s.correction=far + if not self.pick(BLUE):self.label('Far pickup failed');return + if mode!='oracle': + self.place(BLUE,i['blue_goal'],.922,np.pi/2);self.traps['L2']=bool(not self.red_ok());self.label('L2: reusing far correction disturbed the red module') + s.correction=near + if not self.pick(RED):self.label('Red restoration pickup failed');return + self.place(RED,[-.40,-.28],.9+JAR_H/2+.003,0);self.label('Clear the disturbed red module before recovering the blue module') + if not self.pick(BLUE):self.label('Blue recovery pickup failed');return + self.place(BLUE,i['blue_goal'],.922,np.pi/2);self.traps['L4']=not self.blue_ok();self.label('L4: the long module bridges the narrow tray') + if not self.pick(RED):return + self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.recovered['L2']=self.red_ok();self.label('L2 recovery: restored red using the near-workstation correction') + if not self.pick(BLUE):self.label('Blue alignment pickup failed');return + s.correction=near;self.place(BLUE,i['blue_goal'],.920,0);self.recovered['L4']=self.blue_ok();self.label('Aligned module fits; recheck both completed placements') + if not self.red_ok(): + if self.pick(RED):self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0) + s.set_gripper(False,8);s.move_to([-.40,-.05,1.25]);s.hold(30) + def outcome(self,i): + self.sk.hold(100);stages=dict(red_on_mark=self.red_ok(),blue_in_tray=self.blue_ok(),gripper_open=bool(self.sk.grip<0),gripper_clear=bool(self.sk.eef_pos()[2]>1.13)) + static=all(np.linalg.norm(self.env.sim.data.qvel[envs.free_joint_addr(self.env,n)[1]:envs.free_joint_addr(self.env,n)[1]+6])<.06 for n in (RED,BLUE)) + return dict(success=bool(all(stages.values()) and static),stages=stages,static=bool(static),traps=self.traps.copy(),recovered=self.recovered.copy(),detail=str(stages)) + def default_params(self,i):return {'mode':'naive'} + def oracle_params(self,i):return {'mode':'oracle'} + def adapt_params(self,i,h):return {'mode':'adaptive'} + def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None): + hist=[] + for n in range((k or 5) if kind=='blind' else 1): + self.reset_instance(inst);params={'mode':kind};self.execute(inst,params);o=self.outcome(inst);hist.append(dict(attempt=n+1,params=params,outcome=o)) + if on_attempt:on_attempt(n+1,self.env,o) + if o['success']:break + return hist diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/validate.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb5365e77822d5dc2d8ad2fd3489c4d6c82a77b --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/validate.py @@ -0,0 +1,79 @@ +"""Headroom validation of LFF-Bench tasks with scripted reference policies. + +python scripts/validate.py --task l5_slide_to_target --n 20 --k 5 +Writes results//validate.json and thumbnails. +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +import imageio # noqa: E402 + +import lffbench.tasks as task_pkg # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + + +def succ_curve(results, k): + """run-level succ@j for j = 1..k (a run = one instance, attempts share the run's state).""" + out = [] + for j in range(1, k + 1): + out.append(float(np.mean([r is not None and r <= j for r in results]))) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--n", type=int, default=20) + ap.add_argument("--k", type=int, default=5) + ap.add_argument("--seed0", type=int, default=1000) + ap.add_argument("--kinds", default="oracle,naive,adaptive,blind") + ap.add_argument("--thumbs", type=int, default=3) + args = ap.parse_args() + + task = TASKS[args.task]() + outdir = os.path.join(ROOT, "results", args.task) + os.makedirs(outdir, exist_ok=True) + kinds = args.kinds.split(",") + first_success = {k: [] for k in kinds} + runs = [] + t0 = time.time() + for i in range(args.n): + seed = args.seed0 + i + inst = task.sample_instance(seed) + if i < args.thumbs: + task.reset_instance(inst) + imageio.imwrite(os.path.join(outdir, f"init_{seed}.png"), task.snapshot(res=384)) + for kind in kinds: + hist = task.run_scripted(kind, inst, k=args.k, seed=seed) + s = next((h["attempt"] for h in hist if h["outcome"]["success"]), None) + first_success[kind].append(s) + runs.append(dict(seed=seed, kind=kind, inst={k: v for k, v in inst.items() if not k.startswith("_")}, + history=hist)) + if i < args.thumbs and kind == "naive": + imageio.imwrite(os.path.join(outdir, f"naive_end_{seed}.png"), task.snapshot(res=384)) + print(f"[{i + 1}/{args.n}] seed={seed} " + " ".join(f"{k}={first_success[k][-1]}" for k in kinds) + + f" ({time.time() - t0:.0f}s)", flush=True) + + summary = {k: succ_curve(v, args.k) for k, v in first_success.items()} + res = dict(task=args.task, level=task.level, capabilities=list(task.capabilities), n=args.n, k=args.k, + succ_at_k=summary, runs=runs, seconds=time.time() - t0) + with open(os.path.join(outdir, "validate.json"), "w") as f: + json.dump(res, f, indent=1, default=float) + print(json.dumps({k: [round(x, 2) for x in v] for k, v in summary.items()})) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/validate_parts_cart_isolated.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/validate_parts_cart_isolated.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc7b396510a3b831b746bdb17761fc8c32c5678 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/validate_parts_cart_isolated.py @@ -0,0 +1,54 @@ +"""Development physical validation; no model API, no pose injection after reset.""" +import argparse,copy,json,time,hashlib +from pathlib import Path +import numpy as np +from PIL import Image +from lffbench.tasks.lh_parts_cart import PartsCart +from lffbench import envs + +def main(): + p=argparse.ArgumentParser();p.add_argument('--seeds',nargs='+',type=int,default=[1000,1001,1002]);p.add_argument('--out',required=True);p.add_argument('--case',choices=['combined','oracle','l4','l2','l5'],default='combined');a=p.parse_args() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + x=PartsCart(cam_res=512);rows=[] + def clean(obj): + if isinstance(obj,np.ndarray):return obj.tolist() + if isinstance(obj,np.generic):return obj.item() + raise TypeError(type(obj).__name__) + for seed in a.seeds: + i=x.sample_instance(seed) + if a.case in ['l4','l2','l5']:i['traps']={k:k==a.case.upper() for k in ['L4','L2','L5']} + x.reset_instance(i);r=dict(seed=seed,case=a.case,instance=i,checkpoints=[]);rows.append(r) + def snap(label): + o=copy.deepcopy(x.outcome(i));q=out/f's{seed}_{label}.png';Image.fromarray(x.snapshot(res=512)).save(q) + r['checkpoints'].append(dict(label=label,sim_step=x.sk.n_steps,commands=x.sk.robot_commands,outcome=o,image=str(q.resolve()))) + (out/'results.json').write_text(json.dumps(rows,indent=2,default=clean)) + print(seed,label,o['success'],o['traps'],o['stages'],flush=True) + snap('initial') + if a.case=='oracle': + x.execute(i,x.oracle_params(i));snap('oracle_final');continue + if a.case in ['combined','l4']: + x.tool_push_out();snap('L4_blocked') + x.tool_push_front();snap('L4_retrieved') + x.load(careful=a.case not in ['combined','l2']);snap('loaded') + if a.case in ['l4','l5']: + x.repair_load();snap('loading_prerequisite_repaired') + if a.case in ['combined','l2']: + x.repair_load();snap('L2_restored') + if all(x.cargo_ok(j) for j in range(2)): + if a.case in ['combined','l5']: + # First full naive push, then reuse correction loop without its initial push. + x.transport(0.,False);snap('L5_naive_push') + x._transport_only=True + # Feed a no-op execute only for the corrector's initial call; subsequent _push_at are unchanged. + original=x.execute + x.execute=lambda inst,params:None + try: + from lffbench.tasks.l7_offcenter_push import OffcenterPush + OffcenterPush.adaptive_attempt(x,i,0.) + finally:x.execute=original;x._transport_only=False + snap('L5_corrected') + else:x.transport(i['com_offset'] if i['traps']['L5'] else 0.,False) + x.repair_load();x.sk.set_gripper(False,steps=10);e=x.sk.eef_pos();x.sk.move_to([e[0],e[1],envs.TABLE_Z+.24]);snap('final') + x.env.close() + (out/'manifest.json').write_text(json.dumps(dict(case=a.case,seeds=a.seeds,task_sha256=hashlib.sha256(Path(__file__).parents[1].joinpath('lffbench/tasks/lh_parts_cart.py').read_bytes()).hexdigest(),note='scripted development validation, not model runs'),indent=2)) +if __name__=='__main__':main()