diff --git a/leaf/annotations/episode_002352.json b/leaf/annotations/episode_002352.json new file mode 100644 index 0000000000000000000000000000000000000000..0f96c212760fce9bcbb859b6e894c94ba6423b01 --- /dev/null +++ b/leaf/annotations/episode_002352.json @@ -0,0 +1,2668 @@ +{ + "schema": "leaf-replay-1", + "source": { + "batch": "clh_20261102_sonnet", + "run": "clh_20261102_sonnet-claude-sonnet-5-5-claudecodefull-noharness1_lh_order_dispatch_s3002_none_F1_direct_k1_1105-134157_p23202", + "attempts_in_episode": [ + 1 + ], + "episode_in_run": 0, + "condition": "memory_free_retry", + "memory_free_chain_of": "0002", + "memory_free_rep": 1, + "feedback_level": "F1", + "hide_k": false, + "k": 1, + "perception": "rgb", + "instruction_variant": "direct", + "contract_sha256": "138d4c7b8188065024079091348171b0806956433a829407b621e6c1e664920f", + "run_status": "done", + "manifest_id": "0008", + "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_sonnet/clh_20261102_sonnet-claude-sonnet-5-5-claudecodefull-noharness1_lh_order_dispatch_s3002_none_F1_direct_k1_1105-134157_p23202", + "frozen_run": "/mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source/runs/api/clh_20261102_sonnet/clh_20261102_sonnet-claude-sonnet-5-5-claudecodefull-noharness1_lh_order_dispatch_s3002_none_F1_direct_k1_1105-134157_p23202", + "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": 1, + "chain": "0002", + "task": "lh_order_dispatch", + "seed": 3002 + }, + "release_origin": { + "dataset": "compound-lh-20261102-clh_20261102_sonnet", + "episode_index": 11 + }, + "release_episode_index": 2352, + "pre_v181_sidecar_index": { + "episode_index": 11, + "dataset_index_range": [ + 18624, + 20322 + ] + } + }, + "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": "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 attempt ended without success. The tray was knocked out of position, and I never got the red card into it. The tool-call budget (100) ran out first. About 120 of 180 robot commands and 456 s of motion were still unused.\n\n**What I did**\n- **Tray knocked early:** My first diagonal move at low height (`move_eef x=0.5 y=-0.2 z=0.05`) swept through the tray. It ended up rotated about 45° and partly in the green rectangle.\n- **Tray re-aligned:** I pushed it back with the closed gripper, using three short pushes along its long side near the ends. That brought it to roughly 8° of tilt, back inside the yellow rectangle.\n- **Camera calibration:** The wrist camera sees the scene from about 4 cm ahead of the grasp point. I only worked that out after two failed cube grasps, and I recalibrated from the cube position in the wrist image.\n- **Cubes:** I picked the red and then the blue product cube with `gripper=close` at z≈0.016–0.019. A good grasp showed a closed width of about 0.028 m. I put one cube in each compartment of the tray, and both were confirmed in the tray from above.\n- **Red card:** The card was on the box beside the tray. I pushed it toward the tray with the closed gripper at z≈0.049. The card overhung the box edge, shoved the tray away and dropped into the gap between the box and the tray.\n- **Recovery attempt:** I tried to shove the tray back toward the box. The tray ended up snagged on the closed fingers, and the two cubes were no longer sitting in it. The last command was `move_eef gripper=open`.\n\n**What I learned**\n- A single diagonal move at low height can sweep an object, so I should have raised the arm first.\n- The card is too thin to pinch from a flat surface, so it has to be pushed. The tray has to stay pressed against the box wall while the card is pushed, and I should have fixed that with the tray before touching the card.\n- I spent too many tool calls on looking at images and on calibrating the wrist camera.\n\nI never got to the final push of the loaded tray into the green rectangle.", + "mean_think_s": 8.5, + "outcome_class_original": null, + "outcome_class_status": "not_applicable" + }, + "attempts": [ + { + "attempt": 1, + "success": false, + "outcome": { + "success": false, + "cargo": { + "product_red_1": false, + "product_blue_1": false, + "card_1": false + }, + "loaded_in_start": false, + "load_step": null, + "departed_unloaded": true, + "inside": false, + "static": false, + "failure": "cargo", + "stages": { + "product_red_1": false, + "product_blue_1": false, + "card_1": false, + "loaded_in_start": false, + "delivery": false + }, + "events": [ + { + "step": 710, + "item": "product_red_1", + "event": "achieved" + }, + { + "step": 835, + "item": "product_blue_1", + "event": "achieved" + }, + { + "step": 1320, + "item": "product_red_1", + "event": "lost" + }, + { + "step": 1320, + "item": "product_blue_1", + "event": "lost" + }, + { + "step": 1325, + "item": "product_red_1", + "event": "achieved" + }, + { + "step": 1325, + "item": "product_blue_1", + "event": "achieved" + }, + { + "step": 1410, + "item": "product_red_1", + "event": "lost" + }, + { + "step": 1410, + "item": "product_blue_1", + "event": "lost" + } + ], + "l1_attempts": [], + "card_closes": [ + { + "step": 63, + "local": [ + 0.1268, + -0.2738 + ], + "tips_above_card": 0.0691, + "beyond_edge": 0.1438, + "beyond_edge_name": "right", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0798, + "held": false, + "width": 0.0023 + }, + { + "step": 558, + "local": [ + -0.0642, + -0.5062 + ], + "tips_above_card": -0.0279, + "beyond_edge": 0.3762, + "beyond_edge_name": "right", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0786, + "held": false, + "width": 0.0166 + }, + { + "step": 611, + "local": [ + -0.038, + -0.5082 + ], + "tips_above_card": -0.0268, + "beyond_edge": 0.3782, + "beyond_edge_name": "right", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0782, + "held": false, + "width": 0.0023 + }, + { + "step": 666, + "local": [ + -0.055, + -0.5091 + ], + "tips_above_card": -0.0305, + "beyond_edge": 0.3791, + "beyond_edge_name": "right", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0782, + "held": false, + "width": 0.0285 + }, + { + "step": 777, + "local": [ + 0.0736, + -0.5078 + ], + "tips_above_card": -0.0331, + "beyond_edge": 0.3778, + "beyond_edge_name": "right", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0799, + "held": false, + "width": 0.0282 + }, + { + "step": 872, + "local": [ + 0.0063, + 0.0459 + ], + "tips_above_card": 0.1021, + "beyond_edge": -0.0841, + "beyond_edge_name": "left", + "card_on_board": true, + "overhang": -0.065, + "overhang_edge": "forward", + "width_before": 0.0794, + "held": false, + "width": 0.0023 + } + ], + "card_lift": 0.0010980694322174633, + "box_moves": [ + { + "step": 25, + "moved_cm": 9.5, + "turned_deg": -46.7, + "yaw_deg": -46.7, + "gripper_open": true, + "touch_u": 0.0362, + "touch_v": -0.0644, + "face": "right_end", + "inside": false, + "over_turned": true, + "overshot": true, + "sideways": false, + "tipped": false, + "bad": true, + "new_trap": true + }, + { + "step": 360, + "moved_cm": 3.2, + "turned_deg": 14.4, + "yaw_deg": -32.8, + "gripper_open": false, + "touch_u": 0.0605, + "touch_v": 0.0594, + "face": "front", + "inside": false, + "over_turned": true, + "overshot": false, + "sideways": true, + "tipped": false, + "bad": true, + "new_trap": false + }, + { + "step": 378, + "moved_cm": 1.1, + "turned_deg": 4.7, + "yaw_deg": -28.1, + "gripper_open": false, + "touch_u": 0.0565, + "touch_v": 0.0313, + "face": "front", + "inside": false, + "over_turned": true, + "overshot": false, + "sideways": true, + "tipped": false, + "bad": true, + "new_trap": false + }, + { + "step": 431, + "moved_cm": 2.1, + "turned_deg": 9.9, + "yaw_deg": -18.1, + "gripper_open": false, + "touch_u": 0.0577, + "touch_v": 0.0713, + "face": "front", + "inside": false, + "over_turned": true, + "overshot": false, + "sideways": true, + "tipped": false, + "bad": true, + "new_trap": false + }, + { + "step": 497, + "moved_cm": 0.9, + "turned_deg": 4.3, + "yaw_deg": -11.6, + "gripper_open": false, + "touch_u": 0.054, + "touch_v": 0.0751, + "face": "front", + "inside": false, + "over_turned": true, + "overshot": false, + "sideways": true, + "tipped": false, + "bad": true, + "new_trap": false + }, + { + "step": 1246, + "moved_cm": 2.4, + "turned_deg": 0.2, + "yaw_deg": -10.1, + "gripper_open": false, + "touch_u": -0.0179, + "touch_v": 0.1751, + "face": "left_end", + "inside": false, + "over_turned": false, + "overshot": false, + "sideways": false, + "tipped": false, + "bad": false, + "new_trap": false + }, + { + "step": 1333, + "moved_cm": 1.4, + "turned_deg": 0.4, + "yaw_deg": -9.8, + "gripper_open": false, + "touch_u": -0.0101, + "touch_v": 0.0994, + "face": "left_end", + "inside": false, + "over_turned": false, + "overshot": false, + "sideways": false, + "tipped": false, + "bad": false, + "new_trap": false + }, + { + "step": 1403, + "moved_cm": 4.5, + "turned_deg": 7.0, + "yaw_deg": -2.7, + "gripper_open": false, + "touch_u": 0.0406, + "touch_v": -0.13, + "face": "front", + "inside": false, + "over_turned": false, + "overshot": false, + "sideways": true, + "tipped": false, + "bad": true, + "new_trap": true + }, + { + "step": 1653, + "moved_cm": 4.4, + "turned_deg": 8.5, + "yaw_deg": 5.8, + "gripper_open": false, + "touch_u": 0.0238, + "touch_v": -0.1233, + "face": "right_end", + "inside": false, + "over_turned": false, + "overshot": false, + "sideways": true, + "tipped": true, + "bad": true, + "new_trap": false + } + ], + "l5_triggered": false, + "yaw_deg": -74.36665111536807, + "sim_s": 84.9, + "commands": 68, + "touching": false, + "upright": true, + "detail": "Cargo in tray: {'product_red_1': False, 'product_blue_1': False, 'card_1': False}; tray inside delivery rectangle: False." + }, + "finish_reason": "tool-call budget used up (automatic)", + "feedback_shown": "Attempt failed.", + "auto_ended": true, + "think_s": 0.0010013580322265625, + "feedback_f2": "Attempt failed. Cargo in tray: {'product_red_1': False, 'product_blue_1': False, 'card_1': False}; tray inside delivery rectangle: False.", + "judge_frames": [ + 1668, + 1698 + ], + "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": 14.42259693145752, + "agent_obs_images": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s000_agentview.jpg", + "obs/s000_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 2, + "kind": "move_eef", + "frame_start": 8, + "frame_end": 25, + "command": "move_eef x=0.5 y=-0.2 z=0.05", + "args": { + "x": 0.5, + "y": -0.2, + "z": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5028, + -0.2014, + 0.0518 + ], + "gripper_width_after": 0.0789, + "holding_after": false, + "touched_during": true, + "think_s": 9.04512906074524, + "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": 25, + "frame_end": 42, + "command": "move_eef x=0.5 y=-0.05 z=0.45", + "args": { + "x": 0.5, + "y": -0.05, + "z": 0.45 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4991, + -0.0495, + 0.448 + ], + "gripper_width_after": 0.0796, + "holding_after": false, + "touched_during": true, + "think_s": 12.689974784851074, + "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": 42, + "frame_end": 78, + "command": "move_eef x=0.609 y=-0.019 z=0.12 gripper=close", + "args": { + "x": 0.609, + "y": -0.019, + "z": 0.12, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6066, + -0.0189, + 0.1184 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 66.73328471183777, + "agent_obs_images": [ + "obs/s004_agentview.jpg", + "obs/s004_wrist.jpg" + ], + "agent_note": { + "shell": [ + "cd obs; python3 -c \"\nimport cv2,numpy as np\nim=cv2.imread('a1_s003_wrist.jpg') if False else cv2.imread('s003_wrist.jpg')\nhsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n# tray tan color\nprint(im[220,215],im[280,260],im[250,240])\n\"; ls", + "cd obs; python3 -c \"\nimport cv2\nim=cv2.imread('s003_wrist.jpg')\nc=im[150:340,130:350]\nc=cv2.resize(c,None,fx=4,fy=4,interpolation=cv2.INTER_CUBIC)\nfor i in range(0,c.shape[1],100): cv2.line(c,(i,0),(i,c.shape[0]),(0,0,0),1); cv2.putText(c,str(130+i//4),(i,12),0,0.4,(0,0,0),1)\nfor j in range(0,c.shape[0],100): cv2.line(c,(0,j),(c.shape[1],j),(0,0,0),1); cv2.putText(c,str(150+j//4),(0,j+12),0,0.4,(0,0,0),1)\ncv2.imwrite('z.png',c)\"" + ], + "viewed": [ + "obs/s003_agentview.jpg", + "obs/s003_wrist.jpg", + "obs/z.png" + ] + } + }, + { + "attempt": 1, + "step": 5, + "kind": "move_eef", + "frame_start": 78, + "frame_end": 328, + "command": "move_eef z=0.03", + "args": { + "z": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 1.8, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6171, + -0.023, + 0.0445 + ], + "gripper_width_after": 0.0052, + "holding_after": false, + "touched_during": true, + "think_s": 2.017080783843994, + "agent_obs_images": [ + "obs/s005_agentview.jpg", + "obs/s005_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 6, + "kind": "move_eef", + "frame_start": 328, + "frame_end": 334, + "command": "move_eef x=0.632 y=-0.037 z=0.08", + "args": { + "x": 0.632, + "y": -0.037, + "z": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6313, + -0.0367, + 0.0787 + ], + "gripper_width_after": 0.0012, + "holding_after": false, + "touched_during": true, + "think_s": 27.697904586791992, + "agent_obs_images": [ + "obs/s006_agentview.jpg", + "obs/s006_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s005_agentview.jpg", + "obs/s005_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 7, + "kind": "move_eef", + "frame_start": 334, + "frame_end": 340, + "command": "move_eef z=0.03", + "args": { + "z": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6328, + -0.037, + 0.0327 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.017691850662231445, + "agent_obs_images": [ + "obs/s007_agentview.jpg", + "obs/s007_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 8, + "kind": "move_eef", + "frame_start": 340, + "frame_end": 360, + "command": "move_eef x=0.595 y=-0.005 speed=0.05", + "args": { + "x": 0.595, + "y": -0.005, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5968, + -0.0066, + 0.0332 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 1.9674005508422852, + "agent_obs_images": [ + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg" + ], + "agent_note": { + "messages": [ + "Now push along the tray's short-axis direction." + ] + } + }, + { + "attempt": 1, + "step": 9, + "kind": "move_eef", + "frame_start": 360, + "frame_end": 378, + "command": "move_eef z=0.45 x=0.5 y=-0.05", + "args": { + "z": 0.45, + "x": 0.5, + "y": -0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5002, + -0.0496, + 0.4492 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 2.5330758094787598, + "agent_obs_images": [ + "obs/s009_agentview.jpg", + "obs/s009_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 10, + "kind": "move_eef", + "frame_start": 378, + "frame_end": 399, + "command": "move_eef x=0.625 y=0.03 z=0.08", + "args": { + "x": 0.625, + "y": 0.03, + "z": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6223, + 0.0299, + 0.0783 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 13.082870960235596, + "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": 399, + "frame_end": 405, + "command": "move_eef z=0.03", + "args": { + "z": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.624, + 0.0299, + 0.0327 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.007012844085693359, + "agent_obs_images": [ + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 12, + "kind": "move_eef", + "frame_start": 405, + "frame_end": 431, + "command": "move_eef x=0.56 speed=0.05", + "args": { + "x": 0.56, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.562, + 0.0299, + 0.0331 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 0.006905555725097656, + "agent_obs_images": [ + "obs/s012_agentview.jpg", + "obs/s012_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 13, + "kind": "move_eef", + "frame_start": 431, + "frame_end": 449, + "command": "move_eef z=0.45 x=0.5 y=-0.05", + "args": { + "z": 0.45, + "x": 0.5, + "y": -0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5014, + -0.0499, + 0.4506 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 1.8381271362304688, + "agent_obs_images": [ + "obs/s013_agentview.jpg", + "obs/s013_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 14, + "kind": "move_eef", + "frame_start": 449, + "frame_end": 469, + "command": "move_eef x=0.6 y=0.06 z=0.08", + "args": { + "x": 0.6, + "y": 0.06, + "z": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5976, + 0.06, + 0.0786 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 9.556246995925903, + "agent_obs_images": [ + "obs/s014_agentview.jpg", + "obs/s014_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s013_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 15, + "kind": "move_eef", + "frame_start": 469, + "frame_end": 475, + "command": "move_eef z=0.03", + "args": { + "z": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5995, + 0.06, + 0.0328 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.006641387939453125, + "agent_obs_images": [ + "obs/s015_agentview.jpg", + "obs/s015_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 16, + "kind": "move_eef", + "frame_start": 475, + "frame_end": 497, + "command": "move_eef x=0.545 speed=0.05", + "args": { + "x": 0.545, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5473, + 0.0598, + 0.0332 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 0.006170749664306641, + "agent_obs_images": [ + "obs/s016_agentview.jpg", + "obs/s016_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 17, + "kind": "move_eef", + "frame_start": 497, + "frame_end": 514, + "command": "move_eef z=0.45 x=0.5 y=-0.05", + "args": { + "z": 0.45, + "x": 0.5, + "y": -0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4988, + -0.0493, + 0.4472 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 0.0071485042572021484, + "agent_obs_images": [ + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 18, + "kind": "move_eef", + "frame_start": 514, + "frame_end": 547, + "command": "move_eef x=0.442 y=-0.228 z=0.12 gripper=open", + "args": { + "x": 0.442, + "y": -0.228, + "z": 0.12, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4398, + -0.2282, + 0.1187 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 6.561453104019165, + "agent_obs_images": [ + "obs/s018_agentview.jpg", + "obs/s018_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s017_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 19, + "kind": "move_eef", + "frame_start": 547, + "frame_end": 553, + "command": "move_eef x=0.42 y=-0.251 z=0.06", + "args": { + "x": 0.42, + "y": -0.251, + "z": 0.06 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.418, + -0.2509, + 0.061 + ], + "gripper_width_after": 0.0783, + "holding_after": false, + "touched_during": false, + "think_s": 7.353470802307129, + "agent_obs_images": [ + "obs/s019_agentview.jpg", + "obs/s019_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s018_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 20, + "kind": "move_eef", + "frame_start": 553, + "frame_end": 558, + "command": "move_eef z=0.02", + "args": { + "z": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4158, + -0.2512, + 0.0216 + ], + "gripper_width_after": 0.0786, + "holding_after": false, + "touched_during": false, + "think_s": 4.714069843292236, + "agent_obs_images": [ + "obs/s020_agentview.jpg", + "obs/s020_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s019_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 21, + "kind": "move_eef", + "frame_start": 558, + "frame_end": 573, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.4167, + -0.2513, + 0.0227 + ], + "gripper_width_after": 0.0166, + "holding_after": false, + "touched_during": true, + "think_s": 2.6876778602600098, + "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": 573, + "frame_end": 581, + "command": "move_eef z=0.15", + "args": { + "z": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4192, + -0.2509, + 0.1486 + ], + "gripper_width_after": 0.0022, + "holding_after": false, + "touched_during": true, + "think_s": 3.2547333240509033, + "agent_obs_images": [ + "obs/s022_agentview.jpg", + "obs/s022_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 23, + "kind": "move_eef", + "frame_start": 581, + "frame_end": 606, + "command": "move_eef x=0.445 z=0.06 gripper=open", + "args": { + "x": 0.445, + "z": 0.06, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.442, + -0.2535, + 0.059 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 20.98620629310608, + "agent_obs_images": [ + "obs/s023_agentview.jpg", + "obs/s023_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s022_agentview.jpg", + "obs/s022_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 24, + "kind": "move_eef", + "frame_start": 606, + "frame_end": 611, + "command": "move_eef z=0.02", + "args": { + "z": 0.02 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.442, + -0.2532, + 0.0227 + ], + "gripper_width_after": 0.0782, + "holding_after": false, + "touched_during": false, + "think_s": 0.013150215148925781, + "agent_obs_images": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 25, + "kind": "move_eef", + "frame_start": 611, + "frame_end": 626, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.4419, + -0.2532, + 0.0226 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 3.277442693710327, + "agent_obs_images": [ + "obs/s025_agentview.jpg", + "obs/s025_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 26, + "kind": "move_eef", + "frame_start": 626, + "frame_end": 634, + "command": "move_eef z=0.15", + "args": { + "z": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4457, + -0.2542, + 0.1496 + ], + "gripper_width_after": 0.0015, + "holding_after": false, + "touched_during": false, + "think_s": 0.012560844421386719, + "agent_obs_images": [ + "obs/s026_agentview.jpg", + "obs/s026_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 27, + "kind": "move_eef", + "frame_start": 634, + "frame_end": 661, + "command": "move_eef x=0.428 z=0.06 gripper=open", + "args": { + "x": 0.428, + "z": 0.06, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4249, + -0.2545, + 0.0584 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 33.04404664039612, + "agent_obs_images": [ + "obs/s027_agentview.jpg", + "obs/s027_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s026_agentview.jpg", + "obs/s026_wrist.jpg", + "obs/s021_wrist.jpg", + "obs/s025_wrist.jpg", + "obs/s025_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 28, + "kind": "move_eef", + "frame_start": 661, + "frame_end": 666, + "command": "move_eef z=0.016", + "args": { + "z": 0.016 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.425, + -0.2541, + 0.019 + ], + "gripper_width_after": 0.0782, + "holding_after": false, + "touched_during": false, + "think_s": 0.019803762435913086, + "agent_obs_images": [ + "obs/s028_agentview.jpg", + "obs/s028_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 29, + "kind": "move_eef", + "frame_start": 666, + "frame_end": 681, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.4251, + -0.2541, + 0.019 + ], + "gripper_width_after": 0.0285, + "holding_after": true, + "touched_during": true, + "think_s": 0.0067768096923828125, + "agent_obs_images": [ + "obs/s029_agentview.jpg", + "obs/s029_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 30, + "kind": "move_eef", + "frame_start": 681, + "frame_end": 687, + "command": "move_eef z=0.08", + "args": { + "z": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4262, + -0.2552, + 0.0776 + ], + "gripper_width_after": 0.0285, + "holding_after": true, + "touched_during": true, + "think_s": 0.0064868927001953125, + "agent_obs_images": [ + "obs/s030_agentview.jpg", + "obs/s030_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 31, + "kind": "move_eef", + "frame_start": 687, + "frame_end": 695, + "command": "move_eef x=0.506 y=-0.05 z=0.13", + "args": { + "x": 0.506, + "y": -0.05, + "z": 0.13 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.6 + }, + "eef_pos_after": [ + 0.5057, + -0.0533, + 0.1308 + ], + "gripper_width_after": 0.0285, + "holding_after": true, + "touched_during": true, + "think_s": 6.37238073348999, + "agent_obs_images": [ + "obs/s031_agentview.jpg", + "obs/s031_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 32, + "kind": "move_eef", + "frame_start": 695, + "frame_end": 700, + "command": "move_eef x=0.48 z=0.1", + "args": { + "x": 0.48, + "z": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4813, + -0.0517, + 0.102 + ], + "gripper_width_after": 0.0285, + "holding_after": true, + "touched_during": true, + "think_s": 14.023627281188965, + "agent_obs_images": [ + "obs/s032_agentview.jpg", + "obs/s032_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s031_agentview.jpg", + "obs/s031_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 33, + "kind": "move_eef", + "frame_start": 700, + "frame_end": 719, + "command": "move_eef z=0.08 gripper=open", + "args": { + "z": 0.08, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.478, + -0.0519, + 0.081 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 3.151334762573242, + "agent_obs_images": [ + "obs/s033_agentview.jpg", + "obs/s033_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s032_agentview.jpg", + "obs/s032_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 34, + "kind": "move_eef", + "frame_start": 719, + "frame_end": 727, + "command": "move_eef z=0.2", + "args": { + "z": 0.2 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4816, + -0.0522, + 0.2001 + ], + "gripper_width_after": 0.0784, + "holding_after": false, + "touched_during": false, + "think_s": 0.007212400436401367, + "agent_obs_images": [ + "obs/s034_agentview.jpg", + "obs/s034_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 35, + "kind": "move_eef", + "frame_start": 727, + "frame_end": 759, + "command": "move_eef x=0.51 y=-0.235 z=0.08 gripper=open", + "args": { + "x": 0.51, + "y": -0.235, + "z": 0.08, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5125, + -0.2355, + 0.0816 + ], + "gripper_width_after": 0.0797, + "holding_after": false, + "touched_during": false, + "think_s": 6.017167806625366, + "agent_obs_images": [ + "obs/s035_agentview.jpg", + "obs/s035_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s034_agentview.jpg", + "obs/s034_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 36, + "kind": "move_eef", + "frame_start": 759, + "frame_end": 765, + "command": "move_eef x=0.54 y=-0.252 z=0.05", + "args": { + "x": 0.54, + "y": -0.252, + "z": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.539, + -0.2523, + 0.0512 + ], + "gripper_width_after": 0.0798, + "holding_after": false, + "touched_during": false, + "think_s": 4.751009941101074, + "agent_obs_images": [ + "obs/s036_agentview.jpg", + "obs/s036_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s035_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 37, + "kind": "move_eef", + "frame_start": 765, + "frame_end": 772, + "command": "move_eef z=0.016", + "args": { + "z": 0.016 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5408, + -0.2539, + 0.0179 + ], + "gripper_width_after": 0.0798, + "holding_after": false, + "touched_during": false, + "think_s": 0.0068166255950927734, + "agent_obs_images": [ + "obs/s037_agentview.jpg", + "obs/s037_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 38, + "kind": "move_eef", + "frame_start": 772, + "frame_end": 777, + "command": "move_eef x=0.557", + "args": { + "x": 0.557 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5536, + -0.2528, + 0.0164 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 4.44866943359375, + "agent_obs_images": [ + "obs/s038_agentview.jpg", + "obs/s038_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s037_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 39, + "kind": "move_eef", + "frame_start": 777, + "frame_end": 792, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5542, + -0.2534, + 0.0172 + ], + "gripper_width_after": 0.0282, + "holding_after": true, + "touched_during": true, + "think_s": 0.005996227264404297, + "agent_obs_images": [ + "obs/s039_agentview.jpg", + "obs/s039_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 40, + "kind": "move_eef", + "frame_start": 792, + "frame_end": 802, + "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.5563, + -0.254, + 0.121 + ], + "gripper_width_after": 0.0281, + "holding_after": true, + "touched_during": true, + "think_s": 0.007735490798950195, + "agent_obs_images": [ + "obs/s040_agentview.jpg", + "obs/s040_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 41, + "kind": "move_eef", + "frame_start": 802, + "frame_end": 819, + "command": "move_eef x=0.484 y=0.04 z=0.16", + "args": { + "x": 0.484, + "y": 0.04, + "z": 0.16 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4828, + 0.0402, + 0.1593 + ], + "gripper_width_after": 0.0281, + "holding_after": true, + "touched_during": true, + "think_s": 4.686285734176636, + "agent_obs_images": [ + "obs/s041_agentview.jpg", + "obs/s041_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s040_agentview.jpg", + "obs/s040_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 42, + "kind": "move_eef", + "frame_start": 819, + "frame_end": 826, + "command": "move_eef z=0.085", + "args": { + "z": 0.085 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.484, + 0.04, + 0.0873 + ], + "gripper_width_after": 0.0281, + "holding_after": true, + "touched_during": true, + "think_s": 4.165292739868164, + "agent_obs_images": [ + "obs/s042_agentview.jpg", + "obs/s042_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s041_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 43, + "kind": "move_eef", + "frame_start": 826, + "frame_end": 841, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.4841, + 0.0399, + 0.0873 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 0.005795001983642578, + "agent_obs_images": [ + "obs/s043_agentview.jpg", + "obs/s043_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 44, + "kind": "move_eef", + "frame_start": 841, + "frame_end": 853, + "command": "move_eef z=0.3", + "args": { + "z": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4822, + 0.04, + 0.2978 + ], + "gripper_width_after": 0.0787, + "holding_after": false, + "touched_during": false, + "think_s": 0.006421566009521484, + "agent_obs_images": [ + "obs/s044_agentview.jpg", + "obs/s044_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 45, + "kind": "move_eef", + "frame_start": 853, + "frame_end": 887, + "command": "move_eef x=0.484 y=0.3 z=0.15 gripper=close", + "args": { + "x": 0.484, + "y": 0.3, + "z": 0.15, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4863, + 0.301, + 0.1516 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 58.25127172470093, + "agent_obs_images": [ + "obs/s045_agentview.jpg", + "obs/s045_wrist.jpg" + ], + "agent_note": { + "shell": [ + "cd obs; python3 -c \"\nimport cv2\nim=cv2.imread('s044_wrist.jpg')\nc=im[150:420,0:440]\nc=cv2.resize(c,None,fx=2.5,fy=2.5,interpolation=cv2.INTER_CUBIC)\ncv2.imwrite('z2.png',c)\"" + ], + "viewed": [ + "obs/s045_agentview.jpg", + "obs/s045_wrist.jpg", + "obs/s044_agentview.jpg", + "obs/s044_wrist.jpg", + "obs/z2.png" + ] + } + }, + { + "attempt": 1, + "step": 46, + "kind": "move_eef", + "frame_start": 887, + "frame_end": 928, + "command": "move_eef z=0.05 speed=0.05", + "args": { + "z": 0.05, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4862, + 0.301, + 0.0515 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.0066530704498291016, + "agent_obs_images": [ + "obs/s046_agentview.jpg", + "obs/s046_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 47, + "kind": "move_eef", + "frame_start": 928, + "frame_end": 1178, + "command": "move_eef z=0.033 speed=0.03", + "args": { + "z": 0.033, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 1.5, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.4878, + 0.3034, + 0.0474 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 13.231701135635376, + "agent_obs_images": [ + "obs/s047_agentview.jpg", + "obs/s047_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s046_agentview.jpg", + "obs/s046_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 48, + "kind": "move_eef", + "frame_start": 1178, + "frame_end": 1179, + "command": "move_eef z=0.049", + "args": { + "z": 0.049 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4878, + 0.3033, + 0.0478 + ], + "gripper_width_after": 0.0021, + "holding_after": false, + "touched_during": false, + "think_s": 6.191935777664185, + "agent_obs_images": [ + "obs/s048_agentview.jpg", + "obs/s048_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 49, + "kind": "move_eef", + "frame_start": 1179, + "frame_end": 1221, + "command": "move_eef y=0.2 speed=0.05", + "args": { + "y": 0.2, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4879, + 0.2011, + 0.0479 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 0.04757285118103027, + "agent_obs_images": [ + "obs/s049_agentview.jpg", + "obs/s049_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 50, + "kind": "move_eef", + "frame_start": 1221, + "frame_end": 1246, + "command": "move_eef y=0.14 speed=0.05", + "args": { + "y": 0.14, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4888, + 0.1426, + 0.0488 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 2.8274474143981934, + "agent_obs_images": [ + "obs/s050_agentview.jpg", + "obs/s050_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s049_agentview.jpg", + "obs/s049_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 51, + "kind": "move_eef", + "frame_start": 1246, + "frame_end": 1261, + "command": "move_eef z=0.4 x=0.5 y=0.0", + "args": { + "z": 0.4, + "x": 0.5, + "y": 0.0 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4986, + 0.0005, + 0.3975 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 4.515362739562988, + "agent_obs_images": [ + "obs/s051_agentview.jpg", + "obs/s051_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s050_agentview.jpg", + "obs/s050_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 52, + "kind": "move_eef", + "frame_start": 1261, + "frame_end": 1278, + "command": "move_eef x=0.488 y=0.17 z=0.08", + "args": { + "x": 0.488, + "y": 0.17, + "z": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.486, + 0.1705, + 0.079 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 11.20922565460205, + "agent_obs_images": [ + "obs/s052_agentview.jpg", + "obs/s052_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s051_agentview.jpg", + "obs/s051_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 53, + "kind": "move_eef", + "frame_start": 1278, + "frame_end": 1284, + "command": "move_eef z=0.049", + "args": { + "z": 0.049 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4883, + 0.1711, + 0.0513 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.0069234371185302734, + "agent_obs_images": [ + "obs/s053_agentview.jpg", + "obs/s053_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 54, + "kind": "move_eef", + "frame_start": 1284, + "frame_end": 1319, + "command": "move_eef y=0.12 speed=0.03", + "args": { + "y": 0.12, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4885, + 0.1206, + 0.0514 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.006678104400634766, + "agent_obs_images": [ + "obs/s054_agentview.jpg", + "obs/s054_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 55, + "kind": "move_eef", + "frame_start": 1319, + "frame_end": 1333, + "command": "move_eef x=0.45 y=0.0 z=0.3", + "args": { + "x": 0.45, + "y": 0.0, + "z": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4472, + 0.0005, + 0.2974 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 8.159255504608154, + "agent_obs_images": [ + "obs/s055_agentview.jpg", + "obs/s055_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s054_agentview.jpg", + "obs/s054_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 56, + "kind": "move_eef", + "frame_start": 1333, + "frame_end": 1361, + "command": "move_eef x=0.49 y=-0.17 z=0.1 gripper=close", + "args": { + "x": 0.49, + "y": -0.17, + "z": 0.1, + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4906, + -0.1733, + 0.1009 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 99.40723967552185, + "agent_obs_images": [ + "obs/s056_agentview.jpg", + "obs/s056_wrist.jpg" + ], + "agent_note": { + "shell": [ + "cd obs; python3 -c \"\nimport cv2\nim=cv2.imread('s055_agentview.jpg')\nc=im[190:330,120:320]\nc=cv2.resize(c,None,fx=5,fy=5,interpolation=cv2.INTER_CUBIC)\ncv2.imwrite('z3.png',c)\nim=cv2.imread('s055_wrist.jpg')\nc=im[120:400,100:400]\nc=cv2.resize(c,None,fx=3,fy=3,interpolation=cv2.INTER_CUBIC)\ncv2.imwrite('z4.png',c)\"" + ], + "viewed": [ + "obs/z3.png", + "obs/z4.png" + ] + } + }, + { + "attempt": 1, + "step": 57, + "kind": "move_eef", + "frame_start": 1361, + "frame_end": 1367, + "command": "move_eef z=0.03", + "args": { + "z": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4887, + -0.1735, + 0.0318 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": false, + "think_s": 0.014884233474731445, + "agent_obs_images": [ + "obs/s057_agentview.jpg", + "obs/s057_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 58, + "kind": "move_eef", + "frame_start": 1367, + "frame_end": 1403, + "command": "move_eef y=-0.12 speed=0.03", + "args": { + "y": -0.12, + "speed": 0.03 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4893, + -0.1233, + 0.0328 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 0.007677316665649414, + "agent_obs_images": [ + "obs/s058_agentview.jpg", + "obs/s058_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 59, + "kind": "move_eef", + "frame_start": 1403, + "frame_end": 1653, + "command": "move_eef x=0.45 y=0.0 z=0.3", + "args": { + "x": 0.45, + "y": 0.0, + "z": 0.3 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 7.7, + "deg": 0.6 + }, + "eef_pos_after": [ + 0.4085, + -0.0095, + 0.2364 + ], + "gripper_width_after": 0.001, + "holding_after": false, + "touched_during": true, + "think_s": 5.824112892150879, + "agent_obs_images": [ + "obs/s059_agentview.jpg", + "obs/s059_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s059_agentview.jpg", + "obs/s058_agentview.jpg", + "obs/s058_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 60, + "kind": "move_eef", + "frame_start": 1653, + "frame_end": 1668, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.3726, + -0.0492, + 0.1905 + ], + "gripper_width_after": 0.0356, + "holding_after": false, + "touched_during": true, + "think_s": 9.081975936889648, + "agent_obs_images": [ + "obs/s060_agentview.jpg", + "obs/s060_wrist.jpg" + ] + } + ], + "task_events": [ + { + "frame": 710, + "attempt": 1, + "event": { + "step": 710, + "item": "product_red_1", + "event": "achieved" + } + }, + { + "frame": 835, + "attempt": 1, + "event": { + "step": 835, + "item": "product_blue_1", + "event": "achieved" + } + }, + { + "frame": 1320, + "attempt": 1, + "event": { + "step": 1320, + "item": "product_red_1", + "event": "lost" + } + }, + { + "frame": 1320, + "attempt": 1, + "event": { + "step": 1320, + "item": "product_blue_1", + "event": "lost" + } + }, + { + "frame": 1325, + "attempt": 1, + "event": { + "step": 1325, + "item": "product_red_1", + "event": "achieved" + } + }, + { + "frame": 1325, + "attempt": 1, + "event": { + "step": 1325, + "item": "product_blue_1", + "event": "achieved" + } + }, + { + "frame": 1410, + "attempt": 1, + "event": { + "step": 1410, + "item": "product_red_1", + "event": "lost" + } + }, + { + "frame": 1410, + "attempt": 1, + "event": { + "step": 1410, + "item": "product_blue_1", + "event": "lost" + } + } + ], + "frames": { + "n": 1698, + "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": 2352, + "dataset_index_range": [ + 3864362, + 3866060 + ], + "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_002659.json b/leaf/annotations/episode_002659.json new file mode 100644 index 0000000000000000000000000000000000000000..0a377d66569341526e16c3ffb6daacc4653a6791 --- /dev/null +++ b/leaf/annotations/episode_002659.json @@ -0,0 +1,1325 @@ +{ + "schema": "leaf-replay-1", + "source": { + "batch": "g61_evofull_20261025", + "run": "g61_evofull_20261025-gpt-6.1-sol-embodiedevocodex-harness-hidek_l2_knock_restore_s3000_full_F1_direct_k3_1025-130333_p20020", + "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": "50f1246b86249017a82bef866b7534f08fea9912bf249980f2fe826c78c5ba3d", + "run_status": "done", + "manifest_id": "0020", + "replay": { + "n_reports_checked": 27, + "n_mismatch": 0, + "max_eef_dev_m": 0.0 + }, + "backfill_provenance": { + "original_run": "/mnt/cpfs/workspace/agentic-robotics/worktrees/lffbench-robot-harnesses/runs/api/g61_evofull_20261025/g61_evofull_20261025-gpt-6.1-sol-embodiedevocodex-harness-hidek_l2_knock_restore_s3000_full_F1_direct_k3_1025-130333_p20020", + "frozen_run": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/source/runs/api/g61_evofull_20261025/g61_evofull_20261025-gpt-6.1-sol-embodiedevocodex-harness-hidek_l2_knock_restore_s3000_full_F1_direct_k3_1025-130333_p20020", + "runtime": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/source" + }, + "evaluation_config": { + "cond": "harness", + "feedback": "F1", + "mem": "full", + "k": 3, + "rep": 0, + "task": "l2_knock_restore", + "seed": 3000 + }, + "release_origin": { + "dataset": "supp-20261113-g61_evofull_20261025", + "episode_index": 26 + }, + "release_episode_index": 2659, + "pre_v181_sidecar_index": { + "episode_index": 26, + "dataset_index_range": [ + 47477, + 48141 + ] + } + }, + "agent": { + "harness": "embodied_evo_codex", + "harness_version": "0.163.0", + "harness_binary_sha256": "399ff69c431c066e40de318fba45c2b07f45a76b19939d247ee4828fc70c4215", + "model": "gpt-6.1-sol", + "effort": "high", + "provider": "openai", + "codex_catalog": "generic", + "auth": null, + "jail": true + }, + "task": { + "name": "l2_knock_restore", + "level": "L2", + "family": "hidden_variable", + "category": "state_restoration", + "capabilities": [ + "Perceive", + "Plan" + ], + "protocol": "within", + "max_attempts": 5, + "agent_max_steps": 40, + "instruction": "Move the ketchup from the tray into the basket. Everything else must stay on the tray.", + "seed": 3000, + "instance": { + "seed": 3000, + "tray_xy": [ + -0.054460821510850736, + -0.10162269117449049 + ], + "tray_yaw": -0.06528556657359899, + "basket_xy": [ + -0.018517127646359814, + 0.25772774765839546 + ], + "target_dx": 0.005584083346409148, + "target_yaw": 1.5443136503148176, + "neighbors": [ + "chocolate_pudding_1", + "butter_1" + ], + "nb_gap": [ + 0.06959134478253831, + 0.07594572550758519 + ], + "nb_dy": [ + -0.010817375591149434, + -0.011365500917055836 + ], + "nb_yaw": [ + 1.454179400025156, + 1.711243182439102 + ], + "victim": "chocolate_pudding_1", + "side": "left", + "land_gap": 0.01578565514117995, + "land_off": 0.012526175008785327, + "land_dyaw": 0.3083866602083124 + }, + "paper": { + "name": "Knock restore", + "cause": "L2", + "table_cause": "L2", + "hidden_variable": "Which neighbour moves", + "repair_within_attempt": true, + "oracle_first_attempt_pct": "100", + "naive_first_attempt_pct": "0", + "original_cause": "L2", + "original_table_cause": "L2" + }, + "canonical_cause": "L2", + "paper_long_horizon": false, + "instruction_original": "Move the ketchup from the tray into the basket. Everything else must stay on the tray." + }, + "run_outcome": { + "outcome_class": null, + "attempt_history": "S", + "n_attempts": 1, + "run_success": true, + "agent_final_report": "Attempt succeeded.\n\n- Grasped ketchup at `(0.625, -0.105, 0.117)`, yaw `0°`, and released it inside the basket at approximately `(0.647, 0.249, 0.172)`.\n- A carton slipped off during lifting. After an empty grasp, lowering to `z=0.0125` secured it; I returned it to the tray.\n- Final images showed ketchup in the basket and both cartons on the tray.\n- Recorded reusable grasp-verification and recovery procedures in `skills/` and `lessons/`.", + "mean_think_s": 23.62, + "outcome_class_original": "S?", + "outcome_class_status": "unresolved" + }, + "attempts": [ + { + "attempt": 1, + "success": true, + "outcome": { + "success": true, + "target_loc": "basket", + "locations": { + "ketchup_1": "basket", + "chocolate_pudding_1": "tray", + "butter_1": "tray" + }, + "off_tray": [], + "footprints": { + "ketchup_1": { + "center": [ + -0.019196370425557847, + 0.24928000713752957, + 0.9893921968147492 + ], + "yaw": -3.1414956875291633, + "half_xy": [ + 0.028113843917026083, + 0.018381474882918955 + ], + "zmin": 0.91658570202413, + "zmax": 1.0621986916053685 + }, + "chocolate_pudding_1": { + "center": [ + -0.04808115702305714, + -0.10280580924732001, + 0.9210403152986013 + ], + "yaw": 1.5168219990908918, + "half_xy": [ + 0.02531956298587713, + 0.041324772859474876 + ], + "zmin": 0.90717951463958, + "zmax": 0.9349011159576226 + }, + "butter_1": { + "center": [ + 0.03308078000757499, + -0.12315223290458298, + 0.9161131314784358 + ], + "yaw": 1.6459500184726272, + "half_xy": [ + 0.022590979923937375, + 0.03947856559490388 + ], + "zmin": 0.9073103600240463, + "zmax": 0.9249159029328252 + } + }, + "knocked": true, + "detail": "The ketchup is in the basket and everything else is on the tray.", + "detail_indirect": "The red bottle is in the basket and everything else is on the tray." + }, + "finish_reason": "Ketchup released inside basket; displaced carton recovered and returned to tray. Final images show both cartons on tray and ketchup in basket.", + "feedback_shown": "Attempt succeeded.", + "auto_ended": false, + "think_s": 36.808892011642456, + "feedback_f2": "Attempt succeeded. The ketchup is in the basket and everything else is on the tray.", + "judge_frames": [ + 634, + 664 + ], + "corrected_later_in_run": null, + "is_last_attempt_of_run": true, + "agent_finish": { + "messages": [ + "Both cartons are on the tray; ketchup remains in the basket. I’ll submit for verification." + ], + "shell": [ + "apply_patch() { patch -p0; }\npython3 - <<'PY' | apply_patch\nimport difflib\nrecords = {\n 'skills/recover_thin_object.md': '''# Recover a displaced thin object\n\nInputs: object XY estimate, local image scale and camera offset, short-axis\njaw yaw, support height, object thickness estimate, lift clearance, and budget.\nPreconditions: reachable exposed sides; no fragile or hazardous contents.\n\n1. Localize from a high wrist view, refining XY after the yaw change.\n2. Orient jaw closure across the shorter dimension, within maximum opening.\n3. Descend open in stages; grasp-point height must allow fingertips to\n overlap the thin sides without penetrating the support plane.\n4. Close and inspect width. Near-zero width means an empty grasp, not success.\n5. If images show correct XY but fingers are above the object, reopen and\n lower by a small increment bounded by fingertip-to-support clearance.\n6. Lift vertically, verifying object motion and retained jaw separation.\n7. Transfer above a clear interior support region, lower, release, retract.\n8. Inspect all task objects before submitting final verification.\n\nEvidence: carton recovery failed at EEF z=0.0268 (jaw width 0.0023), succeeded\nat z=0.0125 (width 0.0502, then 0.0474 after lift). Returned it at approximately\n(0.624,-0.106,0.061), yaw -90, releasing above tray floor. Both cartons were\nvisible entirely inside the tray after retracting to z=0.317.\nLimitations: support height and fingertip offset must be known or refined;\nabsolute heights here are episode evidence, not a universal prescription.\n''',\n 'submission/result.md': '''# Pre-submission visual result\n\nKetchup grasp: (0.625,-0.105,0.117), yaw 0, width about 0.037 m.\nKetchup release: (0.647,0.249,0.172), inside basket; visually upright afterward.\nA carton was displaced during the initial lift and required recovery.\nCarton regrasp: (0.552,-0.244,0.0125), yaw -90; width about 0.050 m.\nCarton release: (0.624,-0.106,0.061), centered inside the tray.\nFinal EEF retracte" + ], + "viewed": [ + "obs/s027_agentview.jpg", + "obs/s027_wrist.jpg" + ], + "command": "finish reason=\"Ketchup released inside basket; displaced carton recovered and returned to tray. Final images show both cartons on tray and ketchup in basket.\"", + "reply": { + "feedback": "Attempt succeeded.", + "message": "The episode is over. Stop now and report." + } + }, + "error_event_in_attempt": null, + "reviewed_operational_failure": null + } + ], + "commands": [ + { + "attempt": 1, + "step": 1, + "kind": "move_eef", + "frame_start": 0, + "frame_end": 23, + "command": "move_eef z=0.4 gripper=open", + "args": { + "z": 0.4, + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.4513, + -0.0, + 0.3981 + ], + "gripper_width_after": 0.0787, + "holding_after": false, + "touched_during": false, + "think_s": 33.657782316207886, + "agent_obs_images": [ + "obs/s001_agentview.jpg", + "obs/s001_wrist.jpg" + ], + "agent_note": { + "messages": [ + "I’ll inspect the scene, then plan a careful ketchup-only transfer." + ], + "reasoning": [ + "**Calibrating camera position**\n\nI need to calibrate using camera ground features at two heights, while also considering xy perturbation. I think keeping 40 commands is ample. First, I should raise the z-axis by 0.4 to get a better view of everything. It's important to ensure I have enough data to work with to achieve accurate calibration. My focus is on getting this right!" + ], + "shell": [ + "pwd && ls -la && find .. -name AGENTS.md -print && cat obs/a1_s000_state.json", + "cat README.md && mkdir -p skills lessons submission && command -v apply_patch" + ], + "viewed": [ + "obs/s000_agentview.jpg", + "obs/s000_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 2, + "kind": "move_eef", + "frame_start": 23, + "frame_end": 29, + "command": "move_eef x=0.5513 y=0.0 z=0.4", + "args": { + "x": 0.5513, + "y": 0.0, + "z": 0.4 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5496, + -0.0, + 0.4019 + ], + "gripper_width_after": 0.079, + "holding_after": false, + "touched_during": false, + "think_s": 19.204641342163086, + "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": 50, + "command": "move_eef x=0.65 y=-0.11 z=0.4", + "args": { + "x": 0.65, + "y": -0.11, + "z": 0.4 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6506, + -0.1101, + 0.4008 + ], + "gripper_width_after": 0.0797, + "holding_after": false, + "touched_during": false, + "think_s": 43.57962465286255, + "agent_obs_images": [ + "obs/s003_agentview.jpg", + "obs/s003_wrist.jpg" + ], + "agent_note": { + "messages": [ + "I’m calibrating wrist-view motion before approaching the bottle." + ], + "reasoning": [ + "**Considering patch application**\n\nI've noticed that I've made 11 calls already, and I'm trying to gather enough evidence for a pattern after the shift. I need to document this. It sounds like I need to use a shell command to write evidence and apply a patch using Python to parse files. I wonder if I can create a custom function to standardize the diff through a patch that’s installed. I’ll need to confirm by checking the command for the patch function.", + "**Assessing patch application**\n\nI’m thinking about using the function `apply_patch()` to manage patches effectively. It looks like I need to ensure that it satisfies the requirements while adding skills through detailed reasoning, even if those skills are untested. Specifically, I want to write a lesson focused exclusively on \"x calibration\" while planning the current steps involved. It feels important to make sure I'm thorough and clear in my reasoning, so everything aligns correctly." + ], + "shell": [ + "ls /usr/local/bin /usr/bin /tmp | rg 'patch|apply'", + "command -v patch; ls /tmp; ls /usr/local/bin | head -30", + "apply_patch() { patch -p0; }\napply_patch <<'PATCH'\n--- /dev/null\n+++ lessons/wrist_calibration.md\n@@ -0,0 +1,9 @@\n+# Wrist-view calibration evidence\n+\n+- At yaw 0, moving EEF x from 0.4513 to 0.5496 m at z approximately\n+ 0.40 m moved the stationary ketchup cap from (355,131) to (354,220).\n+- Thus positive robot x moves stationary features downward in the wrist\n+ image, approximately 905 pixels/metre at the cap's depth in this view.\n+- Changing camera height changes this scale; do not reuse it at low z.\n+- Gripper fingers appear near the bottom of the wrist view: the image\n+ center is NOT automatically the grasp point. Calibrate offset first.\n--- /dev/null\n+++ submission/plan.md\n@@ -0,0 +1,9 @@\n+# Current plan\n+\n+1. Calibrate wrist-view directions above the scene with an open gripper.\n+2. Estimate bottle XY using observations; refine from high and low views.\n+3. Grasp only its upper body, clear of the two food cartons on the tray.\n+4. Lift vertically and verify the bottle follows while cartons stay put.\n+5. Transfer above the basket, lower cautiously, release, and inspect.\n+\n+Initial tentative bottle XY: x about 0.65, y about -0.11; unverified.\nPATCH" + ], + "viewed": [ + "obs/s002_wrist.jpg", + "obs/s002_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 4, + "kind": "move_eef", + "frame_start": 50, + "frame_end": 73, + "command": "move_eef x=0.625 y=-0.106 z=0.24 speed=0.15", + "args": { + "x": 0.625, + "y": -0.106, + "z": 0.24, + "speed": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6247, + -0.106, + 0.242 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 46.58839273452759, + "agent_obs_images": [ + "obs/s004_agentview.jpg", + "obs/s004_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "**Calculating camera projections**\n\nI'm working on understanding the camera positioning and adjustments. I need to consider the fingers’ positioning around coordinates, especially focusing on the y and x axes. The estimate for the projections is showing some offsets, and there's a thought about needing to adjust the z coordinate slightly too. I’ll refine my calculations for the camera's positions and adjustments based on these metrics to get the precise projections I need." + ], + "shell": [ + "python3 - <<'PY'\nfrom PIL import Image\nimage = Image.open('obs/s003_wrist.jpg')\nimage.crop((0,365,512,445)).resize((1024,160)).save('obs/fingers_zoom.png')\nPY" + ], + "viewed": [ + "obs/s003_wrist.jpg", + "obs/s003_agentview.jpg", + "obs/fingers_zoom.png" + ] + } + }, + { + "attempt": 1, + "step": 5, + "kind": "move_eef", + "frame_start": 73, + "frame_end": 86, + "command": "move_eef x=0.625 y=-0.113 z=0.18 speed=0.1", + "args": { + "x": 0.625, + "y": -0.113, + "z": 0.18, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6253, + -0.1127, + 0.1829 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 31.510406494140625, + "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": 86, + "frame_end": 104, + "command": "move_eef x=0.625 y=-0.105 z=0.115 speed=0.08", + "args": { + "x": 0.625, + "y": -0.105, + "z": 0.115, + "speed": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6249, + -0.1052, + 0.1167 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 25.429611206054688, + "agent_obs_images": [ + "obs/s006_agentview.jpg", + "obs/s006_wrist.jpg" + ], + "agent_note": { + "messages": [ + "The bottle is isolated; I’ll grasp above the cartons." + ], + "reasoning": [ + "**Analyzing cap alignment**\n\nI'm working through some details about the cap and its placement related to the bottle. At a lower EEF of z .11, I think the cap should be positioned lower than .500 if it's above the EEF. Maybe I should align the bottle with the cap at the front? I also need to consider the gripper opening across the y-axis. The two fingertips need to straddle the bottle correctly, so I’ll apply a y correction to -.105 and think about the x value at .625." + ], + "viewed": [ + "obs/s005_agentview.jpg", + "obs/s005_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 7, + "kind": "move_eef", + "frame_start": 104, + "frame_end": 119, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.6249, + -0.1053, + 0.1166 + ], + "gripper_width_after": 0.037, + "holding_after": true, + "touched_during": true, + "think_s": 15.73952841758728, + "agent_obs_images": [ + "obs/s007_agentview.jpg", + "obs/s007_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "**Evaluating grip and positioning**\n\nI’m considering the hand position on the bottle cap, noting the details like fingers being down at 268 and the cap measuring between 258 and 276. Grasping at the midpoint around 260 seems like a good choice. I also want to ensure the wrist is well positioned so that the bottle's body is visible from the front, with the cap slightly below the frame, and that everything looks undisturbed. Alright, I’m feeling good about this!" + ], + "viewed": [ + "obs/s006_agentview.jpg", + "obs/s006_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 8, + "kind": "move_eef", + "frame_start": 119, + "frame_end": 145, + "command": "move_eef z=0.27 speed=0.12", + "args": { + "z": 0.27, + "speed": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.4, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6246, + -0.1053, + 0.2663 + ], + "gripper_width_after": 0.0368, + "holding_after": true, + "touched_during": true, + "think_s": 13.67552399635315, + "agent_obs_images": [ + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s007_agentview.jpg", + "obs/s007_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 9, + "kind": "move_eef", + "frame_start": 145, + "frame_end": 164, + "command": "move_eef z=0.4 speed=0.15", + "args": { + "z": 0.4, + "speed": 0.15 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6246, + -0.1053, + 0.3974 + ], + "gripper_width_after": 0.0368, + "holding_after": true, + "touched_during": true, + "think_s": 41.67603826522827, + "agent_obs_images": [ + "obs/s009_agentview.jpg", + "obs/s009_wrist.jpg" + ], + "agent_note": { + "messages": [ + "The bottle lifted, but a carton slipped out. I’ll recover it after placing the ketchup." + ], + "reasoning": [ + "**Adjusting measurements**\n\nI'm trying to determine the right measurements for grasping. The bottle bottom needs to be at .116, with an offset of .09. At a height of .4, the bottom should clear the rim at .15. I think I need to adjust the z-coordinate to .4 and then move the x and y coordinates to .62 and .28, respectively. It’s important to document any failures along the way. Let's keep track of this!", + "**Counting file lines**\n\nI'm trying to count the lines in the first file, which I think should be file 13. I should use unified counts for accuracy. The first lines seem to have some blank spaces and continuations. I might need to check if file 13 was even created, since there could be a patch issue due to being malformed. I need to adjust the count according to what I find." + ], + "shell": [ + "apply_patch() { patch -p0; }\napply_patch <<'PATCH'\n--- /dev/null\n+++ lessons/lift_neighbor_displacement.md\n@@ -0,0 +1,14 @@\n+# Neighbor displaced during verified bottle lift\n+\n+- Grasp at (0.625,-0.105,0.117), yaw 0, closed to 0.037 m.\n+- Vertical lift to z=0.266 carried the ketchup securely (width 0.0368 m).\n+- BUT the chocolate carton left the tray toward negative y and appeared\n+ on the table at agent-view pixel approximately (106,293).\n+- Initial and post-close views did not reveal that this would happen.\n+ Do not equate nonzero finger width with a clean isolated grasp.\n+- Always inspect ALL neighbors immediately after a short test lift.\n+- Recovery plan: place held target safely, then return displaced carton\n+ to the tray; final success requires both target and neighbor locations.\n+- Unresolved: bottle/carton contact versus gripper contact caused ejection.\n+ A higher cap grasp might reduce this risk in a similar scene.\n--- /dev/null\n+++ skills/verified_pick.md\n@@ -0,0 +1,16 @@\n+# Verify a grasp before transferring\n+\n+Inputs: target XY, grasp height, jaw yaw, lift increment (0.10-0.15 m),\n+clearance height, image paths, neighbor list, and remaining command budget.\n+Preconditions: top-down reachable grasp; known support plane; lift path clear.\n+\n+1. Approach open above the target; refine XY with wrist observations.\n+2. Descend without lateral travel; close and inspect measured jaw width.\n+3. Lift vertically by the test increment, then inspect fixed-camera views.\n+4. Require the target to rise with the fingers AND check every neighbor.\n+5. If a neighbor moves, stop the nominal plan and budget its restoration.\n+6. Only after this check, clear the rim and transfer horizontally.\n+\n+Evidence: ketchup closed at 0.037 m and followed a 0.15 m lift, but a carton\n+was displaced. Thus jaw width alone cannot establish task-level success.\n+Limitations: image-only verification cannot rule out hidden contacts.\nPATCH", + "apply_patch() { patch -p0; }\napply_patch <<'PATCH'\n--- /dev/null\n+++ lessons/lift_neighbor_displacement.md\n@@ -0,0 +1,13 @@\n+# Neighbor displaced during verified bottle lift\n+\n+- Grasp at (0.625,-0.105,0.117), yaw 0, closed to 0.037 m.\n+- Vertical lift to z=0.266 carried the ketchup securely (width 0.0368 m).\n+- BUT the chocolate carton left the tray toward negative y and appeared\n+ on the table at agent-view pixel approximately (106,293).\n+- Initial and post-close views did not reveal that this would happen.\n+ Do not equate nonzero finger width with a clean isolated grasp.\n+- Always inspect ALL neighbors immediately after a short test lift.\n+- Recovery plan: place held target safely, then return displaced carton\n+ to the tray; final success requires both target and neighbor locations.\n+- Unresolved: bottle/carton contact versus gripper contact caused ejection.\n+ A higher cap grasp might reduce this risk in a similar scene.\n--- /dev/null\n+++ skills/verified_pick.md\n@@ -0,0 +1,16 @@\n+# Verify a grasp before transferring\n+\n+Inputs: target XY, grasp height, jaw yaw, lift increment (0.10-0.15 m),\n+clearance height, image paths, neighbor list, and remaining command budget.\n+Preconditions: top-down reachable grasp; known support plane; lift path clear.\n+\n+1. Approach open above the target; refine XY with wrist observations.\n+2. Descend without lateral travel; close and inspect measured jaw width.\n+3. Lift vertically by the test increment, then inspect fixed-camera views.\n+4. Require the target to rise with the fingers AND check every neighbor.\n+5. If a neighbor moves, stop the nominal plan and budget its restoration.\n+6. Only after this check, clear the rim and transfer horizontally.\n+\n+Evidence: ketchup closed at 0.037 m and followed a 0.15 m lift, but a carton\n+was displaced. Thus jaw width alone cannot establish task-level success.\n+Limitations: image-only verification cannot rule out hidden contacts.\nPATCH" + ], + "viewed": [ + "obs/s008_agentview.jpg", + "obs/s008_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 10, + "kind": "move_eef", + "frame_start": 164, + "frame_end": 208, + "command": "move_eef x=0.62 y=0.28 z=0.4 speed=0.18", + "args": { + "x": 0.62, + "y": 0.28, + "z": 0.4, + "speed": 0.18 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.6193, + 0.2774, + 0.3995 + ], + "gripper_width_after": 0.0367, + "holding_after": true, + "touched_during": true, + "think_s": 10.869157075881958, + "agent_obs_images": [ + "obs/s010_agentview.jpg", + "obs/s010_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s009_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 11, + "kind": "move_eef", + "frame_start": 208, + "frame_end": 230, + "command": "move_eef x=0.65 y=0.25 z=0.28 speed=0.12", + "args": { + "x": 0.65, + "y": 0.25, + "z": 0.28, + "speed": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6467, + 0.2493, + 0.2799 + ], + "gripper_width_after": 0.0367, + "holding_after": true, + "touched_during": true, + "think_s": 17.226067304611206, + "agent_obs_images": [ + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s010_agentview.jpg", + "obs/s010_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 12, + "kind": "move_eef", + "frame_start": 230, + "frame_end": 258, + "command": "move_eef z=0.17 speed=0.08", + "args": { + "z": 0.17, + "speed": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6466, + 0.2492, + 0.172 + ], + "gripper_width_after": 0.0367, + "holding_after": true, + "touched_during": true, + "think_s": 14.343511581420898, + "agent_obs_images": [ + "obs/s012_agentview.jpg", + "obs/s012_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s011_agentview.jpg", + "obs/s011_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 13, + "kind": "move_eef", + "frame_start": 258, + "frame_end": 273, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.6466, + 0.2493, + 0.172 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 15.509595394134521, + "agent_obs_images": [ + "obs/s013_agentview.jpg", + "obs/s013_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s012_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 14, + "kind": "move_eef", + "frame_start": 273, + "frame_end": 303, + "command": "move_eef z=0.4 speed=0.16", + "args": { + "z": 0.4, + "speed": 0.16 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6462, + 0.249, + 0.3975 + ], + "gripper_width_after": 0.0794, + "holding_after": false, + "touched_during": false, + "think_s": 17.03910732269287, + "agent_obs_images": [ + "obs/s014_agentview.jpg", + "obs/s014_wrist.jpg" + ], + "agent_note": { + "messages": [ + "The ketchup is in the basket. I’m restoring the carton." + ], + "viewed": [ + "obs/s013_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 15, + "kind": "move_eef", + "frame_start": 303, + "frame_end": 359, + "command": "move_eef x=0.61 y=-0.23 z=0.3 speed=0.18", + "args": { + "x": 0.61, + "y": -0.23, + "z": 0.3, + "speed": 0.18 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.61, + -0.2287, + 0.3006 + ], + "gripper_width_after": 0.0799, + "holding_after": false, + "touched_during": false, + "think_s": 17.922888040542603, + "agent_obs_images": [ + "obs/s015_agentview.jpg", + "obs/s015_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s014_agentview.jpg" + ] + } + }, + { + "attempt": 1, + "step": 16, + "kind": "move_eef", + "frame_start": 359, + "frame_end": 390, + "command": "move_eef x=0.57 y=-0.2455 z=0.13 yaw=90 speed=0.12", + "args": { + "x": 0.57, + "y": -0.2455, + "z": 0.13, + "yaw": 90, + "speed": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.572, + -0.2444, + 0.1325 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 60.656810998916626, + "agent_obs_images": [ + "obs/s016_agentview.jpg", + "obs/s016_wrist.jpg" + ], + "agent_note": { + "shell": [ + "apply_patch() { patch -p0; }\napply_patch <<'PATCH'\n--- /dev/null\n+++ skills/wrist_xy.py\n@@ -0,0 +1,25 @@\n+\"\"\"Local yaw-zero visual servo; caller must supply calibrated geometry.\"\"\"\n+import json\n+import sys\n+\n+\n+def target_xy(eef_xy, target_pixel, pixels_per_metre, camera_x_offset,\n+ max_correction=0.10):\n+ if pixels_per_metre <= 0:\n+ raise ValueError(\"Positive local pixel scale required\")\n+ pixel_u, pixel_v = target_pixel\n+ correction_x = camera_x_offset - (pixel_v - 256) / pixels_per_metre\n+ correction_y = -(pixel_u - 256) / pixels_per_metre\n+ if max(abs(correction_x), abs(correction_y)) > max_correction:\n+ raise ValueError(\"Correction exceeds calibrated local region\")\n+ return [eef_xy[0] + correction_x, eef_xy[1] + correction_y]\n+\n+\n+if __name__ == \"__main__\":\n+ current_x, current_y, pixel_u, pixel_v, scale, offset = map(float, sys.argv[1:])\n+ print(json.dumps({\"target_xy\": target_xy(\n+ [current_x, current_y], [pixel_u, pixel_v], scale, offset),\n+ \"preconditions\": \"yaw zero, downward camera, local scale at target depth\",\n+ \"limitations\": \"offset and scale estimates require visual recheck\",\n+ \"evidence\": \"positive x translated cap downward; y translated oppositely\"}))\nPATCH\npython3 skills/wrist_xy.py 0.61 -0.2287 272 332 950 0.04 > submission/carton_approach.json\ncat submission/carton_approach.json", + "apply_patch() { patch -p0; }\napply_patch <<'PATCH'\n--- /dev/null\n+++ skills/wrist_xy.py\n@@ -0,0 +1,24 @@\n+\"\"\"Local yaw-zero visual servo; caller must supply calibrated geometry.\"\"\"\n+import json\n+import sys\n+\n+\n+def target_xy(eef_xy, target_pixel, pixels_per_metre, camera_x_offset,\n+ max_correction=0.10):\n+ if pixels_per_metre <= 0:\n+ raise ValueError(\"Positive local pixel scale required\")\n+ pixel_u, pixel_v = target_pixel\n+ correction_x = camera_x_offset - (pixel_v - 256) / pixels_per_metre\n+ correction_y = -(pixel_u - 256) / pixels_per_metre\n+ if max(abs(correction_x), abs(correction_y)) > max_correction:\n+ raise ValueError(\"Correction exceeds calibrated local region\")\n+ return [eef_xy[0] + correction_x, eef_xy[1] + correction_y]\n+\n+\n+if __name__ == \"__main__\":\n+ current_x, current_y, pixel_u, pixel_v, scale, offset = map(float, sys.argv[1:])\n+ print(json.dumps({\"target_xy\": target_xy(\n+ [current_x, current_y], [pixel_u, pixel_v], scale, offset),\n+ \"preconditions\": \"yaw zero, downward camera, local scale at target depth\",\n+ \"limitations\": \"offset and scale estimates require visual recheck\",\n+ \"evidence\": \"positive x translated cap downward; y translated oppositely\"}))\nPATCH\npython3 skills/wrist_xy.py 0.61 -0.2287 272 332 950 0.04 > submission/carton_approach.json\ncat submission/carton_approach.json" + ], + "viewed": [ + "obs/s015_agentview.jpg", + "obs/s015_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 17, + "kind": "move_eef", + "frame_start": 390, + "frame_end": 408, + "command": "move_eef x=0.553 y=-0.248 z=0.065 speed=0.08", + "args": { + "x": 0.553, + "y": -0.248, + "z": 0.065, + "speed": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5534, + -0.2479, + 0.0671 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 25.4967143535614, + "agent_obs_images": [ + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "**Evaluating carton measurements**\n\nI’m thinking about the carton top, estimating it might be around .04 inches thick. If the thickness is around .06, then my fingertips would measure about .05. If the carton is .02, I need to lower my measurement to .025 to properly grasp it at .015. I need to check at .07 first to refine centering using a yaw -90 camera. The carton seems small and safe enough overall." + ], + "viewed": [ + "obs/s016_agentview.jpg", + "obs/s016_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 18, + "kind": "move_eef", + "frame_start": 408, + "frame_end": 425, + "command": "move_eef x=0.552 y=-0.2435 z=0.025 speed=0.05", + "args": { + "x": 0.552, + "y": -0.2435, + "z": 0.025, + "speed": 0.05 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5521, + -0.2436, + 0.0269 + ], + "gripper_width_after": 0.08, + "holding_after": false, + "touched_during": false, + "think_s": 27.6681866645813, + "agent_obs_images": [ + "obs/s018_agentview.jpg", + "obs/s018_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s017_agentview.jpg", + "obs/s017_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 19, + "kind": "move_eef", + "frame_start": 425, + "frame_end": 440, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5519, + -0.2437, + 0.0268 + ], + "gripper_width_after": 0.0023, + "holding_after": false, + "touched_during": false, + "think_s": 34.11434078216553, + "agent_obs_images": [ + "obs/s019_agentview.jpg", + "obs/s019_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s018_agentview.jpg", + "obs/s018_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 20, + "kind": "move_eef", + "frame_start": 440, + "frame_end": 455, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5519, + -0.2438, + 0.0267 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": false, + "think_s": 33.43094253540039, + "agent_obs_images": [ + "obs/s020_agentview.jpg", + "obs/s020_wrist.jpg" + ], + "agent_note": { + "reasoning": [ + "**Planning tool actions**\n\nOkay, I’m thinking about the tool count, which is around 72. That leaves me with about 28 commands, giving me enough for around 13 images and patches. I need to execute a command like `move_eef z=.012` with the gripper open. It feels a bit risky since the gripper might close when it touches the carton. I think it’s better to open the gripper at its current position, then lower and close it afterward." + ], + "shell": [ + "apply_patch() { patch -p0; }\napply_patch <<'PATCH'\n--- /dev/null\n+++ lessons/flat_carton.md\n@@ -0,0 +1,8 @@\n+# Flat carton grasp height\n+\n+- Recovery approach used yaw 90 (reported as equivalent -90), XY near\n+ (0.552,-0.244), descending to EEF z=0.027.\n+- Closing reached width 0.0023 m without visible carton motion: empty.\n+- Likely fingertips (EEF minus about 0.01 m) remained above the thin box.\n+- Recovery: reopen, lower incrementally toward z=0.012, and reclose.\n+- Confirm by a short lift; never transfer after an empty-width closure.\nPATCH" + ], + "viewed": [ + "obs/s019_agentview.jpg", + "obs/s019_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 21, + "kind": "move_eef", + "frame_start": 455, + "frame_end": 463, + "command": "move_eef z=0.011 speed=0.04", + "args": { + "z": 0.011, + "speed": 0.04 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.552, + -0.2437, + 0.0125 + ], + "gripper_width_after": 0.0784, + "holding_after": false, + "touched_during": false, + "think_s": 6.3722124099731445, + "agent_obs_images": [ + "obs/s021_agentview.jpg", + "obs/s021_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 22, + "kind": "move_eef", + "frame_start": 463, + "frame_end": 478, + "command": "move_eef gripper=close", + "args": { + "gripper": "close" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.5519, + -0.2439, + 0.0125 + ], + "gripper_width_after": 0.0502, + "holding_after": true, + "touched_during": true, + "think_s": 13.871642589569092, + "agent_obs_images": [ + "obs/s022_agentview.jpg", + "obs/s022_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s021_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 23, + "kind": "move_eef", + "frame_start": 478, + "frame_end": 508, + "command": "move_eef z=0.13 speed=0.08", + "args": { + "z": 0.13, + "speed": 0.08 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.5519, + -0.2438, + 0.1279 + ], + "gripper_width_after": 0.0474, + "holding_after": true, + "touched_during": true, + "think_s": 6.968758821487427, + "agent_obs_images": [ + "obs/s023_agentview.jpg", + "obs/s023_wrist.jpg" + ], + "agent_note": {} + }, + { + "attempt": 1, + "step": 24, + "kind": "move_eef", + "frame_start": 508, + "frame_end": 541, + "command": "move_eef x=0.625 y=-0.105 z=0.16 speed=0.1", + "args": { + "x": 0.625, + "y": -0.105, + "z": 0.16, + "speed": 0.1 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.2, + "deg": 0.1 + }, + "eef_pos_after": [ + 0.6241, + -0.1063, + 0.1596 + ], + "gripper_width_after": 0.0463, + "holding_after": true, + "touched_during": true, + "think_s": 31.458991527557373, + "agent_obs_images": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ], + "agent_note": { + "messages": [ + "The lower grasp worked; the carton is securely lifted." + ], + "reasoning": [ + "**Recording carton placement**\n\nI'm reviewing the placement of the carton now. It looks like I need to record the outcome immediately. I think I have around 80 units on hand, which should be enough for the 20 I need to move the carton to the center of the tray at specific coordinates. \n\nI’ll ensure the carton fits within the tray's bounds while maintaining a 2 cm margin. The orientation is also crucial, as the box's long axis is angled 15 degrees in relation to the tray.\n**Placing carton on the tray**\n\nI need to position the carton in the middle of the tray, ensuring it's away from the butter at the front and the rails. The coordinates should be around x .625, y -0.105, and at a height (z) of 0.02. When I consider the grasping point in relation to the end-effector, it looks like I should adjust the box's placement.\n\nI'll aim for a drop of 0.025 and ensure the carton fits well within the tray boundaries while keeping the gripper tips at a safe height. Combining these steps should work smoothly!" + ], + "shell": [ + "apply_patch() { patch -p0; }\napply_patch <<'PATCH'\n--- lessons/flat_carton.md\n+++ lessons/flat_carton.md\n@@ -6,3 +6,8 @@\n - Likely fingertips (EEF minus about 0.01 m) remained above the thin box.\n - Recovery: reopen, lower incrementally toward z=0.012, and reclose.\n - Confirm by a short lift; never transfer after an empty-width closure.\n+\n+Confirmed recovery: at EEF z=0.0125, closure stopped at 0.0502 m.\n+The carton then followed a lift to z=0.1279; jaw width settled at 0.0474 m.\n+This distinguishes a thin-object height miss from an XY miss in this case.\n+The previous z=0.0268 closure had passed above the object's graspable sides.\nPATCH" + ], + "viewed": [ + "obs/s023_agentview.jpg", + "obs/s023_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 25, + "kind": "move_eef", + "frame_start": 541, + "frame_end": 575, + "command": "move_eef z=0.06 speed=0.06", + "args": { + "z": 0.06, + "speed": 0.06 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.1, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.624, + -0.1063, + 0.0613 + ], + "gripper_width_after": 0.0463, + "holding_after": true, + "touched_during": true, + "think_s": 13.037782907485962, + "agent_obs_images": [ + "obs/s025_agentview.jpg", + "obs/s025_wrist.jpg" + ], + "agent_note": { + "viewed": [ + "obs/s024_agentview.jpg", + "obs/s024_wrist.jpg" + ] + } + }, + { + "attempt": 1, + "step": 26, + "kind": "move_eef", + "frame_start": 575, + "frame_end": 590, + "command": "move_eef gripper=open", + "args": { + "gripper": "open" + }, + "ok": true, + "error": null, + "stopped_from_target": null, + "eef_pos_after": [ + 0.624, + -0.1063, + 0.0613 + ], + "gripper_width_after": 0.0777, + "holding_after": false, + "touched_during": true, + "think_s": 15.039215087890625, + "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": 590, + "frame_end": 634, + "command": "move_eef z=0.32 speed=0.12", + "args": { + "z": 0.32, + "speed": 0.12 + }, + "ok": true, + "error": null, + "stopped_from_target": { + "cm": 0.3, + "deg": 0.0 + }, + "eef_pos_after": [ + 0.6239, + -0.1063, + 0.3173 + ], + "gripper_width_after": 0.0797, + "holding_after": false, + "touched_during": false, + "think_s": 5.520228385925293, + "agent_obs_images": [ + "obs/s027_agentview.jpg", + "obs/s027_wrist.jpg" + ], + "agent_note": {} + } + ], + "task_events": [], + "frames": { + "n": 664, + "fps": 20, + "image_res": 256, + "phase_codes": { + "move": 0, + "gripper": 1, + "judge": 2 + }, + "initial_state": { + "eef_pos": [ + -0.20846466056582413, + -2.8682124719762124e-14, + 1.1732794757296403 + ], + "joint_pos": [ + 4.248669602219315e-14, + -0.16103738899999992, + -3.590958919585269e-14, + -2.44459747, + -3.000087308599816e-13, + 2.2267522, + 0.7853981633973531 + ], + "gripper_qpos": [ + 0.020541867755816148, + -0.02054184665779553 + ] + } + }, + "episode_index": 2659, + "dataset_index_range": [ + 5178936, + 5179600 + ], + "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/final/episode_000002_wrist_image.png b/leaf/final/episode_000002_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..e388607a3a29c6c1b192820883c7a6c65eae7a63 --- /dev/null +++ b/leaf/final/episode_000002_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca313f4311b71fd9c4f21d2f2913048c445142490e28cb2c8759aa7def16f6a4 +size 31292 diff --git a/leaf/final/episode_000008_wrist_image.png b/leaf/final/episode_000008_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..5f943f6193f2caa19ee4ef3e2f6fbc960f1aa169 --- /dev/null +++ b/leaf/final/episode_000008_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d685988e8c1c834c493bd2c69f6ddd67776b24e32bdd413953407b947dc8cce +size 41452 diff --git a/leaf/final/episode_000014_wrist_image.png b/leaf/final/episode_000014_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..9caca6a3ac323af0c5ed171cf6732c7fbae53aa4 --- /dev/null +++ b/leaf/final/episode_000014_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e3be8bf56c9e23d90a3c94c83a2a77881a5d9862d19b4ebff7b2d88b5b6da89a +size 33765 diff --git a/leaf/final/episode_000050_wrist_image.png b/leaf/final/episode_000050_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..d60f61d1af15302598b6f3e23339a55467a8e9c4 --- /dev/null +++ b/leaf/final/episode_000050_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abc0352d9a2d685962c262d1127deee2ff1fbbe41c0acd5901583dd03441e51f +size 42801 diff --git a/leaf/final/episode_000052_image.png b/leaf/final/episode_000052_image.png new file mode 100644 index 0000000000000000000000000000000000000000..dfaf1250657e44270c819b1872e5da5a918868de --- /dev/null +++ b/leaf/final/episode_000052_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b69beb9ab127b21aa1325e36e3b9508502d4e85b2d63117874577ee2a98b0fc +size 53084 diff --git a/leaf/final/episode_000080.npz b/leaf/final/episode_000080.npz new file mode 100644 index 0000000000000000000000000000000000000000..227e52109e96e578a067360cca0d896af290fe96 --- /dev/null +++ b/leaf/final/episode_000080.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d00f2aa566e053eab1aa78df84d95d15c579e9e6d7dbab919c9f15af26d543e8 +size 4062 diff --git a/leaf/final/episode_000200_image.png b/leaf/final/episode_000200_image.png new file mode 100644 index 0000000000000000000000000000000000000000..1fe2628f0e56e9a7b77152c7f134de5b6f601e53 --- /dev/null +++ b/leaf/final/episode_000200_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51d8d630275f42fc73bef16dd3905db3f83579e6628b79f8a63f5c46803249b8 +size 54041 diff --git a/leaf/final/episode_000237_wrist_image.png b/leaf/final/episode_000237_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..176d5f848ce3729c7dad60d591387f2307f5a11d --- /dev/null +++ b/leaf/final/episode_000237_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:018ebfbc5b9873af2c0d5d8c42df97b743c883ccc2d4ce14be0b0bfa96e7324c +size 37880 diff --git a/leaf/final/episode_000275_image.png b/leaf/final/episode_000275_image.png new file mode 100644 index 0000000000000000000000000000000000000000..390ed306e9e5c54b2be38130ca282b61064c668d --- /dev/null +++ b/leaf/final/episode_000275_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9556d0e4b04d7c60065ee3d3ed92be6b8e2e32a782b65ee5b265cca3f9e52cd5 +size 55829 diff --git a/leaf/final/episode_000291_image.png b/leaf/final/episode_000291_image.png new file mode 100644 index 0000000000000000000000000000000000000000..cff6f55d1f7ce069fd1ec6eab4d51d39221b02a8 --- /dev/null +++ b/leaf/final/episode_000291_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b2165218147318f2c9f454a2cc43117e70df0e2771fd40057375479c336c082 +size 53596 diff --git a/leaf/final/episode_000313.npz b/leaf/final/episode_000313.npz new file mode 100644 index 0000000000000000000000000000000000000000..67fbe11e1bdd93785fb9dace70c71c3a094cbc6e --- /dev/null +++ b/leaf/final/episode_000313.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bff35da04ea230e6bd1a2e3531b2116c708d671b41a171f4a582e0a2dd009ee4 +size 3630 diff --git a/leaf/final/episode_000324_image.png b/leaf/final/episode_000324_image.png new file mode 100644 index 0000000000000000000000000000000000000000..c8dab589b69895227fabcca28377b04ecdd9adc6 --- /dev/null +++ b/leaf/final/episode_000324_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54963a8b444a3fa3f0b011f0db9ab8122edc70ab21e1319fc27e0882b538a37b +size 55181 diff --git a/leaf/final/episode_000381.npz b/leaf/final/episode_000381.npz new file mode 100644 index 0000000000000000000000000000000000000000..25352a63fe2ad71c94eb1f34aec747c37a5b4db3 --- /dev/null +++ b/leaf/final/episode_000381.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ca77bc7f59f3569b3573bb6e939d9468fa955e1e9acdd4e1ffdaa689f4678c1 +size 3942 diff --git a/leaf/final/episode_000390.npz b/leaf/final/episode_000390.npz new file mode 100644 index 0000000000000000000000000000000000000000..f43f2159b9475f9485340dc2a63ffb82d7c0fb8e --- /dev/null +++ b/leaf/final/episode_000390.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:417ef186cea908bbe21004933abd5fb043acfce16f37ffba7368457019b05631 +size 4046 diff --git a/leaf/final/episode_000410_image.png b/leaf/final/episode_000410_image.png new file mode 100644 index 0000000000000000000000000000000000000000..7307db5c7d4aeebaf4d6e6f8a12556d83fe51a28 --- /dev/null +++ b/leaf/final/episode_000410_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3083842b6d63041917ec6325335e1668e3a535cfc6281ca5a9eddf69589c9974 +size 56263 diff --git a/leaf/final/episode_000438.npz b/leaf/final/episode_000438.npz new file mode 100644 index 0000000000000000000000000000000000000000..c4c09547fc257a71b9093101fe480179ad1abcc8 --- /dev/null +++ b/leaf/final/episode_000438.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9e5c4a0efdc791e5afbe2398afc1a931ee8c55447bd5ba652e769b647af13b8 +size 3838 diff --git a/leaf/final/episode_000454_wrist_image.png b/leaf/final/episode_000454_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..5422c6cdf25229f9d16c32ec3071152da7630a4e --- /dev/null +++ b/leaf/final/episode_000454_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab338c6825b0bbdeb1e0e810bd99a948237ab395e0c092360ebc463490664369 +size 40928 diff --git a/leaf/final/episode_000460_image.png b/leaf/final/episode_000460_image.png new file mode 100644 index 0000000000000000000000000000000000000000..ee402ba85151089353a192154a1bbdca373fa71e --- /dev/null +++ b/leaf/final/episode_000460_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:113d99cef34cedf5269880986301273dc5189b9a80438b1c26d4ae699c7520e4 +size 56666 diff --git a/leaf/final/episode_000536_wrist_image.png b/leaf/final/episode_000536_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..4f9e21674074ed4a53737f1426303a97deeb0821 --- /dev/null +++ b/leaf/final/episode_000536_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f19d88f23c409eef4c371f551c0e7b0bd1048846ea6a79e677b7ba6356851de3 +size 19680 diff --git a/leaf/final/episode_000538.npz b/leaf/final/episode_000538.npz new file mode 100644 index 0000000000000000000000000000000000000000..2e2c16614ee364e95586d61ecbe45a504b5b2093 --- /dev/null +++ b/leaf/final/episode_000538.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b46ec01d7662b6b70a5657d85080209b9e814183deefe0bd0550188996b76001 +size 3942 diff --git a/leaf/final/episode_000558_wrist_image.png b/leaf/final/episode_000558_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..bd4b5202c21b3045cbe4bf0bb520f416b4916ace --- /dev/null +++ b/leaf/final/episode_000558_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5ceda9ac07b3c2ef091f465a0d36c92d13173dea35b68fd6b0e2e3b04eaf73e +size 41693 diff --git a/leaf/final/episode_000575_image.png b/leaf/final/episode_000575_image.png new file mode 100644 index 0000000000000000000000000000000000000000..71aa13b6e8a1012f4172e403797e143b799a7b82 --- /dev/null +++ b/leaf/final/episode_000575_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76f1a539c6a76955f79e1a56558e26854aabc82eed88bddd11beb8495c6f1c67 +size 61645 diff --git a/leaf/final/episode_000640_wrist_image.png b/leaf/final/episode_000640_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..44e27590f8b4139d922163b1d3fd7d31b92645c4 --- /dev/null +++ b/leaf/final/episode_000640_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73e89724b965ee8bd7174d4dfa834d5a1193a76b5661cee9923682e966674e48 +size 27166 diff --git a/leaf/final/episode_000644_wrist_image.png b/leaf/final/episode_000644_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..5df3ab8e83a3e734663695d8a829dd532383fa72 --- /dev/null +++ b/leaf/final/episode_000644_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb84f337387878e6c24ea90f254578c3e27dfeb4aff32ddc8cdf8bfcef5a5ec4 +size 32679 diff --git a/leaf/final/episode_000707.npz b/leaf/final/episode_000707.npz new file mode 100644 index 0000000000000000000000000000000000000000..8d61c42ffae4ef9046e08e1dfb50c5f8fe6b131b --- /dev/null +++ b/leaf/final/episode_000707.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0668eb5d9ee5f26def1fc23baddc3c52249801ca38b5c08630895131b793fd4 +size 3750 diff --git a/leaf/final/episode_000707_image.png b/leaf/final/episode_000707_image.png new file mode 100644 index 0000000000000000000000000000000000000000..1ae07a30f4e4d99b1badefbb5d0b68c7aeae624f --- /dev/null +++ b/leaf/final/episode_000707_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f90de32926c0e8c88695453b9bdda7b4d9c6afca967b6267ea955009259cd2f +size 59708 diff --git a/leaf/final/episode_000710_image.png b/leaf/final/episode_000710_image.png new file mode 100644 index 0000000000000000000000000000000000000000..e569225816060abacf8e79fd0311ec69504668a0 --- /dev/null +++ b/leaf/final/episode_000710_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:087f1dba1c0464c5a7d947458579a6cebfa544e2c2756bfc594430685180d968 +size 53490 diff --git a/leaf/final/episode_000751_image.png b/leaf/final/episode_000751_image.png new file mode 100644 index 0000000000000000000000000000000000000000..048ef8b224aa59013c3986e8001ee0e106867344 --- /dev/null +++ b/leaf/final/episode_000751_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e94ebab06e121394243dc1d64ac2f806c2f08e1ed1bf8a2a5d428184983b8e0 +size 54845 diff --git a/leaf/final/episode_000770_image.png b/leaf/final/episode_000770_image.png new file mode 100644 index 0000000000000000000000000000000000000000..7671276336d0fb4a14f2552eb474882bd0836f20 --- /dev/null +++ b/leaf/final/episode_000770_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1321644924db1da4bf5730f30de4b3201398d5abffc1ba40f47db27b1ab33ff0 +size 54619 diff --git a/leaf/final/episode_000786_wrist_image.png b/leaf/final/episode_000786_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..3ace7d6e04d9f275a67d8686387793effdd3e499 --- /dev/null +++ b/leaf/final/episode_000786_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1dd4a02186cfab5a7a180b341f59c5247f2cc0d738067259098bdd3e50a7c81 +size 31708 diff --git a/leaf/final/episode_000799.npz b/leaf/final/episode_000799.npz new file mode 100644 index 0000000000000000000000000000000000000000..5eae16b86f6e263336ce1a39d8df71cb695bef60 --- /dev/null +++ b/leaf/final/episode_000799.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c83beff2f4abbbcf7055b257d1a1557e3f713de6a26e969deed4f58e7db29463 +size 3942 diff --git a/leaf/final/episode_000817_wrist_image.png b/leaf/final/episode_000817_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..4ea81f88041ed9a999c3830eda23c1ad97529d59 --- /dev/null +++ b/leaf/final/episode_000817_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce547bd6b5bf5ac7bb82b227d32db0309a82e6b37bd3b752d8665788d5279b71 +size 40236 diff --git a/leaf/final/episode_000845.npz b/leaf/final/episode_000845.npz new file mode 100644 index 0000000000000000000000000000000000000000..d2b42c954eee0821dba99e08679998e865647fba --- /dev/null +++ b/leaf/final/episode_000845.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97ca672e1d4ea8b8a76a221636efa073a8a68af5292b3045dff545dcd0e8031d +size 3838 diff --git a/leaf/final/episode_000911_image.png b/leaf/final/episode_000911_image.png new file mode 100644 index 0000000000000000000000000000000000000000..a00da51591dd53f41ffd92a06fc173ebae0f36d8 --- /dev/null +++ b/leaf/final/episode_000911_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:174e37cab267c0b24a59d598ed1e192d628197c118a8072128ba11662555196c +size 55698 diff --git a/leaf/final/episode_000915_wrist_image.png b/leaf/final/episode_000915_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..b81ca788ea1268cbd3555efe95c4817fcb8cc746 --- /dev/null +++ b/leaf/final/episode_000915_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eec35b1695b3925ffda5cfc2afdcbf9098ea1cbfc9d24c91eea9ce515fb6439a +size 32687 diff --git a/leaf/final/episode_000956_image.png b/leaf/final/episode_000956_image.png new file mode 100644 index 0000000000000000000000000000000000000000..638a890a093e90f2c48ec6edf0eed667cd1f8753 --- /dev/null +++ b/leaf/final/episode_000956_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73e24a1280e318dc81032a438bbd9b53efc7ea431b8242b0e313fcc93fce8758 +size 55683 diff --git a/leaf/final/episode_000991_image.png b/leaf/final/episode_000991_image.png new file mode 100644 index 0000000000000000000000000000000000000000..bdc3bd489590366fcea3bba96f5901dda2cc893a --- /dev/null +++ b/leaf/final/episode_000991_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4e755b68623a1cbe17160f059dcf6f098c721c7cab76a49b4c410e0055caec52 +size 54582 diff --git a/leaf/final/episode_000993.npz b/leaf/final/episode_000993.npz new file mode 100644 index 0000000000000000000000000000000000000000..dca0d0d96af8ab74bc8892a735c15cdf03b295a7 --- /dev/null +++ b/leaf/final/episode_000993.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b52868e58ca77dfca028e6d795d60219f02cd3fd7be65c51966cd613ac11cc1b +size 3942 diff --git a/leaf/final/episode_001007.npz b/leaf/final/episode_001007.npz new file mode 100644 index 0000000000000000000000000000000000000000..42fbac04d52d86f3f44aa5f520513c336b9fee15 --- /dev/null +++ b/leaf/final/episode_001007.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d436c810de7b2fa4a1462001f27437caf0753d781e949facc43fd778d0624608 +size 4046 diff --git a/leaf/final/episode_001126.npz b/leaf/final/episode_001126.npz new file mode 100644 index 0000000000000000000000000000000000000000..263906c5fda7e9ae9bdb4e93566b28f93cce8399 --- /dev/null +++ b/leaf/final/episode_001126.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92f420f27269dcb41f15c38a75a46bff02d978b8a09e96b9be9cfa21356da8e5 +size 3838 diff --git a/leaf/final/episode_001192_image.png b/leaf/final/episode_001192_image.png new file mode 100644 index 0000000000000000000000000000000000000000..69a9974132fa77811c9c040388f23e06c44097ff --- /dev/null +++ b/leaf/final/episode_001192_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b45e62d3dc7a25d7d7597819b82f6540b326ba6659e75a0781567b73a1b319c8 +size 58555 diff --git a/leaf/final/episode_001208_wrist_image.png b/leaf/final/episode_001208_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..0a8d9537fdc92ae2bc0285144846ed89d1010216 --- /dev/null +++ b/leaf/final/episode_001208_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8774e62d3dafbfa765efac17defeae7f1ee3ceca4f09d86b9e0fc8d949fa9ce7 +size 37713 diff --git a/leaf/final/episode_001209_wrist_image.png b/leaf/final/episode_001209_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..50e6753bc731aa670e8cf51da379dbbb9c887b1c --- /dev/null +++ b/leaf/final/episode_001209_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:327f4ad961c68fecbcc1025705724a7a788b8306d420d087a900d0889dd435fc +size 24114 diff --git a/leaf/final/episode_001212_image.png b/leaf/final/episode_001212_image.png new file mode 100644 index 0000000000000000000000000000000000000000..af89c1d2b780cd52d3119152247db6c30f222b3e --- /dev/null +++ b/leaf/final/episode_001212_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32eaafd35dbd001ab37889803b35c38760b63b9806402cb749c51b031fd18d0a +size 57534 diff --git a/leaf/final/episode_001263_image.png b/leaf/final/episode_001263_image.png new file mode 100644 index 0000000000000000000000000000000000000000..e4cb61aea2616100d755e34f2ea7469be70f5e1b --- /dev/null +++ b/leaf/final/episode_001263_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b85f2c60abb2dbd2e489f09bae4e417c6767d737c16964bea8a54ab2722bfde1 +size 59646 diff --git a/leaf/final/episode_001265_wrist_image.png b/leaf/final/episode_001265_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..dd085f95ddee5cba0f195e9f53cdd18fd44943d3 --- /dev/null +++ b/leaf/final/episode_001265_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c32e4771ca814c6327eccdea934c35ac6a34bb41358a0c2048349f8b8ad1f838 +size 26425 diff --git a/leaf/final/episode_001302.npz b/leaf/final/episode_001302.npz new file mode 100644 index 0000000000000000000000000000000000000000..9db5419b51aedb18e618126881eb0effb47491d1 --- /dev/null +++ b/leaf/final/episode_001302.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aaa2ed527bc09b28676183171d10a34c3597cb5dce7947748c8cd9496a1f919b +size 3734 diff --git a/leaf/final/episode_001343.npz b/leaf/final/episode_001343.npz new file mode 100644 index 0000000000000000000000000000000000000000..6fa5744dcfbeff5b3995e0f2e2479b519d8a8645 --- /dev/null +++ b/leaf/final/episode_001343.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d2db11f72fe76229958f8aaec5645b45f3352fcb617bd5bd81e93e1631c5518 +size 3734 diff --git a/leaf/final/episode_001365.npz b/leaf/final/episode_001365.npz new file mode 100644 index 0000000000000000000000000000000000000000..c0f7cd1f81003b3f22d85fed64feb3762bab388f --- /dev/null +++ b/leaf/final/episode_001365.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:513cdc187398fc900997cedae8b0822ac65d0c353777ce5d3445f3a0f5d39b61 +size 4150 diff --git a/leaf/final/episode_001377_image.png b/leaf/final/episode_001377_image.png new file mode 100644 index 0000000000000000000000000000000000000000..760faf28a2fc6dfd5a9961db87019943ce46d25c --- /dev/null +++ b/leaf/final/episode_001377_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fdd9a3602cb520ef645a9cb154bc400c37318c262ef3572e34fe334eeaa6c724 +size 55434 diff --git a/leaf/final/episode_001397.npz b/leaf/final/episode_001397.npz new file mode 100644 index 0000000000000000000000000000000000000000..12198df35de5cd574491f50691a19a9a75045e54 --- /dev/null +++ b/leaf/final/episode_001397.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87ab0e1eec2c9bc4b7bf513b6aba7611d5305b37615c519df73a49167be5af9e +size 3854 diff --git a/leaf/final/episode_001406_image.png b/leaf/final/episode_001406_image.png new file mode 100644 index 0000000000000000000000000000000000000000..ce1ab236c7e3502ce4de0f705208c99b940367af --- /dev/null +++ b/leaf/final/episode_001406_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f7a7316bc7b5281f3edaaebbbd72eaa7050171975ceebfa793f85db43a902835 +size 61993 diff --git a/leaf/final/episode_001460.npz b/leaf/final/episode_001460.npz new file mode 100644 index 0000000000000000000000000000000000000000..548b140645e5e3c1c389ebb013ec2affe4107b3a --- /dev/null +++ b/leaf/final/episode_001460.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee71f6ace8a6ae7f8c8b7c4e549fca768bfb19210c033623bcc0da778cdecc1a +size 3854 diff --git a/leaf/final/episode_001485_image.png b/leaf/final/episode_001485_image.png new file mode 100644 index 0000000000000000000000000000000000000000..c2131848f8926aa061c064ad6e8ae9efb44fc856 --- /dev/null +++ b/leaf/final/episode_001485_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c01fa37a58a7cb529de4ecffdf9fcb347e7a34cad7acfc2d45fdc29914166f36 +size 55211 diff --git a/leaf/final/episode_001494_image.png b/leaf/final/episode_001494_image.png new file mode 100644 index 0000000000000000000000000000000000000000..1ddf6b64a5cc2f6fd5e59fc99e65a55e0d7b18af --- /dev/null +++ b/leaf/final/episode_001494_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e6f304e8140fd859bdb4397245ac582db08ae65193a65e07f510179fddfa0607 +size 56328 diff --git a/leaf/final/episode_001516_wrist_image.png b/leaf/final/episode_001516_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..9f79701b7f58c2f7fcd05969b27681e948a1e7fc --- /dev/null +++ b/leaf/final/episode_001516_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ddcd8c8f3a3d08a82ba78d3f7405d9ad549b855545ca4778c1d09b55ee77820c +size 41001 diff --git a/leaf/final/episode_001523_wrist_image.png b/leaf/final/episode_001523_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..a036066f044f42181508d75608ea2e4f436765d8 --- /dev/null +++ b/leaf/final/episode_001523_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9799312f84225c7bb68888e4a0b309b02aa6a5484f4e11cbd93db4e0d770f31e +size 28768 diff --git a/leaf/final/episode_001528.npz b/leaf/final/episode_001528.npz new file mode 100644 index 0000000000000000000000000000000000000000..03a571e3f58bb9e60725925566b673b2d647e4ab --- /dev/null +++ b/leaf/final/episode_001528.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50df6a1bcb04b9e961b22a1012a9508bd695726c35178a65b5a3156bf3ef9636 +size 3630 diff --git a/leaf/final/episode_001537_wrist_image.png b/leaf/final/episode_001537_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..f4d933e32d091c97f9b9038f4e80a42d30917e62 --- /dev/null +++ b/leaf/final/episode_001537_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be66f5cc8fffc9f7b0d92a7bfaf96271102838e1b7b8637f4dff86ace645fa30 +size 36208 diff --git a/leaf/final/episode_001541_wrist_image.png b/leaf/final/episode_001541_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..cb779c774404991644e18e9dd5ab698c8a209ad1 --- /dev/null +++ b/leaf/final/episode_001541_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:27c6cc690505c19d017110c0ac99f51d040b2b8ab2b0b67958a0563c5a437dd1 +size 32463 diff --git a/leaf/final/episode_001577_wrist_image.png b/leaf/final/episode_001577_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..48ea56587d38339058849536fdd9c451d7532e9b --- /dev/null +++ b/leaf/final/episode_001577_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:884a935a583420f57a58e1a4ff97b21e9b2992d2712d971a8ae90920667c791e +size 45246 diff --git a/leaf/final/episode_001701_image.png b/leaf/final/episode_001701_image.png new file mode 100644 index 0000000000000000000000000000000000000000..8304196e447b77d138e532dca2048f82c9216ff1 --- /dev/null +++ b/leaf/final/episode_001701_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e21974eb2c13059e86787e77da646b6937f44bcaaab87c96a2f75f2bd2163f78 +size 57062 diff --git a/leaf/final/episode_001731_wrist_image.png b/leaf/final/episode_001731_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..614a4211bec72869cfad821464762855154572b4 --- /dev/null +++ b/leaf/final/episode_001731_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4bb52712c63bc33f408b2a418770cb84b8fb74af5ee5936b0eeec3411af89d6e +size 49506 diff --git a/leaf/final/episode_001747.npz b/leaf/final/episode_001747.npz new file mode 100644 index 0000000000000000000000000000000000000000..ae6e29d9301fb0abcb0fd1187dbff76c0b9d0e51 --- /dev/null +++ b/leaf/final/episode_001747.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fa15c8a4ba00751762708c1fdcea123e22a6dbb281568c5e9d39937bf03bb47 +size 3958 diff --git a/leaf/final/episode_001771_wrist_image.png b/leaf/final/episode_001771_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..5cb18ba0ddbb8c0e2d23e4eb9d46129d4ef3e508 --- /dev/null +++ b/leaf/final/episode_001771_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8e1453f5cf757d74a0e71da41b305138844547dcc34a2330fb3ab4fbf2fb023 +size 40772 diff --git a/leaf/final/episode_001818_image.png b/leaf/final/episode_001818_image.png new file mode 100644 index 0000000000000000000000000000000000000000..a34832fd61dc6bc11be5d5fc6bb169f3de31e85e --- /dev/null +++ b/leaf/final/episode_001818_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cffd8d82c9e4c8b2fa2f3ec7c4da9d4e278ef823682e7021377a63a5f43deb08 +size 52793 diff --git a/leaf/final/episode_001858.npz b/leaf/final/episode_001858.npz new file mode 100644 index 0000000000000000000000000000000000000000..5c52c83d97f3df9c71a8711b24790e21d95b5f6a --- /dev/null +++ b/leaf/final/episode_001858.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f345e4e350f89f287863535aacac8bf064afda30c76264e42a0017c7ddc96967 +size 4046 diff --git a/leaf/final/episode_001888_wrist_image.png b/leaf/final/episode_001888_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..24d48c8eded36572ba203959996780ba8c487544 --- /dev/null +++ b/leaf/final/episode_001888_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d7c47f62a9b122ced5028099641848cdf50b7492a8083d933e7d0f336389dcd +size 41369 diff --git a/leaf/final/episode_001896.npz b/leaf/final/episode_001896.npz new file mode 100644 index 0000000000000000000000000000000000000000..b2f5dc1f86bf88aa497b40de21bd8560d31f6764 --- /dev/null +++ b/leaf/final/episode_001896.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c52355e519f3195b2265680d7611e5e6fb044af89fde2b133dab5a275e1ebe90 +size 3630 diff --git a/leaf/final/episode_001940_image.png b/leaf/final/episode_001940_image.png new file mode 100644 index 0000000000000000000000000000000000000000..da6ca7da41164806cc939d910b3cd2c4c33f851c --- /dev/null +++ b/leaf/final/episode_001940_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eafdf1a2c6203ac8da4fb94834c17dd72d31da8814d0f7ab0fc2028ebd51e9a3 +size 55518 diff --git a/leaf/final/episode_001948_image.png b/leaf/final/episode_001948_image.png new file mode 100644 index 0000000000000000000000000000000000000000..d09c46e4e52f46a82989b2d1ed742455ae778ecd --- /dev/null +++ b/leaf/final/episode_001948_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ac4f1e4e9c04b908aef71e6d3229261a98ef059e8b6b1c35ad2aa83693db98c4 +size 61100 diff --git a/leaf/final/episode_001989.npz b/leaf/final/episode_001989.npz new file mode 100644 index 0000000000000000000000000000000000000000..adf29b367b23cc844d4cd49ad5d311eff2b0651b --- /dev/null +++ b/leaf/final/episode_001989.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:69f04980a5b51b6c94c60c7a479be6a61a746c4100f64c260f383ee9a2adff2b +size 3750 diff --git a/leaf/final/episode_001990_image.png b/leaf/final/episode_001990_image.png new file mode 100644 index 0000000000000000000000000000000000000000..c6e9c17b7eca4bb0eceb4c8d732af37806b61202 --- /dev/null +++ b/leaf/final/episode_001990_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37cf79019d7afaada377ec695d1d4c248f14da2630f6b59f196465d8cc82737a +size 62389 diff --git a/leaf/final/episode_001996.npz b/leaf/final/episode_001996.npz new file mode 100644 index 0000000000000000000000000000000000000000..429e8859c1513be94304a22616565b58e039c232 --- /dev/null +++ b/leaf/final/episode_001996.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd7a26909f49d21c8bad53f4d9f7dccf026f1e17db60041911bdfc6d22bd1ad3 +size 3838 diff --git a/leaf/final/episode_002048.npz b/leaf/final/episode_002048.npz new file mode 100644 index 0000000000000000000000000000000000000000..1b8331b4edb96e64e8d769da2b167665c017ada7 --- /dev/null +++ b/leaf/final/episode_002048.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e7939a07cc38175995228707519464f38d5c6337ca7a517ac29ebf3011c36d0 +size 3630 diff --git a/leaf/final/episode_002050_wrist_image.png b/leaf/final/episode_002050_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..ac4ee2b355cde3e49f36e8ab9cb18cbc742c8434 --- /dev/null +++ b/leaf/final/episode_002050_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58306eea132483efd42ab8e5e266a8c7908cc84b241c984d0b63f4a41ff9baee +size 35213 diff --git a/leaf/final/episode_002062_wrist_image.png b/leaf/final/episode_002062_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..85213c6a6eed7c49954b7ada6b2a7f5617848fbc --- /dev/null +++ b/leaf/final/episode_002062_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7d5cda41d65d7731e146b07005c10071e141411072ab3763d0c8259d66dd7ce +size 33229 diff --git a/leaf/final/episode_002115_image.png b/leaf/final/episode_002115_image.png new file mode 100644 index 0000000000000000000000000000000000000000..c3cbc50c7f67e8cab599dbf76ac928e8b4f2430e --- /dev/null +++ b/leaf/final/episode_002115_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b0f7dbcef30d784fbb836ea915d718188296235f5a6b071ccf70a7881b8b1aa +size 55092 diff --git a/leaf/final/episode_002163_wrist_image.png b/leaf/final/episode_002163_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..7d847489c2d2b3d5c08cca00855776dd35f4679b --- /dev/null +++ b/leaf/final/episode_002163_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f5c1196baa11621e75ffd5b547d4a7bd6883362be9f4cda84e8c8736e05be24 +size 38052 diff --git a/leaf/final/episode_002175_wrist_image.png b/leaf/final/episode_002175_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..989e05fbb494b6da39623a99de9ceca58574fd23 --- /dev/null +++ b/leaf/final/episode_002175_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d7c92cb37fb6db02a8d81b4c836c2df883c864d4926d526ec5667726b75cefe +size 34061 diff --git a/leaf/final/episode_002215_wrist_image.png b/leaf/final/episode_002215_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..6d23dcc50e027a2e0892ed35845ca2fd83ba5231 --- /dev/null +++ b/leaf/final/episode_002215_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72c1cb0ce87239660de6907ebac00318e39315d1c2673e3e20b48690367769de +size 47776 diff --git a/leaf/final/episode_002277_image.png b/leaf/final/episode_002277_image.png new file mode 100644 index 0000000000000000000000000000000000000000..24fa04a0e53ad0702ef53469d07ee4dbc1177275 --- /dev/null +++ b/leaf/final/episode_002277_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd90dd6df619f04edae59ebe6bf3171bd561c4ef61bc360e91df06a2df194eab +size 57356 diff --git a/leaf/final/episode_002320_wrist_image.png b/leaf/final/episode_002320_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..6e593de87e63822aca17bc49e4c4c6a88adb97db --- /dev/null +++ b/leaf/final/episode_002320_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:566b1743cc043964504f318f6a699eca363cfb2da4aa5a21227049d7b92e244c +size 17931 diff --git a/leaf/final/episode_002360_image.png b/leaf/final/episode_002360_image.png new file mode 100644 index 0000000000000000000000000000000000000000..457f83f015c3a0cd04b4cf5defffc214d314faf7 --- /dev/null +++ b/leaf/final/episode_002360_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:881f889ef4384d32528acbec2b8abfb692ab018d65a986dba6b37b7378544f3b +size 56900 diff --git a/leaf/final/episode_002361_image.png b/leaf/final/episode_002361_image.png new file mode 100644 index 0000000000000000000000000000000000000000..e6895e4a607af5ebe1fd54eb4350bcde02ec4c5a --- /dev/null +++ b/leaf/final/episode_002361_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:220d77130bf9b368cce7c4b20b7b69c05ac1a69c292154fc615bdc0f3cc3b6db +size 57128 diff --git a/leaf/final/episode_002365_image.png b/leaf/final/episode_002365_image.png new file mode 100644 index 0000000000000000000000000000000000000000..67d95fa9bb26a4a2db267e6a3aa7d1d7e6de0f72 --- /dev/null +++ b/leaf/final/episode_002365_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e42a6f1dbd8776ae237f53ee0d554ce1277bad97706e06cbacfa570ea5bb6c89 +size 56630 diff --git a/leaf/final/episode_002376.npz b/leaf/final/episode_002376.npz new file mode 100644 index 0000000000000000000000000000000000000000..ecf5951d2599c80da46c03f7a3f3ca57ba08a262 --- /dev/null +++ b/leaf/final/episode_002376.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73ea639a62e7a6aacf2048ab3fa76240a4269472ba22e27cd1aef07fd14f3bde +size 3958 diff --git a/leaf/final/episode_002474_image.png b/leaf/final/episode_002474_image.png new file mode 100644 index 0000000000000000000000000000000000000000..4eb885647f8bdafff9b82a000e68257ae30dd43d --- /dev/null +++ b/leaf/final/episode_002474_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a744a07189beea0f1d85479d18e605ac1ef284a39b79acee784edd483a42228 +size 55543 diff --git a/leaf/final/episode_002522_image.png b/leaf/final/episode_002522_image.png new file mode 100644 index 0000000000000000000000000000000000000000..301840add54b13e801d95f726b247b1839c7518a --- /dev/null +++ b/leaf/final/episode_002522_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7bf4d48e2a74e45a73a2eb71e18c34f980fb8d6d3aa006b5ac14f6692e76098 +size 54196 diff --git a/leaf/final/episode_002529_wrist_image.png b/leaf/final/episode_002529_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..02be841334b2bc509f4ecd8858a083f4a99dd8aa --- /dev/null +++ b/leaf/final/episode_002529_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40e5f3ed1962d447ef346f757f8690c7519f78064228b7e1a1ee8621fae35fc6 +size 44828 diff --git a/leaf/final/episode_002581.npz b/leaf/final/episode_002581.npz new file mode 100644 index 0000000000000000000000000000000000000000..483218962bdfecf1e30555977018a2164f000c2a --- /dev/null +++ b/leaf/final/episode_002581.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5842a2a42bd6e3f0c8624385269284c30f5b231016e78b897828f5614bb2fd63 +size 3734 diff --git a/leaf/final/episode_002585.npz b/leaf/final/episode_002585.npz new file mode 100644 index 0000000000000000000000000000000000000000..a490dad73beefc05cf26ee34f7ac91296fb63d62 --- /dev/null +++ b/leaf/final/episode_002585.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56cfd91b845f471694f9ae43708c5c5775ddc0ff4e22eb2954e62659fcf4e239 +size 4150 diff --git a/leaf/final/episode_002654_image.png b/leaf/final/episode_002654_image.png new file mode 100644 index 0000000000000000000000000000000000000000..2ff0b59b336456370faff9a364ee1aff16450786 --- /dev/null +++ b/leaf/final/episode_002654_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c94d2d733bd418803b031c71318223428416834c5a7d39d2718774b333dfd816 +size 53794 diff --git a/leaf/final/episode_002659_image.png b/leaf/final/episode_002659_image.png new file mode 100644 index 0000000000000000000000000000000000000000..07b9f026f4b68814f0728515cebd70ef4e755b58 --- /dev/null +++ b/leaf/final/episode_002659_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2fc2130343c02f5fa9f165bf5b3a360599ff9213027967cff992cb00fd8145a4 +size 70498 diff --git a/leaf/final/episode_002689.npz b/leaf/final/episode_002689.npz new file mode 100644 index 0000000000000000000000000000000000000000..953e05a7d778a1ca7afbef254ca9e5c49093a9be --- /dev/null +++ b/leaf/final/episode_002689.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba8cd3a0ad5764d390d69bb0211b9d0a52ad030eb489f510732a9f6a6c29c794 +size 3942 diff --git a/leaf/final/episode_002700_wrist_image.png b/leaf/final/episode_002700_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..4289b54f8e05b288c288fbbec0361725fce41996 --- /dev/null +++ b/leaf/final/episode_002700_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a27c65ef04958aa30ad4eeecfd1f640105e252d495b673c32919b64b6ccc2399 +size 42032 diff --git a/leaf/final/episode_002710.npz b/leaf/final/episode_002710.npz new file mode 100644 index 0000000000000000000000000000000000000000..a030fc1a6db4a19f36e4c9d0f619aeb820cb9ee5 --- /dev/null +++ b/leaf/final/episode_002710.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0cc467f21a4d8566c6891892e6e19c2d0caeceea01290b8bdbfb35637315aecb +size 3630 diff --git a/leaf/final/episode_002766_wrist_image.png b/leaf/final/episode_002766_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..6dba598ca152d0f4ab886652b52819afb3e87f2c --- /dev/null +++ b/leaf/final/episode_002766_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6647b630f567222c85fc28d70e9767f99ac3a9e1c379019c3b60846201fafd3b +size 38012 diff --git a/leaf/final/episode_002868_wrist_image.png b/leaf/final/episode_002868_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..08608fdd80fa92e27adeb6c5c208104a0588bbc5 --- /dev/null +++ b/leaf/final/episode_002868_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d13f475549fa9d8539b51614329cb3ba740e5b98c78c7fd61cc584e0b6e75ee +size 41722 diff --git a/leaf/final/episode_002920_wrist_image.png b/leaf/final/episode_002920_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..2d3a5f4498d6dd09fc25911d0451180a08a41e72 --- /dev/null +++ b/leaf/final/episode_002920_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c273c84d625d58b29f4c208b24fa48ee527848dd6af6e1bfa897182538678de4 +size 57939 diff --git a/leaf/final/episode_002955_wrist_image.png b/leaf/final/episode_002955_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..01d576fb917393c02f8aa2718916ef1cd42cdf10 --- /dev/null +++ b/leaf/final/episode_002955_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d31de5f1c07b530d2f81cba2d7e14654bf400a6164901e092a36300c3720636 +size 32101 diff --git a/leaf/final/episode_002989_wrist_image.png b/leaf/final/episode_002989_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..2400a851572905b62517f3a8d5a372013b5a07e1 --- /dev/null +++ b/leaf/final/episode_002989_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:267c511c16e6e8d20809ae8698e39180cf87f0e856b3f421cef41bac626bf14e +size 43069 diff --git a/leaf/final/episode_003040_image.png b/leaf/final/episode_003040_image.png new file mode 100644 index 0000000000000000000000000000000000000000..e19506f17ddef7ff6d5583886388d454670a0f3c --- /dev/null +++ b/leaf/final/episode_003040_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a21c4807acffbb614ae63abc78da36b1baea013c2222fd094da36d677cdb66a +size 63191 diff --git a/leaf/final/episode_003045_image.png b/leaf/final/episode_003045_image.png new file mode 100644 index 0000000000000000000000000000000000000000..8597a615c7b2120bea5b2caf606047ad4ff8310e --- /dev/null +++ b/leaf/final/episode_003045_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:498ee7f7381ffb4fca5f6752e3d71fc88bf002eb979a18d81e3a5cc22579fcb9 +size 70365 diff --git a/leaf/final/episode_003088_wrist_image.png b/leaf/final/episode_003088_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..763dac3b86e7d3d187d26cf74c1fbfec958a414f --- /dev/null +++ b/leaf/final/episode_003088_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9fc49e557ed5931612917c081fcaadb5437f2c3906af7ae361177053e90fbd2 +size 38347 diff --git a/leaf/final/episode_003104_image.png b/leaf/final/episode_003104_image.png new file mode 100644 index 0000000000000000000000000000000000000000..74b3fa03a9d7063b8e219c9c6a49b9bf15042942 --- /dev/null +++ b/leaf/final/episode_003104_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92eae36df8c6ba8129b5a0242bdb2a364eb7160db2e86472a9b7f102fb1ed0a3 +size 56346 diff --git a/leaf/final/episode_003124_image.png b/leaf/final/episode_003124_image.png new file mode 100644 index 0000000000000000000000000000000000000000..93824d19203ec2114e20d04ddd6383ab0c3f9068 --- /dev/null +++ b/leaf/final/episode_003124_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42ee16df3d696e5e92f7139aa5b7d6f32e79891903fd05b991415a2bfecea81f +size 51824 diff --git a/leaf/final/episode_003132_image.png b/leaf/final/episode_003132_image.png new file mode 100644 index 0000000000000000000000000000000000000000..0fbbdbe7d5fb88833e7745d531054b5b24de47ec --- /dev/null +++ b/leaf/final/episode_003132_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4973002adaff746f0cdcfea1084e98c7afe96857f0ba622bea99e0d9e2f89ce +size 56178 diff --git a/leaf/final/episode_003135.npz b/leaf/final/episode_003135.npz new file mode 100644 index 0000000000000000000000000000000000000000..5831c649f71e540809151706fdc3fb91c66f2b2c --- /dev/null +++ b/leaf/final/episode_003135.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb500b617a2bbc881d4b5c3ad428c956c841f9b5da881df3d93751179b8a9815 +size 3958 diff --git a/leaf/final/episode_003172_wrist_image.png b/leaf/final/episode_003172_wrist_image.png new file mode 100644 index 0000000000000000000000000000000000000000..d0e7a30409534f958dc5bc72af838793f2033f93 --- /dev/null +++ b/leaf/final/episode_003172_wrist_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1cff883ef006e92a073ae0ce37472ae98899f1bb1d8d3690265633bff5fc8c68 +size 16696 diff --git a/leaf/final/episode_003175.npz b/leaf/final/episode_003175.npz new file mode 100644 index 0000000000000000000000000000000000000000..d3aa1493a1be753eec6d73304d3a88fb9af9b197 --- /dev/null +++ b/leaf/final/episode_003175.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11157c6835152dbff6c7f1832dce0706f1344e56481027d7489ee196a4652018 +size 4062 diff --git a/leaf/final/episode_003182.npz b/leaf/final/episode_003182.npz new file mode 100644 index 0000000000000000000000000000000000000000..1ceb57fbfbe6793b8faa78cc028eb9da04c9a07f --- /dev/null +++ b/leaf/final/episode_003182.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:311e23adbce39a58fe4f2b9928da66d384a5f780dbb46c900e5838b17aba8138 +size 3734 diff --git a/leaf/final/episode_003213.npz b/leaf/final/episode_003213.npz new file mode 100644 index 0000000000000000000000000000000000000000..9bd5b9302d1af6114e403efffd068121833aaaf4 --- /dev/null +++ b/leaf/final/episode_003213.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a20179a424cc9f9efc2b6922f5368aa08ef64d9aa74fe1a46276b6a10478ce4 +size 3734 diff --git a/leaf/final/episode_003215.npz b/leaf/final/episode_003215.npz new file mode 100644 index 0000000000000000000000000000000000000000..6e2482491cc8ece2aacbb9617a6d4207cc7ce3dc --- /dev/null +++ b/leaf/final/episode_003215.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe5801a900b03c1cc46426bf8670c12b03e4dc627b0d89b32ec43d4a53fadfcd +size 3734 diff --git a/leaf/final/episode_003238_image.png b/leaf/final/episode_003238_image.png new file mode 100644 index 0000000000000000000000000000000000000000..c5a87ac16864a0b45e1203bab493c969ed9e4fe9 --- /dev/null +++ b/leaf/final/episode_003238_image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d960755ac8fb7e86ba54406155bf27da95022e837accbb25f8d33f2f6a023af9 +size 58290 diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/claude_code.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/claude_code.py new file mode 100644 index 0000000000000000000000000000000000000000..fe42682aac7bf5331eba70d056ad18a2c454a470 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/claude_code.py @@ -0,0 +1,514 @@ +"""Claude Code CLI as a native harness (docs/15 §3.3; flags measured in research_notes/harness接入调研/02 §2.1). + +Two variants: + claude_code arm B : -p --bare (system prompt ~400 chars, no CLAUDE.md / auto-memory / hooks / plugins) + claude_code_full arm B': same but without --bare: Claude Code's full system prompt; still a one-time config dir and + HOME, an empty opaque work dir, --tools "" and only our MCP server +Both: process env is exactly the whitelist (env -i equivalent; plus the calling HTTP(S) proxy, base.proxy_env), +HOME / CLAUDE_CONFIG_DIR / TMPDIR are one-time dirs +under /tmp/lffstate/, the work dir is /tmp/lffrun/<12 hex> (its path is written into the system prompt), the MCP +server is scripts/mcp_robot_server.py on the run's session. + +Two ways to authenticate (auth=): + apikey ANTHROPIC_API_KEY (api_env) + oauth a Claude subscription: the long-lived token of `claude setup-token`, passed as CLAUDE_CODE_OAUTH_TOKEN + (api_env; never taken from the calling environment). claude_code_full only: --bare reads nothing but + ANTHROPIC_API_KEY / apiKeyHelper (2.1.267 --help). +Measured with 2.1.267 against the fake server (2026-10-20): the same single request in both modes, identical system +prompt, tools, messages and parameters; oauth sends Authorization: Bearer instead of x-api-key, two more beta flags +(oauth-2025-04-20, extended-cache-ttl-2025-04-11) and cache_control ttl=1h. Pins are per auth mode (pin name +claude_code_full-oauth). + +Early exit: `claude -p` ends when the model replies without a tool call, also mid-episode. scripts/harness_run.py then +sends the reference driver's nudge with `claude -p --resume ` (resume_argv), as for Codex. Hence no +--no-session-persistence: the session transcript is kept in the one-time CLAUDE_CONFIG_DIR (removed after the run); +the audit allows only this run's session. Measured against the fake server: the resumed request has the same system +prompt, tools, parameters and headers, then the earlier turns and the nudge as a user message. + +Fail-closed launch: before the real run the same argv / env is started once against a local fake Anthropic server +(free) with a schema-only MCP server; the first request's tool list, system prompt, harness-added message prefix and +request parameters are normalised and hashed, and the launch is refused unless the hash equals the pinned one +(pins/claude_code*.json, written by tests/harness_selfcheck after the self-check passed). During the real run the +stream's init event is checked again (tool list); on a mismatch the process is killed. +""" +import copy +import json +import os +import re +import shutil +import subprocess +import sys +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + new_run_dir, proxy_env, snapshot_tree) +from .fakeapi import FakeAnthropic +from .trajectory import TrajWriter, strip_mcp + +ROOT = C.ROOT +MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py") +MCP_TOOLS = ["mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images"] +BASE_PATH = "/usr/bin:/bin" +OAUTH_KEY = "CLAUDE_CODE_OAUTH_TOKEN" +PREFLIGHT_CREDENTIAL = dict(apikey=("ANTHROPIC_API_KEY", "sk-preflight-not-a-key"), + oauth=(OAUTH_KEY, "sk-ant-oat01-" + "x" * 95 + "AA")) # dummies, only for the fake server + + +def claude_bin(): + return os.environ.get("LFF_CLAUDE_BIN") or shutil.which("claude") or "claude" + + +def _norm(s, spec): + """Remove what legitimately differs between runs from preset prompt text: paths of the one-time dirs, dates.""" + for k, v in sorted(dict(spec.state_dirs, cwd=spec.cwd).items(), key=lambda kv: -len(kv[1])): + s = s.replace(v, f"<{k.upper()}>") + s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "", s) + s = re.sub(r"-tmp-lffrun-[0-9a-f]{12}", "", s) # auto-memory dir name derived from the cwd + s = re.sub(r"(cc_version=\d+\.\d+\.\d+)\.[0-9a-f]+", r"\1.", s) # billing header suffix varies per request + s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "", s) + s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "", s) + s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "", s) + return s + + +def request_fingerprint(body, headers, spec, first_message): + """Normalised preset part of the first request + the checks that do not need a pin.""" + problems = [] + system = body.get("system") + if isinstance(system, str): + system = [dict(type="text", text=system)] + sys_blocks = [dict(text=_norm(b.get("text", ""), spec), cache=bool(b.get("cache_control"))) for b in system or []] + tools = [dict(name=t.get("name"), description=t.get("description"), input_schema=t.get("input_schema")) + for t in body.get("tools") or []] + if [t["name"] for t in tools] != MCP_TOOLS: + problems.append(f"tool list is {[t['name'] for t in tools]}, expected {MCP_TOOLS}") + msgs = body.get("messages") or [] + first = msgs[0] if msgs else {} + content = first.get("content") + if isinstance(content, str): + content = [dict(type="text", text=content)] + prefix, found = [], False + for b in content or []: + if b.get("type") == "text" and b.get("text") == first_message: + found = True + break + prefix.append(_norm(b.get("text", "") if b.get("type") == "text" else json.dumps(b, sort_keys=True), spec)) + if not found: + problems.append("the first user message does not contain our first message byte-for-byte as one block") + params = {k: body.get(k) for k in ("model", "max_tokens", "thinking", "output_config", "context_management", + "temperature", "top_p", "top_k", "tool_choice")} + fp = dict(system=sys_blocks, tools=tools, user_prefix=prefix, params=params, + anthropic_beta=sorted((headers.get("anthropic-beta") or headers.get("Anthropic-Beta") or "").split(",")), + system_chars=sum(len(b.get("text", "")) for b in system or [])) + return fp, problems + + +class ClaudeCode(HarnessAdapter): + name = "claude_code" + bare = True + uses_mcp = True + clean_dirs = ("home", "config", "tmp") + ancestor_files = ("CLAUDE.md", "CLAUDE.local.md", ".claude", "AGENTS.md") + can_resume = True + capabilities = dict( + only_benchmark_tools=Cap("yes", "preflight", '--tools "" + --strict-mcp-config: request tools = 3 MCP tools'), + images_reach_model=Cap("yes", "probe", "MCP image content forwarded as image blocks, md5 equal"), + non_persistent_session=Cap("yes", "probe", "only this run's session (kept for -p --resume) in the one-time " + "config dir, removed after the run"), + pinned_version=Cap("yes", "launch", "claude --version + binary sha256 in harness.json; pin per version"), + machine_readable_events=Cap("yes", "stream", "--output-format stream-json --verbose"), + tool_calls_logged=Cap("yes", "stream", "tool_use / tool_result in stream + mcp_transcript + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "--model / --effort; request output_config.effort checked"), + persistent_memory=Cap("absent", "probe", "--bare: no auto-memory; canaries never reach the request"), + instruction_file_injection=Cap("absent", "probe", "--bare: CLAUDE.md discovery off; canaries absent"), + web_access=Cap("absent", "preflight", "no WebFetch / WebSearch tool in the request"), + host_file_read=Cap("absent", "probe", "no Read tool; MCP shell is jailed; view_images confined"), + builtin_shell=Cap("absent", "preflight", "no Bash tool in the request"), + subagent_delegation=Cap("absent", "preflight", "no Agent / Task tool in the request"), + background_execution=Cap("absent", "preflight", "no Bash / Monitor tool in the request"), + ) + + def __init__(self, api_env=None, max_budget_usd=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + python=None, extra_args=None, jail=False, auth="apikey"): + """api_env: the only API variables passed to the harness: {"ANTHROPIC_API_KEY": ...} (auth="apikey") or + {"CLAUDE_CODE_OAUTH_TOKEN": ...} (auth="oauth", a subscription token of `claude setup-token`), optional + "ANTHROPIC_BASE_URL". Never inherited from the calling environment. jail: run the CLI in the + native-harness jail (lffbench/harnesses/jail.py; /proc stays the host's: Bun needs it).""" + if auth not in PREFLIGHT_CREDENTIAL: + raise ValueError(f"auth must be one of {sorted(PREFLIGHT_CREDENTIAL)}, not {auth!r}") + if auth == "oauth" and self.bare: + raise ValueError("claude_code (--bare) authenticates only with ANTHROPIC_API_KEY / apiKeyHelper; " + "use claude_code_full for a subscription token") + other = PREFLIGHT_CREDENTIAL["oauth" if auth == "apikey" else "apikey"][0] + if other in (api_env or {}): + raise ValueError(f"auth={auth}: api_env must not hold {other} (the CLI would use it instead)") + self.auth = auth + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(claude_bin(), proc="host") + self.api_env = dict(api_env or {}) + self.proxy = proxy_env() + self.max_budget_usd = max_budget_usd + self.timeout_s = timeout_s + self.pins_dir = pins_dir + self.allow_unpinned = allow_unpinned + self.python = python or sys.executable + self.extra_args = list(extra_args or []) + self._version = None + + # ------------------------------------------------------------------------------------------------ version + def version(self): + if self._version is None: + b = claude_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent"), capture_output=True, + text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[0] + self._version = dict(version=v, binary=binary_info(b)) + return self._version + + def pin_key(self, ep): + v = self.version() + name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def auth_info(self): + key = PREFLIGHT_CREDENTIAL[self.auth][0] + return dict(mode=self.auth, credential_var=key, credential_set=bool(self.api_env.get(key)), + keys=sorted(self.api_env)) + + # ------------------------------------------------------------------------------------------------ prepare + def mcp_config(self, session_path=None, describe=False): + """describe: for config_sha256 only (jailed, no relay is set up for it).""" + args = ["--session", session_path] if session_path else ["--schema-only"] + if describe or self.jail is None: + cmd, a = ("" if self.jail is not None else self.python), [MCP_SCRIPT] + args + else: + cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args) + return {"mcpServers": {"lff": {"type": "stdio", "command": cmd, "args": a, "env": {"PATH": BASE_PATH}}}} + + def argv(self, spec_paths, ep, first_message): + a = [claude_bin(), "-p", first_message] + if self.bare: + a.append("--bare") + a += ["--tools", "", "--strict-mcp-config", "--mcp-config", spec_paths["mcp_config"], + "--allowedTools", ",".join(MCP_TOOLS), "--permission-mode", "dontAsk", "--disable-slash-commands", + "--output-format", "stream-json", "--verbose", "--model", ep.model, "--effort", ep.effort] + if self.max_budget_usd: + a += ["--max-budget-usd", str(self.max_budget_usd)] + return a + self.extra_args + + @staticmethod + def session_ids(stdout_path): + """Session ids of the init events in the stream, in order (one per launch / resume).""" + out = [] + try: + for line in open(stdout_path, encoding="utf-8", errors="replace"): + if line.startswith("{") and '"init"' in line: + d = json.loads(line) + if d.get("type") == "system" and d.get("subtype") == "init" and d.get("session_id"): + out.append(d["session_id"]) + except (OSError, ValueError): + pass + return out + + def resume_argv(self, h, message): + """`claude -p ... --resume `: the launch's flags unchanged, the message in the place of the + first message (right after -p, before the variadic --allowedTools).""" + sids = self.session_ids(h.spec.stdout_path) + if not sids: + raise HarnessRefused("resume: no session id in the stream") + a = list(h.spec.argv) + return a[:2] + [message] + a[3:] + ["--resume", sids[0]] + + def env(self, state): + # CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: measured 2026-10-21 with 2.1.299 and claude-fable-5-1: when the model's + # safeguards flag a request, the CLI otherwise answers it, and the rest of the session, with another model + # (claude-opus-4-8) under the requested model's name; with it, a flagged request ends as a refusal + # (system event model_refusal_no_fallback) and the run stays on the model under test + e = dict(PATH=BASE_PATH, HOME=state["home"], CLAUDE_CONFIG_DIR=state["config"], TMPDIR=state["tmp"], + LANG="C.UTF-8", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1", DISABLE_AUTOUPDATER="1", + DISABLE_TELEMETRY="1", DISABLE_ERROR_REPORTING="1", MCP_TIMEOUT="60000", MCP_TOOL_TIMEOUT="900000", + CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK="1") + e.update(self.proxy) + e.update(self.api_env) + return e + + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, home=os.path.join(root, "home"), config=os.path.join(root, "config"), + tmp=os.path.join(root, "tmp")) + for k in ("home", "config", "tmp"): + os.makedirs(state[k], exist_ok=True) + return state + + def prepare(self, ep, first_message, reuse_state=None): + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + mcp_path = os.path.join(state["state"], "mcp.json") + with open(mcp_path, "w") as f: + json.dump(self.mcp_config(ep.session_path), f) + argv = self.argv(dict(mcp_config=mcp_path), ep, first_message) + spec = LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state, + first_message=first_message, config_files=dict(mcp_config=mcp_path), + stdout_path=os.path.join(ep.log_dir, "claude_stream.jsonl"), + stderr_path=os.path.join(ep.log_dir, "claude_stderr.txt"), + redact_argv={2: f""}, + timeout_s=self.timeout_s) + return spec + + def config_sha256(self, spec, ep): + """Hash of everything configurable (argv without the first message, MCP config, env values except keys / + one-time dirs).""" + argv = [("" if a == spec.config_files["mcp_config"] else a) for a in self.logged_argv(spec)[3:]] + env = {k: (v if k not in self.api_env else "") for k, v in spec.env.items() + if k not in ("HOME", "CLAUDE_CONFIG_DIR", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS} + return C.sha256_json(dict(argv=argv, mcp=self.mcp_config("", describe=True), env=env)) + + # ------------------------------------------------------------------------------------------------ preflight + def preflight(self, spec, ep, record_dir=None): + """Run the identical command against a fake API (free); refuse on any mismatch with the pin.""" + t0 = time.time() + fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start() + pre_state = self._state_dirs() + try: + mcp_path = os.path.join(pre_state["state"], "mcp.json") + with open(mcp_path, "w") as f: + json.dump(self.mcp_config(None), f) + argv = self.argv(dict(mcp_config=mcp_path), ep, spec.first_message) + env = {k: v for k, v in self.env(pre_state).items() if k not in self.api_env} # no real credential + cred_key, cred_dummy = PREFLIGHT_CREDENTIAL[self.auth] + env.update({"ANTHROPIC_BASE_URL": fake.base_url, cred_key: cred_dummy}) + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre_state.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=180) + reqs = fake.message_requests() + if not reqs: + raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): " + f"{r.stderr.decode('utf-8', 'replace')[-500:]}") + n, body = reqs[0] + headers = {} + if record_dir: + headers = json.load(open(os.path.join(record_dir, f"req_{n:03d}.json"))).get("headers", {}) + fp, problems = request_fingerprint(body, headers, spec, spec.first_message) + init = next((json.loads(x) for x in r.stdout.decode("utf-8", "replace").splitlines() + if x.startswith('{"type":"system"') and '"init"' in x), {}) + if init.get("tools") != MCP_TOOLS: + problems.append(f"init event tools {init.get('tools')}") + want_src = "ANTHROPIC_API_KEY" if self.auth == "apikey" else "none" # none = no API key: the OAuth token + if init.get("apiKeySource") != want_src: + problems.append(f"init apiKeySource {init.get('apiKeySource')!r}, expected {want_src!r} for " + f"auth={self.auth}") + if self.bare and "memory_paths" in init: + problems.append("init event has memory_paths under --bare") + if [s.get("status") for s in init.get("mcp_servers", [])] != ["connected"]: + problems.append(f"MCP servers {init.get('mcp_servers')}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + fp_sha = C.sha256_json(fp) + out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs), + tools=[t["name"] for t in fp["tools"]], effort_in_request=(fp["params"].get("output_config") + or {}).get("effort"), + model_in_request=fp["params"].get("model"), init_tools=init.get("tools"), + memory_paths=init.get("memory_paths"), dt_s=round(time.time() - t0, 1), problems=problems) + if out["effort_in_request"] != ep.effort: + problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}") + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = fp + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned " + f"{pin['fingerprint_sha256'][:12]} ({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + shutil.rmtree(pre_state["state"], ignore_errors=True) + + def launch(self, spec, ep, skip_preflight=False): + try: + h = super().launch(spec, ep, skip_preflight) + except HarnessRefused: + raise + # second line of defence: the init event of the real run + deadline = time.time() + 120 + while time.time() < deadline and h.proc.poll() is None: + init = self._init_event(spec) + if init is not None: + h.info["init"] = {k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version", + "permissionMode", "memory_paths", "apiKeySource")} + if init.get("tools") != MCP_TOOLS: + self.kill(h) + h.exit_reason = "refused: init tools " + json.dumps(init.get("tools")) + raise HarnessRefused(h.exit_reason) + break + time.sleep(0.2) + return h + + @staticmethod + def _init_event(spec): + try: + with open(spec.stdout_path) as f: + for line in f: + if line.startswith("{"): + d = json.loads(line) + if d.get("type") == "system" and d.get("subtype") == "init": + return d + except (OSError, ValueError): + return None + return None + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + init, result, by_id, compactions, other = None, None, {}, 0, [] + inits, results = [], [] # one init / result per launch or resume + lines = open(spec.stdout_path, encoding="utf-8", errors="replace").read().splitlines() + for line in lines: + if not line.startswith("{"): + continue + d = json.loads(line) + t = d.get("type") + if t == "system" and d.get("subtype") == "init": + init = init or d + inits.append(d) + elif t == "system": + if "compact" in str(d.get("subtype", "")): + compactions += 1 + other.append(d.get("subtype")) + elif t == "assistant": + m = d.get("message") or {} + mid = m.get("id") or d.get("uuid") + st = by_id.get(mid) + if st is None: + u = m.get("usage") or {} + st = tw.add_step("agent", timestamp=d.get("timestamp"), model_name=m.get("model"), + metrics=dict(prompt_tokens=u.get("input_tokens"), + completion_tokens=u.get("output_tokens"), + cached_tokens=u.get("cache_read_input_tokens"))) + by_id[mid] = st + for b in m.get("content") or []: + if b.get("type") == "text": + st["message"] += b.get("text", "") + elif b.get("type") == "thinking": + st["reasoning_content"] += b.get("thinking", "") + elif b.get("type") == "tool_use": + st["tool_calls"].append(dict(tool_call_id=b.get("id"), function_name=strip_mcp(b.get("name")), + native_name=b.get("name"), arguments=b.get("input"))) + elif t == "user": + for b in (d.get("message") or {}).get("content") or []: + if isinstance(b, dict) and b.get("type") == "tool_result": + c = b.get("content") + texts, imgs = [], 0 + for x in (c if isinstance(c, list) else [dict(type="text", text=c)]): + if x.get("type") == "text": + texts.append(x.get("text") or "") + elif x.get("type") == "image": + imgs += 1 + tw.add_result(b.get("tool_use_id"), "\n".join(texts), bool(b.get("is_error")), imgs) + elif t == "result": + result = d + results.append(d) + v = self.version() + tw.set_header(session_id=(init or {}).get("session_id"), source=os.path.basename(spec.stdout_path), + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort), + tools=(init or {}).get("tools")) + + def tot(key, sub=None): # summed over the segments (each resume reports its own usage) + vals = [((r.get("usage") or {}).get(key) if sub is None else r.get(key)) for r in results] + vals = [x for x in vals if isinstance(x, (int, float))] + return sum(vals) if vals else None + cost = tot("total_cost_usd", sub=True) + tw.set_final(h.exit_reason, native_result={k: (result or {}).get(k) for k in + ("subtype", "is_error", "num_turns", "duration_ms", + "duration_api_ms", "total_cost_usd", "usage", "modelUsage")}, + total_prompt_tokens=(tot("input_tokens") or 0) + (tot("cache_read_input_tokens") or 0) + + (tot("cache_creation_input_tokens") or 0), + total_completion_tokens=tot("output_tokens"), total_cached_tokens=tot("cache_read_input_tokens"), + total_cost_usd=cost, compactions=compactions, segments=len(results)) + tw.write() + h.info.update(init_full=init, inits=inits, result=result, results=results, compactions=compactions, + other_system=other, traj=tw) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + init = h.info.get("init_full") or {} + tw = h.info.get("traj") + v, problems, notes = [], [], [] + inits = h.info.get("inits") or [init] + for i, x in enumerate(inits): # every launch / resume + if x.get("tools") != MCP_TOOLS: + v.append(f"init {i} tools {x.get('tools')}") + sids = sorted({x.get("session_id") for x in inits if x.get("session_id")}) + if len(sids) > 1: + v.append(f"several sessions in one run: {sids}") + if h.info.get("resumes"): + notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the " + f"episode was over)") + if self.bare and init.get("memory_paths"): + v.append(f"memory_paths {init.get('memory_paths')}") + if not self.bare and init.get("memory_paths"): + mp = json.dumps(init.get("memory_paths")) + if spec.state_dirs["state"] not in mp and spec.cwd not in mp: + v.append(f"memory_paths outside the one-time dirs: {mp}") + notes.append("full variant: memory_paths point into the one-time dirs (empty at start)") + names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]] + bad = sorted({n for n in names if n not in MCP_TOOLS}) + if bad: + notes.append(f"model asked for unavailable tools (all rejected by the harness): {bad}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + left = dict(config=snapshot_tree(spec.state_dirs["config"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + mcp_logs = [p for p in left["home"] if "/mcp-logs-" in p] + own = [p for p in left["config"] if sids and p.startswith("projects/") + and (p.endswith(f"/{sids[0]}.jsonl") or f"/{sids[0]}/" in p)] # this run's session (for --resume) + transcripts = [p for p in left["config"] + left["home"] if p.endswith(".jsonl") and p not in mcp_logs + and p not in own] + if transcripts: + v.append(f"session transcripts other than this run's session: {transcripts}") + if own: + notes.append(f"this run's own session kept in the one-time config dir (for --resume): {own}") + if mcp_logs: # MCP connection log of the CLI in the one-time HOME (removed after the run, never read back) + notes.append(f"Claude Code wrote its MCP log into the one-time HOME: {mcp_logs}") + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + mcp_env = None + mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl") + if os.path.exists(mt): + for line in open(mt): + d = json.loads(line) + if d.get("ev") == "start" and "env_keys" in d: + mcp_env = d["env_keys"] + out = dict(harness=self.name, violations=v, problems=problems, notes=notes, files_left=left, + mcp_server_env_keys=mcp_env, compactions=h.info.get("compactions"), + init={k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version", + "permissionMode", "memory_paths", "apiKeySource")}, + tool_calls=len(names), unavailable_tool_requests=bad, ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out + + +class ClaudeCodeFull(ClaudeCode): + name = "claude_code_full" + bare = False + capabilities = dict(ClaudeCode.capabilities, + persistent_memory=Cap("partial", "probe", "auto-memory is on in the harness, but its dirs are " + "one-time and empty; canaries outside them never reach the request"), + instruction_file_injection=Cap("partial", "probe", "CLAUDE.md discovery is on, but work / " + "config / home are empty one-time dirs; canaries outside absent")) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/check_breakfast_geometry.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/check_breakfast_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..bb591b652e6beecfdd132163a5405f8253326029 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/check_breakfast_geometry.py @@ -0,0 +1,41 @@ +"""V2 physical height/orientation controls. Initialization interventions are diagnostics only.""" +import json +from pathlib import Path +from PIL import Image +from lffbench import envs +from lffbench.tasks.lh_breakfast_service import BreakfastService + +def main(): + out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/geometry_v2/geometry_controls' + out.mkdir(parents=True,exist_ok=True);rows=[];t=BreakfastService() + for seed in range(1000,1003): + inst=t.sample_instance(seed);t.reset_instance(inst);t.sk.correction=t.sk.bias.copy() + # Move bread clear only at diagnostic initialization, so the obstacle is unambiguous. + envs.set_obj_pose(t.env,'bread_1',[-.09,-.32,.94]);t.env.sim.forward() + def state(stage): + r=dict(seed=seed,stage=stage,lid_deg=t.lid_deg(),butter_height_cm=100*t.butter_height(), + butter_lid_contact=bool(t.butter_lid_contact()),butter_fits=t.butter_in_box(), + applied_torque=float(t.env.sim.data.qfrc_applied[t.dof])) + assert r['applied_torque']==0.,r + rows.append(r);print(json.dumps(r),flush=True) + Image.fromarray(envs.render(t.env,res=512)).save(out/f'{seed}_{stage}.png') + (out/'progress.json').write_text(json.dumps(rows,indent=2)) + return r + # Two empty-box closes prove that the removed closure-count mechanism does not reappear. + for cycle in range(2): + # Let the freely swinging open lid settle before targeting its knob again. + t.open_lid();t.sk.hold(100);t.close_lid(False);t.sk.hold(80) + r=state('empty_close_'+str(cycle+1));assert r['lid_deg']<4 + t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100) + r=state('upright_blocked') + assert r['lid_deg']>10 and r['butter_lid_contact'] and r['butter_height_cm']>7 and not r['butter_fits'],r + # Remove precisely that obstacle, leaving all geometry, forces and joint limits unchanged. + t.open_lid();assert t.pick_place('butter_1',inst['butter_xy'],t.butter_height()/2+.003) + t.close_lid(False);t.sk.hold(80);r=state('obstacle_removed');assert r['lid_deg']<4 + assert t.lay_butter_flat();r=state('laid_flat');assert r['butter_height_cm']<2.9 + t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100) + r=state('flat_inside_closed');assert r['lid_deg']<4 and r['butter_fits'] and not r['butter_lid_contact'],r + (out/'result.json').write_text(json.dumps(dict(passed=True,rows=rows),indent=2)) + t.env.close() + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/feedback_ladder.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/feedback_ladder.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cbcd10f0e9f163fbcc307dbf449147ddab78eb --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/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()/session.json [extra gpt-policy-lffbench options] +# e.g. LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10340 direct 3 gptpolicy rgb 1 +# scripts/gptpolicy_player.sh runs/claude/gptpolicy_l1_bias_place_s3000_..._p10340/session.json +# The robot_server interface (v1 / v2) is detected from the first status reply. +# +# Writes into the session's LOG directory: gptpolicy_transcript.jsonl (every model request/response, +# images as file paths + sha256, every robot-server call), final_report.md, gptpolicy_player.log and +# GPT-Policy's own recording gptpolicy_run_*/. The robot server writes events.jsonl and rollout.mp4. +# The server is stopped at the end (it has finished the episode, and rollout.mp4 is closed by then). +set -uo pipefail +[ $# -ge 1 ] || { echo "usage: $0 /session.json [options]"; exit 2; } +SESSION=$(readlink -f "$1"); shift +LOG=$(dirname "$SESSION") +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +[ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh" +# GPT-Policy checkout + venv from integrations/gpt-policy/setup.sh (override: GPTPOLICY_VENV) +VENV=${GPTPOLICY_VENV:-$ROOT/third_party/gpt-policy/.venv} +ENVF=${LFF_ENV_FILE:-$ROOT/.env} +[ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } # OPENAI_API_KEY / OPENAI_BASE_URL / SSL_CERT_FILE (never echoed) +export PYTHONUNBUFFERED=1 +stop_server() { # also on abnormal exit; SIGTERM makes the server close rollout.mp4 first + if [ "${GPTPOLICY_KEEP_SERVER:-0}" != "1" ] && [ -f "$LOG/server.pid" ]; then + kill "$(cat "$LOG/server.pid")" 2>/dev/null || true + fi +} +trap stop_server EXIT +trap 'exit 143' TERM INT HUP +cd /tmp # neutral working directory; the model has no file access anyway +"$VENV/bin/gpt-policy-lffbench" --session "$SESSION" --model "${GPTPOLICY_MODEL:-gpt-6-astra}" \ + --effort "${GPTPOLICY_EFFORT:-medium}" "$@" 2>&1 | tee -a "$LOG/gptpolicy_player.log" +RC=${PIPESTATUS[0]} +echo "gptpolicy_player.sh: gpt-policy-lffbench exit code $RC" >> "$LOG/gptpolicy_player.log" +exit $RC diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/make_dossier.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/make_dossier.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b97724e0cc03cb852d8fc0ece158512e008827 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/make_dossier.py @@ -0,0 +1,103 @@ +"""Build the record of an earlier failed attempt for the full5 history arms (docs/14 §6). + + python scripts/make_dossier.py [--attempt 1] [--allow-success] + +The record contains only what the agent of that attempt saw: the starting images, every robot command with the +robot's reply (as logged by robot_server), the images those commands produced, the agent's closing remark and the +F1 verdict ("failed"). No outcome codes, measurements or hidden variables. The same builder is used for the own-history +arm (record of a failed independent run on the same instance) and the mismatched arm (record of a failed run on the +twin instance: same layout, different hidden variable), so the two dossiers differ only in content. +""" +import argparse +import json +import os +import shutil + +DROP = ("state_file", "attempt_ended", "camera_file") + + +def shell_args(args): + out = [] + for k, v in args.items(): + v = json.dumps(v) if not isinstance(v, str) else v + out.append(f'{k}="{v}"' if (" " in v or not v) else f"{k}={v}") + return " ".join(out) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("log") + ap.add_argument("out") + ap.add_argument("--attempt", type=int, default=1) + ap.add_argument("--allow-success", action="store_true") + ap.add_argument("--result-extra", default="", + help="layer-3 ladder (docs/20): text appended to the verdict in the Result section (paragraphs " + "separated by blank lines; the first one continues the verdict line). Empty = F1 record, " + "byte-identical to the record built without this option.") + a = ap.parse_args() + evs = [json.loads(line) for line in open(os.path.join(a.log, "events.jsonl")) if line.strip()] + start = next(e for e in evs if e["ev"] == "session_start") + if start.get("style", "la") not in ("la", None) and "style" in start: + raise SystemExit("only la-style runs are supported") + calls = [e for e in evs if e["ev"] == "call" and e.get("attempt") == a.attempt] + done = [e for e in evs if e["ev"] == "done" and e.get("attempt") == a.attempt] + if not done: + raise SystemExit(f"attempt {a.attempt} has no done event (run unfinished?)") + done = done[0] + if done["success"] and not a.allow_success: + raise SystemExit(f"attempt {a.attempt} succeeded; nothing to learn from (use --allow-success to force)") + imgs = os.path.join(a.log, "images") + # commands as that agent issued them: `./robot ` in a CLI workspace, the `robot` tool's argument otherwise + try: + iface = json.load(open(os.path.join(a.log, "agent_iface.json"))).get("agent_iface", "cli") + except OSError: + iface = "cli" + pre = "./robot " if iface == "cli" else "" + os.makedirs(os.path.join(a.out, "obs"), exist_ok=False) + + def copy(rel): + base = os.path.basename(rel) + src = os.path.join(imgs, f"a{a.attempt}_{base}") + if not os.path.exists(src): + return None + shutil.copy(src, os.path.join(a.out, "obs", base)) + return f"obs/{base}" + + # starting images: the first images the agent saw (status at step 0) + first = sorted(f for f in os.listdir(imgs) if f.startswith(f"a{a.attempt}_") and "s000_" in f) + start_imgs = [copy(f.split("_", 1)[1]) for f in first] + lines = ["# Record of the earlier attempt", "", + "Starting scene: " + ", ".join(p for p in start_imgs if p), "", + "## Robot commands and replies", ""] + rec = [] + for i, e in enumerate(calls, 1): + rep = {k: v for k, v in (e.get("report") or {}).items() if k not in DROP} + if "images" in rep: + rep["images"] = [p2 for p2 in (copy(p) for p in rep["images"]) if p2] + cmd = f"{pre}{e['cmd']} {shell_args(e.get('args') or {})}".strip() + lines += [f"{i}. `{cmd}`", " reply: `" + json.dumps(rep) + "`", ""] + rec.append(dict(n=i, command=cmd, reply=rep)) + lines += [f"{len(calls) + 1}. `{pre}finish reason=\"{done.get('reason', '')}\"`", "", + "## Closing remark of that attempt", "", str(done.get("reason", "")), "", + "## Result", ""] + verdict = "The environment judged that attempt: " + ("succeeded." if done["success"] else "failed.") + extra = [x.strip() for x in a.result_extra.split("\n\n") if x.strip()] + if extra: + verdict += " " + extra[0] + lines += [verdict, ""] + for x in extra[1:]: + lines += [x, ""] + with open(os.path.join(a.out, "README.md"), "w") as f: + f.write("\n".join(lines)) + with open(os.path.join(a.out, "record.jsonl"), "w") as f: + for r in rec: + f.write(json.dumps(r) + "\n") + with open(os.path.join(os.path.dirname(os.path.abspath(a.out)), os.path.basename(a.out) + ".source.json"), "w") as f: + json.dump(dict(log=os.path.abspath(a.log), attempt=a.attempt, task=start.get("task"), seed=start.get("seed"), + arm=start.get("arm", "none"), n_commands=len(calls), success=done["success"], + result_extra=a.result_extra), f) + print(json.dumps(dict(out=a.out, n_commands=len(calls), n_images=len(os.listdir(os.path.join(a.out, "obs")))))) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/qwen_vl_server.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/qwen_vl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..33b002cb3516145787158a20c614a4bf1e3e551b --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/qwen_vl_server.py @@ -0,0 +1,535 @@ +#!/usr/bin/env python3 +"""Minimal OpenAI-compatible Chat Completions server (with tool calling) for Qwen3-VL. + +Runs a local HF-format Qwen3-VL checkpoint with transformers (>= 4.57) on one +CUDA-compatible device (here: Alibaba PPU) and exposes: + + POST /v1/chat/completions OpenAI chat.completion (non-streaming; stream=true + is emulated: the full answer is generated first + and then sent as SSE chunks) + GET /v1/models lists the single served model + GET /health liveness + device memory + +Request format accepted (subset of OpenAI): + messages: system / developer / user / assistant (with tool_calls) / tool + user/tool content may be a string or a list of + {"type":"text","text":...} and + {"type":"image_url","image_url":{"url": "data:image/...;base64,..." | http(s) URL | file path}} + tools: [{"type":"function","function":{"name","description","parameters"}}] + tool_choice: "auto" (default) | "none" (tools hidden from the prompt) | + "required" (generation is prefixed with "\n") | + {"type":"function","function":{"name":X}} (prefixed with the call header for X) + parallel_tool_calls: false -> only the first parsed tool call is returned + max_tokens / max_completion_tokens (default --default-max-tokens, 1024) + temperature (absent or 0 -> greedy), top_p, top_k, seed, stop (str or list) +Ignored: n (always 1), response_format, logprobs, presence/frequency penalty, user. + +The model emits Hermes-style {"name":..., "arguments":{...}} +blocks; they are parsed into choices[0].message.tool_calls with arguments as a JSON +string, and the remaining text (if any) becomes message.content (else null). + +Generation is serialised with a lock (one request on the device at a time); the +HTTP layer is a stdlib ThreadingHTTPServer so /health stays responsive. +""" +from __future__ import annotations + +import argparse +import base64 +import io +import json +import logging +import os +import re +import sys +import threading +import time +import traceback +import urllib.request +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +LOG = logging.getLogger("qwen_vl_server") + +TOOL_CALL_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL) +END_MARKERS = ("<|im_end|>", "<|endoftext|>") + + +# ---------------------------------------------------------------------------- +# Request conversion +# ---------------------------------------------------------------------------- +class BadRequest(Exception): + pass + + +def load_image(url: str): + from PIL import Image + + if url.startswith("data:"): + try: + _, b64 = url.split(",", 1) + except ValueError as e: + raise BadRequest("malformed data URL") from e + raw = base64.b64decode(b64) + elif url.startswith("http://") or url.startswith("https://"): + with urllib.request.urlopen(url, timeout=30) as r: + raw = r.read() + else: + path = url[len("file://"):] if url.startswith("file://") else url + with open(path, "rb") as f: + raw = f.read() + img = Image.open(io.BytesIO(raw)) + img.load() + return img.convert("RGB") + + +def convert_content(content, images: list): + """OpenAI content (str | list[part] | None) -> Qwen template content. + + Images are replaced by {"type": "image"} placeholders and the decoded PIL images + are appended to `images` in prompt order (the chat template emits one + <|vision_start|><|image_pad|><|vision_end|> per placeholder, in the same order). + """ + if content is None: + return "" + if isinstance(content, str): + return content + if not isinstance(content, list): + raise BadRequest(f"unsupported content type: {type(content).__name__}") + out = [] + for part in content: + if isinstance(part, str): + out.append({"type": "text", "text": part}) + continue + ptype = part.get("type") + if ptype in ("text", "input_text"): + out.append({"type": "text", "text": part.get("text", "")}) + elif ptype in ("image_url", "input_image", "image"): + iu = part.get("image_url", part.get("image")) + url = iu.get("url") if isinstance(iu, dict) else iu + if not isinstance(url, str): + raise BadRequest("image part without url") + try: + images.append(load_image(url)) + except BadRequest: + raise + except Exception as e: # noqa: BLE001 + raise BadRequest(f"could not load image ({url[:60]}...): {type(e).__name__}: {e}") from e + out.append({"type": "image"}) + else: + raise BadRequest(f"unsupported content part type: {ptype}") + return out + + +def text_only(content) -> str: + if content is None: + return "" + if isinstance(content, str): + return content + return "".join(p.get("text", "") for p in content if isinstance(p, dict)) + + +def convert_messages(messages: list): + if not isinstance(messages, list) or not messages: + raise BadRequest("messages must be a non-empty list") + images: list = [] + system_texts = [] + conv = [] + for m in messages: + role = m.get("role") + if role in ("system", "developer"): + # The Qwen template only renders a leading system message; merge all of them. + system_texts.append(text_only(m.get("content"))) + elif role == "user": + conv.append({"role": "user", "content": convert_content(m.get("content"), images)}) + elif role == "assistant": + c = m.get("content") + msg = {"role": "assistant", "content": text_only(c) if not isinstance(c, str) else c} + tcs = m.get("tool_calls") or [] + if tcs: + norm = [] + for tc in tcs: + fn = tc.get("function", tc) + args = fn.get("arguments", {}) + if not isinstance(args, str): + args = json.dumps(args, ensure_ascii=False) + norm.append({"type": "function", "function": {"name": fn.get("name", ""), "arguments": args}}) + msg["tool_calls"] = norm + conv.append(msg) + elif role in ("tool", "function"): + conv.append({"role": "tool", "content": convert_content(m.get("content"), images)}) + else: + raise BadRequest(f"unsupported role: {role}") + if system_texts: + conv.insert(0, {"role": "system", "content": "\n\n".join(system_texts)}) + return conv, images + + +# ---------------------------------------------------------------------------- +# Output parsing +# ---------------------------------------------------------------------------- +def _loads_lenient(s: str): + s = s.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + pass + # common slips: trailing garbage after the object, missing final brace + start = s.find("{") + if start >= 0: + dec = json.JSONDecoder() + try: + obj, _ = dec.raw_decode(s[start:]) + return obj + except json.JSONDecodeError: + pass + for extra in ("}", "}}", "\"}}"): + try: + return json.loads(s[start:] + extra) + except json.JSONDecodeError: + continue + return None + + +def parse_tool_calls(text: str): + """Return (content_or_None, tool_calls_list).""" + calls = [] + spans = [] + for mt in TOOL_CALL_RE.finditer(text): + spans.append(mt.span()) + calls.append(mt.group(1)) + # an unterminated trailing (e.g. hit max_tokens / model forgot the tag) + last_end = spans[-1][1] if spans else 0 + tail_idx = text.find("", last_end) + if tail_idx >= 0: + spans.append((tail_idx, len(text))) + calls.append(text[tail_idx + len(""):]) + + tool_calls = [] + keep_raw = [] # unparsable blocks stay in content + for (a, b), body in zip(spans, calls): + obj = _loads_lenient(body) + if not isinstance(obj, dict) or "name" not in obj: + keep_raw.append((a, b)) + continue + args = obj.get("arguments", obj.get("parameters", {})) + if isinstance(args, str): + parsed = _loads_lenient(args) + args_str = json.dumps(parsed, ensure_ascii=False) if parsed is not None else args + else: + args_str = json.dumps(args, ensure_ascii=False) + tool_calls.append({ + "id": "call_" + uuid.uuid4().hex[:24], + "type": "function", + "function": {"name": str(obj["name"]), "arguments": args_str}, + }) + + # content = text with successfully parsed blocks removed + parsed_spans = [s for s in spans if s not in keep_raw] + pieces, pos = [], 0 + for a, b in sorted(parsed_spans): + pieces.append(text[pos:a]) + pos = b + pieces.append(text[pos:]) + content = "".join(pieces).strip() + return (content if content else None), tool_calls + + +# ---------------------------------------------------------------------------- +# Model wrapper +# ---------------------------------------------------------------------------- +class Engine: + def __init__(self, args): + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor + + self.torch = torch + self.args = args + self.device = args.device + t0 = time.time() + proc_kwargs = {} + if args.min_pixels: + proc_kwargs["min_pixels"] = args.min_pixels + if args.max_pixels: + proc_kwargs["max_pixels"] = args.max_pixels + if args.attn == "sdpa" and not args.sdpa_native_gqa: + # PPU quirk (measured): torch SDPA with enable_gqa=True fails for decode steps + # (q_len=1, no mask) with "q must have shape (batch_size, seqlen_q, num_heads, + # head_size_og)". Make transformers repeat K/V heads itself instead. + import transformers.integrations.sdpa_attention as _sdpa + + _sdpa.use_gqa_in_sdpa = lambda attention_mask, key: False + self.processor = AutoProcessor.from_pretrained(args.model, **proc_kwargs) + self.tokenizer = self.processor.tokenizer + self.model = AutoModelForImageTextToText.from_pretrained( + args.model, + dtype=torch.bfloat16, + attn_implementation=args.attn, + device_map={"": self.device}, + ).eval() + self.load_time = time.time() - t0 + self.eos_ids = [self.tokenizer.convert_tokens_to_ids(t) for t in END_MARKERS] + self.eos_ids = [i for i in self.eos_ids if isinstance(i, int) and i >= 0] + self.pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.eos_ids[-1] + self.lock = threading.Lock() + LOG.info("model loaded in %.1fs on %s (attn=%s); mem allocated %.2f GiB", + self.load_time, self.device, args.attn, torch.cuda.memory_allocated(self.device) / 2**30) + + def mem(self): + t = self.torch + return { + "allocated_gib": round(t.cuda.memory_allocated(self.device) / 2**30, 2), + "reserved_gib": round(t.cuda.memory_reserved(self.device) / 2**30, 2), + "max_allocated_gib": round(t.cuda.max_memory_allocated(self.device) / 2**30, 2), + } + + def chat(self, req: dict): + torch = self.torch + a = self.args + messages, images = convert_messages(req.get("messages")) + tools = req.get("tools") or None + tool_choice = req.get("tool_choice", "auto") + prefix = "" + if tools: + if tool_choice == "none": + tools = None + elif tool_choice == "required": + prefix = "\n" + elif isinstance(tool_choice, dict): + fname = (tool_choice.get("function") or {}).get("name") or tool_choice.get("name") + if fname: + prefix = '\n{"name": "' + fname + '", "arguments": ' + tmpl_tools = None + if tools: + tmpl_tools = [] + for t in tools: + if isinstance(t, dict) and "function" not in t and "name" in t: + t = {"type": "function", "function": t} + tmpl_tools.append(t) + + prompt = self.processor.apply_chat_template( + messages, tools=tmpl_tools, tokenize=False, add_generation_prompt=True + ) + prefix + inputs = self.processor( + text=[prompt], images=images if images else None, return_tensors="pt" + ).to(self.device) + n_prompt = int(inputs["input_ids"].shape[1]) + if n_prompt > a.max_prompt_tokens: + raise BadRequest(f"prompt has {n_prompt} tokens > --max-prompt-tokens {a.max_prompt_tokens}") + + max_new = req.get("max_completion_tokens") or req.get("max_tokens") or a.default_max_tokens + max_new = int(min(max_new, a.max_tokens_cap)) + temperature = req.get("temperature") + if temperature is None: + temperature = a.default_temperature + gen_kwargs = dict( + max_new_tokens=max_new, + eos_token_id=self.eos_ids, + pad_token_id=self.pad_id, + use_cache=True, + ) + if temperature and float(temperature) > 0: + gen_kwargs.update(do_sample=True, temperature=float(temperature), + top_p=float(req.get("top_p") or 0.8), top_k=int(req.get("top_k") or 20)) + else: + gen_kwargs.update(do_sample=False, temperature=None, top_p=None, top_k=None) + if req.get("seed") is not None: + torch.manual_seed(int(req["seed"])) + + with torch.inference_mode(): + out = self.model.generate(**inputs, **gen_kwargs) + new_ids = out[0, n_prompt:].tolist() + # count tokens up to and including the first EOS + n_completion = len(new_ids) + hit_eos = False + for i, tid in enumerate(new_ids): + if tid in self.eos_ids: + n_completion = i + 1 + hit_eos = True + break + text = self.tokenizer.decode(new_ids[:n_completion], skip_special_tokens=False) + for mk in END_MARKERS: + text = text.replace(mk, "") + text = prefix + text + + stop = req.get("stop") + stopped_by_str = False + if stop: + for s in ([stop] if isinstance(stop, str) else stop): + k = text.find(s, len(prefix)) + if k >= 0: + text = text[:k] + stopped_by_str = True + + if tools: + content, tool_calls = parse_tool_calls(text) + if tool_calls and req.get("parallel_tool_calls") is False: + tool_calls = tool_calls[:1] + else: + content, tool_calls = (text.strip() or None), [] + + if tool_calls: + finish = "tool_calls" + elif hit_eos or stopped_by_str: + finish = "stop" + else: + finish = "length" + message = {"role": "assistant", "content": content} + if tool_calls: + message["tool_calls"] = tool_calls + usage = {"prompt_tokens": n_prompt, "completion_tokens": n_completion, + "total_tokens": n_prompt + n_completion} + return message, finish, usage, len(images), text + + +# ---------------------------------------------------------------------------- +# HTTP +# ---------------------------------------------------------------------------- +ENGINE: Engine | None = None +ARGS = None + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): # route http.server logs through logging + LOG.debug("%s - %s", self.address_string(), fmt % args) + + def _send_json(self, code: int, obj): + body = json.dumps(obj, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _error(self, code: int, msg: str, etype: str): + self._send_json(code, {"error": {"message": msg, "type": etype, "code": code}}) + + def do_GET(self): + if self.path.rstrip("/") in ("/health", "/v1/health"): + self._send_json(200, {"status": "ok", "model": ARGS.served_name, "memory": ENGINE.mem(), + "load_time_s": round(ENGINE.load_time, 1)}) + elif self.path.rstrip("/") == "/v1/models": + self._send_json(200, {"object": "list", "data": [ + {"id": ARGS.served_name, "object": "model", "created": int(time.time()), "owned_by": "local"}]}) + else: + self._error(404, f"no route {self.path}", "not_found") + + def do_POST(self): + if self.path.rstrip("/") not in ("/v1/chat/completions", "/chat/completions"): + self._error(404, f"no route {self.path}", "not_found") + return + try: + n = int(self.headers.get("Content-Length", "0")) + req = json.loads(self.rfile.read(n).decode("utf-8")) + except Exception as e: # noqa: BLE001 + self._error(400, f"invalid JSON body: {e}", "invalid_request_error") + return + t0 = time.time() + try: + with ENGINE.lock: + t_lock = time.time() + message, finish, usage, n_img, raw = ENGINE.chat(req) + except BadRequest as e: + self._error(400, str(e), "invalid_request_error") + return + except Exception as e: # noqa: BLE001 + LOG.error("generation failed: %s\n%s", e, traceback.format_exc()) + if "out of memory" in str(e).lower(): + try: + ENGINE.torch.cuda.empty_cache() + except Exception: # noqa: BLE001 + pass + self._error(500, f"{type(e).__name__}: {e}", "server_error") + return + dt = time.time() - t0 + LOG.info("req images=%d prompt=%d completion=%d finish=%s tool_calls=%d queue=%.2fs gen=%.2fs mem=%s", + n_img, usage["prompt_tokens"], usage["completion_tokens"], finish, + len(message.get("tool_calls", [])), t_lock - t0, time.time() - t_lock, ENGINE.mem()) + if ARGS.log_outputs: + LOG.info("raw output: %r", raw) + cid = "chatcmpl-" + uuid.uuid4().hex[:24] + created = int(time.time()) + model_name = req.get("model") or ARGS.served_name + if req.get("stream"): + self._send_stream(cid, created, model_name, message, finish, usage, req) + return + self._send_json(200, { + "id": cid, + "object": "chat.completion", + "created": created, + "model": model_name, + "choices": [{"index": 0, "message": message, "finish_reason": finish, "logprobs": None}], + "usage": usage, + "server_timing": {"latency_s": round(dt, 3)}, + }) + + def _send_stream(self, cid, created, model_name, message, finish, usage, req): + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.send_header("Connection", "close") + self.end_headers() + self.close_connection = True + + def chunk(delta, fr=None, with_usage=False): + obj = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name, + "choices": [{"index": 0, "delta": delta, "finish_reason": fr, "logprobs": None}]} + if with_usage: + obj["usage"] = usage + self.wfile.write(b"data: " + json.dumps(obj, ensure_ascii=False).encode() + b"\n\n") + + chunk({"role": "assistant", "content": message.get("content") or ""}) + for i, tc in enumerate(message.get("tool_calls", [])): + chunk({"tool_calls": [dict(tc, index=i)]}) + include_usage = bool((req.get("stream_options") or {}).get("include_usage")) + chunk({}, finish, with_usage=include_usage) + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + + +def main(): + global ENGINE, ARGS + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--model", default=os.environ.get("QWEN_VL_MODEL", "Qwen/Qwen3-VL-8B-Instruct")) + p.add_argument("--served-name", default="Qwen3-VL-8B-Instruct") + p.add_argument("--host", default="127.0.0.1") + p.add_argument("--port", type=int, default=8765) + p.add_argument("--device", default="cuda:0") + p.add_argument("--attn", default="sdpa", choices=["sdpa", "eager", "flash_attention_2"]) + p.add_argument("--sdpa-native-gqa", action="store_true", + help="let torch SDPA do GQA (enable_gqa=True); broken on PPU for decode, off by default") + p.add_argument("--default-max-tokens", type=int, default=1024) + p.add_argument("--max-tokens-cap", type=int, default=8192) + p.add_argument("--max-prompt-tokens", type=int, default=65536) + p.add_argument("--default-temperature", type=float, default=0.0, + help="used when the request has no temperature; 0 = greedy") + p.add_argument("--min-pixels", type=int, default=0, help="override image processor min_pixels") + p.add_argument("--max-pixels", type=int, default=0, help="override image processor max_pixels") + p.add_argument("--log-outputs", action="store_true", help="log raw model output text per request") + p.add_argument("--warmup", action="store_true", help="run one tiny generation before serving") + ARGS = p.parse_args() + + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout) + import transformers + + LOG.info("transformers %s from %s", transformers.__version__, os.path.dirname(transformers.__file__)) + ENGINE = Engine(ARGS) + if ARGS.warmup: + t = time.time() + with ENGINE.lock: + ENGINE.chat({"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 4}) + LOG.info("warmup done in %.1fs", time.time() - t) + srv = ThreadingHTTPServer((ARGS.host, ARGS.port), Handler) + srv.daemon_threads = True + LOG.info("serving %s on http://%s:%d/v1/chat/completions", ARGS.served_name, ARGS.host, ARGS.port) + try: + srv.serve_forever() + except KeyboardInterrupt: + pass + finally: + srv.server_close() + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/rpent_player.sh b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/rpent_player.sh new file mode 100644 index 0000000000000000000000000000000000000000..fafef9b4200fe5695c9fbabad0e01b9edd5e3a43 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/rpent_player.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Run one RPent (Harness VLA framework) agent on an LFF-Bench robot_server session. +# usage: scripts/rpent_player.sh /session.json [--model gpt-6-astra] [--effort medium] [--max-turns 400] ... +# Start a v2 session first (the RPent robot `lffbench` speaks interface v2 only), e.g.: +# LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10330 direct 3 rpent rgb 1 +# RPent checkout with the LFF-Bench robot (`lffbench`, planner `api`): integrations/rpent/setup.sh puts it in +# third_party/rpent with its venv in third_party/rpent/.venv (override: RPENT_DIR / RPENT_VENV, e.g. in env.local.sh). +# API key / endpoint: OPENAI_API_KEY / OPENAI_BASE_URL from the environment or from .env (LFF_ENV_FILE). +# Writes into the session's log dir: rpent_transcript.jsonl (every model request/response, images as file refs), +# final_report.md, rpent_result.json, rpent_player.log and rpent/ (RPent's own run.log / transcript / step artifacts). +set -e +[ -f "$1" ] || { echo "usage: $0 [player args]"; exit 2; } +SESSION=$(readlink -f "$1"); shift +LOG=$(dirname "$SESSION") +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +[ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh" +RPENT=${RPENT_DIR:-$ROOT/third_party/rpent} +VENV=${RPENT_VENV:-$RPENT/.venv} +ENVF=${LFF_ENV_FILE:-$ROOT/.env} +[ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } +cd "$RPENT" +PYTHONPATH="$RPENT" "$VENV/bin/python" -m robots.lffbench.player --session "$SESSION" "$@" 2>&1 | tee -a "$LOG/rpent_player.log" +exit "${PIPESTATUS[0]}" diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/start_real_session.sh b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/start_real_session.sh new file mode 100644 index 0000000000000000000000000000000000000000..6ef8faf20fc737b7fcdcd0174f100f1d203ab8d4 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/start_real_session.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Start a REAL-robot server (lffbench/real/session.py) + workspace for one task instance; same output as +# scripts/start_robot_session.sh (SANDBOX=, LOG=, /session.json), so harness_run.py / api_player.py run on it unchanged. +# usage: scripts/start_real_session.sh [instruction direct|indirect] [k] [tag] +# The driver: $LFF_REAL_DRIVER (default http://127.0.0.1:9900, normally an SSH tunnel to the robot PC) and $LFF_DRIVER_TOKEN. +# Blocks until the operator has set up the scene for attempt 1 (up to $LFF_REAL_READY_WAIT s, default 3600). +set -e +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-} +RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT} +SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))') +LOG=${LFF_RUNS_DIR:-$ROOT/runs/real}/$RUN +mkdir -p "$SANDBOX" "$LOG" +cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1 +KARG=""; [ -n "$K" ] && KARG="--k $K" +nohup python -m lffbench.real.session --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \ + --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --run-name "$RUN" ${LFF_EXTRA_ARGS:-} $KARG \ + > "$LOG/server.log" 2>&1 & +echo $! > "$LOG/server.pid" +WAIT=${LFF_REAL_READY_WAIT:-3600} +for i in $(seq 1 "$WAIT"); do + [ -f "$LOG/READY" ] && break + kill -0 "$(cat "$LOG/server.pid")" 2>/dev/null || break + [ $((i % 30)) -eq 0 ] && echo "waiting for the operator to set up the scene ($i s)" >&2 + sleep 1 +done +[ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; exit 1; } +echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json" +echo "SANDBOX=$SANDBOX" +echo "LOG=$LOG" diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/validate.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb5365e77822d5dc2d8ad2fd3489c4d6c82a77b --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/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/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/validate_parts_cart_isolated.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/validate_parts_cart_isolated.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc7b396510a3b831b746bdb17761fc8c32c5678 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/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() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/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_deepseek/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_deepseek/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_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..7b23eb68727314e3e04b81377e1cd9520ac64993 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high", + "fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4", + "written": "2026-10-13 04:12:38", + "summary": { + "system_chars": 26736, + "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/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/agent/cost.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/agent/cost.py new file mode 100644 index 0000000000000000000000000000000000000000..96d2c7f7612fd7dff37a8936e78f3e9470b86768 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/agent/cost.py @@ -0,0 +1,37 @@ +"""Token / cost accounting. + +Prices (USD per 1M tokens) for gpt-6-astra from the OpenAI model page as recorded in +research_notes/.../seed_papers.md Q8 (2026-10): input 10, cached input 1, cache write 12.5, output 50; +prompts > 272K input tokens are billed 2x input/cached and 1.5x output. usage.input_tokens_details has +cached_tokens and (openai SDK >= 3.x) cache_write_tokens; both are priced separately when present. +Reasoning tokens are billed as output tokens (they are included in output_tokens). +""" +import math + +PRICES = { + "gpt-6-astra": dict(input=10.0, cached=1.0, cache_write=12.5, output=50.0, long_threshold=272_000, long_in=2.0, long_out=1.5), +} + + +def call_cost(usage, model="gpt-6-astra"): + p = PRICES.get(model) + if p is None or not usage: + return None + inp = usage.get("input_tokens", 0) or 0 + cached = usage.get("cached_tokens", 0) or 0 + write = usage.get("cache_write_tokens", 0) or 0 # reported by newer SDKs / API versions + out = usage.get("output_tokens", 0) or 0 + li, lo = (p["long_in"], p["long_out"]) if inp > p["long_threshold"] else (1.0, 1.0) + plain = max(inp - cached - write, 0) + return ((plain * p["input"] + write * p["cache_write"] + cached * p["cached"]) * li + out * p["output"] * lo) / 1e6 + + +def image_tokens(w, h, patch=32, per_patch=1.0, overhead=0): + """ASSUMPTION (not verified for gpt-6-astra): patch-based image accounting as for the GPT-5 family, + one token per 32x32 patch (~256 tokens for 512x512). Real numbers come from response.usage.""" + return int(math.ceil(w / patch) * math.ceil(h / patch) * per_patch + overhead) + + +def estimate_request_tokens(stats, image_res=512): + """Rough input-token estimate of one request from OpenAIResponsesBackend.request_stats().""" + return int(stats.get("text_chars", 0) / 4 + stats.get("n_images", 0) * image_tokens(image_res, image_res)) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py new file mode 100644 index 0000000000000000000000000000000000000000..2f83f3b7e5ff6a3aea813f12af38833b11db7818 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py @@ -0,0 +1,73 @@ +"""Controlled-arm spec for l2_turntable_restore (2026-10-12). + +Hidden variable: inst["q0"], the turntable's start angle (rad, + = counter-clockwise seen from above). It is the only +thing the agent has to remember: the main task forces a large turn of the disc (to bring the butter out from under the +shelf), after which nothing in the scene shows the start angle. apply_instance() places the disc at q0 and puts the +butter at disc-frame angle theta (so its world azimuth is theta + q0) on every reset, and reset_instance() records the +start angle from the simulator, so overriding "q0" alone is enough. + +Geometry used below (TurntableRestore.butter_to_basket): with the butter at world azimuth az (about the disc axis) +and box yaw az + tilt, the main task turns the disc by T = wrap(PICK_AZ - tilt - az), PICK_AZ = +90 deg (open side). +Its sign flips at az = flip = -90 deg - tilt (the middle of the covered side); |T| = 180 deg - |az - flip|. + +h0 -> q0 with the butter already at PICK_AZ (open side, long axis along world y): the main task needs no turn + (T ~ 0), so the scripted naive (main task, then stop) leaves the disc at its start angle and succeeds. + NB: the instruction's "under the shelf" is then not literally true (the butter is on the open half). +twin -> q0 with the butter still under the shelf but 35 deg on the OTHER side of flip: the main task turns the disc + the opposite way (|T| = 145 deg, inside the measured 136-179 deg range), so naive still fails visibly, and the + correction (turn back) has the opposite sign; the twin's start angle differs from the original's by + 35 deg + |az - flip| >= 35 deg (tolerance 15 deg), so restoring to the twin's remembered marks fails here. +reveal -> the start angle stated as the direction the yellow stripe points (seen from above), in robot-centric words + (forward = away from the robot, counter-clockwise as in the F2 feedback). +""" +import numpy as np + +HIDDEN_KEYS = ("q0",) + +TARGET = "butter_1" +PICK_AZ = np.pi / 2 # TurntableRestore.PICK_AZ +TWIN_OFF = np.radians(35.0) +STRIPE_ANG = np.pi # disc-frame angle of the yellow stripe (l2_turntable.STRIPE_ANG) + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _geom(inst): + th, tilt = float(inst["theta"][TARGET]), float(inst["tilt"][TARGET]) + return th, tilt, -np.pi / 2 - tilt + + +def h0(inst): + th, tilt, _ = _geom(inst) + return {"q0": _wrap(PICK_AZ - tilt - th)} + + +def twin(inst): + th, tilt, flip = _geom(inst) + s = 1.0 if _wrap(th + float(inst["q0"]) - flip) >= 0 else -1.0 + return {"q0": _wrap(flip - s * TWIN_OFF - th)} + + +def _compass(deg): + names = ("forward", "forward-left", "left", "backward-left", "backward", "backward-right", "right", "forward-right") + return names[int(np.floor(((deg % 360) + 22.5) / 45.0)) % 8] + + +def reveal(inst): + az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG)) + side = "counter-clockwise" if az >= 0 else "clockwise" + return (f"Note: at the start, seen from above, the yellow stripe on the turntable points out from the turntable's " + f"centre {abs(az):.0f} deg {side} from straight forward (roughly {_compass(az)}); that is the angle the " + f"turntable is at now.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): the oracle turns the disc back to the saved start angle after the butter is out.""" + az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG)) + side = "counter-clockwise" if az >= 0 else "clockwise" + return (f"A way to succeed: after the butter is in the basket, turn the turntable back to its start angle before " + f"you finish. At the start, seen from above, the yellow stripe pointed {abs(az):.0f} deg {side} from " + f"straight forward (roughly {_compass(az)}). Grasp a red peg and move the gripper along the rim to turn " + f"the disc until the stripe points that way again (within 15 deg), then release the peg and finish.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py new file mode 100644 index 0000000000000000000000000000000000000000..e3840ef5042baaaf6b33ba45cefbc208da4547e0 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py @@ -0,0 +1,40 @@ +"""Controlled arms for l5_loaded_beam (2026-10-12, docs/14 sec. 6). + +Hidden variable: the bar's centre of mass `com_offset` (m along the bar from its middle, + = the robot's left end), +set at reset by l5_slippery_lift.set_hidden_weight (body_ipos + inertia + envs.refit_bounds, so a changed value is +honoured). `com_total` (bar + both blocks) is derived from it in sample_instance and read by oracle_params, so it is +overridden together. Mass, friction and layout stay as sampled. + +h0 : centre of mass at the middle (0): the common-sense middle grasp lifts the bar level. +twin : the same offset on the other side (-com_offset): the middle grasp still tilts the bar and spills a block, but + now towards the other end, so the right grasp point is mirrored. +reveal: the hidden weight's side and the bar's centre of mass in cm (plus the bar's mass in g), in the F2 words. +""" +HIDDEN_KEYS = ("com_offset", "com_total") + + +def h0(inst): + return dict(com_offset=0.0, com_total=0.0) + + +def twin(inst): + return dict(com_offset=-float(inst["com_offset"]), com_total=-float(inst["com_total"])) + + +def reveal(inst): + e = float(inst["com_offset"]) + side = "left" if e > 0 else "right" + return (f"The bar is not uniform: a heavy weight is hidden inside it towards its {side} end (the robot's {side}). " + f"The bar weighs {1000 * inst['mass']:.0f} g and its centre of mass is {100 * abs(e):.1f} cm to the " + f"{side} of its middle.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): grasp at the combined centre of mass (oracle along = com_total), lift 15 cm at 0.1.""" + a = float(params["along"]) + side = "left" if a > 0 else "right" + return (f"A way to succeed: grasp the bar at its balance point, not at its middle. Open the gripper, turn it so " + f"the jaws close across the bar's 4 cm width, come down over the point {100 * abs(a):.1f} cm to the " + f"robot's {side} of the bar's middle (the centre of mass of the bar and the two blocks) until the " + f"fingers are at the bar's mid-height, close the gripper and lift straight up about 15 cm slowly (speed " + f"about 0.1). Held there, the bar stays level and both blocks stay on it.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py new file mode 100644 index 0000000000000000000000000000000000000000..74eccfbae3bf4872ef4d65f64d620ab85e9e74f5 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py @@ -0,0 +1,61 @@ +"""Controlled arms for l5_slide_to_target (docs/14 §6). + +Hidden variable: mu, the cube-table sliding friction (apply_instance() sets it on every reset; oracle_params() bisects +the strike speed with it). The layout (cube_xy, target_dist) is kept. + +The naive strike is 0.30 m/s. Where the cube stops depends on mu and, by up to ~1.5 cm, on the cube's position on the +table, and the target tolerance is only +-1 cm, so H0 and the twin are calibrated per full5 seed with a simulated sweep +(deterministic sim, scratchpad arms/fine.py, 2026-10-12); other seeds fall back to a power-law fit of the stopping +distance at 0.30 m/s (dist ~ 0.00453 / mu^1.04 m). + + h0 mu at which the 0.30 m/s strike stops the cube on the square's centre (|err| <= 0.3 cm). + twin the opposite trap: if the original cube overshoots (slippery) the twin is grippy and stops short, and vice + versa, so the correction is the other way (slow down <-> speed up). The twin's naive error is at least 2 cm + and, where the twin's oracle still succeeds, about as large as the original's (mirrored). Seeds 3000 and 3007 + overshoot by 6.9 / 4.1 cm, but a grippy cube cannot be made to stop that far short and still be solvable, + so their twins stop 2.1 / 3.4 cm short. + reveal states the friction coefficient only. +""" + +HIDDEN_KEYS = ("mu",) + +# seed: h0 mu (naive err there), twin mu (twin naive err, twin oracle speed m/s -> err). Original naive err in brackets. +_CAL = { + 3000: dict(h0=0.0749, twin=0.1060), # [orig +6.94 cm] h0 +0.26; twin -2.13, oracle 0.551 -> +0.01 + 3001: dict(h0=0.0602, twin=0.0783), # [orig +2.95 cm] h0 +0.14; twin -2.73, oracle 0.450 -> 0.00 + 3003: dict(h0=0.0583, twin=0.0463), # [orig -1.73 cm] h0 +0.03; twin +2.75, oracle 0.242 -> -0.13 + 3004: dict(h0=0.0537, twin=0.0444), # [orig -1.66 cm] h0 -0.31; twin +2.14, oracle 0.240 -> -0.02 + 3007: dict(h0=0.0532, twin=0.0984), # [orig +4.05 cm] h0 +0.15; twin -3.39, oracle 0.570 -> -0.18 +} + + +def _h0_mu(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return c["h0"] if c else (0.00453 / float(inst["target_dist"])) ** (1 / 1.04) + + +def h0(inst): + return {"mu": float(_h0_mu(inst))} + + +def twin(inst): + c = _CAL.get(int(inst.get("seed", -1))) + if c: + return {"mu": float(c["twin"])} + m0 = _h0_mu(inst) # fallback: mirror mu about the H0 value in log space, kept in a solvable range + return {"mu": float(min(max(m0 * m0 / float(inst["mu"]), 0.03), 0.10))} + + +def reveal(inst): + return f"The red cube's sliding friction coefficient on the table is about {float(inst['mu']):.3f}." + + +def fix(inst, params): + """Ladder Fix rung (docs/20): one strike at the oracle speed (bisection with the true mu), 22 cm run-up, stopping + 1.5 cm past the cube's near face -- as l5_slide.execute; move_eef speed = Skills.move_to speed.""" + v = float(params["speed"]) + return (f"A way to succeed: one straight strike at the right speed. Close the gripper (yaw 0), put the fingertips " + f"just above the table (grasp point about 2 cm above the tabletop) 22 cm behind the cube's centre, on the " + f"robot's side and in line with the cube and the target, then in one move_eef command move straight " + f"forward at speed {v:.2f} to a point 1.5 cm past where the cube's near face was (0.5 cm short of its " + f"centre), and lift the gripper. The cube then slides into the target zone.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..d72cb9403cf21f0b5deead7e856fccc350305744 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py @@ -0,0 +1,61 @@ +"""Controlled arms for l5_tablecloth_pull (docs/14 §6). + +Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset, +oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled +from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu. + +Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed +up to ~0.8 m/s (0.8 and 1.0 m/s give identical results: the controller saturates). The naive policy yanks at 0.6 m/s. +Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull +slower". + + h0 mu at which the 0.6 m/s yank lands the cube on the band's centre line (calibrated per full5 seed by a + simulated sweep; a linear fit in band_d for other seeds). + twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot + (err +1.5 .. +2.7 cm), so the lesson is "pull faster" (the twin's oracle pulls at 0.64-0.79 m/s; agents can + command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short. + The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the + twin's naive error is only ~1.5-2.7 cm (similar size to the original's short-fall) and the twin's oracle is + within 0.2-0.5 cm of the band tolerance on some seeds. Calibrated per seed; for other seeds 1.2 x the H0 mu. + reveal states the cube's friction coefficient (the only fact that differs between instances). +""" + +HIDDEN_KEYS = ("mu",) + +# Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim). +# seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm]) +_CAL = { + 3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60 + 3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47 + 3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78 + 3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44 + 3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51 +} + + +def _h0_mu(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"]) + + +def h0(inst): + return {"mu": float(_h0_mu(inst))} + + +def twin(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))} + + +def reveal(inst): + return (f"The red cube's friction coefficient (against the board and against the table) is about " + f"{float(inst['mu']):.3f}.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): one pull of 25 cm at the oracle speed (bisection with the true mu), as + l5_tablecloth_pull.execute; move_eef speed = Skills.move_to speed.""" + v = float(params["speed"]) + return (f"A way to succeed: pull at the right speed. Grasp the black handle (jaws closing across its 4 cm width), " + f"then in one move_eef command pull the board straight towards the robot by 25 cm at speed {v:.2f}; then " + f"open the gripper and lift. The cube then lands in the green band.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/framework_codex.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/framework_codex.py new file mode 100644 index 0000000000000000000000000000000000000000..68a8d7d09835f053760d9d0ca718cd79959b97e4 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/framework_codex.py @@ -0,0 +1,542 @@ +"""Shared launcher for robot frameworks using a native Codex backend. + +The external integration contract is Session.first_message(), Session.tool_specs(), +and Session.call(name, arguments). This launcher owns isolation, model configuration, +pins, trajectory collection and audits; framework plugins own their native loop. +Based on the validated RPent launcher; RPent's historical launcher remains frozen. +""" +import hashlib +import json +import os +import shutil +import subprocess +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + gateway_env, new_run_dir, proxy_env, snapshot_tree) +from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog, + request_fingerprint, toml_str) +from .fakeapi import FakeResponses +from .trajectory import TrajWriter + +ROOT = C.ROOT +JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework" +BASE_PATH = "/usr/bin:/bin" +MCP_SERVER = "lff" +MCP_TOOLS = ["robot", "shell", "view_images"] +TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"} + + + +def tree_sha256(root, skip=TREE_SKIP): + """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs.""" + h = hashlib.sha256() + for dp, dn, fn in os.walk(root): + dn[:] = sorted(d for d in dn if d not in skip) + for f in sorted(fn): + if f.endswith(".pyc"): + continue + p = os.path.join(dp, f) + rel = os.path.relpath(p, root) + if os.path.islink(p): + h.update(f"L {rel} {os.readlink(p)}\n".encode()) + else: + h.update(f"F {rel} {C.sha256_file(p)}\n".encode()) + return h.hexdigest() + + +def runtime_info(home): + """The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv.""" + src, venv = os.path.join(home, "src"), os.path.join(home, "venv") + for d in (src, venv): + if not os.path.isdir(d): + raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)") + + def git(*a): + r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60) + return r.stdout.strip() if r.returncode == 0 else None + commit = git("rev-parse", "HEAD") + patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout + untracked = (git("ls-files", "--others", "--exclude-standard") or "").split() + return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(), + untracked=sorted(u for u in untracked if "__pycache__" not in u), + tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest()) + + +def jail_runtime_copy(home, tree): + """A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not).""" + dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}") + stamp = os.path.join(dst, ".tree_sha256") + if os.path.exists(stamp) and open(stamp).read().strip() == tree: + return dst + os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True) + tmp = dst + ".tmp-" + os.urandom(3).hex() + shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True, + ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc")) + shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode() + ).hexdigest() + if got != tree: + shutil.rmtree(tmp, ignore_errors=True) + raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})") + for dp, dn, fn in os.walk(tmp): + os.chmod(dp, 0o755) + for f in fn: + p = os.path.join(dp, f) + if not os.path.islink(p): + os.chmod(p, os.stat(p).st_mode | 0o444) + with open(os.path.join(tmp, ".tree_sha256"), "w") as f: + f.write(tree) + if os.path.exists(dst): + shutil.rmtree(dst) + os.rename(tmp, dst) + return dst + + +def codex_overrides(effort, catalog_path): + """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c + overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process).""" + return (["model_reasoning_effort=" + toml_str(effort), + "include_permissions_instructions=false", "include_environment_context=false", + "include_collaboration_mode_instructions=false", "skills.include_instructions=false", + "skills.bundled.enabled=false", 'web_search="disabled"', + f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS), + f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"', + f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60", + f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900", + "model_catalog_json=" + toml_str(catalog_path)] + + [f"features.{f}=false" for f in DISABLE]) + + +def _items(stream_path): + """Codex app-server notifications of one robot framework session (robot framework writes them as JSONL).""" + out = [] + if not os.path.exists(stream_path): + return out + for line in open(stream_path, encoding="utf-8", errors="replace"): + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def _item_of(ev): + it = (ev.get("payload") or {}).get("item") or {} + return it.get("root", it) if isinstance(it, dict) else {} + + +class RobotFrameworkCodex(HarnessAdapter): + name = "framework_codex" + runtime_home = "/nonexistent" + runtime_module = "lff_integration.run" + default_steps = 500 + uses_mcp = False + uses_gateway = True + can_resume = False + clean_dirs = ("home", "codex_home", "tmp", "out") + clean_allowed = {"codex_home": (CATALOG_FILE,)} + ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex") + capabilities = dict( + only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as " + "mcp__lff functions + residual resource×3 / request_user_input; robot framework registers " + "no tool of its own (no file tools, no finish)"), + images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, " + "JPEG with its own MIME type"), + non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the " + "run; no preloaded or cross-episode framework memory"), + pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in " + "harness.json; pin per version and tree"), + machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session " + "(codex.out.stream.jsonl) + robot framework run.json"), + tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"), + persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not " + "constructed"), + instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"), + web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"), + host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"), + builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"), + subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"), + background_execution=Cap("absent", "preflight", "no background tool in the request"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500, + home=None, provider=None, auth_home=None): + """Common controlled Codex SDK launcher. + + The plugin entrypoint interprets its declared loop options. For SenseNova, + max_turns is the upstream SDK-step limit, not a provider-response count. + Robot commands, simulation time and tool budgets are always server-owned. + """ + if auth not in ("apikey", "chatgpt"): + raise ValueError("framework_codex auth must be apikey or chatgpt") + if catalog not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}") + self.auth, self.catalog = auth, catalog + self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog) + self.api_env = self._auth_manager.api_env + self.base_url = self._auth_manager.base_url + self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)} + self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned + self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \ + int(max_turns) + self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home + self.proxy = proxy_env() + self._version = None + self._runtime = None + self.runtime_dir = self.home + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(codex_bin(), proc="static") + + # ------------------------------------------------------------------------------------------------ identity + def runtime(self): + if self._runtime is None: + self._runtime = runtime_info(self.home) + if self.jail is not None: + self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"]) + return self._runtime + + def version(self): + if self._version is None: + b = codex_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent", + CODEX_HOME="/nonexistent"), + capture_output=True, text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[-1] + rt = self.runtime() + self._version = dict(version=v, binary=binary_info(b), + framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"], + tree_sha256=rt["tree_sha256"], untracked=rt["untracked"])) + return self._version + + def pin_key(self, ep): + v = self.version() + mode = "" if self.auth == "apikey" else "-chatgpt" + name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def anchor_pin_key(self, ep): + """The main table's codex pin for the same model / effort (apikey, same catalog).""" + v = self.version() + name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}") + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def auth_info(self): + if self.auth == "chatgpt": + return self._auth_manager.auth_info() + return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get( + "OPENAI_API_KEY")), keys=["CODEX_API_KEY"]) + + def config_info(self): + return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session, + max_turns=self.max_turns, framework=self.version()["framework"]) + + # ------------------------------------------------------------------------------------------------ prepare + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")}) + for k in ("home", "codex_home", "tmp", "out"): + os.makedirs(state[k], exist_ok=True) + return state + + def _install_catalog(self, codex_home, ep): + cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort) + path = os.path.join(codex_home, CATALOG_FILE) + with open(path, "w") as f: + json.dump(cat, f) + return path, C.sha256_file(path), os.path.relpath(src, ROOT) + + def argv(self, ep, out_dir, sessions=None, preflight=False): + py = os.path.join(self.runtime_dir, "venv", "bin", "python") + return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir, + "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session), + "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \ + + (["--no-continue"] if preflight else []) + + def env(self, state, ep, base_url, work): + e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"], + CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()), + CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER, + FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides( + ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))), + FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"), + PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8") + if self.auth == "chatgpt": + # The native API provider declares env_key. Codex app-server still requires that + # variable even with requires_openai_auth=true, so select a separate provider + # with no env_key. Do not inject a dummy key or modify the upstream runtime. + provider_id = "lffsubscription" + overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"]) + overrides += ["model_provider=" + toml_str(provider_id), + f"model_providers.{provider_id}.name=" + toml_str(provider_id), + f"model_providers.{provider_id}.wire_api=\"responses\"", + f"model_providers.{provider_id}.base_url=" + toml_str(base_url), + f"model_providers.{provider_id}.requires_openai_auth=true"] + e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides) + e.update(self.proxy) + if self.api_env.get("OPENAI_API_KEY"): + e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"] + return e + + def prepare(self, ep, first_message, reuse_state=None): + self.version() + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + if not reuse_state and os.listdir(state["codex_home"]): + raise HarnessRefused("CODEX_HOME is not empty") + cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep) + return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work, + run_dir=work, state_dirs=state, first_message=first_message, + stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"), + stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"), + config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src, + catalog=self.catalog, code_mode=False)), + timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + argv = [a.replace(spec.state_dirs["out"], "").replace(self.runtime_dir, "") + for a in spec.argv] + hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH", + "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS + env = {k: v for k, v in spec.env.items() if k not in hidden} + env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace( + spec.state_dirs["codex_home"], "") + cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256") + return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat, + framework_tree_sha256=self.version()["framework"]["tree_sha256"])) + + # ------------------------------------------------------------------------------------------------ launch + def launch(self, spec, ep, skip_preflight=False): + """harness_run starts the gateway after prepare(), right before launch: hand its address to the process.""" + self._auth_manager._install_auth(spec.state_dirs["codex_home"]) + spec.env.update(gateway_env(ep.log_dir)) + return super().launch(spec, ep, skip_preflight=skip_preflight) + + def cleanup(self, spec): + self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", "")) + super().cleanup(spec) + + def preflight(self, spec, ep, record_dir=None): + """The same framework process, one session, against a local fake Responses server that answers with text + only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters, + sandbox, robot framework's prefix + our first message) against the pins.""" + t0 = time.time() + fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start() + pre = self._state_dirs() + try: + self._auth_manager._install_auth(pre["codex_home"]) + self._install_catalog(pre["codex_home"], ep) + env = self.env(pre, ep, fake.base_url, spec.cwd) + if self.auth == "apikey": + env["CODEX_API_KEY"] = "sk-preflight-not-a-key" + env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env}) + argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=300) + reqs = fake.model_requests() + if not reqs: + # Native planners may record failures only in run.json, with empty stdout/stderr. + record = os.path.join(pre["out"], "run.json") + detail = "" + if os.path.isfile(record): + with open(record) as f: + failed_run = json.load(f) + detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error")) + raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): " + f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}") + body = reqs[0][1] + fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC) + problems = [p for p in problems if not p.startswith("user input is not exactly our first message")] + users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message" + and it.get("role") == "user" for c in it.get("content") or []] + prefix = None + if len(users) != 1 or not users[0].endswith(spec.first_message): + problems.append(f"the first user message does not end with our first message ({len(users)} blocks)") + else: + prefix = users[0][:-len(spec.first_message)] + effort = (fp["params"].get("reasoning") or {}).get("effort") + if effort != ep.effort: + problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}") + if fp["params"].get("model") != ep.model: + problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + mid_sha = C.sha256_json(fp) + full = dict(middle=fp, framework_prefix=prefix) + fp_sha = C.sha256_json(full) + anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir) + out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha, + framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None, + framework_prefix_chars=len(prefix) if prefix is not None else None, + developer_chars=fp["developer_chars"], n_requests=len(reqs), + top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort, + model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], + dt_s=round(time.time() - t0, 1), problems=problems, + anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"])) + if anchor is None: + out["anchor_status"] = "no main-table pin for this model / effort" + elif anchor["fingerprint_sha256"] != mid_sha: + problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} " + f"({anchor['key']}): the middle layer is not the main table's") + else: + out["anchor_status"] = "match" + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = full + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} " + f"({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + self._auth_manager._sync_auth_back(pre["codex_home"]) + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + dst = os.path.join(ep.log_dir, "framework") + if os.path.isdir(spec.state_dirs["out"]): + shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True) + run = {} + if os.path.exists(os.path.join(dst, "run.json")): + run = json.load(open(os.path.join(dst, "run.json"))) + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + usage = dict(input=0, cached=0, output=0, reasoning=0) + items, threads, errors = [], [], [] + for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \ + else []: + last = None + for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")): + m = ev.get("method") or ev.get("type") + p = ev.get("payload") or {} + if m == "thread/tokenUsage/updated": + last = (p.get("token_usage") or {}).get("total") or last + if p.get("thread_id") and p["thread_id"] not in threads: + threads.append(p["thread_id"]) + elif m in ("error", "fatal", "timeout"): + errors.append(ev) + elif m == "item/completed": + it = _item_of(ev) + t = it.get("type") + items.append(t) + if t == "agentMessage": + tw.add_step("agent", message=it.get("text", "")) + elif t == "reasoning": + tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or "")) + elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"): + name = it.get("tool") or t + tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name, + native_name=f"{it.get('server', '')}.{name}", + item_type=t, arguments=it.get("arguments"), + session=sdir)]) + res = it.get("result") or {} + texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] + imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image") + tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")), + bool(it.get("error")) or it.get("status") == "failed", imgs) + if last: + usage["input"] += last.get("input_tokens") or 0 + usage["cached"] += last.get("cached_input_tokens") or 0 + usage["output"] += last.get("output_tokens") or 0 + usage["reasoning"] += last.get("reasoning_output_tokens") or 0 + # Framework close-out uses the same counted gateway shell, outside + # the model stream. Keep it visible in trajectories and tool totals. + session_record = next((s for s in run.get("sessions", []) + if sdir == f"session_{s['number']:03d}"), {}) + handoff = session_record.get("handoff") or {} + if handoff: + call_id = f"framework-handoff-{sdir}" + tw.add_step("framework", tool_calls=[dict( + tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell", + item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)]) + tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"] + if c.get("type") == "text")) + v = self.version() + tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl", + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort, + framework=v["framework"]), tools=EXPECTED_TOP_GENERIC) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)), + run={k: run.get(k) for k in ("stop", "finished", + "attempts_failed", "tool_calls")}, + sessions=len(run.get("sessions") or [])), + total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"], + total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"]) + tw.write() + h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + items = h.info.get("items") or [] + bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall", + "plan", "hookPrompt")}) + if bad: + v.append(f"items other than messages / reasoning / MCP calls: {bad}") + residual = [] + tw = h.info.get("traj") + for st in (tw.steps if tw else []): + for tc in st["tool_calls"]: + if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS: + continue + if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"): + residual.append(tc["function_name"]) + else: + v.append(f"unexpected tool call {tc['native_name']}") + if residual: + notes.append(f"residual MCP-resource tool calls (empty): {residual}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + run = h.info.get("run") or {} + nsess = len(run.get("sessions") or []) + if len(h.info.get("threads") or []) > max(1, nsess): + v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions") + if nsess > 1: + notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)") + if run.get("stop") not in (None, "episode over"): + notes.append(f"robot framework stopped: {run.get('stop')}") + left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/")) + and not any(t in f for t in (h.info.get("threads") or []))] + if foreign: + v.append(f"session files other than this run's threads: {foreign}") + gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl") + faces = set() + if os.path.exists(gt): + for line in open(gt): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool" and d.get("face"): + faces.add(d["face"]) + if faces - {self.name}: + v.append(f"gateway calls from other access paths: {sorted(faces)}") + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces), + item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/reference.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..93a7ecef47a9e0f879e60d8521618b4378658db2 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/reference.py @@ -0,0 +1,143 @@ +"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness). + +Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its +own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only +adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness. +""" +import json +import os +import sys + +from . import contract as C +from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions +from .trajectory import TrajWriter + +ROOT = C.ROOT +PLAYER = os.path.join(ROOT, "scripts", "api_player.py") +DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py", + "lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py", + "lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"] + + +class Reference(HarnessAdapter): + name = "ours" + capabilities = dict( + only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"), + images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"), + non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"), + pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"), + machine_readable_events=Cap("yes", "stream", "transcript.jsonl"), + tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"), + model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"), + persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"), + instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"), + web_access=Cap("absent", "launch", "no such tool"), + host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"), + builtin_shell=Cap("absent", "launch", "only the jailed shell tool"), + subagent_delegation=Cap("absent", "launch", "no such tool"), + background_execution=Cap("absent", "launch", "no such tool"), + ) + + def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_): + self.provider = provider + self.base_env = dict(env if env is not None else os.environ) + self.timeout_s = timeout_s + self.python = python or sys.executable + + def version(self): + per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))} + sha = C.sha256_json(per) + return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get( + "scripts/api_player.py"))) + + def prepare(self, ep, first_message=None): + argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider, + "--model", ep.model, "--effort", ep.effort, "--style", "la"] + return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="", + stdout_path=os.path.join(ep.log_dir, "api_player.log"), + stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + return C.sha256_json(dict(argv=[a.replace(ep.session_path, "") for a in spec.argv[1:]])) + + def launch(self, spec, ep, skip_preflight=True): + # stdout and stderr go to the same api_player.log (as before the adapter layer) + import subprocess + import time + from .base import RunHandle, env_keys_of + spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code") + log = open(spec.stdout_path, "ab") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) + h.pid = h.proc.pid + time.sleep(0.2) + h.env_observed_keys = env_keys_of(h.pid) + return h + + def collect(self, h): + ep = h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + p = os.path.join(ep.log_dir, "transcript.jsonl") + start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0) + last_agent = None + for line in (open(p) if os.path.exists(p) else []): + d = json.loads(line) + e = d.get("ev") + if e == "start": + start = d + elif e == "user": + if first_user is None: + first_user = d.get("text") + tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t")) + elif e == "assistant": + u = d.get("usage") or {} + tot["inp"] += u.get("input_tokens", 0) + tot["out"] += u.get("output_tokens", 0) + tot["cached"] += u.get("cached_tokens", 0) + last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "", + timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"], + function_name=c["name"], + native_name=c["name"], + arguments=c["arguments"]) + for c in d.get("tool_calls") or []], + metrics=dict(prompt_tokens=u.get("input_tokens"), + completion_tokens=u.get("output_tokens"), + cached_tokens=u.get("cached_tokens"))) + elif e == "tool" and last_agent is not None: + pending = [tc for tc in last_agent["tool_calls"] + if not any(r["source_call_id"] == tc["tool_call_id"] + for r in last_agent["observation"]["results"])] + if pending: + tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or [])) + elif e in ("end", "abort"): + end = d + tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl", + agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model, + effort=ep.effort, provider=ep.provider or self.provider), + tools=[t["name"] for t in (start or {}).get("tools") or []]) + tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")), + native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"], + total_cached_tokens=tot["cached"]) + tw.write() + h.info.update(traj=tw, start=start, first_user=first_user) + if start and first_user is not None: # the same string a native harness gets as its first message + readme = open(os.path.join(ep.sandbox, "README.md")).read() + h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme) + # the same composition as base.first_message_text: identical sha256 for the same instance + h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user + return tw + + def audit(self, h): + ep = h.ep + start = h.info.get("start") or {} + tools, _ = C.tool_schemas() + v = [] + if start and start.get("tools") != tools: + v.append("driver tools differ from the contract's tool schemas") + if h.info.get("instructions_match_readme") is False: + v.append("driver instructions != preamble + README") + out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"]) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/tasks/l5_slippery_lift.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/tasks/l5_slippery_lift.py new file mode 100644 index 0000000000000000000000000000000000000000..1a533e41595c29d413eb2287843cbc50afe7d0dc --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/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/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/agent_viewer/live.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/agent_viewer/live.py new file mode 100644 index 0000000000000000000000000000000000000000..48c7e2fb0e022c1860a5c4b0ca81fbb34db5990c --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/agent_viewer/live.py @@ -0,0 +1,406 @@ +#!/usr/bin/env python3 +"""Read-only terminal viewer for active LFF-Bench runs (ANSI images or ASCII).""" +from __future__ import annotations +import argparse +import base64 +import io +import json +import os +import re +import shutil +import sys +import time +from pathlib import Path + +# Strip terminal controls from untrusted logged text; only this program emits ANSI. +def clean(value): + return re.sub(r'[\x00-\x1f\x7f-\x9f]', ' ', str(value)) + + +def read_json(path): + try: + return json.loads(Path(path).read_text()) + except (OSError, ValueError): + return None + + +class Tail: + """Only consume complete JSONL records; tolerate concurrent append and rotation.""" + def __init__(self, path): + self.path, self.offset, self.pending, self.identity = Path(path), 0, b'', None + self.errors = 0 + self.generation = 0 + + def read(self): + try: + with self.path.open('rb') as stream: + stat = os.fstat(stream.fileno()) + identity = (stat.st_dev, stat.st_ino) + if self.identity is not None and (identity != self.identity or stat.st_size < self.offset): + self.offset, self.pending = 0, b'' + self.generation += 1 + self.identity = identity + stream.seek(self.offset) + chunk = stream.read() + self.offset = stream.tell() + except OSError: + return [] + lines = (self.pending + chunk).split(b'\n') + self.pending = lines.pop() + out = [] + for line in lines: + if not line.strip(): + continue + try: + row = json.loads(line) + if isinstance(row, dict): + out.append(row) + else: + self.errors += 1 + except (ValueError, UnicodeDecodeError): + self.errors += 1 + return out + + +class Run: + def __init__(self, path): + self.path = Path(path) + self.task = self.path.name + self.calls = 0 + self.attempt = 1 + self.outcomes = [] + self.command = '等待工具调用' + self.command_at = None + self.view_paths = [] + self.view_at = None + self.view_sequence = 0 + self.embedded_sequence = 0 + self.embedded_paths = [] + self.embedded = [] + self.summary = '' + self.status = '等待日志' + self.notice = '' + self.last_activity = None + names = ['events.jsonl', 'gateway_transcript.jsonl', 'mcp_transcript.jsonl', + 'transcript.jsonl', 'gpt_transcript.jsonl', 'codex_events.jsonl'] + self.tails = {n: Tail(self.path / n) for n in names} + self.image_cache = {} + + def update(self): + gateway = 'gateway_transcript.jsonl' if (self.path/'gateway_transcript.jsonl').exists() else 'mcp_transcript.jsonl' + api = 'transcript.jsonl' if (self.path/'transcript.jsonl').exists() else 'gpt_transcript.jsonl' + for name in ['events.jsonl', gateway, api, 'codex_events.jsonl']: + tail = self.tails[name] + generation = tail.generation + rows = tail.read() + if tail.generation != generation: + # Avoid mixing observations and counts across replaced/truncated runs. + self.__init__(self.path) + self.notice = '日志已轮转,重新读取' + return self.update() + for row in rows: + if row.get('t') is not None: + self.last_activity = max(self.last_activity or 0, row['t']) + if name == 'events.jsonl': + if row.get('ev') == 'session_start': + self.task = row.get('task', self.task) + self.status = '运行中' + elif row.get('ev') == 'call': + self.calls += 1 + self.attempt = row.get('attempt', self.attempt) + self.command = row.get('cmd', '') + ' ' + json.dumps(row.get('args', {}), ensure_ascii=False) + self.command_at = row.get('t') + elif row.get('ev') == 'done': + self.outcomes.append((row.get('attempt'), row.get('success'))) + elif name == gateway: + if row.get('ev') != 'tool': + continue + if row.get('finished'): + self.status = '任务已结束' + if row.get('name') == 'view_images' and not row.get('is_error') and row.get('images', 0) > 0: + paths = [] + for output in row.get('output', []): + try: + obj = json.loads(output) + paths.extend(obj.get('attached', [])) + except (ValueError, TypeError, AttributeError): + pass + # Only mark confirmed attachments as observed, not requested files. + if paths: + self.view_paths, self.view_at = paths, row.get('t') + self.view_sequence += 1 + if row.get('name') == 'robot': + self.command = row.get('arguments', {}).get('command', self.command) + self.command_at = row.get('t') + elif name == api: + if row.get('ev') in ('user', 'tool') and row.get('images'): + self.view_paths, self.view_at = row['images'], row.get('t') + self.view_sequence += 1 + if row.get('ev') == 'assistant': + self.summary = row.get('reasoning_summary') or row.get('text') or '' + if row.get('ev') in ('end', 'abort'): + self.status = '已结束' if row['ev'] == 'end' else '已中断' + elif name == 'codex_events.jsonl' and row.get('type') == 'item.completed': + item = row.get('item', {}) + if item.get('type') in ('reasoning', 'agent_message'): + self.summary = item.get('text', '') + if item.get('type') == 'mcp_tool_call' and item.get('tool') == 'view_images' and not item.get('error'): + content = (item.get('result') or {}).get('content', []) + paths, raw = [], [] + for c in content: + if c.get('type') == 'text': + try: + paths.extend(json.loads(c.get('text', '')).get('attached', [])) + except (ValueError, AttributeError): + pass + elif c.get('type') == 'image': + try: + raw.append(base64.b64decode(c['data'], validate=True)) + except (ValueError, KeyError): + pass + if raw and len(raw) == len(paths): + self.embedded_paths, self.embedded = paths, raw + self.embedded_sequence += 1 + if not (self.path/gateway).exists(): + self.view_paths = paths + self.view_sequence = self.embedded_sequence + self.notice = f'跳过 {sum(t.errors for t in self.tails.values())} 条损坏日志' if any(t.errors for t in self.tails.values()) else self.notice + + def frames(self): + session = read_json(self.path/'session.json') or {} + roots = [self.path] + if session.get('sandbox'): + roots.append(Path(session['sandbox'])) + result = [] + for index, ref in enumerate(self.view_paths): + if not isinstance(ref, str): + continue + if self.embedded_sequence == self.view_sequence and self.embedded_paths == self.view_paths and index < len(self.embedded): + result.append((ref, self.embedded[index], '工具响应内嵌图片')) + continue + for root in roots: + target = (root/ref).resolve() + if not target.is_relative_to(root.resolve()) or not target.is_file(): + continue + stat = target.stat() + if self.view_at is not None and stat.st_mtime > self.view_at + 0.1: + result.append((ref, None, '文件在观察后已修改,不能确认原图')) + break + key = (str(target), stat.st_mtime_ns, stat.st_size) + if key not in self.image_cache: + self.image_cache = {key: target.read_bytes()} + result.append((ref, self.image_cache[key], '日志引用文件(未校验原始字节)')) + break + else: + result.append((ref, None, '图片文件不可用')) + return result + + +def choose_run(batch): + data = read_json(Path(batch)/'manifest.json') + if not data: + return None, '批次清单暂不可读' + rows = data.get('runs', []) + counts = {key: sum(r.get('status') == key for r in rows) for key in ['done', 'running', 'pending']} + active = [r for r in rows if r.get('status') == 'running' and r.get('log')] + completed = [r for r in rows if r.get('log')] + row = active[0] if active else completed[-1] if completed else None + summary = ' / '.join(f'{key} {count}' for key, count in counts.items()) + return row, summary + + +def image_lines(raw, columns, rows, color): + from PIL import Image, ImageOps + image = Image.open(io.BytesIO(raw)).convert('RGB') + width, height = columns, rows * 2 + image = ImageOps.contain(image, (width, height)) + pixels = image.load() + lines = [] + ramp = ' .:-=+*#%@' + for y in range(0, image.height, 2): + line = '' + for x in range(image.width): + upper, lower = pixels[x,y], pixels[x,min(y+1,image.height-1)] + if color: + line += '\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm▀' % (*upper, *lower) + else: + value = (sum(upper) + sum(lower)) / 6 + line += ramp[min(9, int(value/256*10))] + lines.append(line + ('\033[0m' if color else '')) + return lines + + +# Native image transports keep source pixels rather than quantizing to text cells. +KITTY_IMAGE_ID = 1987000000 + os.getpid() % 100000 + +def choose_renderer(requested, environ=None, tty=True): + env = os.environ if environ is None else environ + if not tty: + return 'ansi' + # This embedded terminal was observed to swallow OSC 1337 images, leaving + # the reserved rectangle blank. Keep a visible preview even for old commands. + if env.get('TERM_PROGRAM') == 'claude-desktop' and requested == 'iterm': + return 'ansi' + if requested != 'auto': + return requested + # Multiplexers need terminal-specific passthrough setup; keep auto conservative. + if env.get('TMUX') or env.get('STY'): + return 'ansi' + if env.get('KITTY_WINDOW_ID') or env.get('TERM') == 'xterm-kitty': + return 'kitty' + if env.get('TERM_PROGRAM') in ('iTerm.app', 'WezTerm'): + return 'iterm' + return 'ansi' + + +def native_image(raw_images, columns, rows, renderer): + from PIL import Image + decoded = [Image.open(io.BytesIO(raw)).convert('RGB') for raw in raw_images] + # Place full-resolution views side by side without resampling source pixels. + canvas = Image.new('RGB', (sum(im.width for im in decoded), max(im.height for im in decoded))) + x = 0 + for im in decoded: + canvas.paste(im, (x, 0)) + x += im.width + buf = io.BytesIO() + canvas.save(buf, format='PNG') + data = base64.b64encode(buf.getvalue()).decode() + if renderer == 'iterm': + sequence = f'\033]1337;File=inline=1;width={columns};height={rows};preserveAspectRatio=1:{data}\a' + else: + # Preserve aspect in the usual 1:2 text cells; don't stretch square inputs. + w = max(1, min(columns, int(rows * 2 * canvas.width / canvas.height))) + h = max(1, min(rows, round(w * canvas.height / canvas.width / 2))) + chunks = [data[i:i+4096] for i in range(0, len(data), 4096)] + sequence = '' + for n, chunk in enumerate(chunks): + meta = f'a=T,f=100,t=d,i={KITTY_IMAGE_ID},q=2,C=1,c={w},r={h},' if n == 0 else '' + sequence += f'\033_G{meta}m={int(n < len(chunks)-1)};{chunk}\033\\' + # Both protocols are given a reserved rectangle; restore before advancing. + return '\0337' + sequence + '\0338' + '\n' * (rows - 1) + + +def clear_native(renderer): + return f'\033_Ga=d,d=I,i={KITTY_IMAGE_ID},q=2\033\\' if renderer == 'kitty' else '' + + +def age(timestamp): + return f'{max(0,int(time.time()-timestamp))} 秒前' if timestamp else '时间未记录' + + +def render(run, label, width, rows, color, images, renderer="ansi", camera="all"): + lines = [clean(label)[:width], f'{clean(run.task)} | {clean(run.status)} | 尝试 {run.attempt} | 机器人动作 {run.calls}', + f'最近动作 ({age(run.command_at)}): {clean(run.command)[:max(15,width-22)]}', + f'最近返回给 Agent 的图片 ({age(run.view_at)}):按观察事件更新,不是连续视频'] + frames = run.frames() + if camera != "all": + keyword = "agentview" if camera == "main" else "wrist" + frames = [f for f in frames if keyword in f[0]][-1:] + if not frames: + lines.append('尚未发现已返回给 Agent 的图片。') + if images and frames: + shown = frames[-2:] + cell = max(12,(width-3*(len(shown)-1))//len(shown)) + columns = [] + for ref, raw, source in shown: + display = ('字符缩略图' if renderer == 'ansi' else '原图像素') if raw else '不可用' + lines.append(f' {clean(ref)} · 来源:{source} · 显示:{display}') + try: + columns.append(image_lines(raw, cell, rows, color) if raw else ['[原图不可用]']) + except Exception as exc: + columns.append([f'[无法解码图片: {type(exc).__name__}]']) + if renderer in ('iterm', 'kitty') and any(raw for _, raw, _ in shown): + try: + lines.append(native_image([raw for _, raw, _ in shown if raw], width, rows, renderer)) + columns = [] + except Exception as exc: + lines.append(f'原图显示编码失败,使用字符预览: {type(exc).__name__}') + for y in range(max(map(len, columns), default=0)): + parts=[] + for c in columns: + part=c[y] if y= 0.5 seconds') + if a.width is not None and a.width<24:parser.error('--width must be >= 24') + if a.image_rows is not None and a.image_rows<2:parser.error('--image-rows must be >= 2') + if a.duration is not None and a.duration<=0:parser.error('--duration must be positive') + if not a.no_images: + try:import PIL + except ImportError:parser.error('Image preview needs Pillow; use the evaluation Python or --no-images') + renderer=choose_renderer('ansi' if a.ascii else a.renderer,tty=sys.stdout.isatty()) + if a.no_images:renderer='ansi' + compatibility_notice = ( + 'Claude 内置终端的 iTerm 图片模式未能显示;已切换为字符预览(非原图清晰度)。' + if os.environ.get('TERM_PROGRAM') == 'claude-desktop' + and a.renderer == 'iterm' and renderer == 'ansi' + and not a.ascii and not a.no_images and sys.stdout.isatty() else '' + ) + interactive=sys.stdout.isatty() and not a.once + current=None + started=time.monotonic() + previous=None + try: + if interactive:print('\033[?1049h\033[?25l',end='',flush=True) + while True: + label='Agent Viewer · LIVE · Ctrl+C 退出' + path=a.run + if a.batch: + selected,summary=choose_run(a.batch) + path=Path(selected['log']) if selected else None + label=f'{a.batch.name} | {summary}' + if path is not None: + if current is None or current.path!=path:current=Run(path) + current.update() + if a.batch and selected:current.status=selected.get('status',current.status) + size=shutil.get_terminal_size((100,36)) + width=a.width or max(24,size.columns-1) + rows=a.image_rows or max(3,size.lines-12-bool(compatibility_notice)) + label += f' | 刷新 {a.interval:g}s · {renderer}' + output=render(current,label,width,rows,sys.stdout.isatty() and not a.ascii,not a.no_images,renderer,a.camera) + if compatibility_notice: + header, _, body = output.partition('\n') + output = header + '\n' + compatibility_notice + '\n' + body + else:output=label+'\n等待批次启动下一任务…' + if output!=previous: + if interactive:print(clear_native(renderer)+'\033[H\033[J'+output,end='',flush=True) + else:print(output,flush=True) + previous=output + if a.once or a.duration and time.monotonic()-started>=a.duration:break + delay=a.interval if a.duration is None else min(a.interval,max(0,a.duration-(time.monotonic()-started))) + time.sleep(delay) + except KeyboardInterrupt: + pass + finally: + if interactive:print(clear_native(renderer)+'\033[0m\033[?25h\033[?1049l',end='',flush=True) + + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/check_setup.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/check_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c91b70fc618700ec2c265ebd1f9f21fed24e2420 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/check_setup.py @@ -0,0 +1,175 @@ +"""Check that this machine can run LFF-Bench. Run after `source run_env.sh`: + + python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail + python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY / + # OPENAI_BASE_URL from the environment or from .env); costs a few tokens + python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail + +Exit code 0 when every check that ran passed. +""" +import argparse +import os +import subprocess +import sys +import tempfile +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py + +results = [] + + +def report(name, ok, detail=""): + results.append(ok) + print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True) + return ok + + +def check_packages(): + report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0]) + from lffbench.agent.backends.base import import_openai + for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"): + try: + m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"]) + report(f"import {mod}", True, getattr(m, "__version__", "")) + except Exception as e: # noqa: BLE001 + report(f"import {mod}", False, f"{type(e).__name__}: {e}") + cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml") + if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")): + import yaml + assets = yaml.safe_load(open(cfg)).get("assets", "") + report("LIBERO assets", os.path.isdir(assets), assets) + report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}") + + +def check_sim(task_name, seed): + import importlib + import pkgutil + + try: + import lffbench.tasks as task_pkg + from lffbench.task_base import TASKS + except Exception as e: # noqa: BLE001 + report("import lffbench", False, f"{type(e).__name__}: {e}") + return + try: + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + except Exception as e: # noqa: BLE001 + report("import tasks", False, f"{type(e).__name__}: {e}") + return + report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks") + t0 = time.time() + try: + task = TASKS[task_name]() + inst = task.sample_instance(seed) + task.reset_instance(inst) + img = task.snapshot() + out = task.outcome(inst) + except Exception as e: # noqa: BLE001 + report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}") + return + ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0 + report(f"simulate + render {task_name}", ok, + f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s") + + +def check_jail(): + if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"), + JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"): + return + probe = r''' +echo "pwd=$(pwd)" +python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1 +echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)" +python3 -c " +import socket +s = socket.socket(); s.settimeout(3) +try: + s.connect(('1.1.1.1', 443)); print('net=open') +except OSError as e: + print('net=blocked') +" +touch made_in_jail && echo "write=ok" +''' + with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws: + argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws, + "timeout", "-k", "5", "60", "bash", "-c", probe] + r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l) + if r.returncode != 0 and not kv: + hint = "" + if "Operation not permitted" in r.stdout or "uid_map" in r.stdout: + hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: " + "sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0") + report("jail runs", False, r.stdout.strip()[-400:] + hint) + return + report("jail runs", True, f"workdir {kv.get('pwd')}") + report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:])) + report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0", + f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}") + report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?")) + report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail"))) + + +def load_env_file(): + path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env") + if not os.path.isfile(path): + return None + for line in open(path): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + k, v = line.split("=", 1) + os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\"")) + return path + + +def check_api(model, effort): + src = load_env_file() + 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" # same as scripts/gpt_player.py + if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")), + f"from {src}" if src else "from the environment (no .env)"): + return + base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)" + from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend + t0 = time.time() + try: + client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client() + resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping", + reasoning=dict(effort=effort), store=False, max_output_tokens=256) + text = (resp.output_text or "").strip() + u = resp.usage + report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, " + f"tokens in {u.input_tokens} / out {u.output_tokens}") + except Exception as e: # noqa: BLE001 + report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint") + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--effort", default="low") + ap.add_argument("--task", default="l5_slide_to_target") + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--skip-sim", action="store_true") + ap.add_argument("--skip-jail", action="store_true") + a = ap.parse_args() + os.environ.setdefault("OMP_NUM_THREADS", "1") + check_packages() + if not a.skip_sim: + check_sim(a.task, a.seed) + if not a.skip_jail: + check_jail() + if a.api: + check_api(a.model, a.effort) + n_bad = results.count(False) + print(f"\n{len(results) - n_bad}/{len(results)} checks passed") + sys.exit(1 if n_bad else 0) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/cs_ir_report.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/cs_ir_report.py new file mode 100644 index 0000000000000000000000000000000000000000..681580fd2dab576a4f9ac1747508e03873147f59 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/cs_ir_report.py @@ -0,0 +1,87 @@ +"""Reproduce the CS/IR audit tables from read-only manifests and hash-bound evidence.""" +import argparse +import json +from pathlib import Path + +import api_batch +import outcomes +from outcome_audit import load_audit, sha256 + +GROUPS = {"GPT": ["cx_main1"], "Sonnet": ["cc_main1"], "Opus": ["cc_opus1"], + "DeepSeek": ["ds_cx1", "ds_cx1b"]} + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--runs-root", required=True) + parser.add_argument("--audit", required=True) + parser.add_argument("--out", required=True) + args = parser.parse_args() + api_batch.RUNS = str(Path(args.runs_root).resolve()) + audit = load_audit(args.audit) + output = Path(args.out) + output.mkdir(parents=True, exist_ok=True) + all_rows, models, manifests, coverage = [], {}, {}, {} + for model, batches in GROUPS.items(): + old, new = [], [] + for batch in batches: + manifest = api_batch.load(batch) + manifests[batch] = sha256(api_batch.mpath(batch)) + old += outcomes.instance_rows(manifest, batch=batch) + new += outcomes.instance_rows(manifest, audit=audit, batch=batch) + for run in manifest["runs"]: + if not (run["cond"] == "harness" and run.get("followup") and run["status"] == "done"): + continue + attempts = outcomes.attempts(run["log"]) + if attempts: + coverage.setdefault(run["task"], set()).update( + k for k in outcomes.ERROR_FLAGS + outcomes.ERROR_COUNTS if k in attempts[0][2]) + before, after = outcomes.summary(old), outcomes.summary(new) + for key in ("n", "A1", "A3", "XR", "F", "n_paired", "A3_paired", "passk_paired", "delta_paired"): + assert before[key] == after[key], f"Audit unexpectedly changed {model} {key}" + assert len({(r["task"], r["seed"]) for r in new}) == len(new), "duplicate model/task/seed" + models[model] = dict(before=before, after=after) + all_rows += [dict(r, model=model) for r in new] + payload = dict(schema="lff-cs-ir-report-1", source_manifests_sha256=manifests, + audit_sha256=sha256(args.audit), models=models, rows=all_rows, + legacy_counter_coverage={k: sorted(v) for k, v in coverage.items()}) + (output / "summary.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + lines = ["# CS / IR 证据审计表(2026-10-24)", "", + "本表由 `scripts/cs_ir_report.py` 生成;定义、局限、合并说明见同目录 `README.md`。", + "旧口径是 task counter heuristic;新口径是逐 run 的物理失败 + 主动修复证据审计。", + "A1、A3、XR、F、配对样本及 Δ_hist 均逐项断言保持不变。", "", + "| 模型 | 旧 CS / IR / S? | 审计 CS / IR / S? | 原 S? 已补 | A1 | A3 |", + "|---|---|---|---|---|---|"] + for model, pair in models.items(): + b, a = pair["before"], pair["after"] + resolved = sum(r["model"] == model and r["legacy_cls"] == "S?" and r["cls"] != "S?" for r in all_rows) + lines.append(f"| {model} | {b['CS']} / {b['IR']} / {b['S?']} | {a['CS']} / {a['IR']} / {a['S?']} | " + f"{resolved}/{b['S?']} | {a['A1']}/{a['n']} | {a['A3']}/{a['n']} |") + lines += ["", "## 每任务新旧分类与原统一字段覆盖", "", + "`旧→新`;只有一个标签表示未变。`缺失` 不是没有错误;有字段也不代表覆盖抓空/掉落等全部失败。", "", + "| 任务 | GPT | Sonnet | Opus | DeepSeek | 原统一错误字段 |", "|---|---|---|---|---|---|"] + for task, counters in coverage.items(): + cells = [] + for model in GROUPS: + row = next(r for r in all_rows if r["model"] == model and r["task"] == task) + cells.append(row["cls"] if row["cls"] == row["legacy_cls"] else f"{row['legacy_cls']}→{row['cls']}") + lines.append("| " + " | ".join([task] + cells + [", ".join(sorted(counters)) or "缺失"]) + " |") + lines += ["", "## 首次成功的证据链", "", "行号均指原 run 文件,E 为 events.jsonl,T 为 trajectory.jsonl;s 为机器人命令序号。", ""] + for row in all_rows: + if not row["a1"]: + continue + entry = audit.get((row["batch"], row["run_id"])) + manifest = api_batch.load(row["batch"]) + run = next(r for r in manifest["runs"] if r["id"] == row["run_id"]) + lines += [f"### {row['model']} · {row['task']} · {row['legacy_cls']} → {row['cls']}", "", + row["audit_basis"], "", f"[原 events.jsonl]({run['log']}/events.jsonl) · " + f"[原 trajectory.jsonl]({run['log']}/trajectory.jsonl)", ""] + if entry: + lines += [f"证据索引:{entry.get('evidence', '')}", "", + f"归因范围:`{entry.get('failure_scope', 'not_adjudicated')}`。", ""] + (output / "TABLES.md").write_text("\n".join(lines) + "\n") + print(json.dumps(models, ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/full_waves.sh b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/full_waves.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4a98c713907c49980d1dfb6571d022deeb09321 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/full_waves.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Run the remaining waves of the full GPT-6 run: wait until at most MAX_LEFT (default 4) runs of the batch are still going, stop the +# robot servers of ended runs (keeps memory bounded), then launch the next wave on all three harnesses. +# usage: scripts/full_waves.sh "" "" ... +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_opus/lff/source_closure/scripts/l6_controls.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/l6_controls.py new file mode 100644 index 0000000000000000000000000000000000000000..41114f4bea52b74c5426c220b1d554cade09f1ad --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/l6_controls.py @@ -0,0 +1,92 @@ +"""python scripts/l6_controls.py [n] + +Extra controls for the two L6 tasks: thumbnails right after the interruption, extra scripted policies, +no-injection sanity check, analytic memoryless baselines. Writes results//controls.json.""" +import sys, json, os, time +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +import numpy as np, imageio +from lffbench import envs +import lffbench.tasks.l6_count, lffbench.tasks.l6_sequence # noqa +from lffbench.task_base import TASKS +name = sys.argv[1] +n = int(sys.argv[2]) if len(sys.argv) > 2 else 20 +out_dir = os.path.join(ROOT, "results", name) +os.makedirs(out_dir, exist_ok=True) +task = TASKS[name](cam_res=384) +extra = ["skip", "inc1"] if name == "l6_count_into_box" else ["skip"] +res = dict(task=name, n=n, seeds=list(range(1000, 1000 + n)), extra={}, no_inject={}, analytic={}) +t0 = time.time() + +# 1) frames right after the interruption (what the agent sees next), seeds 1000-1002, adaptive policy +def interrupted(): + return (task.slip if name == "l6_count_into_box" else task.stop) is not None + + +for seed in range(1000, 1003): + inst = task.sample_instance(seed) + shot = {} + orig_step = task.env.step + + def step(a, _o=orig_step): + r = _o(a) + if "f" not in shot and interrupted(): + shot["cnt"] = shot.get("cnt", 0) + 1 + if shot["cnt"] >= (4 if name == "l6_count_into_box" else 60): # count: 0.2 s; sequence: arm back home + shot["f"] = np.concatenate([envs.render(task.env, "agentview", 384), + envs.render(task.env, "robot0_eye_in_hand", 384)], 1) + return r + task.env.step = step + task.run_scripted("adaptive", inst, k=5, seed=seed) + task.env.step = orig_step + if "f" in shot: + imageio.imwrite(os.path.join(out_dir, f"interrupt_{seed}.png"), shot["f"]) +print("thumbs", f"{time.time()-t0:.0f}s", flush=True) + +# 2) extra scripted policies +for kind in extra: + fs = [] + for i in range(n): + seed = 1000 + i + inst = task.sample_instance(seed) + h = task.run_scripted(kind, inst, k=5, seed=seed) + s = next((x["attempt"] for x in h if x["outcome"]["success"]), None) + fs.append(s) + res["extra"][kind] = dict(first_success=fs, succ_at_k=[float(np.mean([s is not None and s <= j for s in fs])) for j in range(1, 6)]) + print(kind, res["extra"][kind]["succ_at_k"], f"{time.time()-t0:.0f}s", flush=True) + +# 3) no-injection sanity (oracle + naive, first 10 seeds) +task.inject = False +for kind in ("adaptive", "naive"): + fs = [] + for i in range(10): + seed = 1000 + i + inst = task.sample_instance(seed) + h = task.run_scripted(kind, inst, k=1, seed=seed) + fs.append(bool(h[0]["outcome"]["success"])) + res["no_inject"][kind] = float(np.mean(fs)) + print("no inject", kind, res["no_inject"][kind], flush=True) +task.inject = True + +# 4) analytic memoryless baselines over the same seeds (perfect execution assumed) +if name == "l6_count_into_box": + insts = [task.sample_instance(1000 + i) for i in range(n)] + res["analytic"]["uniform_guess_0..N-1@1"] = float(np.mean([1 / x["n_target"] for x in insts])) + best = max(range(0, 6), key=lambda g: np.mean([x["n_target"] - x["p"] == g for x in insts])) + res["analytic"]["best_fixed_number_to_add@1"] = dict(add=best, rate=float(np.mean([x["n_target"] - x["p"] == best for x in insts]))) + res["analytic"]["p_hist"] = {str(v): int(sum(x["p"] == v for x in insts)) for v in range(1, 6)} + res["analytic"]["N_hist"] = {str(v): int(sum(x["n_target"] == v for x in insts)) for v in (4, 5)} + big = [task.sample_instance(5000 + i) for i in range(2000)] + res["analytic"]["uniform_guess@1_2000inst"] = float(np.mean([1 / x["n_target"] for x in big])) + res["analytic"]["best_fixed_add@1_2000inst"] = float(max(np.mean([x["n_target"] - x["p"] == g for x in big]) for g in range(1, 5))) +else: + insts = [task.sample_instance(1000 + i) for i in range(n)] + res["analytic"]["w_hist"] = {str(v): int(sum(x["stop_w"] == v for x in insts)) for v in range(1, 5)} + res["analytic"]["phase_hist"] = {p: int(sum(x["stop_phase"] == p for x in insts)) for p in "AB"} + res["analytic"]["uniform_guess_0..4@1"] = 0.2 + big = [task.sample_instance(5000 + i) for i in range(2000)] + res["analytic"]["best_fixed_guess@1_2000inst"] = float(max(np.mean([x["stop_w"] == g for x in big]) for g in range(0, 5))) + res["analytic"]["skip_expected"] = float(np.mean([x["stop_phase"] == "B" or x["stop_w"] == 3 for x in big])) +res["seconds"] = time.time() - t0 +json.dump(res, open(os.path.join(out_dir, "controls.json"), "w"), indent=1) +print(json.dumps(res["analytic"])) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/outcomes.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/outcomes.py new file mode 100644 index 0000000000000000000000000000000000000000..3df0c20085a48b77bcae6967009d489b8f8ff310 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/outcomes.py @@ -0,0 +1,141 @@ +"""Per-instance outcomes of api_batch.py --memfree followup batches, in the paper's terms (paper/01 §4 3.6): + + CS attempt 1 succeeded with no error event in it IR attempt 1 succeeded after an error event (repaired + XR attempt 1 failed, a later attempt succeeded within the attempt) + F no attempt succeeded S? attempt 1 succeeded, but the task logs no error events + (CS or IR cannot be told apart) + A1 = CS + IR (+ S?), A3 = A1 + XR (history condition); pass@k = the memory-free chain (attempt 1 shared with the + history run, then fresh agents) succeeded; delta = A3 - pass@k, paired per instance. Tasks whose scene persists + between attempts (protocol "within") have no memory-free chain and are listed apart (user 2026-10-20). + + python scripts/outcomes.py --batch cx_main1 [--batch ...] [--json out.json] + +An error event is read from the task's outcome dict of the successful attempt: trap_fired / recovered_in_attempt +true, or one of the n_* counters of mistakes (n_bad_pushes, n_wrong_way, n_regressions, n_load_falls, ...) above 0. +The finish reason of every failed attempt is printed so that false success claims can be judged (not judged here). +""" +import argparse +import ast +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import api_batch # noqa: E402 + +ERROR_FLAGS = ("trap_fired", "recovered_in_attempt") +ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events", + "n_missed_strikes", "n_open_gripper_pushes") + + +def attempts(log): + """[(attempt, success, outcome dict, finish reason)] from the robot server log.""" + out = [] + p = os.path.join(log or "", "events.jsonl") + if not os.path.exists(p): + return out + for line in open(p): + e = json.loads(line) + if e.get("ev") != "done": + continue + o = e.get("outcome") or {} + if isinstance(o, str): + try: + o = ast.literal_eval(o) + except (ValueError, SyntaxError): + o = {} + out.append((int(e["attempt"]), e["success"] in (True, "True"), o, e.get("reason") or "")) + return sorted(out, key=lambda x: x[0]) + + +def error_event(o): + """True / False if the outcome dict says whether an error happened, None if the task logs no error events.""" + keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o] + if not keys: + return None + return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o) + + +def instance_rows(m, audit=None, batch=None): + rows = [] + for r in m["runs"]: + if not (r["cond"] == "harness" and r.get("followup")) or r["status"] != "done": + continue + att = attempts(r.get("log")) + if not att: + continue + if audit is not None and att[0][0] != 1: + raise ValueError(f"Cannot audit {r['task']}: first-attempt record is missing") + hist = "".join("S" if s else "F" for _, s, _, _ in att) + if att[0][1]: + ev = error_event(att[0][2]) + cls = "S?" if ev is None else ("IR" if ev else "CS") + else: + cls = "XR" if any(s for _, s, _, _ in att) else "F" + legacy_cls = cls + audit_basis = None + if audit is not None and att[0][1]: + from outcome_audit import adjudicate + cls, audit_basis = adjudicate(audit, batch, r, True) + within = api_batch.episode_protocol(r.get("log")) == "within" + chain = sorted((x for x in m["runs"] if x.get("chain") == r["id"]), key=lambda x: x["rep"]) + mf = None + if not within: + mf = hist[0] + "".join("S" if any(api_batch.attempt_results(x.get("log"))) else + ("F" if x["status"] == "done" else "?") for x in chain) + failed = [(a, reason) for a, s, _, reason in att if not s] + failed += [(f"mf{x['rep'] + 1}", rr) for x in chain for _, s, _, rr in attempts(x.get("log")) if not s] + rows.append(dict(task=r["task"], seed=r["seed"], cls=cls, legacy_cls=legacy_cls, + batch=batch, run_id=r["id"], audit_basis=audit_basis, + history=hist, memfree=mf, within=within, + a1=att[0][1], a3=any(s for _, s, _, _ in att), + passk=None if mf is None else ("S" in mf), failed_reasons=failed)) + return rows + + +def summary(rows): + n = len(rows) + paired = [x for x in rows if x["passk"] is not None and "?" not in (x["memfree"] or "")] + cnt = {c: sum(1 for x in rows if x["cls"] == c) for c in ("CS", "IR", "S?", "XR", "F")} + return dict(n=n, **cnt, A1=sum(x["a1"] for x in rows), A3=sum(x["a3"] for x in rows), n_paired=len(paired), + A3_paired=sum(x["a3"] for x in paired), passk_paired=sum(x["passk"] for x in paired), + delta_paired=(sum(x["a3"] for x in paired) - sum(x["passk"] for x in paired)) / max(1, len(paired))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", action="append", required=True) + ap.add_argument("--json", default=None) + ap.add_argument("--runs-root", help="read manifests from another checkout's runs/api directory") + ap.add_argument("--audit", help="hash-bound reviewed classifications (unreviewed first successes remain S?)") + a = ap.parse_args() + if a.runs_root: + api_batch.RUNS = os.path.abspath(a.runs_root) + audit = None + if a.audit: + from outcome_audit import load_audit + audit = load_audit(a.audit) + rows = [] + for b in a.batch: + rows += instance_rows(api_batch.load(b), audit=audit, batch=b) + print("Classification: " + ("reviewed evidence (see audit sources)" if audit is not None else + "legacy task-counter heuristic; CS/IR coverage is task-dependent")) + print("| task | seed | outcome | history | memory-free | note |\n|---|---|---|---|---|---|") + for x in rows: + print(f"| {x['task']} | {x['seed']} | {x['cls']} | {x['history']} | {x['memfree'] or '—'} | " + f"{'scene persists: no memory-free chain' if x['within'] else ''} |") + s = summary(rows) + print(f"\nn={s['n']} CS={s['CS']} IR={s['IR']} S?={s['S?']} XR={s['XR']} F={s['F']} A1={s['A1']}/{s['n']} " + f"A3={s['A3']}/{s['n']} paired (no persisting scene, chain finished): n={s['n_paired']} " + f"A3={s['A3_paired']} pass@k={s['passk_paired']} delta={s['delta_paired']:+.3f}") + print("\nfinish reasons of failed attempts (for judging false success claims):") + for x in rows: + for att, reason in x["failed_reasons"]: + print(f" {x['task']} {att}: {reason[:160]}") + if a.json: + with open(a.json, "w") as f: + json.dump(dict(rows=rows, summary=s), f, indent=1, ensure_ascii=False) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/run_agent.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/run_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..4ee5cbb55b9c8df62f070fb56ca6524c045a898a --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/run_agent.py @@ -0,0 +1,220 @@ +"""Run an agent backend on an LFF-Bench task and log everything. + + source run_env.sh && export OMP_NUM_THREADS=1 + python scripts/run_agent.py --task l5_slide_to_target --backend scripted --memory full --feedback F2 --n 3 --k 5 + python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory full --n 20 --k 5 + +Writes runs/agent//___/ with config.json, events.jsonl +(every LLM call with tokens + latency, every tool call with its report, every attempt's outcome and +feedback), images/ (every image the model saw, as the exact JPEG sent) and summary.json (succ@k per run, +first-success attempt, ΔICL fields, tokens / cost / latency). +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + + +def load_tasks(): + import lffbench.tasks as task_pkg + from lffbench.task_base import TASKS + for m in pkgutil.iter_modules(task_pkg.__path__): + try: + importlib.import_module(f"lffbench.tasks.{m.name}") + except Exception as e: # other people's task files may be mid-edit; do not let them break this run + print(f"[warn] could not import lffbench.tasks.{m.name}: {e!r}", file=sys.stderr) + return TASKS + + +def parse(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--task", required=True) + ap.add_argument("--backend", choices=["scripted", "openai", "chat"], default="scripted") + ap.add_argument("--memory", choices=["none", "full", "last", "mismatched"], default="full") + ap.add_argument("--feedback", choices=["F0", "F1", "F2"], default="F2") + ap.add_argument("--n", type=int, default=3, help="number of instances (runs)") + ap.add_argument("--k", type=int, default=None, help="attempts per run (default: task.max_attempts)") + ap.add_argument("--seed0", type=int, default=1000, help="first instance seed (dev seeds 1000+, use 5000+ for test)") + ap.add_argument("--seeds", default=None, help="explicit comma-separated seeds (overrides --seed0/--n)") + ap.add_argument("--out", default=os.path.join(ROOT, "runs", "agent")) + ap.add_argument("--tag", default="") + # harness + ap.add_argument("--instruction", choices=["direct", "indirect"], default="direct") + ap.add_argument("--privileged-locate", action="store_true", help="ablation: add locate(object_name)") + ap.add_argument("--image-res", type=int, default=512) + ap.add_argument("--keyframe-res", type=int, default=None) + ap.add_argument("--keyframes", type=int, default=4) + ap.add_argument("--max-steps", type=int, default=30, help="tool calls per attempt") + ap.add_argument("--no-auto-obs", action="store_true", help="send images only on get_observation") + ap.add_argument("--grasp-report", choices=["bool", "name", "none"], default="bool") + ap.add_argument("--early-stop", choices=["auto", "yes", "no"], default="auto") + ap.add_argument("--jpeg-quality", type=int, default=90) + ap.add_argument("--no-save-images", action="store_true") + # mismatched memory + ap.add_argument("--donor-run", default=None, help="run dir whose attempts serve as mismatched histories") + ap.add_argument("--donor-offset", type=int, default=10000, + help="without --donor-run: donor instance seed = seed + offset, generated with memory=full") + # scripted + ap.add_argument("--scripted-policy", choices=["adaptive", "naive", "oracle", "blind"], default="adaptive") + ap.add_argument("--dry-run-payload", action="store_true", + help="for non-openai backends: also build the GPT-6 request for every call and log its size") + ap.add_argument("--dump-requests", type=int, default=0, + help="write the first N OpenAI requests (images elided) to requests/ for inspection") + # openai + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--effort", default="medium", help="reasoning effort: low|medium|high|xhigh|max") + ap.add_argument("--reasoning-summary", default="auto", choices=["auto", "concise", "detailed", "none"], + help="request and log model-returned summaries by default; none disables the request") + ap.add_argument("--image-detail", default="auto", help="low|high|original|auto") + ap.add_argument("--max-output-tokens", type=int, default=None) + ap.add_argument("--service-tier", default=None) + ap.add_argument("--prompt-cache-retention", default=None, help="in-memory | 24h") + ap.add_argument("--max-live-images", type=int, default=16) + ap.add_argument("--extra-body", default=None, help="JSON merged into the request body (new API fields)") + ap.add_argument("--cache-breakpoints", choices=["none", "history", "history+last"], default="history+last", + help="explicit prompt_cache_breakpoint markers (set none if a gateway rejects the field)") + ap.add_argument("--prompt-cache-options", default=None, help='JSON, e.g. {"ttl": "30m"}') + # chat (OpenAI-compatible local server) + ap.add_argument("--chat-base-url", default=None) + ap.add_argument("--chat-model", default="qwen3-vl-8b") + ap.add_argument("--chat-max-tokens", type=int, default=1024) + return ap.parse_args(argv) + + +def redact_request(req): + """Copy of a request with base64 images replaced by a short marker.""" + def red(o): + if isinstance(o, dict): + return {k: (f"" if k in ("image_url", "url") and isinstance(v, str) + and v.startswith("data:") else red(v)) for k, v in o.items()} + if isinstance(o, list): + return [red(v) for v in o] + if isinstance(o, str) and len(o) > 2000 and o.startswith("gAAAA"): # encrypted reasoning + return f"" + return o + return red(req) + + +def build_backend(args): + from lffbench.agent.backends import make_backend + if args.backend == "scripted": + return make_backend("scripted", policy=args.scripted_policy) + if args.backend == "openai": + if not os.environ.get("OPENAI_API_KEY"): + sys.exit("OPENAI_API_KEY is not set (and OPENAI_BASE_URL if you use a proxy / gateway).") + return make_backend("openai", model=args.model, reasoning_effort=args.effort, + reasoning_summary=None if args.reasoning_summary == "none" else args.reasoning_summary, + image_detail=args.image_detail, + max_output_tokens=args.max_output_tokens, service_tier=args.service_tier, + prompt_cache_retention=args.prompt_cache_retention, max_live_images=args.max_live_images, + jpeg_quality=args.jpeg_quality, cache_breakpoints=args.cache_breakpoints, + prompt_cache_options=json.loads(args.prompt_cache_options) if args.prompt_cache_options + else None, extra_body=json.loads(args.extra_body) if args.extra_body else None) + return make_backend("chat", model=args.chat_model, base_url=args.chat_base_url, max_tokens=args.chat_max_tokens, + max_live_images=min(args.max_live_images, 4), jpeg_quality=args.jpeg_quality) + + +def main(argv=None): + args = parse(argv) + from lffbench.agent.harness import AgentHarness, HarnessConfig, config_dict + from lffbench.agent.metrics import aggregate + from lffbench.agent.replay import derange, load_records + from lffbench.agent.runlog import RunLogger + + tasks = load_tasks() + if args.task not in tasks: + sys.exit(f"unknown task {args.task}; known: {sorted(tasks)}") + backend = build_backend(args) + seeds = [int(s) for s in args.seeds.split(",")] if args.seeds else list(range(args.seed0, args.seed0 + args.n)) + cfg = HarnessConfig(memory=args.memory, feedback=args.feedback, k=args.k, image_res=args.image_res, + keyframe_res=args.keyframe_res, n_keyframes=args.keyframes, auto_obs=not args.no_auto_obs, + max_steps=args.max_steps, privileged_locate=args.privileged_locate, + grasp_report=args.grasp_report, instruction=args.instruction, early_stop=args.early_stop, + jpeg_quality=args.jpeg_quality, save_images=not args.no_save_images, + model_for_cost=args.model if args.backend == "openai" else "none") + stamp = time.strftime("%Y%m%d-%H%M%S") + name = f"{stamp}_{args.backend}{'-' + args.scripted_policy if args.backend == 'scripted' else ''}_{args.memory}_" \ + f"{args.feedback}" + (f"_{args.tag}" if args.tag else "") + run_dir = os.path.join(args.out, args.task, name) + os.makedirs(run_dir, exist_ok=True) + log = RunLogger(run_dir, save_images=cfg.save_images, jpeg_quality=cfg.jpeg_quality) + + t0 = time.time() + task = tasks[args.task]() + print(f"[run_agent] env built in {time.time() - t0:.1f}s -> {run_dir}", flush=True) + k = args.k or task.max_attempts + + probe = None + if args.backend == "openai": + probe = None + elif args.dry_run_payload or args.dump_requests: + from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend + probe = OpenAIResponsesBackend(model=args.model, reasoning_effort=args.effort, image_detail=args.image_detail, + max_live_images=args.max_live_images, jpeg_quality=args.jpeg_quality, + cache_breakpoints=args.cache_breakpoints, client=object()) + if args.dump_requests: + os.makedirs(os.path.join(run_dir, "requests"), exist_ok=True) + dumped = [0] + target = backend if args.backend == "openai" else probe + orig = target.build_request + + def build_and_dump(conv, tools, _orig=orig): + req = _orig(conv, tools) + if dumped[0] < args.dump_requests: + dumped[0] += 1 + with open(os.path.join(run_dir, "requests", f"request_{dumped[0]:03d}.json"), "w") as f: + json.dump(redact_request(req), f, indent=1) + return req + target.build_request = build_and_dump + + log.write_json("config.json", dict(argv=sys.argv, args=vars(args), harness=config_dict(cfg), + backend=backend.config(), task=dict(name=task.name, level=task.level, + protocol=task.protocol, k=k, + capabilities=list(task.capabilities)))) + harness = AgentHarness(task, backend, cfg, log, payload_probe=probe if args.backend != "openai" else None) + + donors = {} + if args.memory == "mismatched": + if args.donor_run: + pool = load_records(args.donor_run, task=task, feedback=args.feedback) + m = derange(seeds, pool) + donors = {s: pool[m[s]] for s in seeds} + else: + dlog = RunLogger(os.path.join(run_dir, "donors"), save_images=True, jpeg_quality=cfg.jpeg_quality) + dcfg = HarnessConfig(**{**config_dict(cfg), "memory": "full", "early_stop": "auto"}) + dh = AgentHarness(task, backend, dcfg, dlog) + for s in seeds: + _, recs = dh.run_instance(s + args.donor_offset) + donors[s] = recs + print(f"[donor] seed={s + args.donor_offset} first_success=" + f"{next((r.attempt for r in recs if r.success), None)}", flush=True) + dlog.close() + + runs = [] + for i, s in enumerate(seeds): + summ, recs = harness.run_instance(s, donor=donors.get(s)) + runs.append(summ) + print(f"[{i + 1}/{len(seeds)}] seed={s} first_success={summ['first_success']} attempts={summ['n_attempts']} " + f"status={summ['status']} llm_calls={summ['n_llm_calls']} tool_calls={summ['n_tool_calls']} " + f"({time.time() - t0:.0f}s)", flush=True) + agg = aggregate(runs, k) + log.write_json("summary.json", dict(task=args.task, backend=backend.config(), memory=args.memory, + feedback=args.feedback, k=k, seeds=seeds, aggregate=agg, + runs=[{kk: v for kk, v in r.items() if not kk.startswith("_")} for r in runs])) + log.close() + print(json.dumps({kk: agg[kk] for kk in ("n_runs", "n_error_runs", "succ_at", "attempt1_success", + "mean_first_success", "pass_at_k_iid_analytic", "repeated_action_rate", + "llm_calls_per_run", "tool_calls_per_run", "sim_wall_per_run_s")}, + default=str)) + print(f"[run_agent] done -> {run_dir}") + return run_dir, agg, runs + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/robot_server.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/robot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2b05a011de75f29faf4674c3b96ca68bdb98cb0d --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/robot_server.py @@ -0,0 +1,966 @@ +"""Robot server for driving an LFF-Bench task from an isolated agent (e.g. a Claude Code subagent). + +The server owns the simulator, the task instance and its hidden variables. The agent only gets a +sandbox directory containing a tiny `robot` CLI (talks to this server over localhost HTTP), a README +with the instructions, and the observation images the server writes into `/obs/`. +Nothing about the benchmark (code paths, hidden variables, success rule, scripted policies) is ever +written into the sandbox. + +Attempt protocol (same semantics as harness.py): + cross `done` -> outcome is measured; if failed and attempts remain, the scene is reset to the same + initial state + hidden variables and the next attempt starts. + within `done` -> outcome is measured; if failed and done-calls remain, continue from the current state. +memory=none: every attempt is meant for a fresh agent; after `done` the server tells the agent to stop +(no feedback) and waits for the orchestrator to start a new agent (`./robot status` shows the state). + +Run: python -m lffbench.agent.robot_server --task l5_slide_to_target --seed 1001 --sandbox --port 8765 +""" +import argparse +import importlib +import json +import os +import pkgutil +import shutil +import sys +import time +import traceback +from http.server import BaseHTTPRequestHandler, HTTPServer +import signal +import textwrap + +import numpy as np + +from .. import tasks as task_pkg +from ..task_base import TASKS +from . import camera as C +from .context import PromptBuilder +from .tools import ACTION_TOOLS, WS_HI, WS_LO, ToolExecutor, _json_default + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +SHELL_TEMPLATE = r'''#!/bin/bash +# Run a shell command inside this workspace, in the episode jail (no network, host data hidden): +# ./shell '' or ./shell <<'EOF' ... EOF (command read from stdin) +WS="$(cd "$(dirname "$0")" && pwd)" +if [ $# -gt 0 ]; then CMD="$*"; else CMD="$(cat)"; fi +exec unshare --user --map-root-user --mount --net -- /opt/lffjail/jail_inner.sh "$WS" timeout -k 5 60 bash -c "$CMD" +''' + +CLI_TEMPLATE = r'''#!/usr/bin/env python3 +"""Robot command-line interface. Usage: ./robot [key=value ...] (./robot help)""" +import json, sys, urllib.request +PORT = __PORT__ +TOKEN = "__TOKEN__" +def main(): + if len(sys.argv) < 2: + sys.argv.append("help") + cmd, args = sys.argv[1], {} + for a in sys.argv[2:]: + if "=" not in a: + print(f"bad argument {a!r}: use key=value"); sys.exit(2) + k, v = a.split("=", 1) + try: + args[k] = json.loads(v) + except ValueError: + args[k] = v + 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=600) as r: + print(r.read().decode()) +main() +''' + + +def strip_axes(text): + """v2: keep the robot-centric words of the F2 feedback ("to the robot's left", "forward") but drop the explicit + coordinate-axis labels ("(+y)", "+x, ", "+yaw"), so the feedback does not hand over the axis convention that the + v2 instructions deliberately leave out.""" + import re + t = re.sub(r"\s?\((?:[+-]?[xyz]|[+-]yaw)\)", "", text) # " (+y)", " (x)", " (-yaw)" + t = re.sub(r"\(([+-][xyz]|[+-]yaw), ", "(", t) # "(+x, away from the robot)" + t = re.sub(r", [+-](?:[xyz]|yaw)\)", ")", t) # "(... robot's left, +yaw)" + t = re.sub(r"\s{2,}", " ", t) + return t + + +class VideoRec: + """Records agentview | wrist while the simulator steps (one frame every `every` control steps, played at + `fps`, i.e. sped up by every * fps / 20). A header shows the attempt, the current robot command and the + report of the previous one; gripper commands and attempt outcomes get short freeze frames.""" + + BAND = 56 + + def __init__(self, path, env, res=320, every=3, fps=20, title=""): + import imageio + from . import camera as _C + self.env, self.res, self.every, self.fps, self.title = env, res, every, fps, title + self.cams = [_C.mj_cam("agentview"), _C.mj_cam("wrist")] + self.w = imageio.get_writer(path, fps=fps, quality=7, macro_block_size=8) + self.n = 0 + self.lines = ["", "", ""] + self.last = None + orig = env.step + + def step(a): + out = orig(a) + self.n += 1 + if self.w is not None and self.n % self.every == 0: + self.grab() + return out + + env.step = step + + def _font(self, size): + from PIL import ImageFont + try: + return ImageFont.load_default(size=size) + except TypeError: + return ImageFont.load_default() + + def grab(self): + from PIL import Image, ImageDraw + from .. import envs as _E + img = np.concatenate([_E.render(self.env, c, self.res) for c in self.cams], axis=1) + im = Image.new("RGB", (2 * self.res, self.res + self.BAND), (0, 0, 0)) + im.paste(Image.fromarray(img), (0, self.BAND)) + d = ImageDraw.Draw(im) + hdr = [self.title] + self.lines[:2] + for i, s_ in enumerate(hdr): + d.text((5, 3 + 17 * i), s_[:120], fill=(255, 255, 255) if i else (255, 220, 120), font=self._font(13)) + self.last = np.asarray(im) + self.w.append_data(self.last) + + def hold(self, secs): + if self.w is None: + return + self.grab() + for _ in range(int(secs * self.fps)): + self.w.append_data(self.last) + + def card(self, lines, secs=3.0, color=(20, 20, 20)): + if self.w is None: + return + from PIL import Image, ImageDraw + im = Image.new("RGB", (2 * self.res, self.res + self.BAND), color) + d = ImageDraw.Draw(im) + y = 14 + for s_ in lines: + for part in textwrap.wrap(s_, 62) or [""]: + d.text((14, y), part, fill=(255, 255, 255), font=self._font(15)) + y += 19 + y += 5 + fr = np.asarray(im) + for _ in range(int(secs * self.fps)): + self.w.append_data(fr) + + def close(self): + if self.w is not None: + self.w.close() + self.w = None + + +def _short(rep): + keys = ("touched_object", "holding_object", "gripper_width_m", "eef_pos", "eef_yaw_deg", "error") + return ", ".join(f"{k}={rep[k]}" for k in keys if k in rep) + + +class RobotSession: + def __init__(self, a): + self.a = a + self.task = TASKS[a.task](cam_res=a.image_res) + if a.max_steps is None: # long procedural tasks declare a larger per-attempt budget + a.max_steps = int(getattr(self.task, "agent_max_steps", 40)) + self.inst = self.task.sample_instance(a.seed) + if getattr(a, "nominal", False): + # control condition: same scene, hidden calibration error removed (L1 tasks only) -> plain pick-and-place + hidden = [k for k in ("bias", "yaw_bias") if k in self.inst] + if not hidden: + raise SystemExit(f"--nominal is not supported for {a.task} (no bias / yaw_bias in the instance)") + for k in [k for k in self.inst if "bias" in k]: # bias, bias_r, yaw_bias, yaw_bias_deg, ... + v = self.inst[k] + if isinstance(v, (list, tuple)): + self.inst[k] = [0.0] * len(v) + elif isinstance(v, (int, float)): + self.inst[k] = 0.0 + self.inst["nominal"] = True + # full5 controlled arms (docs/14 §6): h0 / twin override the hidden variable, hplus states it in the instruction + self.arm, self.arm_overrides, self.reveal_text = getattr(a, "arm", "none") or "none", {}, "" + if self.arm in ("h0", "twin"): + from .. import arm_specs + self.arm_overrides = arm_specs.overrides(a.task, self.arm, self.inst) + self.inst.update(self.arm_overrides) + elif self.arm == "hplus": + from .. import arm_specs + self.reveal_text = arm_specs.reveal(a.task, self.inst).strip() + if a.style in ("v2", "la"): # same rule as the F2 feedback: no axis labels such as "(+y)" + self.reveal_text = strip_axes(self.reveal_text) + self.n_mon_events = 0 # regression snapshots: monitor events already inspected + self.protocol = getattr(self.task, "protocol", "cross") + self.k = a.k or self.task.max_attempts + # --hide-k (memory=full): README and status say 1 attempt, exactly like an independent k=1 run, and the other + # attempts are announced only after a failure, so attempt 1 sees the same thing as the independent run. + self.k_shown = 1 if getattr(a, "hide_k", False) and a.memory == "full" else self.k + assert self.k_shown == self.k or a.style in ("v2", "la"), "--hide-k needs --style v2 or la" + self.sandbox = os.path.abspath(a.sandbox) + self.obs_dir = os.path.join(self.sandbox, "obs") + self.log_dir = os.path.abspath(a.log_dir) + os.makedirs(self.obs_dir, exist_ok=True) + os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True) + self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a") + import secrets + self.token = secrets.token_hex(8) + self.n_actions = 0 # robot commands in the current attempt (step budget) + self.attempt = 1 + self.step = 0 + self.finished = False + self.waiting_new_agent = False + self.history = [] + self.last_send = None + cam_axes = {c: C.describe_axes(self.task.env, c, a.image_res) for c in C.CAMERAS} + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + memory = "none" if a.memory == "none" else "full" + self.pb = PromptBuilder(self.task, self.protocol, self.k, memory, a.feedback, a.image_res, cam_axes, + object_names=names, cams=("agentview", "wrist"), depth_tool=a.perception == "depth") + self.video = None + if a.video: + self.video = VideoRec(a.video, self.task.env, every=a.video_every, fps=a.video_fps, + title=f"{a.task} seed={a.seed} perception={a.perception} (sped up x{a.video_every * a.video_fps // 20})") + self.video.card([f"Task: {a.task} seed {a.seed} memory={a.memory} feedback={a.feedback} k={self.k}", + "Instruction: " + self.instruction(), + "Left: agentview Right: wrist camera. Header: current robot command and the report of " + "the previous one."], 3) + self._start_attempt(reset=True) + # la: agent-facing positions are in the robot-base frame (LIBERO-Agent: "Coordinates are expressed in the + # robot-base frame and measured in metres"); the LIBERO base is axis-aligned with the world, so a translation + self.base_off = np.zeros(3) + if a.style == "la": + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + assert np.allclose(sim.data.body_xmat[bid].reshape(3, 3), np.eye(3), atol=1e-6), "robot base is rotated" + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + self._write_sandbox() + self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol, + memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception, + inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm, + arm_overrides=self.arm_overrides, reveal=self.reveal_text, dossier=getattr(a, "dossier", "") or "")) + + # ------------------------------------------------------------------ helpers + def log(self, d): + d["t"] = time.time() + self.events.write(json.dumps(d, default=_json_default) + "\n") + self.events.flush() + + def instruction(self): + hook = getattr(self.task, "agent_instruction", None) + if hook is not None: + text = hook(self.inst, self.a.instruction) + elif self.a.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""): + text = self.task.instruction_indirect + else: + text = self.task.instruction + return text + (" " + self.reveal_text if getattr(self, "reveal_text", "") else "") + + def feedback_text(self, out): + import inspect + fn = self.task.feedback + if "indirect" in inspect.signature(fn).parameters: + fb = fn(self.inst, out, self.a.feedback, indirect=self.a.instruction == "indirect") + else: + fb = fn(self.inst, out, self.a.feedback) + return strip_axes(fb) if self.a.style in ("v2", "la") else fb + + def _start_attempt(self, reset): + self.n_actions = 0 + if reset: + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.a.image_res, cams=("agentview", "wrist")) + self.step = 0 + self.sim0 = self.task.sk.n_steps # v2: simulated-time budget is counted per attempt + + def _save_obs(self, tag): + """Same bytes as the GPT harness sends (JPEG q90). Under memory=none the file names carry no + attempt number, so a fresh agent cannot tell it is a retry; --hide-k names attempt 1 the same way.""" + from PIL import Image + paths = [] + for ref in self.ex.observe(label=tag): + name = (f"s{self.step:03d}_{ref.camera}.jpg" if self.a.memory == "none" or (self.k_shown < self.k and self.attempt == 1) + else f"a{self.attempt}_s{self.step:03d}_{ref.camera}.jpg") + Image.fromarray(ref.array).save(os.path.join(self.obs_dir, name), quality=90) + shutil.copy(os.path.join(self.obs_dir, name), os.path.join(self.log_dir, "images", f"a{self.attempt}_{name}")) + paths.append(f"obs/{name}") + if self.a.style == "la": + self.last_files = self._write_la_files(f"a{self.attempt}_s{self.step:03d}") + return paths + + def readme(self): + if self.a.style == "la": + return self.readme_la() + if self.a.style == "v2": + return self.readme_v2() + sp = self.pb.system_prompt() + sp = sp.replace("You act only by calling the provided tools, exactly one tool call per turn. Every action tool " + "returns an execution report; after each action you also receive new camera images and the " + "robot's proprioceptive state.", + "You act only through the `./robot` command in this directory (one robot command at a time). " + "Every action command prints an execution report and the paths of new camera images taken " + "after the action; look at them with your file-reading tool.") + sp = sp.replace("Finish by calling done(reason)", "Finish by running `./robot done reason=\"...\"`") + sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the " + "actions you executed and outcome feedback).", + "Each attempt ends when you run `./robot done`; that command prints the outcome feedback (if any) " + "and the images of the reset scene for the next attempt.") + sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the " + "actions you executed).", + "Each attempt ends when you run `./robot done`; that command prints the images of the reset " + "scene for the next attempt.") + sp = sp.replace("before your first tool call", "before your first robot command") + tools = "\n".join([ + " ./robot help this text", + " ./robot status task, current images and proprioception", + " ./robot observe take new images (agentview + wrist) + proprioception", + " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)", + " ./robot open_gripper | ./robot close_gripper", + " ./robot pixel_to_world camera=agentview|wrist u=.. v=.. (pixel -> 3-D point via depth)", + " ./robot done reason=\"...\" end the attempt / segment", + ] if self.a.perception == "depth" else [ + " ./robot help this text", + " ./robot status task, current images and proprioception", + " ./robot observe take new images (agentview + wrist) + proprioception", + " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)", + " ./robot open_gripper | ./robot close_gripper", + " ./robot done reason=\"...\" end the attempt / segment", + ]) + return ("# Robot task\n\n" + sp + "\n\n## Commands\n" + tools + + "\n\nArguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.\n" + "Images are written to obs/ inside this directory. After every action, look at the new images " + "before deciding on the next command.\n" + f"Each attempt allows at most {self.a.max_steps} robot commands (help/status not counted); after that " + "the attempt ends automatically.\n\n## TASK\n" + self.instruction() + "\n") + + def _write_sandbox(self): + os.makedirs(self.sandbox, exist_ok=True) + if self.a.style == "la": + with open(os.path.join(self.log_dir, "agent_iface.json"), "w") as f: + json.dump(dict(token=self.token, port=self.a.port, workspace=self.sandbox, agent_iface=self.a.agent_iface, + max_tool_calls=self.a.max_tool_calls, perception=self.a.perception), f) + with open(os.path.join(self.sandbox, "README.md"), "w") as f: + f.write(self.readme()) + if getattr(self.a, "dossier", ""): + shutil.copytree(self.a.dossier, os.path.join(self.sandbox, "history")) + if self.a.agent_iface == "cli": # coding-agent harness (Claude Code): ./robot + ./shell in the workspace + for name, body in (("robot", CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)), + ("shell", SHELL_TEMPLATE)): + with open(os.path.join(self.sandbox, name), "w") as f: + f.write(body) + os.chmod(os.path.join(self.sandbox, name), 0o755) + return + cli = os.path.join(self.sandbox, "robot") + with open(cli, "w") as f: + f.write(CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)) + os.chmod(cli, 0o755) + with open(os.path.join(self.sandbox, "README.md"), "w") as f: + f.write(self.readme()) + + def status(self): + if self.a.memory == "none": + return dict(task=self.instruction(), finished=self.finished) + st = dict(task=self.instruction(), protocol=self.protocol, attempt=self.attempt, max_attempts=self.k, + finished=self.finished) + if self.waiting_new_agent: + st["note"] = "The previous agent finished its attempt. A new attempt is ready; the scene has been reset." + return st + + # ------------------------------------------------------------------ dispatch + def handle(self, cmd, args): + if self.a.style in ("v2", "la"): + return self.handle_v2(cmd, args) + if cmd == "help": + return dict(text=self.readme()) + if cmd == "status": + st = self.status() + st["images"] = self._save_obs("status") + st.update(self.ex.proprio()) + self.waiting_new_agent = False + return st + if self.finished: + return dict(ok=False, error="The episode is over. Stop now.") + if self.waiting_new_agent: + return dict(ok=False, error="This attempt has ended. Stop now.") + if cmd in ("observe", "pixel_to_world", "move_to", "open_gripper", "close_gripper", "push"): + self.n_actions += 1 + if self.n_actions > self.a.max_steps: + rep = self._done("step budget exhausted (automatic)") + rep["note"] = f"The step budget of {self.a.max_steps} commands for this attempt was used up." + return rep + if cmd == "observe": + self.step += 1 + rep = dict(ok=True, images=self._save_obs("observe")) + rep.update(self.ex.proprio()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + if cmd == "done": + return self._done(args.get("reason", "")) + allowed = tuple(t for t in ACTION_TOOLS if t != "push" or self.a.allow_push) + if self.a.perception == "depth": + allowed += ("pixel_to_world",) + if cmd not in allowed: + return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help") + self.step += 1 + if self.video is not None: + argtxt = " ".join(f"{k}={v}" for k, v in args.items()) + self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}" + res = self.ex.call(cmd, args) + rep = dict(res.report) + if self.video is not None: + self.video.lines[1] = f" -> {_short(rep)}" + if cmd in ("close_gripper", "open_gripper"): + self.video.hold(1.2) + if res.ok and cmd in ACTION_TOOLS: + rep["images"] = self._save_obs(cmd) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, + wall_s=res.wall_s, sim_steps=res.sim_steps)) + return rep + + def _done(self, reason): + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + fb = self.feedback_text(out) + self.history.append(dict(attempt=self.attempt, success=succ, feedback=fb, reason=reason)) + self.log(dict(ev="done", attempt=self.attempt, step=self.step, reason=reason, success=succ, feedback=fb, + outcome={k: v for k, v in out.items() if k != "feedback"})) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.video is not None: + self.video.lines = [f"attempt {self.attempt}/{self.k}: done", f" reason: {reason}", ""] + self.video.hold(1.0) + self.video.card([f"Attempt {self.attempt}: {'SUCCESS' if succ else 'FAILED'}", + f"Commands used in this attempt: {self.n_actions}", "Agent's reason: " + str(reason)[:300], + "Feedback: " + (fb if self.a.memory != "none" and self.a.feedback != "F0" else "(not shown)")], + 3.5, (20, 50, 20) if succ else (60, 20, 20)) + if last: + self.video.close() + else: + self.video.lines = ["", "", ""] + if self.a.memory == "none": + # independent attempts: no feedback to the agent; orchestrator starts a fresh agent + if last: + self.finished = True + else: + self.attempt += 1 + self._start_attempt(reset=self.protocol == "cross") + self.waiting_new_agent = True + return dict(ok=True, ended=True, message="Attempt recorded. Stop now and report what you did.") + rep = dict(ok=True, ended=True) + if self.a.feedback != "F0": + rep["feedback"] = fb + if last and (succ or self.a.feedback != "F0"): + self.finished = True + rep["message"] = "The episode is over. Stop now and report." + return rep + if self.attempt >= self.k or out.get("terminal"): + self.finished = True + rep["message"] = ("The failure cannot be undone, so the episode is over. Stop now and report." + if out.get("terminal") else "No attempts left. The episode is over. Stop now and report.") + return rep + self.attempt += 1 + reveal = "" + if self.k_shown < self.k: # --hide-k: first failure, announce the extra attempts now + self.k_shown = self.k + reveal = f"You get more attempts than README.md says: up to {self.k} in total. " + if self.protocol == "cross": + self._start_attempt(reset=True) + rep["message"] = reveal + (f"Attempt {self.attempt} of {self.k} starts now. The scene has been reset to exactly the " + f"same initial state.") + else: + self._start_attempt(reset=False) + rep["message"] = reveal + (f"Continue from the current state (segment {self.attempt}; you may call done at most " + f"{self.k} times in total).") + self.step += 1 + rep["images"] = self._save_obs("attempt_start") + rep.update(self._la_files()) + if self.a.style in ("v2", "la"): + rep.update(self._state_v2()) + else: + rep.update(self.ex.proprio()) + return rep + + +V2_DROP = ("holding", "touched", "events", "sim_time_s", "tool", "reached", "yaw_used_deg", "target_clipped_to") + + +class _V2: + """Interface v2 (2026-10-07, aligned with LIBERO-Agent / RoboDojo-L3 at the user's request): + - priors: only the task instruction, the attempt rules, the budgets and the command definitions (no axes, + table height, camera orientation or robot geometry); + - observations: two RGB images published as files after every command + end-effector state (position, + yaw, gripper width) + how far the arm stopped from the commanded target + budget left; no + held/touched flags and no per-step task events; + - action: move_eef = absolute target (omitted coordinates keep their value; gripper after the motion; + optional speed); unreachable targets are rejected and the arm does not move; + - an attempt ends with `finish` (alias `done`) or when a budget runs out; the environment judges it.""" + + +def _readme_v2(self): + sec = self.sim_budget() + proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the " + f"same initial state." if self.protocol == "cross" else + f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a " + f"failed attempt you continue from the current state.") + return "\n".join([ + "# Robot task", "", + "You control a robot arm with a two-finger gripper in a physics simulation, only through the `./robot` " + "command in this directory (one command at a time).", "", + "## Task", self.instruction(), "", + "## Attempts", proto + " An attempt ends when you run `./robot finish reason=\"...\"` or when its budget " + "is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the last " + "attempt.", "", + "## Budget (per attempt)", + f"- at most {self.a.max_steps} robot commands (status and help are free);", + f"- at most {sec:.0f} s of simulated robot motion.", + "Every reply shows what is left.", "", + "## Observations", + "Every command writes two new camera images into obs/ and prints their paths: 'agentview' (a fixed camera " + "looking at the table) and 'wrist' (a camera on the gripper). It also reports the end-effector state: " + "eef_pos = [x, y, z] of the gripper's grasp point in metres, eef_yaw_deg = rotation of the gripper about " + "the vertical axis in degrees, gripper_width_m = opening of the fingers in metres, and after a motion how " + "far the gripper stopped from your target.", "", + "## Commands", + " ./robot status task, attempt, budget, current state and images", + " ./robot observe new images and state without moving", + " ./robot move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]", + " move the grasp point to an absolute target in the same frame as eef_pos (metres; yaw in degrees);", + " omitted coordinates keep their current value; the gripper command is executed after the motion;", + " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.", + " ./robot finish reason=\"...\" end the current attempt", + "", + "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""]) + + +def _sim_budget(self): + return 3.0 * self.a.max_steps # seconds of simulated motion per attempt + + +def _budget_left(self): + used = (self.task.sk.n_steps - self.sim0) * 0.05 + return dict(commands=max(self.a.max_steps - self.n_actions, 0), sim_seconds=round(max(self.sim_budget() - used, 0.0), 1)) + + +def _state_v2(self): + p = self.ex.proprio() + pos = p["eef_pos"] + if self.a.style == "la": + pos = [round(float(v), 4) for v in np.asarray(pos, float) - self.base_off] + st = dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + if self.a.style == "la": # read-only joint angles, as LIBERO-Agent (all levels) and RoboDojo give them + st["joint_pos_rad"] = [round(float(v), 4) for v in self._believed_joints()] + st["budget_left"] = self._budget_left() + return st + + +def _clean_v2(rep): + return {k: v for k, v in rep.items() if not k.startswith(V2_DROP)} + + +def _handle_v2(self, cmd, args): + if cmd == "help": + return dict(text=self.readme()) + if cmd == "status": + st = dict(task=self.instruction(), attempt=self.attempt, max_attempts=self.k_shown, finished=self.finished) + st["images"] = self._save_obs("status") + st.update(self._la_files()) + st.update(self._state_v2()) + return st + if self.finished: + return dict(ok=False, error="The episode is over. Stop now.") + if cmd in ("finish", "done"): + return self._done(args.get("reason", "")) + if cmd not in ("observe", "move_eef"): + return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help") + self.n_actions += 1 + if self.n_actions > self.a.max_steps: + rep = self._done("command budget used up (automatic)") + rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up." + return rep + self.step += 1 + if cmd == "observe": + rep = dict(ok=True, images=self._save_obs("observe")) + rep.update(self._la_files()) + rep.update(self._state_v2()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + # ---------------- move_eef + p = self.ex.proprio() + unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"} + if unknown: + rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + off = self.base_off # zero except la (robot-base frame) + try: + 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"]) + except (TypeError, ValueError): + rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + grip = args.get("gripper") + if grip not in (None, "open", "close"): + rep = dict(ok=False, error="gripper must be open or close") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off # simulator (world) frame + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move") + rep.update(self._state_v2()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + if self.video is not None: + argtxt = " ".join(f"{k}={v}" for k, v in args.items()) + self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}" + left = self._budget_left()["sim_seconds"] + raw = {} + 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 + res = self.ex.call("move_to", mv) + raw.update(res.report) + if grip is not None: + res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}) + raw.update(res.report) + rep = dict(ok=bool(raw.get("ok", True))) + if raw.get("error"): + rep["error"] = raw["error"] + rep.update(self._state_v2()) + if moving: + err = np.asarray(tgt) - np.asarray(rep["eef_pos"]) + dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0 + rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1)) + if self.video is not None: + self.video.lines[1] = f" -> eef={rep['eef_pos']} width={rep['gripper_width_m']} {rep.get('stopped_from_target', '')}" + if grip is not None: + self.video.hold(1.2) + rep["images"] = self._save_obs(cmd) + rep.update(self._la_files()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw)) + self._snap_regressions() + if rep["budget_left"]["sim_seconds"] <= 0 and left > 0: + fin = self._done("motion budget used up (automatic)") + fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up." + rep["attempt_ended"] = fin + return rep + + +LOSS_EVENTS = ("lost", "toppled", "tipped", "load_fell", "load_displaced") + + +def _snap_regressions(self): + """Save the simulator state right after a command during which the task monitor registered a loss of earlier + progress (lost / toppled / tipped / load_fell ...), for the "self-inflicted vs handed-over" experiment (docs/14 §6). + Server-side only: snapshots go to /snapshots/, never to the agent's workspace.""" + try: # bookkeeping only: it must never change what the agent gets back + self._snap_regressions_inner() + except Exception: + self.log(dict(ev="snapshot_error", error=traceback.format_exc()[-1500:])) + + +def _snap_regressions_inner(self): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + new = evs[self.n_mon_events:] + self.n_mon_events = len(evs) + loss = [e for e in new if isinstance(e, dict) and str(e.get("ev", e.get("event", ""))) in LOSS_EVENTS] + if not loss: + return + import copy + d = os.path.join(self.log_dir, "snapshots") + os.makedirs(d, exist_ok=True) + name = f"a{self.attempt}_s{self.step:03d}" + try: + flat = np.asarray(self.task.env.sim.get_state().flatten(), float) + except Exception: # keep the run going even if a simulator binding lacks get_state + flat = np.concatenate([self.task.env.sim.data.qpos, self.task.env.sim.data.qvel]).astype(float) + np.save(os.path.join(d, name + "_sim.npy"), flat) + meta = dict(attempt=self.attempt, step=self.step, n_actions=self.n_actions, sim_steps=int(self.task.sk.n_steps - self.sim0), + loss_events=loss, mon=copy.deepcopy(mon)) + def _dflt(o): # task monitors keep sets (ever / lost / lid_hits ...) + return sorted(o, key=str) if isinstance(o, (set, frozenset)) else _json_default(o) + with open(os.path.join(d, name + "_meta.json"), "w") as f: + json.dump(meta, f, default=_dflt) + self.log(dict(ev="regression_snapshot", attempt=self.attempt, step=self.step, file=f"snapshots/{name}", n_loss=len(loss))) + + +def _la_files(self): + """la: paths of the non-image observation files written with the last images (empty for other styles).""" + return dict(self.last_files) if self.a.style == "la" and getattr(self, "last_files", None) else {} + + +def _believed_pose(self): + """4x4 pose of the grasp point as the ROBOT believes it (the frame of eef_pos / move_eef): the true pose shifted by + the task's hidden calibration errors (Skills.bias, and YawSkills.yaw_bias about the vertical axis). A real robot + computes its wrist-camera pose from its own (miscalibrated) kinematics, so the wrist calibration uses this pose.""" + sk = self.task.sk + beta = float(getattr(sk, "yaw_bias", 0.0)) + c, s_ = np.cos(-beta), np.sin(-beta) + Rz = np.array([[c, -s_, 0.0], [s_, c, 0.0], [0.0, 0.0, 1.0]]) + T_true = np.eye(4) + T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos() + T_b = np.eye(4) + T_b[:3, :3], T_b[:3, 3] = Rz @ sk.eef_mat(), sk.eef_pos() - np.asarray(sk.bias, float) + return T_b, T_true + + +def _believed_joints(self, iters=30): + """The 7 arm joint angles as the robot's encoders report them. For tasks with a hidden calibration error (L1) these + are the angles consistent with the robot's own belief: standard forward kinematics of them gives exactly the + reported (believed) grasp pose, as on a real arm whose encoder offsets are miscalibrated; true joint angles would + hand the hidden error to anyone who runs the public Franka kinematics. Without a calibration error they are the true + angles. Solved by damped least squares on a scratch copy of the simulator state (2-3 iterations).""" + import mujoco + env, sk = self.task.env, self.task.sk + rob = env.robots[0] + idx, dof, site = np.array(rob._ref_joint_pos_indexes), np.array(rob._ref_joint_vel_indexes), rob.eef_site_id + m, d0 = env.sim.model._model, env.sim.data._data + T_b, _ = self._believed_pose() + if np.allclose(T_b[:3, 3], d0.site_xpos[site]) and np.allclose(T_b[:3, :3], d0.site_xmat[site].reshape(3, 3)): + return d0.qpos[idx].copy() + d = mujoco.MjData(m) + d.qpos[:] = d0.qpos + jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv)) + for _ in range(iters): + mujoco.mj_kinematics(m, d) + mujoco.mj_comPos(m, d) + ep = T_b[:3, 3] - d.site_xpos[site] + Re = T_b[:3, :3] @ d.site_xmat[site].reshape(3, 3).T + er = 0.5 * np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]]) + if np.linalg.norm(ep) < 1e-7 and np.linalg.norm(er) < 1e-7: + break + mujoco.mj_jacSite(m, d, jp, jr, site) + J = np.vstack([jp[:, dof], jr[:, dof]]) + d.qpos[idx] += J.T @ np.linalg.solve(J @ J.T + 1e-6 * np.eye(6), np.concatenate([ep, er])) + return d.qpos[idx].copy() + + +def _write_la_files(self, prefix): + """la observation files besides the two JPEGs: _state.json always; with --perception rgbd also metric + depth for both cameras (__depth.npy, float32 metres along the optical axis, same upright pixels as + the JPEG) and _camera.json (K and cam_to_world in the eef_pos frame, OpenCV camera axes). + The fixed agentview camera is calibrated in the true frame; the wrist camera pose is computed from the robot's + believed gripper pose (so neither file reveals the hidden calibration error of the L1 tasks).""" + out = {} + st = self._state_v2() + st = dict(eef_pos=st["eef_pos"], eef_yaw_deg=st["eef_yaw_deg"], gripper_width_m=st["gripper_width_m"], + joint_pos_rad=st["joint_pos_rad"], attempt=self.attempt, step=self.step) + with open(os.path.join(self.obs_dir, f"{prefix}_state.json"), "w") as f: + json.dump(st, f, default=_json_default) + out["state_file"] = f"obs/{prefix}_state.json" + if self.a.perception == "rgbd": + res = self.a.image_res + cams, depth_files = {}, [] + T_b, T_true = self._believed_pose() + for cam in ("agentview", "wrist"): + d = C.render_depth(self.task.env, cam, res).astype(np.float32) + np.save(os.path.join(self.obs_dir, f"{prefix}_{cam}_depth.npy"), d) + depth_files.append(f"obs/{prefix}_{cam}_depth.npy") + E = C.cam_to_world(self.task.env, cam) + if cam == "wrist": + E = T_b @ np.linalg.inv(T_true) @ E + E = E.copy() + E[:3, 3] -= self.base_off # robot-base frame + cams[cam] = dict(K=np.round(C.intrinsics(self.task.env, cam, res), 6).tolist(), + cam_to_base=np.round(E, 6).tolist(), width=res, height=res) + with open(os.path.join(self.obs_dir, f"{prefix}_camera.json"), "w") as f: + json.dump(cams, f) + out["depth_files"] = depth_files + out["camera_file"] = f"obs/{prefix}_camera.json" + return out + + + +def _fb_sentence(level): + """README sentence for the feedback level. F1 (default since 2026-10-08): success / failure only, like + LIBERO-Agent's finish_episode outcome; F2 (measured error, e.g. "2.5 cm past the centre") is privileged + simulator information that neither LIBERO-Agent nor RoboDojo gives, kept only as an ablation.""" + return {"F0": "The environment then checks the result.", + "F1": "The environment then checks the result and tells you only whether the attempt succeeded.", + "F2": "The environment then checks the result and tells you whether the attempt succeeded and, if not, " + "what went wrong."}[level] + +def _readme_la(self): + """LIBERO-Agent-style instructions: the agent works in an episode workspace (observations are files, it can run + programs on them); the robot itself is driven only through the harness's `robot` tool.""" + sec = self.sim_budget() + rgbd = self.a.perception == "rgbd" + cli = self.a.agent_iface == "cli" + pre = "./robot " if cli else "" + proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the " + f"same initial state." if self.protocol == "cross" else + f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a " + f"failed attempt you continue from the current state.") + files = [ + "- obs/a_s_agentview.jpg and obs/a_s_wrist.jpg: 512x512 RGB images from " + "'agentview' (a fixed camera looking at the table) and 'wrist' (a camera on the gripper);", + "- obs/a_s_state.json: the end-effector state: eef_pos = [x, y, z] of the gripper's grasp " + "point (midway between the two fingers, about 1 cm above the fingertips), eef_yaw_deg = rotation of the gripper about the vertical axis in degrees, gripper_width_m = opening " + "of the fingers in metres, joint_pos_rad = the 7 arm joint angles (radians, base to wrist; read-only).", + ] + if rgbd: + files += [ + "- obs/a_s_agentview_depth.npy and obs/a_s_wrist_depth.npy: metric depth " + "(numpy float32 array, 512x512, metres along each camera's optical axis), pixel-aligned with the images " + "(row 0 = top of the image);", + "- obs/a_s_camera.json: for each camera, K (3x3 intrinsics of the 512x512 image) and " + "cam_to_base (4x4 pose of the camera in the robot-base frame; camera axes: x right, y down, z forward).", + ] + return "\n".join([ + "# Robot task", "", + "You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics " + "simulation.", "", + "## Task", self.instruction(), "", + "## Attempts", proto + f" An attempt ends when you run the robot command `{pre}finish reason=\"...\"` or when its " + "budget is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the " + "last attempt.", "", + *(["## Earlier attempt", + "Before this episode, an earlier attempt at this task, starting from a scene that looked the same as yours, " + "failed. Its record is in history/: history/README.md lists every robot command of that attempt with the " + "robot's reply and its closing remark, and history/obs/ holds the camera images it produced.", ""] + if getattr(self.a, "dossier", "") else []), + "## Budget (per attempt)", + f"- at most {self.a.max_steps} robot commands (status and help are free);", + f"- at most {sec:.0f} s of simulated robot motion;", + *([] if cli else [f"- at most {self.a.max_tool_calls} tool calls in total (robot, shell and view_image together)."]), + "Every robot reply shows the robot budgets that are left.", "", + "## Coordinates", + "Coordinates are expressed in the robot-base frame and measured in metres; angles are in degrees.", "", + "## Workspace and observations", + "This directory is your workspace for the whole episode. Every robot command writes its observation into " + "obs/ and prints the paths of the new files:", + *files, + "Robot replies also include the end-effector state and, after a motion, how far the gripper stopped from your " + "target. " + ("You can look at any image with your file-reading tool, run shell commands and programs in this " + "workspace with `./shell ''` (python3 with numpy, scipy, Pillow and OpenCV; no network; " + "programs cannot control the robot), and keep your own files and notes in this directory; they " + "persist across attempts." if cli else + "You can look at any image with view_image, run shell commands and programs here (python3 with " + "numpy, scipy, Pillow and OpenCV; no network; programs cannot control the robot), and keep your " + "own files and notes in this directory; they persist across attempts."), "", + "## Robot commands " + ("(run from this directory as `./robot `, one command at a time)" if cli + else "(argument of the `robot` tool)"), + f" {pre}status task, attempt, budget, current state and observation files", + f" {pre}observe new observation without moving", + f" {pre}move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]", + " move the grasp point to an absolute target (robot-base frame, metres; yaw in degrees);", + " omitted coordinates keep their current value; the gripper command is executed after the motion;", + " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.", + f" {pre}finish reason=\"...\" end the current attempt", + "", + "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""]) + + +for _n, _f in (("_believed_joints", _believed_joints), ("readme_la", _readme_la), ("_la_files", _la_files), ("_believed_pose", _believed_pose), + ("_write_la_files", _write_la_files), ("readme_v2", _readme_v2), ("sim_budget", _sim_budget), ("_budget_left", _budget_left), + ("_state_v2", _state_v2), ("handle_v2", _handle_v2), ("_snap_regressions", _snap_regressions), + ("_snap_regressions_inner", _snap_regressions_inner)): + setattr(RobotSession, _n, _f) +RobotSession._clean_v2 = staticmethod(_clean_v2) + + +def serve(a): + sess = RobotSession(a) + + class H(BaseHTTPRequestHandler): + def log_message(self, *x): + pass + + def do_POST(self): + t_recv = time.time() + cmd = "" + try: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + cmd = body.get("cmd", "") + if self.headers.get("X-Token") != sess.token: + rep = dict(ok=False, error="unauthorised") + else: + rep = sess.handle(cmd, body.get("args", {}) or {}) + except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent + sess.log(dict(ev="error", error=traceback.format_exc())) + rep = dict(ok=False, error=f"internal error: {type(e).__name__}") + data = json.dumps(rep, default=_json_default, indent=None).encode() + if "text" in rep: + data = rep["text"].encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(data) + t_send = time.time() + # think time = gap between the previous reply and this request (model inference + its own tool overhead) + sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send, + server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None)) + sess.last_send = t_send + + def _term(*_): + if sess.video is not None: + sess.video.close() + os._exit(0) + + signal.signal(signal.SIGTERM, _term) + srv = HTTPServer(("127.0.0.1", a.port), H) + print(f"robot server ready on 127.0.0.1:{a.port} sandbox={sess.sandbox} log={sess.log_dir}", flush=True) + with open(os.path.join(sess.log_dir, "READY"), "w") as f: + f.write(str(os.getpid())) + srv.serve_forever() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--seed", type=int, required=True) + ap.add_argument("--k", type=int, default=None) + ap.add_argument("--memory", default="full", choices=["full", "none"]) + ap.add_argument("--hide-k", action="store_true", + help="memory=full: README/status say 1 attempt (same as an independent k=1 run); the remaining " + "attempts are announced only after a failed attempt") + ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"]) + ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"]) + ap.add_argument("--image-res", type=int, default=512) + ap.add_argument("--port", type=int, default=8765) + ap.add_argument("--sandbox", required=True) + ap.add_argument("--log-dir", required=True) + ap.add_argument("--max-steps", type=int, default=None, + help="robot commands per attempt (default: the task's agent_max_steps, else 40)") + ap.add_argument("--allow-push", action="store_true", help="expose the composite push primitive (off by default)") + ap.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"], + help="rgb: images only (no pixel_to_world / depth); depth: adds the depth back-projection tool " + "(v1); rgbd (la): also writes metric depth and camera calibration files") + ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"], + help="v2: LIBERO-Agent / RoboDojo-aligned interface (see _V2); la: v2 + LIBERO-Agent workspace " + "(observation files, programs in the workspace, robot only through the harness tool)") + ap.add_argument("--nominal", action="store_true", + help="control: remove the hidden calibration error of an L1 task (bias / yaw_bias = 0)") + ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"], + help="la: tools = harness tools (robot / shell / view_images, our GPT driver); cli = ./robot and " + "./shell in the workspace for a coding agent such as Claude Code") + ap.add_argument("--max-tool-calls", type=int, default=100, + help="la: tool calls per attempt (robot + shell + view_image), enforced by the harness") + ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"], + help="full5 controlled arms (lffbench/arm_specs/.py): h0 = hidden variable at its ordinary value; " + "hplus = hidden variable stated in the instruction; twin = mismatched-history source instance") + ap.add_argument("--dossier", default="", + help="la: copy this directory into the workspace as history/ (record of an earlier failed attempt, " + "made by scripts/make_dossier.py) and say so in README.md") + ap.add_argument("--video", default="", help="record agentview|wrist mp4 to this path") + ap.add_argument("--video-every", type=int, default=3, help="one frame every N control steps (20 Hz)") + ap.add_argument("--video-fps", type=int, default=20) + serve(ap.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/check_setup.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/check_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c91b70fc618700ec2c265ebd1f9f21fed24e2420 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/check_setup.py @@ -0,0 +1,175 @@ +"""Check that this machine can run LFF-Bench. Run after `source run_env.sh`: + + python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail + python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY / + # OPENAI_BASE_URL from the environment or from .env); costs a few tokens + python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail + +Exit code 0 when every check that ran passed. +""" +import argparse +import os +import subprocess +import sys +import tempfile +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py + +results = [] + + +def report(name, ok, detail=""): + results.append(ok) + print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True) + return ok + + +def check_packages(): + report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0]) + from lffbench.agent.backends.base import import_openai + for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"): + try: + m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"]) + report(f"import {mod}", True, getattr(m, "__version__", "")) + except Exception as e: # noqa: BLE001 + report(f"import {mod}", False, f"{type(e).__name__}: {e}") + cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml") + if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")): + import yaml + assets = yaml.safe_load(open(cfg)).get("assets", "") + report("LIBERO assets", os.path.isdir(assets), assets) + report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}") + + +def check_sim(task_name, seed): + import importlib + import pkgutil + + try: + import lffbench.tasks as task_pkg + from lffbench.task_base import TASKS + except Exception as e: # noqa: BLE001 + report("import lffbench", False, f"{type(e).__name__}: {e}") + return + try: + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + except Exception as e: # noqa: BLE001 + report("import tasks", False, f"{type(e).__name__}: {e}") + return + report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks") + t0 = time.time() + try: + task = TASKS[task_name]() + inst = task.sample_instance(seed) + task.reset_instance(inst) + img = task.snapshot() + out = task.outcome(inst) + except Exception as e: # noqa: BLE001 + report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}") + return + ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0 + report(f"simulate + render {task_name}", ok, + f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s") + + +def check_jail(): + if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"), + JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"): + return + probe = r''' +echo "pwd=$(pwd)" +python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1 +echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)" +python3 -c " +import socket +s = socket.socket(); s.settimeout(3) +try: + s.connect(('1.1.1.1', 443)); print('net=open') +except OSError as e: + print('net=blocked') +" +touch made_in_jail && echo "write=ok" +''' + with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws: + argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws, + "timeout", "-k", "5", "60", "bash", "-c", probe] + r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l) + if r.returncode != 0 and not kv: + hint = "" + if "Operation not permitted" in r.stdout or "uid_map" in r.stdout: + hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: " + "sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0") + report("jail runs", False, r.stdout.strip()[-400:] + hint) + return + report("jail runs", True, f"workdir {kv.get('pwd')}") + report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:])) + report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0", + f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}") + report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?")) + report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail"))) + + +def load_env_file(): + path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env") + if not os.path.isfile(path): + return None + for line in open(path): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + k, v = line.split("=", 1) + os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\"")) + return path + + +def check_api(model, effort): + src = load_env_file() + 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" # same as scripts/gpt_player.py + if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")), + f"from {src}" if src else "from the environment (no .env)"): + return + base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)" + from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend + t0 = time.time() + try: + client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client() + resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping", + reasoning=dict(effort=effort), store=False, max_output_tokens=256) + text = (resp.output_text or "").strip() + u = resp.usage + report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, " + f"tokens in {u.input_tokens} / out {u.output_tokens}") + except Exception as e: # noqa: BLE001 + report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint") + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--effort", default="low") + ap.add_argument("--task", default="l5_slide_to_target") + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--skip-sim", action="store_true") + ap.add_argument("--skip-jail", action="store_true") + a = ap.parse_args() + os.environ.setdefault("OMP_NUM_THREADS", "1") + check_packages() + if not a.skip_sim: + check_sim(a.task, a.seed) + if not a.skip_jail: + check_jail() + if a.api: + check_api(a.model, a.effort) + n_bad = results.count(False) + print(f"\n{len(results) - n_bad}/{len(results)} checks passed") + sys.exit(1 if n_bad else 0) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/full_waves.sh b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/full_waves.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4a98c713907c49980d1dfb6571d022deeb09321 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/full_waves.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Run the remaining waves of the full GPT-6 run: wait until at most MAX_LEFT (default 4) runs of the batch are still going, stop the +# robot servers of ended runs (keeps memory bounded), then launch the next wave on all three harnesses. +# usage: scripts/full_waves.sh "" "" ... +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_sonnet/lff/source_closure/scripts/replay_la.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/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_sonnet/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/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/__init__.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..83156cde5c65996496e06fed2b8785dee57aa688 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/__init__.py @@ -0,0 +1,21 @@ +"""Model backends. Import lazily: each API backend needs its provider's SDK (see base.import_sdk).""" +from .base import AttemptInfo, Backend, BackendResponse, RunInfo # noqa: F401 + + +def make_backend(kind, **kw): + if kind == "scripted": + from .scripted import ScriptedBackend + return ScriptedBackend(**kw) + if kind == "openai": + from .openai_responses import OpenAIResponsesBackend + return OpenAIResponsesBackend(**kw) + if kind == "chat": + from .chat_completions import ChatCompletionsBackend + return ChatCompletionsBackend(**kw) + if kind == "anthropic": + from .anthropic_messages import AnthropicMessagesBackend + return AnthropicMessagesBackend(**kw) + if kind == "gemini": + from .gemini import GeminiBackend + return GeminiBackend(**kw) + raise ValueError(kind) diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/gemini.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4240f299561c36a664bf40ab8dceaf44715cf8 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/gemini.py @@ -0,0 +1,206 @@ +"""Google Gemini backend (Gemini API, official SDK `google-genai`). + +Same conversation as the other backends, converted to Gemini `contents`: +- system prompt = system_instruction; tools = function declarations with the harness's JSON schemas; +- every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive) + and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call; +- tool outputs of one turn become `function_response` parts at the start of the next user content; images the + harness attaches after them follow in the same user content; +- thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged; +- implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage). + +Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock. +""" +import base64 +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_sdk + + +def _get(obj, key, default=None): + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + +def _strip_additional(schema): + """The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema.""" + if isinstance(schema, dict): + return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"} + if isinstance(schema, list): + return [_strip_additional(v) for v in schema] + return schema + + +def _image_part(image, quality=None): + head, data = image.data_url(quality).split(",", 1) + mime = head[len("data:"):].split(";", 1)[0] + return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data))) + + +class GeminiBackend(Backend): + name = "gemini" + + def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True, + max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90, + timeout=900.0, client=None): + self.model = model + self.thinking_level = thinking_level + self.thinking_budget = thinking_budget + self.include_thoughts = include_thoughts + self.max_output_tokens = max_output_tokens + self.media_resolution = media_resolution + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self._client = client + self._json_schema_field = None + + def config(self): + return dict(name=self.name, model=self.model, thinking_level=self.thinking_level, + thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts, + max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution, + max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout) + + def client(self): + if self._client is None: + genai = import_sdk("google.genai") + self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000))) + return self._client + + def _declarations(self, specs): + if self._json_schema_field is None: + try: + types = import_sdk("google.genai.types") + self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields + except ImportError: # tests without the SDK + self._json_schema_field = True + out = [] + for s in specs: + d = dict(name=s["name"], description=s["description"]) + if self._json_schema_field: + d["parameters_json_schema"] = s["parameters"] + else: + d["parameters"] = _strip_additional(s["parameters"]) + out.append(d) + return [dict(function_declarations=out)] + + # ------------------------------------------------------------------ request + def convert_items(self, items): + contents = [] + + def push(role, parts): + if contents and contents[-1]["role"] == role: + contents[-1]["parts"].extend(parts) + else: + contents.append(dict(role=role, parts=list(parts))) + + for it in items: + kind = it["kind"] + if kind == "user": + parts = [] + for p in it["parts"]: + if p["type"] == "text": + parts.append(dict(text=p["text"])) + else: + parts.append(_image_part(p["image"], self.jpeg_quality)) + push("user", parts) + elif kind == "assistant": + if it.get("raw") is not None and it.get("backend") == self.name: + content = dict(it["raw"][0]) + contents.append(dict(role="model", parts=list(content.get("parts") or []))) + continue + parts = ([dict(text=it["text"])] if it.get("text") else []) + parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]] + push("model", parts or [dict(text="(no output)")]) + elif kind == "tool_output": + fr = dict(name=it["name"], response=dict(output=it["text"])) + if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"): + fr["id"] = it["call_id"] + push("user", [dict(function_response=fr)]) + else: + raise ValueError(kind) + return contents + + def build_request(self, conv, tools): + items = prune_live_images(conv.items, self.max_live_images) + thinking = dict(include_thoughts=self.include_thoughts) + if self.thinking_budget is not None: + thinking["thinking_budget"] = int(self.thinking_budget) + elif self.thinking_level: + thinking["thinking_level"] = self.thinking_level + config = dict(system_instruction=conv.system, tools=self._declarations(tools), + tool_config=dict(function_calling_config=dict(mode="AUTO")), + automatic_function_calling=dict(disable=True), thinking_config=thinking, + max_output_tokens=int(self.max_output_tokens)) + if self.media_resolution: + config["media_resolution"] = self.media_resolution + return dict(model=self.model, contents=self.convert_items(items), config=config) + + @staticmethod + def request_stats(req): + n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "") + for c in req["contents"]: + for p in c["parts"]: + p = p if isinstance(p, dict) else {} + if p.get("inline_data"): + n_img += 1 + img_bytes += len(p["inline_data"]["data"]) + elif p.get("text"): + txt += len(p["text"]) + elif p.get("function_response"): + txt += len(str(p["function_response"].get("response", ""))) + return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"])) + + # ------------------------------------------------------------------ call + def act(self, conv, tools): + req = self.build_request(conv, tools) + stats = self.request_stats(req) + types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys + t0 = time.time() + resp = self.client().models.generate_content( + model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]], + config=types.GenerateContentConfig.model_validate(req["config"])) + out = self.parse_response(resp) + out.latency_s = time.time() - t0 + out.request_stats = stats + return out + + def parse_response(self, resp): + cands = _get(resp, "candidates") or [] + cand = cands[0] if cands else None + content = _get(cand, "content") if cand is not None else None + parts = (_get(content, "parts") or []) if content is not None else [] + calls, texts, summ = [], [], [] + for i, p in enumerate(parts): + fc = _get(p, "function_call") + if fc is not None: + cid = _get(fc, "id") or f"gemini_call_{i}" + calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {}))) + elif _get(p, "text"): + (summ if _get(p, "thought") else texts).append(_get(p, "text")) + u = _get(resp, "usage_metadata") + usage = {} + if u is not None: + usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0, + cached_tokens=_get(u, "cached_content_token_count", 0) or 0, + output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0), + reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0) + finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE" + status, err = "completed", None + if not parts: + status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})" + elif "MAX_TOKENS" in finish or "MALFORMED" in finish: + status, err = "incomplete", f"incomplete: finish_reason={finish}" + elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish: + status, err = "refusal", f"refusal: finish_reason={finish}" + if content is not None and hasattr(content, "model_dump"): + raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes + elif content is not None: + raw = [dict(content)] + else: + raw = None + return BackendResponse(tool_calls=calls, text="\n".join(texts) or None, + reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw, + status=status, error=err) diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/scripted.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/scripted.py new file mode 100644 index 0000000000000000000000000000000000000000..c30b4b503af9c5801b4667276881f16bbbae3e4b --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/scripted.py @@ -0,0 +1,210 @@ +"""Scripted backend: no model. Runs a task's scripted reference policy (adaptive by default) through the +agent tool interface, to test the harness end to end. + +How: the task's own `execute(inst, params)` runs in a worker thread with `task.sk` replaced by a proxy. +Every Skills primitive it calls (move_to / set_gripper / push / grasp_at / place_at) becomes an agent +tool call that is handed to the harness, executed by the ToolExecutor on the main thread, and its +report is returned to the worker. Only one thread runs at a time (queues hand control back and forth), +so MuJoCo is never touched concurrently. Only schema-valid tool calls are emitted, so this also shows +that the tool interface is expressive enough for the task. + +The scripted policy is privileged: it reads the instance (layout) like the task's reference policies +do. It sees earlier attempts only through the memory mode chosen by the harness and only the outcome +fields allowed by the feedback level (F2: structured measurement, F1: success flag, F0: nothing); if +the adaptive rule cannot run on what it sees, it falls back to the task's blind retry rule. +Supported: cross-protocol tasks that implement execute/default_params/adapt_params (+ oracle/blind). +""" +import math +import queue +import threading +import traceback + +import numpy as np + +from ..context import ToolCall +from .base import Backend, BackendResponse + +TIMEOUT_S = 600 + + +class _Abort(Exception): + pass + + +class _Channel: + def __init__(self): + self.req = queue.Queue() + self.res = queue.Queue() + + def call(self, name, args): # worker side + self.req.put(("call", name, args)) + kind, payload = self.res.get(timeout=TIMEOUT_S) + if kind == "abort": + raise _Abort() + return payload + + +class SkillsProxy: + """Stands in for task.sk inside task.execute(); primitives become agent tool calls.""" + + def __init__(self, real, channel): + self._real = real + self._ch = channel + self.untooled_hold_steps = 0 + self.ignored_wrap_yaw_false = 0 + + def move_to(self, target, yaw=None, speed=None, tol=None, max_steps=None, apply_bias=True, wrap_yaw=True): + if not wrap_yaw: # the move_to tool always wraps yaw mod pi (Skills default); counted, not fatal + self.ignored_wrap_yaw_false += 1 + if not apply_bias: + raise NotImplementedError("apply_bias=False cannot be expressed through the agent tools") + yaw_deg = math.degrees(self._real.yaw if yaw is None else float(yaw)) + rep = self._ch.call("move_to", dict(x=float(target[0]), y=float(target[1]), z=float(target[2]), + yaw=round(yaw_deg, 3), speed=None if speed is None else float(speed))) + return dict(prim="move_to", reached=rep.get("reached"), pos=rep.get("eef_pos")) + + def set_gripper(self, close, steps=15): + rep = self._ch.call("close_gripper" if close else "open_gripper", {}) + return dict(prim="close" if close else "open", width=rep.get("gripper_width_m")) + + def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06): + rep = self._ch.call("push", dict(x=float(start_xy[0]), y=float(start_xy[1]), dir_x=float(direction_xy[0]), + dir_y=float(direction_xy[1]), distance=float(distance), speed=float(speed), + z=None if z is None else float(z), runup=float(pre))) + return dict(prim="push", reached=rep.get("sweep_reached"), pos=rep.get("eef_pos")) + + def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15): + self.set_gripper(False, steps=5) + self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw) + self.move_to([xy[0], xy[1], z_grasp]) + self.set_gripper(True) + self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25) + + def place_at(self, xy, z_release, approach=0.10): + self.move_to([xy[0], xy[1], z_release + approach]) + self.move_to([xy[0], xy[1], z_release]) + self.set_gripper(False) + self.move_to([xy[0], xy[1], z_release + approach]) + + def hold(self, steps=10): + # waiting in place has no tool; executed directly (only physics, no new command) and counted + self.untooled_hold_steps += int(steps) + self._real.hold(steps) + + def __getattr__(self, k): # eef_pos, eef_mat, gripper_width, holding, yaw, ... + return getattr(self._real, k) + + +class ScriptedBackend(Backend): + name = "scripted" + + def __init__(self, policy="adaptive", seed=0): + assert policy in ("adaptive", "naive", "oracle", "blind"), policy + self.policy = policy + self.seed = seed + self.info = None + self.rng = None + + def config(self): + return dict(name=self.name, policy=self.policy, seed=self.seed) + + def begin_run(self, info): + if info.protocol != "cross": + raise NotImplementedError("ScriptedBackend supports cross-protocol tasks only (execute/adapt_params)") + self.info = info + self.rng = np.random.default_rng(self.seed + info.seed) + self._oracle = None + if self.policy == "oracle": # privileged scratch rollouts happen before the harness resets the scene + self._oracle = info.task.oracle_params(info.inst) + + # ------------------------------------------------------------------ params from visible history + def _visible(self, rec): + out = rec.outcome + if self.info.feedback == "F2": + vis = dict(out) + elif self.info.feedback == "F1": + vis = dict(success=out.get("success")) + else: + vis = {} + return dict(attempt=rec.attempt, params=rec.backend_meta.get("params"), outcome=vis) + + def _params(self, attempt, history): + task, inst = self.info.task, self.info.inst + if self.policy == "oracle": + return dict(self._oracle), "oracle" + if self.policy == "naive" or not history and self.policy == "adaptive": + return task.default_params(inst), "default" + if self.policy == "blind": + if attempt == 1: + return task.default_params(inst), "default" + return task.blind_params(inst, attempt - 1, self.rng), "blind" + hist = [self._visible(r) for r in history if r.backend_meta.get("params") is not None] + if not hist: + return task.blind_params(inst, attempt - 1, self.rng), "blind(no usable history)" + try: + return task.adapt_params(inst, hist), "adapt" + except (KeyError, TypeError, ValueError): + return task.blind_params(inst, attempt - 1, self.rng), "blind(feedback too coarse)" + + # ------------------------------------------------------------------ attempt + def begin_attempt(self, ainfo): + self.params, self.rule = self._params(ainfo.attempt, ainfo.history) + self.ch = _Channel() + self.thread = None + self.pending = False + self.last_report = None + self.n = 0 + self.proxy = None + + def _worker(self): + try: + self.info.task.execute(self.info.inst, self.params) + self.ch.req.put(("finished", None)) + except _Abort: + pass + except Exception: + self.ch.req.put(("error", traceback.format_exc())) + + def act(self, conv, tools): + if self.thread is None: + task = self.info.task + self.real_sk = task.sk + self.proxy = SkillsProxy(task.sk, self.ch) + task.sk = self.proxy + self.thread = threading.Thread(target=self._worker, daemon=True) + self.thread.start() + elif self.pending: + self.ch.res.put(("result", self.last_report or {})) + self.pending = False + kind, *rest = self.ch.req.get(timeout=TIMEOUT_S) + self.n += 1 + if kind == "call": + name, args = rest[0], rest[1] + self.pending = True + tc = ToolCall(id=f"scripted_{self.n}", name=name, arguments=args) + text = None + if self.n == 1: + text = f"[scripted {self.policy}: rule={self.rule}, params={self.params}]" + return BackendResponse(tool_calls=[tc], text=text) + if kind == "finished": + return BackendResponse(tool_calls=[ToolCall(id=f"scripted_{self.n}", name="done", + arguments=dict(reason=f"scripted {self.policy} policy finished " + f"with params {self.params}"))]) + raise RuntimeError("scripted policy crashed:\n" + str(rest[0])) + + def on_tool_result(self, call, result): + self.last_report = result.report + + def end_attempt(self): + if self.thread is not None: + if self.thread.is_alive(): + if self.pending: + self.ch.res.put(("abort", None)) + self.thread.join(timeout=30) + self.info.task.sk = self.real_sk + meta = dict(policy=self.policy, rule=self.rule, params=self.params) + if self.proxy is not None and self.proxy.untooled_hold_steps: + meta["untooled_hold_steps"] = self.proxy.untooled_hold_steps + if self.proxy is not None and self.proxy.ignored_wrap_yaw_false: + meta["ignored_wrap_yaw_false"] = self.proxy.ignored_wrap_yaw_false + return meta diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/harness.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/harness.py new file mode 100644 index 0000000000000000000000000000000000000000..323410f477f3320769635cf01dd368be716d9421 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/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/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l4_fit_container.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l4_fit_container.py new file mode 100644 index 0000000000000000000000000000000000000000..afd614b881f930060a9ccb43ebb86d141b9f405b --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l4_fit_container.py @@ -0,0 +1,43 @@ +"""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.") diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py new file mode 100644 index 0000000000000000000000000000000000000000..60abbc57bc9e902476e1cd8d8e5e5a3e619ec5b7 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py @@ -0,0 +1,28 @@ +"""Controlled arms for l7_offcenter_push (docs/14 §6). + +Hidden variable: com_offset = e, the shift of the box's centre of mass along its long axis (world +y = robot's left; +|e| in [4.5, 7.5] cm). apply_instance() writes it into body_ipos on every reset; oracle_params() pushes at c = e. + + h0 e = 0: centre of mass in the middle, so the natural push at the middle of the back face goes straight. + twin e -> -e: same distance from the middle, other end heavy. The naive push turns the box just as much but the + other way (clockwise <-> counterclockwise, the other end lags), and the right contact point is on the other + side of the middle, so the original's lesson ("move the contact toward the left/right end") is reversed. + reveal states |e| and its side in the robot-frame words of the F2 feedback (robot's left / right). +""" + +HIDDEN_KEYS = ("com_offset",) + + +def h0(inst): + return {"com_offset": 0.0} + + +def twin(inst): + return {"com_offset": -float(inst["com_offset"])} + + +def reveal(inst): + e = float(inst["com_offset"]) + side = "left" if e > 0 else "right" + return (f"The box's centre of mass is not at its middle: it is about {100 * abs(e):.1f} cm from the middle along " + f"the box's long side, toward the robot's {side}.") diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..7201f54a4d0ba3fb8e1844420311ced219827fa6 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py @@ -0,0 +1,23 @@ +"""Layer-4 intervention texts for lh_clear_cover (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is +not in the controlled arms of full5. + +Hidden variable: inst["cover"] -- which box carries the nearly invisible clear lid (None in uncovered instances). +reveal says which box is covered and what the lid does to a released cube; not how to deal with it. +fix the oracle's edge push (lh_clear_cover.remove_cover) in move_eef words; params["z_push"] = grasp-point height of + that push in the eef_pos frame, params["push_len"] = length of the sweep (scripts/layer4_plan.py validate). +""" +HIDDEN_KEYS = ("cover",) + + +def reveal(inst): + return (f"The {inst['cover']} box is covered by a loose, nearly invisible clear lid lying on its walls, 8 mm thick. " + f"A cube released over that box stops on the lid at rim height; it is not in the box.") + + +def fix(inst, params): + return (f"A way to succeed: first push the lid off the {inst['cover']} box. Close the gripper, keep yaw 0 and bring " + f"the grasp point to height {params['z_push']:.3f} (the third value of eef_pos), so that the fingertips are " + f"level with the lid's edge, 3 cm outside the edge of the lid that faces the other box. Then in one move_eef " + f"command sweep {params['push_len'] * 100:.0f} cm straight along the line between the two boxes, away from " + f"the other box, at speed 0.06, and lift. The lid is then off. Put each cube into the box of its colour, and " + f"check from the side view that no cube rests at rim height.") diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/contract.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/contract.py new file mode 100644 index 0000000000000000000000000000000000000000..5efe5079fdb7ef9581c6772a9954c3f64b8eda49 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/contract.py @@ -0,0 +1,160 @@ +"""Information contract of one run (docs/15 §1 layer 2) and its hash `contract_sha256`. + +The contract is everything the agent is given that must be identical across harnesses and models for the same +instance and condition: the README text, the three tool schemas, the image spec, the feedback level, --hide-k, the +budgets, the memory condition, the task and seed, and the code that builds the scene and judges it. Two runs whose +`contract_sha256` differ must not share a table cell. + +What is NOT in the contract on purpose: the harness (it is the thing being compared), the model, the port, the +sandbox / log paths, timestamps. + + contract = build_contract(log_dir) # reads session.json, agent_iface.json, events.jsonl, README.md + contract_sha256(contract) # sha256 of the canonical JSON + write_contract(log_dir) # -> /contract.json, returns (contract, sha) +""" +import glob +import hashlib +import json +import os +import re +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # the lffbench repo +CONTRACT_VERSION = 1 +IMAGE_SPEC = dict(cameras=["agentview", "wrist"], width=512, height=512, format="JPEG", jpeg_quality=90, + delivery="files in the workspace, viewed with view_images (bytes unchanged)") +# code that builds the scene, runs the robot and judges the result (task modules are added per task) +SERVER_CODE = ["lffbench/agent/robot_server.py", "lffbench/agent/tools.py", "lffbench/agent/camera.py", + "lffbench/agent/context.py", "lffbench/agent/images.py", "lffbench/envs.py", "lffbench/skills.py", + "lffbench/task_base.py", "lffbench/bddl.py", "lffbench/objects.py"] +# real-robot backend (added for real_* tasks only; the driver itself is recorded as contract["real_driver"]) +REAL_CODE = ["lffbench/real/tasks.py", "lffbench/real/session.py", "lffbench/real/executor.py", "lffbench/real/protocol.py"] + + +def sha256_bytes(b): + return hashlib.sha256(b).hexdigest() + + +def sha256_text(s): + return sha256_bytes(s.encode("utf-8")) + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def canonical(obj): + return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + + +def sha256_json(obj): + return sha256_text(canonical(obj)) + + +def tool_schemas(): + """The three LA tools exactly as the reference driver and the MCP server define them.""" + sys.path.insert(0, os.path.join(ROOT, "scripts")) + from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, PREAMBLE_LA # noqa: E402 + return [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA], PREAMBLE_LA + + +def task_module_files(task): + """Source files of the task class `task` (found by its `name = ""` line; .bak files are ignored).""" + pat = re.compile(r"""^\s*name\s*=\s*["']%s["']""" % re.escape(task), re.M) + hits = [] + for p in sorted(glob.glob(os.path.join(ROOT, "lffbench", "tasks", "*.py"))): + try: + if pat.search(open(p, encoding="utf-8").read()): + hits.append(os.path.relpath(p, ROOT)) + except OSError: + pass + arm = os.path.join(ROOT, "lffbench", "arm_specs", f"{task}.py") + if os.path.exists(arm): + hits.append(os.path.relpath(arm, ROOT)) + real = os.path.join(ROOT, "lffbench", "real", "tasks.py") # real-robot tasks (docs/17): add the real backend's code + if not hits and os.path.exists(real) and pat.search(open(real, encoding="utf-8").read()): + hits += REAL_CODE + return hits + + +def server_code_sha(task): + files = SERVER_CODE + task_module_files(task) + per = {f: (sha256_file(os.path.join(ROOT, f)) if os.path.exists(os.path.join(ROOT, f)) else None) for f in files} + return sha256_json(per), per + + +def session_start(log_dir): + with open(os.path.join(log_dir, "events.jsonl")) as f: + for line in f: + d = json.loads(line) + if d.get("ev") == "session_start": + return d + raise RuntimeError(f"no session_start event in {log_dir}/events.jsonl") + + +def readme_budget(readme): + """The per-attempt budgets as the README states them (what the agent is told).""" + out = {} + for key, pat in (("robot_commands", r"at most (\d+) robot commands"), + ("sim_seconds", r"at most ([\d.]+) s of (?:simulated )?robot motion"), # real robot: "s of robot motion" + ("tool_calls", r"at most (\d+) tool calls")): + m = re.search(pat, readme) + out[key] = float(m.group(1)) if m and "." in m.group(1) else (int(m.group(1)) if m else None) + return out + + +def build_contract(log_dir): + log_dir = os.path.abspath(log_dir) + sess = json.load(open(os.path.join(log_dir, "session.json"))) + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + st = session_start(log_dir) + readme = open(os.path.join(sess["sandbox"], "README.md"), encoding="utf-8").read() + tools, preamble = tool_schemas() + code_sha, code_files = server_code_sha(st["task"]) + out = dict( + contract_version=CONTRACT_VERSION, + task=st["task"], seed=st["seed"], + readme_sha256=sha256_text(readme), + preamble_sha256=sha256_text(preamble), + tools=tools, + image_spec=dict(IMAGE_SPEC, perception=st.get("perception", iface.get("perception"))), + feedback=st.get("feedback"), instruction=st.get("instruction"), + memory=st.get("memory"), k=st.get("k"), k_shown=st.get("k_shown"), hide_k=st.get("k_shown") != st.get("k"), + protocol=st.get("protocol"), arm=st.get("arm"), dossier_sha256=sha256_text(st.get("dossier") or ""), + budget=dict(readme_budget(readme), max_tool_calls=iface.get("max_tool_calls"), + tool_call_budget_enforced_by="mcp_robot_server / api_player (per attempt)"), + agent_iface=iface.get("agent_iface"), + server_code_sha256=code_sha, server_code_files=code_files, + ) + if st.get("backend") == "real": # only real-robot runs get this key, so simulated contracts are unchanged + di = st.get("driver_info") or {} + out["real_driver"] = {k: di.get(k) for k in ("protocol", "robot", "n_joints", "workspace", "yaw_range_deg", + "max_speed", "ik", "driver_version")} + out["real_agent_workspace"] = st.get("agent_workspace") + from .redteam import marker # adversarial acceptance runs only (harness_run --red-team): others are unchanged + rt = marker(log_dir) + if rt: + out["red_team"] = rt + return out + + +def contract_sha256(contract): + return sha256_json(contract) + + +def write_contract(log_dir): + c = build_contract(log_dir) + sha = contract_sha256(c) + with open(os.path.join(log_dir, "contract.json"), "w") as f: + json.dump(dict(contract_sha256=sha, contract=c), f, indent=1, ensure_ascii=False) + return c, sha + + +if __name__ == "__main__": + for d in sys.argv[1:]: + c, sha = write_contract(d) + print(sha, d) diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/reference.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..93a7ecef47a9e0f879e60d8521618b4378658db2 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/reference.py @@ -0,0 +1,143 @@ +"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness). + +Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its +own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only +adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness. +""" +import json +import os +import sys + +from . import contract as C +from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions +from .trajectory import TrajWriter + +ROOT = C.ROOT +PLAYER = os.path.join(ROOT, "scripts", "api_player.py") +DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py", + "lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py", + "lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"] + + +class Reference(HarnessAdapter): + name = "ours" + capabilities = dict( + only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"), + images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"), + non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"), + pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"), + machine_readable_events=Cap("yes", "stream", "transcript.jsonl"), + tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"), + model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"), + persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"), + instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"), + web_access=Cap("absent", "launch", "no such tool"), + host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"), + builtin_shell=Cap("absent", "launch", "only the jailed shell tool"), + subagent_delegation=Cap("absent", "launch", "no such tool"), + background_execution=Cap("absent", "launch", "no such tool"), + ) + + def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_): + self.provider = provider + self.base_env = dict(env if env is not None else os.environ) + self.timeout_s = timeout_s + self.python = python or sys.executable + + def version(self): + per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))} + sha = C.sha256_json(per) + return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get( + "scripts/api_player.py"))) + + def prepare(self, ep, first_message=None): + argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider, + "--model", ep.model, "--effort", ep.effort, "--style", "la"] + return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="", + stdout_path=os.path.join(ep.log_dir, "api_player.log"), + stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + return C.sha256_json(dict(argv=[a.replace(ep.session_path, "") for a in spec.argv[1:]])) + + def launch(self, spec, ep, skip_preflight=True): + # stdout and stderr go to the same api_player.log (as before the adapter layer) + import subprocess + import time + from .base import RunHandle, env_keys_of + spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code") + log = open(spec.stdout_path, "ab") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) + h.pid = h.proc.pid + time.sleep(0.2) + h.env_observed_keys = env_keys_of(h.pid) + return h + + def collect(self, h): + ep = h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + p = os.path.join(ep.log_dir, "transcript.jsonl") + start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0) + last_agent = None + for line in (open(p) if os.path.exists(p) else []): + d = json.loads(line) + e = d.get("ev") + if e == "start": + start = d + elif e == "user": + if first_user is None: + first_user = d.get("text") + tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t")) + elif e == "assistant": + u = d.get("usage") or {} + tot["inp"] += u.get("input_tokens", 0) + tot["out"] += u.get("output_tokens", 0) + tot["cached"] += u.get("cached_tokens", 0) + last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "", + timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"], + function_name=c["name"], + native_name=c["name"], + arguments=c["arguments"]) + for c in d.get("tool_calls") or []], + metrics=dict(prompt_tokens=u.get("input_tokens"), + completion_tokens=u.get("output_tokens"), + cached_tokens=u.get("cached_tokens"))) + elif e == "tool" and last_agent is not None: + pending = [tc for tc in last_agent["tool_calls"] + if not any(r["source_call_id"] == tc["tool_call_id"] + for r in last_agent["observation"]["results"])] + if pending: + tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or [])) + elif e in ("end", "abort"): + end = d + tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl", + agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model, + effort=ep.effort, provider=ep.provider or self.provider), + tools=[t["name"] for t in (start or {}).get("tools") or []]) + tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")), + native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"], + total_cached_tokens=tot["cached"]) + tw.write() + h.info.update(traj=tw, start=start, first_user=first_user) + if start and first_user is not None: # the same string a native harness gets as its first message + readme = open(os.path.join(ep.sandbox, "README.md")).read() + h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme) + # the same composition as base.first_message_text: identical sha256 for the same instance + h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user + return tw + + def audit(self, h): + ep = h.ep + start = h.info.get("start") or {} + tools, _ = C.tool_schemas() + v = [] + if start and start.get("tools") != tools: + v.append("driver tools differ from the contract's tool schemas") + if h.info.get("instructions_match_readme") is False: + v.append("driver instructions != preamble + README") + out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"]) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/trace_html.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/trace_html.py new file mode 100644 index 0000000000000000000000000000000000000000..651afc43f8b160358a4388c58659fa478c4b71f0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/scripts/trace_html.py @@ -0,0 +1,148 @@ +"""Render one player-subagent run as a self-contained HTML trace: everything the agent received, +every command it ran, every result and image it saw, its own text, plus the server-side ground truth. + +python scripts/trace_html.py --batch exp1 --sandbox --out traces/.html +""" +import argparse +import base64 +import html +import json +import os +from datetime import datetime + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (.output files) + +CSS = """ +:root{--bg:#fafaf9;--fg:#1c1917;--mut:#57534e;--card:#fff;--bd:#e7e5e4;--acc:#2563eb;--tool:#f5f5f4;--ok:#15803d;--bad:#b91c1c;--th:#7c3aed} +@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#1c1917;--fg:#e7e5e4;--mut:#a8a29e;--card:#292524;--bd:#44403c;--acc:#60a5fa;--tool:#231f1d;--ok:#4ade80;--bad:#f87171;--th:#c4b5fd}} +body{background:var(--bg);color:var(--fg);font:14px/1.55 system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;margin:0;padding:16px;max-width:1100px;margin:auto} +h1{font-size:20px}h2{font-size:17px;margin-top:28px;border-bottom:1px solid var(--bd);padding-bottom:4px} +.card{background:var(--card);border:1px solid var(--bd);border-radius:8px;padding:10px 12px;margin:8px 0} +pre{white-space:pre-wrap;word-break:break-word;background:var(--tool);border:1px solid var(--bd);border-radius:6px;padding:8px;font:12px/1.45 ui-monospace,Menlo,monospace;margin:4px 0;max-height:420px;overflow:auto} +.lbl{font-size:12px;color:var(--mut);font-weight:600;text-transform:uppercase;letter-spacing:.03em} +.cmd{color:var(--acc)}.think{color:var(--th)}.ok{color:var(--ok);font-weight:600}.bad{color:var(--bad);font-weight:600} +img{max-width:256px;border-radius:4px;border:1px solid var(--bd);margin:2px} +details>summary{cursor:pointer;color:var(--mut)} +table{border-collapse:collapse}td,th{border:1px solid var(--bd);padding:3px 8px;text-align:left;font-size:13px} +.step{display:flex;gap:8px}.n{color:var(--mut);min-width:34px;font-variant-numeric:tabular-nums} +""" + + +def esc(s): + return html.escape(str(s)) + + +def ts(x): + return datetime.fromisoformat(x.replace("Z", "+00:00")).timestamp() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", default="exp1") + ap.add_argument("--sandbox", required=True, help="sandbox hex id") + ap.add_argument("--out", required=True) + ap.add_argument("--title", default="") + a = ap.parse_args() + m = json.load(open(os.path.join(ROOT, "runs", "claude", a.batch, "manifest.json"))) + run = next(r for r in m["runs"] if r["sandbox"].endswith(a.sandbox)) + tr = [json.loads(l) for l in open(os.path.join(TRANSCRIPTS, f"{run['agent']}.output"))] + ev = [json.loads(l) for l in open(os.path.join(run["log"], "events.jsonl"))] + start = next(e for e in ev if e["ev"] == "session_start") + dones = [e for e in ev if e["ev"] == "done"] + http = [e for e in ev if e["ev"] == "http"] + think = [h["think_s"] for h in http if h.get("think_s")] + srv = [h["server_s"] for h in http] + + out = [f"{esc(a.title or 'Agent trace')}"] + out.append(f"

{esc(a.title or run['run'])}

") + out.append("
") + rows = [("任务", run["task"]), ("种子", run["seed"]), ("模型", run["model"]), ("条件", run["cond"] + f"(k={run['k']})"), + ("沙箱", run["sandbox"]), ("服务端 run 名", run["run"]), + ("结果", ";".join(f"第{d['attempt']}次 {'成功' if d['success'] else '失败'}" for d in dones)), + ("命令数 / 模型思考总时长 / 仿真执行总时长", f"{sum(1 for e in ev if e['ev']=='call')} / {sum(think):.0f} s / {sum(srv):.0f} s"), + ("子代理墙钟", f"{(ts(tr[-1]['timestamp']) - ts(tr[0]['timestamp'])) / 60:.1f} min")] + for k, v in rows: + out.append(f"") + out.append("
{esc(k)}{esc(v)}
") + inst = {k: v for k, v in start["inst"].items()} + out.append("
服务端真值(agent 从未看到)
" + esc(json.dumps(inst, indent=1, ensure_ascii=False)[:3000]) + "
") + + # ---------------------------------------------------------------- what the agent received + out.append("

1. agent 收到的上下文

") + out.append("
Claude Code 内置的系统提示和工具定义不在对话记录里(由 Claude Code 注入,这里看不到原文)。下面是记录里能看到的全部注入内容和我的提示。
") + for d in tr: + if d["type"] != "attachment": + continue + at = d["attachment"] + t = at.get("type") + if t == "instructions": + for f in at.get("files", []): + out.append(f"
注入附件:{esc(f.get('type'))} — {esc(f.get('path'))}({len(f.get('content',''))} 字符)
{esc(f.get('content',''))}
") + elif t in ("environment", "model", "date", "session_context", "skill_listing", "deferred_tools_delta", "credential_org"): + body = json.dumps({k: v for k, v in at.items() if k != "type"}, ensure_ascii=False, indent=1) + out.append(f"
注入附件:{esc(t)}({len(body)} 字符)
{esc(body[:6000])}
") + first_user = next(d for d in tr if d["type"] == "user") + out.append("
我给 agent 的提示(原文)
" + esc(first_user["message"]["content"]) + "
") + + # ---------------------------------------------------------------- timeline + out.append("

2. 逐步过程(agent 的文字、执行的命令、收到的结果和图像)

") + n = 0 + results = {} + for d in tr: + if d["type"] == "user" and isinstance(d["message"].get("content"), list): + for c in d["message"]["content"]: + if c.get("type") == "tool_result": + results[c["tool_use_id"]] = c + t0 = ts(tr[0]["timestamp"]) + for d in tr: + if d["type"] != "assistant": + continue + for c in d["message"].get("content", []): + ct = c.get("type") + tt = f"+{ts(d['timestamp']) - t0:6.0f}s" + if ct == "thinking" and c.get("thinking"): + out.append(f"
{tt} 思考
{esc(c['thinking'])}
") + elif ct == "text" and c.get("text", "").strip(): + out.append(f"
{tt} agent 文字
{esc(c['text'])}
") + elif ct == "tool_use": + n += 1 + inp = c.get("input", {}) + if c["name"] == "Bash": + head = f"Bash: {esc(inp.get('command',''))}" + elif c["name"] == "Read": + head = f"Read: {esc(inp.get('file_path',''))}" + elif c["name"] == "SubagentHandback": + head = "最终报告(SubagentHandback)" + else: + head = f"{esc(c['name'])}: {esc(json.dumps(inp, ensure_ascii=False)[:300])}" + block = [f"
{tt} #{n} 工具调用 {head}"] + if c["name"] == "SubagentHandback": + block.append(f"
{esc(inp.get('message',''))}
") + r = results.get(c["id"]) + if r is not None: + rc = r.get("content") + if isinstance(rc, str): + rc = [{"type": "text", "text": rc}] + for part in rc or []: + if part.get("type") == "text": + txt = part["text"] + block.append(f"
返回({len(txt)} 字符)
{esc(txt)}
") + elif part.get("type") == "image": + src = part.get("source", {}) + if src.get("type") == "base64": + block.append(f"") + block.append("
") + out.extend(block) + out.append("

3. 服务端每次 done 的判定

") + for e in dones: + out.append(f"
第 {e['attempt']} 次:{'成功' if e['success'] else '失败'}
{esc(e.get('feedback',''))}
") + out.append("") + os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) + with open(a.out, "w") as f: + f.write("\n".join(out)) + print(a.out, os.path.getsize(a.out), "bytes; tool calls", n) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l4_fit.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l4_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..7465485d3e907ad579bc46be98782eb8c5efad3a --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l4_fit.py @@ -0,0 +1,574 @@ +"""L4-A fit_container: put the phone flat inside the one box it fits into. + +v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and +phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time. +v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is +rendered), CAP_RANGE = 0.8-0.9 cm each, so it is 1.6-1.8 cm longer than the visible phone. The box sizes are drawn +against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone: + fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight), + snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps, + short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps, + narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow, + small 0.5..1.0 cm too short. +A phone that does not fit lies on the rim of the box (or tips in at one end), visibly not inside, although in the +images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it +appears to (by about the overlap seen) -> the box with the most length to spare. + +The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as +the capped length. v2 is kept in l4_fit.py.bak-20261008-height. + +v2 description: + +Scene: a dark "phone" (14.0 x 6.8 x 1.2 cm) lies in the front row of a 2 x 3 grid of slots; five open +boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES): + fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side), + short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest), + narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest), + small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions), + short 0.8-2.0 cm too short, as wide as the fitting box. +Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it +(+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be +turned by ~90 deg. + +Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the +fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in +sim.model, so a single env serves every instance. + +Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed +2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first +failures were plain misalignment instead of a size mismatch). F2 feedback after a failed attempt reports where the phone ended up and by how much it is too +long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger +in that dimension and turn the phone. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +# phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it +PL, PW, PT = 0.140, 0.068, 0.012 +CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden) +# boxes (local x = long axis of the opening) +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035 +BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +N_BOXES = 5 +ROWS_X = (-0.30, -0.08) # back row (near the robot), front row +COLS_Y = (-0.22, 0.0, 0.22) +DROP = 0.012 # phone bottom this far above the rim when released +Z_CARRY = envs.TABLE_Z + 0.15 +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way +PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates +JITTER_DEG = 15.0 +# inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side). +# The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has +# the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio. +# Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box. +# v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap) +BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small") +INNER_RANGES = { + "fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest) + "snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable + "short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box + "narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow + "small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short +} +VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps) +BOX_RGBA = (0.70, 0.60, 0.46, 1.0) + + +def phone_xml(model_name): + hx, hy, hz = PL / 2, PW / 2, PT / 2 + body = (0.13, 0.13, 0.15, 1.0) + screen = (0.02, 0.025, 0.04, 1.0) + g = (f' \n' + f' \n' + f' ') + # v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered). + # Resized per instance in apply_instance (inst["cap"]). + c = CAP_RANGE[1] + for k, sx in enumerate((1, -1)): + g += (f'\n ') + return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy))) + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def wrap_quarter(a): + """angle modulo pi/2 into [-pi/4, pi/4)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +def fits_some_yaw(a, b, clearance=0.002, length=PL): + """Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in + total)?""" + th = np.linspace(0.0, np.pi / 2, 181) + e1 = length * np.cos(th) + PW * np.sin(th) + e2 = length * np.sin(th) + PW * np.cos(th) + return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance))) + + +def _rect_corners(xy, yaw, half): + c, s = np.cos(yaw), np.sin(yaw) + R = np.array([[c, -s], [s, c]]) + pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half) + return pts @ R.T + np.asarray(xy) + + +def _rects_overlap(r1, r2): + """separating-axis test for two rotated rectangles given as (xy, yaw, half)""" + c1, c2 = _rect_corners(*r1), _rect_corners(*r2) + for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2): + ax = np.array([np.cos(yaw), np.sin(yaw)]) + p1, p2 = c1 @ ax, c2 @ ax + if p1.max() < p2.min() or p2.max() < p1.min(): + return False + return True + + +@register_task +class FitContainer(LFFTask): + name = "l4_fit_container" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason") + instruction = "Put the phone flat inside a box that it fits into completely." + instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely." + + # ------------------------------------------------------------ scene + def make_bddl(self): + phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone")) + # one category per box (BDDL lists one object per line; same-category lines would overwrite each + # other). All share the same MJCF; the opening is resized per instance in apply_instance. + cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H, + wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA, + density=3000)) + for c in "ABCDE"] + objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))] + slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)] + for i, (x, y) in enumerate(slots): + objs.append((f"box_{i + 1}", cats[i], f"box{i + 1}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + j = np.radians(JITTER_DEG) + for _ in range(500): + col = int(rng.integers(3)) + phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)] + phone_yaw = float(rng.uniform(-j, j)) + slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])] + kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)] + cap = float(rng.uniform(*CAP_RANGE)) + boxes = [] + for i, (kind, (x, y)) in enumerate(zip(kinds, slots)): + lo, hi = INNER_RANGES[kind] + a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1]) + assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap) + assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b) + crossed = bool(rng.random() < 0.5) + yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j)) + boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed, + xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))], + yaw=yaw, inner=[float(a), float(b)])) + rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007)) + for b in boxes] + rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01))) + if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)): + break + else: + raise RuntimeError("could not sample a non-overlapping layout") + prng = np.random.default_rng(seed + 7919) + perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))] + for b in boxes] + return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes, + fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc) + + def _reshape_box(self, name, a, b): + ix, iy, H = a / 2, b / 2, BOX_HALF_H + parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)), + ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)), + ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))] + m = self.env.sim.model + o = self.env.objects_dict[name] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), names + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def _set_caps(self, cap): + """resize the two hidden bumper caps to `cap` (m) per end""" + m = self.env.sim.model + if not hasattr(self, "_cap_ids"): + self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1") + if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]] + assert len(self._cap_ids) == 2, self._cap_ids + for g in self._cap_ids: + sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0 + size = (cap / 2, PW / 2 - 0.001, PT / 2) + m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0) + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def apply_instance(self, inst): + # walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision + # mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07). + # Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below. + import mujoco + self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + self._set_caps(inst["cap"]) + for b in inst["boxes"]: + self._reshape_box(b["name"], *b["inner"]) + envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"]) + envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005], + yaw=inst["phone_yaw"]) + + # ------------------------------------------------------------ outcome + def _pose2d(self, name): + bid = envs.body_id(self.env, name) + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + p = self.env.sim.data.body_xpos[bid].copy() + return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + + def outcome(self, inst): + envs.settle(self.env, 40) + p, yaw, tilt = self._pose2d("phone_1") + held = bool(self.sk is not None and self.sk.holding("phone_1")) + # which box is the phone in / on: smallest distance of the phone centre outside a box opening + best = None + for j, b in enumerate(inst["boxes"]): + c, byaw, btilt = self._pose2d(b["name"]) + d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2]) + out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0) + dist = float(np.linalg.norm(out)) + if best is None or dist < best[0]: + best = (dist, j, c, byaw, btilt) + dist, j, c, byaw, btilt = best + b = inst["boxes"][j] + a_in, b_in = b["inner"] + floor_top = c[2] - BOX_HALF_H + FLOOR_T + height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor + in_opening = dist < 1e-9 + on_floor = height < 0.004 and tilt < 5.0 + success = bool(in_opening and on_floor and not held and btilt < 10.0) + where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback + # footprint of the phone (as it lies now) against the opening of that box + dl = yaw - byaw + cs, sn = abs(np.cos(dl)), abs(np.sin(dl)) + L = PL + 2 * inst.get("cap", 0.0) # the capped phone + over_long = L * cs + PW * sn - a_in + over_short = L * sn + PW * cs - b_in + along_long = "length" if cs >= sn else "width" + fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long, + over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None, + over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None) + res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2), + tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb) + if held: + res["detail"] = "The phone is still in the gripper." + res["failure"] = "held" + return res + if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006): + res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm " + f"outside the opening of {where}.") + res["failure"] = "table" + return res + if success: + res["detail"] = f"The phone is lying flat on the bottom of {where}." + res["failure"] = None + return res + pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else + f"tilted about {tilt:.0f} degrees with one end down inside the box") + txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}." + dim_l = "long" if along_long == "length" else "wide" + dim_s = "wide" if along_long == "length" else "long" + if fb["over_long_cm"]: + txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side." + if fb["over_short_cm"]: + txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side." + if not fb["over_long_cm"] and not fb["over_short_cm"]: + txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim." + res["detail"] = txt + res["failure"] = "rim" + return res + + @staticmethod + def box_label(inst, j): + """Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left).""" + ys = [b["xy"][1] for b in inst["boxes"]] + xs = [b["xy"][0] for b in inst["boxes"]] + n = len(ys) + order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first + r = order.index(j) + close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04] + if close: # boxes side by side in y: tell them apart by distance from the robot + nearer = all(xs[j] < xs[i] for i in close) + return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position" + if r == 0: + return "the box furthest to the robot's left (+y)" + if r == n - 1: + return "the box furthest to the robot's right (-y)" + return "the middle box (between the others, left to right)" + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released). + Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre + along the box's long / short axis (m), drop = height of the phone bottom above the rim (m).""" + sk, env = self.sk, self.env + px, py = inst["phone_xy"] + zc = envs.TABLE_Z + PT / 2 + g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width + sk.set_gripper(False, steps=5) + sk.move_to([px, py, zc + 0.10], yaw=g0) + sk.move_to([px, py, zc + 0.001], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([px, py, Z_CARRY], speed=0.25) + b = inst["boxes"][int(params["box"])] + c, s = np.cos(b["yaw"]), np.sin(b["yaw"]) + dx, dy = params.get("dx", 0.0), params.get("dy", 0.0) + bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy + sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"])) + # put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip + off = envs.obj_pos(env, "phone_1") - sk.eef_pos() + drop = params.get("drop", DROP) + sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003) + tgt = self._servo_phone([bx, by], RIM_Z + drop) + sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts) + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10]) + sk.move_to(list(PARK), yaw=0.0) + + 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_phone(self, xy, z_bottom, max_steps=60, tol=0.0015): + """Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom. + Returns the final gripper target.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom + PT / 2]) + tgt = e_prev = sk.eef_pos() + for i in range(max_steps): + ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos() + if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + tgt = goal - (ph - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def _naive_yaw(self, inst, j): + """keep the phone's orientation, only snap it to the nearest axis of box j""" + p = inst["phone_yaw"] + return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p)) + + def default_params(self, inst): + """v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the + trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its + tighter direction, i.e. "snug" by construction; phone's long side along the box's long side""" + marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]] + j = int(np.argmax(marg)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def nearest_params(self, inst): + """v2 prior (kept for reference): nearest box, lined up""" + d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]] + j = int(np.argmin(d)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def oracle_params(self, inst): + j = inst["fit"] + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def blind_params(self, inst, attempt, rng): + """no history: a random box (may repeat), lined up like the prior""" + j = int(rng.integers(N_BOXES)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def naive_keep_yaw_params(self, inst): + """old prior (kept for reference): nearest box, keep the phone's orientation""" + d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]] + j = int(np.argmin(d)) + return dict(box=j, place_yaw=self._naive_yaw(inst, j)) + + def adapt_params(self, inst, history): + """Scripted learner on F2 feedback. + + Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the + phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an + estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box + that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and + lines the phone's long side up with the box's long side. + """ + perc = inst["_perc"] + L_est = W_est = None + tried_aligned = set() + for h in history: + o = h["outcome"] + fb = o.get("feedback") or {} + if o.get("failure") != "rim": + continue + j = fb["box"] + a, b = perc[j] + if fb["along_long"] == "length": + if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box + tried_aligned.add(j) + if fb["over_long_cm"]: + L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100) + if fb["over_short_cm"]: + W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100) + else: + if fb["over_short_cm"]: + L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100) + if fb["over_long_cm"]: + W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100) + thr = 0.002 + cands = [] + for j, (a, b) in enumerate(perc): + if j in tried_aligned: + continue + mL = None if L_est is None else a - L_est + mW = None if W_est is None else b - W_est + feasible = (mL is None or mL > thr) and (mW is None or mW > thr) + if mL is not None and mW is not None: + key = min(mL, mW) + elif mL is not None: + key = b + elif mW is not None: + key = a + else: + key = a * b + cands.append((feasible, key, j)) + if not cands: + j = int(np.argmax([a * b for a, b in perc])) + else: + j = max(cands)[2] + return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"])) + + def elim_params(self, inst, history, rng): + """sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up + after the first attempt) and to never retry a box that got a size verdict; picks among the remaining + boxes at random, i.e. no size reasoning / perception.""" + bad = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and ( + fb.get("over_long_cm") or fb.get("over_short_cm")): + bad.add(int(fb["box"])) + left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES)) + j = int(rng.choice(left)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + EXTRA_KINDS = ("elim",) + + 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) + if a == 0: + params = self.default_params(inst) + else: + params = self.elim_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 + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=20, out=None): + """Every (box, orientation) pair on each instance, released centred from DROP above the rim. + Expect success iff the box is the fitting one and the phone's long side is along the box's long side.""" + import json + task = FitContainer() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for j, b in enumerate(inst["boxes"]): + for orient in ("aligned", "crossed"): + task.reset_instance(inst) + task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2)))) + o = task.outcome(inst) + rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]], + orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"), + failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"])) + r = rows[-1] + print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} " + f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["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 stress_check(seed=1002, out=None): + """Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box + (+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow.""" + import copy + import json + task = FitContainer() + base = task.sample_instance(seed) + j = base["fit"] + rows = [] + for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010), + ("narrow_0.5", PL + 0.010, PW - 0.005)]: + for dx, dy, dyaw, drop in [(0, 0, 0, DROP), (0.004, 0, 0, DROP), (0, 0.004, 0, DROP), (0.007, 0, 0, DROP), + (0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]: + inst = copy.deepcopy(base) + inst["boxes"][j]["inner"] = [a, b] + task.reset_instance(inst) + task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)), + dx=dx, dy=dy, drop=drop)) + o = task.outcome(inst) + rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000, + dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"], + height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"])) + print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> " + f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json + # python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json + import sys + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None) + elif sys.argv[1] == "stress": + stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py new file mode 100644 index 0000000000000000000000000000000000000000..55c3e05f0c97631b61329c3dee47a318c1f3b5f1 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py @@ -0,0 +1,1273 @@ +"""LH drawer_cabinet (2026-10-16): tidy the table -- stand two tall bottles on top of a small wooden cabinet, put two +cubes into its open drawer and close the drawer. In 14 of every 20 instances the drawer is a self-closing one: pushed +into the last 8 cm, a strong spring snaps it shut, the light cabinet lurches 2.3-4.2 cm towards the robot, and bottles +already standing on its top fall over (away from the robot, onto the gallery rail at the back of the top). + +Family: long-horizon self-disturbance ("state_restoration"): a later, normal action (closing the drawer) physically +undoes an earlier stage (bottles on the cabinet). The instruction lists the bottles first but fixes no order. The agent +has to see the fallen bottles and stand them up again after the drawer is shut (within an attempt), or learn to put +the cubes in and shut the drawer before it puts the bottles on top (across attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a small wooden cabinet (free body, 18 (x) x 22 (y) x 11 cm, centre 53-56 cm in front of the robot base, front facing + the robot) with a 6 cm gallery rail along the back edge of its top, a 4 cm toe plinth under the drawer and a + back-heavy carcass; its single drawer (inside 15.9 x 16.2 cm, 3 cm walls, 1.8 cm overlay front panel with a painted + finger slot, no handle, 0.8 kg) is pulled out 11 cm towards the robot. The agentview camera looks at the cabinet's + back: the drawer is hidden there (wrist camera only), the top and the bottles are in plain view; + * two tall square bottles (green with a yellow ball cap, brown with a blue ball cap; 4 x 4 cm body, 19.4 cm tall, + 0.18 kg, centre of mass 9 cm up, a rounded glass base whose flat contact is 2.2 x 2.2 cm: they tip beyond ~7 deg) + standing on the table 21-24 cm to one side of the cabinet's centre line; + * two 3.2 cm cubes (red, blue, 23 g) 25-29 cm to the other side (picked from nearer, the forearm sweeps over the + cabinet top and knocks bottles standing there: measured feasibility map, task card). + +Hidden variable (same appearance): the drawer's closing mechanism. "self-closing" (14 of every 20 consecutive seeds): +in the last 8 cm of travel a spring pulls the drawer in with 12.5-15 N (no damper); "soft-close" (6 of 20): the same +spring with a damper, the drawer glides in at 4-6 cm/s. Nuisance variables (no effect on the class): carcass mass +0.35-0.45 kg, felt feet (friction on the table 0.15-0.22). + +Mechanism (physics, no teleport; measured, see the task card): the spring is internal to the cabinet, so when it snaps +the drawer in, it also pulls the light carcass (with the bottles on its top) towards the drawer, i.e. towards the robot: +2.3-4.2 cm within ~0.07 s (drawer hitting its stop at 1.9-2.4 m/s relative to the carcass; validate's naive runs), +then the carcass stops dead. A standing bottle's tilt follows a fast displacement of its support as ~ m h dx / I_edge +(~7 rad per metre here), so the bottles tip away from the robot and come to rest leaning on the rail (45-75 deg). The +robot's hand is at the drawer front, below and 10+ cm away from the bottles, and does not touch them (0 of all slams). +Pushing slower does not help (the spring does the closing; 2-10 cm/s and push heights 3-8 cm all toppled, 32/32); +placing the bottles elsewhere on the top does not help (46/46 over six placements). A soft-close drawer moves the +carcass < 3 mm (0/38 bottles fell). Only an uncontrolled full-speed push (~0.6 m/s, not an agent habit) differs: the +hand then shoves the cabinet itself (self-closing 5/8 fell, soft-close 4/4 fell, onto the arm). Placing the bottles after the drawer is shut is safe. Prototype findings that fixed +the numbers: with a light drawer, a heavier carcass or more friction the bottles only rocked (<= 11 deg): the snap's +jerk and the friction stop cancel; a 2 kg carcass held by friction during the snap instead jerked away from the robot +and tipped the bottles towards (onto) the arm. Without the rail, fallen bottles lay with their caps right behind the +cabinet, where the palm (3 cm behind the grasp point) cannot get at them; with the heavy drawer pulled out and no +plinth, ~3 N pressing on the drawer front tipped the cabinet forward. + +Restoring: the cap is a ball with low torsional friction; grasped from above with the fingers across the lying +bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs straight, and it can be set +down on the cabinet top (lh_bystander's mechanism; the instruction says that a bottle held by its cap hangs straight). +The neck has torsional friction: a bottle pinched at the neck just under the cap is carried without swinging. + +Success (final state, follows from the instruction): both bottles upright (<= 10 deg) with their whole base on the +cabinet top (inside the rail), not held; both cubes inside the drawer; the drawer closed (<= 5 mm); the cabinet +upright and not moved more than 8 cm (the snap itself moves it 2.3-4.2 cm); the gripper open, holding nothing and +touching no task object; scene static. Per-step monitor (server log only; F1 tells the agent success / failure): stage +achieved / lost / restored (with cause: drawer_slam / robot_hand / robot_arm / bottle / picked_up / other), +drawer_slam (impact speed, carcass jerk, bottles on top, which of them fell, whether the robot had touched them before +they started to fall), bottle_fell, trap_fired (a bottle on top was lost to a slam), recovered_in_attempt. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Once shut, the drawer cannot be opened again +(no handle; the self-closing spring would drag the light carcass along anyway). +""" +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 + +Z = envs.TABLE_Z + +# ---------------------------------------------------------------- cabinet (body frame: front face at -x, origin at the +# centre of the footprint, z = 0 on the table) +CAB = "cabinet_1" +CAB_MODEL = "lff_lhd_cabinet" +CD, CW, CH = 0.18, 0.22, 0.11 # carcass depth (x), width (y), height +CT = 0.010 # board thickness +PF = 0.018 # drawer front panel thickness (overlay: it sits in front of the carcass when closed) +DL = 0.165 # drawer box length (x), measured from the inner face of the front panel +DWT = 0.006 # drawer wall thickness +DWH = 0.030 # drawer wall height above its floor +D_FLOOR = CT + 0.003 # drawer floor bottom above the table +FLOOR_TOP = D_FLOOR + DWT +D_IN_Y = CW / 2 - CT - 0.003 - DWT # drawer inner half width (0.081) +D_IN_X = DL - DWT # inner length (from the front panel to the back wall) +Q_MAX = 0.14 # slide range (opening distance) +Q_OPEN = 0.11 # the drawer starts pulled out this far (exposed inside: 11 x 16.2 cm) +WOOD = (0.66, 0.50, 0.33, 1.0) +WOOD_D = (0.55, 0.40, 0.25, 1.0) +PANEL = (0.76, 0.60, 0.40, 1.0) +INNER = (0.84, 0.72, 0.52, 1.0) +SLOT = (0.18, 0.13, 0.09, 1.0) +DRAWER_MASS = 0.80 +PLINTH = 0.04 # the bottom board reaches this far in front of the carcass, under the drawer: with the heavy drawer +# pulled out, the cabinet would otherwise tip forward under a ~3 N push down on the drawer's front +CAB_COM_X = 0.04 # carcass centre of mass towards the back (back-heavy carcass): same reason +RAIL_H, RAIL_T = 0.060, 0.008 # gallery rail along the back edge of the top: a bottle that tips over backwards comes +# to rest leaning on it (~50 deg) instead of falling off behind the cabinet, where its +# cap would lie against the cabinet's back and the palm could not get at it +SLIDE_FRIC = 1.0 # N, slide frictionloss: the open drawer stays where it is +CARCASS_MASS = (0.35, 0.45) +FEET_MU = (0.15, 0.22) + +# drawer closing mechanism (hidden): spring in the last ZONE of travel, optional damper (soft-close) +ZONE = 0.08 +F_SPRING = (12.5, 15.0) +SOFT_V = (0.04, 0.06) # soft-close glide speed (damping = force / speed) +P_SLAM = 0.70 # 14 of every 20 consecutive seeds self-closing +CLOSED = 0.005 # drawer counts as closed +V_SLAM = 0.30 # m/s: an impact on the stop faster than this is a slam (soft-close: ~0.05) + +# ---------------------------------------------------------------- bottles (square body, shoulder, neck, ball cap) +BOTTLES = ("green_bottle_1", "brown_bottle_1") +B_NAME = {"green_bottle_1": "green", "brown_bottle_1": "brown"} +B_RGBA = {"green_bottle_1": (0.16, 0.48, 0.26, 1.0), "brown_bottle_1": (0.50, 0.26, 0.10, 1.0)} +CAP_RGBA = {"green_bottle_1": (0.92, 0.80, 0.15, 1.0), "brown_bottle_1": (0.15, 0.32, 0.85, 1.0)} +RB, HB = 0.020, 0.115 # body half width, height (incl. the foot) +RF, HF = 0.011, 0.005 # rounded glass base: flat contact 2.2 x 2.2 cm +RS, HS = 0.015, 0.010 # shoulder +RN, HN = 0.009, 0.050 # neck: long enough to be pinched below the cap with the palm clear of the cap +RK = 0.012 # ball cap +CAP_SINK = 0.005 +H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.194 +CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing +B_MASS = 0.18 +B_COM = 0.090 # above the bottom +B_MU = 0.8 +CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely +NECK_MU_T = 0.01 # torsional friction of the neck (condim 4): a bottle pinched by its neck does not swing +NECK_GRASP = H_TOT - 0.027 # scripted grasp height above the bottom: the palm (3.1 cm above the grasp point between +# the fingers, measured) clears the cap top by 4 mm; the pads hold the neck top and the cap + +# ---------------------------------------------------------------- cubes +CUBES = ("red_cube_1", "blue_cube_1") +CUBE_COLOR = {"red_cube_1": "red", "blue_cube_1": "blue"} +CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0)) +CUBE_E = 0.032 +CUBE_DENS = 700.0 # 23 g + +# ---------------------------------------------------------------- predicates / monitor +UPRIGHT = np.radians(10.0) +TILT_START = np.radians(6.0) # a standing bottle beyond this has started to fall (it tips at ~6.8 deg) +FALLEN = np.radians(40.0) # lying, or leaning on the gallery rail (45-75 deg) +CAB_MOVE_MAX = 0.08 +CAB_TILT_MAX = np.radians(10.0) +DEBOUNCE = 10 # control steps (0.5 s) a predicate change must persist (checked every other step) +WIN_ROBOT = 40 # control steps: a robot contact this recent can explain a loss +WIN_SLAM = 60 + +# ---------------------------------------------------------------- scripted motion +NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm +FINGER_AHEAD = 0.021 # closed fingertips reach this far ahead of the grasp point (yaw 0, +x) -- measured +REACH_MAX = 0.78 # scripted policies: farthest grasp point at table height (horizontal distance from the base) + + +def _box(name, pos, size, rgba, extra, vis=True, vis_rgba=None): + s = [f''] + if vis: + s.append(f'') + return s + + +def cabinet_xml(name): + """free carcass (bottom, top, two sides, back) + a drawer on a slide joint along -x (opening towards the robot). + Carcass geoms contype 2 / conaffinity 1, drawer geoms contype 4 / conaffinity 1: they never collide with each other + but both collide with the robot, the table and the free objects (contype / conaffinity 1). The slide joint comes + first in the object's joint list (robosuite appends the free joint), see DrawerCabinet.__init__.""" + hx, hy = CD / 2, CW / 2 + cg = 'friction="0.8 0.005 0.0001" contype="2" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"' + carc = [] + carc += _box(f"{name}_bottom", (-PLINTH / 2, 0, CT / 2), (hx + PLINTH / 2, hy, CT / 2), WOOD_D, cg) + carc += _box(f"{name}_top", (0, 0, CH - CT / 2), (hx, hy, CT / 2), WOOD, cg) + carc += _box(f"{name}_side_l", (0, hy - CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_side_r", (0, -hy + CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_back", (hx - CT / 2, 0, CH / 2), (CT / 2, hy - CT, CH / 2 - CT), WOOD, cg) + carc += _box(f"{name}_rail", (hx - RAIL_T / 2, 0, CH + RAIL_H / 2), (RAIL_T / 2, hy, RAIL_H / 2), WOOD_D, cg) + dg = 'friction="0.8 0.005 0.0001" contype="4" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"' + x0 = -hx # inner face of the front panel (closed) + zf = D_FLOOR + dr = [] + dr += _box(f"{name}_front", (x0 - PF / 2, 0, (CT + 0.002 + CH - 0.004) / 2), (PF / 2, hy, (CH - 0.006 - CT) / 2), + PANEL, dg) + dr += _box(f"{name}_dfloor", (x0 + DL / 2, 0, zf + DWT / 2), (DL / 2, D_IN_Y + DWT, DWT / 2), INNER, dg) + zw = zf + DWT + DWH / 2 + dr += _box(f"{name}_dside_l", (x0 + DL / 2, D_IN_Y + DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg) + dr += _box(f"{name}_dside_r", (x0 + DL / 2, -D_IN_Y - DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg) + dr += _box(f"{name}_dback", (x0 + DL - DWT / 2, 0, zw), (DWT / 2, D_IN_Y, DWH / 2), INNER, dg) + # flush finger pull (visual only): a dark slot near the top of the front panel + dr.append(f'') + m = DRAWER_MASS + ixx, iyy, izz = m * (CW ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + CW ** 2) / 12 + drawer = (f'\n' + f' \n' + f' \n' + "\n".join(" " + s for s in dr) + "\n") + m0 = 0.4 + inertial = (f'') + body = "\n ".join([inertial] + carc + drawer.split("\n")) + return f""" + + + + {body} + + + + + + +""" + + +def bottle_xml(name, rgba, cap_rgba): + """square bottle: rounded base (narrow flat foot), body, shoulder, neck, ball cap; origin at mid height""" + h = H_TOT / 2 + zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2 + zk = -h + HB + HS + HN + RK - CAP_SINK + m = B_MASS + ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 14 + izz = m * (2 * (2 * RB) ** 2) / 12 + fr = f'friction="{B_MU} 0.005 0.0001"' + sol = 'solimp="0.95 0.99 0.001" solref="0.005 1"' + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, fr + ' priority="2"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, fr), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, fr), + ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), rgba, + f'friction="{B_MU} {NECK_MU_T} 0.0001" condim="4" priority="2"'), + ("cap", "sphere", (0, 0, zk), (RK,), cap_rgba, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + if nm != "foot": + s.append(f' ') + # rounded base (visual): a slightly narrower bottom band, and a label + s.append(f' ') + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +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 _reach(p): + return float(np.hypot(p[0] + 0.66, p[1])) + + +class DrawerSkills(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 DrawerCabinet(LFFTask): + name = "lh_drawer_cabinet" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 2 bottles x ~8 commands + 3 cubes x ~6 + closing the drawer ~5 + looking ~15; standing 2 fallen bottles + # up again ~20; + slack + agent_max_steps = 120 + instruction = ("Tidy up the table: stand the green bottle and the brown bottle upright on top of the small wooden " + "cabinet, put the red cube and the blue cube into the cabinet's open drawer (it is pulled " + "out towards the robot), and close the drawer. When you finish, both bottles must stand upright on the cabinet top, both cubes must be in " + "the closed drawer, the cabinet must still stand where it is, and the gripper must be open and not " + "touching anything. (Each bottle has a round cap; held by its cap, a bottle hangs straight down.)") + instruction_indirect = ("Clean up: set the two tall bottles (the green one and the brown one) upright on the little " + "wooden cabinet, drop the two small cubes (red and blue) into its pulled-out drawer and " + "shut the drawer. In the end both bottles stand on top of the cabinet, the cubes are inside the shut drawer, " + "the cabinet stays in its place, and the open gripper touches nothing. (A bottle held by " + "its round cap hangs straight down.)") + agent_object_names = ["green bottle (yellow round cap)", "brown bottle (blue round cap)", "red cube", "blue cube", + "small wooden cabinet with its drawer pulled out (the drawer front faces the robot)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + cab = register_generated("LffLhdCabinet", cabinet_xml(CAB_MODEL)) + objs = [(CAB, cab, "cabinet_region", (0.10, -0.02, 0.12, 0.0))] + for i, b in enumerate(BOTTLES): + c = B_NAME[b] + cat = register_generated(f"LffLhdBottle{c.title()}", bottle_xml(f"lff_lhd_bottle_{c}", B_RGBA[b], CAP_RGBA[b])) + objs.append((b, cat, f"{c}_bottle_region", (-0.30, 0.20 + 0.13 * i, -0.28, 0.22 + 0.13 * i))) + for i, n in enumerate(CUBES): + c = CUBE_COLOR[n] + cat = register_generated(f"LffLhdCube{c.title()}", + box_xml(f"lff_lhd_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS, + friction=(0.8, 0.005, 0.0001))) + objs.append((n, cat, f"{c}_cube_region", (-0.30, -0.45 + 0.13 * i, -0.28, -0.43 + 0.13 * i))) + return write_bddl(self.name, "tidy up the table", objs, []) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{CAB}_{CAB_MODEL}" + self.jid = m.joint_name2id(pre + "_slide") + self.qa = int(m.jnt_qposadr[self.jid]) + self.dof = int(m.jnt_dofadr[self.jid]) + self.cab_bid = envs.body_id(self.env, CAB) + self.drawer_bid = m.body_name2id(f"{CAB}_drawer") + # the cabinet's free joint is the LAST of its joints (robosuite appends it after the drawer slide), so + # envs.free_joint_addr / place_upright (joints[0]) must not be used for it + fj = m.joint_name2id(self.env.objects_dict[CAB].joints[-1]) + assert int(m.jnt_type[fj]) == 0 + self.cab_qa, self.cab_da = int(m.jnt_qposadr[fj]), int(m.jnt_dofadr[fj]) + self.feet_gid = m.geom_name2id(pre + "_bottom") + self.cab_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in (self.cab_bid, self.drawer_bid) + and m.geom_contype[g] != 0} + self.bottle_gids = {b: set(envs.obj_geom_ids(self.env, b)) for b in BOTTLES} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, c)) for c in CUBES} + self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhd_bottle_{B_NAME[b]}_cap") for b in BOTTLES} + # per-geom lookup tables for the substep contact scan + self.part = np.zeros(m.ngeom, int) # 1 = hand / fingers, 2 = arm links + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if n.startswith("gripper0_") else 2 + self.bidx = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOTTLES): + self.bidx[list(self.bottle_gids[b])] = i + self.task_obj = np.zeros(m.ngeom, bool) + for s in list(self.bottle_gids.values()) + list(self.cube_gids.values()) + [self.cab_gids]: + self.task_obj[list(s)] = True + self.catch = dict(force=0.0, zone=ZONE, damp=0.0) + sim = self.env.sim + if not getattr(sim, "_lhd_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhd_task", None) + if t is not None: + t._substep() + sim.step = step + sim._lhd_wrapped = True + sim._lhd_task = self + self.inst = None + self.mon = None + self.sk = None + self._sub = {} + + # ------------------------------------------------------------ drawer mechanism (every MuJoCo substep) + def q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def catch_force(self, q, qd): + """generalised force on the slide (positive = opening): inside the last ZONE of travel a constant pull towards + closed (ramped in over 5 mm), plus a damper on closing motion for soft-close drawers""" + c = self.catch + z = c["zone"] + if q >= z or c["force"] <= 0: + return 0.0 + ramp = float(np.clip((z - q) / 0.005, 0.0, 1.0)) + f = -c["force"] * ramp + if qd < 0 and c["damp"] > 0: + f -= c["damp"] * qd * ramp + return f + + def _substep(self): + d = self.env.sim.data + q, qd = float(d.qpos[self.qa]), float(d.qvel[self.dof]) + d.qfrc_applied[self.dof] = self.catch_force(q, qd) + if self.mon is None: + return + sub = self._sub + # slam detection: the closing speed just before the drawer reaches its stop + if q > 0.002: + sub["approach_v"] = -qd + sub["armed"] = True + if q < self.catch["zone"] and sub.get("zone_xy") is None: + sub["zone_xy"] = self.cab_xy().tolist() + elif q > self.catch["zone"] + 0.005: + sub["zone_xy"] = None + elif sub.get("armed"): + sub["armed"] = False + v = float(sub.get("approach_v", 0.0)) + sub.setdefault("impacts", []).append((v, sub.get("zone_xy"))) + sub["zone_xy"] = None + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + for a, b in zip(g1, g2): + ia, ib = self.bidx[a], self.bidx[b] + if ia < 0 and ib < 0: + continue + if ia >= 0 and ib >= 0: + if ia != ib: + sub.setdefault("bb", set()).update((int(ia), int(ib))) + continue + i, o = (ia, b) if ia >= 0 else (ib, a) + p = int(self.part[o]) + if p: + r = sub.setdefault("rob", {}) + r[int(i)] = 2 if (p == 2 or r.get(int(i)) == 2) else 1 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + slam = bool((int(seed) * 7) % 20 < round(20 * P_SLAM)) # balanced: 14 of every 20 consecutive seeds + cx, cy = float(rng.uniform(-0.13, -0.10)), float(rng.uniform(-0.04, 0.04)) + s = 1.0 if rng.random() < 0.5 else -1.0 # bottles on the left (+1) or right (-1), cubes on the other side + bottles = {} + order = rng.permutation(2) + for j, i in enumerate(order): + bx = cx + (-0.05, 0.05)[j] + float(rng.uniform(-0.01, 0.01)) + bottles[BOTTLES[i]] = [bx, cy + s * float(rng.uniform(0.21, 0.24))] + perm = rng.permutation(2) + # cubes 25-29 cm to the side of the cabinet's centre line: picked from nearer, the forearm sweeps over the + # cabinet top and knocks the bottles standing there (measured feasibility map, see the task card) + cubes = {CUBES[i]: [cx + (-0.16, -0.04)[j] + float(rng.uniform(-0.01, 0.01)), + cy - s * float(rng.uniform(0.25, 0.29))] for j, i in enumerate(perm)} + force = float(rng.uniform(*F_SPRING)) + soft_v = float(rng.uniform(*SOFT_V)) + return dict(seed=int(seed), self_closing=slam, drawer="self-closing" if slam else "soft-close", + cab_xy=[cx, cy], bottle_side="left" if s > 0 else "right", bottle_start=bottles, + bottle_yaw={b: float(rng.uniform(-0.3, 0.3)) for b in BOTTLES}, cube_start=cubes, + cube_yaw={c: float(rng.uniform(-0.3, 0.3)) for c in CUBES}, + spring_n=force, damp=0.0 if slam else force / soft_v, + carcass_kg=float(rng.uniform(*CARCASS_MASS)), feet_mu=float(rng.uniform(*FEET_MU)), + naive_noise_seed=int(rng.integers(1 << 30))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + M = float(inst["carcass_kg"]) + m.body_mass[self.cab_bid] = M + m.body_inertia[self.cab_bid] = [M * (CW ** 2 + CH ** 2) / 12, M * (CD ** 2 + CH ** 2) / 12, + M * (CD ** 2 + CW ** 2) / 12] + m.geom_friction[self.feet_gid] = [float(inst["feet_mu"]), 0.005, 0.0001] + m.geom_priority[self.feet_gid] = 3 + self.catch = dict(force=float(inst["spring_n"]), zone=ZONE, damp=float(inst["damp"])) + self.set_drawer(Q_OPEN) + self.place_cabinet(inst["cab_xy"], 0.0) + for b in BOTTLES: + envs.place_upright(self.env, b, inst["bottle_start"][b], yaw=inst["bottle_yaw"][b], clearance=0.0005) + for c in CUBES: + envs.place_upright(self.env, c, inst["cube_start"][c], yaw=inst["cube_yaw"][c], clearance=0.001) + + def set_drawer(self, q): + d = self.env.sim.data + d.qpos[self.qa] = q + d.qvel[self.dof] = 0.0 + + def place_cabinet(self, xy, yaw=0.0, clearance=0.0005): + d = self.env.sim.data + a, v = self.cab_qa, self.cab_da + d.qpos[a:a + 3] = [xy[0], xy[1], Z + clearance] # body origin = bottom of the carcass + d.qpos[a + 3:a + 7] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)] + d.qvel[v:v + 6] = 0.0 + self.env.sim.forward() + + 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 = DrawerSkills(self.env, self, recorder=recorder) + self._sub = {} + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ geometry helpers (world frame) + def cab_R(self): + return self.env.sim.data.body_xmat[self.cab_bid].reshape(3, 3).copy() + + def cab_origin(self): + return self.env.sim.data.body_xpos[self.cab_bid].copy() + + def cab_xy(self): + return self.cab_origin()[:2] + + def to_cab(self, p): + """world point -> cabinet frame (x forward, origin at the footprint centre on the floor)""" + return self.cab_R().T @ (np.asarray(p, float) - self.cab_origin()) + + def from_cab(self, p): + return self.cab_origin() + self.cab_R() @ np.asarray(p, float) + + def top_z(self): + return float(self.from_cab([0.0, 0.0, CH])[2]) + + def cab_front_x(self): + """world x of the carcass's front face (cabinet assumed close to yaw 0)""" + return float(self.from_cab([-CD / 2, 0.0, 0.0])[0]) + + def drawer_front_x(self): + """world x of the drawer front panel's outer face""" + return self.cab_front_x() - self.q() - PF + + def cab_tilt(self): + return float(np.arccos(np.clip(self.cab_R()[2, 2], -1.0, 1.0))) + + def cab_moved(self): + return float(np.linalg.norm(self.cab_xy() - np.asarray(self.inst["cab_xy"]))) + + def R(self, name): + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy() + + def tilt(self, name): + return float(np.arccos(np.clip(self.R(name)[2, 2], -1.0, 1.0))) + + def bottle_base(self, b): + """world position of the centre of the bottle's bottom face""" + return envs.obj_pos(self.env, b) - self.R(b)[:, 2] * H_TOT / 2 + + def cap_xyz(self, b): + return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy() + + def held(self, name): + return self.sk is not None and self.sk.holding(name) + + # ------------------------------------------------------------ stage predicates + def bottle_on_top(self, b, tol=0.0, tilt=UPRIGHT): + if self.tilt(b) > tilt or self.held(b): + return False + c = self.to_cab(self.bottle_base(b)) + if c[0] < -CD / 2 + RF - tol or c[0] > CD / 2 - RAIL_T - RF + tol or abs(c[1]) > CW / 2 - RF + tol: + return False + return bool(-0.006 <= c[2] - CH <= 0.012) + + def cube_in_drawer(self, c): + """cube centre inside the drawer box (drawer frame), its footprint within the walls (+3 mm), resting low enough + to pass under the cabinet top; not held""" + if self.held(c): + return False + d = self.env.sim.data + Rd = d.body_xmat[self.drawer_bid].reshape(3, 3) + p = Rd.T @ (envs.obj_pos(self.env, c) - d.body_xpos[self.drawer_bid]) + x0 = -CD / 2 + e = CUBE_E / 2 * 1.2 # footprint half size (a yawed cube reaches a little farther) + tol = 0.003 + return bool(x0 + e - tol <= p[0] <= x0 + D_IN_X - e + tol and abs(p[1]) <= D_IN_Y - e + tol + and FLOOR_TOP - 0.005 <= p[2] - CUBE_E / 2 <= FLOOR_TOP + DWH + 0.01) + + def drawer_closed(self): + return self.q() <= CLOSED + + def stage_keys(self): + return [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + [f"{CUBE_COLOR[c]}_cube_in_drawer" for c in CUBES] + [ + "drawer_closed"] + + def stage_values(self, hyst=None): + hyst = hyst or {} + v = {} + for b in BOTTLES: + k = f"{B_NAME[b]}_bottle_on_top" + v[k] = self.bottle_on_top(b, 0.003, UPRIGHT + np.radians(3.0)) if hyst.get(k) else self.bottle_on_top(b) + for c in CUBES: + v[f"{CUBE_COLOR[c]}_cube_in_drawer"] = self.cube_in_drawer(c) + v["drawer_closed"] = self.q() <= (CLOSED + 0.003 if hyst.get("drawer_closed") else CLOSED) + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + keys = self.stage_keys() + st = {k: False for k in keys} + self.mon = dict(state=st, ever=[], lost=[], lost_cause={}, events=[], cand={k: 0 for k in keys}, step=0, + last_robot=[None, None], last_bb=None, slams=[], standing_since=[None, None], + fall_start=[None, None], touched_before_fall=[False, False], max_tilt=[0.0, 0.0], + n_fallen=0, fallen=[False, False]) + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + t = int(self.sk.n_steps) + sub, self._sub = self._sub, {k: v for k, v in self._sub.items() if k in ("approach_v", "armed", "zone_xy")} + for i, part in sub.get("rob", {}).items(): + b = BOTTLES[i] + if not self.held(b): + mon["last_robot"][i] = ["hand" if part == 1 else "arm", t, round(float(np.degrees(self.tilt(b))), 1)] + if sub.get("bb"): + mon["last_bb"] = t + for v, zxy in sub.get("impacts", []): + if v >= V_SLAM: + lurch = None + if zxy is not None: + dxy = self.cab_xy() - np.asarray(zxy) + lurch = [round(100 * float(dxy[0]), 2), round(100 * float(dxy[1]), 2)] + on = [B_NAME[b] for b in BOTTLES if mon["state"][f"{B_NAME[b]}_bottle_on_top"]] + e = dict(event="drawer_slam", step=t, speed_mps=round(float(v), 2), cabinet_jerk_cm=lurch, + bottles_on_top=on, bottles_fell=[], robot_touched_before_fall=[]) + mon["events"].append(e) + mon["slams"].append(e) + else: + mon["events"].append(dict(event="drawer_shut", step=t, speed_mps=round(float(v), 3))) + # fall tracking (R4: did the robot touch a bottle before it started to fall?) + for i, b in enumerate(BOTTLES): + tl = self.tilt(b) + mon["max_tilt"][i] = max(mon["max_tilt"][i], float(np.degrees(tl))) + if self.held(b): + mon["standing_since"][i] = None + continue + if tl < np.radians(3.0): + if mon["standing_since"][i] is None: + mon["standing_since"][i] = t + mon["fall_start"][i] = None + elif tl > TILT_START and mon["standing_since"][i] is not None and mon["fall_start"][i] is None: + mon["fall_start"][i] = t + lr = mon["last_robot"][i] + mon["touched_before_fall"][i] = bool(lr is not None and t - lr[1] <= 20 and lr[2] < np.degrees(TILT_START)) + if not mon["fallen"][i] and tl > FALLEN: + mon["fallen"][i] = True + mon["n_fallen"] += 1 + mon["events"].append(dict(event="bottle_fell", bottle=B_NAME[b], step=t, cause=self._cause(i, t), + robot_touched_before_fall=bool(mon["touched_before_fall"][i]), + direction=self._fall_dir(b))) + elif mon["fallen"][i] and tl < UPRIGHT: + mon["fallen"][i] = False + if mon["step"] % 2: + return + vals = self.stage_values(hyst=mon["state"]) + for k, now in vals.items(): + self._check(k, now, t) + + def _fall_dir(self, b): + ax = self.R(b)[:2, 2] + if np.linalg.norm(ax) < 0.2: + return "none" + return ("forward" if ax[0] > 0 else "backward") if abs(ax[0]) >= abs(ax[1]) else ("left" if ax[1] > 0 else "right") + + def _cause(self, i, t): + """why bottle i left the cabinet top""" + b = BOTTLES[i] + mon = self.mon + if self.held(b): + return "picked_up" + lr = mon["last_robot"][i] + robot_recent = lr is not None and t - lr[1] <= WIN_ROBOT + if robot_recent and mon["touched_before_fall"][i]: + return f"robot_{lr[0]}" + if robot_recent and lr[2] < np.degrees(TILT_START): + return f"robot_{lr[0]}" + if mon["slams"] and t - mon["slams"][-1]["step"] <= WIN_SLAM: + return "drawer_slam" + if mon["last_bb"] is not None and t - mon["last_bb"] <= WIN_ROBOT: + return "bottle" + if robot_recent: + return f"robot_{lr[0]}" + return "other" + + def _check(self, key, now, t): + mon = self.mon + if now == mon["state"][key]: + mon["cand"][key] = 0 + return + mon["cand"][key] += 2 + if mon["cand"][key] < DEBOUNCE: + return + mon["cand"][key] = 0 + mon["state"][key] = now + t0 = int(t - DEBOUNCE + 1) + if now: + restored = key in mon["lost"] + e = dict(stage=key, event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"].get(key) + mon["lost"].remove(key) + if key not in mon["ever"]: + mon["ever"].append(key) + mon["events"].append(e) + return + if key not in mon["ever"]: + return + if key.endswith("bottle_on_top"): + i = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES].index(key) + cause = self._cause(i, t) + if cause == "drawer_slam": + s = mon["slams"][-1] + if B_NAME[BOTTLES[i]] not in s["bottles_fell"]: + s["bottles_fell"].append(B_NAME[BOTTLES[i]]) + s["robot_touched_before_fall"].append(bool(mon["touched_before_fall"][i])) + elif key == "drawer_closed": + cause = "opened" + else: + c = CUBES[[f"{CUBE_COLOR[x]}_cube_in_drawer" for x in CUBES].index(key)] + cause = "picked_up" if self.held(c) else "other" + if key not in mon["lost"]: + mon["lost"].append(key) + mon["lost_cause"][key] = cause + mon["events"].append(dict(stage=key, event="lost", step=t0, cause=cause)) + + def _finalize_monitor(self, vals): + """close the event log at finish: a stage the debounced monitor still holds but the final judge does not (or + vice versa) is logged now (final=True)""" + mon = self.mon + t = int(self.sk.n_steps) + for k, now in vals.items(): + if now == mon["state"][k]: + continue + n0 = len(mon["events"]) + mon["cand"][k] = DEBOUNCE # force the transition + self._check(k, now, t + DEBOUNCE - 1) + if len(mon["events"]) > n0: + mon["events"][-1]["final"] = True + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in BOTTLES + CUBES: + _, 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 + v = self.cab_da + return bool(np.linalg.norm(d.qvel[v:v + 3]) < 0.02 and abs(float(d.qvel[self.dof])) < 0.02) + + def robot_touching(self): + d = self.env.sim.data + out = set() + for j in range(d.ncon): + c = d.contact[j] + for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)): + if self.part[a] and self.task_obj[b]: + out.add("a bottle" if self.bidx[b] >= 0 else "the cabinet" if b in self.cab_gids else "a cube") + return sorted(out) + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + touching = set() + for _ in range(20): + sk.hold(1) + touching.update(self.robot_touching()) + touching = sorted(touching) + static = self._static() + vals = self.stage_values() + held = [n for n in BOTTLES + CUBES if self.held(n)] + cab_ok = bool(self.cab_tilt() <= CAB_TILT_MAX and self.cab_moved() <= CAB_MOVE_MAX) + grip_open = bool(sk.grip < 0) + self._finalize_monitor(vals) + mon = self.mon + ev = list(mon["events"]) + success = bool(all(vals.values()) and cab_ok and static and not held and not touching and grip_open) + lost = [e for e in ev if e.get("event") == "lost"] + regress = [e for e in lost if e.get("cause") != "picked_up"] + restored = [e for e in ev if e.get("event") == "restored" and e.get("after") != "picked_up"] + slams = [e for e in ev if e.get("event") == "drawer_slam"] + slam_losses = [e for e in lost if e.get("cause") == "drawer_slam"] + trap = bool(slam_losses) + bkeys = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + never_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k not in mon["ever"]] + lost_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k in mon["ever"]] + cubes_out = [CUBE_COLOR[c] for c in CUBES if not vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]] + if success: + failure = "none" + elif held: + failure = "held" + elif not cab_ok: + failure = "cabinet_moved" + elif lost_bottle: + failure = "bottle_knocked" + elif never_bottle: + failure = "bottle_not_on_top" + elif cubes_out: + failure = "cube_not_in_drawer" + elif not vals["drawer_closed"]: + failure = "drawer_open" + elif touching: + failure = "touching" + elif not grip_open: + failure = "gripper_closed" + else: + failure = "not_static" + detail = self._detail(vals, held, touching, cab_ok, static, grip_open, success, ev) + return dict(success=success, failure=failure, stages=vals, events=ev, n_regressions=len(regress), + n_lost=len(lost), n_restored=len(restored), trap_fired=trap, + recovered_in_attempt=bool(trap and success), n_slams=len(slams), + slam_speeds=[e["speed_mps"] for e in slams], slam_jerk_cm=[e["cabinet_jerk_cm"] for e in slams], + bottles_lost_to_slam=sorted({e["stage"].split("_")[0] for e in slam_losses}), + robot_touched_before_fall=[bool(x) for x in mon["touched_before_fall"]], + bottle_max_tilt_deg=[round(x, 1) for x in mon["max_tilt"]], n_fallen=mon["n_fallen"], + held=held, touching=touching, static=bool(static), gripper_open=grip_open, + drawer_q_cm=round(100 * self.q(), 2), cabinet_moved_cm=round(100 * self.cab_moved(), 2), + cabinet_tilt_deg=round(float(np.degrees(self.cab_tilt())), 1), + bottle_tilts_deg={B_NAME[b]: round(float(np.degrees(self.tilt(b))), 1) for b in BOTTLES}, + self_closing=bool(inst["self_closing"]), detail=detail) + + def _detail(self, vals, held, touching, cab_ok, static, grip_open, success, ev): + parts = [] + if success: + parts.append("Both bottles stand on the cabinet, the two cubes are in the closed drawer.") + top_c = self.from_cab([0.0, 0.0, CH]) + for b in BOTTLES: + k = f"{B_NAME[b]}_bottle_on_top" + if vals[k]: + continue + nm = B_NAME[b] + if b in held: + parts.append(f"The {nm} bottle is still held by the gripper.") + continue + tl = float(np.degrees(self.tilt(b))) + base = self.bottle_base(b) + rel = base - top_c + on_top = abs(float(rel[2])) < 0.03 + ax = self.R(b)[:, 2] + where = f"its base is {_fb(rel[0])} and {_lr(rel[1])} of the centre of the cabinet top" + if tl <= np.degrees(UPRIGHT): + txt = (f"The {nm} bottle stands but not on the cabinet top: {where}." if not on_top else + f"The {nm} bottle stands with part of its base over the edge of the cabinet top: {where}.") + elif on_top and ax[0] > 0.3 and self.to_cab(self.cap_xyz(b))[0] > CD / 2 - RAIL_T: + txt = (f"The {nm} bottle has tipped over forward on the cabinet top and leans {tl:.0f} degrees against " + f"the rail along the top's far edge; {where}.") + elif on_top: + txt = f"The {nm} bottle has tipped over on the cabinet top ({tl:.0f} degrees); {where}." + elif base[2] < Z + 0.03: + txt = f"The {nm} bottle has fallen over and lies on the table; {where}." + else: + txt = f"The {nm} bottle has fallen over and leans {tl:.0f} degrees against something; {where}." + lost = [e for e in ev if e.get("stage") == k and e.get("event") == "lost"] + if lost: + why = lost[-1].get("cause", "other") + txt += {"drawer_slam": " It had stood on the cabinet top; it fell when the drawer snapped shut and the " + "cabinet jerked.", + "robot_hand": " It had stood on the cabinet top; the gripper knocked it.", + "robot_arm": " It had stood on the cabinet top; the robot's arm knocked it.", + "bottle": " It had stood on the cabinet top; the other bottle knocked it."}.get( + why, " It had stood on the cabinet top earlier.") + parts.append(txt) + for c in CUBES: + if vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]: + continue + nm = CUBE_COLOR[c] + if c in held: + parts.append(f"The {nm} cube is still held by the gripper.") + continue + p = envs.obj_pos(self.env, c) + rel = self.to_cab(p) + if abs(rel[0]) < CD / 2 and abs(rel[1]) < CW / 2 and rel[2] > CH - 0.01: + parts.append(f"The {nm} cube lies on the cabinet top, not in the drawer.") + else: + parts.append(f"The {nm} cube is not in the drawer: it is {_fb(rel[0] + CD / 2)} and {_lr(rel[1])} of the " + f"middle of the cabinet's front.") + if not vals["drawer_closed"]: + parts.append(f"The drawer is still {100 * self.q():.1f} cm open.") + if not cab_ok: + if self.cab_tilt() > CAB_TILT_MAX: + parts.append("The cabinet has been knocked over.") + else: + parts.append(f"The cabinet was moved {100 * self.cab_moved():.0f} cm from where it stood.") + if not success and all(vals.values()) and cab_ok: + if touching: + parts.append("The gripper is still touching " + " and ".join(touching) + ".") + elif not grip_open: + parts.append("The gripper is closed.") + elif not static: + parts.append("Something was still moving.") + slams = [e for e in ev if e.get("event") == "drawer_slam" and e.get("bottles_fell")] + if slams and success: + parts.append("(The drawer snapped shut and knocked bottles off the cabinet; they were stood up again.)") + return " ".join(parts) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < z - 0.005: + self._go([cur[0], cur[1], z], speed=speed) + + def _settle(self, name, max_checks=25): + 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 _box_yaw(self, name): + R = self.R(name) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + cands = [y + k * np.pi / 2 for k in (-1, 0, 1)] + return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0) + + def pick_bottle(self, b, grasp="neck", z_clear=0.05, yaw=None, v=0.15): + """Sonnet-like pick of a standing bottle from above: over it, straight down, close, lift until its bottom + clears the cabinet top by z_clear. grasp: neck (1 cm below its top; the body cannot be reached from above, the + palm would land on the cap) | cap (the bottle then hangs from a pivot)""" + sk = self.sk + self._settle(b) + p = envs.obj_pos(self.env, b) + bot = self.bottle_base(b)[2] + zg = {"neck": bot + NECK_GRASP, "cap": bot + CAP_Z}[grasp] + yaw = self._box_yaw(b) if yaw is None else yaw + sk.set_gripper(False, steps=8) + top = bot + H_TOT + self.transit(p[:2], top + 0.06, yaw=yaw, v=v) + self._go([p[0], p[1], zg + 0.015], speed=0.1) + self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + lift = self.top_z() + z_clear + (zg - bot) + self._go([p[0], p[1], lift], speed=0.10) + sk.hold(5) + if not self.held(b): + sk.set_gripper(False, steps=8) + return False + return True + + def put_bottle(self, b, xy, gap=0.01, z_clear=0.05, v=0.12, settle=15): + """carry the held bottle over xy (its axis, not the grasp point), straight down until its bottom is `gap` above + the cabinet top, let go, lift""" + sk = self.sk + rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + zc = self.top_z() + z_clear + (sk.eef_pos()[2] - self.bottle_base(b)[2]) + self.transit(q, zc, v=v, carried=b, margin=z_clear) + sk.hold(settle) + rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, b) + zr = self.top_z() + dz + gap + self._go([q[0], q[1], zr + 0.02], speed=0.08) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.hold(5) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], self.top_z() + H_TOT + 0.06], speed=0.08) + self._settle(b) + + def obstacle_top(self, p0, p1, ignore=(), r=0.09): + """highest top (world z) of standing bottles within r of the straight path p0 -> p1 (xy), and of the cabinet + top if the path passes over it (expanded by 4 cm)""" + a, b = np.asarray(p0, float)[:2], np.asarray(p1, float)[:2] + ab = b - a + L2 = max(float(ab @ ab), 1e-9) + + def dist(q): + u = float(np.clip((q - a) @ ab / L2, 0.0, 1.0)) + return float(np.linalg.norm(a + u * ab - q)) + top = Z + for o in BOTTLES: + if o in ignore or self.held(o): + continue + if dist(envs.obj_pos(self.env, o)[:2]) < r: + top = max(top, envs.obj_max_z(self.env, o)) + for u in np.linspace(0.0, 1.0, 21): + c = self.to_cab(np.r_[a + u * ab, Z]) + if abs(c[0]) < CD / 2 + 0.04 + PF + max(self.q(), 0.0) and abs(c[1]) < CW / 2 + 0.04: + top = max(top, self.top_z() + RAIL_H) + break + return top + + def transit(self, xy, z_min, yaw=None, v=0.15, carried=None, margin=0.06): + """Sonnet-like transit: up (to clear what is in the way), straight across, the caller then goes down""" + sk = self.sk + cur = sk.eef_pos() + obst = self.obstacle_top(cur, xy, ignore=(carried,) if carried else ()) + below = (sk.eef_pos()[2] - envs.obj_min_z(self.env, carried)) if carried else 0.03 + zt = max(cur[2], z_min, obst + margin + below) + if cur[2] < zt - 0.005: + self._go([cur[0], cur[1], zt], speed=v) + self._go([xy[0], xy[1], zt], yaw=yaw, speed=v) + + def pick_cube(self, c, z_carry=0.15, v=0.15): + sk = self.sk + for _ in range(2): + self._settle(c) + p = envs.obj_pos(self.env, c) + yaw = self._box_yaw(c) + sk.set_gripper(False, steps=8) + self.transit(p[:2], Z + z_carry, yaw=yaw, v=v) + self._go([p[0], p[1], p[2] + 0.015], speed=0.1) + self._go([p[0], p[1], p[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], max(Z + z_carry, sk.eef_pos()[2])], speed=v) + if self.held(c): + return True + sk.set_gripper(False, steps=8) + return False + + def drawer_slot(self, k, noise=None): + """world xy of cube slot k (0..1) in the exposed part of the open drawer: a column along the drawer's middle + (with the wrist at yaw 0 the open fingers, 13.2 cm across, stay clear of the side walls and of the cube + already in; the palm, 3.9 cm ahead of the grasp point, stays clear of the carcass; the far slot first)""" + q = min(self.q(), Q_OPEN) + x = self.cab_front_x() - 0.045 - k * (q - 0.070) + y = self.cab_xy()[1] + out = np.array([x, y]) + return out + (np.asarray(noise, float) if noise is not None else 0.0) + + def put_cube(self, c, xy, gap=0.02, z_carry=0.15, v=0.15): + sk = self.sk + self.transit(xy, Z + z_carry, yaw=0.0, v=v, carried=c, margin=0.04) + zr = Z + FLOOR_TOP + CUBE_E / 2 + gap + self._go([xy[0], xy[1], zr + 0.015], speed=0.1) + self._go([xy[0], xy[1], zr], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], Z + z_carry], speed=v) + self._settle(c) + + def close_drawer(self, v=0.04, z_push=0.05, overshoot=0.0, y_off=0.0, approach=0.03): + """closed gripper in front of the drawer, then a straight push forward to where the front panel is flush""" + sk = self.sk + y = self.cab_xy()[1] + y_off + xs = self.drawer_front_x() - FINGER_AHEAD - approach + x_end = self.cab_front_x() - PF - FINGER_AHEAD + overshoot + sk.set_gripper(True, steps=10) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15) + self._go([xs, y, Z + 0.15], yaw=0.0, speed=0.15) + self._go([xs, y, Z + z_push], speed=0.1, tol=0.003) + self._go([x_end, y, Z + z_push], speed=v, tol=0.003, max_steps=int(0.25 / max(v, 0.01) / 0.05) + 60) + self.sk.hold(10) + cur = sk.eef_pos() + self._go([cur[0] - 0.06, cur[1], cur[2]], speed=0.08) + self._go([cur[0] - 0.06, cur[1], Z + 0.20], speed=0.15) + sk.hold(10) + + def top_spots(self, mode="pair", noise=None): + """world xy targets on the cabinet top for the two bottles (left one first): side by side across the middle""" + c = self.from_cab([0.0, 0.0, CH])[:2] + spots = [c + np.array([0.0, 0.05]), c + np.array([0.0, -0.05])] + if noise is not None: + spots = [s + np.asarray(n, float) for s, n in zip(spots, noise)] + return spots + + def free_top_spot(self, b, start=None): + """a spot on the cabinet top (cabinet frame candidates) at least 6.5 cm from the other bottle if that one stands + on the top, and -- if `start` (xy the bottle comes from) is given -- whose straight path from `start` passes + farthest from it""" + other = [o for o in BOTTLES if o != b][0] + cands = [np.array([dx, dy]) for dx in (0.0, -0.03, 0.03) for dy in (0.055, -0.055, 0.0)] + ok_other = self.bottle_on_top(other, 0.01, np.radians(20)) + oc = self.to_cab(self.bottle_base(other))[:2] + if not ok_other: + return self.from_cab([cands[0][0], cands[0][1], CH])[:2] if start is None else min( + (self.from_cab([c[0], c[1], CH])[:2] for c in cands[:2]), + key=lambda w: float(np.linalg.norm(w - np.asarray(start)[:2]))) + best, score = None, -1.0 + st = None if start is None else self.to_cab(np.r_[np.asarray(start)[:2], Z])[:2] + for c in cands: + if np.linalg.norm(c - oc) < 0.065: + continue + if st is None: + return self.from_cab([c[0], c[1], CH])[:2] + ab = c - st + u = float(np.clip((oc - st) @ ab / max(float(ab @ ab), 1e-9), 0.0, 1.0)) + clear = float(np.linalg.norm(st + u * ab - oc)) + if clear > score: + best, score = c, clear + if best is None: + best = max(cands, key=lambda c: float(np.linalg.norm(c - oc))) + return self.from_cab([best[0], best[1], CH])[:2] + + def restand_bottle(self, b, xy=None): + """stand a fallen bottle up again on the cabinet top: grasp the ball cap from above (fingers across the lying + bottle's axis), lift until it hangs free with its bottom above the gallery rail, carry it over a free spot, + lower until the bottom is ~3 mm above the top, let go. Returns True if it stands on the top.""" + sk = self.sk + self._settle(b) + for _ in range(2): + if _reach(self.cap_xyz(b)) > REACH_MAX and self.tilt(b) > FALLEN: + self.pull_in_bottle(b) + k = self.cap_xyz(b) + ax = self.R(b)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it + sk.set_gripper(False, steps=8) + self.transit(k[:2], k[2] + 0.08, yaw=yaw, v=0.15) + sk.hold(5) + k = self.cap_xyz(b) + self._go([k[0], k[1], k[2] + 0.015], speed=0.1) + self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], k[2] + 0.08], speed=0.1) + continue + zl = self.top_z() + RAIL_H + 0.03 + CAP_Z + self._go([k[0], k[1], zl], speed=0.10) + sk.hold(15) + tx, ty = self.free_top_spot(b, start=k[:2]) if xy is None else xy + self._go([tx, ty, zl], speed=0.10) + sk.hold(30) + self._go([tx, ty, self.top_z() + CAP_Z + 0.015], speed=0.08) + self._go([tx, ty, self.top_z() + CAP_Z + 0.003], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([tx, ty, self.top_z() + H_TOT + 0.04], speed=0.08) + sk.hold(20) + self._settle(b) + if self.bottle_on_top(b): + return True + return self.bottle_on_top(b) + + def pull_in_bottle(self, b): + """the lying bottle's cap is out of reach: grasp the body near its bottom end (fingers across it), lift it + 3 cm, pull it towards the robot until the cap is within reach, set it down""" + sk = self.sk + Rb = self.R(b) + ax = Rb[:, 2] + g = envs.obj_pos(self.env, b) - ax * (H_TOT / 2 - 0.04) + zg = max(float(g[2] - Z), 0.02) + yaw = float(np.arctan2(ax[1], ax[0])) + need = _reach(self.cap_xyz(b)) - (REACH_MAX - 0.05) + to_base = np.array([-0.66, 0.0]) - g[:2] + to_base /= max(np.linalg.norm(to_base), 1e-6) + dst = g[:2] + to_base * need + sk.set_gripper(False, steps=8) + self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15) + self._go([g[0], g[1], Z + zg + 0.015], speed=0.1) + self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([g[0], g[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04) + sk.set_gripper(False, steps=12) + self._go([dst[0], dst[1], Z + 0.15], speed=0.1) + self._settle(b) + + # ------------------------------------------------------------ scripted policies + def check_and_fix(self, params, rounds=2): + """look at every stage at the end: stand fallen bottles up on the top, put stray cubes into the drawer if it is + still open""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + break + for b in BOTTLES: + if not self.bottle_on_top(b): + if self.tilt(b) > UPRIGHT or self.bottle_base(b)[2] < self.top_z() - 0.03: + if self.tilt(b) > UPRIGHT: + self.restand_bottle(b) + elif self.pick_bottle(b, grasp="neck"): + self.put_bottle(b, self.free_top_spot(b), gap=0.005) + if not self.drawer_closed(): + for k, c in enumerate(CUBES): + if not self.cube_in_drawer(c) and self.pick_cube(c): + self.put_cube(c, self.drawer_slot(k)) + if all(self.cube_in_drawer(c) for c in CUBES): + self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05)) + self._lift_to(self.top_z() + 0.15) + self.sk.set_gripper(False, steps=8) + self.sk.hold(10) + + def do_bottles(self, params, rng): + noise = params.get("noise") + spots = self.top_spots(noise=noise) + side = 1.0 if self.inst["bottle_side"] == "left" else -1.0 + spots = sorted(spots, key=lambda q: side * float(q[1])) # the spot farther from the bottles' side first + order = list(BOTTLES) if params.get("bottle_order", "listed") == "listed" else list(BOTTLES)[::-1] + for b, xy in zip(order, spots): + for _ in range(2): + if self.pick_bottle(b, grasp=params.get("grasp", "neck"), z_clear=params.get("z_clear", 0.05)): + self.put_bottle(b, xy, gap=params.get("gap", 0.02), z_clear=params.get("z_clear", 0.05)) + break + + def do_cubes(self, params, rng): + noise = params.get("cube_noise") or [None] * 3 + for k, c in enumerate(self._cube_order()): + if self.pick_cube(c): + self.put_cube(c, self.drawer_slot(k, noise[k]), gap=params.get("cube_gap", 0.02)) + + def _cube_order(self): + """nearest the drawer first""" + d = np.array([self.cab_front_x() - Q_OPEN / 2, self.cab_xy()[1]]) + return sorted(CUBES, key=lambda c: float(np.linalg.norm(envs.obj_pos(self.env, c)[:2] - d))) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = params.get("order", "BCD") # B = bottles on top, C = cubes into the drawer, D = close the drawer + for step in order: + if step == "B": + self.do_bottles(params, rng) + elif step == "C": + self.do_cubes(params, rng) + elif step == "D": + self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05), + overshoot=params.get("overshoot", 0.0)) + if params.get("check"): + self.check_and_fix(params) + else: + self._lift_to(self.top_z() + 0.15) + self.sk.set_gripper(False, steps=8) + self.sk.hold(10) + + def _noise(self, rng, err=NAIVE_ERR): + return dict(noise=[rng.uniform(-err, err, 2).tolist() for _ in BOTTLES], + cube_noise=[rng.uniform(-err, err, 2).tolist() for _ in CUBES]) + + def default_params(self, inst): + """Sonnet-like: the order of the instruction (bottles, cubes, drawer); bottles grasped by the body from above, + lifted until they clear the cabinet top by 5 cm, lowered straight down and let go 1-4 cm above it; cubes into + the drawer; the drawer pushed shut slowly (4 cm/s) with the closed gripper; no final look back""" + rng = np.random.default_rng(inst["naive_noise_seed"]) + p = dict(order="BCD", check=False, grasp="neck", gap=float(rng.uniform(0.01, 0.04)), + push_v=float(rng.uniform(0.03, 0.05)), push_z=float(rng.uniform(0.04, 0.06)), + overshoot=float(rng.uniform(0.0, 0.004)), noise_seed=int(inst["naive_noise_seed"])) + p.update(self._noise(rng)) + return p + + def oracle_params(self, inst): + """knows the drawer: cubes in, drawer shut, then the bottles; checks every stage at the end""" + return dict(order="CDB", check=True, grasp="neck", gap=0.008, push_v=0.04, push_z=0.05, overshoot=0.0) + + def adapt_params(self, inst, history): + """attempt >= 2 (after the bottles fell when the drawer was shut): shut the drawer before the bottles go on + top, and look at every stage at the end""" + return dict(self.default_params(inst), order="CDB", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural behaviour with random variations (order of the three sub-tasks, push speed / height, release + height, placement noise), no history, no final look""" + order = str(rng.choice(["BCD", "CBD", "CDB"], p=[0.5, 0.3, 0.2])) + p = dict(order=order, check=False, grasp=str(rng.choice(["neck", "cap"])), gap=float(rng.uniform(0.01, 0.04)), + push_v=float(rng.uniform(0.02, 0.08)), push_z=float(rng.uniform(0.03, 0.07)), + overshoot=float(rng.uniform(0.0, 0.006)), noise_seed=int(rng.integers(1 << 30))) + p.update(self._noise(rng)) + return p + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = naive + a final look that stands fallen bottles up again, + attempts >= 2 drawer first; blind: naive with random variations. + Extra kinds (not in validate's table): switch (naive, then drawer first without a final look), oracle_noise + (oracle with +-5 mm placement noise), naive_slow (naive pushing at the slowest agent speed, 2 cm/s), + naive_check (naive + final look = adaptive's first attempt)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "naive_slow", "naive_check", "naive_neck", "naive_cap") + 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(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) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), order="CDB") + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), **self._noise(np.random.default_rng(seed * 7 + a), 0.005)) + elif kind == "naive_slow": + params = dict(self.default_params(inst), push_v=0.02) + elif kind == "naive_check": + params = dict(self.default_params(inst), check=True) + elif kind == "naive_neck": + params = dict(self.default_params(inst), grasp="neck") + elif kind == "naive_cap": + params = dict(self.default_params(inst), grasp="cap") + 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 single: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_order_dispatch.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbca418828c2aec9e5a248d17a51db00760bef0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_order_dispatch.py @@ -0,0 +1,242 @@ +"""Development composite: physically load two products and a card, then steer a weighted shipping tray. +L1 fixed calibration bias, L3 card edge strategy, L5 off-centre loaded push. Not in the main set. +""" +import numpy as np +import copy +import xml.etree.ElementTree as ET +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import LFFTask, register_task +from .l3_card_edge import CardEdge, card_xml, BOARD_HALF, BOARD_TOP, CARD_HALF, GRASP_OUT +from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, HALF, + MASS, MU, box_fit, box_corners, _yaw, _rot) + +PRODUCTS = ('product_red_1', 'product_blue_1') +CARGO = PRODUCTS + ('card_1',) +PH = .014 + + +def shipping_xml(): + xml = long_box_xml('lff_dispatch_box') + parts=[] + for k,(p,h) in enumerate([((.042,0,.025),(.003,.11,.005)),((-.042,0,.025),(.003,.11,.005)), + ((0,.107,.032),(.039,.003,.012)),((0,-.107,.032),(.039,.003,.012))]): + parts.append(f'') + return xml.replace(' ', '\n'.join(parts)+'\n ',1) + + +class DispatchSkills(PushSkills): + def __init__(self, env, task, bias, recorder=None): + super().__init__(env,bias=bias,recorder=recorder,target=task.target_xy(task.inst)) + self.task=task + self.closes=[] + self.correction=np.zeros(3) + self.n_commands=0 + def reported_eef_pos(self): + return self.eef_pos()-self.bias + def move_to(self,target,*args,**kwargs): + self.n_commands+=1 + if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded") + rep=super().move_to(np.asarray(target)-self.correction,*args,**kwargs) + rep['pos']=np.round(self.reported_eef_pos(),4).tolist() + return rep + def _act(self,dpos,drot,grip): + super()._act(dpos,drot,grip) + self.task.monitor_step() + if self.n_steps*.05>=3*self.task.agent_max_steps:raise RuntimeError('dispatch simulation budget exceeded') + def set_gripper(self,close,steps=15): + self.n_commands+=1 + if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded") + ctx=self.task.close_context() if close and self.grip<0 else None + rep=super().set_gripper(close,steps) + if ctx is not None: + ctx.update(held=self.holding('card_1'),width=round(self.gripper_width(),4)) + self.closes.append(ctx) + return rep + + +@register_task +class OrderDispatch(CardEdge,OffcenterPush): + name='lh_order_dispatch' + level='L1' + failure_causes=('L1','L3','L5') + failure_types=failure_causes + 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.') + instruction_indirect=('Pack the two small coloured cubes and the thin red rectangle into the long brown ' + 'container while the container is at its starting position, then push the loaded container with the closed ' + 'gripper completely into the green marked area. Keep every item inside, and finish with the ' + 'gripper open and clear.') + def make_bddl(self): + card=register_generated('LffDispatchCard',card_xml('lff_dispatch_card')) + board=register_generated('LffDispatchBoard',box_xml('lff_dispatch_board',BOARD_HALF,(.62,.45,.27,1),friction=(.3,.005,.0001)),free=False) + box=register_generated('LffDispatchBox',shipping_xml()) + zone_xml=ET.fromstring(rect_frame_xml('lff_dispatch_zone')) + load_xml=ET.fromstring(rect_frame_xml('lff_dispatch_loading',inner_half=(.10,.15),line_rgba=(.8,.6,.05,1),fill_rgba=(.95,.88,.55,1))) + body=zone_xml.find('worldbody/body/body') + for geom in load_xml.find('worldbody/body/body'): + q=np.fromstring(geom.get('pos','0 0 0'),sep=' ');q[0]-=.11;geom.set('pos',' '.join(map(str,q)));body.append(geom) + zone=register_generated('LffDispatchZone',ET.tostring(zone_xml,encoding='unicode'),free=False) + objs=[('card_1',card,'card_region',(-.305,.395,-.295,.405)),('box_1',box,'box_region',(-.255,-.005,-.245,.005))] + for k,o in enumerate(PRODUCTS): + cat=register_generated('LffDispatchProduct'+('Red' if k==0 else 'Blue'),box_xml('lff_dispatch_product_'+str(k),(PH,PH,PH),((.9,.1,.1,1) if k==0 else (.1,.2,.9,1)),density=500)) + objs.append((o,cat,'prod_region'+str(k),(-.305+.25*k,-.405,-.295+.25*k,-.395))) + return write_bddl(self.name,self.instruction,objs,[('board_1',board,'board_region',(.295,.345,.305,.355)),('zone_1',zone,'zone_region',(.295,-.355,.305,-.345))]) + def __init__(self,cam_res=None): + LFFTask.__init__(self,cam_res) + self.board_bid=self.env.sim.model.body_name2id(self.env.fixtures_dict['board_1'].root_body) + self.inst=None;self.mon=None + def sample_instance(self,seed): + rng=np.random.default_rng(seed) + bx=-.18;by=.20 + return dict(seed=int(seed),board_xy=[bx,by],card_xy=[bx,by],card_yaw=0.,card_along='x', + bin_xy=[-.21,-.08],box_xy=[-.21,-.08],target_dist=.11, + bias=[0.,float(rng.choice([-1,1])*.055),0.],com_offset=float(rng.choice([-1,1])*.06), + mechanisms={'L1':True,'L3':True,'L5':True}) + def apply_instance(self,inst): + self.inst=inst + OffcenterPush.apply_instance(self,inst) + m=self.env.sim.model + m.body_pos[self.board_bid]=[*inst['board_xy'],envs.TABLE_Z+BOARD_HALF[2]] + m.body_quat[self.board_bid]=[1,0,0,0] + envs.set_obj_pose(self.env,'card_1',[*inst['card_xy'],BOARD_TOP+CARD_HALF[2]+.0003],yaw=inst['card_yaw']) + for k,o in enumerate(PRODUCTS): + envs.set_obj_pose(self.env,o,[-.25+.14*k,-.31,envs.TABLE_Z+PH+.001]) + bid=envs.body_id(self.env,'box_1') + if not inst['mechanisms']['L5']:m.body_ipos[bid]=[0,0,0];envs.refit_bounds(self.env,bid) + if not inst['mechanisms']['L3']: + # Initial overhang removes the flat-card obstruction; reset-time placement only. + envs.set_obj_pose(self.env,'card_1',[inst['board_xy'][0]-BOARD_HALF[0]+CARD_HALF[0]-.03,inst['board_xy'][1],BOARD_TOP+CARD_HALF[2]+.0003]) + 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=DispatchSkills(self.env,self,np.array(inst['bias']) if inst['mechanisms']['L1'] else np.zeros(3),recorder) + self.mon=dict(start_xy=self.card_pose()['xy'].copy(),max_lift=0.,max_overhang=0.,fell=False, + loaded=False,load_step=None,departed_unloaded=False,events=[],states={o:False for o in CARGO},l1_attempts=[]) + self.sim0=0;self.ncmd=0;self.budget=None + return self.sk + def in_cargo(self,o,require_support=True): + p=envs.obj_pos(self.env,o);b=envs.obj_pos(self.env,'box_1');R=_rot(_yaw(envs.obj_quat(self.env,'box_1'))) + rel=R.T@(p[:2]-b[:2]);half=PH if o in PRODUCTS else 0. + # Full footprint containment, including card corners. + if o=='card_1': + rels=(self.card_corners()[:,:2]-b[:2])@R + footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104)) + else: + rot=self.env.sim.data.body_xmat[envs.body_id(self.env,o)].reshape(3,3) + corners=np.array([p+rot@np.array([a*PH,b*PH,c*PH]) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + rels=(corners[:,:2]-b[:2])@R + footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104)) + support=any(envs.contacts_between(self.env,envs.obj_geom_ids(self.env,o),envs.obj_geom_ids(self.env,q)) for q in CARGO+('box_1',) if q!=o) + return bool(footprint and (support or not require_support) and b[2]+.015=0 else -1. + grasp=p['xy']+sign*.034*axis + floor=b[2]+HALF[2] + return self.grasp_and_bin(grasp,p['yaw'],floor-.003) + def load_product(self,o,k): + sk=self.sk;p=envs.obj_pos(self.env,o).copy();sk.set_gripper(False,8) + sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0) + approach_offset=(sk.eef_pos()[:2]-p[:2]).tolist() + sk.move_to([p[0],p[1],p[2]+.003],tol=.002,max_steps=120) + offset=(sk.eef_pos()[:2]-p[:2]).tolist() + sk.set_gripper(True,15);sk.move_to([p[0],p[1],envs.TABLE_Z+.19]) + held=sk.holding(o) + self.mon['l1_attempts'].append(dict(item=o,offset=offset,approach_offset=approach_offset,correction=self.sk.correction.tolist(),held=bool(held),step=sk.n_steps)) + if not held:sk.set_gripper(False,8);return False + b=envs.obj_pos(self.env,'box_1');xy=[b[0],b[1]+(-.075 if k==0 else .075)] + sk.move_to([*xy,envs.TABLE_Z+.20]);sk.move_to([*xy,envs.TABLE_Z+.058],speed=.1) + sk.set_gripper(False,12);sk.move_to([*xy,envs.TABLE_Z+.22]);return self.in_cargo(o) + def execute(self,inst,params): + if 'mode' not in params: + return OffcenterPush.execute(self,inst,params) + mode=params['mode'];self.sk.correction=np.asarray(params.get('correction',[0,0,0]),dtype=float) + for k,o in enumerate(PRODUCTS): + if not self.load_product(o,k):return + if mode=='adaptive': + self.sk.correction+=np.array([*self.mon['l1_attempts'][-1]['approach_offset'],0.]) + if mode=='naive': + CardEdge.execute(self,inst,dict(mode='grasp')) + else: + CardEdge.execute(self,inst,dict(mode='edge',overhang=.03)) + self.sk.hold(10) + if not all(self.in_cargo(o) for o in CARGO):return + if mode=='adaptive': + OffcenterPush.adaptive_attempt(self,inst,params.get('c',0.)) + if not self.in_cargo('card_1'):self.repair_card() + else:OffcenterPush.execute(self,inst,dict(c=params.get('c',0.))) + p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.23]);self.sk.set_gripper(False,8) + def outcome(self,inst): + self.sk.hold(30) + p=envs.obj_pos(self.env,'box_1');yaw=_yaw(envs.obj_quat(self.env,'box_1'));fit=box_fit(p[:2],yaw,self.target_xy(inst)) + cargo={o:self.in_cargo(o) for o in CARGO} + velocities=[] + for o in CARGO+('box_1',): + adr=self.env.sim.model.jnt_dofadr[self.env.sim.model.joint_name2id(self.env.objects_dict[o].joints[0])] + velocities.append(self.env.sim.data.qvel[adr:adr+6].copy()) + static=all(np.linalg.norm(v[:3])<.01 and np.linalg.norm(v[3:])<.15 for v in velocities) + m=self.env.sim.model + robot=[g for g in range(m.ngeom) if (m.geom_id2name(g) or '').startswith(('robot0_','gripper0_'))] + touching=any(envs.contacts_between(self.env,robot,envs.obj_geom_ids(self.env,o)) for o in CARGO+('box_1',)) + upright=envs.obj_upright_cos(self.env,'box_1')>.95 + success=bool(all(cargo.values()) and self.mon['loaded'] and not self.mon['departed_unloaded'] and fit['inside'] and static and upright and not touching and self.sk.grip<0) + bad=[m for m in self.sk.box_moves if m.get('bad') and not m.get('gripper_open') and self.mon['load_step'] is not None and m['step']>=self.mon['load_step']] + return copy.deepcopy(dict(success=success,cargo=cargo,loaded_in_start=bool(self.mon['loaded']),load_step=self.mon['load_step'],departed_unloaded=self.mon['departed_unloaded'],inside=fit['inside'],static=bool(static), + failure=None if success else 'cargo' if not all(cargo.values()) else 'loading_order' if not self.mon['loaded'] else 'delivery', + stages={**cargo,'loaded_in_start':self.mon['loaded'],'delivery':fit['inside']},events=self.mon['events'], + l1_attempts=self.mon['l1_attempts'],card_closes=self.sk.closes,card_lift=self.mon['max_lift'], + box_moves=self.sk.box_moves,l5_triggered=bool(bad),yaw_deg=float(np.degrees(yaw)), + sim_s=self.sk.n_steps*.05,commands=self.sk.n_commands,touching=bool(touching),upright=bool(upright), + detail='Cargo in tray: '+str(cargo)+'; tray inside delivery rectangle: '+str(fit['inside'])+'.')) + def default_params(self,inst):return dict(mode='naive') + def oracle_params(self,inst):return dict(mode='oracle',correction=(inst['bias'] if inst['mechanisms']['L1'] else [0,0,0]),c=inst['com_offset'] if inst['mechanisms']['L5'] else 0.) + def adapt_params(self,inst,history): + # Calibration estimate from the measured failed grasp, not hidden bias. + offsets=[x['offset'] for h in history for x in h['outcome']['l1_attempts']] + calibrations=[np.array(x.get('correction',h['params'].get('correction',[0,0,0])))+np.array([*x.get('approach_offset',x['offset']),0.]) for h in history for x in h['outcome']['l1_attempts']] + corr=np.mean(calibrations[-2:],axis=0).tolist() if calibrations else history[-1]['params'].get('correction',[0,0,0]) + moves=[m for h in history for m in h['outcome']['box_moves']] + return dict(mode='adaptive',correction=corr,c=self.bracket(moves)) + def blind_params(self,inst,attempt,rng):return dict(mode='naive',correction=[*rng.normal(0,.005,2),0.]) + def run_scripted(self,*args,**kwargs):return LFFTask.run_scripted(self,*args,**kwargs) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_shim_relay.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_shim_relay.py new file mode 100644 index 0000000000000000000000000000000000000000..fd652431d13fab78894bb1bc440d458e66335467 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_shim_relay.py @@ -0,0 +1,202 @@ +"""Shared support tool transferred between two trays; retain the first placement. + +The single handled wedge raises either gravity-hinged tray through collision. +A shallow pocket retains cargo after the wedge is removed; a flat placement slides. +Guide rails reject a sideways wedge. No latch/event-driven forces or pose writes. +""" +import numpy as np +import copy +import xml.etree.ElementTree as ET +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml,register_generated,_wrap,_fmt +from ..skills import Skills +from ..task_base import LFFTask,register_task + +CARGO=('cargo_red_1','cargo_blue_1');WEDGE='wedge_1';H=.018 +def safe_list(v):return v.round(4).tolist() + +def visible(xml): + root=ET.fromstring(xml) + for body in root.findall('.//body'): + for g in list(body.findall('geom')): + if g.get('group')=='0': + v=copy.deepcopy(g);v.attrib.pop('name',None);v.set('mass','0');v.set('group','1');v.set('contype','0');v.set('conaffinity','0');body.append(v) + return ET.tostring(root,encoding='unicode') + +def platform_xml(name): + parts=[''] + # Two guide rails below the platform; only a narrow longitudinal wedge passes. + for k,y in enumerate((.075,.145)):parts.append(f'') + b=['', + '', + ''] + # Raised pocket walls: actual support, not a hidden success predicate. + for pos,size in [((.030,.040,.018),(.029,.004,.012)),((.030,.100,.018),(.029,.004,.012)),((.001,.070,.018),(.004,.026,.012)),((.059,.070,.018),(.004,.026,.012))]: + b.append(f'') + return ''+''.join(parts)+''+''.join(b)+'' + +def wedge_xml(): + # Ramp descends toward the leading +x edge; the rear plateau supports the board. + vertices=[(x,y,z) for y in (-.024,.024) for x,z in [(-.04,.006),(.09,.006),(.09,.012),(0,.10),(-.04,.10)]] + v=' '.join(_fmt(p) for p in vertices) + root=_wrap('relay_wedge','' + '' + '' + '' + '',.05,.17) + return root.replace('',f'') + +class RelaySkills(Skills): + def __init__(self,env,task,recorder=None): + super().__init__(env,bias=task.inst['bias'],recorder=recorder);self.task=task;self.correction=np.zeros(3) + def move_to(self,target,*a,**kw): + r=super().move_to(np.array(target)-self.correction,*a,**kw);r['pos']=np.round(self.eef_pos()-self.bias,4).tolist();return r + 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 ShimRelay(LFFTask): + name='lh_shim_relay';level='L2';category='state_restoration';failure_causes=('L1','L4','L2');failure_types=failure_causes + protocol='cross';max_attempts=5;agent_max_steps=500 + instruction=('Put the red parcel on the right tray and the blue parcel on the left tray. There is one handled ' + 'support wedge available for the two trays. Finish with both parcels resting entirely on their ' + 'trays, the wedge returned to its yellow parking area, and the gripper open and clear. Each tray ' + 'has a shallow retaining pocket and guide rails underneath.') + instruction_indirect=('Deliver the warm-colored parcel to the robot’s right tray and the cool-colored parcel to its left tray. Leave both released and stable, return the single handled support to the marked parking area, and finish with the gripper open and clear.');capabilities=('Perceive','Reason','Plan','Restore') + def make_bddl(self): + objs=[] + for n,c in enumerate(CARGO): + cat=register_generated('LffRelayCargo'+('Red' if n==0 else 'Blue'),box_xml('relay_cargo'+str(n),(H,H,.022),(.8,.15,.12,1) if n==0 else (.12,.3,.85,1),friction=(.07,.005,.0001))) + objs.append((c,cat,'cargo'+str(n),(-.35+n*.20,.02,-.34+n*.20,.03))) + w=register_generated('LffRelayWedge',visible(wedge_xml()));objs.append((WEDGE,w,'wedge',(-.26,.31,-.25,.32))) + fx=[] + for n in range(2): + cat=register_generated('LffRelayPlatform'+('Right' if n==0 else 'Left'),visible(platform_xml('relay'+str(n))),free=False) + fx.append(('platform_'+str(n+1),cat,'platform'+str(n),(.15+n*.18,-.35,.16+n*.18,-.34))) + mark=register_generated('LffRelayParking',_wrap('parking','',.0005,.17),free=False) + fx.append(('parking_1',mark,'parking',(.2,.1,.21,.11))) + return write_bddl(self.name,self.instruction,objs,fx) + def __init__(self,cam_res=None): + super().__init__(cam_res);m=self.env.sim.model + self.pb=[m.body_name2id(self.env.fixtures_dict['platform_'+str(n+1)].root_body) for n in range(2)] + self.j=[m.joint_name2id('platform_'+str(n+1)+'_hinge') for n in range(2)] + self.qa=[int(m.jnt_qposadr[j]) for j in self.j];self.tb=[int(m.jnt_bodyid[j]) for j in self.j] + self.platform_geoms={k for k in range(m.ngeom) if (m.geom_id2name(k) or '').startswith('platform_')};self.wedge_geoms=set(envs.obj_geom_ids(self.env,WEDGE)) + def sample_instance(self,seed): + rng=np.random.default_rng(seed);bias=[0,float(rng.choice([-1,1]))*.055,0] + return dict(seed=seed,bias=bias,platforms=[[-.02,-.29],[-.02,.29]],park=[-.24,0],starts=[[-.30+float(rng.uniform(-.012,.012)),y+float(rng.uniform(-.012,.012)),.923] for y in (.13,-.13)]) + def apply_instance(self,i): + self.inst=i;m,d=self.env.sim.model,self.env.sim.data + for n,b in enumerate(self.pb):m.body_pos[b]=[*i['platforms'][n],.9];m.body_quat[b]=[1,0,0,0] if n==0 else [0,0,0,1];d.qpos[self.qa[n]]=0;m.jnt_range[self.j[n]]=np.radians([0,18]) + envs.set_obj_pose(self.env,WEDGE,[*i['park'],.901]);envs.scale_mass(self.env,WEDGE,.12) + for n,c in enumerate(CARGO):envs.set_obj_pose(self.env,c,i['starts'][n]) + m.body_pos[m.body_name2id(self.env.fixtures_dict['parking_1'].root_body)]=[i['park'][0]-.03,i['park'][1],.9007] + 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,80) + self.sk=RelaySkills(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);self.probing=False;self.obstacle_hits=0;self.last_insert=None;return self.sk + def board_point(self,n,local): + d=self.env.sim.data;return d.body_xpos[self.tb[n]]+d.body_xmat[self.tb[n]].reshape(3,3)@np.array(local) + def cargo_ok(self,n): + d=self.env.sim.data;p=envs.obj_pos(self.env,CARGO[n]);R=d.body_xmat[self.tb[n]].reshape(3,3);O=d.body_xmat[envs.body_id(self.env,CARGO[n])].reshape(3,3) + points=np.array([R.T@(p+O@np.array([a*H,b*H,c*.022])-d.body_xpos[self.tb[n]]) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + return bool(np.all(np.abs(points[:,0])<.076) and np.all((points[:,1]>.004)&(points[:,1]<.156)) and .002.03 and self.obstacle_hits>0));self.label('Wedge insertion contact') + if wrong: + s.move_to(goal,yaw=yaw,speed=.04);s.move_to([*goal[:2],1.22]);s.hold(20) + else: + s.set_gripper(False,10);s.move_to([*s.eef_pos()[:2],1.22]);s.hold(100) + def extract(self,n): + s=self.sk;k=self.knob();s.set_gripper(False,8);s.move_to([*k[:2],1.22],yaw=0);s.move_to(k,speed=.06);s.set_gripper(True,20) + s.move_to([k[0]-.20,k[1],k[2]],speed=.03);s.move_to([k[0]-.20,k[1],1.22],speed=.08);s.hold(100) + def pick_cargo(self,n): + s=self.sk;p=envs.obj_pos(self.env,CARGO[n]);s.set_gripper(False,8);s.move_to([*p[:2],1.23],yaw=0);s.move_to(p,speed=.08);s.set_gripper(True,20);s.move_to([*p[:2],1.23],speed=.08);self.label('Parcel pickup check '+str(n));return bool(s.holding(CARGO[n])) + def put_cargo(self,n,pocket): + s=self.sk;local=[.030,.07,.027] if pocket else [-.04,.11,.027];goal=self.board_point(n,local) + off=envs.obj_pos(self.env,CARGO[n])-s.eef_pos();goal-=off + s.move_to([*goal[:2],1.23]);s.move_to(goal,speed=.06);s.set_gripper(False,10);s.move_to([*goal[:2],1.24]);s.hold(80) + 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 trays, one shared support wedge') + if mode=='oracle':s.correction=s.bias.copy() + else: + k=self.knob();q=np.array([*k[:2],1.20]);s.move_to(q);obs=(s.eef_pos()-q)*[1,1,0] + ok=self.pick_wedge();self.traps['L1']=not ok;self.label('L1: support-wedge grasp missed') + if mode in ('naive','blind'): + if not ok:return + else:s.correction=obs + if not self.pick_wedge():self.label('Wedge pickup failed');return + self.recovered['L1']=True + if mode!='oracle': + self.insert(0,True);self.traps['L4']=self.last_insert['blocked'];self.label('L4: sideways wedge blocked at the support slot') + if mode in ('naive','blind'):return + if not s.holding(WEDGE):self.label('Wrong-orientation recovery lost wedge');return + self.align_wedge();self.park_wedge();self.label('Regrasp the wedge after contact shifted it in the fingers') + if not self.pick_wedge():return + self.insert(0);self.recovered['L4']=bool(abs(np.degrees(self.env.sim.data.qpos[self.qa[0]]))<5);self.label('Aligned wedge insertion check') + if not self.recovered['L4']:return + if not self.pick_cargo(0):return + self.put_cargo(0,mode=='oracle');self.label('First parcel placed') + if not self.cargo_ok(0):return + self.extract(0);self.traps['L2']=not self.cargo_ok(0);self.label('L2: reclaiming support lost the first placement') + self.insert(1);self.label('Shared wedge transferred to the second tray') + if not self.pick_cargo(1):return + self.put_cargo(1,True) + if not self.cargo_ok(0): + if not self.pick_cargo(0):self.label('Fallen parcel pickup failed');return + off=envs.obj_pos(self.env,CARGO[0])-s.eef_pos();goal=np.array([-.30,.13,.925])-off + s.move_to([*goal[:2],1.23]);s.move_to(goal,speed=.08);s.set_gripper(False,10);s.move_to([*goal[:2],1.23]);s.hold(30);self.label('Park the fallen parcel before raising its tray') + self.extract(1);self.insert(0) + if not self.pick_cargo(0):return + self.put_cargo(0,True);self.label('Restore first parcel inside the retaining pocket') + self.extract(0) + else:self.extract(1) + self.park_wedge();self.recovered['L2']=self.cargo_ok(0);s.set_gripper(False,8);s.move_to([-.40,0,1.25]);s.hold(50);self.label('Both parcels retained after support returned') + def outcome(self,i): + self.sk.hold(100);p=envs.obj_pos(self.env,WEDGE);v=dict(red=self.cargo_ok(0),blue=self.cargo_ok(1),wedge_parked=bool(np.linalg.norm(p[:2]-i['park'])<.020 and .895.98),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,c)[1]:envs.free_joint_addr(self.env,c)[1]+6])<.04 for c in (*CARGO,WEDGE)) + return dict(success=bool(all(v.values()) and static),stages=v,static=bool(static),traps=self.traps.copy(),recovered=self.recovered.copy(),detail=str(v)) + 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);p={'mode':kind} + if kind=='blind':p['jitter']=(np.random.default_rng(seed+n).uniform(-.008,.008,3)*[1,1,0]).tolist() + self.execute(inst,p);o=self.outcome(inst);hist.append(dict(attempt=n+1,params=p,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_auto_001_opus/lff/source_closure/lffbench/tasks/lh_tidy_stack.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_tidy_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..7eb80b6f3a418bf965b10bad15f99797241128a5 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_tidy_stack.py @@ -0,0 +1,1260 @@ +"""LH lh_tidy_stack v2 (2026-10-16): tidy the table -- stack the four storage boxes (red, green, blue, yellow; alike, +6 x 6 x 5 cm) into one pile on a grey mat, in any order, then stand the cup on top. In 18 of every 20 instances one box +(random colour) is an empty, soft carton: it carries one thing, but as soon as a second thing comes to rest above it, +it gives way -- standing it folds sideways, lying on a side face it is crushed flat -- and everything above it slides +off the pile: the stage that made the pile two higher destroys the stage before it. + +Family: long-horizon self-disturbance ("state_restoration"): the later stages' ordinary action (putting the next box on) +undoes earlier ones; the agent has to see which box gave way, take it out of the pile and rebuild with it on top (within +an attempt) or remember its colour (across attempts). The cheapest explanation of a toppled pile ("I did not centre the +box", "I let go too high") is wrong: perfectly centred boxes let go 5 mm above the pile topple it just the same +(control naive_centred). + +v1 -> v2 (Sonnet 5.5 pilot np3_lh_tidy_stack, seeds 3000 / 3002 / 3003, k=3; logs measured by the coordinator and +replayed here): in s3002 attempt 2 boxes that had fallen on their sides were restacked lying (a lying box looks the +same: they are nearly cubes); the soft box lay on its side at level 2 under two boxes and the cup, and the v1 law, which +measured the load along the box axis only, saw -0.06 N and never fired -> judged a success. Sonnet also presses what it +puts down 0.5-1.5 cm below contact (its own logs: the gripper stops 0.6-1.5 cm above the commanded release height), and +in s3003 a cup pressed onto the soft box on top -- where it belongs -- crushed it under one item (v1: 2.45 N). v2: + (1) the load is measured along the world vertical, whichever face the carton rests on (`vertical_loads`: the downward + push on its upper side, limited by the support under it); + (2) a carton lying on a side face (seam vertical) cannot fold under gravity, so it is crushed instead: both halves + flatten towards the face they rest on, the upper half by 70 % and the lower by 30 % (runtime geom sizes + + envs.refit_bounds), the top becomes a 2-3 cm step and what is on it tips off; + (3) only what rests on the carton counts, at most with its own weight (+0.3 N for impacts): something the robot still + holds, the robot pushing down through an item it has just let go of, and the fingers pressing the held carton + itself onto something do not count; the robot's own fingers / hand pushing on its top do (a hard press may crush + it: the closed gripper 3 mm onto its top does; logged as cause "press", not counted as the trap unless it costs a + stage); + (4) items weigh 200 g (box and cup; v1 180 / 160 g) and f_crit = 3.45 N: one item 1.96 N, two 3.92 N; + (5) the rigid boxes' joints are stiffer (20 Nm/rad, stiff limit; at 3 Nm/rad Sonnet's cup press on a 4-high pile bent + every box ~4 deg and the pile leaned 10 deg in the replay); after a fold the carton straightens along a rest + shape that moves back to straight over 1.5 s (released at once, a stiff spring flipped it onto its side); + (6) stacking tolerance 3 cm instead of 2.5 (a correctly stacked oracle_noise pile failed at 2.51 cm). +v1 code and results: scratchpad lh_tidy_stack_v1.py, results/_old/lh_tidy_stack_v1/. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey mat (13 x 13 cm, visual only), centre x in [-0.11, -0.05], |y| <= 5 cm; + * four storage boxes (6 x 6 x 5 cm, bright red / green / blue / yellow with a darker lid line, 200 g; friction 0.5) + 15, 18.5, 22 and 25.5 cm (+-1 cm) from the mat centre, at random angles 30-150 deg from forward on its left and right, + yaw +-17 deg, colours shuffled; + * a dark teal cup (5 cm wide, 7 cm tall, 200 g) on the robot's side of the mat, 23-26 cm away. + +Hidden variable: which box is the soft carton (60 g; mass is not observable). Instances come in balanced blocks of 20 +consecutive seeds ((seed x 7) mod 20 = k): k >= 18 benign (no soft box); otherwise the soft box is the one at rank +k mod 4 of the distance to the mat (0 = nearest = the bottom of a nearest-first pile, 3 = the top): 5 / 5 / 4 / 4. +A nearest-first stacker therefore meets it below the top in 14 of 20 instances. + +Mechanism (physics; nothing is teleported). Every box is built alike: a lower half (the root body) and an upper half +joined by a ball joint at mid-height (the seam is invisible). In the three rigid boxes the joint is locked (range +0.003 rad, stiffness 3 Nm/rad). The soft carton follows a load law (`_law_step`, every MuJoCo substep): its compressive +load (above, low-passed with 0.4 s) is compared with f_crit (instance key "f_crit": the fragility knob). Below it the +joint keeps 3 Nm/rad (one box 1.3 cm off-centre tilts it < 1 deg: looks like the rigid boxes). Above it: + * standing or upside down (seam horizontal): the joint stiffness drops to 0.03 Nm/rad -- a column with m g h ~ 0.27 + Nm/rad on it is unstable, centred or not -- and its rest shape bends 12 deg towards a per-instance side: the upper + half folds sideways (38-54 deg measured, joint limit 54 deg) and what is on it slides off; + * lying on a side face (seam vertical): crushed as above within ~0.1 s. +Unloaded (< 0.5 N) for 0.3 s it recovers over ~1.5 s (still visibly bent / flattened in the images of the next one or +two commands). One item on it is carried (a box let go 4 cm above adds < 0.5 N to the filtered load), two are not. So +the pile survives only with the soft box on top (carrying just the cup): soft at level 1 -> it gives way when box 3 +lands (boxes 2 and 3 fall), level 2 -> when box 4 lands, level 3 -> when the cup lands (box 4 and the cup fall; standing, +the cup ends on its side, which a top-down gripper cannot undo, so that attempt cannot be repaired). Measured (v2, naive +without rebuilding, the 14 trap instances of seeds 1000-1019): standing 14/14 folded at exactly that stage, the soft +box stayed upright in the pile 14/14 (fold 37-55 deg), the cup fell 4/4 at level 3; lying (control naive_lying: the +soft box starts on a side face and is stacked lying) crushed at exactly that stage in every trap instance. + +Why not the linear spring of the brief (a ball joint with one fixed stiffness k): the load that k must carry (the cup) +and the load that must topple it (one more box) differ by a factor of ~2-3, and an inverted pendulum close to its +critical load amplifies placement offsets (tilt = W e / (k - m g h)); measured (results/lh_tidy_stack/linear.json, +instance key law="linear"): no k gives both a soft box that carries the cup on top without sagging and a pile that +topples however carefully it is centred (k <= 0.25 Nm/rad: the correct pile fails 5-10/10; k = 0.5: a centred +level-3 soft box carries box + cup, 2/2). A load threshold (walls that +hold until they buckle) keeps the soft box looking and behaving rigid until the second item, independent of centring. + +Success predicate (from the instruction): all four boxes in one chain -- the bottom one on the mat (lowest point <= 8 mm +above the table, centre within 3.5 cm of the mat centre in x and y: its footprint on the 13 cm mat), each next one +resting on the previous (its lowest point within 1 cm of the top of the box below, centres within 3 cm), every box +flat (some face within 10 deg of horizontal: a fallen box cannot be stood up again by a vertical gripper, so a box on +its side counts), not bent (kink <= 10 deg) and not crushed (<= 15 %) --; the cup upright (<= 10 deg) on the top box +(bottom within 1 cm, centre within 3 cm); nothing held, the gripper not touching anything, the scene static (< 3 mm +in 1 s). Tolerance: 3 cm = the box's half width, i.e. the upper box's centre of mass is over the lower box's top face +(physically resting on it; the static check rejects anything that does not stay). Sonnet's measured placement error is +0.4-1.3 cm, so two placements differ by up to 2.6 cm plus a few mm of landing drift (v2: the 2.5 cm of v1 failed one +correctly stacked oracle_noise pile, seed 1008, at 2.51 cm). + +Event monitor (server log only; F1 gives the agent only success / failure): stage predicates red / green / blue / +yellow (box in the pile) and cup (cup on a complete pile), debounced over 0.5 s: achieved / lost (cause buckle / robot +/ picked_up / other) / restored; `buckle` (= trap fired: load, the robot's share of it, fold or crush, lying, level, +items on it), `collapse` (a buckle that cost a stage). Outcome: success, failure (none / held / touching / collapsed / +regressed / not_stacked / cup_fallen / cup_not_on_top / not_static), trap_fired, recovered_in_attempt, n_buckles, +n_collapses, buckle_how, max_kink_deg, max_crush, detail (F2). The law's state rides along in task.mon["law"]; a +crushed carton's geom sizes are restored at every reset. + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import mujoco +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 + +TZ = envs.TABLE_Z +G = 9.81 +COLOURS = ["red", "green", "blue", "yellow"] +BOXES = [f"box_{c}_1" for c in COLOURS] +COL = dict(zip(BOXES, COLOURS)) +CUP, MAT = "cup_1", "mat_1" +RGBA = {"red": (0.80, 0.16, 0.13, 1.0), "green": (0.17, 0.58, 0.25, 1.0), "blue": (0.16, 0.34, 0.80, 1.0), + "yellow": (0.90, 0.74, 0.14, 1.0)} +CUP_RGBA = (0.10, 0.45, 0.50, 1.0) # dark teal ceramic, darker inside +CUP_INSIDE = (0.20, 0.20, 0.19, 1.0) +MAT_RGBA = (0.45, 0.45, 0.47, 1.0) + +# ---------------------------------------------------------------- boxes (all four built alike: base + upper part) +HX, HY, H = 0.030, 0.030, 0.050 # 6 x 6 x 5 cm (the gripper opens 7.9 cm) +HB = 0.025 # base part height = height of the seam (ball joint) above the bottom: mid-height, so the upper +# half can fold ~56 deg before its edge reaches the surface below +HU = H - HB +BOX_MASS = 0.20 # a filled storage box (v1: 0.18) +SOFT_MASS = 0.06 # the empty carton (mass is not observable by the agent) +BOX_MU = 0.5 +CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"' +# soft-carton law (see SoftLaw): stiff until the compressive load through its walls exceeds F_CRIT, then soft +K_HI = 3.0 # Nm/rad: the intact soft carton (one box 1.3 cm off-centre tilts it ~0.5 deg; a cup pressed onto it +# bends it ~4 deg) +K_RIGID = 20.0 # Nm/rad + a stiff joint limit: the rigid boxes (at 3 Nm/rad a cup pressed onto a 4-high pile bent every +# box 4 deg and the pile leaned 10 deg -- replay of pilot s3003 on v2; at 20 for the soft carton too +# its folds flipped it onto its side 4/14 times) +K_LO = 0.03 # Nm/rad: buckled (one box on it destabilises it: m g h ~ 0.12 Nm/rad) +DAMP = 0.01 +F_CRIT = 3.45 # N, vertical load from above (resting things + whatever the robot pushes or holds onto it): one +# item weighs 1.96 N and a held item pressed onto the carton adds <= ~0.9 N before it slips in the +# fingers (measured, t10_press); two items weigh 3.92 N (v1: 2.45 N with 1.77 / 1.57 N items) +F_REL = 0.5 # N: unloaded below this ... +REL_T = 0.3 # ... for this long -> it springs back +TAU_F = 0.4 # s: low-pass of the load (impacts of a box let go 1-4 cm above do not count) +K_RISE = 1.5 # s: the folded carton straightens along a reference that moves back to straight in this time +BEND_REF = np.radians(12.0) # reference bend of the buckled carton (the weak side; direction per instance) +RANGE_SOFT, RANGE_RIGID = 0.95, 0.003 # rad: kink limit (54 deg) of the soft carton; the rigid boxes are locked +# v2: a carton lying on a side face (its seam vertical) cannot fold under gravity; it is crushed instead: both halves +# flatten towards the surface below, the upper half much more, so the top becomes a 2-3 cm step and what is on it +# tips off (geom sizes changed at runtime + envs.refit_bounds) +CRUSH_ALPHA = (0.30, 0.70) # fraction of the height lost by the base half / the upper half when fully crushed +CRUSH_TAU = (0.08, 0.7) # s: crushing / recovering +FOLD_MIN_UP = 0.7 # |seam normal . vertical| above this: the fold (upright or upside down); below: the crush + +# ---------------------------------------------------------------- cup +CUP_R, CUP_H, CUP_MASS = 0.025, 0.070, 0.20 # v1: 0.16 + +# ---------------------------------------------------------------- mat and layout +MAT_HALF = 0.065 # 13 x 13 cm +MAT_X, MAT_Y = (-0.11, -0.05), (-0.05, 0.05) +BOX_D = (0.15, 0.185, 0.22, 0.255) # distances of the four boxes from the mat centre (+- jitter) +BOX_X = (-0.33, 0.07) # world x range of the box positions (reach) +BOX_YMAX = 0.30 +BOX_YAW = 0.30 +P_BENIGN = 0.10 # 2 of every 20 consecutive seeds: no soft box + +# ---------------------------------------------------------------- predicates +TILT_OK = np.radians(10.0) +KINK_OK = np.radians(10.0) +ON_MAT = 0.035 # bottom box centre within 3.5 cm of the mat centre (x and y): its footprint is on the 13 cm mat +STACK_XY = 0.030 # centre of a box within 3 cm (= the half width) of the centre of the box below: its centre of +# mass is over the lower box's top face (v2; 2.5 cm judged a resting box 2.51 cm off as not stacked) +STACK_Z = 0.010 +CUP_XY = 0.030 +DEBOUNCE = 10 # control steps (0.5 s) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.18 +NAIVE_ERR = (0.004, 0.013) # Sonnet's placement error 0.4-1.3 cm (random direction) +NAIVE_GAP = (0.010, 0.040) # Sonnet lets go 1-4 cm above the surface +NAIVE_BIAS = (0.0, 0.020) # forward bias of the first box on the mat (oblique camera) + + +def box_xml(name, rgba): + """storage box: base part (root body, 1.6 cm) + upper part (child body) on a ball joint at the seam. Rigid boxes + get a ~0 kink range at reset; the soft carton a 31.5 deg range and the load-dependent stiffness of SoftLaw. + Inertials are replaced per instance (mass).""" + mb, mu = BOX_MASS * HB / H, BOX_MASS * HU / H + zb = -H / 2 + HB / 2 + dark = [0.72 * c for c in rgba[:3]] + [1.0] + g = [f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + f' ', + # lid line (visual only): a darker band 8 mm below the top, on all four boxes + f' ', + ' '] + return _wrap(name, "\n".join(g), H / 2, float(np.hypot(HX, HY))) + + +def cup_xml(name): + """open cup, 5 cm wide, 7 cm tall: 12 wall boxes + an octagonal base of two boxes (box contacts; a light MuJoCo + cylinder creeps on a flat surface, lh_nudge_row). Visual: a smooth cylinder with a dark inside.""" + r, h = CUP_R, CUP_H + nseg, wt, bt = 12, 0.004, 0.006 + g = [f' '] + s = r * np.sin(np.pi / nseg) + 0.0008 + rc = r * np.cos(np.pi / nseg) - wt / 2 + for k in range(nseg): + a = 2 * np.pi * k / nseg + q = [np.cos(a / 2), 0, 0, np.sin(a / 2)] + g.append(f' ') + a0 = r * 0.70 + for k, ang in enumerate((0.0, np.pi / 4)): + q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)] + g.append(f' ') + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), h / 2, r) + + +def mat_xml(name): + g = (f' ') + return _wrap(name, g, 0.0005, MAT_HALF * 1.42) + + +def free_adr(env, name): + """(qpos, dof) address of the object's FREE joint. envs.free_joint_addr takes joints[0], which for an object with a + jointed child body is the child's joint (robosuite lists the subtree's joints before the free joint it appends).""" + m = env.sim.model + for jn in env.objects_dict[name].joints: + j = m.joint_name2id(jn) + if int(m.jnt_type[j]) == 0: + return int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]) + raise KeyError(name) + + +def place(env, name, xy, yaw=0.0, surface_z=TZ, clearance=0.0005, tilt=None): + """teleport upright (yaw about z; `tilt` rad about the object's own x axis first, e.g. pi/2 = lying on a side + face -- controls only), lowest collision point `clearance` above surface_z (reset only)""" + qa, da = free_adr(env, name) + d = env.sim.data + d.qpos[qa:qa + 3] = [xy[0], xy[1], surface_z + 0.3] + q = np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]) + if tilt: + w1, z1 = q[0], q[3] + c, s_ = np.cos(tilt / 2), np.sin(tilt / 2) + q = np.array([w1 * c, w1 * s_, z1 * s_, z1 * c]) # q_yaw * q_x(tilt) + d.qpos[qa + 3:qa + 7] = q + d.qvel[da:da + 6] = 0.0 + env.sim.forward() + d.qpos[qa + 2] -= envs.obj_min_z(env, name) - (surface_z + clearance) + env.sim.forward() + + +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 _wrap_q(a, period): + """wrap an angle to [-period/2, period/2)""" + return float((a + period / 2) % period - period / 2) + + +class StackSkills(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 TidyStack(LFFTask): + name = "lh_tidy_stack" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 5 pick-and-places x ~8 commands (40) + a collapse: unstack 1-2 boxes (~16) and rebuild 3-4 (~32) + # + looking / small corrections (~30), with some margin + agent_max_steps = 150 + instruction = ("Tidy up the table: stack the four storage boxes (red, green, blue, yellow) into a single pile on the " + "grey mat, in any order you like, and then put the cup upright on top of the pile. At the end each " + "box must rest flat on the box below it (the bottom one on the mat), the cup must stand on the top " + "box, and the gripper must be open and clear of everything.") + instruction_indirect = ("Clean up the table: pile the four coloured boxes on top of each other on the dark grey " + "square, in whatever order, and finish by standing the teal mug on top of the pile. In the " + "end every box has to sit flat on the one below it (the lowest on the grey square), the mug " + "has to stand on the top box, and the gripper must be open and away from everything.") + agent_object_names = ["storage boxes (red, green, blue, yellow)", "grey mat", "cup"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, b) in enumerate(zip(COLOURS, BOXES)): + cat = register_generated(f"LffLtsBox{c.capitalize()}", box_xml(f"lff_lts_box_{c}", RGBA[c])) + objs.append((b, cat, f"box{i}_region", (-0.30 + 0.13 * i, 0.28, -0.29 + 0.13 * i, 0.29))) + cat = register_generated("LffLtsCup", cup_xml("lff_lts_cup")) + objs.append((CUP, cat, "cup_region", (-0.30, -0.29, -0.29, -0.28))) + mat = register_generated("LffLtsMat", mat_xml("lff_lts_mat"), free=False) + fx = [(MAT, mat, "mat_region", (0.0, -0.29, 0.01, -0.28))] + return write_bddl(self.name, "Stack the four boxes on the grey mat and put the cup on top", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.mat_bid = m.body_name2id(self.env.fixtures_dict[MAT].root_body) + self.jid, self.base_bid, self.upper_bid, self.base_gid, self.upper_gid = {}, {}, {}, {}, {} + for b in BOXES: + for g in envs.obj_geom_ids(self.env, b): + n = m.geom_id2name(g) + if n.endswith("_upper"): + self.upper_gid[b] = g + elif n.endswith("_base"): + self.base_gid[b] = g + self.upper_bid[b] = int(m.geom_bodyid[self.upper_gid[b]]) + self.base_bid[b] = int(m.geom_bodyid[self.base_gid[b]]) + j = next(m.joint_name2id(jn) for jn in self.env.objects_dict[b].joints if jn.endswith("_kink")) + self.jid[b] = j + # every geom of each half (collision and visual) with its compiled size / pos: the crush rescales them + self.half_geoms = {} + for b in BOXES: + hg = [] + for bid in (self.base_bid[b], self.upper_bid[b]): + gs = [g for g in range(int(m.body_geomadr[bid]), int(m.body_geomadr[bid] + m.body_geomnum[bid])) + if int(m.geom_type[g]) == 6] + hg.append((bid, gs, m.geom_size[gs].copy(), m.geom_pos[gs].copy())) + self.half_geoms[b] = hg + self.cup_gids = list(envs.obj_geom_ids(self.env, CUP)) + self.obj_bodies = {b: [self.base_bid[b], self.upper_bid[b]] for b in BOXES} + self.obj_bodies[CUP] = [envs.body_id(self.env, CUP)] + # per-geom lookup: owner index 0-3 = boxes, 4 = cup, -1 other; robot part 1 = finger, 2 = hand / arm + self.owner = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOXES): + self.owner[[self.base_gid[b], self.upper_gid[b]]] = i + self.owner[self.cup_gids] = 4 + self.part = np.zeros(m.ngeom, int) + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if "finger" in n else 2 + self.inst = None + self.law = None + self.mon = None + self.sk = None + self._sub_rob = {} + self._held = set() # owner indices (0-3 boxes, 4 cup) held by the gripper, refreshed every control step + self._rest_cap = np.inf # upper bound of the resting load on the soft carton, refreshed every control step + sim = self.env.sim + if not getattr(sim, "_lts_wrapped", False): + orig = sim.step + + def step(*a, **k): + t = getattr(sim, "_lts_task", None) + if t is not None and t.law is not None: + t._law_step() + orig(*a, **k) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lts_wrapped = True + sim._lts_task = self + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + mx, my = float(rng.uniform(*MAT_X)), float(rng.uniform(*MAT_Y)) + ca = np.pi + float(rng.uniform(-0.5, 0.5)) # the cup stands on the robot's side of the mat, 23-26 cm away + cd = float(rng.uniform(0.23, 0.26)) + cup = [mx + cd * np.cos(ca), my + cd * np.sin(ca)] + for _ in range(500): + ds = np.array(BOX_D) + rng.uniform(-0.01, 0.01, 4) + ang = rng.uniform(np.radians(30), np.radians(150), 4) * rng.choice([-1.0, 1.0], 4) + pos = np.stack([mx + ds * np.cos(ang), my + ds * np.sin(ang)], 1) + if not (np.all((pos[:, 0] >= BOX_X[0]) & (pos[:, 0] <= BOX_X[1])) and np.all(np.abs(pos[:, 1]) <= BOX_YMAX)): + continue + dd = np.linalg.norm(pos[:, None] - pos[None], axis=2) + np.eye(4) + if dd.min() < 0.12 or np.linalg.norm(pos - np.asarray(cup), axis=1).min() < 0.14: + continue + break + else: + raise RuntimeError("layout") + perm = rng.permutation(4) + start = {BOXES[i]: [float(v) for v in pos[perm[i]]] for i in range(4)} + yaw = {b: float(rng.uniform(-BOX_YAW, BOX_YAW)) for b in BOXES} + mat = np.array([mx, my]) + near = sorted(BOXES, key=lambda b: float(np.linalg.norm(np.asarray(start[b]) - mat))) + # balanced blocks of 20 consecutive seeds: 2 benign (no soft box); else the soft carton is the box at rank + # r = 0..3 (0 = nearest the mat, i.e. the bottom of a nearest-first pile; 3 = the top): 5 / 5 / 4 / 4 + k = (int(seed) * 7) % 20 + benign = k >= round(20 * (1 - P_BENIGN)) + rank = None if benign else k % 4 + soft = None if benign else near[rank] + return dict(seed=int(seed), mat=[mx, my], cup=cup, start=start, yaw=yaw, cup_yaw=float(rng.uniform(-np.pi, np.pi)), + soft=soft, soft_colour=COL[soft] if soft else None, benign=bool(benign), + soft_rank_nearest=rank, nearest_order=[COL[b] for b in near], + buckle_dir=float(np.pi / 2 if rng.random() < 0.5 else -np.pi / 2), + f_crit=F_CRIT, naive_gap=float(rng.uniform(*NAIVE_GAP)), naive_bias=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + m.body_pos[self.mat_bid] = [inst["mat"][0], inst["mat"][1], TZ + 0.0005] + for b in BOXES: + j = self.jid[b] + soft = b == inst["soft"] + M = SOFT_MASS if soft else BOX_MASS + for bid, frac, h in ((self.base_bid[b], HB / H, HB), (self.upper_bid[b], HU / H, HU)): + mm = M * frac + m.body_mass[bid] = mm + m.body_inertia[bid] = [mm * (4 * HY * HY + h * h) / 12, mm * (4 * HX * HX + h * h) / 12, + mm * (4 * HX * HX + 4 * HY * HY) / 12] + m.jnt_range[j] = [0.0, RANGE_SOFT if soft else RANGE_RIGID] + m.jnt_solref[j] = [0.02, 1.0] if soft else [0.004, 1.0] # rigid boxes: a stiff limit + m.jnt_stiffness[j] = K_HI if soft else K_RIGID + qa, da = int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]) + m.qpos_spring[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0] + d.qpos[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0] + d.qvel[da:da + 3] = 0.0 + self._set_crush(b, 0.0, 2, -1.0) # undo a crush left over from the previous attempt + place(self.env, b, inst["start"][b], yaw=inst["yaw"][b], tilt=inst.get("lying", {}).get(COL[b])) + place(self.env, CUP, inst["cup"], yaw=inst["cup_yaw"]) + self.law = None + if inst["soft"]: + self.law = dict(box=inst["soft"], f=0.0, fmax=0.0, buckled=False, n=0, rel_t=0.0, t=0.0, buckles=[], + f_crit=float(inst.get("f_crit", F_CRIT)), dir=float(inst["buckle_dir"]), + mode=str(inst.get("law", "threshold")), how=None, crush=0.0, crush_set=0.0, + crush_axis=2, crush_sign=-1.0, f_rest=0.0, f_robot=0.0) + if self.law["mode"] == "linear": # control only: the brief's fixed-stiffness spring (no load threshold) + m.jnt_stiffness[self.jid[inst["soft"]]] = float(inst["k_lin"]) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.law = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = StackSkills(self.env, self, recorder=recorder) + self._sub_rob = {} + self._held = set() + self._rest_cap = np.inf + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ soft-carton law + def _part_axial(self, gid, axis): + """sum of contact forces on geom gid (from any other geom), projected on `axis` (world)""" + m, d = self.env.sim.model, self.env.sim.data + n = d.ncon + if not n: + return 0.0 + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + idx = np.nonzero((g1 == gid) | (g2 == gid))[0] + tot = 0.0 + f6 = np.zeros(6) + for i in idx: + mujoco.mj_contactForce(m._model, d._data, int(i), f6) + fw = d.contact[int(i)].frame.reshape(3, 3).T @ f6[:3] # force on geom2, world frame + tot += float(fw @ axis) * (-1.0 if g1[i] == gid else 1.0) + return tot + + def vertical_loads(self, b): + """vertical contact forces on box b (N), whichever face it rests on: (resting, robot, held, support). + resting = downward push on its upper side (contact point above its centre) from things resting on it; + robot = the same from the robot's own fingers / hand pushing on it (not counted while the robot holds b + itself); held = the same from something the robot holds (pressing it down onto b); support = upward push on + its lower side. Its two halves never touch (parent and child), so only real contacts count.""" + m, d = self.env.sim.model, self.env.sim.data + n = d.ncon + if not n: + return 0.0, 0.0, 0.0, 0.0 + gb, gu = self.base_gid[b], self.upper_gid[b] + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + idx = np.nonzero((g1 == gb) | (g1 == gu) | (g2 == gb) | (g2 == gu))[0] + if not len(idx): + return 0.0, 0.0, 0.0, 0.0 + cz = float(d.xpos[self.base_bid[b]][2]) # the root body sits at the box's centre + held = self._held + b_held = BOXES.index(b) in held + rest = robot = via = sup = 0.0 + f6 = np.zeros(6) + for i in idx: + c = d.contact[int(i)] + mujoco.mj_contactForce(m._model, d._data, int(i), f6) + fz = float(c.frame.reshape(3, 3)[:, 2] @ f6[:3]) # world z of the force on geom2 + mine1 = g1[i] in (gb, gu) + fz = -fz if mine1 else fz # force on box b + other = int(g2[i] if mine1 else g1[i]) + pz = float(c.pos[2]) + if pz > cz + 0.004 and fz < 0.0: + o = self.owner[other] + if self.part[other] > 0: + if not b_held: + robot -= fz + elif o >= 0 and o in held: + via -= fz + else: + rest -= fz + elif pz < cz - 0.004 and fz > 0.0: + sup += fz + # what rests on it pushes at most with its own weight: the robot pressing down through an item it has let go + # of (Sonnet releases with the cup pushed up against the hand, pilot s3003) is not a resting load + rest = min(rest, self._rest_cap) + return rest, robot, via, sup + + def compression(self, b): + """compressive force (N) on the carton, (total, resting): the downward push on its upper side from things + resting on it plus the robot's fingers / hand pushing directly on it, limited by the support under it -- + along the world vertical, whichever face it rests on (v1 measured it along the box axis only: a carton lying + on its side never buckled). Something the robot still holds does not count: Sonnet presses what it puts down + 0.5-1.5 cm below contact (pilot), which must not crush a carton that will carry the item once let go.""" + rest, robot, via, sup = self.vertical_loads(b) + return float(min(rest + robot, sup)), float(min(rest, sup)) + + def _law_step(self): + """per MuJoCo substep: low-pass the compressive load; above f_crit the carton gives way -- standing or upside + down it folds (its kink joint loses its stiffness, its rest shape bends towards its weak side and the load + topples it), lying on a side face it is crushed (both halves flatten, the upper half more); unloaded for + REL_T it slowly recovers its shape""" + law = self.law + b = law["box"] + m = self.env.sim.model + dt = float(m.opt.timestep) + tot, rest = self.compression(b) + law["f"] += (tot - law["f"]) * dt / TAU_F + law["f_rest"] += (rest - law["f_rest"]) * dt / TAU_F + law["fmax"] = max(law["fmax"], law["f"]) + j = self.jid[b] + qa = int(m.jnt_qposadr[j]) + if law["mode"] == "linear": # control: constant stiffness; a "buckle" = the kink passes 15 deg (re-arms < 5) + kk = self.kink(b) + if not law["buckled"] and kk > np.radians(15.0): + law["buckled"] = True + law["n"] += 1 + law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2))) + self._on_buckle() + elif law["buckled"] and kk < np.radians(5.0): + law["buckled"] = False + law["t"] += dt + return + if not law["buckled"]: + if law["f"] > law["f_crit"]: + law["buckled"] = True + law["n"] += 1 + law["rel_t"] = 0.0 + R = self.env.sim.data.xmat[self.base_bid[b]].reshape(3, 3) + law["unbend_q0"] = None + if abs(R[2, 2]) >= FOLD_MIN_UP: # seam horizontal: fold + law["how"] = "fold" + u = R.T @ np.array([np.cos(law["dir"]), np.sin(law["dir"]), 0.0]) + ax = np.array([-u[1], u[0], 0.0]) + ax /= max(np.linalg.norm(ax), 1e-9) + m.qpos_spring[qa:qa + 4] = [np.cos(BEND_REF / 2), *(np.sin(BEND_REF / 2) * ax)] + else: # seam vertical (lying on a side face): crush towards the face it rests on + law["how"] = "crush" + k = int(np.argmax(np.abs(R[2, :2]))) + law["crush_axis"] = k + law["crush_sign"] = -float(np.sign(R[2, k]) or 1.0) # local direction of "down" along axis k + # cause: "load" = what rests on it is enough by itself (>= 60 % of f_crit, i.e. more than one item); + # "press" = the robot's own push made the difference (a hard press with the gripper) + cause = "load" if law["f_rest"] >= 0.6 * law["f_crit"] else "press" + law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2), how=law["how"], + resting_N=round(law["f_rest"], 2), cause=cause)) + self._on_buckle() + elif law["f"] < F_REL: + law["rel_t"] += dt + if law["rel_t"] > REL_T: + law["buckled"] = False + # straighten smoothly: the rest shape starts at the current bend and moves back to straight over + # K_RISE (a stiff spring released at once from a 40-50 deg bend flips the light carton over) + q0 = np.array(self.env.sim.data.qpos[qa:qa + 4], float) + q0 = q0 / max(np.linalg.norm(q0), 1e-9) * (1.0 if q0[0] >= 0 else -1.0) + law["unbend_q0"], law["unbend_s"] = q0.tolist(), 0.0 + m.qpos_spring[qa:qa + 4] = q0 + else: + law["rel_t"] = 0.0 + k = float(m.jnt_stiffness[j]) + if law["buckled"] and law["how"] == "fold": + m.jnt_stiffness[j] = k + (K_LO - k) * min(1.0, dt / 0.02) + else: + m.jnt_stiffness[j] = K_HI + if law.get("unbend_q0") is not None: + law["unbend_s"] = min(1.0, law["unbend_s"] + dt / K_RISE) + q = (1.0 - law["unbend_s"]) * np.asarray(law["unbend_q0"]) + law["unbend_s"] * np.array([1.0, 0, 0, 0]) + m.qpos_spring[qa:qa + 4] = q / np.linalg.norm(q) + if law["unbend_s"] >= 1.0: + law["unbend_q0"] = None + target = 1.0 if (law["buckled"] and law["how"] == "crush") else 0.0 + if target or law["crush"] > 0.0: + tau = CRUSH_TAU[0] if target else CRUSH_TAU[1] + law["crush"] += (target - law["crush"]) * min(1.0, dt / tau) + if not target and law["crush"] < 0.002: + law["crush"] = 0.0 + if abs(law["crush"] - law["crush_set"]) > 0.004 or (law["crush"] == 0.0 and law["crush_set"] > 0.0): + self._set_crush(b, law["crush"], law["crush_axis"], law["crush_sign"]) + law["crush_set"] = law["crush"] + law["t"] += dt + + def _set_crush(self, b, c, axis, sign): + """flatten box b's two halves along their local `axis` by c (0..1) x CRUSH_ALPHA, keeping the faces on the + `sign` side (the side facing down) in place; then refresh the collision bounds""" + m = self.env.sim.model + for (bid, gs, size0, pos0), alpha in zip(self.half_geoms[b], CRUSH_ALPHA): + size, pos = size0.copy(), pos0.copy() + if c > 0.0: + s0 = size0[:, axis] + s1 = s0 * (1.0 - alpha * c) + size[:, axis] = s1 + pos[:, axis] = pos0[:, axis] + sign * (s0 - s1) + m.geom_size[gs] = size + m.geom_pos[gs] = pos + envs.refit_bounds(m, [self.half_geoms[b][0][0], self.half_geoms[b][1][0]]) + + def _on_buckle(self): + mon = self.mon + if mon is None: + return + b = self.law["box"] + ch = self.pile() + on = self.items_on(b) + last = self.law["buckles"][-1] if self.law["buckles"] else {} + e = dict(event="buckle", box=COL[b], step=int(self.sk.n_steps) if self.sk else 0, + load_N=round(self.law["f"], 2), level=(ch.index(b) + 1) if b in ch else None, + items_on=[COL.get(x, "cup") for x in on], how=last.get("how"), cause=last.get("cause"), + resting_N=last.get("resting_N"), + lying=bool(abs(self.R(self.base_bid[b])[2, 2]) < FOLD_MIN_UP)) + mon["events"].append(e) + mon["buckle_steps"].append(e["step"]) + mon["pending_collapse"] = dict(step=e["step"], pile=list(ch), cup=self.cup_on_pile(ch)) + + # ------------------------------------------------------------ geometry / predicates + def R(self, bid): + return self.env.sim.data.xmat[bid].reshape(3, 3) + + def centre(self, name): + return envs.obj_pos(self.env, name) + + def flat_tilt(self, b): + """angle (rad) between world vertical and the base part's axis closest to it (a box may lie on any face)""" + R = self.R(self.base_bid[b]) + return float(np.arccos(np.clip(np.max(np.abs(R[2, :])), -1.0, 1.0))) + + def kink(self, b): + """bend of the upper part against the base part (rad)""" + zb = self.R(self.base_bid[b])[:, 2] + zu = self.R(self.upper_bid[b])[:, 2] + return float(np.arccos(np.clip(zb @ zu, -1.0, 1.0))) + + def cup_tilt(self): + return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, CUP), -1.0, 1.0))) + + def held(self, name): + return self.sk is not None and self.sk.holding(name) + + def crushed(self, b): + """how far box b is crushed (0..1; only the soft carton, lying on a side face, can be)""" + law = self.law + return float(law["crush"]) if (law is not None and law["box"] == b) else 0.0 + + def flat(self, b): + return (self.flat_tilt(b) <= TILT_OK and self.kink(b) <= KINK_OK and self.crushed(b) <= 0.15 + and not self.held(b)) + + def rests_on(self, upper, lower): + cu, cl = self.centre(upper), self.centre(lower) + return (np.linalg.norm(cu[:2] - cl[:2]) <= STACK_XY + and abs(envs.obj_min_z(self.env, upper) - envs.obj_max_z(self.env, lower)) <= STACK_Z) + + def on_mat(self, b): + off = self.centre(b)[:2] - np.asarray(self.inst["mat"]) + return bool(np.all(np.abs(off) <= ON_MAT) and envs.obj_min_z(self.env, b) <= TZ + 0.008) + + def pile(self): + """the longest chain of flat boxes: the bottom one on the mat, each next resting on the previous (centres within + 2 cm, faces within 1 cm)""" + flat = [b for b in BOXES if self.flat(b)] + best = [] + for b0 in [b for b in flat if self.on_mat(b)]: + ch = [b0] + while True: + nxt = [b for b in flat if b not in ch and self.rests_on(b, ch[-1])] + if not nxt: + break + ch.append(min(nxt, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - self.centre(ch[-1])[:2])))) + if len(ch) > len(best): + best = ch + return best + + def cup_on(self, b): + c = self.centre(CUP) + return bool(self.cup_tilt() <= TILT_OK and not self.held(CUP) + and np.linalg.norm(c[:2] - self.centre(b)[:2]) <= CUP_XY + and abs(envs.obj_min_z(self.env, CUP) - envs.obj_max_z(self.env, b)) <= STACK_Z) + + def cup_on_pile(self, ch=None): + ch = self.pile() if ch is None else ch + return bool(len(ch) == len(BOXES) and self.cup_on(ch[-1])) + + def items_on(self, b): + """boxes / cup resting (directly or higher up) on box b, by height and overlap""" + cb = self.centre(b) + top = envs.obj_max_z(self.env, b) + out = [] + for x in BOXES + [CUP]: + if x == b: + continue + c = self.centre(x) + if envs.obj_min_z(self.env, x) > top - 0.015 and np.linalg.norm(c[:2] - cb[:2]) < 0.06: + out.append(x) + return out + + def stage_values(self): + ch = self.pile() + v = {COL[b]: b in ch for b in BOXES} + v["cup"] = self.cup_on_pile(ch) + return v, ch + + # ------------------------------------------------------------ monitor + def _init_monitor(self): + keys = COLOURS + ["cup"] + self.mon = dict(state={k: False for k in keys}, cand={k: 0 for k in keys}, ever={k: False for k in keys}, + lost={k: False for k in keys}, lost_cause={k: None for k in keys}, events=[], n=0, + last_robot={k: -10 ** 6 for k in keys}, buckle_steps=[], pending_collapse=None, + max_kink={COL[b]: 0.0 for b in BOXES}, max_crush={COL[b]: 0.0 for b in BOXES}, + max_height=0, n_collapses=0, + law=self.law) # the carton's law state rides along in the robot server's regression snapshots + + def _substep(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] + o1, o2 = self.owner[g1], self.owner[g2] + p1, p2 = self.part[g1], self.part[g2] + sel = ((o1 >= 0) & (p2 > 0)) | ((o2 >= 0) & (p1 > 0)) + for i in np.nonzero(sel)[0]: + o = o1[i] if o1[i] >= 0 else o2[i] + self._sub_rob[int(o)] = True + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n"] += 1 + t = int(self.sk.n_steps) + self._held = {i for i, x in enumerate(BOXES + [CUP]) if self.held(x)} + if self.law is not None: # weight of the things (not held) on the soft carton, + 0.3 N for impacts + m = self.env.sim.model + self._rest_cap = 0.3 + G * sum(float(np.sum(m.body_mass[self.obj_bodies[x]])) + for x in self.items_on(self.law["box"]) + if (BOXES + [CUP]).index(x) not in self._held) + keys = COLOURS + ["cup"] + for i in list(self._sub_rob): + mon["last_robot"][keys[i]] = t + self._sub_rob = {} + for b in BOXES: + mon["max_kink"][COL[b]] = max(mon["max_kink"][COL[b]], round(float(np.degrees(self.kink(b))), 1)) + mon["max_crush"][COL[b]] = max(mon["max_crush"][COL[b]], round(self.crushed(b), 2)) + if mon["n"] % 2: + return + vals, ch = self.stage_values() + mon["max_height"] = max(mon["max_height"], len(ch)) + for k in keys: + raw = vals[k] + if raw == mon["state"][k]: + mon["cand"][k] = 0 + continue + mon["cand"][k] += 2 + if mon["cand"][k] < DEBOUNCE: + continue + mon["cand"][k] = 0 + mon["state"][k] = raw + t0 = t - DEBOUNCE + 1 + if raw: + restored = mon["lost"][k] + e = dict(stage=k, event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][k] + mon["lost"][k] = False + mon["ever"][k] = True + mon["events"].append(e) + elif mon["ever"][k]: + cause = self._cause(k, t) + mon["lost"][k] = True + mon["lost_cause"][k] = cause + mon["events"].append(dict(stage=k, event="lost", step=t0, cause=cause)) + pc = mon["pending_collapse"] + if cause == "buckle" and pc is not None and not pc.get("counted"): + pc["counted"] = True + mon["n_collapses"] += 1 + mon["events"].append(dict(event="collapse", step=t0, buckled=self.inst["soft_colour"], + pile_before=[COL[b] for b in pc["pile"]])) + + def _cause(self, k, t): + name = CUP if k == "cup" else BOXES[COLOURS.index(k)] + if self.held(name): + return "picked_up" + bs = self.mon["buckle_steps"] + if bs and t - bs[-1] <= 80: # within 4 s of a buckle + return "buckle" + if t - self.mon["last_robot"][k] <= 30: + return "robot" + return "other" + + def _finalize_monitor(self, vals): + mon = self.mon + t = int(self.sk.n_steps) + for k, raw in vals.items(): + if raw == mon["state"][k]: + continue + mon["state"][k] = raw + if raw: + restored = mon["lost"][k] + e = dict(stage=k, event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][k] + mon["lost"][k] = False + mon["ever"][k] = True + mon["events"].append(e) + elif mon["ever"][k]: + cause = self._cause(k, t) + mon["lost"][k] = True + mon["lost_cause"][k] = cause + mon["events"].append(dict(stage=k, event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + n = d.ncon + if not n: + return False + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + return bool(np.any(((self.owner[g1] >= 0) & (self.part[g2] > 0)) | ((self.owner[g2] >= 0) & (self.part[g1] > 0)))) + + def _static_pos(self): + return {x: self.centre(x).copy() for x in BOXES + [CUP]} + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = self._static_pos() + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max(float(np.linalg.norm(self.centre(x) - p0[x])) for x in p0) + static = moved < 0.003 + vals, ch = self.stage_values() + self._finalize_monitor(vals) + mon = self.mon + ev = list(mon["events"]) + held = [COL.get(x, "cup") for x in BOXES + [CUP] if self.held(x)] + success = bool(all(vals.values()) and static and not held and not touching) + buckles = [e for e in ev if e.get("event") == "buckle"] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + soft = inst["soft"] + buckled_now = bool(self.law is not None and self.law["buckled"]) + cup_fallen = self.cup_tilt() > np.radians(45) + if success: + failure = "none" + elif held: + failure = "held" + elif touching and all(vals.values()): + failure = "touching" + elif not all(vals[c] for c in COLOURS): + if buckles and any(mon["ever"][c] for c in COLOURS): + failure = "collapsed" + elif any(mon["lost"][c] for c in COLOURS): + failure = "regressed" + else: + failure = "not_stacked" + elif not vals["cup"]: + failure = "cup_fallen" if cup_fallen else "cup_not_on_top" + else: + failure = "not_static" + # F2 detail (robot-centric words) + parts = [] + if success: + parts.append("All four boxes are stacked on the mat and the cup stands on top.") + else: + if ch: + parts.append("The pile on the mat is " + " / ".join(COL[b] for b in ch) + " (bottom to top).") + else: + parts.append("There is no box resting flat on the mat.") + mat = np.asarray(inst["mat"]) + for b in BOXES: + if b in ch: + continue + c = COL[b] + if self.held(b): + parts.append(f"The {c} box is still held by the gripper.") + continue + off = self.centre(b)[:2] - mat + pose = ("lies tilted" if self.flat_tilt(b) > TILT_OK else + "is crushed flat" if self.crushed(b) > 0.15 else + f"is bent ({np.degrees(self.kink(b)):.0f} degrees)" if self.kink(b) > KINK_OK else "stands") + parts.append(f"The {c} box {pose} {_fb(off[0])} and {_lr(off[1])} of the mat's centre, not in the pile.") + if not vals["cup"]: + if self.held(CUP): + parts.append("The cup is still held by the gripper.") + elif cup_fallen: + parts.append("The cup has fallen over.") + else: + parts.append("The cup is not standing on top of a complete pile.") + if all(vals.values()): + if touching: + parts.append("The gripper is still touching the pile.") + elif not static: + parts.append("Something was still moving.") + loads = [e for e in buckles if e.get("cause") != "press"] + presses = [e for e in buckles if e.get("cause") == "press"] + if loads: + how = ("bent sideways or was crushed" if len({e.get("how") for e in loads}) > 1 else + "was crushed flat" if loads[0].get("how") == "crush" else "bent sideways") + parts.append(f"During the attempt the {loads[0]['box']} box {how} under the weight on it " + f"{len(loads)} time(s) and everything above it slid off.") + if presses: + parts.append(f"The {presses[0]['box']} box gave way {len(presses)} time(s) when the gripper pushed down " + f"on it.") + # trap fired = the carton gave way under what was put on it (or a giving-way cost a stage); a hard press by the + # gripper alone on an otherwise lightly loaded carton is logged (n_press_buckles) but is not the trap + trap = bool(loads) or int(mon["n_collapses"]) > 0 + return dict(success=success, failure=failure, stages=vals, pile=[COL[b] for b in ch], events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), trap_fired=trap, + recovered_in_attempt=bool(trap and success), n_buckles=len(buckles), + n_collapses=int(mon["n_collapses"]), buckle_levels=[e.get("level") for e in buckles], + buckle_loads_N=[e.get("load_N") for e in buckles], max_kink_deg=dict(mon["max_kink"]), + max_crush=dict(mon["max_crush"]), buckle_how=[e.get("how") for e in buckles], + buckle_causes=[e.get("cause") for e in buckles], n_press_buckles=len(presses), + max_height=int(mon["max_height"]), soft=inst["soft_colour"], benign=bool(inst["benign"]), + buckled_at_end=buckled_now, cup_fallen=bool(cup_fallen), held=held, touching=bool(touching), + static=bool(static), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.2): + cur = self.sk.eef_pos() + if cur[2] < z - 0.005: + self._go([cur[0], cur[1], z], speed=speed) + + def _settle(self, steps=40): + """hold until boxes / cup have stopped (max `steps` control steps)""" + p = self._static_pos() + for _ in range(steps // 4): + self.sk.hold(4) + q = self._static_pos() + if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005: + return + p = q + + def settle_scene(self, max_steps=120): + """after a collapse: wait (looking) until nothing moves and no box is visibly bent any more""" + for _ in range(max_steps // 10): + self._settle(10) + if all(self.kink(b) < np.radians(3.0) for b in BOXES): + p = self._static_pos() + self.sk.hold(4) + q = self._static_pos() + if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005: + return + + def grasp_yaw(self, name): + """wrist yaw that closes the fingers across a horizontal box axis: of the two, the one whose open fingers stay + clearest of the other objects (a box that fell against another one), then the one needing the least turn""" + if name == CUP: + return 0.0 + R = self.R(self.base_bid[name]) + up = int(np.argmax(np.abs(R[2, :]))) + c = self.centre(name)[:2] + others = [self.centre(x)[:2] for x in BOXES + [CUP] if x != name] + best = None + for a in range(3): + if a == up: + continue + v = R[:2, a] / max(np.linalg.norm(R[:2, a]), 1e-9) + yaw = _wrap_q(float(np.arctan2(v[1], v[0])) - np.pi / 2, np.pi) # fingers close along (-sin yaw, cos yaw) + fingers = [c + s_ * 0.045 * v for s_ in (1.0, -1.0)] # open fingers ~4.5 cm from the centre + clear = min([float(np.linalg.norm(f - o)) for f in fingers for o in others] + [1.0]) + key = (round(min(clear, 0.05), 3), -abs(yaw)) + if best is None or key > best[0]: + best = (key, yaw) + return best[1] + + def z_clear(self, extra=0.08): + """carry height: above everything on the table""" + top = max(envs.obj_max_z(self.env, x) for x in BOXES + [CUP]) + return max(TZ + Z_CARRY, top + extra) + + def pick(self, name, depth=0.018, z_carry=None, tries=2): + sk = self.sk + for _ in range(tries): + self._settle(20) + p = self.centre(name) + zt = envs.obj_max_z(self.env, name) + yaw = self.grasp_yaw(name) + sk.set_gripper(False, steps=10) + zc = z_carry or self.z_clear() + self._lift_to(zc) + self._go([p[0], p[1], zc], yaw=yaw, speed=0.25) + self._go([p[0], p[1], zt - depth + 0.02], speed=0.12) + self._go([p[0], p[1], max(zt - depth, TZ + 0.012)], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], self.z_clear(0.10)], speed=0.15) + if self.held(name): + return True + sk.set_gripper(False, steps=10) + return False + + def put(self, name, xy, z_surface, gap, yaw=0.0): + """carry the held object over xy (its centre), straight down until its bottom is `gap` above z_surface, let + go, lift 8 cm""" + sk = self.sk + zc = max(self.z_clear(0.10), sk.eef_pos()[2]) + rel = self.centre(name)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + self._go([q[0], q[1], zc], yaw=yaw, speed=0.25) + sk.hold(5) + rel = self.centre(name)[:2] - sk.eef_pos()[:2] # the object can shift in the fingers while the wrist turns + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, name) + zr = z_surface + dz + gap + self._go([q[0], q[1], zr + 0.03], speed=0.12) + self._go([q[0], q[1], zr], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=15) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.08], speed=0.15) + self._settle(40) + + def free_spot(self, near_xy): + """a free place on the table (for a box taken off the pile): >= 11 cm from everything, off the mat, reachable""" + mat = np.asarray(self.inst["mat"]) + others = [self.centre(x)[:2] for x in BOXES + [CUP]] + best, bd = None, -1.0 + for r in (0.17, 0.21, 0.25, 0.29): + for a in np.radians(np.arange(0, 360, 15)): + p = mat + r * np.array([np.cos(a), np.sin(a)]) + if not (BOX_X[0] - 0.02 <= p[0] <= BOX_X[1] and abs(p[1]) <= BOX_YMAX + 0.02): + continue + d = min(float(np.linalg.norm(p - o)) for o in others) + if d >= 0.11: + return p + if d > bd: + best, bd = p, d + return best + + def place_on_pile(self, name, err, gap, rng, bias=0.0): + """put object `name` on the current pile top (or the mat) with a placement error of `err` (m, random direction)""" + ch = [b for b in self.pile() if b != name] + if ch: + # aims every box at the same spot (the bottom box), as an agent that computes the pile's x, y once: errors + # do not add up level by level + tgt = self.centre(ch[0])[:2].copy() + zs = envs.obj_max_z(self.env, ch[-1]) + else: + tgt = np.asarray(self.inst["mat"], float) + np.array([bias, 0.0]) + zs = TZ + if err: + a = rng.uniform(0, 2 * np.pi) + tgt = tgt + float(err) * np.array([np.cos(a), np.sin(a)]) + if not self.pick(name): + return False + self.put(name, tgt, zs, gap) + return True + + def lay_aside(self, name, rng): + if not self.pick(name): + return False + p = self.free_spot(self.centre(name)[:2]) + self.put(name, p, TZ, 0.01) + return True + + # ------------------------------------------------------------ scripted policies + def nearest_order(self): + mat = np.asarray(self.inst["mat"]) + return sorted(BOXES, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - mat))) + + def plan(self, params, rng): + if params.get("order") == "random": + order = [BOXES[i] for i in rng.permutation(4)] + else: + order = self.nearest_order() + soft = params.get("soft_known") + if soft: + order = [b for b in order if COL[b] != soft] + [b for b in order if COL[b] == soft] + return order + + def seen_soft(self): + """the box that visibly bent during this attempt (scripted perception of the kink in the images)""" + mk, mc = self.mon["max_kink"], self.mon["max_crush"] + for c in COLOURS: + if mk[c] > 15.0 or mc[c] > 0.3: + return c + return None + + def build(self, order, params, rng, first=True): + """stack `order` (boxes not yet in the pile) then the cup; returns 'ok', 'collapse' or 'fail'""" + err = params.get("err") + gap = params.get("gap", 0.005) + # a box that could not be picked up is tried again after the others (one more pass) + order = list(order) * 2 + for b in order: + if b in self.pile(): + continue + if params.get("soft_known") and COL[b] == params["soft_known"] and \ + sum(x in self.pile() for x in BOXES if COL[x] != params["soft_known"]) < len(BOXES) - 1: + continue # the soft box only goes on once the three others are in the pile + for _ in range(2): + n_b = len(self.mon["buckle_steps"]) + before = self.pile() + e = rng.uniform(*err) if err else 0.0 + if not self.place_on_pile(b, e, gap, rng, bias=params.get("bias", 0.0) if not before else 0.0): + break + after = self.pile() + if len(self.mon["buckle_steps"]) > n_b or any(x not in after for x in before): + return "collapse" + if b in after: + break + if len(self.pile()) < len(BOXES): + return "fail" + if self.cup_tilt() > np.radians(45): + return "fail" + for _ in range(2): + n_b = len(self.mon["buckle_steps"]) + before = self.pile() + e = rng.uniform(*err) if err else 0.0 + if not self.place_on_pile(CUP, e, gap, rng): + return "fail" + if len(self.mon["buckle_steps"]) > n_b or any(x not in self.pile() for x in before): + return "collapse" + if self.cup_on_pile(): + return "ok" + return "fail" + + def rebuild_soft_top(self, soft_colour, params, rng): + """take the soft box (and whatever is on it) off the pile, then stack the rigid boxes and the soft one last""" + soft = BOXES[COLOURS.index(soft_colour)] + for _ in range(6): + ch = self.pile() + if soft in ch: + self.lay_aside(ch[-1], rng) # from the top down to the soft box + elif self.on_mat(soft) or any(soft in self.items_on(b) for b in ch): + self.lay_aside(soft, rng) # bent / off-centre on the mat or on the pile + else: + break + order = [b for b in self.nearest_order() if b != soft] + [soft] + return self.build(order, dict(params, soft_known=soft_colour), rng) + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = self.plan(params, rng) + res = self.build(order, params, rng) + if res == "collapse": + mode = params.get("on_collapse", "rebuild_same") + if mode == "rebuild_same": # the cheapest explanation: "I did not centre it" -> same order, more care + self.settle_scene() + res = self.build(order, dict(params, err=None, gap=0.005), rng) + elif mode == "identify": # sees which box bent and rebuilds with it on top + self.settle_scene() + soft = self.seen_soft() + if soft and self.cup_tilt() < np.radians(45): + res = self.rebuild_soft_top(soft, params, rng) + self._lift_to(self.z_clear(0.06)) + self.sk.hold(10) + return res + + NAIVE = dict(order="nearest", soft_known=None, on_collapse="rebuild_same") + + def default_params(self, inst): + """Sonnet-like: nearest box first, lifts above everything, straight down, lets go 1-4 cm above (per instance), + 0.4-1.3 cm placement errors, the first box up to 2 cm too far forward; after a collapse it rebuilds once in + the same order, more carefully""" + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, err=NAIVE_ERR, gap=float(inst["naive_gap"]), + bias=float(inst["naive_bias"])) + + def oracle_params(self, inst): + return dict(order="nearest", soft_known=inst["soft_colour"], on_collapse="identify", err=None, gap=0.005) + + def adapt_params(self, inst, history): + soft = None + for h in history: + ev = [e for e in h["outcome"]["events"] if e.get("event") == "buckle"] + if ev: + soft = ev[0]["box"] # the box seen bending (the kink is visible in the images) + return dict(self.default_params(inst), soft_known=soft, on_collapse="identify") + + def blind_params(self, inst, attempt, rng): + return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)), + gap=float(rng.uniform(*NAIVE_GAP)), bias=float(rng.uniform(*NAIVE_BIAS))) + + 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 = [] + single = ("oracle", "naive", "naive_centred", "oracle_noise", "naive_once", "naive_lying", "oracle_lying") + if kind in ("naive_lying", "oracle_lying") and inst["soft"]: + # control (v2): the soft carton starts lying on a side face, so it is stacked lying + inst = dict(inst, lying={inst["soft_colour"]: np.pi / 2}) + 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 habits, but it looks at the collapse and rebuilds soft-on-top + params = (dict(self.default_params(inst), on_collapse="identify") 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": # control: cross-attempt learning only (no within-attempt identification) + params = self.default_params(inst) if a == 0 else dict(self.adapt_params(inst, history), + on_collapse="rebuild_same") + elif kind == "naive_centred": # control (R4): perfect centring, let go 5 mm above, no rebuild + params = dict(self.default_params(inst), err=None, gap=0.005, bias=0.0, on_collapse="none") + elif kind == "naive_once": # control: naive without the careful rebuild + params = dict(self.default_params(inst), on_collapse="none") + elif kind == "naive_lying": # control (v2): naive_once with the soft carton lying on a side face + params = dict(self.default_params(inst), on_collapse="none") + elif kind == "oracle_lying": # control (v2): soft carton lying, but on top (carries only the cup) + params = dict(self.oracle_params(inst)) + elif kind == "oracle_noise": # robustness: soft box on top with Sonnet-like imprecision + params = dict(self.default_params(inst), soft_known=inst["soft_colour"], on_collapse="identify") + 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 single: + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/check_lh_order_dispatch.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/check_lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb4c084795154715e782e18d6cb6c38b5af72c0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/check_lh_order_dispatch.py @@ -0,0 +1,73 @@ +"""Small physical development check; no agent/API calls. Every case starts from a reset. +Oracle recovery is explicitly diagnostic, not learned behaviour. +""" +import argparse,copy,json,sys,time +from pathlib import Path +from PIL import Image +import hashlib +from lffbench import envs +import numpy as np +from lffbench.tasks.lh_order_dispatch import OrderDispatch,PRODUCTS +from lffbench.tasks.l3_card_edge import CardEdge +from lffbench.tasks.l7_offcenter_push import OffcenterPush +p=argparse.ArgumentParser();p.add_argument('--seeds',default='1000,1001,1002');p.add_argument('--cases',default='baseline,oracle_all,L1,L3,L5,combined_recovery');p.add_argument('--out',required=True);a=p.parse_args() +source=Path('lffbench/tasks/lh_order_dispatch.py').read_bytes() +code_sha256=hashlib.sha256(source).hexdigest() +Path(a.out).parent.mkdir(exist_ok=True,parents=True) +Path(a.out).with_suffix('.source.py').write_bytes(source) +task=OrderDispatch(cam_res=512);rows=[] +def capture(label): + dest=Path(a.out).parent/(Path(a.out).stem+'_frames')/f'{seed}_{case}_{label}.png';dest.parent.mkdir(exist_ok=True) + Image.fromarray(envs.render(task.env,res=512)).save(dest) + return dict(path=str(dest.resolve()),sim_step=task.sk.n_steps) + +for seed in map(int,a.seeds.split(',')): + for case in a.cases.split(','): + inst=task.sample_instance(seed);inst['mechanisms']={x:case in ('oracle_all','combined_recovery') or x==case for x in ['L1','L3','L5']};task.reset_instance(inst) + frames=[capture('initial')] + base_move=task.sk.move_to + captured_l5=[False] + def observed_move(*args,**kwargs): + result=base_move(*args,**kwargs) + if task.sk.box_moves and task.sk.box_moves[-1].get('bad') and task.mon['loaded'] and not task.sk.box_moves[-1].get('gripper_open') and not captured_l5[0]: + frames.append(capture('L5_failure'));captured_l5[0]=True + return result + task.sk.move_to=observed_move + try: + failure=None + if case in ('baseline','oracle_all'): + task.execute(inst,task.oracle_params(inst)) + elif case=='L1': + task.load_product(PRODUCTS[0],0);failure=copy.deepcopy(task.outcome(inst)) + frames.append(capture('L1_failure'));measured=failure['l1_attempts'][0]['approach_offset'];task.execute(inst,dict(mode='oracle',correction=[*measured,0],c=0.)) + elif case=='L3': + for k,o in enumerate(PRODUCTS):task.load_product(o,k) + CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure'));failure=copy.deepcopy(task.outcome(inst)) + CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10) + if all(task.in_cargo(o) for o in task.mon['states']):OffcenterPush.execute(task,inst,dict(c=0.)) + pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8) + elif case=='combined_recovery': + task.load_product(PRODUCTS[0],0);frames.append(capture('L1_failure'));failure=copy.deepcopy(task.outcome(inst)) + estimate=np.array([*failure['l1_attempts'][0]['approach_offset'],0.]);task.sk.correction=estimate + for k,o in enumerate(PRODUCTS): + task.load_product(o,k) + estimate+=np.array([*task.mon['l1_attempts'][-1]['approach_offset'],0.]);task.sk.correction=estimate.copy() + CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure')) + CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10) + if all(task.in_cargo(o) for o in task.mon['states']): + OffcenterPush.adaptive_attempt(task,inst,0.) + if not task.in_cargo('card_1'):task.repair_card() + pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8) + else: + # Original corrector takes its estimate only from observed pushes, not hidden com_offset. + task.execute(inst,dict(mode='adaptive',c=0.)) + out=task.outcome(inst);frames.append(capture('final')) + trigger=(not failure['l1_attempts'][0]['held'] if case=='L1' else + not any(c['held'] for c in failure['card_closes'] if c['card_on_board'] and c['overhang']<=0) if case=='L3' else + out['l5_triggered'] if case=='L5' else None) + diagnostics=dict(L1=bool(out['l1_attempts'] and not out['l1_attempts'][0]['held']),L3=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']),L5=out['l5_triggered']) + row=dict(seed=seed,case=case,diagnostics=diagnostics,mechanisms=inst['mechanisms'],triggered=trigger,recovered=out['success'],before_recovery=failure,outcome=out,frames=frames) + except Exception as e: + row=dict(seed=seed,case=case,error=repr(e)) + assert hashlib.sha256(Path('lffbench/tasks/lh_order_dispatch.py').read_bytes()).hexdigest()==code_sha256,'source changed during run' + rows.append(row);Path(a.out).write_text(json.dumps(dict(code_sha256=code_sha256,rows=rows),indent=2));print(seed,case,{k:row.get(k) for k in ('triggered','recovered','error')},flush=True) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/client/lffbench_client/__init__.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/client/lffbench_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5701a1adf87d05ade8ed619db6e6bf1e1c0f796 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/client/lffbench_client/__init__.py @@ -0,0 +1,139 @@ +"""LFF-Bench Python client: the three agent tools of one episode, for any robot harness framework (docs/18 §6.3). + +Only the standard library; it never imports the simulator. It talks to the episode's tool gateway +(scripts/tool_gateway.py), which runs next to the robot server and owns the per-attempt tool-call budget, the jailed +shell and the workspace images. A framework registers the three tools with the schemas from tool_specs() and calls +them through a Session: + + from lffbench_client import Session + s = Session.from_env() # LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN (set by the launcher) + first = s.first_message() # README + first status, as every harness gets it + tools = s.tool_specs("openai_responses") # or raw / mcp / anthropic / openai_chat + r = s.robot("move_eef x=0.5 y=0.0 z=0.2") # -> ToolResult + r.json() # the robot server's reply as a dict + s.view_images(["obs/s001_agentview.jpg"]).images # [(mime, bytes)] + +A ToolResult's content is the list a model should see, in MCP form (text items and base64 image items); finished +says that the episode is over (stop calling tools). Nothing here can reset the scene or read the verdict: the only +feedback is what the robot server writes into the tool results. +""" +import base64 +import dataclasses +import json +import os +import urllib.error +import urllib.parse +import urllib.request + +__all__ = ["Session", "ToolResult", "GatewayError", "STYLES"] +__version__ = "0.1.0" + +STYLES = ("raw", "mcp", "anthropic", "openai_responses", "openai_chat") + + +class GatewayError(RuntimeError): + pass + + +@dataclasses.dataclass +class ToolResult: + content: list # [{"type": "text", "text"} | {"type": "image", "mimeType", "data" (base64)}] + is_error: bool + finished: bool # the episode is over: stop calling tools and report + calls_in_attempt: int # tool calls used in the current attempt (after an automatic finish: 0) + + @property + def text(self): + """All text items, joined by newlines.""" + return "\n".join(c["text"] for c in self.content if c.get("type") == "text") + + def json(self): + """The first text item parsed as JSON (robot / shell / view_images replies are JSON objects).""" + for c in self.content: + if c.get("type") == "text": + return json.loads(c["text"]) + raise ValueError("no text item") + + @property + def images(self): + """[(mime type, bytes)] of the image items.""" + return [(c["mimeType"], base64.b64decode(c["data"])) for c in self.content if c.get("type") == "image"] + + +class Session: + """One episode's tools through its gateway. face labels this access path in the gateway transcript.""" + + def __init__(self, url, token, face="sdk", timeout_s=900.0): + self.url, self.token, self.face, self.timeout_s = url.rstrip("/"), token, face, timeout_s + self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never via a proxy + + @classmethod + def from_env(cls, face="sdk", **kw): + url, token = os.environ.get("LFF_GATEWAY_URL"), os.environ.get("LFF_GATEWAY_TOKEN") + if not url or not token: + raise GatewayError("LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN are not set") + return cls(url, token, face=face, **kw) + + @classmethod + def from_gateway_file(cls, path, face="sdk", **kw): + """gateway.json written by the gateway in the run's log dir (launchers only; harness processes get env vars).""" + d = json.load(open(path)) + return cls(d["url"], d["token"], face=face, **kw) + + # ------------------------------------------------------------------------------------------------ http + def _request(self, method, path, body=None): + req = urllib.request.Request(self.url + path, method=method, + data=None if body is None else json.dumps(body).encode(), + headers={"Authorization": f"Bearer {self.token}", "X-LFF-Face": self.face, + "Content-Type": "application/json"}) + try: + with self._opener.open(req, timeout=self.timeout_s) as r: + return r.read(), r.headers.get("Content-Type", "") + except urllib.error.HTTPError as e: + raise GatewayError(f"{method} {path}: HTTP {e.code}: {e.read()[:500].decode('utf-8', 'replace')}") from None + except urllib.error.URLError as e: + raise GatewayError(f"{method} {path}: {e.reason}") from None + + def _get_json(self, path): + return json.loads(self._request("GET", path)[0]) + + # ------------------------------------------------------------------------------------------------ tools + def call(self, name, arguments=None): + raw, _ = self._request("POST", "/tool", dict(name=name, arguments=arguments or {})) + d = json.loads(raw) + return ToolResult(content=d["content"], is_error=bool(d["is_error"]), finished=bool(d["finished"]), + calls_in_attempt=d.get("calls_in_attempt")) + + def robot(self, command): + """One robot command, exactly as in the instructions (e.g. 'status', 'move_eef x=0.5 z=0.2', 'finish ...').""" + return self.call("robot", dict(command=command)) + + def shell(self, command): + """A bash command in the episode workspace (jailed: no network, nothing outside the workspace).""" + return self.call("shell", dict(command=command)) + + def view_images(self, paths): + """Image files of the workspace (e.g. obs/s001_agentview.jpg); the images come back as image items.""" + return self.call("view_images", dict(paths=list(paths))) + + # ------------------------------------------------------------------------------------------------ instructions + def tool_specs(self, style="raw"): + """The three tool schemas with the reference descriptions, in one of STYLES.""" + if style not in STYLES: + raise ValueError(f"style must be one of {STYLES}") + return self._get_json("/tool_specs?style=" + urllib.parse.quote(style))["tools"] + + def readme(self): + return self._request("GET", "/readme")[0].decode("utf-8") + + def first_message(self): + """Preamble + README + first status report: the first user message every harness gets.""" + return self._request("GET", "/first_message")[0].decode("utf-8") + + def health(self): + return self._get_json("/health") + + def status(self): + """robot_server's `status` for the framework's own loop (e.g. a "continue" nudge that names the attempt): not + a tool call of the model, not counted in the per-attempt budget. Never show it to the model as a tool result.""" + return self._get_json("/status") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/gemini.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4240f299561c36a664bf40ab8dceaf44715cf8 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/agent/backends/gemini.py @@ -0,0 +1,206 @@ +"""Google Gemini backend (Gemini API, official SDK `google-genai`). + +Same conversation as the other backends, converted to Gemini `contents`: +- system prompt = system_instruction; tools = function declarations with the harness's JSON schemas; +- every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive) + and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call; +- tool outputs of one turn become `function_response` parts at the start of the next user content; images the + harness attaches after them follow in the same user content; +- thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged; +- implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage). + +Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock. +""" +import base64 +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_sdk + + +def _get(obj, key, default=None): + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + +def _strip_additional(schema): + """The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema.""" + if isinstance(schema, dict): + return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"} + if isinstance(schema, list): + return [_strip_additional(v) for v in schema] + return schema + + +def _image_part(image, quality=None): + head, data = image.data_url(quality).split(",", 1) + mime = head[len("data:"):].split(";", 1)[0] + return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data))) + + +class GeminiBackend(Backend): + name = "gemini" + + def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True, + max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90, + timeout=900.0, client=None): + self.model = model + self.thinking_level = thinking_level + self.thinking_budget = thinking_budget + self.include_thoughts = include_thoughts + self.max_output_tokens = max_output_tokens + self.media_resolution = media_resolution + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self._client = client + self._json_schema_field = None + + def config(self): + return dict(name=self.name, model=self.model, thinking_level=self.thinking_level, + thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts, + max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution, + max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout) + + def client(self): + if self._client is None: + genai = import_sdk("google.genai") + self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000))) + return self._client + + def _declarations(self, specs): + if self._json_schema_field is None: + try: + types = import_sdk("google.genai.types") + self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields + except ImportError: # tests without the SDK + self._json_schema_field = True + out = [] + for s in specs: + d = dict(name=s["name"], description=s["description"]) + if self._json_schema_field: + d["parameters_json_schema"] = s["parameters"] + else: + d["parameters"] = _strip_additional(s["parameters"]) + out.append(d) + return [dict(function_declarations=out)] + + # ------------------------------------------------------------------ request + def convert_items(self, items): + contents = [] + + def push(role, parts): + if contents and contents[-1]["role"] == role: + contents[-1]["parts"].extend(parts) + else: + contents.append(dict(role=role, parts=list(parts))) + + for it in items: + kind = it["kind"] + if kind == "user": + parts = [] + for p in it["parts"]: + if p["type"] == "text": + parts.append(dict(text=p["text"])) + else: + parts.append(_image_part(p["image"], self.jpeg_quality)) + push("user", parts) + elif kind == "assistant": + if it.get("raw") is not None and it.get("backend") == self.name: + content = dict(it["raw"][0]) + contents.append(dict(role="model", parts=list(content.get("parts") or []))) + continue + parts = ([dict(text=it["text"])] if it.get("text") else []) + parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]] + push("model", parts or [dict(text="(no output)")]) + elif kind == "tool_output": + fr = dict(name=it["name"], response=dict(output=it["text"])) + if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"): + fr["id"] = it["call_id"] + push("user", [dict(function_response=fr)]) + else: + raise ValueError(kind) + return contents + + def build_request(self, conv, tools): + items = prune_live_images(conv.items, self.max_live_images) + thinking = dict(include_thoughts=self.include_thoughts) + if self.thinking_budget is not None: + thinking["thinking_budget"] = int(self.thinking_budget) + elif self.thinking_level: + thinking["thinking_level"] = self.thinking_level + config = dict(system_instruction=conv.system, tools=self._declarations(tools), + tool_config=dict(function_calling_config=dict(mode="AUTO")), + automatic_function_calling=dict(disable=True), thinking_config=thinking, + max_output_tokens=int(self.max_output_tokens)) + if self.media_resolution: + config["media_resolution"] = self.media_resolution + return dict(model=self.model, contents=self.convert_items(items), config=config) + + @staticmethod + def request_stats(req): + n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "") + for c in req["contents"]: + for p in c["parts"]: + p = p if isinstance(p, dict) else {} + if p.get("inline_data"): + n_img += 1 + img_bytes += len(p["inline_data"]["data"]) + elif p.get("text"): + txt += len(p["text"]) + elif p.get("function_response"): + txt += len(str(p["function_response"].get("response", ""))) + return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"])) + + # ------------------------------------------------------------------ call + def act(self, conv, tools): + req = self.build_request(conv, tools) + stats = self.request_stats(req) + types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys + t0 = time.time() + resp = self.client().models.generate_content( + model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]], + config=types.GenerateContentConfig.model_validate(req["config"])) + out = self.parse_response(resp) + out.latency_s = time.time() - t0 + out.request_stats = stats + return out + + def parse_response(self, resp): + cands = _get(resp, "candidates") or [] + cand = cands[0] if cands else None + content = _get(cand, "content") if cand is not None else None + parts = (_get(content, "parts") or []) if content is not None else [] + calls, texts, summ = [], [], [] + for i, p in enumerate(parts): + fc = _get(p, "function_call") + if fc is not None: + cid = _get(fc, "id") or f"gemini_call_{i}" + calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {}))) + elif _get(p, "text"): + (summ if _get(p, "thought") else texts).append(_get(p, "text")) + u = _get(resp, "usage_metadata") + usage = {} + if u is not None: + usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0, + cached_tokens=_get(u, "cached_content_token_count", 0) or 0, + output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0), + reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0) + finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE" + status, err = "completed", None + if not parts: + status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})" + elif "MAX_TOKENS" in finish or "MALFORMED" in finish: + status, err = "incomplete", f"incomplete: finish_reason={finish}" + elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish: + status, err = "refusal", f"refusal: finish_reason={finish}" + if content is not None and hasattr(content, "model_dump"): + raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes + elif content is not None: + raw = [dict(content)] + else: + raw = None + return BackendResponse(tool_calls=calls, text="\n".join(texts) or None, + reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw, + status=status, error=err) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/l4_fit_container.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/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_auto_002_sonnet/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_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..7201f54a4d0ba3fb8e1844420311ced219827fa6 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py @@ -0,0 +1,23 @@ +"""Layer-4 intervention texts for lh_clear_cover (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is +not in the controlled arms of full5. + +Hidden variable: inst["cover"] -- which box carries the nearly invisible clear lid (None in uncovered instances). +reveal says which box is covered and what the lid does to a released cube; not how to deal with it. +fix the oracle's edge push (lh_clear_cover.remove_cover) in move_eef words; params["z_push"] = grasp-point height of + that push in the eef_pos frame, params["push_len"] = length of the sweep (scripts/layer4_plan.py validate). +""" +HIDDEN_KEYS = ("cover",) + + +def reveal(inst): + return (f"The {inst['cover']} box is covered by a loose, nearly invisible clear lid lying on its walls, 8 mm thick. " + f"A cube released over that box stops on the lid at rim height; it is not in the box.") + + +def fix(inst, params): + return (f"A way to succeed: first push the lid off the {inst['cover']} box. Close the gripper, keep yaw 0 and bring " + f"the grasp point to height {params['z_push']:.3f} (the third value of eef_pos), so that the fingertips are " + f"level with the lid's edge, 3 cm outside the edge of the lid that faces the other box. Then in one move_eef " + f"command sweep {params['push_len'] * 100:.0f} cm straight along the line between the two boxes, away from " + f"the other box, at speed 0.06, and lift. The lid is then off. Put each cube into the box of its colour, and " + f"check from the side view that no cube rests at rim height.") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/codex_catalogs/generic_0.163.0.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/codex_catalogs/generic_0.163.0.json new file mode 100644 index 0000000000000000000000000000000000000000..86e8e5f9425338f908922fbdc092fc53347f0fe7 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/codex_catalogs/generic_0.163.0.json @@ -0,0 +1,64 @@ +{ + "codex_version": "0.163.0", + "created": "2026-10-20", + "note": "Shared ('generic') Codex configuration for the main table (user 2026-10-20): every model gets this one catalog entry, with only slug / display_name / input_modalities / supported_reasoning_levels set per model. base_instructions and the other fields reproduce what Codex 0.163.0 sends for a model slug it has no entry for and no model_catalog_json is given (measured against the fake API: identical request apart from message ids): its generic Codex CLI prompt, plain function tools (no code mode), parallel tool calls, reasoning summary auto, no verbosity. See docs/15 8.9.", + "entry": { + "description": "", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { + "effort": "low", + "description": "Fast responses with lighter reasoning" + }, + { + "effort": "medium", + "description": "Balances speed and reasoning depth for everyday tasks" + }, + { + "effort": "high", + "description": "Greater reasoning depth for complex problems" + }, + { + "effort": "xhigh", + "description": "Extra high reasoning depth for complex problems" + } + ], + "shell_type": "default", + "visibility": "list", + "supported_in_api": true, + "priority": 99, + "additional_speed_tiers": [], + "service_tiers": [], + "availability_nux": null, + "upgrade": null, + "model_messages": null, + "include_skills_usage_instructions": false, + "include_plugin_usage_instructions": false, + "include_apps_usage_instructions": false, + "default_reasoning_summary": "auto", + "support_verbosity": false, + "default_verbosity": null, + "apply_patch_tool_type": null, + "web_search_tool_type": "text", + "truncation_policy": { + "mode": "bytes", + "limit": 10000 + }, + "supports_image_detail_original": false, + "context_window": 272000, + "max_context_window": 272000, + "effective_context_window_percent": 95, + "experimental_supported_tools": [], + "input_modalities": [ + "text", + "image" + ], + "supports_search_tool": false, + "supports_experimental_context": false, + "use_responses_lite": false, + "supports_reasoning_effort_updates": false, + "node_repl_auto_review_required": false, + "node_repl_disabled": false, + "base_instructions": "You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.\n\nYour capabilities:\n\n- Receive user prompts and other context provided by the harness, such as files in the workspace.\n- Communicate with the user by streaming thinking & responses, and by making & updating plans.\n- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the \"Sandbox and approvals\" section.\n\nWithin this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).\n\n# How you work\n\n## Personality\n\nYour default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.\n\n# AGENTS.md spec\n- Repos often contain AGENTS.md files. These files can appear anywhere within the repository.\n- These files are a way for humans to give you (the agent) instructions or tips for working within the container.\n- Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code.\n- Instructions in AGENTS.md files:\n - The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it.\n - For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file.\n - Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise.\n - More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions.\n - Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions.\n- The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable.\n\n## Responsiveness\n\n### Preamble messages\n\nBefore making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:\n\n- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.\n- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).\n- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.\n\n**Examples:**\n\n- “I’ve explored the repo; now checking the API route definitions.”\n- “Next, I’ll patch the config and update the related tests.”\n- “I’m about to scaffold the CLI commands and helper functions.”\n- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”\n- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”\n- “Finished poking at the DB gateway. I will now chase down error handling.”\n- “Alright, build pipeline order is interesting. Checking how it reports failures.”\n- “Spotted a clever caching util; now hunting where it gets used.”\n\n## Task execution\n\nYou are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.\n\nYou MUST adhere to the following criteria when solving queries:\n\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {\"command\":[\"apply_patch\",\"*** Begin Patch\\\\n*** Update File: path/to/file.py\\\\n@@ def example():\\\\n- pass\\\\n+ return 123\\\\n*** End Patch\"]}\n\nIf completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:\n\n- Fix the problem at the root cause rather than applying surface-level patches, when possible.\n- Avoid unneeded complexity in your solution.\n- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n- Update documentation as necessary.\n- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n- Use `git log` and `git blame` to search the history of the codebase if additional context is required.\n- NEVER add copyright or license headers unless specifically requested.\n- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.\n- Do not `git commit` your changes or create new git branches unless explicitly requested.\n- Do not add inline comments within code unless explicitly requested.\n- Do not use one-letter variable names unless explicitly requested.\n- NEVER output inline citations like \"【F:README.md†L5-L14】\" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.\n\n## Validating your work\n\nIf the codebase has tests or the ability to build or run, consider using them to verify that your work is complete. \n\nWhen testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests.\n\nSimilarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.\n\nFor all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n\nBe mindful of whether to run validation commands proactively. In the absence of behavioral guidance:\n\n- When running in the non-interactive approval mode **never**, proactively run tests, lint and do whatever you need to ensure you've completed the task.\n- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.\n- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.\n\n## Ambition vs. precision\n\nFor tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.\n\nIf you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.\n\nYou should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.\n\n## Sharing progress updates\n\nFor especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.\n\nBefore doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.\n\nThe messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.\n\n## Presenting your work and final message\n\nYour final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.\n\nYou can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.\n\nThe user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to \"save the file\" or \"copy the code into a file\"—just reference the file path.\n\nIf there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.\n\nBrevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.\n\n### Final answer structure and style guidelines\n\nYou are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.\n\n**Section Headers**\n\n- Use only when they improve clarity — they are not mandatory for every answer.\n- Choose descriptive names that fit the content\n- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`\n- Leave no blank line before the first bullet under a header.\n- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.\n\n**Bullets**\n\n- Use `-` followed by a space for every bullet.\n- Merge related points when possible; avoid a bullet for every trivial detail.\n- Keep bullets to one line unless breaking for clarity is unavoidable.\n- Group into short lists (4–6 bullets) ordered by importance.\n- Use consistent keyword phrasing and formatting across sections.\n\n**Monospace**\n\n- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).\n- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.\n- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).\n\n**File References**\nWhen referencing files in your response, make sure to include the relevant start line and always follow the below rules:\n * Use inline code to make file paths clickable.\n * Each reference should have a stand alone path. Even if it's the same file.\n * Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.\n * Line/column (1‑based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).\n * Do not use URIs like file://, vscode://, or https://.\n * Do not provide range of lines\n * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5\n\n**Structure**\n\n- Place related bullets together; don’t mix unrelated concepts in the same section.\n- Order sections from general → specific → supporting info.\n- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.\n- Match structure to complexity:\n - Multi-part or detailed results → use clear headers and grouped bullets.\n - Simple results → minimal headers, possibly just a short list or paragraph.\n\n**Tone**\n\n- Keep the voice collaborative and natural, like a coding partner handing off work.\n- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition\n- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).\n- Keep descriptions self-contained; don’t refer to “above” or “below”.\n- Use parallel structure in lists for consistency.\n\n**Don’t**\n\n- Don’t use literal words “bold” or “monospace” in the content.\n- Don’t nest bullets or create deep hierarchies.\n- Don’t output ANSI escape codes directly — the CLI renderer applies them.\n- Don’t cram unrelated keywords into a single bullet; split for clarity.\n- Don’t let keyword lists run long — wrap or reformat for scanability.\n\nGenerally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.\n\nFor casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.\n\n# Tool Guidelines\n\n## Shell commands\n\nWhen using the shell, you must adhere to the following guidelines:\n\n- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)\n- Do not use python scripts to attempt to output larger chunks of a file.\n\n" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/fakeapi.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/fakeapi.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9482378574fd6e4fec4b25b958f94103ff4fee --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/fakeapi.py @@ -0,0 +1,188 @@ +"""Local fake model APIs for offline harness checks (no real model, no cost). + +Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a +native harness can be driven turn by turn without a model: + FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic + FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider + +A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get +the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps: + ("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read") + ("text", s) a text block / assistant message + ("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript + ("fcall", name, args) Responses: a plain function call + ("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP + tools this way: name "robot", namespace "mcp__lff"; measured with 0.163) + + srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop() +""" +import itertools +import json +import os +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id") + + +class _Base: + final_text = "done" + + def __init__(self, script=None, record_dir=None, port=0): + self.script = list(script or []) + self.record_dir = record_dir + self.port = port + self.lock = threading.Lock() + self.counter = itertools.count(1) + self.requests = [] # (n, path, body) + if record_dir: + os.makedirs(record_dir, exist_ok=True) + + # ------------------------------------------------------------------ plumbing + def start(self): + outer = self + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _record(self, body): + with outer.lock: + n = next(outer.counter) + outer.requests.append((n, self.path, body)) + if outer.record_dir: + with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f: + json.dump(dict(method=self.command, path=self.path, body=body, + headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}), + f, indent=1, ensure_ascii=False) + return n + + def do_GET(self): + self._record(None) + self._send(404, b"{}", "application/json") + + def do_HEAD(self): + self._send(404, b"", "application/json") + + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0)) + try: + body = json.loads(raw) + except ValueError: + body = raw[:4000].decode("utf-8", "replace") + n = self._record(body) + outer.handle(self, n, body) + + def _send(self, code, data, ctype): + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H) + self.httpd.daemon_threads = True + self.port = self.httpd.server_address[1] + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + return self + + def stop(self): + self.httpd.shutdown() + self.httpd.server_close() + + def turn(self, i): + return self.script[i] if i < len(self.script) else [("text", self.final_text)] + + @staticmethod + def send_sse(h, events): + data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events) + h._send(200, data, "text/event-stream") + + +class FakeAnthropic(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}" + + def handle(self, h, n, body): + if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict): + h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json") + return + msgs = body.get("messages", []) + i = sum(1 for m in msgs if m.get("role") == "assistant") + steps = self.turn(i) + blocks = [] + for j, st in enumerate(steps): + if st[0] == "tool": + blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2])) + else: + blocks.append(dict(type="text", text=st[1])) + stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn" + model = body.get("model", "fake") + evs = [("message_start", dict(type="message_start", message=dict( + id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None, + stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))] + for k, b in enumerate(blocks): + if b["type"] == "tool_use": + evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict( + type="tool_use", id=b["id"], name=b["name"], input={})))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict( + type="input_json_delta", partial_json=json.dumps(b["input"]))))) + else: + evs.append(("content_block_start", dict(type="content_block_start", index=k, + content_block=dict(type="text", text="")))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, + delta=dict(type="text_delta", text=b["text"])))) + evs.append(("content_block_stop", dict(type="content_block_stop", index=k))) + evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None), + usage=dict(output_tokens=5)))) + evs.append(("message_stop", dict(type="message_stop"))) + self.send_sse(h, evs) + + def message_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages") + and "count_tokens" not in p] + + +class FakeResponses(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}/v1" + + def handle(self, h, n, body): + if not isinstance(body, dict) or "input" not in body: + h._send(404, b"{}", "application/json") + return + items = body.get("input") or [] + i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in + ("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message" + and it.get("role") == "assistant")) + steps = self.turn(i) + out = [] + for j, st in enumerate(steps): + if st[0] == "exec": + out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name="exec", status="completed", input=st[1])) + elif st[0] == "fcall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name=st[1], arguments=json.dumps(st[2]), status="completed")) + elif st[0] == "nscall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed")) + else: + out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed", + content=[dict(type="output_text", text=st[1], annotations=[])])) + rid = f"resp_fake_{n}" + evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))] + for k, it in enumerate(out): + evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it))) + evs.append(("response.completed", dict(type="response.completed", response=dict( + id=rid, status="completed", output=out, usage=dict( + input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3, + output_tokens_details=dict(reasoning_tokens=0), total_tokens=103))))) + self.send_sse(h, evs) + + def model_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b] diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/reference.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..93a7ecef47a9e0f879e60d8521618b4378658db2 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/harnesses/reference.py @@ -0,0 +1,143 @@ +"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness). + +Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its +own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only +adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness. +""" +import json +import os +import sys + +from . import contract as C +from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions +from .trajectory import TrajWriter + +ROOT = C.ROOT +PLAYER = os.path.join(ROOT, "scripts", "api_player.py") +DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py", + "lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py", + "lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"] + + +class Reference(HarnessAdapter): + name = "ours" + capabilities = dict( + only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"), + images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"), + non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"), + pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"), + machine_readable_events=Cap("yes", "stream", "transcript.jsonl"), + tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"), + model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"), + persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"), + instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"), + web_access=Cap("absent", "launch", "no such tool"), + host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"), + builtin_shell=Cap("absent", "launch", "only the jailed shell tool"), + subagent_delegation=Cap("absent", "launch", "no such tool"), + background_execution=Cap("absent", "launch", "no such tool"), + ) + + def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_): + self.provider = provider + self.base_env = dict(env if env is not None else os.environ) + self.timeout_s = timeout_s + self.python = python or sys.executable + + def version(self): + per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))} + sha = C.sha256_json(per) + return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get( + "scripts/api_player.py"))) + + def prepare(self, ep, first_message=None): + argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider, + "--model", ep.model, "--effort", ep.effort, "--style", "la"] + return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="", + stdout_path=os.path.join(ep.log_dir, "api_player.log"), + stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + return C.sha256_json(dict(argv=[a.replace(ep.session_path, "") for a in spec.argv[1:]])) + + def launch(self, spec, ep, skip_preflight=True): + # stdout and stderr go to the same api_player.log (as before the adapter layer) + import subprocess + import time + from .base import RunHandle, env_keys_of + spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code") + log = open(spec.stdout_path, "ab") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) + h.pid = h.proc.pid + time.sleep(0.2) + h.env_observed_keys = env_keys_of(h.pid) + return h + + def collect(self, h): + ep = h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + p = os.path.join(ep.log_dir, "transcript.jsonl") + start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0) + last_agent = None + for line in (open(p) if os.path.exists(p) else []): + d = json.loads(line) + e = d.get("ev") + if e == "start": + start = d + elif e == "user": + if first_user is None: + first_user = d.get("text") + tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t")) + elif e == "assistant": + u = d.get("usage") or {} + tot["inp"] += u.get("input_tokens", 0) + tot["out"] += u.get("output_tokens", 0) + tot["cached"] += u.get("cached_tokens", 0) + last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "", + timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"], + function_name=c["name"], + native_name=c["name"], + arguments=c["arguments"]) + for c in d.get("tool_calls") or []], + metrics=dict(prompt_tokens=u.get("input_tokens"), + completion_tokens=u.get("output_tokens"), + cached_tokens=u.get("cached_tokens"))) + elif e == "tool" and last_agent is not None: + pending = [tc for tc in last_agent["tool_calls"] + if not any(r["source_call_id"] == tc["tool_call_id"] + for r in last_agent["observation"]["results"])] + if pending: + tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or [])) + elif e in ("end", "abort"): + end = d + tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl", + agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model, + effort=ep.effort, provider=ep.provider or self.provider), + tools=[t["name"] for t in (start or {}).get("tools") or []]) + tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")), + native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"], + total_cached_tokens=tot["cached"]) + tw.write() + h.info.update(traj=tw, start=start, first_user=first_user) + if start and first_user is not None: # the same string a native harness gets as its first message + readme = open(os.path.join(ep.sandbox, "README.md")).read() + h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme) + # the same composition as base.first_message_text: identical sha256 for the same instance + h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user + return tw + + def audit(self, h): + ep = h.ep + start = h.info.get("start") or {} + tools, _ = C.tool_schemas() + v = [] + if start and start.get("tools") != tools: + v.append("driver tools differ from the contract's tool schemas") + if h.info.get("instructions_match_readme") is False: + v.append("driver instructions != preamble + README") + out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"]) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/real/driver_template.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/real/driver_template.py new file mode 100644 index 0000000000000000000000000000000000000000..e9381480b80fc81dc062c16f1a40b8ebe0475158 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/real/driver_template.py @@ -0,0 +1,196 @@ +"""Skeleton of a hardware driver for LFF-Bench (spec: DRIVER.md). Copy this file and protocol.py to the robot PC, +fill in the five methods marked TODO, run scripts/real_check_driver.py until every check passes. + + python driver_template.py --port 9900 [--token ] [--log ] + +Only Python 3 + numpy + Pillow are needed here (plus your robot / camera SDKs). Keep the server on 127.0.0.1; the +benchmark machine reaches it through an SSH tunnel (DRIVER.md §7). + +What is already done for you: the HTTP protocol, the token, the operator's terminal prompts, the safety checks that +must run before every motion (hard workspace box, speed limit), the motion timing, and an optional recorder that saves +both cameras to an mp4 per attempt. Everything robot-specific is in the TODO methods. +""" +import argparse +import os +import threading +import time + +import numpy as np + +try: # copied next to protocol.py on the robot PC + from protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize +except ImportError: # inside the repo (python -m lffbench.real.driver_template) + from .protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize + +# ---------------------------------------------------------------------------------------------- your setup (edit) +ROBOT = "AgileX PiPER" # TODO: the arm's name as the agent will read it ("You control a real robot arm") +N_JOINTS = 6 # TODO +# Hard workspace of the GRASP POINT in the robot-base frame (metres). Rejected targets never move the arm. Choose it so +# that every point inside is reachable with the gripper pointing straight down at any yaw in YAW_RANGE_DEG, and the +# lower z bound keeps the fingertips >= 5 mm above the table (the boxes are pushed with the fingertips ~1 cm up). +WORKSPACE_LO = [0.15, -0.25, 0.00] # TODO: measure on your table +WORKSPACE_HI = [0.45, 0.25, 0.30] # TODO +YAW_RANGE_DEG = [-120.0, 120.0] # TODO: gripper yaw your wrist reaches (span >= 180) +MAX_SPEED = 0.25 # m/s, the fastest straight-line speed you allow (the agent may ask for less) +HOME = dict(x=0.25, y=0.0, z=0.20, yaw_deg=0.0) # TODO: above the table centre, out of the agentview's way if possible +REACH_TOL = 0.004 # m: a move counts as finished when within this of the target and stopped +MOVE_TIMEOUT = 30.0 # s +DRIVER_VERSION = "template-0" # TODO: your git commit / date + + +class MyDriver(DriverServer): + image_format = "jpeg" # "png" is lossless but ~5x larger; jpeg q95 is fine over a LAN / SSH tunnel + + def __init__(self, record_dir=""): + self.lock = threading.RLock() # hardware access from the recorder thread and from requests + self.record_dir = record_dir + self.recorder = None + # TODO: connect to the arm, enable it, set the TCP (grasp point = midway between the fingertips, about 1 cm + # above their tips), open the cameras. Example for PiPER (piper_sdk; check the SDK docs, not verified here): + # from piper_sdk import C_PiperInterface_V2 + # self.arm = C_PiperInterface_V2("can0"); self.arm.ConnectPort(); ... enable ... + # Cameras: "agentview" = fixed camera looking at the table from the front/side (sees the whole work area); + # "wrist" = camera on the gripper. E.g. cv2.VideoCapture / pyrealsense2 colour stream. + raise NotImplementedError("connect the arm and the cameras") + + # ------------------------------------------------------------------ TODO 1: low-level hardware + def _send_cartesian(self, x, y, z, yaw_deg, speed): + """Start a straight-line (MoveL) motion of the grasp point to (x, y, z) with the gripper pointing straight down + and rotated by yaw_deg about the base z axis (0 = fingers close along the base y axis, +90 = along the base x + axis, counter-clockwise seen from above). Return False if the controller refuses (no IK).""" + raise NotImplementedError + + def _read_pose(self): + """-> (xyz of the grasp point in the base frame [m], yaw_deg, joint angles [rad], is_moving: bool).""" + raise NotImplementedError + + def _set_gripper(self, close): + """Close (force-limited, stop when blocked) or open fully; return when the fingers have stopped.""" + raise NotImplementedError + + def _gripper_width(self): + """Opening between the fingertips, metres.""" + raise NotImplementedError + + def _grab(self): + """-> {"agentview": HxWx3 uint8 RGB, "wrist": ...}: the newest frames (flush camera buffers first).""" + raise NotImplementedError + + def ik(self, eef_pos, yaw_deg): + """Optional (set info()["ik"] = True), needed only for real_bias_place: joint angles that put the grasp point + at eef_pos / yaw_deg (pointing down), the solution closest to the current joints. Do NOT move the arm.""" + raise NotImplementedError + + # ------------------------------------------------------------------ protocol (normally no need to edit) + def info(self): + return dict(protocol=PROTOCOL_VERSION, robot=ROBOT, n_joints=N_JOINTS, cameras=list(CAMERAS), + workspace=dict(lo=WORKSPACE_LO, hi=WORKSPACE_HI), yaw_range_deg=YAW_RANGE_DEG, max_speed=MAX_SPEED, + ik=False, driver_version=DRIVER_VERSION) + + def state(self): + with self.lock: + xyz, yaw, q, _ = self._read_pose() + return dict(eef_pos=[float(v) for v in xyz], eef_yaw_deg=float(yaw), gripper_width_m=float(self._gripper_width()), + joint_pos_rad=[float(v) for v in q]) + + def _inside(self, x, y, z, yaw_deg): + p = np.array([x, y, z]) + return (bool(np.all(p >= WORKSPACE_LO) and np.all(p <= WORKSPACE_HI)) + and YAW_RANGE_DEG[0] <= yaw_deg <= YAW_RANGE_DEG[1]) + + def move(self, x, y, z, yaw_deg, speed): + if not self._inside(x, y, z, yaw_deg): + return False, "outside the hard workspace", 0.0 + speed = MAX_SPEED if speed is None else float(np.clip(speed, 0.005, MAX_SPEED)) + with self.lock: + t0 = time.time() + if not self._send_cartesian(x, y, z, yaw_deg, speed): + return False, "no IK solution", 0.0 + tgt = np.array([x, y, z]) + while True: # blocking: return only once the arm has stopped + xyz, _, _, moving = self._read_pose() + if not moving and np.linalg.norm(np.asarray(xyz) - tgt) < REACH_TOL: + break + if time.time() - t0 > MOVE_TIMEOUT: + if not moving: + break # stopped short (blocked by an object): a normal outcome, the agent sees the pose + raise RuntimeError("move timed out while still moving") # -> fault: the run stops + time.sleep(0.02) + return True, None, time.time() - t0 + + def gripper(self, close): + with self.lock: + t0 = time.time() + self._set_gripper(close) + return time.time() - t0 + + def home(self): + ok, err, _ = self.move(HOME["x"], HOME["y"], HOME["z"], HOME["yaw_deg"], 0.15) + if not ok: + raise RuntimeError(f"cannot reach the home pose: {err}") + self.gripper(False) + return self.state() + + def images(self): + with self.lock: + return self._grab() + + def event(self, ev, run="", attempt=None, **kw): + if not self.record_dir: + return + if ev == "attempt_start": + self._stop_recording() + try: + self.recorder = Recorder(self, os.path.join(self.record_dir, f"{run}_a{attempt}.mp4")) + except Exception as e: # the video is only for the record: a missing imageio must not end a run as a fault + print(f"WARNING: recorder not started ({type(e).__name__}: {e}); " + "pip install imageio imageio-ffmpeg", flush=True) + elif ev in ("attempt_end", "episode_end", "session_end", "run_invalid"): + self._stop_recording() + + def _stop_recording(self): + if self.recorder is not None: + self.recorder.stop() + self.recorder = None + + +class Recorder(threading.Thread): + """agentview | wrist side by side at ~5 fps while an attempt runs (needs imageio + imageio-ffmpeg).""" + + def __init__(self, drv, path, fps=5, res=360): + super().__init__(daemon=True) + import imageio + self.drv, self.fps, self.res, self.halt = drv, fps, res, threading.Event() + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + self.w = imageio.get_writer(path, fps=fps, macro_block_size=8) + self.start() + + def run(self): + while not self.halt.is_set(): + t0 = time.time() + try: + with self.drv.lock: + f = self.drv._grab() + self.w.append_data(np.concatenate([square_resize(f[c], self.res) for c in CAMERAS], axis=1)) + except Exception as e: # never let the recorder break a run + print("recorder:", e) + self.halt.wait(max(0.0, 1.0 / self.fps - (time.time() - t0))) + + def stop(self): + self.halt.set() + self.join(timeout=5) + self.w.close() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=9900) + ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", "")) + ap.add_argument("--log", default="driver_logs", help="operator answers (operator.jsonl) and attempt videos") + a = ap.parse_args() + os.makedirs(a.log, exist_ok=True) + MyDriver(record_dir=a.log).serve(a.port, token=a.token or None, operator_log=os.path.join(a.log, "operator.jsonl")) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/real/executor.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/real/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..edb5a9a3932e891684f2a2c17bb8024c994d46dd --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/real/executor.py @@ -0,0 +1,138 @@ +"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor. + +robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and +call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver +(lffbench/real/protocol.py) instead of the simulator. + +Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and +reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the +ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation. +""" +import math +import time + +import numpy as np + +from ..agent.images import ImageRef +from ..agent.tools import ToolResult, parse_args +from .protocol import CAMERAS, DriverError, square_resize, state_problems + +SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class RealToolExecutor: + def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS): + self.driver, self.info = driver, info + self.bias = np.zeros(3) if bias is None else np.asarray(bias, float) + self.image_res = int(image_res) + self.cams = tuple(cams) + self.n_joints = int(info["n_joints"]) + self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"]) + self.max_speed = float(info["max_speed"]) + self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver + self.n_calls = 0 + self._state = None + self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open) + self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents + self.refresh() + self.yaw_cmd = float(self._state["eef_yaw_deg"]) + + # ------------------------------------------------------------------ state + def _set_state(self, st): + prob = state_problems(st, self.n_joints) + if prob: + raise DriverError("driver state: " + "; ".join(prob)) + self._state = st + + def refresh(self): + self._set_state(self.driver.state()) + + def true_eef(self): + return np.asarray(self._state["eef_pos"], float) + + def believed_eef(self): + return self.true_eef() - self.bias + + def proprio(self): + st = self._state + return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1), + gripper="closed" if self.grip_closed else "open", + gripper_width_m=round(float(st["gripper_width_m"]), 4)) + + def joints(self): + """Joint angles as the robot's encoders would report them under the hidden calibration error.""" + if not np.any(self.bias): + return [float(v) for v in self._state["joint_pos_rad"]] + key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"])) + if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command) + self._ik_key = key + self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])] + return list(self._ik_val) + + def observe(self, label=""): + frames, st = self.driver.observe() + self._set_state(st) + return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip()) + for c in self.cams] + + # ------------------------------------------------------------------ helpers + def wrap_yaw(self, yaw): + """The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to + the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit).""" + cands = [yaw + 180.0 * k for k in range(-3, 4)] + ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw_cmd))) + + # ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call) + def call(self, name, raw_args): + t0 = time.time() + self.n_calls += 1 + args = parse_args(raw_args) + fn = getattr(self, f"_t_{name}", None) + if fn is None: + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + res = fn(**args) + res.args, res.wall_s = args, time.time() - t0 + return res + + def _report(self, name, extra=None): + rep = dict(ok=True, tool=name) + rep.update(extra or {}) + rep.update(self.proprio()) + return rep + + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt = np.array([x, y, z], float) + if not np.all(np.isfinite(tgt)): + return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates")) + spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed)) + yaw_used = self.wrap_yaw(float(yaw)) + cmd = tgt + self.bias # the hidden calibration error acts on every commanded position + rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution) + return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; " + "the arm did not move", driver_error=rep.get("error", ""))) + self.yaw_cmd = yaw_used + reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02) + return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached, + yaw_used_deg=round(yaw_used, 1)))) + + def _gripper(self, close): + rep = self.driver.gripper(close) + self.grip_closed = bool(close) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + name = "close_gripper" if close else "open_gripper" + return ToolResult(name, {}, True, self._report(name)) + + def _t_open_gripper(self): + return self._gripper(False) + + def _t_close_gripper(self): + return self._gripper(True) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l1_bias.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/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_auto_002_sonnet/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_auto_002_sonnet/lff/source_closure/lffbench/tasks/l5_slippery_lift.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/l5_slippery_lift.py new file mode 100644 index 0000000000000000000000000000000000000000..1a533e41595c29d413eb2287843cbc50afe7d0dc --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_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/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_clear_cover.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..542d519109d1f085f749fe2db4dd0c20b51281b5 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/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/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_order_dispatch.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..4fbca418828c2aec9e5a248d17a51db00760bef0 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_002_sonnet/lff/source_closure/lffbench/tasks/lh_order_dispatch.py @@ -0,0 +1,242 @@ +"""Development composite: physically load two products and a card, then steer a weighted shipping tray. +L1 fixed calibration bias, L3 card edge strategy, L5 off-centre loaded push. Not in the main set. +""" +import numpy as np +import copy +import xml.etree.ElementTree as ET +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..task_base import LFFTask, register_task +from .l3_card_edge import CardEdge, card_xml, BOARD_HALF, BOARD_TOP, CARD_HALF, GRASP_OUT +from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, HALF, + MASS, MU, box_fit, box_corners, _yaw, _rot) + +PRODUCTS = ('product_red_1', 'product_blue_1') +CARGO = PRODUCTS + ('card_1',) +PH = .014 + + +def shipping_xml(): + xml = long_box_xml('lff_dispatch_box') + parts=[] + for k,(p,h) in enumerate([((.042,0,.025),(.003,.11,.005)),((-.042,0,.025),(.003,.11,.005)), + ((0,.107,.032),(.039,.003,.012)),((0,-.107,.032),(.039,.003,.012))]): + parts.append(f'') + return xml.replace(' ', '\n'.join(parts)+'\n ',1) + + +class DispatchSkills(PushSkills): + def __init__(self, env, task, bias, recorder=None): + super().__init__(env,bias=bias,recorder=recorder,target=task.target_xy(task.inst)) + self.task=task + self.closes=[] + self.correction=np.zeros(3) + self.n_commands=0 + def reported_eef_pos(self): + return self.eef_pos()-self.bias + def move_to(self,target,*args,**kwargs): + self.n_commands+=1 + if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded") + rep=super().move_to(np.asarray(target)-self.correction,*args,**kwargs) + rep['pos']=np.round(self.reported_eef_pos(),4).tolist() + return rep + def _act(self,dpos,drot,grip): + super()._act(dpos,drot,grip) + self.task.monitor_step() + if self.n_steps*.05>=3*self.task.agent_max_steps:raise RuntimeError('dispatch simulation budget exceeded') + def set_gripper(self,close,steps=15): + self.n_commands+=1 + if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded") + ctx=self.task.close_context() if close and self.grip<0 else None + rep=super().set_gripper(close,steps) + if ctx is not None: + ctx.update(held=self.holding('card_1'),width=round(self.gripper_width(),4)) + self.closes.append(ctx) + return rep + + +@register_task +class OrderDispatch(CardEdge,OffcenterPush): + name='lh_order_dispatch' + level='L1' + failure_causes=('L1','L3','L5') + failure_types=failure_causes + 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.') + instruction_indirect=('Pack the two small coloured cubes and the thin red rectangle into the long brown ' + 'container while the container is at its starting position, then push the loaded container with the closed ' + 'gripper completely into the green marked area. Keep every item inside, and finish with the ' + 'gripper open and clear.') + def make_bddl(self): + card=register_generated('LffDispatchCard',card_xml('lff_dispatch_card')) + board=register_generated('LffDispatchBoard',box_xml('lff_dispatch_board',BOARD_HALF,(.62,.45,.27,1),friction=(.3,.005,.0001)),free=False) + box=register_generated('LffDispatchBox',shipping_xml()) + zone_xml=ET.fromstring(rect_frame_xml('lff_dispatch_zone')) + load_xml=ET.fromstring(rect_frame_xml('lff_dispatch_loading',inner_half=(.10,.15),line_rgba=(.8,.6,.05,1),fill_rgba=(.95,.88,.55,1))) + body=zone_xml.find('worldbody/body/body') + for geom in load_xml.find('worldbody/body/body'): + q=np.fromstring(geom.get('pos','0 0 0'),sep=' ');q[0]-=.11;geom.set('pos',' '.join(map(str,q)));body.append(geom) + zone=register_generated('LffDispatchZone',ET.tostring(zone_xml,encoding='unicode'),free=False) + objs=[('card_1',card,'card_region',(-.305,.395,-.295,.405)),('box_1',box,'box_region',(-.255,-.005,-.245,.005))] + for k,o in enumerate(PRODUCTS): + cat=register_generated('LffDispatchProduct'+('Red' if k==0 else 'Blue'),box_xml('lff_dispatch_product_'+str(k),(PH,PH,PH),((.9,.1,.1,1) if k==0 else (.1,.2,.9,1)),density=500)) + objs.append((o,cat,'prod_region'+str(k),(-.305+.25*k,-.405,-.295+.25*k,-.395))) + return write_bddl(self.name,self.instruction,objs,[('board_1',board,'board_region',(.295,.345,.305,.355)),('zone_1',zone,'zone_region',(.295,-.355,.305,-.345))]) + def __init__(self,cam_res=None): + LFFTask.__init__(self,cam_res) + self.board_bid=self.env.sim.model.body_name2id(self.env.fixtures_dict['board_1'].root_body) + self.inst=None;self.mon=None + def sample_instance(self,seed): + rng=np.random.default_rng(seed) + bx=-.18;by=.20 + return dict(seed=int(seed),board_xy=[bx,by],card_xy=[bx,by],card_yaw=0.,card_along='x', + bin_xy=[-.21,-.08],box_xy=[-.21,-.08],target_dist=.11, + bias=[0.,float(rng.choice([-1,1])*.055),0.],com_offset=float(rng.choice([-1,1])*.06), + mechanisms={'L1':True,'L3':True,'L5':True}) + def apply_instance(self,inst): + self.inst=inst + OffcenterPush.apply_instance(self,inst) + m=self.env.sim.model + m.body_pos[self.board_bid]=[*inst['board_xy'],envs.TABLE_Z+BOARD_HALF[2]] + m.body_quat[self.board_bid]=[1,0,0,0] + envs.set_obj_pose(self.env,'card_1',[*inst['card_xy'],BOARD_TOP+CARD_HALF[2]+.0003],yaw=inst['card_yaw']) + for k,o in enumerate(PRODUCTS): + envs.set_obj_pose(self.env,o,[-.25+.14*k,-.31,envs.TABLE_Z+PH+.001]) + bid=envs.body_id(self.env,'box_1') + if not inst['mechanisms']['L5']:m.body_ipos[bid]=[0,0,0];envs.refit_bounds(self.env,bid) + if not inst['mechanisms']['L3']: + # Initial overhang removes the flat-card obstruction; reset-time placement only. + envs.set_obj_pose(self.env,'card_1',[inst['board_xy'][0]-BOARD_HALF[0]+CARD_HALF[0]-.03,inst['board_xy'][1],BOARD_TOP+CARD_HALF[2]+.0003]) + 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=DispatchSkills(self.env,self,np.array(inst['bias']) if inst['mechanisms']['L1'] else np.zeros(3),recorder) + self.mon=dict(start_xy=self.card_pose()['xy'].copy(),max_lift=0.,max_overhang=0.,fell=False, + loaded=False,load_step=None,departed_unloaded=False,events=[],states={o:False for o in CARGO},l1_attempts=[]) + self.sim0=0;self.ncmd=0;self.budget=None + return self.sk + def in_cargo(self,o,require_support=True): + p=envs.obj_pos(self.env,o);b=envs.obj_pos(self.env,'box_1');R=_rot(_yaw(envs.obj_quat(self.env,'box_1'))) + rel=R.T@(p[:2]-b[:2]);half=PH if o in PRODUCTS else 0. + # Full footprint containment, including card corners. + if o=='card_1': + rels=(self.card_corners()[:,:2]-b[:2])@R + footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104)) + else: + rot=self.env.sim.data.body_xmat[envs.body_id(self.env,o)].reshape(3,3) + corners=np.array([p+rot@np.array([a*PH,b*PH,c*PH]) for a in (-1,1) for b in (-1,1) for c in (-1,1)]) + rels=(corners[:,:2]-b[:2])@R + footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104)) + support=any(envs.contacts_between(self.env,envs.obj_geom_ids(self.env,o),envs.obj_geom_ids(self.env,q)) for q in CARGO+('box_1',) if q!=o) + return bool(footprint and (support or not require_support) and b[2]+.015=0 else -1. + grasp=p['xy']+sign*.034*axis + floor=b[2]+HALF[2] + return self.grasp_and_bin(grasp,p['yaw'],floor-.003) + def load_product(self,o,k): + sk=self.sk;p=envs.obj_pos(self.env,o).copy();sk.set_gripper(False,8) + sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0) + approach_offset=(sk.eef_pos()[:2]-p[:2]).tolist() + sk.move_to([p[0],p[1],p[2]+.003],tol=.002,max_steps=120) + offset=(sk.eef_pos()[:2]-p[:2]).tolist() + sk.set_gripper(True,15);sk.move_to([p[0],p[1],envs.TABLE_Z+.19]) + held=sk.holding(o) + self.mon['l1_attempts'].append(dict(item=o,offset=offset,approach_offset=approach_offset,correction=self.sk.correction.tolist(),held=bool(held),step=sk.n_steps)) + if not held:sk.set_gripper(False,8);return False + b=envs.obj_pos(self.env,'box_1');xy=[b[0],b[1]+(-.075 if k==0 else .075)] + sk.move_to([*xy,envs.TABLE_Z+.20]);sk.move_to([*xy,envs.TABLE_Z+.058],speed=.1) + sk.set_gripper(False,12);sk.move_to([*xy,envs.TABLE_Z+.22]);return self.in_cargo(o) + def execute(self,inst,params): + if 'mode' not in params: + return OffcenterPush.execute(self,inst,params) + mode=params['mode'];self.sk.correction=np.asarray(params.get('correction',[0,0,0]),dtype=float) + for k,o in enumerate(PRODUCTS): + if not self.load_product(o,k):return + if mode=='adaptive': + self.sk.correction+=np.array([*self.mon['l1_attempts'][-1]['approach_offset'],0.]) + if mode=='naive': + CardEdge.execute(self,inst,dict(mode='grasp')) + else: + CardEdge.execute(self,inst,dict(mode='edge',overhang=.03)) + self.sk.hold(10) + if not all(self.in_cargo(o) for o in CARGO):return + if mode=='adaptive': + OffcenterPush.adaptive_attempt(self,inst,params.get('c',0.)) + if not self.in_cargo('card_1'):self.repair_card() + else:OffcenterPush.execute(self,inst,dict(c=params.get('c',0.))) + p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.23]);self.sk.set_gripper(False,8) + def outcome(self,inst): + self.sk.hold(30) + p=envs.obj_pos(self.env,'box_1');yaw=_yaw(envs.obj_quat(self.env,'box_1'));fit=box_fit(p[:2],yaw,self.target_xy(inst)) + cargo={o:self.in_cargo(o) for o in CARGO} + velocities=[] + for o in CARGO+('box_1',): + adr=self.env.sim.model.jnt_dofadr[self.env.sim.model.joint_name2id(self.env.objects_dict[o].joints[0])] + velocities.append(self.env.sim.data.qvel[adr:adr+6].copy()) + static=all(np.linalg.norm(v[:3])<.01 and np.linalg.norm(v[3:])<.15 for v in velocities) + m=self.env.sim.model + robot=[g for g in range(m.ngeom) if (m.geom_id2name(g) or '').startswith(('robot0_','gripper0_'))] + touching=any(envs.contacts_between(self.env,robot,envs.obj_geom_ids(self.env,o)) for o in CARGO+('box_1',)) + upright=envs.obj_upright_cos(self.env,'box_1')>.95 + success=bool(all(cargo.values()) and self.mon['loaded'] and not self.mon['departed_unloaded'] and fit['inside'] and static and upright and not touching and self.sk.grip<0) + bad=[m for m in self.sk.box_moves if m.get('bad') and not m.get('gripper_open') and self.mon['load_step'] is not None and m['step']>=self.mon['load_step']] + return copy.deepcopy(dict(success=success,cargo=cargo,loaded_in_start=bool(self.mon['loaded']),load_step=self.mon['load_step'],departed_unloaded=self.mon['departed_unloaded'],inside=fit['inside'],static=bool(static), + failure=None if success else 'cargo' if not all(cargo.values()) else 'loading_order' if not self.mon['loaded'] else 'delivery', + stages={**cargo,'loaded_in_start':self.mon['loaded'],'delivery':fit['inside']},events=self.mon['events'], + l1_attempts=self.mon['l1_attempts'],card_closes=self.sk.closes,card_lift=self.mon['max_lift'], + box_moves=self.sk.box_moves,l5_triggered=bool(bad),yaw_deg=float(np.degrees(yaw)), + sim_s=self.sk.n_steps*.05,commands=self.sk.n_commands,touching=bool(touching),upright=bool(upright), + detail='Cargo in tray: '+str(cargo)+'; tray inside delivery rectangle: '+str(fit['inside'])+'.')) + def default_params(self,inst):return dict(mode='naive') + def oracle_params(self,inst):return dict(mode='oracle',correction=(inst['bias'] if inst['mechanisms']['L1'] else [0,0,0]),c=inst['com_offset'] if inst['mechanisms']['L5'] else 0.) + def adapt_params(self,inst,history): + # Calibration estimate from the measured failed grasp, not hidden bias. + offsets=[x['offset'] for h in history for x in h['outcome']['l1_attempts']] + calibrations=[np.array(x.get('correction',h['params'].get('correction',[0,0,0])))+np.array([*x.get('approach_offset',x['offset']),0.]) for h in history for x in h['outcome']['l1_attempts']] + corr=np.mean(calibrations[-2:],axis=0).tolist() if calibrations else history[-1]['params'].get('correction',[0,0,0]) + moves=[m for h in history for m in h['outcome']['box_moves']] + return dict(mode='adaptive',correction=corr,c=self.bracket(moves)) + def blind_params(self,inst,attempt,rng):return dict(mode='naive',correction=[*rng.normal(0,.005,2),0.]) + def run_scripted(self,*args,**kwargs):return LFFTask.run_scripted(self,*args,**kwargs) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/envs.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/envs.py new file mode 100644 index 0000000000000000000000000000000000000000..6458cf95f3fe41dae232ea814c6ba7351ac0caa4 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/envs.py @@ -0,0 +1,325 @@ +"""Environment construction and low-level sim helpers on top of LIBERO / robosuite.""" +import os + +os.environ.setdefault("MUJOCO_GL", "osmesa") +os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa") +# LIBERO reads its paths from /config.yaml (written by setup/install.sh into /.libero) +os.environ.setdefault("LIBERO_CONFIG_PATH", os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".libero")) + +import numpy as np + +TABLE_Z = 0.90 # LIBERO main_table top surface (table_offset z) +# Upper limit of the Panda elbow (robot0_joint4; stock -0.0698). The arm is fully stretched at about -0.47 rad; a fast +# move out of a far pose could carry the elbow past that into (-0.47, -0.07], where the OSC's only way to shorten the +# arm runs into the stock limit and every later move stops 4-17 cm short for the rest of the attempt (measured +# 2026-10-19: 50 of 160 targets of the workspace box; 44 of 714 logged LA attempts). Capping the joint keeps the elbow +# on the normal side: reach is unchanged, and no scripted oracle / naive run of the main set goes above -0.73. +ELBOW_Q4_MAX = -0.55 + + +def make_env(bddl_path, cam_res=256, cams=("agentview", "robot0_eye_in_hand"), depth=False, controller=None): + """Build a LIBERO env from a BDDL file without camera rendering on every step. + + Images are rendered on demand with `render(env, cam)`. + """ + import robosuite as suite + import libero.libero.envs.bddl_utils as BDDLUtils + from libero.libero.envs import TASK_MAPPING + + cfg = suite.load_controller_config(default_controller="OSC_POSE") + if controller is None: + from .skills import CONTROLLER + controller = CONTROLLER + if controller: + cfg.update(controller) + info = BDDLUtils.get_problem_info(bddl_path) + env = TASK_MAPPING[info["problem_name"]]( + bddl_path, + robots=["Panda"], + controller_configs=cfg, + gripper_types="default", + initialization_noise=None, + use_camera_obs=False, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + horizon=10 ** 7, + ignore_done=True, + hard_reset=False, + camera_names=list(cams), + camera_heights=cam_res, + camera_widths=cam_res, + camera_depths=depth, + camera_segmentations=None, + renderer="mujoco", + renderer_config=None, + ) + env.lff_language = info["language_instruction"] + m = env.sim.model # hard_reset=False: the model (and this limit) survives env.reset() + m.jnt_range[m.joint_name2id("robot0_joint4"), 1] = ELBOW_Q4_MAX + return env + + +def render(env, cam="agentview", res=256, depth=False): + """Render an RGB image (H, W, 3, uint8), upright.""" + out = env.sim.render(camera_name=cam, width=res, height=res, depth=depth) + if depth: + rgb, d = out + return rgb[::-1].copy(), d[::-1].copy() + return out[::-1].copy() + + +# ---------------------------------------------------------------- object state helpers + +def body_id(env, obj_name): + return env.sim.model.body_name2id(env.objects_dict[obj_name].root_body) + + +def obj_pos(env, obj_name): + return env.sim.data.body_xpos[body_id(env, obj_name)].copy() + + +def obj_quat(env, obj_name): + """wxyz""" + return env.sim.data.body_xquat[body_id(env, obj_name)].copy() + + +def obj_upright_cos(env, obj_name): + """cos of the angle between the object's z axis and world z.""" + xmat = env.sim.data.body_xmat[body_id(env, obj_name)].reshape(3, 3) + return float(xmat[2, 2]) + + +def free_joint_addr(env, obj_name): + jname = env.objects_dict[obj_name].joints[0] + jid = env.sim.model.joint_name2id(jname) + return env.sim.model.jnt_qposadr[jid], env.sim.model.jnt_dofadr[jid] + + +def set_obj_pose(env, obj_name, pos, yaw=0.0, quat_wxyz=None): + """Teleport a free-joint object (used only at reset / by the protocol, never by agents).""" + qa, da = free_joint_addr(env, obj_name) + if quat_wxyz is None: + quat_wxyz = np.array([np.cos(yaw / 2), 0, 0, np.sin(yaw / 2)]) + env.sim.data.qpos[qa:qa + 3] = pos + env.sim.data.qpos[qa + 3:qa + 7] = quat_wxyz + env.sim.data.qvel[da:da + 6] = 0.0 + + +def obj_geom_ids(env, obj_name): + return [env.sim.model.geom_name2id(g) for g in env.objects_dict[obj_name].contact_geoms] + + +def set_friction(env, obj_name, mu, priority=2): + """Set sliding friction of an object's collision geoms and give them priority so their + friction is used in contacts (MuJoCo otherwise takes the max of the two geoms).""" + for g in obj_geom_ids(env, obj_name): + env.sim.model.geom_friction[g, 0] = mu + env.sim.model.geom_priority[g] = priority + + +def scale_mass(env, obj_name, mass): + bid = body_id(env, obj_name) + m0 = env.sim.model.body_mass[bid] + env.sim.model.body_mass[bid] = mass + env.sim.model.body_inertia[bid] *= mass / max(m0, 1e-9) + + +def settle(env, steps=20): + """Let physics settle while holding the arm still.""" + for _ in range(steps): + env.step(np.zeros(env.action_dim)) + + +def contacts_between(env, geoms_a, geoms_b): + a, b = set(geoms_a), set(geoms_b) + d = env.sim.data + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in a and c.geom2 in b) or (c.geom1 in b and c.geom2 in a): + return True + return False + + +def robot_geom_ids(env): + m = env.sim.model + ids = [] + for g in range(m.ngeom): + n = m.geom_id2name(g) or "" + if n.startswith("robot0_") or n.startswith("gripper0_"): + ids.append(g) + return ids + + +# ---------------------------------------------------------------- upright placement (added 2026-10-06) + +def _quat_mul(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 canonical_quat(env, obj_name): + """The orientation LIBERO's own placement gives an object, with any random yaw set to 0 (wxyz). + + Reproduces LIBERO exactly, including its convention bug: TableRegionSampler._sample_quat builds an + xyzw quaternion, multiplies it with obj.init_quat (xyzw), and bddl_base_domain writes that array + straight into the wxyz qpos slot. E.g. scanned objects (plate, bowls, basket; rotation (pi/2, pi/2) + about x) therefore end up yawed by 90 deg, not rolled; HOPE groceries (dict rotation) come out + as (0.5, 0.5, 0.5, 0.5), which is the same under both readings. (Fixed 2026-10-06 after the L3 + developer found plates being stood on edge.)""" + from robosuite.utils.transform_utils import quat_multiply + + o = env.objects_dict[obj_name] + rot = getattr(o, "rotation", None) + ax = getattr(o, "rotation_axis", None) or "z" + + def xyzw(axis, a): + h = a / 2 + return {"x": np.array([np.sin(h), 0.0, 0.0, np.cos(h)]), + "y": np.array([0.0, np.sin(h), 0.0, np.cos(h)]), + "z": np.array([0.0, 0.0, np.sin(h), np.cos(h)])}[axis] + + def fixed(r): # a random range means a free angle -> use 0 (only yaw ranges occur in practice) + return float(r[0]) if float(min(r)) == float(max(r)) else 0.0 + + if isinstance(rot, dict): + q = np.array([0.0, 0.0, 0.0, 1.0]) + for axis, r in rot.items(): + q = quat_multiply(xyzw(axis, fixed(r)), q) + else: + if rot is None: + a = 0.0 + elif isinstance(rot, (tuple, list)): + a = fixed(rot) + else: + a = float(rot) + q = xyzw(ax, a) + init = np.array(getattr(o, "init_quat", [0.0, 0.0, 0.0, 1.0]), dtype=float) + q = quat_multiply(q, init) + return np.array(q, dtype=float) # used directly as wxyz, like LIBERO does + + +def obj_min_z(env, obj_name): + """Lowest world z of the object's collision geoms (exact for boxes, AABB bound for meshes).""" + m, d = env.sim.model, env.sim.data + zmin = np.inf + for g in obj_geom_ids(env, obj_name): + R = d.geom_xmat[g].reshape(3, 3) + c_local = m.geom_aabb[g, :3] + half = m.geom_aabb[g, 3:] + cz = d.geom_xpos[g][2] + R[2] @ c_local + zmin = min(zmin, cz - np.abs(R[2]) @ half) + return float(zmin) + + +def obj_max_z(env, obj_name): + """Highest world z of the object's collision geoms (exact for boxes, AABB bound for meshes).""" + m, d = env.sim.model, env.sim.data + zmax = -np.inf + for g in obj_geom_ids(env, obj_name): + R = d.geom_xmat[g].reshape(3, 3) + cz = d.geom_xpos[g][2] + R[2] @ m.geom_aabb[g, :3] + zmax = max(zmax, cz + np.abs(R[2]) @ m.geom_aabb[g, 3:]) + return float(zmax) + + +FINGERTIP_BELOW_SITE = 0.0095 # lowest point of the Panda finger collision meshes below the grasp site (measured) + + +def place_upright(env, obj_name, xy, yaw=0.0, surface_z=TABLE_Z, clearance=0.002): + """Teleport an object upright (LIBERO canonical orientation, then `yaw` about world z) so that its + lowest collision point sits `clearance` above `surface_z`. Call env.sim.forward() / settle after.""" + q = _quat_mul(np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]), canonical_quat(env, obj_name)) + set_obj_pose(env, obj_name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q) + env.sim.forward() + dz = obj_min_z(env, obj_name) - (surface_z + clearance) + qa, _ = free_joint_addr(env, obj_name) + env.sim.data.qpos[qa + 2] -= dz + env.sim.forward() + + +# ---------------------------------------------------------------- collision bounds after runtime edits (2026-10-12) + +def _quat2mat(q): + w, x, y, z = q + return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + + +def _prim_bounds(m, g): + """(half extents in the geom frame, bounding-sphere radius) of a primitive geom from geom_size; None otherwise""" + t, s = int(m.geom_type[g]), m.geom_size[g] + if t == 6: # box + return np.array(s[:3], float), float(np.linalg.norm(s[:3])) + if t == 4: # ellipsoid + return np.array(s[:3], float), float(max(s[:3])) + if t == 2: # sphere + return np.full(3, float(s[0])), float(s[0]) + if t == 5: # cylinder + return np.array([s[0], s[0], s[1]], float), float(np.hypot(s[0], s[1])) + if t == 3: # capsule + return np.array([s[0], s[0], s[0] + s[1]], float), float(s[0] + s[1]) + return None + + +def refit_bounds(model, bodies, margin=0.0, geoms=True): + """Make the collision bounds of `bodies` (body id or ids) consistent again after runtime edits of their geoms + (geom_size / geom_pos / geom_quat) or of their inertial frame (body_ipos / body_iquat). `model`: an env, a + robosuite MjModel wrapper or a raw mujoco.MjModel. + + MuJoCo (3.2.3) computes these bounds at compile time and never updates them: geom_aabb / geom_rbound (geom + frame; broad phase and geom-pair filters) and the per-body bounding-volume hierarchy bvh_aabb, stored in the + body's INERTIAL frame and used by the mid-phase whenever one of the two bodies of a pair has >= 2 collision + geoms. Stale boxes make MuJoCo silently skip contacts (lh_fence v1: a post whose centre of mass was raised sank + 2.2 cm into the table; measured 2026-10-12: a body with a single collision geom whose COM moved 6 cm missed every + contact with a 2-geom body beyond the shifted box). With geoms=True the primitive geoms' geom_aabb / geom_rbound + are recomputed from geom_size (meshes keep theirs); then every BVH node becomes the union of its leaf geoms' + boxes (+ margin) in the runtime inertial frame, following body_sameframe / geom_sameframe like mj_kinematics + (on a pristine model this reproduces the compiled bvh_aabb exactly). + Also note: a runtime body_ipos is ignored by MuJoCo if the compiled inertial pos is the body origin + (body_sameframe = 1); bodies whose centre of mass is moved at runtime need a non-zero compiled inertial pos.""" + if hasattr(model, "sim"): + model = model.sim.model + m = getattr(model, "_model", model) + for b in np.atleast_1d(bodies): + b = int(b) + if geoms: + for g in range(int(m.body_geomadr[b]), int(m.body_geomadr[b] + m.body_geomnum[b])): + pb = _prim_bounds(m, g) + if pb is not None: + m.geom_aabb[g] = [0.0, 0.0, 0.0, *pb[0]] + m.geom_rbound[g] = pb[1] + a, n = int(m.body_bvhadr[b]), int(m.body_bvhnum[b]) + if a < 0 or n < 1: + continue + sf = int(m.body_sameframe[b]) # 1: inertial frame = body frame, 3: same orientation as the body + ip = np.zeros(3) if sf == 1 else np.array(m.body_ipos[b], float) + iR = np.eye(3) if sf in (1, 3) else _quat2mat(m.body_iquat[b]) + + def rec(i): + g = int(m.bvh_nodeid[i]) + if g >= 0: + gsf = int(m.geom_sameframe[g]) # 1: body frame, 2: inertial frame, 3/4: their orientation + gp = np.zeros(3) if gsf == 1 else ip if gsf == 2 else np.array(m.geom_pos[g], float) + gR = np.eye(3) if gsf in (1, 3) else iR if gsf in (2, 4) else _quat2mat(m.geom_quat[g]) + R = iR.T @ gR + c = iR.T @ (gp - ip) + R @ np.asarray(m.geom_aabb[g, :3]) + h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:]) + lo, hi = c - h, c + h + else: + l1, h1 = rec(a + int(m.bvh_child[i][0])) + l2, h2 = rec(a + int(m.bvh_child[i][1])) + lo, hi = np.minimum(l1, l2), np.maximum(h1, h2) + m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin]) + return lo, hi + rec(a) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/skills.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..dd56a43114d6b80192f28dcafab9a36f2351f005 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/skills.py @@ -0,0 +1,156 @@ +"""Motion primitives executed with robosuite's OSC_POSE controller. + +All positions are world-frame metres (LIBERO table top is z = TABLE_Z = 0.90). +`bias` is a hidden calibration error added to every commanded position (used by L1 tasks); +agents never see it. +""" +import numpy as np +import robosuite.utils.transform_utils as T + +from .envs import TABLE_Z + +DT = 0.05 # control period (20 Hz) +ROT_SCALE = 0.5 +# Faster OSC than LIBERO's default (default caps the end effector at ~0.25 m/s; this reaches ~0.6 m/s). +CONTROLLER = dict(kp=300, output_max=[0.1, 0.1, 0.1, 0.5, 0.5, 0.5], output_min=[-0.1, -0.1, -0.1, -0.5, -0.5, -0.5]) + + +def _rotz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def _rot_err(R_target, R_cur): + """axis-angle (world frame) rotating R_cur to R_target""" + R = R_target @ R_cur.T + q = T.mat2quat(R) # xyzw + return T.quat2axisangle(q) + + +class Skills: + def __init__(self, env, bias=None, recorder=None): + self.env = env + self.pos_scale = float(env.robots[0].controller.output_max[0]) + self.bias = np.zeros(3) if bias is None else np.asarray(bias, float) + self.grip = -1.0 # -1 open, +1 closed + self.R0 = self.eef_mat().copy() # top-down orientation at reset == yaw 0 + self.yaw = 0.0 + self.recorder = recorder # callable(env) invoked every `record_every` control steps + self.record_every = 4 + self.n_steps = 0 + self.log = [] + + # ------------------------------------------------------------------ state + def eef_pos(self): + return self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id].copy() + + def eef_mat(self): + return self.env.sim.data.site_xmat[self.env.robots[0].eef_site_id].reshape(3, 3).copy() + + def gripper_width(self): + g = self.env.robots[0].gripper + q = [self.env.sim.data.qpos[self.env.sim.model.joint_name2id(j)] for j in g.joints] + return float(abs(q[0] - q[1])) + + def holding(self, obj_name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, + object_geoms=self.env.objects_dict[obj_name])) + + # ------------------------------------------------------------------ low level + def _act(self, dpos, drot, grip): + a = np.zeros(7) + a[:3] = np.clip(dpos / self.pos_scale, -1, 1) + a[3:6] = np.clip(drot / ROT_SCALE, -1, 1) + a[6] = grip + self.env.step(a) + self.n_steps += 1 + if self.recorder is not None and self.n_steps % self.record_every == 0: + self.recorder(self.env) + + def hold(self, steps=10): + p, R = self.eef_pos(), self._R() + for _ in range(steps): + self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + + def _R(self, yaw=None): + return _rotz(self.yaw if yaw is None else yaw) @ self.R0 + + # ------------------------------------------------------------------ primitives + YAW_LIMIT = np.pi / 2 + 0.4 + + def wrap_yaw(self, yaw): + """A parallel-jaw gripper is symmetric under a rotation by pi, so pick the equivalent yaw closest + to the current one inside |yaw| <= pi/2 + 0.4. Without this, asking for ~180 deg of wrist rotation + makes the OSC (whose axis-angle error is ambiguous at pi) wind the arm into its joint limits and + it never recovers (found by the L3 developer: push towards -y -> 0/6 success, 2026-10-06).""" + cands = [yaw + k * np.pi for k in range(-3, 4)] + ok = [c for c in cands if abs(c) <= self.YAW_LIMIT] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw))) + + def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True): + """Move the gripper site to `target` (world xyz). If `speed` (m/s) is given the reference + moves along a straight line at that speed; otherwise go as fast as the controller allows. + `yaw` is wrapped to the closest gripper-symmetric equivalent unless wrap_yaw=False. + Returns a report dict.""" + 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 + for k in range(max_steps): + if speed is not None: + s = min(dist, s + speed * DT) + ref = p0 + direction * s + # lead the reference a little so the OSC lag does not throttle the speed + ref = ref + direction * min(dist - s, speed * DT * 1.5) + else: + ref = tgt + cur = self.eef_pos() + self._act(ref - cur, _rot_err(R, self.eef_mat()), self.grip) + err = np.linalg.norm(tgt - self.eef_pos()) + if err < tol and (speed is None or s >= dist): + 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) + self.log.append(rep) + return rep + + def set_gripper(self, close, steps=15): + self.grip = 1.0 if close else -1.0 + self.hold(steps) + rep = dict(prim="close" if close else "open", width=round(self.gripper_width(), 4)) + self.log.append(rep) + return rep + + def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15): + """Composite: above -> descend -> close -> lift. For scripted policies.""" + self.set_gripper(False, steps=5) + self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw) + self.move_to([xy[0], xy[1], z_grasp], tol=0.003) + self.set_gripper(True, steps=15) + self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25) + + def place_at(self, xy, z_release, approach=0.10): + self.move_to([xy[0], xy[1], z_release + approach]) + self.move_to([xy[0], xy[1], z_release], tol=0.004) + self.set_gripper(False, steps=12) + self.move_to([xy[0], xy[1], z_release + approach]) + + def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06): + """Straight-line push: go to `pre` m behind the start point at height z with the gripper closed, + then sweep `pre + distance` along direction at `speed`, stop, and lift away.""" + d = np.asarray(direction_xy, float) + d = d / np.linalg.norm(d) + z = TABLE_Z + 0.02 if z is None else z + s = np.asarray(start_xy, float) - d * pre + self.set_gripper(True, steps=5) + self.move_to([s[0], s[1], z + 0.12], yaw=np.arctan2(d[1], d[0]) - np.pi / 2) + self.move_to([s[0], s[1], z], tol=0.003) + e = s + d * (pre + distance) + rep = self.move_to([e[0], e[1], z], speed=speed, tol=0.01, max_steps=400) + self.hold(2) + self.move_to([e[0], e[1], z + 0.12], speed=0.3) + return rep diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/mcp_robot_server.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/mcp_robot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18f433abeec51793dbf999e9da2a165b16d9393d --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/mcp_robot_server.py @@ -0,0 +1,140 @@ +"""MCP server (stdio) exposing one robot_server session to a native agent harness (Claude Code, Codex, Gemini CLI, ...). + +The tools are exactly the unified harness's LA tools (scripts/api_player.py): `robot`, `shell` (jailed, in the episode +workspace) and `view_images` (returned as MCP image content), with the same per-attempt tool-call budget: when it is +used up the attempt is finished automatically and the result is appended to that call's output. So a native harness +and the API harness see the same README, tools and limits; only the agent loop around them differs. + + python scripts/mcp_robot_server.py --session runs/<...>/session.json + python scripts/mcp_robot_server.py --schema-only (launch preflight: same tools/list, no session, every call fails) +Every call is logged to /mcp_transcript.jsonl (the first line lists the names of the environment variables the +harness passed to this process, for the harness self-check). Nothing but JSON-RPC goes to stdout. +The tools themselves are scripts/tool_gateway.py's ToolCore: through the episode's tool gateway when the launcher +started one (gateway.json in the log dir; docs/18 §6.1), otherwise in this process. +""" +import argparse +import json +import os +import sys +import time +import traceback + +ENV_AT_START = dict(os.environ) # what the harness passed (before our own imports touch the environment) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "client")) +from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA # noqa: E402 +from lffbench_client import Session as Client # noqa: E402 +from tool_gateway import GATEWAY_FILE, ToolCore # noqa: E402 + +PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") +TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] + + +class Session: + """One episode's tools. With a tool gateway (scripts/tool_gateway.py, started by harness_run.py; its gateway.json is + in the run's log dir) every call goes to the gateway, which owns the per-attempt budget for the whole episode, also + across the MCP processes of a resumed CLI. Without one, the same ToolCore runs in this process and the budget is + carried over from mcp_transcript.jsonl. Either way the tool outputs are the gateway's ToolCore's, byte for byte.""" + + def __init__(self, session_path): + self.log_dir = os.path.dirname(os.path.abspath(session_path)) + tpath = os.path.join(self.log_dir, "mcp_transcript.jsonl") + gfile = os.path.join(self.log_dir, GATEWAY_FILE) + self.gateway = Client.from_gateway_file(gfile, face="mcp") if os.path.exists(gfile) else None + self.core = None if self.gateway else ToolCore(session_path, carry_from=tpath) + self.calls_in_attempt = self.core.calls_in_attempt if self.core else None + self.finished = self.core.finished if self.core else False + self.tlog = open(tpath, "a") + + def log(self, d): + d["t"] = time.time() + self.tlog.write(json.dumps(d, ensure_ascii=False) + "\n") + self.tlog.flush() + + def call(self, name, args): + """-> (MCP content list, is_error)""" + if self.core is not None: + content, err = self.core.call(name, args) + self.calls_in_attempt, self.finished = self.core.calls_in_attempt, self.core.finished + return content, err + r = self.gateway.call(name, args) + self.calls_in_attempt, self.finished = r.calls_in_attempt, r.finished + return r.content, r.is_error + + +class SchemaOnly: + """No robot session: the harness preflight only needs tools/list (byte-identical to a real session).""" + finished = False + + def log(self, d): + pass + + def call(self, name, args): + return [dict(type="text", text="schema-only preflight server: no robot session")], True + + +def serve(sess): + def send(obj): + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + msg = json.loads(line) + except ValueError: + send(dict(jsonrpc="2.0", id=None, error=dict(code=-32700, message="parse error"))) + continue + mid, method, params = msg.get("id"), msg.get("method"), msg.get("params") or {} + if mid is None: # notification (notifications/initialized, cancelled, ...) + continue + try: + if method == "initialize": + want = params.get("protocolVersion") + result = dict(protocolVersion=want if want in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], + capabilities=dict(tools=dict(listChanged=False)), + serverInfo=dict(name="lffbench-robot", version="1.0")) + elif method == "ping": + result = {} + elif method == "tools/list": + result = dict(tools=[dict(name=t["name"], description=t["description"], inputSchema=t["parameters"]) + for t in TOOLS]) + elif method == "tools/call": + name, args = params.get("name"), params.get("arguments") or {} + t0 = time.time() + content, err = sess.call(name, args) + sess.log(dict(ev="tool", name=name, arguments=args, dt=round(time.time() - t0, 2), is_error=err, + output=[c["text"] for c in content if c["type"] == "text"], + images=sum(1 for c in content if c["type"] == "image"), finished=sess.finished, + calls_in_attempt=getattr(sess, "calls_in_attempt", None))) + result = dict(content=content, isError=err) + else: + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32601, message=f"method not found: {method}"))) + continue + send(dict(jsonrpc="2.0", id=mid, result=result)) + except Exception as e: + sess.log(dict(ev="error", method=method, error=traceback.format_exc()[-2000:])) + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32603, message=f"{type(e).__name__}: {e}"))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--session", help="session.json written by start_robot_session.sh (la style)") + ap.add_argument("--schema-only", action="store_true", help="serve the tool list only (harness launch preflight)") + a = ap.parse_args() + if a.schema_only: + serve(SchemaOnly()) + return + if not a.session: + ap.error("--session is required (or --schema-only)") + sess = Session(a.session) + import hashlib # names + 8-hex sha256 of each value (enough to tell inherited from fresh values, reveals nothing) + sess.log(dict(ev="start", session=a.session, pid=os.getpid(), env_keys=sorted(ENV_AT_START), + env_value_sha8={k: hashlib.sha256(v.encode()).hexdigest()[:8] for k, v in ENV_AT_START.items()})) + serve(sess) + + +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.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/validate_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..58349b4c88968dfe22e0ccbb7ce398754fd98f2c --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/validate_parts_cart.py @@ -0,0 +1,52 @@ +"""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 ['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'],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() diff --git a/leaf/release/source_packages/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/batches.json b/leaf/release/source_packages/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/batches.json new file mode 100644 index 0000000000000000000000000000000000000000..80a3490cb773b02a2f3cb950da5de5fe7a7ca736 --- /dev/null +++ b/leaf/release/source_packages/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/batches.json @@ -0,0 +1,9 @@ +{ + "rcc_devbaseB_sonnet_20261110": { + "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/source/runs/api/rcc_devbaseB_sonnet_20261110/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/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/rejected.json b/leaf/release/source_packages/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/rejected.json new file mode 100644 index 0000000000000000000000000000000000000000..0637a088a01e8ddab3bf3fa98dbe804cbde1a0dc --- /dev/null +++ b/leaf/release/source_packages/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/rejected.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/leaf/release/source_packages/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/release/image_stats.json b/leaf/release/source_packages/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/release/image_stats.json new file mode 100644 index 0000000000000000000000000000000000000000..2340cccf4956c70349a7e3f34a1db47aaffcf6f2 --- /dev/null +++ b/leaf/release/source_packages/supp-20261113-rcc_devbaseB_sonnet_20261110/lff/release/image_stats.json @@ -0,0 +1,1387 @@ +{ + "status": "pass", + "created": "2026-11-13T11:04:10.446583+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": 123, + "observation.images.wrist_image": 123 + }, + "old_zero_std_episode_camera_pairs": 82, + "old_global_image_stats": { + "observation.images.image": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.5585720009701932 + ] + ], + [ + [ + 0.5192743334117472 + ] + ], + [ + [ + 0.4778114398758036 + ] + ] + ], + "std": [ + [ + [ + 0.008907528266854595 + ] + ], + [ + [ + 0.0096633307690528 + ] + ], + [ + [ + 0.009616912241147814 + ] + ] + ], + "count": [ + 8003 + ], + "q01": [ + [ + [ + 0.0819479934962048 + ] + ], + [ + [ + 0.08567482413322296 + ] + ], + [ + [ + 0.07621998437359252 + ] + ] + ], + "q10": [ + [ + [ + 0.3899852429865231 + ] + ], + [ + [ + 0.35700595548130304 + ] + ], + [ + [ + 0.31654713311171934 + ] + ] + ], + "q50": [ + [ + [ + 0.5874488448187888 + ] + ], + [ + [ + 0.5401061480098103 + ] + ], + [ + [ + 0.49408104074191705 + ] + ] + ], + "q90": [ + [ + [ + 0.753175468547152 + ] + ], + [ + [ + 0.6879868212801848 + ] + ], + [ + [ + 0.6223850225684587 + ] + ] + ], + "q99": [ + [ + [ + 0.7872617433005187 + ] + ], + [ + [ + 0.7324377711843939 + ] + ], + [ + [ + 0.6941700959218654 + ] + ] + ] + }, + "observation.images.wrist_image": { + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "mean": [ + [ + [ + 0.5934650816180247 + ] + ], + [ + [ + 0.533917741750535 + ] + ], + [ + [ + 0.4724623777411476 + ] + ] + ], + "std": [ + [ + [ + 0.028616170464236323 + ] + ], + [ + [ + 0.042094433746944354 + ] + ], + [ + [ + 0.05287697460836529 + ] + ] + ], + "count": [ + 8003 + ], + "q01": [ + [ + [ + 0.04953653899595898 + ] + ], + [ + [ + 0.04816675894786891 + ] + ], + [ + [ + 0.033593907577194076 + ] + ] + ], + "q10": [ + [ + [ + 0.16942681972211268 + ] + ], + [ + [ + 0.16907418490069137 + ] + ], + [ + [ + 0.1593064119421857 + ] + ] + ], + "q50": [ + [ + [ + 0.7266070861874675 + ] + ], + [ + [ + 0.6484351357977254 + ] + ], + [ + [ + 0.5654902725630279 + ] + ] + ], + "q90": [ + [ + [ + 0.7863918581733865 + ] + ], + [ + [ + 0.7145264682676097 + ] + ], + [ + [ + 0.6403361623182605 + ] + ] + ], + "q99": [ + [ + [ + 0.8610473077364778 + ] + ], + [ + [ + 0.8019985718902362 + ] + ], + [ + [ + 0.7770979485676718 + ] + ] + ] + } + }, + "new_global_image_stats": { + "observation.images.image": { + "count": [ + 123 + ], + "mean": [ + [ + [ + 0.558898304045799 + ] + ], + [ + [ + 0.5196136640016303 + ] + ], + [ + [ + 0.4780500006071407 + ] + ] + ], + "std": [ + [ + [ + 0.1684242781004645 + ] + ], + [ + [ + 0.14948691572216846 + ] + ], + [ + [ + 0.13531017615213262 + ] + ] + ], + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "q01": [ + [ + [ + 0.08235294117647059 + ] + ], + [ + [ + 0.08627450980392157 + ] + ], + [ + [ + 0.07450980392156863 + ] + ] + ], + "q10": [ + [ + [ + 0.4 + ] + ], + [ + [ + 0.3568627450980392 + ] + ], + [ + [ + 0.3333333333333333 + ] + ] + ], + "q50": [ + [ + [ + 0.5882352941176471 + ] + ], + [ + [ + 0.5411764705882353 + ] + ], + [ + [ + 0.49411764705882355 + ] + ] + ], + "q90": [ + [ + [ + 0.7529411764705882 + ] + ], + [ + [ + 0.6862745098039216 + ] + ], + [ + [ + 0.6235294117647059 + ] + ] + ], + "q99": [ + [ + [ + 0.788235294117647 + ] + ], + [ + [ + 0.7254901960784313 + ] + ], + [ + [ + 0.6901960784313725 + ] + ] + ] + }, + "observation.images.wrist_image": { + "count": [ + 123 + ], + "mean": [ + [ + [ + 0.5914790489942325 + ] + ], + [ + [ + 0.5334318360776094 + ] + ], + [ + [ + 0.47236496061680516 + ] + ] + ], + "std": [ + [ + [ + 0.25325286164972644 + ] + ], + [ + [ + 0.22987468464546848 + ] + ], + [ + [ + 0.21259928448405016 + ] + ] + ], + "min": [ + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ], + [ + [ + 0.0 + ] + ] + ], + "max": [ + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ], + [ + [ + 1.0 + ] + ] + ], + "q01": [ + [ + [ + 0.03529411764705882 + ] + ], + [ + [ + 0.0392156862745098 + ] + ], + [ + [ + 0.023529411764705882 + ] + ] + ], + "q10": [ + [ + [ + 0.1843137254901961 + ] + ], + [ + [ + 0.1843137254901961 + ] + ], + [ + [ + 0.16862745098039217 + ] + ] + ], + "q50": [ + [ + [ + 0.7333333333333333 + ] + ], + [ + [ + 0.6666666666666666 + ] + ], + [ + [ + 0.596078431372549 + ] + ] + ], + "q90": [ + [ + [ + 0.7843137254901961 + ] + ], + [ + [ + 0.7176470588235294 + ] + ], + [ + [ + 0.6470588235294118 + ] + ] + ], + "q99": [ + [ + [ + 0.9176470588235294 + ] + ], + [ + [ + 0.8627450980392157 + ] + ], + [ + [ + 0.8666666666666667 + ] + ] + ] + } + }, + "samples": [ + { + "camera": "observation.images.image", + "episode_index": 0, + "frame_indices": [ + 139, + 278, + 417 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 0, + "frame_indices": [ + 139, + 278, + 417 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 1, + "frame_indices": [ + 211, + 422, + 633 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 1, + "frame_indices": [ + 211, + 422, + 633 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 2, + "frame_indices": [ + 274, + 549, + 824 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 2, + "frame_indices": [ + 274, + 549, + 824 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 3, + "frame_indices": [ + 226, + 452, + 678 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 3, + "frame_indices": [ + 226, + 452, + 678 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 4, + "frame_indices": [ + 268, + 536, + 804 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 4, + "frame_indices": [ + 268, + 536, + 804 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 5, + "frame_indices": [ + 229, + 459, + 689 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 5, + "frame_indices": [ + 229, + 459, + 689 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 6, + "frame_indices": [ + 374, + 748, + 1122 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 6, + "frame_indices": [ + 374, + 748, + 1122 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 7, + "frame_indices": [ + 341, + 683, + 1024 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 7, + "frame_indices": [ + 341, + 683, + 1024 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 8, + "frame_indices": [ + 178, + 356, + 534 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 8, + "frame_indices": [ + 178, + 356, + 534 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 9, + "frame_indices": [ + 218, + 436, + 654 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 9, + "frame_indices": [ + 218, + 436, + 654 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 10, + "frame_indices": [ + 526, + 1053, + 1579 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 10, + "frame_indices": [ + 526, + 1053, + 1579 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 11, + "frame_indices": [ + 483, + 966, + 1449 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 11, + "frame_indices": [ + 483, + 966, + 1449 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 12, + "frame_indices": [ + 478, + 957, + 1435 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 12, + "frame_indices": [ + 478, + 957, + 1435 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 13, + "frame_indices": [ + 363, + 726, + 1089 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 13, + "frame_indices": [ + 363, + 726, + 1089 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 14, + "frame_indices": [ + 625, + 1251, + 1877 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 14, + "frame_indices": [ + 625, + 1251, + 1877 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 15, + "frame_indices": [ + 319, + 638, + 957 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 15, + "frame_indices": [ + 319, + 638, + 957 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 16, + "frame_indices": [ + 269, + 539, + 809 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 16, + "frame_indices": [ + 269, + 539, + 809 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 17, + "frame_indices": [ + 180, + 361, + 541 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 17, + "frame_indices": [ + 180, + 361, + 541 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 18, + "frame_indices": [ + 406, + 812, + 1218 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 18, + "frame_indices": [ + 406, + 812, + 1218 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 19, + "frame_indices": [ + 199, + 398, + 597 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 19, + "frame_indices": [ + 199, + 398, + 597 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 20, + "frame_indices": [ + 242, + 484, + 726 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 20, + "frame_indices": [ + 242, + 484, + 726 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 21, + "frame_indices": [ + 169, + 339, + 509 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 21, + "frame_indices": [ + 169, + 339, + 509 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 22, + "frame_indices": [ + 181, + 362, + 543 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 22, + "frame_indices": [ + 181, + 362, + 543 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 23, + "frame_indices": [ + 217, + 434, + 651 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 23, + "frame_indices": [ + 217, + 434, + 651 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 24, + "frame_indices": [ + 81, + 163, + 245 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 24, + "frame_indices": [ + 81, + 163, + 245 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 25, + "frame_indices": [ + 393, + 787, + 1181 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 25, + "frame_indices": [ + 393, + 787, + 1181 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 26, + "frame_indices": [ + 382, + 765, + 1148 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 26, + "frame_indices": [ + 382, + 765, + 1148 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 27, + "frame_indices": [ + 307, + 615, + 923 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 27, + "frame_indices": [ + 307, + 615, + 923 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 28, + "frame_indices": [ + 414, + 829, + 1244 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 28, + "frame_indices": [ + 414, + 829, + 1244 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 29, + "frame_indices": [ + 214, + 429, + 644 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 29, + "frame_indices": [ + 214, + 429, + 644 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 30, + "frame_indices": [ + 257, + 515, + 773 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 30, + "frame_indices": [ + 257, + 515, + 773 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 31, + "frame_indices": [ + 97, + 195, + 293 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 31, + "frame_indices": [ + 97, + 195, + 293 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 32, + "frame_indices": [ + 182, + 364, + 546 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 32, + "frame_indices": [ + 182, + 364, + 546 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 33, + "frame_indices": [ + 386, + 773, + 1159 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 33, + "frame_indices": [ + 386, + 773, + 1159 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 34, + "frame_indices": [ + 7, + 15, + 22 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 34, + "frame_indices": [ + 7, + 15, + 22 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 35, + "frame_indices": [ + 29, + 58, + 87 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 35, + "frame_indices": [ + 29, + 58, + 87 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 36, + "frame_indices": [ + 481, + 962, + 1443 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 36, + "frame_indices": [ + 481, + 962, + 1443 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 37, + "frame_indices": [ + 607, + 1215, + 1823 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 37, + "frame_indices": [ + 607, + 1215, + 1823 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 38, + "frame_indices": [ + 265, + 530, + 795 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 38, + "frame_indices": [ + 265, + 530, + 795 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 39, + "frame_indices": [ + 197, + 394, + 591 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 39, + "frame_indices": [ + 197, + 394, + 591 + ] + }, + { + "camera": "observation.images.image", + "episode_index": 40, + "frame_indices": [ + 398, + 797, + 1196 + ] + }, + { + "camera": "observation.images.wrist_image", + "episode_index": 40, + "frame_indices": [ + 398, + 797, + 1196 + ] + } + ], + "wall_seconds": 22.088979482650757 +} diff --git a/leaf/release/source_packages/v1.5/lff/release/source_packages/backfill-20261102-lf1_sonnet_r2/lff/batches.json b/leaf/release/source_packages/v1.5/lff/release/source_packages/backfill-20261102-lf1_sonnet_r2/lff/batches.json new file mode 100644 index 0000000000000000000000000000000000000000..ed0f54af566e0a19d3fb4b4465bb36d4515a3ff7 --- /dev/null +++ b/leaf/release/source_packages/v1.5/lff/release/source_packages/backfill-20261102-lf1_sonnet_r2/lff/batches.json @@ -0,0 +1,9 @@ +{ + "lf1_sonnet_r2": { + "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_backfill_20261102/source/runs/api/lf1_sonnet_r2/manifest.json", + "supplement": true, + "selected_runs": 21, + "exported_runs": 20, + "note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config." + } +} diff --git a/videos/observation.images.image/chunk-000/file-011.mp4 b/videos/observation.images.image/chunk-000/file-011.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..baa660bdc12acd897b7f5994840f87daa032e74a --- /dev/null +++ b/videos/observation.images.image/chunk-000/file-011.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13553fec1b38f7b147b64879a40bab08ed72d402959f1aaa09a4ee7c81405992 +size 80570954 diff --git a/videos/observation.images.image/chunk-000/file-036.mp4 b/videos/observation.images.image/chunk-000/file-036.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..043df03d25bc3c9165cadc74c0b9ef0db70b11dc --- /dev/null +++ b/videos/observation.images.image/chunk-000/file-036.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3852e1d3751b6ed1bd9b515d73fe1940c380219544ef1885b1758ee414ba06fb +size 103358625 diff --git a/videos/observation.images.image/chunk-000/file-229.mp4 b/videos/observation.images.image/chunk-000/file-229.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..92a1e3e30cf28f13e789b90b86d9f10bf26b5982 --- /dev/null +++ b/videos/observation.images.image/chunk-000/file-229.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f568d80042dade0a1a50fcee691055ad571b4a162a833ac463f84809fbe861bf +size 65138650 diff --git a/videos/observation.images.image/chunk-000/file-526.mp4 b/videos/observation.images.image/chunk-000/file-526.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..346f96e797206988a872c93c85c66183412e8c68 --- /dev/null +++ b/videos/observation.images.image/chunk-000/file-526.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d715aac0143afc5edca267ae50bbe8536796ac1c142e6e3a18a2e1bc2d65e73a +size 10821505 diff --git a/videos/observation.images.image/chunk-000/file-858.mp4 b/videos/observation.images.image/chunk-000/file-858.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..1cf4715cc3e971daf4c64c61f6b1ebe5acc83391 --- /dev/null +++ b/videos/observation.images.image/chunk-000/file-858.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a56bd5c94bcd472b0455acd9c7b557a1b7997ab02f522748a744abeecf2d8c4f +size 1728361 diff --git a/videos/observation.images.image/chunk-000/file-956.mp4 b/videos/observation.images.image/chunk-000/file-956.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..8a9304ed49961959a97918a911456964b28b9d94 --- /dev/null +++ b/videos/observation.images.image/chunk-000/file-956.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49dc49ace9657ce965596c72b649be6e9c68c049902703d588b05282e1f6d665 +size 60948 diff --git a/videos/observation.images.wrist_image/chunk-000/file-082.mp4 b/videos/observation.images.wrist_image/chunk-000/file-082.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..cea1b362eda53766da34a559c601f9db2380e43f --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-082.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13899cee3b5f189ad8c74be64846656c2aa543480d333889d0dd4b984c767c14 +size 69755116 diff --git a/videos/observation.images.wrist_image/chunk-000/file-093.mp4 b/videos/observation.images.wrist_image/chunk-000/file-093.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..f683afb4a83a2293e2d140d0f5b2683939e4f597 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-093.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:085d8556c08f5f18bb98fb2f2a526d7f74d19784d32a0241dc92d2573175f117 +size 78953495 diff --git a/videos/observation.images.wrist_image/chunk-000/file-100.mp4 b/videos/observation.images.wrist_image/chunk-000/file-100.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..954ed81fcf865a460e95fa9a4f85490851a7df4e --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-100.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b504141ac097de472a2328d05487340ae97852c255fc3bd2b3d0d8074071498d +size 103914075 diff --git a/videos/observation.images.wrist_image/chunk-000/file-109.mp4 b/videos/observation.images.wrist_image/chunk-000/file-109.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..3d0b10d1e39022db7e07f53738b44f29bc1bd82a --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-109.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e2fd99db576a08b03a66ca6d2b8bf958c4dc83060763f77261850c3c7a8cc3d +size 35265508 diff --git a/videos/observation.images.wrist_image/chunk-000/file-115.mp4 b/videos/observation.images.wrist_image/chunk-000/file-115.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..43d0708389daee3ddffac0524279c7da98fa7d32 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-115.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fad2657d93ddaa20c996b3998fcfddbabe642d32802fe1a38c2cad51028cab1a +size 73406172 diff --git a/videos/observation.images.wrist_image/chunk-000/file-185.mp4 b/videos/observation.images.wrist_image/chunk-000/file-185.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..7abe6cb69d0c14edb01097eda783a7cd38bb713d --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-185.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2355c418afc7382544c029213bf8cfc089531f86a55b46366f4b1c3695d85dc0 +size 19896115 diff --git a/videos/observation.images.wrist_image/chunk-000/file-213.mp4 b/videos/observation.images.wrist_image/chunk-000/file-213.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..fba2818e294ac45094c99f1551b57dd06f171159 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-213.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5978521d595824dd316a8e8caf5ef19a5e255f0923f737fb2c59c3bffad5da13 +size 72306695 diff --git a/videos/observation.images.wrist_image/chunk-000/file-239.mp4 b/videos/observation.images.wrist_image/chunk-000/file-239.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a9c917bb4f8eca16ae5896434ff56d8539cb004c --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-239.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:277a66481cb585d05e8095a5945f32a52105f220f8d5f484dd42257e4ec5934a +size 55162542 diff --git a/videos/observation.images.wrist_image/chunk-000/file-243.mp4 b/videos/observation.images.wrist_image/chunk-000/file-243.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..46b0ec3c8b731cc4d4b2d6d0036519cb2d3c0daa --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-243.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8a194f04b6bb4f53431e9cd838345b4f6267b87ce046bbe14652e3b678d28ea +size 34239010 diff --git a/videos/observation.images.wrist_image/chunk-000/file-317.mp4 b/videos/observation.images.wrist_image/chunk-000/file-317.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..6d289dc31c96608625a0680e48917cc5caa08b37 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-317.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4db9bcf5bac28fda92aeced3a3c638615110eb9bcb9ff5a8db748765d3eaaf08 +size 65647870 diff --git a/videos/observation.images.wrist_image/chunk-000/file-321.mp4 b/videos/observation.images.wrist_image/chunk-000/file-321.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..39461206e1d61e9f0944560b13bee583bce1eef8 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-321.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:876ccea450144fed3d7b8d5cc26aaf580862f8fa92cc92214a89524ec5c5ef27 +size 41681872 diff --git a/videos/observation.images.wrist_image/chunk-000/file-498.mp4 b/videos/observation.images.wrist_image/chunk-000/file-498.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..1fedc5e69a8363b3059175213f024a0e72cd6d1b --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-498.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:17b1e205b43c851965801528b526604caad864e6661a66358fd5e34304d734c6 +size 6514717 diff --git a/videos/observation.images.wrist_image/chunk-000/file-515.mp4 b/videos/observation.images.wrist_image/chunk-000/file-515.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a6fd562ad79a57f2a80623807238dc3e0cada59e --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-515.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b316405e038f500f7d3cdd47d4f07a316137488aa1d259ca10a096457eb7d559 +size 34773955 diff --git a/videos/observation.images.wrist_image/chunk-000/file-553.mp4 b/videos/observation.images.wrist_image/chunk-000/file-553.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..8d8b501dc1f1d5922ee795ca22b002a2dd41e84d --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-553.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b96781feef59e0ce9ea1e8582f052f6642e95fcc54c4ef19b40ed854d6e94bb +size 48629076 diff --git a/videos/observation.images.wrist_image/chunk-000/file-652.mp4 b/videos/observation.images.wrist_image/chunk-000/file-652.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..8ce20d7dad82ff9da5d7bad21c9ae2725278cbd9 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-652.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d10daac6bc31170e530e55cead7a6b09850cba6459052d82d550cf83dbea4abb +size 47992197 diff --git a/videos/observation.images.wrist_image/chunk-000/file-713.mp4 b/videos/observation.images.wrist_image/chunk-000/file-713.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..925fa7393ab40325198be0c55fae740f19278bd7 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-713.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b40459cbb89868113a0e5bcebf684be09877411196e3c3024ce61859c4a44544 +size 25570890 diff --git a/videos/observation.images.wrist_image/chunk-000/file-722.mp4 b/videos/observation.images.wrist_image/chunk-000/file-722.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..54b45c4ecc17d48da1b2cb88f8b139ae7cc705cf --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-722.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4a712946fb2983f6849c6c4cc3fd72893aba88bbbc5297b38e1dfa9fc981759 +size 1715029 diff --git a/videos/observation.images.wrist_image/chunk-000/file-723.mp4 b/videos/observation.images.wrist_image/chunk-000/file-723.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..214b4f0ae7aaa506a78b3c611bb8fe245f5ce8d5 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-723.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d651fac053ef466d4922bbac05d316bac6d41d00e74bd9771ddf9a1afbc9a225 +size 23795979 diff --git a/videos/observation.images.wrist_image/chunk-000/file-741.mp4 b/videos/observation.images.wrist_image/chunk-000/file-741.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..8b60d3096b534b53fb3f89650d3f7fc36697873c --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-741.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06752027d363907df7ee16c4794ac09f1762d8d448056683254e3429dbfed0ae +size 14306872 diff --git a/videos/observation.images.wrist_image/chunk-000/file-786.mp4 b/videos/observation.images.wrist_image/chunk-000/file-786.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..cd2f02bf3f59e3d4fdb364c478ba0daf84efcc97 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-786.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4730604e6ec3be3065a051f00834f034c0bad25e33021450d639219eecf57fc +size 4866100 diff --git a/videos/observation.images.wrist_image/chunk-000/file-897.mp4 b/videos/observation.images.wrist_image/chunk-000/file-897.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..aa1d20b22dfd912640354af135a719e11e99998f --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-897.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6db7d1886f95740890db294e356cb0eaf67773f8f62e715eeb9298926da7e18a +size 26505171 diff --git a/videos/observation.images.wrist_image/chunk-000/file-915.mp4 b/videos/observation.images.wrist_image/chunk-000/file-915.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..c6ae4188e3466dc02c03c0fb279559ffaa5b81ba --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-000/file-915.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e698257e8b22f96918598da664327aa4c56e51a953a31d9af504a88f726a2e1e +size 13340859 diff --git a/videos/observation.images.wrist_image/chunk-001/file-008.mp4 b/videos/observation.images.wrist_image/chunk-001/file-008.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..91524f20d8779aa14b489daebb194b236b3a67c7 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-001/file-008.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0f41493a4fb7c13b66b735ccf5080b7d83e3189433b819865e566c00d1dba96 +size 32065556 diff --git a/videos/observation.images.wrist_image/chunk-001/file-025.mp4 b/videos/observation.images.wrist_image/chunk-001/file-025.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..95cb72139f171753957532f71e43962dd18c2a13 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-001/file-025.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35804d2a2c6d2d2997a6ced9e90b483a42d6423ee79ded13c3b4473d361e0d21 +size 27450665 diff --git a/videos/observation.images.wrist_image/chunk-001/file-031.mp4 b/videos/observation.images.wrist_image/chunk-001/file-031.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..4215e993802ffe0488f29d47caff9b028eab6167 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-001/file-031.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:966500350589488ce7f05094df30577bdc555df39e4b4b968c32e73f1241f73f +size 6440138 diff --git a/videos/observation.images.wrist_image/chunk-001/file-041.mp4 b/videos/observation.images.wrist_image/chunk-001/file-041.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..216a486fab3e8b40a837a67e2f154839c8b2c49e --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-001/file-041.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af009ba0e00b7c8129e78a197abcdef11ddce654c157507527dfa8e530924b77 +size 15939499 diff --git a/videos/observation.images.wrist_image/chunk-001/file-046.mp4 b/videos/observation.images.wrist_image/chunk-001/file-046.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..cae566421dac26df96ebc700486ab62772d68ba7 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-001/file-046.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c80da0d06a3ec60d3fc99730bff007aabc6379ffe94d2595f09632e9fd0a2cc +size 41756814 diff --git a/videos/observation.images.wrist_image/chunk-001/file-051.mp4 b/videos/observation.images.wrist_image/chunk-001/file-051.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..9d9361124ae1907434bf3993381ae3b3ce59a6b8 --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-001/file-051.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b01a57878902bfad04b62925db41ccb1075fe068b6bdc79359beadf7a7d105c2 +size 51105082 diff --git a/videos/observation.images.wrist_image/chunk-001/file-056.mp4 b/videos/observation.images.wrist_image/chunk-001/file-056.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..a730fad68c56a10fff2c3f0722a52857f707bbef --- /dev/null +++ b/videos/observation.images.wrist_image/chunk-001/file-056.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ffee7de51fccfc5a697eae52da58f7addeda1a5b37612fa2409be793f01627a +size 40263308