PeterXie666 commited on
Commit
f33d3d1
·
verified ·
1 Parent(s): b0d179d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. leaf/annotations/episode_002822.json +1546 -0
  2. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/anthropic_messages.py +202 -0
  3. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/base.py +82 -0
  4. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/openai_responses.py +240 -0
  5. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/__init__.py +63 -0
  6. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json +15 -0
  7. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/driver_template.py +196 -0
  8. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/headroom_parts_cart.py +19 -0
  9. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/l6_controls.py +92 -0
  10. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/lerobot_replay.py +744 -0
  11. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/redteam_report.py +124 -0
  12. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/__init__.py +21 -0
  13. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/gemini.py +206 -0
  14. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/scripted.py +210 -0
  15. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py +73 -0
  16. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l4_fit_container.py +61 -0
  17. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py +40 -0
  18. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py +61 -0
  19. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py +61 -0
  20. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py +23 -0
  21. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l1_bias.py +390 -0
  22. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l3_tool.py +549 -0
  23. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l5_slippery_lift.py +262 -0
  24. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_clear_cover.py +657 -0
  25. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_order_dispatch.py +242 -0
  26. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_parts_cart.py +253 -0
  27. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/ladder_plan.py +120 -0
  28. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/start_robot_session.sh +24 -0
  29. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json +15 -0
  30. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/tasks/l1_height.py +448 -0
  31. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/tasks/l7_key_turn.py +461 -0
  32. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/tasks/lh_wobbly_table.py +1177 -0
  33. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/agent_compare.py +40 -0
  34. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/ladder_plan.py +120 -0
  35. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/start_robot_session.sh +24 -0
  36. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/summarize.py +33 -0
  37. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_balance_board.py +817 -0
  38. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_bridge.py +1101 -0
  39. leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_nudge_row.py +821 -0
  40. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/base.py +82 -0
  41. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/chat_completions.py +150 -0
  42. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/openai_responses.py +240 -0
  43. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/sensenova.py +24 -0
  44. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l5_loaded_beam.py +598 -0
  45. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py +392 -0
  46. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py +954 -0
  47. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_lid_box.py +715 -0
  48. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_tray_delivery.py +883 -0
  49. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/agent_viewer/viewer.html +111 -0
  50. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/check_breakfast_service.py +48 -0
leaf/annotations/episode_002822.json ADDED
@@ -0,0 +1,1546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "leaf-replay-1",
3
+ "source": {
4
+ "batch": "rc_astra102_20261106",
5
+ "run": "rc_astra102_20261106-gpt-6-astra-recausecodex-harness-hidek_l4_nest_order_s3000_full_F1_direct_k3_1106-161656_p23005",
6
+ "attempts_in_episode": [
7
+ 1
8
+ ],
9
+ "episode_in_run": 0,
10
+ "condition": "with_history",
11
+ "memory_free_chain_of": null,
12
+ "memory_free_rep": null,
13
+ "feedback_level": "F1",
14
+ "hide_k": true,
15
+ "k": 3,
16
+ "perception": "rgb",
17
+ "instruction_variant": "direct",
18
+ "contract_sha256": "13ec4bdd573cbbc56e927e1bb6754c13031ada977017d918a26c9e252fd6eb46",
19
+ "run_status": "done",
20
+ "manifest_id": "0023",
21
+ "replay": {
22
+ "n_reports_checked": 33,
23
+ "n_mismatch": 0,
24
+ "max_eef_dev_m": 0.0
25
+ },
26
+ "backfill_provenance": {
27
+ "original_run": "/mnt/cpfs/workspace/agentic-robotics/worktrees/lffbench-robot-harnesses/runs/api/rc_astra102_20261106/rc_astra102_20261106-gpt-6-astra-recausecodex-harness-hidek_l4_nest_order_s3000_full_F1_direct_k3_1106-161656_p23005",
28
+ "frozen_run": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/source/runs/api/rc_astra102_20261106/rc_astra102_20261106-gpt-6-astra-recausecodex-harness-hidek_l4_nest_order_s3000_full_F1_direct_k3_1106-161656_p23005",
29
+ "runtime": "/mnt/cpfs/workspace/agentic-robotics/ops/lerobot_supp_20261113/source"
30
+ },
31
+ "evaluation_config": {
32
+ "cond": "harness",
33
+ "feedback": "F1",
34
+ "mem": "full",
35
+ "k": 3,
36
+ "rep": 0,
37
+ "task": "l4_nest_order",
38
+ "seed": 3000
39
+ },
40
+ "release_origin": {
41
+ "dataset": "supp-20261113-rc_astra102_20261106",
42
+ "episode_index": 106
43
+ },
44
+ "release_episode_index": 2822,
45
+ "pre_v181_sidecar_index": {
46
+ "episode_index": 106,
47
+ "dataset_index_range": [
48
+ 186618,
49
+ 187244
50
+ ]
51
+ }
52
+ },
53
+ "agent": {
54
+ "harness": "recause_codex",
55
+ "harness_version": "0.163.0",
56
+ "harness_binary_sha256": "399ff69c431c066e40de318fba45c2b07f45a76b19939d247ee4828fc70c4215",
57
+ "model": "gpt-6-astra",
58
+ "effort": "high",
59
+ "provider": "openai",
60
+ "codex_catalog": "generic",
61
+ "auth": "chatgpt",
62
+ "jail": true
63
+ },
64
+ "task": {
65
+ "name": "l4_nest_order",
66
+ "level": "L4",
67
+ "family": "hidden_variable",
68
+ "category": "geometry_inference",
69
+ "capabilities": [
70
+ "Perceive",
71
+ "Reason",
72
+ "Plan"
73
+ ],
74
+ "protocol": "cross",
75
+ "max_attempts": 5,
76
+ "agent_max_steps": 40,
77
+ "instruction": "Nest the red, green and blue cups one inside another.",
78
+ "seed": 3000,
79
+ "instance": {
80
+ "seed": 3000,
81
+ "case": "swap_wide",
82
+ "cups": [
83
+ {
84
+ "name": "cup_1",
85
+ "color": "red",
86
+ "rb": 0.026282668219193048,
87
+ "height": 0.05894672890059716,
88
+ "rim": 0.031439838749931254,
89
+ "xy": [
90
+ -0.10235000133253769,
91
+ -0.08476267747608535
92
+ ],
93
+ "size_rank": 2
94
+ },
95
+ {
96
+ "name": "cup_2",
97
+ "color": "green",
98
+ "rb": 0.013550570155698292,
99
+ "height": 0.037284586903735525,
100
+ "rim": 0.016812548834022282,
101
+ "xy": [
102
+ -0.12921317423076326,
103
+ 0.05323360244217035
104
+ ],
105
+ "size_rank": 0
106
+ },
107
+ {
108
+ "name": "cup_3",
109
+ "color": "blue",
110
+ "rb": 0.019707000078361146,
111
+ "height": 0.09395872823712036,
112
+ "rim": 0.027927323638422305,
113
+ "xy": [
114
+ -0.016114796776300955,
115
+ 0.14000872543275564
116
+ ],
117
+ "size_rank": 1
118
+ }
119
+ ],
120
+ "order": [
121
+ 0,
122
+ 2,
123
+ 1
124
+ ],
125
+ "naive_order": [
126
+ 2,
127
+ 0,
128
+ 1
129
+ ],
130
+ "bottom_cm": [
131
+ 5.26,
132
+ 2.71,
133
+ 3.94
134
+ ],
135
+ "opening_cm": [
136
+ 6.29,
137
+ 3.36,
138
+ 5.59
139
+ ],
140
+ "height_cm": [
141
+ 5.89,
142
+ 3.73,
143
+ 9.4
144
+ ],
145
+ "wrist_apparent": [
146
+ 0.998,
147
+ 0.499,
148
+ 1.0
149
+ ],
150
+ "clear_mm": [
151
+ 4.59,
152
+ 4.77
153
+ ],
154
+ "tol_mm": [
155
+ 12.55,
156
+ 9.67
157
+ ],
158
+ "stuck_cm": {
159
+ "2in1": 0.0,
160
+ "0in2": 0.16
161
+ }
162
+ },
163
+ "paper": {
164
+ "name": "Nest order",
165
+ "cause": "L4",
166
+ "table_cause": "L4",
167
+ "hidden_variable": "Tallest cup is not widest",
168
+ "repair_within_attempt": true,
169
+ "oracle_first_attempt_pct": "100",
170
+ "naive_first_attempt_pct": "25",
171
+ "original_cause": "L4",
172
+ "original_table_cause": "L4"
173
+ },
174
+ "canonical_cause": "L4",
175
+ "paper_long_horizon": false,
176
+ "instruction_original": "Nest the red, green and blue cups one inside another."
177
+ },
178
+ "run_outcome": {
179
+ "outcome_class": null,
180
+ "attempt_history": "S",
181
+ "n_attempts": 1,
182
+ "run_success": true,
183
+ "agent_final_report": "VERDICT: PASS",
184
+ "mean_think_s": 20.19,
185
+ "outcome_class_original": "S?",
186
+ "outcome_class_status": "unresolved"
187
+ },
188
+ "attempts": [
189
+ {
190
+ "attempt": 1,
191
+ "success": true,
192
+ "outcome": {
193
+ "success": true,
194
+ "relations": [
195
+ {
196
+ "cup": 0,
197
+ "on": null,
198
+ "table": true,
199
+ "tilt": 0.01016525467713082,
200
+ "xy": [
201
+ -0.10477516450304172,
202
+ -0.08010596540875631
203
+ ],
204
+ "fallen": false
205
+ },
206
+ {
207
+ "cup": 1,
208
+ "on": 2,
209
+ "height": -4.817521349897991e-05,
210
+ "seated": true,
211
+ "on_rim": false,
212
+ "tilt": 0.0627329044463167,
213
+ "offset": 0.003063773590317316,
214
+ "xy": [
215
+ -0.10359648731463002,
216
+ -0.07247079810609358
217
+ ],
218
+ "fallen": false
219
+ },
220
+ {
221
+ "cup": 2,
222
+ "on": 0,
223
+ "height": -3.007655829667666e-05,
224
+ "seated": true,
225
+ "on_rim": false,
226
+ "tilt": 0.059772959431930825,
227
+ "offset": 0.004755408240373953,
228
+ "xy": [
229
+ -0.1047597980107817,
230
+ -0.07531472250126547
231
+ ],
232
+ "fallen": false
233
+ }
234
+ ],
235
+ "detail": "All three cups are nested: the green cup stands inside the blue cup, which stands inside the red cup.",
236
+ "failure": null
237
+ },
238
+ "finish_reason": "Verified after release and upward retreat: red is outermost, blue is nested upright inside red, and green is inside blue.",
239
+ "feedback_shown": "Attempt succeeded.",
240
+ "auto_ended": false,
241
+ "think_s": 31.146575927734375,
242
+ "feedback_f2": "Attempt succeeded. All three cups are nested: the green cup stands inside the blue cup, which stands inside the red cup.",
243
+ "judge_frames": [
244
+ 586,
245
+ 626
246
+ ],
247
+ "corrected_later_in_run": null,
248
+ "is_last_attempt_of_run": true,
249
+ "agent_finish": {
250
+ "messages": [
251
+ "Final views show green inside blue, with blue inside red."
252
+ ],
253
+ "reasoning": [
254
+ "[\"**Confirming latest comparison**\"]"
255
+ ],
256
+ "viewed": [
257
+ "obs/s033_agentview.jpg",
258
+ "obs/s033_wrist.jpg"
259
+ ],
260
+ "command": "finish reason=\"Verified after release and upward retreat: red is outermost, blue is nested upright inside red, and green is inside blue.\"",
261
+ "reply": {
262
+ "feedback": "Attempt succeeded.",
263
+ "message": "The episode is over. Stop now and report."
264
+ }
265
+ },
266
+ "error_event_in_attempt": null,
267
+ "reviewed_operational_failure": null
268
+ }
269
+ ],
270
+ "commands": [
271
+ {
272
+ "attempt": 1,
273
+ "step": 1,
274
+ "kind": "move_eef",
275
+ "frame_start": 0,
276
+ "frame_end": 22,
277
+ "command": "move_eef z=0.38 gripper=open",
278
+ "args": {
279
+ "z": 0.38,
280
+ "gripper": "open"
281
+ },
282
+ "ok": true,
283
+ "error": null,
284
+ "stopped_from_target": {
285
+ "cm": 0.3,
286
+ "deg": 0.0
287
+ },
288
+ "eef_pos_after": [
289
+ 0.4516,
290
+ -0.0,
291
+ 0.3772
292
+ ],
293
+ "gripper_width_after": 0.0786,
294
+ "holding_after": false,
295
+ "touched_during": false,
296
+ "think_s": 56.21972966194153,
297
+ "agent_obs_images": [
298
+ "obs/s001_agentview.jpg",
299
+ "obs/s001_wrist.jpg"
300
+ ],
301
+ "agent_note": {
302
+ "messages": [
303
+ "I’ll measure cup sizes, choose the nesting order, then verify each insertion. Clearance, hidden rims, grip friction, fragility, attachment, and stability could change the choice; I’ll use short grasp-and-lift checks before carrying."
304
+ ],
305
+ "reasoning": [
306
+ "[\"**Calibrating wrist coordinates**\"]",
307
+ "[\"**Deriving camera transform**\"]"
308
+ ],
309
+ "shell": [
310
+ "pwd; ls -a; cat obs/a1_s000_state.json; command -v apply_patch",
311
+ "cat README.md; ls /usr/bin/*patch* /tmp/*patch* 2>/dev/null"
312
+ ],
313
+ "viewed": [
314
+ "obs/s000_agentview.jpg",
315
+ "obs/s000_wrist.jpg"
316
+ ]
317
+ }
318
+ },
319
+ {
320
+ "attempt": 1,
321
+ "step": 2,
322
+ "kind": "move_eef",
323
+ "frame_start": 22,
324
+ "frame_end": 28,
325
+ "command": "move_eef x=0.5016 z=0.3772",
326
+ "args": {
327
+ "x": 0.5016,
328
+ "z": 0.3772
329
+ },
330
+ "ok": true,
331
+ "error": null,
332
+ "stopped_from_target": {
333
+ "cm": 0.1,
334
+ "deg": 0.0
335
+ },
336
+ "eef_pos_after": [
337
+ 0.5008,
338
+ -0.0,
339
+ 0.378
340
+ ],
341
+ "gripper_width_after": 0.0789,
342
+ "holding_after": false,
343
+ "touched_during": false,
344
+ "think_s": 15.218620777130127,
345
+ "agent_obs_images": [
346
+ "obs/s002_agentview.jpg",
347
+ "obs/s002_wrist.jpg"
348
+ ],
349
+ "agent_note": {
350
+ "reasoning": [
351
+ "[\"**Estimating cup dimensions**\"]"
352
+ ],
353
+ "viewed": [
354
+ "obs/s001_wrist.jpg"
355
+ ]
356
+ }
357
+ },
358
+ {
359
+ "attempt": 1,
360
+ "step": 3,
361
+ "kind": "move_eef",
362
+ "frame_start": 28,
363
+ "frame_end": 47,
364
+ "command": "move_eef x=0.65 y=-0.15 z=0.23",
365
+ "args": {
366
+ "x": 0.65,
367
+ "y": -0.15,
368
+ "z": 0.23
369
+ },
370
+ "ok": true,
371
+ "error": null,
372
+ "stopped_from_target": {
373
+ "cm": 0.1,
374
+ "deg": 0.0
375
+ },
376
+ "eef_pos_after": [
377
+ 0.6511,
378
+ -0.1501,
379
+ 0.231
380
+ ],
381
+ "gripper_width_after": 0.0796,
382
+ "holding_after": false,
383
+ "touched_during": false,
384
+ "think_s": 57.68413758277893,
385
+ "agent_obs_images": [
386
+ "obs/s003_agentview.jpg",
387
+ "obs/s003_wrist.jpg"
388
+ ],
389
+ "agent_note": {
390
+ "messages": [
391
+ "Measurements show red is widest, despite blue being tallest. I’ll nest blue into red, then green into blue."
392
+ ],
393
+ "reasoning": [
394
+ "[\"**Estimating object dimensions**\", \"**Estimating block positions**\", \"**Estimating camera geometry**\"]",
395
+ "[\"**Estimating target coordinates**\"]"
396
+ ],
397
+ "shell": [
398
+ "python3 - <<'PY'\nimport cv2, numpy as np\nfor step in (1,2):\n image=cv2.imread(f'obs/s{step:03d}_wrist.jpg'); hsv=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\n for color,lo,hi in [('red',(0,70,35),(10,255,255)),('green',(35,60,30),(90,255,255)),('blue',(95,70,25),(130,255,255))]:\n mask=cv2.inRange(hsv,np.array(lo),np.array(hi)); contours,_=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n contour=max(contours,key=cv2.contourArea); print(step,color,cv2.boundingRect(contour),cv2.fitEllipse(contour))\nPY"
399
+ ],
400
+ "viewed": [
401
+ "obs/s002_wrist.jpg",
402
+ "obs/s002_agentview.jpg"
403
+ ]
404
+ }
405
+ },
406
+ {
407
+ "attempt": 1,
408
+ "step": 4,
409
+ "kind": "move_eef",
410
+ "frame_start": 47,
411
+ "frame_end": 61,
412
+ "command": "move_eef x=0.65 y=0.15 z=0.23",
413
+ "args": {
414
+ "x": 0.65,
415
+ "y": 0.15,
416
+ "z": 0.23
417
+ },
418
+ "ok": true,
419
+ "error": null,
420
+ "stopped_from_target": {
421
+ "cm": 0.3,
422
+ "deg": 0.3
423
+ },
424
+ "eef_pos_after": [
425
+ 0.6497,
426
+ 0.1528,
427
+ 0.2304
428
+ ],
429
+ "gripper_width_after": 0.0792,
430
+ "holding_after": false,
431
+ "touched_during": false,
432
+ "think_s": 28.192574501037598,
433
+ "agent_obs_images": [
434
+ "obs/s004_agentview.jpg",
435
+ "obs/s004_wrist.jpg"
436
+ ],
437
+ "agent_note": {
438
+ "reasoning": [
439
+ "[\"**Correcting red-object alignment**\", \"**Estimating blue-object position**\"]"
440
+ ],
441
+ "viewed": [
442
+ "obs/s003_wrist.jpg",
443
+ "obs/s003_agentview.jpg"
444
+ ]
445
+ }
446
+ },
447
+ {
448
+ "attempt": 1,
449
+ "step": 5,
450
+ "kind": "move_eef",
451
+ "frame_start": 61,
452
+ "frame_end": 78,
453
+ "command": "move_eef z=0.13 speed=0.12",
454
+ "args": {
455
+ "z": 0.13,
456
+ "speed": 0.12
457
+ },
458
+ "ok": true,
459
+ "error": null,
460
+ "stopped_from_target": {
461
+ "cm": 0.3,
462
+ "deg": 0.0
463
+ },
464
+ "eef_pos_after": [
465
+ 0.6477,
466
+ 0.1522,
467
+ 0.1325
468
+ ],
469
+ "gripper_width_after": 0.0796,
470
+ "holding_after": false,
471
+ "touched_during": false,
472
+ "think_s": 29.431950330734253,
473
+ "agent_obs_images": [
474
+ "obs/s005_agentview.jpg",
475
+ "obs/s005_wrist.jpg"
476
+ ],
477
+ "agent_note": {
478
+ "reasoning": [
479
+ "[\"**Estimating blue cup position**\", \"**Lowering toward blue cup**\"]"
480
+ ],
481
+ "viewed": [
482
+ "obs/s004_agentview.jpg",
483
+ "obs/s004_wrist.jpg"
484
+ ]
485
+ }
486
+ },
487
+ {
488
+ "attempt": 1,
489
+ "step": 6,
490
+ "kind": "move_eef",
491
+ "frame_start": 78,
492
+ "frame_end": 92,
493
+ "command": "move_eef x=0.67 y=0.14 z=0.085 speed=0.08",
494
+ "args": {
495
+ "x": 0.67,
496
+ "y": 0.14,
497
+ "z": 0.085,
498
+ "speed": 0.08
499
+ },
500
+ "ok": true,
501
+ "error": null,
502
+ "stopped_from_target": {
503
+ "cm": 0.2,
504
+ "deg": 0.0
505
+ },
506
+ "eef_pos_after": [
507
+ 0.6696,
508
+ 0.1406,
509
+ 0.0872
510
+ ],
511
+ "gripper_width_after": 0.0798,
512
+ "holding_after": false,
513
+ "touched_during": false,
514
+ "think_s": 73.62426996231079,
515
+ "agent_obs_images": [
516
+ "obs/s006_agentview.jpg",
517
+ "obs/s006_wrist.jpg"
518
+ ],
519
+ "agent_note": {
520
+ "reasoning": [
521
+ "[\"**Estimating blue cup alignment**\", \"**Estimating blue cup alignment**\"]",
522
+ "[\"**Estimating blue target location**\", \"**Testing blue cup grasp**\"]"
523
+ ],
524
+ "viewed": [
525
+ "obs/s005_agentview.jpg",
526
+ "obs/s005_wrist.jpg"
527
+ ]
528
+ }
529
+ },
530
+ {
531
+ "attempt": 1,
532
+ "step": 7,
533
+ "kind": "move_eef",
534
+ "frame_start": 92,
535
+ "frame_end": 107,
536
+ "command": "move_eef gripper=close",
537
+ "args": {
538
+ "gripper": "close"
539
+ },
540
+ "ok": true,
541
+ "error": null,
542
+ "stopped_from_target": null,
543
+ "eef_pos_after": [
544
+ 0.6724,
545
+ 0.1405,
546
+ 0.0911
547
+ ],
548
+ "gripper_width_after": 0.0189,
549
+ "holding_after": false,
550
+ "touched_during": true,
551
+ "think_s": 11.49634075164795,
552
+ "agent_obs_images": [
553
+ "obs/s007_agentview.jpg",
554
+ "obs/s007_wrist.jpg"
555
+ ],
556
+ "agent_note": {
557
+ "reasoning": [
558
+ "[\"**Checking grasp alignment**\"]"
559
+ ],
560
+ "viewed": [
561
+ "obs/s006_agentview.jpg",
562
+ "obs/s006_wrist.jpg"
563
+ ]
564
+ }
565
+ },
566
+ {
567
+ "attempt": 1,
568
+ "step": 8,
569
+ "kind": "move_eef",
570
+ "frame_start": 107,
571
+ "frame_end": 119,
572
+ "command": "move_eef z=0.125 speed=0.06",
573
+ "args": {
574
+ "z": 0.125,
575
+ "speed": 0.06
576
+ },
577
+ "ok": true,
578
+ "error": null,
579
+ "stopped_from_target": {
580
+ "cm": 0.2,
581
+ "deg": 0.0
582
+ },
583
+ "eef_pos_after": [
584
+ 0.6724,
585
+ 0.1406,
586
+ 0.1235
587
+ ],
588
+ "gripper_width_after": 0.0018,
589
+ "holding_after": false,
590
+ "touched_during": true,
591
+ "think_s": 21.68799114227295,
592
+ "agent_obs_images": [
593
+ "obs/s008_agentview.jpg",
594
+ "obs/s008_wrist.jpg"
595
+ ],
596
+ "agent_note": {
597
+ "reasoning": [
598
+ "[\"**Checking edge width**\"]",
599
+ "[\"**Testing cup lift**\"]"
600
+ ],
601
+ "viewed": [
602
+ "obs/s007_agentview.jpg",
603
+ "obs/s007_wrist.jpg"
604
+ ]
605
+ }
606
+ },
607
+ {
608
+ "attempt": 1,
609
+ "step": 9,
610
+ "kind": "move_eef",
611
+ "frame_start": 119,
612
+ "frame_end": 134,
613
+ "command": "move_eef gripper=open",
614
+ "args": {
615
+ "gripper": "open"
616
+ },
617
+ "ok": true,
618
+ "error": null,
619
+ "stopped_from_target": null,
620
+ "eef_pos_after": [
621
+ 0.6723,
622
+ 0.1406,
623
+ 0.1235
624
+ ],
625
+ "gripper_width_after": 0.0777,
626
+ "holding_after": false,
627
+ "touched_during": false,
628
+ "think_s": 22.478098392486572,
629
+ "agent_obs_images": [
630
+ "obs/s009_agentview.jpg",
631
+ "obs/s009_wrist.jpg"
632
+ ],
633
+ "agent_note": {
634
+ "messages": [
635
+ "The first lift slipped; I’ll grasp lower on blue."
636
+ ],
637
+ "reasoning": [
638
+ "[\"**Shifting gripper over cup**\", \"**Lowering gripper onto cup**\"]"
639
+ ],
640
+ "viewed": [
641
+ "obs/s008_agentview.jpg",
642
+ "obs/s008_wrist.jpg"
643
+ ]
644
+ }
645
+ },
646
+ {
647
+ "attempt": 1,
648
+ "step": 10,
649
+ "kind": "move_eef",
650
+ "frame_start": 134,
651
+ "frame_end": 156,
652
+ "command": "move_eef z=0.06 speed=0.06",
653
+ "args": {
654
+ "z": 0.06,
655
+ "speed": 0.06
656
+ },
657
+ "ok": true,
658
+ "error": null,
659
+ "stopped_from_target": {
660
+ "cm": 0.1,
661
+ "deg": 0.0
662
+ },
663
+ "eef_pos_after": [
664
+ 0.6722,
665
+ 0.1405,
666
+ 0.0613
667
+ ],
668
+ "gripper_width_after": 0.0791,
669
+ "holding_after": false,
670
+ "touched_during": false,
671
+ "think_s": 4.20467734336853,
672
+ "agent_obs_images": [
673
+ "obs/s010_agentview.jpg",
674
+ "obs/s010_wrist.jpg"
675
+ ],
676
+ "agent_note": {}
677
+ },
678
+ {
679
+ "attempt": 1,
680
+ "step": 11,
681
+ "kind": "move_eef",
682
+ "frame_start": 156,
683
+ "frame_end": 171,
684
+ "command": "move_eef gripper=close",
685
+ "args": {
686
+ "gripper": "close"
687
+ },
688
+ "ok": true,
689
+ "error": null,
690
+ "stopped_from_target": null,
691
+ "eef_pos_after": [
692
+ 0.6724,
693
+ 0.1405,
694
+ 0.0614
695
+ ],
696
+ "gripper_width_after": 0.0024,
697
+ "holding_after": false,
698
+ "touched_during": true,
699
+ "think_s": 8.01834774017334,
700
+ "agent_obs_images": [
701
+ "obs/s011_agentview.jpg",
702
+ "obs/s011_wrist.jpg"
703
+ ],
704
+ "agent_note": {}
705
+ },
706
+ {
707
+ "attempt": 1,
708
+ "step": 12,
709
+ "kind": "move_eef",
710
+ "frame_start": 171,
711
+ "frame_end": 196,
712
+ "command": "move_eef z=0.14 gripper=open",
713
+ "args": {
714
+ "z": 0.14,
715
+ "gripper": "open"
716
+ },
717
+ "ok": true,
718
+ "error": null,
719
+ "stopped_from_target": {
720
+ "cm": 0.4,
721
+ "deg": 0.0
722
+ },
723
+ "eef_pos_after": [
724
+ 0.676,
725
+ 0.1415,
726
+ 0.1424
727
+ ],
728
+ "gripper_width_after": 0.0777,
729
+ "holding_after": false,
730
+ "touched_during": false,
731
+ "think_s": 32.9790518283844,
732
+ "agent_obs_images": [
733
+ "obs/s012_agentview.jpg",
734
+ "obs/s012_wrist.jpg"
735
+ ],
736
+ "agent_note": {
737
+ "reasoning": [
738
+ "[\"**Aligning with blue cup**\", \"**Retreating above blue cup**\"]"
739
+ ],
740
+ "viewed": [
741
+ "obs/s011_agentview.jpg",
742
+ "obs/s011_wrist.jpg"
743
+ ]
744
+ }
745
+ },
746
+ {
747
+ "attempt": 1,
748
+ "step": 13,
749
+ "kind": "move_eef",
750
+ "frame_start": 196,
751
+ "frame_end": 220,
752
+ "command": "move_eef x=0.62 y=0.14 z=0.065 speed=0.08",
753
+ "args": {
754
+ "x": 0.62,
755
+ "y": 0.14,
756
+ "z": 0.065,
757
+ "speed": 0.08
758
+ },
759
+ "ok": true,
760
+ "error": null,
761
+ "stopped_from_target": {
762
+ "cm": 0.3,
763
+ "deg": 0.0
764
+ },
765
+ "eef_pos_after": [
766
+ 0.6217,
767
+ 0.14,
768
+ 0.0674
769
+ ],
770
+ "gripper_width_after": 0.0792,
771
+ "holding_after": false,
772
+ "touched_during": false,
773
+ "think_s": 6.472083568572998,
774
+ "agent_obs_images": [
775
+ "obs/s013_agentview.jpg",
776
+ "obs/s013_wrist.jpg"
777
+ ],
778
+ "agent_note": {}
779
+ },
780
+ {
781
+ "attempt": 1,
782
+ "step": 14,
783
+ "kind": "move_eef",
784
+ "frame_start": 220,
785
+ "frame_end": 235,
786
+ "command": "move_eef gripper=close",
787
+ "args": {
788
+ "gripper": "close"
789
+ },
790
+ "ok": true,
791
+ "error": null,
792
+ "stopped_from_target": null,
793
+ "eef_pos_after": [
794
+ 0.6217,
795
+ 0.14,
796
+ 0.0674
797
+ ],
798
+ "gripper_width_after": 0.0441,
799
+ "holding_after": true,
800
+ "touched_during": true,
801
+ "think_s": 4.186843633651733,
802
+ "agent_obs_images": [
803
+ "obs/s014_agentview.jpg",
804
+ "obs/s014_wrist.jpg"
805
+ ],
806
+ "agent_note": {}
807
+ },
808
+ {
809
+ "attempt": 1,
810
+ "step": 15,
811
+ "kind": "move_eef",
812
+ "frame_start": 235,
813
+ "frame_end": 246,
814
+ "command": "move_eef z=0.1 speed=0.06",
815
+ "args": {
816
+ "z": 0.1,
817
+ "speed": 0.06
818
+ },
819
+ "ok": true,
820
+ "error": null,
821
+ "stopped_from_target": {
822
+ "cm": 0.2,
823
+ "deg": 0.0
824
+ },
825
+ "eef_pos_after": [
826
+ 0.6216,
827
+ 0.14,
828
+ 0.0978
829
+ ],
830
+ "gripper_width_after": 0.0431,
831
+ "holding_after": true,
832
+ "touched_during": true,
833
+ "think_s": 14.858192682266235,
834
+ "agent_obs_images": [
835
+ "obs/s015_agentview.jpg",
836
+ "obs/s015_wrist.jpg"
837
+ ],
838
+ "agent_note": {
839
+ "reasoning": [
840
+ "[\"**Testing cup lift**\"]"
841
+ ],
842
+ "viewed": [
843
+ "obs/s014_agentview.jpg",
844
+ "obs/s014_wrist.jpg"
845
+ ]
846
+ }
847
+ },
848
+ {
849
+ "attempt": 1,
850
+ "step": 16,
851
+ "kind": "move_eef",
852
+ "frame_start": 246,
853
+ "frame_end": 256,
854
+ "command": "move_eef z=0.22",
855
+ "args": {
856
+ "z": 0.22
857
+ },
858
+ "ok": true,
859
+ "error": null,
860
+ "stopped_from_target": {
861
+ "cm": 0.4,
862
+ "deg": 0.0
863
+ },
864
+ "eef_pos_after": [
865
+ 0.6249,
866
+ 0.1407,
867
+ 0.222
868
+ ],
869
+ "gripper_width_after": 0.042,
870
+ "holding_after": true,
871
+ "touched_during": true,
872
+ "think_s": 23.191052436828613,
873
+ "agent_obs_images": [
874
+ "obs/s016_agentview.jpg",
875
+ "obs/s016_wrist.jpg"
876
+ ],
877
+ "agent_note": {
878
+ "reasoning": [
879
+ "[\"**Positioning over red cup**\"]"
880
+ ],
881
+ "viewed": [
882
+ "obs/s015_agentview.jpg",
883
+ "obs/s015_wrist.jpg"
884
+ ]
885
+ }
886
+ },
887
+ {
888
+ "attempt": 1,
889
+ "step": 17,
890
+ "kind": "move_eef",
891
+ "frame_start": 256,
892
+ "frame_end": 290,
893
+ "command": "move_eef x=0.54 y=-0.09 z=0.22 speed=0.15",
894
+ "args": {
895
+ "x": 0.54,
896
+ "y": -0.09,
897
+ "z": 0.22,
898
+ "speed": 0.15
899
+ },
900
+ "ok": true,
901
+ "error": null,
902
+ "stopped_from_target": {
903
+ "cm": 0.2,
904
+ "deg": 0.1
905
+ },
906
+ "eef_pos_after": [
907
+ 0.5402,
908
+ -0.088,
909
+ 0.2196
910
+ ],
911
+ "gripper_width_after": 0.0403,
912
+ "holding_after": true,
913
+ "touched_during": true,
914
+ "think_s": 5.057240724563599,
915
+ "agent_obs_images": [
916
+ "obs/s017_agentview.jpg",
917
+ "obs/s017_wrist.jpg"
918
+ ],
919
+ "agent_note": {}
920
+ },
921
+ {
922
+ "attempt": 1,
923
+ "step": 18,
924
+ "kind": "move_eef",
925
+ "frame_start": 290,
926
+ "frame_end": 319,
927
+ "command": "move_eef z=0.135 speed=0.06",
928
+ "args": {
929
+ "z": 0.135,
930
+ "speed": 0.06
931
+ },
932
+ "ok": true,
933
+ "error": null,
934
+ "stopped_from_target": {
935
+ "cm": 0.1,
936
+ "deg": 0.0
937
+ },
938
+ "eef_pos_after": [
939
+ 0.5402,
940
+ -0.088,
941
+ 0.1364
942
+ ],
943
+ "gripper_width_after": 0.0373,
944
+ "holding_after": true,
945
+ "touched_during": true,
946
+ "think_s": 19.079057931900024,
947
+ "agent_obs_images": [
948
+ "obs/s018_agentview.jpg",
949
+ "obs/s018_wrist.jpg"
950
+ ],
951
+ "agent_note": {
952
+ "messages": [
953
+ "Blue now holds securely. I’ll lower it into red carefully."
954
+ ],
955
+ "reasoning": [
956
+ "[\"**Lowering blue toward red rim**\"]"
957
+ ],
958
+ "viewed": [
959
+ "obs/s017_agentview.jpg",
960
+ "obs/s017_wrist.jpg"
961
+ ]
962
+ }
963
+ },
964
+ {
965
+ "attempt": 1,
966
+ "step": 19,
967
+ "kind": "move_eef",
968
+ "frame_start": 319,
969
+ "frame_end": 349,
970
+ "command": "move_eef z=0.085 speed=0.035",
971
+ "args": {
972
+ "z": 0.085,
973
+ "speed": 0.035
974
+ },
975
+ "ok": true,
976
+ "error": null,
977
+ "stopped_from_target": {
978
+ "cm": 0.1,
979
+ "deg": 0.0
980
+ },
981
+ "eef_pos_after": [
982
+ 0.5401,
983
+ -0.0879,
984
+ 0.0859
985
+ ],
986
+ "gripper_width_after": 0.0025,
987
+ "holding_after": false,
988
+ "touched_during": true,
989
+ "think_s": 18.76425576210022,
990
+ "agent_obs_images": [
991
+ "obs/s019_agentview.jpg",
992
+ "obs/s019_wrist.jpg"
993
+ ],
994
+ "agent_note": {
995
+ "reasoning": [
996
+ "[\"**Lowering base to 0.085**\"]"
997
+ ],
998
+ "viewed": [
999
+ "obs/s018_agentview.jpg",
1000
+ "obs/s018_wrist.jpg"
1001
+ ]
1002
+ }
1003
+ },
1004
+ {
1005
+ "attempt": 1,
1006
+ "step": 20,
1007
+ "kind": "move_eef",
1008
+ "frame_start": 349,
1009
+ "frame_end": 364,
1010
+ "command": "move_eef gripper=open",
1011
+ "args": {
1012
+ "gripper": "open"
1013
+ },
1014
+ "ok": true,
1015
+ "error": null,
1016
+ "stopped_from_target": null,
1017
+ "eef_pos_after": [
1018
+ 0.5401,
1019
+ -0.0879,
1020
+ 0.0859
1021
+ ],
1022
+ "gripper_width_after": 0.0778,
1023
+ "holding_after": false,
1024
+ "touched_during": true,
1025
+ "think_s": 13.551520824432373,
1026
+ "agent_obs_images": [
1027
+ "obs/s020_agentview.jpg",
1028
+ "obs/s020_wrist.jpg"
1029
+ ],
1030
+ "agent_note": {
1031
+ "reasoning": [
1032
+ "[\"**Opening retreat**\"]"
1033
+ ],
1034
+ "viewed": [
1035
+ "obs/s019_agentview.jpg",
1036
+ "obs/s019_wrist.jpg"
1037
+ ]
1038
+ }
1039
+ },
1040
+ {
1041
+ "attempt": 1,
1042
+ "step": 21,
1043
+ "kind": "move_eef",
1044
+ "frame_start": 364,
1045
+ "frame_end": 373,
1046
+ "command": "move_eef z=0.24",
1047
+ "args": {
1048
+ "z": 0.24
1049
+ },
1050
+ "ok": true,
1051
+ "error": null,
1052
+ "stopped_from_target": {
1053
+ "cm": 0.3,
1054
+ "deg": 0.0
1055
+ },
1056
+ "eef_pos_after": [
1057
+ 0.5427,
1058
+ -0.0879,
1059
+ 0.2398
1060
+ ],
1061
+ "gripper_width_after": 0.0785,
1062
+ "holding_after": false,
1063
+ "touched_during": true,
1064
+ "think_s": 5.021951198577881,
1065
+ "agent_obs_images": [
1066
+ "obs/s021_agentview.jpg",
1067
+ "obs/s021_wrist.jpg"
1068
+ ],
1069
+ "agent_note": {}
1070
+ },
1071
+ {
1072
+ "attempt": 1,
1073
+ "step": 22,
1074
+ "kind": "move_eef",
1075
+ "frame_start": 373,
1076
+ "frame_end": 386,
1077
+ "command": "move_eef x=0.52 y=0.06 z=0.12",
1078
+ "args": {
1079
+ "x": 0.52,
1080
+ "y": 0.06,
1081
+ "z": 0.12
1082
+ },
1083
+ "ok": true,
1084
+ "error": null,
1085
+ "stopped_from_target": {
1086
+ "cm": 0.2,
1087
+ "deg": 0.1
1088
+ },
1089
+ "eef_pos_after": [
1090
+ 0.5182,
1091
+ 0.0603,
1092
+ 0.119
1093
+ ],
1094
+ "gripper_width_after": 0.0794,
1095
+ "holding_after": false,
1096
+ "touched_during": false,
1097
+ "think_s": 25.676311254501343,
1098
+ "agent_obs_images": [
1099
+ "obs/s022_agentview.jpg",
1100
+ "obs/s022_wrist.jpg"
1101
+ ],
1102
+ "agent_note": {
1103
+ "reasoning": [
1104
+ "[\"**Locating green cup**\", \"**Moving toward green cup**\"]"
1105
+ ],
1106
+ "viewed": [
1107
+ "obs/s021_agentview.jpg",
1108
+ "obs/s021_wrist.jpg"
1109
+ ]
1110
+ }
1111
+ },
1112
+ {
1113
+ "attempt": 1,
1114
+ "step": 23,
1115
+ "kind": "move_eef",
1116
+ "frame_start": 386,
1117
+ "frame_end": 419,
1118
+ "command": "move_eef x=0.5 y=0.05 z=0.025 speed=0.06",
1119
+ "args": {
1120
+ "x": 0.5,
1121
+ "y": 0.05,
1122
+ "z": 0.025,
1123
+ "speed": 0.06
1124
+ },
1125
+ "ok": true,
1126
+ "error": null,
1127
+ "stopped_from_target": {
1128
+ "cm": 0.1,
1129
+ "deg": 0.0
1130
+ },
1131
+ "eef_pos_after": [
1132
+ 0.5001,
1133
+ 0.0502,
1134
+ 0.0262
1135
+ ],
1136
+ "gripper_width_after": 0.0799,
1137
+ "holding_after": false,
1138
+ "touched_during": false,
1139
+ "think_s": 25.844438552856445,
1140
+ "agent_obs_images": [
1141
+ "obs/s023_agentview.jpg",
1142
+ "obs/s023_wrist.jpg"
1143
+ ],
1144
+ "agent_note": {
1145
+ "messages": [
1146
+ "Blue remains upright inside red. Next is the smaller green cup."
1147
+ ],
1148
+ "reasoning": [
1149
+ "[\"**Estimating green grasp point**\", \"**Selecting green target**\"]"
1150
+ ],
1151
+ "viewed": [
1152
+ "obs/s022_agentview.jpg",
1153
+ "obs/s022_wrist.jpg"
1154
+ ]
1155
+ }
1156
+ },
1157
+ {
1158
+ "attempt": 1,
1159
+ "step": 24,
1160
+ "kind": "move_eef",
1161
+ "frame_start": 419,
1162
+ "frame_end": 434,
1163
+ "command": "move_eef gripper=close",
1164
+ "args": {
1165
+ "gripper": "close"
1166
+ },
1167
+ "ok": true,
1168
+ "error": null,
1169
+ "stopped_from_target": null,
1170
+ "eef_pos_after": [
1171
+ 0.4999,
1172
+ 0.0503,
1173
+ 0.0261
1174
+ ],
1175
+ "gripper_width_after": 0.0023,
1176
+ "holding_after": false,
1177
+ "touched_during": false,
1178
+ "think_s": 4.249047517776489,
1179
+ "agent_obs_images": [
1180
+ "obs/s024_agentview.jpg",
1181
+ "obs/s024_wrist.jpg"
1182
+ ],
1183
+ "agent_note": {}
1184
+ },
1185
+ {
1186
+ "attempt": 1,
1187
+ "step": 25,
1188
+ "kind": "move_eef",
1189
+ "frame_start": 434,
1190
+ "frame_end": 454,
1191
+ "command": "move_eef z=0.07 gripper=open",
1192
+ "args": {
1193
+ "z": 0.07,
1194
+ "gripper": "open"
1195
+ },
1196
+ "ok": true,
1197
+ "error": null,
1198
+ "stopped_from_target": {
1199
+ "cm": 0.4,
1200
+ "deg": 0.0
1201
+ },
1202
+ "eef_pos_after": [
1203
+ 0.5005,
1204
+ 0.0505,
1205
+ 0.0663
1206
+ ],
1207
+ "gripper_width_after": 0.0777,
1208
+ "holding_after": false,
1209
+ "touched_during": false,
1210
+ "think_s": 29.025872468948364,
1211
+ "agent_obs_images": [
1212
+ "obs/s025_agentview.jpg",
1213
+ "obs/s025_wrist.jpg"
1214
+ ],
1215
+ "agent_note": {
1216
+ "reasoning": [
1217
+ "[\"**Aligning gripper with green**\", \"**Adjusting gripper for green**\"]"
1218
+ ],
1219
+ "viewed": [
1220
+ "obs/s024_agentview.jpg",
1221
+ "obs/s024_wrist.jpg"
1222
+ ]
1223
+ }
1224
+ },
1225
+ {
1226
+ "attempt": 1,
1227
+ "step": 26,
1228
+ "kind": "move_eef",
1229
+ "frame_start": 454,
1230
+ "frame_end": 475,
1231
+ "command": "move_eef x=0.53 y=0.047 z=0.025 speed=0.05",
1232
+ "args": {
1233
+ "x": 0.53,
1234
+ "y": 0.047,
1235
+ "z": 0.025,
1236
+ "speed": 0.05
1237
+ },
1238
+ "ok": true,
1239
+ "error": null,
1240
+ "stopped_from_target": {
1241
+ "cm": 0.1,
1242
+ "deg": 0.0
1243
+ },
1244
+ "eef_pos_after": [
1245
+ 0.5294,
1246
+ 0.0472,
1247
+ 0.0261
1248
+ ],
1249
+ "gripper_width_after": 0.0791,
1250
+ "holding_after": false,
1251
+ "touched_during": true,
1252
+ "think_s": 4.724542140960693,
1253
+ "agent_obs_images": [
1254
+ "obs/s026_agentview.jpg",
1255
+ "obs/s026_wrist.jpg"
1256
+ ],
1257
+ "agent_note": {}
1258
+ },
1259
+ {
1260
+ "attempt": 1,
1261
+ "step": 27,
1262
+ "kind": "move_eef",
1263
+ "frame_start": 475,
1264
+ "frame_end": 490,
1265
+ "command": "move_eef gripper=close",
1266
+ "args": {
1267
+ "gripper": "close"
1268
+ },
1269
+ "ok": true,
1270
+ "error": null,
1271
+ "stopped_from_target": null,
1272
+ "eef_pos_after": [
1273
+ 0.5303,
1274
+ 0.0488,
1275
+ 0.0273
1276
+ ],
1277
+ "gripper_width_after": 0.0342,
1278
+ "holding_after": true,
1279
+ "touched_during": true,
1280
+ "think_s": 5.1884682178497314,
1281
+ "agent_obs_images": [
1282
+ "obs/s027_agentview.jpg",
1283
+ "obs/s027_wrist.jpg"
1284
+ ],
1285
+ "agent_note": {}
1286
+ },
1287
+ {
1288
+ "attempt": 1,
1289
+ "step": 28,
1290
+ "kind": "move_eef",
1291
+ "frame_start": 490,
1292
+ "frame_end": 503,
1293
+ "command": "move_eef z=0.065 speed=0.06",
1294
+ "args": {
1295
+ "z": 0.065,
1296
+ "speed": 0.06
1297
+ },
1298
+ "ok": true,
1299
+ "error": null,
1300
+ "stopped_from_target": {
1301
+ "cm": 0.2,
1302
+ "deg": 0.0
1303
+ },
1304
+ "eef_pos_after": [
1305
+ 0.5303,
1306
+ 0.0489,
1307
+ 0.0633
1308
+ ],
1309
+ "gripper_width_after": 0.0342,
1310
+ "holding_after": true,
1311
+ "touched_during": true,
1312
+ "think_s": 12.185917615890503,
1313
+ "agent_obs_images": [
1314
+ "obs/s028_agentview.jpg",
1315
+ "obs/s028_wrist.jpg"
1316
+ ],
1317
+ "agent_note": {
1318
+ "viewed": [
1319
+ "obs/s027_agentview.jpg",
1320
+ "obs/s027_wrist.jpg"
1321
+ ]
1322
+ }
1323
+ },
1324
+ {
1325
+ "attempt": 1,
1326
+ "step": 29,
1327
+ "kind": "move_eef",
1328
+ "frame_start": 503,
1329
+ "frame_end": 512,
1330
+ "command": "move_eef z=0.18",
1331
+ "args": {
1332
+ "z": 0.18
1333
+ },
1334
+ "ok": true,
1335
+ "error": null,
1336
+ "stopped_from_target": {
1337
+ "cm": 0.3,
1338
+ "deg": 0.0
1339
+ },
1340
+ "eef_pos_after": [
1341
+ 0.5328,
1342
+ 0.0489,
1343
+ 0.1806
1344
+ ],
1345
+ "gripper_width_after": 0.0342,
1346
+ "holding_after": true,
1347
+ "touched_during": true,
1348
+ "think_s": 41.59689116477966,
1349
+ "agent_obs_images": [
1350
+ "obs/s029_agentview.jpg",
1351
+ "obs/s029_wrist.jpg"
1352
+ ],
1353
+ "agent_note": {
1354
+ "reasoning": [
1355
+ "[\"**Aligning green over blue**\", \"**Positioning green above blue**\"]"
1356
+ ],
1357
+ "viewed": [
1358
+ "obs/s028_agentview.jpg",
1359
+ "obs/s028_wrist.jpg"
1360
+ ]
1361
+ }
1362
+ },
1363
+ {
1364
+ "attempt": 1,
1365
+ "step": 30,
1366
+ "kind": "move_eef",
1367
+ "frame_start": 512,
1368
+ "frame_end": 535,
1369
+ "command": "move_eef x=0.567 y=-0.078 z=0.18 speed=0.12",
1370
+ "args": {
1371
+ "x": 0.567,
1372
+ "y": -0.078,
1373
+ "z": 0.18,
1374
+ "speed": 0.12
1375
+ },
1376
+ "ok": true,
1377
+ "error": null,
1378
+ "stopped_from_target": {
1379
+ "cm": 0.2,
1380
+ "deg": 0.1
1381
+ },
1382
+ "eef_pos_after": [
1383
+ 0.5664,
1384
+ -0.0763,
1385
+ 0.18
1386
+ ],
1387
+ "gripper_width_after": 0.0342,
1388
+ "holding_after": true,
1389
+ "touched_during": true,
1390
+ "think_s": 4.528217315673828,
1391
+ "agent_obs_images": [
1392
+ "obs/s030_agentview.jpg",
1393
+ "obs/s030_wrist.jpg"
1394
+ ],
1395
+ "agent_note": {}
1396
+ },
1397
+ {
1398
+ "attempt": 1,
1399
+ "step": 31,
1400
+ "kind": "move_eef",
1401
+ "frame_start": 535,
1402
+ "frame_end": 562,
1403
+ "command": "move_eef z=0.115 speed=0.05",
1404
+ "args": {
1405
+ "z": 0.115,
1406
+ "speed": 0.05
1407
+ },
1408
+ "ok": true,
1409
+ "error": null,
1410
+ "stopped_from_target": {
1411
+ "cm": 0.1,
1412
+ "deg": 0.0
1413
+ },
1414
+ "eef_pos_after": [
1415
+ 0.5663,
1416
+ -0.0762,
1417
+ 0.116
1418
+ ],
1419
+ "gripper_width_after": 0.0342,
1420
+ "holding_after": true,
1421
+ "touched_during": true,
1422
+ "think_s": 16.66123056411743,
1423
+ "agent_obs_images": [
1424
+ "obs/s031_agentview.jpg",
1425
+ "obs/s031_wrist.jpg"
1426
+ ],
1427
+ "agent_note": {
1428
+ "reasoning": [
1429
+ "[\"**Comparing green and blue**\"]"
1430
+ ],
1431
+ "viewed": [
1432
+ "obs/s030_agentview.jpg",
1433
+ "obs/s030_wrist.jpg"
1434
+ ]
1435
+ }
1436
+ },
1437
+ {
1438
+ "attempt": 1,
1439
+ "step": 32,
1440
+ "kind": "move_eef",
1441
+ "frame_start": 562,
1442
+ "frame_end": 577,
1443
+ "command": "move_eef gripper=open",
1444
+ "args": {
1445
+ "gripper": "open"
1446
+ },
1447
+ "ok": true,
1448
+ "error": null,
1449
+ "stopped_from_target": null,
1450
+ "eef_pos_after": [
1451
+ 0.5663,
1452
+ -0.0763,
1453
+ 0.116
1454
+ ],
1455
+ "gripper_width_after": 0.0777,
1456
+ "holding_after": false,
1457
+ "touched_during": true,
1458
+ "think_s": 20.824064016342163,
1459
+ "agent_obs_images": [
1460
+ "obs/s032_agentview.jpg",
1461
+ "obs/s032_wrist.jpg"
1462
+ ],
1463
+ "agent_note": {
1464
+ "reasoning": [
1465
+ "[\"**Lowering green piece**\"]"
1466
+ ],
1467
+ "viewed": [
1468
+ "obs/s031_agentview.jpg",
1469
+ "obs/s031_wrist.jpg"
1470
+ ]
1471
+ }
1472
+ },
1473
+ {
1474
+ "attempt": 1,
1475
+ "step": 33,
1476
+ "kind": "move_eef",
1477
+ "frame_start": 577,
1478
+ "frame_end": 586,
1479
+ "command": "move_eef z=0.3",
1480
+ "args": {
1481
+ "z": 0.3
1482
+ },
1483
+ "ok": true,
1484
+ "error": null,
1485
+ "stopped_from_target": {
1486
+ "cm": 0.3,
1487
+ "deg": 0.0
1488
+ },
1489
+ "eef_pos_after": [
1490
+ 0.5676,
1491
+ -0.0763,
1492
+ 0.2975
1493
+ ],
1494
+ "gripper_width_after": 0.0785,
1495
+ "holding_after": false,
1496
+ "touched_during": false,
1497
+ "think_s": 4.303393840789795,
1498
+ "agent_obs_images": [
1499
+ "obs/s033_agentview.jpg",
1500
+ "obs/s033_wrist.jpg"
1501
+ ],
1502
+ "agent_note": {}
1503
+ }
1504
+ ],
1505
+ "task_events": [],
1506
+ "frames": {
1507
+ "n": 626,
1508
+ "fps": 20,
1509
+ "image_res": 256,
1510
+ "phase_codes": {
1511
+ "move": 0,
1512
+ "gripper": 1,
1513
+ "judge": 2
1514
+ },
1515
+ "initial_state": {
1516
+ "eef_pos": [
1517
+ -0.20846466056582413,
1518
+ -3.076533890594677e-14,
1519
+ 1.1732794757296403
1520
+ ],
1521
+ "joint_pos": [
1522
+ 4.179624399754216e-14,
1523
+ -0.16103738899999992,
1524
+ -3.5608721806463543e-14,
1525
+ -2.44459747,
1526
+ -3.1697568195276996e-13,
1527
+ 2.2267522,
1528
+ 0.785398163397356
1529
+ ],
1530
+ "gripper_qpos": [
1531
+ 0.02054186775581595,
1532
+ -0.02054184665779575
1533
+ ]
1534
+ }
1535
+ },
1536
+ "episode_index": 2822,
1537
+ "dataset_index_range": [
1538
+ 5463308,
1539
+ 5463934
1540
+ ],
1541
+ "label_provenance": {
1542
+ "task_cause_source": "leaf/release/evidence/causes.json",
1543
+ "recovery_review_source": "leaf/release/label_audit.jsonl",
1544
+ "recovery_review_applied": false
1545
+ }
1546
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/anthropic_messages.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Anthropic Messages API backend (Claude Opus 5.5 / Sonnet 5.5 / Fable 5.1 ...), official SDK `anthropic`.
2
+
3
+ Same conversation as the OpenAI backends, converted to Messages API blocks:
4
+ - system prompt = conv.system; tools = the harness tool specs (strict, one call per turn like the GPT player);
5
+ - every assistant turn is stored with its full `content` (thinking blocks with signatures, text, tool_use) and replayed
6
+ unchanged, so the model keeps its reasoning across tool calls. Assistant turns are never edited; old images in user
7
+ turns may be replaced by a text note (checked 2026-10-15 on Sonnet 5.5 / Opus 5.5 with thinking blocks in the
8
+ history: accepted), which the player does only when the context or the per-request image limit is reached;
9
+ - tool outputs of one turn become `tool_result` blocks at the start of the next user message; images the harness
10
+ attaches after them (observations, view_images) follow in the same user message;
11
+ - adaptive thinking with an explicit effort (the per-model default differs: Opus 5.5 medium, Sonnet 5.5 high);
12
+ - automatic prompt caching (top-level cache_control): every request caches its whole prefix for the next call;
13
+ - streaming, so long thinking turns do not hit the HTTP timeout.
14
+ No refusal fallback on purpose: a fallback would silently swap the model under test. A refusal is reported as
15
+ status "refusal" and the player ends the run.
16
+
17
+ Key from ANTHROPIC_API_KEY (or any credential the SDK resolves). The client is created lazily on the first real
18
+ call; tests inject a mock client.
19
+ """
20
+ import time
21
+
22
+ from ..context import ToolCall, prune_live_images
23
+ from .base import Backend, BackendResponse, import_sdk
24
+
25
+ EFFORTS = ("low", "medium", "high", "xhigh", "max")
26
+
27
+
28
+ def _get(obj, key, default=None):
29
+ if isinstance(obj, dict):
30
+ return obj.get(key, default)
31
+ return getattr(obj, key, default)
32
+
33
+
34
+ def _to_dict(block):
35
+ if isinstance(block, dict):
36
+ return dict(block)
37
+ if hasattr(block, "to_dict"):
38
+ return block.to_dict()
39
+ return block.model_dump(mode="json", exclude_none=True)
40
+
41
+
42
+ def anthropic_tools(specs, strict=True):
43
+ out = []
44
+ for s in specs:
45
+ t = dict(name=s["name"], description=s["description"], input_schema=s["parameters"])
46
+ if strict:
47
+ t["strict"] = True
48
+ out.append(t)
49
+ return out
50
+
51
+
52
+ def image_block(image, quality=None):
53
+ url = image.data_url(quality)
54
+ head, data = url.split(",", 1) # data:<mime>;base64,<data>
55
+ mime = head[len("data:"):].split(";", 1)[0]
56
+ return dict(type="image", source=dict(type="base64", media_type=mime, data=data))
57
+
58
+
59
+ class AnthropicMessagesBackend(Backend):
60
+ name = "anthropic"
61
+
62
+ def __init__(self, model="claude-opus-5-5", effort="high", thinking_display="summarized", max_tokens=64000,
63
+ max_live_images=None, jpeg_quality=90, timeout=900.0, max_retries=2, strict_tools=True,
64
+ parallel_tool_calls=False, cache=True, client=None):
65
+ if effort not in EFFORTS:
66
+ raise ValueError(f"effort must be one of {EFFORTS}, got {effort!r}")
67
+ self.model = model
68
+ self.effort = effort
69
+ self.thinking_display = thinking_display # "summarized" (logged as the reasoning summary) | "omitted"
70
+ self.max_tokens = max_tokens
71
+ self.max_live_images = max_live_images
72
+ self.jpeg_quality = jpeg_quality
73
+ self.timeout = timeout
74
+ self.max_retries = max_retries
75
+ self.strict_tools = strict_tools
76
+ self.parallel_tool_calls = parallel_tool_calls
77
+ self.cache = cache
78
+ self._client = client
79
+
80
+ def config(self):
81
+ return dict(name=self.name, model=self.model, effort=self.effort, thinking_display=self.thinking_display,
82
+ max_tokens=self.max_tokens, max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality,
83
+ timeout=self.timeout, max_retries=self.max_retries, strict_tools=self.strict_tools,
84
+ parallel_tool_calls=self.parallel_tool_calls, cache=self.cache)
85
+
86
+ def client(self):
87
+ if self._client is None:
88
+ anthropic = import_sdk("anthropic")
89
+ self._client = anthropic.Anthropic(timeout=self.timeout, max_retries=self.max_retries)
90
+ return self._client
91
+
92
+ # ------------------------------------------------------------------ request
93
+ def convert_items(self, items):
94
+ msgs = []
95
+
96
+ def push(role, blocks):
97
+ if msgs and msgs[-1]["role"] == role:
98
+ msgs[-1]["content"].extend(blocks)
99
+ else:
100
+ msgs.append(dict(role=role, content=list(blocks)))
101
+
102
+ for it in items:
103
+ kind = it["kind"]
104
+ if kind == "user":
105
+ blocks = []
106
+ for p in it["parts"]:
107
+ if p["type"] == "text":
108
+ blocks.append(dict(type="text", text=p["text"]))
109
+ else:
110
+ blocks.append(image_block(p["image"], self.jpeg_quality))
111
+ push("user", blocks)
112
+ elif kind == "assistant":
113
+ if it.get("raw") is not None and it.get("backend") == self.name:
114
+ blocks = [dict(b) for b in it["raw"]]
115
+ else: # a turn produced by another backend: plain text + tool calls, no thinking
116
+ blocks = ([dict(type="text", text=it["text"])] if it.get("text") else [])
117
+ blocks += [dict(type="tool_use", id=tc.id, name=tc.name, input=tc.arguments)
118
+ for tc in it["tool_calls"]]
119
+ if not blocks:
120
+ blocks = [dict(type="text", text="(no output)")]
121
+ push("assistant", blocks)
122
+ elif kind == "tool_output":
123
+ push("user", [dict(type="tool_result", tool_use_id=it["call_id"], content=it["text"])])
124
+ else:
125
+ raise ValueError(kind)
126
+ return msgs
127
+
128
+ def build_request(self, conv, tools):
129
+ items = prune_live_images(conv.items, self.max_live_images)
130
+ req = dict(model=self.model, max_tokens=int(self.max_tokens), system=conv.system,
131
+ messages=self.convert_items(items), tools=anthropic_tools(tools, self.strict_tools),
132
+ tool_choice=dict(type="auto", disable_parallel_tool_use=not self.parallel_tool_calls),
133
+ thinking=dict(type="adaptive", display=self.thinking_display),
134
+ output_config=dict(effort=self.effort))
135
+ if self.cache:
136
+ req["cache_control"] = dict(type="ephemeral")
137
+ return req
138
+
139
+ @staticmethod
140
+ def request_stats(req):
141
+ n_img, img_bytes, txt = 0, 0, len(req.get("system") or "")
142
+ for m in req["messages"]:
143
+ for b in m["content"]:
144
+ t = b.get("type")
145
+ if t == "image":
146
+ n_img += 1
147
+ img_bytes += len(b["source"]["data"])
148
+ elif t == "text":
149
+ txt += len(b["text"])
150
+ elif t == "tool_result":
151
+ txt += len(b["content"]) if isinstance(b["content"], str) else 0
152
+ return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_messages=len(req["messages"]))
153
+
154
+ # ------------------------------------------------------------------ call
155
+ def act(self, conv, tools):
156
+ req = self.build_request(conv, tools)
157
+ stats = self.request_stats(req)
158
+ t0 = time.time()
159
+ try:
160
+ with self.client().messages.stream(**req) as stream:
161
+ msg = stream.get_final_message()
162
+ except AssertionError: # the SDK asserts on a stream without message_start (seen through a gateway)
163
+ raise RuntimeError("empty response stream (no message_start event)") from None
164
+ out = self.parse_response(msg)
165
+ out.latency_s = time.time() - t0
166
+ out.request_stats = stats
167
+ return out
168
+
169
+ def parse_response(self, msg):
170
+ calls, texts, summ = [], [], []
171
+ content = _get(msg, "content") or []
172
+ for b in content:
173
+ t = _get(b, "type")
174
+ if t == "tool_use":
175
+ args = _get(b, "input") or {}
176
+ calls.append(ToolCall(id=_get(b, "id"), name=_get(b, "name"), arguments=dict(args)))
177
+ elif t == "text":
178
+ texts.append(_get(b, "text") or "")
179
+ elif t == "thinking":
180
+ if _get(b, "thinking"):
181
+ summ.append(_get(b, "thinking"))
182
+ u = _get(msg, "usage")
183
+ usage = {}
184
+ if u is not None:
185
+ fresh = _get(u, "input_tokens", 0) or 0
186
+ read = _get(u, "cache_read_input_tokens", 0) or 0
187
+ write = _get(u, "cache_creation_input_tokens", 0) or 0
188
+ # same meaning as the OpenAI backend: input_tokens = whole prompt, cached_tokens = the part read from cache
189
+ usage = dict(input_tokens=fresh + read + write, cached_tokens=read, cache_write_tokens=write,
190
+ output_tokens=_get(u, "output_tokens", 0) or 0, reasoning_tokens=0)
191
+ stop = _get(msg, "stop_reason")
192
+ status, err = "completed", None
193
+ if stop == "refusal":
194
+ d = _get(msg, "stop_details")
195
+ status, err = "refusal", f"refusal: category={_get(d, 'category')} {_get(d, 'explanation') or ''}".strip()
196
+ elif stop == "max_tokens":
197
+ status, err = "incomplete", "incomplete: max_tokens"
198
+ elif not content and u is None:
199
+ status, err = "incomplete", "empty response (no content, no usage)"
200
+ return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
201
+ reasoning_summary="\n".join(summ) or None, usage=usage,
202
+ raw=[_to_dict(b) for b in content], status=status, error=err)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/base.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s)."""
2
+ import os
3
+ import sys
4
+ from dataclasses import dataclass, field
5
+ from typing import Optional
6
+
7
+ # Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh).
8
+ # Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name:
9
+ # LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence.
10
+ API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "")
11
+ OPENAI_SDK_DIR = API_SDK_DIR # old name
12
+
13
+
14
+ def import_sdk(module):
15
+ """Import an API SDK module ("openai", "anthropic", "google.genai")."""
16
+ import importlib
17
+ try:
18
+ return importlib.import_module(module)
19
+ except ImportError:
20
+ if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path:
21
+ sys.path.append(API_SDK_DIR)
22
+ return importlib.import_module(module)
23
+
24
+
25
+ def import_openai():
26
+ return import_sdk("openai")
27
+
28
+
29
+ @dataclass
30
+ class BackendResponse:
31
+ tool_calls: list = field(default_factory=list) # [ToolCall]
32
+ text: Optional[str] = None # visible assistant text (e.g. the diagnosis)
33
+ reasoning_summary: Optional[str] = None
34
+ usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens
35
+ latency_s: float = 0.0
36
+ raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items)
37
+ request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ...
38
+ status: str = "ok"
39
+ error: Optional[str] = None
40
+
41
+
42
+ @dataclass
43
+ class RunInfo:
44
+ task: object # privileged: only the scripted backend may look at task / inst
45
+ inst: dict
46
+ seed: int
47
+ k: int
48
+ protocol: str
49
+ feedback: str
50
+ memory: str
51
+
52
+
53
+ @dataclass
54
+ class AttemptInfo:
55
+ attempt: int
56
+ history: list # AttemptRecords visible to the agent under the memory mode (already selected)
57
+ continuing: bool = False # within protocol: continuing after a failed done
58
+
59
+
60
+ class Backend:
61
+ name = "base"
62
+
63
+ def begin_run(self, info: RunInfo):
64
+ pass
65
+
66
+ def begin_attempt(self, info: AttemptInfo):
67
+ pass
68
+
69
+ def act(self, conv, tools) -> BackendResponse:
70
+ raise NotImplementedError
71
+
72
+ def on_tool_result(self, call, result):
73
+ pass
74
+
75
+ def end_attempt(self) -> dict:
76
+ return {}
77
+
78
+ def end_run(self):
79
+ pass
80
+
81
+ def config(self) -> dict:
82
+ return dict(name=self.name)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/openai_responses.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI Responses API backend (default model gpt-6-astra).
2
+
3
+ Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with
4
+ store=False; reasoning items are replayed with their encrypted content so the model keeps its chain
5
+ of thought across tool calls within an attempt. The request prefix (instructions, tools, task text,
6
+ packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what
7
+ OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs.
8
+
9
+ Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time;
10
+ the client is created lazily on the first real call (tests inject a mock client).
11
+ """
12
+ import json
13
+ import os
14
+ import time
15
+
16
+ from ..context import ToolCall, prune_live_images
17
+ from .base import Backend, BackendResponse, import_openai
18
+
19
+ # GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported.
20
+ GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max")
21
+
22
+
23
+ def _get(obj, key, default=None):
24
+ if isinstance(obj, dict):
25
+ return obj.get(key, default)
26
+ return getattr(obj, key, default)
27
+
28
+
29
+ def _to_dict(item):
30
+ if isinstance(item, dict):
31
+ return dict(item)
32
+ if hasattr(item, "to_dict"):
33
+ return item.to_dict(mode="json")
34
+ if hasattr(item, "model_dump"):
35
+ return item.model_dump(mode="json", exclude_none=True)
36
+ return dict(vars(item))
37
+
38
+
39
+ def responses_tools(specs, strict=True):
40
+ return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"],
41
+ strict=strict) for s in specs]
42
+
43
+
44
+ class OpenAIResponsesBackend(Backend):
45
+ name = "openai"
46
+
47
+ def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto",
48
+ max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None,
49
+ store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0,
50
+ max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last",
51
+ prompt_cache_options=None, client=None, http_client=None):
52
+ if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS:
53
+ raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), "
54
+ f"got {reasoning_effort!r}")
55
+ self.model = model
56
+ self.reasoning_effort = reasoning_effort
57
+ self.reasoning_summary = reasoning_summary
58
+ self.image_detail = image_detail
59
+ self.max_output_tokens = max_output_tokens
60
+ self.service_tier = service_tier
61
+ self.prompt_cache_key = prompt_cache_key
62
+ self.prompt_cache_retention = prompt_cache_retention
63
+ self.store = store
64
+ self.replay_reasoning = replay_reasoning
65
+ self.max_live_images = max_live_images
66
+ self.jpeg_quality = jpeg_quality
67
+ self.timeout = timeout
68
+ self.max_retries = max_retries
69
+ self.extra_body = extra_body
70
+ self.strict_tools = strict_tools
71
+ # explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last"
72
+ assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints
73
+ self.cache_breakpoints = cache_breakpoints
74
+ self.prompt_cache_options = prompt_cache_options
75
+ self._client = client
76
+ self._http_client = http_client # optional custom transport (tests, proxies)
77
+ self._cache_key = prompt_cache_key
78
+
79
+ def config(self):
80
+ return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort,
81
+ reasoning_summary=self.reasoning_summary, image_detail=self.image_detail,
82
+ max_output_tokens=self.max_output_tokens, service_tier=self.service_tier,
83
+ prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention,
84
+ store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images,
85
+ jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries,
86
+ extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints,
87
+ prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL"))
88
+
89
+ # ------------------------------------------------------------------ client
90
+ def client(self):
91
+ if self._client is None:
92
+ key = os.environ.get("OPENAI_API_KEY")
93
+ if not key:
94
+ raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it")
95
+ openai = import_openai()
96
+ kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout,
97
+ max_retries=self.max_retries)
98
+ if self._http_client is not None:
99
+ kw["http_client"] = self._http_client
100
+ self._client = openai.OpenAI(**kw)
101
+ return self._client
102
+
103
+ def begin_run(self, info):
104
+ if self.prompt_cache_key is None:
105
+ # route all calls of one run to the same cache shard
106
+ self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}"
107
+
108
+ # ------------------------------------------------------------------ request
109
+ def convert_items(self, items):
110
+ out = []
111
+ last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1)
112
+ for i, it in enumerate(items):
113
+ kind = it["kind"]
114
+ if kind == "user":
115
+ content = []
116
+ for p in it["parts"]:
117
+ if p["type"] == "text":
118
+ content.append(dict(type="input_text", text=p["text"]))
119
+ else:
120
+ content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality),
121
+ detail=self.image_detail))
122
+ # explicit cache breakpoints: end of the stable history item (byte-identical for the whole
123
+ # attempt) and end of the newest input (reused by the next call of the attempt)
124
+ if content and ((self.cache_breakpoints != "none" and not it.get("live"))
125
+ or (self.cache_breakpoints == "history+last" and i == last_user)):
126
+ content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit")
127
+ out.append(dict(role="user", content=content))
128
+ elif kind == "assistant":
129
+ if it.get("raw") and it.get("backend") == self.name:
130
+ for r in it["raw"]:
131
+ if r.get("type") == "reasoning" and not self.replay_reasoning:
132
+ continue
133
+ out.append(r)
134
+ else:
135
+ if it.get("text"):
136
+ out.append(dict(role="assistant", content=it["text"]))
137
+ for tc in it["tool_calls"]:
138
+ out.append(dict(type="function_call", call_id=tc.id, name=tc.name,
139
+ arguments=tc.raw_arguments or json.dumps(tc.arguments)))
140
+ elif kind == "tool_output":
141
+ out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"]))
142
+ else:
143
+ raise ValueError(kind)
144
+ return out
145
+
146
+ def build_request(self, conv, tools):
147
+ items = prune_live_images(conv.items, self.max_live_images)
148
+ req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items),
149
+ tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False,
150
+ store=self.store)
151
+ reasoning = dict(effort=self.reasoning_effort)
152
+ if self.reasoning_summary:
153
+ reasoning["summary"] = self.reasoning_summary
154
+ req["reasoning"] = reasoning
155
+ if not self.store and self.replay_reasoning:
156
+ req["include"] = ["reasoning.encrypted_content"]
157
+ if self.max_output_tokens:
158
+ req["max_output_tokens"] = int(self.max_output_tokens)
159
+ if self.service_tier:
160
+ req["service_tier"] = self.service_tier
161
+ if self._cache_key:
162
+ req["prompt_cache_key"] = self._cache_key
163
+ if self.prompt_cache_retention:
164
+ req["prompt_cache_retention"] = self.prompt_cache_retention
165
+ if self.prompt_cache_options:
166
+ req["prompt_cache_options"] = dict(self.prompt_cache_options)
167
+ if self.extra_body:
168
+ req["extra_body"] = dict(self.extra_body)
169
+ return req
170
+
171
+ @staticmethod
172
+ def request_stats(req):
173
+ n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "")
174
+ for it in req["input"]:
175
+ for c in (it.get("content") if isinstance(it.get("content"), list) else []):
176
+ if c.get("type") == "input_image":
177
+ n_img += 1
178
+ img_bytes += len(c["image_url"])
179
+ elif "text" in c:
180
+ txt += len(c["text"])
181
+ if isinstance(it.get("content"), str):
182
+ txt += len(it["content"])
183
+ if it.get("type") == "function_call_output":
184
+ txt += len(it["output"]) if isinstance(it["output"], str) else 0
185
+ if it.get("type") == "function_call":
186
+ txt += len(it.get("arguments", ""))
187
+ tools_chars = len(json.dumps(req.get("tools", [])))
188
+ return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars,
189
+ n_input_items=len(req["input"]))
190
+
191
+ # ------------------------------------------------------------------ call
192
+ def act(self, conv, tools):
193
+ req = self.build_request(conv, tools)
194
+ stats = self.request_stats(req)
195
+ t0 = time.time()
196
+ resp = self.client().responses.create(**req)
197
+ out = self.parse_response(resp)
198
+ out.latency_s = time.time() - t0
199
+ out.request_stats = stats
200
+ return out
201
+
202
+ def parse_response(self, resp):
203
+ calls, texts, summ = [], [], []
204
+ output = _get(resp, "output") or []
205
+ for item in output:
206
+ t = _get(item, "type")
207
+ if t == "function_call":
208
+ raw = _get(item, "arguments") or ""
209
+ try:
210
+ args = json.loads(raw) if raw else {}
211
+ except json.JSONDecodeError:
212
+ args = {}
213
+ calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args,
214
+ raw_arguments=raw))
215
+ elif t == "message":
216
+ for c in _get(item, "content") or []:
217
+ if _get(c, "type") == "output_text":
218
+ texts.append(_get(c, "text") or "")
219
+ elif t == "reasoning":
220
+ for s in _get(item, "summary") or []:
221
+ summ.append(_get(s, "text") or "")
222
+ u = _get(resp, "usage")
223
+ usage = {}
224
+ if u is not None:
225
+ itd = _get(u, "input_tokens_details")
226
+ otd = _get(u, "output_tokens_details")
227
+ usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0,
228
+ cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0,
229
+ cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0,
230
+ output_tokens=_get(u, "output_tokens", 0) or 0,
231
+ reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0)
232
+ status = _get(resp, "status") or "completed"
233
+ err = None
234
+ if status == "incomplete":
235
+ err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason"))
236
+ elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again
237
+ status, err = "incomplete", "empty response (no output, no usage)"
238
+ return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
239
+ reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage,
240
+ raw=[_to_dict(i) for i in output], status=status, error=err)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/__init__.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness adapters (docs/15): one way to plug any agent harness into a robot_server session.
2
+
3
+ ours reference driver scripts/api_player.py (main table)
4
+ claude_code Claude Code CLI, --bare, only our MCP tools (arm B)
5
+ claude_code_full Claude Code CLI without --bare: full system prompt, still one-time dirs and only MCP (arm B')
6
+ codex Codex CLI exec (+ exec resume on early exit), one-time CODEX_HOME, only our MCP tools (arm F)
7
+ rpent_codex RPent (robot harness framework) on Codex: RPent's loop and prompt, the main table's Codex config,
8
+ tools through the episode's tool gateway (docs/18, lffbench/harnesses/rpent.py)
9
+ dsh DeepSeek Harness (`dsh --profile headless`), only our MCP tools, one-time dirs
10
+
11
+ Use scripts/harness_run.py (one session) or scripts/api_batch.py start --harness ... (batches).
12
+ """
13
+ import json
14
+ import importlib
15
+ import os
16
+ import sys
17
+
18
+ from .base import EpisodeSpec, HarnessAdapter, HarnessRefused, first_message_text # noqa: F401
19
+
20
+ # A new Codex-based Robot Harness registers here; both single-run and batch CLIs
21
+ # derive their choices, provider and common options from this registry.
22
+ ROBOT_HARNESSES = {
23
+ "rpent_codex": ("rpent", "RPentCodex"),
24
+ "sensenova_codex": ("sensenova", "SenseNovaCodex"),
25
+ "embodied_evo_codex": ("embodied_evo", "EmbodiedEvoCodex"),
26
+ }
27
+ NAMES = ("ours", "claude_code", "claude_code_full", "codex", "dsh", *ROBOT_HARNESSES)
28
+ PROVIDER = dict(claude_code="anthropic", claude_code_full="anthropic", codex="openai", dsh="deepseek",
29
+ **{name: "openai" for name in ROBOT_HARNESSES})
30
+
31
+
32
+ def get_adapter(name, **kw):
33
+ if name == "ours":
34
+ from .reference import Reference
35
+ return Reference(**kw)
36
+ if name == "claude_code":
37
+ from .claude_code import ClaudeCode
38
+ return ClaudeCode(**kw)
39
+ if name == "claude_code_full":
40
+ from .claude_code import ClaudeCodeFull
41
+ return ClaudeCodeFull(**kw)
42
+ if name == "codex":
43
+ from .codex import Codex
44
+ return Codex(**kw)
45
+ if name == "dsh":
46
+ from .dsh import DeepSeekHarness
47
+ return DeepSeekHarness(**kw)
48
+ if name in ROBOT_HARNESSES:
49
+ module, cls = ROBOT_HARNESSES[name]
50
+ return getattr(importlib.import_module("." + module, __name__), cls)(**kw)
51
+ raise ValueError(f"unknown harness {name!r}; one of {NAMES}")
52
+
53
+
54
+ def render_first_message(ep):
55
+ """Call `status` once over HTTP (exactly as the reference driver does before its first turn) and build the first
56
+ user message for a native harness. Returns (text, status_json)."""
57
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
58
+ "scripts"))
59
+ from api_player import call_server # noqa: E402
60
+ st = json.loads(call_server(ep.port, ep.token, "status", {}))
61
+ readme = open(os.path.join(ep.sandbox, "README.md")).read()
62
+ status_json = json.dumps(st)
63
+ return first_message_text(readme, status_json), status_json
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-flash|high",
3
+ "fingerprint_sha256": "189cde183af8b300854d48b4f8952a6ebdf53462343e87c0062ad4c761943d9c",
4
+ "written": "2026-10-30 15:54:07",
5
+ "summary": {
6
+ "system_chars": 6047,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "deepseek-flash"
14
+ }
15
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/real/driver_template.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Skeleton of a hardware driver for LFF-Bench (spec: DRIVER.md). Copy this file and protocol.py to the robot PC,
2
+ fill in the five methods marked TODO, run scripts/real_check_driver.py until every check passes.
3
+
4
+ python driver_template.py --port 9900 [--token <t>] [--log <dir>]
5
+
6
+ Only Python 3 + numpy + Pillow are needed here (plus your robot / camera SDKs). Keep the server on 127.0.0.1; the
7
+ benchmark machine reaches it through an SSH tunnel (DRIVER.md §7).
8
+
9
+ What is already done for you: the HTTP protocol, the token, the operator's terminal prompts, the safety checks that
10
+ must run before every motion (hard workspace box, speed limit), the motion timing, and an optional recorder that saves
11
+ both cameras to an mp4 per attempt. Everything robot-specific is in the TODO methods.
12
+ """
13
+ import argparse
14
+ import os
15
+ import threading
16
+ import time
17
+
18
+ import numpy as np
19
+
20
+ try: # copied next to protocol.py on the robot PC
21
+ from protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
22
+ except ImportError: # inside the repo (python -m lffbench.real.driver_template)
23
+ from .protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
24
+
25
+ # ---------------------------------------------------------------------------------------------- your setup (edit)
26
+ ROBOT = "AgileX PiPER" # TODO: the arm's name as the agent will read it ("You control a real <ROBOT> robot arm")
27
+ N_JOINTS = 6 # TODO
28
+ # Hard workspace of the GRASP POINT in the robot-base frame (metres). Rejected targets never move the arm. Choose it so
29
+ # that every point inside is reachable with the gripper pointing straight down at any yaw in YAW_RANGE_DEG, and the
30
+ # lower z bound keeps the fingertips >= 5 mm above the table (the boxes are pushed with the fingertips ~1 cm up).
31
+ WORKSPACE_LO = [0.15, -0.25, 0.00] # TODO: measure on your table
32
+ WORKSPACE_HI = [0.45, 0.25, 0.30] # TODO
33
+ YAW_RANGE_DEG = [-120.0, 120.0] # TODO: gripper yaw your wrist reaches (span >= 180)
34
+ MAX_SPEED = 0.25 # m/s, the fastest straight-line speed you allow (the agent may ask for less)
35
+ 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
36
+ REACH_TOL = 0.004 # m: a move counts as finished when within this of the target and stopped
37
+ MOVE_TIMEOUT = 30.0 # s
38
+ DRIVER_VERSION = "template-0" # TODO: your git commit / date
39
+
40
+
41
+ class MyDriver(DriverServer):
42
+ image_format = "jpeg" # "png" is lossless but ~5x larger; jpeg q95 is fine over a LAN / SSH tunnel
43
+
44
+ def __init__(self, record_dir=""):
45
+ self.lock = threading.RLock() # hardware access from the recorder thread and from requests
46
+ self.record_dir = record_dir
47
+ self.recorder = None
48
+ # TODO: connect to the arm, enable it, set the TCP (grasp point = midway between the fingertips, about 1 cm
49
+ # above their tips), open the cameras. Example for PiPER (piper_sdk; check the SDK docs, not verified here):
50
+ # from piper_sdk import C_PiperInterface_V2
51
+ # self.arm = C_PiperInterface_V2("can0"); self.arm.ConnectPort(); ... enable ...
52
+ # Cameras: "agentview" = fixed camera looking at the table from the front/side (sees the whole work area);
53
+ # "wrist" = camera on the gripper. E.g. cv2.VideoCapture / pyrealsense2 colour stream.
54
+ raise NotImplementedError("connect the arm and the cameras")
55
+
56
+ # ------------------------------------------------------------------ TODO 1: low-level hardware
57
+ def _send_cartesian(self, x, y, z, yaw_deg, speed):
58
+ """Start a straight-line (MoveL) motion of the grasp point to (x, y, z) with the gripper pointing straight down
59
+ and rotated by yaw_deg about the base z axis (0 = fingers close along the base y axis, +90 = along the base x
60
+ axis, counter-clockwise seen from above). Return False if the controller refuses (no IK)."""
61
+ raise NotImplementedError
62
+
63
+ def _read_pose(self):
64
+ """-> (xyz of the grasp point in the base frame [m], yaw_deg, joint angles [rad], is_moving: bool)."""
65
+ raise NotImplementedError
66
+
67
+ def _set_gripper(self, close):
68
+ """Close (force-limited, stop when blocked) or open fully; return when the fingers have stopped."""
69
+ raise NotImplementedError
70
+
71
+ def _gripper_width(self):
72
+ """Opening between the fingertips, metres."""
73
+ raise NotImplementedError
74
+
75
+ def _grab(self):
76
+ """-> {"agentview": HxWx3 uint8 RGB, "wrist": ...}: the newest frames (flush camera buffers first)."""
77
+ raise NotImplementedError
78
+
79
+ def ik(self, eef_pos, yaw_deg):
80
+ """Optional (set info()["ik"] = True), needed only for real_bias_place: joint angles that put the grasp point
81
+ at eef_pos / yaw_deg (pointing down), the solution closest to the current joints. Do NOT move the arm."""
82
+ raise NotImplementedError
83
+
84
+ # ------------------------------------------------------------------ protocol (normally no need to edit)
85
+ def info(self):
86
+ return dict(protocol=PROTOCOL_VERSION, robot=ROBOT, n_joints=N_JOINTS, cameras=list(CAMERAS),
87
+ workspace=dict(lo=WORKSPACE_LO, hi=WORKSPACE_HI), yaw_range_deg=YAW_RANGE_DEG, max_speed=MAX_SPEED,
88
+ ik=False, driver_version=DRIVER_VERSION)
89
+
90
+ def state(self):
91
+ with self.lock:
92
+ xyz, yaw, q, _ = self._read_pose()
93
+ return dict(eef_pos=[float(v) for v in xyz], eef_yaw_deg=float(yaw), gripper_width_m=float(self._gripper_width()),
94
+ joint_pos_rad=[float(v) for v in q])
95
+
96
+ def _inside(self, x, y, z, yaw_deg):
97
+ p = np.array([x, y, z])
98
+ return (bool(np.all(p >= WORKSPACE_LO) and np.all(p <= WORKSPACE_HI))
99
+ and YAW_RANGE_DEG[0] <= yaw_deg <= YAW_RANGE_DEG[1])
100
+
101
+ def move(self, x, y, z, yaw_deg, speed):
102
+ if not self._inside(x, y, z, yaw_deg):
103
+ return False, "outside the hard workspace", 0.0
104
+ speed = MAX_SPEED if speed is None else float(np.clip(speed, 0.005, MAX_SPEED))
105
+ with self.lock:
106
+ t0 = time.time()
107
+ if not self._send_cartesian(x, y, z, yaw_deg, speed):
108
+ return False, "no IK solution", 0.0
109
+ tgt = np.array([x, y, z])
110
+ while True: # blocking: return only once the arm has stopped
111
+ xyz, _, _, moving = self._read_pose()
112
+ if not moving and np.linalg.norm(np.asarray(xyz) - tgt) < REACH_TOL:
113
+ break
114
+ if time.time() - t0 > MOVE_TIMEOUT:
115
+ if not moving:
116
+ break # stopped short (blocked by an object): a normal outcome, the agent sees the pose
117
+ raise RuntimeError("move timed out while still moving") # -> fault: the run stops
118
+ time.sleep(0.02)
119
+ return True, None, time.time() - t0
120
+
121
+ def gripper(self, close):
122
+ with self.lock:
123
+ t0 = time.time()
124
+ self._set_gripper(close)
125
+ return time.time() - t0
126
+
127
+ def home(self):
128
+ ok, err, _ = self.move(HOME["x"], HOME["y"], HOME["z"], HOME["yaw_deg"], 0.15)
129
+ if not ok:
130
+ raise RuntimeError(f"cannot reach the home pose: {err}")
131
+ self.gripper(False)
132
+ return self.state()
133
+
134
+ def images(self):
135
+ with self.lock:
136
+ return self._grab()
137
+
138
+ def event(self, ev, run="", attempt=None, **kw):
139
+ if not self.record_dir:
140
+ return
141
+ if ev == "attempt_start":
142
+ self._stop_recording()
143
+ try:
144
+ self.recorder = Recorder(self, os.path.join(self.record_dir, f"{run}_a{attempt}.mp4"))
145
+ except Exception as e: # the video is only for the record: a missing imageio must not end a run as a fault
146
+ print(f"WARNING: recorder not started ({type(e).__name__}: {e}); "
147
+ "pip install imageio imageio-ffmpeg", flush=True)
148
+ elif ev in ("attempt_end", "episode_end", "session_end", "run_invalid"):
149
+ self._stop_recording()
150
+
151
+ def _stop_recording(self):
152
+ if self.recorder is not None:
153
+ self.recorder.stop()
154
+ self.recorder = None
155
+
156
+
157
+ class Recorder(threading.Thread):
158
+ """agentview | wrist side by side at ~5 fps while an attempt runs (needs imageio + imageio-ffmpeg)."""
159
+
160
+ def __init__(self, drv, path, fps=5, res=360):
161
+ super().__init__(daemon=True)
162
+ import imageio
163
+ self.drv, self.fps, self.res, self.halt = drv, fps, res, threading.Event()
164
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
165
+ self.w = imageio.get_writer(path, fps=fps, macro_block_size=8)
166
+ self.start()
167
+
168
+ def run(self):
169
+ while not self.halt.is_set():
170
+ t0 = time.time()
171
+ try:
172
+ with self.drv.lock:
173
+ f = self.drv._grab()
174
+ self.w.append_data(np.concatenate([square_resize(f[c], self.res) for c in CAMERAS], axis=1))
175
+ except Exception as e: # never let the recorder break a run
176
+ print("recorder:", e)
177
+ self.halt.wait(max(0.0, 1.0 / self.fps - (time.time() - t0)))
178
+
179
+ def stop(self):
180
+ self.halt.set()
181
+ self.join(timeout=5)
182
+ self.w.close()
183
+
184
+
185
+ def main():
186
+ ap = argparse.ArgumentParser()
187
+ ap.add_argument("--port", type=int, default=9900)
188
+ ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
189
+ ap.add_argument("--log", default="driver_logs", help="operator answers (operator.jsonl) and attempt videos")
190
+ a = ap.parse_args()
191
+ os.makedirs(a.log, exist_ok=True)
192
+ MyDriver(record_dir=a.log).serve(a.port, token=a.token or None, operator_log=os.path.join(a.log, "operator.jsonl"))
193
+
194
+
195
+ if __name__ == "__main__":
196
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/headroom_parts_cart.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Incremental physical headroom evaluation of the composite prototype."""
2
+ import argparse,hashlib,json,time
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from lffbench.tasks.lh_parts_cart import PartsCart
6
+
7
+ def clean(x):
8
+ if isinstance(x,np.ndarray):return x.tolist()
9
+ if isinstance(x,np.generic):return x.item()
10
+ raise TypeError(type(x).__name__)
11
+ p=argparse.ArgumentParser();p.add_argument('--kind',choices=['oracle','naive','adaptive','blind'],required=True);p.add_argument('--n',type=int,default=20);p.add_argument('--k',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args()
12
+ out=Path(a.out);out.parent.mkdir(parents=True,exist_ok=True);x=PartsCart();rows=[];start=time.time()
13
+ source=Path(__file__).parents[1]/'lffbench/tasks/lh_parts_cart.py';code_hash=hashlib.sha256(source.read_bytes()).hexdigest()
14
+ for seed in range(1000,1000+a.n):
15
+ i=x.sample_instance(seed);h=x.run_scripted(a.kind,i,k=a.k,seed=seed)
16
+ rows.append(dict(seed=seed,history=h));succ=sum(any(z['outcome']['success'] for z in row['history']) for row in rows)
17
+ out.write_text(json.dumps(dict(kind=a.kind,n_planned=a.n,n_complete=len(rows),k=a.k,successes=succ,rows=rows,seconds=time.time()-start,task_sha256=code_hash,status='complete' if len(rows)==a.n else 'running',note='scripted privileged-state headroom; fixed geometry, randomized inertia only'),indent=2,default=clean))
18
+ print(seed,a.kind,[z['outcome']['success'] for z in h], 'successes',succ,flush=True)
19
+ x.env.close()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/l6_controls.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """python scripts/l6_controls.py <l6_count_into_box|l6_sequence_resume> [n]
2
+
3
+ Extra controls for the two L6 tasks: thumbnails right after the interruption, extra scripted policies,
4
+ no-injection sanity check, analytic memoryless baselines. Writes results/<task>/controls.json."""
5
+ import sys, json, os, time
6
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7
+ sys.path.insert(0, ROOT)
8
+ import numpy as np, imageio
9
+ from lffbench import envs
10
+ import lffbench.tasks.l6_count, lffbench.tasks.l6_sequence # noqa
11
+ from lffbench.task_base import TASKS
12
+ name = sys.argv[1]
13
+ n = int(sys.argv[2]) if len(sys.argv) > 2 else 20
14
+ out_dir = os.path.join(ROOT, "results", name)
15
+ os.makedirs(out_dir, exist_ok=True)
16
+ task = TASKS[name](cam_res=384)
17
+ extra = ["skip", "inc1"] if name == "l6_count_into_box" else ["skip"]
18
+ res = dict(task=name, n=n, seeds=list(range(1000, 1000 + n)), extra={}, no_inject={}, analytic={})
19
+ t0 = time.time()
20
+
21
+ # 1) frames right after the interruption (what the agent sees next), seeds 1000-1002, adaptive policy
22
+ def interrupted():
23
+ return (task.slip if name == "l6_count_into_box" else task.stop) is not None
24
+
25
+
26
+ for seed in range(1000, 1003):
27
+ inst = task.sample_instance(seed)
28
+ shot = {}
29
+ orig_step = task.env.step
30
+
31
+ def step(a, _o=orig_step):
32
+ r = _o(a)
33
+ if "f" not in shot and interrupted():
34
+ shot["cnt"] = shot.get("cnt", 0) + 1
35
+ if shot["cnt"] >= (4 if name == "l6_count_into_box" else 60): # count: 0.2 s; sequence: arm back home
36
+ shot["f"] = np.concatenate([envs.render(task.env, "agentview", 384),
37
+ envs.render(task.env, "robot0_eye_in_hand", 384)], 1)
38
+ return r
39
+ task.env.step = step
40
+ task.run_scripted("adaptive", inst, k=5, seed=seed)
41
+ task.env.step = orig_step
42
+ if "f" in shot:
43
+ imageio.imwrite(os.path.join(out_dir, f"interrupt_{seed}.png"), shot["f"])
44
+ print("thumbs", f"{time.time()-t0:.0f}s", flush=True)
45
+
46
+ # 2) extra scripted policies
47
+ for kind in extra:
48
+ fs = []
49
+ for i in range(n):
50
+ seed = 1000 + i
51
+ inst = task.sample_instance(seed)
52
+ h = task.run_scripted(kind, inst, k=5, seed=seed)
53
+ s = next((x["attempt"] for x in h if x["outcome"]["success"]), None)
54
+ fs.append(s)
55
+ 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)])
56
+ print(kind, res["extra"][kind]["succ_at_k"], f"{time.time()-t0:.0f}s", flush=True)
57
+
58
+ # 3) no-injection sanity (oracle + naive, first 10 seeds)
59
+ task.inject = False
60
+ for kind in ("adaptive", "naive"):
61
+ fs = []
62
+ for i in range(10):
63
+ seed = 1000 + i
64
+ inst = task.sample_instance(seed)
65
+ h = task.run_scripted(kind, inst, k=1, seed=seed)
66
+ fs.append(bool(h[0]["outcome"]["success"]))
67
+ res["no_inject"][kind] = float(np.mean(fs))
68
+ print("no inject", kind, res["no_inject"][kind], flush=True)
69
+ task.inject = True
70
+
71
+ # 4) analytic memoryless baselines over the same seeds (perfect execution assumed)
72
+ if name == "l6_count_into_box":
73
+ insts = [task.sample_instance(1000 + i) for i in range(n)]
74
+ res["analytic"]["uniform_guess_0..N-1@1"] = float(np.mean([1 / x["n_target"] for x in insts]))
75
+ best = max(range(0, 6), key=lambda g: np.mean([x["n_target"] - x["p"] == g for x in insts]))
76
+ 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])))
77
+ res["analytic"]["p_hist"] = {str(v): int(sum(x["p"] == v for x in insts)) for v in range(1, 6)}
78
+ res["analytic"]["N_hist"] = {str(v): int(sum(x["n_target"] == v for x in insts)) for v in (4, 5)}
79
+ big = [task.sample_instance(5000 + i) for i in range(2000)]
80
+ res["analytic"]["uniform_guess@1_2000inst"] = float(np.mean([1 / x["n_target"] for x in big]))
81
+ 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)))
82
+ else:
83
+ insts = [task.sample_instance(1000 + i) for i in range(n)]
84
+ res["analytic"]["w_hist"] = {str(v): int(sum(x["stop_w"] == v for x in insts)) for v in range(1, 5)}
85
+ res["analytic"]["phase_hist"] = {p: int(sum(x["stop_phase"] == p for x in insts)) for p in "AB"}
86
+ res["analytic"]["uniform_guess_0..4@1"] = 0.2
87
+ big = [task.sample_instance(5000 + i) for i in range(2000)]
88
+ 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)))
89
+ res["analytic"]["skip_expected"] = float(np.mean([x["stop_phase"] == "B" or x["stop_w"] == 3 for x in big]))
90
+ res["seconds"] = time.time() - t0
91
+ json.dump(res, open(os.path.join(out_dir, "controls.json"), "w"), indent=1)
92
+ print(json.dumps(res["analytic"]))
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/lerobot_replay.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
2
+ against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
3
+ LeRobot export (scripts/lerobot_export.py).
4
+
5
+ python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
6
+ python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
7
+
8
+ Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
9
+ commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
10
+ is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
11
+ like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
12
+ outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
13
+ ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
14
+ hashes equal the current files are expected to match (check_code()).
15
+
16
+ Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
17
+ proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
18
+ protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
19
+ per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
20
+ fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
21
+ agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
22
+ frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
23
+ sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
24
+ final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
25
+ annotation.json episode annotation (build_annotation)
26
+ and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
27
+ """
28
+ import argparse
29
+ import ast
30
+ import hashlib
31
+ import importlib
32
+ import json
33
+ import math
34
+ import os
35
+ import pkgutil
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import time
40
+ from collections import defaultdict
41
+
42
+ import numpy as np
43
+
44
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
45
+ sys.path.insert(0, LFF_ROOT)
46
+
47
+ from lffbench import envs # noqa: E402
48
+ from lffbench import tasks as task_pkg # noqa: E402
49
+ from lffbench.agent import camera as C # noqa: E402
50
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
51
+ from lffbench.task_base import TASKS # noqa: E402
52
+
53
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
54
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
55
+
56
+ # per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
57
+ # task's outcome() check after `finish` (the arm holds still; not an agent action)
58
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
59
+ FPS = 20
60
+ SCHEMA = "lff-replay-1"
61
+
62
+ # error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
63
+ ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
64
+ ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
65
+ "n_missed_strikes", "n_open_gripper_pushes")
66
+
67
+
68
+ def load_jsonl(p):
69
+ out = []
70
+ if not os.path.exists(p):
71
+ return out
72
+ with open(p) as f:
73
+ for line in f:
74
+ line = line.strip()
75
+ if line:
76
+ try:
77
+ out.append(json.loads(line))
78
+ except ValueError:
79
+ pass
80
+ return out
81
+
82
+
83
+ def norm_json(o):
84
+ return json.loads(json.dumps(o, default=_json_default))
85
+
86
+
87
+ def sha256(p):
88
+ with open(p, "rb") as f:
89
+ return hashlib.sha256(f.read()).hexdigest()
90
+
91
+
92
+ def check_code(run_dir):
93
+ """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
94
+ p = os.path.join(run_dir, "contract.json")
95
+ if not os.path.exists(p):
96
+ return [("contract.json", None, None)]
97
+ files = json.load(open(p))["contract"].get("server_code_files", {})
98
+ bad = []
99
+ for f, h in files.items():
100
+ q = os.path.join(LFF_ROOT, f)
101
+ cur = sha256(q) if os.path.exists(q) else None
102
+ if cur != h:
103
+ bad.append((f, h, cur))
104
+ return bad
105
+
106
+
107
+ def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
108
+ """Differences between two JSON values (numbers compared with an absolute tolerance)."""
109
+ out = [] if out is None else out
110
+ if len(out) >= limit:
111
+ return out
112
+ if isinstance(a, dict) and isinstance(b, dict):
113
+ for k in sorted(set(a) | set(b)):
114
+ if k not in a or k not in b:
115
+ out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
116
+ else:
117
+ diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
118
+ elif isinstance(a, list) and isinstance(b, list):
119
+ if len(a) != len(b):
120
+ out.append((path, f"len {len(a)}", f"len {len(b)}"))
121
+ else:
122
+ for i, (x, y) in enumerate(zip(a, b)):
123
+ diff_json(x, y, f"{path}[{i}]", tol, out, limit)
124
+ elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
125
+ if a != b:
126
+ out.append((path, a, b))
127
+ elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
128
+ out.append((path, a, b))
129
+ return out
130
+
131
+
132
+ def error_event(o):
133
+ """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
134
+ if not isinstance(o, dict):
135
+ return None
136
+ keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
137
+ if not keys:
138
+ return None
139
+ 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)
140
+
141
+
142
+ # ====================================================================================================== logs -> notes
143
+
144
+ class RunLog:
145
+ """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
146
+ narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
147
+
148
+ def __init__(self, run_dir, manifest=None):
149
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
150
+ self.run = os.path.basename(self.run_dir)
151
+ self.batch = os.path.basename(os.path.dirname(self.run_dir))
152
+ self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
153
+ self.start = next(e for e in self.ev if e["ev"] == "session_start")
154
+ self.calls, self.dones, self.harness_status = {}, [], []
155
+ last = None
156
+ for e in self.ev:
157
+ if e["ev"] == "call":
158
+ self.calls[(int(e["attempt"]), int(e["step"]))] = e
159
+ last = e
160
+ elif e["ev"] == "done":
161
+ self.dones.append(e)
162
+ last = e
163
+ elif e["ev"] == "http" and last is not None and "think_s" not in last:
164
+ ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
165
+ (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
166
+ if ok:
167
+ last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
168
+ self.manifest = manifest or {}
169
+ self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
170
+ p = os.path.join(self.run_dir, "harness.json")
171
+ self.harness = json.load(open(p)) if os.path.exists(p) else {}
172
+ self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
173
+ self._narration()
174
+
175
+ # ---------------------------------------------------------------- agent narration
176
+ def _narration(self):
177
+ """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
178
+ finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
179
+ self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
180
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
181
+ attempt = 1
182
+
183
+ def take():
184
+ nonlocal buf
185
+ out = {k: v for k, v in buf.items() if v}
186
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
187
+ return out
188
+
189
+ last_msg = ""
190
+ for t in self.traj:
191
+ if t.get("kind") == "header":
192
+ self.headers.append(t.get("agent") or {})
193
+ continue
194
+ if t.get("kind") != "step":
195
+ continue
196
+ if (t.get("message") or "").strip():
197
+ buf["messages"].append(t["message"].strip())
198
+ last_msg = t["message"].strip()
199
+ if (t.get("reasoning_content") or "").strip():
200
+ buf["reasoning"].append(t["reasoning_content"].strip())
201
+ res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
202
+ for c in t.get("tool_calls") or []:
203
+ fn, args = c.get("function_name"), c.get("arguments") or {}
204
+ if fn == "shell":
205
+ buf["shell"].append(str(args.get("command", ""))[:2000])
206
+ elif fn == "view_images":
207
+ buf["viewed"].extend(args.get("paths") or [])
208
+ elif fn == "robot":
209
+ cmd = str(args.get("command", "")).strip()
210
+ r = res.get(c.get("tool_call_id")) or {}
211
+ try:
212
+ rep = json.loads(r.get("content") or "{}")
213
+ except ValueError:
214
+ rep = {}
215
+ word = cmd.split()[0] if cmd else ""
216
+ m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
217
+ if word in ("move_eef", "observe") and m:
218
+ a, s = int(m.group(1)), int(m.group(2))
219
+ n = take()
220
+ n["command"] = cmd
221
+ self.notes[(a, s)] = n
222
+ attempt = a
223
+ elif word in ("finish", "done"):
224
+ n = take()
225
+ n["command"] = cmd
226
+ n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
227
+ self.finish_notes.setdefault(attempt, n)
228
+ if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
229
+ attempt += 1
230
+ # status / help / errors: their narration stays in the buffer for the next command
231
+ self.final_report = last_msg
232
+
233
+ # ---------------------------------------------------------------- run-level labels
234
+ def attempts(self):
235
+ out = []
236
+ for e in self.dones:
237
+ o = e.get("outcome") or {}
238
+ if isinstance(o, str):
239
+ try:
240
+ o = ast.literal_eval(o)
241
+ except (ValueError, SyntaxError):
242
+ o = {}
243
+ out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
244
+ reason=e.get("reason") or ""))
245
+ return sorted(out, key=lambda x: x["attempt"])
246
+
247
+ def condition(self):
248
+ s, en = self.start, self.entry
249
+ mem = s.get("memory", en.get("mem"))
250
+ chain = en.get("chain")
251
+ if mem == "full":
252
+ cond = "with_history"
253
+ elif chain:
254
+ cond = "memory_free_retry"
255
+ else:
256
+ cond = "independent_single_attempt"
257
+ return cond, chain
258
+
259
+ def outcome_class(self):
260
+ """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
261
+ att = self.attempts()
262
+ if not att or self.start.get("memory") != "full":
263
+ return None, "".join("S" if a["success"] else "F" for a in att)
264
+ hist = "".join("S" if a["success"] else "F" for a in att)
265
+ if att[0]["success"]:
266
+ ev = error_event(att[0]["outcome"])
267
+ cls = "S?" if ev is None else ("IR" if ev else "CS")
268
+ else:
269
+ cls = "XR" if any(a["success"] for a in att) else "F"
270
+ return cls, hist
271
+
272
+ def agent_info(self):
273
+ h, en = self.harness, self.entry
274
+ hdr = self.headers[0] if self.headers else {}
275
+ return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
276
+ harness_version=h.get("version") or hdr.get("version"),
277
+ harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
278
+ model=h.get("model") or en.get("model") or hdr.get("model_name"),
279
+ effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
280
+ provider=h.get("provider") or en.get("provider"),
281
+ codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
282
+ jail=en.get("jail"))
283
+
284
+
285
+ # ====================================================================================================== recording
286
+
287
+ class EpisodeSink:
288
+ """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
289
+
290
+ def __init__(self, path):
291
+ self.path = path
292
+ os.makedirs(path, exist_ok=True)
293
+ self.w = None
294
+ self.num = defaultdict(list)
295
+ self.n = 0
296
+
297
+ def add(self, st, imgs):
298
+ import imageio
299
+ if self.w is None:
300
+ self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
301
+ pixelformat="rgb24", macro_block_size=1,
302
+ ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
303
+ for k in ("agentview", "wrist")]
304
+ for w, im in zip(self.w, imgs):
305
+ w.append_data(im)
306
+ for k, v in st.items():
307
+ self.num[k].append(v)
308
+ self.n += 1
309
+
310
+ def close(self, final_state, final_imgs):
311
+ from PIL import Image
312
+ if self.w is not None:
313
+ for w in self.w:
314
+ w.close()
315
+ arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
316
+ np.savez(os.path.join(self.path, "frames.npz"), **arr)
317
+ if self.num.get("sim_state"):
318
+ np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
319
+ np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
320
+ for k, im in zip(("agentview", "wrist"), final_imgs):
321
+ Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
322
+
323
+
324
+ class Recorder:
325
+ """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
326
+
327
+ def __init__(self, rp, res):
328
+ self.rp, self.res = rp, int(res)
329
+ self.active = False
330
+ self.sink = None
331
+ self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
332
+ env = rp.task.env
333
+ self.env, self.rob = env, env.robots[0]
334
+ self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
335
+ orig = env.step
336
+
337
+ def step(a):
338
+ if self.active and self.sink is not None:
339
+ self.capture(np.asarray(a, np.float64))
340
+ out = orig(a)
341
+ if self.active and self.sink is not None:
342
+ self.rp.poll_events(self.sink.n - 1)
343
+ return out
344
+
345
+ env.step = step
346
+
347
+ @property
348
+ def n(self):
349
+ return self.sink.n if self.sink is not None else 0
350
+
351
+ def state(self):
352
+ import robosuite.utils.transform_utils as T
353
+ env, rob = self.env, self.rob
354
+ d = env.sim.data
355
+ eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
356
+ q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
357
+ gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
358
+ try:
359
+ flat = np.asarray(env.sim.get_state().flatten(), np.float64)
360
+ except Exception:
361
+ flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
362
+ sk = self.rp.task.sk
363
+ return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
364
+ gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
365
+ joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
366
+ gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
367
+ eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
368
+ sim_time=np.float64(d.time), sim_state=flat)
369
+
370
+ def images(self):
371
+ return [envs.render(self.env, c, self.res) for c in self.cams]
372
+
373
+ def capture(self, a):
374
+ st = self.state()
375
+ st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
376
+ phase=np.int64(self.cur["phase"]))
377
+ self.sink.add(st, self.images())
378
+
379
+
380
+ class RunReplay:
381
+ def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
382
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
383
+ self.run_name = os.path.basename(self.run_dir)
384
+ self.log = RunLog(self.run_dir, manifest)
385
+ self.ev = self.log.ev
386
+ self.start = self.log.start
387
+ cp = os.path.join(self.run_dir, "contract.json")
388
+ self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
389
+ spec = self.contract.get("image_spec") or {}
390
+ self.image_res = int(spec.get("width", 512))
391
+ self.code_diff = check_code(self.run_dir)
392
+ s = self.start
393
+ self.task = TASKS[s["task"]](cam_res=self.image_res)
394
+ inst = self.task.sample_instance(s["seed"])
395
+ logged = s.get("inst") or {}
396
+ sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
397
+ self.inst_diff = diff_json(sampled, logged, "inst")
398
+ if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
399
+ inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
400
+ self.inst_diff = []
401
+ self.inst = inst
402
+ self.protocol = getattr(self.task, "protocol", "cross")
403
+ self.k = int(s.get("k") or self.task.max_attempts)
404
+ self.attempt = 1
405
+ self.mismatch = [] # (where, what, logged, replayed)
406
+ self.n_checked = 0
407
+ self.max_dev_m = 0.0
408
+ self.unfinished = None
409
+ self.rec = Recorder(self, res) if record else None
410
+ self.res = int(res)
411
+ self.out_root = out_root
412
+ self.n_mon = 0
413
+ self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
414
+ self.episodes = [] # summaries of the written episodes
415
+ self.task.reset_instance(self.inst)
416
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
417
+ sim = self.task.env.sim
418
+ bid = sim.model.body_name2id("robot0_base")
419
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
420
+ if self.rec:
421
+ self._open_episode()
422
+
423
+ # ------------------------------------------------------------------ episodes
424
+ def _ep_dir(self):
425
+ return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
426
+
427
+ def _open_episode(self):
428
+ self.rec.sink = EpisodeSink(self._ep_dir())
429
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
430
+ self.rec.active = True
431
+ self.events, self.spans, self.ep_attempts = [], [], []
432
+ self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
433
+
434
+ def close_episode(self):
435
+ if not self.rec:
436
+ self.ep_attempts = []
437
+ return
438
+ sink = self.rec.sink
439
+ st = self.rec.state()
440
+ imgs = self.rec.images()
441
+ st.pop("sim_state", None)
442
+ sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
443
+ ann = build_annotation(self, sink)
444
+ with open(os.path.join(sink.path, "annotation.json"), "w") as f:
445
+ json.dump(ann, f, indent=1, default=_json_default)
446
+ self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
447
+ attempts=[a["attempt"] for a in self.ep_attempts]))
448
+ self.rec.active = False
449
+ self.rec.sink = None
450
+ self.ep_index += 1
451
+
452
+ # ------------------------------------------------------------------ monitor events (task-side error events)
453
+ def poll_events(self, frame):
454
+ mon = getattr(self.task, "mon", None)
455
+ evs = mon.get("events") if isinstance(mon, dict) else None
456
+ if not isinstance(evs, list):
457
+ return
458
+ if len(evs) < self.n_mon: # monitor was rebuilt
459
+ self.n_mon = 0
460
+ for e in evs[self.n_mon:]:
461
+ self.events.append(dict(frame=int(frame), attempt=self.attempt,
462
+ event=norm_json(e) if isinstance(e, dict) else str(e)))
463
+ self.n_mon = len(evs)
464
+
465
+ # ------------------------------------------------------------------ state as the server reports it
466
+ def proprio_la(self):
467
+ p = self.ex.proprio()
468
+ pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
469
+ return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
470
+
471
+ def compare(self, where, rep_logged, rep):
472
+ self.n_checked += 1
473
+ for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
474
+ if k not in rep_logged or k not in rep:
475
+ continue
476
+ a, b = rep_logged[k], rep[k]
477
+ if k == "eef_pos":
478
+ dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
479
+ self.max_dev_m = max(self.max_dev_m, dev)
480
+ if dev > 1.5e-4:
481
+ self.mismatch.append((where, k, a, b))
482
+ elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
483
+ self.mismatch.append((where, k, a, b))
484
+ if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
485
+ self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
486
+
487
+ def _span(self, e, f0, kind):
488
+ if self.rec:
489
+ self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
490
+ frame_end=self.rec.n))
491
+
492
+ # ------------------------------------------------------------------ commands (robot_server._handle_v2)
493
+ def move_eef(self, e):
494
+ args = e.get("args") or {}
495
+ where = f"a{e['attempt']}s{e['step']}"
496
+ logged = e.get("report") or {}
497
+ f0 = self.rec.n if self.rec else 0
498
+ p = self.ex.proprio()
499
+ if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
500
+ self._span(e, f0, "error")
501
+ return self.compare(where, logged, dict(ok=False))
502
+ off = self.base_off
503
+ try:
504
+ cur = np.asarray(p["eef_pos"], float) - off
505
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
506
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
507
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
508
+ except (TypeError, ValueError):
509
+ self._span(e, f0, "error")
510
+ return self.compare(where, logged, dict(ok=False))
511
+ grip = args.get("gripper")
512
+ if grip not in (None, "open", "close"):
513
+ self._span(e, f0, "error")
514
+ return self.compare(where, logged, dict(ok=False))
515
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
516
+ tgt_w = np.asarray(tgt) + off
517
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
518
+ self._span(e, f0, "rejected")
519
+ return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
520
+ raw = {}
521
+ if self.rec:
522
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
523
+ if moving:
524
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
525
+ if speed is not None:
526
+ mv["speed"] = speed
527
+ raw.update(self.ex.call("move_to", mv).report)
528
+ if grip is not None:
529
+ if self.rec:
530
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
531
+ raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
532
+ rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
533
+ self.compare(where, logged, rep)
534
+ lr = e.get("raw") or {}
535
+ for k in ("holding_object", "touched_object"):
536
+ if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
537
+ self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
538
+ self._span(e, f0, "move_eef")
539
+
540
+ def observe(self, e):
541
+ f0 = self.rec.n if self.rec else 0
542
+ self._span(e, f0, "observe")
543
+
544
+ def done(self, e):
545
+ f0 = self.rec.n if self.rec else 0
546
+ if self.rec:
547
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
548
+ out = self.task.outcome(self.inst)
549
+ succ = bool(out["success"])
550
+ where = f"a{e['attempt']}done"
551
+ if succ != bool(e.get("success") in (True, "True")):
552
+ self.mismatch.append((where, "success", e.get("success"), succ))
553
+ lo = e.get("outcome") or {}
554
+ ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
555
+ if isinstance(lo, dict):
556
+ for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
557
+ self.mismatch.append((where,) + d)
558
+ info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
559
+ feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
560
+ think_s=e.get("think_s"))
561
+ try:
562
+ info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
563
+ except Exception as ex_:
564
+ info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
565
+ if self.rec:
566
+ info["judge_frames"] = [f0, self.rec.n]
567
+ self.ep_attempts.append(info)
568
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
569
+ if self.protocol == "cross" or last:
570
+ self.close_episode()
571
+ if last:
572
+ return True
573
+ self.attempt += 1
574
+ if self.protocol == "cross":
575
+ self.task.reset_instance(self.inst)
576
+ self.n_mon = 0
577
+ if self.rec:
578
+ self._open_episode()
579
+ elif self.rec:
580
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
581
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
582
+ return False
583
+
584
+ def run(self):
585
+ t0 = time.time()
586
+ finished = False
587
+ for e in self.ev:
588
+ if e["ev"] == "call":
589
+ if e.get("cmd") == "move_eef":
590
+ self.move_eef(e)
591
+ elif e.get("cmd") == "observe":
592
+ self.observe(e)
593
+ else:
594
+ self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
595
+ elif e["ev"] == "done":
596
+ finished = self.done(e)
597
+ if finished:
598
+ break
599
+ self.unfinished = not finished
600
+ if not finished and self.rec and self.rec.sink is not None:
601
+ # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
602
+ if self.rec.n or self.ep_attempts:
603
+ self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
604
+ finish_reason="", feedback_shown="", auto_ended=False))
605
+ self.close_episode()
606
+ else:
607
+ shutil.rmtree(self.rec.sink.path, ignore_errors=True)
608
+ self.rec.sink = None
609
+ self.wall_s = time.time() - t0
610
+ return self
611
+
612
+ def summary(self):
613
+ return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
614
+ protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
615
+ n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
616
+ unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
617
+ first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
618
+
619
+
620
+ # ====================================================================================================== annotation
621
+
622
+ def task_info(task, inst):
623
+ cls = type(task)
624
+ return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
625
+ category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
626
+ max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
627
+ instruction=cls.instruction)
628
+
629
+
630
+ def build_annotation(rp, sink):
631
+ """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
632
+ failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
633
+ task-side error events with frame indices."""
634
+ log = rp.log
635
+ s = rp.start
636
+ cond, chain = log.condition()
637
+ cls, hist = log.outcome_class()
638
+ att_all = log.attempts()
639
+ attempts = []
640
+ for a in rp.ep_attempts:
641
+ a = dict(a)
642
+ n = a["attempt"]
643
+ later = [x for x in att_all if x["attempt"] > n]
644
+ a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
645
+ a["is_last_attempt_of_run"] = not later
646
+ fn = log.finish_notes.get(n)
647
+ if fn:
648
+ a["agent_finish"] = fn
649
+ a["error_event_in_attempt"] = error_event(a.get("outcome"))
650
+ attempts.append(a)
651
+ # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
652
+ for a in attempts:
653
+ nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
654
+ if a.get("success") is False and nxt:
655
+ note = log.notes[nxt[0]]
656
+ a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
657
+ commands = []
658
+ for sp in rp.spans:
659
+ e = log.calls.get((sp["attempt"], sp["step"])) or {}
660
+ rep = e.get("report") or {}
661
+ c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
662
+ frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
663
+ args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
664
+ stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
665
+ gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
666
+ touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
667
+ agent_obs_images=rep.get("images"))
668
+ note = log.notes.get((sp["attempt"], sp["step"]))
669
+ if note:
670
+ c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
671
+ commands.append(c)
672
+ t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
673
+ return dict(
674
+ schema=SCHEMA,
675
+ source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
676
+ episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
677
+ memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
678
+ feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
679
+ k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
680
+ contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
681
+ if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
682
+ agent=log.agent_info(),
683
+ task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
684
+ instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
685
+ run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
686
+ run_success=any(x["success"] for x in att_all) if att_all else None,
687
+ agent_final_report=log.final_report[:6000] or None,
688
+ mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
689
+ attempts=attempts,
690
+ commands=commands,
691
+ task_events=rp.events,
692
+ frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
693
+ phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
694
+ joint_pos=rp.ep_initial["joint_pos"],
695
+ gripper_qpos=rp.ep_initial["gripper_qpos"])),
696
+ )
697
+
698
+
699
+ # ====================================================================================================== CLI
700
+
701
+ def load_manifest(run_dir):
702
+ p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
703
+ return json.load(open(p)) if os.path.exists(p) else {}
704
+
705
+
706
+ def main():
707
+ ap = argparse.ArgumentParser()
708
+ ap.add_argument("mode", choices=["check", "record"])
709
+ ap.add_argument("runs", nargs="+")
710
+ ap.add_argument("--json", default="")
711
+ ap.add_argument("--out", default="")
712
+ ap.add_argument("--res", type=int, default=256)
713
+ ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
714
+ a = ap.parse_args()
715
+ rows = []
716
+ for r in a.runs:
717
+ r = r.rstrip("/")
718
+ try:
719
+ if a.mode == "check":
720
+ s = RunReplay(r, manifest=load_manifest(r)).run().summary()
721
+ else:
722
+ batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
723
+ rd = os.path.join(a.out, batch, name)
724
+ if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
725
+ print(json.dumps(dict(run=name, skipped="exists")), flush=True)
726
+ continue
727
+ shutil.rmtree(rd, ignore_errors=True)
728
+ rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
729
+ s = rp.summary()
730
+ s["episodes"] = rp.episodes
731
+ with open(os.path.join(rd, "replay.json"), "w") as f:
732
+ json.dump(s, f, indent=1)
733
+ except Exception:
734
+ import traceback
735
+ s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
736
+ rows.append(s)
737
+ print(json.dumps(s), flush=True)
738
+ if a.json:
739
+ with open(a.json, "w") as f:
740
+ json.dump(rows, f, indent=1)
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/redteam_report.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adversarial acceptance report: every red-team run of a batch, what it reached and what needs a human look.
2
+
3
+ python scripts/api_batch.py start --batch rt1 --harness codex --jail --red-team --memfree none --no-hide-k \
4
+ --model gpt-6-astra --effort high --k 3 --video --tasks <task:seed> ...
5
+ python scripts/redteam_report.py --batch rt1 [--out rt1_report.md] [--json rt1.json]
6
+
7
+ Acceptance (lffbench/harnesses/redteam.py; Embodied First Exam PROTOCOL H.1): a task passes when its red-team runs
8
+ end with no success and no flag. Everything else is listed for review:
9
+ success the environment reported "Attempt succeeded." Watch the video / read the trajectory: a hole in the
10
+ success check or the sandbox (fix the task, bump its version, rerun) or the task solved in the ordinary
11
+ way (note it; not a finding);
12
+ audit the adapter's audit found a violation (tools, memory, sandbox);
13
+ model_gateway the model gateway refused a request (provider-side tools, other paths, other models, ...);
14
+ not_red_team the run's contract has no red_team key (it was not launched with --red-team): never counted.
15
+ The agent's own "RED-TEAM REPORT:" and its redteam_notes.md are quoted so that claimed exploits can be checked.
16
+ """
17
+ import argparse
18
+ import glob
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24
+ import api_batch # noqa: E402
25
+ from outcomes import attempts # noqa: E402
26
+
27
+
28
+ def final_report(log):
29
+ """The agent's last text containing RED-TEAM REPORT (trajectory.jsonl of the adapter layer), or None."""
30
+ best = None
31
+ p = os.path.join(log, "trajectory.jsonl")
32
+ if not os.path.exists(p):
33
+ return None
34
+ for line in open(p):
35
+ try:
36
+ d = json.loads(line)
37
+ except ValueError:
38
+ continue
39
+ for v in (d.get("text"), d.get("content"), d.get("message")):
40
+ if isinstance(v, str) and "RED-TEAM REPORT" in v:
41
+ best = v
42
+ return best
43
+
44
+
45
+ def notes(r):
46
+ sb = r.get("sandbox")
47
+ for p in ([os.path.join(sb, "redteam_notes.md")] if sb else []) + glob.glob(os.path.join(r.get("log") or "", "**",
48
+ "redteam_notes.md"),
49
+ recursive=True):
50
+ if os.path.exists(p):
51
+ return open(p, errors="replace").read()
52
+ return None
53
+
54
+
55
+ def run_row(r):
56
+ log = r.get("log") or ""
57
+ hj = {}
58
+ try:
59
+ hj = json.load(open(os.path.join(log, "harness.json")))
60
+ except (OSError, ValueError):
61
+ pass
62
+ try:
63
+ contract = json.load(open(os.path.join(log, "contract.json")))
64
+ except (OSError, ValueError):
65
+ contract = {}
66
+ att = attempts(log)
67
+ flags = []
68
+ if not (contract.get("contract") or contract).get("red_team"):
69
+ flags.append("not_red_team")
70
+ if any(s for _, s, _, _ in att):
71
+ flags.append("success")
72
+ if hj.get("audit_ok") is False or hj.get("violations"):
73
+ flags.append("audit")
74
+ if hj.get("review_flags"):
75
+ flags.append("model_gateway")
76
+ return dict(task=r["task"], seed=r["seed"], run=r.get("run"), status=r.get("status"),
77
+ attempts="".join("S" if s else "F" for _, s, _, _ in att), flags=flags,
78
+ success_outcomes=[o for _, s, o, _ in att if s], finish_reasons=[x for _, _, _, x in att],
79
+ violations=hj.get("violations"), review_flags=hj.get("review_flags"),
80
+ report=final_report(log), notes=notes(r), log=log)
81
+
82
+
83
+ def main():
84
+ ap = argparse.ArgumentParser()
85
+ ap.add_argument("--batch", action="append", required=True)
86
+ ap.add_argument("--out", default=None, help="markdown report (default: print)")
87
+ ap.add_argument("--json", default=None)
88
+ a = ap.parse_args()
89
+ rows = [run_row(r) for b in a.batch for r in api_batch.load(b)["runs"] if r.get("red_team")]
90
+ by_task = {}
91
+ for x in rows:
92
+ by_task.setdefault(x["task"], []).append(x)
93
+ md = ["# Adversarial acceptance (red-team) report", "", f"batches: {', '.join(a.batch)}; runs: {len(rows)}", "",
94
+ "| task | seed | status | attempts | verdict | flags |", "|---|---|---|---|---|---|"]
95
+ for task in sorted(by_task):
96
+ for x in by_task[task]:
97
+ verdict = ("incomplete" if x["status"] != "done" else "REVIEW" if x["flags"] else "pass")
98
+ md.append(f"| {task} | {x['seed']} | {x['status']} | {x['attempts'] or '-'} | {verdict} | "
99
+ f"{', '.join(x['flags']) or '-'} |")
100
+ passed = sorted(t for t, xs in by_task.items() if all(x["status"] == "done" and not x["flags"] for x in xs))
101
+ md += ["", f"tasks passing: {len(passed)}/{len(by_task)}", ""]
102
+ for x in rows:
103
+ if not x["flags"]:
104
+ continue
105
+ md += [f"## {x['task']} s{x['seed']}: {', '.join(x['flags'])}", "", f"log: `{x['log']}`", ""]
106
+ if x["success_outcomes"]:
107
+ md += ["success outcome(s): `" + json.dumps(x["success_outcomes"], default=str)[:1500] + "`", ""]
108
+ if x["violations"] or x["review_flags"]:
109
+ md += [f"violations: {x['violations']}; review flags: {x['review_flags']}", ""]
110
+ if x["report"]:
111
+ md += ["agent report:", "", "```", x["report"][:4000], "```", ""]
112
+ if x["notes"]:
113
+ md += ["redteam_notes.md:", "", "```", x["notes"][:4000], "```", ""]
114
+ text = "\n".join(md) + "\n"
115
+ if a.out:
116
+ open(a.out, "w").write(text)
117
+ else:
118
+ print(text)
119
+ if a.json:
120
+ json.dump(rows, open(a.json, "w"), indent=1, default=str)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model backends. Import lazily: each API backend needs its provider's SDK (see base.import_sdk)."""
2
+ from .base import AttemptInfo, Backend, BackendResponse, RunInfo # noqa: F401
3
+
4
+
5
+ def make_backend(kind, **kw):
6
+ if kind == "scripted":
7
+ from .scripted import ScriptedBackend
8
+ return ScriptedBackend(**kw)
9
+ if kind == "openai":
10
+ from .openai_responses import OpenAIResponsesBackend
11
+ return OpenAIResponsesBackend(**kw)
12
+ if kind == "chat":
13
+ from .chat_completions import ChatCompletionsBackend
14
+ return ChatCompletionsBackend(**kw)
15
+ if kind == "anthropic":
16
+ from .anthropic_messages import AnthropicMessagesBackend
17
+ return AnthropicMessagesBackend(**kw)
18
+ if kind == "gemini":
19
+ from .gemini import GeminiBackend
20
+ return GeminiBackend(**kw)
21
+ raise ValueError(kind)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/gemini.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Google Gemini backend (Gemini API, official SDK `google-genai`).
2
+
3
+ Same conversation as the other backends, converted to Gemini `contents`:
4
+ - system prompt = system_instruction; tools = function declarations with the harness's JSON schemas;
5
+ - every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive)
6
+ and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call;
7
+ - tool outputs of one turn become `function_response` parts at the start of the next user content; images the
8
+ harness attaches after them follow in the same user content;
9
+ - thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged;
10
+ - implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage).
11
+
12
+ Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock.
13
+ """
14
+ import base64
15
+ import time
16
+
17
+ from ..context import ToolCall, prune_live_images
18
+ from .base import Backend, BackendResponse, import_sdk
19
+
20
+
21
+ def _get(obj, key, default=None):
22
+ if isinstance(obj, dict):
23
+ return obj.get(key, default)
24
+ return getattr(obj, key, default)
25
+
26
+
27
+ def _strip_additional(schema):
28
+ """The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema."""
29
+ if isinstance(schema, dict):
30
+ return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"}
31
+ if isinstance(schema, list):
32
+ return [_strip_additional(v) for v in schema]
33
+ return schema
34
+
35
+
36
+ def _image_part(image, quality=None):
37
+ head, data = image.data_url(quality).split(",", 1)
38
+ mime = head[len("data:"):].split(";", 1)[0]
39
+ return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data)))
40
+
41
+
42
+ class GeminiBackend(Backend):
43
+ name = "gemini"
44
+
45
+ def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True,
46
+ max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90,
47
+ timeout=900.0, client=None):
48
+ self.model = model
49
+ self.thinking_level = thinking_level
50
+ self.thinking_budget = thinking_budget
51
+ self.include_thoughts = include_thoughts
52
+ self.max_output_tokens = max_output_tokens
53
+ self.media_resolution = media_resolution
54
+ self.max_live_images = max_live_images
55
+ self.jpeg_quality = jpeg_quality
56
+ self.timeout = timeout
57
+ self._client = client
58
+ self._json_schema_field = None
59
+
60
+ def config(self):
61
+ return dict(name=self.name, model=self.model, thinking_level=self.thinking_level,
62
+ thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts,
63
+ max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution,
64
+ max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout)
65
+
66
+ def client(self):
67
+ if self._client is None:
68
+ genai = import_sdk("google.genai")
69
+ self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000)))
70
+ return self._client
71
+
72
+ def _declarations(self, specs):
73
+ if self._json_schema_field is None:
74
+ try:
75
+ types = import_sdk("google.genai.types")
76
+ self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields
77
+ except ImportError: # tests without the SDK
78
+ self._json_schema_field = True
79
+ out = []
80
+ for s in specs:
81
+ d = dict(name=s["name"], description=s["description"])
82
+ if self._json_schema_field:
83
+ d["parameters_json_schema"] = s["parameters"]
84
+ else:
85
+ d["parameters"] = _strip_additional(s["parameters"])
86
+ out.append(d)
87
+ return [dict(function_declarations=out)]
88
+
89
+ # ------------------------------------------------------------------ request
90
+ def convert_items(self, items):
91
+ contents = []
92
+
93
+ def push(role, parts):
94
+ if contents and contents[-1]["role"] == role:
95
+ contents[-1]["parts"].extend(parts)
96
+ else:
97
+ contents.append(dict(role=role, parts=list(parts)))
98
+
99
+ for it in items:
100
+ kind = it["kind"]
101
+ if kind == "user":
102
+ parts = []
103
+ for p in it["parts"]:
104
+ if p["type"] == "text":
105
+ parts.append(dict(text=p["text"]))
106
+ else:
107
+ parts.append(_image_part(p["image"], self.jpeg_quality))
108
+ push("user", parts)
109
+ elif kind == "assistant":
110
+ if it.get("raw") is not None and it.get("backend") == self.name:
111
+ content = dict(it["raw"][0])
112
+ contents.append(dict(role="model", parts=list(content.get("parts") or [])))
113
+ continue
114
+ parts = ([dict(text=it["text"])] if it.get("text") else [])
115
+ parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]]
116
+ push("model", parts or [dict(text="(no output)")])
117
+ elif kind == "tool_output":
118
+ fr = dict(name=it["name"], response=dict(output=it["text"]))
119
+ if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"):
120
+ fr["id"] = it["call_id"]
121
+ push("user", [dict(function_response=fr)])
122
+ else:
123
+ raise ValueError(kind)
124
+ return contents
125
+
126
+ def build_request(self, conv, tools):
127
+ items = prune_live_images(conv.items, self.max_live_images)
128
+ thinking = dict(include_thoughts=self.include_thoughts)
129
+ if self.thinking_budget is not None:
130
+ thinking["thinking_budget"] = int(self.thinking_budget)
131
+ elif self.thinking_level:
132
+ thinking["thinking_level"] = self.thinking_level
133
+ config = dict(system_instruction=conv.system, tools=self._declarations(tools),
134
+ tool_config=dict(function_calling_config=dict(mode="AUTO")),
135
+ automatic_function_calling=dict(disable=True), thinking_config=thinking,
136
+ max_output_tokens=int(self.max_output_tokens))
137
+ if self.media_resolution:
138
+ config["media_resolution"] = self.media_resolution
139
+ return dict(model=self.model, contents=self.convert_items(items), config=config)
140
+
141
+ @staticmethod
142
+ def request_stats(req):
143
+ n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "")
144
+ for c in req["contents"]:
145
+ for p in c["parts"]:
146
+ p = p if isinstance(p, dict) else {}
147
+ if p.get("inline_data"):
148
+ n_img += 1
149
+ img_bytes += len(p["inline_data"]["data"])
150
+ elif p.get("text"):
151
+ txt += len(p["text"])
152
+ elif p.get("function_response"):
153
+ txt += len(str(p["function_response"].get("response", "")))
154
+ return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"]))
155
+
156
+ # ------------------------------------------------------------------ call
157
+ def act(self, conv, tools):
158
+ req = self.build_request(conv, tools)
159
+ stats = self.request_stats(req)
160
+ types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys
161
+ t0 = time.time()
162
+ resp = self.client().models.generate_content(
163
+ model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]],
164
+ config=types.GenerateContentConfig.model_validate(req["config"]))
165
+ out = self.parse_response(resp)
166
+ out.latency_s = time.time() - t0
167
+ out.request_stats = stats
168
+ return out
169
+
170
+ def parse_response(self, resp):
171
+ cands = _get(resp, "candidates") or []
172
+ cand = cands[0] if cands else None
173
+ content = _get(cand, "content") if cand is not None else None
174
+ parts = (_get(content, "parts") or []) if content is not None else []
175
+ calls, texts, summ = [], [], []
176
+ for i, p in enumerate(parts):
177
+ fc = _get(p, "function_call")
178
+ if fc is not None:
179
+ cid = _get(fc, "id") or f"gemini_call_{i}"
180
+ calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {})))
181
+ elif _get(p, "text"):
182
+ (summ if _get(p, "thought") else texts).append(_get(p, "text"))
183
+ u = _get(resp, "usage_metadata")
184
+ usage = {}
185
+ if u is not None:
186
+ usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0,
187
+ cached_tokens=_get(u, "cached_content_token_count", 0) or 0,
188
+ output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0),
189
+ reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0)
190
+ finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE"
191
+ status, err = "completed", None
192
+ if not parts:
193
+ status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})"
194
+ elif "MAX_TOKENS" in finish or "MALFORMED" in finish:
195
+ status, err = "incomplete", f"incomplete: finish_reason={finish}"
196
+ elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish:
197
+ status, err = "refusal", f"refusal: finish_reason={finish}"
198
+ if content is not None and hasattr(content, "model_dump"):
199
+ raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes
200
+ elif content is not None:
201
+ raw = [dict(content)]
202
+ else:
203
+ raw = None
204
+ return BackendResponse(tool_calls=calls, text="\n".join(texts) or None,
205
+ reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw,
206
+ status=status, error=err)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/scripted.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scripted backend: no model. Runs a task's scripted reference policy (adaptive by default) through the
2
+ agent tool interface, to test the harness end to end.
3
+
4
+ How: the task's own `execute(inst, params)` runs in a worker thread with `task.sk` replaced by a proxy.
5
+ Every Skills primitive it calls (move_to / set_gripper / push / grasp_at / place_at) becomes an agent
6
+ tool call that is handed to the harness, executed by the ToolExecutor on the main thread, and its
7
+ report is returned to the worker. Only one thread runs at a time (queues hand control back and forth),
8
+ so MuJoCo is never touched concurrently. Only schema-valid tool calls are emitted, so this also shows
9
+ that the tool interface is expressive enough for the task.
10
+
11
+ The scripted policy is privileged: it reads the instance (layout) like the task's reference policies
12
+ do. It sees earlier attempts only through the memory mode chosen by the harness and only the outcome
13
+ fields allowed by the feedback level (F2: structured measurement, F1: success flag, F0: nothing); if
14
+ the adaptive rule cannot run on what it sees, it falls back to the task's blind retry rule.
15
+ Supported: cross-protocol tasks that implement execute/default_params/adapt_params (+ oracle/blind).
16
+ """
17
+ import math
18
+ import queue
19
+ import threading
20
+ import traceback
21
+
22
+ import numpy as np
23
+
24
+ from ..context import ToolCall
25
+ from .base import Backend, BackendResponse
26
+
27
+ TIMEOUT_S = 600
28
+
29
+
30
+ class _Abort(Exception):
31
+ pass
32
+
33
+
34
+ class _Channel:
35
+ def __init__(self):
36
+ self.req = queue.Queue()
37
+ self.res = queue.Queue()
38
+
39
+ def call(self, name, args): # worker side
40
+ self.req.put(("call", name, args))
41
+ kind, payload = self.res.get(timeout=TIMEOUT_S)
42
+ if kind == "abort":
43
+ raise _Abort()
44
+ return payload
45
+
46
+
47
+ class SkillsProxy:
48
+ """Stands in for task.sk inside task.execute(); primitives become agent tool calls."""
49
+
50
+ def __init__(self, real, channel):
51
+ self._real = real
52
+ self._ch = channel
53
+ self.untooled_hold_steps = 0
54
+ self.ignored_wrap_yaw_false = 0
55
+
56
+ def move_to(self, target, yaw=None, speed=None, tol=None, max_steps=None, apply_bias=True, wrap_yaw=True):
57
+ if not wrap_yaw: # the move_to tool always wraps yaw mod pi (Skills default); counted, not fatal
58
+ self.ignored_wrap_yaw_false += 1
59
+ if not apply_bias:
60
+ raise NotImplementedError("apply_bias=False cannot be expressed through the agent tools")
61
+ yaw_deg = math.degrees(self._real.yaw if yaw is None else float(yaw))
62
+ rep = self._ch.call("move_to", dict(x=float(target[0]), y=float(target[1]), z=float(target[2]),
63
+ yaw=round(yaw_deg, 3), speed=None if speed is None else float(speed)))
64
+ return dict(prim="move_to", reached=rep.get("reached"), pos=rep.get("eef_pos"))
65
+
66
+ def set_gripper(self, close, steps=15):
67
+ rep = self._ch.call("close_gripper" if close else "open_gripper", {})
68
+ return dict(prim="close" if close else "open", width=rep.get("gripper_width_m"))
69
+
70
+ def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06):
71
+ rep = self._ch.call("push", dict(x=float(start_xy[0]), y=float(start_xy[1]), dir_x=float(direction_xy[0]),
72
+ dir_y=float(direction_xy[1]), distance=float(distance), speed=float(speed),
73
+ z=None if z is None else float(z), runup=float(pre)))
74
+ return dict(prim="push", reached=rep.get("sweep_reached"), pos=rep.get("eef_pos"))
75
+
76
+ def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15):
77
+ self.set_gripper(False, steps=5)
78
+ self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw)
79
+ self.move_to([xy[0], xy[1], z_grasp])
80
+ self.set_gripper(True)
81
+ self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25)
82
+
83
+ def place_at(self, xy, z_release, approach=0.10):
84
+ self.move_to([xy[0], xy[1], z_release + approach])
85
+ self.move_to([xy[0], xy[1], z_release])
86
+ self.set_gripper(False)
87
+ self.move_to([xy[0], xy[1], z_release + approach])
88
+
89
+ def hold(self, steps=10):
90
+ # waiting in place has no tool; executed directly (only physics, no new command) and counted
91
+ self.untooled_hold_steps += int(steps)
92
+ self._real.hold(steps)
93
+
94
+ def __getattr__(self, k): # eef_pos, eef_mat, gripper_width, holding, yaw, ...
95
+ return getattr(self._real, k)
96
+
97
+
98
+ class ScriptedBackend(Backend):
99
+ name = "scripted"
100
+
101
+ def __init__(self, policy="adaptive", seed=0):
102
+ assert policy in ("adaptive", "naive", "oracle", "blind"), policy
103
+ self.policy = policy
104
+ self.seed = seed
105
+ self.info = None
106
+ self.rng = None
107
+
108
+ def config(self):
109
+ return dict(name=self.name, policy=self.policy, seed=self.seed)
110
+
111
+ def begin_run(self, info):
112
+ if info.protocol != "cross":
113
+ raise NotImplementedError("ScriptedBackend supports cross-protocol tasks only (execute/adapt_params)")
114
+ self.info = info
115
+ self.rng = np.random.default_rng(self.seed + info.seed)
116
+ self._oracle = None
117
+ if self.policy == "oracle": # privileged scratch rollouts happen before the harness resets the scene
118
+ self._oracle = info.task.oracle_params(info.inst)
119
+
120
+ # ------------------------------------------------------------------ params from visible history
121
+ def _visible(self, rec):
122
+ out = rec.outcome
123
+ if self.info.feedback == "F2":
124
+ vis = dict(out)
125
+ elif self.info.feedback == "F1":
126
+ vis = dict(success=out.get("success"))
127
+ else:
128
+ vis = {}
129
+ return dict(attempt=rec.attempt, params=rec.backend_meta.get("params"), outcome=vis)
130
+
131
+ def _params(self, attempt, history):
132
+ task, inst = self.info.task, self.info.inst
133
+ if self.policy == "oracle":
134
+ return dict(self._oracle), "oracle"
135
+ if self.policy == "naive" or not history and self.policy == "adaptive":
136
+ return task.default_params(inst), "default"
137
+ if self.policy == "blind":
138
+ if attempt == 1:
139
+ return task.default_params(inst), "default"
140
+ return task.blind_params(inst, attempt - 1, self.rng), "blind"
141
+ hist = [self._visible(r) for r in history if r.backend_meta.get("params") is not None]
142
+ if not hist:
143
+ return task.blind_params(inst, attempt - 1, self.rng), "blind(no usable history)"
144
+ try:
145
+ return task.adapt_params(inst, hist), "adapt"
146
+ except (KeyError, TypeError, ValueError):
147
+ return task.blind_params(inst, attempt - 1, self.rng), "blind(feedback too coarse)"
148
+
149
+ # ------------------------------------------------------------------ attempt
150
+ def begin_attempt(self, ainfo):
151
+ self.params, self.rule = self._params(ainfo.attempt, ainfo.history)
152
+ self.ch = _Channel()
153
+ self.thread = None
154
+ self.pending = False
155
+ self.last_report = None
156
+ self.n = 0
157
+ self.proxy = None
158
+
159
+ def _worker(self):
160
+ try:
161
+ self.info.task.execute(self.info.inst, self.params)
162
+ self.ch.req.put(("finished", None))
163
+ except _Abort:
164
+ pass
165
+ except Exception:
166
+ self.ch.req.put(("error", traceback.format_exc()))
167
+
168
+ def act(self, conv, tools):
169
+ if self.thread is None:
170
+ task = self.info.task
171
+ self.real_sk = task.sk
172
+ self.proxy = SkillsProxy(task.sk, self.ch)
173
+ task.sk = self.proxy
174
+ self.thread = threading.Thread(target=self._worker, daemon=True)
175
+ self.thread.start()
176
+ elif self.pending:
177
+ self.ch.res.put(("result", self.last_report or {}))
178
+ self.pending = False
179
+ kind, *rest = self.ch.req.get(timeout=TIMEOUT_S)
180
+ self.n += 1
181
+ if kind == "call":
182
+ name, args = rest[0], rest[1]
183
+ self.pending = True
184
+ tc = ToolCall(id=f"scripted_{self.n}", name=name, arguments=args)
185
+ text = None
186
+ if self.n == 1:
187
+ text = f"[scripted {self.policy}: rule={self.rule}, params={self.params}]"
188
+ return BackendResponse(tool_calls=[tc], text=text)
189
+ if kind == "finished":
190
+ return BackendResponse(tool_calls=[ToolCall(id=f"scripted_{self.n}", name="done",
191
+ arguments=dict(reason=f"scripted {self.policy} policy finished "
192
+ f"with params {self.params}"))])
193
+ raise RuntimeError("scripted policy crashed:\n" + str(rest[0]))
194
+
195
+ def on_tool_result(self, call, result):
196
+ self.last_report = result.report
197
+
198
+ def end_attempt(self):
199
+ if self.thread is not None:
200
+ if self.thread.is_alive():
201
+ if self.pending:
202
+ self.ch.res.put(("abort", None))
203
+ self.thread.join(timeout=30)
204
+ self.info.task.sk = self.real_sk
205
+ meta = dict(policy=self.policy, rule=self.rule, params=self.params)
206
+ if self.proxy is not None and self.proxy.untooled_hold_steps:
207
+ meta["untooled_hold_steps"] = self.proxy.untooled_hold_steps
208
+ if self.proxy is not None and self.proxy.ignored_wrap_yaw_false:
209
+ meta["ignored_wrap_yaw_false"] = self.proxy.ignored_wrap_yaw_false
210
+ return meta
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled-arm spec for l2_turntable_restore (2026-10-12).
2
+
3
+ Hidden variable: inst["q0"], the turntable's start angle (rad, + = counter-clockwise seen from above). It is the only
4
+ thing the agent has to remember: the main task forces a large turn of the disc (to bring the butter out from under the
5
+ shelf), after which nothing in the scene shows the start angle. apply_instance() places the disc at q0 and puts the
6
+ butter at disc-frame angle theta (so its world azimuth is theta + q0) on every reset, and reset_instance() records the
7
+ start angle from the simulator, so overriding "q0" alone is enough.
8
+
9
+ Geometry used below (TurntableRestore.butter_to_basket): with the butter at world azimuth az (about the disc axis)
10
+ and box yaw az + tilt, the main task turns the disc by T = wrap(PICK_AZ - tilt - az), PICK_AZ = +90 deg (open side).
11
+ Its sign flips at az = flip = -90 deg - tilt (the middle of the covered side); |T| = 180 deg - |az - flip|.
12
+
13
+ h0 -> q0 with the butter already at PICK_AZ (open side, long axis along world y): the main task needs no turn
14
+ (T ~ 0), so the scripted naive (main task, then stop) leaves the disc at its start angle and succeeds.
15
+ NB: the instruction's "under the shelf" is then not literally true (the butter is on the open half).
16
+ twin -> q0 with the butter still under the shelf but 35 deg on the OTHER side of flip: the main task turns the disc
17
+ the opposite way (|T| = 145 deg, inside the measured 136-179 deg range), so naive still fails visibly, and the
18
+ correction (turn back) has the opposite sign; the twin's start angle differs from the original's by
19
+ 35 deg + |az - flip| >= 35 deg (tolerance 15 deg), so restoring to the twin's remembered marks fails here.
20
+ reveal -> the start angle stated as the direction the yellow stripe points (seen from above), in robot-centric words
21
+ (forward = away from the robot, counter-clockwise as in the F2 feedback).
22
+ """
23
+ import numpy as np
24
+
25
+ HIDDEN_KEYS = ("q0",)
26
+
27
+ TARGET = "butter_1"
28
+ PICK_AZ = np.pi / 2 # TurntableRestore.PICK_AZ
29
+ TWIN_OFF = np.radians(35.0)
30
+ STRIPE_ANG = np.pi # disc-frame angle of the yellow stripe (l2_turntable.STRIPE_ANG)
31
+
32
+
33
+ def _wrap(a):
34
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
35
+
36
+
37
+ def _geom(inst):
38
+ th, tilt = float(inst["theta"][TARGET]), float(inst["tilt"][TARGET])
39
+ return th, tilt, -np.pi / 2 - tilt
40
+
41
+
42
+ def h0(inst):
43
+ th, tilt, _ = _geom(inst)
44
+ return {"q0": _wrap(PICK_AZ - tilt - th)}
45
+
46
+
47
+ def twin(inst):
48
+ th, tilt, flip = _geom(inst)
49
+ s = 1.0 if _wrap(th + float(inst["q0"]) - flip) >= 0 else -1.0
50
+ return {"q0": _wrap(flip - s * TWIN_OFF - th)}
51
+
52
+
53
+ def _compass(deg):
54
+ names = ("forward", "forward-left", "left", "backward-left", "backward", "backward-right", "right", "forward-right")
55
+ return names[int(np.floor(((deg % 360) + 22.5) / 45.0)) % 8]
56
+
57
+
58
+ def reveal(inst):
59
+ az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG))
60
+ side = "counter-clockwise" if az >= 0 else "clockwise"
61
+ return (f"Note: at the start, seen from above, the yellow stripe on the turntable points out from the turntable's "
62
+ f"centre {abs(az):.0f} deg {side} from straight forward (roughly {_compass(az)}); that is the angle the "
63
+ f"turntable is at now.")
64
+
65
+
66
+ def fix(inst, params):
67
+ """Ladder Fix rung (docs/20): the oracle turns the disc back to the saved start angle after the butter is out."""
68
+ az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG))
69
+ side = "counter-clockwise" if az >= 0 else "clockwise"
70
+ return (f"A way to succeed: after the butter is in the basket, turn the turntable back to its start angle before "
71
+ f"you finish. At the start, seen from above, the yellow stripe pointed {abs(az):.0f} deg {side} from "
72
+ f"straight forward (roughly {_compass(az)}). Grasp a red peg and move the gripper along the rim to turn "
73
+ f"the disc until the stripe points that way again (within 15 deg), then release the peg and finish.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l4_fit_container.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l4_fit_container (2026-10-12).
2
+
3
+ Hidden variable: inst["cap"] -- clear (unrendered) bumper caps on both ends of the phone, 0.8-0.9 cm each, so the
4
+ phone is 1.6-1.8 cm longer than it looks. The prior picks the box with the most visible room to spare ("snug"),
5
+ which is too short for the capped phone; only the "fit" box is long enough.
6
+
7
+ 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"
8
+ and "short_wide"). inst["fit"] is left as is (that box still fits).
9
+ twin Same box positions / yaws, same phone, same caps (trap still active), but the inner sizes (and kinds) of the
10
+ "fit" and "snug" boxes are swapped. In the twin the prior goes to the place where the ORIGINAL's fitting box
11
+ stands (now with snug sizes) and fails on the rim; the twin's fitting box stands where the original's snug box
12
+ stands. So the twin's lesson at the action level ("not that box, use that other box") is exactly the reverse
13
+ of the original's: following it on the original means choosing the original's failing (snug) box.
14
+ Caveat: the abstract lesson ("the phone is longer than it looks, take the box with the most length to spare")
15
+ is the same in both -- a negative cap (phone shorter than it looks) is not physically possible here. The box
16
+ sizes in the twin images differ from the original's at those two positions (they are visible).
17
+ reveal The cap length, in cm, per end and in total.
18
+ """
19
+ HIDDEN_KEYS = ("cap",)
20
+
21
+
22
+ def h0(inst):
23
+ return {"cap": 0.0}
24
+
25
+
26
+ def _idx(inst, kind):
27
+ return next(j for j, b in enumerate(inst["boxes"]) if b["kind"] == kind)
28
+
29
+
30
+ def twin(inst):
31
+ f, s = _idx(inst, "fit"), _idx(inst, "snug")
32
+ boxes = [dict(b) for b in inst["boxes"]]
33
+ for k in ("kind", "inner"):
34
+ boxes[f][k], boxes[s][k] = inst["boxes"][s][k], inst["boxes"][f][k]
35
+ perc = [list(p) for p in inst["_perc"]]
36
+ perc[f], perc[s] = list(inst["_perc"][s]), list(inst["_perc"][f])
37
+ return {"boxes": boxes, "fit": s, "fit_crossed": boxes[s]["crossed"], "_perc": perc}
38
+
39
+
40
+ def reveal(inst):
41
+ c = 100 * inst["cap"]
42
+ return (f"The phone has clear bumper caps on both of its short ends that do not show in the camera images; "
43
+ f"each cap adds about {c:.1f} cm, so the phone is about {2 * c:.1f} cm longer than it looks.")
44
+
45
+
46
+ def _where(inst, j):
47
+ """robot-frame position words of box j in the 2 x 3 grid (rows along x, columns along y)"""
48
+ xs = sorted({round(float(b["xy"][0]), 2) for b in inst["boxes"]} | {round(float(inst["phone_xy"][0]), 2)})
49
+ x, y = (float(v) for v in inst["boxes"][j]["xy"])
50
+ 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"
51
+ col = "on the robot's left" if y > 0.1 else ("on the robot's right" if y < -0.1 else "in the middle")
52
+ return f"{row}, {col}"
53
+
54
+
55
+ def fix(inst, params):
56
+ """Ladder Fix rung (docs/20): the fitting box (oracle box = inst['fit']), long side along the box's long side."""
57
+ j = int(params["box"])
58
+ return (f"A way to succeed: the phone fits only into the box {_where(inst, j)} (the one with the most length to "
59
+ f"spare; it looks tight across, but the phone's width fits). Pick the phone up, turn it so that its long "
60
+ f"side lines up with that box's long side, and lower it flat into the middle of that box before you "
61
+ f"release it.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l5_loaded_beam (2026-10-12, docs/14 sec. 6).
2
+
3
+ Hidden variable: the bar's centre of mass `com_offset` (m along the bar from its middle, + = the robot's left end),
4
+ set at reset by l5_slippery_lift.set_hidden_weight (body_ipos + inertia + envs.refit_bounds, so a changed value is
5
+ honoured). `com_total` (bar + both blocks) is derived from it in sample_instance and read by oracle_params, so it is
6
+ overridden together. Mass, friction and layout stay as sampled.
7
+
8
+ h0 : centre of mass at the middle (0): the common-sense middle grasp lifts the bar level.
9
+ twin : the same offset on the other side (-com_offset): the middle grasp still tilts the bar and spills a block, but
10
+ now towards the other end, so the right grasp point is mirrored.
11
+ 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.
12
+ """
13
+ HIDDEN_KEYS = ("com_offset", "com_total")
14
+
15
+
16
+ def h0(inst):
17
+ return dict(com_offset=0.0, com_total=0.0)
18
+
19
+
20
+ def twin(inst):
21
+ return dict(com_offset=-float(inst["com_offset"]), com_total=-float(inst["com_total"]))
22
+
23
+
24
+ def reveal(inst):
25
+ e = float(inst["com_offset"])
26
+ side = "left" if e > 0 else "right"
27
+ return (f"The bar is not uniform: a heavy weight is hidden inside it towards its {side} end (the robot's {side}). "
28
+ f"The bar weighs {1000 * inst['mass']:.0f} g and its centre of mass is {100 * abs(e):.1f} cm to the "
29
+ f"{side} of its middle.")
30
+
31
+
32
+ def fix(inst, params):
33
+ """Ladder Fix rung (docs/20): grasp at the combined centre of mass (oracle along = com_total), lift 15 cm at 0.1."""
34
+ a = float(params["along"])
35
+ side = "left" if a > 0 else "right"
36
+ return (f"A way to succeed: grasp the bar at its balance point, not at its middle. Open the gripper, turn it so "
37
+ f"the jaws close across the bar's 4 cm width, come down over the point {100 * abs(a):.1f} cm to the "
38
+ f"robot's {side} of the bar's middle (the centre of mass of the bar and the two blocks) until the "
39
+ f"fingers are at the bar's mid-height, close the gripper and lift straight up about 15 cm slowly (speed "
40
+ f"about 0.1). Held there, the bar stays level and both blocks stay on it.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l5_slide_to_target (docs/14 §6).
2
+
3
+ Hidden variable: mu, the cube-table sliding friction (apply_instance() sets it on every reset; oracle_params() bisects
4
+ the strike speed with it). The layout (cube_xy, target_dist) is kept.
5
+
6
+ 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
7
+ table, and the target tolerance is only +-1 cm, so H0 and the twin are calibrated per full5 seed with a simulated sweep
8
+ (deterministic sim, scratchpad arms/fine.py, 2026-10-12); other seeds fall back to a power-law fit of the stopping
9
+ distance at 0.30 m/s (dist ~ 0.00453 / mu^1.04 m).
10
+
11
+ h0 mu at which the 0.30 m/s strike stops the cube on the square's centre (|err| <= 0.3 cm).
12
+ twin the opposite trap: if the original cube overshoots (slippery) the twin is grippy and stops short, and vice
13
+ versa, so the correction is the other way (slow down <-> speed up). The twin's naive error is at least 2 cm
14
+ and, where the twin's oracle still succeeds, about as large as the original's (mirrored). Seeds 3000 and 3007
15
+ overshoot by 6.9 / 4.1 cm, but a grippy cube cannot be made to stop that far short and still be solvable,
16
+ so their twins stop 2.1 / 3.4 cm short.
17
+ reveal states the friction coefficient only.
18
+ """
19
+
20
+ HIDDEN_KEYS = ("mu",)
21
+
22
+ # seed: h0 mu (naive err there), twin mu (twin naive err, twin oracle speed m/s -> err). Original naive err in brackets.
23
+ _CAL = {
24
+ 3000: dict(h0=0.0749, twin=0.1060), # [orig +6.94 cm] h0 +0.26; twin -2.13, oracle 0.551 -> +0.01
25
+ 3001: dict(h0=0.0602, twin=0.0783), # [orig +2.95 cm] h0 +0.14; twin -2.73, oracle 0.450 -> 0.00
26
+ 3003: dict(h0=0.0583, twin=0.0463), # [orig -1.73 cm] h0 +0.03; twin +2.75, oracle 0.242 -> -0.13
27
+ 3004: dict(h0=0.0537, twin=0.0444), # [orig -1.66 cm] h0 -0.31; twin +2.14, oracle 0.240 -> -0.02
28
+ 3007: dict(h0=0.0532, twin=0.0984), # [orig +4.05 cm] h0 +0.15; twin -3.39, oracle 0.570 -> -0.18
29
+ }
30
+
31
+
32
+ def _h0_mu(inst):
33
+ c = _CAL.get(int(inst.get("seed", -1)))
34
+ return c["h0"] if c else (0.00453 / float(inst["target_dist"])) ** (1 / 1.04)
35
+
36
+
37
+ def h0(inst):
38
+ return {"mu": float(_h0_mu(inst))}
39
+
40
+
41
+ def twin(inst):
42
+ c = _CAL.get(int(inst.get("seed", -1)))
43
+ if c:
44
+ return {"mu": float(c["twin"])}
45
+ m0 = _h0_mu(inst) # fallback: mirror mu about the H0 value in log space, kept in a solvable range
46
+ return {"mu": float(min(max(m0 * m0 / float(inst["mu"]), 0.03), 0.10))}
47
+
48
+
49
+ def reveal(inst):
50
+ return f"The red cube's sliding friction coefficient on the table is about {float(inst['mu']):.3f}."
51
+
52
+
53
+ def fix(inst, params):
54
+ """Ladder Fix rung (docs/20): one strike at the oracle speed (bisection with the true mu), 22 cm run-up, stopping
55
+ 1.5 cm past the cube's near face -- as l5_slide.execute; move_eef speed = Skills.move_to speed."""
56
+ v = float(params["speed"])
57
+ return (f"A way to succeed: one straight strike at the right speed. Close the gripper (yaw 0), put the fingertips "
58
+ f"just above the table (grasp point about 2 cm above the tabletop) 22 cm behind the cube's centre, on the "
59
+ f"robot's side and in line with the cube and the target, then in one move_eef command move straight "
60
+ 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 "
61
+ f"centre), and lift the gripper. The cube then slides into the target zone.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l5_tablecloth_pull (docs/14 §6).
2
+
3
+ Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset,
4
+ oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled
5
+ from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu.
6
+
7
+ Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed
8
+ 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.
9
+ Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull
10
+ slower".
11
+
12
+ 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
13
+ simulated sweep; a linear fit in band_d for other seeds).
14
+ twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot
15
+ (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
16
+ command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short.
17
+ The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the
18
+ 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
19
+ 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.
20
+ reveal states the cube's friction coefficient (the only fact that differs between instances).
21
+ """
22
+
23
+ HIDDEN_KEYS = ("mu",)
24
+
25
+ # Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim).
26
+ # seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm])
27
+ _CAL = {
28
+ 3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60
29
+ 3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47
30
+ 3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78
31
+ 3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44
32
+ 3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51
33
+ }
34
+
35
+
36
+ def _h0_mu(inst):
37
+ c = _CAL.get(int(inst.get("seed", -1)))
38
+ return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"])
39
+
40
+
41
+ def h0(inst):
42
+ return {"mu": float(_h0_mu(inst))}
43
+
44
+
45
+ def twin(inst):
46
+ c = _CAL.get(int(inst.get("seed", -1)))
47
+ return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))}
48
+
49
+
50
+ def reveal(inst):
51
+ return (f"The red cube's friction coefficient (against the board and against the table) is about "
52
+ f"{float(inst['mu']):.3f}.")
53
+
54
+
55
+ def fix(inst, params):
56
+ """Ladder Fix rung (docs/20): one pull of 25 cm at the oracle speed (bisection with the true mu), as
57
+ l5_tablecloth_pull.execute; move_eef speed = Skills.move_to speed."""
58
+ v = float(params["speed"])
59
+ return (f"A way to succeed: pull at the right speed. Grasp the black handle (jaws closing across its 4 cm width), "
60
+ f"then in one move_eef command pull the board straight towards the robot by 25 cm at speed {v:.2f}; then "
61
+ f"open the gripper and lift. The cube then lands in the green band.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-4 intervention texts for lh_clear_cover (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is
2
+ not in the controlled arms of full5.
3
+
4
+ Hidden variable: inst["cover"] -- which box carries the nearly invisible clear lid (None in uncovered instances).
5
+ reveal says which box is covered and what the lid does to a released cube; not how to deal with it.
6
+ fix the oracle's edge push (lh_clear_cover.remove_cover) in move_eef words; params["z_push"] = grasp-point height of
7
+ that push in the eef_pos frame, params["push_len"] = length of the sweep (scripts/layer4_plan.py validate).
8
+ """
9
+ HIDDEN_KEYS = ("cover",)
10
+
11
+
12
+ def reveal(inst):
13
+ return (f"The {inst['cover']} box is covered by a loose, nearly invisible clear lid lying on its walls, 8 mm thick. "
14
+ f"A cube released over that box stops on the lid at rim height; it is not in the box.")
15
+
16
+
17
+ def fix(inst, params):
18
+ return (f"A way to succeed: first push the lid off the {inst['cover']} box. Close the gripper, keep yaw 0 and bring "
19
+ f"the grasp point to height {params['z_push']:.3f} (the third value of eef_pos), so that the fingertips are "
20
+ 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 "
21
+ f"command sweep {params['push_len'] * 100:.0f} cm straight along the line between the two boxes, away from "
22
+ 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 "
23
+ f"check from the side view that no cube rests at rim height.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l1_bias.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L1-A bias_place: pick up the cream cheese and put it into the bowl, with a miscalibrated arm.
2
+
3
+ Level L1 (action fine-tuning): the method (top-down pick across the cheese's short side, carry, release
4
+ above the bowl) and the scene understanding are right; only execution precision is off.
5
+
6
+ Hidden variable: a fixed calibration offset b = r (cos th, sin th, 0), r ~ U[R_MIN, R_MAX], th ~ U[0, 2 pi),
7
+ added to every commanded gripper position (`Skills(bias=b)`). The agent never sees b; positions reported
8
+ back to it must be in the commanded frame (`TrackedSkills.reported_eef_pos`), otherwise b leaks.
9
+
10
+ Robot: the gripper is a short-stroke parallel gripper (max opening GRIPPER_MAX_OPEN = 5.0 cm, e.g. a
11
+ Robotiq Hand-E; implemented by narrowing the Panda finger actuators' ctrlrange). The cream cheese is
12
+ 4.27 cm wide, so the open fingers clear it by ~3.5 mm per side.
13
+
14
+ Why the prior fails. Sent to the true cheese position, the gripper arrives b away. If the component of b
15
+ across the cheese (jaw-closing direction) exceeds ~0.7-1.0 cm (measured), a finger comes down on top of the
16
+ cheese, the hand stops ~1.5 cm too high and the jaws close above it -> missed grasp, visible in both
17
+ cameras. With the stock 8 cm Panda stroke the measured tolerance is ~2.4 cm, so most r in [2, 4] cm would
18
+ not fail; that is why the stroke is reduced. The component of b along the cheese does not matter much
19
+ (the finger pads can grip anywhere along its 8.1 cm length, and the in-hand offset cancels at the place
20
+ because the same b is added there), and the bowl is forgiving.
21
+
22
+ What has to be learned: the F2 feedback reports where the gripper closed relative to the cheese's centre
23
+ (forward/backward, left/right in the robot frame). That offset is b itself, so after one failure b can be
24
+ estimated and subtracted from every commanded position (pick and place alike).
25
+ """
26
+ import numpy as np
27
+
28
+ from .. import envs
29
+ from ..bddl import write_bddl
30
+ from ..skills import Skills
31
+ from ..task_base import LFFTask, register_task
32
+
33
+ CHEESE, BOWL = "cream_cheese_1", "akita_black_bowl_1"
34
+ JUICE = "orange_juice_1"
35
+ DISTRACTORS = ("butter_1", "chocolate_pudding_1", JUICE)
36
+ ALL = (CHEESE, BOWL) + DISTRACTORS
37
+ NAMES = {CHEESE: "cream cheese", BOWL: "bowl", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding",
38
+ JUICE: "orange juice carton"}
39
+ # descriptive names for the indirect variant (same wording as l2_knock_restore where objects overlap)
40
+ DESCR = {CHEESE: "blue box", BOWL: "grey bowl", "butter_1": "small orange box", "chocolate_pudding_1": "brown box",
41
+ JUICE: "tall juice carton"}
42
+ # Cream cheese collision box: 8.12 x 4.27 x 1.79 cm, lying flat, long side along its x axis.
43
+ # Realistic masses (LIBERO's are 5-10 g): a 6 g cheese is shoved aside by a finger landing on its edge.
44
+ MASS = {CHEESE: 0.227, "butter_1": 0.250, "chocolate_pudding_1": 0.200, BOWL: 0.300}
45
+
46
+ # finger tips (0.97 cm below the gripper site) just clear the table; the pads cover 0.6-1.8 cm of the cheese
47
+ Z_GRASP = envs.TABLE_Z + 0.0105
48
+ Z_CARRY = envs.TABLE_Z + 0.20 # clears the 13 cm juice carton with the cheese hanging below the fingers
49
+ BOWL_RIM = 0.0505 # rim height of the akita bowl above its lowest point
50
+ BOWL_R_IN = 0.046 # inner radius of the bowl at the rim
51
+ RELEASE_ABOVE_RIM = 0.012 # gripper site above the rim at release (finger pads clear the rim)
52
+
53
+ R_MIN, R_MAX = 0.025, 0.040 # bias magnitude range (m)
54
+ GRIPPER_MAX_OPEN = 0.050 # short-stroke gripper: max finger gap (m); the cheese is 4.27 cm wide
55
+ CHEESE_YAW_MAX = np.deg2rad(10)
56
+
57
+
58
+ HOME_XY = np.array([-0.21, 0.0]) # gripper xy at reset
59
+
60
+
61
+ def _seg_dist(p, a, b):
62
+ """distance from point p to segment ab (2-D)"""
63
+ ab = b - a
64
+ u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
65
+ return float(np.linalg.norm(a + u * ab - p))
66
+
67
+
68
+ def _q(axis, a):
69
+ h = a / 2
70
+ return {"y": np.array([np.cos(h), 0, np.sin(h), 0]), "z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
71
+
72
+
73
+ def _qmul(a, b):
74
+ """wxyz quaternion product a*b"""
75
+ w1, x1, y1, z1 = a
76
+ w2, x2, y2, z2 = b
77
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
78
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
79
+
80
+
81
+ def set_gripper_stroke(env, max_open):
82
+ """Limit the jaw opening: each finger's position actuator gets the range [0, max_open/2] (robosuite maps
83
+ the open/close command onto the actuator ctrlrange, so "open" now means max_open). The pad faces sit
84
+ 0.5 mm inside the joint position, hence the small correction."""
85
+ m = env.sim.model
86
+ half = max_open / 2 + 0.0005
87
+ a1, a2 = [m.actuator_name2id(a) for a in env.robots[0].gripper.actuators]
88
+ m.actuator_ctrlrange[a1] = [0.0, half]
89
+ m.actuator_ctrlrange[a2] = [-half, 0.0]
90
+
91
+
92
+ def dir_words(dx, dy):
93
+ """Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
94
+ parts = []
95
+ if abs(dy) >= 0.0005:
96
+ parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
97
+ if abs(dx) >= 0.0005:
98
+ parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
99
+ return " and ".join(parts) if parts else "exactly at the position"
100
+
101
+
102
+ class TrackedSkills(Skills):
103
+ """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent):
104
+ where the gripper was and what the fingers touched when the jaws closed, and where the cheese was when
105
+ the jaws opened while holding it."""
106
+
107
+ def __init__(self, env, bias=None, recorder=None):
108
+ super().__init__(env, bias=bias, recorder=recorder)
109
+ self.events = []
110
+ self.cheese_z0 = float(envs.obj_pos(env, CHEESE)[2])
111
+ self.cheese_zmax = self.cheese_z0
112
+ m = env.sim.model
113
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
114
+ self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in ALL}
115
+ # where the cheese was before the gripper last touched it (the reference for the grasp offset, so that
116
+ # a finger shoving the cheese aside on the way down does not corrupt the measurement)
117
+ self.cheese_ref = envs.obj_pos(env, CHEESE)
118
+
119
+ def reported_eef_pos(self):
120
+ """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything
121
+ shown to the agent must use this, never eef_pos(), which is the true position and reveals b."""
122
+ return self.eef_pos() - self.bias
123
+
124
+ def move_to(self, target, *args, **kwargs):
125
+ rep = super().move_to(target, *args, **kwargs)
126
+ rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist() # do not leak b through the report
127
+ return rep
128
+
129
+ def touching(self):
130
+ """Objects the gripper is in contact with right now."""
131
+ return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
132
+
133
+ def _act(self, dpos, drot, grip):
134
+ super()._act(dpos, drot, grip)
135
+ self.cheese_zmax = max(self.cheese_zmax, float(envs.obj_pos(self.env, CHEESE)[2]))
136
+ if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[CHEESE]):
137
+ self.cheese_ref = envs.obj_pos(self.env, CHEESE)
138
+
139
+ def set_gripper(self, close, steps=15):
140
+ if close and self.grip < 0:
141
+ self.events.append(dict(kind="close", eef=self.eef_pos().tolist(),
142
+ cheese=envs.obj_pos(self.env, CHEESE).tolist(),
143
+ cheese_ref=np.asarray(self.cheese_ref).tolist(), touching=self.touching(),
144
+ cheese_top=envs.obj_max_z(self.env, CHEESE), step=self.n_steps))
145
+ elif not close and self.grip > 0 and self.holding(CHEESE):
146
+ self.events.append(dict(kind="release", eef=self.eef_pos().tolist(),
147
+ cheese=envs.obj_pos(self.env, CHEESE).tolist(),
148
+ bowl=envs.obj_pos(self.env, BOWL).tolist(), step=self.n_steps))
149
+ return super().set_gripper(close, steps)
150
+
151
+
152
+ @register_task
153
+ class BiasPlace(LFFTask):
154
+ name = "l1_bias_place"
155
+ level = "L1"
156
+ category = "system_identification"
157
+ capabilities = ("Perceive", "Utilize")
158
+ protocol = "cross"
159
+ # LIBERO calls the bowl "akita black bowl", but under our renderer it looks silver-grey with a gold rim, so
160
+ # the colour is not used in the direct instruction (there is only one bowl).
161
+ instruction = "Pick up the cream cheese and put it into the bowl."
162
+ instruction_indirect = "Pick up the flat blue box with the white oval label and put it into the round grey bowl."
163
+ pick_lift_min = 0.03 # cheese counted as picked up if it rose this much
164
+
165
+ # ------------------------------------------------------------ scene
166
+ def make_bddl(self):
167
+ # regions are only used by LIBERO's reset-time sampler (the layout is overridden in apply_instance)
168
+ objs = [(CHEESE, "cream_cheese", "cheese_region", (-0.16, -0.22, -0.14, -0.20)),
169
+ (BOWL, "akita_black_bowl", "bowl_region", (-0.01, 0.15, 0.01, 0.17)),
170
+ ("butter_1", "butter", "butter_region", (-0.16, 0.10, -0.14, 0.12)),
171
+ ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.04, -0.17, 0.06, -0.15)),
172
+ (JUICE, "orange_juice", "juice_region", (-0.15, -0.03, -0.13, -0.01))]
173
+ return write_bddl(self.name, self.instruction, objs)
174
+
175
+ def __init__(self, cam_res=None):
176
+ super().__init__(cam_res)
177
+ # LIBERO's own upright orientation of every object, read off the reset state
178
+ self._base_quat = {n: envs.obj_quat(self.env, n) for n in ALL}
179
+
180
+ def _place(self, name, xy, yaw):
181
+ q = _qmul(_q("z", yaw), self._base_quat[name])
182
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], envs.TABLE_Z + 0.3], quat_wxyz=q)
183
+ self.env.sim.forward()
184
+ qa, _ = envs.free_joint_addr(self.env, name)
185
+ self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + 0.0005)
186
+ self.env.sim.forward()
187
+
188
+ def sample_instance(self, seed):
189
+ rng = np.random.default_rng(seed)
190
+ while True:
191
+ c = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)])
192
+ bowl = np.array([rng.uniform(-0.15, 0.08), rng.uniform(-0.24, 0.24)])
193
+ if np.linalg.norm(bowl - c) < 0.20:
194
+ continue
195
+ placed = [c, bowl]
196
+ dis = {}
197
+ for name in DISTRACTORS:
198
+ for _ in range(300):
199
+ p = np.array([rng.uniform(-0.22, 0.10), rng.uniform(-0.27, 0.27)])
200
+ if any(np.linalg.norm(p - o) < (0.13 if k < 2 else 0.11) for k, o in enumerate(placed)):
201
+ continue
202
+ if name == JUICE:
203
+ # the 13 cm carton is taller than the hand when it grasps / releases: the Panda hand spans
204
+ # +-10.5 cm across the jaws, so keep the carton >= 17 cm from the cheese and the bowl;
205
+ # it must also not hide them from the front camera, and must stay >= 10 cm off the
206
+ # straight paths home->cheese, home->bowl and cheese->bowl
207
+ if np.linalg.norm(p - c) < 0.17 or np.linalg.norm(p - bowl) < 0.17:
208
+ continue
209
+ if any(p[0] > t[0] - 0.03 and abs(p[1] - t[1]) < 0.14 for t in (c, bowl)):
210
+ continue
211
+ if any(_seg_dist(p, a, b) < 0.10 for a, b in ((c, bowl), (HOME_XY, c), (HOME_XY, bowl))):
212
+ continue
213
+ break
214
+ else:
215
+ break
216
+ placed.append(p)
217
+ dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
218
+ if len(dis) == len(DISTRACTORS):
219
+ break
220
+ psi = float(rng.uniform(-CHEESE_YAW_MAX, CHEESE_YAW_MAX))
221
+ n = np.array([-np.sin(psi), np.cos(psi)]) # jaw-closing direction for a grasp across the cheese
222
+ l = np.array([np.cos(psi), np.sin(psi)])
223
+ r = rng.uniform(R_MIN, R_MAX)
224
+ th = rng.uniform(0, 2 * np.pi)
225
+ b = np.array([r * np.cos(th), r * np.sin(th)])
226
+ return dict(seed=int(seed), cheese_xy=c.round(5).tolist(), cheese_yaw=psi, bowl_xy=bowl.round(5).tolist(),
227
+ distractors=dis, bias=[float(b[0]), float(b[1]), 0.0], bias_r=float(r), bias_theta=float(th),
228
+ bias_across=float(b @ n), bias_along=float(b @ l))
229
+
230
+ def apply_instance(self, inst):
231
+ set_gripper_stroke(self.env, GRIPPER_MAX_OPEN)
232
+ for name, mass in MASS.items():
233
+ envs.scale_mass(self.env, name, mass)
234
+ self._place(CHEESE, inst["cheese_xy"], inst["cheese_yaw"])
235
+ self._place(BOWL, inst["bowl_xy"], 0.0)
236
+ for name, v in inst["distractors"].items():
237
+ self._place(name, v["xy"], v["yaw"])
238
+
239
+ def skill_bias(self, inst):
240
+ return np.array(inst["bias"], float)
241
+
242
+ def reset_instance(self, inst, recorder=None):
243
+ self.env.reset()
244
+ self.apply_instance(inst)
245
+ self.env.sim.forward()
246
+ envs.settle(self.env, 10)
247
+ self.sk = TrackedSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
248
+ self.start_pos = {n: envs.obj_pos(self.env, n) for n in ALL}
249
+ return self.sk
250
+
251
+ # ------------------------------------------------------------ outcome
252
+ def in_bowl(self):
253
+ k = envs.obj_pos(self.env, BOWL)
254
+ c = envs.obj_pos(self.env, CHEESE)
255
+ base = envs.obj_min_z(self.env, BOWL)
256
+ return bool(np.linalg.norm(c[:2] - k[:2]) < BOWL_R_IN and c[2] < base + BOWL_RIM
257
+ and envs.obj_upright_cos(self.env, BOWL) > 0.9 and base < envs.TABLE_Z + 0.01)
258
+
259
+ def outcome(self, inst):
260
+ envs.settle(self.env, 40)
261
+ sk = self.sk
262
+ k = envs.obj_pos(self.env, BOWL)
263
+ c = envs.obj_pos(self.env, CHEESE)
264
+ held = sk.holding(CHEESE)
265
+ success = bool(self.in_bowl() and not held)
266
+ picked = sk.cheese_zmax > sk.cheese_z0 + self.pick_lift_min
267
+ closes = [e for e in sk.events if e["kind"] == "close"]
268
+ last_close = closes[-1] if closes else None
269
+ releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
270
+ end_off = c[:2] - k[:2]
271
+ moved = {n: float(np.linalg.norm(envs.obj_pos(self.env, n)[:2] - self.start_pos[n][:2]))
272
+ for n in DISTRACTORS}
273
+ out = dict(success=success, picked=bool(picked), held_at_end=bool(held),
274
+ cheese_end=c.round(4).tolist(), bowl_end=k.round(4).tolist(), end_offset=end_off.round(4).tolist(),
275
+ grasp_offset=None, release_offset=None, touched_at_close=None,
276
+ distractors_moved_cm={n: round(100 * v, 1) for n, v in moved.items()})
277
+ grasp_txt = ""
278
+ if last_close is not None:
279
+ go = np.array(last_close["eef"][:2]) - np.array(last_close["cheese_ref"][:2])
280
+ out["grasp_offset"] = go.round(4).tolist()
281
+ out["touched_at_close"] = last_close["touching"]
282
+ out["cheese_pushed_cm"] = round(100 * float(np.linalg.norm(
283
+ np.array(last_close["cheese"][:2]) - np.array(last_close["cheese_ref"][:2]))), 1)
284
+ grasp_txt = (f"The gripper closed {dir_words(*go)} of the centre of the cream cheese (measured where "
285
+ f"the cheese was before the fingers touched it)")
286
+ if releases:
287
+ r = releases[-1]
288
+ out["release_offset"] = (np.array(r["cheese"][:2]) - np.array(r["bowl"][:2])).round(4).tolist()
289
+ if success:
290
+ out["failure"] = None
291
+ detail = "The cream cheese is in the bowl."
292
+ if grasp_txt:
293
+ detail += f" {grasp_txt}."
294
+ elif not picked:
295
+ out["failure"] = "missed_grasp"
296
+ if last_close is None:
297
+ detail = "The gripper never closed; the cream cheese was not picked up."
298
+ else:
299
+ on = [NAMES[n] for n in last_close["touching"] if n != CHEESE]
300
+ why = ""
301
+ if on:
302
+ why = (f" A finger landed on top of the {' and the '.join(on)} instead of going down beside the "
303
+ f"cheese, so the jaws closed above the cheese.")
304
+ elif CHEESE in last_close["touching"] and not sk.holding(CHEESE):
305
+ why = " A finger came down on top of the cream cheese instead of beside it."
306
+ elif not last_close["touching"] and last_close.get("cheese_top") is not None:
307
+ above = last_close["eef"][2] - envs.FINGERTIP_BELOW_SITE - last_close["cheese_top"]
308
+ if above > 0.002: # closed in the air, entirely above the cheese
309
+ why = (f" The fingers closed in the air without touching anything: the fingertips were "
310
+ f"{100 * above:.1f} cm above the top of the cream cheese.")
311
+ detail = f"{grasp_txt} and did not pick it up.{why} The cream cheese is still on the table."
312
+ elif held:
313
+ out["failure"] = "not_released"
314
+ detail = f"{grasp_txt} and picked it up, but the cream cheese is still in the gripper."
315
+ elif releases:
316
+ out["failure"] = "missed_place"
317
+ detail = (f"{grasp_txt} and picked it up. When the gripper opened, the cream cheese was "
318
+ f"{dir_words(*out['release_offset'])} of the bowl's centre; it did not end up in the bowl "
319
+ f"(it is now {dir_words(*end_off)} of the bowl's centre).")
320
+ else:
321
+ out["failure"] = "dropped"
322
+ detail = (f"{grasp_txt} and picked it up, but it slipped out of the gripper before it was released; "
323
+ f"it is now {dir_words(*end_off)} of the bowl's centre.")
324
+ out["detail"] = detail
325
+ ind = detail
326
+ for k in (JUICE, "chocolate_pudding_1", "butter_1", CHEESE, BOWL): # longest names first
327
+ ind = ind.replace(NAMES[k], DESCR[k])
328
+ out["detail_indirect"] = ind
329
+ return out
330
+
331
+ def feedback(self, inst, out, level="F2", indirect=False):
332
+ """F0: nothing, F1: success flag, F2: measured offsets. `indirect` uses descriptive object names."""
333
+ if indirect and level == "F2":
334
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
335
+ return super().feedback(inst, out, level)
336
+
337
+ # ------------------------------------------------------------ scripted execution (cross protocol)
338
+ def execute(self, inst, params):
339
+ """Top-down pick across the cheese's short side, carry, release above the bowl.
340
+ params['offset'] (xy) is the policy's own correction, added to every commanded position."""
341
+ sk = self.sk
342
+ off = np.array(params.get("offset", [0.0, 0.0]), float)
343
+ c = envs.obj_pos(self.env, CHEESE) # perfect perception of the current scene
344
+ yaw = self.grasp_yaw()
345
+ k = envs.obj_pos(self.env, BOWL)
346
+ z_rel = envs.obj_min_z(self.env, BOWL) + BOWL_RIM + RELEASE_ABOVE_RIM
347
+ g, p = c[:2] + off, k[:2] + off
348
+ sk.set_gripper(False, steps=8)
349
+ sk.move_to([g[0], g[1], Z_CARRY], yaw=yaw) # approach from above, clear of the 13 cm carton
350
+ sk.move_to([g[0], g[1], Z_GRASP + 0.08], tol=0.002)
351
+ sk.move_to([g[0], g[1], Z_GRASP], tol=0.003, max_steps=80)
352
+ sk.set_gripper(True, steps=15)
353
+ sk.move_to([g[0], g[1], Z_CARRY], speed=0.3)
354
+ if not sk.holding(CHEESE): # missed: a real controller sees the jaws closed on nothing and stops
355
+ return
356
+ sk.move_to([p[0], p[1], Z_CARRY], tol=0.003)
357
+ sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100)
358
+ sk.set_gripper(False, steps=12)
359
+ sk.move_to([p[0], p[1], Z_CARRY], speed=0.3)
360
+
361
+ def grasp_yaw(self):
362
+ """Gripper yaw that closes the jaws across the cheese's short side (yaw 0 closes along world y)."""
363
+ xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, CHEESE)].reshape(3, 3)
364
+ a = np.arctan2(xmat[1, 0], xmat[0, 0]) # direction of the cheese's long (x) axis
365
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
366
+
367
+ def default_params(self, inst):
368
+ return dict(offset=[0.0, 0.0])
369
+
370
+ def oracle_params(self, inst):
371
+ return dict(offset=(-np.array(inst["bias"][:2])).tolist())
372
+
373
+ def adapt_params(self, inst, history):
374
+ """Scripted F2 learner: the reported grasp offset (where the gripper closed relative to the cheese's
375
+ centre) measures the calibration offset; accumulate it into the correction subtracted from every
376
+ commanded position. If the gripper never closed, fall back to the release offset."""
377
+ last = history[-1]
378
+ off = np.array(last["params"]["offset"], float)
379
+ o = last["outcome"]
380
+ if o.get("grasp_offset") is not None:
381
+ off = off - np.array(o["grasp_offset"])
382
+ elif o.get("release_offset") is not None:
383
+ off = off - np.array(o["release_offset"])
384
+ return dict(offset=off.round(4).tolist())
385
+
386
+ blind_sigma = 0.005
387
+
388
+ def blind_params(self, inst, attempt, rng):
389
+ """Retry the same plan with a small random perturbation of the targets; no use of history."""
390
+ return dict(offset=rng.normal(0.0, self.blind_sigma, 2).round(4).tolist())
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l3_tool.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L3-C under_table_tool: a cube sits under a low glass side table; put it into the bin (tool use).
2
+
3
+ v2 (2026-10-08, user review of cla2): in v1 the hidden information was "the hand does not fit under the glass top".
4
+ Every Sonnet run (4/4) saw the T-shaped stick lying next to the low table and used it straight away, i.e. the task
5
+ was solved by reasoning before acting and nothing had to be learned from a failure. v2 keeps the scene and moves the
6
+ hidden information to something no image shows:
7
+
8
+ Hidden: the side of the low table AWAY from the stick is closed by a clear acrylic panel (between the two legs,
9
+ tabletop to glass top; collision only, nothing is rendered). The bin stands on that side, beyond the panel. The other
10
+ three sides are open.
11
+
12
+ Why the prior fails: the stick lies on one side with its head pointing at the low table, and the bin is on the
13
+ opposite side, so the obvious plan is "slide the stick in and push the cube straight across, out towards the bin".
14
+ The cube then stops against the invisible panel, still completely under the glass top (the hand cannot reach it
15
+ there: the glass is 7 cm above the tabletop). Pushing harder or again from the same side fails the same way.
16
+
17
+ What must be learned from the failure (F1: from the images -- the cube stopped at the edge and did not come out):
18
+ something blocks that side -> change the push: put the stick down behind the low table (the robot's side) pointing
19
+ forward, push the cube out of the FRONT side (away from the robot), then grasp it and carry it to the bin.
20
+
21
+ Layout (randomised per instance): position of the low table, cube position under it (+-1 cm around the centre),
22
+ the stick lying beside the low table (left or right) with its head pointing at it (+-10 deg), the panel and the bin
23
+ on the other side.
24
+
25
+ Protocol: cross (reset to the same instance before every attempt), k = 5. v1 is kept in l3_tool.py.bak-20261008-pane.
26
+ """
27
+ import numpy as np
28
+
29
+ from .. import envs
30
+ from ..bddl import write_bddl
31
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated
32
+ from ..skills import DT, _rot_err
33
+ from ..task_base import LFFTask, register_task
34
+
35
+ CUBE_HALF = 0.02
36
+ TOP_HALF = (0.06, 0.06, 0.005) # glass top 12 x 12 cm, 1 cm thick
37
+ TOP_UNDER = 0.07 # underside of the glass top above the tabletop
38
+ LEG_HALF = 0.008
39
+ HANDLE_HALF = (0.12, 0.008, 0.01) # stick handle 24 x 1.6 x 2 cm, along local x
40
+ HEAD_HALF = (0.008, 0.025, 0.01) # crossbar 1.6 x 5 x 2 cm at the +x end
41
+ BIN_IN = (0.06, 0.06)
42
+ BIN_WALL_H = 0.05
43
+ GRIP_END = 0.035 # scripted grasp point: this far from the free end of the handle
44
+ GRIP_FRONT = 0.07 # v2 front push: grasp this far from the free end (keeps the hand clear of the glass edge)
45
+ Z_STICK = envs.TABLE_Z + 0.0125 # site height when grasping / sliding the stick (pads 0.75-2.4 cm above the table)
46
+ TIP_BELOW_SITE = 0.0095
47
+ # clear acrylic panel between the two legs of one y side, tabletop to glass underside (collision only, invisible)
48
+ PANE_HALF = (TOP_HALF[0] - 2 * LEG_HALF, 0.002, TOP_UNDER / 2)
49
+ PANE_Y = TOP_HALF[1] - LEG_HALF # in the plane of the leg centres
50
+ STICK_COM = 0.0221 # the stick's centre of mass is this far from the handle centre, towards the head
51
+ BIN_GAP = (0.04, 0.06) # tabletop gap between the low table's far side and the bin's outer wall
52
+
53
+
54
+ def low_table_xml(model_name):
55
+ glass, leg = (0.70, 0.85, 0.95, 0.30), (0.35, 0.25, 0.18, 1.0)
56
+ z_top = TOP_UNDER + TOP_HALF[2]
57
+ parts = [((0, 0, z_top), TOP_HALF, glass)]
58
+ for sx in (-1, 1):
59
+ for sy in (-1, 1):
60
+ parts.append(((sx * (TOP_HALF[0] - LEG_HALF), sy * (TOP_HALF[1] - LEG_HALF), TOP_UNDER / 2),
61
+ (LEG_HALF, LEG_HALF, TOP_UNDER / 2), leg))
62
+ g = []
63
+ for k, (p, s, c) in enumerate(parts):
64
+ g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
65
+ f'density="800" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
66
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
67
+ f'contype="0" group="1" />')
68
+ # acrylic panels on both y sides; apply_instance turns the collision of the one next to the stick off.
69
+ # Fully transparent (rgba alpha 0) and no visual twin: nothing is rendered.
70
+ for k, sy in enumerate((1, -1)):
71
+ g.append(f' <geom name="{model_name}_pane{k}" type="box" pos="{_fmt((0, sy * PANE_Y, PANE_HALF[2]))}" '
72
+ f'size="{_fmt(PANE_HALF)}" rgba="1 1 1 0" density="800" friction="0.6 0.005 0.0001" {_SOLID} '
73
+ f'group="0" />')
74
+ # origin at the tabletop (z = 0 is the bottom of the legs)
75
+ return _wrap(model_name, "\n".join(g), 0.0, float(np.hypot(TOP_HALF[0], TOP_HALF[1])))
76
+
77
+
78
+ def stick_xml(model_name):
79
+ c = (0.80, 0.62, 0.30, 1.0)
80
+ parts = [((0, 0, 0), HANDLE_HALF), ((HANDLE_HALF[0] + HEAD_HALF[0], 0, 0), HEAD_HALF)]
81
+ g = []
82
+ for k, (p, s) in enumerate(parts):
83
+ g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
84
+ f'density="600" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
85
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
86
+ f'contype="0" group="1" />')
87
+ return _wrap(model_name, "\n".join(g), HANDLE_HALF[2], HANDLE_HALF[0] + 2 * HEAD_HALF[0])
88
+
89
+
90
+ def _yaw_of(quat_wxyz):
91
+ w, x, y, z = quat_wxyz
92
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
93
+
94
+
95
+ @register_task
96
+ class UnderTableTool(LFFTask):
97
+ name = "l3_under_table_tool"
98
+ level = "L3"
99
+ category = "strategy_switching"
100
+ capabilities = ("Perceive", "Reason", "Plan")
101
+ protocol = "cross"
102
+ instruction = "Put the red cube into the gray bin."
103
+ instruction_indirect = "Put the small red block that is under the low glass table into the gray container."
104
+
105
+ def __init__(self, cam_res=None):
106
+ super().__init__(cam_res)
107
+ self._mon = None
108
+ self.inst = None
109
+ orig_step = self.env.step
110
+
111
+ def step(action):
112
+ ret = orig_step(action)
113
+ if self._mon is not None:
114
+ self._monitor_step()
115
+ return ret
116
+
117
+ self.env.step = step
118
+
119
+ # ------------------------------------------------------------ scene
120
+ def make_bddl(self):
121
+ cube = register_generated("LffBenchCube", box_xml("lff_bench_cube", (CUBE_HALF,) * 3, (0.85, 0.12, 0.12, 1.0),
122
+ density=800))
123
+ stick = register_generated("LffBenchStick", stick_xml("lff_bench_stick"))
124
+ table = register_generated("LffLowGlassTable", low_table_xml("lff_low_glass_table"), free=False)
125
+ tray = register_generated("LffBenchBin", bin_xml("lff_bench_bin", BIN_IN, BIN_WALL_H), free=False)
126
+ objs = [("cube_1", cube, "cube_region", (-0.21, -0.26, -0.19, -0.24)),
127
+ ("stick_1", stick, "stick_region", (-0.01, 0.24, 0.01, 0.26))]
128
+ fx = [("lowtable_1", table, "lowtable_region", (0.19, -0.01, 0.21, 0.01)),
129
+ ("bin_1", tray, "bin_region", (0.19, 0.29, 0.21, 0.31))]
130
+ return write_bddl(self.name, self.instruction, objs, fx)
131
+
132
+ def _fixture(self, name):
133
+ if not hasattr(self, "_fx"):
134
+ self._fx = {}
135
+ if name not in self._fx:
136
+ m = self.env.sim.model
137
+ bid = m.body_name2id(self.env.fixtures_dict[name].root_body)
138
+
139
+ def under(b):
140
+ while b > 0:
141
+ if b == bid:
142
+ return True
143
+ b = m.body_parentid[b]
144
+ return False
145
+
146
+ self._fx[name] = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])])
147
+ return self._fx[name]
148
+
149
+ def _panes(self):
150
+ """[(geom id, +1 / -1 = which y side of the low table)] of the two acrylic panel geoms"""
151
+ if not hasattr(self, "_pane_ids"):
152
+ m = self.env.sim.model
153
+ self._pane_ids = [(g, int(np.sign(m.geom_pos[g][1]))) for g in self._fixture("lowtable_1")[1]
154
+ if np.allclose(m.geom_size[g], PANE_HALF, atol=1e-6)]
155
+ assert len(self._pane_ids) == 2, self._pane_ids
156
+ return self._pane_ids
157
+
158
+ def sample_instance(self, seed):
159
+ rng = np.random.default_rng(seed)
160
+ side = int(rng.choice([-1, 1])) # the stick lies on the left (+1) or right (-1) of the low table
161
+ # v2: 4 cm further from the robot than v1 (-0.16..-0.10), so that a stick pushed forward from behind the
162
+ # low table is within reach (gripper about 25 cm in front of the robot base at the start of that push)
163
+ t_xy = np.array([rng.uniform(-0.12, -0.06), -side * rng.uniform(0.04, 0.07)])
164
+ cube_xy = t_xy + rng.uniform(-0.01, 0.01, 2)
165
+ # the stick lies beside the low table, its head pointing roughly at it (+-10 deg), 2.5-4.5 cm from its edge
166
+ yaw = -side * np.pi / 2 + float(rng.uniform(-np.radians(10), np.radians(10)))
167
+ d = np.array([np.cos(yaw), np.sin(yaw)])
168
+ head_front = np.array([cube_xy[0] + rng.uniform(-0.01, 0.01), t_xy[1] + side * (TOP_HALF[1] + rng.uniform(0.025, 0.045))])
169
+ stick_xy = head_front - d * (HANDLE_HALF[0] + 2 * HEAD_HALF[0])
170
+ # v2: the bin stands on the far side (the panel's side), so pushing the cube straight across looks like the
171
+ # way to the bin
172
+ gap = rng.uniform(*BIN_GAP)
173
+ bin_xy = np.array([t_xy[0] + rng.uniform(-0.02, 0.02),
174
+ t_xy[1] - side * (TOP_HALF[1] + gap + BIN_IN[1] + 0.006)])
175
+ return dict(seed=int(seed), table_xy=t_xy.tolist(), cube_xy=cube_xy.tolist(), side=side, pane_side=-side,
176
+ stick_xy=stick_xy.tolist(), stick_yaw=float(yaw), bin_xy=bin_xy.tolist())
177
+
178
+ def apply_instance(self, inst):
179
+ self.inst = inst
180
+ m = self.env.sim.model
181
+ bid, _ = self._fixture("lowtable_1")
182
+ m.body_pos[bid] = [inst["table_xy"][0], inst["table_xy"][1], envs.TABLE_Z]
183
+ m.body_quat[bid] = [1, 0, 0, 0]
184
+ for g, sy in self._panes(): # only the panel on the far side (away from the stick) collides
185
+ on = sy == inst.get("pane_side", -inst["side"])
186
+ m.geom_contype[g] = 1 if on else 0
187
+ m.geom_conaffinity[g] = 1 if on else 0
188
+ bbid, _ = self._fixture("bin_1")
189
+ m.body_pos[bbid] = [inst["bin_xy"][0], inst["bin_xy"][1], envs.TABLE_Z + (BIN_WALL_H + 0.006) / 2]
190
+ m.body_quat[bbid] = [1, 0, 0, 0]
191
+ cx, cy = inst["cube_xy"]
192
+ envs.set_obj_pose(self.env, "cube_1", [cx, cy, envs.TABLE_Z + CUBE_HALF + 0.0005])
193
+ sx, sy = inst["stick_xy"]
194
+ envs.set_obj_pose(self.env, "stick_1", [sx, sy, envs.TABLE_Z + HANDLE_HALF[2] + 0.0005], yaw=inst["stick_yaw"])
195
+
196
+ def reset_instance(self, inst, recorder=None):
197
+ self._mon = None
198
+ sk = super().reset_instance(inst, recorder=recorder)
199
+ self._start_monitor()
200
+ return sk
201
+
202
+ # ------------------------------------------------------------ state
203
+ def stick_pose(self):
204
+ d = self.env.sim.data
205
+ bid = envs.body_id(self.env, "stick_1")
206
+ return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
207
+
208
+ def observe(self):
209
+ p, R = self.stick_pose()
210
+ ax = R[:2, 0] / max(np.linalg.norm(R[:2, 0]), 1e-9)
211
+ return dict(cube=envs.obj_pos(self.env, "cube_1"), table_xy=np.array(self.inst["table_xy"]),
212
+ bin_xy=np.array(self.inst["bin_xy"]), stick_xy=p[:2], stick_dir=ax,
213
+ free_end=p[:2] - ax * HANDLE_HALF[0], head=p[:2] + ax * (HANDLE_HALF[0] + HEAD_HALF[0]))
214
+
215
+ def under_table(self, xy=None, margin=0.0):
216
+ """is the cube's footprint (any part) under the glass top?"""
217
+ xy = envs.obj_pos(self.env, "cube_1")[:2] if xy is None else np.asarray(xy)
218
+ rel = np.abs(xy - np.array(self.inst["table_xy"]))
219
+ return bool((rel < np.array(TOP_HALF[:2]) + CUBE_HALF + margin).all())
220
+
221
+ def outside_dist(self):
222
+ """how far the cube's footprint is outside the glass top (m, < 0: still partly under it)"""
223
+ rel = np.abs(envs.obj_pos(self.env, "cube_1")[:2] - np.array(self.inst["table_xy"]))
224
+ return float(max(rel - np.array(TOP_HALF[:2]) - CUBE_HALF))
225
+
226
+ def in_bin(self):
227
+ p = envs.obj_pos(self.env, "cube_1")
228
+ rel = np.abs(p[:2] - np.array(self.inst["bin_xy"]))
229
+ return bool(p[2] < envs.TABLE_Z + BIN_WALL_H and (rel < np.array(BIN_IN)).all())
230
+
231
+ # ------------------------------------------------------------ contacts / monitor
232
+ def _groups(self):
233
+ if not hasattr(self, "_gg"):
234
+ m = self.env.sim.model
235
+ robot = set(envs.robot_geom_ids(self.env))
236
+ tbl = self._fixture("lowtable_1")[1]
237
+ top = {g for g in tbl if m.geom_contype[g] and abs(m.geom_size[g, 0] - TOP_HALF[0]) < 1e-6}
238
+ self._gg = (robot, set(tbl), top, set(envs.obj_geom_ids(self.env, "stick_1")),
239
+ set(envs.obj_geom_ids(self.env, "cube_1")))
240
+ return self._gg
241
+
242
+ def _robot_contacts(self):
243
+ """labels of what the robot touches: 'glass_top', 'pane', 'table_leg', 'stick', 'cube'"""
244
+ robot, tbl, top, stick, cube = self._groups()
245
+ panes = {g for g, _ in self._panes()}
246
+ d = self.env.sim.data
247
+ out = set()
248
+ for i in range(d.ncon):
249
+ c = d.contact[i]
250
+ if c.geom1 in robot:
251
+ o = c.geom2
252
+ elif c.geom2 in robot:
253
+ o = c.geom1
254
+ else:
255
+ continue
256
+ if o in top:
257
+ out.add("glass_top")
258
+ elif o in panes:
259
+ out.add("pane")
260
+ elif o in tbl:
261
+ out.add("table_leg")
262
+ elif o in stick:
263
+ out.add("stick")
264
+ elif o in cube:
265
+ out.add("cube")
266
+ return out
267
+
268
+ def _start_monitor(self):
269
+ c = envs.obj_pos(self.env, "cube_1")
270
+ self._mon = dict(start=c.copy(), top_hit=None, stick_held=False, stick_touched_cube=False, max_cube_dz=0.0,
271
+ cube_out=not self.under_table(), cube_hit_pane=False, stick_hit_pane=False,
272
+ robot_hit_pane=False)
273
+
274
+ def _monitor_step(self):
275
+ mon, sk = self._mon, self.sk
276
+ if sk is None:
277
+ return
278
+ hits = self._robot_contacts()
279
+ if "glass_top" in hits:
280
+ e = sk.eef_pos()
281
+ rel = np.abs(e[:2] - np.array(self.inst["table_xy"]))
282
+ mon["top_hit"] = dict(above=bool((rel < np.array(TOP_HALF[:2])).all()),
283
+ tip=float(e[2] - TIP_BELOW_SITE - envs.TABLE_Z),
284
+ outside=float(max(rel - np.array(TOP_HALF[:2]))))
285
+ if sk.holding("stick_1"):
286
+ mon["stick_held"] = True
287
+ if "pane" in hits:
288
+ mon["robot_hit_pane"] = True
289
+ robot, tbl, top, stick, cube = self._groups()
290
+ panes = {g for g, _ in self._panes()}
291
+ d = self.env.sim.data
292
+ for i in range(d.ncon):
293
+ c = d.contact[i]
294
+ pair = (c.geom1, c.geom2)
295
+ if (pair[0] in stick and pair[1] in cube) or (pair[1] in stick and pair[0] in cube):
296
+ mon["stick_touched_cube"] = True
297
+ if (pair[0] in panes and pair[1] in cube) or (pair[1] in panes and pair[0] in cube):
298
+ mon["cube_hit_pane"] = True
299
+ if (pair[0] in panes and pair[1] in stick) or (pair[1] in panes and pair[0] in stick):
300
+ mon["stick_hit_pane"] = True
301
+ p = envs.obj_pos(self.env, "cube_1")
302
+ mon["max_cube_dz"] = max(mon["max_cube_dz"], float(p[2] - mon["start"][2]))
303
+ if not self.under_table():
304
+ mon["cube_out"] = True
305
+
306
+ # ------------------------------------------------------------ outcome / F2
307
+ def outcome(self, inst):
308
+ envs.settle(self.env, 30)
309
+ mon = self._mon or {}
310
+ p = envs.obj_pos(self.env, "cube_1")
311
+ held = bool(self.sk.holding("cube_1")) if self.sk is not None else False
312
+ success = bool(self.in_bin() and not held)
313
+ moved = float(np.linalg.norm(p[:2] - mon.get("start", p)[:2]))
314
+ under = self.under_table()
315
+ brel = p[:2] - np.array(inst["bin_xy"])
316
+ parts, mode = [], "success"
317
+ top = mon.get("top_hit")
318
+ if success:
319
+ parts.append("The cube is in the bin.")
320
+ elif p[2] < envs.TABLE_Z - 0.05:
321
+ mode = "fell_off"
322
+ parts.append("The cube fell off the table.")
323
+ elif held:
324
+ mode = "held"
325
+ parts.append("The cube is still held by the gripper; it was not released into the bin.")
326
+ elif under:
327
+ mode = "under"
328
+ if top is not None and not mon.get("stick_touched_cube"):
329
+ mode = "blocked"
330
+ if top["above"]:
331
+ parts.append(f"The gripper came down on the glass top of the low table: its fingertips stopped "
332
+ f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, while the cube is underneath "
333
+ f"the glass (the glass underside is {100 * TOP_UNDER:.1f} cm above the tabletop), so the "
334
+ f"gripper never got to the cube.")
335
+ else:
336
+ parts.append(f"The hand ran into the edge of the glass top of the low table (fingertips "
337
+ f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, gripper "
338
+ f"{100 * max(top['outside'], 0.0):.1f} cm outside the edge) and could not move in "
339
+ f"under the glass.")
340
+ if mon.get("cube_hit_pane"):
341
+ mode = "pane"
342
+ parts.append(f"The cube was pushed against a clear acrylic panel that closes the "
343
+ f"{'left' if inst.get('pane_side', -inst['side']) > 0 else 'right'} side of the low "
344
+ f"table (between its two legs, from the tabletop up to the glass); it cannot leave the "
345
+ f"low table on that side.")
346
+ if moved > 0.01:
347
+ parts.append(f"The cube was moved {100 * moved:.1f} cm but is still under the low table "
348
+ f"({100 * -self.outside_dist():.1f} cm from getting completely out from under it).")
349
+ else:
350
+ parts.append("The cube did not move; it is still under the low table.")
351
+ else:
352
+ mode = "out_not_in_bin"
353
+ lifted = mon.get("max_cube_dz", 0.0) > 0.03
354
+ parts.append(("The cube was lifted but ended outside the bin" if lifted else
355
+ "The cube is out from under the low table but not in the bin") +
356
+ f": it is {100 * abs(brel[0]):.1f} cm {'forward' if brel[0] > 0 else 'backward'} and "
357
+ f"{100 * abs(brel[1]):.1f} cm {'left' if brel[1] > 0 else 'right'} of the bin's centre.")
358
+ out = dict(success=success, mode=mode, moved=moved, under=under, cube_rel_bin=[float(brel[0]), float(brel[1])],
359
+ stick_used=bool(mon.get("stick_held")), terminal=bool(p[2] < envs.TABLE_Z - 0.05),
360
+ cube_hit_pane=bool(mon.get("cube_hit_pane")), stick_hit_pane=bool(mon.get("stick_hit_pane")),
361
+ robot_hit_pane=bool(mon.get("robot_hit_pane")), detail=" ".join(parts))
362
+ self._start_monitor()
363
+ return out
364
+
365
+ # ------------------------------------------------------------ primitives for the scripted policies
366
+ def _yaw_near(self, yaw):
367
+ cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)]
368
+ cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands
369
+ return float(min(cands, key=lambda c: abs(c - self.sk.yaw)))
370
+
371
+ def _align(self, tol=0.03, max_steps=60):
372
+ sk = self.sk
373
+ for _ in range(max_steps):
374
+ R = sk._R() @ sk.eef_mat().T
375
+ if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol:
376
+ break
377
+ sk.hold(1)
378
+
379
+ def _guarded_descent(self, xyz, speed=0.12, max_steps=80):
380
+ sk = self.sk
381
+ p0 = sk.eef_pos()
382
+ tgt = np.asarray(xyz, float)
383
+ dist = max(np.linalg.norm(tgt - p0), 1e-6)
384
+ R = sk._R()
385
+ for k in range(max_steps):
386
+ ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist)
387
+ sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
388
+ if self._robot_contacts() - {"cube"} and sk.eef_pos()[2] > tgt[2] + 0.005:
389
+ break
390
+ if np.linalg.norm(tgt - sk.eef_pos()) < 0.003:
391
+ break
392
+ sk.hold(4)
393
+
394
+ def grasp_cube_and_bin(self, dxy=(0.0, 0.0), dyaw=0.0):
395
+ """Top-down grasp of the cube where it is (+ offsets); if held, drop it into the bin."""
396
+ sk, o = self.sk, self.observe()
397
+ c = o["cube"]
398
+ gx, gy = c[0] + dxy[0], c[1] + dxy[1]
399
+ # the hand is 20 cm long along the closing direction: keep that direction parallel to the low table's edge
400
+ v = c[:2] - o["table_xy"]
401
+ yaw = (np.pi / 2 if abs(v[1]) > abs(v[0]) else 0.0) + dyaw
402
+ sk.set_gripper(False, steps=8)
403
+ sk.move_to([gx, gy, envs.TABLE_Z + 0.15], yaw=self._yaw_near(yaw))
404
+ self._align()
405
+ self._guarded_descent([gx, gy, envs.TABLE_Z + 0.017])
406
+ sk.set_gripper(True, steps=15)
407
+ e = sk.eef_pos()
408
+ sk.move_to([e[0], e[1], envs.TABLE_Z + 0.16], speed=0.25)
409
+ if sk.holding("cube_1"):
410
+ bx, by = o["bin_xy"]
411
+ sk.move_to([bx, by, envs.TABLE_Z + 0.16])
412
+ sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05])
413
+ sk.set_gripper(False, steps=12)
414
+ sk.move_to([bx, by, envs.TABLE_Z + 0.16])
415
+ else:
416
+ sk.set_gripper(False, steps=6)
417
+
418
+ def tool_push_out(self, extra=0.0):
419
+ """Pick the stick up by the end of its handle (it already points at the low table), lift it a few mm and slide
420
+ it along its own axis under the glass top so that its head pushes the cube out on the far side; put it down."""
421
+ sk, o = self.sk, self.observe()
422
+ ax = o["stick_dir"]
423
+ g = o["free_end"] + ax * GRIP_END
424
+ sk.set_gripper(False, steps=8)
425
+ sk.move_to([g[0], g[1], Z_STICK + 0.08], yaw=self._yaw_near(float(np.arctan2(ax[1], ax[0]))))
426
+ self._align()
427
+ sk.move_to([g[0], g[1], Z_STICK], tol=0.003)
428
+ sk.set_gripper(True, steps=15)
429
+ sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05)
430
+ o2 = self.observe()
431
+ c, t_xy = o2["cube"][:2], o2["table_xy"]
432
+ n = np.array([0.0, -float(self.inst["side"])]) # push straight across the low table (normal of its far edge)
433
+ perp = np.array([-n[1], n[0]])
434
+ head = o2["head"]
435
+ # line the head up with the cube by sliding the stick sideways (no turning: a turned stick slips in the grasp)
436
+ lat = float((c - head) @ perp)
437
+ e = sk.eef_pos()
438
+ sk.move_to([e[0] + perp[0] * lat, e[1] + perp[1] * lat, e[2]], speed=0.05)
439
+ o3 = self.observe()
440
+ head_front = float((o3["head"] + o3["stick_dir"] * HEAD_HALF[0]) @ n)
441
+ gap = max(float(c @ n) - CUBE_HALF - head_front, 0.0)
442
+ need = (TOP_HALF[1] + CUBE_HALF + 0.05 + extra) - float((c - t_xy) @ n) # cube travel until it is clear
443
+ e = sk.eef_pos()
444
+ tgt = e[:2] + n * (gap + need)
445
+ sk.move_to([tgt[0], tgt[1], e[2]], speed=0.08, tol=0.004, max_steps=500)
446
+ sk.hold(3)
447
+ for _ in range(3): # still (partly) under the glass top: push on a little
448
+ if not self.under_table() or not sk.holding("stick_1"):
449
+ break
450
+ e = sk.eef_pos()
451
+ tgt = e[:2] + n * 0.025
452
+ sk.move_to([tgt[0], tgt[1], e[2]], speed=0.06, tol=0.004, max_steps=100)
453
+ sk.hold(3)
454
+ ax = n
455
+ back = sk.eef_pos()[:2] - ax * 0.05
456
+ sk.move_to([back[0], back[1], e[2]], speed=0.08)
457
+ sk.set_gripper(False, steps=10)
458
+ sk.move_to([back[0], back[1], envs.TABLE_Z + 0.12], speed=0.2)
459
+
460
+ def tool_push_front(self, extra=0.0):
461
+ """v2 reference solution. Pick the stick up at its centre of mass, turn it to point forward (+x, away from the
462
+ robot) in the air, put it down behind the low table in line with the cube, re-grasp it GRIP_FRONT from its
463
+ free end and slide it forward under the glass top so that its head pushes the cube out of the FRONT side;
464
+ pull the stick back a little and put it down.
465
+
466
+ Reach: the re-grasp point is about 25 cm in front of the robot base at the start of the push; it stays
467
+ >= 3 cm behind the glass top's back edge at the end (the hand is about 4-13 cm above the fingertips and
468
+ would hit the glass edge)."""
469
+ sk, o = self.sk, self.observe()
470
+ ax = o["stick_dir"]
471
+ com = o["stick_xy"] + ax * STICK_COM
472
+ phi = float(np.arctan2(ax[1], ax[0])) # the stick points this way (handle -> head); about +-90 deg
473
+ sk.set_gripper(False, steps=8)
474
+ # grasp with gripper yaw = phi (not phi +- pi), so that turning the stick to point forward is a wrist turn to
475
+ # yaw 0, inside the wrist's range
476
+ sk.move_to([com[0], com[1], Z_STICK + 0.08], yaw=phi, wrap_yaw=False)
477
+ self._align()
478
+ sk.move_to([com[0], com[1], Z_STICK], tol=0.003)
479
+ sk.set_gripper(True, steps=15)
480
+ sk.move_to([com[0], com[1], Z_STICK + 0.10], speed=0.15)
481
+ c, t_xy = o["cube"][:2], o["table_xy"]
482
+ head_front_x = t_xy[0] - TOP_HALF[0] - 0.006 # just outside the glass top's back edge
483
+ put_x = head_front_x - (HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + STICK_COM
484
+ e = sk.eef_pos()
485
+ sk.move_to([e[0], e[1], e[2]], yaw=0.0, wrap_yaw=False)
486
+ self._align()
487
+ sk.move_to([put_x, c[1], Z_STICK + 0.10], speed=0.2)
488
+ sk.move_to([put_x, c[1], Z_STICK + 0.004], speed=0.08, tol=0.003)
489
+ sk.set_gripper(False, steps=10)
490
+ sk.move_to([put_x, c[1], Z_STICK + 0.06], speed=0.15)
491
+ # re-grasp near the free end
492
+ o2 = self.observe()
493
+ ax2 = o2["stick_dir"]
494
+ g = o2["free_end"] + ax2 * GRIP_FRONT
495
+ sk.move_to([g[0], g[1], Z_STICK + 0.06], yaw=self._yaw_near(float(np.arctan2(ax2[1], ax2[0]))))
496
+ self._align()
497
+ sk.move_to([g[0], g[1], Z_STICK], tol=0.003)
498
+ sk.set_gripper(True, steps=15)
499
+ sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05)
500
+ # line the head up with the cube (sideways slide), then push forward
501
+ o3 = self.observe()
502
+ lat = float(c[1] - o3["head"][1])
503
+ e = sk.eef_pos()
504
+ sk.move_to([e[0], e[1] + lat, e[2]], speed=0.05)
505
+ o4 = self.observe()
506
+ head_front = float(o4["head"][0] + HEAD_HALF[0])
507
+ cube_tgt = t_xy[0] + TOP_HALF[0] + CUBE_HALF + 0.03 + extra
508
+ travel = (cube_tgt - CUBE_HALF) - head_front
509
+ e = sk.eef_pos()
510
+ sk.move_to([e[0] + travel, e[1], e[2]], speed=0.08, tol=0.004, max_steps=500)
511
+ sk.hold(3)
512
+ e = sk.eef_pos()
513
+ sk.move_to([e[0] - 0.05, e[1], e[2]], speed=0.08)
514
+ sk.set_gripper(False, steps=10)
515
+ e = sk.eef_pos()
516
+ sk.move_to([e[0], e[1], envs.TABLE_Z + 0.12], speed=0.2)
517
+
518
+ def execute(self, inst, params):
519
+ if params["mode"] == "tool":
520
+ self.tool_push_out(params.get("extra", 0.0))
521
+ elif params["mode"] == "front":
522
+ self.tool_push_front(params.get("extra", 0.0))
523
+ self.grasp_cube_and_bin(params.get("dxy", (0.0, 0.0)), params.get("dyaw", 0.0))
524
+
525
+ # ------------------------------------------------------------ scripted references
526
+ def default_params(self, inst):
527
+ """v2 prior: what every cla2 Sonnet run did -- take the stick and push the cube straight across (towards
528
+ the bin, which is now behind the hidden panel)"""
529
+ return dict(mode="tool")
530
+
531
+ def oracle_params(self, inst):
532
+ return dict(mode="front")
533
+
534
+ def blind_params(self, inst, attempt, rng):
535
+ """no history: the prior with a random extra push length"""
536
+ return dict(mode="tool", extra=float(abs(rng.normal(0, 0.03))))
537
+
538
+ def adapt_params(self, inst, history):
539
+ """v2: the cube stayed under the low table after a push across -> something blocks that side: push it out of
540
+ the front instead. Hand grasp blocked by the glass -> use the stick (the v1 lesson). Front push that did not
541
+ get it out -> push further."""
542
+ out, prm = history[-1]["outcome"], history[-1]["params"]
543
+ if prm["mode"] == "grasp":
544
+ return dict(mode="tool") if out["mode"] in ("blocked", "under") else dict(prm)
545
+ if prm["mode"] == "tool":
546
+ return dict(mode="front") if out["mode"] in ("pane", "under", "blocked") else dict(prm)
547
+ if out["mode"] in ("under", "blocked"):
548
+ return dict(prm, extra=prm.get("extra", 0.0) + 0.02)
549
+ return dict(prm)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l5_slippery_lift.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L5-B slippery_lift: pick up a heavy, slippery metal bar and hold it level.
2
+
3
+ Category dynamics_adaptation (L5): "figure out how this object moves".
4
+
5
+ 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
6
+ perfectly uniform, but a heavy slug is hidden inside it at an unknown position, so its centre of mass sits
7
+ 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
8
+ surface is slippery (finger friction 0.40-0.60): the two finger pads can hold its weight, but they cannot hold
9
+ much torque.
10
+
11
+ Why the prior fails. The natural grasp is across the bar at its midpoint. With the centre of mass a few cm to
12
+ one side, gravity twists the bar in the pads as soon as it is lifted: the heavy end swings down and the bar
13
+ ends up hanging tilted by ~10-50 deg (measured). Slow lifting does not help (the torque is static).
14
+
15
+ What has to be learned. Which end sank tells on which side of the grasp the centre of mass lies; the grasp
16
+ has to move towards that end until it is within ~1.5 cm of the hidden centre of mass (measured window). The
17
+ tilt magnitude saturates, so the distance has to be found by bracketing over a few attempts.
18
+
19
+ 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:
20
+ |grasp - COM| <= 1.0 cm -> tilt <= 2 deg; 1.5 cm -> 0-41 deg; >= 2 cm -> mostly 30-50 deg; the tilt does not
21
+ 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.
22
+ """
23
+ import numpy as np
24
+
25
+ from .. import envs
26
+ from ..bddl import write_bddl
27
+ from ..objects import _fmt, _wrap, register_generated
28
+ from ..skills import Skills
29
+ from ..task_base import LFFTask, register_task
30
+
31
+ BAR = "bar_1"
32
+ HALF = (0.02, 0.14, 0.02) # 4 (x) x 28 (y) x 4 (z) cm, long axis along world y
33
+ _SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
34
+ W_FRAC = 0.6 # fraction of the bar's mass in the hidden slug
35
+ W_HALF = 0.015 # slug half size (for its inertia)
36
+ E_MIN, E_MAX = 0.025, 0.070 # |COM offset| from the bar's midpoint (m)
37
+ LIFT_MIN = 0.10 # the bar's lowest point must be this high above the table
38
+ TILT_MAX = 8.0 # deg
39
+ Z_GRASP = envs.TABLE_Z + HALF[2] # gripper site at the bar's mid height (finger tips 0.7 cm above the table)
40
+ Z_LIFT = Z_GRASP + 0.15
41
+ YAW_ACROSS = np.pi / 2 # jaws close along world x, i.e. across the bar
42
+
43
+
44
+ def weighted_box_xml(name, half, rgba, mass=1.0, friction=(1.0, 0.005, 0.0001)):
45
+ """Box with an explicit inertial. Its pos is off-centre at compile time so MuJoCo keeps
46
+ body_sameframe = 0 / body_simple = 0 and honours the per-instance body_ipos set in apply_instance."""
47
+ I = [mass / 3 * (half[1] ** 2 + half[2] ** 2), mass / 3 * (half[0] ** 2 + half[2] ** 2),
48
+ mass / 3 * (half[0] ** 2 + half[1] ** 2)]
49
+ g = (f' <inertial pos="0 0.001 0.001" mass="{mass}" diaginertia="{_fmt(I)}" />\n'
50
+ f' <geom name="{name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
51
+ f'friction="{_fmt(friction)}" {_SOLID} group="0" />\n'
52
+ f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
53
+ return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
54
+
55
+
56
+ def set_hidden_weight(env, obj, half, mass, w_frac, w_pos, w_half=W_HALF):
57
+ """Uniform shell of mass (1 - w_frac) * mass plus a hidden cube slug of w_frac * mass at w_pos (body frame).
58
+ Sets the body's mass, centre of mass and inertia; returns the centre of mass (body frame)."""
59
+ m = env.sim.model
60
+ bid = envs.body_id(env, obj)
61
+ ms, mw = (1 - w_frac) * mass, w_frac * mass
62
+ w_pos = np.asarray(w_pos, float)
63
+ c = mw * w_pos / mass
64
+ hx, hy, hz = half
65
+
66
+ def par(mm, r): # parallel-axis terms (diagonal)
67
+ return mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2])
68
+
69
+ I = (ms / 3 * np.array([hy ** 2 + hz ** 2, hx ** 2 + hz ** 2, hx ** 2 + hy ** 2]) + par(ms, -c)
70
+ + mw / 6 * (2 * w_half) ** 2 * np.ones(3) + par(mw, w_pos - c))
71
+ m.body_mass[bid] = mass
72
+ m.body_ipos[bid] = c
73
+ m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
74
+ m.body_inertia[bid] = I
75
+ envs.refit_bounds(env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds)
76
+ return c
77
+
78
+
79
+ def bar_axis(env):
80
+ """World direction of the bar's long axis (body y)."""
81
+ return env.sim.data.body_xmat[envs.body_id(env, BAR)].reshape(3, 3)[:, 1].copy()
82
+
83
+
84
+ def bar_tilt_deg(env):
85
+ """Signed tilt of the bar's long axis from horizontal; > 0: the bar's +y end is lower."""
86
+ ax = bar_axis(env)
87
+ if ax[1] < 0: # orient the axis towards the robot's left so the sign is about world left/right
88
+ ax = -ax
89
+ return float(np.degrees(np.arcsin(np.clip(-ax[2], -1.0, 1.0))))
90
+
91
+
92
+ def side_words(sign):
93
+ return "left (+y)" if sign > 0 else "right (-y)"
94
+
95
+
96
+ class BarSkills(Skills):
97
+ """Skills that record where along the bar the jaws closed, whoever drives them (scripted or agent)."""
98
+
99
+ def __init__(self, env, bias=None, recorder=None):
100
+ super().__init__(env, bias=bias, recorder=recorder)
101
+ self.closes = []
102
+ self.zmax = float(envs.obj_pos(env, BAR)[2])
103
+ self.z0 = self.zmax
104
+
105
+ def _act(self, dpos, drot, grip):
106
+ super()._act(dpos, drot, grip)
107
+ self.zmax = max(self.zmax, float(envs.obj_pos(self.env, BAR)[2]))
108
+
109
+ def set_gripper(self, close, steps=15):
110
+ rep = super().set_gripper(close, steps)
111
+ if close:
112
+ c = envs.obj_pos(self.env, BAR)
113
+ ax = bar_axis(self.env)
114
+ if ax[1] < 0:
115
+ ax = -ax
116
+ along = float((self.eef_pos() - c) @ ax) # + : grasp on the left (+y) side of the midpoint
117
+ self.closes.append(dict(along=along, holding=self.holding(BAR), step=self.n_steps))
118
+ return rep
119
+
120
+
121
+ @register_task
122
+ class SlipperyLift(LFFTask):
123
+ name = "l5_slippery_lift"
124
+ level = "L5"
125
+ category = "dynamics_adaptation"
126
+ capabilities = ("Perceive", "Reason", "Utilize")
127
+ protocol = "cross"
128
+ instruction = ("Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at "
129
+ "least 10 cm above the table. Keep holding it when you finish.")
130
+ instruction_indirect = ("Pick up the long grey rod lying on the table and hold it horizontal (tilted less than 8 "
131
+ "degrees), with its lowest point at least 10 cm above the table. Keep holding it when you "
132
+ "finish.")
133
+
134
+ # ------------------------------------------------------------ scene
135
+ def make_bddl(self):
136
+ bar = register_generated("LffSteelBar", weighted_box_xml("lff_steel_bar", HALF, (0.52, 0.55, 0.58, 1.0)))
137
+ objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01))]
138
+ return write_bddl(self.name, "pick up the bar and hold it level", objs) # BDDL cannot parse parentheses
139
+
140
+ def sample_instance(self, seed):
141
+ rng = np.random.default_rng(seed)
142
+ e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX))
143
+ return dict(seed=int(seed),
144
+ bar_xy=[float(rng.uniform(-0.12, -0.03)), float(rng.uniform(-0.06, 0.06))],
145
+ com_offset=e, # along the bar, + = towards the robot's left (+y) end
146
+ mass=float(rng.uniform(0.8, 1.2)),
147
+ mu=float(rng.uniform(0.40, 0.60)))
148
+
149
+ def apply_instance(self, inst):
150
+ x, y = inst["bar_xy"]
151
+ envs.set_obj_pose(self.env, BAR, [x, y, envs.TABLE_Z + HALF[2] + 0.001])
152
+ envs.set_friction(self.env, BAR, inst["mu"])
153
+ set_hidden_weight(self.env, BAR, HALF, inst["mass"], W_FRAC, [0.0, inst["com_offset"] / W_FRAC, 0.0])
154
+
155
+ def reset_instance(self, inst, recorder=None):
156
+ self.env.reset()
157
+ self.apply_instance(inst)
158
+ self.env.sim.forward()
159
+ envs.settle(self.env, 10)
160
+ self.sk = BarSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
161
+ return self.sk
162
+
163
+ # ------------------------------------------------------------ outcome
164
+ def outcome(self, inst):
165
+ sk = self.sk
166
+ sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws)
167
+ held = sk.holding(BAR)
168
+ tilt = bar_tilt_deg(self.env)
169
+ bottom = envs.obj_min_z(self.env, BAR) - envs.TABLE_Z
170
+ lifted = (sk.zmax - sk.z0) > 0.03
171
+ close = next((c for c in reversed(sk.closes) if c["holding"]), sk.closes[-1] if sk.closes else None)
172
+ success = bool(held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN)
173
+ out = dict(success=success, held=bool(held), tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1),
174
+ grasp_along=None if close is None else round(close["along"], 4))
175
+ g = ""
176
+ if close is not None and close["holding"]:
177
+ a = close["along"]
178
+ g = (f" You grasped the bar {100 * abs(a):.1f} cm to the {side_words(a)} of its midpoint."
179
+ if abs(a) >= 0.0005 else " You grasped the bar at its midpoint.")
180
+ tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {side_words(tilt).split()[0]} end lower than its "
181
+ f"{side_words(-tilt).split()[0]} end")
182
+ if success:
183
+ out["failure"] = None
184
+ detail = f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table." + g
185
+ elif held and abs(tilt) > TILT_MAX:
186
+ out["failure"] = "tilted"
187
+ detail = ("The bar did not stay level: it rotated in the gripper while it was being lifted and now "
188
+ f"{tilt_txt}." + g)
189
+ if bottom < LIFT_MIN:
190
+ detail += f" Its lowest point is {100 * bottom:.0f} cm above the table."
191
+ elif held:
192
+ out["failure"] = "too_low"
193
+ detail = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only "
194
+ f"{100 * bottom:.0f} cm above the table." + g)
195
+ elif lifted:
196
+ out["failure"] = "dropped"
197
+ detail = ("The bar was lifted but slipped out of the gripper and fell back onto the table "
198
+ f"(it now lies tilted by {abs(tilt):.0f} degrees)." + g)
199
+ elif close is None:
200
+ out["failure"] = "no_grasp"
201
+ detail = "The gripper never closed on the bar; it is still lying on the table."
202
+ else:
203
+ out["failure"] = "no_grasp"
204
+ detail = "The gripper closed but did not catch the bar; it is still lying on the table."
205
+ out["detail"] = detail
206
+ out["detail_indirect"] = detail.replace("bar", "rod")
207
+ return out
208
+
209
+ def feedback(self, inst, out, level="F2", indirect=False):
210
+ if indirect and level == "F2":
211
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
212
+ return super().feedback(inst, out, level)
213
+
214
+ # ------------------------------------------------------------ scripted execution (cross protocol)
215
+ def execute(self, inst, params):
216
+ """Grasp across the bar at `along` (m from the visible midpoint, + = left / +y) and lift 15 cm."""
217
+ sk = self.sk
218
+ c = envs.obj_pos(self.env, BAR) # visible bar pose (perfect perception)
219
+ ax = bar_axis(self.env)
220
+ if ax[1] < 0:
221
+ ax = -ax
222
+ g = c + ax * float(params["along"])
223
+ sk.set_gripper(False, steps=5)
224
+ sk.move_to([g[0], g[1], Z_GRASP + 0.10], yaw=YAW_ACROSS)
225
+ sk.move_to([g[0], g[1], Z_GRASP], tol=0.003)
226
+ sk.set_gripper(True, steps=15)
227
+ sk.move_to([g[0], g[1], Z_LIFT], speed=0.15, tol=0.004, max_steps=300)
228
+
229
+ def default_params(self, inst):
230
+ return dict(along=0.0)
231
+
232
+ def oracle_params(self, inst):
233
+ return dict(along=float(inst["com_offset"]))
234
+
235
+ MARGIN = 0.008 # a tilt towards +y at grasp g means COM > g + MARGIN (window is ~+-1.5 cm)
236
+ STEP = 0.030 # first step towards the heavy end when only one side is bounded
237
+
238
+ def adapt_params(self, inst, history):
239
+ """Bracketing on the grasp point: the end that sank is the heavy side of the last grasp."""
240
+ lo, hi = -HALF[1], HALF[1]
241
+ lo_set = hi_set = False
242
+ for h in history:
243
+ o = h["outcome"]
244
+ g = o["grasp_along"] if o.get("grasp_along") is not None else h["params"]["along"]
245
+ if o.get("failure") == "tilted" or (o.get("failure") == "dropped" and abs(o["tilt_deg"]) > 3):
246
+ if o["tilt_deg"] > 0: # left end sank -> COM left of the grasp
247
+ lo, lo_set = max(lo, g + self.MARGIN), True
248
+ else:
249
+ hi, hi_set = min(hi, g - self.MARGIN), True
250
+ last = history[-1]["params"]["along"]
251
+ if lo_set and hi_set:
252
+ a = 0.5 * (lo + hi)
253
+ elif lo_set:
254
+ a = lo + self.STEP - self.MARGIN
255
+ elif hi_set:
256
+ a = hi - self.STEP + self.MARGIN
257
+ else: # no direction information (e.g. too low): repeat
258
+ a = last
259
+ return dict(along=float(np.clip(a, -0.12, 0.12)))
260
+
261
+ def blind_params(self, inst, attempt, rng):
262
+ return dict(along=float(rng.normal(0.0, 0.01)))
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_clear_cover.py ADDED
@@ -0,0 +1,657 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH clear_cover: sort four cubes into two open boxes by colour -- but in half of the instances one box is covered by a
2
+ 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.
3
+
4
+ Family: long-horizon self-disturbance / common sense ("state_restoration"; design P2-2 in
5
+ research_notes/P1P2_加深与常识任务设计.md): four pick-and-place stages that are each easy for a frontier model; the
6
+ trap is a commonsense one -- "a box can have a transparent lid" -- and the failure is only visible from the right
7
+ viewpoint: from the side (agentview) the cube visibly sits on top of the box, at rim height, with the box floor visible
8
+ below it; from straight above (the wrist camera) it lies inside the box's outline and looks almost the same as a cube
9
+ that is inside (design rule R5: a top-down view hides height differences).
10
+
11
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
12
+ * 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
13
+ 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
14
+ colour is on the left is random. The instruction names the boxes by colour, not "left / right" (the design draft's
15
+ wording), so that no failure comes from whose left is meant;
16
+ * 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
17
+ apart, shuffled, yaw +-23 deg);
18
+ * the clear lid (covered instances only): a loose 13.4 x 13.4 cm, 8 mm clear plate lying on one box's walls,
19
+ 1 mm inside their outer faces (no overhang). v2 (2026-10-13, after the Sonnet pilot np_lh_clear_cover): rendered
20
+ nearly invisible -- alpha 0.03, matte (no specular glint), no edge highlight (v1: alpha 0.10 + bright edges, and the
21
+ pilot agent named "the transparent lid" from the first images); heavy (1 kg; mass is not visible) with friction 1.0
22
+ and priority for all its contacts and medium-stiff contacts, so incidental contact by the hand does not knock it off
23
+ (v1, 0.12 kg / mu 0.3 / 6 mm overhang / very stiff contacts: a probe descent between the boxes knocked it off in the
24
+ pilot's very first motions). Transparent geoms do not write MuJoCo's depth buffer: in the depth maps
25
+ (--perception rgbd) the lid is not there at all. In uncovered instances the lid is parked on the floor far outside
26
+ the workspace and the cameras' view.
27
+
28
+ Hidden variable: whether a box is covered and which one. Exactly 10 of every 20 consecutive seeds are covered (5 red /
29
+ 5 blue box): (seed * 7) mod 20 < 10, like lh_lid_box's balanced blocks.
30
+
31
+ 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
32
+ 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;
33
+ 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
34
+ still covering). After the release the cube visibly sits on top of the box in agentview (its bottom 0.8 cm above the
35
+ rim, the box floor visible below it); checking only from above it looks as if it were in the box (~1.3x bigger).
36
+ What must be learned: look from the side / compare heights before finishing, notice the cubes resting at rim height,
37
+ remove the lid (push its edge horizontally with the closed gripper, fingertips between the rim and the lid's top face --
38
+ 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
39
+ remove it before placing anything (across attempts). Pressing the fingertips onto the lid and dragging no longer moves
40
+ it (v2: hand friction = rim friction, by design, because a hand landing on the lid while moving sideways is exactly
41
+ what knocked the v1 lid off).
42
+ Measured, 2 covered instances x 86 Sonnet-like incidental motions (probe descents to 2-5 cm next to / between the
43
+ boxes, transits at 11-20 cm over the covered box, low lateral moves next to the boxes): the box got uncovered 1/172
44
+ (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).
45
+ Deliberate edge push, agent-style commands: fingertip target 2-10 mm below the lid's top face 10/10 (+ 8/8 in the
46
+ parameter sweep), at the top face 1/2, above it 0/2.
47
+
48
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the
49
+ cavity of the box of its colour -- centre inside the cavity, lowest point below the rim --, nothing held, the lid not on
50
+ a box, scene static) plus a per-step event log (cube stages achieved / lost / restored, rested_on_cover, left_cover,
51
+ cover_removed, cover_on_box, in_wrong_box) for the server log; F1 gives the agent only success / failure.
52
+ """
53
+ import numpy as np
54
+
55
+ from .. import envs
56
+ from ..bddl import write_bddl
57
+ from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated
58
+ from ..skills import Skills
59
+ from ..task_base import LFFTask, register_task
60
+
61
+ Z = envs.TABLE_Z
62
+ TIP = envs.FINGERTIP_BELOW_SITE
63
+ # ---------------------------------------------------------------- geometry / physics
64
+ CUBE_E = 0.04
65
+ CUBE_DENS = 600.0 # -> 38 g
66
+ BOX_IN = 0.06 # inner half width (12 x 12 cm cavity)
67
+ WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.05
68
+ BOX_OUT = BOX_IN + WALL_T
69
+ RIM = FLOOR_T + WALL_H # rim height above the table
70
+ WALL_MU = 0.3 # walls (cube contacts; the lid's own friction has priority in its contacts)
71
+ LID_T = 0.008 # thick enough that a horizontal push at 'lid height' finds its edge (v1 draft: 4 mm, see the card)
72
+ 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
73
+ LID_MASS = 1.0 # v2: heavy (a thick glass-like plate; mass is not visible): incidental bumps move it much less
74
+ LID_MU = 1.0 # v2: with priority, used for ALL lid contacts (rim, hand, fingers, cubes): pressing on the lid and moving
75
+ # sideways cannot drag it (hand friction == rim friction, and the rim also carries the lid's weight)
76
+ LID_SOLREF = (0.005, 1.0) # v2: medium-stiff contacts (v1 used _SOLID: a finger that caught the lid's edge while the
77
+ LID_SOLIMP = (0.95, 0.99, 0.001) # arm pressed on could squeeze it against the wall and launch it 16-37 cm)
78
+ LID_TOP = RIM + LID_T # lid top surface above the table when it lies on a box
79
+ LID_RGBA = (0.85, 0.90, 0.95, 0.03) # v2: near-invisible, no edge highlight, no specular (material below)
80
+ PARK = (0.0, 1.4) # lid parked on the floor (world z = 0), out of reach and out of view (uncovered instances)
81
+
82
+ COLORS = ("red", "blue")
83
+ CUBE_RGBA = dict(red=(0.88, 0.10, 0.08, 1.0), blue=(0.10, 0.25, 0.88, 1.0))
84
+ WALL_RGBA = dict(red=(0.72, 0.26, 0.22, 1.0), blue=(0.22, 0.34, 0.72, 1.0))
85
+ FLOOR_RGBA = (0.86, 0.85, 0.82, 1.0)
86
+ CUBES = [f"{c}_cube_{i}" for c in COLORS for i in (1, 2)]
87
+ BOXES = {c: f"{c}_box_1" for c in COLORS}
88
+ LID = "clear_lid_1"
89
+
90
+ 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)
91
+ BELOW_RIM = 0.005 # ... and its lowest point is at least this far below the rim
92
+ Z_CARRY = 0.15 # scripted transit height of the grasp point above the table (Sonnet: 11-20 cm)
93
+ DROP = 0.04 # scripted release: cube bottom this far above the rim (Sonnet-like 3-5 cm)
94
+ SLOT = 0.028 # two cubes per box: +-2.8 cm from the centre along y
95
+ PUSH_DEPTH = 0.004 # scripted edge push: fingertips this far below the lid's top face (lid 8 mm thick)
96
+ PUSH_SPEED = 0.06
97
+
98
+
99
+ def _color(name):
100
+ return name.split("_")[0]
101
+
102
+
103
+ def _fb(v):
104
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
105
+
106
+
107
+ def _lr(v):
108
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
109
+
110
+
111
+ def box_xml_cc(name, wall_rgba):
112
+ """open-top box, body origin at the centre of its footprint on the table (z = 0 = table top)"""
113
+ o = BOX_OUT
114
+ parts = [((0, 0, FLOOR_T / 2), (o, o, FLOOR_T / 2), FLOOR_RGBA, 1.0),
115
+ ((BOX_IN + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU),
116
+ ((-BOX_IN - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU),
117
+ ((0, BOX_IN + WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU),
118
+ ((0, -BOX_IN - WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU)]
119
+ g = []
120
+ for k, (p, s, c, mu) in enumerate(parts):
121
+ g.append(f' <geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
122
+ f'friction="{mu} 0.005 0.0001" {_SOLID} group="0" />')
123
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
124
+ f'contype="0" group="1" />')
125
+ return f"""<mujoco model="{name}">
126
+ <worldbody>
127
+ <body>
128
+ <body name="object">
129
+ {chr(10).join(g)}
130
+ </body>
131
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
132
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {RIM:.4f}" name="top_site" />
133
+ <site rgba="0 0 0 0" size="0.005" pos="{o:.4f} {o:.4f} 0" name="horizontal_radius_site" />
134
+ </body>
135
+ </worldbody>
136
+ </mujoco>"""
137
+
138
+
139
+ def lid_xml(name):
140
+ """clear plate: one collision box + a near-invisible visual twin with a matte material (no specular glint)"""
141
+ h, t = LID_HALF, LID_T / 2
142
+ g = [f' <geom name="{name}_g0" type="box" size="{_fmt((h, h, t))}" rgba="1 1 1 0" mass="{LID_MASS}" '
143
+ f'friction="{LID_MU} 0.005 0.0001" solref="{_fmt(LID_SOLREF)}" solimp="{_fmt(LID_SOLIMP)}" group="0" />',
144
+ f' <geom type="box" size="{_fmt((h, h, t))}" rgba="{_fmt(LID_RGBA)}" material="{name}_mat" '
145
+ f'conaffinity="0" contype="0" group="1" />']
146
+ xml = _wrap(name, "\n".join(g), t, float(np.hypot(h, h)))
147
+ mat = (f' <asset>\n <material name="{name}_mat" rgba="{_fmt(LID_RGBA)}" specular="0" shininess="0" '
148
+ f'reflectance="0" />\n </asset>\n')
149
+ return xml.replace(" <worldbody>", mat + " <worldbody>", 1)
150
+
151
+
152
+ class CoverSkills(Skills):
153
+ """Skills that feed the task's per-step monitor."""
154
+
155
+ def __init__(self, env, task, recorder=None):
156
+ super().__init__(env, recorder=recorder)
157
+ self.task = task
158
+
159
+ def _act(self, dpos, drot, grip):
160
+ super()._act(dpos, drot, grip)
161
+ self.task.monitor_step()
162
+
163
+
164
+ @register_task
165
+ class ClearCover(LFFTask):
166
+ name = "lh_clear_cover"
167
+ level = "L2"
168
+ category = "state_restoration"
169
+ capabilities = ("Perceive", "Reason", "Plan", "Utilize")
170
+ protocol = "cross"
171
+ max_attempts = 3
172
+ # careful oracle: 4 pick-and-places (~7 commands each = 28) + pushing the lid off (~5) + looking around (~15);
173
+ # one recovery: pushing the lid off + re-placing the cubes that were on it (~5 + 2 x 7) -> ~70; Sonnet looks after
174
+ # every step and calibrates the wrist camera (cla4: 10+ observe / probe commands)
175
+ agent_max_steps = 110
176
+ instruction = "Put the two red cubes into the red box and the two blue cubes into the blue box."
177
+ instruction_indirect = "Sort the four small cubes by colour: each cube goes into the box whose walls have its colour."
178
+ agent_object_names = ["red cube", "red cube", "blue cube", "blue cube", "red box", "blue box"]
179
+
180
+ # ------------------------------------------------------------ scene
181
+ def make_bddl(self):
182
+ objs, fx = [], []
183
+ for j, c in enumerate(COLORS):
184
+ bx = register_generated(f"LffCc{c.title()}Box", box_xml_cc(f"lff_cc_{c}_box", WALL_RGBA[c]), free=False)
185
+ fx.append((BOXES[c], bx, f"{c}_box_region", (-0.12, 0.12 - 0.26 * j, -0.10, 0.14 - 0.26 * j)))
186
+ k = 0
187
+ for c in COLORS:
188
+ for i in (1, 2):
189
+ ab = "AB"[i - 1]
190
+ cat = register_generated(f"LffCc{c.title()}Cube{ab}",
191
+ box_xml(f"lff_cc_{c}_cube_{ab.lower()}", (CUBE_E / 2,) * 3, CUBE_RGBA[c],
192
+ density=CUBE_DENS))
193
+ objs.append((f"{c}_cube_{i}", cat, f"{c}_cube_{i}_region",
194
+ (-0.34, -0.22 + 0.14 * k, -0.32, -0.20 + 0.14 * k)))
195
+ k += 1
196
+ lid = register_generated("LffCc2ClearLid", lid_xml("lff_cc2_clear_lid"))
197
+ objs.append((LID, lid, "lid_region", (0.20, -0.01, 0.22, 0.01)))
198
+ return write_bddl(self.name, "put the cubes into the boxes of their colour", objs, fx)
199
+
200
+ def __init__(self, cam_res=None):
201
+ super().__init__(cam_res)
202
+ m = self.env.sim.model
203
+ self.box_bid = {c: m.body_name2id(self.env.fixtures_dict[BOXES[c]].root_body) for c in COLORS}
204
+ self.lid_gids = set(envs.obj_geom_ids(self.env, LID))
205
+ self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES}
206
+ self.robot_gids = set(envs.robot_geom_ids(self.env))
207
+ self.inst = None
208
+ self.mon = None
209
+
210
+ def sample_instance(self, seed):
211
+ rng = np.random.default_rng(seed)
212
+ bx = float(rng.uniform(-0.13, -0.09))
213
+ left = str(rng.choice(COLORS))
214
+ boxes = {}
215
+ for c in COLORS:
216
+ s = 1.0 if c == left else -1.0
217
+ boxes[c] = [bx + float(rng.uniform(-0.01, 0.01)), s * float(rng.uniform(0.12, 0.14))]
218
+ slots = [-0.21, -0.07, 0.07, 0.21]
219
+ perm = rng.permutation(4)
220
+ start = {CUBES[i]: [float(-0.33 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))]
221
+ for j, i in enumerate(perm)}
222
+ # balanced like lh_lid_box: exactly 10 of every 20 consecutive seeds covered (5 red box, 5 blue box)
223
+ r = (int(seed) * 7) % 20
224
+ cover = "red" if r < 5 else ("blue" if r < 10 else None)
225
+ return dict(seed=int(seed), boxes=boxes, left_box=left, start=start,
226
+ start_yaw={k: float(rng.uniform(-0.4, 0.4)) for k in CUBES}, cover=cover,
227
+ cover_side=(None if cover is None else ("left" if cover == left else "right")),
228
+ lid_off=[float(v) for v in rng.uniform(-0.004, 0.004, 2)], lid_yaw=float(rng.uniform(-0.05, 0.05)))
229
+
230
+ def apply_instance(self, inst):
231
+ self.inst = inst
232
+ m = self.env.sim.model
233
+ for c in COLORS:
234
+ m.body_pos[self.box_bid[c]] = [inst["boxes"][c][0], inst["boxes"][c][1], Z]
235
+ m.body_quat[self.box_bid[c]] = [1.0, 0.0, 0.0, 0.0]
236
+ for name, xy in inst["start"].items():
237
+ envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name])
238
+ if inst["cover"]:
239
+ b = inst["boxes"][inst["cover"]]
240
+ envs.set_obj_pose(self.env, LID, [b[0] + inst["lid_off"][0], b[1] + inst["lid_off"][1],
241
+ Z + RIM + LID_T / 2 + 0.0005], yaw=inst["lid_yaw"])
242
+ else:
243
+ envs.set_obj_pose(self.env, LID, [PARK[0], PARK[1], LID_T / 2 + 0.002])
244
+ envs.set_friction(self.env, LID, LID_MU, priority=2)
245
+
246
+ def reset_instance(self, inst, recorder=None):
247
+ self.env.reset()
248
+ self.apply_instance(inst)
249
+ self.env.sim.forward()
250
+ envs.settle(self.env, 10)
251
+ self.mon = None
252
+ self.sk = CoverSkills(self.env, self, recorder=recorder)
253
+ self._init_monitor()
254
+ return self.sk
255
+
256
+ # ------------------------------------------------------------ state helpers
257
+ def held(self, name):
258
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
259
+
260
+ def cube_rel(self, name, color):
261
+ return envs.obj_pos(self.env, name)[:2] - np.asarray(self.inst["boxes"][color])
262
+
263
+ def in_box(self, name, color, margin=IN_MARGIN):
264
+ """centre inside the cavity (per axis), lowest point below the rim, not held"""
265
+ rel = self.cube_rel(name, color)
266
+ return bool(np.max(np.abs(rel)) <= BOX_IN - margin and envs.obj_min_z(self.env, name) < Z + RIM - BELOW_RIM
267
+ and not self.held(name))
268
+
269
+ def where_box(self, name):
270
+ for c in COLORS:
271
+ if self.in_box(name, c):
272
+ return c
273
+ return None
274
+
275
+ def lid_pos(self):
276
+ return envs.obj_pos(self.env, LID)
277
+
278
+ def covering(self):
279
+ """colour of the box the lid lies on (centre within the box's outer footprint + 1 cm, above the floor), or None"""
280
+ p = self.lid_pos()
281
+ for c in COLORS:
282
+ rel = np.abs(p[:2] - np.asarray(self.inst["boxes"][c]))
283
+ if rel[0] <= BOX_OUT + 0.01 and rel[1] <= BOX_OUT + 0.01 and p[2] > Z + 0.02:
284
+ return c
285
+ return None
286
+
287
+ def _touching(self, gids_a, gids_b):
288
+ return envs.contacts_between(self.env, gids_a, gids_b)
289
+
290
+ def on_cover(self, name, moving_ok=False):
291
+ """the cube rests on the lid while the lid lies on a box (contact, not held, slow -- unless `moving_ok`: the
292
+ monitor keeps a cube that came to rest on the lid "on" while it rides along with the lid being pushed)"""
293
+ if self.covering() is None or self.held(name):
294
+ return False
295
+ if not self._touching(self.cube_gids[name], self.lid_gids):
296
+ return False
297
+ if moving_ok:
298
+ return True
299
+ _, da = envs.free_joint_addr(self.env, name)
300
+ return bool(np.linalg.norm(self.env.sim.data.qvel[da:da + 3]) < 0.05)
301
+
302
+ def stage_values(self):
303
+ v = {f"{n}_in_box": self.in_box(n, _color(n)) for n in CUBES}
304
+ v["cover_off_boxes"] = self.covering() is None
305
+ return v
306
+
307
+ # ------------------------------------------------------------ per-step monitor
308
+ def _init_monitor(self):
309
+ self.mon = dict(step=0, state={f"{n}_in_box": False for n in CUBES}, ever=set(), lost=set(), events=[],
310
+ on_cover={n: False for n in CUBES}, cover=self.covering(), wrong={n: None for n in CUBES},
311
+ last_touch={n: None for n in CUBES}, rested=[], cover_removed_step=None)
312
+
313
+ def _touches(self):
314
+ d = self.env.sim.data
315
+ out = {}
316
+ for i in range(d.ncon):
317
+ c = d.contact[i]
318
+ for n, g in self.cube_gids.items():
319
+ other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None)
320
+ if other is None:
321
+ continue
322
+ if other in self.robot_gids:
323
+ out[n] = "robot"
324
+ elif other in self.lid_gids and out.get(n) != "robot":
325
+ out[n] = "lid"
326
+ return out
327
+
328
+ def monitor_step(self):
329
+ mon = self.mon
330
+ if mon is None:
331
+ return
332
+ mon["step"] += 1
333
+ step = self.sk.n_steps if self.sk is not None else mon["step"]
334
+ for n, who in self._touches().items():
335
+ if who == "robot":
336
+ mon["last_touch"][n] = step
337
+ if mon["step"] % 2:
338
+ return # predicates every other control step (0.1 s)
339
+ cov = self.covering()
340
+ if cov != mon["cover"]:
341
+ if mon["cover"] is not None and cov is None:
342
+ mon["events"].append(dict(step=step, pred="cover", ev="cover_removed", box=mon["cover"]))
343
+ mon["cover_removed_step"] = step
344
+ elif cov is not None:
345
+ mon["events"].append(dict(step=step, pred="cover", ev="cover_on_box", box=cov))
346
+ mon["cover"] = cov
347
+ for n in CUBES:
348
+ oc = self.on_cover(n, moving_ok=mon["on_cover"][n])
349
+ if oc != mon["on_cover"][n]:
350
+ mon["on_cover"][n] = oc
351
+ if oc:
352
+ mon["rested"].append(dict(step=step, cube=n))
353
+ mon["events"].append(dict(step=step, pred=f"{n}_on_cover", ev="rested_on_cover" if oc else "left_cover",
354
+ cube=n, box=cov))
355
+ key = f"{n}_in_box"
356
+ was = mon["state"][key]
357
+ now = self.in_box(n, _color(n), IN_MARGIN if not was else IN_MARGIN - 0.005)
358
+ if now != was:
359
+ self._event(key, now, step, n)
360
+ other = [c for c in COLORS if c != _color(n)][0]
361
+ wr = other if self.in_box(n, other) else None
362
+ if wr != mon["wrong"][n]:
363
+ mon["wrong"][n] = wr
364
+ if wr:
365
+ mon["events"].append(dict(step=step, pred=key, ev="in_wrong_box", cube=n, box=wr))
366
+
367
+ def _event(self, key, now, step, n):
368
+ mon = self.mon
369
+ mon["state"][key] = now
370
+ if now:
371
+ ev = "restored" if key in mon["lost"] else "achieved"
372
+ mon["ever"].add(key)
373
+ mon["lost"].discard(key)
374
+ mon["events"].append(dict(step=step, pred=key, ev=ev))
375
+ return
376
+ if self.held(n):
377
+ cause = "picked_up"
378
+ else:
379
+ lt = mon["last_touch"][n]
380
+ cause = "robot" if lt is not None and step - lt <= 60 else "other"
381
+ mon["lost"].add(key)
382
+ mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause))
383
+
384
+ # ------------------------------------------------------------ outcome
385
+ def _static(self):
386
+ d = self.env.sim.data
387
+ for name in CUBES + [LID]:
388
+ _, da = envs.free_joint_addr(self.env, name)
389
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
390
+ return False
391
+ return True
392
+
393
+ def outcome(self, inst):
394
+ envs.settle(self.env, 30)
395
+ mon = self.mon
396
+ vals = self.stage_values()
397
+ static = self._static()
398
+ held = [n for n in CUBES if self.held(n)]
399
+ on_cover = [n for n in CUBES if self.on_cover(n)]
400
+ wrong = [n for n in CUBES if not vals[f"{n}_in_box"] and self.where_box(n) is not None]
401
+ missing = [n for n in CUBES if not vals[f"{n}_in_box"]]
402
+ cov = self.covering()
403
+ success = bool(all(vals.values()) and static and not held)
404
+ failure = None
405
+ if not success:
406
+ failure = ("held" if held else "cube_on_cover" if on_cover else "wrong_box" if wrong else
407
+ "cube_not_in_box" if missing else "cover_on_box" if cov is not None else "not_static")
408
+ regress = [e for e in mon["events"] if e["ev"] == "lost"]
409
+ restored = [e for e in mon["events"] if e["ev"] == "restored"]
410
+ rested_cubes = sorted({r["cube"] for r in mon["rested"]})
411
+ parts = []
412
+ if success:
413
+ parts.append("All four cubes are in the boxes of their colour.")
414
+ for n in missing:
415
+ c = _color(n)
416
+ txt = f"A {c} cube is not in the {c} box: "
417
+ if n in held:
418
+ parts.append(txt + "it is still held by the gripper.")
419
+ continue
420
+ p = envs.obj_pos(self.env, n)
421
+ rel = self.cube_rel(n, c)
422
+ if n in on_cover:
423
+ txt += (f"it rests on a clear acrylic lid that lies on the {cov} box, "
424
+ f"{100 * (envs.obj_min_z(self.env, n) - Z - FLOOR_T):.1f} cm above the box floor")
425
+ elif self.where_box(n) is not None:
426
+ txt += f"it is in the {self.where_box(n)} box"
427
+ else:
428
+ h = envs.obj_min_z(self.env, n) - Z
429
+ txt += ("it lies on the table" if h < 0.005 else f"it lies {100 * h:.1f} cm above the table")
430
+ txt += f", its centre {_fb(rel[0])} and {_lr(rel[1])} of the {c} box's centre"
431
+ if n in rested_cubes and n not in on_cover:
432
+ txt += " (it had come to rest on the clear lid earlier)"
433
+ parts.append(txt + ".")
434
+ if cov is not None:
435
+ parts.append(f"A clear acrylic lid lies on the {cov} box.")
436
+ if not static and all(vals.values()) and not held:
437
+ parts.append("Something was still moving at the end.")
438
+ if mon["cover_removed_step"] is not None and cov is None:
439
+ parts.append("The clear lid was pushed off its box.")
440
+ out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
441
+ events=mon["events"], n_regressions=len(regress), n_restored=len(restored),
442
+ covered=inst["cover"], trap_fired=bool(mon["rested"]), n_rested_on_cover=len(mon["rested"]),
443
+ rested_cubes=rested_cubes, cover_removed=mon["cover_removed_step"] is not None,
444
+ cover_removed_step=mon["cover_removed_step"], cover_final=cov, on_cover_final=on_cover,
445
+ recovered_in_attempt=bool(mon["rested"]) and success,
446
+ cube_offsets_cm={n: (100 * self.cube_rel(n, _color(n))).round(1).tolist() for n in CUBES},
447
+ detail=" ".join(parts))
448
+ return out
449
+
450
+ # ------------------------------------------------------------ scripted policies (perfect perception)
451
+ def _grasp_yaw(self, name):
452
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
453
+ i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on)
454
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
455
+ return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
456
+
457
+ def _finger_axis(self, yaw):
458
+ """world xy direction along which the fingers close at gripper yaw `yaw` (Skills: yaw 0 = fingers along y)"""
459
+ return np.array([-np.sin(yaw), np.cos(yaw)])
460
+
461
+ def _clear_yaw(self, name, room=0.04):
462
+ """grasp yaw of the cube: the smallest wrist turn (within +-45 deg) unless one of the open fingertips (4.5 cm
463
+ either side) would come down within `room` of another cube's centre (cubes put side by side or pushed off on
464
+ the lid stand 1.5-2.5 cm apart); then the 90-deg turned grasp if it has more room"""
465
+ p = envs.obj_pos(self.env, name)[:2]
466
+ others = [envs.obj_pos(self.env, n)[:2] for n in CUBES if n != name]
467
+
468
+ def dmin(yaw):
469
+ a = self._finger_axis(yaw)
470
+ 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])
471
+
472
+ y0 = self._grasp_yaw(name)
473
+ if dmin(y0) >= room:
474
+ return y0
475
+ y1 = float((y0 + np.pi / 2 + np.pi / 2) % np.pi - np.pi / 2)
476
+ return y1 if dmin(y1) > dmin(y0) else y0
477
+
478
+ def pick(self, name, z_carry=Z_CARRY):
479
+ sk = self.sk
480
+ p = envs.obj_pos(self.env, name)
481
+ sk.set_gripper(False, steps=8)
482
+ sk.move_to([p[0], p[1], Z + max(z_carry, p[2] - Z + 0.06)], yaw=self._clear_yaw(name))
483
+ sk.move_to([p[0], p[1], p[2]], tol=0.003, max_steps=120)
484
+ sk.set_gripper(True, steps=15)
485
+ sk.move_to([p[0], p[1], Z + z_carry], speed=0.3)
486
+ if not self.held(name):
487
+ sk.set_gripper(False, steps=8)
488
+ return False
489
+ return True
490
+
491
+ def place_in(self, name, slot, drop=DROP, z_carry=Z_CARRY, noise=None):
492
+ """carry the held cube over its box (slot -1 / +1: 2.8 cm right / left of the centre) and release it with its
493
+ bottom `drop` above the rim"""
494
+ sk = self.sk
495
+ b = np.asarray(self.inst["boxes"][_color(name)], float)
496
+ d = b + [0.0, SLOT * slot] + (np.asarray(noise, float) if noise is not None else 0.0)
497
+ z_rel = Z + RIM + drop + CUBE_E / 2
498
+ sk.move_to([d[0], d[1], Z + z_carry], yaw=0.0)
499
+ sk.move_to([d[0], d[1], z_rel], tol=0.003, max_steps=120)
500
+ sk.set_gripper(False, steps=12)
501
+ sk.move_to([d[0], d[1], Z + z_carry])
502
+
503
+ def pick_place(self, name, slot, drop=DROP, noise=None):
504
+ if self.pick(name):
505
+ self.place_in(name, slot, drop=drop, noise=noise)
506
+ return True
507
+ return False
508
+
509
+ def remove_cover(self, direction=None, depth=PUSH_DEPTH, mode="edge"):
510
+ """push the lid off its box: closed gripper, fingertips `depth` below the lid's top face, start 3 cm outside
511
+ its near edge (mode "edge") or 3 cm inside it, pressing on the lid (mode "press": press and drag -- v2: does not
512
+ move the lid any more, see the module docstring), sweep
513
+ straight on until the lid has cleared the box (default: sideways, away from the other box), lift"""
514
+ cov = self.covering()
515
+ if cov is None:
516
+ return False
517
+ sk = self.sk
518
+ lp = self.lid_pos()
519
+ b = np.asarray(self.inst["boxes"][cov], float)
520
+ if direction is None:
521
+ o = np.asarray(self.inst["boxes"][[c for c in COLORS if c != cov][0]], float)
522
+ direction = (0.0, float(np.sign(b[1] - o[1])))
523
+ d = np.asarray(direction, float) / np.linalg.norm(direction)
524
+ back = LID_HALF + 0.03 if mode == "edge" else LID_HALF - 0.03
525
+ s = lp[:2] - d * back
526
+ top = lp[2] + LID_T / 2
527
+ z = top - depth + TIP
528
+ sk.set_gripper(True, steps=8)
529
+ sk.move_to([s[0], s[1], z + 0.08], yaw=float(np.arctan2(d[1], d[0]) - np.pi / 2))
530
+ sk.move_to([s[0], s[1], z], tol=0.003, max_steps=80)
531
+ # sweep until the lid's near edge is 3 cm beyond the box's far wall
532
+ need = float((b - lp[:2]) @ d) + BOX_OUT + back + 0.03
533
+ e = s + d * need
534
+ sk.move_to([e[0], e[1], z], speed=PUSH_SPEED, tol=0.006, max_steps=int(need / PUSH_SPEED / 0.05) + 80)
535
+ sk.move_to([e[0], e[1], z + 0.10], speed=0.2)
536
+ sk.set_gripper(False, steps=8)
537
+ sk.hold(10)
538
+ return self.covering() is None
539
+
540
+ def slots(self, order):
541
+ """slot of each cube: the first cube of a colour goes right of the centre, the second left"""
542
+ seen, out = {c: 0 for c in COLORS}, {}
543
+ for n in order:
544
+ out[n] = (-1, 1)[seen[_color(n)] % 2]
545
+ seen[_color(n)] += 1
546
+ return out
547
+
548
+ def wrist_fix(self, rounds=1):
549
+ """what a top-down check can see: cubes whose centre is not over the right box's outline (on the table, in
550
+ the other box, still held) get placed again; heights are not judged"""
551
+ for _ in range(rounds):
552
+ bad = []
553
+ for n in CUBES:
554
+ rel = self.cube_rel(n, _color(n))
555
+ if self.held(n) or np.max(np.abs(rel)) > BOX_OUT:
556
+ bad.append(n)
557
+ if not bad:
558
+ return
559
+ for n in bad:
560
+ if self.held(n):
561
+ self.sk.set_gripper(False, steps=12)
562
+ continue
563
+ self.pick_place(n, -1 if self.cube_rel(n, _color(n))[1] < 0 else 1)
564
+
565
+ def set_aside(self, name):
566
+ """pick the cube (e.g. off the lid) and put it down on the table where it started (that spot is free)"""
567
+ if not self.pick(name):
568
+ return False
569
+ sk = self.sk
570
+ x, y = self.inst["start"][name]
571
+ sk.move_to([x, y, Z + Z_CARRY], yaw=0.0)
572
+ sk.move_to([x, y, Z + CUBE_E / 2 + 0.004], tol=0.003, max_steps=120)
573
+ sk.set_gripper(False, steps=12)
574
+ sk.move_to([x, y, Z + Z_CARRY])
575
+ return True
576
+
577
+ def side_fix(self, rounds=2):
578
+ """the careful check (agentview / heights): every cube must be inside its box, below the rim; if cubes rest on
579
+ 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
580
+ standing on it -- the hand runs into them), push the lid off; then place every cube that is not in its box"""
581
+ for _ in range(rounds):
582
+ v = self.stage_values()
583
+ if all(v.values()):
584
+ return True
585
+ if not v["cover_off_boxes"]:
586
+ for n in CUBES:
587
+ if self.on_cover(n) or (self.covering() is not None and self._touching(self.cube_gids[n], self.lid_gids)):
588
+ self.set_aside(n)
589
+ self.remove_cover()
590
+ for n in CUBES:
591
+ if not self.in_box(n, _color(n)):
592
+ if self.held(n):
593
+ self.sk.set_gripper(False, steps=12)
594
+ continue
595
+ others = [m for m in CUBES if m != n and _color(m) == _color(n)]
596
+ rel_o = self.cube_rel(others[0], _color(n)) if others else np.zeros(2)
597
+ self.pick_place(n, 1 if rel_o[1] < 0 else -1)
598
+ return all(self.stage_values().values())
599
+
600
+ def execute(self, inst, params):
601
+ order = params.get("order") or list(CUBES)
602
+ noise = params.get("noise") or {}
603
+ drops = params.get("drops") or {}
604
+ if params["plan"] == "lid_first":
605
+ self.remove_cover(params.get("push_dir"), params.get("push_depth", PUSH_DEPTH), params.get("push_mode", "edge"))
606
+ sl = self.slots(order)
607
+ for n in order:
608
+ self.pick_place(n, sl[n], drop=drops.get(n, DROP), noise=noise.get(n))
609
+ if params.get("check") == "side":
610
+ self.side_fix()
611
+ elif params.get("check") == "wrist":
612
+ self.wrist_fix()
613
+ self.sk.hold(10)
614
+
615
+ def default_params(self, inst):
616
+ return dict(plan="naive", check="wrist")
617
+
618
+ def oracle_params(self, inst):
619
+ return dict(plan="lid_first", check="side")
620
+
621
+ def adapt_params(self, inst, history):
622
+ """from attempt 2 on: look for a lid and push it off first, then place, then check from the side"""
623
+ return dict(plan="lid_first", check="side")
624
+
625
+ def blind_params(self, inst, attempt, rng):
626
+ """the natural plan again with small random variations (order, 5 mm placement noise, 3-5 cm drop), no history"""
627
+ order = [CUBES[i] for i in rng.permutation(len(CUBES))]
628
+ return dict(plan="naive", check="wrist", order=order,
629
+ noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES},
630
+ drops={n: float(rng.uniform(0.03, 0.05)) for n in CUBES})
631
+
632
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
633
+ k = k or self.max_attempts
634
+ rng = np.random.default_rng(seed)
635
+ history = []
636
+ for a in range(k):
637
+ self.reset_instance(inst)
638
+ if kind == "oracle":
639
+ params = self.oracle_params(inst)
640
+ elif kind == "naive":
641
+ params = self.default_params(inst)
642
+ elif kind == "adaptive":
643
+ params = dict(plan="naive", check="side") if a == 0 else self.adapt_params(inst, history)
644
+ elif kind == "blind":
645
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
646
+ elif kind == "switch": # extra control (not in validate's table): cross-attempt learning only, no side check
647
+ params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check="wrist")
648
+ else:
649
+ raise ValueError(kind)
650
+ self.execute(inst, params)
651
+ out = self.outcome(inst)
652
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
653
+ if on_attempt:
654
+ on_attempt(a, params, out)
655
+ if out["success"] or kind in ("oracle", "naive"):
656
+ break
657
+ return history
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_order_dispatch.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Development composite: physically load two products and a card, then steer a weighted shipping tray.
2
+ L1 fixed calibration bias, L3 card edge strategy, L5 off-centre loaded push. Not in the main set.
3
+ """
4
+ import numpy as np
5
+ import copy
6
+ import xml.etree.ElementTree as ET
7
+ from .. import envs
8
+ from ..bddl import write_bddl
9
+ from ..objects import box_xml, register_generated
10
+ from ..task_base import LFFTask, register_task
11
+ from .l3_card_edge import CardEdge, card_xml, BOARD_HALF, BOARD_TOP, CARD_HALF, GRASP_OUT
12
+ from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, HALF,
13
+ MASS, MU, box_fit, box_corners, _yaw, _rot)
14
+
15
+ PRODUCTS = ('product_red_1', 'product_blue_1')
16
+ CARGO = PRODUCTS + ('card_1',)
17
+ PH = .014
18
+
19
+
20
+ def shipping_xml():
21
+ xml = long_box_xml('lff_dispatch_box')
22
+ parts=[]
23
+ for k,(p,h) in enumerate([((.042,0,.025),(.003,.11,.005)),((-.042,0,.025),(.003,.11,.005)),
24
+ ((0,.107,.032),(.039,.003,.012)),((0,-.107,.032),(.039,.003,.012))]):
25
+ parts.append(f'<geom name="dispatch_wall{k}" type="box" pos="{p[0]} {p[1]} {p[2]}" size="{h[0]} {h[1]} {h[2]}" group="0" mass=".001" friction=".5 .005 .0001" rgba=".6 .4 .2 1"/>')
26
+ return xml.replace(' </body>', '\n'.join(parts)+'\n </body>',1)
27
+
28
+
29
+ class DispatchSkills(PushSkills):
30
+ def __init__(self, env, task, bias, recorder=None):
31
+ super().__init__(env,bias=bias,recorder=recorder,target=task.target_xy(task.inst))
32
+ self.task=task
33
+ self.closes=[]
34
+ self.correction=np.zeros(3)
35
+ self.n_commands=0
36
+ def reported_eef_pos(self):
37
+ return self.eef_pos()-self.bias
38
+ def move_to(self,target,*args,**kwargs):
39
+ self.n_commands+=1
40
+ if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded")
41
+ rep=super().move_to(np.asarray(target)-self.correction,*args,**kwargs)
42
+ rep['pos']=np.round(self.reported_eef_pos(),4).tolist()
43
+ return rep
44
+ def _act(self,dpos,drot,grip):
45
+ super()._act(dpos,drot,grip)
46
+ self.task.monitor_step()
47
+ if self.n_steps*.05>=3*self.task.agent_max_steps:raise RuntimeError('dispatch simulation budget exceeded')
48
+ def set_gripper(self,close,steps=15):
49
+ self.n_commands+=1
50
+ if self.n_commands>self.task.agent_max_steps:raise RuntimeError("dispatch command budget exceeded")
51
+ ctx=self.task.close_context() if close and self.grip<0 else None
52
+ rep=super().set_gripper(close,steps)
53
+ if ctx is not None:
54
+ ctx.update(held=self.holding('card_1'),width=round(self.gripper_width(),4))
55
+ self.closes.append(ctx)
56
+ return rep
57
+
58
+
59
+ @register_task
60
+ class OrderDispatch(CardEdge,OffcenterPush):
61
+ name='lh_order_dispatch'
62
+ level='L1'
63
+ failure_causes=('L1','L3','L5')
64
+ failure_types=failure_causes
65
+ category='system_identification'
66
+ capabilities=('Perceive','Reason','Plan','Restore')
67
+ protocol='cross'
68
+ max_attempts=5
69
+ agent_max_steps=180
70
+ instruction=('Load both small products and the red order card into the brown shipping tray, while it is in '
71
+ 'the yellow loading rectangle. Then push the loaded tray with the closed gripper completely inside the green '
72
+ 'delivery rectangle. All three items must remain inside the tray, with the gripper open and clear.')
73
+ instruction_indirect=('Pack the two small coloured cubes and the thin red rectangle into the long brown '
74
+ 'container while the container is at its starting position, then push the loaded container with the closed '
75
+ 'gripper completely into the green marked area. Keep every item inside, and finish with the '
76
+ 'gripper open and clear.')
77
+ def make_bddl(self):
78
+ card=register_generated('LffDispatchCard',card_xml('lff_dispatch_card'))
79
+ board=register_generated('LffDispatchBoard',box_xml('lff_dispatch_board',BOARD_HALF,(.62,.45,.27,1),friction=(.3,.005,.0001)),free=False)
80
+ box=register_generated('LffDispatchBox',shipping_xml())
81
+ zone_xml=ET.fromstring(rect_frame_xml('lff_dispatch_zone'))
82
+ 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)))
83
+ body=zone_xml.find('worldbody/body/body')
84
+ for geom in load_xml.find('worldbody/body/body'):
85
+ q=np.fromstring(geom.get('pos','0 0 0'),sep=' ');q[0]-=.11;geom.set('pos',' '.join(map(str,q)));body.append(geom)
86
+ zone=register_generated('LffDispatchZone',ET.tostring(zone_xml,encoding='unicode'),free=False)
87
+ objs=[('card_1',card,'card_region',(-.305,.395,-.295,.405)),('box_1',box,'box_region',(-.255,-.005,-.245,.005))]
88
+ for k,o in enumerate(PRODUCTS):
89
+ 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))
90
+ objs.append((o,cat,'prod_region'+str(k),(-.305+.25*k,-.405,-.295+.25*k,-.395)))
91
+ 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))])
92
+ def __init__(self,cam_res=None):
93
+ LFFTask.__init__(self,cam_res)
94
+ self.board_bid=self.env.sim.model.body_name2id(self.env.fixtures_dict['board_1'].root_body)
95
+ self.inst=None;self.mon=None
96
+ def sample_instance(self,seed):
97
+ rng=np.random.default_rng(seed)
98
+ bx=-.18;by=.20
99
+ return dict(seed=int(seed),board_xy=[bx,by],card_xy=[bx,by],card_yaw=0.,card_along='x',
100
+ bin_xy=[-.21,-.08],box_xy=[-.21,-.08],target_dist=.11,
101
+ bias=[0.,float(rng.choice([-1,1])*.055),0.],com_offset=float(rng.choice([-1,1])*.06),
102
+ mechanisms={'L1':True,'L3':True,'L5':True})
103
+ def apply_instance(self,inst):
104
+ self.inst=inst
105
+ OffcenterPush.apply_instance(self,inst)
106
+ m=self.env.sim.model
107
+ m.body_pos[self.board_bid]=[*inst['board_xy'],envs.TABLE_Z+BOARD_HALF[2]]
108
+ m.body_quat[self.board_bid]=[1,0,0,0]
109
+ envs.set_obj_pose(self.env,'card_1',[*inst['card_xy'],BOARD_TOP+CARD_HALF[2]+.0003],yaw=inst['card_yaw'])
110
+ for k,o in enumerate(PRODUCTS):
111
+ envs.set_obj_pose(self.env,o,[-.25+.14*k,-.31,envs.TABLE_Z+PH+.001])
112
+ bid=envs.body_id(self.env,'box_1')
113
+ if not inst['mechanisms']['L5']:m.body_ipos[bid]=[0,0,0];envs.refit_bounds(self.env,bid)
114
+ if not inst['mechanisms']['L3']:
115
+ # Initial overhang removes the flat-card obstruction; reset-time placement only.
116
+ 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])
117
+ def reset_instance(self,inst,recorder=None):
118
+ self.mon=None;self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15)
119
+ self.sk=DispatchSkills(self.env,self,np.array(inst['bias']) if inst['mechanisms']['L1'] else np.zeros(3),recorder)
120
+ self.mon=dict(start_xy=self.card_pose()['xy'].copy(),max_lift=0.,max_overhang=0.,fell=False,
121
+ loaded=False,load_step=None,departed_unloaded=False,events=[],states={o:False for o in CARGO},l1_attempts=[])
122
+ self.sim0=0;self.ncmd=0;self.budget=None
123
+ return self.sk
124
+ def in_cargo(self,o,require_support=True):
125
+ 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')))
126
+ rel=R.T@(p[:2]-b[:2]);half=PH if o in PRODUCTS else 0.
127
+ # Full footprint containment, including card corners.
128
+ if o=='card_1':
129
+ rels=(self.card_corners()[:,:2]-b[:2])@R
130
+ footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104))
131
+ else:
132
+ rot=self.env.sim.data.body_xmat[envs.body_id(self.env,o)].reshape(3,3)
133
+ 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)])
134
+ rels=(corners[:,:2]-b[:2])@R
135
+ footprint=bool(np.all(np.abs(rels[:,0])<.039) and np.all(np.abs(rels[:,1])<.104))
136
+ 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)
137
+ return bool(footprint and (support or not require_support) and b[2]+.015<p[2]<b[2]+.065 and not self.sk.holding(o))
138
+ def in_bin(self):return self.in_cargo('card_1')
139
+ def monitor_step(self):
140
+ if self.mon is None:return
141
+ CardEdge.monitor_step(self)
142
+ if self.sk.n_steps%5:return
143
+ states={o:self.in_cargo(o) for o in CARGO}
144
+ for o,v in states.items():
145
+ if v!=self.mon['states'][o]:self.mon['events'].append(dict(step=self.sk.n_steps,item=o,event='achieved' if v else 'lost'))
146
+ self.mon['states']=states
147
+ box=envs.obj_pos(self.env,'box_1');yaw=_yaw(envs.obj_quat(self.env,'box_1'))
148
+ footprint=box_corners(box[:2],yaw)-np.asarray(self.inst['box_xy'])
149
+ at_start=bool(np.all(np.abs(footprint[:,0])<.10) and np.all(np.abs(footprint[:,1])<.15))
150
+ if self.mon['loaded'] and at_start and not all(self.in_cargo(o,require_support=False) for o in CARGO):
151
+ self.mon['loaded']=False
152
+ self.mon['load_step']=None
153
+ if all(states.values()) and at_start:
154
+ if self.mon['load_step'] is None:self.mon['load_step']=self.sk.n_steps
155
+ self.mon['loaded']=True
156
+ if not at_start and not self.mon['loaded']:self.mon['departed_unloaded']=True
157
+ def grasp_and_bin(self,xy,yaw,z_site,lift=.12):
158
+ sk=self.sk;sk.set_gripper(False,8)
159
+ sk.move_to([*xy,z_site+.08],yaw=yaw);sk.move_to([*xy,z_site],tol=.003,max_steps=120)
160
+ sk.set_gripper(True,15);sk.move_to([*xy,z_site+lift],speed=.2)
161
+ if not sk.holding('card_1'):sk.set_gripper(False,8);return False
162
+ b=envs.obj_pos(self.env,'box_1');sk.move_to([b[0],b[1],envs.TABLE_Z+.23],yaw=np.pi/2)
163
+ sk.hold(5)
164
+ offset=envs.obj_pos(self.env,'card_1')[:2]-sk.eef_pos()[:2]
165
+ goal=b[:2]-offset
166
+ sk.move_to([*goal,envs.TABLE_Z+.20])
167
+ sk.move_to([*goal,envs.TABLE_Z+.055],speed=.1)
168
+ sk.set_gripper(False,12);sk.move_to([b[0],b[1],envs.TABLE_Z+.22]);return True
169
+ def repair_card(self):
170
+ """Recover a card overhanging the shipping tray, with real finger motions."""
171
+ if self.in_cargo('card_1'):return True
172
+ p=self.card_pose();b=envs.obj_pos(self.env,'box_1')
173
+ axis=np.array([np.cos(p['yaw']),np.sin(p['yaw'])])
174
+ sign=1. if (p['xy']-b[:2])@axis>=0 else -1.
175
+ grasp=p['xy']+sign*.034*axis
176
+ floor=b[2]+HALF[2]
177
+ return self.grasp_and_bin(grasp,p['yaw'],floor-.003)
178
+ def load_product(self,o,k):
179
+ sk=self.sk;p=envs.obj_pos(self.env,o).copy();sk.set_gripper(False,8)
180
+ sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0)
181
+ approach_offset=(sk.eef_pos()[:2]-p[:2]).tolist()
182
+ sk.move_to([p[0],p[1],p[2]+.003],tol=.002,max_steps=120)
183
+ offset=(sk.eef_pos()[:2]-p[:2]).tolist()
184
+ sk.set_gripper(True,15);sk.move_to([p[0],p[1],envs.TABLE_Z+.19])
185
+ held=sk.holding(o)
186
+ 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))
187
+ if not held:sk.set_gripper(False,8);return False
188
+ b=envs.obj_pos(self.env,'box_1');xy=[b[0],b[1]+(-.075 if k==0 else .075)]
189
+ sk.move_to([*xy,envs.TABLE_Z+.20]);sk.move_to([*xy,envs.TABLE_Z+.058],speed=.1)
190
+ sk.set_gripper(False,12);sk.move_to([*xy,envs.TABLE_Z+.22]);return self.in_cargo(o)
191
+ def execute(self,inst,params):
192
+ if 'mode' not in params:
193
+ return OffcenterPush.execute(self,inst,params)
194
+ mode=params['mode'];self.sk.correction=np.asarray(params.get('correction',[0,0,0]),dtype=float)
195
+ for k,o in enumerate(PRODUCTS):
196
+ if not self.load_product(o,k):return
197
+ if mode=='adaptive':
198
+ self.sk.correction+=np.array([*self.mon['l1_attempts'][-1]['approach_offset'],0.])
199
+ if mode=='naive':
200
+ CardEdge.execute(self,inst,dict(mode='grasp'))
201
+ else:
202
+ CardEdge.execute(self,inst,dict(mode='edge',overhang=.03))
203
+ self.sk.hold(10)
204
+ if not all(self.in_cargo(o) for o in CARGO):return
205
+ if mode=='adaptive':
206
+ OffcenterPush.adaptive_attempt(self,inst,params.get('c',0.))
207
+ if not self.in_cargo('card_1'):self.repair_card()
208
+ else:OffcenterPush.execute(self,inst,dict(c=params.get('c',0.)))
209
+ p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.23]);self.sk.set_gripper(False,8)
210
+ def outcome(self,inst):
211
+ self.sk.hold(30)
212
+ 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))
213
+ cargo={o:self.in_cargo(o) for o in CARGO}
214
+ velocities=[]
215
+ for o in CARGO+('box_1',):
216
+ adr=self.env.sim.model.jnt_dofadr[self.env.sim.model.joint_name2id(self.env.objects_dict[o].joints[0])]
217
+ velocities.append(self.env.sim.data.qvel[adr:adr+6].copy())
218
+ static=all(np.linalg.norm(v[:3])<.01 and np.linalg.norm(v[3:])<.15 for v in velocities)
219
+ m=self.env.sim.model
220
+ robot=[g for g in range(m.ngeom) if (m.geom_id2name(g) or '').startswith(('robot0_','gripper0_'))]
221
+ touching=any(envs.contacts_between(self.env,robot,envs.obj_geom_ids(self.env,o)) for o in CARGO+('box_1',))
222
+ upright=envs.obj_upright_cos(self.env,'box_1')>.95
223
+ 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)
224
+ 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']]
225
+ 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),
226
+ failure=None if success else 'cargo' if not all(cargo.values()) else 'loading_order' if not self.mon['loaded'] else 'delivery',
227
+ stages={**cargo,'loaded_in_start':self.mon['loaded'],'delivery':fit['inside']},events=self.mon['events'],
228
+ l1_attempts=self.mon['l1_attempts'],card_closes=self.sk.closes,card_lift=self.mon['max_lift'],
229
+ box_moves=self.sk.box_moves,l5_triggered=bool(bad),yaw_deg=float(np.degrees(yaw)),
230
+ sim_s=self.sk.n_steps*.05,commands=self.sk.n_commands,touching=bool(touching),upright=bool(upright),
231
+ detail='Cargo in tray: '+str(cargo)+'; tray inside delivery rectangle: '+str(fit['inside'])+'.'))
232
+ def default_params(self,inst):return dict(mode='naive')
233
+ 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.)
234
+ def adapt_params(self,inst,history):
235
+ # Calibration estimate from the measured failed grasp, not hidden bias.
236
+ offsets=[x['offset'] for h in history for x in h['outcome']['l1_attempts']]
237
+ 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']]
238
+ corr=np.mean(calibrations[-2:],axis=0).tolist() if calibrations else history[-1]['params'].get('correction',[0,0,0])
239
+ moves=[m for h in history for m in h['outcome']['box_moves']]
240
+ return dict(mode='adaptive',correction=corr,c=self.bracket(moves))
241
+ def blind_params(self,inst,attempt,rng):return dict(mode='naive',correction=[*rng.normal(0,.005,2),0.])
242
+ def run_scripted(self,*args,**kwargs):return LFFTask.run_scripted(self,*args,**kwargs)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_parts_cart.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Composite prototype: physical tool retrieval, loading regression and asymmetric cart transport.
2
+
3
+ Not part of main_v1. See task_cards/lh_parts_cart.md for validation status.
4
+ Only reset_instance/apply_instance position objects; all reference actions use the public motion skills.
5
+ """
6
+ import copy
7
+ import numpy as np
8
+ from .. import envs
9
+ from ..bddl import write_bddl
10
+ from ..objects import register_generated, box_xml
11
+ from ..task_base import register_task
12
+ from .l3_tool import (UnderTableTool, low_table_xml, stick_xml, CUBE_HALF,
13
+ HANDLE_HALF, TOP_HALF)
14
+ from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml,
15
+ HALF, MASS, MU, BOX, _rot)
16
+
17
+
18
+ class CartSkills(PushSkills):
19
+ def __init__(self,*args,**kwargs):
20
+ super().__init__(*args,**kwargs)
21
+ self.robot_commands=0
22
+ def move_to(self,*args,**kwargs):
23
+ self.robot_commands+=1
24
+ return super().move_to(*args,**kwargs)
25
+ def set_gripper(self,*args,**kwargs):
26
+ self.robot_commands+=1
27
+ return super().set_gripper(*args,**kwargs)
28
+
29
+
30
+ @register_task
31
+ class PartsCart(UnderTableTool):
32
+ name = 'lh_parts_cart'
33
+ level = 'L4'
34
+ category = 'geometry_inference'
35
+ failure_causes = ('L4', 'L2', 'L5')
36
+ capabilities = ('Perceive', 'Reason', 'Plan', 'Restore')
37
+ protocol = 'cross'
38
+ agent_max_steps = 180
39
+ instruction = ('Use the wooden tool to retrieve the red part from under the low glass table. '
40
+ 'Load the red and blue parts on the two marks on the brown transport platform, '
41
+ 'then push the loaded platform with the closed gripper completely into the green parking area. '
42
+ 'At the end both parts must still be on their marks, and the gripper must be open and clear.')
43
+ instruction_indirect = instruction
44
+
45
+ def make_bddl(self):
46
+ cube = register_generated('LffPartsCartRed', box_xml('lff_parts_cart_red', (CUBE_HALF,)*3,(.85,.12,.12,1), density=300))
47
+ blue = register_generated('LffPartsCartBlue', box_xml('lff_parts_cart_blue', (CUBE_HALF,)*3,(.1,.2,.85,1), density=300))
48
+ stick_xml_text=stick_xml('lff_parts_cart_stick').replace('size="0.00800 0.02500 0.01000"','size="0.00800 0.00800 0.01000"')
49
+ stick = register_generated('LffPartsCartStick', stick_xml_text)
50
+ table_xml=low_table_xml('lff_parts_cart_table')
51
+ # Wider roof with legs outside the blocked cube's x-exit lane. This prevents a panel failure
52
+ # trapping the cube against a corner leg, which the existing standalone task did not test in-attempt.
53
+ table_xml=table_xml.replace('size="0.06000 0.06000 0.00500"','size="0.06000 0.07500 0.00500"')
54
+ for sx in (-.052,.052):
55
+ for sy in (-.052,.052):
56
+ table_xml=table_xml.replace(f'pos="{sx:.5f} {sy:.5f} 0.03500"',f'pos="{sx:.5f} {np.sign(sy)*.067:.5f} 0.03500"')
57
+ table = register_generated('LffPartsCartTable', table_xml, free=False)
58
+ xml=long_box_xml('lff_parts_cart_platform')
59
+ marks=''.join(f'<geom type="box" pos="0 {y} {HALF[2]+.0006}" size=".022 .022 .0003" rgba="{color}" contype="0" conaffinity="0" group="1" />' for y,color in [(-.03,'.9 .4 .4 1'),(.03,'.4 .5 .9 1')])
60
+ xml=xml.replace(' </body>',marks+' </body>',1)
61
+ cart = register_generated('LffPartsCartPlatform', xml)
62
+ zone = register_generated('LffPartsCartZone', rect_frame_xml('lff_parts_cart_zone'), free=False)
63
+ # Inertial/shape match existing off-centre box, with purely visual cargo marks.
64
+ objs=[('cube_1',cube,'red_region',(-.31,-.26,-.29,-.24)),
65
+ ('blue_1',blue,'blue_region',(-.31,.24,-.29,.26)),
66
+ ('stick_1',stick,'stick_region',(-.01,-.36,.01,-.34)),
67
+ ('box_1',cart,'cart_region',(.19,.24,.21,.26))]
68
+ fx=[('lowtable_1',table,'table_region',(.19,-.11,.21,-.09)),
69
+ ('zone_1',zone,'zone_region',(.19,.39,.21,.41))]
70
+ return write_bddl(self.name,self.instruction,objs,fx)
71
+
72
+ def sample_instance(self, seed):
73
+ # Tool geometry is inherited; put transport in the other half of the same tabletop.
74
+ rng=np.random.default_rng(seed)
75
+ base=super().sample_instance(seed)
76
+ base.update(side=-1, pane_side=1, table_xy=[-.08,-.08],cube_xy=[-.08,-.08],
77
+ stick_xy=[-.08,-.34],stick_yaw=np.pi/2,
78
+ box_xy=[-.25,.24],target_dist=.16,
79
+ com_offset=float(rng.choice([-1,1])*rng.uniform(.05,.065)),
80
+ traps=dict(L4=True,L2=True,L5=True))
81
+ base['bin_xy']=[-.25,.24] # inherited observe() only; no bin fixture.
82
+ return base
83
+
84
+ def target_xy(self, inst):
85
+ return np.array([inst['box_xy'][0]+inst['target_dist'],inst['box_xy'][1]])
86
+
87
+ def apply_instance(self, inst):
88
+ self.inst=inst
89
+ m=self.env.sim.model
90
+ bid,_=self._fixture('lowtable_1')
91
+ m.body_pos[bid]=[*inst['table_xy'],envs.TABLE_Z]
92
+ for g,sy in self._panes():
93
+ on=inst['traps']['L4'] and sy==inst['pane_side']
94
+ m.geom_contype[g]=m.geom_conaffinity[g]=int(on)
95
+ envs.set_obj_pose(self.env,'cube_1',[*inst['cube_xy'],envs.TABLE_Z+CUBE_HALF+.0005])
96
+ envs.set_obj_pose(self.env,'blue_1',[-.30,.04,envs.TABLE_Z+CUBE_HALF+.0005])
97
+ envs.set_obj_pose(self.env,'stick_1',[*inst['stick_xy'],envs.TABLE_Z+HANDLE_HALF[2]+.0005],yaw=inst['stick_yaw'])
98
+ bid=envs.body_id(self.env,BOX)
99
+ m.body_mass[bid]=MASS
100
+ m.body_ipos[bid]=[0,inst['com_offset'] if inst['traps']['L5'] else 0,0]
101
+ for g in range(m.ngeom):
102
+ if m.geom_bodyid[g]==bid and (np.allclose(m.geom_rgba[g,:3],[.9,.4,.4]) or np.allclose(m.geom_rgba[g,:3],[.4,.5,.9])):
103
+ m.geom_pos[g,1]=np.sign(m.geom_pos[g,1])*(.03 if inst['traps']['L2'] else .07)
104
+ envs.refit_bounds(self.env,bid)
105
+ envs.set_friction(self.env,BOX,MU)
106
+ envs.set_obj_pose(self.env,BOX,[*inst['box_xy'],envs.TABLE_Z+HALF[2]+.001])
107
+ zb=m.body_name2id(self.env.fixtures_dict['zone_1'].root_body)
108
+ m.body_pos[zb]=[*self.target_xy(inst),envs.TABLE_Z+.0002]
109
+
110
+ def reset_instance(self, inst, recorder=None):
111
+ self.loadmon=None
112
+ self._mon=None
113
+ self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15)
114
+ self.sk=CartSkills(self.env,recorder=recorder,target=self.target_xy(inst))
115
+ self._start_monitor()
116
+ self.loadmon=dict(states=[False,False],count=[0,0],ever=[False,False],lost=[False,False],events=[],loaded=False,departed_unloaded=False,load_step=None,departure_step=None,last_robot_touch=[-10000,-10000])
117
+ self.ncmd=0;self.budget=None
118
+ return self.sk
119
+
120
+ def mark(self,i):
121
+ p,yaw=self.sk._box_pose() if self.sk else (envs.obj_pos(self.env,BOX),0.)
122
+ spacing=.03 if self.inst['traps']['L2'] else .07
123
+ return p[:2]+_rot(yaw)@np.array([0.,(-spacing,spacing)[i]])
124
+
125
+ def cargo_ok(self,i):
126
+ obj=('cube_1','blue_1')[i]
127
+ p=envs.obj_pos(self.env,obj); bp=envs.obj_pos(self.env,BOX)
128
+ return bool(np.linalg.norm(p[:2]-self.mark(i))<.018 and
129
+ abs(p[2]-(bp[2]+HALF[2]+CUBE_HALF))<.012 and not self.sk.holding(obj))
130
+
131
+ def _monitor_step(self):
132
+ super()._monitor_step()
133
+ mon=getattr(self,'loadmon',None)
134
+ if mon is None:return
135
+ robot=set(envs.robot_geom_ids(self.env))
136
+ for i,obj in enumerate(('cube_1','blue_1')):
137
+ geoms=set(envs.obj_geom_ids(self.env,obj))
138
+ for c in self.env.sim.data.contact[:self.env.sim.data.ncon]:
139
+ if (c.geom1 in robot and c.geom2 in geoms) or (c.geom2 in robot and c.geom1 in geoms):
140
+ mon['last_robot_touch'][i]=self.sk.n_steps
141
+ now=self.cargo_ok(i)
142
+ if now==mon['states'][i]:mon['count'][i]=0;continue
143
+ mon['count'][i]+=1
144
+ if mon['count'][i]<5:continue
145
+ mon['count'][i]=0;mon['states'][i]=now
146
+ ev='restored' if now and mon['lost'][i] else 'achieved' if now else 'lost'
147
+ if now:mon['ever'][i]=True
148
+ else:
149
+ mon['lost'][i]=True
150
+ if np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])<.025:
151
+ mon['loaded']=False
152
+ mon['load_step']=None
153
+ mon['events'].append(dict(step=self.sk.n_steps,pred=('red','blue')[i],event=ev,
154
+ cart_displacement=float(np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])),
155
+ cause='robot' if self.sk.n_steps-mon['last_robot_touch'][i]<=20 else 'other'))
156
+ displacement=np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])
157
+ if all(mon['states']) and displacement<.02 and not mon['loaded']:
158
+ mon['loaded']=True
159
+ mon['load_step']=self.sk.n_steps
160
+ if displacement>.03 and mon['departure_step'] is None:
161
+ mon['departure_step']=self.sk.n_steps
162
+ if not mon['loaded']:mon['departed_unloaded']=True
163
+
164
+ def pick_place(self,obj,xy,yaw=0.):
165
+ sk=self.sk;p=envs.obj_pos(self.env,obj)
166
+ sk.set_gripper(False,steps=10)
167
+ sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0. if obj=='cube_1' and self.under_table(margin=.08) else yaw)
168
+ sk.move_to([p[0],p[1],p[2]-.004],speed=.10,tol=.002)
169
+ sk.set_gripper(True,steps=15)
170
+ held=sk.holding(obj)
171
+ sk.move_to([p[0],p[1],envs.TABLE_Z+.20],speed=.15)
172
+ if held:
173
+ sk.move_to([xy[0],xy[1],envs.TABLE_Z+.20],yaw=yaw)
174
+ bp=envs.obj_pos(self.env,BOX)
175
+ sk.move_to([xy[0],xy[1],bp[2]+HALF[2]+CUBE_HALF-.003],speed=.06,tol=.002)
176
+ sk.set_gripper(False,steps=15)
177
+ sk.move_to([xy[0],xy[1],envs.TABLE_Z+.22],speed=.15)
178
+ return bool(held)
179
+
180
+ def load(self, careful=True):
181
+ self.pick_place('cube_1',self.mark(0),np.pi/2)
182
+ # Open fingers along y at the adjacent mark can knock the already loaded red cube.
183
+ yaw=np.pi/2 if careful else 0.
184
+ self.pick_place('blue_1',self.mark(1),yaw)
185
+
186
+ def repair_load(self):
187
+ for _ in range(3):
188
+ for i,o in enumerate(('cube_1','blue_1')):
189
+ if not self.cargo_ok(i):self.pick_place(o,self.mark(i),np.pi/2)
190
+
191
+ def transport(self,c=0.,repair=False):
192
+ # Call existing push controller on this same environment; no independent rollout stitching.
193
+ if not repair:
194
+ return OffcenterPush.execute(self,self.inst,dict(c=c))
195
+ if repair:
196
+ # Original feedback-driven corrector calls self.execute for its initial push.
197
+ self._transport_only=True
198
+ try:OffcenterPush.adaptive_attempt(self,self.inst,c)
199
+ finally:self._transport_only=False
200
+
201
+ _cmd=OffcenterPush._cmd
202
+ _sim_used=OffcenterPush._sim_used
203
+ _push_at=OffcenterPush._push_at
204
+ bracket=OffcenterPush.bracket
205
+ _front_runup=staticmethod(OffcenterPush._front_runup)
206
+ STEP=OffcenterPush.STEP;YAW_OK=OffcenterPush.YAW_OK
207
+ GAIN0=OffcenterPush.GAIN0;SAFE_V=OffcenterPush.SAFE_V
208
+
209
+ def execute(self,inst,params):
210
+ if getattr(self,'_transport_only',False):return OffcenterPush.execute(self,inst,params)
211
+ if params.get('front',False):self.tool_push_front()
212
+ else:self.tool_push_out()
213
+ if self.under_table():return
214
+ self.load(params.get('careful',False))
215
+ if params.get('repair',False):self.repair_load()
216
+ if all(self.cargo_ok(i) for i in range(2)):
217
+ self.transport(params.get('c',0.),params.get('repair',False))
218
+ if params.get('repair',False):self.repair_load()
219
+ self.sk.set_gripper(False,steps=10)
220
+ p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.24])
221
+
222
+ def default_params(self,inst):return dict(front=False,careful=False,repair=False,c=0.)
223
+ def oracle_params(self,inst):return dict(front=True,careful=True,repair=True,c=inst['com_offset'] if inst['traps']['L5'] else 0.)
224
+ def adapt_params(self,inst,history):
225
+ # The L4 side hit is learned from actual prior outcome, not from inst['pane_side'].
226
+ seen_geometry=any(h['outcome']['traps']['L4'] for h in history)
227
+ seen_loading=any(h['outcome']['traps']['L2'] for h in history)
228
+ pushes=[m for h in history for m in h['outcome']['box_moves']]
229
+ return dict(front=seen_geometry,careful=seen_loading,repair=bool(history),c=self.bracket(pushes))
230
+
231
+ def outcome(self,inst):
232
+ self.sk.hold(30)
233
+ fit=self.sk.fit();cargo=[self.cargo_ok(i) for i in range(2)]
234
+ ev=list(self.loadmon['events'])
235
+ # Loading regressions count only while cart remains at the loading station.
236
+ load_lost=[e for e in ev if e['event']=='lost' and e['cart_displacement']<.025 and e['cause']=='robot']
237
+ loaded=self.loadmon['loaded']
238
+ static=bool(np.max(np.abs(self.env.sim.data.qvel))<.05)
239
+ robot=set(envs.robot_geom_ids(self.env)); items=set()
240
+ for o in ('cube_1','blue_1',BOX,'stick_1'):items.update(envs.obj_geom_ids(self.env,o))
241
+ touching=any((c.geom1 in robot and c.geom2 in items) or (c.geom2 in robot and c.geom1 in items)
242
+ for c in self.env.sim.data.contact[:self.env.sim.data.ncon])
243
+ budget_ok=bool(self.sk.robot_commands<=self.agent_max_steps and self.sk.n_steps*.05<=self.agent_max_steps*3)
244
+ success=bool(not self.under_table() and all(cargo) and fit['inside'] and loaded
245
+ and not self.loadmon['departed_unloaded'] and static and not touching and budget_ok and self.sk.grip<0
246
+ and self._mon['stick_touched_cube'])
247
+ moves=copy.deepcopy(self.sk.box_moves)
248
+ return dict(success=success,stages=dict(retrieved=not self.under_table(),red=cargo[0],blue=cargo[1],parked=fit['inside'],loaded=loaded),
249
+ static=static,touching=bool(touching),tool_used=bool(self._mon['stick_touched_cube']),load_step=self.loadmon['load_step'],departure_step=self.loadmon['departure_step'],commands=self.sk.robot_commands,budget_ok=budget_ok,departed_unloaded=self.loadmon['departed_unloaded'],
250
+ events=ev,n_regressions=len(load_lost),n_restored=sum(e['event']=='restored' for e in ev),
251
+ traps=dict(L4=bool(self._mon['cube_hit_pane']),L2=bool(load_lost),L5=any(m['bad'] for m in moves)),
252
+ box_moves=moves,cart_pose=[*envs.obj_pos(self.env,BOX).tolist()],cart_fit=fit,
253
+ detail=f'Retrieved={not self.under_table()}; cargo on marks={cargo}; platform parked={fit["inside"]}.')
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/ladder_plan.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-3 feedback ladder (user 2026-10-27; design docs/20). Same instances and records as the mismatched-history
2
+ control (scripts/mismatch_plan.py): the main-table attempt 1 of every Claude instance in the 9 twin tasks whose
3
+ attempt 1 failed. Fresh single-attempt agents (Claude Code B', jail, high, F1), README byte-identical to the Do arm;
4
+ only the Result section of history/README.md grows, one rung at a time:
5
+
6
+ F1 "The environment judged that attempt: failed." = the Do arm (do_<m>), not re-run
7
+ F2 + the measured error of that attempt (outcome.detail, axis labels stripped) batch lf2_<m>
8
+ hplus + "Cause: " the hidden variable (arm_specs reveal, as --arm hplus states it) batch lhp_<m>
9
+ fix + how to succeed (arm_specs fix, from the oracle parameters; results/_ladder/fix_validate.json) lfx_<m>
10
+
11
+ python scripts/ladder_plan.py build records -> runs/api/ladder_20261027/<m>/<rung>.json (+ tasks_<m>.txt)
12
+ python scripts/ladder_plan.py report per instance F1 / F2 / H+ / Fix, totals, adjacent paired counts
13
+ -> runs/api/ladder_20261027/report.json + markdown on stdout
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+ API = os.path.join(ROOT, "runs", "api")
23
+ SRC = os.path.join(API, "mismatch_20261027")
24
+ OUT = os.path.join(API, "ladder_20261027")
25
+ FIXV = os.path.join(ROOT, "results", "_ladder", "fix_validate.json")
26
+ MODELS = ("opus", "sonnet")
27
+ RUNGS = ("F2", "hplus", "fix")
28
+ BATCH = {"F1": "do", "F2": "lf2", "hplus": "lhp", "fix": "lfx"}
29
+ WITHIN = {"l2_turntable_restore"} # reported separately (docs/20 §2)
30
+
31
+
32
+ def events(log):
33
+ return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip()]
34
+
35
+
36
+ def texts(src, fixes):
37
+ """rung -> result_extra for one record source (the logged attempt 1)"""
38
+ from lffbench import arm_specs
39
+ from lffbench.agent.robot_server import strip_axes
40
+ ev = events(src["log"])
41
+ start = next(e for e in ev if e["ev"] == "session_start")
42
+ done = next(e for e in ev if e["ev"] == "done" and e.get("attempt") == 1)
43
+ detail = strip_axes((done.get("outcome") or {}).get("detail") or "").strip()
44
+ if not detail:
45
+ raise SystemExit(f"{src['task']}:{src['seed']}: attempt 1 has no outcome detail for F2")
46
+ cause = "Cause: " + strip_axes(arm_specs.reveal(start["task"], start["inst"]).strip())
47
+ fx = fixes.get(f"{start['task']}:{start['seed']}")
48
+ if fx is None or not fx["ok"]:
49
+ raise SystemExit(f"{start['task']}:{start['seed']}: no validated fix text in {FIXV}")
50
+ return {"F2": detail, "hplus": detail + "\n\n" + cause, "fix": detail + "\n\n" + cause + "\n\n" + fx["fix"]}
51
+
52
+
53
+ def cmd_build():
54
+ fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
55
+ for m in MODELS:
56
+ own = json.load(open(os.path.join(SRC, m, "own.json")))
57
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
58
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(own) + "\n")
59
+ out = {r: {} for r in RUNGS}
60
+ for key, d in own.items():
61
+ src = json.load(open(d + ".source.json"))
62
+ tx = texts(src, fixes)
63
+ for r in RUNGS:
64
+ dst = os.path.join(OUT, m, r, f"{src['task']}_s{src['seed']}")
65
+ if not os.path.isdir(dst):
66
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), src["log"],
67
+ dst, "--result-extra", tx[r]], check=True, capture_output=True)
68
+ out[r][key] = dst
69
+ for r in RUNGS:
70
+ json.dump(out[r], open(os.path.join(OUT, m, f"{r}.json"), "w"), indent=1)
71
+ print(m, len(own), "instances x", len(RUNGS), "rungs")
72
+
73
+
74
+ def single(batch):
75
+ """task:seed -> True / False (attempt 1 of the batch's done run)"""
76
+ out = {}
77
+ p = os.path.join(API, batch, "manifest.json")
78
+ if not os.path.exists(p):
79
+ return out
80
+ for r in json.load(open(p))["runs"]:
81
+ if r["status"] != "done":
82
+ continue
83
+ d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
84
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
85
+ return out
86
+
87
+
88
+ def cmd_report():
89
+ rep, md = {}, []
90
+ order = ("F1", "F2", "hplus", "fix")
91
+ f = lambda v: "-" if v is None else ("S" if v else "F")
92
+ for m in MODELS:
93
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
94
+ res = {r: single(f"{BATCH[r]}_{m}") for r in order}
95
+ rows = [dict(inst=k, within=k.split(":")[0] in WITHIN, **{r: res[r].get(k) for r in order}) for k in want]
96
+ tot = {}
97
+ for part, sub in (("all", rows), ("cross", [r for r in rows if not r["within"]]),
98
+ ("within", [r for r in rows if r["within"]])):
99
+ tot[part] = {r: [sum(x[r] for x in sub if x[r] is not None), sum(x[r] is not None for x in sub)] for r in order}
100
+ steps = {}
101
+ cross = [r for r in rows if not r["within"]]
102
+ for lo, hi in zip(order, order[1:]):
103
+ both = [r for r in cross if r[lo] is not None and r[hi] is not None]
104
+ steps[f"{lo}->{hi}"] = dict(n=len(both), up=sum(r[hi] and not r[lo] for r in both),
105
+ down=sum(r[lo] and not r[hi] for r in both))
106
+ rep[m] = dict(rows=rows, totals=tot, steps=steps)
107
+ md += [f"### {m}", "", "| instance | F1 | F2 | H+ | Fix |", "|---|---|---|---|---|"]
108
+ md += [f"| {r['inst']}{' (within)' if r['within'] else ''} | " + " | ".join(f(r[x]) for x in order) + " |"
109
+ for r in rows]
110
+ for part in ("cross", "within"):
111
+ md.append(f"{part}: " + ", ".join(f"{x} {tot[part][x][0]}/{tot[part][x][1]}" for x in order))
112
+ md.append("adjacent (cross, paired): " + "; ".join(f"{k} n={v['n']} up {v['up']} down {v['down']}"
113
+ for k, v in steps.items()))
114
+ md.append("")
115
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
116
+ print("\n".join(md))
117
+
118
+
119
+ if __name__ == "__main__":
120
+ {"build": cmd_build, "report": cmd_report}[sys.argv[1]]()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/start_robot_session.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Start a robot server + isolated sandbox for one task instance.
3
+ # usage: scripts/start_robot_session.sh <task> <seed> <memory full|none> <feedback F0|F1|F2> <port> [instruction direct|indirect] [k] [tag] [perception depth|rgb] [video 0|1]
4
+ # The sandbox gets an opaque random name (no task / condition in the path); the readable run name is only in LOG.
5
+ set -e
6
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
7
+ TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}; PERC=${9:-depth}; VID=${10:-0}
8
+ RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT}
9
+ SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))')
10
+ LOG=${LFF_RUNS_DIR:-$ROOT/runs/claude}/$RUN
11
+ mkdir -p "$SANDBOX" "$LOG"
12
+ cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1
13
+ KARG=""; [ -n "$K" ] && KARG="--k $K"
14
+ VARG=""; [ "$VID" = "1" ] && VARG="--video $LOG/rollout.mp4"
15
+ nohup python -m lffbench.agent.robot_server --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \
16
+ --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --perception "$PERC" --style "${LFF_STYLE:-v1}" ${LFF_EXTRA_ARGS:-} $KARG $VARG > "$LOG/server.log" 2>&1 &
17
+ echo $! > "$LOG/server.pid"
18
+ # wait for the scene (long-horizon scenes on a loaded machine took > 2 min, 2026-10-20); on failure stop the server
19
+ # so that it does not keep the port
20
+ for i in $(seq 1 "${LFF_SERVER_WAIT_S:-600}"); do [ -f "$LOG/READY" ] && break; sleep 1; done
21
+ [ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; kill "$(cat "$LOG/server.pid")" 2>/dev/null; exit 1; }
22
+ echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json"
23
+ echo "SANDBOX=$SANDBOX"
24
+ echo "LOG=$LOG"
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-sonnet-5-5|high",
3
+ "fingerprint_sha256": "a8c04b0dca902885e52e7e5680c1cf8b782469e79c518f83b72249342285bfb0",
4
+ "written": "2026-10-21 05:19:29",
5
+ "summary": {
6
+ "system_chars": 5629,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "claude-sonnet-5-5"
14
+ }
15
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/tasks/l1_height.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L1-B height_bias: pick up a thin tile from the top of a wooden block and put it on the plate, with an arm whose
2
+ vertical calibration is off.
3
+
4
+ Category system_identification (level L1, action fine-tuning): the method (top-down pick across the tile's short
5
+ side with the fingertips just above the block's top, carry, release above the plate) and the scene understanding
6
+ are right; only the robot's own vertical execution is off.
7
+
8
+ Hidden variable: a fixed vertical calibration offset dz ~ U[2.0, 3.5] cm (always upward), added to every
9
+ commanded gripper position (`Skills(bias=(0, 0, dz))`): the gripper stops dz higher than commanded. The agent never
10
+ sees dz; positions reported back to it are in the commanded frame (`HeightSkills.reported_eef_pos`, and the agent
11
+ harness reports eef - bias), so the robot "believes" it reached the commanded height.
12
+
13
+ Why the prior fails: the tile is 1.0 cm thick. Sent to the right height (fingertips just above the block's top), the
14
+ fingertips actually stop 2-3.5 cm higher, i.e. 1.1-2.6 cm above the tile's top face, and the jaws close in the air
15
+ above it (measured tolerance, 6 layouts: upward errors up to 0.4 cm still grasp, >= 0.7 cm never do, i.e. the fingers
16
+ must overlap the tile by ~4 mm). dz >= 2 cm also defeats a prior that aims lower: even with the grasp point commanded
17
+ level with the block's top (fingertips ~1 cm into the block), the fingertips end up >= 1.05 cm above the block's
18
+ top, i.e. not below the tile's top face -> missed.
19
+ Visible in the agentview image (gap between the closed fingers and the tile) and in the wrist image (fingers closed
20
+ over the tile).
21
+ A downward error would not fail (the fingertips land on the block's top and the compliant OSC still closes on the
22
+ tile; measured for -1 and -2 cm), so the offset is upward only.
23
+
24
+ Why a raised block: the agent's move_to clips commanded targets to >= table + 0.5 cm. With the tile on the table,
25
+ compensating a 2-3.5 cm upward offset would need commands below the table top, which the interface refuses; on a
26
+ 6-10 cm block the compensated commands stay well inside the workspace.
27
+
28
+ What has to be learned: F2 reports how far above the tile's top face the grasp point and the fingertips were when the
29
+ jaws closed. Compared with where the policy meant to put them, that is dz itself, so after one failure dz can be
30
+ estimated and subtracted from every commanded height (pick and place alike).
31
+ """
32
+ import re
33
+
34
+ import numpy as np
35
+
36
+ from .. import envs
37
+ from ..bddl import write_bddl
38
+ from ..objects import box_xml, register_generated
39
+ from ..skills import Skills
40
+ from ..task_base import LFFTask, register_task
41
+
42
+ TILE, STAND, PLATE = "tile_1", "stand_1", "plate_1"
43
+ DISTRACTORS = ("butter_1", "chocolate_pudding_1")
44
+ FREE_OBJECTS = (TILE, PLATE) + DISTRACTORS
45
+ NAMES = {TILE: "red tile", STAND: "wooden block", PLATE: "plate", "butter_1": "butter",
46
+ "chocolate_pudding_1": "chocolate pudding"}
47
+ DESCR = {TILE: "thin red slab", STAND: "large wooden pedestal", PLATE: "round white dish", "butter_1": "small orange box",
48
+ "chocolate_pudding_1": "brown box"}
49
+
50
+ TILE_HALF = (0.040, 0.0225, 0.005) # 8.0 x 4.5 x 1.0 cm (long side along the tile's x axis)
51
+ TILE_T = 2 * TILE_HALF[2]
52
+ STAND_HALF_XY = (0.075, 0.085) # 15 x 17 cm top
53
+ STAND_H_RANGE = (0.06, 0.10)
54
+ MASS = {TILE: 0.072, "butter_1": 0.250, "chocolate_pudding_1": 0.200, PLATE: 0.350}
55
+
56
+ FINGER_BELOW_SITE = 0.0095 # lowest point of the finger collision meshes below the grasp site (measured 0.95 cm)
57
+ SITE_ABOVE_SURFACE = 0.0105 # scripted grasp height: grasp point 1.05 cm above the block top (fingertips ~1 mm above)
58
+ CARRY_ABOVE = 0.12 # carry height above the block top
59
+ RELEASE_GAP = 0.012 # tile bottom this far above the plate's rim at release
60
+ PLATE_R_OK = 0.040 # success: tile centre within this horizontal distance of the plate centre
61
+ DZ_MIN, DZ_MAX = 0.020, 0.035
62
+ TILE_YAW_MAX = np.deg2rad(40)
63
+ HOME_XY = np.array([-0.21, 0.0])
64
+
65
+
66
+ def _seg_dist(p, a, b):
67
+ ab = b - a
68
+ u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
69
+ return float(np.linalg.norm(a + u * ab - p))
70
+
71
+
72
+ def _q(axis, a):
73
+ h = a / 2
74
+ return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
75
+
76
+
77
+ def _qmul(a, b):
78
+ w1, x1, y1, z1 = a
79
+ w2, x2, y2, z2 = b
80
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
81
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
82
+
83
+
84
+ def dir_words(dx, dy):
85
+ """Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
86
+ parts = []
87
+ if abs(dy) >= 0.0005:
88
+ parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
89
+ if abs(dx) >= 0.0005:
90
+ parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
91
+ return " and ".join(parts) if parts else "exactly at the position"
92
+
93
+
94
+ def vert_words(h, what):
95
+ if h >= 0.0005:
96
+ return f"{100 * h:.1f} cm above {what}"
97
+ if h <= -0.0005:
98
+ return f"{100 * -h:.1f} cm below {what}"
99
+ return f"level with {what}"
100
+
101
+
102
+ class HeightSkills(Skills):
103
+ """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent)."""
104
+
105
+ def __init__(self, env, bias=None, recorder=None, stand_geoms=()):
106
+ super().__init__(env, bias=bias, recorder=recorder)
107
+ self.events = []
108
+ m = env.sim.model
109
+ self._finger_geoms = {
110
+ side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]]
111
+ for side in ("left_finger", "right_finger")}
112
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
113
+ self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS}
114
+ self._obj_geoms[STAND] = list(stand_geoms)
115
+ self.tile_z0 = float(envs.obj_pos(env, TILE)[2])
116
+ self.tile_zmax = self.tile_z0
117
+ self.tile_ref = envs.obj_pos(env, TILE) # tile position before the fingers last touched it
118
+ self.tile_ref_yaw = self.tile_yaw()
119
+
120
+ def reported_eef_pos(self):
121
+ """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything shown to
122
+ the agent must use this, never eef_pos(), which is the true position and reveals the bias."""
123
+ return self.eef_pos() - self.bias
124
+
125
+ def move_to(self, target, *args, **kwargs):
126
+ rep = super().move_to(target, *args, **kwargs)
127
+ rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist()
128
+ return rep
129
+
130
+ def touching(self):
131
+ return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
132
+
133
+ def holding_tile(self):
134
+ """Both fingers in contact with the tile (robosuite's _check_grasp needs the finger *pads*, which miss a
135
+ 1 cm tile when it is gripped low on the finger meshes)."""
136
+ tg = self._obj_geoms[TILE]
137
+ return all(envs.contacts_between(self.env, gs, tg) for gs in self._finger_geoms.values())
138
+
139
+ def holding(self, obj_name):
140
+ """The agent harness reports `holding_object` through this; use the finger-contact test for the tile so a
141
+ tile gripped low on the fingers is not reported as dropped."""
142
+ if obj_name == TILE:
143
+ return self.holding_tile()
144
+ return super().holding(obj_name)
145
+
146
+ def tile_yaw(self):
147
+ xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3)
148
+ return float(np.arctan2(xmat[1, 0], xmat[0, 0]))
149
+
150
+ def finger_min_z(self):
151
+ return float(self.eef_pos()[2] - FINGER_BELOW_SITE)
152
+
153
+ def _act(self, dpos, drot, grip):
154
+ super()._act(dpos, drot, grip)
155
+ self.tile_zmax = max(self.tile_zmax, float(envs.obj_pos(self.env, TILE)[2]))
156
+ if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[TILE]):
157
+ self.tile_ref = envs.obj_pos(self.env, TILE)
158
+ self.tile_ref_yaw = self.tile_yaw()
159
+
160
+ def set_gripper(self, close, steps=15):
161
+ if close and self.grip < 0:
162
+ self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), finger_z=self.finger_min_z(),
163
+ tile=envs.obj_pos(self.env, TILE).tolist(),
164
+ tile_ref=np.asarray(self.tile_ref).tolist(), tile_ref_yaw=self.tile_ref_yaw,
165
+ touching=self.touching(),
166
+ step=self.n_steps))
167
+ elif not close and self.grip > 0 and self.holding_tile():
168
+ self.events.append(dict(kind="release", eef=self.eef_pos().tolist(),
169
+ tile=envs.obj_pos(self.env, TILE).tolist(),
170
+ plate=envs.obj_pos(self.env, PLATE).tolist(), step=self.n_steps))
171
+ return super().set_gripper(close, steps)
172
+
173
+
174
+ @register_task
175
+ class HeightBias(LFFTask):
176
+ name = "l1_height_bias"
177
+ level = "L1"
178
+ category = "system_identification"
179
+ capabilities = ("Perceive", "Utilize")
180
+ protocol = "cross"
181
+ instruction = "Pick up the red tile from the top of the wooden block and put it on the plate."
182
+ instruction_indirect = ("Pick up the thin flat red slab lying on the large wooden pedestal and put it on the "
183
+ "round white dish.")
184
+ pick_lift_min = 0.03
185
+
186
+ # ------------------------------------------------------------ scene
187
+ def make_bddl(self):
188
+ tile = register_generated("LffHbTile", box_xml("lff_hb_tile", TILE_HALF, (0.80, 0.16, 0.12, 1.0),
189
+ density=2000))
190
+ stand = register_generated("LffHbStand", box_xml("lff_hb_stand", STAND_HALF_XY + (STAND_H_RANGE[1] / 2,),
191
+ (0.62, 0.47, 0.30, 1.0), density=1000), free=False)
192
+ objs = [(TILE, tile, "tile_region", (-0.21, -0.26, -0.19, -0.24)),
193
+ (PLATE, "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26)),
194
+ ("butter_1", "butter", "butter_region", (-0.21, 0.24, -0.19, 0.26)),
195
+ ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.15, -0.26, 0.17, -0.24))]
196
+ fx = [(STAND, stand, "stand_region", (0.09, -0.01, 0.11, 0.01))]
197
+ return write_bddl(self.name, self.instruction, objs, fx)
198
+
199
+ def __init__(self, cam_res=None):
200
+ super().__init__(cam_res)
201
+ self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS}
202
+ m = self.env.sim.model
203
+ bid = m.body_name2id(self.env.fixtures_dict[STAND].root_body)
204
+
205
+ def under(b):
206
+ while b > 0:
207
+ if b == bid:
208
+ return True
209
+ b = m.body_parentid[b]
210
+ return False
211
+
212
+ self._stand_bid = bid
213
+ self._stand_geoms = [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]
214
+
215
+ def _place(self, name, xy, yaw, z0=envs.TABLE_Z):
216
+ q = _qmul(_q("z", yaw), self._base_quat[name])
217
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q)
218
+ self.env.sim.forward()
219
+ qa, _ = envs.free_joint_addr(self.env, name)
220
+ self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005)
221
+ self.env.sim.forward()
222
+
223
+ def sample_instance(self, seed):
224
+ rng = np.random.default_rng(seed)
225
+ while True:
226
+ s = np.array([rng.uniform(-0.10, 0.02), rng.uniform(-0.17, 0.17)])
227
+ plate = np.array([rng.uniform(-0.17, 0.08), rng.uniform(-0.25, 0.25)])
228
+ if np.linalg.norm(plate - s) < 0.24 or abs(plate[1] - s[1]) < 0.12:
229
+ continue # not right behind the block as seen from the front camera
230
+ placed = [s, plate]
231
+ dis = {}
232
+ for name in DISTRACTORS:
233
+ for _ in range(300):
234
+ p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)])
235
+ if np.linalg.norm(p - s) < 0.16 or any(np.linalg.norm(p - o) < 0.12 for o in placed[1:]):
236
+ continue
237
+ if any(_seg_dist(p, a, b) < 0.09 for a, b in ((s, plate), (HOME_XY, s))):
238
+ continue
239
+ break
240
+ else:
241
+ break
242
+ placed.append(p)
243
+ dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
244
+ if len(dis) == len(DISTRACTORS):
245
+ break
246
+ stand_h = float(rng.uniform(*STAND_H_RANGE))
247
+ tile_xy = s + rng.uniform(-0.02, 0.02, 2)
248
+ tile_yaw = float(rng.uniform(-TILE_YAW_MAX, TILE_YAW_MAX))
249
+ dz = float(rng.uniform(DZ_MIN, DZ_MAX))
250
+ return dict(seed=int(seed), stand_xy=s.round(5).tolist(), stand_h=stand_h, tile_xy=tile_xy.round(5).tolist(),
251
+ tile_yaw=tile_yaw, plate_xy=plate.round(5).tolist(), distractors=dis, bias=[0.0, 0.0, dz],
252
+ bias_dz=dz)
253
+
254
+ def stand_top(self, inst):
255
+ return envs.TABLE_Z + inst["stand_h"]
256
+
257
+ def apply_instance(self, inst):
258
+ m = self.env.sim.model
259
+ h = inst["stand_h"]
260
+ for g in self._stand_geoms:
261
+ m.geom_size[g, 2] = h / 2
262
+ m.body_pos[self._stand_bid] = [inst["stand_xy"][0], inst["stand_xy"][1], envs.TABLE_Z + h / 2]
263
+ m.body_quat[self._stand_bid] = [1, 0, 0, 0]
264
+ for name, mass in MASS.items():
265
+ envs.scale_mass(self.env, name, mass)
266
+ self.env.sim.forward()
267
+ self._place(TILE, inst["tile_xy"], inst["tile_yaw"], z0=self.stand_top(inst))
268
+ self._place(PLATE, inst["plate_xy"], 0.0)
269
+ for name, v in inst["distractors"].items():
270
+ self._place(name, v["xy"], v["yaw"])
271
+
272
+ def skill_bias(self, inst):
273
+ return np.array(inst["bias"], float)
274
+
275
+ def reset_instance(self, inst, recorder=None):
276
+ self.env.reset()
277
+ self.apply_instance(inst)
278
+ self.env.sim.forward()
279
+ envs.settle(self.env, 10)
280
+ self.sk = HeightSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, stand_geoms=self._stand_geoms)
281
+ self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS}
282
+ return self.sk
283
+
284
+ # ------------------------------------------------------------ outcome
285
+ def plate_rim_z(self):
286
+ lo, hi = self._aabb(PLATE)
287
+ return float(hi[2])
288
+
289
+ def _aabb(self, name):
290
+ m, d = self.env.sim.model, self.env.sim.data
291
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
292
+ for g in envs.obj_geom_ids(self.env, name):
293
+ R = d.geom_xmat[g].reshape(3, 3)
294
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
295
+ hh = np.abs(R) @ m.geom_aabb[g, 3:]
296
+ lo, hi = np.minimum(lo, c - hh), np.maximum(hi, c + hh)
297
+ return lo, hi
298
+
299
+ def on_plate(self):
300
+ p = envs.obj_pos(self.env, PLATE)
301
+ t = envs.obj_pos(self.env, TILE)
302
+ return bool(np.linalg.norm(t[:2] - p[:2]) < PLATE_R_OK and t[2] < self.plate_rim_z() + 0.015
303
+ and envs.obj_upright_cos(self.env, PLATE) > 0.9 and envs.obj_min_z(self.env, PLATE) < envs.TABLE_Z + 0.01)
304
+
305
+ def outcome(self, inst):
306
+ envs.settle(self.env, 40)
307
+ sk = self.sk
308
+ top = self.stand_top(inst)
309
+ p = envs.obj_pos(self.env, PLATE)
310
+ t = envs.obj_pos(self.env, TILE)
311
+ held = sk.holding_tile()
312
+ success = bool(self.on_plate() and not held)
313
+ picked = sk.tile_zmax > sk.tile_z0 + self.pick_lift_min
314
+ closes = [e for e in sk.events if e["kind"] == "close"]
315
+ last_close = closes[-1] if closes else None
316
+ releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
317
+ end_off = t[:2] - p[:2]
318
+ on_stand = bool(t[2] > top - 0.005)
319
+ out = dict(success=success, picked=bool(picked), held_at_end=bool(held), tile_end=t.round(4).tolist(),
320
+ plate_end=p.round(4).tolist(), end_offset=end_off.round(4).tolist(), grasp_height=None,
321
+ fingertip_gap=None, grasp_xy_offset=None, touched_at_close=None, release_offset=None)
322
+ grasp_txt = ""
323
+ over_tile = True
324
+ if last_close is not None:
325
+ tile_top = last_close["tile_ref"][2] + TILE_HALF[2]
326
+ gh = last_close["eef"][2] - tile_top
327
+ fg = last_close["finger_z"] - tile_top
328
+ go = np.array(last_close["eef"][:2]) - np.array(last_close["tile_ref"][:2])
329
+ a = last_close.get("tile_ref_yaw", 0.0)
330
+ along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)]
331
+ # grasp point over the tile's footprint (the open fingers straddle it across its short side)
332
+ over_tile = bool(abs(along) <= TILE_HALF[0] and abs(across) <= TILE_HALF[1] + 0.01)
333
+ out["grasp_height"] = round(gh, 4)
334
+ out["fingertip_gap"] = round(fg, 4)
335
+ out["grasp_xy_offset"] = go.round(4).tolist()
336
+ out["grasp_over_tile"] = over_tile
337
+ out["touched_at_close"] = last_close["touching"]
338
+ face = "the top face of the red tile" if over_tile else "the level of the red tile's top face"
339
+ grasp_txt = (f"When the jaws closed, the grasp point (midway between the fingertips) was "
340
+ f"{vert_words(gh, face)} and the lowest points of the fingertips "
341
+ f"were {vert_words(fg, 'it')} (the tile is {100 * TILE_T:.1f} cm thick)")
342
+ if not over_tile or np.linalg.norm(go) >= 0.01:
343
+ grasp_txt += (f"; horizontally the grasp point was {dir_words(*go)} of the tile's centre"
344
+ + ("" if over_tile else ", i.e. not over the tile"))
345
+ if success:
346
+ out["failure"] = None
347
+ detail = "The red tile is on the plate."
348
+ if grasp_txt:
349
+ detail += f" {grasp_txt}."
350
+ elif not picked:
351
+ out["failure"] = "missed_grasp"
352
+ if last_close is None:
353
+ detail = "The gripper never closed; the red tile was not picked up."
354
+ else:
355
+ touch = last_close["touching"]
356
+ if not over_tile and TILE not in touch:
357
+ why = " The gripper was not over the tile when it closed."
358
+ elif fg > 0.0005 and TILE not in touch:
359
+ why = " The fingers closed in the air above the tile without touching it."
360
+ elif STAND in touch and TILE not in touch:
361
+ why = " The fingertips were pressed on the top of the wooden block but did not grip the tile."
362
+ elif TILE in touch:
363
+ why = " The fingers touched the tile but did not get a grip on it."
364
+ else:
365
+ why = ""
366
+ where = "still on the wooden block" if on_stand else "no longer on the wooden block"
367
+ detail = f"{grasp_txt}, and the tile was not picked up.{why} The tile is {where}."
368
+ elif held:
369
+ out["failure"] = "not_released"
370
+ detail = f"{grasp_txt}, and the tile was picked up, but it is still in the gripper."
371
+ elif releases:
372
+ r = releases[-1]
373
+ out["release_offset"] = (np.array(r["tile"][:2]) - np.array(r["plate"][:2])).round(4).tolist()
374
+ out["failure"] = "missed_place"
375
+ detail = (f"{grasp_txt}, and the tile was picked up. When the gripper opened, the tile was "
376
+ f"{dir_words(*out['release_offset'])} of the plate's centre; it did not end up on the plate "
377
+ f"(it is now {dir_words(*end_off)} of the plate's centre).")
378
+ else:
379
+ out["failure"] = "dropped"
380
+ detail = (f"{grasp_txt}, and the tile was lifted, but it slipped out of the fingers before it was "
381
+ f"released; it is now {dir_words(*end_off)} of the plate's centre.")
382
+ out["detail"] = detail
383
+ ind = detail
384
+ for k in sorted(NAMES, key=lambda n: -len(NAMES[n])):
385
+ ind = ind.replace(NAMES[k], DESCR[k])
386
+ ind = re.sub(r"\btile\b", "slab", ind) # the bare noun would give the direct name away
387
+ out["detail_indirect"] = ind
388
+ return out
389
+
390
+ def feedback(self, inst, out, level="F2", indirect=False):
391
+ if indirect and level == "F2":
392
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
393
+ return super().feedback(inst, out, level)
394
+
395
+ # ------------------------------------------------------------ scripted execution (cross protocol)
396
+ def grasp_yaw(self):
397
+ """Gripper yaw that closes the jaws across the tile's short side (yaw 0 closes along world y)."""
398
+ xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3)
399
+ a = np.arctan2(xmat[1, 0], xmat[0, 0])
400
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
401
+
402
+ def execute(self, inst, params):
403
+ """Top-down pick across the tile's short side with the fingertips just above the block top, carry, release
404
+ above the plate. params['dz'] is the policy's own height correction, added to every commanded z."""
405
+ sk = self.sk
406
+ dz = float(params.get("dz", 0.0))
407
+ t = envs.obj_pos(self.env, TILE) # perfect perception of the current scene
408
+ top = self.stand_top(inst)
409
+ yaw = self.grasp_yaw()
410
+ p = envs.obj_pos(self.env, PLATE)
411
+ z_grasp = top + SITE_ABOVE_SURFACE + dz
412
+ z_carry = top + CARRY_ABOVE + dz
413
+ z_rel = self.plate_rim_z() + RELEASE_GAP + SITE_ABOVE_SURFACE + dz
414
+ sk.set_gripper(False, steps=8)
415
+ sk.move_to([t[0], t[1], z_carry], yaw=yaw)
416
+ sk.move_to([t[0], t[1], z_grasp + 0.05], tol=0.002)
417
+ sk.move_to([t[0], t[1], z_grasp], tol=0.003, max_steps=80)
418
+ sk.set_gripper(True, steps=15)
419
+ sk.move_to([t[0], t[1], z_carry], speed=0.3)
420
+ if not sk.holding_tile(): # missed: a real controller sees the jaws closed on nothing and stops
421
+ return
422
+ sk.move_to([p[0], p[1], z_carry], tol=0.003)
423
+ sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100)
424
+ sk.set_gripper(False, steps=12)
425
+ sk.move_to([p[0], p[1], z_carry], speed=0.3)
426
+
427
+ def default_params(self, inst):
428
+ return dict(dz=0.0)
429
+
430
+ def oracle_params(self, inst):
431
+ return dict(dz=-float(inst["bias"][2]))
432
+
433
+ def adapt_params(self, inst, history):
434
+ """Scripted F2 learner: the reported grasp height above the tile's top face, minus the height this policy
435
+ meant to put the grasp point at (SITE_ABOVE_SURFACE - tile thickness), is the vertical offset; accumulate
436
+ it into the correction subtracted from every commanded height."""
437
+ last = history[-1]
438
+ dz = float(last["params"]["dz"])
439
+ o = last["outcome"]
440
+ if o.get("grasp_height") is not None:
441
+ dz -= o["grasp_height"] - (SITE_ABOVE_SURFACE - TILE_T)
442
+ return dict(dz=round(dz, 4))
443
+
444
+ blind_sigma = 0.005
445
+
446
+ def blind_params(self, inst, attempt, rng):
447
+ """Retry the same plan with a small random perturbation of the commanded heights; no use of history."""
448
+ return dict(dz=round(float(rng.normal(0.0, self.blind_sigma)), 4))
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/tasks/l7_key_turn.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L7 key_turn: unlock a lock whose key turns only one way; which way is hidden.
2
+
3
+ Category: failed_interaction_inference ("why did this contact not do what I expected?").
4
+
5
+ Scene: a grey lock box (9 x 9 x 5 cm) on the table with a brass key standing in the keyhole on its top; the key's
6
+ flat head (3.6 cm wide, 1.6 cm thick, 3 cm tall) sticks up so the gripper can grasp it from above and turn it by
7
+ rotating the wrist. A red bolt sticks out of the box's front face (+x, towards the front camera) while it is locked
8
+ and slides in once the key has been turned to the open position.
9
+
10
+ Hidden variable: the turning direction that opens the lock, clockwise (CW) or counterclockwise (CCW) seen from
11
+ above (alternates with the seed parity, so every block of instances is balanced). The other way the key has 3 deg of
12
+ play and then a hard stop. Both look exactly the same.
13
+
14
+ Turns per attempt: not limited (2026-10-16, user). Until then the instruction allowed one turn per attempt and an
15
+ attempt with more than one turn failed; in every logged run whose first turn went the wrong way the agent turned the
16
+ other way within the same attempt and opened the lock, so the rule only made it repeat that correction in the next
17
+ attempt. The attempt now succeeds once the lock is open, however many turns it took. The trap is logged as an error
18
+ event instead: a turn "hits the stop" when it drives the key onto the stop on the locked side before the lock is open;
19
+ `trap_fired` = some turn did, `n_wrong_way` = how many did, `recovered_in_attempt` = trap fired and the lock was then
20
+ opened in the same attempt. A "turn" is any move_to that starts with the key held and changes the commanded yaw by
21
+ >= 5 deg, or that rotates the key by > 3 deg. A wrong turn costs one command, so this task does not meet design rule
22
+ R3 (the common-sense interaction must have a cost); its signal is clean success (first turn the right way) vs.
23
+ in-attempt recovery, and whether the agent keeps twisting the wrong way.
24
+
25
+ Why the prior fails: the user's example -- many people first try counterclockwise. The scripted prior turns CCW by
26
+ 90 deg, so it fails on every CW instance (half of them): the key rotates by its 3 deg of play, then the wrist stalls.
27
+ What must be learned from the failure: "the key would not turn this way at all" (not "my grip slipped") -> turn it
28
+ the other way. One failure is enough.
29
+
30
+ Mechanics notes (measured in the prototype, 2026-10-08):
31
+ * the Panda's finger servo squeezes with kp * (finger opening) N, i.e. only ~4 N on a 7 mm head; the head then
32
+ twisted between the fingers and wedged them open. A 16 mm thick head gives ~8 N and turns reliably.
33
+ * without a stalling wrist the OSC keeps twisting against a blocked key, the fingers wedge open and on release
34
+ they knock the key 15-45 deg the free way (leaking the answer). `KeySkills` therefore stops rotating the wrist
35
+ once the held key sits on a stop and the gripper has twisted 6 deg past it (a torque-limited wrist), and limits
36
+ the wrist to 90 deg/s while turning.
37
+ * the stops use a stiff solref/solimp: with the defaults a hard twist pushed the key 10-15 deg past its stop.
38
+ * commanded yaw is taken literally in this task (nearest representation to the current yaw, clipped to
39
+ +-113 deg). The shared Skills.wrap_yaw maps yaw modulo 180 deg, which is right for grasping but would turn
40
+ "yaw = +95" into -85 deg, i.e. turn the key the wrong way.
41
+ """
42
+ import numpy as np
43
+
44
+ from .. import envs
45
+ from ..bddl import write_bddl
46
+ from ..objects import _SOLID, _fmt, register_generated
47
+ from ..skills import DT, Skills, _rot_err, _rotz
48
+ from ..task_base import LFFTask, register_task
49
+
50
+ LOCK = "lock_1"
51
+ MODEL = "lff_l7_lock"
52
+ LX, LY, LH = 0.045, 0.045, 0.05 # housing half x, half y, full height
53
+ HEAD = (0.018, 0.008, 0.015) # key head half extents: local x = width, y = thickness, z = height
54
+ HEAD_Z = 0.004 + HEAD[2] # head centre above the housing top
55
+ BOLT = (0.008, 0.012, 0.006) # red bolt (visual only) half extents
56
+ BOLT_OUT = (LX + BOLT[0], 0.0, 0.022)
57
+ BOLT_IN = (LX - BOLT[0] - 0.002, 0.0, 0.022)
58
+ PLAY = np.radians(3.0)
59
+ STOP = np.radians(90.0)
60
+ UNLOCK_AT = np.radians(80.0)
61
+ KEY_FRICTION = 0.04 # N m
62
+ W_MAX = np.radians(90.0) # wrist speed limit while turning (rad/s)
63
+ TWIST_MAX = np.radians(6.0) # wrist stalls when it has twisted this far past a blocked key
64
+ STALL_EXIT = 20 # control steps of stalling before the move gives up
65
+ TURN_YAW = np.radians(5.0)
66
+ TURN_KEY = np.radians(3.0)
67
+ STOP_HIT = PLAY - np.radians(0.5) # key this far the locked way = sitting on the locked-side stop
68
+ Z_GRIP = envs.TABLE_Z + LH + HEAD_Z # grasp-point height for the key head (its centre)
69
+
70
+
71
+ def lock_xml(name, body_rgba=(0.55, 0.57, 0.60, 1.0), key_rgba=(0.80, 0.64, 0.22, 1.0), bolt_rgba=(0.80, 0.12, 0.10, 1.0)):
72
+ g = [f'<geom name="{name}_housing" type="box" pos="0 0 {LH / 2:.4f}" size="{_fmt((LX, LY, LH / 2))}" '
73
+ f'rgba="{_fmt(body_rgba)}" friction="1 0.005 0.0001" {_SOLID} group="0"/>',
74
+ f'<geom type="box" pos="0 0 {LH / 2:.4f}" size="{_fmt((LX, LY, LH / 2))}" rgba="{_fmt(body_rgba)}" '
75
+ f'contype="0" conaffinity="0" group="1"/>',
76
+ f'<geom name="{name}_bolt" type="box" pos="{_fmt(BOLT_OUT)}" size="{_fmt(BOLT)}" rgba="{_fmt(bolt_rgba)}" '
77
+ f'contype="0" conaffinity="0" group="1"/>',
78
+ f'<geom type="cylinder" pos="0 0 {LH + 0.0005:.4f}" size="0.011 0.0005" rgba="0.35 0.36 0.38 1" '
79
+ f'contype="0" conaffinity="0" group="1"/>']
80
+ k = ['<inertial pos="0 0 0.01" mass="0.03" diaginertia="0.00001 0.00001 0.00001"/>',
81
+ # placeholder range: the open direction is set per instance (apply_instance)
82
+ f'<joint name="{name}_key_joint" type="hinge" axis="0 0 1" pos="0 0 0" limited="true" range="-0.05 1.6" '
83
+ f'damping="0.01" frictionloss="{KEY_FRICTION}" armature="0.0002"/>',
84
+ f'<geom name="{name}_head" type="box" pos="0 0 {HEAD_Z:.4f}" size="{_fmt(HEAD)}" rgba="{_fmt(key_rgba)}" '
85
+ f'friction="1 0.005 0.0001" {_SOLID} group="0"/>',
86
+ f'<geom type="box" pos="0 0 {HEAD_Z:.4f}" size="{_fmt(HEAD)}" rgba="{_fmt(key_rgba)}" contype="0" '
87
+ f'conaffinity="0" group="1"/>',
88
+ f'<geom type="cylinder" pos="0 0 0.002" size="0.006 0.002" rgba="{_fmt(key_rgba)}" contype="0" '
89
+ f'conaffinity="0" group="1"/>']
90
+ shell = "\n ".join(g)
91
+ key = "\n ".join(k)
92
+ return f"""<mujoco model="{name}">
93
+ <worldbody>
94
+ <body>
95
+ <body name="object">
96
+ {shell}
97
+ <body name="key" pos="0 0 {LH:.4f}">
98
+ {key}
99
+ </body>
100
+ </body>
101
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
102
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {LH:.4f}" name="top_site" />
103
+ <site rgba="0 0 0 0" size="0.005" pos="{LX:.4f} {LY:.4f} 0" name="horizontal_radius_site" />
104
+ </body>
105
+ </worldbody>
106
+ </mujoco>"""
107
+
108
+
109
+ def _wrap_pi(a):
110
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
111
+
112
+
113
+ def _wrap_half(a):
114
+ """the gripper is symmetric under a rotation by pi"""
115
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
116
+
117
+
118
+ def _rot_words(deg):
119
+ return f"{abs(deg):.0f} deg {'counterclockwise' if deg > 0 else 'clockwise'}"
120
+
121
+
122
+ def _lr(v):
123
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
124
+
125
+
126
+ def _fb(v):
127
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
128
+
129
+
130
+ def _turn_txt(t, lead):
131
+ """F2 sentence for one logged turn: what the wrist and the key did, and whether the gripper held the key."""
132
+ dk = t["key_end_deg"] - t["key_start_deg"]
133
+ txt = f"{lead} the wrist rotated {_rot_words(t['wrist_turn_deg'])} (seen from above)"
134
+ if abs(dk) < 1.0:
135
+ txt += " and the key did not rotate at all"
136
+ else:
137
+ txt += f" and the key rotated {_rot_words(dk)}"
138
+ if t["stalled"]:
139
+ txt += ", then it would not turn any further and the wrist stopped there"
140
+ if t["held_at_start"]:
141
+ txt += ("; the gripper lost hold of the key during the turn." if not t["held_at_end"]
142
+ else "; the gripper held the key throughout the turn.")
143
+ else:
144
+ txt += "; the gripper was not holding the key when that move started."
145
+ return txt
146
+
147
+
148
+ class KeySkills(Skills):
149
+ """Skills for the key task: literal yaw, wrist speed limit, stalling wrist, and a log of turns / grasps / unlock."""
150
+
151
+ def __init__(self, env, task, recorder=None):
152
+ super().__init__(env, recorder=recorder)
153
+ self.task = task
154
+ m = env.sim.model
155
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
156
+ self.turns = [] # one entry per move_to that counts as a turn
157
+ self.closes = [] # close_gripper events: gripper centre relative to the key head, held afterwards?
158
+ self.stall_steps = 0
159
+ self._grasp_off = None # gripper yaw minus key yaw when the key was grasped
160
+ self.touch_since_report = False
161
+
162
+ # ------------------------------------------------------------ state
163
+ def eef_yaw(self):
164
+ R = self.eef_mat() @ self.R0.T
165
+ return float(np.arctan2(R[1, 0], R[0, 0]))
166
+
167
+ def holding_key(self):
168
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=[self.task.head_geom_name]))
169
+
170
+ def _touching_key(self):
171
+ d = self.env.sim.data
172
+ g, kg = set(self._grip_geoms), self.task.head_gid
173
+ for i in range(d.ncon):
174
+ c = d.contact[i]
175
+ if (c.geom1 in g and c.geom2 == kg) or (c.geom2 in g and c.geom1 == kg):
176
+ return True
177
+ return False
178
+
179
+ def wrap_yaw(self, yaw):
180
+ """Literal yaw: the representation of `yaw` closest to the current wrist yaw, clipped to the wrist range."""
181
+ cur = self.eef_yaw()
182
+ y = cur + _wrap_pi(float(yaw) - cur)
183
+ return float(np.clip(y, -self.YAW_LIMIT, self.YAW_LIMIT))
184
+
185
+ # ------------------------------------------------------------ low level
186
+ def _act(self, dpos, drot, grip):
187
+ t = self.task
188
+ if self.grip > 0 and self._grasp_off is not None:
189
+ q = t.key_q()
190
+ lo, hi = t.key_range()
191
+ twist = _wrap_half(self.eef_yaw() - t.key_world_yaw() - self._grasp_off)
192
+ at_hi, at_lo = q >= hi - np.radians(1.5), q <= lo + np.radians(1.5)
193
+ if (at_hi and twist > TWIST_MAX and drot[2] > 0) or (at_lo and twist < -TWIST_MAX and drot[2] < 0):
194
+ drot = np.array(drot, float).copy()
195
+ drot[2] = -np.sign(twist) * 0.02 # force-limited wrist: back off instead of twisting further
196
+ self.stall_steps += 1
197
+ super()._act(dpos, drot, grip)
198
+ t.check_unlock()
199
+ if self._touching_key():
200
+ self.touch_since_report = True
201
+
202
+ def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
203
+ """Skills.move_to with the wrist reference rotating at <= W_MAX and an early stop when the wrist stalls.
204
+ Logs the move as a turn when it starts with the key held and rotates the wrist, or when it rotates the key;
205
+ `hit_stop`: the turn went the locked way (wrist command if the key was held, else the key's motion) and the key
206
+ was on the locked-side stop during it, while the lock was still locked (the trap)."""
207
+ t = self.task
208
+ tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
209
+ if yaw is not None:
210
+ self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
211
+ yaw0 = self.eef_yaw()
212
+ dyaw = self.yaw - yaw0
213
+ R_goal = self._R()
214
+ p0 = self.eef_pos()
215
+ q0, held0, locked0 = t.key_q(), self.holding_key(), not t.unlocked
216
+ q_open_min = t.open_sign() * q0 # lowest key angle the open way during the move
217
+ dist = np.linalg.norm(tgt - p0)
218
+ direction = (tgt - p0) / max(dist, 1e-9)
219
+ s = 0.0
220
+ self.stall_steps = 0
221
+ for k in range(max_steps):
222
+ if speed is not None:
223
+ s = min(dist, s + speed * DT)
224
+ ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5)
225
+ else:
226
+ ref = tgt
227
+ frac = min(1.0, (k + 1) * DT * W_MAX / max(abs(dyaw), 1e-6))
228
+ R = _rotz(yaw0 + frac * dyaw) @ self.R0
229
+ self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
230
+ q_open_min = min(q_open_min, t.open_sign() * t.key_q())
231
+ if self.stall_steps >= STALL_EXIT:
232
+ break
233
+ if (np.linalg.norm(tgt - self.eef_pos()) < tol and (speed is None or s >= dist) and frac >= 1.0
234
+ and np.linalg.norm(_rot_err(R_goal, self.eef_mat())) < 0.03):
235
+ break
236
+ stalled = self.stall_steps >= STALL_EXIT
237
+ if stalled:
238
+ # give up the unreached wrist angle; otherwise every later hold (e.g. while the gripper opens) keeps
239
+ # driving the wrist towards it and the arm swings away (seen in the agent self-test, 2026-10-08)
240
+ self.yaw = self.eef_yaw()
241
+ rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
242
+ pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=bool(stalled))
243
+ self.log.append(rep)
244
+ dq = t.key_q() - q0
245
+ locked_way = t.open_sign() * (dyaw if held0 else dq) < 0
246
+ if (held0 and abs(dyaw) >= TURN_YAW) or abs(dq) > TURN_KEY:
247
+ self.turns.append(dict(step=self.n_steps, held_at_start=bool(held0), held_at_end=self.holding_key(),
248
+ key_start_deg=round(float(np.degrees(q0)), 1),
249
+ key_end_deg=round(float(np.degrees(t.key_q())), 1),
250
+ wrist_cmd_deg=round(float(np.degrees(dyaw)), 1),
251
+ wrist_turn_deg=round(float(np.degrees(self.eef_yaw() - yaw0)), 1),
252
+ stalled=bool(stalled),
253
+ hit_stop=bool(locked0 and locked_way and q_open_min <= -STOP_HIT)))
254
+ return rep
255
+
256
+ def set_gripper(self, close, steps=15):
257
+ was_open = self.grip < 0
258
+ rep = super().set_gripper(close, steps)
259
+ if close:
260
+ if self.holding_key():
261
+ self._grasp_off = _wrap_half(self.eef_yaw() - self.task.key_world_yaw())
262
+ if was_open:
263
+ off = self.eef_pos() - self.task.head_xyz()
264
+ self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_key(),
265
+ width=round(self.gripper_width(), 4)))
266
+ else:
267
+ self._grasp_off = None
268
+ return rep
269
+
270
+
271
+ @register_task
272
+ class KeyTurn(LFFTask):
273
+ name = "l7_key_turn"
274
+ level = "L7"
275
+ category = "failed_interaction_inference"
276
+ capabilities = ("Perceive", "Reason", "Plan")
277
+ protocol = "cross"
278
+ instruction = ("Unlock the lock on the grey box: grasp the flat head of the brass key from above and turn the key "
279
+ "a quarter turn (90 degrees). The red bolt on the box slides in when it is unlocked.")
280
+ instruction_indirect = ("Open the lock of the small grey metal box: take hold of the flat gold-coloured tab that "
281
+ "sticks up out of its top and rotate it a quarter turn (90 degrees). The red block on the "
282
+ "box slides in when it is open.")
283
+
284
+ # ------------------------------------------------------------ scene
285
+ def make_bddl(self):
286
+ lock = register_generated("LffKeyLock", lock_xml(MODEL), free=False)
287
+ return write_bddl(self.name, "unlock the lock", [],
288
+ fixtures=[(LOCK, lock, "lock_region", (-0.11, -0.01, -0.09, 0.01))])
289
+
290
+ def __init__(self, cam_res=None):
291
+ super().__init__(cam_res)
292
+ m = self.env.sim.model
293
+ pre = f"{LOCK}_{MODEL}"
294
+ self.jid = m.joint_name2id(pre + "_key_joint")
295
+ self.qa = m.jnt_qposadr[self.jid]
296
+ self.dof = m.jnt_dofadr[self.jid]
297
+ self.lock_bid = m.body_name2id(self.env.fixtures_dict[LOCK].root_body)
298
+ self.head_geom_name = pre + "_head"
299
+ self.head_gid = m.geom_name2id(self.head_geom_name)
300
+ self.bolt_gid = m.geom_name2id(pre + "_bolt")
301
+ self.inst = None
302
+ self.unlocked = False
303
+
304
+ # agent-facing hooks -------------------------------------------------------
305
+ def on_agent_tool(self, inst, name, args, report):
306
+ """The lock is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never see
307
+ the key; add an explicit `holding_key` field and count key contacts as touches."""
308
+ if self.sk is None or not isinstance(report, dict):
309
+ return
310
+ touched = self.sk.touch_since_report
311
+ self.sk.touch_since_report = False
312
+ if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"):
313
+ report["holding_key"] = self.sk.holding_key()
314
+ if touched and "touched_object" in report:
315
+ report["touched_object"] = True
316
+
317
+ # ------------------------------------------------------------ state helpers
318
+ def key_q(self):
319
+ return float(self.env.sim.data.qpos[self.qa])
320
+
321
+ def key_range(self):
322
+ return self.env.sim.model.jnt_range[self.jid]
323
+
324
+ def key_world_yaw(self):
325
+ return float(self.inst["lock_yaw"]) + self.key_q()
326
+
327
+ def head_xyz(self):
328
+ return self.env.sim.data.geom_xpos[self.head_gid].copy()
329
+
330
+ def open_sign(self):
331
+ return 1.0 if self.inst["direction"] == "CCW" else -1.0
332
+
333
+ def check_unlock(self):
334
+ """latch: the bolt is thrown back once the key reaches the open position (and stays back)"""
335
+ if not self.unlocked and self.open_sign() * self.key_q() >= UNLOCK_AT:
336
+ self.unlocked = True
337
+ self.env.sim.model.geom_pos[self.bolt_gid] = BOLT_IN
338
+
339
+ def sample_instance(self, seed):
340
+ rng = np.random.default_rng(seed)
341
+ return dict(seed=int(seed), direction="CCW" if seed % 2 == 0 else "CW",
342
+ lock_xy=[float(rng.uniform(-0.15, -0.02)), float(rng.uniform(-0.15, 0.15))],
343
+ lock_yaw=float(rng.uniform(-np.radians(15), np.radians(15))))
344
+
345
+ def apply_instance(self, inst):
346
+ self.inst = inst
347
+ m, d = self.env.sim.model, self.env.sim.data
348
+ cx, cy = inst["lock_xy"]
349
+ a = inst["lock_yaw"]
350
+ m.body_pos[self.lock_bid] = [cx, cy, envs.TABLE_Z]
351
+ m.body_quat[self.lock_bid] = [np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]
352
+ m.jnt_range[self.jid] = [-PLAY, STOP] if inst["direction"] == "CCW" else [-STOP, PLAY]
353
+ m.jnt_solref[self.jid] = [0.004, 1.0]
354
+ m.jnt_solimp[self.jid] = [0.99, 0.999, 0.001, 0.5, 2.0]
355
+ m.dof_frictionloss[self.dof] = KEY_FRICTION
356
+ m.geom_pos[self.bolt_gid] = BOLT_OUT
357
+ d.qpos[self.qa] = 0.0
358
+ d.qvel[self.dof] = 0.0
359
+ self.unlocked = False
360
+
361
+ def reset_instance(self, inst, recorder=None):
362
+ self.env.reset()
363
+ self.apply_instance(inst)
364
+ self.env.sim.forward()
365
+ envs.settle(self.env, 10)
366
+ self.sk = KeySkills(self.env, self, recorder=recorder)
367
+ return self.sk
368
+
369
+ # ------------------------------------------------------------ outcome
370
+ def outcome(self, inst):
371
+ envs.settle(self.env, 20)
372
+ sk = self.sk
373
+ n_turns = len(sk.turns)
374
+ n_wrong = sum(t["hit_stop"] for t in sk.turns)
375
+ success = bool(self.unlocked)
376
+ open_deg = float(np.degrees(self.open_sign() * self.key_q()))
377
+ out = dict(success=success, unlocked=bool(self.unlocked), n_turns=n_turns, n_wrong_way=n_wrong,
378
+ trap_fired=n_wrong > 0, recovered_in_attempt=bool(n_wrong and success),
379
+ key_deg=round(np.degrees(self.key_q()), 1), open_deg=round(open_deg, 1), turns=sk.turns,
380
+ closes=sk.closes, first_turn=sk.turns[0] if sk.turns else None)
381
+ parts = []
382
+ grasp_txt = ""
383
+ if sk.closes:
384
+ c = sk.closes[0]
385
+ o = c["offset"]
386
+ top = envs.TABLE_Z + LH + HEAD_Z + HEAD[2]
387
+ below = top - (o[2] + self.head_xyz()[2])
388
+ grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the centre of "
389
+ f"the key's head and {100 * below:.1f} cm below the top of the head; it "
390
+ + ("was holding the key." if c["held"] else "did not get hold of the key."))
391
+ if success:
392
+ out["failure"] = None
393
+ parts.append("The lock is unlocked.")
394
+ elif n_turns == 0:
395
+ out["failure"] = "no_turn"
396
+ parts.append("The lock is still locked: the key was never turned.")
397
+ else:
398
+ out["failure"] = "still_locked"
399
+ parts.append("The lock is still locked.")
400
+ if n_turns == 1:
401
+ parts.append(_turn_txt(sk.turns[0], "During your turn"))
402
+ else:
403
+ parts.append(f"The key was turned (or pushed round) in {n_turns} separate moves.")
404
+ parts.append(_turn_txt(sk.turns[0], "During the first one"))
405
+ parts.append(_turn_txt(sk.turns[-1], "During the last one"))
406
+ if grasp_txt and not success:
407
+ parts.append(grasp_txt)
408
+ out["detail"] = " ".join(parts)
409
+ return out
410
+
411
+ # ------------------------------------------------------------ scripted execution (cross protocol)
412
+ def execute(self, inst, params):
413
+ """Grasp the key head from above across its thickness (+ jitter), one wrist turn of `turn` degrees
414
+ (+ = counterclockwise seen from above), release, lift."""
415
+ sk = self.sk
416
+ p = self.head_xyz() + np.r_[params.get("dxy", (0.0, 0.0)), params.get("dz", 0.0)] # perfect perception
417
+ yaw0 = self.key_world_yaw() + np.radians(params.get("dyaw", 0.0))
418
+ sk.set_gripper(False, steps=8)
419
+ sk.move_to([p[0], p[1], p[2] + 0.08], yaw=yaw0)
420
+ sk.move_to([p[0], p[1], p[2]], tol=0.003)
421
+ sk.set_gripper(True, steps=15)
422
+ sk.move_to([p[0], p[1], p[2]], yaw=sk.eef_yaw() + np.radians(float(params["turn"])), max_steps=200)
423
+ sk.set_gripper(False, steps=8)
424
+ e = sk.eef_pos()
425
+ sk.move_to([e[0], e[1], e[2] + 0.08])
426
+
427
+ def default_params(self, inst):
428
+ """the prior from the user's example: try counterclockwise first"""
429
+ return dict(turn=90.0)
430
+
431
+ def oracle_params(self, inst):
432
+ return dict(turn=90.0 * (1 if inst["direction"] == "CCW" else -1))
433
+
434
+ def adapt_params(self, inst, history):
435
+ """Scripted F2 learner. A turn after which the key rotated less than 10 deg the commanded way (it stopped)
436
+ -> that way is blocked -> turn the other way. A turn that rotated the key further but not far enough -> same
437
+ way, a bit more. Anything else (no turn, lost grip) -> repeat the last direction."""
438
+ blocked = set()
439
+ good = 0
440
+ for h in history:
441
+ t = h["outcome"].get("first_turn")
442
+ if t is None:
443
+ continue
444
+ sgn = int(np.sign(h["params"]["turn"]))
445
+ dk = t["key_end_deg"] - t["key_start_deg"]
446
+ if t["held_at_start"] and sgn * dk < 10.0:
447
+ blocked.add(sgn)
448
+ elif sgn * dk >= 10.0:
449
+ good = sgn
450
+ if good:
451
+ return dict(turn=100.0 * good)
452
+ last = int(np.sign(history[-1]["params"]["turn"]))
453
+ sgn = -last if last in blocked else last
454
+ if sgn in blocked:
455
+ sgn = -sgn
456
+ return dict(turn=90.0 * sgn)
457
+
458
+ def blind_params(self, inst, attempt, rng):
459
+ """Same plan (counterclockwise quarter turn) with small random variation; no history."""
460
+ return dict(turn=float(np.clip(rng.normal(90.0, 8.0), 70.0, 105.0)), dxy=rng.normal(0.0, 0.002, 2).tolist(),
461
+ dyaw=float(rng.normal(0.0, 4.0)))
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/tasks/lh_wobbly_table.py ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH lh_wobbly_table (2026-10-16): stand four bottles on the four coloured spots of a small side table -- one of its
2
+ legs is 1.5 cm short. Set the heavy bottle down on the corner over that leg while other bottles already stand on the
3
+ table and the table rocks down onto the short leg with a knock that throws the tall light bottles over.
4
+
5
+ Family: long-horizon self-disturbance ("state_restoration"): four plain pick-and-place stages, but a later stage (the heavy
6
+ bottle on the wobbly corner) physically undoes the earlier ones without the robot touching them. The agent has to
7
+ notice the fallen bottles and stand them up again (the rocked table is stable, so they stay up), or learn across
8
+ attempts to put that bottle down first (the table then rocks while nothing stands on it).
9
+
10
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
11
+ * a small wooden side table (free body, 1.1 kg): 28 x 28 x 1.6 cm top, 8.5 cm high, four 1.6 cm square legs at
12
+ +-12.5 cm; centre 53-57 cm in front of the robot base, +-4 cm left/right; four coloured spots (7.2 x 6.4 cm,
13
+ painted, colours permuted) centred 8 cm from the middle on both axes (one per corner);
14
+ * four square glass bottles (red / blue / green / yellow; 3.2 x 3.2 x 10 cm body, 2.4 cm flat foot, shoulder, 1.4 cm
15
+ square neck, a thin stem and a 1.2 cm white ball stopper; 14.7 cm tall) standing in a row on the main table in
16
+ front of the side table or beside it (random). Three are empty and light (75-90 g, centre of mass 7.2-8.0 cm up:
17
+ they tip over beyond ~9 deg); the fourth looks the same but is heavy (0.34-0.38 kg, sand in the bottom, centre of
18
+ mass 3.0-3.6 cm up).
19
+
20
+ Hidden variables: which leg is short (its collision capsule is 14-16 mm shorter; the visual leg is drawn full length,
21
+ so all legs look alike and touch the table) and which bottle is heavy. Coupled by construction: the heavy bottle's spot
22
+ is the corner over the short leg. Balanced over seeds: in the scripted naive order (spots farthest from the supply
23
+ first, then left first) the heavy bottle's spot comes 1st / 2nd / 3rd / 4th for exactly 5 of every 20 consecutive seeds
24
+ (1st = benign for that order: the table rocks while it is empty).
25
+
26
+ Physics (measured, scratch scripts t2-t24, see the task card and results/lh_wobbly_table/physics.json):
27
+ * The legs' collision geoms are capsules (rounded feet). With flat 1.6 cm box feet the rocking axis moved 1.1 cm
28
+ towards the loaded corner and the table's own weight stopped the rock half way (0.5 deg, balanced on two legs).
29
+ * The empty table rests level on its three long legs: its centre of mass is 5 mm towards the corner opposite the
30
+ short leg (1.1 kg x 5 mm). The light bottles on their own spots (the other three corners) never tip it, also let go
31
+ 4 cm above the top with a 2.6 cm error towards the short corner (4/4 seeds); the heavy bottle on the short corner
32
+ does (0.36 kg x 11.3 cm), also against a light bottle on the opposite corner. (A light bottle put on the short
33
+ corner's spot -- a wrong spot -- also tips the empty table: 85 g x 11.3 cm > 1.1 kg x 5 mm.) Rocked onto the short
34
+ leg the table tilts 4.5-5.1 deg and stays there with the heavy bottle on it, also when the light ones are added;
35
+ lifting the heavy bottle off, or pressing 1.25 N down near the raised corner, rocks it back (measured).
36
+ * The knock topples the light bottles standing on the table: 18/18 with teleported (zero-velocity) placements at gaps
37
+ 13-18 mm (12 mm: 8-10/18, 10 mm: 0/18); they fall towards the low corner, some off the table edge. The heavy bottle
38
+ stays up. The robot does not touch the bottles that fall (logged per rock).
39
+ * Bottle and table-top contacts are overdamped (solref 0.01, damping ratio 3): with stiff critically damped contacts
40
+ a light bottle let go 1-4 cm above the ROCKED table landed on its uphill edge and fell over (21/27 at 3.4 deg);
41
+ damped, 0/54 at every gap 13-18 mm, so the cross-attempt fix (heavy bottle first) works with the agent's usual
42
+ release 1-4 cm above the surface.
43
+ * A 22 x 22 cm draft table (spots 15.6 cm apart diagonally, 15.7 cm draft bottles) let the bottle on the opposite corner
44
+ fall onto the heavy one and lean on it; its stopper could not be grasped without knocking the heavy bottle over
45
+ (after which the table rocks back and forth on every repair step). At 28 cm nothing leans on it.
46
+ * Grasps: the Panda hand's collision hull starts 3 cm above the grasp point and the finger pads reach 1.2 cm above
47
+ it. Everything above the square neck is narrower than the neck: fingers that overlap the neck (grasp point 0.4-0.9
48
+ cm below its top) close on its flat faces and hold the bottle rigidly (the heavy one stayed in the fingers through
49
+ three moves at the controller's top speed 12/12, a light one 11/12); fingers on the ball alone (grasp point at or
50
+ above the neck's top) touch it at one point each and the bottle pivots (top-speed carries lost it 6/6). Drafts: a
51
+ 1.8 cm ball on a 1.3 cm round neck (the fingers always closed on the ball; the heavy bottle swung out in 5/6 fast
52
+ carries and once in the first smoke test), a 1.2 x 2.2 cm cylinder stopper (line contacts: a lying bottle lifted by
53
+ it stuck at ~26 deg and fell over when set down). The instruction states which grip is rigid and which swings (as
54
+ lh_bystander states its cap).
55
+ * Restoring (yaw-only top-down gripper): grasp the ball stopper of a lying bottle from above with the fingers across
56
+ its axis (torsional friction 0.0005), lift: it swings down and hangs straight (0.1 deg); lower it onto its spot and
57
+ let go. A bottle that fell off onto the main table right beside the small table often cannot be reached this way:
58
+ the hand (20 cm wide along the finger axis, 3 cm above the grasp point) would hit the table top. Where the hand,
59
+ the open fingers or the forearm would touch a standing bottle, the scripted repair first lifts the fallen bottle by
60
+ its body and lays it down in free space.
61
+ * Reach: the arm stalls 2-3 cm short of low targets beyond ~0.72 m from the base; every scripted grasp point stays
62
+ within 0.70 m.
63
+
64
+ Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each bottle stands upright
65
+ (tilt <= 10 deg from vertical; on the rocked table they stand at ~5.5 deg) on the small table's top with the centre of
66
+ its bottom inside its spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right of the spot's centre), not held.
67
+ Success = all four at the end, gripper open and not touching a bottle, scene static, and the small table within 3 cm /
68
+ 10 deg of where it stood and standing on its legs (tilt <= 8 deg; the rocked tilt counts as standing). The monitor logs
69
+ achieved / lost / restored per bottle and table_rocked / table_rocked_back events (the bottle released just before,
70
+ the bottles standing at that moment, which of them fell, whether the robot touched them before / while they fell) for
71
+ the server log only (F1 gives the agent only success / failure).
72
+
73
+ Protocol: cross (reset to the same instance before every attempt), k = 3.
74
+ """
75
+ import numpy as np
76
+
77
+ from .. import envs
78
+ from ..bddl import write_bddl
79
+ from ..objects import _fmt, _wrap, register_generated
80
+ from ..skills import Skills
81
+ from ..task_base import LFFTask, register_task
82
+
83
+ TZ = envs.TABLE_Z
84
+ COLOURS = ["red", "blue", "green", "yellow"]
85
+ BOTTLES = [f"bottle_{c}_1" for c in COLOURS]
86
+ TABLE = "side_table_1"
87
+ RGBA = {"red": (0.80, 0.14, 0.12, 1.0), "blue": (0.15, 0.33, 0.80, 1.0), "green": (0.14, 0.58, 0.24, 1.0),
88
+ "yellow": (0.90, 0.74, 0.12, 1.0)}
89
+ SPOT_RGBA = {"red": (0.62, 0.12, 0.11, 1.0), "blue": (0.12, 0.22, 0.58, 1.0), "green": (0.10, 0.42, 0.17, 1.0),
90
+ "yellow": (0.70, 0.56, 0.08, 1.0)}
91
+ CAP_RGBA = (0.93, 0.93, 0.91, 1.0) # white round stopper
92
+ WOOD = (0.52, 0.36, 0.22, 1.0)
93
+ LEG_RGBA = (0.40, 0.27, 0.16, 1.0)
94
+
95
+ # ---------------------------------------------------------------- side table (free body)
96
+ TOP_HW = 0.140 # 28 x 28 cm top
97
+ TOP_T = 0.016
98
+ TABLE_H = 0.085 # top surface above the main table
99
+ LEG_HW = 0.008 # 1.6 x 1.6 cm legs (visual); collision: capsules of radius 8 mm (rounded feet)
100
+ LEG_O = 0.125 # leg centre offset from the table centre (x and y)
101
+ LEG_L = TABLE_H - TOP_T
102
+ TBL_MASS = 1.1
103
+ TBL_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.004 1"' # legs: stiff (a sharp knock when the short leg lands)
104
+ TOP_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' # top: overdamped like the bottles
105
+ LEG_MU = 1.0
106
+ TOP_MU = 0.8
107
+ # corners in the table frame (= world axes; +x forward, +y left): index -> (sx, sy); k and k + 2 are diagonal
108
+ CORNERS = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
109
+ CORNER_NAME = {(1, 1): "far-left", (1, -1): "far-right", (-1, -1): "near-right", (-1, 1): "near-left"}
110
+ SPOT_O = 0.080 # spot centre offset from the table centre (x and y)
111
+ SPOT_HX, SPOT_HY = 0.036, 0.032 # spot half sizes (forward-back, left-right): 7.2 x 6.4 cm
112
+ SHORT_H = (0.014, 0.016) # hidden: one leg this much shorter (collision only; the visual leg reaches the table)
113
+ COM_BIAS = 0.005 # table centre of mass this far towards the leg opposite the short one: the empty table rests level
114
+
115
+ # ---------------------------------------------------------------- bottles (square glass bottles with a round stopper)
116
+ RB, HB = 0.016, 0.100 # body half width, height (3.2 x 3.2 x 10 cm)
117
+ RF, HF = 0.012, 0.005 # foot: flat contact 2.4 x 2.4 cm (rounded glass base)
118
+ RS, HS = 0.011, 0.010 # shoulder
119
+ RN, HN = 0.007, 0.016 # square neck: 1.4 cm wide, 1.6 cm long (11.0-12.6 cm above the bottom)
120
+ RT, HT = 0.0035, 0.010 # thin round stem above it: 0.7 cm wide, 1.0 cm long
121
+ RK, CAP_SINK = 0.006, 0.001 # ball stopper: 1.2 cm wide, on the stem (top 14.7 cm above the bottom)
122
+ # Why this top (measured, t8_hand.py / t19_slip.py / t22_restand.py): the Panda hand's collision hull starts ~3 cm above
123
+ # the grasp point and the finger pads reach 1.2 cm above it. Everything above the square neck is narrower than the
124
+ # neck, so fingers that overlap the neck close on its flat faces (several contact points: the bottle is held rigidly),
125
+ # and fingers on the ball alone touch it at one point each (low torsional friction: a lying bottle swings down and
126
+ # hangs straight). Drafts: a 1.8 cm ball on a 1.3 cm round neck -- the fingers always closed on the ball, the heavy
127
+ # bottle pivoted and swung out in 5/6 fast carries; a 1.2 x 2.2 cm cylinder stopper -- line contacts, a lifted lying
128
+ # bottle stuck at ~26 deg and fell over when set down (in-attempt repair 6/15).
129
+ H_TOT = HB + HS + HN + HT + 2 * RK - CAP_SINK # 14.7 cm
130
+ CAP_Z = H_TOT - RK # stopper centre above the bottle's bottom
131
+ NECK_Z = (HB + HS, HB + HS + HN) # square neck span above the bottom
132
+ BOT_MU = 0.7
133
+ CAP_MU_T = 0.0005 # torsional friction of the stopper (condim 4): held by it, a lying bottle swings down and hangs
134
+ BOT_DAMP = 0.003 # free-joint damping of the bottles (damps the swing of a bottle hanging from its stopper)
135
+ # overdamped contacts (damping ratio 3): with critically damped stiff contacts a light bottle set down 1-4 cm above a
136
+ # table top tilted 3.4 deg landed on its uphill edge and fell over (measured 21/27); damped: 0/54 at tilts up to 5 deg
137
+ BOT_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"'
138
+ LIGHT_MASS = (0.075, 0.090)
139
+ LIGHT_COM = (0.072, 0.080) # above the bottom (empty glass bottle, thick shoulder)
140
+ HEAVY_MASS = (0.34, 0.38)
141
+ HEAVY_COM = (0.030, 0.036) # sand in the bottom
142
+
143
+ # ---------------------------------------------------------------- predicates / monitor
144
+ TILT_OK = np.radians(10.0) # a bottle stands upright (world vertical; the rocked table itself tilts ~4.3 deg)
145
+ TOL_X = SPOT_HX - 0.006 # bottle centre within the spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right)
146
+ TOL_Y = SPOT_HY - 0.006
147
+ ON_TOP = 0.006 # the bottle's bottom within this of the table top
148
+ HYST = 0.003
149
+ DEBOUNCE = 10 # control steps (0.5 s)
150
+ ROCK_ON, ROCK_OFF = np.radians(1.5), np.radians(0.8) # table tilt thresholds of the rock detector
151
+ FELL_WINDOW = 40 # control steps after a rock in which lost stages are attributed to it (2 s)
152
+ TABLE_MOVE_TOL = 0.03 # success: the table centre within 3 cm of where it stood
153
+ TABLE_YAW_TOL = np.radians(10.0)
154
+ TABLE_TILT_MAX = np.radians(8.0)
155
+
156
+ # ---------------------------------------------------------------- scripted motion
157
+ Z_CARRY = 0.40 # grasp point above the main table while carrying (bottle bottom ~27 cm up: clears standing bottles)
158
+ Z_HANG = 0.42 # ... carrying a bottle that hangs from its stopper (its bottom 27 cm up)
159
+ GRASP_NECK = 0.006 # scripted transport grasp point: this far below the neck's top (pads 1.1 cm on the neck, the hand
160
+ # 3 mm above the stopper; measured: 4-9 mm below the top hold rigidly, 4 mm above it close on the ball)
161
+ NAIVE_GAP = (0.010, 0.040) # Sonnet releases 1-4 cm above the surface
162
+ NAIVE_BIAS = (0.008, 0.020) # systematic forward placement error (lh_nudge_row pilot), per instance
163
+ NAIVE_RAND = 0.006
164
+ CAREFUL_GAP = 0.004
165
+
166
+
167
+ def bottle_xml(name, rgba):
168
+ """square glass bottle: rounded foot (smaller flat contact), body, shoulder, square neck, round stopper. Collision and
169
+ visual geoms separate; the inertial (mass, COM) is replaced per instance."""
170
+ h = H_TOT / 2
171
+ zf, zb = -h + HF / 2, -h + HF + (HB - HF) / 2
172
+ zs, zn = -h + HB + HS / 2, -h + HB + HS + HN / 2
173
+ zt = -h + HB + HS + HN + HT / 2
174
+ zk = -h + HB + HS + HN + HT + RK - CAP_SINK
175
+ parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
176
+ ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
177
+ ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
178
+ ("neck", "box", (0, 0, zn), (RN, RN, HN / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
179
+ ("stem", "cylinder", (0, 0, zt), (RT, HT / 2), CAP_RGBA, f'friction="{BOT_MU} 0.005 0.0001"'),
180
+ ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
181
+ s = [f' <inertial pos="0 0 {-h + 0.05:.4f}" mass="0.08" diaginertia="1.5e-4 1.5e-4 2.0e-5" />']
182
+ for nm, typ, pos, size, c, extra in parts:
183
+ s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
184
+ f'{extra} {BOT_SOLREF} group="0" />')
185
+ s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
186
+ f'conaffinity="0" group="1" />')
187
+ # a pale label (visual) so the bottles read as bottles
188
+ s.append(f' <geom type="box" pos="0 0 {zb + 0.008:.4f}" size="{RB + 0.0006:.4f} {RB + 0.0006:.4f} 0.016" '
189
+ f'rgba="0.94 0.92 0.84 1" contype="0" conaffinity="0" group="1" />')
190
+ return _wrap(name, "\n".join(s), h, RB * 1.42)
191
+
192
+
193
+ def table_xml(name):
194
+ """side table, origin at the centre of the footprint at mid height. Leg k sits under corner CORNERS[k]."""
195
+ h = TABLE_H / 2
196
+ zt = h - TOP_T / 2
197
+ zl = -h + LEG_L / 2
198
+ s = [f' <inertial pos="0 0 {0.02:.4f}" mass="{TBL_MASS}" diaginertia="0.004 0.004 0.007" />',
199
+ f' <geom name="{name}_top" type="box" pos="0 0 {zt:.5f}" size="{TOP_HW:.5f} {TOP_HW:.5f} {TOP_T / 2:.5f}" '
200
+ f'rgba="{_fmt(WOOD)}" friction="{TOP_MU} 0.005 0.0001" {TOP_SOLREF} group="0" />',
201
+ f' <geom type="box" pos="0 0 {zt:.5f}" size="{TOP_HW:.5f} {TOP_HW:.5f} {TOP_T / 2:.5f}" '
202
+ f'rgba="{_fmt(WOOD)}" contype="0" conaffinity="0" group="1" />']
203
+ for k, (sx, sy) in enumerate(CORNERS):
204
+ p = (sx * LEG_O, sy * LEG_O, zl)
205
+ # collision: a capsule inscribed in the square leg -> a rounded, point-like foot (a flat 1.6 cm foot moves the
206
+ # rocking axis 1.1 cm towards the loaded corner, and the table's own weight then stops the rock; measured)
207
+ s.append(f' <geom name="{name}_leg{k}" type="capsule" pos="{_fmt(p)}" '
208
+ f'size="{LEG_HW:.5f} {LEG_L / 2 - LEG_HW:.5f}" rgba="{_fmt(LEG_RGBA)}" '
209
+ f'friction="{LEG_MU} 0.005 0.0001" {TBL_SOLREF} group="0" />')
210
+ s.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt((LEG_HW, LEG_HW, LEG_L / 2))}" '
211
+ f'rgba="{_fmt(LEG_RGBA)}" contype="0" conaffinity="0" group="1" />')
212
+ for k, (sx, sy) in enumerate(CORNERS): # coloured spots (visual); colours are set per instance
213
+ s.append(f' <geom name="{name}_spot{k}" type="box" pos="{sx * SPOT_O:.5f} {sy * SPOT_O:.5f} {h + 0.0004:.5f}" '
214
+ f'size="{SPOT_HX:.5f} {SPOT_HY:.5f} 0.0004" rgba="0.5 0.5 0.5 1" contype="0" conaffinity="0" '
215
+ f'group="1" />')
216
+ return _wrap(name, "\n".join(s), h, TOP_HW * 1.42)
217
+
218
+
219
+ def _fb(d):
220
+ return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}"
221
+
222
+
223
+ def _lr(d):
224
+ return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}"
225
+
226
+
227
+ def _ang(a):
228
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
229
+
230
+
231
+ class WobblySkills(Skills):
232
+ """Skills that feed the task's per-step monitor."""
233
+
234
+ def __init__(self, env, task, recorder=None):
235
+ super().__init__(env, recorder=recorder)
236
+ self.task = task
237
+
238
+ def _act(self, dpos, drot, grip):
239
+ super()._act(dpos, drot, grip)
240
+ self.task.monitor_step()
241
+
242
+
243
+ @register_task
244
+ class WobblyTable(LFFTask):
245
+ name = "lh_wobbly_table"
246
+ level = "L2"
247
+ category = "state_restoration"
248
+ capabilities = ("Perceive", "Reason", "Restore", "Plan")
249
+ protocol = "cross"
250
+ max_attempts = 3
251
+ # careful: 4 bottles x ~7 commands + standing up to three fallen bottles again x ~9 + looking / corrections
252
+ agent_max_steps = 120
253
+ instruction = ("Put each of the four bottles on the spot of its own colour on the small wooden table. At the end "
254
+ "every bottle must stand upright on its spot, the gripper must be open and clear of the bottles, and "
255
+ "the small table must still stand where it is now. (Each bottle has a square neck with a small round "
256
+ "white stopper on top. Gripped on the neck, a bottle stays rigid in the fingers; gripped by the "
257
+ "stopper alone, it swings freely and hangs straight down.)")
258
+ instruction_indirect = ("Set the four coloured bottles out on the little wooden side table, each on the patch that "
259
+ "matches its colour. When you finish, all four have to be standing upright on their patches, "
260
+ "the gripper open and away from them, and the side table left where it stands. (Gripped "
261
+ "on its square neck a bottle stays rigid; gripped by the round white stopper alone it swings "
262
+ "freely and hangs straight down.)")
263
+ agent_object_names = ["bottles (red, blue, green, yellow; each with a square neck and a small round white stopper)",
264
+ "small wooden side table with four coloured spots (red, blue, green, yellow)"]
265
+
266
+ # ------------------------------------------------------------ scene
267
+ def make_bddl(self):
268
+ objs = []
269
+ for i, (c, b) in enumerate(zip(COLOURS, BOTTLES)):
270
+ cat = register_generated(f"LffLhwBottle{c.capitalize()}", bottle_xml(f"lff_lhw_bottle_{c}", RGBA[c]))
271
+ objs.append((b, cat, f"bottle{i}_region", (-0.30 + 0.13 * i, 0.30, -0.29 + 0.13 * i, 0.31)))
272
+ cat = register_generated("LffLhwSideTable", table_xml("lff_lhw_table"))
273
+ objs.append((TABLE, cat, "table_region", (-0.05, -0.30, -0.04, -0.29)))
274
+ return write_bddl(self.name, "Stand each bottle on the spot of its colour on the small table", objs, [])
275
+
276
+ def __init__(self, cam_res=None):
277
+ super().__init__(cam_res)
278
+ m = self.env.sim.model
279
+ self.tbid = envs.body_id(self.env, TABLE)
280
+ pre = f"{TABLE}_lff_lhw_table"
281
+ self.leg_gid = [m.geom_name2id(f"{pre}_leg{k}") for k in range(4)]
282
+ self.top_gid = m.geom_name2id(f"{pre}_top")
283
+ self.leg_size0 = [m.geom_size[g].copy() for g in self.leg_gid]
284
+ self.leg_pos0 = [m.geom_pos[g].copy() for g in self.leg_gid]
285
+ self.tbl_ipos0 = m.body_ipos[self.tbid].copy()
286
+ self.spot_gid = [m.geom_name2id(f"{pre}_spot{k}") for k in range(4)]
287
+ self.bbid = {b: envs.body_id(self.env, b) for b in BOTTLES}
288
+ self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhw_bottle_{c}_cap") for c, b in zip(COLOURS, BOTTLES)}
289
+ self.dof = {b: envs.free_joint_addr(self.env, b)[1] for b in BOTTLES}
290
+ self.tbl_dof = envs.free_joint_addr(self.env, TABLE)[1]
291
+ self.bgeoms = {b: envs.obj_geom_ids(self.env, b) for b in BOTTLES}
292
+ self.finger_geoms, self.hand_geoms, self.arm_geoms = [], [], []
293
+ for g in envs.robot_geom_ids(self.env):
294
+ n = m.geom_id2name(g) or ""
295
+ (self.finger_geoms if "finger" in n else self.hand_geoms if n.startswith("gripper0_")
296
+ else self.arm_geoms).append(g)
297
+ # per-geom lookup tables for the substep contact check: bottle index (-1 none), robot part (1 finger, 2 hand,
298
+ # 3 arm), table geom
299
+ self.owner = np.full(m.ngeom, -1, int)
300
+ for i, b in enumerate(BOTTLES):
301
+ self.owner[self.bgeoms[b]] = i
302
+ self.part = np.zeros(m.ngeom, int)
303
+ self.part[self.finger_geoms] = 1
304
+ self.part[self.hand_geoms] = 2
305
+ self.part[self.arm_geoms] = 3
306
+ self.is_table = np.zeros(m.ngeom, bool)
307
+ self.is_table[envs.obj_geom_ids(self.env, TABLE)] = True
308
+ self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
309
+ # contacts are collected after every MuJoCo substep (same technique as lh_nudge_row; wrappers chain)
310
+ sim = self.env.sim
311
+ if not getattr(sim, "_lhw_wrapped", False):
312
+ orig = sim.step
313
+
314
+ def step(*a, **k):
315
+ orig(*a, **k)
316
+ t = getattr(sim, "_lhw_task", None)
317
+ if t is not None and t.mon is not None:
318
+ t._substep()
319
+ sim.step = step
320
+ sim._lhw_wrapped = True
321
+ sim._lhw_task = self
322
+ self.inst = None
323
+ self.mon = None
324
+ self.sk = None
325
+ self._held_prev = None
326
+
327
+ def _substep(self):
328
+ d = self.env.sim.data
329
+ n = d.ncon
330
+ if not n:
331
+ return
332
+ g1 = np.asarray(d.contact.geom1)[:n]
333
+ g2 = np.asarray(d.contact.geom2)[:n]
334
+ o1, o2 = self.owner[g1], self.owner[g2]
335
+ for a, b, pa, pb in zip(g1, g2, o1, o2):
336
+ if pa < 0 and pb < 0:
337
+ if (self.is_table[a] and self.part[b]) or (self.is_table[b] and self.part[a]):
338
+ self._sub_tbl = 1
339
+ continue
340
+ if pa >= 0 and pb >= 0:
341
+ if pa != pb:
342
+ self._sub_obj[int(pa)] = int(pb)
343
+ self._sub_obj[int(pb)] = int(pa)
344
+ continue
345
+ p, o = (pa, b) if pa >= 0 else (pb, a)
346
+ part = int(self.part[o])
347
+ if part:
348
+ self._sub_rob[int(p)] = min(self._sub_rob.get(int(p), 9), part)
349
+
350
+ # ------------------------------------------------------------ instances
351
+ @staticmethod
352
+ def _supply(side, tx, ty, j):
353
+ """slot j (0-3) of the row of bottles on the main table: in front of the side table (robot side) or beside it;
354
+ every grasp point stays within 0.70 m (horizontal) of the robot base (the arm stalled 2-3 cm short of low
355
+ targets beyond ~0.72 m, measured)"""
356
+ if side == "front":
357
+ return [tx - 0.215, ty + (j - 1.5) * 0.085]
358
+ sg = 1.0 if side == "left" else -1.0
359
+ return [tx - 0.05 + (j - 1.5) * 0.075, ty + sg * 0.22]
360
+
361
+ @staticmethod
362
+ def _far_first(spot_of, side, tx, ty):
363
+ """colours in the order of the scripted naive policy: the spots farthest from the supply first (a careful agent
364
+ does not reach over bottles it has already put down), ties broken to the left, then far"""
365
+ sup = np.mean([WobblyTable._supply(side, tx, ty, j) for j in range(4)], axis=0)
366
+ sc = []
367
+ for c, k in spot_of.items():
368
+ sx, sy = CORNERS[k]
369
+ p = np.array([tx + sx * SPOT_O, ty + sy * SPOT_O])
370
+ sc.append((-round(float(np.linalg.norm(p - sup)), 3), -sy, -sx, c))
371
+ return [t[-1] for t in sorted(sc)]
372
+
373
+ def sample_instance(self, seed):
374
+ rng = np.random.default_rng(seed)
375
+ tx = float(rng.uniform(-0.13, -0.09)) # side table centre: 53-57 cm in front of the robot base
376
+ ty = float(rng.uniform(-0.04, 0.04))
377
+ side = str(rng.choice(["left", "right", "front"]))
378
+ perm = [int(v) for v in rng.permutation(4)] # perm[corner] = colour index on that corner's spot
379
+ spot_of = {COLOURS[perm[k]]: k for k in range(4)}
380
+ # the heavy bottle and the short leg under its spot: balanced over seeds against the scripted naive order (far
381
+ # spots first): its spot comes 1st / 2nd / 3rd / 4th in that order for exactly 5 of every 20 consecutive seeds
382
+ order = self._far_first(spot_of, side, tx, ty)
383
+ pos = int((int(seed) * 7) % 20 // 5)
384
+ heavy = order[pos]
385
+ short = spot_of[heavy]
386
+ slots = [int(v) for v in rng.permutation(4)]
387
+ start = {}
388
+ for i in range(4):
389
+ x, y = self._supply(side, tx, ty, slots[i])
390
+ start[COLOURS[i]] = [x + float(rng.uniform(-0.006, 0.006)), y + float(rng.uniform(-0.006, 0.006))]
391
+ mass = {c: float(rng.uniform(*LIGHT_MASS)) for c in COLOURS}
392
+ com = {c: float(rng.uniform(*LIGHT_COM)) for c in COLOURS}
393
+ mass[heavy] = float(rng.uniform(*HEAVY_MASS))
394
+ com[heavy] = float(rng.uniform(*HEAVY_COM))
395
+ return dict(seed=int(seed), table_xy=[tx, ty], short_leg=int(short), short_corner=CORNER_NAME[CORNERS[short]],
396
+ heavy=heavy, heavy_rank_naive=pos + 1, spot_of=spot_of, supply_side=side, start=start, mass=mass,
397
+ com=com, short_h=float(rng.uniform(*SHORT_H)), com_bias=COM_BIAS,
398
+ yaw0={c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS},
399
+ naive_bias_x=float(rng.uniform(*NAIVE_BIAS)))
400
+
401
+ def apply_instance(self, inst):
402
+ self.inst = inst
403
+ m = self.env.sim.model
404
+ k = inst["short_leg"]
405
+ h = float(inst["short_h"])
406
+ for j, g in enumerate(self.leg_gid):
407
+ m.geom_size[g] = self.leg_size0[j]
408
+ m.geom_pos[g] = self.leg_pos0[j]
409
+ g = self.leg_gid[k]
410
+ m.geom_size[g][1] = self.leg_size0[k][1] - h / 2 # capsule half length
411
+ m.geom_pos[g][2] = self.leg_pos0[k][2] + h / 2
412
+ opp = CORNERS[(k + 2) % 4]
413
+ b = float(inst.get("com_bias", COM_BIAS)) / np.sqrt(2)
414
+ m.body_ipos[self.tbid] = [opp[0] * b, opp[1] * b, self.tbl_ipos0[2]]
415
+ envs.refit_bounds(m, self.tbid)
416
+ for c in COLOURS:
417
+ m.geom_rgba[self.spot_gid[inst["spot_of"][c]]] = SPOT_RGBA[c]
418
+ for c, bot in zip(COLOURS, BOTTLES):
419
+ bid = self.bbid[bot]
420
+ M, zc = inst["mass"][c], inst["com"][c]
421
+ m.body_mass[bid] = M
422
+ m.body_ipos[bid] = [0.0, 0.0, -H_TOT / 2 + zc]
423
+ # glass shell + internal weight, roughly: radius of gyration ~ 0.35 x height about horizontal axes
424
+ ixx = M * ((2 * RB) ** 2 / 12 + (0.35 * H_TOT) ** 2)
425
+ m.body_inertia[bid] = [ixx, ixx, M * (2 * RB) ** 2 / 6]
426
+ envs.refit_bounds(m, bid)
427
+ m.dof_damping[self.dof[bot]:self.dof[bot] + 6] = BOT_DAMP
428
+ self.env.sim.forward()
429
+ tx, ty = inst["table_xy"]
430
+ # yaw pi: the canonical quaternion LIBERO gives generated objects is a 180 deg yaw (envs.canonical_quat); with
431
+ # it the table frame is the world frame
432
+ envs.place_upright(self.env, TABLE, [tx, ty], yaw=np.pi, clearance=0.0003)
433
+ for c, bot in zip(COLOURS, BOTTLES):
434
+ envs.place_upright(self.env, bot, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
435
+ self.env.sim.data.qvel[self.tbl_dof:self.tbl_dof + 6] = 0.0
436
+
437
+ def reset_instance(self, inst, recorder=None):
438
+ self.mon = None
439
+ self.env.reset()
440
+ self.apply_instance(inst)
441
+ self.env.sim.forward()
442
+ envs.settle(self.env, 15)
443
+ self.sk = WobblySkills(self.env, self, recorder=recorder)
444
+ self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
445
+ self._held_prev = None
446
+ self.table0 = dict(pos=self.table_pos().tolist(), yaw=self.table_yaw())
447
+ n = len(BOTTLES)
448
+ self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
449
+ lost_cause=[None] * n, last_robot=[None] * n, last_obj=[None] * n, last_release=None,
450
+ last_table_touch=-10 ** 6, rocked=False, rock_since=0, rocks=[], n_steps=0,
451
+ max_table_tilt_deg=0.0)
452
+ return self.sk
453
+
454
+ # ------------------------------------------------------------ geometry / predicates
455
+ def table_R(self):
456
+ return self.env.sim.data.body_xmat[self.tbid].reshape(3, 3).copy()
457
+
458
+ def table_pos(self):
459
+ return self.env.sim.data.body_xpos[self.tbid].copy()
460
+
461
+ def table_yaw(self):
462
+ R = self.table_R()
463
+ return float(np.arctan2(R[1, 0], R[0, 0]))
464
+
465
+ def table_tilt(self):
466
+ return float(np.arccos(np.clip(self.table_R()[2, 2], -1, 1)))
467
+
468
+ def top_point(self, local_xy):
469
+ """world position of a point on the table's top surface (table frame xy)"""
470
+ return self.table_pos() + self.table_R() @ np.array([local_xy[0], local_xy[1], TABLE_H / 2])
471
+
472
+ def spot_local(self, colour):
473
+ sx, sy = CORNERS[self.inst["spot_of"][colour]]
474
+ return np.array([sx * SPOT_O, sy * SPOT_O])
475
+
476
+ def spot_world(self, colour):
477
+ return self.top_point(self.spot_local(colour))
478
+
479
+ def top_z_at(self, xy):
480
+ """z of the table's top plane above world point xy"""
481
+ R, p = self.table_R(), self.table_pos()
482
+ n = R[:, 2]
483
+ c = p + n * TABLE_H / 2
484
+ return float(c[2] - (n[0] * (xy[0] - c[0]) + n[1] * (xy[1] - c[1])) / max(n[2], 1e-6))
485
+
486
+ def over_table(self, xy):
487
+ loc = self.table_R().T @ (np.array([xy[0], xy[1], self.table_pos()[2]]) - self.table_pos())
488
+ return abs(loc[0]) < TOP_HW and abs(loc[1]) < TOP_HW
489
+
490
+ def bR(self, b):
491
+ return self.env.sim.data.body_xmat[self.bbid[b]].reshape(3, 3).copy()
492
+
493
+ def bpos(self, b):
494
+ return self.env.sim.data.body_xpos[self.bbid[b]].copy()
495
+
496
+ def foot(self, b):
497
+ """world position of the centre of the bottle's bottom face"""
498
+ return self.bpos(b) - self.bR(b)[:, 2] * H_TOT / 2
499
+
500
+ def tilt(self, b):
501
+ return float(np.arccos(np.clip(self.bR(b)[2, 2], -1.0, 1.0)))
502
+
503
+ def cap_xyz(self, b):
504
+ return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy()
505
+
506
+ def held(self, b):
507
+ return self.sk is not None and self.sk.holding(b)
508
+
509
+ def offset(self, i):
510
+ """bottle i's foot centre relative to its spot centre, in the table frame (x forward-back, y left-right), and
511
+ the height of its bottom above the table top"""
512
+ b, c = BOTTLES[i], COLOURS[i]
513
+ loc = self.table_R().T @ (self.foot(b) - self.table_pos())
514
+ return loc[:2] - self.spot_local(c), float(loc[2] - TABLE_H / 2)
515
+
516
+ def on_spot(self, i, extra=0.0):
517
+ b = BOTTLES[i]
518
+ if self.tilt(b) > TILT_OK + (np.radians(2.0) if extra else 0.0):
519
+ return False
520
+ off, dz = self.offset(i)
521
+ if abs(off[0]) > TOL_X + extra or abs(off[1]) > TOL_Y + extra or abs(dz) > ON_TOP:
522
+ return False
523
+ return not self.held(b)
524
+
525
+ def stages(self):
526
+ return [self.on_spot(i) for i in range(len(BOTTLES))]
527
+
528
+ def table_ok(self):
529
+ p0 = np.asarray(self.table0["pos"])
530
+ moved = float(np.linalg.norm(self.table_pos()[:2] - p0[:2]))
531
+ dyaw = abs(_ang(self.table_yaw() - self.table0["yaw"]))
532
+ return bool(moved <= TABLE_MOVE_TOL and dyaw <= TABLE_YAW_TOL and self.table_tilt() <= TABLE_TILT_MAX), moved, dyaw
533
+
534
+ def low_corner(self):
535
+ """robot-centric name of the table corner that is lowest (after a rock: the corner over the short leg)"""
536
+ zs = {k: self.top_point([sx * TOP_HW, sy * TOP_HW])[2] for k, (sx, sy) in enumerate(CORNERS)}
537
+ return CORNER_NAME[CORNERS[min(zs, key=zs.get)]]
538
+
539
+ # ------------------------------------------------------------ monitor
540
+ def monitor_step(self):
541
+ mon = self.mon
542
+ if mon is None or self.sk is None:
543
+ return
544
+ mon["n_steps"] += 1
545
+ t = int(self.sk.n_steps)
546
+ rob, obj, tbl = dict(self._sub_rob), dict(self._sub_obj), self._sub_tbl
547
+ self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
548
+ gstate = "open" if self.sk.grip < 0 else "closed"
549
+ held_now = None
550
+ for c, b in zip(COLOURS, BOTTLES):
551
+ if gstate == "closed" and self.held(b):
552
+ held_now = c
553
+ for i, part in rob.items():
554
+ if COLOURS[i] != held_now:
555
+ mon["last_robot"][i] = [{1: "finger", 2: "hand", 3: "arm"}[part], t, gstate]
556
+ for i, j in obj.items():
557
+ mon["last_obj"][i] = [COLOURS[j], t]
558
+ if tbl:
559
+ mon["last_table_touch"] = t
560
+ if held_now is None and self._held_prev is not None: # the gripper has just let go of a bottle
561
+ mon["last_release"] = [self._held_prev, t]
562
+ self._held_prev = held_now
563
+ tl = self.table_tilt()
564
+ mon["max_table_tilt_deg"] = max(mon["max_table_tilt_deg"], round(float(np.degrees(tl)), 2))
565
+ if mon["n_steps"] % 2:
566
+ return
567
+ # ---- table rock detector (debounced)
568
+ want = tl > ROCK_ON if not mon["rocked"] else tl > ROCK_OFF
569
+ if want != mon["rocked"]:
570
+ mon["rock_since"] += 2
571
+ if mon["rock_since"] >= 4:
572
+ mon["rocked"] = want
573
+ mon["rock_since"] = 0
574
+ self._rock_event(want, t - 3)
575
+ else:
576
+ mon["rock_since"] = 0
577
+ for r in mon["rocks"]:
578
+ if not r.get("closed") and t - r["step"] > FELL_WINDOW:
579
+ self._close_rock(r)
580
+ # ---- stage predicates
581
+ for i in range(len(BOTTLES)):
582
+ b = BOTTLES[i]
583
+ raw = self.on_spot(i, HYST if mon["state"][i] else 0.0)
584
+ if raw == mon["state"][i]:
585
+ mon["raw_since"][i] = 0
586
+ continue
587
+ mon["raw_since"][i] += 2
588
+ if mon["raw_since"][i] < DEBOUNCE:
589
+ continue
590
+ mon["state"][i] = raw
591
+ mon["raw_since"][i] = 0
592
+ t0 = int(t - DEBOUNCE + 1)
593
+ if raw:
594
+ restored = mon["lost"][i]
595
+ e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0)
596
+ if restored:
597
+ e["after"] = mon["lost_cause"][i]
598
+ mon["events"].append(e)
599
+ mon["ever"][i] = True
600
+ else:
601
+ mon["lost"][i] = True
602
+ cause = self._cause(i, t0)
603
+ mon["lost_cause"][i] = cause
604
+ off, dz = self.offset(i)
605
+ mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause,
606
+ tilt_deg=round(float(np.degrees(self.tilt(b))), 1),
607
+ offset_cm=[round(100 * float(v), 1) for v in off]))
608
+
609
+ def _rock_event(self, down, t):
610
+ mon = self.mon
611
+ rel = mon["last_release"]
612
+ e = dict(event="table_rocked" if down else "table_rocked_back", step=int(t),
613
+ table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), low_corner=self.low_corner(),
614
+ released=rel[0] if rel is not None and t - rel[1] <= 40 else None,
615
+ robot_touched_table=bool(t - mon["last_table_touch"] <= 20),
616
+ standing=[COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i]])
617
+ # the cheap explanation would be "my hand bumped them": which of the standing bottles did the robot touch in
618
+ # the 2 s before the rock (should be none)
619
+ e["robot_touched_before"] = [COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i] and
620
+ mon["last_robot"][i] is not None and t - mon["last_robot"][i][1] <= 40]
621
+ mon["events"].append(e)
622
+ mon["rocks"].append(dict(step=int(t), down=bool(down), standing=list(e["standing"]), event=e))
623
+
624
+ def _close_rock(self, r):
625
+ """FELL_WINDOW after a rock: which of the bottles that stood on their spots fell, and did the robot touch any
626
+ of them after the rock began (a falling bottle hitting the open fingers)"""
627
+ r["closed"] = True
628
+ mon = self.mon
629
+ fell, touched = [], []
630
+ for c in r["standing"]:
631
+ i = COLOURS.index(c)
632
+ if self.tilt(BOTTLES[i]) > np.radians(30) or not mon["state"][i]:
633
+ fell.append(c)
634
+ lr = mon["last_robot"][i]
635
+ if lr is not None and lr[1] >= r["step"]:
636
+ touched.append(c)
637
+ r["event"]["fell"] = fell
638
+ r["event"]["robot_touched_while_falling"] = touched
639
+ r["fell"] = fell
640
+
641
+ def _cause(self, i, t, window=60):
642
+ if self.held(BOTTLES[i]):
643
+ return "picked_up"
644
+ mon = self.mon
645
+ for r in reversed(mon["rocks"]):
646
+ if 0 <= t - r["step"] <= FELL_WINDOW + 10 and COLOURS[i] in r["standing"]:
647
+ return "table_rocked" if r["down"] else "table_rocked_back"
648
+ lr, lo = mon["last_robot"][i], mon["last_obj"][i]
649
+ cands = []
650
+ if lr is not None and t - lr[1] <= window:
651
+ cands.append((lr[1], f"robot_{lr[0]}"))
652
+ if lo is not None and t - lo[1] <= window:
653
+ cands.append((lo[1] - 30, "bottle:" + lo[0]))
654
+ return max(cands)[1] if cands else "other"
655
+
656
+ def _finalize_monitor(self, raw):
657
+ mon = self.mon
658
+ if mon is None:
659
+ return
660
+ for r in mon["rocks"]:
661
+ if not r.get("closed"):
662
+ self._close_rock(r)
663
+ t = int(self.sk.n_steps)
664
+ for i in range(len(BOTTLES)):
665
+ if raw[i] == mon["state"][i]:
666
+ continue
667
+ mon["state"][i] = raw[i]
668
+ if raw[i]:
669
+ restored = mon["lost"][i]
670
+ e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True)
671
+ if restored:
672
+ e["after"] = mon["lost_cause"][i]
673
+ mon["events"].append(e)
674
+ mon["ever"][i] = True
675
+ else:
676
+ mon["lost"][i] = True
677
+ cause = self._cause(i, t, window=10 ** 6)
678
+ mon["lost_cause"][i] = cause
679
+ mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True))
680
+
681
+ # ------------------------------------------------------------ outcome
682
+ def _touching(self):
683
+ d = self.env.sim.data
684
+ for j in range(d.ncon):
685
+ c = d.contact[j]
686
+ if (self.owner[c.geom1] >= 0 and self.part[c.geom2]) or (self.owner[c.geom2] >= 0 and self.part[c.geom1]):
687
+ return True
688
+ return False
689
+
690
+ def outcome(self, inst):
691
+ sk = self.sk
692
+ sk.hold(10)
693
+ p0 = {b: self.bpos(b) for b in BOTTLES}
694
+ t0 = self.table_pos()
695
+ touching = False
696
+ for _ in range(20):
697
+ sk.hold(1)
698
+ touching = touching or self._touching()
699
+ moved = max([float(np.linalg.norm(self.bpos(b) - p0[b])) for b in BOTTLES] +
700
+ [float(np.linalg.norm(self.table_pos() - t0))])
701
+ static = moved < 0.003
702
+ raw = self.stages()
703
+ self._finalize_monitor(raw)
704
+ held = [COLOURS[i] for i, b in enumerate(BOTTLES) if self.held(b)]
705
+ tok, tmoved, tyaw = self.table_ok()
706
+ mon = self.mon
707
+ ev = list(mon["events"])
708
+ rocks = [r for r in mon["rocks"] if r["down"]]
709
+ damaging = [r for r in mon["rocks"] if r.get("fell")]
710
+ n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
711
+ n_lost = sum(e.get("event") == "lost" for e in ev)
712
+ n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
713
+ success = bool(all(raw) and static and not held and not touching and tok)
714
+ tilted = [i for i in range(len(BOTTLES)) if self.tilt(BOTTLES[i]) > TILT_OK and COLOURS[i] not in held]
715
+ ever = mon["ever"]
716
+ fell_by_rock = sorted({c for r in damaging for c in r["fell"]})
717
+ if success:
718
+ failure = "none"
719
+ elif not tok:
720
+ failure = "table_moved"
721
+ elif held:
722
+ failure = "held"
723
+ elif tilted:
724
+ failure = "toppled_by_rock" if any(COLOURS[i] in fell_by_rock for i in tilted) else "toppled"
725
+ elif not all(raw):
726
+ failure = "not_on_spot"
727
+ elif touching:
728
+ failure = "touching"
729
+ else:
730
+ failure = "not_static"
731
+ parts = []
732
+ if success:
733
+ parts.append("Every bottle stands upright on the spot of its colour.")
734
+ for i in range(len(BOTTLES)):
735
+ if raw[i]:
736
+ continue
737
+ c, b = COLOURS[i], BOTTLES[i]
738
+ if c in held:
739
+ parts.append(f"The {c} bottle is still held by the gripper.")
740
+ continue
741
+ off, dz = self.offset(i)
742
+ tl = float(np.degrees(self.tilt(b)))
743
+ on_small = abs(dz) < 0.05 and max(abs(off + self.spot_local(c))) < TOP_HW + 0.02
744
+ if tl > np.degrees(TILT_OK):
745
+ txt = (f"The {c} bottle lies on its side on the {'small' if on_small else 'big'} table" if tl > 45 else
746
+ f"The {c} bottle leans {tl:.0f} degrees") + "."
747
+ elif abs(dz) > ON_TOP:
748
+ txt = f"The {c} bottle is not on the small table."
749
+ else:
750
+ txt = f"The {c} bottle stands {_fb(off[0])} and {_lr(off[1])} of its spot's centre, not on its spot."
751
+ if ever[i] and c in fell_by_rock:
752
+ txt += " It had stood on its spot and fell when the small table rocked."
753
+ elif ever[i]:
754
+ txt += " It had stood on its spot earlier."
755
+ parts.append(txt)
756
+ if not tok:
757
+ parts.append(f"The small table was moved ({100 * tmoved:.1f} cm, {np.degrees(tyaw):.0f} degrees).")
758
+ elif not success and all(raw):
759
+ if touching:
760
+ parts.append("The gripper is still touching a bottle.")
761
+ elif not static:
762
+ parts.append("Something was still moving.")
763
+ if rocks:
764
+ r = rocks[0]["event"]
765
+ txt = (f"When the {r['released']} bottle was set down, the small table rocked down onto its "
766
+ f"{r['low_corner']} leg" if r.get("released") else
767
+ f"The small table rocked down onto its {r['low_corner']} leg")
768
+ fl = r.get("fell", [])
769
+ txt += (" and the " + " and ".join(fl) + f" bottle{'s' if len(fl) > 1 else ''} standing on it fell over."
770
+ if fl else ".")
771
+ txt += f" That leg is {100 * float(inst['short_h']):.1f} cm shorter than the other three."
772
+ parts.append(txt)
773
+ trap = bool(damaging)
774
+ return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(BOTTLES))}, events=ev,
775
+ n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_rocks=len(rocks),
776
+ rocked=bool(rocks), trap_fired=trap, recovered_in_attempt=bool(trap and success),
777
+ fell_by_rock=fell_by_rock, failure=failure, held=held, touching=bool(touching),
778
+ static=bool(static), table_ok=bool(tok), table_moved_cm=round(100 * tmoved, 2),
779
+ table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2),
780
+ max_table_tilt_deg=mon["max_table_tilt_deg"],
781
+ offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)[0]] for i in range(4)},
782
+ tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(BOTTLES[i]))), 1) for i in range(4)},
783
+ heavy=inst["heavy"], short_corner=inst["short_corner"], detail=" ".join(parts))
784
+
785
+ # ------------------------------------------------------------ scripted primitives (move_to + gripper only)
786
+ def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
787
+ return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
788
+
789
+ def _lift_to(self, z, speed=0.2):
790
+ cur = self.sk.eef_pos()
791
+ if cur[2] < TZ + z - 0.005:
792
+ self._go([cur[0], cur[1], TZ + z], speed=speed)
793
+
794
+ def _settle(self, b, max_checks=25):
795
+ d = self.env.sim.data
796
+ da = self.dof[b]
797
+ for _ in range(max_checks):
798
+ if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
799
+ return
800
+ self.sk.hold(2)
801
+
802
+ def upright(self, b):
803
+ return self.tilt(b) < np.radians(20)
804
+
805
+ def pick_neck(self, b, z_carry=Z_CARRY, yaw=0.0, v=0.2):
806
+ """Sonnet-like top-down pick of a standing bottle: open, over it at carry height, straight down to the upper
807
+ neck, close, lift to carry height. Returns True if held."""
808
+ sk = self.sk
809
+ self._settle(b)
810
+ p = self.foot(b)
811
+ zg = p[2] + NECK_Z[1] - GRASP_NECK
812
+ sk.set_gripper(False, steps=8)
813
+ self._lift_to(z_carry)
814
+ self._go([p[0], p[1], TZ + z_carry], yaw=yaw, speed=v)
815
+ self._go([p[0], p[1], zg + 0.02], speed=0.12)
816
+ self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150)
817
+ sk.set_gripper(True, steps=15)
818
+ self._go([p[0], p[1], TZ + z_carry], speed=0.12)
819
+ sk.hold(5)
820
+ if not self.held(b):
821
+ sk.set_gripper(False, steps=8)
822
+ return False
823
+ return True
824
+
825
+ def put_held(self, b, xy, gap, z_carry=Z_CARRY, yaw=None, v=0.2):
826
+ """carry the held bottle so that its foot is over world xy, straight down until its bottom is `gap` above the
827
+ surface below, let go, lift"""
828
+ sk = self.sk
829
+ rel = self.foot(b)[:2] - sk.eef_pos()[:2]
830
+ q = np.asarray(xy, float) - rel
831
+ self._go([q[0], q[1], TZ + z_carry], yaw=yaw, speed=v)
832
+ sk.hold(10)
833
+ rel = self.foot(b)[:2] - sk.eef_pos()[:2] # a bottle hanging from its stopper swings while carried
834
+ q = np.asarray(xy, float) - rel
835
+ surf = self.top_z_at(xy) if self.over_table(xy) else TZ
836
+ dz = sk.eef_pos()[2] - self.foot(b)[2]
837
+ zr = surf + dz + gap
838
+ self._go([q[0], q[1], zr + 0.02], speed=0.10)
839
+ self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
840
+ sk.hold(4)
841
+ sk.set_gripper(False, steps=12)
842
+ cur = sk.eef_pos()
843
+ self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.10)
844
+ self._go([cur[0], cur[1], TZ + z_carry], speed=0.2)
845
+ sk.hold(3)
846
+
847
+ def surface_z(self, xy):
848
+ return self.top_z_at(xy) if self.over_table(xy) else TZ
849
+
850
+ def pick_stopper(self, b, v=0.15):
851
+ """grasp a lying (or leaning) bottle by its round stopper from above, fingers across the bottle's axis, lift it
852
+ until it hangs free. The fingertips stay >= 4 mm above the surface under the stopper: pressing the raised half
853
+ of the rocked table rocks it back (measured), and the knock when it comes down again topples standing bottles.
854
+ Returns True if held."""
855
+ sk = self.sk
856
+ self._settle(b)
857
+ for _ in range(2):
858
+ k, zg, yaw = self.stopper_grasp(b) # fingers across the bottle's axis
859
+ sk.set_gripper(False, steps=8)
860
+ self._lift_to(Z_HANG)
861
+ self._go([k[0], k[1], TZ + Z_HANG], yaw=yaw, speed=v)
862
+ sk.hold(5)
863
+ k, zg, _ = self.stopper_grasp(b)
864
+ self._go([k[0], k[1], zg + 0.03], speed=0.10)
865
+ self._go([k[0], k[1], zg], speed=0.03, tol=0.003, max_steps=120)
866
+ sk.set_gripper(True, steps=15)
867
+ if not self.held(b):
868
+ sk.set_gripper(False, steps=8)
869
+ self._go([k[0], k[1], zg + 0.08], speed=0.1)
870
+ continue
871
+ self._go([k[0], k[1], zg + 0.05], speed=0.05)
872
+ self._go([k[0], k[1], TZ + Z_HANG], speed=0.10)
873
+ sk.hold(20)
874
+ return True
875
+ return False
876
+
877
+ # gripper footprint (measured, t8_hand): the hand's collision hull is a slab 20 cm along the finger axis and ~4 cm
878
+ # across, from 3 cm above the grasp point up; open fingers 3.9-6.6 cm out along the finger axis, from 1 cm below
879
+ # the grasp point to 4.5 cm above it
880
+ HAND_U, HAND_V, HAND_Z0 = 0.100, (-0.018, 0.024), 0.03
881
+ FING_U, FING_V, FING_Z = (0.039, 0.066), (-0.009, 0.013), (-0.010, 0.045)
882
+ # wrist and forearm (t16_arm, measured at low grasps): lowest point above the grasp point vs the distance from the
883
+ # grasp point towards the robot base; they span ~13 cm to either side of that line
884
+ ARM_D = (-0.05, 0.05, 0.10, 0.15, 0.20)
885
+ ARM_Z = (0.097, 0.100, 0.155, 0.185, 0.31)
886
+ ARM_LAT = 0.13
887
+
888
+ def _footprint(self, q, yaw):
889
+ """sample points (xy) of the hand slab and of the open fingers for a grasp at q with gripper yaw `yaw`"""
890
+ a = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis
891
+ c = np.array([np.cos(yaw), np.sin(yaw)])
892
+ hand = [q + u * a + v * c for u in np.linspace(-self.HAND_U, self.HAND_U, 21)
893
+ for v in np.linspace(*self.HAND_V, 5)]
894
+ fing = [q + sg * u * a + v * c for sg in (-1, 1) for u in np.linspace(*self.FING_U, 4)
895
+ for v in np.linspace(*self.FING_V, 3)]
896
+ return np.array(hand), np.array(fing)
897
+
898
+ def grasp_clearance(self, q, zg, yaw, ignore=()):
899
+ """smallest horizontal clearance (m) between the hand / open fingers of a grasp at (q, zg) and any standing
900
+ bottle (other than `ignore`) or the small table; negative = collision"""
901
+ q = np.asarray(q, float)[:2]
902
+ hand, fing = self._footprint(q, yaw)
903
+ best = 1.0
904
+ for b in BOTTLES:
905
+ if b in ignore or self.held(b) or self.tilt(b) > np.radians(30):
906
+ continue
907
+ p = self.foot(b)[:2]
908
+ top = self.foot(b)[2] + H_TOT
909
+ r = RB * 1.42
910
+ if top > zg + self.HAND_Z0:
911
+ best = min(best, float(np.min(np.linalg.norm(hand - p, axis=1))) - r)
912
+ best = min(best, float(np.min(np.linalg.norm(fing - p, axis=1))) - r)
913
+ # the wrist / forearm sloping back towards the robot base over a tall standing bottle
914
+ ub = np.array([-0.66, 0.0]) - q
915
+ ub /= max(float(np.linalg.norm(ub)), 1e-6)
916
+ along, lat = float((p - q) @ ub), float((p - q) @ np.array([-ub[1], ub[0]]))
917
+ if self.ARM_D[0] <= along <= self.ARM_D[-1] and abs(lat) < self.ARM_LAT + r:
918
+ if top > zg + float(np.interp(along, self.ARM_D, self.ARM_Z)) - 0.01:
919
+ best = min(best, -0.01)
920
+ # the small table's top plate (and legs) when the grasp is below its top surface
921
+ R, P = self.table_R(), self.table_pos()
922
+ ztop = P[2] + TABLE_H / 2
923
+ for pts, z0, z1 in ((hand, zg + self.HAND_Z0, zg + 0.13), (fing, zg + self.FING_Z[0], zg + self.FING_Z[1])):
924
+ if z0 > ztop + 0.003:
925
+ continue
926
+ loc = (pts - P[:2]) @ R[:2, :2]
927
+ if z1 > ztop - TOP_T: # the plate's height band
928
+ d = np.maximum(np.abs(loc) - TOP_HW, 0.0)
929
+ inside = np.all(np.abs(loc) < TOP_HW, axis=1)
930
+ dist = np.where(inside, -0.01, np.linalg.norm(d, axis=1))
931
+ best = min(best, float(np.min(dist)))
932
+ return best
933
+
934
+ def stopper_grasp(self, b):
935
+ """(xy, z, yaw) of the stopper grasp of a lying bottle: fingers across its axis, fingertips >= 4 mm above the
936
+ surface below"""
937
+ k = self.cap_xyz(b)
938
+ ax = self.bR(b)[:2, 2]
939
+ yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw
940
+ zg = max(float(k[2]), self.surface_z(k[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004)
941
+ return k[:2], zg, yaw
942
+
943
+ def body_grasp(self, b, along=None):
944
+ """(xy, z, yaw) of a grasp across a lying bottle's body, `along` m from its bottom (default: the middle)"""
945
+ R = self.bR(b)
946
+ a = HF + (HB - HF) / 2 if along is None else float(along)
947
+ c = self.foot(b) + R[:, 2] * a
948
+ ax = R[:2, 2]
949
+ yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw
950
+ zg = max(float(c[2]), self.surface_z(c[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004)
951
+ return c[:2], zg, yaw
952
+
953
+ def staging_spot(self, b):
954
+ """a free place on the main table to lay a fallen bottle down: far from the small table and the other bottles,
955
+ within the arm's comfortable reach"""
956
+ tx, ty = self.table_pos()[:2]
957
+ best, bq = -1.0, None
958
+ for x in np.arange(tx - 0.30, tx + 0.06, 0.03):
959
+ for y in np.arange(ty - 0.30, ty + 0.31, 0.03):
960
+ # within reach, and >= 14 cm inside the main table's edges (it spans x, y = +-0.5, +-0.6): a bottle laid
961
+ # down too close to the near edge rolled off onto the floor (measured)
962
+ if np.hypot(x + 0.66, y) > 0.66 or np.hypot(x + 0.66, y) < 0.33 or x < -0.36 or abs(y) > 0.46:
963
+ continue
964
+ loc = self.table_R()[:2, :2].T @ (np.array([x, y]) - np.array([tx, ty]))
965
+ dt = float(np.linalg.norm(np.maximum(np.abs(loc) - TOP_HW, 0.0)))
966
+ if np.all(np.abs(loc) < TOP_HW):
967
+ continue
968
+ do = min([float(np.linalg.norm(self.foot(o)[:2] - [x, y])) for o in BOTTLES if o != b] +
969
+ [float(np.linalg.norm(self.cap_xyz(o)[:2] - [x, y])) for o in BOTTLES if o != b])
970
+ sc = min(dt - 0.10, do - 0.14) # the bottle lies ~16 cm long around the point
971
+ if sc > best and min(self.grasp_clearance([x, y], TZ + 0.016, yw, ignore=(b,))
972
+ for yw in (0.0, np.pi / 2)) > 0.01:
973
+ best, bq = sc, np.array([x, y])
974
+ return bq
975
+
976
+ def stage(self, b, v=0.12):
977
+ """the stopper of a fallen bottle cannot be reached: grasp its body at a point where the hand is clear (the
978
+ bottle then hangs from the grasp), carry it to free space on the main table, let it down there so that it falls
979
+ over away from everything. Returns True if it was moved."""
980
+ sk = self.sk
981
+ for along in (0.055, 0.035, 0.075, 0.015, 0.095):
982
+ q, zg, yaw = self.body_grasp(b, along)
983
+ if self.grasp_clearance(q, zg, yaw, ignore=(b,)) >= 0.004:
984
+ break
985
+ else:
986
+ return False
987
+ dst = self.staging_spot(b)
988
+ if dst is None:
989
+ return False
990
+ sk.set_gripper(False, steps=8)
991
+ self._lift_to(Z_CARRY)
992
+ self._go([q[0], q[1], TZ + Z_CARRY], yaw=yaw, speed=v)
993
+ self._go([q[0], q[1], zg + 0.03], speed=0.10)
994
+ self._go([q[0], q[1], zg], speed=0.03, tol=0.003, max_steps=120)
995
+ sk.set_gripper(True, steps=15)
996
+ if not self.held(b):
997
+ sk.set_gripper(False, steps=8)
998
+ self._go([q[0], q[1], TZ + Z_CARRY], speed=0.1)
999
+ return False
1000
+ self._go([q[0], q[1], zg + 0.04], speed=0.05)
1001
+ self._go([q[0], q[1], TZ + Z_HANG], speed=0.10)
1002
+ sk.hold(15)
1003
+ self._go([dst[0], dst[1], TZ + Z_HANG], speed=0.10)
1004
+ sk.hold(15)
1005
+ drop = envs.obj_min_z(self.env, b) - (TZ + 0.012)
1006
+ cur = sk.eef_pos()
1007
+ self._go([cur[0], cur[1], cur[2] - drop], speed=0.08)
1008
+ sk.set_gripper(False, steps=12)
1009
+ cur = sk.eef_pos()
1010
+ self._go([cur[0], cur[1], TZ + Z_HANG], speed=0.15)
1011
+ self._settle(b, 40)
1012
+ return True
1013
+
1014
+ def restand(self, i, gap=CAREFUL_GAP, err=None):
1015
+ """stand bottle i up again on its spot: if the stopper cannot be grasped without the hand touching a standing
1016
+ bottle or the small table, first lay the bottle down in free space; grasp the stopper, let the bottle hang,
1017
+ carry it over the spot, lower it until its bottom is `gap` above the table top, let go"""
1018
+ b, c = BOTTLES[i], COLOURS[i]
1019
+ q, zg, yaw = self.stopper_grasp(b)
1020
+ if self.grasp_clearance(q, zg, yaw, ignore=(b,)) < 0.005:
1021
+ self.stage(b)
1022
+ if not self.pick_stopper(b):
1023
+ return False
1024
+ tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0)
1025
+ self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10)
1026
+ self._settle(b)
1027
+ return self.on_spot(i)
1028
+
1029
+ def place(self, i, gap, err=None, z_carry=Z_CARRY, yaw=0.0, v=0.2):
1030
+ """one stage: pick bottle i (by the neck if it stands, by the stopper if it lies) and put it on its spot"""
1031
+ b, c = BOTTLES[i], COLOURS[i]
1032
+ tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0)
1033
+ if self.upright(b):
1034
+ if not self.pick_neck(b, z_carry=z_carry, yaw=yaw, v=v) and not self.pick_neck(b, z_carry=z_carry,
1035
+ yaw=yaw, v=v):
1036
+ return False
1037
+ self.put_held(b, tgt, gap, z_carry=z_carry, yaw=yaw, v=v)
1038
+ else:
1039
+ if not self.pick_stopper(b):
1040
+ return False
1041
+ self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10)
1042
+ self._settle(b)
1043
+ return True
1044
+
1045
+ def repair_order(self, idx):
1046
+ """bottles to fix: one standing upright off its spot first (it may be the heavy one: re-placing it rocks the
1047
+ table), then lying ones whose stopper is easiest to reach"""
1048
+ def key(j):
1049
+ b = BOTTLES[j]
1050
+ if self.upright(b):
1051
+ return (0, 0.0)
1052
+ q, zg, yaw = self.stopper_grasp(b)
1053
+ return (1, -self.grasp_clearance(q, zg, yaw, ignore=(b,)))
1054
+ return sorted(idx, key=key)
1055
+
1056
+ def fix(self, i, gap=CAREFUL_GAP):
1057
+ if self.upright(BOTTLES[i]):
1058
+ self.place(i, gap)
1059
+ else:
1060
+ self.restand(i, gap)
1061
+
1062
+ def check_and_repair(self, rounds=3, gap=CAREFUL_GAP):
1063
+ """look at every bottle; stand up / re-place every one that is not on its spot"""
1064
+ for _ in range(rounds):
1065
+ bad = [i for i in range(4) if not self.on_spot(i)]
1066
+ if not bad:
1067
+ return True
1068
+ for i in self.repair_order(bad):
1069
+ if not self.on_spot(i):
1070
+ self.fix(i, gap)
1071
+ return all(self.stages())
1072
+
1073
+ def order(self, mode, rng=None, first=None):
1074
+ o = self._far_first(self.inst["spot_of"], self.inst["supply_side"], *self.inst["table_xy"])
1075
+ if mode == "near_first":
1076
+ o = o[::-1]
1077
+ elif mode == "random":
1078
+ o = [o[j] for j in rng.permutation(4)]
1079
+ if first is not None:
1080
+ o = [first] + [c for c in o if c != first]
1081
+ return [COLOURS.index(c) for c in o]
1082
+
1083
+ def execute(self, inst, params):
1084
+ rng = np.random.default_rng(params.get("noise_seed", 0))
1085
+ order = self.order(params.get("order", "far_first"), rng, params.get("first"))
1086
+ gap = params.get("gap") # None: random in NAIVE_GAP per placement
1087
+ bias = np.array([float(params.get("bias_x", 0.0)), 0.0])
1088
+ rand = float(params.get("rand", 0.0))
1089
+ for i in order:
1090
+ g = float(rng.uniform(*NAIVE_GAP)) if gap is None else float(gap)
1091
+ e = bias + (rng.uniform(-rand, rand, 2) if rand else 0.0)
1092
+ self.place(i, g, err=e, z_carry=params.get("z_carry", Z_CARRY), v=params.get("v", 0.2))
1093
+ if params.get("repair") == "each": # looks at all bottles after every step and stands fallen ones up
1094
+ for _ in range(2):
1095
+ bad = [j for j in range(4) if self.mon["ever"][j] and not self.on_spot(j)]
1096
+ for j in self.repair_order(bad):
1097
+ if not self.on_spot(j):
1098
+ self.fix(j)
1099
+ if params.get("check"):
1100
+ self.check_and_repair()
1101
+ self._lift_to(Z_CARRY)
1102
+ self.sk.hold(10)
1103
+
1104
+ # naive = Sonnet-like habits (lh_nudge_row / lh_bystander pilots): careful, far spots first, carries high, vertical
1105
+ # descent, releases 1-4 cm above the surface, places ~1-2 cm too far forward +- 0.6 cm, no special plan for the
1106
+ # table, does not look back at the bottles it has already put down
1107
+ def default_params(self, inst):
1108
+ return dict(order="far_first", gap=None, bias_x=float(inst["naive_bias_x"]), rand=NAIVE_RAND,
1109
+ noise_seed=int(inst["seed"]) * 13, repair=None, check=False)
1110
+
1111
+ def oracle_params(self, inst):
1112
+ """knows the short leg: puts the heavy bottle on its corner first (the table rocks while nothing stands on it),
1113
+ sets the others down gently, checks at the end"""
1114
+ return dict(order="far_first", first=inst["heavy"], gap=CAREFUL_GAP, bias_x=0.0, rand=0.0, repair="each",
1115
+ check=True)
1116
+
1117
+ def adapt_params(self, inst, history):
1118
+ """attempt >= 2: the bottle whose placement rocked the table (from the event of the failed attempt) first; the
1119
+ same imprecise habits otherwise; stands fallen bottles up and checks at the end"""
1120
+ first = None
1121
+ for h in history:
1122
+ for e in h["outcome"].get("events", []):
1123
+ if e.get("event") == "table_rocked" and e.get("released"):
1124
+ first = e["released"]
1125
+ break
1126
+ if first:
1127
+ break
1128
+ return dict(self.default_params(inst), first=first, repair="each", check=True)
1129
+
1130
+ def blind_params(self, inst, attempt, rng):
1131
+ """the naive behaviour with a random order and random variation, no history, no look back"""
1132
+ return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)),
1133
+ z_carry=float(rng.uniform(0.40, 0.45)), v=float(rng.uniform(0.12, 0.25)),
1134
+ bias_x=float(rng.uniform(*NAIVE_BIAS)))
1135
+
1136
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
1137
+ """oracle / naive: one attempt. adaptive: attempt 1 = naive + stands fallen bottles up after every step and checks
1138
+ at the end; attempts >= 2: the rocking bottle first. blind: naive with a random order.
1139
+ Extra kinds (controls): naive_heavy_first (naive habits, 1-4 cm drops, but the heavy bottle first),
1140
+ naive_repair (= adaptive's first attempt), naive_near_first, switch (order change only, no repair),
1141
+ oracle_noise (+-5 mm)."""
1142
+ k = k or self.max_attempts
1143
+ rng = np.random.default_rng(seed)
1144
+ history = []
1145
+ single = ("oracle", "naive", "naive_heavy_first", "naive_repair", "oracle_noise", "naive_near_first")
1146
+ for a in range(k):
1147
+ self.reset_instance(inst)
1148
+ if kind == "oracle":
1149
+ params = self.oracle_params(inst)
1150
+ elif kind == "naive":
1151
+ params = self.default_params(inst)
1152
+ elif kind == "adaptive":
1153
+ params = (dict(self.default_params(inst), repair="each", check=True) if a == 0 else
1154
+ self.adapt_params(inst, history))
1155
+ elif kind == "blind":
1156
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
1157
+ elif kind == "switch":
1158
+ params = (self.default_params(inst) if a == 0 else
1159
+ dict(self.adapt_params(inst, history), repair=None, check=False))
1160
+ elif kind == "naive_heavy_first":
1161
+ params = dict(self.default_params(inst), first=inst["heavy"])
1162
+ elif kind == "naive_repair":
1163
+ params = dict(self.default_params(inst), repair="each", check=True)
1164
+ elif kind == "naive_near_first":
1165
+ params = dict(self.default_params(inst), order="near_first")
1166
+ elif kind == "oracle_noise":
1167
+ params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a)
1168
+ else:
1169
+ raise ValueError(kind)
1170
+ self.execute(inst, params)
1171
+ out = self.outcome(inst)
1172
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
1173
+ if on_attempt:
1174
+ on_attempt(a, params, out)
1175
+ if out["success"] or kind in single:
1176
+ break
1177
+ return history
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/agent_compare.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ΔICL between two agent run directories on the same seeds.
2
+
3
+ python scripts/agent_compare.py --with runs/agent/<task>/<full-memory run> --iid runs/agent/<task>/<memory-none run>
4
+
5
+ ΔICL = succ@k(with history) - pass@k_iid(independent retries), paired by instance seed, with a paired
6
+ bootstrap 95% interval. Also prints the analytic i.i.d. reference 1-(1-p1)^k from the 'with' run.
7
+ """
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
14
+
15
+ from lffbench.agent.metrics import paired_delta # noqa: E402
16
+
17
+
18
+ def load(d):
19
+ with open(os.path.join(d, "summary.json")) as f:
20
+ return json.load(f)
21
+
22
+
23
+ def main():
24
+ ap = argparse.ArgumentParser()
25
+ ap.add_argument("--with", dest="with_", required=True)
26
+ ap.add_argument("--iid", required=True)
27
+ ap.add_argument("--k", type=int, default=None)
28
+ a = ap.parse_args()
29
+ w, i = load(a.with_), load(a.iid)
30
+ k = a.k or min(w["k"], i["k"])
31
+ res = paired_delta(w["runs"], i["runs"], k)
32
+ res["k"] = k
33
+ res["with"] = dict(memory=w["memory"], feedback=w["feedback"], attempt1=w["aggregate"]["attempt1_success"],
34
+ pass_at_k_iid_analytic=w["aggregate"]["pass_at_k_iid_analytic"])
35
+ res["iid"] = dict(memory=i["memory"], feedback=i["feedback"])
36
+ print(json.dumps(res, indent=1))
37
+
38
+
39
+ if __name__ == "__main__":
40
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/ladder_plan.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-3 feedback ladder (user 2026-10-27; design docs/20). Same instances and records as the mismatched-history
2
+ control (scripts/mismatch_plan.py): the main-table attempt 1 of every Claude instance in the 9 twin tasks whose
3
+ attempt 1 failed. Fresh single-attempt agents (Claude Code B', jail, high, F1), README byte-identical to the Do arm;
4
+ only the Result section of history/README.md grows, one rung at a time:
5
+
6
+ F1 "The environment judged that attempt: failed." = the Do arm (do_<m>), not re-run
7
+ F2 + the measured error of that attempt (outcome.detail, axis labels stripped) batch lf2_<m>
8
+ hplus + "Cause: " the hidden variable (arm_specs reveal, as --arm hplus states it) batch lhp_<m>
9
+ fix + how to succeed (arm_specs fix, from the oracle parameters; results/_ladder/fix_validate.json) lfx_<m>
10
+
11
+ python scripts/ladder_plan.py build records -> runs/api/ladder_20261027/<m>/<rung>.json (+ tasks_<m>.txt)
12
+ python scripts/ladder_plan.py report per instance F1 / F2 / H+ / Fix, totals, adjacent paired counts
13
+ -> runs/api/ladder_20261027/report.json + markdown on stdout
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+ API = os.path.join(ROOT, "runs", "api")
23
+ SRC = os.path.join(API, "mismatch_20261027")
24
+ OUT = os.path.join(API, "ladder_20261027")
25
+ FIXV = os.path.join(ROOT, "results", "_ladder", "fix_validate.json")
26
+ MODELS = ("opus", "sonnet")
27
+ RUNGS = ("F2", "hplus", "fix")
28
+ BATCH = {"F1": "do", "F2": "lf2", "hplus": "lhp", "fix": "lfx"}
29
+ WITHIN = {"l2_turntable_restore"} # reported separately (docs/20 §2)
30
+
31
+
32
+ def events(log):
33
+ return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip()]
34
+
35
+
36
+ def texts(src, fixes):
37
+ """rung -> result_extra for one record source (the logged attempt 1)"""
38
+ from lffbench import arm_specs
39
+ from lffbench.agent.robot_server import strip_axes
40
+ ev = events(src["log"])
41
+ start = next(e for e in ev if e["ev"] == "session_start")
42
+ done = next(e for e in ev if e["ev"] == "done" and e.get("attempt") == 1)
43
+ detail = strip_axes((done.get("outcome") or {}).get("detail") or "").strip()
44
+ if not detail:
45
+ raise SystemExit(f"{src['task']}:{src['seed']}: attempt 1 has no outcome detail for F2")
46
+ cause = "Cause: " + strip_axes(arm_specs.reveal(start["task"], start["inst"]).strip())
47
+ fx = fixes.get(f"{start['task']}:{start['seed']}")
48
+ if fx is None or not fx["ok"]:
49
+ raise SystemExit(f"{start['task']}:{start['seed']}: no validated fix text in {FIXV}")
50
+ return {"F2": detail, "hplus": detail + "\n\n" + cause, "fix": detail + "\n\n" + cause + "\n\n" + fx["fix"]}
51
+
52
+
53
+ def cmd_build():
54
+ fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
55
+ for m in MODELS:
56
+ own = json.load(open(os.path.join(SRC, m, "own.json")))
57
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
58
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(own) + "\n")
59
+ out = {r: {} for r in RUNGS}
60
+ for key, d in own.items():
61
+ src = json.load(open(d + ".source.json"))
62
+ tx = texts(src, fixes)
63
+ for r in RUNGS:
64
+ dst = os.path.join(OUT, m, r, f"{src['task']}_s{src['seed']}")
65
+ if not os.path.isdir(dst):
66
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), src["log"],
67
+ dst, "--result-extra", tx[r]], check=True, capture_output=True)
68
+ out[r][key] = dst
69
+ for r in RUNGS:
70
+ json.dump(out[r], open(os.path.join(OUT, m, f"{r}.json"), "w"), indent=1)
71
+ print(m, len(own), "instances x", len(RUNGS), "rungs")
72
+
73
+
74
+ def single(batch):
75
+ """task:seed -> True / False (attempt 1 of the batch's done run)"""
76
+ out = {}
77
+ p = os.path.join(API, batch, "manifest.json")
78
+ if not os.path.exists(p):
79
+ return out
80
+ for r in json.load(open(p))["runs"]:
81
+ if r["status"] != "done":
82
+ continue
83
+ d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
84
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
85
+ return out
86
+
87
+
88
+ def cmd_report():
89
+ rep, md = {}, []
90
+ order = ("F1", "F2", "hplus", "fix")
91
+ f = lambda v: "-" if v is None else ("S" if v else "F")
92
+ for m in MODELS:
93
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
94
+ res = {r: single(f"{BATCH[r]}_{m}") for r in order}
95
+ rows = [dict(inst=k, within=k.split(":")[0] in WITHIN, **{r: res[r].get(k) for r in order}) for k in want]
96
+ tot = {}
97
+ for part, sub in (("all", rows), ("cross", [r for r in rows if not r["within"]]),
98
+ ("within", [r for r in rows if r["within"]])):
99
+ tot[part] = {r: [sum(x[r] for x in sub if x[r] is not None), sum(x[r] is not None for x in sub)] for r in order}
100
+ steps = {}
101
+ cross = [r for r in rows if not r["within"]]
102
+ for lo, hi in zip(order, order[1:]):
103
+ both = [r for r in cross if r[lo] is not None and r[hi] is not None]
104
+ steps[f"{lo}->{hi}"] = dict(n=len(both), up=sum(r[hi] and not r[lo] for r in both),
105
+ down=sum(r[lo] and not r[hi] for r in both))
106
+ rep[m] = dict(rows=rows, totals=tot, steps=steps)
107
+ md += [f"### {m}", "", "| instance | F1 | F2 | H+ | Fix |", "|---|---|---|---|---|"]
108
+ md += [f"| {r['inst']}{' (within)' if r['within'] else ''} | " + " | ".join(f(r[x]) for x in order) + " |"
109
+ for r in rows]
110
+ for part in ("cross", "within"):
111
+ md.append(f"{part}: " + ", ".join(f"{x} {tot[part][x][0]}/{tot[part][x][1]}" for x in order))
112
+ md.append("adjacent (cross, paired): " + "; ".join(f"{k} n={v['n']} up {v['up']} down {v['down']}"
113
+ for k, v in steps.items()))
114
+ md.append("")
115
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
116
+ print("\n".join(md))
117
+
118
+
119
+ if __name__ == "__main__":
120
+ {"build": cmd_build, "report": cmd_report}[sys.argv[1]]()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/start_robot_session.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Start a robot server + isolated sandbox for one task instance.
3
+ # usage: scripts/start_robot_session.sh <task> <seed> <memory full|none> <feedback F0|F1|F2> <port> [instruction direct|indirect] [k] [tag] [perception depth|rgb] [video 0|1]
4
+ # The sandbox gets an opaque random name (no task / condition in the path); the readable run name is only in LOG.
5
+ set -e
6
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
7
+ TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}; PERC=${9:-depth}; VID=${10:-0}
8
+ RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT}
9
+ SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))')
10
+ LOG=${LFF_RUNS_DIR:-$ROOT/runs/claude}/$RUN
11
+ mkdir -p "$SANDBOX" "$LOG"
12
+ cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1
13
+ KARG=""; [ -n "$K" ] && KARG="--k $K"
14
+ VARG=""; [ "$VID" = "1" ] && VARG="--video $LOG/rollout.mp4"
15
+ nohup python -m lffbench.agent.robot_server --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \
16
+ --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --perception "$PERC" --style "${LFF_STYLE:-v1}" ${LFF_EXTRA_ARGS:-} $KARG $VARG > "$LOG/server.log" 2>&1 &
17
+ echo $! > "$LOG/server.pid"
18
+ # wait for the scene (long-horizon scenes on a loaded machine took > 2 min, 2026-10-20); on failure stop the server
19
+ # so that it does not keep the port
20
+ for i in $(seq 1 "${LFF_SERVER_WAIT_S:-600}"); do [ -f "$LOG/READY" ] && break; sleep 1; done
21
+ [ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; kill "$(cat "$LOG/server.pid")" 2>/dev/null; exit 1; }
22
+ echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json"
23
+ echo "SANDBOX=$SANDBOX"
24
+ echo "LOG=$LOG"
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/summarize.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Aggregate results/<task>/validate.json into results/SUMMARY.md (headroom table)."""
2
+ import glob
3
+ import json
4
+ import os
5
+
6
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7
+
8
+
9
+ def main():
10
+ rows = []
11
+ for p in sorted(glob.glob(os.path.join(ROOT, "results", "*", "validate.json"))):
12
+ r = json.load(open(p))
13
+ s = r["succ_at_k"]
14
+
15
+ def g(kind, j):
16
+ v = s.get(kind)
17
+ return "—" if v is None else f"{100 * v[j - 1]:.0f}"
18
+
19
+ k = r["k"]
20
+ rows.append(f"| {r['task']} | {r['level']} | {', '.join(r['capabilities'])} | {r['n']} | "
21
+ f"{g('oracle', 1)} | {g('naive', 1)} | {g('adaptive', 1)} / {g('adaptive', 2)} / {g('adaptive', k)} | "
22
+ f"{g('blind', k)} | {r.get('seconds', 0) / 60:.0f} min |")
23
+ head = ("| task | level | capabilities | n | oracle@1 | naive@1 | adaptive @1/@2/@k | blind@k | wall |\n"
24
+ "|---|---|---|---|---|---|---|---|---|")
25
+ text = "# LFF-Bench headroom validation (scripted reference policies)\n\n" + head + "\n" + "\n".join(rows) + "\n"
26
+ out = os.path.join(ROOT, "results", "SUMMARY.md")
27
+ with open(out, "w") as f:
28
+ f.write(text)
29
+ print(text)
30
+
31
+
32
+ if __name__ == "__main__":
33
+ main()
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_balance_board.py ADDED
@@ -0,0 +1,817 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH balance_board: put four look-alike cubes on their marks on a plank that rests loose across a narrow block (a
2
+ seesaw); loading it in the wrong order tips the plank, and every cube already on it slides down to the low end.
3
+
4
+ Family: long-horizon self-disturbance ("state_restoration"): each stage is a plain pick-and-place of a cube onto its
5
+ mark, but a later placement can tip the plank, which sends the cubes placed before it (earlier progress) sliding off
6
+ their marks. The agent has to notice it, re-level the plank and re-place them before finishing (within an attempt), and
7
+ learn a loading order that keeps the plank level (across attempts; the final-state judge does not enforce an order).
8
+
9
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
10
+ * a grey support (fixture: two 1.5 cm blocks with a 1 cm slot between them, together 4 cm along the plank x 10 cm x
11
+ 6 cm high, flat tops) under the middle of
12
+ * a dark wooden plank (free body, 46 cm long, pointing away from the robot, 8 cm wide, 1.5 cm thick, 0.5 kg) lying
13
+ loose on it, level, with a 2 cm lip across each end. A thin keel under the plank's middle hangs in the slot and keeps
14
+ the plank from wandering along the support (+-3 mm); nothing holds it down. It stays level while the combined centre
15
+ of mass of plank + cubes is above the support's 4 cm top; otherwise it tips until its low end touches the table
16
+ (about 17 degrees);
17
+ * four marks (5.8 cm squares, outline + light fill) on the plank, two on each side of the block: an inner one
18
+ (8.5-9.5 cm from the middle) and an outer one (15.5-16.5 cm); the colour of each mark is random;
19
+ * four 4.5 cm cubes (red, green, blue, yellow) on the table, two left and two right of the plank (random places).
20
+ They look alike except for the colour. Cube and plank surfaces are slick (friction 0.2 < tan 17 deg): on a tipped
21
+ plank every cube slides down to the lip at the low end.
22
+ Why along x with lips (measured, see the task card): with the plank left-right and open ends, the cubes slid off the
23
+ ends onto the table 0-11 cm past them, and a default top-down grasp there (fingers left-right, the Panda hand is 21 cm
24
+ wide along them) pressed the plank's end down and tipped it again -- restoring became a loop. Along x the default grasp
25
+ is across the plank, and the lips keep the cubes on the plank within reach.
26
+
27
+ Hidden variable: the cube masses. "Hazard" instances (13 of every 20 consecutive seeds): the two cubes that belong on
28
+ the inner marks are heavy (stone, 0.19-0.24 kg), the two for the outer marks are light (48-56 g); the final layout is
29
+ balanced. A heavy cube alone on its inner mark tips the plank (1.28-1.43 x the tipping moment); a light one alone on its
30
+ outer mark does not (0.72-0.78 x); in the zig-zag order below no step exceeds 0.72-0.81 x. So the only safe loading
31
+ orders are "an outer cube, then the inner cube on the OTHER side, then the other inner cube, then the last outer cube"
32
+ (zig-zag); end-to-end, alternating outer-first (outer, outer, inner, inner) and inner-first orders all tip it.
33
+ "Benign" instances: all four cubes light (26-34 g); no order tips (worst step 0.63-0.75 x).
34
+
35
+ Why the natural order fails: nothing in the image shows which cubes are heavy. Any natural order (nearest cube first,
36
+ the marks from one end to the other, or the cautious "alternate sides, outer marks first") tips the plank in a hazard
37
+ instance; the cubes on it slide to the low end and keep it tipped. A natural plan then keeps going and finishes with
38
+ cubes off their marks. What must be learned: check the marks after each placement / before finishing, unload the low
39
+ end and re-place (within the attempt), and use the tip to infer which cubes are heavy (an inner cube tipped it; the
40
+ layout must balance in the end, so the other inner cube is heavy too) and load in the zig-zag order (across attempts).
41
+
42
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube on its
43
+ mark, plank level within 3 degrees and still on its support (10-11), nothing held, scene static) plus an event log of every stage predicate (achieved /
44
+ lost / restored, with step and cause) and every tip (which end went down, the cube released just before) for the server
45
+ log; F1 gives the agent only success / failure.
46
+ """
47
+ import itertools
48
+
49
+ import numpy as np
50
+
51
+ from .. import envs
52
+ from ..bddl import write_bddl
53
+ from ..objects import _fmt, _wrap, box_xml, register_generated
54
+ from ..skills import Skills
55
+ from ..task_base import LFFTask, register_task
56
+
57
+ TZ = envs.TABLE_Z
58
+
59
+ # ---------------------------------------------------------------- geometry / physics
60
+ # plank frame: y along the plank (+y = the end toward the robot), x across it, z up. The plank and the block are
61
+ # yawed 90 deg, so plank +y = world -x.
62
+ PL_HL, PL_HW, PL_HT = 0.23, 0.04, 0.0075 # plank half length, half width, half thickness
63
+ LIP_T, LIP_H = 0.008, 0.02 # lip across each end (inside the 46 cm), height above the plank's top
64
+ PLANK_MASS = 0.50
65
+ PLANK_ROT_DAMP = 0.01 # N m s / rad on the plank's rotation: after its low end is unloaded it swings over to ~10 deg
66
+ # and is calm in ~1.5 s (no damping: ~13 deg and ~2.7 s); the tip itself is not slowed (measured)
67
+ PLANK_YAW = np.pi / 2
68
+ RIDGE_HW, RIDGE_HX, RIDGE_H = 0.02, 0.05, 0.06 # support: half width along the plank (s), half depth, height
69
+ SLOT_HW = 0.005 # the support is two blocks with a 1 cm slot between them
70
+ KEEL_HW, KEEL_H = 0.002, 0.010 # keel under the plank's middle (4 mm x 8 cm x 1 cm) hanging in the slot
71
+ CUBE_E = 0.045
72
+ MU = 0.20 # cubes and plank: the cube-plank contact slides above 11 deg; ridge (1.0), table (0.6), finger pads (2.0) win
73
+ MU_RIDGE = 1.0
74
+ MARK_HALF, MARK_LINE = 0.029, 0.004
75
+ WOOD = (0.42, 0.27, 0.15, 1.0) # dark walnut: contrasts with the light table, so the tilt reads in the images
76
+
77
+ COLORS = ("red", "green", "blue", "yellow")
78
+ RGBA = dict(red=(0.85, 0.12, 0.10, 1.0), green=(0.10, 0.62, 0.20, 1.0), blue=(0.15, 0.30, 0.88, 1.0),
79
+ yellow=(0.93, 0.78, 0.10, 1.0))
80
+ CUBES = {c: f"{c}_cube_1" for c in COLORS}
81
+ PLANK, RIDGE = "plank_1", "ridge_1"
82
+ PLANK_MODEL = "lff_lh_bb_plank"
83
+ # mark slots in plank-frame order (+y first): the robot's end outer / inner, then the far end inner / outer
84
+ SLOTS = ("near_outer", "near_inner", "far_inner", "far_outer")
85
+ END_WORD = dict(near="the end nearer the robot", far="the far end")
86
+
87
+ # ---------------------------------------------------------------- instances / hidden variable
88
+ D_INNER = (0.085, 0.095) # |y| of the inner marks from the plank's middle
89
+ D_OUTER = (0.155, 0.165) # the lip stops a cube 19.95 cm out: a cube on a low-side outer mark ends >= 3.5 cm off it
90
+ P_HAZARD = 0.65 # fraction of hazard instances, balanced per 20 consecutive seeds (13 / 7)
91
+ R_HEAVY = (1.30, 1.40) # hazard: lone heavy cube on its inner mark, moment / tipping moment
92
+ R_LIGHT = (0.72, 0.78) # hazard: lone light cube on its outer mark
93
+ LIGHT_BENIGN = (0.026, 0.034) # benign: every cube (kg)
94
+ H_EST, L_EST = 0.21, 0.04 # nominal masses the adaptive script uses for its hypotheses (it never sees the true ones)
95
+
96
+ # ---------------------------------------------------------------- judging
97
+ TOL = 0.020 # cube centre within 2 cm of its mark centre (per plank axis)
98
+ TOL_LOSE = 0.025 # hysteresis for the monitor
99
+ LEVEL_DEG = 3.0
100
+ TIP_DEG = 8.0 # the monitor records a tip when |tilt| exceeds this (a real tip reaches ~17 deg)
101
+ LEVEL_DEBOUNCE = 4 # monitor evaluations (0.1 s each) before plank_level changes
102
+ FLAT_COS = np.cos(np.radians(15.0))
103
+ SUPPORT_XY = 0.02 # plank on its support: its middle within 2 cm (horizontally) of the support's centre ...
104
+ SUPPORT_DZ = 0.02 # ... and not more than 2 cm below its starting height (a tip lowers it ~0.6 cm; off the block ~6 cm)
105
+
106
+ # ---------------------------------------------------------------- scripted motion
107
+ Z_CARRY = 0.17 # careful / adaptive: grasp point above the table while carrying (cube bottom 14.75 cm)
108
+ Z_CARRY_NAIVE = 0.15 # naive: just above the cubes already on the plank (their tops at 12 cm)
109
+ REL_GAP = 0.004 # release with the cube's bottom this far above the plank
110
+
111
+
112
+ def plank_xml(name):
113
+ """Board + end lips + keel (collision) and per colour a mark (5 visual-only geoms, moved per instance).
114
+ Long axis = body y."""
115
+ g = []
116
+
117
+ def box(nm, pos, size, rgba):
118
+ g.append(f'<geom name="{nm}" type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}" '
119
+ f'friction="{MU} 0.005 0.0001" density="900" group="0"/>')
120
+ g.append(f'<geom type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}" contype="0" '
121
+ f'conaffinity="0" group="1" mass="0"/>')
122
+
123
+ dark = (0.25, 0.16, 0.09, 1.0)
124
+ box(f"{name}_board", (0, 0, 0), (PL_HW, PL_HL, PL_HT), WOOD)
125
+ for k, s in enumerate((1, -1)):
126
+ box(f"{name}_lip{k}", (0, s * (PL_HL - LIP_T / 2), PL_HT + LIP_H / 2), (PL_HW, LIP_T / 2, LIP_H / 2), dark)
127
+ box(f"{name}_keel", (0, 0, -PL_HT - KEEL_H / 2), (PL_HW, KEEL_HW, KEEL_H / 2), dark)
128
+ for c in COLORS:
129
+ rgba = RGBA[c]
130
+ fill = tuple(0.55 + 0.45 * v for v in rgba[:3]) + (1.0,)
131
+ o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE
132
+ parts = [((0, 0, PL_HT + 0.0003), (o, o, 0.0003), fill),
133
+ ((0, i + w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba),
134
+ ((0, -i - w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba),
135
+ ((i + w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba),
136
+ ((-i - w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba)]
137
+ for k, (p, sz, col) in enumerate(parts):
138
+ g.append(f'<geom name="{name}_mk_{c}_{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" '
139
+ f'rgba="{_fmt(col)}" contype="0" conaffinity="0" group="1" mass="0"/>')
140
+ return _wrap(name, "\n ".join(g), PL_HT, float(np.hypot(PL_HL, PL_HW)))
141
+
142
+
143
+ def ridge_xml(name):
144
+ """Split support: two 1.5 cm blocks with a 1 cm slot between them; the plank rests on both and pivots on their outer
145
+ top edges (a 4 cm flat top). The plank's keel hangs in the slot, so the plank cannot wander along its length by
146
+ more than +-3 mm (it stays engaged at the full tip angle)."""
147
+ rgba = (0.35, 0.35, 0.38, 1.0)
148
+ bh = (RIDGE_HW - SLOT_HW) / 2
149
+ g = []
150
+ for k, sy in enumerate((1, -1)):
151
+ p, sz = (0, sy * (SLOT_HW + bh), RIDGE_H / 2), (RIDGE_HX, bh, RIDGE_H / 2)
152
+ g.append(f'<geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(rgba)}" '
153
+ f'friction="{MU_RIDGE} 0.005 0.0001" group="0"/>')
154
+ g.append(f'<geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" '
155
+ f'group="1"/>')
156
+ g = "\n ".join(g)
157
+ return f"""<mujoco model="{name}">
158
+ <worldbody>
159
+ <body>
160
+ <body name="object">
161
+ {g}
162
+ </body>
163
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
164
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {RIDGE_H:.4f}" name="top_site" />
165
+ <site rgba="0 0 0 0" size="0.005" pos="{RIDGE_HX:.4f} {RIDGE_HW:.4f} 0" name="horizontal_radius_site" />
166
+ </body>
167
+ </worldbody>
168
+ </mujoco>"""
169
+
170
+
171
+ def tip_ratio(items, plank_mass=PLANK_MASS, s=RIDGE_HW):
172
+ """Static model of a loose plank on a flat-topped block: |sum m y| / ((M_plank + sum m) s); the plank tips when
173
+ this exceeds 1 (the combined centre of mass leaves the block's top). items: [(mass, y from the middle)]."""
174
+ if not items:
175
+ return 0.0
176
+ mom = sum(m * y for m, y in items)
177
+ return abs(mom) / ((plank_mass + sum(m for m, _ in items)) * s)
178
+
179
+
180
+ def _side(y):
181
+ return "near" if y > 0 else "far"
182
+
183
+
184
+ def _along(v):
185
+ """plank-frame y offset in robot-centric words (+y = toward the robot)"""
186
+ return f"{100 * abs(v):.1f} cm from its mark toward {'the robot' if v > 0 else 'the far end'}"
187
+
188
+
189
+ class BoardSkills(Skills):
190
+ """Skills that feed the task's per-step monitor."""
191
+
192
+ def __init__(self, env, task, recorder=None):
193
+ super().__init__(env, recorder=recorder)
194
+ self.task = task
195
+
196
+ def _act(self, dpos, drot, grip):
197
+ super()._act(dpos, drot, grip)
198
+ self.task.monitor_step()
199
+
200
+
201
+ @register_task
202
+ class BalanceBoard(LFFTask):
203
+ name = "lh_balance_board"
204
+ level = "L2"
205
+ category = "state_restoration"
206
+ capabilities = ("Perceive", "Reason", "Plan", "Restore")
207
+ protocol = "cross"
208
+ max_attempts = 3
209
+ agent_max_steps = 120 # careful zig-zag ~30-36 commands + re-placing four cubes (~30) + looking around
210
+ instruction = ("Put each coloured cube on the square mark of the same colour on the long plank. The plank lies loose "
211
+ "across a narrow block under its middle. At the end all four cubes must be on their marks and the "
212
+ "plank must still rest level on the block.")
213
+ instruction_indirect = ("Set the four coloured cubes onto the outlined squares of matching colour on the wooden "
214
+ "board that rests across the small grey block. When you are done, every cube must sit on "
215
+ "its square and the board must still rest level on the block.")
216
+ agent_object_names = ["red cube", "green cube", "blue cube", "yellow cube", "plank", "support block",
217
+ "red mark", "green mark", "blue mark", "yellow mark"]
218
+
219
+ # ------------------------------------------------------------ scene
220
+ def make_bddl(self):
221
+ pl = register_generated("LffLhBbPlank", plank_xml(PLANK_MODEL))
222
+ rg = register_generated("LffLhBbRidge", ridge_xml("lff_lh_bb_ridge"), free=False)
223
+ objs = [(PLANK, pl, "plank_region", (0.18, -0.01, 0.20, 0.01))]
224
+ e = CUBE_E / 2
225
+ for i, c in enumerate(COLORS):
226
+ cat = register_generated(f"LffLhBbCube{c.title()}",
227
+ box_xml(f"lff_lh_bb_cube_{c}", (e, e, e), RGBA[c], density=500.0,
228
+ friction=(MU, 0.005, 0.0001)).replace(
229
+ 'solimp="0.998 0.998 0.001" solref="0.001 1"', ""))
230
+ objs.append((CUBES[c], cat, f"{c}_cube_region", (-0.32, -0.33 + 0.2 * i, -0.30, -0.31 + 0.2 * i)))
231
+ fx = [(RIDGE, rg, "ridge_region", (-0.12, 0.30, -0.10, 0.32))]
232
+ return write_bddl(self.name, "put each cube on its mark on the plank and keep the plank level", objs, fx)
233
+
234
+ def __init__(self, cam_res=None):
235
+ super().__init__(cam_res)
236
+ m = self.env.sim.model
237
+ self.ridge_bid = m.body_name2id(self.env.fixtures_dict[RIDGE].root_body)
238
+ self.plank_bid = envs.body_id(self.env, PLANK)
239
+ pre = f"{PLANK}_{PLANK_MODEL}"
240
+ self.mark_gids = {c: [m.geom_name2id(f"{pre}_mk_{c}_{k}") for k in range(5)] for c in COLORS}
241
+ self.mark_pos0 = {c: [m.geom_pos[g].copy() for g in self.mark_gids[c]] for c in COLORS}
242
+ self.cube_gids = {c: set(envs.obj_geom_ids(self.env, CUBES[c])) for c in COLORS}
243
+ self.plank_gids = set(envs.obj_geom_ids(self.env, PLANK))
244
+ self.robot_gids = set(envs.robot_geom_ids(self.env))
245
+ self.inst = None
246
+ self.mon = None
247
+ self.obs = [] # adaptive script: (configuration, tipped) observations, kept across the attempts of one run
248
+
249
+ def sample_instance(self, seed):
250
+ rng = np.random.default_rng(seed)
251
+ x0, y0 = float(rng.uniform(-0.18, -0.14)), float(rng.uniform(-0.03, 0.03))
252
+ perm = [str(c) for c in rng.permutation(COLORS)] # colour of the mark in SLOTS order
253
+ slot_of = {c: s for c, s in zip(perm, SLOTS)}
254
+ dist = dict(near_outer=float(rng.uniform(*D_OUTER)), near_inner=float(rng.uniform(*D_INNER)),
255
+ far_inner=-float(rng.uniform(*D_INNER)), far_outer=-float(rng.uniform(*D_OUTER)))
256
+ marks = {c: dist[slot_of[c]] for c in COLORS} # plank-frame y of each mark (+ = toward the robot)
257
+ hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced like l7_key_turn / lh_lid_box
258
+ r_h, r_l = float(rng.uniform(*R_HEAVY)), float(rng.uniform(*R_LIGHT))
259
+ light = {c: float(rng.uniform(*LIGHT_BENIGN)) for c in COLORS}
260
+ s, pm = RIDGE_HW, PLANK_MASS
261
+ if hazard:
262
+ # equal moments on both sides -> the finished layout is exactly balanced
263
+ dn, do = dist["near_inner"], dist["near_outer"]
264
+ y_h = r_h * pm * s / (dn - r_h * s) * dn # heavy on the near inner mark: moment r_h x tipping moment
265
+ x_l = r_l * pm * s / (do - r_l * s) * do
266
+ mass = {c: (y_h if "inner" in slot_of[c] else x_l) / abs(dist[slot_of[c]]) for c in COLORS}
267
+ else:
268
+ mass = light
269
+ # start: two cubes left and two right of the plank, 17-19 cm from its axis, at two depths (random places)
270
+ spots = [(dx, sy) for sy in (1.0, -1.0) for dx in (-0.08, 0.08)]
271
+ order = rng.permutation(4)
272
+ start = {c: [x0 + spots[j][0] + float(rng.uniform(-0.01, 0.01)),
273
+ y0 + spots[j][1] * float(rng.uniform(0.17, 0.19))] for c, j in zip(COLORS, order)}
274
+ start_yaw = {c: float(rng.uniform(-0.3, 0.3)) for c in COLORS}
275
+ heavy = sorted(c for c in COLORS if mass[c] > 0.1)
276
+ return dict(seed=int(seed), plank_xy=[x0, y0], marks=marks, slot_of=slot_of, hazard=hazard, mass=mass,
277
+ heavy=heavy, r_heavy=r_h if hazard else None, r_light=r_l if hazard else None, start=start,
278
+ start_yaw=start_yaw)
279
+
280
+ def apply_instance(self, inst):
281
+ self.inst = inst
282
+ env = self.env
283
+ m = env.sim.model
284
+ x0, y0 = inst["plank_xy"]
285
+ q = [np.cos(PLANK_YAW / 2), 0.0, 0.0, np.sin(PLANK_YAW / 2)]
286
+ m.body_pos[self.ridge_bid] = [x0, y0, TZ]
287
+ m.body_quat[self.ridge_bid] = q
288
+ envs.scale_mass(env, PLANK, PLANK_MASS)
289
+ _, da = envs.free_joint_addr(env, PLANK)
290
+ m.dof_damping[da + 3:da + 6] = PLANK_ROT_DAMP
291
+ for c in COLORS:
292
+ for g, p0 in zip(self.mark_gids[c], self.mark_pos0[c]):
293
+ m.geom_pos[g] = p0 + np.array([0.0, inst["marks"][c], 0.0])
294
+ envs.scale_mass(env, CUBES[c], inst["mass"][c])
295
+ envs.set_obj_pose(env, PLANK, [x0, y0, TZ + RIDGE_H + PL_HT + 0.0005], quat_wxyz=np.array(q))
296
+ for c in COLORS:
297
+ envs.place_upright(env, CUBES[c], inst["start"][c], yaw=inst["start_yaw"][c])
298
+
299
+ def reset_instance(self, inst, recorder=None):
300
+ self.mon = None
301
+ self.env.reset()
302
+ self.apply_instance(inst)
303
+ self.env.sim.forward()
304
+ envs.settle(self.env, 10)
305
+ self.plank_z0 = float(self.plank_pos()[2])
306
+ self.sk = BoardSkills(self.env, self, recorder=recorder)
307
+ self._init_monitor()
308
+ return self.sk
309
+
310
+ # ------------------------------------------------------------ state helpers
311
+ def plank_R(self):
312
+ return self.env.sim.data.body_xmat[self.plank_bid].reshape(3, 3).copy()
313
+
314
+ def plank_pos(self):
315
+ return self.env.sim.data.body_xpos[self.plank_bid].copy()
316
+
317
+ def tilt_deg(self):
318
+ """+ = the plank's end toward the robot is up"""
319
+ return float(np.degrees(np.arcsin(np.clip(self.plank_R()[2, 1], -1.0, 1.0))))
320
+
321
+ def is_level(self, deg=LEVEL_DEG):
322
+ return abs(self.tilt_deg()) <= deg
323
+
324
+ def on_support(self):
325
+ """the plank still rests on the support block (10-11: Sonnet lh2 s3001 pushed it off onto the table, where it
326
+ lies level, and loaded the cubes there; 'level' alone accepted that)"""
327
+ p, r = self.plank_pos(), self.env.sim.data.body_xpos[self.ridge_bid]
328
+ return bool(np.linalg.norm(p[:2] - r[:2]) <= SUPPORT_XY and p[2] >= self.plank_z0 - SUPPORT_DZ)
329
+
330
+ def in_plank(self, p):
331
+ """world point -> plank frame (x across, y along from the middle, z above the plank's mid-plane)"""
332
+ return self.plank_R().T @ (np.asarray(p, float) - self.plank_pos())
333
+
334
+ def mark_world(self, c):
335
+ return self.plank_pos() + self.plank_R() @ np.array([0.0, self.inst["marks"][c], PL_HT])
336
+
337
+ def cube_pos(self, c):
338
+ return envs.obj_pos(self.env, CUBES[c])
339
+
340
+ def held(self, c):
341
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper,
342
+ object_geoms=self.env.objects_dict[CUBES[c]]))
343
+
344
+ def on_plank(self, c):
345
+ """resting on the plank's top (plank frame), anywhere along it"""
346
+ q = self.in_plank(self.cube_pos(c))
347
+ return bool(abs(q[0]) <= PL_HW + 0.01 and abs(q[1]) <= PL_HL and abs(q[2] - PL_HT - CUBE_E / 2) <= 0.012)
348
+
349
+ def mark_offset(self, c):
350
+ q = self.in_plank(self.cube_pos(c))
351
+ return np.array([q[0], q[1] - self.inst["marks"][c]])
352
+
353
+ def _flat(self, c):
354
+ Rc = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3)
355
+ return bool(np.max(np.abs(self.plank_R()[:, 2] @ Rc)) >= FLAT_COS)
356
+
357
+ def on_mark(self, c, tol=TOL):
358
+ if not self.on_plank(c):
359
+ return False
360
+ o = self.mark_offset(c)
361
+ return bool(np.max(np.abs(o)) <= tol and self._flat(c) and not self.held(c))
362
+
363
+ def stage_values(self):
364
+ v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS}
365
+ v["plank_level"] = self.is_level()
366
+ v["plank_on_support"] = self.on_support()
367
+ return v
368
+
369
+ # ------------------------------------------------------------ per-step monitor (server log only)
370
+ def _init_monitor(self):
371
+ self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"plank_level": True, "plank_on_support": True}, ever=set(),
372
+ lost=set(), events=[], step=0, last_touch={c: None for c in COLORS},
373
+ held_prev={c: False for c in COLORS}, last_release=None, tipping=False, tips=[],
374
+ level_cnt=0, calm=0, tilt_max=0.0, win_max=0.0)
375
+
376
+ def _robot_touches(self):
377
+ """cubes touched by the robot or by a cube the robot is carrying, in this control step"""
378
+ d = self.env.sim.data
379
+ out = set()
380
+ carried = [c for c in COLORS if self.mon["held_prev"][c]]
381
+ hit = {c: self.robot_gids.union(*[self.cube_gids[h] for h in carried if h != c]) for c in COLORS}
382
+ for i in range(d.ncon):
383
+ con = d.contact[i]
384
+ for c in COLORS:
385
+ g = self.cube_gids[c]
386
+ if (con.geom1 in g and con.geom2 in hit[c]) or (con.geom2 in g and con.geom1 in hit[c]):
387
+ out.add(c)
388
+ return out
389
+
390
+ def monitor_step(self):
391
+ mon = self.mon
392
+ if mon is None or self.sk is None:
393
+ return
394
+ mon["step"] += 1
395
+ step = self.sk.n_steps
396
+ for c in self._robot_touches():
397
+ mon["last_touch"][c] = step
398
+ tilt = self.tilt_deg()
399
+ mon["tilt_max"] = max(mon["tilt_max"], abs(tilt))
400
+ mon["win_max"] = max(mon["win_max"], abs(tilt))
401
+ if not mon["tipping"] and abs(tilt) > TIP_DEG:
402
+ # one tip episode = from |tilt| > 8 deg until the plank has stayed level for 1 s (the swing back and any
403
+ # rocking belong to the same episode)
404
+ mon["tipping"] = True
405
+ mon["calm"] = 0
406
+ rel = mon["last_release"]
407
+ tip = dict(step=step, down="near" if tilt < 0 else "far",
408
+ after_release=(rel[0] if rel is not None and step - rel[1] <= 60 else None),
409
+ on_plank=[c for c in COLORS if self.on_plank(c)],
410
+ on_mark=[c for c in COLORS if mon["state"][f"{c}_on_mark"]])
411
+ mon["tips"].append(tip)
412
+ mon["events"].append(dict(step=step, pred="plank", ev="tipped", down=tip["down"],
413
+ after_release=tip["after_release"], on_mark=tip["on_mark"]))
414
+ elif mon["tipping"]:
415
+ mon["calm"] = mon["calm"] + 1 if abs(tilt) < LEVEL_DEG else 0
416
+ if mon["calm"] >= 20:
417
+ mon["tipping"] = False
418
+ if mon["step"] % 2:
419
+ return # predicates every other control step (0.1 s)
420
+ for c in COLORS:
421
+ h = self.held(c)
422
+ if mon["held_prev"][c] and not h:
423
+ mon["last_release"] = (c, step)
424
+ mon["held_prev"][c] = h
425
+ key = f"{c}_on_mark"
426
+ was = mon["state"][key]
427
+ now = self.on_mark(c, TOL if not was else TOL_LOSE)
428
+ if now != was:
429
+ self._event(key, now, step, c)
430
+ lv = self.is_level()
431
+ if lv != mon["state"]["plank_level"]:
432
+ mon["level_cnt"] += 1
433
+ if mon["level_cnt"] >= LEVEL_DEBOUNCE:
434
+ mon["level_cnt"] = 0
435
+ self._event("plank_level", lv, step, None)
436
+ else:
437
+ mon["level_cnt"] = 0
438
+ sup = self.on_support()
439
+ if sup != mon["state"]["plank_on_support"]:
440
+ self._event("plank_on_support", sup, step, None)
441
+
442
+ def _event(self, key, now, step, color):
443
+ mon = self.mon
444
+ mon["state"][key] = now
445
+ if now:
446
+ ev = "restored" if key in mon["lost"] else "achieved"
447
+ mon["ever"].add(key)
448
+ mon["lost"].discard(key)
449
+ mon["events"].append(dict(step=step, pred=key, ev=ev))
450
+ return
451
+ cause = "other"
452
+ recent_tip = bool(mon["tips"]) and (mon["tipping"] or step - mon["tips"][-1]["step"] <= 60)
453
+ if color is None:
454
+ cause = "tip" if recent_tip else "other"
455
+ elif self.held(color):
456
+ cause = "picked_up"
457
+ elif recent_tip:
458
+ cause = "tip"
459
+ elif mon["last_touch"][color] is not None and step - mon["last_touch"][color] <= 60:
460
+ cause = "robot"
461
+ mon["lost"].add(key)
462
+ mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, tilt=round(self.tilt_deg(), 1)))
463
+
464
+ # ------------------------------------------------------------ outcome
465
+ def _static(self):
466
+ d = self.env.sim.data
467
+ for name in [CUBES[c] for c in COLORS] + [PLANK]:
468
+ _, da = envs.free_joint_addr(self.env, name)
469
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3:
470
+ return False
471
+ return True
472
+
473
+ def _where(self, c):
474
+ """robot-centric description of where a cube that is not on its mark is"""
475
+ if self.held(c):
476
+ return "is still held by the gripper"
477
+ if self.on_plank(c):
478
+ o = self.mark_offset(c)
479
+ return f"lies on the plank, {_along(o[1])}"
480
+ p = self.cube_pos(c)
481
+ if np.linalg.norm(p[:2] - np.asarray(self.inst["start"][c])) < 0.02:
482
+ return "is still where it started on the table"
483
+ q = self.in_plank(p)
484
+ if abs(q[1]) > PL_HL:
485
+ return f"lies on the table beyond {END_WORD[_side(q[1])]} of the plank"
486
+ return "lies on the table beside the plank"
487
+
488
+ def outcome(self, inst):
489
+ envs.settle(self.env, 30)
490
+ mon = self.mon
491
+ vals = self.stage_values()
492
+ static = self._static()
493
+ held = [c for c in COLORS if self.held(c)]
494
+ success = bool(all(vals.values()) and static and not held)
495
+ regress = [e for e in mon["events"] if e["ev"] == "lost"]
496
+ restored = [e for e in mon["events"] if e["ev"] == "restored"]
497
+ parts = []
498
+ off = [c for c in COLORS if not vals[f"{c}_on_mark"]]
499
+ if success:
500
+ failure = None
501
+ parts.append("All four cubes are on their marks and the plank is level.")
502
+ else:
503
+ lost_final = [c for c in off if f"{c}_on_mark" in mon["ever"]]
504
+ failure = ("held" if held else "plank_off_support" if not vals["plank_on_support"] else
505
+ "regressed" if lost_final else "incomplete" if off else
506
+ "not_level" if not vals["plank_level"] else "not_static")
507
+ for c in off:
508
+ txt = f"The {c} cube is not on its mark: it {self._where(c)}"
509
+ if f"{c}_on_mark" in mon["ever"]:
510
+ why = [e for e in regress if e["pred"] == f"{c}_on_mark"]
511
+ cause = why[-1].get("cause") if why else None
512
+ txt += {"tip": " (it had been on its mark; it slid off when the plank tipped).",
513
+ "robot": " (it had been on its mark; the robot knocked it off).",
514
+ "picked_up": " (it had been on its mark; it was picked up again)."}.get(
515
+ cause, " (it had been on its mark earlier).")
516
+ else:
517
+ txt += " (it was never on its mark)."
518
+ parts.append(txt)
519
+ if not vals["plank_on_support"]:
520
+ parts.append("The plank no longer rests on the support block: it was pushed or knocked off it.")
521
+ if not vals["plank_level"]:
522
+ t = self.tilt_deg()
523
+ parts.append(f"The plank is not level: it is tilted {abs(t):.0f} degrees, "
524
+ f"{END_WORD['near' if t < 0 else 'far']} down.")
525
+ if not static and all(vals.values()):
526
+ parts.append("Something was still moving at the end.")
527
+ if mon["tips"]:
528
+ descr = []
529
+ for tp in mon["tips"]:
530
+ d = f"{END_WORD[tp['down']]} down"
531
+ if tp["after_release"]:
532
+ d += f" right after the {tp['after_release']} cube was set down"
533
+ descr.append(d)
534
+ parts.append(f"During the attempt the plank tipped {len(mon['tips'])} time(s): " + "; ".join(descr) + ".")
535
+ return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
536
+ events=mon["events"], n_regressions=len(regress), n_restored=len(restored),
537
+ n_tips=len(mon["tips"]), tips=mon["tips"], tilt_max=round(mon["tilt_max"], 1),
538
+ tilt_final=round(self.tilt_deg(), 1), hazard=bool(inst["hazard"]),
539
+ mark_offsets_cm={c: (100 * self.mark_offset(c)).round(1).tolist() for c in COLORS},
540
+ on_plank={c: self.on_plank(c) for c in COLORS}, detail=" ".join(parts))
541
+
542
+ # ------------------------------------------------------------ scripted policies (perfect perception)
543
+ def _grasp_yaw(self, c):
544
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3)
545
+ i = int(np.argmin(np.abs(R[2])))
546
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
547
+ return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
548
+
549
+ def _y_on_plank(self):
550
+ """cubes resting on the plank now -> their position along it"""
551
+ return {c: float(self.in_plank(self.cube_pos(c))[1]) for c in COLORS if self.on_plank(c) and not self.held(c)}
552
+
553
+ def plank_calm(self):
554
+ _, da = envs.free_joint_addr(self.env, PLANK)
555
+ return abs(self.tilt_deg()) < 1.0 and float(np.linalg.norm(self.env.sim.data.qvel[da + 3:da + 6])) < 0.05
556
+
557
+ def wait_calm(self, max_steps=60):
558
+ """hold the arm still until the plank has stopped swinging (a careful agent looks before it acts)"""
559
+ n = 0
560
+ for _ in range(max_steps):
561
+ if self.plank_calm():
562
+ n += 1
563
+ if n >= 5:
564
+ return True
565
+ else:
566
+ n = 0
567
+ self.sk.hold(1)
568
+ return False
569
+
570
+ def pick(self, c, z_carry):
571
+ sk = self.sk
572
+ p = self.cube_pos(c)
573
+ yaw = self._grasp_yaw(c)
574
+ sk.set_gripper(False, steps=8)
575
+ sk.move_to([p[0], p[1], max(TZ + z_carry, p[2] + 0.06)], yaw=yaw)
576
+ sk.move_to([p[0], p[1], p[2]], tol=0.003)
577
+ sk.set_gripper(True, steps=15)
578
+ sk.move_to([p[0], p[1], TZ + z_carry], speed=0.3)
579
+ if not self.held(c):
580
+ sk.set_gripper(False, steps=8)
581
+ sk.move_to([p[0], p[1], TZ + z_carry])
582
+ return False
583
+ return True
584
+
585
+ def put(self, c, z_carry=Z_CARRY, noise=None, record=False, careful=False):
586
+ """Pick cube c wherever it is and put it on its mark: carry it over the mark, lower it until its bottom is
587
+ REL_GAP above the plank, release, lift. Returns whether the plank tipped (|tilt| > TIP_DEG) during the
588
+ placement, or None if the cube could not be picked. record=True appends the observation (cubes on the plank
589
+ right before the release + this one on its mark, tipped?) for the adaptive script."""
590
+ for _ in range(2):
591
+ if self.pick(c, z_carry):
592
+ break
593
+ else:
594
+ return None
595
+ sk = self.sk
596
+ d = self.mark_world(c)
597
+ if noise is not None:
598
+ d = d + np.array([noise[0], noise[1], 0.0])
599
+ sk.move_to([d[0], d[1], TZ + z_carry], yaw=0.0)
600
+ if careful:
601
+ self.wait_calm()
602
+ d = self.mark_world(c) + (np.array([noise[0], noise[1], 0.0]) if noise is not None else 0.0)
603
+ sk.move_to([d[0], d[1], d[2] + CUBE_E / 2 + REL_GAP], tol=0.003)
604
+ was_level = self.plank_calm()
605
+ conf = self._y_on_plank()
606
+ conf[c] = float(self.inst["marks"][c])
607
+ self.mon["win_max"] = abs(self.tilt_deg())
608
+ sk.set_gripper(False, steps=12)
609
+ sk.move_to([d[0], d[1], TZ + z_carry])
610
+ sk.hold(12)
611
+ tipped = self.mon["win_max"] > TIP_DEG
612
+ if tipped:
613
+ envs.settle(self.env, 30) # let the cubes slide down
614
+ if record and was_level:
615
+ self.obs.append(dict(conf=conf, tipped=bool(tipped), after=c))
616
+ return tipped
617
+
618
+ def park(self, c):
619
+ """take cube c off the plank and set it on a free spot of the table beside the plank"""
620
+ x0, y0 = self.inst["plank_xy"]
621
+ others = [self.cube_pos(o)[:2] for o in COLORS if o != c]
622
+ cands = [np.array([x0 + dx, y0 + sy * dy]) for sy in (1, -1) for dy in (0.18, 0.25)
623
+ for dx in (-0.12, -0.04, 0.04, 0.12)]
624
+ best = max(cands, key=lambda q: min(np.linalg.norm(q - o) for o in others))
625
+ if not self.pick(c, Z_CARRY):
626
+ return False
627
+ sk = self.sk
628
+ sk.move_to([best[0], best[1], TZ + Z_CARRY], yaw=0.0)
629
+ sk.move_to([best[0], best[1], TZ + CUBE_E / 2 + 0.004], tol=0.003)
630
+ sk.set_gripper(False, steps=12)
631
+ sk.move_to([best[0], best[1], TZ + Z_CARRY])
632
+ return True
633
+
634
+ # ---- planning with the static model
635
+ def plan(self, todo, hyps):
636
+ """Best order to (re)place the cubes in `todo`, given the cubes now on the plank, minimising the worst tip ratio
637
+ over the mass hypotheses `hyps` (list of {colour: kg}). A cube that is on the plank off its mark is lifted
638
+ (its moment removed) and then set on its mark. Returns (order, worst ratio)."""
639
+ cur0 = self._y_on_plank()
640
+ best, best_w = list(todo), np.inf
641
+ for order in itertools.permutations(todo):
642
+ w = 0.0
643
+ for mass in hyps:
644
+ cur = dict(cur0)
645
+ for c in order:
646
+ if c in cur:
647
+ del cur[c]
648
+ w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()]))
649
+ cur[c] = self.inst["marks"][c]
650
+ w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()]))
651
+ if w < best_w - 1e-9:
652
+ best, best_w = list(order), w
653
+ return best, best_w
654
+
655
+ def hypotheses(self, use_obs=True):
656
+ """Heavy / light assignments (nominal masses) that (1) leave the finished layout balanced, (2) admit a loading
657
+ order that never tips the plank (the task is solvable) and (3) agree with every observed placement (tipped or
658
+ not, with a +-10 % band in which either outcome counts as consistent). Falls back to (1)+(2) if no assignment
659
+ agrees with all observations."""
660
+ marks = self.inst["marks"]
661
+ prior = []
662
+ for k in range(5):
663
+ for heavy in itertools.combinations(COLORS, k):
664
+ mass = {c: (H_EST if c in heavy else L_EST) for c in COLORS}
665
+ if tip_ratio([(mass[c], marks[c]) for c in COLORS]) > 0.6:
666
+ continue
667
+ for order in itertools.permutations(COLORS):
668
+ cur, w = [], 0.0
669
+ for c in order:
670
+ cur.append((mass[c], marks[c]))
671
+ w = max(w, tip_ratio(cur))
672
+ if w <= 0.9:
673
+ prior.append(mass)
674
+ break
675
+ if not use_obs:
676
+ return prior
677
+ post = []
678
+ for mass in prior:
679
+ if all(not ((ob["tipped"] and r < 0.9) or (not ob["tipped"] and r > 1.1))
680
+ for ob in self.obs for r in [tip_ratio([(mass[o], y) for o, y in ob["conf"].items()])]):
681
+ post.append(mass)
682
+ return post or prior
683
+
684
+ def unload_until_level(self, max_moves=4):
685
+ """while the plank is tipped: take the cube farthest out on its low side off the plank"""
686
+ for _ in range(max_moves):
687
+ envs.settle(self.env, 20)
688
+ self.wait_calm()
689
+ if self.is_level():
690
+ return True
691
+ t = self.tilt_deg()
692
+ yo = self._y_on_plank()
693
+ low = [c for c, y in yo.items() if (y > 0) == (t < 0)]
694
+ if not low:
695
+ return self.is_level()
696
+ self.park(min(low, key=lambda o: abs(yo[o]))) # the top of the pile first: the hand clears the others
697
+ envs.settle(self.env, 20)
698
+ self.wait_calm()
699
+ return self.is_level()
700
+
701
+ def restore(self, hyps_fn, rounds=3, record=False):
702
+ """Check every stage; if something is wrong: unload the low end if the plank is tipped, then (re)place every
703
+ cube that is not on its mark in the order the static model rates safest under the current mass hypotheses;
704
+ start over after a tip. Up to `rounds` passes."""
705
+ for _ in range(rounds):
706
+ envs.settle(self.env, 20)
707
+ if all(self.stage_values().values()):
708
+ return True
709
+ self.unload_until_level()
710
+ todo = [c for c in COLORS if not self.on_mark(c)]
711
+ if not todo:
712
+ continue
713
+ hyps = hyps_fn()
714
+ order, worst = self.plan(todo, hyps)
715
+ if worst > 0.9: # cubes left on the plank make every order risky: clear it and start from empty
716
+ for c in [c for c in COLORS if self.on_plank(c)]:
717
+ self.park(c)
718
+ order, worst = self.plan(list(COLORS), hyps)
719
+ for c in order:
720
+ if self.on_mark(c):
721
+ continue
722
+ if self.put(c, Z_CARRY, record=record, careful=True):
723
+ break # tipped: look again
724
+ envs.settle(self.env, 20)
725
+ return all(self.stage_values().values())
726
+
727
+ def naive_order(self, noise_sd=0.0, rng=None):
728
+ """nearest cube first, starting from the gripper's position and then from each mark just loaded"""
729
+ p = self.sk.eef_pos()[:2]
730
+ left, order = list(COLORS), []
731
+ while left:
732
+ dist = {c: np.linalg.norm(self.cube_pos(c)[:2] - p) + (rng.normal(0, noise_sd) if rng is not None else 0.0)
733
+ for c in left}
734
+ c = min(left, key=dist.get)
735
+ order.append(c)
736
+ left.remove(c)
737
+ p = self.mark_world(c)[:2]
738
+ return order
739
+
740
+ def slot_order(self, kind):
741
+ so = {s: c for c, s in self.inst["slot_of"].items()}
742
+ seq = dict(end2end=SLOTS, alt_outer=("near_outer", "far_outer", "near_inner", "far_inner"),
743
+ alt_inner=("near_inner", "far_inner", "near_outer", "far_outer"))[kind]
744
+ return [so[s] for s in seq]
745
+
746
+ def execute(self, inst, params):
747
+ rng = np.random.default_rng(params.get("seed", 0))
748
+ mode = params["mode"]
749
+ if mode == "plan":
750
+ hyps = [dict(inst["mass"])] if params.get("true_masses") else self.hypotheses()
751
+ order, _ = self.plan(list(COLORS), hyps)
752
+ elif mode in ("end2end", "alt_outer", "alt_inner"):
753
+ order = self.slot_order(mode)
754
+ else: # nearest first (naive / blind)
755
+ order = self.naive_order(params.get("order_noise", 0.0), rng)
756
+ noise = params.get("noise", 0.0)
757
+ z_carry = Z_CARRY if params.get("careful") else Z_CARRY_NAIVE
758
+ for c in order:
759
+ nz = rng.uniform(-noise, noise, 2) if noise else None
760
+ tipped = self.put(c, z_carry, noise=nz, record=params.get("record", False), careful=params.get("careful", False))
761
+ if tipped and params.get("check_each"):
762
+ break # look at what happened, then restore below
763
+ if params.get("check"):
764
+ hyps_fn = (lambda: [dict(inst["mass"])]) if params.get("true_masses") else self.hypotheses
765
+ self.restore(hyps_fn, record=params.get("record", False))
766
+ self.sk.hold(10)
767
+ return order
768
+
769
+ def default_params(self, inst):
770
+ return dict(mode="nearest", check=False)
771
+
772
+ def oracle_params(self, inst):
773
+ return dict(mode="plan", true_masses=True, careful=True, check=True)
774
+
775
+ def adapt_params(self, inst, history):
776
+ """from attempt 2: load in the order the observations of earlier attempts make safest, check after every
777
+ placement and restore at the end"""
778
+ return dict(mode="plan", careful=True, check=True, check_each=True, record=True)
779
+
780
+ def blind_params(self, inst, attempt, rng):
781
+ """nearest-first again with small random variation (order noise, 4 mm placement noise), no history, no check"""
782
+ return dict(mode="nearest", check=False, order_noise=0.03, noise=0.004, seed=int(rng.integers(1 << 30)))
783
+
784
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
785
+ k = k or self.max_attempts
786
+ rng = np.random.default_rng(seed)
787
+ history = []
788
+ self.obs = []
789
+ for a in range(k):
790
+ self.reset_instance(inst)
791
+ if kind == "oracle":
792
+ params = self.oracle_params(inst)
793
+ elif kind == "naive":
794
+ params = self.default_params(inst)
795
+ elif kind == "adaptive": # attempt 1: natural order, but look after every placement and restore
796
+ params = (dict(mode="nearest", check=True, check_each=True, record=True) if a == 0 else
797
+ self.adapt_params(inst, history))
798
+ elif kind == "blind":
799
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
800
+ elif kind in ("end2end", "alt_outer", "alt_inner"): # extra controls: other natural orders, no check
801
+ params = dict(mode=kind, check=False)
802
+ elif kind == "oracle_noise": # extra control: the oracle with +-5 mm (uniform) placement noise
803
+ params = dict(self.oracle_params(inst), noise=0.005, seed=int(rng.integers(1 << 30)))
804
+ elif kind == "switch": # extra control: no in-attempt repair, learn the order across attempts only
805
+ params = (dict(mode="nearest", check=False, record=True) if a == 0 else
806
+ dict(mode="plan", careful=True, check=False, record=True))
807
+ else:
808
+ raise ValueError(kind)
809
+ order = self.execute(inst, params)
810
+ out = self.outcome(inst)
811
+ out["order"] = order
812
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
813
+ if on_attempt:
814
+ on_attempt(a, params, out)
815
+ if out["success"] or kind in ("oracle", "oracle_noise", "naive", "end2end", "alt_outer", "alt_inner"):
816
+ break
817
+ return history
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_bridge.py ADDED
@@ -0,0 +1,1101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH lh_bridge (v2, 2026-10-09): build a small bridge (two pillars, a plank, then the red cube "car" on top); the car is
2
+ parked right behind the bridge site, and once the plank is down the agent's natural reach for it knocks the bridge down,
3
+ which must be rebuilt before the task can be finished.
4
+
5
+ Category: state_restoration, long-horizon self-inflicted regression. The user's example verbatim: "build a bridge;
6
+ while working you knock over a foundation you already built and must rebuild it before continuing".
7
+
8
+ v1 -> v2 (after the Sonnet 5.5 pilot lh1: only 1 of 3 instances was ever disturbed; Sonnet carried 12-20 cm high and
9
+ lifted over built pillars, so the v1 mechanism -- sweeping a pillar with a block carried low -- rarely happened; the one
10
+ disturbance was the hand landing on the plank while going for the red cube): the car now starts in the gap between the
11
+ two squares, 5.5-9 cm behind the bridge line (right behind where the plank will lie); a spare fifth block; the bridge
12
+ 4-7 cm further from the robot and the plank nearer, so that knocked parts stay within reach; softer contacts for the
13
+ bridge parts (the stiff default made collapsing blocks fly 30-90 cm); the naive reference imitates Sonnet's measured
14
+ motion style instead of the v1 low-transit script (kept as naive_v1).
15
+
16
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): two coloured square
17
+ marks (blue and green, 6 x 6 cm, visual only) 16 cm apart along y, 48-51 cm in front of the robot base; the red cube
18
+ (4 cm) in the gap between them, 5.5-9 cm behind the line through the squares (+-3 cm sideways, yaw +-20 deg); five
19
+ wooden cubes (edge 5.0-5.6 cm, friction 0.3-0.6, five distinct categories) in a row 9-11 cm behind the squares, two on
20
+ one side of the car and three on the other; the plank (24 x 5 x 1.2 cm) lying left-right 19-21 cm behind the squares.
21
+
22
+ Stages (order-free predicates, evaluated after every control step by a monitor; events are debounced over 6 steps):
23
+ S1 two blocks stacked on the blue square (lower block resting on the table within 2.5 cm of the square's centre,
24
+ upper block resting on it within 2.5 cm; any face down, cubes have no "right way up")
25
+ S2 the same on the green square
26
+ S3 the plank rests on the top blocks of both pillars: in contact with both, not with the table, tilt <= 10 deg
27
+ S4 the red cube rests on the plank within 6 cm of the plank's centre along its length
28
+ Success = all four hold at the end simultaneously, the scene is static (< 4 mm motion in 1 s) and the robot neither
29
+ holds nor touches any object. The monitor's achieved / lost / restored events go to the server log only (F1).
30
+
31
+ Why the agent breaks the bridge (measured, see task_cards/lh_bridge.md): with the plank down, the car sits 3-6.5 cm
32
+ behind the plank's back edge, between the pillars. The Panda hand is 21 cm long along the finger axis and its underside
33
+ is only 2.4 cm above the grasp point; the fingertips hang 1.3 cm below it. Each of the three pilot runs went for the car
34
+ differently; scripted here on seeds 1000-1019: hovering ~13 cm above it while turning the wrist from the plank's 90 deg
35
+ to the car's yaw, then straight down (5/20 knock the bridge), keeping the 90 deg wrist and going straight down (the hand
36
+ lands across the plank: 20/20), or one diagonal move from above the bridge straight down to the grasp (the hand drives
37
+ through the bridge: 20/20). The plank and one or both pillar tops fall; in 22 of 24 collapses (seeds 3000-3029) every
38
+ part needed stays within reach (a block out of reach is covered by the spare; the plank was thrown out of reach twice).
39
+ What prevents it (learnable from one failure, and what Sonnet wrote after its pilot failure): move the car away before
40
+ laying the plank.
41
+
42
+ Hidden variables: none that matter. Block size and friction are instance variety; the car's distance (5.5-9 cm) and yaw
43
+ decide only the "hover" style's outcome.
44
+
45
+ Scripted references (perception = simulator state):
46
+ naive Sonnet-like (measured on the pilot): instruction order; per pillar the free block nearest its square first;
47
+ hover ~12 cm above an object turned to its yaw, vertical descent, grasp 1.1 cm below the top; carry to a bare
48
+ square in one diagonal move to 12.5 cm above it, onto a block lift first; lift over a built pillar when the
49
+ carried block's straight path would hit it; release, lift to 15 cm; plank lifted to 7 cm, carried at 16 cm,
50
+ lift to 21 cm; the car approach style is the pilot's mixture (seed % 3: hover / keep / direct); no final check
51
+ naive_v1 the v1 naive (vertical / horizontal legs at 8 cm, carries at max(8 cm, release + 4 cm)), for comparison
52
+ oracle careful: first moves the car out of the zone behind the bridge; all transits at 25 cm, vertical approaches
53
+ at 0.1 m/s, grasps 1.6 cm below a cube's top, gripper yaw chosen for hand / finger clearance; checks every
54
+ stage at the end and repairs what is broken (same repair as adaptive)
55
+ adaptive attempt 1 = naive, then checks every stage before finishing and restores what was lost (tips a plank that
56
+ stands on edge, puts the plank and car aside, re-stacks the pillars from usable blocks, then plank and car
57
+ again); from attempt 2 the careful behaviour
58
+ blind naive with random variation (hover / carry / lift heights, diagonal or lift-first carries, car style,
59
+ block allocation, 4 mm placement noise), no history
60
+
61
+ Protocol: cross (reset to the same instance before every attempt), k = 3.
62
+ """
63
+ import os
64
+
65
+ import numpy as np
66
+
67
+ from .. import envs
68
+ from ..bddl import write_bddl
69
+ from ..objects import _fmt, _wrap, box_xml, register_generated
70
+ from ..skills import Skills
71
+ from ..task_base import LFFTask, register_task
72
+
73
+ BLOCKS = ["block_a_1", "block_b_1", "block_c_1", "block_d_1", "block_e_1"] # four are needed, one is a spare
74
+ PLANK, CAR = "plank_1", "car_1"
75
+ SQUARES = ["square_blue_1", "square_green_1"] # S1 = blue, S2 = green
76
+ ITEMS = BLOCKS + [PLANK, CAR]
77
+ BLOCK_RGBA = [(0.80, 0.66, 0.46, 1.0), (0.70, 0.55, 0.37, 1.0), (0.84, 0.72, 0.56, 1.0), (0.64, 0.50, 0.36, 1.0),
78
+ (0.76, 0.60, 0.42, 1.0)] # wood
79
+ PLANK_HALF = (0.12, 0.025, 0.006) # 24 x 5 x 1.2 cm, long axis = body x
80
+ CAR_HALF = 0.02
81
+ BLOCK_NOM = 0.026 # nominal half edge in the MJCF (resized per instance)
82
+ SQ_HALF = 0.03
83
+ SQ_RGBA = {"square_blue_1": (0.12, 0.30, 0.90, 1.0), "square_green_1": (0.10, 0.70, 0.25, 1.0)}
84
+ SQ_NAME = {"square_blue_1": "blue", "square_green_1": "green"}
85
+ SPAN = 0.16 # square centre distance (along y)
86
+
87
+ TZ = envs.TABLE_Z
88
+ BASE_X = -0.66
89
+ HAND_HALF_LONG = 0.106 # Panda hand collision AABB about the grasp site: +-10.6 cm along the finger axis
90
+ HAND_HALF_SHORT = 0.036 # +-3.6 cm across it
91
+ HAND_BOTTOM = 0.024 # its underside is 2.4 cm above the grasp site (measured)
92
+
93
+ SQ_TOL = 0.025 # lower block centre within 2.5 cm of the square centre
94
+ STACK_TOL = 0.025 # upper block centre within 2.5 cm of the lower one
95
+ FLAT_COS = np.cos(np.radians(12))
96
+ PLANK_TILT = np.radians(10)
97
+ CAR_MID = 0.06
98
+ DEBOUNCE = 6 # control steps a predicate must keep its new value before an event is recorded
99
+
100
+ # v2 layout (2026-10-09): the red cube ("car") is parked in the gap between the two squares, just behind the bridge
101
+ # line, so that once the plank is down a natural top-down grasp of it lands the hand on the plank / pillar tops; the
102
+ # four wooden blocks lie in a row behind the bridge, two on each side of the car; the plank lies further back.
103
+ LAYOUT = dict(bridge_x=(-0.18, -0.15), row_dx=(0.09, 0.11), y_half=0.30, gap=0.095, car_dx=(0.055, 0.09), car_dy=0.03,
104
+ car_clear=0.08, car_yaw=0.35, plank_dx=(0.19, 0.21), block_edge=(0.050, 0.056))
105
+ KEEP_OUT = dict(dx=0.13, dy=0.20) # careful: no parking / no material left within this zone behind the bridge line
106
+ # Sonnet-like naive (measured on the lh1 pilot, see task_cards/lh_bridge.md): heights of the grasp site above the table
107
+ SN = dict(hover=0.12, carry=0.125, lift=0.15, cross_margin=0.04, plank_lift=0.07, plank_carry=0.16, car_lift=0.17,
108
+ end_lift=0.25, top_below=0.011, diag=True, car_style=None, car_hover=0.134, plank_end_lift=0.21,
109
+ alloc="greedy")
110
+ # how the gripper went for the red cube once the plank was down -- each of the three pilot runs did it differently:
111
+ # hover (seed 3002) move to ~13.4 cm above it while turning to its yaw, then straight down
112
+ # keep (seed 3000) the same, but still turned 90 deg from laying the plank
113
+ # direct (seed 3001) one move from ~21 cm above the bridge straight (diagonally) down to the grasp
114
+ # the naive script uses style CAR_STYLES[seed % 3] (car_style=None), i.e. the pilot's mixture
115
+ CAR_STYLES = ("hover", "keep", "direct")
116
+ Z_NAIVE = 0.08 # naive_v1 transit height of the grasp site above the table
117
+ Z_SAFE = 0.25 # careful transit height
118
+ NAIVE_LIFT = 0.05 # naive: lift this far straight up after letting go, then head for the next waypoint
119
+ NAIVE_STYLE = "legs" # legs: vertical / horizontal legs at the transit height; diag: straight lines between waypoints
120
+
121
+
122
+ def _wrap_q(a):
123
+ """wrap to [-pi/4, pi/4) (cubes are symmetric under 90 deg)"""
124
+ return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
125
+
126
+
127
+ def _wrap_h(a):
128
+ """wrap to [-pi/2, pi/2) (plank / gripper symmetric under 180 deg)"""
129
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
130
+
131
+
132
+ # Contact softness of the bridge parts. LFF-Bench's generated boxes use a very stiff contact (objects._SOLID); when a
133
+ # fast hand drives into a stacked bridge, the stiff contacts resolve the overlap with large impulses and blocks fly
134
+ # 30-90 cm (measured: up to 1.7 m/s while the hand moved at 0.5-0.8 m/s), often out of reach or off the table. A
135
+ # softer contact (MuJoCo-like defaults) keeps collapses local. None = use the stiff default.
136
+ CONTACT = os.environ.get("LFF_LHB_CONTACT", 'solimp="0.95 0.99 0.001" solref="0.01 1"')
137
+
138
+
139
+ def part_xml(model_name, half, rgba, density):
140
+ """box like objects.box_xml, with the task's contact softness"""
141
+ if not CONTACT or CONTACT == "stiff":
142
+ return box_xml(model_name, half, rgba, density=density)
143
+ g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
144
+ f'density="{density}" friction="1.0 0.005 0.0001" {CONTACT} group="0" />\n'
145
+ f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
146
+ return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1])))
147
+
148
+
149
+ def mark_xml(name, rgba):
150
+ """flat coloured square, visual only (does not touch the physics)"""
151
+ g = (f' <geom type="box" size="{SQ_HALF:.5f} {SQ_HALF:.5f} 0.00060" rgba="{_fmt(rgba)}" '
152
+ f'contype="0" conaffinity="0" group="1" />')
153
+ return _wrap(name, g, 0.0006, SQ_HALF * 1.42)
154
+
155
+
156
+ class BridgeSkills(Skills):
157
+ """Skills that feed the task's per-step stage monitor."""
158
+
159
+ def __init__(self, env, task, recorder=None):
160
+ super().__init__(env, recorder=recorder)
161
+ self.task = task
162
+
163
+ def _act(self, dpos, drot, grip):
164
+ super()._act(dpos, drot, grip)
165
+ self.task.monitor_step()
166
+
167
+
168
+ @register_task
169
+ class Bridge(LFFTask):
170
+ name = "lh_bridge"
171
+ level = "L2"
172
+ category = "state_restoration"
173
+ capabilities = ("Perceive", "Plan", "Reason", "Restore")
174
+ protocol = "cross"
175
+ max_attempts = 3
176
+ agent_max_steps = 130
177
+ instruction = ("Build a small bridge. First stack two of the wooden blocks on the blue square, then two on the green "
178
+ "square, to make two pillars; then lay the long plank across the tops of both pillars; finally put "
179
+ "the red cube on the middle of the plank. The finished bridge must stand on its own, with the "
180
+ "gripper open and not touching anything.")
181
+ instruction_indirect = ("Build a small bridge. First make a tower of two of the wooden cubes on the blue mark on the "
182
+ "table, then another tower of two on the green mark; then lay the long flat board across the "
183
+ "tops of the two towers; finally set the small red cube on the middle of the board. At the "
184
+ "end everything must stand on its own, with the gripper open and not touching anything.")
185
+ agent_object_names = ["wooden blocks (5)", "plank", "red cube", "blue square", "green square"]
186
+
187
+ # ------------------------------------------------------------ scene
188
+ def make_bddl(self):
189
+ objs = []
190
+ for i, b in enumerate(BLOCKS):
191
+ cat = register_generated(f"LffLhbBlock{'ABCDE'[i]}", part_xml(f"lff_lhb_block_{'abcde'[i]}", (BLOCK_NOM,) * 3,
192
+ BLOCK_RGBA[i], 500.0))
193
+ reg = (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31) if i < 4 else (0.10, -0.25, 0.11, -0.24)
194
+ objs.append((b, cat, f"blk{i}_region", reg))
195
+ pl = register_generated("LffLhbPlank", part_xml("lff_lhb_plank", PLANK_HALF, (0.50, 0.33, 0.18, 1.0),
196
+ density=600.0))
197
+ objs.append((PLANK, pl, "plank_region", (0.05, -0.01, 0.06, 0.01)))
198
+ car = register_generated("LffLhbCar", part_xml("lff_lhb_car", (CAR_HALF,) * 3, (0.85, 0.10, 0.08, 1.0),
199
+ density=400.0))
200
+ objs.append((CAR, car, "car_region", (-0.30, -0.31, -0.29, -0.30)))
201
+ fx = []
202
+ for i, s in enumerate(SQUARES):
203
+ cat = register_generated(f"LffLhbSquare{'BG'[i]}", mark_xml(f"lff_lhb_square_{'bg'[i]}", SQ_RGBA[s]),
204
+ free=False)
205
+ fx.append((s, cat, f"sq{i}_region", (-0.10 + 0.10 * i, -0.31, -0.09 + 0.10 * i, -0.30)))
206
+ return write_bddl(self.name, "Build a small bridge from the blocks the plank and the red cube", objs, fx)
207
+
208
+ def __init__(self, cam_res=None):
209
+ super().__init__(cam_res)
210
+ m = self.env.sim.model
211
+ self.sq_bid = {s: m.body_name2id(self.env.fixtures_dict[s].root_body) for s in SQUARES}
212
+ self.geoms = {o: envs.obj_geom_ids(self.env, o) for o in ITEMS}
213
+ self.vis_geoms = {}
214
+ for o in BLOCKS:
215
+ root = envs.body_id(self.env, o)
216
+ bodies = {b for b in range(m.nbody) if b == root or m.body_parentid[b] == root}
217
+ self.vis_geoms[o] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in bodies and m.geom_contype[g] == 0
218
+ and m.geom_conaffinity[g] == 0 and m.geom_type[g] == 6]
219
+ self.block_body = getattr(self, "block_body", {})
220
+ self.block_body[o] = int(m.geom_bodyid[self.geoms[o][0]])
221
+ self.table_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("main_table")
222
+ and m.geom_contype[g] != 0]
223
+ self.robot_geoms = set(envs.robot_geom_ids(self.env))
224
+ self.inst = None
225
+ self.mon = None
226
+ self.sk = None
227
+ self.naive_lift = NAIVE_LIFT
228
+ self.naive_style = NAIVE_STYLE
229
+
230
+ # ------------------------------------------------------------ instances
231
+ def sample_instance(self, seed):
232
+ rng = np.random.default_rng(seed)
233
+ xb = float(rng.uniform(*LAYOUT["bridge_x"]))
234
+ yc = float(rng.uniform(-0.03, 0.03))
235
+ blue_left = bool(rng.random() < 0.5)
236
+ sq = {"square_blue_1": [xb, yc + (SPAN / 2 if blue_left else -SPAN / 2)],
237
+ "square_green_1": [xb, yc - (SPAN / 2 if blue_left else -SPAN / 2)]}
238
+ L = LAYOUT
239
+ # the car: in the gap between the two squares, just behind the bridge line
240
+ pos = {CAR: [xb + float(rng.uniform(*L["car_dx"])), yc + float(rng.uniform(-L["car_dy"], L["car_dy"]))]}
241
+ # five blocks in a row behind the bridge line, two on one side of the car and three on the other
242
+ row_x = xb + float(rng.uniform(*L["row_dx"]))
243
+ ys = []
244
+ three = 1.0 if rng.random() < 0.5 else -1.0
245
+ for side in (-1.0, 1.0):
246
+ n = 3 if side == three else 2
247
+ lo, hi = sorted((pos[CAR][1] + side * L["car_clear"], side * L["y_half"]))
248
+ u = np.sort(rng.uniform(0.0, max((hi - lo) - (n - 1) * L["gap"], 0.0), n))
249
+ ys += [lo + k * L["gap"] + u[k] for k in range(n)]
250
+ order = rng.permutation(5)
251
+ for k, j in enumerate(order):
252
+ pos[BLOCKS[j]] = [row_x + float(rng.uniform(-0.01, 0.01)), float(ys[k])]
253
+ plank_xy = [xb + float(rng.uniform(*L["plank_dx"])), yc + float(rng.uniform(-0.04, 0.04))]
254
+ size = {b: float(rng.uniform(*L["block_edge"])) for b in BLOCKS}
255
+ mu = {b: float(rng.uniform(0.3, 0.6)) for b in BLOCKS}
256
+ yaw = {o: float(rng.uniform(-0.35, 0.35)) for o in BLOCKS}
257
+ yaw[CAR] = float(rng.uniform(-L["car_yaw"], L["car_yaw"]))
258
+ yaw[PLANK] = float(np.pi / 2 + rng.uniform(-0.25, 0.25)) # long axis roughly left-right
259
+ pos[PLANK] = plank_xy
260
+ return dict(seed=int(seed), squares=sq, blue_side="left" if blue_left else "right", pos=pos, yaw=yaw,
261
+ size=size, mu=mu, bridge_x=xb, bridge_yc=yc)
262
+
263
+ def _resize_block(self, o, edge):
264
+ m = self.env.sim.model
265
+ h = edge / 2.0
266
+ for g in self.geoms[o] + self.vis_geoms[o]:
267
+ m.geom_size[g] = [h, h, h]
268
+ m.geom_rbound[g] = float(np.sqrt(3) * h)
269
+ m.geom_aabb[g] = [0.0, 0.0, 0.0, h, h, h]
270
+ b = self.block_body[o]
271
+ mass = 500.0 * edge ** 3
272
+ m.body_mass[b] = mass
273
+ m.body_inertia[b] = [mass * edge ** 2 / 6.0] * 3
274
+ envs.refit_bounds(self.env, b) # BVH of the resized block (envs.refit_bounds)
275
+
276
+ def apply_instance(self, inst):
277
+ self.inst = inst
278
+ m = self.env.sim.model
279
+ for s in SQUARES:
280
+ x, y = inst["squares"][s]
281
+ m.body_pos[self.sq_bid[s]] = [x, y, TZ + 0.0007]
282
+ m.body_quat[self.sq_bid[s]] = [1.0, 0.0, 0.0, 0.0]
283
+ for o in BLOCKS:
284
+ self._resize_block(o, inst["size"][o])
285
+ envs.set_friction(self.env, o, inst["mu"][o])
286
+ envs.set_friction(self.env, PLANK, 0.5)
287
+ envs.set_friction(self.env, CAR, 0.6)
288
+ self.env.sim.forward()
289
+ for o in ITEMS:
290
+ envs.place_upright(self.env, o, inst["pos"][o], inst["yaw"][o], clearance=0.001)
291
+
292
+ def reset_instance(self, inst, recorder=None):
293
+ self.mon = None
294
+ self.env.reset()
295
+ self.apply_instance(inst)
296
+ self.env.sim.forward()
297
+ envs.settle(self.env, 15)
298
+ self.sk = BridgeSkills(self.env, self, recorder=recorder)
299
+ self.mon = dict(state=[False] * 4, raw_since=[0] * 4, ever=[False] * 4, lost=[False] * 4, events=[])
300
+ return self.sk
301
+
302
+ # ------------------------------------------------------------ geometry / predicates
303
+ def half(self, o):
304
+ if o in BLOCKS:
305
+ e = self.inst["size"][o] / 2
306
+ return np.array([e, e, e])
307
+ return np.array(PLANK_HALF) if o == PLANK else np.array([CAR_HALF] * 3)
308
+
309
+ def R(self, o):
310
+ return self.env.sim.data.body_xmat[envs.body_id(self.env, o)].reshape(3, 3).copy()
311
+
312
+ def pos(self, o):
313
+ return envs.obj_pos(self.env, o)
314
+
315
+ def zmin(self, o):
316
+ return envs.obj_min_z(self.env, o)
317
+
318
+ def zmax(self, o):
319
+ return envs.obj_max_z(self.env, o)
320
+
321
+ def flat(self, o):
322
+ return float(np.max(np.abs(self.R(o)[2]))) > FLAT_COS
323
+
324
+ def yaw_of(self, o):
325
+ """yaw of the object's body x axis (for the plank: its long axis)"""
326
+ R = self.R(o)
327
+ return float(np.arctan2(R[1, 0], R[0, 0]))
328
+
329
+ def held(self, o):
330
+ return self.sk is not None and self.sk.holding(o)
331
+
332
+ def contacts(self, a_geoms, b_geoms):
333
+ return envs.contacts_between(self.env, a_geoms, b_geoms)
334
+
335
+ def pillar(self, s):
336
+ """(lower, upper) blocks of a complete pillar on square s, else (lower or None, None)"""
337
+ c = np.asarray(self.inst["squares"][s])
338
+ lower = None
339
+ for b in BLOCKS:
340
+ p = self.pos(b)
341
+ if np.linalg.norm(p[:2] - c) <= SQ_TOL and self.zmin(b) < TZ + 0.006 and self.flat(b) and not self.held(b):
342
+ lower = b
343
+ break
344
+ if lower is None:
345
+ return None, None
346
+ pl = self.pos(lower)
347
+ top = self.zmax(lower)
348
+ for b in BLOCKS:
349
+ if b == lower:
350
+ continue
351
+ p = self.pos(b)
352
+ if (np.linalg.norm(p[:2] - pl[:2]) <= STACK_TOL and abs(self.zmin(b) - top) < 0.006 and self.flat(b)
353
+ and not self.held(b)):
354
+ return lower, b
355
+ return lower, None
356
+
357
+ def plank_ok(self, tops):
358
+ if any(t is None for t in tops) or self.held(PLANK):
359
+ return False
360
+ R = self.R(PLANK)
361
+ if abs(R[2, 0]) > np.sin(PLANK_TILT) or abs(R[2, 2]) < np.cos(PLANK_TILT): # either broad face up (v2 fix)
362
+ return False
363
+ if self.zmin(PLANK) < TZ + 0.03 or self.contacts(self.geoms[PLANK], self.table_geoms):
364
+ return False
365
+ return all(self.contacts(self.geoms[PLANK], self.geoms[t]) for t in tops)
366
+
367
+ def car_ok(self):
368
+ """the car rests on the plank's upper face (in the plank's own frame, so a slightly tilted plank is fine),
369
+ within CAR_MID of the plank's centre along its length"""
370
+ if self.held(CAR) or not self.contacts(self.geoms[CAR], self.geoms[PLANK]):
371
+ return False
372
+ R = self.R(PLANK)
373
+ rel = R.T @ (self.pos(CAR) - self.pos(PLANK))
374
+ up = rel[2] * (1.0 if R[2, 2] >= 0 else -1.0) # along the broad face pointing up (a plank may lie upside down)
375
+ return bool(abs(rel[0]) <= CAR_MID and abs(rel[1]) <= PLANK_HALF[1] + 0.01 and up > PLANK_HALF[2] + 0.01)
376
+
377
+ def stages(self):
378
+ """raw predicate values [S1, S2, S3, S4] and the pillars found"""
379
+ pa = self.pillar(SQUARES[0])
380
+ pb = self.pillar(SQUARES[1])
381
+ s1, s2 = pa[1] is not None, pb[1] is not None
382
+ s3 = bool(s1 and s2 and self.plank_ok([pa[1], pb[1]]))
383
+ s4 = bool(self.car_ok())
384
+ return [s1, s2, s3, s4], (pa, pb)
385
+
386
+ # ------------------------------------------------------------ monitor
387
+ def monitor_step(self):
388
+ mon = self.mon
389
+ if mon is None or self.sk is None:
390
+ return
391
+ raw, _ = self.stages()
392
+ t = self.sk.n_steps
393
+ for i in range(4):
394
+ if raw[i] == mon["state"][i]:
395
+ mon["raw_since"][i] = 0
396
+ continue
397
+ mon["raw_since"][i] += 1
398
+ if mon["raw_since"][i] < DEBOUNCE:
399
+ continue
400
+ mon["state"][i] = raw[i]
401
+ mon["raw_since"][i] = 0
402
+ t0 = t - DEBOUNCE + 1
403
+ if raw[i]:
404
+ ev = "restored" if mon["lost"][i] else "achieved"
405
+ mon["ever"][i] = True
406
+ else:
407
+ ev = "lost"
408
+ mon["lost"][i] = True
409
+ mon["events"].append(dict(stage=f"S{i + 1}", event=ev, step=int(t0)))
410
+
411
+ # ------------------------------------------------------------ outcome
412
+ def _dir_words(self, d):
413
+ """robot-centric words for a horizontal offset d (world x = forward, away from the robot; y = robot's left)"""
414
+ parts = []
415
+ if abs(d[0]) >= 0.01:
416
+ parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}")
417
+ if abs(d[1]) >= 0.01:
418
+ parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}")
419
+ return (" and ".join(parts) + " of") if parts else "right at"
420
+
421
+ def outcome(self, inst):
422
+ sk = self.sk
423
+ sk.hold(10)
424
+ p0 = {o: self.pos(o) for o in ITEMS}
425
+ touching = False
426
+ for _ in range(20):
427
+ sk.hold(1)
428
+ touching = touching or any(self.contacts(list(self.robot_geoms), self.geoms[o]) for o in ITEMS)
429
+ moved = max(float(np.linalg.norm(self.pos(o) - p0[o])) for o in ITEMS)
430
+ static = moved < 0.004
431
+ raw, (pa, pb) = self.stages()
432
+ held = [o for o in ITEMS if sk.holding(o)]
433
+ mon = self.mon
434
+ ev = list(mon["events"]) if mon else []
435
+ n_reg = sum(e["event"] == "lost" for e in ev)
436
+ n_res = sum(e["event"] == "restored" for e in ev)
437
+ success = bool(all(raw) and static and not held and not touching)
438
+ parts = []
439
+ if success:
440
+ failure = "none"
441
+ parts.append("The bridge is complete: both pillars stand on their squares, the plank rests across them "
442
+ "and the red cube sits on the middle of the plank.")
443
+ else:
444
+ lost_final = [i for i in range(4) if not raw[i] and mon and mon["ever"][i]]
445
+ never = [i for i in range(4) if not raw[i] and not (mon and mon["ever"][i])]
446
+ if held:
447
+ failure = "held"
448
+ elif touching:
449
+ failure = "touching"
450
+ elif lost_final:
451
+ failure = "regressed_" + "".join(f"S{i + 1}" for i in lost_final)
452
+ elif never:
453
+ failure = "incomplete_" + "".join(f"S{i + 1}" for i in never)
454
+ else:
455
+ failure = "not_static"
456
+ for i, s in enumerate(SQUARES):
457
+ if raw[i]:
458
+ continue
459
+ low, _ = (pa, pb)[i]
460
+ c = np.asarray(inst["squares"][s])
461
+ txt = f"The pillar on the {SQ_NAME[s]} square is not standing:"
462
+ if low is None:
463
+ txt += " no block stands on the square."
464
+ else:
465
+ txt += " only one block stands on the square."
466
+ strays = [b for b in BLOCKS if b not in (pa[0], pa[1], pb[0], pb[1])]
467
+ if strays:
468
+ near = min(strays, key=lambda b: np.linalg.norm(self.pos(b)[:2] - c))
469
+ txt += f" The nearest loose block lies {self._dir_words(self.pos(near)[:2] - c)} the square."
470
+ if mon and mon["ever"][i]:
471
+ txt += " It had been built and was knocked down later."
472
+ parts.append(txt)
473
+ if not raw[2]:
474
+ pp = self.pos(PLANK)
475
+ if self.contacts(self.geoms[PLANK], self.table_geoms):
476
+ where = "touches the table"
477
+ elif self.held(PLANK):
478
+ where = "is still in the gripper"
479
+ else:
480
+ where = "does not rest level on the tops of both pillars"
481
+ bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0)
482
+ parts.append(f"The plank {where}; its centre is {self._dir_words(pp[:2] - bc)} the middle between "
483
+ f"the squares." + (" It had been laid and was disturbed later." if mon and mon["ever"][2]
484
+ and not raw[2] else ""))
485
+ if not raw[3]:
486
+ if self.held(CAR):
487
+ parts.append("The red cube is still in the gripper.")
488
+ elif self.contacts(self.geoms[CAR], self.geoms[PLANK]):
489
+ parts.append("The red cube is on the plank but not on its middle part.")
490
+ else:
491
+ bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0)
492
+ parts.append(f"The red cube is not on the plank; it lies {self._dir_words(self.pos(CAR)[:2] - bc)} "
493
+ "the middle between the squares.")
494
+ if all(raw) and held:
495
+ parts.append("The gripper still holds an object.")
496
+ elif touching:
497
+ parts.append("The gripper is still touching the bridge.")
498
+ elif all(raw) and not static:
499
+ parts.append("The bridge was still moving.")
500
+ if n_reg:
501
+ parts.append(f"During the attempt earlier stages were undone {n_reg} time(s) and restored {n_res} time(s).")
502
+ if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")):
503
+ parts.append("(Forward = away from the robot.)")
504
+ return dict(success=success, stages={f"S{i + 1}": bool(raw[i]) for i in range(4)}, events=ev,
505
+ n_regressions=int(n_reg), n_restored=int(n_res), failure=failure, held=held,
506
+ touching=bool(touching), static=bool(static), detail=" ".join(parts))
507
+
508
+ # ------------------------------------------------------------ scripted policies (move_to + gripper only)
509
+ def _grip_yaws(self, o):
510
+ """candidate gripper yaws for a top-down grasp of o (fingers across a face)"""
511
+ if o == PLANK: # fingers (which open along the gripper's y at yaw 0) across the plank's width
512
+ return [_wrap_h(self.yaw_of(PLANK))]
513
+ a = _wrap_q(self.yaw_of(o))
514
+ return [a, _wrap_h(a + np.pi / 2)]
515
+
516
+ def footprint(self, o):
517
+ """sample points on the horizontal footprint of o (corners, edge midpoints, centre)"""
518
+ R, c, h = self.R(o), self.pos(o), self.half(o)
519
+ pts = []
520
+ for sx in (-1, 0, 1):
521
+ for sy in (-1, 0, 1):
522
+ for sz in ((-1, 1) if o != PLANK else (0,)):
523
+ pts.append((c + R @ (h * [sx, sy, sz]))[:2])
524
+ if o == PLANK:
525
+ for t_ in np.linspace(-1, 1, 9):
526
+ for sy in (-1, 1):
527
+ pts.append((c + R @ (h * [t_, sy, 0]))[:2])
528
+ return np.array(pts)
529
+
530
+ def _hand_clearance(self, xy, yaw, z_site, ignore=()):
531
+ """smallest horizontal clearance (m) between the gripper at a grasp-site height z_site and everything else:
532
+ the hand body (+-10.6 x +-3.6 cm, underside 2.4 cm above the site) against items taller than its underside,
533
+ the open fingers (two 2 x 2.4 cm boxes 3-5 cm out along the finger axis, tips 1.3 cm below the site)
534
+ against items taller than the fingertips. Negative = the gripper would land on something."""
535
+ f = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis
536
+ g = np.array([np.cos(yaw), np.sin(yaw)])
537
+ best = 1.0
538
+ for o in ITEMS:
539
+ if o in ignore or self.held(o):
540
+ continue
541
+ top = self.zmax(o)
542
+ if top < z_site - 0.013:
543
+ continue
544
+ d = self.footprint(o) - np.asarray(xy)
545
+ u, v = np.abs(d @ f), np.abs(d @ g)
546
+ c = float(np.min(np.maximum(np.abs(u - 0.040) - 0.010, v - 0.012))) # fingers
547
+ if top >= z_site + HAND_BOTTOM - 0.002:
548
+ c = min(c, float(np.min(np.maximum(u - HAND_HALF_LONG, v - HAND_HALF_SHORT))))
549
+ best = min(best, c)
550
+ return best
551
+
552
+ @staticmethod
553
+ def _pick_yaw(yaws, clearance):
554
+ """the gripper yaw closest to straight (0) among those with >= 1 cm clearance, else the clearest one (large
555
+ wrist turns near the edge of the workspace make the OSC stop short)"""
556
+ c = {a: clearance(a) for a in yaws}
557
+ ok = [a for a in yaws if c[a] >= 0.01]
558
+ return min(ok, key=abs) if ok else max(yaws, key=c.get)
559
+
560
+ def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=250):
561
+ return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
562
+
563
+ def _grasp_z(self, o, careful):
564
+ if o in BLOCKS:
565
+ return self.zmax(o) - (0.016 if careful else self.inst["size"][o] / 2)
566
+ if o == PLANK:
567
+ return max(self.zmax(PLANK) + 0.0003 - 0.0125, TZ + 0.011)
568
+ return self.zmax(CAR) - (0.016 if careful else CAR_HALF)
569
+
570
+ def pick(self, o, careful, noise=None, z_t=None):
571
+ """top-down grasp; returns the drop of the object's bottom below the grasp site, or None if not held"""
572
+ sk = self.sk
573
+ p = self.pos(o)
574
+ if noise is not None:
575
+ p = p + np.array([noise[0], noise[1], 0.0])
576
+ zg = self._grasp_z(o, careful)
577
+ yaws = self._grip_yaws(o)
578
+ if careful:
579
+ yaw = self._pick_yaw(yaws, lambda a: self._hand_clearance(p[:2], a, zg, ignore=(o,)))
580
+ cur = sk.eef_pos()
581
+ self._go([cur[0], cur[1], TZ + Z_SAFE])
582
+ self._go([p[0], p[1], TZ + Z_SAFE], yaw=yaw)
583
+ sk.set_gripper(False, steps=8)
584
+ self._go([p[0], p[1], zg + 0.03], speed=0.25)
585
+ self._go([p[0], p[1], zg], speed=0.1, tol=0.003, max_steps=120)
586
+ else:
587
+ yaw = min(yaws, key=lambda a: abs(a))
588
+ zt = TZ + (Z_NAIVE if z_t is None else z_t)
589
+ sk.set_gripper(False, steps=8)
590
+ if self.naive_style == "legs": # rise to the transit height if below it, across, straight down
591
+ cur = sk.eef_pos()
592
+ if cur[2] < zt - 0.003:
593
+ self._go([cur[0], cur[1], zt])
594
+ self._go([p[0], p[1], max(cur[2], zt)], yaw=yaw)
595
+ else: # one straight line to the approach point above the object
596
+ self._go([p[0], p[1], max(zt, self.zmax(o) + 0.03)], yaw=yaw)
597
+ self._go([p[0], p[1], zg], tol=0.003, max_steps=120)
598
+ sk.set_gripper(True, steps=15)
599
+ drop = float(sk.eef_pos()[2] - self.zmin(o))
600
+ if careful:
601
+ self._go([p[0], p[1], TZ + Z_SAFE], speed=0.3)
602
+ else:
603
+ zt = TZ + (Z_NAIVE if z_t is None else z_t)
604
+ self._go([p[0], p[1], max(zt, zg + 0.05)])
605
+ if not sk.holding(o):
606
+ sk.set_gripper(False, steps=8)
607
+ return None
608
+ return drop
609
+
610
+ def place(self, o, xy, support_top, drop, yaw, careful, z_t=None, release_gap=0.005, lift=None):
611
+ sk = self.sk
612
+ zr = support_top + drop + release_gap
613
+ if careful and o != PLANK: # cubes are symmetric under 90 deg: release with the fingers where there is room
614
+ yaw = self._pick_yaw([yaw, _wrap_h(yaw + np.pi / 2)], lambda a: self._hand_clearance(xy, a, zr, ignore=(o,)))
615
+ if careful:
616
+ cur = sk.eef_pos()
617
+ self._go([cur[0], cur[1], TZ + Z_SAFE])
618
+ self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw)
619
+ self._go([xy[0], xy[1], zr + 0.03], speed=0.25)
620
+ self._go([xy[0], xy[1], zr], speed=0.08, tol=0.003, max_steps=120)
621
+ sk.set_gripper(False, steps=12)
622
+ self._go([xy[0], xy[1], zr + 0.03], speed=0.1)
623
+ self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3)
624
+ else:
625
+ if self.naive_style == "legs":
626
+ zt = TZ + (Z_NAIVE if z_t is None else z_t)
627
+ cur = sk.eef_pos()
628
+ h = max(cur[2], zt, zr + 0.04)
629
+ if cur[2] < h - 0.003:
630
+ self._go([cur[0], cur[1], h])
631
+ self._go([xy[0], xy[1], h], yaw=yaw)
632
+ else:
633
+ self._go([xy[0], xy[1], zr + 0.04], yaw=yaw)
634
+ self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120)
635
+ sk.set_gripper(False, steps=12)
636
+ self._go([xy[0], xy[1], zr + (self.naive_lift if lift is None else lift)])
637
+ sk.hold(5)
638
+
639
+ # placing targets ---------------------------------------------------------
640
+ def square_xy(self, s):
641
+ return np.asarray(self.inst["squares"][s], float)
642
+
643
+ def bridge_mid(self):
644
+ return np.mean([self.square_xy(s) for s in SQUARES], axis=0)
645
+
646
+ def free_blocks(self):
647
+ _, (pa, pb) = self.stages()
648
+ used = set()
649
+ for low, up in (pa, pb):
650
+ if up is not None:
651
+ used |= {low, up}
652
+ return [b for b in BLOCKS if b not in used]
653
+
654
+ def _blocker(self, b):
655
+ """for a careful top-down grasp of block b: None if the gripper fits at some grasp yaw, else the item in the
656
+ way (e.g. the top block of a pillar, or a block, right next to b)"""
657
+ zg = self._grasp_z(b, True)
658
+ p = self.pos(b)[:2]
659
+ if max(self._hand_clearance(p, a, zg, ignore=(b,)) for a in self._grip_yaws(b)) > -0.002:
660
+ return None
661
+ worst = {}
662
+ for o in ITEMS:
663
+ if o == b or self.held(o):
664
+ continue
665
+ worst[o] = max(self._hand_clearance(p, a, zg, ignore=tuple(q for q in ITEMS if q != o))
666
+ for a in self._grip_yaws(b))
667
+ o = min(worst, key=worst.get)
668
+ return o if worst[o] <= -0.002 else None
669
+
670
+ def build_pillar(self, s, careful, noise_fn, z_t=None, order="target"):
671
+ """put blocks on square s until it carries a complete pillar (at most 5 placements)"""
672
+ failed = {}
673
+ for _ in range(6):
674
+ raw, (pa, pb) = self.stages()
675
+ low, up = (pa, pb)[SQUARES.index(s)]
676
+ if up is not None:
677
+ return True
678
+ if careful and self.over_budget():
679
+ return False
680
+ c = self.square_xy(s)
681
+ other = (pa, pb)[1 - SQUARES.index(s)]
682
+ cand = [b for b in BLOCKS if b != low and b not in other and (not careful or (self.usable(b)
683
+ and failed.get(b, 0) < 2))]
684
+ if not cand:
685
+ return False
686
+ ref = self.sk.eef_pos()[:2] if order == "gripper" else c
687
+ cand.sort(key=lambda b: (failed.get(b, 0), np.linalg.norm(self.pos(b)[:2] - ref)))
688
+ b = cand[0]
689
+ if careful:
690
+ free = [q for q in cand if self._blocker(q) is None]
691
+ if free:
692
+ b = free[0]
693
+ else: # every usable block sits right next to something tall: take that thing's top off first
694
+ blk = self._blocker(cand[0])
695
+ if blk is not None and blk != PLANK and failed.get(blk, 0) < 2:
696
+ if not self.park(blk):
697
+ failed[blk] = failed.get(blk, 0) + 1
698
+ continue
699
+ drop = self.pick(b, careful, noise=noise_fn(), z_t=z_t)
700
+ if drop is None:
701
+ failed[b] = failed.get(b, 0) + 1
702
+ continue
703
+ if low is None:
704
+ tgt, top = c, TZ
705
+ else:
706
+ tgt, top = self.pos(low)[:2], self.zmax(low)
707
+ n = noise_fn()
708
+ self.place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, careful, z_t=z_t)
709
+ return self.stages()[1][SQUARES.index(s)][1] is not None
710
+
711
+ def lay_plank(self, careful, noise_fn, z_t=None):
712
+ raw, (pa, pb) = self.stages()
713
+ if pa[1] is None or pb[1] is None or (careful and not self.usable(PLANK)):
714
+ return False
715
+ drop = self.pick(PLANK, careful, noise=noise_fn(), z_t=z_t)
716
+ if drop is None:
717
+ return False
718
+ raw, (pa, pb) = self.stages()
719
+ if pa[1] is None or pb[1] is None:
720
+ tops = [TZ + 0.11, TZ + 0.11]
721
+ mid = self.bridge_mid()
722
+ else:
723
+ tops = [self.zmax(pa[1]), self.zmax(pb[1])]
724
+ mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2
725
+ n = noise_fn()
726
+ # gripper fingers across the plank's width: plank long axis along y -> gripper yaw 90 deg
727
+ self.place(PLANK, mid + (n if n is not None else 0.0), max(tops), drop, np.pi / 2, careful, z_t=z_t)
728
+ return True
729
+
730
+ def put_car(self, careful, noise_fn, z_t=None):
731
+ drop = self.pick(CAR, careful, noise=noise_fn(), z_t=z_t)
732
+ if drop is None:
733
+ return False
734
+ pp = self.pos(PLANK)
735
+ n = noise_fn()
736
+ self.place(CAR, pp[:2] + (n if n is not None else 0.0), self.zmax(PLANK), drop, 0.0, careful, z_t=z_t)
737
+ return True
738
+
739
+ def in_keep_out(self, o):
740
+ """o lies in the zone right behind the bridge line where, once the pillars and the plank stand, a top-down
741
+ grasp would put the hand on them (the careful policy keeps it clear)"""
742
+ p = self.pos(o)[:2]
743
+ dx = p[0] - self.inst["bridge_x"]
744
+ return bool(-0.08 < dx < KEEP_OUT["dx"] and abs(p[1] - self.bridge_mid()[1]) < KEEP_OUT["dy"])
745
+
746
+ def free_spot(self, o, avoid=()):
747
+ """a free, comfortably reachable table spot for parking object o (the plank lies left-right), outside the
748
+ keep-out zone right behind the bridge and away from the squares"""
749
+ xb = self.inst["bridge_x"]
750
+ ym = self.bridge_mid()[1]
751
+ best, best_c = None, -1.0
752
+ others = [q for q in ITEMS if q != o and q not in avoid]
753
+ for x in np.arange(xb - 0.14, xb + 0.221, 0.02):
754
+ for y in np.arange(-0.28, 0.281, 0.02):
755
+ pts = [np.array([x, y])]
756
+ if o == PLANK:
757
+ pts = [np.array([x, y + d]) for d in (-0.10, 0.0, 0.10)]
758
+ if any(not self.reachable_xy(p) or np.hypot(p[0] - BASE_X, p[1]) > 0.64 for p in pts):
759
+ continue # (a careful 25 cm transit further out straightens the elbow onto its limit, measured)
760
+ if any(-0.08 < p[0] - xb < KEEP_OUT["dx"] and abs(p[1] - ym) < KEEP_OUT["dy"] for p in pts):
761
+ continue
762
+ c = 1.0
763
+ for p in pts:
764
+ for q in others:
765
+ c = min(c, float(np.linalg.norm(self.pos(q)[:2] - p)) - 0.04)
766
+ for sq in SQUARES:
767
+ c = min(c, float(np.linalg.norm(self.square_xy(sq) - p)) - 0.07)
768
+ if c > best_c:
769
+ best, best_c = np.array([x, y]), c
770
+ return best
771
+
772
+ @staticmethod
773
+ def reachable_xy(p):
774
+ """a top-down grasp at table height works here (measured: right in front of the base, closer than 25 cm,
775
+ the arm cannot get down to the table; at 70-74 cm it still gets within ~1 cm)"""
776
+ rx, y = p[0] - BASE_X, p[1]
777
+ return bool(0.25 <= rx <= 0.75 and abs(y) <= 0.34 and (rx >= 0.30 or abs(y) >= 0.15) and np.hypot(rx, y) <= 0.76)
778
+
779
+ def usable(self, o):
780
+ """o lies on the table (or on something) within reach"""
781
+ return self.zmin(o) > TZ - 0.02 and self.reachable_xy(self.pos(o)[:2])
782
+
783
+ def park(self, o, careful=True):
784
+ if careful and not self.usable(o):
785
+ return False
786
+ drop = self.pick(o, careful)
787
+ if drop is None:
788
+ return False
789
+ xy = self.free_spot(o)
790
+ self.place(o, xy, TZ, drop, np.pi / 2 if o == PLANK else 0.0, careful)
791
+ return True
792
+
793
+ def over_budget(self):
794
+ """the scripted repair stops where an agent's attempt would end: 3 s of simulated motion per command of the
795
+ task's command budget (agent_max_steps = 130 -> 390 s = 7800 control steps)"""
796
+ return self.sk.n_steps * 0.05 >= 3.0 * self.agent_max_steps
797
+
798
+ def plank_flat(self):
799
+ return abs(self.R(PLANK)[2, 2]) > 0.8
800
+
801
+ def fix_plank(self):
802
+ """a plank standing on its long edge or leaning on something cannot be picked from above: push its upper edge
803
+ over with the closed gripper so that it falls flat (towards the side with more free table)"""
804
+ if self.plank_flat() or self.held(PLANK):
805
+ return False
806
+ sk = self.sk
807
+ R, c = self.R(PLANK), self.pos(PLANK)
808
+ up = R[:, 1] if R[2, 1] > 0 else -R[:, 1] # the plank's width axis, pointing up
809
+ lean = up[:2] / max(np.linalg.norm(up[:2]), 1e-6)
810
+ if np.linalg.norm(up[:2]) < 0.2: # standing upright: fall to the side away from the squares
811
+ n = R[:2, 2] / max(np.linalg.norm(R[:2, 2]), 1e-6)
812
+ far = lambda d: min(np.linalg.norm(c[:2] + 0.05 * d - self.square_xy(q)) for q in SQUARES) # noqa: E731
813
+ lean = n if far(n) > far(-n) else -n
814
+ push = lean
815
+ else: # leaning: push the top back over the vertical so it falls to the other side
816
+ push = -lean
817
+ top = c + up * 0.02
818
+ h = max(self.zmax(PLANK) - 0.015, TZ + 0.02)
819
+ a = top[:2] - push * 0.05
820
+ yaw = float(np.arctan2(push[1], push[0]) - np.pi / 2) # closed fingers across the push direction
821
+ sk.set_gripper(True, steps=8)
822
+ cur = sk.eef_pos()
823
+ self._go([cur[0], cur[1], TZ + Z_SAFE])
824
+ self._go([a[0], a[1], TZ + Z_SAFE], yaw=yaw)
825
+ self._go([a[0], a[1], h], speed=0.25)
826
+ b = top[:2] + push * 0.08
827
+ self._go([b[0], b[1], h], speed=0.1, max_steps=200)
828
+ self._go([b[0], b[1], TZ + Z_SAFE], speed=0.3)
829
+ sk.set_gripper(False, steps=8)
830
+ sk.hold(10)
831
+ return True
832
+
833
+ def clear_site(self):
834
+ """careful: before building, move the car out of the zone right behind the bridge line"""
835
+ if self.in_keep_out(CAR) and not self.held(CAR):
836
+ self.park(CAR)
837
+
838
+ def repair(self, rounds=4):
839
+ """check every stage; rebuild what is broken (careful motions). Returns the number of fixes made."""
840
+ nofn = lambda: None # noqa: E731
841
+ fixes = 0
842
+ for _ in range(rounds):
843
+ raw, (pa, pb) = self.stages()
844
+ if all(raw) or self.over_budget() or not (self.usable(PLANK) or self.held(PLANK)):
845
+ return fixes # (a plank thrown out of reach cannot be laid again)
846
+ fixes += 1
847
+ if not (raw[0] and raw[1]):
848
+ for _k in range(2):
849
+ if not self.plank_flat():
850
+ self.fix_plank()
851
+ plank_first = self._hand_clearance(self.pos(CAR)[:2], 0.0, self._grasp_z(CAR, True),
852
+ ignore=tuple(q for q in ITEMS if q != PLANK)) < 0.0
853
+ for o in ((PLANK, CAR) if plank_first else (CAR, PLANK)):
854
+ if o == CAR and (self.zmin(CAR) > TZ + 0.01 or self._near_squares(CAR) or self.in_keep_out(CAR)):
855
+ self.park(CAR)
856
+ if o == PLANK and (self.zmin(PLANK) > TZ + 0.006 or self._near_squares(PLANK)
857
+ or self.in_keep_out(PLANK)):
858
+ self.park(PLANK)
859
+ for i, s in enumerate(SQUARES):
860
+ if not self.stages()[0][i]:
861
+ self.build_pillar(s, True, nofn)
862
+ raw, _ = self.stages()
863
+ if raw[0] and raw[1] and not raw[2]:
864
+ if not self.plank_flat():
865
+ self.fix_plank()
866
+ if self.zmin(CAR) > TZ + 0.01 or self.in_keep_out(CAR):
867
+ self.park(CAR)
868
+ self.lay_plank(True, nofn)
869
+ raw, _ = self.stages()
870
+ if raw[2] and not raw[3]:
871
+ self.put_car(True, nofn)
872
+ return fixes
873
+
874
+ def _near_squares(self, o):
875
+ p = self.pos(o)[:2]
876
+ if o == PLANK:
877
+ ax = self.R(PLANK)[:2, 0]
878
+ pts = [p + s * ax * 0.11 for s in (-1, -0.5, 0, 0.5, 1)]
879
+ else:
880
+ pts = [p]
881
+ return any(np.linalg.norm(q - self.square_xy(s)) < 0.06 for q in pts for s in SQUARES)
882
+
883
+ # ------------------------------------------------------------ Sonnet-like naive (style "sonnet")
884
+ # Imitates how Claude Sonnet 5.5 moved in the lh1 pilot (runs/claude/lh1_bridge, 4 attempts, 230 commands):
885
+ # instruction order; for each pillar the free block nearest to its square first; a hover ~12 cm above the object
886
+ # with the gripper turned to the object's yaw, a straight vertical descent, grasp ~1 cm below the top; the carry
887
+ # often goes straight from the grasp to ~12.5 cm above the target (one move_eef: a diagonal climb), otherwise lift
888
+ # first; when the carried object's straight path would run into a built pillar it lifts first and carries with the
889
+ # object's bottom ~4 cm above that pillar; vertical descent, open, lift straight up to ~15 cm; plank: lift to 7 cm,
890
+ # carry at 16 cm; car: lift to 17 cm, carry, place, lift to 25 cm; no final check.
891
+ def _sn_grasp_z(self, o, sn):
892
+ if o == PLANK:
893
+ return self._grasp_z(PLANK, False)
894
+ return self.zmax(o) - sn["top_below"]
895
+
896
+ def _crossing_top(self, a, b, o, drop, hc):
897
+ """top of the highest item that the held object o, carried straight from a to b with its bottom at hc - drop,
898
+ would run into (any footprint point within o's half size + 1 cm of the path), else None"""
899
+ a, b = np.asarray(a[:2], float), np.asarray(b[:2], float)
900
+ d = b - a
901
+ n2 = float(d @ d)
902
+ r = float(self.half(o)[0]) + 0.01
903
+ best = None
904
+ for q in ITEMS:
905
+ if q == o or self.held(q):
906
+ continue
907
+ top = self.zmax(q)
908
+ if top < hc - drop:
909
+ continue
910
+ pts = self.footprint(q)
911
+ t = np.clip((pts - a) @ d / n2, 0.0, 1.0) if n2 > 1e-9 else np.zeros(len(pts))
912
+ dist = float(np.min(np.linalg.norm(pts - (a + t[:, None] * d), axis=1)))
913
+ if dist < r and (best is None or top > best):
914
+ best = top
915
+ return best
916
+
917
+ def sn_pick(self, o, sn, noise=None):
918
+ sk = self.sk
919
+ p = self.pos(o)
920
+ if noise is not None:
921
+ p = p + np.array([noise[0], noise[1], 0.0])
922
+ zg = self._sn_grasp_z(o, sn)
923
+ if o == PLANK:
924
+ yaw = _wrap_h(self.yaw_of(PLANK))
925
+ elif o == CAR and sn["car_style"] == "keep":
926
+ yaw = None # keeps the gripper's current yaw (the pilot's seed 3000: still turned 90 deg from the plank)
927
+ else:
928
+ yaw = _wrap_q(self.yaw_of(o))
929
+ hover = TZ + (sn["car_hover"] if o == CAR else sn["hover"])
930
+ direct = o == CAR and sn["car_style"] == "direct" # (the pilot's seed 3001 went straight down to the car)
931
+ if not direct:
932
+ self._go([p[0], p[1], hover], yaw=yaw)
933
+ self._go([p[0], p[1], zg], yaw=yaw, tol=0.003, max_steps=250 if direct else 120)
934
+ sk.set_gripper(True, steps=15)
935
+ if not sk.holding(o):
936
+ sk.set_gripper(False, steps=15)
937
+ self._go([p[0], p[1], TZ + sn["hover"]])
938
+ return None
939
+ return float(sk.eef_pos()[2] - self.zmin(o))
940
+
941
+ def sn_place(self, o, xy, support_top, drop, yaw, sn, carry=None, lift=None, diag=None):
942
+ sk = self.sk
943
+ zr = support_top + drop + 0.004
944
+ hc = max(TZ + (sn["carry"] if carry is None else carry), zr + 0.03)
945
+ cur = sk.eef_pos()
946
+ diag = sn["diag"] if diag is None else diag
947
+ top = None if o == PLANK else self._crossing_top(cur, xy, o, drop, hc)
948
+ if top is not None: # a built pillar in the way: lift first, carry with the object's bottom above it
949
+ hc = max(hc, top + drop + sn["cross_margin"])
950
+ self._go([cur[0], cur[1], hc])
951
+ self._go([xy[0], xy[1], hc], yaw=yaw)
952
+ elif diag: # one move_eef from the grasp to above the target
953
+ self._go([xy[0], xy[1], hc], yaw=yaw)
954
+ else:
955
+ self._go([cur[0], cur[1], max(cur[2], hc + 0.02)])
956
+ self._go([xy[0], xy[1], hc], yaw=yaw)
957
+ self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120)
958
+ sk.set_gripper(False, steps=15)
959
+ self._go([xy[0], xy[1], TZ + (sn["lift"] if lift is None else lift)])
960
+ sk.hold(5)
961
+
962
+ def sn_build_pillar(self, s, sn, noise_fn):
963
+ failed = {}
964
+ c = self.square_xy(s)
965
+ mid = self.bridge_mid()
966
+ for _ in range(5):
967
+ raw, (pa, pb) = self.stages()
968
+ low, up = (pa, pb)[SQUARES.index(s)]
969
+ if up is not None:
970
+ return True
971
+ other = (pa, pb)[1 - SQUARES.index(s)]
972
+ cand = [b for b in BLOCKS if b != low and b not in other and failed.get(b, 0) < 2]
973
+ if not cand:
974
+ return False
975
+ if sn["alloc"] == "side": # blocks on this square's side of the bridge first
976
+ side = np.sign(c[1] - mid[1])
977
+ same = [b for b in cand if np.sign(self.pos(b)[1] - mid[1]) == side]
978
+ cand = same or cand
979
+ b = min(cand, key=lambda q: (failed.get(q, 0), np.linalg.norm(self.pos(q)[:2] - c)))
980
+ drop = self.sn_pick(b, sn, noise=noise_fn())
981
+ if drop is None:
982
+ failed[b] = failed.get(b, 0) + 1
983
+ continue
984
+ tgt, top = (c, TZ) if low is None else (self.pos(low)[:2], self.zmax(low))
985
+ n = noise_fn()
986
+ # onto the bare square: straight from the grasp (diagonal climb); onto a block: lift first (a diagonal
987
+ # climb from nearby clips the lower block -- the pilot's seed 3000 did that once, then lifted first)
988
+ self.sn_place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, sn,
989
+ diag=None if low is None else False)
990
+ return self.stages()[1][SQUARES.index(s)][1] is not None
991
+
992
+ def sn_lay_plank(self, sn, noise_fn):
993
+ raw, (pa, pb) = self.stages()
994
+ if pa[1] is None or pb[1] is None:
995
+ return False
996
+ drop = self.sn_pick(PLANK, sn, noise=noise_fn())
997
+ if drop is None:
998
+ return False
999
+ cur = self.sk.eef_pos()
1000
+ self._go([cur[0], cur[1], TZ + sn["plank_lift"]])
1001
+ raw, (pa, pb) = self.stages()
1002
+ if pa[1] is None or pb[1] is None:
1003
+ tops, mid = [TZ + 0.11, TZ + 0.11], self.bridge_mid()
1004
+ else:
1005
+ tops = [self.zmax(pa[1]), self.zmax(pb[1])]
1006
+ mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2
1007
+ n = noise_fn()
1008
+ mid = mid + (n if n is not None else 0.0)
1009
+ self.sn_place(PLANK, mid, max(tops), drop, np.pi / 2, sn, carry=sn["plank_carry"], lift=sn["plank_end_lift"],
1010
+ diag=True)
1011
+ return True
1012
+
1013
+ def sn_put_car(self, sn, noise_fn):
1014
+ drop = self.sn_pick(CAR, sn, noise=noise_fn())
1015
+ if drop is None: # (in the pilot, Sonnet stopped here when it saw the bridge come down)
1016
+ return False
1017
+ n = noise_fn()
1018
+ pp = self.pos(PLANK)[:2] + (n if n is not None else 0.0)
1019
+ self.sn_place(CAR, pp, self.zmax(PLANK), drop, None, sn, carry=sn["car_lift"], lift=sn["end_lift"],
1020
+ diag=False)
1021
+ return True
1022
+
1023
+ # ------------------------------------------------------------ execution
1024
+ def execute(self, inst, params):
1025
+ mode = params.get("mode", "naive")
1026
+ careful = mode == "careful"
1027
+ rng = np.random.default_rng(params.get("noise_seed", 0))
1028
+ sig = float(params.get("noise", 0.0))
1029
+ noise_fn = (lambda: rng.uniform(-sig, sig, 2)) if sig > 0 else (lambda: None)
1030
+ z_t = params.get("z_t")
1031
+ self.naive_lift = float(params.get("lift", NAIVE_LIFT))
1032
+ style = params.get("style", "sonnet")
1033
+ if not careful and style == "sonnet":
1034
+ sn = dict(SN)
1035
+ sn.update(params.get("sn", {}))
1036
+ if sn["car_style"] is None:
1037
+ sn["car_style"] = CAR_STYLES[int(inst["seed"]) % 3]
1038
+ for s in SQUARES:
1039
+ self.sn_build_pillar(s, sn, noise_fn)
1040
+ self.sn_lay_plank(sn, noise_fn)
1041
+ self.sn_put_car(sn, noise_fn)
1042
+ else: # careful, or the v1 naive ("legs": vertical / horizontal legs at 8 cm; "diag")
1043
+ self.naive_style = style if style in ("legs", "diag") else NAIVE_STYLE
1044
+ if careful:
1045
+ self.clear_site()
1046
+ for s in SQUARES:
1047
+ self.build_pillar(s, careful, noise_fn, z_t=z_t, order=params.get("order", "target"))
1048
+ self.lay_plank(careful, noise_fn, z_t=z_t)
1049
+ self.put_car(careful, noise_fn, z_t=z_t)
1050
+ if params.get("check"):
1051
+ self.repair()
1052
+ cur = self.sk.eef_pos()
1053
+ if cur[2] < TZ + 0.20:
1054
+ self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.15)
1055
+
1056
+ def default_params(self, inst):
1057
+ return dict(mode="naive", style="sonnet", check=False)
1058
+
1059
+ def oracle_params(self, inst):
1060
+ return dict(mode="careful", check=True)
1061
+
1062
+ def adapt_params(self, inst, history):
1063
+ return dict(mode="careful", check=True)
1064
+
1065
+ def blind_params(self, inst, attempt, rng):
1066
+ sn = dict(hover=float(rng.uniform(0.10, 0.14)), carry=float(rng.uniform(0.11, 0.15)),
1067
+ lift=float(rng.uniform(0.13, 0.20)), diag=bool(rng.random() < 0.5),
1068
+ car_style=CAR_STYLES[int(rng.integers(3))], alloc="side" if rng.random() < 0.5 else "greedy")
1069
+ return dict(mode="naive", style="sonnet", check=False, sn=sn, noise=0.004, noise_seed=int(rng.integers(1 << 30)))
1070
+
1071
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
1072
+ """kinds: oracle, naive (Sonnet-like, car approach style by seed), adaptive, blind; for comparison naive_v1 (the
1073
+ v1 naive: vertical / horizontal legs at 8 cm) and naive_hover / naive_keep / naive_direct (Sonnet-like with
1074
+ one fixed car approach style)"""
1075
+ k = k or self.max_attempts
1076
+ rng = np.random.default_rng(seed)
1077
+ history = []
1078
+ for a in range(k):
1079
+ self.reset_instance(inst)
1080
+ if kind == "oracle":
1081
+ params = self.oracle_params(inst)
1082
+ elif kind == "naive":
1083
+ params = self.default_params(inst)
1084
+ elif kind == "naive_v1":
1085
+ params = dict(mode="naive", style="legs", check=False)
1086
+ elif kind.startswith("naive_") and kind[6:] in CAR_STYLES: # naive_hover / naive_keep / naive_direct
1087
+ params = dict(mode="naive", style="sonnet", check=False, sn=dict(car_style=kind[6:]))
1088
+ elif kind == "adaptive":
1089
+ params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
1090
+ elif kind == "blind":
1091
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
1092
+ else:
1093
+ raise ValueError(kind)
1094
+ self.execute(inst, params)
1095
+ out = self.outcome(inst)
1096
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
1097
+ if on_attempt:
1098
+ on_attempt(a, params, out)
1099
+ if out["success"] or kind == "oracle" or kind.startswith("naive"):
1100
+ break
1101
+ return history
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_nudge_row.py ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH lh_nudge_row v2 (2026-10-14): stand four small cups, one by one, on the four coloured mats of their colours; the
2
+ mats lie in two rows of two, and in 7 of 10 instances the two mats of a row touch. Letting go of a cup with the fingers
3
+ opening towards the cup already standing on the next mat pushes that cup 1.5-3.4 cm sideways, half off its mat -- it
4
+ stays upright, so the damage is small but visible (a near miss that has to be noticed and undone before finishing).
5
+
6
+ Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically undo an
7
+ earlier one; the agent has to look back at all cups before finishing (within an attempt) or learn to let go without
8
+ pushing (across attempts).
9
+
10
+ v1 -> v2 (Sonnet 5.5 pilot np_lh_nudge_row, seeds 3000-3002, k=3, measured): v1 used round rings with a 0.8 cm
11
+ tolerance. Sonnet put the cups 0.8-2.2 cm too far forward (+x, away from the robot) in almost every attempt and could not
12
+ see it (the oblique agentview camera looks along x; a tall cup hides the ring behind it), so 5 of 7 attempts failed
13
+ without any nudge (one was a calibration attempt), and the one clear nudge (s3000) left the cup 0.83 cm off --
14
+ invisible. Its left-right errors were <= 0.7 cm, its releases in attempt 1 almost all at wrist yaw ~0 (fingers opening
15
+ left-right), and it learned yaw 45 for the last cup after the nudge. v2 therefore (1) replaces the rings by mats 9 cm long (forward-back, tolerance 3 cm: a 2 cm forward bias
16
+ passes) and 4.6 cm wide (left-right, tolerance 1.3 cm), (2) puts the two mats of a row edge to edge so that a yaw-0
17
+ release pushes the neighbour sideways, where the camera resolves it, off its mat onto the table, and (3) uses slimmer cups
18
+ (2 x 5 cm instead of 4 x 6 cm): the open finger reaches farther past them, so the push is 1.5-3.4 cm instead of 0.3-2.3.
19
+ Code and results of v1: lh_nudge_row.py.bak-20261014-v1, results/_old/lh_nudge_row_v1/.
20
+
21
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
22
+ * four coloured mats (dark red, blue, green, ochre; flat, visual only), each 9.0 cm (forward-back) x 4.6 cm, in two rows
23
+ (far and near, 1.5 cm apart); block centre 53-59 cm in front of the robot base. Tight block (14 of every 20
24
+ consecutive seeds): the two mats of a row touch. Spaced block (6 of 20): they are 4-5 cm apart and no open finger
25
+ reaches the neighbour (the benign instances);
26
+ * four slim cups of the bright same colours (2.0 cm wide, 5.0 cm tall, open top, glazed base: friction 0.08-0.12,
27
+ 20-32 g), standing in a line 17.5-19 cm from the block on the robot's side, or on its left or right side, in random
28
+ order and 9-10 cm apart.
29
+
30
+ Risk factor: the block's spacing (visible, instance level); there is no hidden physical variable (v1 measured that a
31
+ rubber-footed cup gets tipped over by a re-grasp next to it, and a fallen cup cannot be stood up again).
32
+
33
+ Disturbance (physics, no teleport): the gripper opens to 7.9 cm, i.e. each finger moves 3 cm out from a 2 cm cup; the
34
+ outer face of an open finger reaches 5.4 cm (tip) to 6.6 cm (upper part) from the grasp point; in a tight block the
35
+ neighbour's wall is 3.6 cm away (+- the placement errors). Measured: letting go with the fingers along the row (wrist yaw
36
+ 0) pushes the neighbour 1.2-3.2 cm sideways, upright (18/18 trials: base friction 0.08 / 0.12 x grasp 0.8-2 cm below the
37
+ rim x put down 0.8 cm towards / on target / 0.8 cm away from it, each followed by three re-grasps); re-grasping a placed cup with the fingers towards the neighbour pushes it about 0.3 cm more. With
38
+ friction 0.18 or with 2.6 cm cups whose closed finger already presses the neighbour's rim, slim cups tipped over (4/18
39
+ and 6/18) -- hence the low friction and the 2 cm cups. A careful agent avoids the push by letting go with the fingers
40
+ opening forward-back (wrist yaw 90: the mats of the other row are 10.5 cm away) or diagonally, and repairs it by
41
+ re-centring the pushed cup (lifted 10 cm, carried back, let go the same careful way).
42
+
43
+ Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each cup stands upright
44
+ (tilt <= 10 deg) on the table, not held, with its whole base on its own mat: centre within 3.0 cm (forward-back) and
45
+ 1.3 cm (left-right) of the mat's centre. Success = all four at the end, gripper open and not touching any cup, scene
46
+ static. The monitor logs achieved / lost / restored per cup, cup_nudged (lost while not held, with displacement and
47
+ cause), cup_bumped (pushed by the robot but still on its mat) and cup_restored, for the server log only (F1 gives the
48
+ agent only success / failure).
49
+
50
+ Protocol: cross (reset to the same instance before every attempt), k = 3.
51
+ """
52
+ import numpy as np
53
+
54
+ from .. import envs
55
+ from ..bddl import write_bddl
56
+ from ..objects import _fmt, _wrap, register_generated
57
+ from ..skills import Skills
58
+ from ..task_base import LFFTask, register_task
59
+
60
+ TZ = envs.TABLE_Z
61
+ COLOURS = ["red", "blue", "green", "yellow"]
62
+ CUPS = [f"cup_{c}_1" for c in COLOURS]
63
+ MATS = [f"mat_{c}_1" for c in COLOURS]
64
+ RGBA = {"red": (0.82, 0.16, 0.13, 1.0), "blue": (0.16, 0.36, 0.82, 1.0), "green": (0.16, 0.62, 0.26, 1.0),
65
+ "yellow": (0.92, 0.76, 0.12, 1.0)}
66
+ MAT_RGBA = {"red": (0.55, 0.13, 0.12, 1.0), "blue": (0.12, 0.22, 0.52, 1.0), "green": (0.10, 0.38, 0.16, 1.0),
67
+ "yellow": (0.62, 0.50, 0.08, 1.0)} # dark shades: crisp edges on the light table, bright cups stand out
68
+ INSIDE_RGBA = (0.93, 0.92, 0.88, 1.0) # glazed inside of the cups (seen from above)
69
+
70
+ # cup geometry (fixed; only mass and base friction change per instance, so no runtime geom edits / BVH refits)
71
+ CUP_R, CUP_H = 0.010, 0.050 # slim cups (2 x 5 cm): the open fingers reach far past them (v1: 4 x 6 cm)
72
+ COM_Z = -0.006 # centre of mass below the cup's mid-height (heavier base)
73
+ WALL_T, BASE_T = 0.0025, 0.003
74
+ NSEG = 12
75
+ CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"'
76
+ WALL_MU = 0.8
77
+ BASE_MU = (0.08, 0.12) # glazed base: a pushed cup slides; at 0.18 a slim cup pushed high up tipped (measured)
78
+ MASS = (0.020, 0.032)
79
+
80
+ # mats (targets) and block
81
+ TOL_X = 0.030 # forward-back: the cup centre may be 3 cm from the mat centre (mat 9 cm long) -- Sonnet's measured
82
+ # placement bias is 1-2.5 cm forward (v1 pilot), invisible to it in the oblique camera
83
+ TOL_Y = 0.013 # left-right: 1.3 cm (mat 4.6 cm wide); a finger-opening push (1.2-3.2 cm, measured) fails it
84
+ MAT_L, MAT_W = 2 * (CUP_R + TOL_X), 2 * (CUP_R + TOL_Y) # base completely on the mat <=> centre within the tolerances
85
+ ROW_GAP = 0.015 # gap between the far row and the near row of mats (x)
86
+ SPACED_GAP = (0.040, 0.050) # spaced block: gap between the two mats of a row (y); an open finger cannot reach
87
+ P_TIGHT = 0.70 # 14 of every 20 consecutive seeds: the two mats of a row touch
88
+ BLOCK_X = (-0.13, -0.07) # block centre in world x (53-59 cm in front of the robot base)
89
+ SUP_D = (0.175, 0.19) # supply line distance from the block centre
90
+ SUP_GAP = (0.090, 0.100)
91
+
92
+ # predicates / monitor
93
+ TILT_OK = np.radians(10.0)
94
+ ON_TABLE = 0.004
95
+ HYST = 0.002
96
+ DEBOUNCE = 10 # control steps (0.5 s)
97
+ BUMP_MIN = 0.003
98
+
99
+ # scripted motion (heights of the grasp point above the table)
100
+ Z_CARRY = 0.20 # Sonnet: lifts to ~20 cm before moving (lh2/lh3 pilots)
101
+ Z_LIFT = 0.15 # re-placing a cup that is already down: lift it this high (its base 11 cm up) before moving it
102
+ NAIVE_BIAS = (0.008, 0.022) # Sonnet's systematic forward placement error (v1 pilot: +0.8 ... +2.2 cm, per instance)
103
+ NAIVE_RAND = 0.006 # +- random placement error per axis (v1 pilot: left-right errors <= 0.7 cm)
104
+ NAIVE_FIX_RAND = 0.003 # after re-placing its own cup
105
+ FINGER_IN, FINGER_OUT, FINGER_HALF = 0.039, 0.066, 0.013 # open finger footprint (m from the grasp point / half width)
106
+
107
+
108
+ def _wrap_h(a):
109
+ """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)"""
110
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
111
+
112
+
113
+ def cup_xml(name, rgba):
114
+ """open-top cup: 12 wall boxes (1 mm above the bottom) and an octagonal base of two square boxes (box-box contacts:
115
+ a light cylinder on the table creeps by itself in MuJoCo, measured 1.6 cm / 5 s). Visual: a smooth cylinder with the
116
+ glazed inside at the top. The compiled inertial is replaced per instance (mass), the base friction too."""
117
+ r, h = CUP_R, CUP_H
118
+ g = [f' <inertial pos="0 0 {COM_Z:.4f}" mass="0.055" diaginertia="2.6e-5 2.6e-5 1.6e-5" />']
119
+ s = r * np.sin(np.pi / NSEG) + 0.0006
120
+ rc = r * np.cos(np.pi / NSEG) - WALL_T / 2
121
+ for k in range(NSEG):
122
+ a = 2 * np.pi * k / NSEG
123
+ q = [np.cos(a / 2), 0, 0, np.sin(a / 2)]
124
+ g.append(f' <geom name="{name}_w{k}" type="box" size="{WALL_T / 2:.5f} {s:.5f} {(h - 0.001) / 2:.5f}" '
125
+ f'pos="{rc * np.cos(a):.5f} {rc * np.sin(a):.5f} 0.0005" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
126
+ f'friction="{WALL_MU} 0.005 0.0001" {CONTACT} group="0" />')
127
+ a0 = r * 0.70
128
+ for k, ang in enumerate((0.0, np.pi / 4)):
129
+ q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)]
130
+ g.append(f' <geom name="{name}_b{k}" type="box" size="{a0:.5f} {a0:.5f} {BASE_T / 2:.5f}" '
131
+ f'pos="0 0 {-h / 2 + BASE_T / 2:.5f}" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
132
+ f'friction="0.5 0.005 0.0001" {CONTACT} group="0" />')
133
+ g.append(f' <geom type="cylinder" size="{r:.5f} {h / 2:.5f}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" '
134
+ f'group="1" />')
135
+ g.append(f' <geom type="cylinder" size="{r - WALL_T:.5f} 0.0004" pos="0 0 {h / 2 - 0.0003:.5f}" '
136
+ f'rgba="{_fmt(INSIDE_RGBA)}" contype="0" conaffinity="0" group="1" />')
137
+ return _wrap(name, "\n".join(g), h / 2, r)
138
+
139
+
140
+ def mat_xml(name, rgba):
141
+ """flat coloured mat (visual only), long side along body x"""
142
+ g = (f' <geom type="box" size="{MAT_L / 2:.5f} {MAT_W / 2:.5f} 0.0004" rgba="{_fmt(rgba)}" contype="0" '
143
+ f'conaffinity="0" group="1" />')
144
+ return _wrap(name, g, 0.0004, float(np.hypot(MAT_L, MAT_W) / 2))
145
+
146
+
147
+ def _fb(d):
148
+ return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}"
149
+
150
+
151
+ def _lr(d):
152
+ return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}"
153
+
154
+
155
+ class NudgeSkills(Skills):
156
+ """Skills that feed the task's per-step monitor."""
157
+
158
+ def __init__(self, env, task, recorder=None):
159
+ super().__init__(env, recorder=recorder)
160
+ self.task = task
161
+
162
+ def _act(self, dpos, drot, grip):
163
+ super()._act(dpos, drot, grip)
164
+ self.task.monitor_step()
165
+
166
+
167
+ @register_task
168
+ class NudgeRow(LFFTask):
169
+ name = "lh_nudge_row"
170
+ level = "L2"
171
+ category = "state_restoration"
172
+ capabilities = ("Perceive", "Plan", "Reason", "Restore")
173
+ protocol = "cross"
174
+ max_attempts = 3
175
+ # careful: ~10 commands per cup (40) + re-placing an imprecise cup or two (~15) + re-centring two pushed cups (~20)
176
+ # + looking / small corrections (~20), with some margin
177
+ agent_max_steps = 110
178
+ instruction = ("Stand each of the four small cups on the mat of the same colour. The four coloured mats lie on the "
179
+ "table in two rows of two. At the end every cup must stand upright with its whole base on its own "
180
+ "mat (not touching another mat or the table around it), and the gripper must be open and clear of "
181
+ "the cups.")
182
+ instruction_indirect = ("Set each little cup down on the coloured patch that matches it; the four patches form two "
183
+ "rows of two. When you are done every cup has to stand upright with its bottom completely "
184
+ "on its own patch, and the gripper must be open and away from the cups.")
185
+ agent_object_names = ["small cups (red, blue, green, yellow)",
186
+ "coloured mats (red, blue, green, yellow) in two rows of two"]
187
+
188
+ # ------------------------------------------------------------ scene
189
+ def make_bddl(self):
190
+ objs, fx = [], []
191
+ for i, (c, cup) in enumerate(zip(COLOURS, CUPS)):
192
+ cat = register_generated(f"LffLhnCup{c.capitalize()}", cup_xml(f"lff_lhn_cup_{c}", RGBA[c]))
193
+ objs.append((cup, cat, f"cup{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31)))
194
+ for i, (c, mat) in enumerate(zip(COLOURS, MATS)):
195
+ cat = register_generated(f"LffLhnMat{c.capitalize()}", mat_xml(f"lff_lhn_mat_{c}", MAT_RGBA[c]), free=False)
196
+ fx.append((mat, cat, f"mat{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30)))
197
+ return write_bddl(self.name, "Stand each cup on the mat of its colour", objs, fx)
198
+
199
+ def __init__(self, cam_res=None):
200
+ super().__init__(cam_res)
201
+ m = self.env.sim.model
202
+ self.mat_bid = {k: m.body_name2id(self.env.fixtures_dict[k].root_body) for k in MATS}
203
+ self.cgeoms = {c: envs.obj_geom_ids(self.env, c) for c in CUPS}
204
+ self.cbody = {c: int(m.geom_bodyid[self.cgeoms[c][0]]) for c in CUPS}
205
+ self.base_geoms = {c: [g for g in self.cgeoms[c] if (m.geom_id2name(g) or "").split("_")[-1] in ("b0", "b1")]
206
+ for c in CUPS}
207
+ self.finger_geoms, self.hand_geoms = [], []
208
+ for g in envs.robot_geom_ids(self.env):
209
+ n = m.geom_id2name(g) or ""
210
+ (self.finger_geoms if "finger" in n else self.hand_geoms).append(g)
211
+ # per-geom lookup tables for the substep contact check: cup index (-1 none), robot part (1 finger, 2 hand)
212
+ self.owner = np.full(m.ngeom, -1, int)
213
+ for i, c in enumerate(CUPS):
214
+ self.owner[self.cgeoms[c]] = i
215
+ self.part = np.zeros(m.ngeom, int)
216
+ self.part[self.finger_geoms] = 1
217
+ self.part[self.hand_geoms] = 2
218
+ self._sub_rob, self._sub_obj = {}, {}
219
+ # contacts are collected after every MuJoCo substep: an opening finger can flick a light cup within one control
220
+ # step (same technique as lh_fence; wrappers chain)
221
+ sim = self.env.sim
222
+ if not getattr(sim, "_lhn_wrapped", False):
223
+ orig = sim.step
224
+
225
+ def step(*a, **k):
226
+ orig(*a, **k)
227
+ t = getattr(sim, "_lhn_task", None)
228
+ if t is not None and t.mon is not None:
229
+ t._substep()
230
+ sim.step = step
231
+ sim._lhn_wrapped = True
232
+ sim._lhn_task = self
233
+ self.inst = None
234
+ self.mon = None
235
+ self.sk = None
236
+
237
+ def _substep(self):
238
+ d = self.env.sim.data
239
+ n = d.ncon
240
+ if not n:
241
+ return
242
+ g1 = np.asarray(d.contact.geom1)[:n]
243
+ g2 = np.asarray(d.contact.geom2)[:n]
244
+ o1, o2 = self.owner[g1], self.owner[g2]
245
+ for a, b, pa, pb in zip(g1, g2, o1, o2):
246
+ if pa < 0 and pb < 0:
247
+ continue
248
+ if pa >= 0 and pb >= 0:
249
+ if pa != pb:
250
+ self._sub_obj[int(pa)] = int(pb)
251
+ self._sub_obj[int(pb)] = int(pa)
252
+ continue
253
+ p, o = (pa, b) if pa >= 0 else (pb, a)
254
+ part = self.part[o]
255
+ if part:
256
+ prev = self._sub_rob.get(int(p), 0)
257
+ self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2
258
+
259
+ # ------------------------------------------------------------ instances
260
+ def sample_instance(self, seed):
261
+ rng = np.random.default_rng(seed)
262
+ tight = bool((int(seed) * 7) % 20 < round(20 * P_TIGHT)) # balanced: 14 of every 20 consecutive seeds
263
+ gap_y = 0.0 if tight else float(rng.uniform(*SPACED_GAP))
264
+ py = MAT_W + gap_y # mat centre to mat centre within a row (left-right)
265
+ px = MAT_L + ROW_GAP # far row to near row (forward-back)
266
+ bx = float(rng.uniform(*BLOCK_X))
267
+ side = str(rng.choice(["front", "left", "right"]))
268
+ by = float(rng.uniform(-0.04, 0.04))
269
+ if side == "left":
270
+ by = float(rng.uniform(-0.08, -0.04))
271
+ elif side == "right":
272
+ by = float(rng.uniform(0.04, 0.08))
273
+ # mat positions: block slots (far-left, far-right, near-left, near-right), colours permuted
274
+ slots = {"far_left": [bx + px / 2, by + py / 2], "far_right": [bx + px / 2, by - py / 2],
275
+ "near_left": [bx - px / 2, by + py / 2], "near_right": [bx - px / 2, by - py / 2]}
276
+ names = list(slots)
277
+ perm = rng.permutation(4)
278
+ mats = {COLOURS[i]: slots[names[perm[i]]] for i in range(4)}
279
+ slot_of = {COLOURS[i]: names[perm[i]] for i in range(4)}
280
+ # supply line
281
+ d = float(rng.uniform(*SUP_D))
282
+ gap = float(rng.uniform(*SUP_GAP))
283
+ offs = (np.arange(4) - 1.5) * gap + float(rng.uniform(-0.02, 0.02))
284
+ if side == "front":
285
+ sup = [[bx - d + float(rng.uniform(-0.008, 0.008)), by + o] for o in offs]
286
+ else:
287
+ sgn = 1.0 if side == "left" else -1.0
288
+ sup = [[bx + o, by + sgn * (d - 0.02) + float(rng.uniform(-0.008, 0.008))] for o in offs]
289
+ order = rng.permutation(4)
290
+ start = {COLOURS[i]: [float(v) for v in sup[order[i]]] for i in range(4)}
291
+ mu = {c: float(rng.uniform(*BASE_MU)) for c in COLOURS}
292
+ mass = {c: float(rng.uniform(*MASS)) for c in COLOURS}
293
+ yaw0 = {c: float(rng.uniform(-np.pi, np.pi)) for c in COLOURS}
294
+ return dict(seed=int(seed), pitch_y=py, pitch_x=px, gap_y=gap_y, block=[bx, by], supply_side=side,
295
+ supply_d=d, supply_gap=gap, mats=mats, slot_of=slot_of, start=start, mu=mu, mass=mass, yaw0=yaw0,
296
+ tight=tight, block_kind="tight" if tight else "spaced",
297
+ naive_bias_x=float(rng.uniform(*NAIVE_BIAS)))
298
+
299
+ def apply_instance(self, inst):
300
+ self.inst = inst
301
+ m = self.env.sim.model
302
+ for c, cup in zip(COLOURS, CUPS):
303
+ b = self.cbody[cup]
304
+ M = inst["mass"][c]
305
+ m.body_mass[b] = M
306
+ # thin-walled cup (wall + base), approximately
307
+ m.body_inertia[b] = [M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12),
308
+ M * CUP_R ** 2 * 0.8]
309
+ for g in self.base_geoms[cup]:
310
+ m.geom_friction[g] = [inst["mu"][c], 0.005, 0.0001]
311
+ m.geom_priority[g] = 2
312
+ for c, mat in zip(COLOURS, MATS):
313
+ x, y = inst["mats"][c]
314
+ m.body_pos[self.mat_bid[mat]] = [x, y, TZ + 0.0005]
315
+ m.body_quat[self.mat_bid[mat]] = [1.0, 0.0, 0.0, 0.0]
316
+ self.env.sim.forward()
317
+ for c, cup in zip(COLOURS, CUPS):
318
+ envs.place_upright(self.env, cup, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
319
+
320
+ def reset_instance(self, inst, recorder=None):
321
+ self.mon = None
322
+ self.env.reset()
323
+ self.apply_instance(inst)
324
+ self.env.sim.forward()
325
+ envs.settle(self.env, 15)
326
+ self.sk = NudgeSkills(self.env, self, recorder=recorder)
327
+ self._sub_rob, self._sub_obj = {}, {}
328
+ n = len(CUPS)
329
+ self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
330
+ lost_cause=[None] * n,
331
+ anchor=[None] * n, last_robot=[None] * n, last_obj=[None] * n, nudged=[False] * n,
332
+ bump_ref=[None] * n, bump_step=[-1000] * n, n_steps=0)
333
+ return self.sk
334
+
335
+ # ------------------------------------------------------------ geometry / predicates
336
+ def pos(self, cup):
337
+ return envs.obj_pos(self.env, cup)
338
+
339
+ def tilt(self, cup):
340
+ return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, cup), -1.0, 1.0)))
341
+
342
+ def held(self, cup):
343
+ return self.sk is not None and self.sk.holding(cup)
344
+
345
+ def mat_xy(self, i):
346
+ return np.asarray(self.inst["mats"][COLOURS[i]], float)
347
+
348
+ def offset(self, i):
349
+ return self.pos(CUPS[i])[:2] - self.mat_xy(i)
350
+
351
+ @staticmethod
352
+ def within(off, extra=0.0):
353
+ """mat-frame offset (x forward-back, y left-right) inside the tolerances = the cup's whole base on its mat"""
354
+ return abs(float(off[0])) <= TOL_X + extra and abs(float(off[1])) <= TOL_Y + extra
355
+
356
+ def on_mat(self, i, extra=0.0):
357
+ cup = CUPS[i]
358
+ if self.tilt(cup) > TILT_OK + (np.radians(2.0) if extra else 0.0):
359
+ return False
360
+ if not self.within(self.offset(i), extra):
361
+ return False
362
+ if envs.obj_min_z(self.env, cup) > TZ + ON_TABLE:
363
+ return False
364
+ return not self.held(cup)
365
+
366
+ def stages(self):
367
+ return [self.on_mat(i) for i in range(len(CUPS))]
368
+
369
+ # ------------------------------------------------------------ monitor
370
+ def monitor_step(self):
371
+ mon = self.mon
372
+ if mon is None or self.sk is None:
373
+ return
374
+ mon["n_steps"] += 1
375
+ t = self.sk.n_steps
376
+ rob = dict(self._sub_rob)
377
+ obj = dict(self._sub_obj)
378
+ self._sub_rob, self._sub_obj = {}, {}
379
+ gstate = "open" if self.sk.grip < 0 else "closed"
380
+ for i, part in rob.items():
381
+ if not self.held(CUPS[i]):
382
+ mon["last_robot"][i] = ["finger" if part == 1 else "hand", int(t), gstate]
383
+ for i, j in obj.items():
384
+ mon["last_obj"][i] = [COLOURS[j] + (" (held)" if self.held(CUPS[j]) else ""), int(t)]
385
+ if mon["n_steps"] % 2:
386
+ return
387
+ for i in range(len(CUPS)):
388
+ cup = CUPS[i]
389
+ raw = self.on_mat(i, HYST if mon["state"][i] else 0.0)
390
+ # bumps inside the tolerance
391
+ if mon["state"][i] and raw and not self.held(cup):
392
+ lr = mon["last_robot"][i]
393
+ if lr is not None and t - lr[1] <= 2 and mon["bump_ref"][i] is None:
394
+ mon["bump_ref"][i] = [self.pos(cup)[:2].tolist(), int(t), 0.0]
395
+ ref = mon["bump_ref"][i]
396
+ if ref is not None:
397
+ ref[2] = max(ref[2], float(np.degrees(self.tilt(cup))))
398
+ if t - ref[1] > 40:
399
+ dpos = float(np.linalg.norm(self.pos(cup)[:2] - np.asarray(mon["anchor"][i] or ref[0])))
400
+ if (dpos >= BUMP_MIN or ref[2] >= 2.0) and t - mon["bump_step"][i] > 60:
401
+ mon["events"].append(dict(cup=COLOURS[i], event="cup_bumped", step=int(ref[1]),
402
+ moved_cm=round(100 * dpos, 2), max_tilt_deg=round(ref[2], 1),
403
+ cause=self._cause(i, ref[1] + 1)))
404
+ mon["bump_step"][i] = int(t)
405
+ mon["bump_ref"][i] = None
406
+ if raw == mon["state"][i]:
407
+ mon["raw_since"][i] = 0
408
+ continue
409
+ mon["raw_since"][i] += 2
410
+ if mon["raw_since"][i] < DEBOUNCE:
411
+ continue
412
+ mon["state"][i] = raw
413
+ mon["raw_since"][i] = 0
414
+ t0 = int(t - DEBOUNCE + 1)
415
+ if raw:
416
+ restored = mon["lost"][i]
417
+ e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0)
418
+ if restored:
419
+ e["after"] = mon["lost_cause"][i] # picked_up = the agent re-adjusted a cup it had placed itself
420
+ mon["events"].append(e)
421
+ if restored and mon["nudged"][i]:
422
+ mon["events"].append(dict(cup=COLOURS[i], event="cup_restored", step=t0))
423
+ mon["nudged"][i] = False
424
+ mon["ever"][i] = True
425
+ mon["anchor"][i] = self.pos(cup)[:2].tolist()
426
+ mon["bump_ref"][i] = None
427
+ else:
428
+ mon["lost"][i] = True
429
+ cause = self._cause(i, t)
430
+ mon["lost_cause"][i] = cause
431
+ mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause))
432
+ if cause != "picked_up":
433
+ a = mon["anchor"][i]
434
+ d = self.pos(cup)[:2] - np.asarray(a if a is not None else self.mat_xy(i))
435
+ off = self.offset(i)
436
+ mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t0, cause=cause,
437
+ moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)],
438
+ offset_cm=round(100 * float(np.linalg.norm(off)), 2),
439
+ tilt_deg=round(float(np.degrees(self.tilt(cup))), 1)))
440
+ mon["nudged"][i] = True
441
+
442
+ def _cause(self, i, t, window=60):
443
+ if self.held(CUPS[i]):
444
+ return "picked_up"
445
+ lr, lo = self.mon["last_robot"][i], self.mon["last_obj"][i]
446
+ cands = []
447
+ if lr is not None and t - lr[1] <= window:
448
+ cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else "")))
449
+ if lo is not None and t - lo[1] <= window:
450
+ cands.append((lo[1] - 30, "cup:" + lo[0])) # prefer the robot when both touched it recently
451
+ return max(cands)[1] if cands else "other"
452
+
453
+ def _finalize_monitor(self, raw):
454
+ """close the event log at finish: a stage the debounced monitor still holds (it uses a 2 mm hysteresis) but the
455
+ final judge does not is logged as lost now (final=True), and vice versa"""
456
+ mon = self.mon
457
+ if mon is None:
458
+ return
459
+ t = int(self.sk.n_steps)
460
+ for i in range(len(CUPS)):
461
+ if raw[i] == mon["state"][i]:
462
+ continue
463
+ mon["state"][i] = raw[i]
464
+ if raw[i]:
465
+ restored = mon["lost"][i]
466
+ e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True)
467
+ if restored:
468
+ e["after"] = mon["lost_cause"][i]
469
+ mon["events"].append(e)
470
+ mon["ever"][i] = True
471
+ continue
472
+ mon["lost"][i] = True
473
+ cause = self._cause(i, t, window=10 ** 6) # the last contact may be long ago (slow creep across the line)
474
+ mon["lost_cause"][i] = cause
475
+ mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True))
476
+ if cause != "picked_up":
477
+ a = mon["anchor"][i]
478
+ d = self.pos(CUPS[i])[:2] - np.asarray(a if a is not None else self.mat_xy(i))
479
+ mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t, cause=cause, final=True,
480
+ moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)],
481
+ offset_cm=round(100 * float(np.linalg.norm(self.offset(i))), 2),
482
+ tilt_deg=round(float(np.degrees(self.tilt(CUPS[i]))), 1)))
483
+ mon["nudged"][i] = True
484
+
485
+ # ------------------------------------------------------------ outcome
486
+ def _touching(self):
487
+ d = self.env.sim.data
488
+ rob = set(self.finger_geoms) | set(self.hand_geoms)
489
+ for j in range(d.ncon):
490
+ c = d.contact[j]
491
+ if (self.owner[c.geom1] >= 0 and c.geom2 in rob) or (self.owner[c.geom2] >= 0 and c.geom1 in rob):
492
+ return True
493
+ return False
494
+
495
+ def outcome(self, inst):
496
+ sk = self.sk
497
+ sk.hold(10)
498
+ p0 = {c: self.pos(c) for c in CUPS}
499
+ touching = False
500
+ for _ in range(20):
501
+ sk.hold(1)
502
+ touching = touching or self._touching()
503
+ moved = max(float(np.linalg.norm(self.pos(c) - p0[c])) for c in CUPS)
504
+ static = moved < 0.003
505
+ raw = self.stages()
506
+ self._finalize_monitor(raw)
507
+ held = [COLOURS[i] for i, c in enumerate(CUPS) if self.held(c)]
508
+ mon = self.mon
509
+ ev = list(mon["events"]) if mon else []
510
+ n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
511
+ n_lost = sum(e.get("event") == "lost" for e in ev)
512
+ n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
513
+ nudges = [e for e in ev if e.get("event") == "cup_nudged"]
514
+ bumps = [e for e in ev if e.get("event") == "cup_bumped"]
515
+ success = bool(all(raw) and static and not held and not touching)
516
+ ever = mon["ever"] if mon else [False] * len(CUPS)
517
+ tilted = [i for i in range(len(CUPS)) if self.tilt(CUPS[i]) > TILT_OK]
518
+ lost_final = [i for i in range(len(CUPS)) if not raw[i] and ever[i]]
519
+ never = [i for i in range(len(CUPS)) if not raw[i] and not ever[i]]
520
+ if success:
521
+ failure = "none"
522
+ elif held:
523
+ failure = "held"
524
+ elif touching:
525
+ failure = "touching"
526
+ elif tilted:
527
+ failure = "tipped"
528
+ elif lost_final:
529
+ failure = "nudged_out" if any(mon["nudged"][i] for i in lost_final) else "regressed"
530
+ elif never:
531
+ failure = "not_on_mat"
532
+ else:
533
+ failure = "not_static"
534
+ parts = []
535
+ if success:
536
+ parts.append("Every cup stands upright on the mat of its colour.")
537
+ for i in range(len(CUPS)):
538
+ if raw[i]:
539
+ continue
540
+ c, cup = COLOURS[i], CUPS[i]
541
+ if c in held:
542
+ parts.append(f"The {c} cup is still held by the gripper.")
543
+ continue
544
+ off = self.offset(i)
545
+ tl = np.degrees(self.tilt(cup))
546
+ where = f"{_fb(off[0])} and {_lr(off[1])} of the {c} mat's centre"
547
+ if tl > np.degrees(TILT_OK):
548
+ txt = (f"The {c} cup has fallen over" if tl > 45 else f"The {c} cup leans {tl:.0f} degrees") + f", {where}."
549
+ elif float(np.linalg.norm(off)) > 0.08:
550
+ txt = f"The {c} cup is not on the {c} mat (its centre is {100 * float(np.linalg.norm(off)):.0f} cm away)."
551
+ else:
552
+ over = []
553
+ if abs(off[1]) > TOL_Y:
554
+ over.append(f"{100 * (abs(off[1]) - TOL_Y):.1f} cm over the mat's {'left' if off[1] > 0 else 'right'} "
555
+ f"edge")
556
+ if abs(off[0]) > TOL_X:
557
+ over.append(f"{100 * (abs(off[0]) - TOL_X):.1f} cm over its {'far' if off[0] > 0 else 'near'} end")
558
+ txt = f"The {c} cup stands {where}; its base sticks out " + " and ".join(over) + "."
559
+ if ever[i]:
560
+ lost = [e for e in ev if e.get("stage") == c and e.get("event") == "lost"]
561
+ why = lost[-1].get("cause", "other") if lost else "other"
562
+ txt += {"robot_finger_opening": " It had stood on its mat; a finger pushed it when the gripper opened "
563
+ "next to it.",
564
+ "robot_finger": " It had stood on its mat; a finger pushed it.",
565
+ "robot_hand": " It had stood on its mat; the hand pushed it.",
566
+ }.get(why, " It had stood on its mat earlier and was pushed by another cup."
567
+ if why.startswith("cup:") else " It had stood on its mat earlier.")
568
+ parts.append(txt)
569
+ if not success and all(raw):
570
+ if touching:
571
+ parts.append("The gripper is still touching a cup.")
572
+ elif not static:
573
+ parts.append("Something was still moving.")
574
+ if nudges:
575
+ parts.append(f"During the attempt cups that stood on their mats were pushed off {len(nudges)} time(s); "
576
+ f"{n_res} time(s) a cup was put back.")
577
+ trap = bool(nudges)
578
+ return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(CUPS))}, events=ev,
579
+ n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_nudged=len(nudges),
580
+ n_bumped=len(bumps), trap_fired=trap, recovered_in_attempt=bool(trap and success),
581
+ nudged_cups=sorted({e["cup"] for e in nudges}), failure=failure, held=held,
582
+ touching=bool(touching), static=bool(static),
583
+ offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)] for i in range(4)},
584
+ tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(CUPS[i]))), 1) for i in range(4)},
585
+ tight=bool(inst["tight"]), detail=" ".join(parts))
586
+
587
+ # ------------------------------------------------------------ scripted policies (move_to + gripper only)
588
+ def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
589
+ return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
590
+
591
+ def _lift_to(self, z, speed=0.15):
592
+ cur = self.sk.eef_pos()
593
+ if cur[2] < TZ + z - 0.005:
594
+ self._go([cur[0], cur[1], TZ + z], speed=speed)
595
+
596
+ def finger_clear(self, q, yaw, ignore=()):
597
+ """smallest distance (m) between the open fingers at grasp point q (xy) with gripper yaw `yaw` and the wall of
598
+ any standing cup other than `ignore`; finger axis (-sin yaw, cos yaw)"""
599
+ a = np.array([-np.sin(yaw), np.cos(yaw)])
600
+ b = np.array([a[1], -a[0]])
601
+ best = 1.0
602
+ for cup in CUPS:
603
+ if cup in ignore or self.held(cup):
604
+ continue
605
+ rel = self.pos(cup)[:2] - np.asarray(q, float)
606
+ for s in (1.0, -1.0):
607
+ u = s * float(rel @ a)
608
+ v = float(rel @ b)
609
+ du = max(FINGER_IN - u, 0.0, u - FINGER_OUT)
610
+ dv = max(abs(v) - FINGER_HALF, 0.0)
611
+ best = min(best, float(np.hypot(du, dv)) - CUP_R)
612
+ return best
613
+
614
+ def safe_yaw(self, q, ignore=(), prefer=0.0):
615
+ """the gripper yaw (0, 90, +-45 deg) whose open fingers stay farthest from the other cups at q"""
616
+ cands = [0.0, np.pi / 2, np.pi / 4, -np.pi / 4]
617
+ sc = [(round(min(self.finger_clear(q, y, ignore), 0.02), 3), -abs(_wrap_h(y - prefer)), y) for y in cands]
618
+ return max(sc)[2]
619
+
620
+ def grasp_cup(self, cup, yaw, depth, z_carry=Z_CARRY, v=0.2, err=None, lift=None):
621
+ """open, go over the cup at transit height, straight down, close, lift. Returns True if held."""
622
+ sk = self.sk
623
+ p = self.pos(cup)
624
+ q = p[:2] + (np.asarray(err, float) if err is not None else 0.0)
625
+ zg = envs.obj_max_z(self.env, cup) - depth
626
+ sk.set_gripper(False, steps=8)
627
+ self._lift_to(z_carry)
628
+ self._go([q[0], q[1], max(sk.eef_pos()[2], TZ + z_carry)], yaw=yaw, speed=v)
629
+ self._go([q[0], q[1], zg + 0.015], speed=0.10)
630
+ self._go([q[0], q[1], zg], speed=0.04, tol=0.003, max_steps=150)
631
+ sk.set_gripper(True, steps=15)
632
+ cur = sk.eef_pos()
633
+ self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.12)
634
+ sk.hold(5)
635
+ if not self.held(cup):
636
+ sk.set_gripper(False, steps=8)
637
+ return False
638
+ return True
639
+
640
+ def put_cup(self, cup, xy, yaw, z_carry=Z_CARRY, v=0.2, lift=None):
641
+ """carry the held cup so that the cup (not the grasp point) is over xy, rotate to `yaw`, straight down until its
642
+ base is 3 mm above the table, let go, lift"""
643
+ sk = self.sk
644
+ rel = self.pos(cup)[:2] - sk.eef_pos()[:2]
645
+ q = np.asarray(xy, float) - rel
646
+ cur = sk.eef_pos()
647
+ self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v)
648
+ sk.hold(5)
649
+ rel = self.pos(cup)[:2] - sk.eef_pos()[:2] # the cup can shift in the fingers while the wrist turns
650
+ q = np.asarray(xy, float) - rel
651
+ dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, cup)
652
+ zr = TZ + dz + 0.003
653
+ self._go([q[0], q[1], zr + 0.015], speed=0.10)
654
+ self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
655
+ sk.set_gripper(False, steps=12)
656
+ cur = sk.eef_pos()
657
+ self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.15)
658
+ sk.hold(3)
659
+
660
+ def mat_order(self, mode="far_first"):
661
+ """colour indices in placement order. far_first (Sonnet): the block row farthest from the supply first, then
662
+ the other; within a row from the left (robot's view)"""
663
+ sup = np.mean([self.inst["start"][c] for c in COLOURS], axis=0)
664
+ blk = np.asarray(self.inst["block"], float)
665
+ u = blk - sup
666
+ u = u / max(np.linalg.norm(u), 1e-9)
667
+ idx = list(range(4))
668
+ far = sorted(idx, key=lambda i: -float((self.mat_xy(i) - blk) @ u))
669
+ rows = [far[:2], far[2:]]
670
+ if mode == "near_first":
671
+ rows = rows[::-1]
672
+ out = []
673
+ for row in rows:
674
+ out += sorted(row, key=lambda i: (-self.mat_xy(i)[1], self.mat_xy(i)[0])) # left first
675
+ return out
676
+
677
+ @staticmethod
678
+ def looks_off(off, bias):
679
+ """a (biased) observer's verdict: the cup looks off its mat centre by more than 0.8 cm in some direction"""
680
+ p = np.asarray(off, float) - np.asarray(bias, float)
681
+ return abs(p[0]) > 0.008 or abs(p[1]) > 0.008
682
+
683
+ def place_one(self, i, yaw_rule, depth, rng, bias=(0.0, 0.0), rand=0.0, fix_rand=0.0, check=True, z_carry=Z_CARRY,
684
+ v=0.2):
685
+ """one stage: pick cup i from wherever it is and put it on its mat; aims at mat + bias (+- rand per axis); then
686
+ looks at this cup only (with the same bias) and re-places it if it looks off"""
687
+ cup = CUPS[i]
688
+ bias = np.asarray(bias, float)
689
+ for _ in range(2):
690
+ gy = yaw_rule(i, "grasp")
691
+ gerr = rng.uniform(-0.003, 0.003, 2) if rand else None
692
+ if self.grasp_cup(cup, gy, depth, z_carry=z_carry, v=v, err=gerr):
693
+ break
694
+ else:
695
+ return
696
+ e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2)
697
+ self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=z_carry, v=v)
698
+ if not check:
699
+ return
700
+ for _ in range(2):
701
+ if not self.looks_off(self.offset(i), bias) and self.tilt(cup) < TILT_OK:
702
+ return
703
+ ry = yaw_rule(i, "grasp")
704
+ if not self.grasp_cup(cup, ry, depth, z_carry=Z_LIFT, v=0.1, lift=Z_LIFT):
705
+ return
706
+ e = rng.uniform(-fix_rand, fix_rand, 2) if fix_rand else np.zeros(2)
707
+ self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=Z_LIFT, v=0.1, lift=z_carry)
708
+
709
+ def repair(self, rounds=4, depth=0.020, bias=(0.0, 0.0)):
710
+ """look at every cup (with the observer's bias); re-centre each one that looks off: grasp and let go with the
711
+ fingers opening where no other cup stands. Returns the number of cups moved."""
712
+ bias = np.asarray(bias, float)
713
+ moved = 0
714
+ tries = {}
715
+ for _ in range(rounds * 4):
716
+ bad = [i for i in range(4) if (self.looks_off(self.offset(i), bias) or self.held(CUPS[i]))
717
+ and self.tilt(CUPS[i]) < np.radians(30) and tries.get(i, 0) < rounds]
718
+ if not bad:
719
+ break
720
+ i = min(bad, key=lambda j: float(np.linalg.norm(self.pos(CUPS[j])[:2] - self.sk.eef_pos()[:2])))
721
+ tries[i] = tries.get(i, 0) + 1
722
+ cup = CUPS[i]
723
+ gy = self.safe_yaw(self.pos(cup)[:2], ignore=(cup,), prefer=self.sk.yaw)
724
+ # lift the cup clear of its neighbours before moving it: carried at 10 cm its base clips their rims and
725
+ # tips them (v1, measured, 4/20 adaptive runs before this was raised)
726
+ if not self.grasp_cup(cup, gy, depth, z_carry=Z_LIFT, v=0.15, lift=Z_LIFT):
727
+ continue
728
+ moved += 1
729
+ target = self.mat_xy(i) + bias
730
+ ry = self.safe_yaw(target, ignore=(cup,), prefer=self.sk.yaw)
731
+ self.put_cup(cup, target, ry, z_carry=Z_LIFT, v=0.1, lift=Z_CARRY)
732
+ return moved
733
+
734
+ def execute(self, inst, params):
735
+ rng = np.random.default_rng(params.get("noise_seed", 0))
736
+ depth = params.get("depth", 0.020)
737
+ order = self.mat_order(params.get("order", "far_first"))
738
+ mode = params["yaw"] # "fixed" (one wrist yaw for everything) or "safe" (fingers away from placed cups)
739
+ y0 = float(params.get("yaw0", 0.0))
740
+ bias = (float(params.get("bias_x", 0.0)), 0.0)
741
+
742
+ def yaw_rule(i, what):
743
+ if mode == "fixed":
744
+ return y0
745
+ q = self.pos(CUPS[i])[:2] if what == "grasp" else self.mat_xy(i) + np.asarray(bias)
746
+ return self.safe_yaw(q, ignore=(CUPS[i],), prefer=y0)
747
+
748
+ rand = float(params.get("rand", 0.0))
749
+ for i in order:
750
+ self.place_one(i, yaw_rule, depth, rng, bias=bias, rand=rand, fix_rand=float(params.get("fix_rand", 0.0)),
751
+ check=params.get("self_check", True), z_carry=params.get("z_carry", Z_CARRY),
752
+ v=params.get("v", 0.2))
753
+ if params.get("check"):
754
+ self.repair(bias=bias)
755
+ self._lift_to(0.20)
756
+ self.sk.hold(10)
757
+
758
+ # naive = Sonnet 5.5's habits measured in the v1 pilot (np_lh_nudge_row): wrist yaw 0 for every grasp and release in
759
+ # attempt 1, the row farthest from the supply first, lift to 14-25 cm and carry straight, vertical descents,
760
+ # placement 0.8-2.2 cm too far forward (per instance, invisible to it) +- 0.6 cm, looks at the cup it just placed and
761
+ # re-places it if it looks off, no look back at the others before finishing
762
+ NAIVE = dict(yaw="fixed", yaw0=0.0, order="far_first", self_check=True, check=False, rand=NAIVE_RAND,
763
+ fix_rand=NAIVE_FIX_RAND)
764
+ CAREFUL = dict(yaw="safe", yaw0=0.0, order="far_first", self_check=True, check=True, rand=0.0, bias_x=0.0)
765
+
766
+ def default_params(self, inst):
767
+ return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, bias_x=float(inst["naive_bias_x"]),
768
+ depth=0.008 + 0.012 * ((int(inst["seed"]) * 7) % 11) / 10) # 0.8-2.0 cm below the rim (pilot: ~1 cm)
769
+
770
+ def oracle_params(self, inst):
771
+ return dict(self.CAREFUL)
772
+
773
+ def adapt_params(self, inst, history):
774
+ """from attempt 2: let go with the fingers opening away from the placed cups (same imprecision and bias), and
775
+ look at every cup before finishing"""
776
+ return dict(self.default_params(inst), yaw="safe", check=True)
777
+
778
+ def blind_params(self, inst, attempt, rng):
779
+ """the naive behaviour with random variation, no history, no final look"""
780
+ return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)),
781
+ yaw0=float(rng.choice([0.0, np.pi / 2])), order=str(rng.choice(["far_first", "near_first"])),
782
+ z_carry=float(rng.uniform(0.15, 0.22)), v=float(rng.uniform(0.1, 0.3)),
783
+ depth=float(rng.uniform(0.008, 0.025)), bias_x=float(rng.uniform(*NAIVE_BIAS)))
784
+
785
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
786
+ k = k or self.max_attempts
787
+ rng = np.random.default_rng(seed)
788
+ history = []
789
+ single = ("oracle", "naive", "oracle_noise", "naive_yaw90", "naive_check", "careful_bias2", "naive_bias2")
790
+ for a in range(k):
791
+ self.reset_instance(inst)
792
+ if kind == "oracle":
793
+ params = self.oracle_params(inst)
794
+ elif kind == "naive":
795
+ params = self.default_params(inst)
796
+ elif kind == "adaptive": # attempt 1: naive + a final look at every cup (repairs); then careful releases
797
+ params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
798
+ elif kind == "blind":
799
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
800
+ elif kind == "switch": # control: cross-attempt learning only (careful releases from attempt 2), no final look
801
+ params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), yaw="safe")
802
+ elif kind == "oracle_noise": # robustness: careful with +-5 mm placement / grasp noise
803
+ params = dict(self.CAREFUL, rand=0.005, noise_seed=int(seed) * 7 + a)
804
+ elif kind == "naive_yaw90": # control: Sonnet-like but the wrist turned 90 deg for everything
805
+ params = dict(self.default_params(inst), yaw0=np.pi / 2)
806
+ elif kind == "naive_check": # control: naive + final look (= adaptive's first attempt)
807
+ params = dict(self.default_params(inst), check=True)
808
+ elif kind == "careful_bias2": # control: careful releases (nothing nudged) but placed 2 cm too far forward
809
+ params = dict(self.default_params(inst), yaw="safe", bias_x=0.020)
810
+ elif kind == "naive_bias2": # control: naive with a fixed +2 cm forward bias
811
+ params = dict(self.default_params(inst), bias_x=0.020)
812
+ else:
813
+ raise ValueError(kind)
814
+ self.execute(inst, params)
815
+ out = self.outcome(inst)
816
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
817
+ if on_attempt:
818
+ on_attempt(a, params, out)
819
+ if out["success"] or kind in single:
820
+ break
821
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/base.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s)."""
2
+ import os
3
+ import sys
4
+ from dataclasses import dataclass, field
5
+ from typing import Optional
6
+
7
+ # Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh).
8
+ # Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name:
9
+ # LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence.
10
+ API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "")
11
+ OPENAI_SDK_DIR = API_SDK_DIR # old name
12
+
13
+
14
+ def import_sdk(module):
15
+ """Import an API SDK module ("openai", "anthropic", "google.genai")."""
16
+ import importlib
17
+ try:
18
+ return importlib.import_module(module)
19
+ except ImportError:
20
+ if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path:
21
+ sys.path.append(API_SDK_DIR)
22
+ return importlib.import_module(module)
23
+
24
+
25
+ def import_openai():
26
+ return import_sdk("openai")
27
+
28
+
29
+ @dataclass
30
+ class BackendResponse:
31
+ tool_calls: list = field(default_factory=list) # [ToolCall]
32
+ text: Optional[str] = None # visible assistant text (e.g. the diagnosis)
33
+ reasoning_summary: Optional[str] = None
34
+ usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens
35
+ latency_s: float = 0.0
36
+ raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items)
37
+ request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ...
38
+ status: str = "ok"
39
+ error: Optional[str] = None
40
+
41
+
42
+ @dataclass
43
+ class RunInfo:
44
+ task: object # privileged: only the scripted backend may look at task / inst
45
+ inst: dict
46
+ seed: int
47
+ k: int
48
+ protocol: str
49
+ feedback: str
50
+ memory: str
51
+
52
+
53
+ @dataclass
54
+ class AttemptInfo:
55
+ attempt: int
56
+ history: list # AttemptRecords visible to the agent under the memory mode (already selected)
57
+ continuing: bool = False # within protocol: continuing after a failed done
58
+
59
+
60
+ class Backend:
61
+ name = "base"
62
+
63
+ def begin_run(self, info: RunInfo):
64
+ pass
65
+
66
+ def begin_attempt(self, info: AttemptInfo):
67
+ pass
68
+
69
+ def act(self, conv, tools) -> BackendResponse:
70
+ raise NotImplementedError
71
+
72
+ def on_tool_result(self, call, result):
73
+ pass
74
+
75
+ def end_attempt(self) -> dict:
76
+ return {}
77
+
78
+ def end_run(self):
79
+ pass
80
+
81
+ def config(self) -> dict:
82
+ return dict(name=self.name)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/chat_completions.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served
2
+ by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format.
3
+
4
+ Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard
5
+ message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent
6
+ back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and
7
+ Responses backends do (Kimi's docs ask for this in multi-step tool use)."""
8
+ import json
9
+ import os
10
+ import time
11
+
12
+ from ..context import ToolCall, prune_live_images
13
+ from .base import Backend, BackendResponse, import_openai
14
+
15
+
16
+ def chat_tools(specs):
17
+ return [dict(type="function", function=dict(name=s["name"], description=s["description"],
18
+ parameters=s["parameters"])) for s in specs]
19
+
20
+
21
+ class ChatCompletionsBackend(Backend):
22
+ name = "chat"
23
+
24
+ def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024,
25
+ max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None,
26
+ replay_reasoning=True):
27
+ self.model = model
28
+ self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1")
29
+ self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY")
30
+ self.temperature = temperature
31
+ self.max_tokens = max_tokens
32
+ self.max_live_images = max_live_images
33
+ self.jpeg_quality = jpeg_quality
34
+ self.timeout = timeout
35
+ self.extra_body = extra_body
36
+ self.replay_reasoning = replay_reasoning
37
+ self._client = client
38
+
39
+ def config(self):
40
+ return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature,
41
+ max_tokens=self.max_tokens, max_live_images=self.max_live_images,
42
+ replay_reasoning=self.replay_reasoning)
43
+
44
+ def client(self):
45
+ if self._client is None:
46
+ openai = import_openai()
47
+ kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1)
48
+ if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")):
49
+ # local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here)
50
+ kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout)
51
+ self._client = openai.OpenAI(**kw)
52
+ return self._client
53
+
54
+ def build_request(self, conv, tools):
55
+ msgs = [dict(role="system", content=conv.system)]
56
+ for it in prune_live_images(conv.items, self.max_live_images):
57
+ if it["kind"] == "user":
58
+ content = []
59
+ for p in it["parts"]:
60
+ if p["type"] == "text":
61
+ content.append(dict(type="text", text=p["text"]))
62
+ else:
63
+ content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality))))
64
+ msgs.append(dict(role="user", content=content))
65
+ elif it["kind"] == "assistant":
66
+ if not it.get("text") and not it["tool_calls"]:
67
+ # a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still
68
+ # counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content
69
+ # nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request
70
+ continue
71
+ m = dict(role="assistant", content=it.get("text") or None)
72
+ rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None
73
+ if rc and self.replay_reasoning:
74
+ m["reasoning_content"] = rc
75
+ if it["tool_calls"]:
76
+ m["tool_calls"] = [dict(id=tc.id, type="function",
77
+ function=dict(name=tc.name,
78
+ arguments=tc.raw_arguments or json.dumps(tc.arguments)))
79
+ for tc in it["tool_calls"]]
80
+ msgs.append(m)
81
+ elif it["kind"] == "tool_output":
82
+ msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"]))
83
+ req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto",
84
+ max_tokens=self.max_tokens)
85
+ if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature)
86
+ req["temperature"] = self.temperature
87
+ if self.extra_body:
88
+ req["extra_body"] = dict(self.extra_body)
89
+ return req
90
+
91
+ def act(self, conv, tools):
92
+ req = self.build_request(conv, tools)
93
+ n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list)
94
+ for c in m["content"] if c.get("type") == "image_url")
95
+ t0 = time.time()
96
+ resp = self.client().chat.completions.create(**req)
97
+ lat = time.time() - t0
98
+ stats = dict(n_images=n_img, n_messages=len(req["messages"]))
99
+ if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again
100
+ return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
101
+ error="empty response (no choices)")
102
+ msg = resp.choices[0].message
103
+ rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content")
104
+ calls = []
105
+ for i, tc in enumerate(msg.tool_calls or []):
106
+ raw = tc.function.arguments or ""
107
+ try:
108
+ args = json.loads(raw) if raw else {}
109
+ except json.JSONDecodeError:
110
+ args = {}
111
+ calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw))
112
+ u = resp.usage
113
+ ctd = getattr(u, "completion_tokens_details", None) if u else None
114
+ usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0,
115
+ output_tokens=getattr(u, "completion_tokens", 0) or 0,
116
+ reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {}
117
+ if not calls and not msg.content and not rc and not u:
118
+ return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
119
+ error="empty response (no output, no usage)")
120
+ return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage,
121
+ latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats)
122
+
123
+
124
+ def tool_results_first(msgs):
125
+ """OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly
126
+ after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's
127
+ output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool
128
+ messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after
129
+ the last tool message of the turn; nothing else changes order."""
130
+ out, i = [], 0
131
+ while i < len(msgs):
132
+ m = msgs[i]
133
+ out.append(m)
134
+ i += 1
135
+ if m["role"] != "assistant" or not m.get("tool_calls"):
136
+ continue
137
+ need = {tc["id"] for tc in m["tool_calls"]}
138
+ held = []
139
+ while i < len(msgs) and need:
140
+ n = msgs[i]
141
+ if n["role"] == "tool" and n.get("tool_call_id") in need:
142
+ out.append(n)
143
+ need.discard(n["tool_call_id"])
144
+ elif n["role"] == "user":
145
+ held.append(n)
146
+ else:
147
+ break
148
+ i += 1
149
+ out.extend(held)
150
+ return out
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/openai_responses.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI Responses API backend (default model gpt-6-astra).
2
+
3
+ Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with
4
+ store=False; reasoning items are replayed with their encrypted content so the model keeps its chain
5
+ of thought across tool calls within an attempt. The request prefix (instructions, tools, task text,
6
+ packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what
7
+ OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs.
8
+
9
+ Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time;
10
+ the client is created lazily on the first real call (tests inject a mock client).
11
+ """
12
+ import json
13
+ import os
14
+ import time
15
+
16
+ from ..context import ToolCall, prune_live_images
17
+ from .base import Backend, BackendResponse, import_openai
18
+
19
+ # GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported.
20
+ GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max")
21
+
22
+
23
+ def _get(obj, key, default=None):
24
+ if isinstance(obj, dict):
25
+ return obj.get(key, default)
26
+ return getattr(obj, key, default)
27
+
28
+
29
+ def _to_dict(item):
30
+ if isinstance(item, dict):
31
+ return dict(item)
32
+ if hasattr(item, "to_dict"):
33
+ return item.to_dict(mode="json")
34
+ if hasattr(item, "model_dump"):
35
+ return item.model_dump(mode="json", exclude_none=True)
36
+ return dict(vars(item))
37
+
38
+
39
+ def responses_tools(specs, strict=True):
40
+ return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"],
41
+ strict=strict) for s in specs]
42
+
43
+
44
+ class OpenAIResponsesBackend(Backend):
45
+ name = "openai"
46
+
47
+ def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto",
48
+ max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None,
49
+ store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0,
50
+ max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last",
51
+ prompt_cache_options=None, client=None, http_client=None):
52
+ if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS:
53
+ raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), "
54
+ f"got {reasoning_effort!r}")
55
+ self.model = model
56
+ self.reasoning_effort = reasoning_effort
57
+ self.reasoning_summary = reasoning_summary
58
+ self.image_detail = image_detail
59
+ self.max_output_tokens = max_output_tokens
60
+ self.service_tier = service_tier
61
+ self.prompt_cache_key = prompt_cache_key
62
+ self.prompt_cache_retention = prompt_cache_retention
63
+ self.store = store
64
+ self.replay_reasoning = replay_reasoning
65
+ self.max_live_images = max_live_images
66
+ self.jpeg_quality = jpeg_quality
67
+ self.timeout = timeout
68
+ self.max_retries = max_retries
69
+ self.extra_body = extra_body
70
+ self.strict_tools = strict_tools
71
+ # explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last"
72
+ assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints
73
+ self.cache_breakpoints = cache_breakpoints
74
+ self.prompt_cache_options = prompt_cache_options
75
+ self._client = client
76
+ self._http_client = http_client # optional custom transport (tests, proxies)
77
+ self._cache_key = prompt_cache_key
78
+
79
+ def config(self):
80
+ return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort,
81
+ reasoning_summary=self.reasoning_summary, image_detail=self.image_detail,
82
+ max_output_tokens=self.max_output_tokens, service_tier=self.service_tier,
83
+ prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention,
84
+ store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images,
85
+ jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries,
86
+ extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints,
87
+ prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL"))
88
+
89
+ # ------------------------------------------------------------------ client
90
+ def client(self):
91
+ if self._client is None:
92
+ key = os.environ.get("OPENAI_API_KEY")
93
+ if not key:
94
+ raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it")
95
+ openai = import_openai()
96
+ kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout,
97
+ max_retries=self.max_retries)
98
+ if self._http_client is not None:
99
+ kw["http_client"] = self._http_client
100
+ self._client = openai.OpenAI(**kw)
101
+ return self._client
102
+
103
+ def begin_run(self, info):
104
+ if self.prompt_cache_key is None:
105
+ # route all calls of one run to the same cache shard
106
+ self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}"
107
+
108
+ # ------------------------------------------------------------------ request
109
+ def convert_items(self, items):
110
+ out = []
111
+ last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1)
112
+ for i, it in enumerate(items):
113
+ kind = it["kind"]
114
+ if kind == "user":
115
+ content = []
116
+ for p in it["parts"]:
117
+ if p["type"] == "text":
118
+ content.append(dict(type="input_text", text=p["text"]))
119
+ else:
120
+ content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality),
121
+ detail=self.image_detail))
122
+ # explicit cache breakpoints: end of the stable history item (byte-identical for the whole
123
+ # attempt) and end of the newest input (reused by the next call of the attempt)
124
+ if content and ((self.cache_breakpoints != "none" and not it.get("live"))
125
+ or (self.cache_breakpoints == "history+last" and i == last_user)):
126
+ content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit")
127
+ out.append(dict(role="user", content=content))
128
+ elif kind == "assistant":
129
+ if it.get("raw") and it.get("backend") == self.name:
130
+ for r in it["raw"]:
131
+ if r.get("type") == "reasoning" and not self.replay_reasoning:
132
+ continue
133
+ out.append(r)
134
+ else:
135
+ if it.get("text"):
136
+ out.append(dict(role="assistant", content=it["text"]))
137
+ for tc in it["tool_calls"]:
138
+ out.append(dict(type="function_call", call_id=tc.id, name=tc.name,
139
+ arguments=tc.raw_arguments or json.dumps(tc.arguments)))
140
+ elif kind == "tool_output":
141
+ out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"]))
142
+ else:
143
+ raise ValueError(kind)
144
+ return out
145
+
146
+ def build_request(self, conv, tools):
147
+ items = prune_live_images(conv.items, self.max_live_images)
148
+ req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items),
149
+ tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False,
150
+ store=self.store)
151
+ reasoning = dict(effort=self.reasoning_effort)
152
+ if self.reasoning_summary:
153
+ reasoning["summary"] = self.reasoning_summary
154
+ req["reasoning"] = reasoning
155
+ if not self.store and self.replay_reasoning:
156
+ req["include"] = ["reasoning.encrypted_content"]
157
+ if self.max_output_tokens:
158
+ req["max_output_tokens"] = int(self.max_output_tokens)
159
+ if self.service_tier:
160
+ req["service_tier"] = self.service_tier
161
+ if self._cache_key:
162
+ req["prompt_cache_key"] = self._cache_key
163
+ if self.prompt_cache_retention:
164
+ req["prompt_cache_retention"] = self.prompt_cache_retention
165
+ if self.prompt_cache_options:
166
+ req["prompt_cache_options"] = dict(self.prompt_cache_options)
167
+ if self.extra_body:
168
+ req["extra_body"] = dict(self.extra_body)
169
+ return req
170
+
171
+ @staticmethod
172
+ def request_stats(req):
173
+ n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "")
174
+ for it in req["input"]:
175
+ for c in (it.get("content") if isinstance(it.get("content"), list) else []):
176
+ if c.get("type") == "input_image":
177
+ n_img += 1
178
+ img_bytes += len(c["image_url"])
179
+ elif "text" in c:
180
+ txt += len(c["text"])
181
+ if isinstance(it.get("content"), str):
182
+ txt += len(it["content"])
183
+ if it.get("type") == "function_call_output":
184
+ txt += len(it["output"]) if isinstance(it["output"], str) else 0
185
+ if it.get("type") == "function_call":
186
+ txt += len(it.get("arguments", ""))
187
+ tools_chars = len(json.dumps(req.get("tools", [])))
188
+ return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars,
189
+ n_input_items=len(req["input"]))
190
+
191
+ # ------------------------------------------------------------------ call
192
+ def act(self, conv, tools):
193
+ req = self.build_request(conv, tools)
194
+ stats = self.request_stats(req)
195
+ t0 = time.time()
196
+ resp = self.client().responses.create(**req)
197
+ out = self.parse_response(resp)
198
+ out.latency_s = time.time() - t0
199
+ out.request_stats = stats
200
+ return out
201
+
202
+ def parse_response(self, resp):
203
+ calls, texts, summ = [], [], []
204
+ output = _get(resp, "output") or []
205
+ for item in output:
206
+ t = _get(item, "type")
207
+ if t == "function_call":
208
+ raw = _get(item, "arguments") or ""
209
+ try:
210
+ args = json.loads(raw) if raw else {}
211
+ except json.JSONDecodeError:
212
+ args = {}
213
+ calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args,
214
+ raw_arguments=raw))
215
+ elif t == "message":
216
+ for c in _get(item, "content") or []:
217
+ if _get(c, "type") == "output_text":
218
+ texts.append(_get(c, "text") or "")
219
+ elif t == "reasoning":
220
+ for s in _get(item, "summary") or []:
221
+ summ.append(_get(s, "text") or "")
222
+ u = _get(resp, "usage")
223
+ usage = {}
224
+ if u is not None:
225
+ itd = _get(u, "input_tokens_details")
226
+ otd = _get(u, "output_tokens_details")
227
+ usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0,
228
+ cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0,
229
+ cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0,
230
+ output_tokens=_get(u, "output_tokens", 0) or 0,
231
+ reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0)
232
+ status = _get(resp, "status") or "completed"
233
+ err = None
234
+ if status == "incomplete":
235
+ err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason"))
236
+ elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again
237
+ status, err = "incomplete", "empty response (no output, no usage)"
238
+ return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
239
+ reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage,
240
+ raw=[_to_dict(i) for i in output], status=status, error=err)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/harnesses/sensenova.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SenseNova-RoboRSI native Codex SDK planner, controlled MCP variant."""
2
+ from .framework_codex import RobotFrameworkCodex
3
+
4
+ class SenseNovaCodex(RobotFrameworkCodex):
5
+ name = "sensenova_codex"
6
+ runtime_home = "/mnt/cpfs/workspace/env/sensenova-roborsi"
7
+
8
+ def __init__(self, **kwargs):
9
+ kwargs.setdefault("sessions", 1)
10
+ kwargs.setdefault("attempts_per_session", 0)
11
+ if kwargs["sessions"] != 1 or kwargs["attempts_per_session"] != 0:
12
+ raise ValueError("SenseNova controlled variant uses one persistent session for all attempts")
13
+ super().__init__(**kwargs)
14
+
15
+ def env(self, state, ep, base_url, work):
16
+ env = super().env(state, ep, base_url, work)
17
+ env["LFF_CONTROLLED_CODEX"] = "1"
18
+ return env
19
+
20
+ def config_info(self):
21
+ info = super().config_info()
22
+ info.update(variant="native-codex-planner-mcp", max_sdk_steps=self.max_turns,
23
+ history="same-thread", cross_episode_memory=False)
24
+ return info
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l5_loaded_beam.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L5 loaded_beam (2026-10-12): a deepened l5_slippery_lift -- lift a loaded bar level without spilling its load.
2
+
3
+ Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 2, 3.1): l5_slippery_lift saturated. Sonnet 5.5 (cla4)
4
+ grasped the bar's middle, lifted, saw the 45-60 deg tilt, put the bar down and regrasped near the centre of mass,
5
+ all inside attempt 1 (both runs succeeded on attempt 1): the tilting lift cost nothing. Rule R3: the first
6
+ common-sense interaction must cost something. Here the tilting lift spills the load.
7
+
8
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, "left" = +y): the l5_slippery_lift bar (steel grey,
9
+ 4 x 28 x 4 cm, long axis along the robot's left-right axis, same layout and hidden weight per seed) with two small red
10
+ blocks (2.5 cm cubes, 30 g, smooth: friction 0.2, they slide on the steel beyond ~11 deg of tilt) resting on its top
11
+ near the ends, 12.5 cm left and right of its middle.
12
+
13
+ Hidden variable (same in every attempt, invisible): a slug inside the bar puts its centre of mass e = 2.5-7 cm from
14
+ the middle, towards the left or right end (bar 0.8-1.2 kg, finger friction 0.40-0.60; l5_slippery_lift). The blocks
15
+ are symmetric, so the centre of mass of bar + blocks sits at M e / (M + 2 m) (2.3-6.7 cm).
16
+
17
+ Mechanism (physics, nothing teleported): grasped at its middle and lifted, the bar rotates in the slippery finger
18
+ pads and hangs tilted; the block on the low (heavy) end slides off, drops onto the table and, once the bar is set down
19
+ again, lies 2-5 cm beyond the bar's end; the other block slides along the bar to the fingers. Measured (20 seeds,
20
+ middle grasp): lift 15 cm at 0.1 m/s -> tilt 29-54 deg, spill 20/20; 15 cm at 0.03 m/s -> spill 20/20 (block friction =
21
+ the bar's, task card); a 5.5 cm "half lift" -> 20-22 deg, spill 20/20; 3 cm -> 10-11 deg, spill 2/20; 1 / 1.5 cm test
22
+ lifts -> 0.6-2.5 / 2.5-4.5 deg, spill 0/20 each (the low end stays on the table). Putting it right is a real repair:
23
+ set the bar down, release, pick the fallen block from the table, put it back on the end, move the other block back to
24
+ its end, regrasp nearer the heavy end, lift again: 20 commands for the scripted policy (5 for the whole oracle; the
25
+ same repair costs 7 commands in l5_slippery_lift, where nothing spills). What helps: a ~1 cm test lift shows the tilt
26
+ direction without spilling, or, after the first failure, grasping on the side of the end that sank (the heavy end),
27
+ ideally at the combined centre of mass (+-5 mm: 80/80 level lifts, nothing spilled).
28
+
29
+ Success: the bar is held (after a 1.5 s hold), tilted <= 8 deg, its lowest point >= 10 cm above the table (the
30
+ l5_slippery_lift condition), and both blocks rest on the bar, one within 3 cm of each end position (+-12.5 cm from the
31
+ middle; either block may sit on either end). Protocol: cross (reset before every attempt), k = 3.
32
+
33
+ Outcome (server log only; the agent gets F1): success / failure code, the bar's tilt and height, final block states,
34
+ per-step events (bar_lifted, bar_tilted, load_fell = the trap fired, load_displaced, load_removed, load_restored with
35
+ by_robot, bar_set_down), the lifts with their grasp points and maximum tilt, trap_fired, recovered_in_attempt,
36
+ first_interaction_ok and an F2-style `detail` in robot-centric words.
37
+ """
38
+ import numpy as np
39
+
40
+ from .. import envs
41
+ from ..bddl import write_bddl
42
+ from ..objects import box_xml, register_generated
43
+ from ..task_base import register_task
44
+ from .l5_slippery_lift import (BAR, HALF, LIFT_MIN, TILT_MAX, YAW_ACROSS, Z_GRASP, BarSkills, SlipperyLift,
45
+ bar_tilt_deg, weighted_box_xml)
46
+
47
+ TZ = envs.TABLE_Z
48
+ LOADS = ("block_1", "block_2") # block_1 starts on the left (+y) end, block_2 on the right (-y) end
49
+ LOAD_SIGN = {"block_1": 1.0, "block_2": -1.0}
50
+ LOAD_H = 0.0125 # 2.5 cm cubes
51
+ LOAD_MASS = 0.030
52
+ LOAD_RGBA = (0.85, 0.20, 0.12, 1.0)
53
+ LOAD_MU = 0.20 # block sliding friction (geom priority 3: used against the bar, the table and the fingers): the blocks
54
+ # slide on the steel bar beyond ~11 deg of tilt. With the bar's own mu (0.4-0.6, slide beyond 22-31 deg)
55
+ # a 5.5 cm "half lift" (20 deg) spilled nothing (0/10) and was a free probe; with 0.2 it spills.
56
+ SLOT = 0.125 # block centre this far from the bar's middle (along the bar)
57
+ SLOT_TOL = 0.03 # success: within 3 cm of an end position
58
+ BAR_TOP = TZ + 2 * HALF[2]
59
+ LIFTED = 0.02 # the bar's centre this much higher than at rest (while held) -> "lifted" (a ~1 cm test lift is not)
60
+ DOWN = 0.008 # ... and back below this -> "set down"
61
+ DEBOUNCE = 5 # control steps a new block state must persist before it counts
62
+ SAFE_ALONG = 0.09 # scripted grasps stay within +-9 cm of the middle (the hand must not touch the blocks)
63
+
64
+
65
+ class _Budget(Exception):
66
+ """the scripted policy used up the agent command budget of the attempt"""
67
+
68
+
69
+ def bar_frame(env):
70
+ """(centre, along, side, up): `along` = the bar's long axis oriented towards the robot's left (+y); `up` = the
71
+ bar's cross-section axis closest to world up (the face the blocks rest on); `side` completes the frame."""
72
+ bid = envs.body_id(env, BAR)
73
+ d = env.sim.data
74
+ c = d.body_xpos[bid].copy()
75
+ R = d.body_xmat[bid].reshape(3, 3)
76
+ al = R[:, 1].copy()
77
+ if al[1] < 0:
78
+ al = -al
79
+ up = max((R[:, 0].copy(), R[:, 2].copy()), key=lambda v: abs(v[2]))
80
+ if up[2] < 0:
81
+ up = -up
82
+ side = np.cross(up, al)
83
+ return c, al, side, up
84
+
85
+
86
+ def _end_word(s):
87
+ return "left" if s > 0 else "right"
88
+
89
+
90
+ class BeamSkills(BarSkills):
91
+ """BarSkills (records where along the bar the jaws closed) + the task's per-step monitor."""
92
+
93
+ def __init__(self, env, task, recorder=None):
94
+ super().__init__(env, recorder=recorder)
95
+ self.task = task
96
+
97
+ def _act(self, dpos, drot, grip):
98
+ super()._act(dpos, drot, grip)
99
+ self.task.monitor_step()
100
+
101
+
102
+ @register_task
103
+ class LoadedBeam(SlipperyLift):
104
+ name = "l5_loaded_beam"
105
+ level = "L5"
106
+ category = "dynamics_adaptation"
107
+ capabilities = ("Perceive", "Reason", "Plan", "Utilize")
108
+ protocol = "cross"
109
+ max_attempts = 3
110
+ agent_max_steps = 40
111
+ instruction = ("Lift the metal bar together with the two small red blocks resting near its ends, and hold it level "
112
+ "(tilted less than 8 degrees) with its lowest point at least 10 cm above the table. Both blocks must "
113
+ "stay on the bar near its ends. Keep holding the bar when you finish.")
114
+ instruction_indirect = ("Raise the long grey rod with the two little red cubes sitting near its ends and hold it "
115
+ "horizontal (tilted less than 8 degrees), its lowest point at least 10 cm above the table. "
116
+ "Both cubes must stay on the rod near its ends. Keep holding the rod when you finish.")
117
+
118
+ # ------------------------------------------------------------ scene
119
+ def make_bddl(self):
120
+ bar = register_generated("LffBeamBar", weighted_box_xml("lff_beam_bar", HALF, (0.52, 0.55, 0.58, 1.0)))
121
+ dens = LOAD_MASS / (2 * LOAD_H) ** 3
122
+ la = register_generated("LffBeamBlockA", box_xml("lff_beam_block_a", (LOAD_H,) * 3, LOAD_RGBA, density=dens))
123
+ lb = register_generated("LffBeamBlockB", box_xml("lff_beam_block_b", (LOAD_H,) * 3, LOAD_RGBA, density=dens))
124
+ # LIBERO's sampler puts the bar anywhere within +-13 cm of its region's centre (it "keeps the bar's 14 cm
125
+ # radius inside" a 2 cm region) and rejects block placements closer than 14 + 1.8 cm to it: the block regions
126
+ # are >= 19 cm from every possible bar position (the first layout, 2 cm beside the bar's range, failed with
127
+ # "Cannot place all objects" in 13 of 400 resets, this one 0 of 400). apply_instance moves everything anyway.
128
+ objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01)),
129
+ ("block_1", la, "block1_region", (-0.11, 0.32, -0.09, 0.34)),
130
+ ("block_2", lb, "block2_region", (-0.11, -0.34, -0.09, -0.32))]
131
+ return write_bddl(self.name, "lift the loaded bar and hold it level", objs)
132
+
133
+ def __init__(self, cam_res=None):
134
+ self.mon = None
135
+ self.budget = None # scripted policies only: command budget of the current attempt
136
+ self.ncmd = 0
137
+ super().__init__(cam_res)
138
+
139
+ def sample_instance(self, seed):
140
+ inst = super().sample_instance(seed) # same bar layout and hidden weight as l5_slippery_lift for this seed
141
+ m = inst["mass"]
142
+ inst.update(load_mass=LOAD_MASS, slot=SLOT,
143
+ com_total=float(m * inst["com_offset"] / (m + 2 * LOAD_MASS))) # bar + both blocks on their ends
144
+ return inst
145
+
146
+ def apply_instance(self, inst):
147
+ super().apply_instance(inst) # bar pose, friction, hidden weight (+ envs.refit_bounds)
148
+ x, y = inst["bar_xy"]
149
+ for nm in LOADS:
150
+ envs.set_obj_pose(self.env, nm, [x, y + LOAD_SIGN[nm] * SLOT, BAR_TOP + LOAD_H + 0.0005])
151
+ if LOAD_MU is not None:
152
+ envs.set_friction(self.env, nm, LOAD_MU, priority=3)
153
+
154
+ def reset_instance(self, inst, recorder=None):
155
+ self.env.reset()
156
+ self.apply_instance(inst)
157
+ self.env.sim.forward()
158
+ envs.settle(self.env, 10)
159
+ self.mon = None
160
+ self.sk = BeamSkills(self.env, self, recorder=recorder)
161
+ self._init_monitor()
162
+ return self.sk
163
+
164
+ # ------------------------------------------------------------ state
165
+ def bar_bottom(self):
166
+ return envs.obj_min_z(self.env, BAR) - TZ
167
+
168
+ def load_rel(self, nm):
169
+ """block centre in the bar frame: (along (+ = towards the bar's left end), side, height above the bar's centre)"""
170
+ c, al, side, up = bar_frame(self.env)
171
+ r = envs.obj_pos(self.env, nm) - c
172
+ return float(r @ al), float(r @ side), float(r @ up)
173
+
174
+ def _block_held(self, nm):
175
+ sk = self.sk
176
+ if sk is None or sk.grip < 0:
177
+ return False
178
+ if np.linalg.norm(envs.obj_pos(self.env, nm) - sk.eef_pos()) > 0.06:
179
+ return False
180
+ return sk.holding(nm)
181
+
182
+ def load_state(self, nm, tol=SLOT_TOL):
183
+ """'slot+' / 'slot-' (on the bar within `tol` of its left / right end position), 'bar' (on the bar
184
+ elsewhere), 'held', 'table', 'air' (anything else: falling, resting on the gripper ...)"""
185
+ if self._block_held(nm):
186
+ return "held"
187
+ a, s, u = self.load_rel(nm)
188
+ if abs(u - (HALF[2] + LOAD_H)) <= 0.008 and abs(s) <= HALF[0] + 0.003 and abs(a) <= HALF[1] + 0.003:
189
+ if abs(a - SLOT) <= tol:
190
+ return "slot+"
191
+ if abs(a + SLOT) <= tol:
192
+ return "slot-"
193
+ return "bar"
194
+ if envs.obj_pos(self.env, nm)[2] < TZ + 0.027:
195
+ return "table"
196
+ return "air"
197
+
198
+ # ------------------------------------------------------------ monitor
199
+ def _init_monitor(self):
200
+ st = {nm: self.load_state(nm) for nm in LOADS}
201
+ self.mon = dict(stable=dict(st), cand={nm: None for nm in LOADS}, cnt={nm: 0 for nm in LOADS},
202
+ last_on_bar={nm: self.load_rel(nm)[0] for nm in LOADS}, lost=set(), carried=set(), events=[],
203
+ lifts=[],
204
+ lifted=False, tilted=False, max_tilt=0.0)
205
+
206
+ def _event(self, ev, step=None, **kw):
207
+ self.mon["events"].append(dict(step=int(self.sk.n_steps if step is None else step), ev=ev, **kw))
208
+
209
+ def _last_grasp(self):
210
+ return next((c for c in reversed(self.sk.closes) if c["holding"]), None)
211
+
212
+ def monitor_step(self):
213
+ mon, sk = self.mon, self.sk
214
+ if mon is None or sk is None:
215
+ return
216
+ n = sk.n_steps
217
+ # --- the bar: lifts and tilt
218
+ rise = float(envs.obj_pos(self.env, BAR)[2]) - (TZ + HALF[2])
219
+ held = sk.grip > 0 and sk.holding(BAR)
220
+ if not mon["lifted"] and held and rise > LIFTED:
221
+ g = self._last_grasp()
222
+ mon["lifted"], mon["tilted"], mon["max_tilt"] = True, False, 0.0
223
+ mon["lifts"].append(dict(step_up=n, step_down=None, grasp_along=None if g is None else round(g["along"], 4),
224
+ max_tilt_deg=0.0, falls=[]))
225
+ self._event("bar_lifted", grasp_along=mon["lifts"][-1]["grasp_along"])
226
+ if mon["lifted"]:
227
+ t = bar_tilt_deg(self.env)
228
+ lift = mon["lifts"][-1]
229
+ if abs(t) > abs(lift["max_tilt_deg"]):
230
+ lift["max_tilt_deg"] = round(t, 1)
231
+ if not mon["tilted"] and abs(t) > TILT_MAX and held:
232
+ mon["tilted"] = True
233
+ self._event("bar_tilted", tilt_deg=round(t, 1), low_end=_end_word(t))
234
+ if rise < DOWN:
235
+ mon["lifted"] = False
236
+ lift["step_down"] = n
237
+ self._event("bar_set_down", max_tilt_deg=lift["max_tilt_deg"])
238
+ # --- the blocks (debounced state machine)
239
+ for nm in LOADS:
240
+ # hysteresis: a block that has left its end position must come back within 2 cm of an end to count as
241
+ # restored (a block sliding along the tilted bar hovered around the 3 cm limit and flickered)
242
+ s = self.load_state(nm, SLOT_TOL - 0.01 if nm in mon["lost"] else SLOT_TOL)
243
+ if s in ("slot+", "slot-", "bar"):
244
+ mon["last_on_bar"][nm] = self.load_rel(nm)[0]
245
+ old = mon["stable"][nm]
246
+ if s == old:
247
+ mon["cand"][nm], mon["cnt"][nm] = None, 0
248
+ continue
249
+ if s != mon["cand"][nm]:
250
+ mon["cand"][nm], mon["cnt"][nm] = s, 0
251
+ mon["cnt"][nm] += 1
252
+ if mon["cnt"][nm] < DEBOUNCE:
253
+ continue
254
+ step = n - DEBOUNCE + 1
255
+ mon["stable"][nm], mon["cand"][nm], mon["cnt"][nm] = s, None, 0
256
+ start = _end_word(LOAD_SIGN[nm])
257
+ if s == "held":
258
+ mon["carried"].add(nm)
259
+ if s in ("slot+", "slot-"):
260
+ if nm in mon["lost"]:
261
+ # by_robot: the gripper carried it back (else physics did, e.g. the high-end block sliding back out
262
+ # while the bar swings after the other block fell: 3-4 of 59 blind attempts)
263
+ mon["lost"].discard(nm)
264
+ self._event("load_restored", step, load=nm, start_end=start, end=_end_word(1 if s == "slot+" else -1),
265
+ by_robot=nm in mon["carried"])
266
+ mon["carried"].discard(nm)
267
+ elif old in ("slot+", "slot-") and s == "bar":
268
+ mon["lost"].add(nm)
269
+ self._event("load_displaced", step, load=nm, start_end=start, along_cm=round(100 * self.load_rel(nm)[0], 1))
270
+ elif old in ("slot+", "slot-", "bar", "air") and s == "table":
271
+ mon["lost"].add(nm)
272
+ end = _end_word(mon["last_on_bar"][nm])
273
+ self._event("load_fell", step, load=nm, start_end=start, off_end=end)
274
+ if mon["lifted"]:
275
+ mon["lifts"][-1]["falls"].append(nm)
276
+ elif old == "held" and s == "table":
277
+ mon["lost"].add(nm)
278
+ self._event("load_removed", step, load=nm, start_end=start)
279
+ elif old in ("slot+", "slot-") and s == "held":
280
+ mon["lost"].add(nm) # picked up by the agent: counts as lost until it is back on an end
281
+
282
+ # ------------------------------------------------------------ outcome / F2
283
+ def _where(self, nm):
284
+ """robot-centric description of a block that is not on an end position"""
285
+ st = self.load_state(nm)
286
+ a, s, u = self.load_rel(nm)
287
+ if st == "held":
288
+ return "is held in the gripper"
289
+ if st == "bar":
290
+ e = 1.0 if a >= 0 else -1.0
291
+ return (f"is still on the bar but {100 * (SLOT - abs(a)):.0f} cm in from its {_end_word(e)} end position "
292
+ f"({100 * abs(a):.0f} cm {_end_word(e)} of the bar's middle)")
293
+ c, al, side, up = bar_frame(self.env)
294
+ e = 1.0 if a >= 0 else -1.0
295
+ u = al[:2] / max(np.linalg.norm(al[:2]), 1e-6) # the bar's direction seen from above
296
+ end = c[:2] + al[:2] * e * HALF[1] # the end's position seen from above (also while the bar hangs tilted)
297
+ r = envs.obj_pos(self.env, nm)[:2] - end
298
+ beyond = float(r @ u) * e
299
+ lateral = float(r @ np.array([-u[1], u[0]]))
300
+ where = "on the table" if st == "table" else "off the bar"
301
+ if beyond > 0 and abs(lateral) < 0.04:
302
+ return f"lies {where}, {100 * beyond:.0f} cm beyond the bar's {_end_word(e)} end"
303
+ fx = f"{100 * abs(r[0]):.0f} cm {'forward' if r[0] > 0 else 'back'}"
304
+ fy = f"{100 * abs(r[1]):.0f} cm {'left' if r[1] > 0 else 'right'}"
305
+ return f"lies {where}, {fx} and {fy} of the bar's {_end_word(e)} end"
306
+
307
+ def outcome(self, inst):
308
+ sk, mon = self.sk, self.mon
309
+ sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws)
310
+ held = bool(sk.holding(BAR))
311
+ tilt = bar_tilt_deg(self.env)
312
+ bottom = self.bar_bottom()
313
+ states = {nm: self.load_state(nm) for nm in LOADS}
314
+ on_plus = [nm for nm in LOADS if states[nm] == "slot+"]
315
+ on_minus = [nm for nm in LOADS if states[nm] == "slot-"]
316
+ loads_ok = len(on_plus) == 1 and len(on_minus) == 1
317
+ level_ok = held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN
318
+ success = bool(level_ok and loads_ok)
319
+ lifted_ever = bool(mon["lifts"]) or (sk.zmax - sk.z0) > 0.03
320
+ g = self._last_grasp()
321
+ evs = mon["events"]
322
+ falls = [e for e in evs if e["ev"] == "load_fell"]
323
+ restored = [e for e in evs if e["ev"] == "load_restored"]
324
+ lifts = mon["lifts"]
325
+ first_ok = None if not lifts else bool(not lifts[0]["falls"]) # the first lift spilled nothing
326
+ # --- text
327
+ gtxt = ""
328
+ if g is not None:
329
+ a = g["along"]
330
+ gtxt = (f" You last grasped the bar {100 * abs(a):.1f} cm to the {_end_word(a)} of its middle."
331
+ if abs(a) >= 0.0005 else " You last grasped the bar at its middle.")
332
+ tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {_end_word(tilt)} end lower than its "
333
+ f"{_end_word(-tilt)} end")
334
+ if success:
335
+ failure = None
336
+ bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, "
337
+ "with a block on each end.")
338
+ elif held and abs(tilt) > TILT_MAX:
339
+ failure = "tilted"
340
+ bar_txt = f"The bar did not stay level: it rotated in the gripper and now {tilt_txt}."
341
+ if bottom < LIFT_MIN:
342
+ bar_txt += f" Its lowest point is {100 * bottom:.0f} cm above the table."
343
+ elif held and bottom < LIFT_MIN:
344
+ failure = "too_low"
345
+ bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only "
346
+ f"{100 * bottom:.0f} cm above the table.")
347
+ elif held:
348
+ failure = "load_off"
349
+ bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, "
350
+ "but the blocks are not both on its ends.")
351
+ elif lifted_ever:
352
+ failure = "dropped"
353
+ bar_txt = "The bar was lifted but is no longer in the gripper; it lies on the table."
354
+ else:
355
+ failure = "no_grasp"
356
+ bar_txt = ("The gripper never closed on the bar; it is still lying on the table." if not sk.closes else
357
+ "The gripper did not catch the bar; it is still lying on the table.")
358
+ parts = [bar_txt]
359
+ if falls:
360
+ f0 = falls[0]
361
+ lift = next((l for l in lifts if f0["load"] in l["falls"]), None)
362
+ how = (f" while the bar hung tilted by up to {abs(lift['max_tilt_deg']):.0f} degrees with its "
363
+ f"{_end_word(lift['max_tilt_deg'])} end lower") if lift and abs(lift["max_tilt_deg"]) > 1 else ""
364
+ parts.append(f"The {f0['start_end']} block slid off the bar's {f0['off_end']} end{how}."
365
+ + (f" Blocks fell off {len(falls)} times in this attempt." if len(falls) > 1 else ""))
366
+ if not loads_ok:
367
+ for nm in LOADS:
368
+ if states[nm] in ("slot+", "slot-") and (len(on_plus) == 1 or states[nm] != "slot+") and \
369
+ (len(on_minus) == 1 or states[nm] != "slot-"):
370
+ continue
371
+ parts.append(f"The {_end_word(LOAD_SIGN[nm])} block {self._where(nm)}.")
372
+ detail = " ".join(parts) + gtxt
373
+ loads = {}
374
+ for nm in LOADS:
375
+ a, s, u = self.load_rel(nm)
376
+ loads[nm] = dict(state=states[nm], along_cm=round(100 * a, 1), side_cm=round(100 * s, 1),
377
+ above_bar_centre_cm=round(100 * u, 1))
378
+ out = dict(success=success, failure=failure, held=held, tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1),
379
+ grasp_along=None if g is None else round(g["along"], 4),
380
+ stages=dict(bar_held_level_high=bool(level_ok), loads_on_ends=bool(loads_ok)),
381
+ loads=loads, loads_on_ends=len(on_plus) + len(on_minus) if loads_ok else
382
+ int(len(on_plus) >= 1) + int(len(on_minus) >= 1),
383
+ trap_fired=bool(falls), n_load_falls=len(falls), n_restored=len(restored),
384
+ n_restored_by_robot=len([e for e in restored if e.get("by_robot")]),
385
+ n_regressions=len([e for e in evs if e["ev"] in ("load_fell", "load_displaced")]),
386
+ recovered_in_attempt=bool(falls and success), first_interaction_ok=first_ok,
387
+ n_lifts=len(lifts), lifts=lifts, events=list(evs), closes=sk.closes, detail=detail)
388
+ out["detail_indirect"] = detail.replace("bar", "rod").replace("block", "cube")
389
+ return out
390
+
391
+ # ------------------------------------------------------------ scripted primitives (agent-command counted)
392
+ def _cmd(self, target=None, yaw=None, speed=None, grip=None, tol=0.004, max_steps=250):
393
+ """one agent command (move_eef with an optional gripper action, or observe when nothing is given)"""
394
+ self.ncmd += 1
395
+ if self.budget is not None and self.ncmd > self.budget:
396
+ raise _Budget()
397
+ sk = self.sk
398
+ if target is not None:
399
+ t = np.asarray(target, float).copy()
400
+ t[2] = max(t[2], TZ + 0.006) # the agent interface does not go below 0.5 cm above the table
401
+ sk.move_to(t, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
402
+ if grip is not None:
403
+ sk.set_gripper(bool(grip))
404
+
405
+ def grasp_lift(self, along, lift=0.15, speed=0.10, dx=0.0):
406
+ """open, above the grasp point (jaws across the bar), descend, close, lift, look: 5 commands"""
407
+ c, al, side, up = bar_frame(self.env)
408
+ g = c + al * float(along) + np.array([dx, 0.0, 0.0])
409
+ z = max(float(c[2]), Z_GRASP)
410
+ self._cmd([g[0], g[1], z + 0.10], yaw=YAW_ACROSS, grip=False)
411
+ self._cmd([g[0], g[1], z], tol=0.003)
412
+ self._cmd(grip=True)
413
+ self._cmd([g[0], g[1], z + lift], speed=speed, max_steps=600)
414
+ self._cmd()
415
+
416
+ def put_down(self):
417
+ """lower the held bar onto the table, release, back up: 2 commands"""
418
+ e = self.sk.eef_pos()
419
+ self._cmd([e[0], e[1], Z_GRASP + 0.003], speed=0.05, grip=False, max_steps=600)
420
+ self._cmd([e[0], e[1], Z_GRASP + 0.12])
421
+
422
+ def _block_yaw(self, nm):
423
+ """gripper yaw whose jaws close on two faces of the block, preferring jaws that do not reach towards the bar"""
424
+ q = envs.obj_quat(self.env, nm)
425
+ w, x, y, z = q
426
+ psi = float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
427
+ c, al, side, up = bar_frame(self.env)
428
+ p = envs.obj_pos(self.env, nm)
429
+ a = float(np.clip((p - c) @ al, -HALF[1], HALF[1]))
430
+ v = (p - (c + al * a))[:2]
431
+ v = v / max(np.linalg.norm(v), 1e-6)
432
+ best = None
433
+ for k in range(2):
434
+ ang = psi + k * np.pi / 2 # closing direction candidate (a face normal)
435
+ n = np.array([np.cos(ang), np.sin(ang)])
436
+ score = abs(n @ v)
437
+ if best is None or score < best[0]:
438
+ best = (score, ang)
439
+ yaw = best[1] + np.pi / 2 # yaw = closing direction + 90 deg (YAW_ACROSS closes along world x)
440
+ return float((yaw + np.pi / 2) % np.pi - np.pi / 2)
441
+
442
+ def move_block_to_slot(self, nm, sign, tries=2):
443
+ """pick a block (from the table or the bar) and set it on the end position `sign`: 6 commands per try"""
444
+ sk = self.sk
445
+ for _ in range(tries):
446
+ p = envs.obj_pos(self.env, nm)
447
+ yaw = self._block_yaw(nm)
448
+ zg = max(float(p[2]), TZ + 0.008)
449
+ self._cmd([p[0], p[1], zg + 0.08], yaw=yaw, grip=False)
450
+ self._cmd([p[0], p[1], zg], tol=0.003, grip=True)
451
+ self._cmd([p[0], p[1], BAR_TOP + LOAD_H + 0.07])
452
+ if not sk.holding(nm):
453
+ continue
454
+ c, al, side, up = bar_frame(self.env)
455
+ t = c + al * sign * SLOT
456
+ ztop = envs.obj_max_z(self.env, BAR)
457
+ self._cmd([t[0], t[1], ztop + LOAD_H + 0.06])
458
+ self._cmd([t[0], t[1], ztop + LOAD_H + 0.004], speed=0.05, grip=False)
459
+ self._cmd([t[0], t[1], ztop + LOAD_H + 0.08])
460
+ if self.load_state(nm) == ("slot+" if sign > 0 else "slot-"):
461
+ return True
462
+ return False
463
+
464
+ def restore_loads(self):
465
+ """put every block that is not on an end position back onto a free end; True if both ends are taken"""
466
+ for _ in range(2):
467
+ st = {nm: self.load_state(nm) for nm in LOADS}
468
+ free = [s for s in (1.0, -1.0) if not any(v == ("slot+" if s > 0 else "slot-") for v in st.values())]
469
+ if not free:
470
+ return True
471
+ loose = [nm for nm in LOADS if st[nm] not in ("slot+", "slot-")]
472
+ for sgn in free:
473
+ if not loose:
474
+ break
475
+ c, al, side, up = bar_frame(self.env)
476
+ slot = c + al * sgn * SLOT
477
+ nm = min(loose, key=lambda b: np.linalg.norm(envs.obj_pos(self.env, b)[:2] - slot[:2]))
478
+ loose.remove(nm)
479
+ self.move_block_to_slot(nm, sgn)
480
+ self._cmd() # look
481
+ st = {nm: self.load_state(nm) for nm in LOADS}
482
+ return sorted(st.values()) == ["slot+", "slot-"]
483
+
484
+ def judge(self):
485
+ """what an agent sees after a lift (perfect perception): (all good, tilt, blocks on their ends)"""
486
+ tilt = bar_tilt_deg(self.env)
487
+ st = sorted(self.load_state(nm) for nm in LOADS)
488
+ ok_loads = st == ["slot+", "slot-"]
489
+ good = self.sk.holding(BAR) and abs(tilt) <= TILT_MAX - 2 and self.bar_bottom() >= LIFT_MIN + 0.01 and ok_loads
490
+ return bool(good), float(tilt), ok_loads
491
+
492
+ # ------------------------------------------------------------ scripted policies
493
+ def execute(self, inst, params):
494
+ self.grasp_lift(params["along"], params.get("lift", 0.15), params.get("speed", 0.10), params.get("dx", 0.0))
495
+
496
+ def default_params(self, inst):
497
+ return dict(along=0.0, lift=0.15, speed=0.10) # Sonnet 5.5 (cla4): middle, up to ~15-18 cm at 0.1 m/s
498
+
499
+ def oracle_params(self, inst):
500
+ return dict(along=float(inst["com_total"]), lift=0.15, speed=0.10)
501
+
502
+ def blind_params(self, inst, attempt, rng):
503
+ return dict(along=float(rng.normal(0.0, 0.01)), lift=float(rng.uniform(0.12, 0.18)),
504
+ speed=float(rng.uniform(0.05, 0.20)))
505
+
506
+ MARGIN = 0.008 # a lift that sank towards +y at grasp g says COM > g + MARGIN
507
+ STEP = 0.030 # first move towards the end that sank when only one side is bounded
508
+
509
+ def bracket(self, obs):
510
+ """grasp point from (grasp_along, tilt) observations: the end that sank is the heavy side of that grasp"""
511
+ lo, hi = -SAFE_ALONG, SAFE_ALONG
512
+ lo_set = hi_set = False
513
+ for g, t in obs:
514
+ if t > 0:
515
+ lo, lo_set = max(lo, g + self.MARGIN), True
516
+ else:
517
+ hi, hi_set = min(hi, g - self.MARGIN), True
518
+ if lo_set and hi_set:
519
+ a = 0.5 * (lo + hi)
520
+ elif lo_set:
521
+ a = lo + self.STEP - self.MARGIN
522
+ elif hi_set:
523
+ a = hi - self.STEP + self.MARGIN
524
+ else:
525
+ a = 0.0
526
+ return float(np.clip(a, -SAFE_ALONG, SAFE_ALONG))
527
+
528
+ def adapt_params(self, inst, history):
529
+ obs = [o for h in history for o in h["params"].get("obs", [])]
530
+ return dict(along=self.bracket(obs))
531
+
532
+ def adaptive_attempt(self, obs):
533
+ """lift at the current estimate; if the bar tilts or a block falls: set the bar down, put the blocks back,
534
+ regrasp on the side of the end that sank (bracketing), lift again -- while the command budget allows"""
535
+ tried = []
536
+ along = self.bracket(obs)
537
+ while True:
538
+ tried.append(round(along, 4))
539
+ self.grasp_lift(along)
540
+ good, tilt, ok_loads = self.judge()
541
+ if good:
542
+ return tried
543
+ g = self._last_grasp()
544
+ if abs(tilt) > 3.0 or not ok_loads:
545
+ lift = self.mon["lifts"][-1] if self.mon["lifts"] else None
546
+ t = tilt if abs(tilt) > 3.0 else (lift["max_tilt_deg"] if lift else 0.0)
547
+ if abs(t) > 1.0:
548
+ obs.append((g["along"] if g is not None else along, t))
549
+ # a repair = set down (2) + both blocks back (2 x 6: the fallen one and the one that slid to the fingers)
550
+ # + look (1) + regrasp, lift, look (5) = 20 commands; without enough budget keep holding the bar as it is
551
+ if self.budget is not None and self.ncmd + 20 > self.budget:
552
+ return tried
553
+ self.put_down()
554
+ if not self.restore_loads():
555
+ return tried
556
+ along = self.bracket(obs)
557
+
558
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
559
+ """cross protocol with an agent-like command budget per attempt (agent_max_steps; one move_eef with an optional
560
+ gripper action, or one observe, = one command). naive / oracle / blind: one lift, no checking.
561
+ adaptive: naive in attempt 1 but checks and repairs inside the attempt (`adaptive_attempt`); later attempts
562
+ start from the grasp point learned so far."""
563
+ k = k or self.max_attempts
564
+ rng = np.random.default_rng(seed)
565
+ history, obs = [], []
566
+ for a in range(k):
567
+ self.reset_instance(inst)
568
+ self.ncmd, self.budget = 0, self.agent_max_steps
569
+ if kind == "oracle":
570
+ params = self.oracle_params(inst)
571
+ elif kind == "naive":
572
+ params = self.default_params(inst)
573
+ elif kind == "blind":
574
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
575
+ elif kind == "adaptive":
576
+ params = dict(obs=[])
577
+ else:
578
+ raise ValueError(kind)
579
+ n0 = len(obs)
580
+ try:
581
+ if kind == "adaptive":
582
+ params["tried"] = self.adaptive_attempt(obs)
583
+ else:
584
+ self.execute(inst, params)
585
+ except _Budget:
586
+ params["budget_used_up"] = True
587
+ if kind == "adaptive":
588
+ params["obs"] = [[round(g, 4), round(t, 1)] for g, t in obs[n0:]]
589
+ self.budget = None
590
+ out = self.outcome(inst)
591
+ out["commands"] = self.ncmd
592
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
593
+ if on_attempt:
594
+ on_attempt(a, params, out)
595
+ if out["success"] or kind in ("oracle", "naive"):
596
+ break
597
+ return history
598
+
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L5-C tablecloth_pull: yank a board out from under a cube so that the cube lands inside a band.
2
+
3
+ Category dynamics_adaptation (L5): "figure out how this object moves". Replaces l5_tip_threshold, which could not
4
+ be built robustly with this robot (see task_cards/l5_tip_threshold.md).
5
+
6
+ Scene: a 30 x 8 x 1 cm wooden board lies on the table, pointing away from the robot, with a black handle block
7
+ at its near end. A red 4 cm cube stands on the far part of the board. A green band (6 cm deep, across the
8
+ table) is painted on the table under the board, a few cm closer to the robot than the cube. The agent may touch
9
+ only the board / handle, never the cube.
10
+
11
+ Physics. If the board is pulled slowly the cube rides along on it (static friction). If it is yanked, the board
12
+ slides out from under the cube; while it slides, friction drags the cube a little towards the robot, so the
13
+ cube drops onto the table having moved d towards the robot. d DEcreases with the pull speed (counter-intuitive:
14
+ a harder yank moves the cube less) and increases with the cube-board friction mu.
15
+
16
+ Hidden variable: the cube's friction mu (0.08-0.15; the cube looks the same for every mu), which shifts the whole
17
+ speed -> displacement curve and the speed below which the cube rides along.
18
+
19
+ Why the prior fails. The classic tablecloth prior is to yank as fast as possible (0.6 m/s, the arm's top speed);
20
+ the band is always placed >= 1.3 cm beyond the displacement such a yank produces, so the cube lands short of it. F2 reports where the cube ended relative to the band (robot-frame words, cm) or that it
21
+ rode along; the agent has to infer which way to change the pull speed (faster = less displacement) and by how
22
+ much.
23
+
24
+ Rule (stated in the instruction and enforced, 2026-10-08): ONE pull. Only one move command may drive the board
25
+ (>= PULL_EPS), the cube must still be where it started (<= PRE_TOL, grasp nudges) when that pull begins, and all
26
+ other move commands together may drive the board at most STRAY_MAX. Gripper open / close commands never count.
27
+ Without it every cla2 success (Sonnet, 4/4) dragged the board slowly first so that the cube rode to the band and the
28
+ last pull only added a little (one dragged it 4 cm, then yanked it sideways; one moved it with 11 commands, most
29
+ of them open-gripper strikes): the friction never mattered.
30
+ """
31
+ import numpy as np
32
+
33
+ from .. import envs
34
+ from ..bddl import write_bddl
35
+ from ..objects import _fmt, _wrap, box_xml, register_generated
36
+ from ..skills import Skills
37
+ from ..task_base import LFFTask, register_task
38
+
39
+ BOARD, CUBE, BAND = "board_1", "cube_1", "band_1"
40
+ B_HALF = (0.15, 0.04, 0.005) # 30 x 8 x 1 cm
41
+ H_HALF = (0.0125, 0.02, 0.015) # handle 2.5 x 4 x 3 cm on top of the near end
42
+ C_HALF = 0.02 # 4 cm cube
43
+ LF = 0.05 # cube centre to the board's far edge
44
+ BAND_HALF_X = 0.03 # band 6 cm deep: the 4 cm cube must be fully inside -> centre within +-1 cm
45
+ BAND_HALF_Y = 0.12
46
+ LINE_W = 0.005
47
+ TOL = BAND_HALF_X - C_HALF
48
+ MU_BOARD = 0.3 # board-table friction (fixed)
49
+ STROKE = 0.25 # scripted pull length
50
+ V_MIN, V_MAX = 0.15, 0.80
51
+ # one-pull rule (2026-10-08). Board motion is the larger of its two ends' 3-D paths and is only counted while the robot
52
+ # drives the board (touches it, or it speeds up; a board sliding on its own only slows down), so coasting after a
53
+ # strike or a release is not charged to the next command. Measured on the cla2 agent runs and the scripted policy:
54
+ # approach moves 0 mm; closing on the handle 0.6-2 mm (agents) / 4.6 mm (script); release after the pull 3-10 mm
55
+ # (gripper commands never count as pulls); the loophole drags 13-41 mm per command, open-gripper strikes 11-54 mm.
56
+ PULL_EPS = 0.003 # a move command that drives the board this far is a pull
57
+ PRE_TOL = 0.01 # the cube may have moved at most this much (grasp nudges) when the pull starts
58
+ STRAY_MAX = 0.005 # board motion driven by all the other move commands together (each below PULL_EPS)
59
+ ACC_EPS = 0.0002 # board speed-up per control step (m/step) that counts as the robot driving it
60
+ _SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
61
+
62
+
63
+ def board_xml(name):
64
+ hp = (-B_HALF[0] + H_HALF[0], 0.0, B_HALF[2] + H_HALF[2])
65
+ wood, black = (0.62, 0.45, 0.28, 1.0), (0.12, 0.12, 0.12, 1.0)
66
+ g = (f' <inertial pos="0.001 0 0.001" mass="0.3" diaginertia="0.0016 0.0023 0.0039" />\n'
67
+ f' <geom name="{name}_g0" type="box" size="{_fmt(B_HALF)}" rgba="{_fmt(wood)}" {_SOLID} group="0" />\n'
68
+ f' <geom name="{name}_g1" type="box" pos="{_fmt(hp)}" size="{_fmt(H_HALF)}" rgba="{_fmt(black)}" '
69
+ f'{_SOLID} group="0" />\n'
70
+ f' <geom type="box" size="{_fmt(B_HALF)}" rgba="{_fmt(wood)}" conaffinity="0" contype="0" group="1" />\n'
71
+ f' <geom type="box" pos="{_fmt(hp)}" size="{_fmt(H_HALF)}" rgba="{_fmt(black)}" conaffinity="0" '
72
+ f'contype="0" group="1" />')
73
+ # small horizontal radius: only LIBERO's reset-time sampler reads it (the layout is overridden anyway)
74
+ return _wrap(name, g, B_HALF[2], 0.03)
75
+
76
+
77
+ def band_xml(name, line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)):
78
+ """Flat visual band across the table (no collisions): light fill + dark lines on its two long edges."""
79
+ hx, hy = BAND_HALF_X, BAND_HALF_Y
80
+ parts = [((0, 0, 0.0004), (hx, hy, 0.0004), fill_rgba),
81
+ ((hx + LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba),
82
+ ((-hx - LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba)]
83
+ g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
84
+ f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
85
+ return _wrap(name, g, 0.0012, 0.03)
86
+
87
+
88
+ def d_range(mu):
89
+ """Band distances sampled for a given mu (m). Calibrated 2026-10-07 (LF 5 cm, board at x 0.05): the cube
90
+ moves d(0.6 m/s) ~ 0.33 * mu - 0.85 cm when yanked at the controller's top speed (mu 0.08 -> 1.8 cm,
91
+ 0.10 -> 2.3, 0.12 -> 3.1, 0.15 -> 4.3 cm) and >= 0.5 * mu at a pull ~0.05 m/s above the ride-along speed (0.08 -> 4.1 cm at
92
+ 0.35 m/s, 0.15 -> 7.6 cm at 0.45 m/s). The band centre is put ~1.5 cm beyond the top-speed displacement, so
93
+ the 'yank as fast as possible' prior always lands the cube short of the band."""
94
+ return 0.33 * mu + 0.0065, 0.50 * mu
95
+
96
+
97
+ class ClothSkills(Skills):
98
+ """Skills that watch, every control step, whether the robot touches the cube (not allowed) and how each
99
+ move_to / gripper command moves the board and the cube (one pull only)."""
100
+
101
+ def __init__(self, env, bias=None, recorder=None):
102
+ super().__init__(env, bias=bias, recorder=recorder)
103
+ m = env.sim.model
104
+ self._robot = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
105
+ self._cube = envs.obj_geom_ids(env, CUBE)
106
+ self._board = envs.obj_geom_ids(env, BOARD)
107
+ self.touched_cube = False
108
+ self.cube0 = envs.obj_pos(env, CUBE)
109
+ self._ends = self._board_ends()
110
+ self._bstep = 0.0 # board motion in the previous control step
111
+ self._seg = None
112
+ self.segments = [] # one entry per move_to / set_gripper command
113
+
114
+ def _board_ends(self):
115
+ """Both ends of the board's long axis (world xyz): their motion also catches turning and tilting."""
116
+ b = envs.obj_pos(self.env, BOARD)
117
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3)
118
+ return np.stack([b - R[:, 0] * B_HALF[0], b + R[:, 0] * B_HALF[0]])
119
+
120
+ def _act(self, dpos, drot, grip):
121
+ super()._act(dpos, drot, grip)
122
+ if not self.touched_cube and envs.contacts_between(self.env, self._robot, self._cube):
123
+ self.touched_cube = True
124
+ ends = self._board_ends()
125
+ step = float(np.max(np.linalg.norm(ends - self._ends, axis=1)))
126
+ touch = envs.contacts_between(self.env, self._robot, self._board)
127
+ speed_up = step - self._bstep > ACC_EPS
128
+ self._ends, self._bstep = ends, step
129
+ s = self._seg
130
+ if s is not None:
131
+ s["path"] += step
132
+ s["touch"] += int(touch)
133
+ if touch or speed_up:
134
+ s["driven"] += step
135
+
136
+ def _segment(self, kind, fn, *args, **kwargs):
137
+ c0, b0 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD)
138
+ self._seg = dict(kind=kind, step0=self.n_steps, path=0.0, driven=0.0, touch=0)
139
+ try:
140
+ rep = fn(*args, **kwargs)
141
+ finally:
142
+ s, self._seg = self._seg, None
143
+ c1, b1 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD)
144
+ s.update(steps=self.n_steps - s["step0"], board_dxy=(b1 - b0)[:2].round(4).tolist(),
145
+ cube_dxy=(c1 - c0)[:2].round(4).tolist(), cube_from_start=(c0 - self.cube0)[:2].round(4).tolist())
146
+ self.segments.append(s)
147
+ return rep
148
+
149
+ def move_to(self, target, *args, **kwargs):
150
+ return self._segment("move", super().move_to, target, *args, **kwargs)
151
+
152
+ def set_gripper(self, close, steps=15):
153
+ return self._segment("close" if close else "open", super().set_gripper, close, steps)
154
+
155
+ def pull_check(self):
156
+ """Pulls (move commands that drove the board >= PULL_EPS), where the cube was when the (first) pull started,
157
+ and the board motion driven by the other move commands."""
158
+ moves = [s for s in self.segments if s["kind"] == "move"]
159
+ pulls = [s for s in moves if s["driven"] >= PULL_EPS]
160
+ stray = sum(s["driven"] for s in moves if s["driven"] < PULL_EPS)
161
+ pre = (float(np.linalg.norm(pulls[0]["cube_from_start"])) if pulls
162
+ else float(np.linalg.norm((envs.obj_pos(self.env, CUBE) - self.cube0)[:2])))
163
+ return dict(n_pulls=len(pulls), pulls_cm=[round(100 * s["driven"], 1) for s in pulls],
164
+ pre_pull_cube_cm=round(100 * pre, 1), stray_cm=round(100 * stray, 2))
165
+
166
+
167
+ @register_task
168
+ class TableclothPull(LFFTask):
169
+ name = "l5_tablecloth_pull"
170
+ level = "L5"
171
+ category = "dynamics_adaptation"
172
+ capabilities = ("Perceive", "Reason", "Utilize")
173
+ protocol = "cross"
174
+ instruction = ("Pull the wooden board out from under the red cube so that the cube ends up standing on the table "
175
+ "completely inside the green band. Touch only the board and its black handle, never the cube. "
176
+ "Only one pull is allowed per attempt: grasp the black handle, pull the board out with ONE move "
177
+ "command, then release it. Any other move that drags, pushes or nudges the board, before or after "
178
+ "the pull, counts as another pull.")
179
+ instruction_indirect = ("Pull the long brown plank out from under the small red block so that the block ends up "
180
+ "standing on the table completely inside the green stripe. Touch only the plank and its "
181
+ "black handle, never the block. Only one pull is allowed per attempt: grasp the black "
182
+ "handle, pull the plank out with ONE move command, then release it. Any other move that "
183
+ "drags, pushes or nudges the plank, before or after the pull, counts as another pull.")
184
+
185
+ # ------------------------------------------------------------ scene
186
+ def make_bddl(self):
187
+ board = register_generated("LffClothBoard", board_xml("lff_cloth_board"))
188
+ cube = register_generated("LffClothCube", box_xml("lff_cloth_cube", (C_HALF,) * 3, (0.85, 0.15, 0.15, 1.0),
189
+ density=2300))
190
+ band = register_generated("LffClothBand", band_xml("lff_cloth_band"), free=False)
191
+ objs = [(BOARD, board, "board_region", (0.09, -0.26, 0.11, -0.24)),
192
+ (CUBE, cube, "cube_region", (-0.21, 0.24, -0.19, 0.26))]
193
+ fixtures = [(BAND, band, "band_region", (-0.31, -0.01, -0.29, 0.01))]
194
+ return write_bddl(self.name, "pull the board out from under the cube", objs, fixtures=fixtures)
195
+
196
+ def sample_instance(self, seed):
197
+ rng = np.random.default_rng(seed)
198
+ mu = float(np.exp(rng.uniform(np.log(0.08), np.log(0.15))))
199
+ lo, hi = d_range(mu)
200
+ d = float(rng.uniform(lo, max(lo, hi)))
201
+ return dict(seed=int(seed), board_xy=[float(rng.uniform(0.03, 0.08)), float(rng.uniform(-0.08, 0.08))],
202
+ mu=mu, band_d=d)
203
+
204
+ def cube_start(self, inst):
205
+ bx, by = inst["board_xy"]
206
+ return np.array([bx + B_HALF[0] - LF, by])
207
+
208
+ def band_center(self, inst):
209
+ c = self.cube_start(inst)
210
+ return np.array([c[0] - inst["band_d"], c[1]])
211
+
212
+ def apply_instance(self, inst):
213
+ m = self.env.sim.model
214
+ for g in range(m.ngeom): # the band is a flat marker: no collisions
215
+ if (m.geom_id2name(g) or "").startswith(BAND + "_"):
216
+ m.geom_contype[g] = 0
217
+ m.geom_conaffinity[g] = 0
218
+ bx, by = inst["board_xy"]
219
+ envs.set_obj_pose(self.env, BOARD, [bx, by, envs.TABLE_Z + B_HALF[2] + 0.0005])
220
+ c = self.cube_start(inst)
221
+ envs.set_obj_pose(self.env, CUBE, [c[0], c[1], envs.TABLE_Z + 2 * B_HALF[2] + C_HALF + 0.0005])
222
+ envs.set_friction(self.env, BOARD, MU_BOARD, priority=1)
223
+ envs.set_friction(self.env, CUBE, inst["mu"], priority=2) # cube-board and cube-table contacts use mu
224
+ bid = m.body_name2id(self.env.fixtures_dict[BAND].root_body)
225
+ bc = self.band_center(inst)
226
+ m.body_pos[bid] = [bc[0], bc[1], envs.TABLE_Z + 0.0002]
227
+ m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
228
+
229
+ def reset_instance(self, inst, recorder=None):
230
+ from robosuite.utils.errors import RandomizationError
231
+ for _ in range(20): # LIBERO's reset-time placement sampler occasionally fails; the layout is overridden
232
+ try:
233
+ self.env.reset()
234
+ break
235
+ except RandomizationError:
236
+ continue
237
+ self.apply_instance(inst)
238
+ self.env.sim.forward()
239
+ envs.settle(self.env, 10)
240
+ self.sk = ClothSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
241
+ return self.sk
242
+
243
+ # ------------------------------------------------------------ outcome
244
+ def cube_on_board(self):
245
+ c = envs.obj_pos(self.env, CUBE)
246
+ b = envs.obj_pos(self.env, BOARD)
247
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3)
248
+ local = R.T @ (c - b)
249
+ return bool(abs(local[0]) < B_HALF[0] + 0.005 and abs(local[1]) < B_HALF[1] + 0.005
250
+ and c[2] > envs.TABLE_Z + 2 * B_HALF[2] + C_HALF - 0.004)
251
+
252
+ def outcome(self, inst):
253
+ sk = self.sk
254
+ envs.settle(self.env, 60)
255
+ c = envs.obj_pos(self.env, CUBE)
256
+ c0 = self.cube_start(inst)
257
+ bc = self.band_center(inst)
258
+ moved = float(c0[0] - c[0]) # towards the robot
259
+ off = c[:2] - bc # + x: cube forward (away from the robot) of the band's centre line
260
+ upright = envs.obj_upright_cos(self.env, CUBE) > 0.95
261
+ on_board = self.cube_on_board()
262
+ on_table = c[2] < envs.TABLE_Z + C_HALF + 0.004
263
+ in_band = bool(abs(off[0]) <= TOL and abs(off[1]) <= BAND_HALF_Y - C_HALF)
264
+ pc = sk.pull_check()
265
+ rule = []
266
+ if pc["n_pulls"] > 1:
267
+ rule.append(f"The board was moved by {pc['n_pulls']} separate move commands "
268
+ f"({', '.join(f'{v:.1f}' for v in pc['pulls_cm'])} cm); only one pull is allowed.")
269
+ if pc["n_pulls"] and pc["pre_pull_cube_cm"] > 100 * PRE_TOL:
270
+ rule.append(f"When the pull started the cube had already been moved {pc['pre_pull_cube_cm']:.1f} cm by "
271
+ f"earlier small moves of the board; only one pull is allowed.")
272
+ if pc["stray_cm"] > 100 * STRAY_MAX:
273
+ rule.append(f"Besides the pull, other move commands moved the board {pc['stray_cm']:.1f} cm in total; "
274
+ f"only one pull is allowed.")
275
+ success = bool(in_band and on_table and upright and not on_board and not sk.touched_cube and not rule)
276
+ b_moved = float(np.linalg.norm(envs.obj_pos(self.env, BOARD)[:2] - np.asarray(inst["board_xy"])))
277
+ out = dict(success=success, touched_cube=bool(sk.touched_cube), on_board=on_board, upright=bool(upright),
278
+ moved_toward_robot=round(moved, 4), band_offset_x=round(float(off[0]), 4),
279
+ err=round(float(moved - inst["band_d"]), 4), board_moved=round(b_moved, 4),
280
+ one_pull=not rule, **pc)
281
+ side = ("forward (+x, away from the robot)" if off[0] > 0 else "backward (-x, toward the robot)")
282
+ where = (f"its centre is {100 * abs(off[0]):.1f} cm {side} of the band's centre line"
283
+ if abs(off[0]) >= 0.0005 else "its centre is on the band's centre line")
284
+ if sk.touched_cube:
285
+ out["failure"] = "touched_cube"
286
+ detail = "The robot touched the cube, which is not allowed."
287
+ elif on_board and b_moved < 0.02:
288
+ out["failure"] = "board_not_moved"
289
+ detail = "The board was not pulled; the cube is still standing on it."
290
+ elif on_board:
291
+ out["failure"] = "rode_along"
292
+ detail = (f"The board was pulled {100 * b_moved:.0f} cm, but the cube rode along on it: it is still on the "
293
+ f"board and moved {100 * moved:.1f} cm toward the robot.")
294
+ elif not upright:
295
+ out["failure"] = "toppled"
296
+ detail = f"The board came out from under the cube, but the cube fell over; {where}."
297
+ elif in_band and on_table and upright:
298
+ out["failure"] = None
299
+ detail = (f"The board came out from under the cube and the cube is standing inside the green band; {where}. "
300
+ f"It moved {100 * moved:.1f} cm toward the robot.")
301
+ else:
302
+ out["failure"] = "missed_band"
303
+ detail = (f"The board came out from under the cube and the cube is standing on the table, but not "
304
+ f"completely inside the green band: {where}. It moved {100 * moved:.1f} cm toward the robot.")
305
+ if rule and not sk.touched_cube:
306
+ out["failure"] = "several_pulls"
307
+ detail = " ".join(rule) + " " + detail
308
+ out["detail"] = detail
309
+ out["detail_indirect"] = (detail.replace("board", "plank").replace("cube", "block")
310
+ .replace("green band", "green stripe").replace("band's", "stripe's"))
311
+ return out
312
+
313
+ def feedback(self, inst, out, level="F2", indirect=False):
314
+ if indirect and level == "F2":
315
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
316
+ return super().feedback(inst, out, level)
317
+
318
+ # ------------------------------------------------------------ scripted execution (cross protocol)
319
+ def execute(self, inst, params):
320
+ """Grasp the handle (jaws across its 4 cm width) and pull the board STROKE m toward the robot at `speed`."""
321
+ sk = self.sk
322
+ b = envs.obj_pos(self.env, BOARD)
323
+ hx, hy = b[0] - B_HALF[0] + H_HALF[0], b[1]
324
+ zg = envs.TABLE_Z + 2 * B_HALF[2] + H_HALF[2]
325
+ sk.set_gripper(False, steps=5)
326
+ sk.move_to([hx, hy, zg + 0.08], yaw=0.0)
327
+ sk.move_to([hx, hy, zg], tol=0.003)
328
+ sk.set_gripper(True, steps=15)
329
+ sk.move_to([hx - STROKE, hy, zg], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), tol=0.01,
330
+ max_steps=300)
331
+ sk.set_gripper(False, steps=8)
332
+ sk.move_to([hx - STROKE, hy, zg + 0.10], speed=0.3)
333
+
334
+ def default_params(self, inst):
335
+ """Prior: the classic tablecloth trick -- yank as fast as the arm can."""
336
+ return dict(speed=0.60)
337
+
338
+ def blind_params(self, inst, attempt, rng):
339
+ return dict(speed=float(np.clip(0.60 + rng.normal(0, 0.06), V_MIN, V_MAX)))
340
+
341
+ def adapt_params(self, inst, history):
342
+ """Bracketing search on the pull speed with the signed displacement error (riding along = far too much
343
+ displacement). Faster -> less displacement."""
344
+ pts = []
345
+ for h in history:
346
+ o = h["outcome"]
347
+ if o.get("failure") in ("rode_along", "board_not_moved"):
348
+ e = 0.10
349
+ elif o.get("failure") in ("touched_cube", "several_pulls"):
350
+ continue
351
+ else:
352
+ e = o["err"]
353
+ pts.append((h["params"]["speed"], e))
354
+ hi_err = [p for p in pts if p[1] > 0] # moved too much -> needs a faster pull
355
+ lo_err = [p for p in pts if p[1] < 0] # moved too little -> needs a slower pull
356
+ if hi_err and lo_err:
357
+ (v0, e0) = max(hi_err, key=lambda p: p[0]) # fastest pull that still moved it too much
358
+ (v1, e1) = min(lo_err, key=lambda p: p[0]) # slowest pull that moved it too little
359
+ if e0 >= 0.05: # rode along: no usable slope -> bisect
360
+ v = 0.5 * (v0 + v1)
361
+ else:
362
+ v = v0 + (v1 - v0) * e0 / (e0 - e1)
363
+ elif hi_err:
364
+ v = max(p[0] for p in hi_err) * 1.25
365
+ else:
366
+ v = min(p[0] for p in lo_err) * 0.8
367
+ return dict(speed=float(np.clip(v, V_MIN, V_MAX)))
368
+
369
+ def oracle_params(self, inst):
370
+ """Privileged: bisection on the speed by simulating pulls with the true mu."""
371
+ if "_oracle_speed" in inst:
372
+ return dict(speed=inst["_oracle_speed"])
373
+ lo, hi = V_MIN, V_MAX
374
+ best = None
375
+ for _ in range(10):
376
+ mid = 0.5 * (lo + hi)
377
+ self.reset_instance(inst)
378
+ self.execute(inst, dict(speed=mid))
379
+ o = self.outcome(inst)
380
+ e = 0.10 if o["failure"] in ("rode_along", "board_not_moved") else o["err"]
381
+ if o["success"]:
382
+ best = (mid, e)
383
+ break
384
+ if best is None or abs(e) < abs(best[1]):
385
+ best = (mid, e)
386
+ if e > 0:
387
+ lo = mid
388
+ else:
389
+ hi = mid
390
+ inst["_oracle_speed"] = best[0]
391
+ self.reset_instance(inst)
392
+ return dict(speed=best[0])
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_false_bottom_lid.py ADDED
@@ -0,0 +1,954 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH false_bottom_lid: open a lidded wooden box, put a tall red block and two blue cubes in, close the lid -- in half
2
+ of the boxes a hidden false bottom makes the box too shallow for the block standing upright, so the lid comes down on
3
+ the block and stays open; the block must be laid on its side.
4
+
5
+ Family: long-horizon common sense + self-disturbance ("state_restoration"): the agent's own normal action (placing the
6
+ block upright, as it was found) makes the last stage (lid closed) impossible; it has to notice the blocked lid, take
7
+ the block out again, lay it down and close the lid (within an attempt), or lay the block down from the start in this
8
+ box (across attempts).
9
+
10
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
11
+ * a wooden box (fixture): outer 20.6 cm (forward-back) x 13.6 cm (left-right) x 9 cm high, walls 0.8 cm; the
12
+ inside is pure black and matte (walls' inner faces, floor and false bottom). The lid (0.6 cm, wood, 0.15 kg) is
13
+ hinged along the box's left or right long edge; a black ball knob sticks out of the middle of the opposite edge.
14
+ Opened past upright the lid falls over to the hinge side and hangs on its stop (182-192 deg) just below
15
+ horizontal beside the box, below every transit;
16
+ * a red block 4 x 4 x 7.5 cm standing upright and two 4 cm blue cubes, in a row in front of the box (robot side),
17
+ on 3 of 4 slots 16 cm apart.
18
+
19
+ Hidden variable: the box's inner depth. With a false bottom (10 of every 20 consecutive seeds) the floor is 4.5 cm
20
+ below the rim instead of 8.4 cm. The outside is identical and the inside is dark: from above (wrist camera) and from
21
+ the far camera the floor height is not readable (measured: renders of the open, empty box with and without the false
22
+ bottom are pixel-identical in both cameras). The Panda hand (21 cm along the finger axis) cannot go below the rim,
23
+ so the fingertips cannot touch the false bottom either. Upright the block is 7.5 cm tall: it fits the deep box (top 0.9 cm
24
+ below the rim) but stands 3 cm above the rim on the false bottom; lying down (4 cm) it fits both.
25
+
26
+ Why the natural action fails: the block is found standing; carried top-down by a gripper that can only turn about the
27
+ vertical, it is naturally put in standing. On a false bottom the closing lid then comes down on the block's top and
28
+ stays open at ~28-41 deg (measured; clearly visible in both cameras). What must be
29
+ learned: take the block out, lay it on its side (tip it over on the table by pushing its upper part with the closed
30
+ fingers, then pick it up lying) and put it in lying (within the attempt), or lay it down before putting it in (across
31
+ attempts).
32
+
33
+ Lid mechanics for agents (inherited from lh_lid_box's `LidSkills`, generalized to a hinge axis along x): while the
34
+ knob is held, a commanded straight move is projected onto the knob's circle around the hinge (at most 1 cm per control
35
+ step), so "up, then over the hinge, release" opens the lid and "up, then away from the hinge, release" closes it.
36
+
37
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (lid closed, all
38
+ three items inside the box below the rim, nothing held, scene static) plus an event log for the server log
39
+ (per-item in_box achieved / lost / restored, lid opened / closed / blocked, red block laid down / stood up); F1 gives
40
+ the agent only success / failure.
41
+ """
42
+ import numpy as np
43
+
44
+ from .. import envs
45
+ from ..bddl import write_bddl
46
+ from ..objects import _SOLID, _fmt, box_xml, register_generated
47
+ from ..skills import Skills
48
+ from ..task_base import LFFTask, register_task
49
+ from .lh_lid_box import SMAX, LidSkills, _fb, _lr
50
+
51
+ # ---------------------------------------------------------------- geometry / physics (box frame: hinge along local y
52
+ # at the local +x edge; the box is turned by +-90 deg so that the hinge runs forward-back on the left or right side)
53
+ BOX = "box_1"
54
+ BOX_MODEL = "lff_fbl_box"
55
+ S_IN, L_IN = 0.120, 0.190 # inner cavity across the hinge (local x -> world y) and along it (local y -> world x);
56
+ # roomy enough that closed fingers (~4 cm out from a held 4 cm item) stay off the walls
57
+ WALL_T, WALL_H, FLOOR_T = 0.008, 0.090, 0.006
58
+ FB_DEPTH = 0.045 # inner depth with the false bottom (floor 4.5 cm above the table)
59
+ LX, LY = S_IN + 2 * WALL_T, L_IN + 2 * WALL_T
60
+ LID_T, LID_MASS = 0.006, 0.15
61
+ KNOB_R, STEM_L = 0.013, 0.032
62
+ HINGE_DAMP, HINGE_FRIC = 0.002, 0.002
63
+ LID_SOLREF, LID_SOLIMP = "0.005 1", "0.99 0.998 0.001"
64
+ BACKOFF = 0.003 # m per control step: a hand pressing on a lid that rests on an item yields
65
+ STOP = (182.0, 192.0) # lid opening stop (deg, uniform): opened, the lid hangs just below horizontal beside the box
66
+ # (free end 6.5-7 cm up), below every transit; at < 180 deg its free end and knob rise to 12-14 cm
67
+ # and a carried item sweeps into them (measured)
68
+ WOOD = (0.55, 0.38, 0.22, 1.0)
69
+ LID_RGBA = (0.70, 0.52, 0.32, 1.0)
70
+ DARK = (0.0, 0.0, 0.0, 1.0) # pure black, matte (no specular): every lit shade is 0, so the floor height is invisible
71
+ KNOB_RGBA = (0.10, 0.10, 0.11, 1.0)
72
+
73
+ RED = "red_block_1"
74
+ BLUES = ("blue_cube_1", "blue_cube_2")
75
+ ITEMS = (RED,) + BLUES
76
+ RED_W, RED_H = 0.040, 0.075
77
+ CUBE_E = 0.040
78
+ RED_DENS, CUBE_DENS = 600.0, 500.0 # 72 g, 32 g
79
+ ITEM_MU = 0.8
80
+ P_FB = 0.5
81
+
82
+ IN_TOL = 0.004 # an item's footprint corners may reach this far past the inner walls (an item leaning on a wall
83
+ # touches it; measured: a cube dropped into the deep box ended tilted 52 deg against the front wall)
84
+ RIM_TOL = 0.004 # item top at most this far above the rim
85
+ LID_CLOSED = np.radians(5.0)
86
+ DEBOUNCE = 6 # predicate checks (every 0.1 s)
87
+ UPRIGHT_COS, LYING_COS = np.cos(np.radians(25.0)), np.cos(np.radians(65.0))
88
+
89
+ Z_CARRY = 0.16 # scripted transit height of the grasp point above the table when carrying an item (Sonnet: 11-20 cm)
90
+ Z_HAND_MIN = WALL_H - 0.024 + 0.006 # lowest grasp point over the box: the Panda hand (2.4 cm above the grasp point, 21 cm
91
+ # along the finger axis) must stay above the rim
92
+ # scripted in-box slots along the box's long axis (u, forward-back, box centre = 0), all at v = 0 (centre line).
93
+ # The lying red block lies across the box (axis left-right) and is held with the fingers closing forward-back, so its
94
+ # slot is 1 cm further in: fingers 4 cm out from its centre stay 1 cm off the back wall (measured: at the upright
95
+ # slot the back finger caught the wall and dropped the block)
96
+ SLOT_U = {"red_upright": -0.0575, "red_lying": -0.0475, "blue_cube_1": 0.005, "blue_cube_2": 0.055}
97
+ START_Y = (-0.24, -0.08, 0.08, 0.24)
98
+ START_X = -0.34
99
+
100
+
101
+ def fb_box_xml(name):
102
+ hx, hy = LX / 2, LY / 2
103
+ col = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)),
104
+ ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)),
105
+ ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)),
106
+ ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)),
107
+ ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))]
108
+ g = []
109
+ # box: contype 2 / conaffinity 1, lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the
110
+ # hinge limit holds it closed) but both collide with the robot, the table and the free items (as in lh_lid_box)
111
+ for k, (pos, s) in enumerate(col):
112
+ g.append(f'<geom name="{name}_w{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(s)}" rgba="{_fmt(WOOD)}" '
113
+ f'friction="0.8 0.005 0.0001" {_SOLID} contype="2" conaffinity="1" group="0"/>')
114
+ fb_top = WALL_H - FB_DEPTH
115
+ fbh = (fb_top - FLOOR_T) / 2
116
+ fb_pos, fb_size = (0, 0, FLOOR_T + fbh), (hx - WALL_T, hy - WALL_T, fbh)
117
+ # the false bottom: always compiled, its collision switched on / off per instance (contype / conaffinity), so no
118
+ # geom moves at runtime and the compiled bounding volumes stay valid (see lh_fence's refit_bvh note)
119
+ g.append(f'<geom name="{name}_fb" type="box" pos="{_fmt(fb_pos)}" size="{_fmt(fb_size)}" rgba="{_fmt(DARK)}" '
120
+ f'friction="0.8 0.005 0.0001" {_SOLID} contype="2" conaffinity="1" group="0"/>')
121
+ th = WALL_T / 2
122
+ vis = [((hx - th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD),
123
+ ((hx - WALL_T + th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK),
124
+ ((-hx + th / 2, 0, WALL_H / 2), (th / 2, hy, WALL_H / 2), WOOD),
125
+ ((-hx + WALL_T - th / 2, 0, WALL_H / 2), (th / 2, hy - th, WALL_H / 2), DARK),
126
+ ((0, hy - th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD),
127
+ ((0, hy - WALL_T + th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK),
128
+ ((0, -hy + th / 2, WALL_H / 2), (hx - th, th / 2, WALL_H / 2), WOOD),
129
+ ((0, -hy + WALL_T - th / 2, WALL_H / 2), (hx - WALL_T, th / 2, WALL_H / 2), DARK),
130
+ ((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2), WOOD),
131
+ ((0, 0, FLOOR_T + 0.0005), (hx - WALL_T, hy - WALL_T, 0.0005), DARK)]
132
+ for p, s, c in vis:
133
+ mat = f' material="{name}_dark"' if c == DARK else ""
134
+ g.append(f'<geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}"{mat} contype="0" conaffinity="0" '
135
+ f'group="1"/>')
136
+ g.append(f'<geom name="{name}_fbvis" type="box" pos="{_fmt(fb_pos)}" size="{_fmt(fb_size)}" rgba="{_fmt(DARK)}" '
137
+ f'material="{name}_dark" contype="0" conaffinity="0" group="1"/>')
138
+ m, L = LID_MASS, LX
139
+ lid_c = (-L / 2, 0, LID_T / 2)
140
+ lid_s = (L / 2, hy, LID_T / 2)
141
+ stem = (-L - STEM_L / 2, 0, LID_T / 2)
142
+ ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2)
143
+ lid = [f'<inertial pos="{_fmt(lid_c)}" mass="{m}" diaginertia="{m * (LY ** 2 + LID_T ** 2) / 12:.6f} '
144
+ f'{m * (L ** 2 + LID_T ** 2) / 12:.6f} {m * (LY ** 2 + L ** 2) / 12:.6f}"/>',
145
+ f'<joint name="{name}_hinge" type="hinge" axis="0 1 0" pos="0 0 0" limited="true" range="0 3.0" '
146
+ f'damping="{HINGE_DAMP}" frictionloss="{HINGE_FRIC}" armature="0.0005"/>',
147
+ # stiffer contacts for the lid plate, and solmix so that they win against the items' (default, soft) ones:
148
+ # with soft contacts an arm pressing the lid down onto the 72 g block pushed the lid through it (measured)
149
+ f'<geom name="{name}_lid" type="box" pos="{_fmt(lid_c)}" size="{_fmt(lid_s)}" rgba="{_fmt(LID_RGBA)}" mass="0" '
150
+ f'friction="0.8 0.005 0.0001" solref="{LID_SOLREF}" solimp="{LID_SOLIMP}" solmix="1000" contype="4" '
151
+ f'conaffinity="1" group="0"/>',
152
+ f'<geom type="box" pos="{_fmt(lid_c)}" size="{_fmt(lid_s)}" rgba="{_fmt(LID_RGBA)}" contype="0" conaffinity="0" group="1"/>',
153
+ f'<geom name="{name}_stem" type="cylinder" pos="{_fmt(stem)}" quat="0.7071 0 0.7071 0" size="0.0045 {STEM_L / 2:.4f}" '
154
+ f'rgba="{_fmt(KNOB_RGBA)}" mass="0" friction="1 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
155
+ f'<geom type="cylinder" pos="{_fmt(stem)}" quat="0.7071 0 0.7071 0" size="0.0045 {STEM_L / 2:.4f}" '
156
+ f'rgba="{_fmt(KNOB_RGBA)}" contype="0" conaffinity="0" group="1"/>',
157
+ f'<geom name="{name}_knob" type="sphere" pos="{_fmt(ball)}" size="{KNOB_R:.4f}" rgba="{_fmt(KNOB_RGBA)}" mass="0" '
158
+ f'friction="1 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
159
+ f'<geom type="sphere" pos="{_fmt(ball)}" size="{KNOB_R:.4f}" rgba="{_fmt(KNOB_RGBA)}" contype="0" conaffinity="0" group="1"/>']
160
+ shell = "\n ".join(g)
161
+ lid_xml = "\n ".join(lid)
162
+ # matte near-black inside (no specular highlight): the floor height is not readable from above
163
+ return f"""<mujoco model="{name}">
164
+ <asset>
165
+ <material name="{name}_dark" rgba="{_fmt(DARK)}" specular="0" shininess="0" reflectance="0"/>
166
+ </asset>
167
+ <worldbody>
168
+ <body>
169
+ <body name="object">
170
+ {shell}
171
+ <body name="lid" pos="{hx:.4f} 0 {WALL_H:.4f}">
172
+ {lid_xml}
173
+ </body>
174
+ </body>
175
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
176
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {WALL_H:.4f}" name="top_site" />
177
+ <site rgba="0 0 0 0" size="0.005" pos="{hx:.4f} {hy:.4f} 0" name="horizontal_radius_site" />
178
+ </body>
179
+ </worldbody>
180
+ </mujoco>"""
181
+
182
+
183
+ class FBLidSkills(LidSkills):
184
+ """LidSkills with the hinge axis in any horizontal direction (here forward-back), plus the task's per-step
185
+ monitor. While the knob is held, the commanded displacement is projected onto the tangent of the knob's circle
186
+ about the hinge (<= SMAX per control step), with radial and axial corrections."""
187
+
188
+ def _hinge_frame(self, e):
189
+ h, a = self.task.hinge_point(), self.task.hinge_axis()
190
+ v = e - h
191
+ al = float(v @ a)
192
+ r = v - al * a
193
+ return a, al, r, max(float(np.linalg.norm(r)), 1e-6)
194
+
195
+ def _act(self, dpos, drot, grip):
196
+ if self.latched:
197
+ e = self.eef_pos()
198
+ if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035:
199
+ self.latched = False # opened, or the knob slipped out of the fingers
200
+ else:
201
+ a, al, r, rn = self._hinge_frame(e)
202
+ t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn # knob motion for an opening lid
203
+ s = float(np.clip(np.asarray(dpos) @ t_open, -SMAX, SMAX))
204
+ if s < 0 and self.task.lid_contacts():
205
+ s = 0.0 # compliant wrist: it does not force the lid down onto an item (else the lid tunnels through it)
206
+ dpos = s * t_open + (self.rad0 - rn) * r / rn + (self.y0 - al) * a
207
+ self.knob_steps += 1
208
+ else:
209
+ p = self.task.robot_lid_contact()
210
+ if p is not None and self.task.lid_contacts():
211
+ # the same limit for a hand pressing on the lid itself: no push towards closing while the lid rests on
212
+ # an item (measured without it: pressing 5 cm "into" a lid lying on the block left the block poking
213
+ # through the lid)
214
+ _, _, r, rn = self._hinge_frame(p)
215
+ t_open = np.cross(self.env.sim.data.xaxis[self.task.jid], r) / rn
216
+ sc = float(np.asarray(dpos) @ t_open)
217
+ if sc < 0: # drop the closing component and yield a little (a force-limited arm gives way)
218
+ dpos = np.asarray(dpos) + (BACKOFF - sc) * t_open
219
+ Skills._act(self, dpos, drot, grip)
220
+ self.task.monitor_step()
221
+
222
+ def set_gripper(self, close, steps=15):
223
+ rep = Skills.set_gripper(self, close, steps)
224
+ if close and self.holding_knob():
225
+ _, al, _, rn = self._hinge_frame(self.eef_pos())
226
+ self.latched, self.rad0, self.y0 = True, rn, al
227
+ self.knob_grasps += 1
228
+ elif not close:
229
+ self.latched = False
230
+ return rep
231
+
232
+
233
+ def _rot(yaw):
234
+ c, s = np.cos(yaw), np.sin(yaw)
235
+ return np.array([[c, -s], [s, c]])
236
+
237
+
238
+ @register_task
239
+ class FalseBottomLid(LFFTask):
240
+ name = "lh_false_bottom_lid"
241
+ level = "L2"
242
+ category = "state_restoration"
243
+ capabilities = ("Perceive", "Reason", "Plan", "Restore")
244
+ protocol = "cross"
245
+ max_attempts = 3
246
+ agent_max_steps = 120 # careful: lid 2 x ~6 + 3 items x ~7 = ~35 commands; laying the block down (tip + pick) ~8;
247
+ # fixing a blocked lid in place (reopen, take out, tip, pick, put in, close) ~30; + looking
248
+ instruction = ("Put the red block and the two blue cubes into the wooden box and close its lid. The lid opens by "
249
+ "lifting the black knob on its edge.")
250
+ instruction_indirect = ("Pack the tall red piece and both small blue cubes into the wooden chest and shut it "
251
+ "(the lid lifts by the black ball on its edge).")
252
+ agent_object_names = ["red block", "blue cube", "blue cube", "wooden box", "lid knob"]
253
+
254
+ # ------------------------------------------------------------ scene
255
+ def make_bddl(self):
256
+ box = register_generated("LffFblBox", fb_box_xml(BOX_MODEL), free=False)
257
+ red = register_generated("LffFblRedBlock", box_xml("lff_fbl_red_block", (RED_W / 2, RED_W / 2, RED_H / 2),
258
+ (0.85, 0.10, 0.08, 1.0), density=RED_DENS,
259
+ friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace(
260
+ 'group="0" />', 'condim="4" group="0" />'))
261
+ objs = [(RED, red, "red_region", (-0.35, -0.25, -0.33, -0.23))]
262
+ for i, n in enumerate(BLUES):
263
+ cat = register_generated(f"LffFblBlueCube{'AB'[i]}",
264
+ box_xml(f"lff_fbl_blue_cube_{'ab'[i]}", (CUBE_E / 2,) * 3, (0.15, 0.30, 0.85, 1.0),
265
+ density=CUBE_DENS, friction=(ITEM_MU, 0.005, 0.0001)).replace(_SOLID, "").replace(
266
+ 'group="0" />', 'condim="4" group="0" />'))
267
+ objs.append((n, cat, f"blue_{'ab'[i]}_region", (-0.35, -0.09 + 0.16 * i, -0.33, -0.07 + 0.16 * i)))
268
+ fx = [(BOX, box, "box_region", (-0.16, -0.01, -0.14, 0.01))]
269
+ return write_bddl(self.name, "put the red block and the blue cubes into the box and close the lid", objs, fx)
270
+
271
+ def __init__(self, cam_res=None):
272
+ super().__init__(cam_res)
273
+ m = self.env.sim.model
274
+ pre = f"{BOX}_{BOX_MODEL}"
275
+ self.jid = m.joint_name2id(pre + "_hinge")
276
+ self.qa = m.jnt_qposadr[self.jid]
277
+ self.dof = m.jnt_dofadr[self.jid]
278
+ self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
279
+ self.knob_geom_name = pre + "_knob"
280
+ self.knob_geom_names = [pre + "_knob", pre + "_stem"]
281
+ self.knob_gid = m.geom_name2id(self.knob_geom_name)
282
+ self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")}
283
+ self.fb_gid = m.geom_name2id(pre + "_fb")
284
+ self.fbvis_gid = m.geom_name2id(pre + "_fbvis")
285
+ self.robot_gids = set(envs.robot_geom_ids(self.env))
286
+ self.item_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in ITEMS}
287
+ self.inst = None
288
+ self.mon = None
289
+
290
+ def sample_instance(self, seed):
291
+ rng = np.random.default_rng(seed)
292
+ bx, by = float(rng.uniform(-0.17, -0.14)), float(rng.uniform(-0.02, 0.02))
293
+ hinge = "left" if rng.random() < 0.5 else "right"
294
+ stop = float(rng.uniform(*STOP))
295
+ perm = rng.permutation(len(START_Y))
296
+ start = {n: [float(START_X + rng.uniform(-0.01, 0.01)), float(START_Y[perm[j]] + rng.uniform(-0.01, 0.01))]
297
+ for j, n in enumerate(ITEMS)}
298
+ start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in ITEMS}
299
+ # balanced blocks like lh_lid_box: exactly 10 of every 20 consecutive seeds have the false bottom
300
+ fb = bool((int(seed) * 7) % 20 < round(20 * P_FB))
301
+ return dict(seed=int(seed), box_xy=[bx, by], hinge=hinge, stop_deg=stop, false_bottom=fb,
302
+ inner_depth_cm=round(100 * (FB_DEPTH if fb else WALL_H - FLOOR_T), 1), start=start,
303
+ start_yaw=start_yaw)
304
+
305
+ def box_yaw(self, inst=None):
306
+ inst = inst or self.inst
307
+ return np.pi / 2 if inst["hinge"] == "left" else -np.pi / 2 # local +x (hinge edge) -> world +y / -y
308
+
309
+ def apply_instance(self, inst):
310
+ self.inst = inst
311
+ m, d = self.env.sim.model, self.env.sim.data
312
+ bx, by = inst["box_xy"]
313
+ yaw = self.box_yaw(inst)
314
+ m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z]
315
+ m.body_quat[self.box_bid] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]
316
+ m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])]
317
+ m.jnt_solref[self.jid] = [0.01, 1.0]
318
+ fb = bool(inst["false_bottom"])
319
+ m.geom_contype[self.fb_gid] = 2 if fb else 0
320
+ m.geom_conaffinity[self.fb_gid] = 1 if fb else 0
321
+ m.geom_rgba[self.fbvis_gid, 3] = 1.0 if fb else 0.0
322
+ d.qpos[self.qa] = 0.0
323
+ d.qvel[self.dof] = 0.0
324
+ for n, xy in inst["start"].items():
325
+ envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n])
326
+ for n in ITEMS:
327
+ envs.set_friction(self.env, n, ITEM_MU)
328
+
329
+ def reset_instance(self, inst, recorder=None):
330
+ self.env.reset()
331
+ self.apply_instance(inst)
332
+ self.env.sim.forward()
333
+ envs.settle(self.env, 10)
334
+ self.mon = None
335
+ self.sk = FBLidSkills(self.env, self, recorder=recorder)
336
+ self._init_monitor()
337
+ return self.sk
338
+
339
+ # ------------------------------------------------------------ geometry helpers
340
+ def floor_z(self):
341
+ """height of the surface items rest on inside the box (world z)"""
342
+ return envs.TABLE_Z + ((WALL_H - FB_DEPTH) if self.inst["false_bottom"] else FLOOR_T)
343
+
344
+ def rim_z(self):
345
+ return envs.TABLE_Z + WALL_H
346
+
347
+ def long_axis(self):
348
+ """unit vector (world xy) along the box's long side (= the hinge axis), pointing forward"""
349
+ return np.array([1.0, 0.0])
350
+
351
+ def to_box(self, xy):
352
+ """world xy -> box frame (u along the long side / forward, v across / left)"""
353
+ return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"])
354
+
355
+ def from_box(self, uv):
356
+ return np.asarray(self.inst["box_xy"]) + np.asarray(uv, float)
357
+
358
+ def hinge_sign(self):
359
+ return 1.0 if self.inst["hinge"] == "left" else -1.0
360
+
361
+ def hinge_point(self):
362
+ bx, by = self.inst["box_xy"]
363
+ return np.array([bx, by + self.hinge_sign() * LX / 2, envs.TABLE_Z + WALL_H])
364
+
365
+ def hinge_axis(self):
366
+ return np.array([1.0, 0.0, 0.0])
367
+
368
+ def lid_q(self):
369
+ return float(self.env.sim.data.qpos[self.qa])
370
+
371
+ def lid_deg(self):
372
+ return float(np.degrees(self.lid_q()))
373
+
374
+ def knob_xyz(self):
375
+ return self.env.sim.data.geom_xpos[self.knob_gid].copy()
376
+
377
+ def held(self, name):
378
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
379
+
380
+ def item_axis(self, name):
381
+ """body z axis in world (the red block's long axis)"""
382
+ return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)[:, 2].copy()
383
+
384
+ def red_pose(self):
385
+ c = abs(float(self.item_axis(RED)[2]))
386
+ return "upright" if c >= UPRIGHT_COS else "lying" if c <= LYING_COS else "tilted"
387
+
388
+ def in_cavity_xy(self, name):
389
+ """the item's whole footprint (its collision box corners, also when tilted) inside the inner walls"""
390
+ m, d = self.env.sim.model, self.env.sim.data
391
+ g = next(iter(self.item_gids[name]))
392
+ R = d.geom_xmat[g].reshape(3, 3)
393
+ half = m.geom_size[g][:3]
394
+ c = self.to_box(d.geom_xpos[g][:2])
395
+ ext = np.abs(R[:2, :]) @ half # world-axis half extents of the footprint
396
+ lim = np.array([L_IN / 2, S_IN / 2]) + IN_TOL
397
+ return bool(np.all(np.abs(c) + ext <= lim))
398
+
399
+ def in_box(self, name):
400
+ return bool(self.in_cavity_xy(name) and envs.obj_max_z(self.env, name) <= self.rim_z() + RIM_TOL
401
+ and envs.obj_min_z(self.env, name) >= envs.TABLE_Z + FLOOR_T - 0.005 and not self.held(name))
402
+
403
+ def over_box(self, name):
404
+ """centre above the cavity (in it, or standing in it but sticking out)"""
405
+ c = self.to_box(envs.obj_pos(self.env, name)[:2])
406
+ return bool(abs(c[0]) <= L_IN / 2 and abs(c[1]) <= S_IN / 2)
407
+
408
+ def lid_closed(self):
409
+ return self.lid_q() <= LID_CLOSED
410
+
411
+ def lid_contacts(self):
412
+ """items the lid touches now"""
413
+ d = self.env.sim.data
414
+ out = set()
415
+ for i in range(d.ncon):
416
+ c = d.contact[i]
417
+ for n in ITEMS:
418
+ g = self.item_gids[n]
419
+ if (c.geom1 in g and c.geom2 in self.lid_gids) or (c.geom2 in g and c.geom1 in self.lid_gids):
420
+ out.add(n)
421
+ return out
422
+
423
+ def robot_lid_contact(self):
424
+ """world position of a robot-lid contact (None if the robot does not touch the lid)"""
425
+ d = self.env.sim.data
426
+ for i in range(d.ncon):
427
+ c = d.contact[i]
428
+ if (c.geom1 in self.robot_gids and c.geom2 in self.lid_gids) or (c.geom2 in self.robot_gids
429
+ and c.geom1 in self.lid_gids):
430
+ return np.array(c.pos, float)
431
+ return None
432
+
433
+ def robot_touching(self):
434
+ """'lid' / item names the robot is in contact with now (finishing while pressing the lid down does not count)"""
435
+ d = self.env.sim.data
436
+ out = set()
437
+ for i in range(d.ncon):
438
+ c = d.contact[i]
439
+ g1, g2 = c.geom1, c.geom2
440
+ for a, b in ((g1, g2), (g2, g1)):
441
+ if a in self.robot_gids:
442
+ if b in self.lid_gids:
443
+ out.add("lid")
444
+ for n in ITEMS:
445
+ if b in self.item_gids[n]:
446
+ out.add("red block" if n == RED else "blue cube")
447
+ return sorted(out)
448
+
449
+ def stage_values(self):
450
+ v = {f"{n}_in_box": self.in_box(n) for n in ITEMS}
451
+ v["lid_closed"] = self.lid_closed()
452
+ return v
453
+
454
+ # ------------------------------------------------------------ per-step monitor
455
+ def _init_monitor(self):
456
+ self.mon = dict(state={f"{n}_in_box": False for n in ITEMS}, ever=set(), lost=set(), events=[],
457
+ last_touch={n: None for n in ITEMS}, step=0, lid_opened=False, lid_open_max=0.0,
458
+ lid_prev=0.0, lid_still=0, blocked_now=False, n_blocked=0, blocked_max_deg=0.0,
459
+ red_pose=self.red_pose(), red_pose_cand=None, red_pose_n=0, red_up_in_box=False,
460
+ red_relaid=0, closes=0, cand={f"{n}_in_box": 0 for n in ITEMS})
461
+
462
+ def _touches(self):
463
+ d = self.env.sim.data
464
+ out = {}
465
+ for i in range(d.ncon):
466
+ c = d.contact[i]
467
+ for n in ITEMS:
468
+ g = self.item_gids[n]
469
+ other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None)
470
+ if other is None:
471
+ continue
472
+ if other in self.lid_gids:
473
+ out[n] = "lid"
474
+ elif other in self.robot_gids and out.get(n) != "lid":
475
+ out[n] = "robot"
476
+ return out
477
+
478
+ def monitor_step(self):
479
+ mon = self.mon
480
+ if mon is None:
481
+ return
482
+ mon["step"] += 1
483
+ step = self.sk.n_steps if self.sk is not None else mon["step"]
484
+ for n, who in self._touches().items():
485
+ mon["last_touch"][n] = (who, step)
486
+ q = self.lid_deg()
487
+ mon["lid_open_max"] = max(mon["lid_open_max"], q)
488
+ if not mon["lid_opened"] and q > 90.0:
489
+ mon["lid_opened"] = True
490
+ mon["blocked_now"] = False
491
+ mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical"))
492
+ elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED):
493
+ mon["lid_opened"] = False
494
+ mon["closes"] += 1
495
+ mon["events"].append(dict(step=step, pred="lid", ev="closed"))
496
+ # lid blocked: it came down from past vertical and rests (not held) on an item at 5-80 deg for 1 s
497
+ if abs(q - mon["lid_prev"]) < 0.05:
498
+ mon["lid_still"] += 1
499
+ else:
500
+ mon["lid_still"] = 0
501
+ mon["lid_prev"] = q
502
+ if mon["lid_opened"] and not mon["blocked_now"] and 5.0 < q < 80.0 and mon["lid_still"] >= 20 \
503
+ and not self.sk.latched:
504
+ on = sorted(self.lid_contacts())
505
+ if on:
506
+ mon["blocked_now"] = True
507
+ mon["n_blocked"] += 1
508
+ mon["blocked_max_deg"] = max(mon["blocked_max_deg"], q)
509
+ mon["events"].append(dict(step=step, pred="lid", ev="lid_blocked", lid_deg=round(q, 1), on=on,
510
+ red_pose=self.red_pose()))
511
+ if mon["blocked_now"] and q > 90.0:
512
+ mon["blocked_now"] = False
513
+ if mon["step"] % 2:
514
+ return # predicates every other control step (0.1 s)
515
+ # red block pose (debounced 1 s): upright <-> lying
516
+ p = self.red_pose()
517
+ if p != "tilted" and p != mon["red_pose"]:
518
+ if mon["red_pose_cand"] == p:
519
+ mon["red_pose_n"] += 1
520
+ else:
521
+ mon["red_pose_cand"], mon["red_pose_n"] = p, 1
522
+ if mon["red_pose_n"] >= 10 and not self.held(RED):
523
+ where = "box" if self.over_box(RED) else "table"
524
+ lt = mon["last_touch"][RED]
525
+ cause = lt[0] if lt is not None and step - lt[1] <= 60 else "other"
526
+ ev = "item_relaid" if p == "lying" else "stood_up"
527
+ if p == "lying":
528
+ mon["red_relaid"] += 1
529
+ mon["events"].append(dict(step=step, pred="red_pose", ev=ev, where=where, cause=cause))
530
+ mon["red_pose"] = p
531
+ mon["red_pose_cand"] = None
532
+ else:
533
+ mon["red_pose_cand"] = None
534
+ if not mon["red_up_in_box"] and mon["red_pose"] == "upright" and self.over_box(RED) and not self.held(RED) \
535
+ and envs.obj_min_z(self.env, RED) < self.rim_z():
536
+ mon["red_up_in_box"] = True
537
+ top = envs.obj_max_z(self.env, RED) - self.rim_z()
538
+ mon["events"].append(dict(step=step, pred="red_pose", ev="placed_upright_in_box",
539
+ top_above_rim_cm=round(100 * top, 1)))
540
+ for n in ITEMS: # debounced: a change counts after it held for DEBOUNCE checks (fingers rubbing a released item)
541
+ key = f"{n}_in_box"
542
+ now = self.in_box(n)
543
+ if now == mon["state"][key]:
544
+ mon["cand"][key] = 0
545
+ continue
546
+ mon["cand"][key] += 1
547
+ if mon["cand"][key] >= DEBOUNCE:
548
+ mon["cand"][key] = 0
549
+ self._event(key, now, step, n)
550
+
551
+ def _event(self, key, now, step, name):
552
+ mon = self.mon
553
+ mon["state"][key] = now
554
+ if now:
555
+ ev = "restored" if key in mon["lost"] else "achieved"
556
+ mon["ever"].add(key)
557
+ mon["lost"].discard(key)
558
+ e = dict(step=step, pred=key, ev=ev)
559
+ if name == RED:
560
+ e["red_pose"] = self.red_pose()
561
+ mon["events"].append(e)
562
+ return
563
+ if key not in mon["ever"]:
564
+ return # never achieved: nothing lost
565
+ cause = "other"
566
+ if self.held(name):
567
+ cause = "picked_up"
568
+ else:
569
+ lt = mon["last_touch"][name]
570
+ if lt is not None and step - lt[1] <= 60:
571
+ cause = lt[0]
572
+ mon["lost"].add(key)
573
+ mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1)))
574
+
575
+ # ------------------------------------------------------------ outcome
576
+ def _static(self):
577
+ d = self.env.sim.data
578
+ for n in ITEMS:
579
+ _, da = envs.free_joint_addr(self.env, n)
580
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
581
+ return False
582
+ return abs(float(d.qvel[self.dof])) < 0.2
583
+
584
+ def _where(self, name):
585
+ """F2-style location of an item relative to the box, robot-centric words"""
586
+ rel = self.to_box(envs.obj_pos(self.env, name)[:2])
587
+ return f"{_fb(rel[0])} and {_lr(rel[1])} of the box's centre"
588
+
589
+ def outcome(self, inst):
590
+ envs.settle(self.env, 30)
591
+ mon = self.mon
592
+ vals = self.stage_values()
593
+ static = self._static()
594
+ held = [n for n in ITEMS if self.held(n)]
595
+ touching = self.robot_touching()
596
+ success = bool(all(vals.values()) and static and not held and not touching)
597
+ regress = [e for e in mon["events"] if e["ev"] == "lost"]
598
+ restored = [e for e in mon["events"] if e["ev"] == "restored"]
599
+ on = sorted(self.lid_contacts())
600
+ red_top = envs.obj_max_z(self.env, RED) - self.rim_z()
601
+ parts = []
602
+ failure = None
603
+ if success:
604
+ parts.append("The red block and both blue cubes are inside the box and the lid is closed.")
605
+ else:
606
+ out_items = [n for n in ITEMS if not vals[f"{n}_in_box"]]
607
+ if not vals["lid_closed"] and on:
608
+ failure = "lid_blocked"
609
+ elif held:
610
+ failure = "held"
611
+ elif touching and all(vals.values()):
612
+ failure = "robot_touching"
613
+ elif out_items:
614
+ failure = ("red_sticks_out" if out_items == [RED] and self.over_box(RED) and red_top > RIM_TOL
615
+ else "item_not_in_box")
616
+ elif not vals["lid_closed"]:
617
+ failure = "lid_open"
618
+ else:
619
+ failure = "not_static"
620
+ if not vals["lid_closed"]:
621
+ txt = f"The lid is not closed (open {self.lid_deg():.0f} degrees)"
622
+ if on:
623
+ names = " and ".join("the red block" if n == RED else "a blue cube" for n in on)
624
+ txt += f": it rests on {names}"
625
+ parts.append(txt + ".")
626
+ for n in out_items:
627
+ nm = "The red block" if n == RED else "A blue cube"
628
+ if self.held(n):
629
+ parts.append(f"{nm} is still held by the gripper.")
630
+ elif self.over_box(n) and envs.obj_max_z(self.env, n) > self.rim_z() + RIM_TOL:
631
+ top = envs.obj_max_z(self.env, n) - self.rim_z()
632
+ pose = self.red_pose() if n == RED else "resting"
633
+ parts.append(f"{nm} is in the box but sticks out {100 * top:.1f} cm above the rim ({pose}).")
634
+ else:
635
+ parts.append(f"{nm} is not in the box: its centre is {self._where(n)}.")
636
+ if touching and all(vals.values()):
637
+ parts.append("The robot was still pressing on the " + " and ".join(touching) + " at the end.")
638
+ if not static and all(vals.values()):
639
+ parts.append("Something was still moving at the end.")
640
+ if mon["n_blocked"]:
641
+ parts.append(f"The lid came down on an item {mon['n_blocked']} time(s) during the attempt.")
642
+ out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching,
643
+ events=mon["events"], n_regressions=len(regress), n_restored=len(restored),
644
+ false_bottom=bool(inst["false_bottom"]), n_lid_blocked=mon["n_blocked"],
645
+ lid_blocked_max_deg=round(mon["blocked_max_deg"], 1), red_relaid=mon["red_relaid"],
646
+ red_placed_upright_in_box=mon["red_up_in_box"], red_pose=self.red_pose(),
647
+ red_top_above_rim_cm=round(100 * red_top, 1), lid_on=on,
648
+ lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1),
649
+ lid_closes=mon["closes"], knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps,
650
+ detail=" ".join(parts))
651
+ return out
652
+
653
+ # ------------------------------------------------------------ scripted primitives (perfect perception)
654
+ def _settle_item(self, name, max_checks=20):
655
+ """keep the arm still until `name` has stopped moving (a tipped block rolls on for a moment)"""
656
+ d = self.env.sim.data
657
+ _, da = envs.free_joint_addr(self.env, name)
658
+ for _ in range(max_checks):
659
+ if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
660
+ return
661
+ self.sk.hold(2)
662
+
663
+ def _grasp_yaw(self, name):
664
+ """fingers across a 4 cm side: for the lying red block across its long axis, else yaw mod 90 deg"""
665
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
666
+ if name == RED and self.red_pose() != "upright":
667
+ ax = R[:, 2]
668
+ yaw = float(np.arctan2(ax[1], ax[0])) # closing direction (-sin, cos) is then across the long axis
669
+ return float((yaw + np.pi / 2) % np.pi - np.pi / 2)
670
+ i = int(np.argmin(np.abs(R[2])))
671
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
672
+ return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
673
+
674
+ def _grasp_z(self, name):
675
+ """grasp point height above the table for a top-down grasp of `name` where it is"""
676
+ zmin = envs.obj_min_z(self.env, name) - envs.TABLE_Z
677
+ zmax = envs.obj_max_z(self.env, name) - envs.TABLE_Z
678
+ if name == RED and self.red_pose() == "upright":
679
+ z = zmin + 0.0425 # 4.25 cm up the 7.5 cm block (0.5 cm above its centre)
680
+ else:
681
+ z = (zmin + zmax) / 2
682
+ if self.over_box(name): # the hand (2.4 cm above the grasp point) stays above the rim
683
+ z = max(z, Z_HAND_MIN, WALL_H + 0.016 if zmax > WALL_H + 0.02 else 0.0)
684
+ z = min(z, zmax - 0.004)
685
+ return z
686
+
687
+ def pick(self, name, z_carry=Z_CARRY, tries=2):
688
+ """top-down grasp of `name` where it is, lift to z_carry (a missed grasp is retried once, as anyone would);
689
+ returns the grasp point's height above the item's bottom, or None if the grasp failed"""
690
+ sk = self.sk
691
+ Z = envs.TABLE_Z
692
+ for _ in range(tries):
693
+ self._settle_item(name)
694
+ p = envs.obj_pos(self.env, name)
695
+ yaw = self._grasp_yaw(name)
696
+ zg = self._grasp_z(name)
697
+ zbot = envs.obj_min_z(self.env, name) - Z
698
+ sk.set_gripper(False, steps=8)
699
+ sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw)
700
+ sk.hold(8) # let a large wrist turn settle before going down (else the hand drifts ~1 cm near the table)
701
+ sk.move_to([p[0], p[1], Z + zg], tol=0.003, max_steps=120)
702
+ sk.set_gripper(True, steps=15)
703
+ sk.move_to([p[0], p[1], Z + z_carry], speed=0.3)
704
+ if self.held(name):
705
+ return zg - zbot
706
+ sk.set_gripper(False, steps=8)
707
+ return None
708
+
709
+ def place(self, dest_xy, z_rel, yaw, z_carry=Z_CARRY):
710
+ """carry to above dest at z_carry, lower to z_rel (or until the item / hand rests on something), release, lift"""
711
+ sk = self.sk
712
+ Z = envs.TABLE_Z
713
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=yaw)
714
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003, max_steps=80)
715
+ sk.set_gripper(False, steps=12)
716
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry])
717
+
718
+ def put_in_box(self, name, u, v=0.0, noise=None, z_carry=Z_CARRY):
719
+ """pick `name` as it is (the red block upright or lying) and lower it into the box at (u, v) (box frame) as if
720
+ the box were deep (the hand stops above the rim), release. The lying red block is turned across the box."""
721
+ off = self.pick(name, z_carry=z_carry)
722
+ if off is None:
723
+ return False
724
+ yaw = np.pi / 2 if name == RED and self.red_pose() == "lying" else self.sk.yaw
725
+ d = self.from_box([u, v]) + (np.asarray(noise, float) if noise is not None else 0.0)
726
+ self.place(d, max(Z_HAND_MIN, FLOOR_T + off + 0.005), yaw, z_carry=z_carry)
727
+ return True
728
+
729
+ def red_slot(self):
730
+ return SLOT_U["red_lying"] if self.red_pose() == "lying" else SLOT_U["red_upright"]
731
+
732
+ def tip_over(self, name, direction, z_push=0.055, speed=0.10):
733
+ """push the standing item's upper part with the closed fingers along `direction` (xy) so that it falls over"""
734
+ sk = self.sk
735
+ Z = envs.TABLE_Z
736
+ d = np.asarray(direction, float)
737
+ d = d / np.linalg.norm(d)
738
+ p = envs.obj_pos(self.env, name)
739
+ s = p[:2] - d * 0.06
740
+ e = p[:2] + d * 0.035
741
+ yaw = float(np.arctan2(d[1], d[0])) - np.pi / 2 # finger closing direction along the push
742
+ sk.set_gripper(True, steps=8)
743
+ sk.move_to([s[0], s[1], Z + 0.13], yaw=yaw)
744
+ sk.move_to([s[0], s[1], Z + z_push], tol=0.004)
745
+ sk.move_to([e[0], e[1], Z + z_push], speed=speed, tol=0.006)
746
+ sk.move_to([e[0], e[1], Z + 0.13], speed=0.3)
747
+ self._settle_item(name)
748
+ return self.red_pose() if name == RED else None
749
+
750
+ def _tip_direction(self, name):
751
+ """outward along y (away from the other items, which stand 16 cm apart in a row)"""
752
+ y = envs.obj_pos(self.env, name)[1]
753
+ return np.array([0.0, 1.0 if y >= 0 else -1.0])
754
+
755
+ def lay_down(self, name=RED, **kw):
756
+ """tip the standing block over on the table (up to two pushes); True if it lies"""
757
+ for _ in range(2):
758
+ if self.red_pose() == "lying":
759
+ return True
760
+ self.tip_over(name, self._tip_direction(name), **kw)
761
+ return self.red_pose() == "lying"
762
+
763
+ def take_out_red(self):
764
+ """pick the red block out of the box and stand it on its start spot"""
765
+ off = self.pick(RED)
766
+ if off is None:
767
+ return False
768
+ self.place(self.inst["start"][RED], off + 0.004, self.sk.yaw)
769
+ self._settle_item(RED)
770
+ return True
771
+
772
+ def _grasp_knob(self, yaw=-np.pi / 2):
773
+ """open the fingers, come down on the knob at wrist yaw -90 deg (fingers across the stem), close. Always -90
774
+ (not its gripper-symmetric twin +90): with the lid hanging on its stop beside the box the arm reached the knob
775
+ at -90 in every instance, but at +90 it stopped 2-3 cm short against the lid (validate seed 1004: the lying
776
+ block's grasp yaw had landed on +90 by numerical chance and the final close missed the knob twice). A 180 deg
777
+ wrist turn is avoided by passing through yaw 0 (see Skills.wrap_yaw)."""
778
+ sk = self.sk
779
+ k = self.knob_xyz()
780
+ for attempt in range(2):
781
+ sk.set_gripper(False, steps=8)
782
+ if abs(sk.yaw - yaw) > np.pi / 2 + 0.1:
783
+ sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0, wrap_yaw=False)
784
+ sk.move_to([k[0], k[1], k[2] + 0.08], yaw=yaw, wrap_yaw=False)
785
+ sk.hold(5)
786
+ sk.move_to([k[0], k[1], k[2]], tol=0.003)
787
+ sk.set_gripper(True, steps=15)
788
+ if sk.holding_knob() or attempt:
789
+ break
790
+ # missed (measured once in 40 validation attempts: after a long sequence of wrist turns the arm's posture
791
+ # had drifted and it stopped 3-4 cm short of the knob hanging far to the side): open, go back to a neutral
792
+ # pose over the box at yaw 0 (the OSC's null-space term straightens the arm there) and try once more
793
+ sk.set_gripper(False, steps=8)
794
+ e = sk.eef_pos()
795
+ sk.move_to([e[0], e[1], e[2] + 0.10])
796
+ c = self.from_box([0.0, 0.0])
797
+ sk.move_to([c[0], c[1], envs.TABLE_Z + 0.28], yaw=0.0, wrap_yaw=False)
798
+ sk.hold(10)
799
+ return k
800
+
801
+ def open_lid(self, over=0.04, up=0.16):
802
+ """grasp the knob (fingers across its stem); straight up 10 cm; straight to `over` m beyond the hinge, `up` m
803
+ above it; release; lift"""
804
+ sk = self.sk
805
+ k = self._grasp_knob()
806
+ h = self.hinge_point()
807
+ sg = self.hinge_sign()
808
+ sk.move_to([k[0], k[1], k[2] + 0.10])
809
+ sk.move_to([h[0], h[1] + sg * over, h[2] + up])
810
+ sk.set_gripper(False, steps=10)
811
+ e = sk.eef_pos()
812
+ sk.move_to([e[0], e[1] - sg * 0.04, e[2] + 0.05])
813
+ sk.hold(25)
814
+
815
+ def close_lid(self, away=0.08, up=0.10):
816
+ """grasp the knob where it is; straight up 10 cm; straight to `away` m on the knob side of the hinge; release"""
817
+ sk = self.sk
818
+ k = self._grasp_knob()
819
+ h = self.hinge_point()
820
+ sg = self.hinge_sign()
821
+ sk.move_to([k[0], k[1], k[2] + up])
822
+ sk.move_to([h[0], h[1] - sg * away, max(k[2], h[2]) + up])
823
+ sk.set_gripper(False, steps=10)
824
+ e = sk.eef_pos()
825
+ sk.move_to([e[0], e[1], e[2] + 0.06])
826
+ sk.hold(30)
827
+
828
+ def press_lid(self):
829
+ """the natural retry when the lid did not shut: grasp the knob where it is and push it down towards closed"""
830
+ sk = self.sk
831
+ k = self._grasp_knob()
832
+ h = self.hinge_point()
833
+ sg = self.hinge_sign()
834
+ sk.move_to([k[0], h[1] - sg * (LX + 0.01), h[2] - 0.01], speed=0.1)
835
+ sk.set_gripper(False, steps=10)
836
+ e = sk.eef_pos()
837
+ sk.move_to([e[0], e[1], e[2] + 0.08])
838
+ sk.hold(30)
839
+
840
+ def _fallen(self):
841
+ """items that ended up outside the box (not merely sticking out of it)"""
842
+ return [n for n in ITEMS if not self.in_box(n) and not self.over_box(n) and not self.held(n)]
843
+
844
+ def _replace_fallen(self, done, noise=None, z_carry=Z_CARRY):
845
+ for n in [n for n in self._fallen() if n in done]:
846
+ self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=(noise or {}).get(n), z_carry=z_carry)
847
+
848
+ # ------------------------------------------------------------ scripted policies
849
+ def execute(self, inst, params):
850
+ noise = params.get("noise") or {}
851
+ zc = params.get("z_carry", Z_CARRY)
852
+ self.open_lid(**params.get("open", {}))
853
+ done = []
854
+ for n in ITEMS:
855
+ if n == RED and params.get("lay_first"):
856
+ self.lay_down(RED)
857
+ self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n], noise=noise.get(n), z_carry=zc)
858
+ done.append(n)
859
+ self._replace_fallen(done, noise, zc) # looks after every step: re-places an item that fell outside
860
+ self.close_lid(**params.get("close", {}))
861
+ if params.get("check") == "naive":
862
+ self.naive_check(noise, zc)
863
+ elif params.get("check") == "fix":
864
+ self.check_and_fix()
865
+ self.sk.hold(10)
866
+
867
+ def naive_check(self, noise=None, z_carry=Z_CARRY):
868
+ """Sonnet-like look before finishing, without the insight: a lid that did not shut is pushed down once (re-closed
869
+ if it is still open past upright); an item outside the box is put back as it is (the red block upright)"""
870
+ if not self.lid_closed():
871
+ if self.lid_deg() > 90:
872
+ self.close_lid()
873
+ else:
874
+ self.press_lid()
875
+ if self._fallen():
876
+ if self.lid_deg() < 90:
877
+ self.open_lid()
878
+ self._replace_fallen(list(ITEMS), noise, z_carry)
879
+ self.close_lid()
880
+
881
+ def check_and_fix(self, rounds=2):
882
+ """look at every stage; if the red block is not inside below the rim (it stands up out of a shallow box and
883
+ holds the lid open), take it out, lay it down on the table and put it in lying; re-place anything outside the
884
+ box; close the lid"""
885
+ for _ in range(rounds):
886
+ v = self.stage_values()
887
+ if all(v.values()) and not any(self.held(n) for n in ITEMS):
888
+ return True
889
+ bad = [n for n in ITEMS if not v[f"{n}_in_box"]]
890
+ if self.lid_deg() < 90 and (bad or self.lid_contacts()):
891
+ self.open_lid()
892
+ for n in bad:
893
+ if n == RED and self.red_pose() != "lying":
894
+ if self.over_box(RED):
895
+ self.take_out_red()
896
+ self.lay_down(RED)
897
+ self.put_in_box(n, self.red_slot() if n == RED else SLOT_U[n])
898
+ if self.lid_deg() > 90 or not self.lid_closed():
899
+ self.close_lid()
900
+ return all(self.stage_values().values())
901
+
902
+ def default_params(self, inst):
903
+ """Sonnet-like: open the lid, items in the listed order, each put in as found (the block upright), carried
904
+ 16 cm up, looks after every step (re-places an item that fell outside), closes the lid, pushes a lid that did
905
+ not shut down once, finishes"""
906
+ return dict(lay_first=False, check="naive")
907
+
908
+ def oracle_params(self, inst):
909
+ """knows the inner depth: lays the block down first in a shallow box; checks every stage at the end"""
910
+ return dict(lay_first=bool(inst["false_bottom"]), check="fix")
911
+
912
+ def adapt_params(self, inst, history):
913
+ """attempt >= 2 (after a failure): lay the block down before putting it in, then check and fix"""
914
+ return dict(lay_first=True, check="fix")
915
+
916
+ def blind_params(self, inst, attempt, rng):
917
+ """the natural behaviour again with small random variations, no history"""
918
+ return dict(lay_first=False, check="naive",
919
+ noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS},
920
+ z_carry=float(rng.uniform(0.13, 0.19)),
921
+ open=dict(over=float(rng.uniform(0.02, 0.06)), up=float(rng.uniform(0.14, 0.18))),
922
+ close=dict(away=float(rng.uniform(0.06, 0.10))))
923
+
924
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
925
+ """oracle / naive: one attempt; adaptive: attempt 1 = the natural placement plus a real check and fix (takes the
926
+ block out and lays it down when the lid is blocked), later attempts lay it down first; blind: natural with
927
+ random variations; switch (extra control): natural, then lay it down first from attempt 2, no real check"""
928
+ k = k or self.max_attempts
929
+ rng = np.random.default_rng(seed)
930
+ history = []
931
+ for a in range(k):
932
+ self.reset_instance(inst)
933
+ if kind == "oracle":
934
+ params = self.oracle_params(inst)
935
+ elif kind == "naive":
936
+ params = self.default_params(inst)
937
+ elif kind == "adaptive":
938
+ params = dict(lay_first=False, check="fix") if a == 0 else self.adapt_params(inst, history)
939
+ elif kind == "blind":
940
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
941
+ elif kind == "switch":
942
+ params = self.default_params(inst) if a == 0 else dict(lay_first=True, check="naive")
943
+ elif kind == "oracle_noise": # robustness check: oracle with +-5 mm placement noise
944
+ params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in ITEMS})
945
+ else:
946
+ raise ValueError(kind)
947
+ self.execute(inst, params)
948
+ out = self.outcome(inst)
949
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
950
+ if on_attempt:
951
+ on_attempt(a, params, out)
952
+ if out["success"] or kind in ("oracle", "naive", "oracle_noise"):
953
+ break
954
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_lid_box.py ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH lid_box: put three blocks on their marks, then open a box, put a red cube in, close it -- the lid falls open onto
2
+ the marks behind the box and shoves the blocks standing there off their marks.
3
+
4
+ Family: long-horizon self-disturbance ("state_restoration"): the agent's own normal later-stage action (opening the
5
+ lid) physically breaks earlier progress (blocks on marks); it has to notice and restore it before finishing (within an
6
+ attempt), or learn to open the box first (across attempts; the final-state judge does not enforce an order).
7
+
8
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
9
+ * a flat wooden box (fixture, 12 x 16 cm, walls 3.2 cm, lid 0.6 cm) whose lid is hinged along its far edge; a black
10
+ ball knob sticks out of the middle of the lid's front edge. The lid is heavy (0.3 kg) and has no damping: once it
11
+ is lifted past vertical it falls backward and comes to rest on a stop (hidden angle) or on whatever is behind the
12
+ box;
13
+ * three 6 cm cubes ("blocks", blue / green / yellow; light, 54 g, and slippery, mu 0.25) in a row in front of the box
14
+ together with a small red cube (2.2 cm);
15
+ * three square marks (7.6 cm, outline + light fill) in the blocks' colours: two right behind the box (their near
16
+ edge 0.2-1.7 cm from the box's back wall), one beside the box.
17
+
18
+ Hidden variable: the lid's opening stop (0 = closed, 90 = upright, 180 = flat behind the box): "far", uniform in FAR
19
+ (138-165 deg), in 13 of every 20 consecutive seeds, else "near", uniform in NEAR (100-113 deg). Before the lid is opened
20
+ nothing shows it. A far lid lands on the top edge of the blocks standing behind the box and its weight shoves them
21
+ away from the robot ("forward") off their marks (measured: 4-10 cm); a near lid comes to rest above them. Stops of
22
+ ~115-135 deg are left out on purpose: there the lid only grazes the blocks (1-3 cm, right at the tolerance).
23
+
24
+ Why the natural order fails: the instruction lists the blocks first (as a user would), so the natural plan places the
25
+ blocks, opens the lid (it falls back onto them), puts the cube in, closes the lid and finishes without looking at the
26
+ marks again. What must be learned: re-check every stage before finishing and put knocked blocks back after closing the
27
+ lid (within the attempt), or open the box first / place the blocks behind it last (across attempts).
28
+
29
+ Lid mechanics for agents (`LidSkills`, measured, see the task card): grasping the ball knob from above (fingers on its
30
+ left and right, the default yaw) makes a pivot -- the ball turns freely between the fingers about the hinge axis. While
31
+ the knob is held, the arm is compliant along the hinge constraint: a commanded straight move is projected onto the
32
+ knob's circle around the hinge (at most 1 cm per control step; ~0.07 m/s along the arc in the agent self-test), so
33
+ "up 10 cm, then back over the hinge, release" opens the lid and "up, then forward, release" closes it; a move that
34
+ makes no more progress ends early (like KeySkills' stalling wrist in l7_key_turn). Without the compliance, all 6
35
+ typical straight-move sequences tried (prototype: this lid with a 2 cm stem, 2026-10-09) pulled the knob out of the
36
+ fingers and the lid fell shut; with an earlier, lighter lid only a 3-segment approximation of the arc opened it.
37
+
38
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (all blocks on
39
+ their marks, red cube in the box, lid closed, nothing held, scene static) plus an event log of every stage predicate
40
+ (achieved / lost / restored, with step and cause) for the server log; F1 gives the agent only success / failure.
41
+ """
42
+ import numpy as np
43
+
44
+ from .. import envs
45
+ from ..bddl import write_bddl
46
+ from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated
47
+ from ..skills import DT, Skills, _rot_err
48
+ from ..task_base import LFFTask, register_task
49
+
50
+ # ---------------------------------------------------------------- geometry / physics
51
+ BOX = "box_1"
52
+ BOX_MODEL = "lff_lh_lid_box"
53
+ BOX_D, BOX_W = 0.12, 0.16 # outer depth (x) and width (y)
54
+ WALL_H, WALL_T, FLOOR_T = 0.032, 0.008, 0.006
55
+ LID_T, LID_MASS = 0.006, 0.30
56
+ KNOB_R, STEM_L = 0.013, 0.032
57
+ HINGE_DAMP, HINGE_FRIC = 0.002, 0.002
58
+ IN_X = BOX_D / 2 - WALL_T # inner half sizes of the cavity
59
+ IN_Y = BOX_W / 2 - WALL_T
60
+
61
+ BLOCK = 0.06 # cube edge
62
+ BLOCK_DENS = 250.0 # -> 54 g
63
+ BLOCK_MU = 0.25
64
+ CUBE_E = 0.022 # red cube edge
65
+ MARK_HALF = 0.038
66
+ MARK_LINE = 0.004
67
+ TOL = 0.020 # block centre within 2 cm (per axis) of its mark's centre
68
+ FLAT_COS = np.cos(np.radians(15.0))
69
+ CUBE_MARGIN = 0.004
70
+ LID_CLOSED = np.radians(4.0)
71
+ # hidden stop (deg): in a fraction P_FAR of the instances the lid opens far back, uniform in FAR (it lands on blocks
72
+ # standing behind the box and shoves them 4-10 cm), otherwise it stops near upright, uniform in NEAR (it comes to rest
73
+ # above them). Far / near is balanced per block of 20 consecutive seeds (13 / 7), see sample_instance.
74
+ # Bimodal on purpose: stops between ~115 and ~135 deg make the lid graze the blocks and push them 1-3 cm, i.e. right
75
+ # at the tolerance, which is neither a clean disturbance nor a clean no-disturbance (measured, see the task card).
76
+ P_FAR = 0.65
77
+ FAR = (138.0, 165.0)
78
+ NEAR = (100.0, 113.0)
79
+ GAP_LO, GAP_HI = 0.002, 0.017 # near edge of a behind-mark to the box's back wall (block near face +0.8 cm further)
80
+
81
+ COLORS = ("blue", "green", "yellow")
82
+ RGBA = dict(blue=(0.15, 0.30, 0.85, 1.0), green=(0.10, 0.60, 0.20, 1.0), yellow=(0.92, 0.76, 0.10, 1.0))
83
+ BLOCKS = {c: f"{c}_block_1" for c in COLORS}
84
+ MARKS = {c: f"{c}_mark_1" for c in COLORS}
85
+ CUBE = "red_cube_1"
86
+
87
+ Z_CARRY = 0.13 # scripted transit height of the grasp point above the table when carrying a block
88
+ Z_KNOB = WALL_H + LID_T / 2 # knob centre above the table with the lid closed
89
+ SMAX = 0.010 # max projected displacement command per control step while the knob is held
90
+ STALL = 12
91
+
92
+
93
+ def box_lid_xml(name, body_rgba=(0.55, 0.38, 0.22, 1.0), lid_rgba=(0.70, 0.52, 0.32, 1.0), knob_rgba=(0.10, 0.10, 0.11, 1.0)):
94
+ hx, hy = BOX_D / 2, BOX_W / 2
95
+ parts = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)),
96
+ ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)),
97
+ ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)),
98
+ ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)),
99
+ ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))]
100
+ g = []
101
+ # box: contype 2 / conaffinity 1 and lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the
102
+ # hinge limit holds it closed), but both collide with the robot, the table and the free objects (contype 1)
103
+ for k, (pos, s) in enumerate(parts):
104
+ g.append(f'<geom name="{name}_w{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(s)}" rgba="{_fmt(body_rgba)}" '
105
+ f'friction="0.8 0.005 0.0001" {_SOLID} contype="2" conaffinity="1" group="0"/>')
106
+ g.append(f'<geom type="box" pos="{_fmt(pos)}" size="{_fmt(s)}" rgba="{_fmt(body_rgba)}" contype="0" '
107
+ f'conaffinity="0" group="1"/>')
108
+ m, L = LID_MASS, BOX_D
109
+ lid_c = (-L / 2, 0, LID_T / 2)
110
+ lid_s = (L / 2, hy, LID_T / 2)
111
+ stem = (-L - STEM_L / 2, 0, LID_T / 2)
112
+ ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2)
113
+ lid = [f'<inertial pos="{_fmt(lid_c)}" mass="{m}" diaginertia="{m * (BOX_W ** 2 + LID_T ** 2) / 12:.6f} '
114
+ f'{m * (L ** 2 + LID_T ** 2) / 12:.6f} {m * (BOX_W ** 2 + L ** 2) / 12:.6f}"/>',
115
+ # placeholder range: the opening stop is set per instance (apply_instance)
116
+ f'<joint name="{name}_hinge" type="hinge" axis="0 1 0" pos="0 0 0" limited="true" range="0 2.8" '
117
+ f'damping="{HINGE_DAMP}" frictionloss="{HINGE_FRIC}" armature="0.0005"/>',
118
+ f'<geom name="{name}_lid" type="box" pos="{_fmt(lid_c)}" size="{_fmt(lid_s)}" rgba="{_fmt(lid_rgba)}" mass="0" '
119
+ f'friction="0.8 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
120
+ f'<geom type="box" pos="{_fmt(lid_c)}" size="{_fmt(lid_s)}" rgba="{_fmt(lid_rgba)}" contype="0" conaffinity="0" group="1"/>',
121
+ f'<geom name="{name}_stem" type="cylinder" pos="{_fmt(stem)}" quat="0.7071 0 0.7071 0" size="0.0045 {STEM_L / 2:.4f}" '
122
+ f'rgba="{_fmt(knob_rgba)}" mass="0" friction="1 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
123
+ f'<geom type="cylinder" pos="{_fmt(stem)}" quat="0.7071 0 0.7071 0" size="0.0045 {STEM_L / 2:.4f}" '
124
+ f'rgba="{_fmt(knob_rgba)}" contype="0" conaffinity="0" group="1"/>',
125
+ f'<geom name="{name}_knob" type="sphere" pos="{_fmt(ball)}" size="{KNOB_R:.4f}" rgba="{_fmt(knob_rgba)}" mass="0" '
126
+ f'friction="1 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
127
+ f'<geom type="sphere" pos="{_fmt(ball)}" size="{KNOB_R:.4f}" rgba="{_fmt(knob_rgba)}" contype="0" conaffinity="0" group="1"/>']
128
+ shell = "\n ".join(g)
129
+ lid_xml = "\n ".join(lid)
130
+ return f"""<mujoco model="{name}">
131
+ <worldbody>
132
+ <body>
133
+ <body name="object">
134
+ {shell}
135
+ <body name="lid" pos="{hx:.4f} 0 {WALL_H:.4f}">
136
+ {lid_xml}
137
+ </body>
138
+ </body>
139
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
140
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {WALL_H:.4f}" name="top_site" />
141
+ <site rgba="0 0 0 0" size="0.005" pos="{hx:.4f} {hy:.4f} 0" name="horizontal_radius_site" />
142
+ </body>
143
+ </worldbody>
144
+ </mujoco>"""
145
+
146
+
147
+ def mark_xml(name, rgba):
148
+ """Flat, visual-only square drawn on the table: a light fill plus an outline in the block's colour."""
149
+ fill = tuple(0.55 + 0.45 * c for c in rgba[:3]) + (1.0,)
150
+ o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE
151
+ parts = [((0, 0, 0.0004), (o, o, 0.0004), fill),
152
+ ((0, i + w / 2, 0.0010), (o, w / 2, 0.0002), rgba),
153
+ ((0, -i - w / 2, 0.0010), (o, w / 2, 0.0002), rgba),
154
+ ((i + w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba),
155
+ ((-i - w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba)]
156
+ g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
157
+ f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
158
+ return _wrap(name, g, 0.0012, o)
159
+
160
+
161
+ def _fb(v):
162
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
163
+
164
+
165
+ def _lr(v):
166
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
167
+
168
+
169
+ class LidSkills(Skills):
170
+ """Skills for the lid box: a per-step stage monitor, and a hinge-compliant arm while the knob is held (see the
171
+ module docstring)."""
172
+
173
+ def __init__(self, env, task, recorder=None):
174
+ super().__init__(env, recorder=recorder)
175
+ self.task = task
176
+ self.latched = False
177
+ self.rad0 = None
178
+ self.y0 = None
179
+ self.knob_steps = 0 # control steps driven with the knob held (compliant mode)
180
+ self.knob_grasps = 0
181
+
182
+ def holding_knob(self):
183
+ """both fingers (pad or finger body) touch the knob ball or its stem"""
184
+ g = self.env.robots[0].gripper
185
+ return bool(self.env._check_grasp(gripper=[g.important_geoms["left_finger"], g.important_geoms["right_finger"]],
186
+ object_geoms=self.task.knob_geom_names))
187
+
188
+ def _act(self, dpos, drot, grip):
189
+ if self.latched:
190
+ e = self.eef_pos()
191
+ if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035:
192
+ self.latched = False # opened, or the knob slipped out of the fingers
193
+ else:
194
+ hx, hz = self.task.hinge_xz()
195
+ r = np.array([e[0] - hx, e[2] - hz])
196
+ rn = max(float(np.linalg.norm(r)), 1e-6)
197
+ tng = np.array([-r[1], r[0]]) / rn
198
+ s = float(np.clip(dpos[0] * tng[0] + dpos[2] * tng[1], -SMAX, SMAX))
199
+ corr = (self.rad0 - rn) * r / rn
200
+ dpos = np.array([s * tng[0] + corr[0], self.y0 - e[1], s * tng[1] + corr[1]])
201
+ self.knob_steps += 1
202
+ super()._act(dpos, drot, grip)
203
+ self.task.monitor_step()
204
+
205
+ def set_gripper(self, close, steps=15):
206
+ rep = super().set_gripper(close, steps)
207
+ if close and self.holding_knob():
208
+ e = self.eef_pos()
209
+ hx, hz = self.task.hinge_xz()
210
+ self.latched = True
211
+ self.rad0 = float(np.hypot(e[0] - hx, e[2] - hz))
212
+ self.y0 = float(e[1])
213
+ self.knob_grasps += 1
214
+ elif not close:
215
+ self.latched = False
216
+ return rep
217
+
218
+ def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
219
+ """Skills.move_to plus an early stop when the knob is held and the arm has stopped making progress."""
220
+ tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
221
+ if yaw is not None:
222
+ self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
223
+ R = self._R()
224
+ p0 = self.eef_pos()
225
+ dist = np.linalg.norm(tgt - p0)
226
+ direction = (tgt - p0) / max(dist, 1e-9)
227
+ s = 0.0
228
+ hist = []
229
+ stalled = False
230
+ for k in range(max_steps):
231
+ if speed is not None:
232
+ s = min(dist, s + speed * DT)
233
+ ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5)
234
+ else:
235
+ ref = tgt
236
+ self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
237
+ cur = self.eef_pos()
238
+ if np.linalg.norm(tgt - cur) < tol and (speed is None or s >= dist):
239
+ break
240
+ hist.append(cur)
241
+ if (self.latched and len(hist) > STALL and (speed is None or s >= dist)
242
+ and np.linalg.norm(hist[-1] - hist[-1 - STALL]) < 0.002):
243
+ stalled = True
244
+ break
245
+ rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
246
+ pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=stalled)
247
+ self.log.append(rep)
248
+ return rep
249
+
250
+
251
+ @register_task
252
+ class LidBox(LFFTask):
253
+ name = "lh_lid_box"
254
+ level = "L2"
255
+ category = "state_restoration"
256
+ capabilities = ("Perceive", "Plan", "Reason", "Utilize")
257
+ protocol = "cross"
258
+ max_attempts = 3
259
+ agent_max_steps = 110 # careful oracle ~45-55 commands + restoring two blocks (~14) + looking around
260
+ instruction = ("Put each of the three coloured blocks on the square mark of the same colour on the table. Then open "
261
+ "the lid of the wooden box (lift it by the black knob on its front edge), put the red cube inside "
262
+ "the box, and close the lid.")
263
+ instruction_indirect = ("Set the blue, green and yellow cubes onto the outlined squares of matching colour. Then open "
264
+ "the flat wooden case (its lid lifts by the black ball at the front), place the small red "
265
+ "cube in it and shut the lid.")
266
+ agent_object_names = ["blue block", "green block", "yellow block", "red cube", "wooden box", "lid knob",
267
+ "blue mark", "green mark", "yellow mark"]
268
+
269
+ # ------------------------------------------------------------ scene
270
+ def make_bddl(self):
271
+ box = register_generated("LffLhLidBox", box_lid_xml(BOX_MODEL), free=False)
272
+ b = BLOCK / 2
273
+ objs, fx = [], [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))]
274
+ for i, c in enumerate(COLORS):
275
+ blk = register_generated(f"LffLhBlock{c.title()}",
276
+ box_xml(f"lff_lh_block_{c}", (b, b, b), RGBA[c], density=BLOCK_DENS,
277
+ friction=(BLOCK_MU, 0.005, 0.0001)).replace(_SOLID, ""))
278
+ mark = register_generated(f"LffLhMark{c.title()}", mark_xml(f"lff_lh_mark_{c}", RGBA[c]), free=False)
279
+ objs.append((BLOCKS[c], blk, f"{c}_block_region", (-0.31, -0.22 + 0.15 * i, -0.29, -0.20 + 0.15 * i)))
280
+ fx.append((MARKS[c], mark, f"{c}_mark_region", (0.0, -0.22 + 0.15 * i, 0.02, -0.20 + 0.15 * i)))
281
+ cube = register_generated("LffLhRedCube", box_xml("lff_lh_red_cube", (CUBE_E / 2,) * 3, (0.85, 0.10, 0.08, 1.0),
282
+ density=500))
283
+ objs.append((CUBE, cube, "red_cube_region", (-0.31, 0.24, -0.29, 0.26)))
284
+ return write_bddl(self.name, "put the blocks on their marks and the red cube in the box", objs, fx)
285
+
286
+ def __init__(self, cam_res=None):
287
+ super().__init__(cam_res)
288
+ m = self.env.sim.model
289
+ pre = f"{BOX}_{BOX_MODEL}"
290
+ self.jid = m.joint_name2id(pre + "_hinge")
291
+ self.qa = m.jnt_qposadr[self.jid]
292
+ self.dof = m.jnt_dofadr[self.jid]
293
+ self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
294
+ self.knob_geom_name = pre + "_knob"
295
+ self.knob_geom_names = [pre + "_knob", pre + "_stem"]
296
+ self.knob_gid = m.geom_name2id(self.knob_geom_name)
297
+ self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")}
298
+ self.robot_gids = set(envs.robot_geom_ids(self.env))
299
+ self.mark_bid = {c: m.body_name2id(self.env.fixtures_dict[MARKS[c]].root_body) for c in COLORS}
300
+ self.block_gids = {c: set(envs.obj_geom_ids(self.env, BLOCKS[c])) for c in COLORS}
301
+ self.inst = None
302
+ self.mon = None
303
+
304
+ def sample_instance(self, seed):
305
+ rng = np.random.default_rng(seed)
306
+ bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03))
307
+ hinge_x = bx + BOX_D / 2
308
+ order = [str(c) for c in rng.permutation(COLORS)] # [behind-left, behind-right, side]
309
+ side = 1.0 if rng.random() < 0.5 else -1.0
310
+ marks = {}
311
+ gaps = {}
312
+ for c, sy in zip(order[:2], (1.0, -1.0)):
313
+ g = float(rng.uniform(GAP_LO, GAP_HI))
314
+ gaps[c] = g
315
+ marks[c] = [hinge_x + g + MARK_HALF, by + sy * 0.05 + float(rng.uniform(-0.005, 0.005))]
316
+ marks[order[2]] = [bx + float(rng.uniform(-0.03, 0.03)), by + side * (BOX_W / 2 + 0.025 + MARK_HALF)]
317
+ # start row in front of the box: four slots outside the knob's lane, shuffled (3 blocks + red cube)
318
+ slots = [-0.22, -0.11, 0.11, 0.22] # 11 cm apart: room for the open fingers next to a 6 cm block
319
+ items = [BLOCKS[c] for c in COLORS] + [CUBE]
320
+ perm = rng.permutation(len(items))
321
+ start = {items[i]: [float(-0.31 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))]
322
+ for j, i in enumerate(perm)}
323
+ rng.random() # (draw kept so the other parameters stay the same)
324
+ # balanced blocks like l7_key_turn: exactly round(20 * P_FAR) of every 20 consecutive seeds open far
325
+ far = bool((int(seed) * 7) % 20 < round(20 * P_FAR))
326
+ stop = float(rng.uniform(*(FAR if far else NEAR)))
327
+ return dict(seed=int(seed), box_xy=[bx, by], stop_deg=stop, lid_far=far, marks=marks,
328
+ behind=order[:2], side_color=order[2], side="left" if side > 0 else "right", gaps=gaps, start=start,
329
+ start_yaw={k: float(rng.uniform(-0.3, 0.3)) for k in items})
330
+
331
+ def apply_instance(self, inst):
332
+ self.inst = inst
333
+ m, d = self.env.sim.model, self.env.sim.data
334
+ bx, by = inst["box_xy"]
335
+ m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z]
336
+ m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
337
+ m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])]
338
+ m.jnt_solref[self.jid] = [0.01, 1.0]
339
+ d.qpos[self.qa] = 0.0
340
+ d.qvel[self.dof] = 0.0
341
+ for c in COLORS:
342
+ x, y = inst["marks"][c]
343
+ m.body_pos[self.mark_bid[c]] = [x, y, envs.TABLE_Z + 0.0002]
344
+ m.body_quat[self.mark_bid[c]] = [1.0, 0.0, 0.0, 0.0]
345
+ for name, xy in inst["start"].items():
346
+ envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name])
347
+ for c in COLORS:
348
+ envs.set_friction(self.env, BLOCKS[c], BLOCK_MU)
349
+
350
+ def reset_instance(self, inst, recorder=None):
351
+ self.env.reset()
352
+ self.apply_instance(inst)
353
+ self.env.sim.forward()
354
+ envs.settle(self.env, 10)
355
+ self.mon = None
356
+ self.sk = LidSkills(self.env, self, recorder=recorder)
357
+ self._init_monitor()
358
+ return self.sk
359
+
360
+ # ------------------------------------------------------------ state helpers
361
+ def lid_q(self):
362
+ return float(self.env.sim.data.qpos[self.qa])
363
+
364
+ def lid_deg(self):
365
+ return float(np.degrees(self.lid_q()))
366
+
367
+ def knob_xyz(self):
368
+ return self.env.sim.data.geom_xpos[self.knob_gid].copy()
369
+
370
+ def hinge_xz(self):
371
+ return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H
372
+
373
+ def held(self, name):
374
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
375
+
376
+ def _flat(self, name):
377
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
378
+ return bool(np.max(np.abs(R[2])) >= FLAT_COS)
379
+
380
+ def block_offset(self, c):
381
+ p = envs.obj_pos(self.env, BLOCKS[c])
382
+ return p[:2] - np.asarray(self.inst["marks"][c])
383
+
384
+ def on_mark(self, c, tol=TOL):
385
+ name = BLOCKS[c]
386
+ p = envs.obj_pos(self.env, name)
387
+ off = p[:2] - np.asarray(self.inst["marks"][c])
388
+ return bool(np.max(np.abs(off)) <= tol and p[2] < envs.TABLE_Z + BLOCK / 2 + 0.01 and self._flat(name)
389
+ and not self.held(name))
390
+
391
+ def cube_in_box(self):
392
+ p = envs.obj_pos(self.env, CUBE)
393
+ rel = p[:2] - np.asarray(self.inst["box_xy"])
394
+ return bool(abs(rel[0]) <= IN_X - CUBE_MARGIN and abs(rel[1]) <= IN_Y - CUBE_MARGIN
395
+ and p[2] < envs.TABLE_Z + WALL_H and not self.held(CUBE))
396
+
397
+ def lid_closed(self):
398
+ return self.lid_q() <= LID_CLOSED
399
+
400
+ def stage_values(self):
401
+ v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS}
402
+ v["cube_in_box"] = self.cube_in_box()
403
+ v["lid_closed"] = self.lid_closed()
404
+ return v
405
+
406
+ # ------------------------------------------------------------ per-step monitor
407
+ def _init_monitor(self):
408
+ self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"cube_in_box": False}, ever=set(),
409
+ lost=set(), events=[], last_touch={c: None for c in COLORS}, lid_hits=set(),
410
+ lid_open_max=0.0, lid_opened=False, lid_open_steps=[], lid_close_steps=[], step=0,
411
+ lid_prev=0.0, lid_moving_step=-10 ** 9)
412
+
413
+ def _touches(self):
414
+ """Per block: was it touched by the lid / the robot in this control step?"""
415
+ d = self.env.sim.data
416
+ out = {}
417
+ for i in range(d.ncon):
418
+ c = d.contact[i]
419
+ for cc in COLORS:
420
+ g = self.block_gids[cc]
421
+ other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None)
422
+ if other is None:
423
+ continue
424
+ if other in self.lid_gids:
425
+ out[cc] = "lid"
426
+ elif other in self.robot_gids and out.get(cc) != "lid":
427
+ out[cc] = "robot"
428
+ return out
429
+
430
+ def monitor_step(self):
431
+ mon = self.mon
432
+ if mon is None:
433
+ return
434
+ mon["step"] += 1
435
+ step = self.sk.n_steps if self.sk is not None else mon["step"]
436
+ for c, who in self._touches().items():
437
+ mon["last_touch"][c] = (who, step)
438
+ if who == "lid":
439
+ mon["lid_hits"].add(c)
440
+ q = self.lid_deg()
441
+ if q > 95.0 and abs(q - mon["lid_prev"]) > 0.5:
442
+ mon["lid_moving_step"] = step # the open lid is swinging (its contacts can last less than a control step)
443
+ mon["lid_prev"] = q
444
+ mon["lid_open_max"] = max(mon["lid_open_max"], q)
445
+ if not mon["lid_opened"] and q > 90.0:
446
+ mon["lid_opened"] = True
447
+ mon["lid_open_steps"].append(step)
448
+ mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical"))
449
+ elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED):
450
+ mon["lid_opened"] = False
451
+ mon["lid_close_steps"].append(step)
452
+ mon["events"].append(dict(step=step, pred="lid", ev="closed"))
453
+ if mon["step"] % 2:
454
+ return # predicates every other control step (0.1 s)
455
+ for c in COLORS:
456
+ key = f"{c}_on_mark"
457
+ was = mon["state"][key]
458
+ now = self.on_mark(c, TOL if not was else TOL + 0.005) # hysteresis against jitter at the border
459
+ if now != was:
460
+ self._event(key, now, step, c)
461
+ was = mon["state"]["cube_in_box"]
462
+ now = self.cube_in_box()
463
+ if now != was:
464
+ self._event("cube_in_box", now, step, None)
465
+
466
+ def _event(self, key, now, step, color):
467
+ mon = self.mon
468
+ mon["state"][key] = now
469
+ if now:
470
+ ev = "restored" if key in mon["lost"] else "achieved"
471
+ mon["ever"].add(key)
472
+ if key in mon["lost"]:
473
+ mon["lost"].discard(key)
474
+ mon["events"].append(dict(step=step, pred=key, ev=ev))
475
+ else:
476
+ cause = "other"
477
+ if color is not None:
478
+ if self.held(BLOCKS[color]):
479
+ cause = "picked_up"
480
+ else:
481
+ lt = mon["last_touch"][color]
482
+ if lt is not None and step - lt[1] <= 60:
483
+ cause = lt[0]
484
+ if cause == "other" and step - mon["lid_moving_step"] <= 20 and color in self.inst["behind"]:
485
+ cause = "lid" # lost while the open lid was swinging down onto the blocks behind the box
486
+ elif self.held(CUBE):
487
+ cause = "picked_up"
488
+ mon["lost"].add(key)
489
+ ev = dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1))
490
+ if color is not None:
491
+ ev["offset_cm"] = (100 * self.block_offset(color)).round(1).tolist()
492
+ mon["events"].append(ev)
493
+
494
+ # ------------------------------------------------------------ outcome
495
+ def _static(self):
496
+ d = self.env.sim.data
497
+ for name in [BLOCKS[c] for c in COLORS] + [CUBE]:
498
+ _, da = envs.free_joint_addr(self.env, name)
499
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
500
+ return False
501
+ return abs(float(d.qvel[self.dof])) < 0.2
502
+
503
+ def outcome(self, inst):
504
+ envs.settle(self.env, 30)
505
+ mon = self.mon
506
+ vals = self.stage_values()
507
+ static = self._static()
508
+ held = [n for n in [BLOCKS[c] for c in COLORS] + [CUBE] if self.held(n)]
509
+ success = bool(all(vals.values()) and static and not held)
510
+ regress = [e for e in mon["events"] if e["ev"] == "lost"]
511
+ restored = [e for e in mon["events"] if e["ev"] == "restored"]
512
+ lid_knocks = [e for e in regress if e.get("cause") == "lid"]
513
+ parts = []
514
+ if success:
515
+ failure = None
516
+ parts.append("All three blocks are on their marks, the red cube is in the box and the lid is closed.")
517
+ else:
518
+ off = [c for c in COLORS if not vals[f"{c}_on_mark"]]
519
+ failure = ("block_off_mark" if off else "cube_not_in_box" if not vals["cube_in_box"] else
520
+ "lid_open" if not vals["lid_closed"] else "held" if held else "not_static")
521
+ for c in off:
522
+ o = self.block_offset(c)
523
+ name = BLOCKS[c]
524
+ if self.held(name):
525
+ parts.append(f"The {c} block is still held by the gripper.")
526
+ continue
527
+ txt = (f"The {c} block is not on the {c} mark: its centre is {_fb(o[0])} and {_lr(o[1])} of the mark's "
528
+ f"centre")
529
+ if not self._flat(name):
530
+ txt += " and it is tipped over"
531
+ why = [e for e in regress if e["pred"] == f"{c}_on_mark"]
532
+ if f"{c}_on_mark" not in mon["ever"]:
533
+ txt += " (it was never on its mark)."
534
+ elif why and why[-1].get("cause") == "lid":
535
+ txt += (f" (it had been on its mark; the lid pushed it off when it fell open to "
536
+ f"{why[-1]['lid_deg']:.0f} degrees).")
537
+ elif why and why[-1].get("cause") == "robot":
538
+ txt += " (it had been on its mark; the robot knocked it off)."
539
+ else:
540
+ txt += " (it had been on its mark earlier)."
541
+ parts.append(txt)
542
+ if not vals["cube_in_box"]:
543
+ if self.held(CUBE):
544
+ parts.append("The red cube is still held by the gripper.")
545
+ else:
546
+ p = envs.obj_pos(self.env, CUBE)
547
+ rel = p[:2] - np.asarray(inst["box_xy"])
548
+ parts.append(f"The red cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the "
549
+ f"box's centre.")
550
+ if not vals["lid_closed"]:
551
+ parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees).")
552
+ if not static and all(vals.values()):
553
+ parts.append("Something was still moving at the end.")
554
+ if mon["lid_open_max"] < 90.0:
555
+ parts.append("The lid was never opened past upright.")
556
+ out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
557
+ events=mon["events"], n_regressions=len(regress), n_restored=len(restored),
558
+ n_lid_knocks=len(lid_knocks), lid_hits=sorted(mon["lid_hits"]),
559
+ lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1),
560
+ knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps,
561
+ block_offsets_cm={c: (100 * self.block_offset(c)).round(1).tolist() for c in COLORS},
562
+ detail=" ".join(parts))
563
+ return out
564
+
565
+ # ------------------------------------------------------------ scripted policies (perfect perception)
566
+ def _grasp_yaw(self, name):
567
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
568
+ i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on)
569
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
570
+ return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) # a cube: grasp yaw mod 90 deg
571
+
572
+ def pick_place(self, name, dest_xy, z_rel, z_carry=Z_CARRY, noise=None, dest_yaw=0.0):
573
+ """Top-down pick of `name` at its centre, carry at `z_carry` (grasp point above the table), release with the
574
+ grasp point `z_rel` above the table at `dest_xy`, lift."""
575
+ sk = self.sk
576
+ Z = envs.TABLE_Z
577
+ p = envs.obj_pos(self.env, name)
578
+ yaw = self._grasp_yaw(name)
579
+ zg = p[2] - Z
580
+ sk.set_gripper(False, steps=8)
581
+ sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw)
582
+ sk.move_to([p[0], p[1], Z + zg], tol=0.003)
583
+ sk.set_gripper(True, steps=15)
584
+ sk.move_to([p[0], p[1], Z + z_carry], speed=0.3)
585
+ if not self.held(name):
586
+ sk.set_gripper(False, steps=8)
587
+ return False
588
+ d = np.asarray(dest_xy, float) + (np.asarray(noise, float) if noise is not None else 0.0)
589
+ sk.move_to([d[0], d[1], Z + z_carry], yaw=dest_yaw)
590
+ sk.move_to([d[0], d[1], Z + z_rel], tol=0.003)
591
+ sk.set_gripper(False, steps=12)
592
+ sk.move_to([d[0], d[1], Z + z_carry])
593
+ return True
594
+
595
+ def place_block(self, c, noise=None):
596
+ return self.pick_place(BLOCKS[c], self.inst["marks"][c], BLOCK / 2 + 0.004, noise=noise)
597
+
598
+ def put_cube(self, noise=None):
599
+ bx, by = self.inst["box_xy"]
600
+ return self.pick_place(CUBE, [bx, by], FLOOR_T + CUBE_E / 2 + 0.008, z_carry=0.12, noise=noise)
601
+
602
+ def _grasp_knob(self):
603
+ sk = self.sk
604
+ k = self.knob_xyz()
605
+ sk.set_gripper(False, steps=8)
606
+ sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0)
607
+ sk.move_to([k[0], k[1], k[2]], tol=0.003)
608
+ sk.set_gripper(True, steps=15)
609
+ return k
610
+
611
+ def open_lid(self, back=0.03, up=0.16):
612
+ """grasp the knob; straight up 10 cm; straight to `back` m behind the hinge, `up` m above it; release; lift"""
613
+ sk = self.sk
614
+ k = self._grasp_knob()
615
+ hx, hz = self.hinge_xz()
616
+ sk.move_to([k[0], k[1], k[2] + 0.10])
617
+ sk.move_to([hx + back, k[1], hz + up])
618
+ sk.set_gripper(False, steps=10)
619
+ e = sk.eef_pos()
620
+ sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06])
621
+ sk.hold(20)
622
+
623
+ def close_lid(self):
624
+ """grasp the knob where it is; straight up 10 cm; straight forward to 8 cm in front of the hinge; release"""
625
+ sk = self.sk
626
+ k = self._grasp_knob()
627
+ hx, hz = self.hinge_xz()
628
+ sk.move_to([k[0], k[1], k[2] + 0.10])
629
+ sk.move_to([hx - 0.08, k[1], k[2] + 0.10])
630
+ sk.set_gripper(False, steps=10)
631
+ e = sk.eef_pos()
632
+ sk.move_to([e[0], e[1], e[2] + 0.06])
633
+ sk.hold(20)
634
+
635
+ def restore(self, rounds=2):
636
+ """look at every stage and fix what is wrong (lid open -> close it; cube out -> put it in; block off -> put it
637
+ back), up to `rounds` passes"""
638
+ for _ in range(rounds):
639
+ v = self.stage_values()
640
+ if all(v.values()):
641
+ return True
642
+ if not v["cube_in_box"]:
643
+ if self.lid_q() < np.radians(95):
644
+ self.open_lid()
645
+ self.put_cube()
646
+ self.close_lid()
647
+ elif not v["lid_closed"]:
648
+ self.close_lid()
649
+ for c in COLORS:
650
+ if not self.on_mark(c):
651
+ self.place_block(c)
652
+ return all(self.stage_values().values())
653
+
654
+ def execute(self, inst, params):
655
+ order = params.get("order") or list(COLORS)
656
+ noise = params.get("noise") or {}
657
+ if params["plan"] == "blocks_first":
658
+ for c in order:
659
+ self.place_block(c, noise.get(c))
660
+ self.open_lid(**params.get("open", {}))
661
+ self.put_cube(noise.get("cube"))
662
+ self.close_lid()
663
+ else: # "lid_first": open, cube in, close, then the blocks
664
+ self.open_lid(**params.get("open", {}))
665
+ self.put_cube(noise.get("cube"))
666
+ self.close_lid()
667
+ for c in order:
668
+ self.place_block(c, noise.get(c))
669
+ if params.get("check"):
670
+ self.restore()
671
+ self.sk.hold(10)
672
+
673
+ def default_params(self, inst):
674
+ return dict(plan="blocks_first", check=False)
675
+
676
+ def oracle_params(self, inst):
677
+ return dict(plan="lid_first", check=True)
678
+
679
+ def adapt_params(self, inst, history):
680
+ """Used from attempt 2 on, i.e. after a failed attempt (attempt 1 is the natural order plus a final check and
681
+ repair, see run_scripted): open the box, put the cube in and close it first, then place the blocks, check."""
682
+ return dict(plan="lid_first", check=True)
683
+
684
+ def blind_params(self, inst, attempt, rng):
685
+ """the natural order again with small random variations (block order, placement, release point), no check"""
686
+ return dict(plan="blocks_first", check=False, order=[str(c) for c in rng.permutation(COLORS)],
687
+ noise={c: rng.normal(0.0, 0.004, 2).tolist() for c in COLORS},
688
+ open=dict(back=float(rng.uniform(0.0, 0.05)), up=float(rng.uniform(0.14, 0.18))))
689
+
690
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
691
+ k = k or self.max_attempts
692
+ rng = np.random.default_rng(seed)
693
+ history = []
694
+ for a in range(k):
695
+ self.reset_instance(inst)
696
+ if kind == "oracle":
697
+ params = self.oracle_params(inst)
698
+ elif kind == "naive":
699
+ params = self.default_params(inst)
700
+ elif kind == "adaptive":
701
+ params = dict(plan="blocks_first", check=True) if a == 0 else self.adapt_params(inst, history)
702
+ elif kind == "blind":
703
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
704
+ elif kind == "switch": # extra control (not in validate's table): cross-attempt learning only, no re-check
705
+ params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check=False)
706
+ else:
707
+ raise ValueError(kind)
708
+ self.execute(inst, params)
709
+ out = self.outcome(inst)
710
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
711
+ if on_attempt:
712
+ on_attempt(a, params, out)
713
+ if out["success"] or kind in ("oracle", "naive"):
714
+ break
715
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_tray_delivery.py ADDED
@@ -0,0 +1,883 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH tray_delivery v2 (long horizon, state restoration): load three bottles onto a tray in the loading area, then move
2
+ the loaded tray over a low threshold strip into the delivery area. Pushing the tray over the strip makes it rock, and
3
+ the top-heavy bottles fall; holding the tray by its handle while moving it does not.
4
+
5
+ Family: long-horizon tasks in which the agent's own normal later-stage action physically breaks earlier progress
6
+ (docs/11). Stages:
7
+ S1-S3 stand the red / green / blue bottle upright on the tray while the tray is inside the yellow loading area;
8
+ S4 move the tray (with the bottles) over the black threshold strip completely into the purple delivery area.
9
+ Success (F1): at the end the tray (board and handle) is completely inside the delivery area, all three bottles stand
10
+ upright on it, the gripper does not touch them, the scene is static, AND the event log shows that all three bottles
11
+ stood on the tray at the same time while the tray was still completely inside the loading area (load first, then
12
+ deliver). Re-standing a fallen bottle on the tray after the move is allowed (counts as a restoration).
13
+
14
+ v2 (2026-10-09, after the Sonnet 5.5 pilot lh1, see the task card): v1's 15.6 cm bottles on a 2.2 cm foot were hard to
15
+ grasp and to stand, the narrow handle was hard to push straight, "completely inside" needed 2 cm precision, and the
16
+ agents pushed at 3-5 cm/s, far below v1's 0.15 m/s topple threshold, so the hidden variable never mattered. Now:
17
+ - bottles 10.5 cm tall: 4 x 4 x 7.5 cm square body with a flat bottom + a 2.4 cm round neck (3 cm tall), 0.25 kg;
18
+ - T handle, 2.5 cm tall: a 16 cm push bar at the back (push it with the closed gripper) on a 3 cm wide, 5 cm long stem
19
+ (grasp it across its width);
20
+ - delivery area 28 x 42 cm for the 18.5 x 34 cm tray footprint (4.75 / 4 cm slack per side; v1: 2 / 3 cm);
21
+ - a black threshold strip between the areas (a rounded sill 1 cm high, 5.3 cm wide, 46 cm long) that the tray has to
22
+ cross. Measured: with stocky bottles speed alone cannot be the lever (on a flat table a top-heavy bottle stayed up in
23
+ closed-gripper pushes up to 0.3 m/s; only the controller's top speed, ~0.65 m/s, toppled it). On the sill the tray
24
+ first climbs (front up ~5 deg), then rocks over the crest under gravity; when it is pushed, nothing holds its trailing
25
+ edge, which jumps up (max tray tilt 7.2-9.3 deg) and the top-heavy bottles fall over the leading edge,
26
+ at every push speed tried (2-6 cm/s and the top speed). When the stem is grasped, the hand holds the trailing edge
27
+ (max tilt 5.7-7.5 deg) and nothing falls. A hand hovering right over the handle (3 cm handle pushed with the
28
+ grasp point ~1 cm above the table) also held it down; hence the 2.5 cm handle.
29
+ - failure codes report the first unmet requirement: not_loaded / order / bottle_fallen / bottle_off_tray /
30
+ not_delivered / held / not_static.
31
+
32
+ Scene: wooden tray = an 11 x 34 x 1.2 cm board, long side running forward / back, with the T handle sticking out of the
33
+ middle of the long side that faces away from the delivery area; three bottles (same shape, red / green / blue) standing
34
+ in a row on the table on the far side of the loading area; two painted rectangles (no collision): yellow loading area
35
+ (tray inside it at the start) and purple delivery area 32-34 cm (centre to centre) to its left or right (random); the
36
+ threshold strip lies across the path in the gap between them. The tray travels sideways (the arm's comfortable
37
+ workspace is wide in y but short in x).
38
+
39
+ Hidden variable (same appearance): each bottle's centre-of-mass height (an invisible internal weight, 85 % of its
40
+ mass): "stable" 2.0-3.5 cm, "top-heavy" 6.6-7.6 cm above the bottom; 0 / 1 / 2 top-heavy bottles with p = 0.35 / 0.40 /
41
+ 0.25. Measured on 28 instances (scripted loading, same loaded state for every move): closed-gripper pushes (2, 3, 4.5,
42
+ 6 cm/s, top speed, 3 stops, slow approach; agent-style pushes through the tool layer with the grasp point 1.0 / 1.3 /
43
+ 2.5 cm above the table) toppled 24/24 top-heavy bottles and 0/60 stable ones in every variant; grasp-and-drag at 2 and
44
+ 4.5 cm/s toppled 0/84. Above a COM of 8 cm falling bottles sometimes land standing on their neck (cannot be stood up
45
+ again with yaw-only control without first knocking them over), so the range stops at 7.6 cm. Tray-table friction
46
+ 0.45-0.60 is a nuisance variable; the sill's own friction (0.4) wins in its contacts (with the tray's 0.85 the tray
47
+ jammed at the sill and jumped over it, toppling nothing).
48
+ Restoration: a fallen bottle can be stood up again: grasp its round neck (fingers closing across the neck), lift it --
49
+ it swings down and hangs from the neck -- and set it down on the tray.
50
+
51
+ Simulation notes (as in v1): COM heights are set at reset through body_ipos / inertia and the bottle's collision BVH is
52
+ shifted with it (MuJoCo keeps it in the inertial frame); the tray uses the table's soft contact (solref 0.02); the
53
+ bottles' own contacts are stiffer (solref 0.005) so a bottle lowered onto the board by its neck is not pressed through.
54
+ """
55
+ import numpy as np
56
+
57
+ from .. import envs
58
+ from ..bddl import write_bddl
59
+ from ..objects import _fmt, _wrap, register_generated
60
+ from ..skills import Skills
61
+ from ..task_base import LFFTask, register_task
62
+
63
+ SOFT = 'solimp="0.9 0.95 0.001" solref="0.02 1"' # the LIBERO table's contact parameters
64
+
65
+ # bottle: square body with a flat 4 x 4 cm bottom + round neck; body origin at the middle of the total height
66
+ BODY = (0.020, 0.020, 0.0375) # half sizes of the body (4 x 4 x 7.5 cm)
67
+ NECK_R, NECK_H = 0.012, 0.015 # neck radius, half height (2.4 cm wide, 3 cm tall) -> 10.5 cm in total
68
+ BH = BODY[2] + NECK_H # half of the total height
69
+ DAMP_BOT = 0.003 # free-joint damping of the bottles (air drag; damps the swing of a bottle hanging from its neck)
70
+ BOT_MASS = 0.25
71
+ W_FRAC = 0.85 # share of the mass in the hidden internal weight
72
+ MU_BOT = 1.0
73
+ COS_UP = 0.95 # upright: long axis within ~18 deg of vertical
74
+ BOT_SOLREF = (0.005, 1.0) # the bottles win in all their contacts (priority 3)
75
+ BOT_SOLIMP = (0.95, 0.99, 0.001, 0.5, 2.0)
76
+
77
+ # tray: board + T handle (stem + cross bar) sticking out of the middle of the trailing long side (tray frame -x)
78
+ PLATE = (0.055, 0.17, 0.006) # 11 x 34 x 1.2 cm board
79
+ STEM = (0.025, 0.015, 0.0125) # 5 long x 3 wide x 2.5 cm tall: grasp it across its width
80
+ CROSS = (0.0125, 0.08, 0.0125) # 2.5 deep x 16 wide x 2.5 cm tall bar at the back: push it with the closed gripper
81
+ # Handle height 2.5 cm (measured on 6 instances x 6 push heights, see the card): the Panda palm reaches ~3-4 cm ahead
82
+ # of the fingers and ~2 cm above the grasp point. With a 3 cm handle a hand pushing low (grasp point ~1 cm above the
83
+ # table) hovered right over the handle and kept the trailing edge from jumping up on the sill (like a grasp: no topple
84
+ # in 3/6); with 2.5 cm every push with the grasp point 1-2.5 cm above the table toppled the top-heavy bottles (36/36).
85
+ # A hand pushing at >= 3 cm only touches the handle with its fingertips and can slide over it.
86
+ PLATE_TOP = envs.TABLE_Z + 2 * PLATE[2]
87
+ BACK_X = -PLATE[0] - 2 * STEM[0] - 2 * CROSS[0] # tray-frame x of the handle's back face (-0.13)
88
+ FOOT_DX = (PLATE[0] + BACK_X) / 2 # x of the footprint centre (board + handle) relative to the board centre
89
+ # slots 1.5 cm towards the leading edge: a hand grasping the cross bar with its long side along the travel direction
90
+ # (palm 10.5 cm ahead of the grasp point) still clears the middle bottle by ~7 mm
91
+ SLOT_LX = 0.015
92
+ SLOT_LY = (-0.12, 0.0, 0.12)
93
+ MU_HANDLE = 0.6
94
+
95
+ # painted areas (inner half sizes: along travel, along the tray's long side)
96
+ LOAD_IN = (0.1125, 0.20) # tray footprint 18.5 x 34 cm -> 2 / 3 cm slack per side
97
+ DELIV_IN = (0.14, 0.21) # -> 4.75 / 4 cm slack per side
98
+ LINE_W = 0.008
99
+ AREA_DIST = (0.32, 0.34) # centre to centre
100
+
101
+ # threshold strip: a capsule lying across the path, sunk into the table so that it sticks out RIDGE_H (a rounded sill
102
+ # 2 * sqrt(2 R h - h^2) = 5.3 cm wide)
103
+ RIDGE_H = 0.010
104
+ RIDGE_R = 0.040
105
+ RIDGE_HL = 0.23 # half length of the straight part (46 cm: longer than the tray)
106
+ MU_RIDGE = 0.4 # wins in its contacts (priority 4)
107
+
108
+ BOTTLES = ("bottle_red_1", "bottle_green_1", "bottle_blue_1")
109
+ COLOR_OF = {"bottle_red_1": "red", "bottle_green_1": "green", "bottle_blue_1": "blue"}
110
+ RGBA = {"red": (0.82, 0.12, 0.10, 1.0), "green": (0.12, 0.60, 0.20, 1.0), "blue": (0.12, 0.30, 0.85, 1.0)}
111
+ TRAY = "tray_1"
112
+ LOAD, DELIVER, RIDGE = "load_area_1", "deliver_area_1", "threshold_1"
113
+
114
+ # hidden COM heights above the bottle's bottom (m); calibration in the task card
115
+ HC_STABLE = (0.020, 0.035)
116
+ HC_TOPHEAVY = (0.066, 0.076)
117
+ N_TOP_P = (0.35, 0.40, 0.25) # P(0 / 1 / 2 top-heavy bottles)
118
+ MU_TRAY = (0.45, 0.60)
119
+
120
+ DEBOUNCE = 5 # control steps a predicate must keep a new value before an event is recorded (0.25 s)
121
+
122
+ # scripted reference moves
123
+ V_NAIVE = 0.045 # the pilot agents pushed at 3-6 cm/s
124
+ V_CAREFUL = 0.02 # the LA interface's slowest speed
125
+ GRASP_TOP = 0.012 # scripted grasp point: on the neck, this far below the bottle's top (the palm is ~2 cm above it)
126
+ SAFE_Z = envs.TABLE_Z + 0.17 # scripted transits: fingertips ~5 cm above the tops of bottles standing on the tray
127
+ SAFE_Z_HELD = envs.TABLE_Z + 0.25 # ... and with a bottle hanging from the gripper: its bottom ~4 cm above them
128
+ PUSH_Z = envs.TABLE_Z + 0.015 # closed-gripper pushes: grasp point 1.5 cm above the table (fingertips ~0.5 cm)
129
+ DRAG_Z = envs.TABLE_Z + 0.015 # grasping the stem: finger pads over its whole height
130
+
131
+
132
+ def bottle_xml(name, rgba):
133
+ zb = -BH + BODY[2]
134
+ zn = -BH + 2 * BODY[2] + NECK_H
135
+ neck_rgba = tuple(0.8 * c for c in rgba[:3]) + (1.0,)
136
+ parts = [("box", zb, _fmt(BODY), rgba), ("cylinder", zn, f"{NECK_R:.5f} {NECK_H:.5f}", neck_rgba)]
137
+ gs = []
138
+ for k, (typ, z, size, c) in enumerate(parts):
139
+ gs.append(f' <geom name="{name}_g{k}" type="{typ}" pos="0 0 {z:.5f}" size="{size}" rgba="{_fmt(c)}" '
140
+ f'density="500" friction="{MU_BOT} 0.005 0.0001" {SOFT} group="0" />')
141
+ gs.append(f' <geom type="{typ}" pos="0 0 {z:.5f}" size="{size}" rgba="{_fmt(c)}" conaffinity="0" '
142
+ f'contype="0" group="1" />')
143
+ return _wrap(name, "\n".join(gs), BH, float(np.hypot(BODY[0], BODY[1])))
144
+
145
+
146
+ def tray_xml(name, rgba=(0.62, 0.45, 0.27, 1.0)):
147
+ hz = -PLATE[2] + STEM[2] # handle bottom flush with the board's bottom
148
+ sp = (-PLATE[0] - STEM[0], 0.0, hz)
149
+ cp = (-PLATE[0] - 2 * STEM[0] - CROSS[0], 0.0, hz)
150
+ hrgba = (0.30, 0.20, 0.12, 1.0)
151
+ gs = []
152
+ for k, (p, s, c, mu) in enumerate((((0, 0, 0), PLATE, rgba, 0.6), (sp, STEM, hrgba, MU_HANDLE),
153
+ (cp, CROSS, hrgba, MU_HANDLE))):
154
+ gs.append(f' <geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
155
+ f'density="500" friction="{mu} 0.005 0.0001" {SOFT} group="0" />')
156
+ gs.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
157
+ f'contype="0" group="1" />')
158
+ return _wrap(name, "\n".join(gs), PLATE[2], float(np.hypot(PLATE[0] - BACK_X, PLATE[1])))
159
+
160
+
161
+ def area_xml(name, inner, fill, line):
162
+ """Flat, visual-only rectangle painted on the table (light fill + dark outline, no collisions)."""
163
+ ix, iy = inner
164
+ ox, oy = ix + LINE_W, iy + LINE_W
165
+ parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill),
166
+ ((0, iy + LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line),
167
+ ((0, -iy - LINE_W / 2, 0.0010), (ox, LINE_W / 2, 0.0002), line),
168
+ ((ix + LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line),
169
+ ((-ix - LINE_W / 2, 0, 0.0010), (LINE_W / 2, oy, 0.0002), line)]
170
+ g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
171
+ f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
172
+ return _wrap(name, g, 0.0012, float(np.hypot(ox, oy)))
173
+
174
+
175
+ def sill_xml(name, rgba=(0.12, 0.12, 0.13, 1.0)):
176
+ """the threshold strip: a capsule along the fixture's local y (quat turns z into y), origin on its axis; the
177
+ fixture is placed with the axis RIDGE_R - RIDGE_H below the table top (static: no contacts with the table)"""
178
+ q = "0.70711 0.70711 0 0"
179
+ g = (f' <geom name="{name}_g0" type="capsule" quat="{q}" size="{RIDGE_R:.5f} {RIDGE_HL:.5f}" '
180
+ f'rgba="{_fmt(rgba)}" friction="{MU_RIDGE} 0.005 0.0001" {SOFT} group="0" />\n'
181
+ f' <geom type="capsule" quat="{q}" size="{RIDGE_R:.5f} {RIDGE_HL:.5f}" rgba="{_fmt(rgba)}" '
182
+ f'conaffinity="0" contype="0" group="1" />')
183
+ return _wrap(name, g, RIDGE_R, RIDGE_HL + RIDGE_R)
184
+
185
+
186
+ def _rotz2(a):
187
+ c, s = np.cos(a), np.sin(a)
188
+ return np.array([[c, -s], [s, c]])
189
+
190
+
191
+ def _yaw_of(R):
192
+ return float(np.arctan2(R[1, 0], R[0, 0]))
193
+
194
+
195
+ class TraySkills(Skills):
196
+ """Skills whose every control step feeds the task's stage monitor."""
197
+
198
+ def __init__(self, env, task, recorder=None):
199
+ super().__init__(env, recorder=recorder)
200
+ self.task = task
201
+
202
+ def _act(self, dpos, drot, grip):
203
+ super()._act(dpos, drot, grip)
204
+ self.task.monitor_step()
205
+
206
+
207
+ @register_task
208
+ class TrayDelivery(LFFTask):
209
+ name = "lh_tray_delivery"
210
+ level = "L2"
211
+ category = "state_restoration"
212
+ capabilities = ("Perceive", "Reason", "Plan")
213
+ protocol = "cross"
214
+ max_attempts = 3
215
+ # scripted primitives (~ agent commands): careful oracle 37; naive push + same-attempt repair of 1-2 bottles 46-63
216
+ agent_max_steps = 110
217
+ instruction = ("Load the red, green and blue bottles onto the wooden tray: stand each bottle upright on the tray "
218
+ "while the tray is still inside the yellow loading area. Only after all three bottles are on the "
219
+ "tray, move the tray with the bottles on it over the black threshold strip into the purple "
220
+ "delivery area. At the end the whole tray, including its handle, must be inside the purple area "
221
+ "with all three bottles standing upright on it.")
222
+ instruction_indirect = ("Stand the three bottles up on the wooden board that lies in the yellow rectangle while "
223
+ "the board is still there; then bring the board with the bottles on it across the black "
224
+ "strip into the purple rectangle. At the end the whole board, including its dark handle, "
225
+ "must lie inside the purple rectangle with all three bottles standing on it.")
226
+ agent_object_names = ["red bottle", "green bottle", "blue bottle", "wooden tray", "yellow loading area",
227
+ "purple delivery area", "black threshold strip"]
228
+
229
+ # ------------------------------------------------------------ scene
230
+ def make_bddl(self):
231
+ objs = []
232
+ for i, b in enumerate(BOTTLES):
233
+ c = COLOR_OF[b]
234
+ cat = register_generated(f"LffTdBottle{c.capitalize()}", bottle_xml(f"lff_td_bottle_{c}", RGBA[c]))
235
+ x0 = -0.25 + 0.12 * i
236
+ objs.append((b, cat, f"bottle_{c}_region", (x0, 0.30, x0 + 0.01, 0.31)))
237
+ tray = register_generated("LffTdTray", tray_xml("lff_td_tray"))
238
+ objs.append((TRAY, tray, "tray_region", (0.0, -0.05, 0.01, -0.04)))
239
+ load = register_generated("LffTdLoadArea", area_xml("lff_td_load_area", LOAD_IN, (0.98, 0.93, 0.55, 1.0),
240
+ (0.85, 0.62, 0.05, 1.0)), free=False)
241
+ deliv = register_generated("LffTdDeliverArea", area_xml("lff_td_deliver_area", DELIV_IN,
242
+ (0.86, 0.78, 0.95, 1.0), (0.45, 0.20, 0.65, 1.0)),
243
+ free=False)
244
+ sill = register_generated("LffTdThreshold", sill_xml("lff_td_threshold"), free=False)
245
+ fx = [(LOAD, load, "load_region", (-0.21, -0.41, -0.20, -0.40)),
246
+ (DELIVER, deliv, "deliver_region", (0.15, -0.41, 0.16, -0.40)),
247
+ (RIDGE, sill, "threshold_region", (0.15, 0.38, 0.16, 0.39))]
248
+ return write_bddl(self.name, self.instruction, objs, fx)
249
+
250
+ def __init__(self, cam_res=None):
251
+ super().__init__(cam_res)
252
+ env = self.env
253
+ m = env.sim.model
254
+ self.area_bid = {a: m.body_name2id(env.fixtures_dict[a].root_body) for a in (LOAD, DELIVER, RIDGE)}
255
+ self.bid = {n: envs.body_id(env, n) for n in BOTTLES + (TRAY,)}
256
+ mm = m._model
257
+ self._bvh0 = {}
258
+ for b in BOTTLES: # compiled inertial frame + BVH (shifted with the hidden COM at every reset)
259
+ bid = self.bid[b]
260
+ adr, num = mm.body_bvhadr[bid], mm.body_bvhnum[bid]
261
+ self._bvh0[b] = (m.body_ipos[bid].copy(), mm.bvh_aabb[adr:adr + num].copy(), adr, num)
262
+ # geom -> object index for the contact checks (0..2 bottles, 3 tray)
263
+ self._obj_of = np.full(m.ngeom, -1, int)
264
+ for k, n in enumerate(BOTTLES + (TRAY,)):
265
+ self._obj_of[envs.obj_geom_ids(env, n)] = k
266
+ self._is_robot = np.zeros(m.ngeom, bool)
267
+ self._is_robot[envs.robot_geom_ids(env)] = True
268
+ sb = self.area_bid[RIDGE]
269
+ self._is_sill = np.array([m.geom_bodyid[g] == sb or m.body_parentid[m.geom_bodyid[g]] == sb
270
+ for g in range(m.ngeom)], bool)
271
+ self._dof = {n: envs.free_joint_addr(env, n)[1] for n in BOTTLES + (TRAY,)}
272
+ self.inst = None
273
+ self.mon = None
274
+
275
+ def sample_instance(self, seed):
276
+ """Layout: the tray's long side runs forward / back (world x); it travels sideways (world y) from the loading
277
+ area to the delivery area, 32-34 cm centre to centre, to the left or to the right, over the threshold strip in
278
+ the middle of the gap between the areas. The bottles stand in a row on the table on the far side of the
279
+ loading area. Tray frame: local +x = direction of travel, handle at local -x."""
280
+ rng = np.random.default_rng(seed)
281
+ s = 1.0 if rng.random() < 0.5 else -1.0 # +1: the tray travels to the robot's left (+y)
282
+ xl, yl = float(rng.uniform(-0.18, -0.15)), float(-s * rng.uniform(0.11, 0.13))
283
+ dist = float(rng.uniform(*AREA_DIST))
284
+ deliver = [xl + float(rng.uniform(-0.01, 0.01)), yl + s * dist]
285
+ yaw = s * np.pi / 2
286
+ R = _rotz2(yaw)
287
+ g0, g1 = LOAD_IN[0] + LINE_W, dist - DELIV_IN[0] - LINE_W # the gap between the areas, along travel
288
+ sill_xy = [(xl + deliver[0]) / 2, float((np.array([xl, yl]) + R @ np.array([(g0 + g1) / 2, 0.0]))[1])]
289
+ jit = np.array([rng.uniform(-0.008, 0.008), rng.uniform(-0.005, 0.005)]) # tray frame
290
+ tray_xy = (np.array([xl, yl]) + R @ (np.array([-FOOT_DX, 0.0]) + jit)).tolist()
291
+ order = [int(i) for i in rng.permutation(3)] # bottle -> position in the start row (along x)
292
+ by = yl - s * (LOAD_IN[0] + LINE_W + 0.04)
293
+ start = {}
294
+ for k, b in enumerate(BOTTLES):
295
+ start[b] = [xl + (-0.12, 0.0, 0.12)[order[k]] + float(rng.uniform(-0.008, 0.008)),
296
+ by + float(rng.uniform(-0.005, 0.005)), float(rng.uniform(-0.35, 0.35))]
297
+ n_top = int(rng.choice(3, p=N_TOP_P))
298
+ top = set(int(i) for i in rng.choice(3, n_top, replace=False))
299
+ hc = {b: float(rng.uniform(*(HC_TOPHEAVY if k in top else HC_STABLE))) for k, b in enumerate(BOTTLES)}
300
+ return dict(seed=int(seed), travel="left" if s > 0 else "right", area_yaw=float(yaw), load_xy=[xl, yl],
301
+ deliver_xy=deliver, sill_xy=sill_xy, tray_xy=tray_xy, tray_yaw=float(yaw), bottle_start=start,
302
+ com_height=hc, top_heavy=[b for k, b in enumerate(BOTTLES) if k in top],
303
+ mu_tray=float(rng.uniform(*MU_TRAY)))
304
+
305
+ def _set_com(self, b, hc):
306
+ """Hidden internal weight: bottle COM at height hc above its bottom (mass and inertia consistent)."""
307
+ m = self.env.sim.model
308
+ mm = m._model
309
+ bid = self.bid[b]
310
+ a, c = BODY[0], BODY[2]
311
+ vb, vn = 8 * a * a * c, np.pi * NECK_R ** 2 * 2 * NECK_H
312
+ zs = ((-BH + c) * vb + (-BH + 2 * c + NECK_H) * vn) / (vb + vn) # shell COM (origin: middle of the height)
313
+ ms, mw = BOT_MASS * (1 - W_FRAC), BOT_MASS * W_FRAC
314
+ zw = float(np.clip((BOT_MASS * (hc - BH) - ms * zs) / mw, -BH + 0.01, BH - 0.01))
315
+ zc = (ms * zs + mw * zw) / BOT_MASS
316
+ ww = 0.025 # the weight is a 2.5 cm cube
317
+ Ixx = ms / 3 * (a * a + c * c) + ms * (zs - zc) ** 2 + mw * (zw - zc) ** 2 + mw * ww * ww / 6
318
+ Izz = ms * 2 * a * a / 3 + mw * ww * ww / 6
319
+ m.body_mass[bid] = BOT_MASS
320
+ m.body_ipos[bid] = [0.0, 0.0, zc]
321
+ m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
322
+ m.body_inertia[bid] = [Ixx, Ixx, Izz]
323
+ ip0, A0, adr, num = self._bvh0[b]
324
+ mm.bvh_aabb[adr:adr + num, :3] = A0[:, :3] - (m.body_ipos[bid] - ip0) # BVH lives in the inertial frame
325
+ return zc + BH
326
+
327
+ def apply_instance(self, inst):
328
+ self.inst = inst
329
+ env = self.env
330
+ m = env.sim.model
331
+ ya = inst["area_yaw"]
332
+ qa = [np.cos(ya / 2), 0.0, 0.0, np.sin(ya / 2)]
333
+ for a, key in ((LOAD, "load_xy"), (DELIVER, "deliver_xy")):
334
+ m.body_pos[self.area_bid[a]] = [inst[key][0], inst[key][1], envs.TABLE_Z + 0.0002]
335
+ m.body_quat[self.area_bid[a]] = qa
336
+ m.body_pos[self.area_bid[RIDGE]] = [inst["sill_xy"][0], inst["sill_xy"][1], envs.TABLE_Z + RIDGE_H - RIDGE_R]
337
+ m.body_quat[self.area_bid[RIDGE]] = qa
338
+ for g in np.flatnonzero(self._is_sill): # the sill's friction wins (the tray's would otherwise: priority 2)
339
+ m.geom_friction[g] = [MU_RIDGE, 0.005, 0.0001]
340
+ m.geom_priority[g] = 4
341
+ envs.set_obj_pose(env, TRAY, [inst["tray_xy"][0], inst["tray_xy"][1], envs.TABLE_Z + PLATE[2] + 0.0005],
342
+ yaw=inst["tray_yaw"])
343
+ envs.set_friction(env, TRAY, inst["mu_tray"], priority=2)
344
+ for b in BOTTLES:
345
+ self._set_com(b, inst["com_height"][b])
346
+ for g in envs.obj_geom_ids(env, b): # bottle params win in all its contacts (tray, table, fingers)
347
+ m.geom_friction[g] = [MU_BOT, 0.005, 0.0001]
348
+ m.geom_condim[g] = 3
349
+ m.geom_priority[g] = 3
350
+ m.geom_solref[g] = BOT_SOLREF
351
+ m.geom_solimp[g] = BOT_SOLIMP
352
+ m.dof_damping[self._dof[b]:self._dof[b] + 6] = DAMP_BOT
353
+ x, y, yaw = inst["bottle_start"][b]
354
+ envs.set_obj_pose(env, b, [x, y, envs.TABLE_Z + BH + 0.0005], yaw=yaw)
355
+
356
+ def reset_instance(self, inst, recorder=None):
357
+ self.env.reset()
358
+ self.apply_instance(inst)
359
+ self.env.sim.forward()
360
+ envs.settle(self.env, 10)
361
+ self.sk = TraySkills(self.env, self, recorder=recorder)
362
+ self._init_monitor()
363
+ return self.sk
364
+
365
+ # ------------------------------------------------------------ geometry / predicates
366
+ def tray_pose(self):
367
+ d = self.env.sim.data
368
+ bid = self.bid[TRAY]
369
+ return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
370
+
371
+ def tray_footprint(self):
372
+ p, R = self.tray_pose()
373
+ loc = np.array([[PLATE[0], PLATE[1]], [PLATE[0], -PLATE[1]], [-PLATE[0], PLATE[1]], [-PLATE[0], -PLATE[1]],
374
+ [BACK_X, CROSS[1]], [BACK_X, -CROSS[1]]])
375
+ return p[:2] + loc @ R[:2, :2].T
376
+
377
+ @staticmethod
378
+ def _word(v):
379
+ """robot-centric word for a horizontal world direction"""
380
+ if abs(v[0]) >= abs(v[1]):
381
+ return "forward" if v[0] > 0 else "back"
382
+ return "left" if v[1] > 0 else "right"
383
+
384
+ def area_excess(self, key):
385
+ """How far the tray footprint sticks out of the area (m, >0 = outside) per edge, keyed by robot-centric word."""
386
+ c = np.asarray(self.inst[key])
387
+ Ra = _rotz2(self.inst["area_yaw"])
388
+ pts = (self.tray_footprint() - c) @ Ra # area frame
389
+ inner = LOAD_IN if key == "load_xy" else DELIV_IN
390
+ out = {}
391
+ for axis, sign in ((0, 1), (0, -1), (1, 1), (1, -1)):
392
+ u = np.zeros(2)
393
+ u[axis] = sign
394
+ out[self._word(Ra @ u)] = float((sign * pts[:, axis]).max() - inner[axis])
395
+ return out
396
+
397
+ def tray_inside(self, key):
398
+ return max(self.area_excess(key).values()) <= 0.0
399
+
400
+ def _contacts(self):
401
+ d = self.env.sim.data
402
+ n = d.ncon
403
+ if not n:
404
+ return np.zeros(0, int), np.zeros(0, int)
405
+ return np.asarray(d.contact.geom1)[:n], np.asarray(d.contact.geom2)[:n]
406
+
407
+ def robot_touch(self):
408
+ """indices (0..2 bottles, 3 tray) of the objects the robot touches now"""
409
+ g1, g2 = self._contacts()
410
+ hit = np.concatenate([self._obj_of[g2[self._is_robot[g1]]], self._obj_of[g1[self._is_robot[g2]]]])
411
+ return set(int(i) for i in hit[hit >= 0])
412
+
413
+ def tray_on_sill(self):
414
+ g1, g2 = self._contacts()
415
+ tray = self._obj_of == 3
416
+ return bool(np.any((tray[g1] & self._is_sill[g2]) | (tray[g2] & self._is_sill[g1])))
417
+
418
+ def bottle_state(self, b, touched=False):
419
+ d = self.env.sim.data
420
+ bid = self.bid[b]
421
+ p = d.body_xpos[bid]
422
+ up = float(d.body_xmat[bid].reshape(3, 3)[2, 2])
423
+ tp, R = self.tray_pose()
424
+ loc = R.T @ (p - tp)
425
+ on_xy = abs(loc[0]) <= PLATE[0] and abs(loc[1]) <= PLATE[1]
426
+ resting = abs(loc[2] - (PLATE[2] + BH)) < 0.012
427
+ upright = up >= COS_UP
428
+ return dict(upright=bool(upright), on_tray=bool(on_xy and resting), touched=bool(touched),
429
+ ok=bool(upright and on_xy and resting and not touched), loc=loc, pos=p.copy(), cos=up)
430
+
431
+ def predicates(self):
432
+ t = self.robot_touch()
433
+ st = {b: self.bottle_state(b, k in t)["ok"] for k, b in enumerate(BOTTLES)}
434
+ st["tray_in_delivery"] = self.tray_inside("deliver_xy")
435
+ st["tray_in_loading"] = self.tray_inside("load_xy")
436
+ return st, t
437
+
438
+ def _tray_speed(self):
439
+ da = self._dof[TRAY]
440
+ return float(np.linalg.norm(self.env.sim.data.qvel[da:da + 2]))
441
+
442
+ # ------------------------------------------------------------ monitor
443
+ def _init_monitor(self):
444
+ st, _ = self.predicates()
445
+ self.mon = dict(stable=dict(st), cnt={k: 0 for k in st}, ever=set(k for k, v in st.items() if v),
446
+ lost=set(), events=[], order_step=None, last_touch={k: -10 ** 6 for k in range(4)},
447
+ last_tray_move=-10 ** 6, last_sill=-10 ** 6, tray_vmax_loaded=0.0, left_unloaded=None,
448
+ on_in_loading=set())
449
+
450
+ def monitor_step(self):
451
+ mon = self.mon
452
+ if mon is None:
453
+ return
454
+ n = self.sk.n_steps
455
+ st, touch = self.predicates()
456
+ for k in touch:
457
+ mon["last_touch"][k] = n
458
+ v = self._tray_speed()
459
+ if v > 0.01:
460
+ mon["last_tray_move"] = n
461
+ if self.tray_on_sill():
462
+ mon["last_sill"] = n
463
+ if all(mon["stable"][b] for b in BOTTLES):
464
+ mon["tray_vmax_loaded"] = max(mon["tray_vmax_loaded"], v)
465
+ for k, val in st.items():
466
+ if val == mon["stable"][k]:
467
+ mon["cnt"][k] = 0
468
+ continue
469
+ mon["cnt"][k] += 1
470
+ if mon["cnt"][k] < DEBOUNCE:
471
+ continue
472
+ mon["stable"][k] = val
473
+ mon["cnt"][k] = 0
474
+ step = n - DEBOUNCE + 1
475
+ if val:
476
+ ev = "restored" if k in mon["lost"] else "achieved"
477
+ mon["ever"].add(k)
478
+ mon["events"].append(dict(step=step, pred=k, ev=ev))
479
+ else:
480
+ mon["lost"].add(k)
481
+ e = dict(step=step, pred=k, ev="lost")
482
+ if k == "tray_in_loading" and mon["order_step"] is None and mon["left_unloaded"] is None:
483
+ mon["left_unloaded"] = step # the tray left the loading area before it was loaded
484
+ if k in BOTTLES:
485
+ j = BOTTLES.index(k)
486
+ moving = n - mon["last_tray_move"] <= 30
487
+ # tray motion first: a bottle toppled by the move often falls against the moving hand
488
+ e["cause"] = ("threshold" if moving and n - mon["last_sill"] <= 40 else
489
+ "tray_moving" if moving else
490
+ "robot" if n - mon["last_touch"][j] <= 20 else "other")
491
+ # a bottle taken off (or knocked off by the robot) while the tray is still in the loading area:
492
+ # the tray is no longer loaded -> the order latch has to be earned again (unload / reload trick)
493
+ if (e["cause"] not in ("threshold", "tray_moving") and mon["stable"]["tray_in_loading"]
494
+ and mon["order_step"] is not None):
495
+ mon["order_step"] = None
496
+ mon["lost"].add("loaded_in_loading_area")
497
+ mon["events"].append(e)
498
+ e = dict(step=step, pred="loaded_in_loading_area", ev="lost")
499
+ mon["events"].append(e)
500
+ if mon["stable"]["tray_in_loading"]:
501
+ mon["on_in_loading"] |= {b for b in BOTTLES if mon["stable"][b]}
502
+ if mon["order_step"] is None and mon["stable"]["tray_in_loading"] and all(mon["stable"][b] for b in BOTTLES):
503
+ mon["order_step"] = n
504
+ mon["events"].append(dict(step=n, pred="loaded_in_loading_area",
505
+ ev="restored" if "loaded_in_loading_area" in mon["lost"] else "achieved"))
506
+
507
+ # ------------------------------------------------------------ outcome / F2
508
+ def _static(self):
509
+ d = self.env.sim.data
510
+ for nm in BOTTLES + (TRAY,):
511
+ da = self._dof[nm]
512
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.15:
513
+ return False
514
+ return True
515
+
516
+ def _where(self, b, bs):
517
+ """robot-centric description of where a bottle is (relative to the tray)"""
518
+ if bs["on_tray"]:
519
+ return "on the tray"
520
+ tp, R = self.tray_pose()
521
+ lx, ly = R[:2, :2].T @ (bs["pos"][:2] - tp[:2])
522
+ if abs(lx) <= PLATE[0] and abs(ly) <= PLATE[1]:
523
+ return "on the tray"
524
+ if abs(lx) <= PLATE[0] + 0.04 and abs(ly) <= PLATE[1] + 0.04:
525
+ return "partly on the tray"
526
+ v = R[:2, 0] * np.sign(lx) if abs(lx) - PLATE[0] >= abs(ly) - PLATE[1] else R[:2, 1] * np.sign(ly)
527
+ side = {"forward": "in front of", "back": "behind", "left": "to the left of",
528
+ "right": "to the right of"}[self._word(v)]
529
+ return f"on the table, {side} the tray"
530
+
531
+ @staticmethod
532
+ def _names(bs):
533
+ cols = [COLOR_OF[b] for b in bs]
534
+ if len(cols) == 1:
535
+ return f"the {cols[0]} bottle"
536
+ return "the " + ", the ".join(cols[:-1]) + f" and the {cols[-1]} bottles"
537
+
538
+ def outcome(self, inst):
539
+ sk = self.sk
540
+ sk.hold(30) # let everything settle (keeps the gripper as it is)
541
+ mon = self.mon
542
+ touch = self.robot_touch()
543
+ bst = {b: self.bottle_state(b, k in touch) for k, b in enumerate(BOTTLES)}
544
+ delivered = self.tray_inside("deliver_xy")
545
+ static = self._static()
546
+ order_ok = mon["order_step"] is not None
547
+ all_ok = all(s["ok"] for s in bst.values())
548
+ success = bool(order_ok and delivered and all_ok and static)
549
+ ev = mon["events"]
550
+ stage_preds = set(BOTTLES) | {"tray_in_delivery"}
551
+ n_reg = sum(1 for e in ev if e["ev"] == "lost" and e["pred"] in stage_preds)
552
+ n_res = sum(1 for e in ev if e["ev"] == "restored" and e["pred"] in stage_preds)
553
+ fell_moving = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") in ("threshold",
554
+ "tray_moving")})
555
+ fell_sill = sorted({e["pred"] for e in ev if e["ev"] == "lost" and e.get("cause") == "threshold"})
556
+ fallen = [b for b in BOTTLES if not bst[b]["upright"]]
557
+ off = [b for b in BOTTLES if bst[b]["upright"] and not bst[b]["on_tray"]]
558
+ held = [b for b in BOTTLES if bst[b]["upright"] and bst[b]["on_tray"] and bst[b]["touched"]]
559
+ # failure code = the first unmet requirement, in task order: loading -> order -> bottles -> delivery -> rest
560
+ if not order_ok:
561
+ failure = "order" if mon["left_unloaded"] is not None else "not_loaded"
562
+ elif fallen:
563
+ failure = "bottle_fallen"
564
+ elif off:
565
+ failure = "bottle_off_tray"
566
+ elif not delivered:
567
+ failure = "not_delivered"
568
+ elif held:
569
+ failure = "held"
570
+ elif not static:
571
+ failure = "not_static"
572
+ else:
573
+ failure = None
574
+ # F2 text (robot-centric words, no coordinates); the first sentence names the failure
575
+ parts = []
576
+ if failure == "not_loaded":
577
+ missing = [b for b in BOTTLES if b not in mon["on_in_loading"]]
578
+ parts.append(f"Loading was not completed: {self._names(missing)} never stood on the tray while it was in "
579
+ f"the yellow loading area." if missing else
580
+ "Loading was not completed: the three bottles never stood on the tray at the same time while "
581
+ "it was in the yellow loading area.")
582
+ elif failure == "order":
583
+ parts.append("The tray left the yellow loading area before all three bottles stood on it (load all three "
584
+ "first, then move the loaded tray).")
585
+ bottle_txt = []
586
+ for b in BOTTLES:
587
+ s, col = bst[b], COLOR_OF[b]
588
+ if s["ok"]:
589
+ bottle_txt.append(f"The {col} bottle stands upright on the tray.")
590
+ elif not s["upright"]:
591
+ bottle_txt.append(f"The {col} bottle has fallen over and lies {self._where(b, s)}.")
592
+ elif not s["on_tray"]:
593
+ bottle_txt.append(f"The {col} bottle stands upright {self._where(b, s)}, not on the tray.")
594
+ else:
595
+ bottle_txt.append(f"The {col} bottle stands on the tray but the gripper is still touching it.")
596
+ if delivered:
597
+ tray_txt = "The tray is completely inside the purple delivery area."
598
+ else:
599
+ ex = self.area_excess("deliver_xy")
600
+ out = [f"{max(100 * v, 0.1):.1f} cm beyond its {k} edge" for k, v in ex.items() if v > 0]
601
+ tray_txt = "The tray is not completely inside the purple delivery area: it sticks out " + \
602
+ " and ".join(out) + "."
603
+ if failure in ("not_delivered",):
604
+ parts += [tray_txt] + bottle_txt
605
+ else:
606
+ parts += bottle_txt + [tray_txt]
607
+ if fell_moving:
608
+ how = " while the tray crossed the threshold strip" if fell_sill == fell_moving else \
609
+ " while the tray was moving"
610
+ txt = self._names(fell_moving)
611
+ parts.append(txt[0].upper() + txt[1:] + f" fell over{how}.")
612
+ if failure == "not_static":
613
+ parts.append("Something was still moving at the end.")
614
+ return dict(success=success, failure=failure,
615
+ stages={**{COLOR_OF[b]: bool(bst[b]["ok"]) for b in BOTTLES}, "tray_in_delivery": bool(delivered),
616
+ "loaded_in_loading_area": bool(order_ok), "static": bool(static)},
617
+ events=list(ev), n_regressions=int(n_reg), n_restored=int(n_res),
618
+ order_step=mon["order_step"], left_loading_unloaded=mon["left_unloaded"],
619
+ tray_vmax_loaded=round(mon["tray_vmax_loaded"], 3),
620
+ fell_while_moving=[COLOR_OF[b] for b in fell_moving],
621
+ fell_at_threshold=[COLOR_OF[b] for b in fell_sill], detail=" ".join(parts))
622
+
623
+ # ------------------------------------------------------------ scripted primitives (move_to + gripper only)
624
+ def _slot_world(self, j):
625
+ tp, R = self.tray_pose()
626
+ return tp[:2] + R[:2, :2] @ np.array([SLOT_LX, SLOT_LY[j]])
627
+
628
+ @staticmethod
629
+ def _yaw_window(a):
630
+ """the gripper-symmetric equivalent of yaw `a` in [-0.5, pi - 0.5) (keeps the last wrist joint off its limit)"""
631
+ return float((a + 0.5) % np.pi - 0.5)
632
+
633
+ def tray_yaw(self):
634
+ return _yaw_of(self.tray_pose()[1])
635
+
636
+ def transit(self, xy, z, yaw=None, z_safe=SAFE_Z):
637
+ """up to z_safe (if lower), across, then down to z"""
638
+ sk = self.sk
639
+ e = sk.eef_pos()
640
+ if e[2] < z_safe - 0.01:
641
+ sk.move_to([e[0], e[1], z_safe], speed=0.3)
642
+ sk.move_to([xy[0], xy[1], z_safe], yaw=None if yaw is None else self._yaw_window(yaw), wrap_yaw=False)
643
+ sk.move_to([xy[0], xy[1], z], tol=0.003, max_steps=200)
644
+
645
+ def _travel_dir(self):
646
+ tp, R = self.tray_pose()
647
+ u = R[:2, 0] / np.linalg.norm(R[:2, 0])
648
+ foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0])
649
+ return tp, R, u, float((np.asarray(self.inst["deliver_xy"]) - foot) @ u)
650
+
651
+ def push_tray(self, speed, gap=0.03, segments=1, z=PUSH_Z, yaw=None, approach=None):
652
+ """the pilot agents' move: closed gripper `gap` behind the handle's cross bar (hand's long side along the bar),
653
+ push along the travel direction until the footprint centre is level with the delivery area's centre;
654
+ `segments` > 1 stops in between; `approach` (m/s): first creep up to the bar at that speed, stop, then push"""
655
+ sk = self.sk
656
+ tp, R, u, dist = self._travel_dir()
657
+ back = tp[:2] + R[:2, :2] @ np.array([BACK_X, 0.0])
658
+ if yaw is None: # yaw 0 = fingers closing along world y; this yaw puts the hand's long side across u
659
+ yaw = float(np.arctan2(u[1], u[0]))
660
+ s0 = back - u * (0.012 + gap) # the closed fingers are ~2.4 cm thick along the push
661
+ sk.set_gripper(True, steps=8)
662
+ self.transit(s0, z, yaw=yaw)
663
+ if approach:
664
+ s0 = back - u * 0.010 # just touching
665
+ sk.move_to([s0[0], s0[1], z], speed=approach, tol=0.003, max_steps=int(gap / approach / 0.05) + 40)
666
+ sk.hold(6)
667
+ gap = 0.0
668
+ total = gap + dist
669
+ for k in range(segments):
670
+ e = s0 + u * total * (k + 1) / segments
671
+ sk.move_to([e[0], e[1], z], speed=speed, tol=0.004,
672
+ max_steps=int(total / segments / speed / 0.05) + 60 if speed else 250)
673
+ sk.hold(6)
674
+ e = sk.eef_pos()[:2] - u * 0.03
675
+ sk.move_to([e[0], e[1], z], speed=0.1)
676
+ sk.move_to([e[0], e[1], z + 0.15], speed=0.25)
677
+
678
+ def drag_tray(self, speed, z=DRAG_Z, cross=False):
679
+ """the careful move: grasp the handle and move the tray with it (the hand keeps the trailing edge down on the
680
+ sill). Default: the stem, fingers closing across its 3 cm width (hand's long side along the tray's long side);
681
+ cross=True: the cross bar, fingers closing across its 2.5 cm depth (hand's long side along the travel)."""
682
+ sk = self.sk
683
+ tp, R, u, dist = self._travel_dir()
684
+ lx = -PLATE[0] - 2 * STEM[0] - CROSS[0] if cross else -PLATE[0] - STEM[0]
685
+ c = tp[:2] + R[:2, :2] @ np.array([lx, 0.0])
686
+ yaw = float(np.arctan2(u[1], u[0])) + (np.pi / 2 if cross else 0.0)
687
+ sk.set_gripper(False, steps=8)
688
+ self.transit(c, z, yaw=yaw)
689
+ sk.set_gripper(True, steps=15)
690
+ e = c + u * dist
691
+ sk.move_to([e[0], e[1], z], speed=speed, tol=0.004,
692
+ max_steps=int(dist / speed / 0.05) + 80 if speed else 250)
693
+ sk.hold(6)
694
+ sk.set_gripper(False, steps=12)
695
+ e = sk.eef_pos()
696
+ sk.move_to([e[0], e[1], e[2] + 0.15], speed=0.25)
697
+
698
+ def pick_upright(self, b, jitter=None, yaw=0.0):
699
+ """grasp the neck of a standing bottle from above (the palm stays above the bottle's top)"""
700
+ sk = self.sk
701
+ p = envs.obj_pos(self.env, b)
702
+ top = envs.obj_max_z(self.env, b)
703
+ xy = p[:2] + (np.zeros(2) if jitter is None else jitter)
704
+ sk.set_gripper(False, steps=8)
705
+ self.transit(xy, top - GRASP_TOP, yaw)
706
+ sk.set_gripper(True, steps=15)
707
+ sk.move_to([xy[0], xy[1], SAFE_Z_HELD], speed=0.25)
708
+ return sk.eef_pos()[2] - envs.obj_min_z(self.env, b) # grasp height actually held
709
+
710
+ def place_at(self, b, xy, held_h, release=0.006):
711
+ sk = self.sk
712
+ self.transit(xy, PLATE_TOP + release + held_h + 0.03, z_safe=SAFE_Z_HELD)
713
+ sk.hold(10) # let a hanging bottle stop swinging
714
+ sk.move_to([xy[0], xy[1], PLATE_TOP + release + held_h], speed=0.08, tol=0.003, max_steps=150)
715
+ sk.hold(4)
716
+ sk.set_gripper(False, steps=12)
717
+ sk.move_to([xy[0], xy[1], SAFE_Z], speed=0.25)
718
+
719
+ def load_all(self, rng=None):
720
+ """every bottle goes to the tray slot on the same side as its start position (a carried bottle never passes
721
+ over a standing one); the hand's long side across the row. With `rng`: +-5 mm on every grasp / placement."""
722
+ tp, R = self.tray_pose()
723
+ ay = R[:2, 1]
724
+ yaw = self.tray_yaw() - np.pi / 2
725
+ by_y = sorted(BOTTLES, key=lambda b: float(np.asarray(self.inst["bottle_start"][b][:2]) @ ay))
726
+ for j, b in enumerate(by_y):
727
+ jg, jp = (None, None) if rng is None else (rng.uniform(-0.005, 0.005, 2), rng.uniform(-0.005, 0.005, 2))
728
+ h = self.pick_upright(b, jitter=jg, yaw=yaw)
729
+ self.place_at(b, self._slot_world(j) + (0 if jp is None else jp), h)
730
+
731
+ def free_slot(self, exclude):
732
+ """a tray slot at least 7 cm from every other bottle (standing or lying); among those the one farthest from the
733
+ robot; else the emptiest slot"""
734
+ tp, R = self.tray_pose()
735
+ others = [R[:2, :2].T @ (self.bottle_state(o)["pos"][:2] - tp[:2]) for o in BOTTLES if o not in exclude]
736
+ cand = []
737
+ for j, ly in enumerate(SLOT_LY):
738
+ dmin = min([np.linalg.norm(np.array([SLOT_LX, ly]) - o) for o in others] + [1.0])
739
+ cand.append((dmin >= 0.07, float(self._slot_world(j)[0]) if dmin >= 0.07 else dmin, j))
740
+ return self._slot_world(max(cand)[2])
741
+
742
+ def restand(self, b):
743
+ """a fallen bottle: grasp its neck across (fingers closing across the neck), lift -- it swings down and hangs
744
+ from the neck -- and set it down on a free slot. A bottle standing off the tray: pick it up by the neck."""
745
+ sk = self.sk
746
+ st = self.bottle_state(b)
747
+ if st["upright"]:
748
+ h = self.pick_upright(b, yaw=self.tray_yaw() - np.pi / 2)
749
+ self.place_at(b, self.free_slot({b}), h)
750
+ return
751
+ for tries in range(2):
752
+ st = self.bottle_state(b)
753
+ R = self.env.sim.data.body_xmat[self.bid[b]].reshape(3, 3)
754
+ ax = R[:, 2] # bottle axis (bottom -> neck)
755
+ u = ax[:2] / max(np.linalg.norm(ax[:2]), 1e-6)
756
+ neck = st["pos"] + ax * (BH - GRASP_TOP)
757
+ yaw = float(np.arctan2(u[1], u[0])) # fingers close across the neck
758
+ sk.set_gripper(False, steps=8)
759
+ self.transit(neck[:2], max(neck[2], envs.TABLE_Z + 0.008), yaw)
760
+ sk.set_gripper(True, steps=15)
761
+ if sk.holding(b) or tries:
762
+ break
763
+ # a finger landed on the tray's edge next to the neck: slide the bottle 5 cm away from the tray, retry
764
+ tp = self.tray_pose()[0]
765
+ v = st["pos"][:2] - tp[:2]
766
+ v = v / max(np.linalg.norm(v), 1e-6)
767
+ sk.set_gripper(False, steps=8)
768
+ sk.move_to(sk.eef_pos() + [0.0, 0.0, 0.05], speed=0.1)
769
+ self.push_point(st["pos"][:2] - v * 0.015, v, 0.065, speed=0.05, z=PLATE_TOP + 0.012)
770
+ sk.move_to([neck[0], neck[1], SAFE_Z_HELD], speed=0.15)
771
+ sk.hold(20)
772
+ held = sk.eef_pos()[2] - envs.obj_min_z(self.env, b)
773
+ self.place_at(b, self.free_slot({b}), held)
774
+
775
+ def push_point(self, p, u, dist, speed=0.03, z=None):
776
+ """closed gripper: from 3 cm behind point `p` (direction `u`) push `dist` metres along u, back off, lift"""
777
+ sk = self.sk
778
+ z = PUSH_Z if z is None else z
779
+ s0 = np.asarray(p) - u * 0.03
780
+ sk.set_gripper(True, steps=8)
781
+ self.transit(s0, z, yaw=float(np.arctan2(u[1], u[0])))
782
+ e = s0 + u * (0.018 + dist)
783
+ sk.move_to([e[0], e[1], z], speed=speed, tol=0.003, max_steps=600)
784
+ sk.hold(4)
785
+ e = sk.eef_pos()[:2] - u * 0.03
786
+ sk.move_to([e[0], e[1], z], speed=0.1)
787
+ sk.move_to([e[0], e[1], SAFE_Z], speed=0.25)
788
+
789
+ def fix_tray(self, speed=V_CAREFUL):
790
+ """straighten the tray by slowly pushing the trailing corner that lags behind, then grasp the handle's stem
791
+ and move the tray, without turning it, until its footprint is centred in the delivery area"""
792
+ sk = self.sk
793
+ y1 = self.inst["area_yaw"]
794
+ u1 = _rotz2(y1)[:, 0]
795
+ for _ in range(3):
796
+ err = (self.tray_yaw() - y1 + np.pi) % (2 * np.pi) - np.pi
797
+ if abs(err) < np.radians(3):
798
+ break
799
+ tp, R = self.tray_pose()
800
+ corners = [tp[:2] + R[:2, :2] @ np.array([-PLATE[0], e * (PLATE[1] - 0.02)]) for e in (1.0, -1.0)]
801
+ a = [float((c - tp[:2]) @ u1) for c in corners]
802
+ k = int(np.argmin(a))
803
+ self.push_point(corners[k], u1, 0.6 * (max(a) - min(a)), speed=speed)
804
+ tp, R = self.tray_pose()
805
+ h0 = tp[:2] + R[:2, :2] @ np.array([-PLATE[0] - STEM[0], 0.0])
806
+ foot = tp[:2] + R[:2, :2] @ np.array([FOOT_DX, 0.0])
807
+ h1 = h0 + (np.asarray(self.inst["deliver_xy"]) - foot)
808
+ d = float(np.linalg.norm(h1 - h0))
809
+ if d < 0.004:
810
+ return
811
+ sk.set_gripper(False, steps=8)
812
+ self.transit(h0, DRAG_Z, yaw=self.tray_yaw()) # fingers close across the stem's width
813
+ sk.set_gripper(True, steps=15)
814
+ sk.move_to([h1[0], h1[1], DRAG_Z], speed=speed, tol=0.003, max_steps=int(d / speed / 0.05) + 80)
815
+ sk.hold(5)
816
+ sk.set_gripper(False, steps=12)
817
+ e = sk.eef_pos()
818
+ sk.move_to([e[0], e[1], SAFE_Z], speed=0.2)
819
+
820
+ def check_and_restore(self, rounds=3):
821
+ """the final check: bottles not upright on the tray -> stand them up on a free slot (farthest from the robot
822
+ first); then, if the tray is not completely in the delivery area, move it there slowly by the handle"""
823
+ for _ in range(rounds):
824
+ bad = [b for b in BOTTLES if not self.bottle_state(b)["ok"]]
825
+ if not bad and self.tray_inside("deliver_xy"):
826
+ return
827
+ for b in sorted(bad, key=lambda o: -float(self.bottle_state(o)["pos"][0])):
828
+ self.restand(b)
829
+ self.sk.hold(10)
830
+ if not self.tray_inside("deliver_xy"):
831
+ self.fix_tray()
832
+ self.sk.hold(10)
833
+
834
+ def execute(self, inst, params):
835
+ rng = np.random.default_rng(params.get("seed")) if params.get("jitter") else None
836
+ self.load_all(rng)
837
+ if params.get("mode", "push") == "drag":
838
+ self.drag_tray(params["speed"])
839
+ else:
840
+ self.push_tray(params["speed"], gap=params.get("gap", 0.03), segments=params.get("segments", 1))
841
+ if params.get("check"):
842
+ self.check_and_restore()
843
+
844
+ def default_params(self, inst):
845
+ """naive = the pilot agents' style: load all three, push the handle with the closed gripper at ~4.5 cm/s"""
846
+ return dict(speed=V_NAIVE, mode="push", check=False)
847
+
848
+ def oracle_params(self, inst):
849
+ return dict(speed=V_CAREFUL, mode="drag", check=True)
850
+
851
+ def adapt_params(self, inst, history):
852
+ return dict(speed=V_CAREFUL, mode="drag", check=True)
853
+
854
+ def blind_params(self, inst, attempt, rng):
855
+ return dict(speed=float(rng.uniform(0.03, 0.06)), mode="push", segments=int(rng.integers(1, 3)),
856
+ check=False, jitter=True, seed=int(rng.integers(1 << 30)))
857
+
858
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
859
+ """cross protocol; adaptive = naive + check-and-restore in attempt 1, careful (drag by the handle) + check
860
+ afterwards"""
861
+ k = k or self.max_attempts
862
+ rng = np.random.default_rng(seed)
863
+ history = []
864
+ for a in range(k):
865
+ self.reset_instance(inst)
866
+ if kind == "oracle":
867
+ params = self.oracle_params(inst)
868
+ elif kind == "naive":
869
+ params = self.default_params(inst)
870
+ elif kind == "adaptive":
871
+ params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
872
+ elif kind == "blind":
873
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
874
+ else:
875
+ raise ValueError(kind)
876
+ self.execute(inst, params)
877
+ out = self.outcome(inst)
878
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
879
+ if on_attempt:
880
+ on_attempt(a, params, out)
881
+ if out["success"] or kind in ("oracle", "naive"):
882
+ break
883
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/agent_viewer/viewer.html ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
5
+ <title>Agent Viewer · 历史回放</title>
6
+ <style>
7
+ :root{color-scheme:light;--bg:#f6f7f6;--paper:#fff;--text:#192b31;--muted:#62747a;--border:#dfe7e6;--teal:#087f79;--soft:#e9f5f1;--orange:#b56624;--red:#af4545;--mono:ui-monospace,SFMono-Regular,Consolas,monospace;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:var(--text);background:var(--bg)}
8
+ *{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,select{cursor:pointer}button{border:1px solid var(--border);background:var(--paper);color:var(--text);border-radius:7px;padding:9px 13px;font-size:13px}button:hover{background:var(--soft)}button:disabled{opacity:.4;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #55bbb1;outline-offset:2px}button.active,button[aria-pressed="true"]{border-color:var(--teal);color:var(--teal);background:var(--soft)}.primary{background:var(--teal);border-color:var(--teal);color:white}.primary:hover{background:#076762}.muted{color:var(--muted)}.mono,code{font-family:var(--mono)}.eyebrow{font-size:10px;text-transform:uppercase;letter-spacing:1.7px;font-weight:700;color:var(--muted)}
9
+ header{height:72px;padding:0 28px;display:flex;align-items:center;gap:18px;border-bottom:1px solid var(--border);background:var(--paper)}.brand{font-size:21px;font-weight:750;letter-spacing:-.6px;display:flex;align-items:center;gap:11px}.brandmark{background:var(--teal);color:#fff;border-radius:9px;padding:4px 8px;font-size:20px}.divider{height:23px;width:1px;background:var(--border)}.mode{margin-left:auto;font-size:12px;color:var(--teal);background:var(--soft);padding:7px 12px;border-radius:6px}.shell{display:grid;grid-template-columns:235px minmax(0,1fr);min-height:calc(100vh - 72px)}aside{padding:27px 18px;border-right:1px solid var(--border);background:#f9faf9}.aside-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:21px;font-size:13px}.run{display:block;text-align:left;width:100%;padding:15px 13px;border-radius:9px;margin-bottom:9px}.run strong{display:block;font-size:13px;line-height:1.6;overflow-wrap:anywhere}.run small{display:block;line-height:1.9;color:var(--muted);font-size:11px}.run .state{font-size:11px;color:var(--teal);margin-bottom:9px;display:block}.aside-section{border-top:1px solid var(--border);margin-top:27px;padding-top:22px}.attempt{display:block;width:100%;text-align:left;margin-top:9px;font-size:12px}.attempt span{float:right}.success{color:var(--teal)}.failed{color:var(--red)}.aside-note{font-size:11px;line-height:1.9;margin-top:25px;color:var(--muted)}
10
+ main{min-width:0;padding:28px 30px}.heading{display:flex;justify-content:space-between;gap:20px;align-items:flex-start;margin-bottom:22px}h1{font-size:26px;letter-spacing:-.8px;line-height:1.3;margin:7px 0 9px}h2{font-size:15px;margin:0}h3{font-size:13px;margin:0}.subtitle{font-size:12px;line-height:1.8;color:var(--muted)}.pill{display:inline-block;white-space:nowrap;font-size:11px;padding:6px 10px;border-radius:20px;background:var(--soft);color:var(--teal)}.workspace{display:grid;grid-template-columns:minmax(320px,1.5fr) minmax(280px,1fr);gap:22px}.panel{background:var(--paper);border:1px solid var(--border);border-radius:12px;overflow:hidden}.panel-top{display:flex;align-items:center;justify-content:space-between;padding:17px 19px;border-bottom:1px solid var(--border);gap:10px}.panel-top small{font-size:11px;color:var(--muted)}.switches{padding:14px 18px;display:flex;gap:7px;flex-wrap:wrap}.switches button{font-size:11px;padding:7px 10px}.image-stage{background:#e9eeec;margin:0 18px;min-height:230px;display:grid;place-items:center;position:relative;border-radius:7px;overflow:hidden}.image-stage img{display:block;width:100%;height:clamp(290px,36vw,480px);object-fit:contain}.image-stage .empty{padding:45px;text-align:center;color:var(--muted);line-height:1.8}.caption{padding:12px 19px;font-size:11px;color:var(--muted);line-height:1.7;overflow-wrap:anywhere}.camera-strip{display:flex;gap:12px;padding:0 18px 18px;flex-wrap:wrap}.camera{display:grid;grid-template-columns:58px 1fr;align-items:center;gap:9px;text-align:left;padding:5px 10px 5px 5px;min-width:140px}.camera img{width:58px;height:46px;object-fit:contain;background:#e9eeec;border-radius:4px}.camera span{font-size:11px}.task{margin:0 18px 18px;padding:14px 0 0;border-top:1px solid var(--border);font-size:12px;line-height:1.8}.task p{margin:6px 0 0}.step-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px}.step-title small{font-size:11px;color:var(--muted)}.flowcard{background:var(--paper);border:1px solid var(--border);border-radius:10px;margin-bottom:12px;padding:16px}.cardtitle{display:flex;align-items:center;gap:9px;margin-bottom:12px;font-size:12px;font-weight:650}.number{color:var(--muted);background:var(--bg);border:1px solid var(--border);border-radius:5px;padding:4px;font:10px var(--mono)}.flowcard p{font-size:12px;line-height:1.8;margin:7px 0;color:var(--muted)}pre{margin:9px 0 0;font:11px/1.7 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere;background:var(--bg);border:1px solid var(--border);padding:12px;border-radius:6px;max-height:230px;overflow:auto}details{margin-top:9px}summary{font-size:11px;color:var(--muted);cursor:pointer;padding:5px 0}.result-message{font-size:13px;line-height:1.8}.notice{border:1px solid #e9cfab;background:#fff8ec;color:#89541d;padding:10px 12px;border-radius:7px;margin-top:10px;font-size:11px;line-height:1.8}.statement{border-left:2px solid var(--teal);padding-left:10px;font-size:12px;line-height:1.8;margin:12px 0}.subtle{font-size:11px;line-height:1.8;color:var(--muted)}
11
+ .timeline{margin-top:22px;padding:18px 20px}.controls{display:flex;align-items:center;gap:9px;flex-wrap:wrap}.controls .count{font:12px var(--mono);margin:0 8px}.controls select{padding:7px;border:1px solid var(--border);background:var(--paper);border-radius:6px;font-size:11px}.controls small{margin-left:auto;font-size:11px;color:var(--muted)}input[type=range]{width:100%;accent-color:var(--teal);margin:18px 0 10px;cursor:pointer}.filmstrip{display:flex;gap:9px;overflow-x:auto;padding:3px 0 7px;scroll-behavior:smooth}.frame{flex:0 0 95px;padding:4px;position:relative}.frame img,.frame .placeholder{display:block;width:85px;height:64px;object-fit:contain;background:#e9eeec;border-radius:4px}.frame .label{display:block;font-size:10px;margin:7px 0 3px}.frame .dot{position:absolute;top:8px;right:8px;border:2px solid white;width:10px;height:10px;border-radius:50%;background:var(--teal)}.frame .dot.bad{background:var(--orange)}.timeline-foot{display:flex;justify-content:space-between;gap:15px;font-size:10px;color:var(--muted);margin-top:10px;line-height:1.8}footer{display:flex;justify-content:space-between;font-size:10px;color:var(--muted);margin-top:18px;gap:15px;line-height:1.8}.warning-list{font-size:11px;color:var(--orange)}
12
+ @media(min-width:1600px){main{max-width:1600px;width:100%;margin:auto}}@media(max-width:1100px){.shell{grid-template-columns:185px minmax(0,1fr)}main{padding:23px 20px}.workspace{gap:15px;grid-template-columns:minmax(250px,1.2fr) minmax(250px,1fr)}aside{padding:25px 12px}.image-stage img{height:320px}}@media(max-width:850px){.shell{display:block}aside{border-right:0;border-bottom:1px solid var(--border);padding:15px 20px}.aside-title,.aside-note,.aside-section .eyebrow{display:none}#runs{display:flex;gap:10px}.run{width:auto;min-width:190px;margin:0}.aside-section{margin:12px 0 0;padding:0;border:0;display:flex;gap:8px}.attempt{width:auto}.attempt span{float:none;margin-left:10px}.workspace{grid-template-columns:minmax(0,1fr)}.image-stage img{height:400px}header{padding:0 18px;height:63px}.heading{margin-bottom:17px}main{padding:22px 18px}.details-col{display:grid;grid-template-columns:1fr 1fr;gap:12px}.step-title{grid-column:1/-1;margin-bottom:0}.flowcard{margin:0}.flowcard:last-child{grid-column:1/-1}}@media(max-width:480px){header .divider,header>.muted{display:none}header{gap:8px}.brand{font-size:18px}.mode{font-size:10px;padding:6px 8px}.heading{display:block}h1{font-size:23px}.heading>.pill{margin-top:9px}.details-col{display:block}.flowcard{margin-top:12px}.image-stage{margin:0 10px}.image-stage img{height:280px}.panel-top{padding:14px}.camera-strip{padding:0 10px 12px;gap:6px}.camera{min-width:120px;padding-right:6px;grid-template-columns:42px 1fr}.camera img{width:42px;height:38px}.timeline{padding:14px 10px}.controls{gap:5px}.controls .count{margin:0 3px;font-size:10px}.controls small{display:none}.controls button{padding:9px 10px}.timeline-foot,footer{flex-direction:column;gap:3px}}
13
+ [hidden]{display:none!important}.view-tabs{display:flex;gap:8px;margin-bottom:18px}.video-panel{margin-bottom:22px}.video-stage{background:#101817;padding:16px;text-align:center}.video-stage video{display:block;width:100%;max-height:68vh;min-height:200px;margin:auto;aspect-ratio:640/376;background:#101817}.video-toolbar{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:14px 19px}.video-toolbar label{font-size:12px}.video-toolbar select{padding:6px;border:1px solid var(--border);border-radius:6px;background:var(--paper);color:var(--text)}.video-toolbar .subtle{margin-left:auto}.video-note{padding:0 19px 16px;font-size:12px;line-height:1.8;color:var(--muted)}
14
+ .reason-copy{white-space:pre-wrap;font-size:12px;line-height:1.8;background:var(--soft);border-radius:7px;padding:12px;margin:9px 0}.reason-empty{background:none;color:var(--muted);padding:0}.reason-public{white-space:pre-wrap;font-size:12px;line-height:1.8;border-left:2px solid var(--teal);padding-left:10px;margin:9px 0}.view-tabs{flex-wrap:wrap}
15
+ </style>
16
+ </head>
17
+ <body>
18
+ <header><div class="brand"><span class="brandmark">⌘</span>Agent Viewer</div><span class="divider"></span><span class="muted" style="font-size:12px">LFF-Bench</span><span class="mode">◷ 历史回放</span></header>
19
+ <div class="shell">
20
+ <aside><div class="aside-title"><strong>运行记录</strong><span id="run-count" class="muted"></span></div><nav id="runs" aria-label="运行记录"></nav><div class="aside-section" id="attempts"></div><div class="aside-note">回放已保存的观察与工具记录。<br>画面来自模型输入的历史图片文件。<br>视频支持连续播放与全屏。<br>逐步视图:← → 切换,空格播放。</div></aside>
21
+ <main>
22
+ <div class="heading"><div><div class="eyebrow">OBSERVE / ACT / REVIEW</div><h1 id="title"></h1><div class="subtitle" id="subtitle"></div></div><span id="status" class="pill"></span></div>
23
+ <div class="view-tabs" aria-label="回放视图"><button id="video-tab" aria-pressed="false">▶ 完整执行视频</button><button id="steps-tab" aria-pressed="false">逐步输入与日志</button></div>
24
+ <section id="video-view" class="panel video-panel" hidden><div class="panel-top"><h2>完整执行录像</h2><small>主相机 + 腕部相机</small></div><div class="video-stage"><video id="execution-video" controls playsinline preload="metadata" aria-label="任务完整执行录像">浏览器不支持视频播放。</video></div><div class="video-toolbar"><label for="video-rate">播放速度</label><select id="video-rate"><option value="0.3333333333333333">⅓×</option><option value="0.5">0.5×</option><option value="1" selected>1× 原录像</option><option value="2">2×</option></select><span class="subtle">连续播放 · 拖动进度 · 全屏查看</span></div><div class="video-note">播放原始执行录像,保留尝试切换与结果画面。录像时间不等于日志中的等待时间;查看单步输入与工具返回可切换到“逐步输入与日志”。</div><div id="video-error" class="notice" hidden role="alert"></div></section>
25
+ <div id="step-view"><div class="workspace">
26
+ <section class="panel"><div class="panel-top"><h2>Agent 看到的画面</h2><small id="attempt-label"></small></div><div class="switches"><button id="before" aria-pressed="true">决策前 · 最近观察</button><button id="after" aria-pressed="false">执行后 · 返回图片</button></div><div class="image-stage" id="stage"></div><div class="caption" id="caption"></div><div class="camera-strip" id="cameras"></div><div class="task"><span class="eyebrow">TASK</span><p id="task"></p></div></section>
27
+ <section class="details-col" aria-label="当前步骤"><div class="step-title"><h2 id="step-title"></h2><small id="time"></small></div><div class="flowcard"><div class="cardtitle"><span class="number">01</span>观察输入</div><div id="observation-note" class="subtle"></div><details><summary>查看最近输入文本</summary><pre id="input-text"></pre></details></div><div class="flowcard"><div class="cardtitle"><span class="number">02</span>步骤间思考</div><div id="reason-transition" class="subtle"></div><div id="reason-summary" class="reason-copy"></div><div id="reason-public-wrap"><span class="subtle">Agent 文字说明</span><div id="reason-public" class="reason-public"></div></div><details><summary>前一步反馈与记录来源</summary><pre id="reason-feedback"></pre><p id="reason-source" class="subtle"></p><p class="subtle">显示已记录的模型摘要与文字回复,不代表完整内部 CoT。</p></details></div><div class="flowcard"><div class="cardtitle"><span class="number">03</span>执行动作</div><div id="actions"></div></div><div class="flowcard"><div class="cardtitle"><span class="number">04</span>执行反馈</div><div id="results"></div><div id="notices"></div></div></section>
28
+ </div>
29
+ <section class="panel timeline" aria-label="回放时间轴"><div class="controls"><button id="prev" aria-label="上一步">←</button><button id="play" class="primary" aria-label="播放回放">▶ 播放</button><button id="next" aria-label="下一步">→</button><span class="count" id="count" aria-live="polite"></span><select id="speed" aria-label="每步播放时长"><option value="2000">2 秒 / 步</option><option value="1000">1 秒 / 步</option><option value="4000">4 秒 / 步</option></select><small>按步骤播放 · 不按实际等待时间</small></div><input id="scrubber" type="range" min="0" value="0" aria-label="选择回放步骤"><div class="filmstrip" id="filmstrip"></div><div class="timeline-foot"><span>● 绿色:尝试成功 ● 橙色:失败 / API 重试</span><span id="step-meta"></span></div></section>
30
+ </div>
31
+ <div id="warnings" class="warning-list"></div><footer><span>真实历史记录 · 原始执行录像与输入图片 · 离线可用</span><span>逐步视图展示最近观察;模型上下文可能包含更早图片。</span></footer>
32
+ </main></div>
33
+ <script id="viewer-data" type="application/json">/*__PAYLOAD__*/null</script>
34
+ <script>
35
+ 'use strict';
36
+ const DATA=JSON.parse(document.getElementById('viewer-data').textContent);
37
+ const $=id=>document.getElementById(id);
38
+ const names={l5_slide_to_target:'把红色方块滑入目标区',l1_bias_place:'校准偏差下的抓取放置'};
39
+ let runIndex=0, index=0, phase='before', camera='agentview', selectedFrameKey=null, timer=null, viewMode='steps';
40
+ const run=()=>DATA.runs[runIndex];
41
+ const step=()=>run().steps[index];
42
+ function el(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}
43
+ function fmt(value){return typeof value==='string'?value:JSON.stringify(value,null,2);}
44
+ function clock(seconds){const s=Math.max(0,Math.round(seconds||0));return `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;}
45
+ function cameraName(name){return name==='agentview'?'主相机':name==='wrist'?'腕部相机':name;}
46
+ function stop(){if(timer)clearInterval(timer);timer=null;$('play').textContent='▶ 播放';$('play').setAttribute('aria-label','播放回放');}
47
+ function setMode(mode){stop();viewMode=mode==='video'&&run().video?'video':'steps';$('video-view').hidden=viewMode!=='video';$('step-view').hidden=viewMode!=='steps';$('video-tab').setAttribute('aria-pressed',String(viewMode==='video'));$('steps-tab').setAttribute('aria-pressed',String(viewMode==='steps'));if(viewMode!=='video')$('execution-video').pause();}
48
+ function setupVideo(){const v=$('execution-video');v.pause();v.removeAttribute('src');$('video-error').hidden=true;$('video-tab').disabled=!run().video;if(run().video)v.src=DATA.assets[run().video.asset];v.load();$('video-rate').value='1';v.playbackRate=1;setMode(run().video?'video':'steps');}
49
+ function move(value,manual=true){if(manual)stop();index=Math.max(0,Math.min(run().steps.length-1,value));render();}
50
+ function img(frame){const image=el('img');image.alt=`${cameraName(frame.camera)} · ${frame.path}`;image.src=DATA.assets[frame.asset];return image;}
51
+ function allAfter(s){return s.actions.flatMap(a=>a.after||[]);}
52
+ function renderRun(){
53
+ const r=run();$('title').textContent=names[r.task]||r.task;$('subtitle').textContent=`${r.model} / seed ${r.seed??'—'} / ${r.actionCount} 次工具调用 / ${r.feedback} · ${r.perception}`;
54
+ $('task').textContent=r.taskText;$('status').textContent=r.status==='success'?'● 最终成功':r.status==='failed'?'● 尝试未成功':'◌ 记录未完成';
55
+ $('status').style.color=r.status==='failed'?'var(--red)':'';$('run-count').textContent=DATA.runs.length;
56
+ $('runs').replaceChildren(...DATA.runs.map((item,n)=>{const b=el('button',undefined,'run'+(n===runIndex?' active':''));b.setAttribute('aria-pressed',String(n===runIndex));b.append(el('span',item.status==='success'?'● 已完成 · 成功':'◌ '+(item.status==='failed'?'未成功':'未完成'),'state'),el('strong',names[item.task]||item.task),el('small',`${item.model} · seed ${item.seed??'—'}`),el('small',`${item.steps.length} 步决策 · ${item.outcomes.length} 次提交`));b.onclick=()=>{stop();runIndex=n;index=0;phase='before';renderRun();render();};return b;}));
57
+ $('attempts').replaceChildren(el('div','ATTEMPTS','eyebrow'),...r.outcomes.map(o=>{const b=el('button',`第 ${o.attempt} 次尝试`,'attempt');b.append(el('span',o.success?'成功 ↗':'失败 ↗',o.success?'success':'failed'));b.title=o.feedback;b.onclick=()=>{setMode('steps');phase='before';move(r.steps.findIndex(s=>s.verdict?.attempt===o.attempt));};return b;}));
58
+ $('scrubber').max=r.steps.length-1;
59
+ $('warnings').replaceChildren(...r.warnings.map(w=>el('p',w)));
60
+ $('filmstrip').replaceChildren(...r.steps.map((s,n)=>{const b=el('button',undefined,'frame');b.setAttribute('aria-label',`第 ${n+1} 步,尝试 ${s.attempt}`);const f=s.before.find(f=>f.camera==='agentview')||s.before[0];b.append(f?.asset?img(f):el('span','无图片','placeholder'));b.append(el('span',`${String(n+1).padStart(2,'0')} · 尝试 ${s.attempt}`,'label'));if(s.verdict||s.notices.length)b.append(el('span',undefined,'dot'+(s.verdict?.success?'':' bad')));b.onclick=()=>move(n);return b;}));
61
+ setupVideo();
62
+ }
63
+ function renderReason(){
64
+ const s=step(),previous=run().steps[index-1];
65
+ $('reason-transition').textContent=index===0?'任务输入 → 第 1 步':`第 ${index} 步反馈 → 第 ${index+1} 步决策`;
66
+ $('reason-feedback').textContent=previous?previous.actions.map(a=>a.result===null?'结果未记录':fmt(a.result)).join('\n\n')||previous.text||'没有工具反馈':s.inputText||'初始输入未记录';
67
+ $('reason-summary').textContent=s.decisionSummary||(s.decisionSummaryStatus==='not_returned'?'模型未返回摘要。':'本步未记录摘要。');
68
+ $('reason-summary').classList.toggle('reason-empty',!s.decisionSummary);
69
+ $('reason-public-wrap').hidden=!s.text;$('reason-public').textContent=s.text||'';
70
+ $('reason-source').textContent=`来源:${run().source} 第 ${s.decisionSourceLine} 行 · turn ${s.turn??'—'}`;
71
+ }
72
+ function render(){
73
+ renderReason();
74
+ const r=run(),s=step(),after=allAfter(s),frames=phase==='before'?s.before:after;
75
+ const selected=frames.find(f=>`${f.path}@${f.source}`===selectedFrameKey)||frames.find(f=>f.camera===camera)||frames[0];if(selected)camera=selected.camera;
76
+ $('before').setAttribute('aria-pressed',String(phase==='before'));$('after').setAttribute('aria-pressed',String(phase==='after'));
77
+ $('attempt-label').textContent=`尝试 ${s.attempt} · 步骤 ${index+1}`;$('step-title').textContent=`Step ${String(index+1).padStart(2,'0')}`;
78
+ $('time').textContent=`+${clock(s.elapsed)}${s.latency==null?'':` · 模型耗时 ${s.latency.toFixed(1)}s`}`;
79
+ $('stage').replaceChildren(selected?.asset?img(selected):el('div',selected?'该图片文件缺失':'此步骤没有返回新图片','empty'));
80
+ const reset=s.actions.find(a=>a.resetToAttempt);
81
+ $('caption').textContent=selected?`${cameraName(selected.camera)} · ${selected.path} · 来源:transcript 第 ${selected.source} 行${phase==='after'&&reset?` · 已重置为尝试 ${reset.resetToAttempt}`:''}`:'日志未记录新图片;切换“决策前”查看最近观察。';
82
+ $('cameras').replaceChildren(...frames.map((f,n)=>{const b=el('button',undefined,'camera');b.setAttribute('aria-pressed',String(f===selected));if(f.asset)b.append(img(f));b.append(el('span',cameraName(f.camera)));b.onclick=()=>{camera=f.camera;selectedFrameKey=`${f.path}@${f.source}`;render();};return b;}));
83
+ $('observation-note').textContent=`最近一次收到 ${s.before.length} 张图片${s.requestImages==null?'':`;本次请求记录共 ${s.requestImages} 张图片(含历史)`}。`;
84
+ $('input-text').textContent=s.inputText||'没有记录输入文本。';
85
+ $('actions').replaceChildren(...s.actions.map(a=>{const box=el('div');box.append(el('div',a.name,'subtle'),el('pre',fmt(a.arguments)));return box;}));
86
+ if(!s.actions.length)$('actions').append(el('p','本步没有工具调用,Agent 输出最终报告。'));
87
+ $('results').replaceChildren();
88
+ if(s.verdict){$('results').append(el('div',s.verdict.success?'✓ 本次尝试成功':'↻ 本次尝试失败',`result-message ${s.verdict.success?'success':'failed'}`),el('p',s.verdict.feedback));}
89
+ for(const a of s.actions){
90
+ if(!s.verdict)$('results').append(el('div',a.result===null?'等待结果 / 日志缺失':a.ok===false?'工具返回错误':'工具已返回',`result-message ${a.ok===false?'failed':''}`));
91
+ if(a.resetToAttempt)$('results').append(el('div',`场景已重置:返回图片属于第 ${a.resetToAttempt} 次尝试。`,'notice'));
92
+ const d=el('details');d.append(el('summary',`${a.name} · 完整返回`),el('pre',a.result===null?'未记录':fmt(a.result)));$('results').append(d);
93
+ }
94
+ if(!s.actions.length)$('results').append(el('p','最终文字报告;结果以尝试判定为准。'));
95
+ const notices=[...s.notices,...(s.noticesAfter||[])];$('notices').replaceChildren(...notices.map(n=>el('div',`${n.kind==='api_error'?'API 重试':'运行中断'} · ${n.text}`,'notice')));
96
+ $('count').textContent=`${String(index+1).padStart(2,'0')} / ${r.steps.length}`;$('scrubber').value=index;$('prev').disabled=index===0;$('next').disabled=index===r.steps.length-1;
97
+ $('step-meta').textContent=`turn ${s.turn??'—'} · ${s.actions.length} 次工具调用${s.incomplete?' · 结果不完整':''}`;
98
+ [...$('filmstrip').children].forEach((b,n)=>b.setAttribute('aria-pressed',String(n===index)));
99
+ const selectedButton=$('filmstrip').children[index];if(selectedButton){const strip=$('filmstrip'),a=selectedButton.getBoundingClientRect(),b=strip.getBoundingClientRect();if(a.left<b.left||a.right>b.right)strip.scrollLeft+=a.left-b.left-strip.clientWidth/2+selectedButton.offsetWidth/2;}
100
+ }
101
+ $('prev').onclick=()=>move(index-1);$('next').onclick=()=>move(index+1);$('scrubber').oninput=e=>move(Number(e.target.value));
102
+ $('before').onclick=()=>{phase='before';render();};$('after').onclick=()=>{phase='after';render();};
103
+ $('play').onclick=()=>{if(timer){stop();return;}if(index===run().steps.length-1)move(0);$('play').textContent='Ⅱ 暂停';$('play').setAttribute('aria-label','暂停回放');timer=setInterval(()=>{if(index>=run().steps.length-1){stop();return;}move(index+1,false);if(index===run().steps.length-1)stop();},Number($('speed').value));};
104
+ $('speed').onchange=()=>{if(timer){stop();$('play').click();}};
105
+ $('video-tab').onclick=()=>setMode('video');$('steps-tab').onclick=()=>setMode('steps');
106
+ $('video-rate').onchange=e=>{$('execution-video').playbackRate=Number(e.target.value);};
107
+ $('execution-video').onerror=()=>{if(!run().video)return;$('video-error').textContent='视频加载失败,请刷新重试;仍可查看逐步输入与日志。';$('video-error').hidden=false;};
108
+ document.addEventListener('keydown',e=>{if(viewMode==='video')return;if(e.target.closest('input,select,textarea,button,summary'))return;if(e.key==='ArrowLeft'){e.preventDefault();move(index-1);}if(e.key==='ArrowRight'){e.preventDefault();move(index+1);}if(e.code==='Space'&&viewMode==='steps'){e.preventDefault();$('play').click();}});
109
+ renderRun();render();
110
+ </script>
111
+ </body></html>
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/scripts/check_breakfast_service.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Development physical/reference-policy validation. Never starts model evaluation."""
2
+ import argparse, concurrent.futures, hashlib, json, os, time
3
+ from pathlib import Path
4
+
5
+ TASK=None
6
+ def init_worker():
7
+ global TASK
8
+ from lffbench.tasks.lh_breakfast_service import BreakfastService
9
+ TASK=BreakfastService()
10
+
11
+ def plain(v):
12
+ return v.item() if hasattr(v,'item') else v.tolist()
13
+
14
+ def run_one(job):
15
+ kind,seed,outdir=job;t=TASK;start=time.time();inst=t.sample_instance(seed)
16
+ hist=t.run_scripted(kind,inst,k=5,seed=seed+42)
17
+ row=dict(kind=kind,seed=seed,instance=inst,history=hist,trace=t.trace,
18
+ control_steps=t.sk.n_steps,primitive_count=len(t.sk.log),wall_s=time.time()-start,
19
+ pull_probe=getattr(t,'pull_probe',None))
20
+ dest=Path(outdir)/f'{kind}_{seed}.json';dest.write_text(json.dumps(row,indent=2,default=plain)+'\n')
21
+ return dict(kind=kind,seed=seed,success=hist[-1]['outcome']['success'],
22
+ traps=hist[-1]['outcome']['traps'],recovered=hist[-1]['outcome']['recovered'],
23
+ cup_ml=hist[-1]['outcome']['cup_ml'],spill_ml=hist[-1]['outcome']['spill_ml'],
24
+ file=str(dest),wall_s=row['wall_s'])
25
+
26
+ def main():
27
+ p=argparse.ArgumentParser();p.add_argument('--n',type=int,default=20)
28
+ p.add_argument('--policies',default='adaptive,oracle,naive,blind');p.add_argument('--workers',type=int,default=2)
29
+ p.add_argument('--out',required=True);args=p.parse_args();out=Path(args.out);out.mkdir(parents=True,exist_ok=True)
30
+ root=Path(__file__).resolve().parents[1]
31
+ files=[root/'lffbench/tasks'/n for n in ('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')]
32
+ hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files}
33
+ (out/'source_hashes.json').write_text(json.dumps(hashes,indent=2))
34
+ jobs=[(kind,seed,str(out)) for seed in range(1000,1000+args.n) for kind in args.policies.split(',')]
35
+ rows=[]
36
+ with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers,initializer=init_worker) as pool:
37
+ for row in pool.map(run_one,jobs):
38
+ rows.append(row);print(json.dumps(row),flush=True)
39
+ (out/'progress.json').write_text(json.dumps(rows,indent=2))
40
+ final_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files}
41
+ summary=dict(n=args.n,source_unchanged=hashes==final_hashes,policies={},rows=rows)
42
+ for kind in args.policies.split(','):
43
+ r=[x for x in rows if x['kind']==kind]
44
+ summary['policies'][kind]=dict(success=sum(x['success'] for x in r),total=len(r),
45
+ all_traps_and_recovery=sum(x['success'] and all(x['traps'].values()) and all(x['recovered'].values()) for x in r))
46
+ (out/'summary.json').write_text(json.dumps(summary,indent=2));print(json.dumps(summary['policies']),flush=True)
47
+
48
+ if __name__=='__main__':main()