PeterXie666 commited on
Commit
1c4dad4
·
verified ·
1 Parent(s): 96fab24

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/final/episode_000387.npz +3 -0
  2. leaf/final/episode_000694_image.png +3 -0
  3. leaf/final/episode_001244_wrist_image.png +3 -0
  4. leaf/final/episode_001271_wrist_image.png +3 -0
  5. leaf/final/episode_001324.npz +3 -0
  6. leaf/final/episode_001550_image.png +3 -0
  7. leaf/final/episode_002565_image.png +3 -0
  8. leaf/final/episode_002718.npz +3 -0
  9. leaf/final/episode_003262_wrist_image.png +3 -0
  10. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py +40 -0
  11. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py +61 -0
  12. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/codex_catalogs/native_0.163.0.json +0 -0
  13. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
  14. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json +15 -0
  15. 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-v4.1-flash_high.json +15 -0
  16. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +23 -0
  17. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l2_restore_layout.py +502 -0
  18. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l6_swap.py +466 -0
  19. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py +1273 -0
  20. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-v4.1-flash_high.json +15 -0
  21. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json +23 -0
  22. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json +36 -0
  23. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/make_video.py +132 -0
  24. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/client/lffbench_client/__init__.py +139 -0
  25. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/codex_catalogs/generic_0.163.0.json +64 -0
  26. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/codex_catalogs/native_0.163.0.json +0 -0
  27. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
  28. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json +15 -0
  29. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/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/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
  31. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json +23 -0
  32. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json +36 -0
  33. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json +23 -0
  34. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json +36 -0
  35. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json +15 -0
  36. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_viewer/README.md +150 -0
  37. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_viewer/export.py +219 -0
  38. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_viewer/live.py +406 -0
  39. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_viewer/viewer.html +111 -0
  40. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/__init__.py +0 -0
  41. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l2_knock.py +457 -0
  42. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l6_sequence.py +513 -0
  43. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py +398 -0
  44. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py +468 -0
  45. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_split_calibration.py +142 -0
  46. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/batches.json +9 -0
  47. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/rejected.json +1 -0
  48. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/client/pyproject.toml +13 -0
  49. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/evaluation_tool_caps.json +5 -0
  50. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/__init__.py +1 -0
leaf/final/episode_000387.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:479f85e0b95ed43b0ddf478028fdc5202a1577655f1488895852bc61fe623d8c
3
+ size 4046
leaf/final/episode_000694_image.png ADDED

Git LFS Details

  • SHA256: 3160b2adcf9a9c6dca71691c10b87a3269718ec8e67be3d93daf81127a78e247
  • Pointer size: 130 Bytes
  • Size of remote file: 56.7 kB
leaf/final/episode_001244_wrist_image.png ADDED

Git LFS Details

  • SHA256: 2fc17e12ba14108a6a2302a2c3dada759e22364f6dd689b968aa183c1afa87a7
  • Pointer size: 130 Bytes
  • Size of remote file: 35.3 kB
leaf/final/episode_001271_wrist_image.png ADDED

Git LFS Details

  • SHA256: 0505b5e39d004d8612667227c40e5edf17f011c4b0c98d3081cb11d846bd8fb0
  • Pointer size: 130 Bytes
  • Size of remote file: 22.1 kB
leaf/final/episode_001324.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:185d0f992a444c85184a782bb16e5bb09aec4e68d7417be28b4c30ddc93c515d
3
+ size 3838
leaf/final/episode_001550_image.png ADDED

Git LFS Details

  • SHA256: 81834db5353fa8d98b4ab7174d15058d940f20fe8ed8719269bfae77c390636f
  • Pointer size: 130 Bytes
  • Size of remote file: 57.3 kB
leaf/final/episode_002565_image.png ADDED

Git LFS Details

  • SHA256: a3fd82f0b8c3faf0c08fd5e00d3ab31be0974a91fe7e13782e0cf25693497e2e
  • Pointer size: 130 Bytes
  • Size of remote file: 60.1 kB
leaf/final/episode_002718.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60a7c146d6618daf000b95e3f91d1015af15256d9afd15f53e7f1faf82ba7af2
3
+ size 3630
leaf/final/episode_003262_wrist_image.png ADDED

Git LFS Details

  • SHA256: 964db48ba8d72a8a766b36dba4806b54b71a24e92c72172568d265739afa687b
  • Pointer size: 130 Bytes
  • Size of remote file: 21 kB
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_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/breakfast-v2-20261103-breakfast_v2_20261103_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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/codex_catalogs/native_0.163.0.json ADDED
The diff for this file is too large to render. See raw diff
 
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
3
+ "fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4",
4
+ "written": "2026-10-20 02:16:14",
5
+ "summary": {
6
+ "system_chars": 26736,
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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-opus-5-5|high",
3
+ "fingerprint_sha256": "1e12511be3f4985ca25bad34cc2db4a0b317d6565b2d12034672aaac2d97bc85",
4
+ "written": "2026-10-21 05:19:32",
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-opus-5-5"
14
+ }
15
+ }
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-v4.1-flash_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-v4.1-flash|high",
3
+ "fingerprint_sha256": "c5305ffa663057875e7ec2ef2900433eb510f1ee6b3fab7fb7acdca3c289cdc6",
4
+ "written": "2026-10-30 16:00:21",
5
+ "summary": {
6
+ "system_chars": 6052,
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-v4.1-flash"
14
+ }
15
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
4
+ "written": "2026-10-26 07:02:41",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "gpt-6.1-sol",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l2_restore_layout.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was.
2
+
3
+ Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare
4
+ table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the
5
+ robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the
6
+ first frame.
7
+
8
+ Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the
9
+ neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the
10
+ ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is
11
+ real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still
12
+ succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim
13
+ back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in
14
+ its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was).
15
+
16
+ Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
17
+ round chosen by the policy; the outcome (success + F2 text) is computed after each round.
18
+
19
+ Scripted references
20
+ oracle knows the victim: right after the main task it puts the victim back at its saved start pose.
21
+ naive main task, then done.
22
+ adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are
23
+ out of place (Retrieve their saved poses) and puts them back (Utilize).
24
+ blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the
25
+ basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind.
26
+ nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows
27
+ which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw).
28
+ """
29
+ import numpy as np
30
+
31
+ from .. import envs
32
+ from ..bddl import write_bddl
33
+ from ..task_base import LFFTask, register_task
34
+
35
+ TARGET = "ketchup_1"
36
+ BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
37
+ BASKET = "basket_1"
38
+ ITEMS = (TARGET,) + BOXES
39
+
40
+ # LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer
41
+ BASKET_IN = 0.060 # half size of the inner floor
42
+ BASKET_RIM = 0.150 # rim height above the basket's lowest point
43
+ BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
44
+ BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout)
45
+
46
+ POS_TOL = 0.03 # success: box centre within 3 cm of its start
47
+ YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180)
48
+ STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start
49
+
50
+ REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres
51
+ KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest
52
+ MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base
53
+ BASE_X = -0.66
54
+ R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm)
55
+ GAP = 0.03 # free space between footprints (finger room)
56
+ SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table
57
+ SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached
58
+
59
+ NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
60
+ "chocolate_pudding_1": "chocolate pudding", BASKET: "basket"}
61
+ DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
62
+ "chocolate_pudding_1": "brown box", BASKET: "wicker basket"}
63
+
64
+
65
+ def _qz(a):
66
+ return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
67
+
68
+
69
+ def _wrap_half(a):
70
+ """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
71
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
72
+
73
+
74
+ def _seg_dist(p, a, b):
75
+ """distance from point p to segment a-b (2D)"""
76
+ p, a, b = (np.asarray(v, float) for v in (p, a, b))
77
+ ab = b - a
78
+ t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0)
79
+ return float(np.linalg.norm(p - (a + t * ab)))
80
+
81
+
82
+ def _in_rect(xy, r):
83
+ return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3]
84
+
85
+
86
+ def _reach_ok(xy):
87
+ return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH
88
+
89
+
90
+ @register_task
91
+ class RestoreLayout(LFFTask):
92
+ name = "l2_restore_layout"
93
+ level = "L2"
94
+ category = "state_restoration"
95
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
96
+ protocol = "within"
97
+ max_attempts = 5
98
+ instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it "
99
+ "is now, in the same position and orientation.")
100
+ instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay "
101
+ "exactly where it is now, in the same position and orientation.")
102
+ knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
103
+
104
+ def __init__(self, cam_res=None):
105
+ super().__init__(cam_res)
106
+ # upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down;
107
+ # basket and boxes are upright in their mesh frame
108
+ self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
109
+ self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
110
+ self._inj = None
111
+ self.start = {}
112
+ self._home = None
113
+ # per-control-step monitor on env.step: also sees attempts driven by the agent harness
114
+ orig_step = self.env.step
115
+
116
+ def step(action):
117
+ ret = orig_step(action)
118
+ if self._inj is not None:
119
+ self._knock_step()
120
+ return ret
121
+
122
+ self.env.step = step
123
+
124
+ # ------------------------------------------------------------ scene
125
+ def make_bddl(self):
126
+ names = [*ITEMS, BASKET]
127
+ objs = []
128
+ for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
129
+ x0 = -0.30 + 0.13 * (i % 3)
130
+ y0 = -0.25 + 0.25 * (i // 3)
131
+ objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
132
+ return write_bddl(self.name, self.instruction, objs)
133
+
134
+ def sample_instance(self, seed):
135
+ rng = np.random.default_rng(seed)
136
+ for _ in range(5000):
137
+ basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)])
138
+ k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)])
139
+ victim = str(rng.choice(BOXES))
140
+ others = [b for b in BOXES if b != victim]
141
+ a_v = rng.uniform(0, 2 * np.pi)
142
+ r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02)
143
+ pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])}
144
+ ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim])
145
+ for o in others:
146
+ if not ok:
147
+ break
148
+ for _ in range(200):
149
+ p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])])
150
+ if not _reach_ok(p):
151
+ continue
152
+ if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP:
153
+ continue
154
+ if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET):
155
+ continue
156
+ pos[o] = p
157
+ break
158
+ else:
159
+ ok = False
160
+ if not ok:
161
+ continue
162
+ if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS):
163
+ continue
164
+ # the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign)
165
+ ang = a_v + rng.uniform(-np.radians(35), np.radians(35))
166
+ dist = rng.uniform(0.09, 0.14)
167
+ u = np.array([np.cos(ang), np.sin(ang)])
168
+ end = pos[victim] + dist * u
169
+ if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)):
170
+ continue
171
+ if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03:
172
+ continue
173
+ # the path and the resting spot keep clear of the other boxes (finger room around the victim too)
174
+ if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others):
175
+ continue
176
+ if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others):
177
+ continue
178
+ if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP:
179
+ continue
180
+ turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80)))
181
+ return dict(seed=int(seed),
182
+ basket_xy=basket.round(4).tolist(),
183
+ xy={n: pos[n].round(4).tolist() for n in ITEMS},
184
+ yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES},
185
+ TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))},
186
+ # hidden variables of the injected failure
187
+ victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn,
188
+ knock_end=end.round(4).tolist())
189
+ raise RuntimeError("could not sample a layout")
190
+
191
+ def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
192
+ """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only)."""
193
+ q = envs._quat_mul(_qz(yaw), self.q_up[name])
194
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
195
+ self.env.sim.forward()
196
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
197
+ qa, _ = envs.free_joint_addr(self.env, name)
198
+ self.env.sim.data.qpos[qa + 2] -= dz
199
+ self.env.sim.forward()
200
+
201
+ def apply_instance(self, inst):
202
+ envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock)
203
+ self.place(BASKET, inst["basket_xy"], 0.0)
204
+ for n in ITEMS:
205
+ self.place(n, inst["xy"][n], inst["yaw"][n])
206
+ self.env.sim.forward()
207
+
208
+ def reset_instance(self, inst, recorder=None):
209
+ self._inj = None
210
+ sk = super().reset_instance(inst, recorder)
211
+ self.start = {n: self.footprint(n) for n in ITEMS}
212
+ self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0)
213
+ self._home = sk.eef_pos()
214
+ return sk
215
+
216
+ # ------------------------------------------------------------ measurements
217
+ def footprint(self, name):
218
+ """Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range.
219
+ Scripted policies use it as a stand-in for perception."""
220
+ m, d = self.env.sim.model, self.env.sim.data
221
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
222
+ best = None
223
+ for g in envs.obj_geom_ids(self.env, name):
224
+ R = d.geom_xmat[g].reshape(3, 3)
225
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
226
+ e = np.abs(R) @ m.geom_aabb[g, 3:]
227
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
228
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
229
+ if best is None or vol > best[0]:
230
+ best = (vol, R, m.geom_aabb[g, 3:])
231
+ _, R, half = best
232
+ horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
233
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
234
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
235
+ half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
236
+
237
+ def body_yaw(self, name):
238
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
239
+ return float(np.arctan2(R[1, 0], R[0, 0]))
240
+
241
+ # ------------------------------------------------------------ failure injection (physical knock)
242
+ def _knock_step(self):
243
+ st = self._inj
244
+ if st["done"]:
245
+ if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps)
246
+ self._spin(st)
247
+ return
248
+ if self.sk is None:
249
+ return
250
+ if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
251
+ return
252
+ if not self.sk.holding(TARGET):
253
+ return
254
+ st["done"] = True
255
+ inst = st["inst"]
256
+ v = inst["victim"]
257
+ if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL:
258
+ return # the victim was moved beforehand: nothing happens
259
+ qa, da = envs.free_joint_addr(self.env, v)
260
+ v0 = np.sqrt(inst["knock_dist"] / SLIDE_K)
261
+ dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])])
262
+ d = self.env.sim.data
263
+ d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0]
264
+ st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"],
265
+ spin_steps=6)
266
+ self._spin(st)
267
+
268
+ def _spin(self, st):
269
+ v = st["inst"]["victim"]
270
+ _, da = envs.free_joint_addr(self.env, v)
271
+ turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0
272
+ rest = st["spin_left"] - turned
273
+ st["spin_steps"] -= 1
274
+ if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]):
275
+ st["spin_steps"] = 0
276
+ return
277
+ # measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short
278
+ w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W))
279
+ self.env.sim.data.qvel[da + 5] = np.sign(rest) * w
280
+
281
+ # ------------------------------------------------------------ outcome
282
+ def where_target(self):
283
+ """'basket', 'gripper', 'table' or 'other' for the ketchup."""
284
+ f = self.footprint(TARGET)
285
+ c = np.array(f["center"])
286
+ if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02:
287
+ return "gripper", f
288
+ bp = envs.obj_pos(self.env, BASKET)
289
+ if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM:
290
+ return "basket", f
291
+ if f["zmin"] < envs.TABLE_Z + 0.01:
292
+ return "table", f
293
+ return "other", f
294
+
295
+ def box_state(self, name):
296
+ """Pose error of a box w.r.t. its start pose and where it is."""
297
+ f = self.footprint(name)
298
+ s = self.start[name]
299
+ c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2])
300
+ dpos = float(np.linalg.norm(c - c0))
301
+ dyaw = _wrap_half(f["yaw"] - s["yaw"])
302
+ held = bool(self.sk is not None and self.sk.holding(name))
303
+ upright = envs.obj_upright_cos(self.env, name) > 0.9
304
+ on_table = f["zmin"] < envs.TABLE_Z + 0.01
305
+ bp = envs.obj_pos(self.env, BASKET)
306
+ loc = ("gripper" if held else
307
+ "basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else
308
+ "table" if on_table and upright else
309
+ "table_tipped" if on_table else "other")
310
+ ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL)
311
+ return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"],
312
+ offset=(c - c0).tolist())
313
+
314
+ @staticmethod
315
+ def _offset_words(off, dyaw):
316
+ """robot-centric words for a displacement (current - start) and turn (for the offset tier only)"""
317
+ parts = []
318
+ if abs(off[0]) >= 0.005:
319
+ parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}")
320
+ if abs(off[1]) >= 0.005:
321
+ parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}")
322
+ s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot"
323
+ if abs(dyaw) >= np.radians(3):
324
+ s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)"
325
+ return s
326
+
327
+ def _describe(self, tloc, boxes, names, offset=False):
328
+ tn = names[TARGET]
329
+ msgs = []
330
+ if tloc != "basket":
331
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
332
+ "table": f"The {tn} is on the table, not in the basket."}
333
+ .get(tloc, f"The {tn} is not in the basket."))
334
+ for n in BOXES:
335
+ b = boxes[n]
336
+ if b["ok"]:
337
+ continue
338
+ if b["loc"] == "gripper":
339
+ msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.")
340
+ continue
341
+ if b["loc"] == "basket":
342
+ msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.")
343
+ continue
344
+ if b["loc"] == "table_tipped":
345
+ msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.")
346
+ continue
347
+ if b["loc"] != "table":
348
+ msgs.append(f"The {names[n]} is not where it was at the start.")
349
+ continue
350
+ what = []
351
+ if b["dpos"] > POS_TOL:
352
+ what.append("position")
353
+ if abs(b["dyaw"]) > YAW_TOL:
354
+ what.append("orientation")
355
+ m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)."
356
+ if offset:
357
+ m += f" It is {self._offset_words(b['offset'], b['dyaw'])}."
358
+ msgs.append(m)
359
+ if not msgs:
360
+ msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.")
361
+ return " ".join(msgs)
362
+
363
+ def outcome(self, inst):
364
+ envs.settle(self.env, 30)
365
+ tloc, tf = self.where_target()
366
+ boxes = {n: self.box_state(n) for n in BOXES}
367
+ moved = [n for n in BOXES if not boxes[n]["ok"]]
368
+ success = bool(tloc == "basket" and not moved)
369
+ return dict(success=success, target_loc=tloc, moved=moved,
370
+ boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4),
371
+ dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()},
372
+ knocked=bool(self._inj and self._inj["knocked"]),
373
+ detail=self._describe(tloc, boxes, NAMES),
374
+ detail_indirect=self._describe(tloc, boxes, DESCR),
375
+ detail_offset=self._describe(tloc, boxes, NAMES, offset=True))
376
+
377
+ def feedback(self, inst, out, level="F2", indirect=False, offset=False):
378
+ """F0: nothing, F1: success flag, F2: which item is out of place (never where it was).
379
+ offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric
380
+ words -- this externalises the memory and is not the default."""
381
+ if level == "F2":
382
+ key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
383
+ out = dict(out, detail=out.get(key, out["detail"]))
384
+ return super().feedback(inst, out, level)
385
+
386
+ # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only)
387
+ def go_home(self):
388
+ """End of an attempt: lift the arm out of the camera's way."""
389
+ sk = self.sk
390
+ p = sk.eef_pos()
391
+ sk.move_to([p[0], p[1], max(p[2], self._home[2])])
392
+ sk.move_to(self._home)
393
+
394
+ def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None,
395
+ travel_z=1.15):
396
+ """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
397
+ object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis."""
398
+ sk = self.sk
399
+ f = fp or self.footprint(name)
400
+ c = np.array(f["center"])
401
+ h = f["zmax"] - f["zmin"]
402
+ gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
403
+ if name == TARGET:
404
+ zg = f["zmax"] - 0.035
405
+ else:
406
+ zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site
407
+ sk.set_gripper(False, steps=6)
408
+ p = sk.eef_pos()
409
+ if p[2] < travel_z - 0.02:
410
+ sk.move_to([p[0], p[1], travel_z])
411
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
412
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
413
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
414
+ sk.set_gripper(True, steps=12)
415
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
416
+ gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
417
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
418
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2,
419
+ max_steps=150)
420
+ sk.hold(4)
421
+ sk.set_gripper(False, steps=10)
422
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
423
+
424
+ def main_task(self, fp=None):
425
+ """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
426
+ b = envs.obj_pos(self.env, BASKET)
427
+ floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
428
+ self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
429
+
430
+ def restore(self, name, pose):
431
+ """Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw)."""
432
+ self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05,
433
+ clearance=0.004)
434
+
435
+ def do(self, actions, inst):
436
+ for act in actions:
437
+ if act[0] == "ketchup_to_basket":
438
+ self.main_task(fp=act[1] if len(act) > 1 else None)
439
+ elif act[0] == "restore": # ["restore", name, pose]
440
+ self.restore(act[1], act[2])
441
+ else:
442
+ raise ValueError(act)
443
+
444
+ # ------------------------------------------------------------ scripted reference policies
445
+ def _guess_pose(self, name, rng):
446
+ """nomem control: a random free spot within 15 cm of where the box is now, random yaw."""
447
+ cur = np.array(self.footprint(name)["center"][:2])
448
+ others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name]
449
+ for _ in range(200):
450
+ r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi)
451
+ p = cur + r * np.array([np.cos(a), np.sin(a)])
452
+ if _in_rect(p, KNOCK_REGION) and _reach_ok(p) and all(np.linalg.norm(p - o) > 2 * R_BOX + 0.01 for o in others):
453
+ return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
454
+ return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
455
+
456
+ def _plan(self, kind, inst, a, history, rng, memory):
457
+ """Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose]."""
458
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
459
+ return [["ketchup_to_basket"]]
460
+ if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory)
461
+ return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]]
462
+ last = history[-1]["outcome"]
463
+ if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were
464
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
465
+ return acts + [["restore", n, memory[n]] for n in last["moved"]]
466
+ if kind == "nomem": # F2 but no start frame: guesses
467
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
468
+ return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]]
469
+ if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
470
+ fp = self.footprint(TARGET)
471
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
472
+ return [["ketchup_to_basket", fp]]
473
+ raise ValueError(kind)
474
+
475
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
476
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
477
+ k = k or self.max_attempts
478
+ rng = np.random.default_rng(seed)
479
+ history = []
480
+ self.reset_instance(inst)
481
+ memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save
482
+ for a in range(k):
483
+ actions = self._plan(kind, inst, a, history, rng, memory)
484
+ self.do(actions, inst)
485
+ self.go_home()
486
+ out = self.outcome(inst)
487
+ params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else
488
+ [x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)]
489
+ for x in actions])
490
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
491
+ if on_attempt:
492
+ on_attempt(a, params, out)
493
+ if out["success"] or kind in ("oracle", "naive"):
494
+ break
495
+ return history
496
+
497
+ # cross-protocol hooks are not used by this task
498
+ def default_params(self, inst):
499
+ return dict(policy="naive")
500
+
501
+ def oracle_params(self, inst):
502
+ return dict(policy="oracle")
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l6_swap.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L6-A swap_interrupt: swap two items between identical pads; the second carry is interrupted by a slip.
2
+
3
+ Scene: four identical dark round pads (flat markers, no collision). The cream cheese (X) starts on pad A,
4
+ the butter (Y) on pad B, pads C and D are empty. Pad positions, which pad is which and the drop spot are
5
+ random per seed. Goal: X on B and Y on A.
6
+
7
+ Standard procedure: X: A -> C (temporary), Y: B -> A, X: C -> B. During the second carry (whichever item is
8
+ carried while the other one has already left its start pad), the carried item "slips": the gripper opens
9
+ and the item lands on the table at a hidden spot that is on no pad. Afterwards X sits on C, Y lies on the
10
+ table and A, B, D are empty -- the current image no longer shows which empty pad was whose. The information
11
+ needed to finish ("what has been done, where did each item start") is only in the agent's own history.
12
+
13
+ The drop spot is placed next to a *lure* pad: the spare pad ("spare", 50 %), the carried item's own start pad
14
+ ("source", 25 %) or its true destination ("dest", 25 %). So "put it on the nearest pad" is usually wrong and
15
+ proximity is close to uninformative; a stronger bias towards the start pad would open a memoryless shortcut
16
+ (tidy both items onto their nearest pads = undo, then swap again), see the task card.
17
+
18
+ Protocol: within (one episode, no reset). Attempt granularity: an attempt is everything the agent does until
19
+ it declares the task done; after each attempt the outcome is measured (F1/F2 feedback) and, if it failed, the
20
+ agent continues from the current state. The slip is injected once per episode, inside attempt 1 (it is an
21
+ in-attempt failure event, reported immediately: see `drain_events`). Scripted references:
22
+
23
+ oracle knows the true start layout; after the slip puts Y on A and X on B.
24
+ adaptive saves the start layout from its first frame (Save), recalls it after the slip (Retrieve) and
25
+ finishes the swap from the right step (Utilize); later attempts fix residual misplacements from
26
+ memory + F2 feedback.
27
+ naive memoryless continuation (one attempt): after the slip it re-plans from the current frame only --
28
+ the stray item goes to the nearest empty pad, the item that is still on a pad goes to the nearest
29
+ remaining empty pad.
30
+ blind memoryless restart (k attempts): does not know which step it was at; tidies the stray item onto
31
+ the nearest empty pad and then performs the whole swap again from the current frame; every later
32
+ attempt again swaps the two items (repeated swap, cf. RMBench).
33
+ blind_continue (extra control, not in the acceptance table) attempt 1 = naive, later attempts = swap again.
34
+ """
35
+ import numpy as np
36
+
37
+ from .. import envs
38
+ from ..bddl import write_bddl
39
+ from ..objects import _wrap, register_generated
40
+ from ..task_base import LFFTask, register_task
41
+
42
+ N_PADS = 4
43
+ PAD_R = 0.055 # pad radius (11 cm discs); items are 8 x 4.3 x 1.8 cm boxes lying flat
44
+ PAD_HALF_T = 0.0008
45
+ PAD_RGBA = (0.22, 0.24, 0.28, 1.0)
46
+ SUCC_R = 0.04 # item centre within 4 cm of the pad centre counts as "on that pad" for success
47
+ PAD_MIN_DIST = 0.17
48
+ PAD_REGION = (-0.26, 0.04, -0.25, 0.25) # x0, x1, y0, y1 (world)
49
+ PAD_REACH = 0.71 # max horizontal distance of a pad centre from the robot base
50
+ DROP_REGION = (-0.31, 0.07, -0.30, 0.30)
51
+ # beyond ~0.75 m from the base the arm ends up fully stretched (elbow at its joint limit) and the OSC gets stuck
52
+ MAX_REACH = 0.73
53
+ DROP_CLEAR = PAD_R + 0.05 # drop centre this far from every pad centre -> item fully off the pads
54
+ LURE_MARGIN = 0.03 # the lure pad is nearer to the drop spot than any other pad by at least this much
55
+ GRASP_DZ = 0.012 # gripper-site height above the table for a top-down grasp of the flat boxes
56
+ LIFT = 0.15
57
+ BASE_X = -0.66 # robot base x (world); base-frame coordinates = (x - BASE_X, y)
58
+ LURE_P = (("source", 0.25), ("spare", 0.5), ("dest", 0.25))
59
+
60
+ X, Y = "cream_cheese_1", "butter_1"
61
+ NAME = {X: "cream cheese", Y: "butter"}
62
+ PADS = [f"pad_{i + 1}" for i in range(N_PADS)]
63
+
64
+
65
+ def _pad_xml(model_name):
66
+ c = " ".join(f"{v:.3f}" for v in PAD_RGBA)
67
+ g = (f' <geom name="{model_name}_g0" type="cylinder" size="{PAD_R:.4f} {PAD_HALF_T:.4f}" rgba="{c}" '
68
+ f'density="10" contype="0" conaffinity="0" group="0" />\n'
69
+ f' <geom type="cylinder" size="{PAD_R:.4f} {PAD_HALF_T:.4f}" rgba="{c}" conaffinity="0" '
70
+ f'contype="0" group="1" />')
71
+ # flat marker without collisions: gravity compensation keeps it from sinking through the table
72
+ return _wrap(model_name, g, PAD_HALF_T, PAD_R).replace('<body name="object">',
73
+ '<body name="object" gravcomp="1">')
74
+
75
+
76
+ def _yaw_of(env, obj):
77
+ R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3)
78
+ yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x
79
+ return (yaw + np.pi / 2) % np.pi - np.pi / 2 # boxes are symmetric under pi
80
+
81
+
82
+ def drop_spot(pads, src, dest, other_xy, lure, phase, dist):
83
+ """Geometry of the injected drop. pads: (N,2); src / dest: start pads of the carried / other item;
84
+ other_xy: current xy of the other item. Returns (xy, lure_pad) or (None, None)."""
85
+ pads = np.asarray(pads, float)
86
+ rest = [i for i in range(len(pads)) if i not in (src, dest)]
87
+ # spare = an empty pad that is neither start pad and not the one the other item is parked on
88
+ occ = [i for i in rest if np.linalg.norm(pads[i] - other_xy) < PAD_R]
89
+ spare_c = [i for i in rest if i not in occ] or rest
90
+ spare = max(spare_c, key=lambda i: np.linalg.norm(pads[i] - other_xy))
91
+ lp = {"source": src, "dest": dest, "spare": spare}[lure]
92
+ for d in (dist, dist + 0.01, dist - 0.01, dist + 0.02):
93
+ for ang in phase + np.linspace(0, 2 * np.pi, 48, endpoint=False):
94
+ xy = pads[lp] + d * np.array([np.cos(ang), np.sin(ang)])
95
+ if not (DROP_REGION[0] <= xy[0] <= DROP_REGION[1] and DROP_REGION[2] <= xy[1] <= DROP_REGION[3]):
96
+ continue
97
+ if np.hypot(xy[0] - BASE_X, xy[1]) > MAX_REACH:
98
+ continue
99
+ dd = np.linalg.norm(pads - xy, axis=1)
100
+ if dd.min() < DROP_CLEAR or np.linalg.norm(xy - other_xy) < 0.12:
101
+ continue
102
+ if np.any(np.delete(dd, lp) < dd[lp] + LURE_MARGIN):
103
+ continue
104
+ return xy, int(lp)
105
+ return None, None
106
+
107
+
108
+ @register_task
109
+ class SwapInterrupt(LFFTask):
110
+ name = "l6_swap_interrupt"
111
+ level = "L6"
112
+ category = "procedural_memory"
113
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
114
+ protocol = "within"
115
+ max_attempts = 5
116
+ instruction = ("Swap the positions of the cream cheese and the butter: each must end up on the round pad "
117
+ "where the other one started. You may use the empty pads as temporary spots.")
118
+ instruction_indirect = ("Swap the positions of the pale blue box with the oval logo and the red-and-yellow "
119
+ "box: each must end up on the round pad where the other one started. You may use the "
120
+ "empty pads as temporary spots.")
121
+ inject = True # set False to run the same scene without the slip (sanity check)
122
+
123
+ # ------------------------------------------------------------ scene
124
+ def make_bddl(self):
125
+ cats = [register_generated(f"LffSwapPad{L}", _pad_xml(f"lff_swap_pad_{L.lower()}")) for L in "ABCD"]
126
+ objs = [(X, "cream_cheese", "cc_region", (-0.21, -0.21, -0.19, -0.19)),
127
+ (Y, "butter", "bu_region", (-0.21, 0.19, -0.19, 0.21)),
128
+ (PADS[0], cats[0], "p1_region", (0.05, -0.21, 0.07, -0.19)),
129
+ (PADS[1], cats[1], "p2_region", (0.05, 0.19, 0.07, 0.21)),
130
+ (PADS[2], cats[2], "p3_region", (-0.06, -0.01, -0.04, 0.01)),
131
+ (PADS[3], cats[3], "p4_region", (-0.31, -0.01, -0.29, 0.01))]
132
+ return write_bddl(self.name, self.instruction, objs)
133
+
134
+ def sample_instance(self, seed):
135
+ rng = np.random.default_rng(seed)
136
+ for _ in range(1000):
137
+ pads = []
138
+ while len(pads) < N_PADS:
139
+ p = np.array([rng.uniform(*PAD_REGION[:2]), rng.uniform(*PAD_REGION[2:])])
140
+ if np.hypot(p[0] - BASE_X, p[1]) > PAD_REACH:
141
+ continue
142
+ if all(np.linalg.norm(p - q) >= PAD_MIN_DIST for q in pads):
143
+ pads.append(p)
144
+ pads = np.array(pads)
145
+ x_pad, y_pad = 0, 1 # pad order is already random
146
+ u, acc = rng.uniform(), 0.0
147
+ for lure, pr in LURE_P:
148
+ acc += pr
149
+ if u < acc:
150
+ break
151
+ phase, dist = float(rng.uniform(0, 2 * np.pi)), float(rng.uniform(0.115, 0.14))
152
+ # canonical execution: X parked on the empty pad nearest to its start pad, then Y is carried
153
+ empt = [i for i in range(N_PADS) if i not in (x_pad, y_pad)]
154
+ buf = min(empt, key=lambda i: np.linalg.norm(pads[i] - pads[x_pad]))
155
+ xy, lp = drop_spot(pads, y_pad, x_pad, pads[buf], lure, phase, dist)
156
+ if xy is None:
157
+ continue
158
+ return dict(seed=int(seed), pads=pads.round(4).tolist(), x_pad=x_pad, y_pad=y_pad,
159
+ yaw_x=float(rng.uniform(-0.3, 0.3)), yaw_y=float(rng.uniform(-0.3, 0.3)),
160
+ lure=lure, drop_phase=phase, drop_dist=dist, drop_yaw=float(rng.uniform(-1.4, 1.4)),
161
+ trigger_dist=float(rng.uniform(0.05, 0.10)),
162
+ canonical_buffer=int(buf), canonical_drop_xy=xy.round(4).tolist())
163
+ raise RuntimeError("could not sample a layout")
164
+
165
+ def apply_instance(self, inst):
166
+ for i, p in enumerate(inst["pads"]):
167
+ envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001])
168
+ envs.place_upright(self.env, X, inst["pads"][inst["x_pad"]], inst["yaw_x"])
169
+ envs.place_upright(self.env, Y, inst["pads"][inst["y_pad"]], inst["yaw_y"])
170
+ self.env.sim.forward()
171
+ self.slip = None
172
+ self.events = []
173
+ self._event_cursor = 0 # for drain_events (harness, per tool call)
174
+ self._outcome_cursor = 0 # for outcome (per attempt)
175
+ self._inst = inst
176
+
177
+ def reset_instance(self, inst, recorder=None):
178
+ sk = super().reset_instance(inst)
179
+ self._user_recorder = recorder
180
+ sk.recorder = self._on_step # slip trigger is checked on every control step
181
+ sk.record_every = 1
182
+ self._home = sk.eef_pos()
183
+ return sk
184
+
185
+ def go_home(self):
186
+ """Lift the arm out of the camera's way (end of an attempt)."""
187
+ p = self.sk.eef_pos()
188
+ self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
189
+ self.sk.move_to(self._home)
190
+
191
+ # ------------------------------------------------------------ slip injection (state triggered)
192
+ def _on_step(self, env):
193
+ if self.inject and self.slip is None:
194
+ self._maybe_slip()
195
+ if self._user_recorder is not None and self.sk.n_steps % 4 == 0:
196
+ self._user_recorder(env)
197
+
198
+ def _maybe_slip(self):
199
+ """Fires during the first carry of an item while the other item has already left its start pad,
200
+ i.e. the second transport of a swap, whatever order the agent chose."""
201
+ inst, env = self._inst, self.env
202
+ pads = np.asarray(inst["pads"])
203
+ start = {X: inst["x_pad"], Y: inst["y_pad"]}
204
+ for o, other in ((X, Y), (Y, X)):
205
+ p = envs.obj_pos(env, o)
206
+ if p[2] < envs.TABLE_Z + 0.05:
207
+ continue
208
+ if np.linalg.norm(p[:2] - pads[start[o]]) < inst["trigger_dist"]:
209
+ continue
210
+ q = envs.obj_pos(env, other)
211
+ if np.linalg.norm(q[:2] - pads[start[other]]) < PAD_R:
212
+ continue
213
+ if not self.sk.holding(o):
214
+ continue
215
+ self._do_slip(o, other, q[:2])
216
+ return
217
+
218
+ def _do_slip(self, o, other, other_xy):
219
+ inst = self._inst
220
+ start = {X: inst["x_pad"], Y: inst["y_pad"]}
221
+ args = (inst["pads"], start[o], start[other], other_xy)
222
+ xy, lp = drop_spot(*args, inst["lure"], inst["drop_phase"], inst["drop_dist"])
223
+ lure = inst["lure"]
224
+ for alt in ("source", "spare", "dest"): # fallback (only if the agent did something unusual)
225
+ if xy is not None:
226
+ break
227
+ xy, lp = drop_spot(*args, alt, inst["drop_phase"], inst["drop_dist"])
228
+ lure = alt
229
+ if xy is None:
230
+ xy, lp, lure = np.asarray(inst["canonical_drop_xy"]), -1, "fallback"
231
+ envs.place_upright(self.env, o, xy, inst["drop_yaw"])
232
+ self.sk.grip = -1.0 # the gripper opens
233
+ self.env.sim.forward()
234
+ text = f"The {NAME[o]} slipped out of the gripper and fell onto the table."
235
+ self.slip = dict(obj=o, xy=[float(v) for v in xy], lure=lure, lure_pad=lp, step=int(self.sk.n_steps))
236
+ self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=o, text=text))
237
+
238
+ def drain_events(self):
239
+ """Event texts since the last call (for the harness: append to the current tool-call report)."""
240
+ ev = self.events[self._event_cursor:]
241
+ self._event_cursor = len(self.events)
242
+ return [e["text"] for e in ev]
243
+
244
+ # ------------------------------------------------------------ perception helpers (what an agent can see)
245
+ def pad_xy(self):
246
+ return np.array([envs.obj_pos(self.env, p)[:2] for p in PADS])
247
+
248
+ def on_pad(self, o, r=PAD_R):
249
+ d = np.linalg.norm(self.pad_xy() - envs.obj_pos(self.env, o)[:2], axis=1)
250
+ return int(np.argmin(d)) if d.min() < r else None
251
+
252
+ def empty_pads(self):
253
+ occ = {self.on_pad(X), self.on_pad(Y)}
254
+ return [i for i in range(N_PADS) if i not in occ]
255
+
256
+ def _nearest(self, cands, xy):
257
+ pads = self.pad_xy()
258
+ return min(cands, key=lambda i: np.linalg.norm(pads[i] - np.asarray(xy)[:2]))
259
+
260
+ @staticmethod
261
+ def _bf(xy):
262
+ return f"({xy[0] - BASE_X:.2f}, {xy[1]:+.2f})"
263
+
264
+ def pad_label(self, i, cur=None):
265
+ """Robot-centric name of pad i relative to the other pads (no coordinates in agent feedback)."""
266
+ cur = self.pad_xy() if cur is None else cur
267
+ c = cur.mean(axis=0)
268
+ fb = "far" if cur[i][0] > c[0] else "near"
269
+ lr = "left" if cur[i][1] > c[1] else "right"
270
+ same = [j for j in range(len(cur)) if ("far" if cur[j][0] > c[0] else "near") == fb
271
+ and ("left" if cur[j][1] > c[1] else "right") == lr]
272
+ lab = f"the {fb}-{lr} pad"
273
+ if len(same) > 1: # two pads in the same quadrant: tell them apart left to right
274
+ order = sorted(same, key=lambda j: -cur[j][1])
275
+ side = "more to the robot's left" if order.index(i) == 0 else "more to the robot's right"
276
+ lab += f" ({side} of the two)"
277
+ return lab
278
+
279
+ # ------------------------------------------------------------ outcome
280
+ def outcome(self, inst):
281
+ envs.settle(self.env, 20)
282
+ pads = np.asarray(inst["pads"])
283
+ target = {X: inst["y_pad"], Y: inst["x_pad"]}
284
+ res, ok = {}, True
285
+ for o in (X, Y):
286
+ p = envs.obj_pos(self.env, o)
287
+ dt = float(np.linalg.norm(p[:2] - pads[target[o]]))
288
+ resting = bool(envs.TABLE_Z - 0.01 < p[2] < envs.TABLE_Z + 0.05 and not self.sk.holding(o))
289
+ res[o] = dict(xy=[float(p[0]), float(p[1])], on_pad=self.on_pad(o), dist_to_target=dt, resting=resting)
290
+ ok = ok and resting and dt <= SUCC_R
291
+ # F2 detail: only what is observable now + events of this attempt; nothing about the start layout
292
+ parts = []
293
+ cur = self.pad_xy()
294
+ for o in (X, Y):
295
+ r = res[o]
296
+ if r["on_pad"] is not None:
297
+ parts.append(f"the {NAME[o]} is on {self.pad_label(r['on_pad'], cur)}")
298
+ else:
299
+ dd = np.linalg.norm(cur - np.asarray(r["xy"]), axis=1)
300
+ d = dd.min() - PAD_R
301
+ parts.append(f"the {NAME[o]} is on the table, on no pad "
302
+ f"({100 * d:.0f} cm from the edge of {self.pad_label(int(dd.argmin()), cur)})")
303
+ emp = [self.pad_label(i, cur) for i in self.empty_pads()]
304
+ detail = ("Now " + "; ".join(parts) + "; empty: " + (", ".join(emp) if emp else "none")
305
+ + " (left/right = the robot's left/right, near/far = toward/away from the robot).")
306
+ new_ev = [e["text"] for e in self.events[self._outcome_cursor:]]
307
+ self._outcome_cursor = len(self.events)
308
+ if new_ev:
309
+ detail = "During this attempt: " + " ".join(new_ev) + " " + detail
310
+ return dict(success=bool(ok), items={NAME[o]: res[o] for o in (X, Y)},
311
+ slip=self.slip, detail=detail)
312
+
313
+ # ------------------------------------------------------------ motion
314
+ def _pick(self, o):
315
+ sk = self.sk
316
+ for _ in range(2):
317
+ p = envs.obj_pos(self.env, o)
318
+ sk.grasp_at(p[:2], envs.TABLE_Z + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=LIFT)
319
+ if sk.holding(o):
320
+ return True
321
+ sk.set_gripper(False, steps=8)
322
+ sk.move_to([p[0], p[1], envs.TABLE_Z + LIFT])
323
+ return False
324
+
325
+ def _move(self, o, pad, log):
326
+ """Pick item o and put it on pad `pad`. Returns False if the item slipped on the way."""
327
+ n_ev = len(self.events)
328
+ frm = self.on_pad(o)
329
+ ok = self._pick(o)
330
+ rec = dict(obj=NAME[o], from_pad=frm, to_pad=int(pad), grasped=ok)
331
+ log.append(rec)
332
+ if not ok:
333
+ return True
334
+ xy = self.pad_xy()[pad]
335
+ sk = self.sk
336
+ sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + LIFT]) # carry (the slip may fire here)
337
+ if len(self.events) > n_ev:
338
+ rec["slipped"] = True
339
+ return False
340
+ sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.004], tol=0.004)
341
+ sk.set_gripper(False, steps=12)
342
+ sk.move_to([xy[0], xy[1], envs.TABLE_Z + GRASP_DZ + 0.10])
343
+ return True
344
+
345
+ def _run(self, moves, log):
346
+ """moves: list of (item, pad) computed up front (an open-loop plan). Stops at a slip."""
347
+ for o, pad in moves:
348
+ if not self._move(o, pad, log):
349
+ return False
350
+ return True
351
+
352
+ def _swap_now(self, log, rng=None):
353
+ """The standard swap of the two items' *current* pads via an empty pad (no memory)."""
354
+ a, b = self.on_pad(X), self.on_pad(Y)
355
+ empt = self.empty_pads()
356
+ if a is None or b is None or not empt:
357
+ return
358
+ buf = int(rng.choice(empt)) if rng is not None else self._nearest(empt, self.pad_xy()[a])
359
+ self._run([(X, buf), (Y, a), (X, b)], log)
360
+
361
+ def _tidy_stray(self, log):
362
+ for o in (X, Y):
363
+ if self.on_pad(o) is None and self.empty_pads():
364
+ self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
365
+
366
+ def _fixup(self, target, log):
367
+ """Move items until each is on its target pad (target: item -> pad index)."""
368
+ pads = self.pad_xy()
369
+ for _ in range(6):
370
+ todo = [o for o in (Y, X) if np.linalg.norm(envs.obj_pos(self.env, o)[:2] - pads[target[o]]) > SUCC_R]
371
+ if not todo:
372
+ return
373
+ free = [o for o in todo if self.on_pad({X: Y, Y: X}[o], r=PAD_R) != target[o]]
374
+ if free:
375
+ self._move(free[0], target[free[0]], log)
376
+ else: # the two items block each other: park one on an empty pad that is no one's target
377
+ o = todo[0]
378
+ spare = [i for i in self.empty_pads() if i not in target.values()] or self.empty_pads()
379
+ self._move(o, self._nearest(spare, envs.obj_pos(self.env, o)), log)
380
+
381
+ # ------------------------------------------------------------ scripted references (within protocol)
382
+ def _memory(self):
383
+ """Save: what the agent sees in its first frame -- which pad (by position) each item starts on."""
384
+ return {X: self.pad_xy()[self.on_pad(X)].tolist(), Y: self.pad_xy()[self.on_pad(Y)].tolist()}
385
+
386
+ def saved_memory(self, first):
387
+ """What the adaptive policy recalls after the slip (identity; patched by the mismatched-memory control)."""
388
+ return first
389
+
390
+ def _attempt1(self, kind, inst, mem, rng, first):
391
+ log = []
392
+ plan = dict(kind=kind, moves=log)
393
+ a = self._nearest(range(N_PADS), first[X]) # the open-loop plan is made from the first frame
394
+ b = self._nearest(range(N_PADS), first[Y])
395
+ empt = [i for i in range(N_PADS) if i not in (a, b)]
396
+ buf = self._nearest(empt, self.pad_xy()[a])
397
+ plan["plan"] = f"X->{buf}, Y->{a}, X->{b}"
398
+ if self._run([(X, buf), (Y, a), (X, b)], log):
399
+ plan["recovery"] = "none (no slip)"
400
+ return plan
401
+ # ---- the carry was interrupted by the slip: recover
402
+ if kind == "oracle": # privileged: true start layout
403
+ plan["recovery"] = "oracle: true layout"
404
+ self._fixup({X: inst["y_pad"], Y: inst["x_pad"]}, log)
405
+ elif kind == "adaptive": # Retrieve the saved first frame and the step log; finish from the right step
406
+ ta = self._nearest(range(N_PADS), mem[X])
407
+ tb = self._nearest(range(N_PADS), mem[Y])
408
+ plan["recovery"] = f"memory: butter -> pad {ta} (cream cheese's start), cream cheese -> pad {tb}"
409
+ self._fixup({X: tb, Y: ta}, log)
410
+ elif kind in ("naive", "blind_continue"): # memoryless continuation from the current frame
411
+ stray = [o for o in (X, Y) if self.on_pad(o) is None]
412
+ parked = [o for o in (X, Y) if self.on_pad(o) is not None]
413
+ plan["recovery"] = "current frame: stray item -> nearest empty pad; parked item -> nearest empty pad"
414
+ for o in stray:
415
+ self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
416
+ for o in parked:
417
+ if self.empty_pads():
418
+ self._move(o, self._nearest(self.empty_pads(), envs.obj_pos(self.env, o)), log)
419
+ elif kind == "blind": # memoryless restart: tidy up, then the whole swap again
420
+ plan["recovery"] = "restart: stray item -> nearest empty pad, then swap again"
421
+ self._tidy_stray(log)
422
+ self._swap_now(log, rng)
423
+ else:
424
+ raise ValueError(kind)
425
+ return plan
426
+
427
+ def _retry(self, kind, inst, mem, rng):
428
+ log = []
429
+ plan = dict(kind=kind, moves=log)
430
+ if kind == "adaptive":
431
+ ta = self._nearest(range(N_PADS), mem[X])
432
+ tb = self._nearest(range(N_PADS), mem[Y])
433
+ plan["recovery"] = "memory + F2: fix items not on their targets"
434
+ self._fixup({X: tb, Y: ta}, log)
435
+ elif kind in ("blind", "blind_continue"):
436
+ plan["recovery"] = "no history: tidy, then swap the two items again"
437
+ self._tidy_stray(log)
438
+ self._swap_now(log, rng)
439
+ else:
440
+ raise ValueError(kind)
441
+ return plan
442
+
443
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
444
+ k = k or self.max_attempts
445
+ rng = np.random.default_rng(seed)
446
+ self.reset_instance(inst)
447
+ first = self._memory()
448
+ mem = self.saved_memory(first)
449
+ history = []
450
+ for a in range(k):
451
+ plan = self._attempt1(kind, inst, mem, rng, first) if a == 0 else self._retry(kind, inst, mem, rng)
452
+ self.go_home() # "done": the agent declares the attempt finished
453
+ out = self.outcome(inst)
454
+ history.append(dict(attempt=a + 1, params=plan, outcome=out))
455
+ if on_attempt:
456
+ on_attempt(a, plan, out)
457
+ if out["success"] or kind in ("oracle", "naive"):
458
+ break
459
+ return history
460
+
461
+ # cross-protocol hooks are not used by this task
462
+ def default_params(self, inst):
463
+ return dict(policy="naive")
464
+
465
+ def oracle_params(self, inst):
466
+ return dict(policy="oracle")
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py ADDED
@@ -0,0 +1,1273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH drawer_cabinet (2026-10-16): tidy the table -- stand two tall bottles on top of a small wooden cabinet, put two
2
+ cubes into its open drawer and close the drawer. In 14 of every 20 instances the drawer is a self-closing one: pushed
3
+ into the last 8 cm, a strong spring snaps it shut, the light cabinet lurches 2.3-4.2 cm towards the robot, and bottles
4
+ already standing on its top fall over (away from the robot, onto the gallery rail at the back of the top).
5
+
6
+ Family: long-horizon self-disturbance ("state_restoration"): a later, normal action (closing the drawer) physically
7
+ undoes an earlier stage (bottles on the cabinet). The instruction lists the bottles first but fixes no order. The agent
8
+ has to see the fallen bottles and stand them up again after the drawer is shut (within an attempt), or learn to put
9
+ the cubes in and shut the drawer before it puts the bottles on top (across attempts).
10
+
11
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
12
+ * a small wooden cabinet (free body, 18 (x) x 22 (y) x 11 cm, centre 53-56 cm in front of the robot base, front facing
13
+ the robot) with a 6 cm gallery rail along the back edge of its top, a 4 cm toe plinth under the drawer and a
14
+ back-heavy carcass; its single drawer (inside 15.9 x 16.2 cm, 3 cm walls, 1.8 cm overlay front panel with a painted
15
+ finger slot, no handle, 0.8 kg) is pulled out 11 cm towards the robot. The agentview camera looks at the cabinet's
16
+ back: the drawer is hidden there (wrist camera only), the top and the bottles are in plain view;
17
+ * two tall square bottles (green with a yellow ball cap, brown with a blue ball cap; 4 x 4 cm body, 19.4 cm tall,
18
+ 0.18 kg, centre of mass 9 cm up, a rounded glass base whose flat contact is 2.2 x 2.2 cm: they tip beyond ~7 deg)
19
+ standing on the table 21-24 cm to one side of the cabinet's centre line;
20
+ * two 3.2 cm cubes (red, blue, 23 g) 25-29 cm to the other side (picked from nearer, the forearm sweeps over the
21
+ cabinet top and knocks bottles standing there: measured feasibility map, task card).
22
+
23
+ Hidden variable (same appearance): the drawer's closing mechanism. "self-closing" (14 of every 20 consecutive seeds):
24
+ in the last 8 cm of travel a spring pulls the drawer in with 12.5-15 N (no damper); "soft-close" (6 of 20): the same
25
+ spring with a damper, the drawer glides in at 4-6 cm/s. Nuisance variables (no effect on the class): carcass mass
26
+ 0.35-0.45 kg, felt feet (friction on the table 0.15-0.22).
27
+
28
+ Mechanism (physics, no teleport; measured, see the task card): the spring is internal to the cabinet, so when it snaps
29
+ the drawer in, it also pulls the light carcass (with the bottles on its top) towards the drawer, i.e. towards the robot:
30
+ 2.3-4.2 cm within ~0.07 s (drawer hitting its stop at 1.9-2.4 m/s relative to the carcass; validate's naive runs),
31
+ then the carcass stops dead. A standing bottle's tilt follows a fast displacement of its support as ~ m h dx / I_edge
32
+ (~7 rad per metre here), so the bottles tip away from the robot and come to rest leaning on the rail (45-75 deg). The
33
+ robot's hand is at the drawer front, below and 10+ cm away from the bottles, and does not touch them (0 of all slams).
34
+ Pushing slower does not help (the spring does the closing; 2-10 cm/s and push heights 3-8 cm all toppled, 32/32);
35
+ placing the bottles elsewhere on the top does not help (46/46 over six placements). A soft-close drawer moves the
36
+ carcass < 3 mm (0/38 bottles fell). Only an uncontrolled full-speed push (~0.6 m/s, not an agent habit) differs: the
37
+ hand then shoves the cabinet itself (self-closing 5/8 fell, soft-close 4/4 fell, onto the arm). Placing the bottles after the drawer is shut is safe. Prototype findings that fixed
38
+ the numbers: with a light drawer, a heavier carcass or more friction the bottles only rocked (<= 11 deg): the snap's
39
+ jerk and the friction stop cancel; a 2 kg carcass held by friction during the snap instead jerked away from the robot
40
+ and tipped the bottles towards (onto) the arm. Without the rail, fallen bottles lay with their caps right behind the
41
+ cabinet, where the palm (3 cm behind the grasp point) cannot get at them; with the heavy drawer pulled out and no
42
+ plinth, ~3 N pressing on the drawer front tipped the cabinet forward.
43
+
44
+ Restoring: the cap is a ball with low torsional friction; grasped from above with the fingers across the lying
45
+ bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs straight, and it can be set
46
+ down on the cabinet top (lh_bystander's mechanism; the instruction says that a bottle held by its cap hangs straight).
47
+ The neck has torsional friction: a bottle pinched at the neck just under the cap is carried without swinging.
48
+
49
+ Success (final state, follows from the instruction): both bottles upright (<= 10 deg) with their whole base on the
50
+ cabinet top (inside the rail), not held; both cubes inside the drawer; the drawer closed (<= 5 mm); the cabinet
51
+ upright and not moved more than 8 cm (the snap itself moves it 2.3-4.2 cm); the gripper open, holding nothing and
52
+ touching no task object; scene static. Per-step monitor (server log only; F1 tells the agent success / failure): stage
53
+ achieved / lost / restored (with cause: drawer_slam / robot_hand / robot_arm / bottle / picked_up / other),
54
+ drawer_slam (impact speed, carcass jerk, bottles on top, which of them fell, whether the robot had touched them before
55
+ they started to fall), bottle_fell, trap_fired (a bottle on top was lost to a slam), recovered_in_attempt.
56
+
57
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Once shut, the drawer cannot be opened again
58
+ (no handle; the self-closing spring would drag the light carcass along anyway).
59
+ """
60
+ import numpy as np
61
+
62
+ from .. import envs
63
+ from ..bddl import write_bddl
64
+ from ..objects import _fmt, _wrap, box_xml, register_generated
65
+ from ..skills import Skills
66
+ from ..task_base import LFFTask, register_task
67
+
68
+ Z = envs.TABLE_Z
69
+
70
+ # ---------------------------------------------------------------- cabinet (body frame: front face at -x, origin at the
71
+ # centre of the footprint, z = 0 on the table)
72
+ CAB = "cabinet_1"
73
+ CAB_MODEL = "lff_lhd_cabinet"
74
+ CD, CW, CH = 0.18, 0.22, 0.11 # carcass depth (x), width (y), height
75
+ CT = 0.010 # board thickness
76
+ PF = 0.018 # drawer front panel thickness (overlay: it sits in front of the carcass when closed)
77
+ DL = 0.165 # drawer box length (x), measured from the inner face of the front panel
78
+ DWT = 0.006 # drawer wall thickness
79
+ DWH = 0.030 # drawer wall height above its floor
80
+ D_FLOOR = CT + 0.003 # drawer floor bottom above the table
81
+ FLOOR_TOP = D_FLOOR + DWT
82
+ D_IN_Y = CW / 2 - CT - 0.003 - DWT # drawer inner half width (0.081)
83
+ D_IN_X = DL - DWT # inner length (from the front panel to the back wall)
84
+ Q_MAX = 0.14 # slide range (opening distance)
85
+ Q_OPEN = 0.11 # the drawer starts pulled out this far (exposed inside: 11 x 16.2 cm)
86
+ WOOD = (0.66, 0.50, 0.33, 1.0)
87
+ WOOD_D = (0.55, 0.40, 0.25, 1.0)
88
+ PANEL = (0.76, 0.60, 0.40, 1.0)
89
+ INNER = (0.84, 0.72, 0.52, 1.0)
90
+ SLOT = (0.18, 0.13, 0.09, 1.0)
91
+ DRAWER_MASS = 0.80
92
+ PLINTH = 0.04 # the bottom board reaches this far in front of the carcass, under the drawer: with the heavy drawer
93
+ # pulled out, the cabinet would otherwise tip forward under a ~3 N push down on the drawer's front
94
+ CAB_COM_X = 0.04 # carcass centre of mass towards the back (back-heavy carcass): same reason
95
+ RAIL_H, RAIL_T = 0.060, 0.008 # gallery rail along the back edge of the top: a bottle that tips over backwards comes
96
+ # to rest leaning on it (~50 deg) instead of falling off behind the cabinet, where its
97
+ # cap would lie against the cabinet's back and the palm could not get at it
98
+ SLIDE_FRIC = 1.0 # N, slide frictionloss: the open drawer stays where it is
99
+ CARCASS_MASS = (0.35, 0.45)
100
+ FEET_MU = (0.15, 0.22)
101
+
102
+ # drawer closing mechanism (hidden): spring in the last ZONE of travel, optional damper (soft-close)
103
+ ZONE = 0.08
104
+ F_SPRING = (12.5, 15.0)
105
+ SOFT_V = (0.04, 0.06) # soft-close glide speed (damping = force / speed)
106
+ P_SLAM = 0.70 # 14 of every 20 consecutive seeds self-closing
107
+ CLOSED = 0.005 # drawer counts as closed
108
+ V_SLAM = 0.30 # m/s: an impact on the stop faster than this is a slam (soft-close: ~0.05)
109
+
110
+ # ---------------------------------------------------------------- bottles (square body, shoulder, neck, ball cap)
111
+ BOTTLES = ("green_bottle_1", "brown_bottle_1")
112
+ B_NAME = {"green_bottle_1": "green", "brown_bottle_1": "brown"}
113
+ B_RGBA = {"green_bottle_1": (0.16, 0.48, 0.26, 1.0), "brown_bottle_1": (0.50, 0.26, 0.10, 1.0)}
114
+ CAP_RGBA = {"green_bottle_1": (0.92, 0.80, 0.15, 1.0), "brown_bottle_1": (0.15, 0.32, 0.85, 1.0)}
115
+ RB, HB = 0.020, 0.115 # body half width, height (incl. the foot)
116
+ RF, HF = 0.011, 0.005 # rounded glass base: flat contact 2.2 x 2.2 cm
117
+ RS, HS = 0.015, 0.010 # shoulder
118
+ RN, HN = 0.009, 0.050 # neck: long enough to be pinched below the cap with the palm clear of the cap
119
+ RK = 0.012 # ball cap
120
+ CAP_SINK = 0.005
121
+ H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.194
122
+ CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing
123
+ B_MASS = 0.18
124
+ B_COM = 0.090 # above the bottom
125
+ B_MU = 0.8
126
+ CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely
127
+ NECK_MU_T = 0.01 # torsional friction of the neck (condim 4): a bottle pinched by its neck does not swing
128
+ NECK_GRASP = H_TOT - 0.027 # scripted grasp height above the bottom: the palm (3.1 cm above the grasp point between
129
+ # the fingers, measured) clears the cap top by 4 mm; the pads hold the neck top and the cap
130
+
131
+ # ---------------------------------------------------------------- cubes
132
+ CUBES = ("red_cube_1", "blue_cube_1")
133
+ CUBE_COLOR = {"red_cube_1": "red", "blue_cube_1": "blue"}
134
+ CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0))
135
+ CUBE_E = 0.032
136
+ CUBE_DENS = 700.0 # 23 g
137
+
138
+ # ---------------------------------------------------------------- predicates / monitor
139
+ UPRIGHT = np.radians(10.0)
140
+ TILT_START = np.radians(6.0) # a standing bottle beyond this has started to fall (it tips at ~6.8 deg)
141
+ FALLEN = np.radians(40.0) # lying, or leaning on the gallery rail (45-75 deg)
142
+ CAB_MOVE_MAX = 0.08
143
+ CAB_TILT_MAX = np.radians(10.0)
144
+ DEBOUNCE = 10 # control steps (0.5 s) a predicate change must persist (checked every other step)
145
+ WIN_ROBOT = 40 # control steps: a robot contact this recent can explain a loss
146
+ WIN_SLAM = 60
147
+
148
+ # ---------------------------------------------------------------- scripted motion
149
+ NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm
150
+ FINGER_AHEAD = 0.021 # closed fingertips reach this far ahead of the grasp point (yaw 0, +x) -- measured
151
+ REACH_MAX = 0.78 # scripted policies: farthest grasp point at table height (horizontal distance from the base)
152
+
153
+
154
+ def _box(name, pos, size, rgba, extra, vis=True, vis_rgba=None):
155
+ s = [f'<geom name="{name}" type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}" {extra} group="0"/>']
156
+ if vis:
157
+ s.append(f'<geom type="box" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(vis_rgba or rgba)}" contype="0" '
158
+ f'conaffinity="0" group="1"/>')
159
+ return s
160
+
161
+
162
+ def cabinet_xml(name):
163
+ """free carcass (bottom, top, two sides, back) + a drawer on a slide joint along -x (opening towards the robot).
164
+ Carcass geoms contype 2 / conaffinity 1, drawer geoms contype 4 / conaffinity 1: they never collide with each other
165
+ but both collide with the robot, the table and the free objects (contype / conaffinity 1). The slide joint comes
166
+ first in the object's joint list (robosuite appends the free joint), see DrawerCabinet.__init__."""
167
+ hx, hy = CD / 2, CW / 2
168
+ cg = 'friction="0.8 0.005 0.0001" contype="2" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"'
169
+ carc = []
170
+ carc += _box(f"{name}_bottom", (-PLINTH / 2, 0, CT / 2), (hx + PLINTH / 2, hy, CT / 2), WOOD_D, cg)
171
+ carc += _box(f"{name}_top", (0, 0, CH - CT / 2), (hx, hy, CT / 2), WOOD, cg)
172
+ carc += _box(f"{name}_side_l", (0, hy - CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg)
173
+ carc += _box(f"{name}_side_r", (0, -hy + CT / 2, CH / 2), (hx, CT / 2, CH / 2 - CT), WOOD, cg)
174
+ carc += _box(f"{name}_back", (hx - CT / 2, 0, CH / 2), (CT / 2, hy - CT, CH / 2 - CT), WOOD, cg)
175
+ carc += _box(f"{name}_rail", (hx - RAIL_T / 2, 0, CH + RAIL_H / 2), (RAIL_T / 2, hy, RAIL_H / 2), WOOD_D, cg)
176
+ dg = 'friction="0.8 0.005 0.0001" contype="4" conaffinity="1" solimp="0.95 0.99 0.001" solref="0.004 1"'
177
+ x0 = -hx # inner face of the front panel (closed)
178
+ zf = D_FLOOR
179
+ dr = []
180
+ dr += _box(f"{name}_front", (x0 - PF / 2, 0, (CT + 0.002 + CH - 0.004) / 2), (PF / 2, hy, (CH - 0.006 - CT) / 2),
181
+ PANEL, dg)
182
+ dr += _box(f"{name}_dfloor", (x0 + DL / 2, 0, zf + DWT / 2), (DL / 2, D_IN_Y + DWT, DWT / 2), INNER, dg)
183
+ zw = zf + DWT + DWH / 2
184
+ dr += _box(f"{name}_dside_l", (x0 + DL / 2, D_IN_Y + DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg)
185
+ dr += _box(f"{name}_dside_r", (x0 + DL / 2, -D_IN_Y - DWT / 2, zw), (DL / 2, DWT / 2, DWH / 2), INNER, dg)
186
+ dr += _box(f"{name}_dback", (x0 + DL - DWT / 2, 0, zw), (DWT / 2, D_IN_Y, DWH / 2), INNER, dg)
187
+ # flush finger pull (visual only): a dark slot near the top of the front panel
188
+ dr.append(f'<geom type="box" pos="{_fmt((x0 - PF - 0.0005, 0, CH - 0.022))}" size="0.0008 0.035 0.006" '
189
+ f'rgba="{_fmt(SLOT)}" contype="0" conaffinity="0" group="1"/>')
190
+ m = DRAWER_MASS
191
+ ixx, iyy, izz = m * (CW ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + 0.06 ** 2) / 12, m * (DL ** 2 + CW ** 2) / 12
192
+ drawer = (f'<body name="drawer" pos="0 0 0">\n'
193
+ f' <inertial pos="{x0 + DL * 0.4:.4f} 0 0.04" mass="{m}" diaginertia="{ixx:.6f} {iyy:.6f} {izz:.6f}"/>\n'
194
+ f' <joint name="{name}_slide" type="slide" axis="-1 0 0" pos="0 0 0" limited="true" range="0 {Q_MAX}" '
195
+ f'frictionloss="{SLIDE_FRIC}" damping="0.3" armature="0.01" solreflimit="0.004 1" '
196
+ f'solimplimit="0.95 0.99 0.001"/>\n' + "\n".join(" " + s for s in dr) + "\n</body>")
197
+ m0 = 0.4
198
+ inertial = (f'<inertial pos="{CAB_COM_X:.4f} 0 {CH * 0.5:.4f}" mass="{m0}" diaginertia="{m0 * (CW ** 2 + CH ** 2) / 12:.6f} '
199
+ f'{m0 * (CD ** 2 + CH ** 2) / 12:.6f} {m0 * (CD ** 2 + CW ** 2) / 12:.6f}"/>')
200
+ body = "\n ".join([inertial] + carc + drawer.split("\n"))
201
+ return f"""<mujoco model="{name}">
202
+ <worldbody>
203
+ <body>
204
+ <body name="object">
205
+ {body}
206
+ </body>
207
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
208
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {CH:.4f}" name="top_site" />
209
+ <site rgba="0 0 0 0" size="0.005" pos="{CD / 2:.4f} {CW / 2:.4f} 0" name="horizontal_radius_site" />
210
+ </body>
211
+ </worldbody>
212
+ </mujoco>"""
213
+
214
+
215
+ def bottle_xml(name, rgba, cap_rgba):
216
+ """square bottle: rounded base (narrow flat foot), body, shoulder, neck, ball cap; origin at mid height"""
217
+ h = H_TOT / 2
218
+ zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2
219
+ zk = -h + HB + HS + HN + RK - CAP_SINK
220
+ m = B_MASS
221
+ ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 14
222
+ izz = m * (2 * (2 * RB) ** 2) / 12
223
+ fr = f'friction="{B_MU} 0.005 0.0001"'
224
+ sol = 'solimp="0.95 0.99 0.001" solref="0.005 1"'
225
+ parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, fr + ' priority="2"'),
226
+ ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, fr),
227
+ ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, fr),
228
+ ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), rgba,
229
+ f'friction="{B_MU} {NECK_MU_T} 0.0001" condim="4" priority="2"'),
230
+ ("cap", "sphere", (0, 0, zk), (RK,), cap_rgba, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
231
+ s = [f' <inertial pos="0 0 {-h + B_COM:.4f}" mass="{m}" diaginertia="{ixx:.6f} {ixx:.6f} {izz:.6f}" />']
232
+ for nm, typ, pos, size, c, extra in parts:
233
+ s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
234
+ f'{extra} {sol} group="0" />')
235
+ if nm != "foot":
236
+ s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
237
+ f'conaffinity="0" group="1" />')
238
+ # rounded base (visual): a slightly narrower bottom band, and a label
239
+ s.append(f' <geom type="box" pos="0 0 {zf:.4f}" size="{RB - 0.004:.4f} {RB - 0.004:.4f} {HF / 2:.4f}" '
240
+ f'rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1" />')
241
+ s.append(f' <geom type="box" pos="0 0 {zb + 0.005:.4f}" size="{RB + 0.0008:.4f} {RB + 0.0008:.4f} 0.028" '
242
+ f'rgba="0.92 0.90 0.80 1" contype="0" conaffinity="0" group="1" />')
243
+ return _wrap(name, "\n".join(s), h, RB * 1.42)
244
+
245
+
246
+ def _fb(v):
247
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
248
+
249
+
250
+ def _lr(v):
251
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
252
+
253
+
254
+ def _reach(p):
255
+ return float(np.hypot(p[0] + 0.66, p[1]))
256
+
257
+
258
+ class DrawerSkills(Skills):
259
+ """Skills that feed the task's per-step monitor."""
260
+
261
+ def __init__(self, env, task, recorder=None):
262
+ super().__init__(env, recorder=recorder)
263
+ self.task = task
264
+
265
+ def _act(self, dpos, drot, grip):
266
+ super()._act(dpos, drot, grip)
267
+ self.task.monitor_step()
268
+
269
+
270
+ @register_task
271
+ class DrawerCabinet(LFFTask):
272
+ name = "lh_drawer_cabinet"
273
+ level = "L2"
274
+ category = "state_restoration"
275
+ capabilities = ("Perceive", "Reason", "Restore", "Plan")
276
+ protocol = "cross"
277
+ max_attempts = 3
278
+ # careful: 2 bottles x ~8 commands + 3 cubes x ~6 + closing the drawer ~5 + looking ~15; standing 2 fallen bottles
279
+ # up again ~20; + slack
280
+ agent_max_steps = 120
281
+ instruction = ("Tidy up the table: stand the green bottle and the brown bottle upright on top of the small wooden "
282
+ "cabinet, put the red cube and the blue cube into the cabinet's open drawer (it is pulled "
283
+ "out towards the robot), and close the drawer. When you finish, both bottles must stand upright on the cabinet top, both cubes must be in "
284
+ "the closed drawer, the cabinet must still stand where it is, and the gripper must be open and not "
285
+ "touching anything. (Each bottle has a round cap; held by its cap, a bottle hangs straight down.)")
286
+ instruction_indirect = ("Clean up: set the two tall bottles (the green one and the brown one) upright on the little "
287
+ "wooden cabinet, drop the two small cubes (red and blue) into its pulled-out drawer and "
288
+ "shut the drawer. In the end both bottles stand on top of the cabinet, the cubes are inside the shut drawer, "
289
+ "the cabinet stays in its place, and the open gripper touches nothing. (A bottle held by "
290
+ "its round cap hangs straight down.)")
291
+ agent_object_names = ["green bottle (yellow round cap)", "brown bottle (blue round cap)", "red cube", "blue cube",
292
+ "small wooden cabinet with its drawer pulled out (the drawer front faces the robot)"]
293
+
294
+ # ------------------------------------------------------------ scene
295
+ def make_bddl(self):
296
+ cab = register_generated("LffLhdCabinet", cabinet_xml(CAB_MODEL))
297
+ objs = [(CAB, cab, "cabinet_region", (0.10, -0.02, 0.12, 0.0))]
298
+ for i, b in enumerate(BOTTLES):
299
+ c = B_NAME[b]
300
+ cat = register_generated(f"LffLhdBottle{c.title()}", bottle_xml(f"lff_lhd_bottle_{c}", B_RGBA[b], CAP_RGBA[b]))
301
+ objs.append((b, cat, f"{c}_bottle_region", (-0.30, 0.20 + 0.13 * i, -0.28, 0.22 + 0.13 * i)))
302
+ for i, n in enumerate(CUBES):
303
+ c = CUBE_COLOR[n]
304
+ cat = register_generated(f"LffLhdCube{c.title()}",
305
+ box_xml(f"lff_lhd_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS,
306
+ friction=(0.8, 0.005, 0.0001)))
307
+ objs.append((n, cat, f"{c}_cube_region", (-0.30, -0.45 + 0.13 * i, -0.28, -0.43 + 0.13 * i)))
308
+ return write_bddl(self.name, "tidy up the table", objs, [])
309
+
310
+ def __init__(self, cam_res=None):
311
+ super().__init__(cam_res)
312
+ m = self.env.sim.model
313
+ pre = f"{CAB}_{CAB_MODEL}"
314
+ self.jid = m.joint_name2id(pre + "_slide")
315
+ self.qa = int(m.jnt_qposadr[self.jid])
316
+ self.dof = int(m.jnt_dofadr[self.jid])
317
+ self.cab_bid = envs.body_id(self.env, CAB)
318
+ self.drawer_bid = m.body_name2id(f"{CAB}_drawer")
319
+ # the cabinet's free joint is the LAST of its joints (robosuite appends it after the drawer slide), so
320
+ # envs.free_joint_addr / place_upright (joints[0]) must not be used for it
321
+ fj = m.joint_name2id(self.env.objects_dict[CAB].joints[-1])
322
+ assert int(m.jnt_type[fj]) == 0
323
+ self.cab_qa, self.cab_da = int(m.jnt_qposadr[fj]), int(m.jnt_dofadr[fj])
324
+ self.feet_gid = m.geom_name2id(pre + "_bottom")
325
+ self.cab_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in (self.cab_bid, self.drawer_bid)
326
+ and m.geom_contype[g] != 0}
327
+ self.bottle_gids = {b: set(envs.obj_geom_ids(self.env, b)) for b in BOTTLES}
328
+ self.cube_gids = {c: set(envs.obj_geom_ids(self.env, c)) for c in CUBES}
329
+ self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhd_bottle_{B_NAME[b]}_cap") for b in BOTTLES}
330
+ # per-geom lookup tables for the substep contact scan
331
+ self.part = np.zeros(m.ngeom, int) # 1 = hand / fingers, 2 = arm links
332
+ for g in envs.robot_geom_ids(self.env):
333
+ n = m.geom_id2name(g) or ""
334
+ self.part[g] = 1 if n.startswith("gripper0_") else 2
335
+ self.bidx = np.full(m.ngeom, -1, int)
336
+ for i, b in enumerate(BOTTLES):
337
+ self.bidx[list(self.bottle_gids[b])] = i
338
+ self.task_obj = np.zeros(m.ngeom, bool)
339
+ for s in list(self.bottle_gids.values()) + list(self.cube_gids.values()) + [self.cab_gids]:
340
+ self.task_obj[list(s)] = True
341
+ self.catch = dict(force=0.0, zone=ZONE, damp=0.0)
342
+ sim = self.env.sim
343
+ if not getattr(sim, "_lhd_wrapped", False):
344
+ orig = sim.step
345
+
346
+ def step(*a, **k):
347
+ orig(*a, **k)
348
+ t = getattr(sim, "_lhd_task", None)
349
+ if t is not None:
350
+ t._substep()
351
+ sim.step = step
352
+ sim._lhd_wrapped = True
353
+ sim._lhd_task = self
354
+ self.inst = None
355
+ self.mon = None
356
+ self.sk = None
357
+ self._sub = {}
358
+
359
+ # ------------------------------------------------------------ drawer mechanism (every MuJoCo substep)
360
+ def q(self):
361
+ return float(self.env.sim.data.qpos[self.qa])
362
+
363
+ def catch_force(self, q, qd):
364
+ """generalised force on the slide (positive = opening): inside the last ZONE of travel a constant pull towards
365
+ closed (ramped in over 5 mm), plus a damper on closing motion for soft-close drawers"""
366
+ c = self.catch
367
+ z = c["zone"]
368
+ if q >= z or c["force"] <= 0:
369
+ return 0.0
370
+ ramp = float(np.clip((z - q) / 0.005, 0.0, 1.0))
371
+ f = -c["force"] * ramp
372
+ if qd < 0 and c["damp"] > 0:
373
+ f -= c["damp"] * qd * ramp
374
+ return f
375
+
376
+ def _substep(self):
377
+ d = self.env.sim.data
378
+ q, qd = float(d.qpos[self.qa]), float(d.qvel[self.dof])
379
+ d.qfrc_applied[self.dof] = self.catch_force(q, qd)
380
+ if self.mon is None:
381
+ return
382
+ sub = self._sub
383
+ # slam detection: the closing speed just before the drawer reaches its stop
384
+ if q > 0.002:
385
+ sub["approach_v"] = -qd
386
+ sub["armed"] = True
387
+ if q < self.catch["zone"] and sub.get("zone_xy") is None:
388
+ sub["zone_xy"] = self.cab_xy().tolist()
389
+ elif q > self.catch["zone"] + 0.005:
390
+ sub["zone_xy"] = None
391
+ elif sub.get("armed"):
392
+ sub["armed"] = False
393
+ v = float(sub.get("approach_v", 0.0))
394
+ sub.setdefault("impacts", []).append((v, sub.get("zone_xy")))
395
+ sub["zone_xy"] = None
396
+ n = d.ncon
397
+ if not n:
398
+ return
399
+ g1 = np.asarray(d.contact.geom1)[:n]
400
+ g2 = np.asarray(d.contact.geom2)[:n]
401
+ for a, b in zip(g1, g2):
402
+ ia, ib = self.bidx[a], self.bidx[b]
403
+ if ia < 0 and ib < 0:
404
+ continue
405
+ if ia >= 0 and ib >= 0:
406
+ if ia != ib:
407
+ sub.setdefault("bb", set()).update((int(ia), int(ib)))
408
+ continue
409
+ i, o = (ia, b) if ia >= 0 else (ib, a)
410
+ p = int(self.part[o])
411
+ if p:
412
+ r = sub.setdefault("rob", {})
413
+ r[int(i)] = 2 if (p == 2 or r.get(int(i)) == 2) else 1
414
+
415
+ # ------------------------------------------------------------ instances
416
+ def sample_instance(self, seed):
417
+ rng = np.random.default_rng(seed)
418
+ slam = bool((int(seed) * 7) % 20 < round(20 * P_SLAM)) # balanced: 14 of every 20 consecutive seeds
419
+ cx, cy = float(rng.uniform(-0.13, -0.10)), float(rng.uniform(-0.04, 0.04))
420
+ s = 1.0 if rng.random() < 0.5 else -1.0 # bottles on the left (+1) or right (-1), cubes on the other side
421
+ bottles = {}
422
+ order = rng.permutation(2)
423
+ for j, i in enumerate(order):
424
+ bx = cx + (-0.05, 0.05)[j] + float(rng.uniform(-0.01, 0.01))
425
+ bottles[BOTTLES[i]] = [bx, cy + s * float(rng.uniform(0.21, 0.24))]
426
+ perm = rng.permutation(2)
427
+ # cubes 25-29 cm to the side of the cabinet's centre line: picked from nearer, the forearm sweeps over the
428
+ # cabinet top and knocks the bottles standing there (measured feasibility map, see the task card)
429
+ cubes = {CUBES[i]: [cx + (-0.16, -0.04)[j] + float(rng.uniform(-0.01, 0.01)),
430
+ cy - s * float(rng.uniform(0.25, 0.29))] for j, i in enumerate(perm)}
431
+ force = float(rng.uniform(*F_SPRING))
432
+ soft_v = float(rng.uniform(*SOFT_V))
433
+ return dict(seed=int(seed), self_closing=slam, drawer="self-closing" if slam else "soft-close",
434
+ cab_xy=[cx, cy], bottle_side="left" if s > 0 else "right", bottle_start=bottles,
435
+ bottle_yaw={b: float(rng.uniform(-0.3, 0.3)) for b in BOTTLES}, cube_start=cubes,
436
+ cube_yaw={c: float(rng.uniform(-0.3, 0.3)) for c in CUBES},
437
+ spring_n=force, damp=0.0 if slam else force / soft_v,
438
+ carcass_kg=float(rng.uniform(*CARCASS_MASS)), feet_mu=float(rng.uniform(*FEET_MU)),
439
+ naive_noise_seed=int(rng.integers(1 << 30)))
440
+
441
+ def apply_instance(self, inst):
442
+ self.inst = inst
443
+ m = self.env.sim.model
444
+ M = float(inst["carcass_kg"])
445
+ m.body_mass[self.cab_bid] = M
446
+ m.body_inertia[self.cab_bid] = [M * (CW ** 2 + CH ** 2) / 12, M * (CD ** 2 + CH ** 2) / 12,
447
+ M * (CD ** 2 + CW ** 2) / 12]
448
+ m.geom_friction[self.feet_gid] = [float(inst["feet_mu"]), 0.005, 0.0001]
449
+ m.geom_priority[self.feet_gid] = 3
450
+ self.catch = dict(force=float(inst["spring_n"]), zone=ZONE, damp=float(inst["damp"]))
451
+ self.set_drawer(Q_OPEN)
452
+ self.place_cabinet(inst["cab_xy"], 0.0)
453
+ for b in BOTTLES:
454
+ envs.place_upright(self.env, b, inst["bottle_start"][b], yaw=inst["bottle_yaw"][b], clearance=0.0005)
455
+ for c in CUBES:
456
+ envs.place_upright(self.env, c, inst["cube_start"][c], yaw=inst["cube_yaw"][c], clearance=0.001)
457
+
458
+ def set_drawer(self, q):
459
+ d = self.env.sim.data
460
+ d.qpos[self.qa] = q
461
+ d.qvel[self.dof] = 0.0
462
+
463
+ def place_cabinet(self, xy, yaw=0.0, clearance=0.0005):
464
+ d = self.env.sim.data
465
+ a, v = self.cab_qa, self.cab_da
466
+ d.qpos[a:a + 3] = [xy[0], xy[1], Z + clearance] # body origin = bottom of the carcass
467
+ d.qpos[a + 3:a + 7] = [np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]
468
+ d.qvel[v:v + 6] = 0.0
469
+ self.env.sim.forward()
470
+
471
+ def reset_instance(self, inst, recorder=None):
472
+ self.mon = None
473
+ self.env.reset()
474
+ self.apply_instance(inst)
475
+ self.env.sim.forward()
476
+ envs.settle(self.env, 15)
477
+ self.sk = DrawerSkills(self.env, self, recorder=recorder)
478
+ self._sub = {}
479
+ self._init_monitor()
480
+ return self.sk
481
+
482
+ # ------------------------------------------------------------ geometry helpers (world frame)
483
+ def cab_R(self):
484
+ return self.env.sim.data.body_xmat[self.cab_bid].reshape(3, 3).copy()
485
+
486
+ def cab_origin(self):
487
+ return self.env.sim.data.body_xpos[self.cab_bid].copy()
488
+
489
+ def cab_xy(self):
490
+ return self.cab_origin()[:2]
491
+
492
+ def to_cab(self, p):
493
+ """world point -> cabinet frame (x forward, origin at the footprint centre on the floor)"""
494
+ return self.cab_R().T @ (np.asarray(p, float) - self.cab_origin())
495
+
496
+ def from_cab(self, p):
497
+ return self.cab_origin() + self.cab_R() @ np.asarray(p, float)
498
+
499
+ def top_z(self):
500
+ return float(self.from_cab([0.0, 0.0, CH])[2])
501
+
502
+ def cab_front_x(self):
503
+ """world x of the carcass's front face (cabinet assumed close to yaw 0)"""
504
+ return float(self.from_cab([-CD / 2, 0.0, 0.0])[0])
505
+
506
+ def drawer_front_x(self):
507
+ """world x of the drawer front panel's outer face"""
508
+ return self.cab_front_x() - self.q() - PF
509
+
510
+ def cab_tilt(self):
511
+ return float(np.arccos(np.clip(self.cab_R()[2, 2], -1.0, 1.0)))
512
+
513
+ def cab_moved(self):
514
+ return float(np.linalg.norm(self.cab_xy() - np.asarray(self.inst["cab_xy"])))
515
+
516
+ def R(self, name):
517
+ return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy()
518
+
519
+ def tilt(self, name):
520
+ return float(np.arccos(np.clip(self.R(name)[2, 2], -1.0, 1.0)))
521
+
522
+ def bottle_base(self, b):
523
+ """world position of the centre of the bottle's bottom face"""
524
+ return envs.obj_pos(self.env, b) - self.R(b)[:, 2] * H_TOT / 2
525
+
526
+ def cap_xyz(self, b):
527
+ return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy()
528
+
529
+ def held(self, name):
530
+ return self.sk is not None and self.sk.holding(name)
531
+
532
+ # ------------------------------------------------------------ stage predicates
533
+ def bottle_on_top(self, b, tol=0.0, tilt=UPRIGHT):
534
+ if self.tilt(b) > tilt or self.held(b):
535
+ return False
536
+ c = self.to_cab(self.bottle_base(b))
537
+ if c[0] < -CD / 2 + RF - tol or c[0] > CD / 2 - RAIL_T - RF + tol or abs(c[1]) > CW / 2 - RF + tol:
538
+ return False
539
+ return bool(-0.006 <= c[2] - CH <= 0.012)
540
+
541
+ def cube_in_drawer(self, c):
542
+ """cube centre inside the drawer box (drawer frame), its footprint within the walls (+3 mm), resting low enough
543
+ to pass under the cabinet top; not held"""
544
+ if self.held(c):
545
+ return False
546
+ d = self.env.sim.data
547
+ Rd = d.body_xmat[self.drawer_bid].reshape(3, 3)
548
+ p = Rd.T @ (envs.obj_pos(self.env, c) - d.body_xpos[self.drawer_bid])
549
+ x0 = -CD / 2
550
+ e = CUBE_E / 2 * 1.2 # footprint half size (a yawed cube reaches a little farther)
551
+ tol = 0.003
552
+ return bool(x0 + e - tol <= p[0] <= x0 + D_IN_X - e + tol and abs(p[1]) <= D_IN_Y - e + tol
553
+ and FLOOR_TOP - 0.005 <= p[2] - CUBE_E / 2 <= FLOOR_TOP + DWH + 0.01)
554
+
555
+ def drawer_closed(self):
556
+ return self.q() <= CLOSED
557
+
558
+ def stage_keys(self):
559
+ return [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES] + [f"{CUBE_COLOR[c]}_cube_in_drawer" for c in CUBES] + [
560
+ "drawer_closed"]
561
+
562
+ def stage_values(self, hyst=None):
563
+ hyst = hyst or {}
564
+ v = {}
565
+ for b in BOTTLES:
566
+ k = f"{B_NAME[b]}_bottle_on_top"
567
+ v[k] = self.bottle_on_top(b, 0.003, UPRIGHT + np.radians(3.0)) if hyst.get(k) else self.bottle_on_top(b)
568
+ for c in CUBES:
569
+ v[f"{CUBE_COLOR[c]}_cube_in_drawer"] = self.cube_in_drawer(c)
570
+ v["drawer_closed"] = self.q() <= (CLOSED + 0.003 if hyst.get("drawer_closed") else CLOSED)
571
+ return v
572
+
573
+ # ------------------------------------------------------------ per-step monitor
574
+ def _init_monitor(self):
575
+ keys = self.stage_keys()
576
+ st = {k: False for k in keys}
577
+ self.mon = dict(state=st, ever=[], lost=[], lost_cause={}, events=[], cand={k: 0 for k in keys}, step=0,
578
+ last_robot=[None, None], last_bb=None, slams=[], standing_since=[None, None],
579
+ fall_start=[None, None], touched_before_fall=[False, False], max_tilt=[0.0, 0.0],
580
+ n_fallen=0, fallen=[False, False])
581
+
582
+ def monitor_step(self):
583
+ mon = self.mon
584
+ if mon is None or self.sk is None:
585
+ return
586
+ mon["step"] += 1
587
+ t = int(self.sk.n_steps)
588
+ sub, self._sub = self._sub, {k: v for k, v in self._sub.items() if k in ("approach_v", "armed", "zone_xy")}
589
+ for i, part in sub.get("rob", {}).items():
590
+ b = BOTTLES[i]
591
+ if not self.held(b):
592
+ mon["last_robot"][i] = ["hand" if part == 1 else "arm", t, round(float(np.degrees(self.tilt(b))), 1)]
593
+ if sub.get("bb"):
594
+ mon["last_bb"] = t
595
+ for v, zxy in sub.get("impacts", []):
596
+ if v >= V_SLAM:
597
+ lurch = None
598
+ if zxy is not None:
599
+ dxy = self.cab_xy() - np.asarray(zxy)
600
+ lurch = [round(100 * float(dxy[0]), 2), round(100 * float(dxy[1]), 2)]
601
+ on = [B_NAME[b] for b in BOTTLES if mon["state"][f"{B_NAME[b]}_bottle_on_top"]]
602
+ e = dict(event="drawer_slam", step=t, speed_mps=round(float(v), 2), cabinet_jerk_cm=lurch,
603
+ bottles_on_top=on, bottles_fell=[], robot_touched_before_fall=[])
604
+ mon["events"].append(e)
605
+ mon["slams"].append(e)
606
+ else:
607
+ mon["events"].append(dict(event="drawer_shut", step=t, speed_mps=round(float(v), 3)))
608
+ # fall tracking (R4: did the robot touch a bottle before it started to fall?)
609
+ for i, b in enumerate(BOTTLES):
610
+ tl = self.tilt(b)
611
+ mon["max_tilt"][i] = max(mon["max_tilt"][i], float(np.degrees(tl)))
612
+ if self.held(b):
613
+ mon["standing_since"][i] = None
614
+ continue
615
+ if tl < np.radians(3.0):
616
+ if mon["standing_since"][i] is None:
617
+ mon["standing_since"][i] = t
618
+ mon["fall_start"][i] = None
619
+ elif tl > TILT_START and mon["standing_since"][i] is not None and mon["fall_start"][i] is None:
620
+ mon["fall_start"][i] = t
621
+ lr = mon["last_robot"][i]
622
+ mon["touched_before_fall"][i] = bool(lr is not None and t - lr[1] <= 20 and lr[2] < np.degrees(TILT_START))
623
+ if not mon["fallen"][i] and tl > FALLEN:
624
+ mon["fallen"][i] = True
625
+ mon["n_fallen"] += 1
626
+ mon["events"].append(dict(event="bottle_fell", bottle=B_NAME[b], step=t, cause=self._cause(i, t),
627
+ robot_touched_before_fall=bool(mon["touched_before_fall"][i]),
628
+ direction=self._fall_dir(b)))
629
+ elif mon["fallen"][i] and tl < UPRIGHT:
630
+ mon["fallen"][i] = False
631
+ if mon["step"] % 2:
632
+ return
633
+ vals = self.stage_values(hyst=mon["state"])
634
+ for k, now in vals.items():
635
+ self._check(k, now, t)
636
+
637
+ def _fall_dir(self, b):
638
+ ax = self.R(b)[:2, 2]
639
+ if np.linalg.norm(ax) < 0.2:
640
+ return "none"
641
+ return ("forward" if ax[0] > 0 else "backward") if abs(ax[0]) >= abs(ax[1]) else ("left" if ax[1] > 0 else "right")
642
+
643
+ def _cause(self, i, t):
644
+ """why bottle i left the cabinet top"""
645
+ b = BOTTLES[i]
646
+ mon = self.mon
647
+ if self.held(b):
648
+ return "picked_up"
649
+ lr = mon["last_robot"][i]
650
+ robot_recent = lr is not None and t - lr[1] <= WIN_ROBOT
651
+ if robot_recent and mon["touched_before_fall"][i]:
652
+ return f"robot_{lr[0]}"
653
+ if robot_recent and lr[2] < np.degrees(TILT_START):
654
+ return f"robot_{lr[0]}"
655
+ if mon["slams"] and t - mon["slams"][-1]["step"] <= WIN_SLAM:
656
+ return "drawer_slam"
657
+ if mon["last_bb"] is not None and t - mon["last_bb"] <= WIN_ROBOT:
658
+ return "bottle"
659
+ if robot_recent:
660
+ return f"robot_{lr[0]}"
661
+ return "other"
662
+
663
+ def _check(self, key, now, t):
664
+ mon = self.mon
665
+ if now == mon["state"][key]:
666
+ mon["cand"][key] = 0
667
+ return
668
+ mon["cand"][key] += 2
669
+ if mon["cand"][key] < DEBOUNCE:
670
+ return
671
+ mon["cand"][key] = 0
672
+ mon["state"][key] = now
673
+ t0 = int(t - DEBOUNCE + 1)
674
+ if now:
675
+ restored = key in mon["lost"]
676
+ e = dict(stage=key, event="restored" if restored else "achieved", step=t0)
677
+ if restored:
678
+ e["after"] = mon["lost_cause"].get(key)
679
+ mon["lost"].remove(key)
680
+ if key not in mon["ever"]:
681
+ mon["ever"].append(key)
682
+ mon["events"].append(e)
683
+ return
684
+ if key not in mon["ever"]:
685
+ return
686
+ if key.endswith("bottle_on_top"):
687
+ i = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES].index(key)
688
+ cause = self._cause(i, t)
689
+ if cause == "drawer_slam":
690
+ s = mon["slams"][-1]
691
+ if B_NAME[BOTTLES[i]] not in s["bottles_fell"]:
692
+ s["bottles_fell"].append(B_NAME[BOTTLES[i]])
693
+ s["robot_touched_before_fall"].append(bool(mon["touched_before_fall"][i]))
694
+ elif key == "drawer_closed":
695
+ cause = "opened"
696
+ else:
697
+ c = CUBES[[f"{CUBE_COLOR[x]}_cube_in_drawer" for x in CUBES].index(key)]
698
+ cause = "picked_up" if self.held(c) else "other"
699
+ if key not in mon["lost"]:
700
+ mon["lost"].append(key)
701
+ mon["lost_cause"][key] = cause
702
+ mon["events"].append(dict(stage=key, event="lost", step=t0, cause=cause))
703
+
704
+ def _finalize_monitor(self, vals):
705
+ """close the event log at finish: a stage the debounced monitor still holds but the final judge does not (or
706
+ vice versa) is logged now (final=True)"""
707
+ mon = self.mon
708
+ t = int(self.sk.n_steps)
709
+ for k, now in vals.items():
710
+ if now == mon["state"][k]:
711
+ continue
712
+ n0 = len(mon["events"])
713
+ mon["cand"][k] = DEBOUNCE # force the transition
714
+ self._check(k, now, t + DEBOUNCE - 1)
715
+ if len(mon["events"]) > n0:
716
+ mon["events"][-1]["final"] = True
717
+
718
+ # ------------------------------------------------------------ outcome
719
+ def _static(self):
720
+ d = self.env.sim.data
721
+ for n in BOTTLES + CUBES:
722
+ _, da = envs.free_joint_addr(self.env, n)
723
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
724
+ return False
725
+ v = self.cab_da
726
+ return bool(np.linalg.norm(d.qvel[v:v + 3]) < 0.02 and abs(float(d.qvel[self.dof])) < 0.02)
727
+
728
+ def robot_touching(self):
729
+ d = self.env.sim.data
730
+ out = set()
731
+ for j in range(d.ncon):
732
+ c = d.contact[j]
733
+ for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)):
734
+ if self.part[a] and self.task_obj[b]:
735
+ out.add("a bottle" if self.bidx[b] >= 0 else "the cabinet" if b in self.cab_gids else "a cube")
736
+ return sorted(out)
737
+
738
+ def outcome(self, inst):
739
+ sk = self.sk
740
+ sk.hold(10)
741
+ touching = set()
742
+ for _ in range(20):
743
+ sk.hold(1)
744
+ touching.update(self.robot_touching())
745
+ touching = sorted(touching)
746
+ static = self._static()
747
+ vals = self.stage_values()
748
+ held = [n for n in BOTTLES + CUBES if self.held(n)]
749
+ cab_ok = bool(self.cab_tilt() <= CAB_TILT_MAX and self.cab_moved() <= CAB_MOVE_MAX)
750
+ grip_open = bool(sk.grip < 0)
751
+ self._finalize_monitor(vals)
752
+ mon = self.mon
753
+ ev = list(mon["events"])
754
+ success = bool(all(vals.values()) and cab_ok and static and not held and not touching and grip_open)
755
+ lost = [e for e in ev if e.get("event") == "lost"]
756
+ regress = [e for e in lost if e.get("cause") != "picked_up"]
757
+ restored = [e for e in ev if e.get("event") == "restored" and e.get("after") != "picked_up"]
758
+ slams = [e for e in ev if e.get("event") == "drawer_slam"]
759
+ slam_losses = [e for e in lost if e.get("cause") == "drawer_slam"]
760
+ trap = bool(slam_losses)
761
+ bkeys = [f"{B_NAME[b]}_bottle_on_top" for b in BOTTLES]
762
+ never_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k not in mon["ever"]]
763
+ lost_bottle = [B_NAME[b] for b, k in zip(BOTTLES, bkeys) if not vals[k] and k in mon["ever"]]
764
+ cubes_out = [CUBE_COLOR[c] for c in CUBES if not vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]]
765
+ if success:
766
+ failure = "none"
767
+ elif held:
768
+ failure = "held"
769
+ elif not cab_ok:
770
+ failure = "cabinet_moved"
771
+ elif lost_bottle:
772
+ failure = "bottle_knocked"
773
+ elif never_bottle:
774
+ failure = "bottle_not_on_top"
775
+ elif cubes_out:
776
+ failure = "cube_not_in_drawer"
777
+ elif not vals["drawer_closed"]:
778
+ failure = "drawer_open"
779
+ elif touching:
780
+ failure = "touching"
781
+ elif not grip_open:
782
+ failure = "gripper_closed"
783
+ else:
784
+ failure = "not_static"
785
+ detail = self._detail(vals, held, touching, cab_ok, static, grip_open, success, ev)
786
+ return dict(success=success, failure=failure, stages=vals, events=ev, n_regressions=len(regress),
787
+ n_lost=len(lost), n_restored=len(restored), trap_fired=trap,
788
+ recovered_in_attempt=bool(trap and success), n_slams=len(slams),
789
+ slam_speeds=[e["speed_mps"] for e in slams], slam_jerk_cm=[e["cabinet_jerk_cm"] for e in slams],
790
+ bottles_lost_to_slam=sorted({e["stage"].split("_")[0] for e in slam_losses}),
791
+ robot_touched_before_fall=[bool(x) for x in mon["touched_before_fall"]],
792
+ bottle_max_tilt_deg=[round(x, 1) for x in mon["max_tilt"]], n_fallen=mon["n_fallen"],
793
+ held=held, touching=touching, static=bool(static), gripper_open=grip_open,
794
+ drawer_q_cm=round(100 * self.q(), 2), cabinet_moved_cm=round(100 * self.cab_moved(), 2),
795
+ cabinet_tilt_deg=round(float(np.degrees(self.cab_tilt())), 1),
796
+ bottle_tilts_deg={B_NAME[b]: round(float(np.degrees(self.tilt(b))), 1) for b in BOTTLES},
797
+ self_closing=bool(inst["self_closing"]), detail=detail)
798
+
799
+ def _detail(self, vals, held, touching, cab_ok, static, grip_open, success, ev):
800
+ parts = []
801
+ if success:
802
+ parts.append("Both bottles stand on the cabinet, the two cubes are in the closed drawer.")
803
+ top_c = self.from_cab([0.0, 0.0, CH])
804
+ for b in BOTTLES:
805
+ k = f"{B_NAME[b]}_bottle_on_top"
806
+ if vals[k]:
807
+ continue
808
+ nm = B_NAME[b]
809
+ if b in held:
810
+ parts.append(f"The {nm} bottle is still held by the gripper.")
811
+ continue
812
+ tl = float(np.degrees(self.tilt(b)))
813
+ base = self.bottle_base(b)
814
+ rel = base - top_c
815
+ on_top = abs(float(rel[2])) < 0.03
816
+ ax = self.R(b)[:, 2]
817
+ where = f"its base is {_fb(rel[0])} and {_lr(rel[1])} of the centre of the cabinet top"
818
+ if tl <= np.degrees(UPRIGHT):
819
+ txt = (f"The {nm} bottle stands but not on the cabinet top: {where}." if not on_top else
820
+ f"The {nm} bottle stands with part of its base over the edge of the cabinet top: {where}.")
821
+ elif on_top and ax[0] > 0.3 and self.to_cab(self.cap_xyz(b))[0] > CD / 2 - RAIL_T:
822
+ txt = (f"The {nm} bottle has tipped over forward on the cabinet top and leans {tl:.0f} degrees against "
823
+ f"the rail along the top's far edge; {where}.")
824
+ elif on_top:
825
+ txt = f"The {nm} bottle has tipped over on the cabinet top ({tl:.0f} degrees); {where}."
826
+ elif base[2] < Z + 0.03:
827
+ txt = f"The {nm} bottle has fallen over and lies on the table; {where}."
828
+ else:
829
+ txt = f"The {nm} bottle has fallen over and leans {tl:.0f} degrees against something; {where}."
830
+ lost = [e for e in ev if e.get("stage") == k and e.get("event") == "lost"]
831
+ if lost:
832
+ why = lost[-1].get("cause", "other")
833
+ txt += {"drawer_slam": " It had stood on the cabinet top; it fell when the drawer snapped shut and the "
834
+ "cabinet jerked.",
835
+ "robot_hand": " It had stood on the cabinet top; the gripper knocked it.",
836
+ "robot_arm": " It had stood on the cabinet top; the robot's arm knocked it.",
837
+ "bottle": " It had stood on the cabinet top; the other bottle knocked it."}.get(
838
+ why, " It had stood on the cabinet top earlier.")
839
+ parts.append(txt)
840
+ for c in CUBES:
841
+ if vals[f"{CUBE_COLOR[c]}_cube_in_drawer"]:
842
+ continue
843
+ nm = CUBE_COLOR[c]
844
+ if c in held:
845
+ parts.append(f"The {nm} cube is still held by the gripper.")
846
+ continue
847
+ p = envs.obj_pos(self.env, c)
848
+ rel = self.to_cab(p)
849
+ if abs(rel[0]) < CD / 2 and abs(rel[1]) < CW / 2 and rel[2] > CH - 0.01:
850
+ parts.append(f"The {nm} cube lies on the cabinet top, not in the drawer.")
851
+ else:
852
+ parts.append(f"The {nm} cube is not in the drawer: it is {_fb(rel[0] + CD / 2)} and {_lr(rel[1])} of the "
853
+ f"middle of the cabinet's front.")
854
+ if not vals["drawer_closed"]:
855
+ parts.append(f"The drawer is still {100 * self.q():.1f} cm open.")
856
+ if not cab_ok:
857
+ if self.cab_tilt() > CAB_TILT_MAX:
858
+ parts.append("The cabinet has been knocked over.")
859
+ else:
860
+ parts.append(f"The cabinet was moved {100 * self.cab_moved():.0f} cm from where it stood.")
861
+ if not success and all(vals.values()) and cab_ok:
862
+ if touching:
863
+ parts.append("The gripper is still touching " + " and ".join(touching) + ".")
864
+ elif not grip_open:
865
+ parts.append("The gripper is closed.")
866
+ elif not static:
867
+ parts.append("Something was still moving.")
868
+ slams = [e for e in ev if e.get("event") == "drawer_slam" and e.get("bottles_fell")]
869
+ if slams and success:
870
+ parts.append("(The drawer snapped shut and knocked bottles off the cabinet; they were stood up again.)")
871
+ return " ".join(parts)
872
+
873
+ # ------------------------------------------------------------ scripted primitives (move_to + gripper only)
874
+ def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
875
+ return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
876
+
877
+ def _lift_to(self, z, speed=0.15):
878
+ cur = self.sk.eef_pos()
879
+ if cur[2] < z - 0.005:
880
+ self._go([cur[0], cur[1], z], speed=speed)
881
+
882
+ def _settle(self, name, max_checks=25):
883
+ d = self.env.sim.data
884
+ _, da = envs.free_joint_addr(self.env, name)
885
+ for _ in range(max_checks):
886
+ if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
887
+ return
888
+ self.sk.hold(2)
889
+
890
+ def _box_yaw(self, name):
891
+ R = self.R(name)
892
+ i = int(np.argmin(np.abs(R[2])))
893
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
894
+ y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
895
+ cands = [y + k * np.pi / 2 for k in (-1, 0, 1)]
896
+ return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0)
897
+
898
+ def pick_bottle(self, b, grasp="neck", z_clear=0.05, yaw=None, v=0.15):
899
+ """Sonnet-like pick of a standing bottle from above: over it, straight down, close, lift until its bottom
900
+ clears the cabinet top by z_clear. grasp: neck (1 cm below its top; the body cannot be reached from above, the
901
+ palm would land on the cap) | cap (the bottle then hangs from a pivot)"""
902
+ sk = self.sk
903
+ self._settle(b)
904
+ p = envs.obj_pos(self.env, b)
905
+ bot = self.bottle_base(b)[2]
906
+ zg = {"neck": bot + NECK_GRASP, "cap": bot + CAP_Z}[grasp]
907
+ yaw = self._box_yaw(b) if yaw is None else yaw
908
+ sk.set_gripper(False, steps=8)
909
+ top = bot + H_TOT
910
+ self.transit(p[:2], top + 0.06, yaw=yaw, v=v)
911
+ self._go([p[0], p[1], zg + 0.015], speed=0.1)
912
+ self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150)
913
+ sk.set_gripper(True, steps=15)
914
+ lift = self.top_z() + z_clear + (zg - bot)
915
+ self._go([p[0], p[1], lift], speed=0.10)
916
+ sk.hold(5)
917
+ if not self.held(b):
918
+ sk.set_gripper(False, steps=8)
919
+ return False
920
+ return True
921
+
922
+ def put_bottle(self, b, xy, gap=0.01, z_clear=0.05, v=0.12, settle=15):
923
+ """carry the held bottle over xy (its axis, not the grasp point), straight down until its bottom is `gap` above
924
+ the cabinet top, let go, lift"""
925
+ sk = self.sk
926
+ rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2]
927
+ q = np.asarray(xy, float) - rel
928
+ zc = self.top_z() + z_clear + (sk.eef_pos()[2] - self.bottle_base(b)[2])
929
+ self.transit(q, zc, v=v, carried=b, margin=z_clear)
930
+ sk.hold(settle)
931
+ rel = envs.obj_pos(self.env, b)[:2] - sk.eef_pos()[:2]
932
+ q = np.asarray(xy, float) - rel
933
+ dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, b)
934
+ zr = self.top_z() + dz + gap
935
+ self._go([q[0], q[1], zr + 0.02], speed=0.08)
936
+ self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
937
+ sk.hold(5)
938
+ sk.set_gripper(False, steps=12)
939
+ cur = sk.eef_pos()
940
+ self._go([cur[0], cur[1], self.top_z() + H_TOT + 0.06], speed=0.08)
941
+ self._settle(b)
942
+
943
+ def obstacle_top(self, p0, p1, ignore=(), r=0.09):
944
+ """highest top (world z) of standing bottles within r of the straight path p0 -> p1 (xy), and of the cabinet
945
+ top if the path passes over it (expanded by 4 cm)"""
946
+ a, b = np.asarray(p0, float)[:2], np.asarray(p1, float)[:2]
947
+ ab = b - a
948
+ L2 = max(float(ab @ ab), 1e-9)
949
+
950
+ def dist(q):
951
+ u = float(np.clip((q - a) @ ab / L2, 0.0, 1.0))
952
+ return float(np.linalg.norm(a + u * ab - q))
953
+ top = Z
954
+ for o in BOTTLES:
955
+ if o in ignore or self.held(o):
956
+ continue
957
+ if dist(envs.obj_pos(self.env, o)[:2]) < r:
958
+ top = max(top, envs.obj_max_z(self.env, o))
959
+ for u in np.linspace(0.0, 1.0, 21):
960
+ c = self.to_cab(np.r_[a + u * ab, Z])
961
+ if abs(c[0]) < CD / 2 + 0.04 + PF + max(self.q(), 0.0) and abs(c[1]) < CW / 2 + 0.04:
962
+ top = max(top, self.top_z() + RAIL_H)
963
+ break
964
+ return top
965
+
966
+ def transit(self, xy, z_min, yaw=None, v=0.15, carried=None, margin=0.06):
967
+ """Sonnet-like transit: up (to clear what is in the way), straight across, the caller then goes down"""
968
+ sk = self.sk
969
+ cur = sk.eef_pos()
970
+ obst = self.obstacle_top(cur, xy, ignore=(carried,) if carried else ())
971
+ below = (sk.eef_pos()[2] - envs.obj_min_z(self.env, carried)) if carried else 0.03
972
+ zt = max(cur[2], z_min, obst + margin + below)
973
+ if cur[2] < zt - 0.005:
974
+ self._go([cur[0], cur[1], zt], speed=v)
975
+ self._go([xy[0], xy[1], zt], yaw=yaw, speed=v)
976
+
977
+ def pick_cube(self, c, z_carry=0.15, v=0.15):
978
+ sk = self.sk
979
+ for _ in range(2):
980
+ self._settle(c)
981
+ p = envs.obj_pos(self.env, c)
982
+ yaw = self._box_yaw(c)
983
+ sk.set_gripper(False, steps=8)
984
+ self.transit(p[:2], Z + z_carry, yaw=yaw, v=v)
985
+ self._go([p[0], p[1], p[2] + 0.015], speed=0.1)
986
+ self._go([p[0], p[1], p[2]], speed=0.04, tol=0.003, max_steps=120)
987
+ sk.set_gripper(True, steps=15)
988
+ self._go([p[0], p[1], max(Z + z_carry, sk.eef_pos()[2])], speed=v)
989
+ if self.held(c):
990
+ return True
991
+ sk.set_gripper(False, steps=8)
992
+ return False
993
+
994
+ def drawer_slot(self, k, noise=None):
995
+ """world xy of cube slot k (0..1) in the exposed part of the open drawer: a column along the drawer's middle
996
+ (with the wrist at yaw 0 the open fingers, 13.2 cm across, stay clear of the side walls and of the cube
997
+ already in; the palm, 3.9 cm ahead of the grasp point, stays clear of the carcass; the far slot first)"""
998
+ q = min(self.q(), Q_OPEN)
999
+ x = self.cab_front_x() - 0.045 - k * (q - 0.070)
1000
+ y = self.cab_xy()[1]
1001
+ out = np.array([x, y])
1002
+ return out + (np.asarray(noise, float) if noise is not None else 0.0)
1003
+
1004
+ def put_cube(self, c, xy, gap=0.02, z_carry=0.15, v=0.15):
1005
+ sk = self.sk
1006
+ self.transit(xy, Z + z_carry, yaw=0.0, v=v, carried=c, margin=0.04)
1007
+ zr = Z + FLOOR_TOP + CUBE_E / 2 + gap
1008
+ self._go([xy[0], xy[1], zr + 0.015], speed=0.1)
1009
+ self._go([xy[0], xy[1], zr], speed=0.04, tol=0.003, max_steps=120)
1010
+ sk.set_gripper(False, steps=12)
1011
+ self._go([xy[0], xy[1], Z + z_carry], speed=v)
1012
+ self._settle(c)
1013
+
1014
+ def close_drawer(self, v=0.04, z_push=0.05, overshoot=0.0, y_off=0.0, approach=0.03):
1015
+ """closed gripper in front of the drawer, then a straight push forward to where the front panel is flush"""
1016
+ sk = self.sk
1017
+ y = self.cab_xy()[1] + y_off
1018
+ xs = self.drawer_front_x() - FINGER_AHEAD - approach
1019
+ x_end = self.cab_front_x() - PF - FINGER_AHEAD + overshoot
1020
+ sk.set_gripper(True, steps=10)
1021
+ cur = sk.eef_pos()
1022
+ self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15)
1023
+ self._go([xs, y, Z + 0.15], yaw=0.0, speed=0.15)
1024
+ self._go([xs, y, Z + z_push], speed=0.1, tol=0.003)
1025
+ self._go([x_end, y, Z + z_push], speed=v, tol=0.003, max_steps=int(0.25 / max(v, 0.01) / 0.05) + 60)
1026
+ self.sk.hold(10)
1027
+ cur = sk.eef_pos()
1028
+ self._go([cur[0] - 0.06, cur[1], cur[2]], speed=0.08)
1029
+ self._go([cur[0] - 0.06, cur[1], Z + 0.20], speed=0.15)
1030
+ sk.hold(10)
1031
+
1032
+ def top_spots(self, mode="pair", noise=None):
1033
+ """world xy targets on the cabinet top for the two bottles (left one first): side by side across the middle"""
1034
+ c = self.from_cab([0.0, 0.0, CH])[:2]
1035
+ spots = [c + np.array([0.0, 0.05]), c + np.array([0.0, -0.05])]
1036
+ if noise is not None:
1037
+ spots = [s + np.asarray(n, float) for s, n in zip(spots, noise)]
1038
+ return spots
1039
+
1040
+ def free_top_spot(self, b, start=None):
1041
+ """a spot on the cabinet top (cabinet frame candidates) at least 6.5 cm from the other bottle if that one stands
1042
+ on the top, and -- if `start` (xy the bottle comes from) is given -- whose straight path from `start` passes
1043
+ farthest from it"""
1044
+ other = [o for o in BOTTLES if o != b][0]
1045
+ cands = [np.array([dx, dy]) for dx in (0.0, -0.03, 0.03) for dy in (0.055, -0.055, 0.0)]
1046
+ ok_other = self.bottle_on_top(other, 0.01, np.radians(20))
1047
+ oc = self.to_cab(self.bottle_base(other))[:2]
1048
+ if not ok_other:
1049
+ return self.from_cab([cands[0][0], cands[0][1], CH])[:2] if start is None else min(
1050
+ (self.from_cab([c[0], c[1], CH])[:2] for c in cands[:2]),
1051
+ key=lambda w: float(np.linalg.norm(w - np.asarray(start)[:2])))
1052
+ best, score = None, -1.0
1053
+ st = None if start is None else self.to_cab(np.r_[np.asarray(start)[:2], Z])[:2]
1054
+ for c in cands:
1055
+ if np.linalg.norm(c - oc) < 0.065:
1056
+ continue
1057
+ if st is None:
1058
+ return self.from_cab([c[0], c[1], CH])[:2]
1059
+ ab = c - st
1060
+ u = float(np.clip((oc - st) @ ab / max(float(ab @ ab), 1e-9), 0.0, 1.0))
1061
+ clear = float(np.linalg.norm(st + u * ab - oc))
1062
+ if clear > score:
1063
+ best, score = c, clear
1064
+ if best is None:
1065
+ best = max(cands, key=lambda c: float(np.linalg.norm(c - oc)))
1066
+ return self.from_cab([best[0], best[1], CH])[:2]
1067
+
1068
+ def restand_bottle(self, b, xy=None):
1069
+ """stand a fallen bottle up again on the cabinet top: grasp the ball cap from above (fingers across the lying
1070
+ bottle's axis), lift until it hangs free with its bottom above the gallery rail, carry it over a free spot,
1071
+ lower until the bottom is ~3 mm above the top, let go. Returns True if it stands on the top."""
1072
+ sk = self.sk
1073
+ self._settle(b)
1074
+ for _ in range(2):
1075
+ if _reach(self.cap_xyz(b)) > REACH_MAX and self.tilt(b) > FALLEN:
1076
+ self.pull_in_bottle(b)
1077
+ k = self.cap_xyz(b)
1078
+ ax = self.R(b)[:2, 2]
1079
+ yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it
1080
+ sk.set_gripper(False, steps=8)
1081
+ self.transit(k[:2], k[2] + 0.08, yaw=yaw, v=0.15)
1082
+ sk.hold(5)
1083
+ k = self.cap_xyz(b)
1084
+ self._go([k[0], k[1], k[2] + 0.015], speed=0.1)
1085
+ self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120)
1086
+ sk.set_gripper(True, steps=15)
1087
+ if not self.held(b):
1088
+ sk.set_gripper(False, steps=8)
1089
+ self._go([k[0], k[1], k[2] + 0.08], speed=0.1)
1090
+ continue
1091
+ zl = self.top_z() + RAIL_H + 0.03 + CAP_Z
1092
+ self._go([k[0], k[1], zl], speed=0.10)
1093
+ sk.hold(15)
1094
+ tx, ty = self.free_top_spot(b, start=k[:2]) if xy is None else xy
1095
+ self._go([tx, ty, zl], speed=0.10)
1096
+ sk.hold(30)
1097
+ self._go([tx, ty, self.top_z() + CAP_Z + 0.015], speed=0.08)
1098
+ self._go([tx, ty, self.top_z() + CAP_Z + 0.003], speed=0.03, tol=0.003, max_steps=120)
1099
+ sk.set_gripper(False, steps=12)
1100
+ self._go([tx, ty, self.top_z() + H_TOT + 0.04], speed=0.08)
1101
+ sk.hold(20)
1102
+ self._settle(b)
1103
+ if self.bottle_on_top(b):
1104
+ return True
1105
+ return self.bottle_on_top(b)
1106
+
1107
+ def pull_in_bottle(self, b):
1108
+ """the lying bottle's cap is out of reach: grasp the body near its bottom end (fingers across it), lift it
1109
+ 3 cm, pull it towards the robot until the cap is within reach, set it down"""
1110
+ sk = self.sk
1111
+ Rb = self.R(b)
1112
+ ax = Rb[:, 2]
1113
+ g = envs.obj_pos(self.env, b) - ax * (H_TOT / 2 - 0.04)
1114
+ zg = max(float(g[2] - Z), 0.02)
1115
+ yaw = float(np.arctan2(ax[1], ax[0]))
1116
+ need = _reach(self.cap_xyz(b)) - (REACH_MAX - 0.05)
1117
+ to_base = np.array([-0.66, 0.0]) - g[:2]
1118
+ to_base /= max(np.linalg.norm(to_base), 1e-6)
1119
+ dst = g[:2] + to_base * need
1120
+ sk.set_gripper(False, steps=8)
1121
+ self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15)
1122
+ self._go([g[0], g[1], Z + zg + 0.015], speed=0.1)
1123
+ self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
1124
+ sk.set_gripper(True, steps=15)
1125
+ self._go([g[0], g[1], Z + zg + 0.03], speed=0.08)
1126
+ self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08)
1127
+ self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04)
1128
+ sk.set_gripper(False, steps=12)
1129
+ self._go([dst[0], dst[1], Z + 0.15], speed=0.1)
1130
+ self._settle(b)
1131
+
1132
+ # ------------------------------------------------------------ scripted policies
1133
+ def check_and_fix(self, params, rounds=2):
1134
+ """look at every stage at the end: stand fallen bottles up on the top, put stray cubes into the drawer if it is
1135
+ still open"""
1136
+ for _ in range(rounds):
1137
+ v = self.stage_values()
1138
+ if all(v.values()):
1139
+ break
1140
+ for b in BOTTLES:
1141
+ if not self.bottle_on_top(b):
1142
+ if self.tilt(b) > UPRIGHT or self.bottle_base(b)[2] < self.top_z() - 0.03:
1143
+ if self.tilt(b) > UPRIGHT:
1144
+ self.restand_bottle(b)
1145
+ elif self.pick_bottle(b, grasp="neck"):
1146
+ self.put_bottle(b, self.free_top_spot(b), gap=0.005)
1147
+ if not self.drawer_closed():
1148
+ for k, c in enumerate(CUBES):
1149
+ if not self.cube_in_drawer(c) and self.pick_cube(c):
1150
+ self.put_cube(c, self.drawer_slot(k))
1151
+ if all(self.cube_in_drawer(c) for c in CUBES):
1152
+ self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05))
1153
+ self._lift_to(self.top_z() + 0.15)
1154
+ self.sk.set_gripper(False, steps=8)
1155
+ self.sk.hold(10)
1156
+
1157
+ def do_bottles(self, params, rng):
1158
+ noise = params.get("noise")
1159
+ spots = self.top_spots(noise=noise)
1160
+ side = 1.0 if self.inst["bottle_side"] == "left" else -1.0
1161
+ spots = sorted(spots, key=lambda q: side * float(q[1])) # the spot farther from the bottles' side first
1162
+ order = list(BOTTLES) if params.get("bottle_order", "listed") == "listed" else list(BOTTLES)[::-1]
1163
+ for b, xy in zip(order, spots):
1164
+ for _ in range(2):
1165
+ if self.pick_bottle(b, grasp=params.get("grasp", "neck"), z_clear=params.get("z_clear", 0.05)):
1166
+ self.put_bottle(b, xy, gap=params.get("gap", 0.02), z_clear=params.get("z_clear", 0.05))
1167
+ break
1168
+
1169
+ def do_cubes(self, params, rng):
1170
+ noise = params.get("cube_noise") or [None] * 3
1171
+ for k, c in enumerate(self._cube_order()):
1172
+ if self.pick_cube(c):
1173
+ self.put_cube(c, self.drawer_slot(k, noise[k]), gap=params.get("cube_gap", 0.02))
1174
+
1175
+ def _cube_order(self):
1176
+ """nearest the drawer first"""
1177
+ d = np.array([self.cab_front_x() - Q_OPEN / 2, self.cab_xy()[1]])
1178
+ return sorted(CUBES, key=lambda c: float(np.linalg.norm(envs.obj_pos(self.env, c)[:2] - d)))
1179
+
1180
+ def execute(self, inst, params):
1181
+ rng = np.random.default_rng(params.get("noise_seed", 0))
1182
+ order = params.get("order", "BCD") # B = bottles on top, C = cubes into the drawer, D = close the drawer
1183
+ for step in order:
1184
+ if step == "B":
1185
+ self.do_bottles(params, rng)
1186
+ elif step == "C":
1187
+ self.do_cubes(params, rng)
1188
+ elif step == "D":
1189
+ self.close_drawer(v=params.get("push_v", 0.04), z_push=params.get("push_z", 0.05),
1190
+ overshoot=params.get("overshoot", 0.0))
1191
+ if params.get("check"):
1192
+ self.check_and_fix(params)
1193
+ else:
1194
+ self._lift_to(self.top_z() + 0.15)
1195
+ self.sk.set_gripper(False, steps=8)
1196
+ self.sk.hold(10)
1197
+
1198
+ def _noise(self, rng, err=NAIVE_ERR):
1199
+ return dict(noise=[rng.uniform(-err, err, 2).tolist() for _ in BOTTLES],
1200
+ cube_noise=[rng.uniform(-err, err, 2).tolist() for _ in CUBES])
1201
+
1202
+ def default_params(self, inst):
1203
+ """Sonnet-like: the order of the instruction (bottles, cubes, drawer); bottles grasped by the body from above,
1204
+ lifted until they clear the cabinet top by 5 cm, lowered straight down and let go 1-4 cm above it; cubes into
1205
+ the drawer; the drawer pushed shut slowly (4 cm/s) with the closed gripper; no final look back"""
1206
+ rng = np.random.default_rng(inst["naive_noise_seed"])
1207
+ p = dict(order="BCD", check=False, grasp="neck", gap=float(rng.uniform(0.01, 0.04)),
1208
+ push_v=float(rng.uniform(0.03, 0.05)), push_z=float(rng.uniform(0.04, 0.06)),
1209
+ overshoot=float(rng.uniform(0.0, 0.004)), noise_seed=int(inst["naive_noise_seed"]))
1210
+ p.update(self._noise(rng))
1211
+ return p
1212
+
1213
+ def oracle_params(self, inst):
1214
+ """knows the drawer: cubes in, drawer shut, then the bottles; checks every stage at the end"""
1215
+ return dict(order="CDB", check=True, grasp="neck", gap=0.008, push_v=0.04, push_z=0.05, overshoot=0.0)
1216
+
1217
+ def adapt_params(self, inst, history):
1218
+ """attempt >= 2 (after the bottles fell when the drawer was shut): shut the drawer before the bottles go on
1219
+ top, and look at every stage at the end"""
1220
+ return dict(self.default_params(inst), order="CDB", check=True)
1221
+
1222
+ def blind_params(self, inst, attempt, rng):
1223
+ """the natural behaviour with random variations (order of the three sub-tasks, push speed / height, release
1224
+ height, placement noise), no history, no final look"""
1225
+ order = str(rng.choice(["BCD", "CBD", "CDB"], p=[0.5, 0.3, 0.2]))
1226
+ p = dict(order=order, check=False, grasp=str(rng.choice(["neck", "cap"])), gap=float(rng.uniform(0.01, 0.04)),
1227
+ push_v=float(rng.uniform(0.02, 0.08)), push_z=float(rng.uniform(0.03, 0.07)),
1228
+ overshoot=float(rng.uniform(0.0, 0.006)), noise_seed=int(rng.integers(1 << 30)))
1229
+ p.update(self._noise(rng))
1230
+ return p
1231
+
1232
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
1233
+ """oracle / naive: one attempt; adaptive: attempt 1 = naive + a final look that stands fallen bottles up again,
1234
+ attempts >= 2 drawer first; blind: naive with random variations.
1235
+ Extra kinds (not in validate's table): switch (naive, then drawer first without a final look), oracle_noise
1236
+ (oracle with +-5 mm placement noise), naive_slow (naive pushing at the slowest agent speed, 2 cm/s),
1237
+ naive_check (naive + final look = adaptive's first attempt)"""
1238
+ k = k or self.max_attempts
1239
+ rng = np.random.default_rng(seed)
1240
+ history = []
1241
+ single = ("oracle", "naive", "oracle_noise", "naive_slow", "naive_check", "naive_neck", "naive_cap")
1242
+ for a in range(k):
1243
+ self.reset_instance(inst)
1244
+ if kind == "oracle":
1245
+ params = self.oracle_params(inst)
1246
+ elif kind == "naive":
1247
+ params = self.default_params(inst)
1248
+ elif kind == "adaptive":
1249
+ params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
1250
+ elif kind == "blind":
1251
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
1252
+ elif kind == "switch":
1253
+ params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), order="CDB")
1254
+ elif kind == "oracle_noise":
1255
+ params = dict(self.oracle_params(inst), **self._noise(np.random.default_rng(seed * 7 + a), 0.005))
1256
+ elif kind == "naive_slow":
1257
+ params = dict(self.default_params(inst), push_v=0.02)
1258
+ elif kind == "naive_check":
1259
+ params = dict(self.default_params(inst), check=True)
1260
+ elif kind == "naive_neck":
1261
+ params = dict(self.default_params(inst), grasp="neck")
1262
+ elif kind == "naive_cap":
1263
+ params = dict(self.default_params(inst), grasp="cap")
1264
+ else:
1265
+ raise ValueError(kind)
1266
+ self.execute(inst, params)
1267
+ out = self.outcome(inst)
1268
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
1269
+ if on_attempt:
1270
+ on_attempt(a, params, out)
1271
+ if out["success"] or kind in single:
1272
+ break
1273
+ return history
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-v4.1-flash_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full|2.1.267|0399c793ff571d59|deepseek-v4.1-flash|high",
3
+ "fingerprint_sha256": "c5305ffa663057875e7ec2ef2900433eb510f1ee6b3fab7fb7acdca3c289cdc6",
4
+ "written": "2026-10-30 16:00:21",
5
+ "summary": {
6
+ "system_chars": 6052,
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-v4.1-flash"
14
+ }
15
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-flash|high",
3
+ "fingerprint_sha256": "c998aa8a7624948e949f21c563d129e964416edc94f9e22b0237a9d8c46dbe47",
4
+ "written": "2026-10-20 02:36:39",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "deepseek-flash",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|medium",
3
+ "fingerprint_sha256": "cdffdbedeb4b110f1f29227ee9459940be8175df4ca71546690ff6db0cccbd6a",
4
+ "written": "2026-10-13 04:13:35",
5
+ "summary": {
6
+ "developer_chars": 23961,
7
+ "top_tools": [
8
+ "collaboration.followup_task",
9
+ "collaboration.interrupt_agent",
10
+ "collaboration.list_agents",
11
+ "collaboration.send_message",
12
+ "collaboration.spawn_agent",
13
+ "collaboration.wait_agent",
14
+ "functions.exec",
15
+ "functions.request_user_input",
16
+ "functions.request_user_input_async",
17
+ "functions.wait"
18
+ ],
19
+ "all_tools": [
20
+ "apply_patch",
21
+ "clock__curr_time",
22
+ "list_mcp_resource_templates",
23
+ "list_mcp_resources",
24
+ "mcp__lff__robot",
25
+ "mcp__lff__shell",
26
+ "mcp__lff__view_images",
27
+ "read_mcp_resource"
28
+ ],
29
+ "effort_in_request": "medium",
30
+ "model_in_request": "gpt-6-astra",
31
+ "sandbox": {
32
+ "sandbox": "seccomp",
33
+ "sandbox_mode": "read-only"
34
+ }
35
+ }
36
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/make_video.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Record a scripted rollout of a task as an mp4 (agentview | wrist), with title cards between attempts.
2
+
3
+ python scripts/make_video.py --task l1_bias_place --kind adaptive --seed 1000
4
+ """
5
+ import argparse
6
+ import importlib
7
+ import os
8
+ import pkgutil
9
+ import sys
10
+ import textwrap
11
+
12
+ import numpy as np
13
+
14
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15
+ sys.path.insert(0, ROOT)
16
+
17
+ import imageio # noqa: E402
18
+ from PIL import Image, ImageDraw, ImageFont # noqa: E402
19
+
20
+ import lffbench.tasks as task_pkg # noqa: E402
21
+ from lffbench import envs # noqa: E402
22
+ from lffbench.task_base import TASKS # noqa: E402
23
+
24
+ for m in pkgutil.iter_modules(task_pkg.__path__):
25
+ importlib.import_module(f"lffbench.tasks.{m.name}")
26
+
27
+ RES = 320
28
+ FPS = 15
29
+
30
+
31
+ def font(size):
32
+ try:
33
+ return ImageFont.load_default(size=size)
34
+ except TypeError:
35
+ return ImageFont.load_default()
36
+
37
+
38
+ def header(img, lines):
39
+ im = Image.fromarray(img)
40
+ d = ImageDraw.Draw(im)
41
+ d.rectangle([0, 0, im.width, 18 * len(lines) + 6], fill=(0, 0, 0))
42
+ for i, s in enumerate(lines):
43
+ d.text((6, 3 + 18 * i), s, fill=(255, 255, 255), font=font(15))
44
+ return np.asarray(im)
45
+
46
+
47
+ def card(lines, w, h, color=(20, 20, 20)):
48
+ im = Image.new("RGB", (w, h), color)
49
+ d = ImageDraw.Draw(im)
50
+ y = 20
51
+ for s in lines:
52
+ for part in textwrap.wrap(s, 70) or [""]:
53
+ d.text((20, y), part, fill=(255, 255, 255), font=font(18))
54
+ y += 24
55
+ y += 6
56
+ return np.asarray(im)
57
+
58
+
59
+ def main():
60
+ ap = argparse.ArgumentParser()
61
+ ap.add_argument("--task", required=True)
62
+ ap.add_argument("--kind", default="adaptive")
63
+ ap.add_argument("--seed", type=int, default=1000)
64
+ ap.add_argument("--k", type=int, default=5)
65
+ ap.add_argument("--every", type=int, default=3, help="record one frame every N control steps")
66
+ ap.add_argument("--out", default=None)
67
+ args = ap.parse_args()
68
+
69
+ task = TASKS[args.task]()
70
+ env = task.env
71
+ inst = task.sample_instance(args.seed)
72
+ frames = []
73
+ state = dict(n=0, attempt=1)
74
+ W = 2 * RES
75
+
76
+ def grab():
77
+ a = envs.render(env, "agentview", RES)
78
+ w = envs.render(env, "robot0_eye_in_hand", RES)
79
+ img = np.concatenate([a, w], axis=1)
80
+ return header(img, [f"{args.task} [{task.level}] policy={args.kind} seed={args.seed}",
81
+ f"attempt {state['attempt']} t={state['n'] * 0.05:5.1f}s (sim) left: agentview right: wrist"])
82
+
83
+ orig_step = env.step
84
+
85
+ def step(a):
86
+ out = orig_step(a)
87
+ state["n"] += 1
88
+ if state["n"] % args.every == 0:
89
+ frames.append(grab())
90
+ return out
91
+
92
+ env.step = step
93
+
94
+ def on_attempt(a, params, out):
95
+ txt = [f"Attempt {a + 1}: {'SUCCESS' if out['success'] else 'FAILED'}"]
96
+ if out.get("detail"):
97
+ txt.append("Feedback (F2): " + out["detail"])
98
+ p = {k: (round(v, 3) if isinstance(v, float) else v) for k, v in (params or {}).items()
99
+ if not isinstance(v, (list, dict)) or len(str(v)) < 120}
100
+ if p:
101
+ txt.append(f"params: {p}")
102
+ if not out["success"]:
103
+ txt.append(f"-> attempt {a + 2}")
104
+ frames.extend([card(txt, W, RES, (40, 20, 20) if not out["success"] else (20, 50, 20))] * (FPS * 3))
105
+ state["attempt"] = a + 2
106
+
107
+ intro = card([f"Task: {args.task} (level {task.level}; capabilities: {', '.join(task.capabilities)})",
108
+ f"Instruction: {task.instruction}",
109
+ f"Policy: {args.kind} (scripted reference)",
110
+ "Hidden variables are not visible to the policy."], W, RES)
111
+ frames.extend([intro] * (FPS * 3))
112
+ task.reset_instance(inst)
113
+ frames.append(grab())
114
+ n_cards_before = len(frames)
115
+ hist = task.run_scripted(args.kind, inst, k=args.k, seed=args.seed, on_attempt=on_attempt)
116
+ # tasks whose run_scripted does not call on_attempt: summarise at the end
117
+ if not any(f is not None and f.shape[0] == RES and (f[5, 5] == np.array([40, 20, 20])).all() for f in frames[n_cards_before:]) \
118
+ and not any((f[5, 5] == np.array([20, 50, 20])).all() for f in frames[n_cards_before:]):
119
+ lines = []
120
+ for h in hist:
121
+ o = h["outcome"]
122
+ lines.append(f"Attempt {h['attempt']}: {'SUCCESS' if o['success'] else 'FAILED'} — {o.get('detail', '')}")
123
+ frames.extend([card(lines[-6:], W, RES)] * (FPS * 4))
124
+ out = args.out or os.path.join(ROOT, "videos", f"{args.task}_{args.kind}_s{args.seed}.mp4")
125
+ os.makedirs(os.path.dirname(out), exist_ok=True)
126
+ imageio.mimwrite(out, frames, fps=FPS, quality=7, macro_block_size=8)
127
+ first = next((h["attempt"] for h in hist if h["outcome"]["success"]), None)
128
+ print(f"wrote {out} frames={len(frames)} attempts={len(hist)} first_success={first}")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/client/lffbench_client/__init__.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LFF-Bench Python client: the three agent tools of one episode, for any robot harness framework (docs/18 §6.3).
2
+
3
+ Only the standard library; it never imports the simulator. It talks to the episode's tool gateway
4
+ (scripts/tool_gateway.py), which runs next to the robot server and owns the per-attempt tool-call budget, the jailed
5
+ shell and the workspace images. A framework registers the three tools with the schemas from tool_specs() and calls
6
+ them through a Session:
7
+
8
+ from lffbench_client import Session
9
+ s = Session.from_env() # LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN (set by the launcher)
10
+ first = s.first_message() # README + first status, as every harness gets it
11
+ tools = s.tool_specs("openai_responses") # or raw / mcp / anthropic / openai_chat
12
+ r = s.robot("move_eef x=0.5 y=0.0 z=0.2") # -> ToolResult
13
+ r.json() # the robot server's reply as a dict
14
+ s.view_images(["obs/s001_agentview.jpg"]).images # [(mime, bytes)]
15
+
16
+ A ToolResult's content is the list a model should see, in MCP form (text items and base64 image items); finished
17
+ says that the episode is over (stop calling tools). Nothing here can reset the scene or read the verdict: the only
18
+ feedback is what the robot server writes into the tool results.
19
+ """
20
+ import base64
21
+ import dataclasses
22
+ import json
23
+ import os
24
+ import urllib.error
25
+ import urllib.parse
26
+ import urllib.request
27
+
28
+ __all__ = ["Session", "ToolResult", "GatewayError", "STYLES"]
29
+ __version__ = "0.1.0"
30
+
31
+ STYLES = ("raw", "mcp", "anthropic", "openai_responses", "openai_chat")
32
+
33
+
34
+ class GatewayError(RuntimeError):
35
+ pass
36
+
37
+
38
+ @dataclasses.dataclass
39
+ class ToolResult:
40
+ content: list # [{"type": "text", "text"} | {"type": "image", "mimeType", "data" (base64)}]
41
+ is_error: bool
42
+ finished: bool # the episode is over: stop calling tools and report
43
+ calls_in_attempt: int # tool calls used in the current attempt (after an automatic finish: 0)
44
+
45
+ @property
46
+ def text(self):
47
+ """All text items, joined by newlines."""
48
+ return "\n".join(c["text"] for c in self.content if c.get("type") == "text")
49
+
50
+ def json(self):
51
+ """The first text item parsed as JSON (robot / shell / view_images replies are JSON objects)."""
52
+ for c in self.content:
53
+ if c.get("type") == "text":
54
+ return json.loads(c["text"])
55
+ raise ValueError("no text item")
56
+
57
+ @property
58
+ def images(self):
59
+ """[(mime type, bytes)] of the image items."""
60
+ return [(c["mimeType"], base64.b64decode(c["data"])) for c in self.content if c.get("type") == "image"]
61
+
62
+
63
+ class Session:
64
+ """One episode's tools through its gateway. face labels this access path in the gateway transcript."""
65
+
66
+ def __init__(self, url, token, face="sdk", timeout_s=900.0):
67
+ self.url, self.token, self.face, self.timeout_s = url.rstrip("/"), token, face, timeout_s
68
+ self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never via a proxy
69
+
70
+ @classmethod
71
+ def from_env(cls, face="sdk", **kw):
72
+ url, token = os.environ.get("LFF_GATEWAY_URL"), os.environ.get("LFF_GATEWAY_TOKEN")
73
+ if not url or not token:
74
+ raise GatewayError("LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN are not set")
75
+ return cls(url, token, face=face, **kw)
76
+
77
+ @classmethod
78
+ def from_gateway_file(cls, path, face="sdk", **kw):
79
+ """gateway.json written by the gateway in the run's log dir (launchers only; harness processes get env vars)."""
80
+ d = json.load(open(path))
81
+ return cls(d["url"], d["token"], face=face, **kw)
82
+
83
+ # ------------------------------------------------------------------------------------------------ http
84
+ def _request(self, method, path, body=None):
85
+ req = urllib.request.Request(self.url + path, method=method,
86
+ data=None if body is None else json.dumps(body).encode(),
87
+ headers={"Authorization": f"Bearer {self.token}", "X-LFF-Face": self.face,
88
+ "Content-Type": "application/json"})
89
+ try:
90
+ with self._opener.open(req, timeout=self.timeout_s) as r:
91
+ return r.read(), r.headers.get("Content-Type", "")
92
+ except urllib.error.HTTPError as e:
93
+ raise GatewayError(f"{method} {path}: HTTP {e.code}: {e.read()[:500].decode('utf-8', 'replace')}") from None
94
+ except urllib.error.URLError as e:
95
+ raise GatewayError(f"{method} {path}: {e.reason}") from None
96
+
97
+ def _get_json(self, path):
98
+ return json.loads(self._request("GET", path)[0])
99
+
100
+ # ------------------------------------------------------------------------------------------------ tools
101
+ def call(self, name, arguments=None):
102
+ raw, _ = self._request("POST", "/tool", dict(name=name, arguments=arguments or {}))
103
+ d = json.loads(raw)
104
+ return ToolResult(content=d["content"], is_error=bool(d["is_error"]), finished=bool(d["finished"]),
105
+ calls_in_attempt=d.get("calls_in_attempt"))
106
+
107
+ def robot(self, command):
108
+ """One robot command, exactly as in the instructions (e.g. 'status', 'move_eef x=0.5 z=0.2', 'finish ...')."""
109
+ return self.call("robot", dict(command=command))
110
+
111
+ def shell(self, command):
112
+ """A bash command in the episode workspace (jailed: no network, nothing outside the workspace)."""
113
+ return self.call("shell", dict(command=command))
114
+
115
+ def view_images(self, paths):
116
+ """Image files of the workspace (e.g. obs/s001_agentview.jpg); the images come back as image items."""
117
+ return self.call("view_images", dict(paths=list(paths)))
118
+
119
+ # ------------------------------------------------------------------------------------------------ instructions
120
+ def tool_specs(self, style="raw"):
121
+ """The three tool schemas with the reference descriptions, in one of STYLES."""
122
+ if style not in STYLES:
123
+ raise ValueError(f"style must be one of {STYLES}")
124
+ return self._get_json("/tool_specs?style=" + urllib.parse.quote(style))["tools"]
125
+
126
+ def readme(self):
127
+ return self._request("GET", "/readme")[0].decode("utf-8")
128
+
129
+ def first_message(self):
130
+ """Preamble + README + first status report: the first user message every harness gets."""
131
+ return self._request("GET", "/first_message")[0].decode("utf-8")
132
+
133
+ def health(self):
134
+ return self._get_json("/health")
135
+
136
+ def status(self):
137
+ """robot_server's `status` for the framework's own loop (e.g. a "continue" nudge that names the attempt): not
138
+ a tool call of the model, not counted in the per-attempt budget. Never show it to the model as a tool result."""
139
+ return self._get_json("/status")
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/codex_catalogs/generic_0.163.0.json ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "codex_version": "0.163.0",
3
+ "created": "2026-10-20",
4
+ "note": "Shared ('generic') Codex configuration for the main table (user 2026-10-20): every model gets this one catalog entry, with only slug / display_name / input_modalities / supported_reasoning_levels set per model. base_instructions and the other fields reproduce what Codex 0.163.0 sends for a model slug it has no entry for and no model_catalog_json is given (measured against the fake API: identical request apart from message ids): its generic Codex CLI prompt, plain function tools (no code mode), parallel tool calls, reasoning summary auto, no verbosity. See docs/15 8.9.",
5
+ "entry": {
6
+ "description": "",
7
+ "default_reasoning_level": "medium",
8
+ "supported_reasoning_levels": [
9
+ {
10
+ "effort": "low",
11
+ "description": "Fast responses with lighter reasoning"
12
+ },
13
+ {
14
+ "effort": "medium",
15
+ "description": "Balances speed and reasoning depth for everyday tasks"
16
+ },
17
+ {
18
+ "effort": "high",
19
+ "description": "Greater reasoning depth for complex problems"
20
+ },
21
+ {
22
+ "effort": "xhigh",
23
+ "description": "Extra high reasoning depth for complex problems"
24
+ }
25
+ ],
26
+ "shell_type": "default",
27
+ "visibility": "list",
28
+ "supported_in_api": true,
29
+ "priority": 99,
30
+ "additional_speed_tiers": [],
31
+ "service_tiers": [],
32
+ "availability_nux": null,
33
+ "upgrade": null,
34
+ "model_messages": null,
35
+ "include_skills_usage_instructions": false,
36
+ "include_plugin_usage_instructions": false,
37
+ "include_apps_usage_instructions": false,
38
+ "default_reasoning_summary": "auto",
39
+ "support_verbosity": false,
40
+ "default_verbosity": null,
41
+ "apply_patch_tool_type": null,
42
+ "web_search_tool_type": "text",
43
+ "truncation_policy": {
44
+ "mode": "bytes",
45
+ "limit": 10000
46
+ },
47
+ "supports_image_detail_original": false,
48
+ "context_window": 272000,
49
+ "max_context_window": 272000,
50
+ "effective_context_window_percent": 95,
51
+ "experimental_supported_tools": [],
52
+ "input_modalities": [
53
+ "text",
54
+ "image"
55
+ ],
56
+ "supports_search_tool": false,
57
+ "supports_experimental_context": false,
58
+ "use_responses_lite": false,
59
+ "supports_reasoning_effort_updates": false,
60
+ "node_repl_auto_review_required": false,
61
+ "node_repl_disabled": false,
62
+ "base_instructions": "You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.\n\nYour capabilities:\n\n- Receive user prompts and other context provided by the harness, such as files in the workspace.\n- Communicate with the user by streaming thinking & responses, and by making & updating plans.\n- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the \"Sandbox and approvals\" section.\n\nWithin this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).\n\n# How you work\n\n## Personality\n\nYour default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.\n\n# AGENTS.md spec\n- Repos often contain AGENTS.md files. These files can appear anywhere within the repository.\n- These files are a way for humans to give you (the agent) instructions or tips for working within the container.\n- Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code.\n- Instructions in AGENTS.md files:\n - The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it.\n - For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file.\n - Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise.\n - More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions.\n - Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions.\n- The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable.\n\n## Responsiveness\n\n### Preamble messages\n\nBefore making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:\n\n- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.\n- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).\n- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.\n- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.\n- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.\n\n**Examples:**\n\n- “I’ve explored the repo; now checking the API route definitions.”\n- “Next, I’ll patch the config and update the related tests.”\n- “I’m about to scaffold the CLI commands and helper functions.”\n- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”\n- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”\n- “Finished poking at the DB gateway. I will now chase down error handling.”\n- “Alright, build pipeline order is interesting. Checking how it reports failures.”\n- “Spotted a clever caching util; now hunting where it gets used.”\n\n## Task execution\n\nYou are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.\n\nYou MUST adhere to the following criteria when solving queries:\n\n- Working on the repo(s) in the current environment is allowed, even if they are proprietary.\n- Analyzing code for vulnerabilities is allowed.\n- Showing user code and tool call details is allowed.\n- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {\"command\":[\"apply_patch\",\"*** Begin Patch\\\\n*** Update File: path/to/file.py\\\\n@@ def example():\\\\n- pass\\\\n+ return 123\\\\n*** End Patch\"]}\n\nIf completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:\n\n- Fix the problem at the root cause rather than applying surface-level patches, when possible.\n- Avoid unneeded complexity in your solution.\n- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n- Update documentation as necessary.\n- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.\n- Use `git log` and `git blame` to search the history of the codebase if additional context is required.\n- NEVER add copyright or license headers unless specifically requested.\n- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.\n- Do not `git commit` your changes or create new git branches unless explicitly requested.\n- Do not add inline comments within code unless explicitly requested.\n- Do not use one-letter variable names unless explicitly requested.\n- NEVER output inline citations like \"【F:README.md†L5-L14】\" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.\n\n## Validating your work\n\nIf the codebase has tests or the ability to build or run, consider using them to verify that your work is complete. \n\nWhen testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests.\n\nSimilarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.\n\nFor all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)\n\nBe mindful of whether to run validation commands proactively. In the absence of behavioral guidance:\n\n- When running in the non-interactive approval mode **never**, proactively run tests, lint and do whatever you need to ensure you've completed the task.\n- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.\n- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.\n\n## Ambition vs. precision\n\nFor tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.\n\nIf you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.\n\nYou should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.\n\n## Sharing progress updates\n\nFor especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.\n\nBefore doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.\n\nThe messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.\n\n## Presenting your work and final message\n\nYour final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.\n\nYou can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.\n\nThe user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to \"save the file\" or \"copy the code into a file\"—just reference the file path.\n\nIf there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.\n\nBrevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.\n\n### Final answer structure and style guidelines\n\nYou are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.\n\n**Section Headers**\n\n- Use only when they improve clarity — they are not mandatory for every answer.\n- Choose descriptive names that fit the content\n- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`\n- Leave no blank line before the first bullet under a header.\n- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.\n\n**Bullets**\n\n- Use `-` followed by a space for every bullet.\n- Merge related points when possible; avoid a bullet for every trivial detail.\n- Keep bullets to one line unless breaking for clarity is unavoidable.\n- Group into short lists (4–6 bullets) ordered by importance.\n- Use consistent keyword phrasing and formatting across sections.\n\n**Monospace**\n\n- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).\n- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.\n- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).\n\n**File References**\nWhen referencing files in your response, make sure to include the relevant start line and always follow the below rules:\n * Use inline code to make file paths clickable.\n * Each reference should have a stand alone path. Even if it's the same file.\n * Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.\n * Line/column (1‑based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).\n * Do not use URIs like file://, vscode://, or https://.\n * Do not provide range of lines\n * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\\repo\\project\\main.rs:12:5\n\n**Structure**\n\n- Place related bullets together; don’t mix unrelated concepts in the same section.\n- Order sections from general → specific → supporting info.\n- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.\n- Match structure to complexity:\n - Multi-part or detailed results → use clear headers and grouped bullets.\n - Simple results → minimal headers, possibly just a short list or paragraph.\n\n**Tone**\n\n- Keep the voice collaborative and natural, like a coding partner handing off work.\n- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition\n- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).\n- Keep descriptions self-contained; don’t refer to “above” or “below”.\n- Use parallel structure in lists for consistency.\n\n**Don’t**\n\n- Don’t use literal words “bold” or “monospace” in the content.\n- Don’t nest bullets or create deep hierarchies.\n- Don’t output ANSI escape codes directly — the CLI renderer applies them.\n- Don’t cram unrelated keywords into a single bullet; split for clarity.\n- Don’t let keyword lists run long — wrap or reformat for scanability.\n\nGenerally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.\n\nFor casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.\n\n# Tool Guidelines\n\n## Shell commands\n\nWhen using the shell, you must adhere to the following guidelines:\n\n- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)\n- Do not use python scripts to attempt to output larger chunks of a file.\n\n"
63
+ }
64
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/codex_catalogs/native_0.163.0.json ADDED
The diff for this file is too large to render. See raw diff
 
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
3
+ "fingerprint_sha256": "fbf323682711d7010fa8cd2c9036b1082dab2a6cd4cf80983be1adf64e037d7c",
4
+ "written": "2026-10-20 02:16:00",
5
+ "summary": {
6
+ "system_chars": 182,
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/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-fable-5-1|high",
3
+ "fingerprint_sha256": "f44d5ded7b8b847b934c86d8f7b51fa90ae396a1f33bca51e1c946f09da1031b",
4
+ "written": "2026-10-21 05:19:35",
5
+ "summary": {
6
+ "system_chars": 11701,
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-fable-5-1"
14
+ }
15
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/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/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
3
+ "fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4",
4
+ "written": "2026-10-13 04:12:38",
5
+ "summary": {
6
+ "system_chars": 26736,
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/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|high",
3
+ "fingerprint_sha256": "41fecee198c38459b5fae54c29ebf99c368e60381b3f11418dea02590bba5222",
4
+ "written": "2026-10-20 02:33:15",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "gpt-6-astra",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt|0.163.0|399ff69c431c066e|gpt-6-astra|medium",
3
+ "fingerprint_sha256": "034292e12859cda9de8c2481b91f6c3194b83754303be8c40c3ec775bcabf9ad",
4
+ "written": "2026-10-19 22:12:31",
5
+ "summary": {
6
+ "developer_chars": 24091,
7
+ "top_tools": [
8
+ "collaboration.followup_task",
9
+ "collaboration.interrupt_agent",
10
+ "collaboration.list_agents",
11
+ "collaboration.send_message",
12
+ "collaboration.spawn_agent",
13
+ "collaboration.wait_agent",
14
+ "functions.exec",
15
+ "functions.request_user_input",
16
+ "functions.request_user_input_async",
17
+ "functions.wait"
18
+ ],
19
+ "all_tools": [
20
+ "apply_patch",
21
+ "clock__curr_time",
22
+ "list_mcp_resource_templates",
23
+ "list_mcp_resources",
24
+ "mcp__lff__robot",
25
+ "mcp__lff__shell",
26
+ "mcp__lff__view_images",
27
+ "read_mcp_resource"
28
+ ],
29
+ "effort_in_request": "medium",
30
+ "model_in_request": "gpt-6-astra",
31
+ "sandbox": {
32
+ "sandbox": "seccomp",
33
+ "sandbox_mode": "read-only"
34
+ }
35
+ }
36
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-flash|high",
3
+ "fingerprint_sha256": "c998aa8a7624948e949f21c563d129e964416edc94f9e22b0237a9d8c46dbe47",
4
+ "written": "2026-10-20 02:36:39",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "deepseek-flash",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|medium",
3
+ "fingerprint_sha256": "cdffdbedeb4b110f1f29227ee9459940be8175df4ca71546690ff6db0cccbd6a",
4
+ "written": "2026-10-13 04:13:35",
5
+ "summary": {
6
+ "developer_chars": 23961,
7
+ "top_tools": [
8
+ "collaboration.followup_task",
9
+ "collaboration.interrupt_agent",
10
+ "collaboration.list_agents",
11
+ "collaboration.send_message",
12
+ "collaboration.spawn_agent",
13
+ "collaboration.wait_agent",
14
+ "functions.exec",
15
+ "functions.request_user_input",
16
+ "functions.request_user_input_async",
17
+ "functions.wait"
18
+ ],
19
+ "all_tools": [
20
+ "apply_patch",
21
+ "clock__curr_time",
22
+ "list_mcp_resource_templates",
23
+ "list_mcp_resources",
24
+ "mcp__lff__robot",
25
+ "mcp__lff__shell",
26
+ "mcp__lff__view_images",
27
+ "read_mcp_resource"
28
+ ],
29
+ "effort_in_request": "medium",
30
+ "model_in_request": "gpt-6-astra",
31
+ "sandbox": {
32
+ "sandbox": "seccomp",
33
+ "sandbox_mode": "read-only"
34
+ }
35
+ }
36
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-flash|high",
3
+ "fingerprint_sha256": "18044f5deb7b4d0d662d620fce120e85e3f94103fa2699346221fa46d093fc8f",
4
+ "written": "2026-10-31 06:05:50",
5
+ "summary": {
6
+ "system_chars": 109,
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/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_viewer/README.md ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Agent Viewer — historical replay
2
+
3
+ Export saved LFF-Bench API-player logs to one offline HTML page, including original
4
+ image bytes and the complete `rollout.mp4` when available. No model calls, simulator, server, build tools, or frontend dependencies
5
+ are required to generate or open the result.
6
+
7
+ From the repository root:
8
+
9
+ ```bash
10
+ python scripts/agent_viewer/export.py \
11
+ --run runs/gpt/exp2d/exp2d-gpt-6-astra_l5_slide_to_target_s1000_full_F2_direct_k3_1007-060153_p9738 \
12
+ --out traces/agent-viewer-slide/index.html
13
+ ```
14
+
15
+ Open the resulting HTML file in a browser. Repeat `--run` to include multiple
16
+ runs. If a run's original sandbox has moved, use `--sandbox /new/image/root`
17
+ with a single run. Relative images copied into the run directory take precedence.
18
+ The export remains usable after the original sandbox is removed.
19
+
20
+ ## What the viewer shows
21
+
22
+ - Continuous execution video is the default view when `rollout.mp4` exists, with
23
+ native playback, seeking, fullscreen and playback speed controls. The original
24
+ MP4 is embedded byte-for-byte; no still-image slideshow is substituted.
25
+ - The separate step view retains input images and tool logs. Selecting an attempt
26
+ opens its step details. Video and logs are not automatically synchronized because
27
+ old recordings have no frame-to-event index and omit model waiting time.
28
+
29
+ - One step per recorded assistant response; tool calls and results stay together.
30
+ - The most recent observation **before** each decision, and separately the new
31
+ images returned **after** its actions. Older images may also be in model context;
32
+ the viewer shows the request's recorded image count when available.
33
+ - Camera switching, per-step playback, scrubbing, keyboard navigation (arrows and
34
+ space), and jumps to attempt verdicts. Playback uses fixed seconds per step,
35
+ with original elapsed/model latency shown separately.
36
+ - Tool arguments, raw tool results, public assistant replies, API retries, missing
37
+ images, and incomplete calls. Recorded reasoning summaries are exported verbatim between observation and action in the step details.
38
+ The summary of decision N is shown between the preceding feedback and action N.
39
+ Public replies are labeled separately; missing summaries stay explicitly missing.
40
+ These are recorded summaries, not full internal CoT or reconstructed reasoning.
41
+ - A reset warning when a failed `done` returns the next attempt's initial images.
42
+ Attempt success comes from server `done` events, not the assistant's claim.
43
+
44
+ ## Current input contract and limitations
45
+
46
+ Supports the API-player `ev` schema in `transcript.jsonl` or
47
+ `gpt_transcript.jsonl`, with `session.json` and optional `events.jsonl`. Other
48
+ harness formats (MCP, native Codex/Claude, RPent, GPT-Policy) need adapters and
49
+ are not claimed as supported. Corrupt JSON and ambiguous result matching fail
50
+ explicitly instead of silently pairing the wrong steps.
51
+
52
+ Image files are copied byte-for-byte at export time. Old logs contain paths rather
53
+ than image hashes, so files overwritten since the run cannot be authenticated as
54
+ the original model inputs. Missing images are visibly marked; no replacement
55
+ frames are invented. Runs without a video fall back to step replay with the video tab disabled.
56
+
57
+ The sample video is 19.05 seconds, H.264, 640×376 at 20 fps. Its action segments
58
+ were recorded at 3× simulation speed; choose ⅓× playback to slow them back down.
59
+ The recording includes both attempts and their verdict cards, but not model/API
60
+ waiting time.
61
+
62
+ The sample `l5_slide_to_target`, seed 1000, has 14 assistant responses, 13 tool
63
+ calls, and two verdicts: failure then success. It is a historical development
64
+ run using depth perception and F2 feedback, not evidence of general benchmark
65
+ performance. The first push overshot by 4 cm; the next push reduced its endpoint
66
+ from x=-0.105 m to x=-0.145 m and succeeded.
67
+
68
+ ## Verification
69
+
70
+ ```bash
71
+ python -m unittest discover -s tests -p test_agent_viewer.py -v
72
+ ```
73
+
74
+ Regression cases cover observation/action ordering, resets, carried-forward
75
+ observations, API retries, missing artifacts, incomplete calls, reordered call
76
+ IDs, malformed logs, path restrictions, and safe embedding of untrusted text.
77
+
78
+ ## Recording future runs
79
+
80
+ `api_player.py` already requests provider summaries (`auto` for OpenAI) and
81
+ saves returned `reasoning_summary` plus public `text` for each assistant turn.
82
+ `run_agent.py` now also defaults `--reasoning-summary` to `auto`; pass `none`
83
+ when an endpoint cannot support the option. Both loggers add
84
+ `reasoning_summary_status`: `recorded` when a summary is present and
85
+ `not_returned` when the response contains none. This labels response availability,
86
+ not whether summaries were requested or whether the model reasoned internally.
87
+
88
+ Historical missing records are left unchanged. No extra model calls or
89
+ retrospective rationale generation are used. Changes apply to newly started
90
+ processes from this checkout; other worktrees and native CLI harnesses retain
91
+ their own logging behavior. The viewer still imports API-player transcripts;
92
+ `run_agent` logs use a different schema and need an adapter to view here.
93
+
94
+ ## Live terminal viewer
95
+
96
+ `live.py` observes existing runs without contacting the robot/model or changing the
97
+ run. Use a terminal with truecolor support for low-resolution color image previews;
98
+ `--ascii` provides a monochrome fallback. Pillow is the only image dependency and
99
+ is already present in the evaluation environment.
100
+
101
+ ```bash
102
+ python scripts/agent_viewer/live.py --batch /absolute/path/to/runs/api/BATCH
103
+ python scripts/agent_viewer/live.py --run /absolute/path/to/RUN --once --ascii
104
+ ```
105
+
106
+ A batch view follows the first running run and switches when the manifest advances;
107
+ for concurrent runs in one batch, use `--run` to select another. Refresh defaults to
108
+ 6 seconds. `Ctrl+C` exits; `--no-images`, `--width`, `--image-rows`, `--interval`, and
109
+ `--duration` control presentation. A redirected output uses ASCII and no screen
110
+ control codes. `--once` prints one snapshot.
111
+
112
+ Supported live sources: API-player transcripts; framework gateway/MCP tool logs;
113
+ and Codex `item.completed` events. Only successful `view_images` attachments or
114
+ API-player image inputs become displayed observations. Robot-produced files alone
115
+ do not establish that the Agent saw them. Matching embedded images from native
116
+ Codex events take precedence over file references; potentially overwritten files
117
+ are marked unavailable. The current view displays the latest observation batch,
118
+ not continuous video, and explicitly labels its age. Recorded summaries are shown
119
+ when the relevant stream provides them. It does not expose `session.json` tokens,
120
+ server-side hidden task parameters, or send any robot commands.
121
+
122
+ ```bash
123
+ python -m unittest discover -s tests -p test_live_viewer.py -v
124
+ ```
125
+
126
+ ### Clearer terminal images
127
+
128
+ The old character preview was limited to 20 rows (at most ~40 vertical pixels).
129
+ It now uses available terminal height and width. `--camera main` or `--camera wrist`
130
+ selects a larger single view. Character mode is still a low-resolution preview.
131
+
132
+ For actual image pixels, use `--renderer iterm` (iTerm2 / WezTerm / VS Code with
133
+ `terminal.integrated.enableImages: true`) or `--renderer kitty`. Native mode
134
+ encodes original-resolution pixels as PNG; the terminal fits the display without
135
+ reducing the transmitted image to text-cell resolution. `auto` recognizes iTerm2,
136
+ WezTerm and Kitty environment markers; unknown terminals and multiplexers retain
137
+ the ANSI fallback. VS Code needs an explicit `--renderer iterm` after its setting
138
+ is enabled. Native protocol encoding is tested; visual compatibility still needs
139
+ to be checked in the user's terminal. Use a direct terminal outside tmux/screen
140
+ if image passthrough has not been configured. Redirected output always stays text.
141
+
142
+ Existing CLI processes keep their original interval and renderer: exit with Ctrl+C
143
+ and restart to pick up changes. Evaluation processes need no restart.
144
+
145
+ The user's Claude development terminal (`TERM_PROGRAM=claude-desktop`) displayed
146
+ an empty image area with the iTerm transport. In that environment, even an explicit
147
+ `--renderer iterm` now falls back to ANSI with a visible explanation. This avoids
148
+ blank frames but does not provide native image detail. Use `--camera main` for a
149
+ larger single-camera preview; original-resolution viewing needs an image-capable
150
+ viewer. No Claude terminal setting enabling inline images has been verified.
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_viewer/export.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export saved API-player runs as a portable, offline Agent Viewer.
2
+
3
+ No simulator/model calls are made. Original image bytes are embedded once.
4
+ Supports transcript.jsonl and gpt_transcript.jsonl (API-player event schema).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import base64
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from pathlib import Path
14
+
15
+
16
+ def read_jsonl(path):
17
+ rows = []
18
+ for number, line in enumerate(path.read_text().splitlines(), 1):
19
+ if line.strip():
20
+ try:
21
+ rows.append(json.loads(line))
22
+ except json.JSONDecodeError as exc:
23
+ raise ValueError(f"{path.name}:{number}: malformed JSON; export a completed log") from exc
24
+ return rows
25
+
26
+
27
+ def parse_output(value):
28
+ if isinstance(value, dict):
29
+ return value
30
+ try:
31
+ parsed = json.loads(value)
32
+ return parsed if isinstance(parsed, dict) else {}
33
+ except (ValueError, TypeError):
34
+ return {}
35
+
36
+
37
+ def build_run(folder, assets, sandbox_override=None):
38
+ folder = Path(folder)
39
+ transcript = next((folder / name for name in ('transcript.jsonl', 'gpt_transcript.jsonl')
40
+ if (folder / name).exists()), None)
41
+ if not transcript:
42
+ raise ValueError(f"No supported API-player transcript in {folder}")
43
+ rows = read_jsonl(transcript)
44
+ if not any(row.get('ev') == 'assistant' for row in rows):
45
+ raise ValueError(f"No API-player assistant events in {transcript}")
46
+ session = json.loads((folder / 'session.json').read_text())
47
+ events = read_jsonl(folder / 'events.jsonl') if (folder / 'events.jsonl').exists() else []
48
+ start = next((r for r in rows if r.get('ev') == 'start'), {})
49
+ server = next((r for r in events if r.get('ev') == 'session_start'), {})
50
+ sandbox = Path(sandbox_override or session.get('sandbox', folder))
51
+ warnings, cache = [], {}
52
+
53
+ def images(refs, source, timestamp):
54
+ result = []
55
+ for ref in refs:
56
+ if not isinstance(ref, str):
57
+ raise ValueError('Expected image path strings in API-player transcript')
58
+ if ref not in cache:
59
+ relative = Path(ref)
60
+ roots = [folder, sandbox]
61
+ candidates = []
62
+ # Only export images within the explicitly selected run/sandbox.
63
+ for root in roots:
64
+ candidate = (root / relative).resolve()
65
+ if candidate.is_relative_to(root.resolve()):
66
+ candidates.append(candidate)
67
+ path = next((p for p in candidates if p.is_file()), None)
68
+ key = None
69
+ if path:
70
+ raw = path.read_bytes()
71
+ if raw.startswith(b'\xff\xd8\xff'):
72
+ mime = 'image/jpeg'
73
+ elif raw.startswith(b'\x89PNG\r\n\x1a\n'):
74
+ mime = 'image/png'
75
+ elif raw[:6] in (b'GIF87a', b'GIF89a'):
76
+ mime = 'image/gif'
77
+ elif raw[:4] == b'RIFF' and raw[8:12] == b'WEBP':
78
+ mime = 'image/webp'
79
+ else:
80
+ raise ValueError(f'Unsupported image bytes: {ref}')
81
+ key = hashlib.sha256(raw).hexdigest()[:24]
82
+ assets[key] = f'data:{mime};base64,' + base64.b64encode(raw).decode()
83
+ else:
84
+ warnings.append(f'图片缺失:{ref}')
85
+ name = relative.stem
86
+ camera = 'agentview' if 'agentview' in name else 'wrist' if 'wrist' in name else name
87
+ cache[ref] = {'asset': key, 'path': ref, 'camera': camera}
88
+ result.append({**cache[ref], 'source': source, 'at': timestamp})
89
+ return result
90
+
91
+ outcomes = [{'attempt': e.get('attempt'), 'success': e.get('success'),
92
+ 'feedback': e.get('feedback', ''), 'at': e.get('t')}
93
+ for e in events if e.get('ev') == 'done']
94
+ steps, pending, latest, latest_text = [], [], [], ''
95
+ attempt, origin, active, task_text = 1, rows[0].get('t', 0), None, ''
96
+ for line, row in enumerate(rows, 1):
97
+ kind = row.get('ev')
98
+ if kind == 'user':
99
+ latest_text = row.get('text', '')
100
+ if not task_text:
101
+ match = re.search(r'\{.*\}', latest_text, re.S)
102
+ task_text = parse_output(match.group() if match else '').get('task', latest_text)
103
+ if row.get('images'):
104
+ latest = images(row['images'], line, row.get('t'))
105
+ elif kind in ('api_error', 'abort'):
106
+ pending.append({'kind': kind, 'text': row.get('error', ''), 'at': row.get('t')})
107
+ elif kind == 'assistant':
108
+ calls = row.get('tool_calls', [])
109
+ active = {
110
+ 'index': len(steps), 'turn': row.get('turn'), 'attempt': attempt,
111
+ 'at': row.get('t'), 'elapsed': max(0, row.get('t', origin) - origin),
112
+ 'latency': row.get('latency_s'), 'before': list(latest),
113
+ 'inputText': latest_text, 'text': row.get('text') or '',
114
+ 'decisionSummary': row.get('reasoning_summary') or None,
115
+ 'decisionSummaryStatus': row.get('reasoning_summary_status', 'not_recorded'),
116
+ 'decisionSourceLine': line,
117
+ 'actions': [{'id': c.get('id'), 'name': c.get('name', 'tool'),
118
+ 'arguments': c.get('arguments', {}), 'result': None,
119
+ 'after': []} for c in calls],
120
+ 'notices': pending, 'verdict': None,
121
+ 'requestImages': row.get('request_stats', {}).get('n_images'),
122
+ }
123
+ pending = []
124
+ steps.append(active)
125
+ elif kind == 'tool':
126
+ if active is None:
127
+ warnings.append(f'第 {line} 行工具结果缺少前置调用')
128
+ continue
129
+ if row.get('turn') is not None and row.get('turn') != active['turn']:
130
+ raise ValueError(f'Tool turn mismatch at transcript line {line}')
131
+ unresolved = [a for a in active['actions'] if a['result'] is None]
132
+ call_id = row.get('call_id') or row.get('tool_call_id')
133
+ action = next((a for a in unresolved if call_id and a['id'] == call_id), None)
134
+ if call_id and action is None:
135
+ raise ValueError(f'Unknown tool call id at transcript line {line}')
136
+ if action is None:
137
+ action = next((a for a in unresolved if isinstance(a['arguments'], dict)
138
+ and a['arguments'].get('command') == row.get('command')), None)
139
+ if action is None and len(unresolved) == 1:
140
+ action = unresolved[0]
141
+ if action is None:
142
+ raise ValueError(f'Ambiguous tool result at transcript line {line}')
143
+ output = row.get('output', '')
144
+ action['result'] = output
145
+ action['at'] = row.get('t')
146
+ action['after'] = images(row.get('images', []), line, row.get('t'))
147
+ parsed = parse_output(output)
148
+ action['ok'] = parsed.get('ok')
149
+ latest_text = output if isinstance(output, str) else json.dumps(output, ensure_ascii=False)
150
+ if action['after']:
151
+ latest = list(action['after'])
152
+ command = row.get('command') or (action['arguments'].get('command', '')
153
+ if isinstance(action['arguments'], dict) else '')
154
+ if command.split(' ', 1)[0] == 'done':
155
+ verdict = next((o for o in outcomes if o['attempt'] == attempt), None)
156
+ if verdict:
157
+ active['verdict'] = verdict
158
+ # A failed done may immediately return RESET images for the next attempt.
159
+ message = parsed.get('message', '')
160
+ next_attempt = re.search(r'Attempt\s+(\d+)\s+of', message)
161
+ if next_attempt:
162
+ attempt = int(next_attempt.group(1))
163
+ action['resetToAttempt'] = attempt
164
+ if pending:
165
+ steps[-1]['noticesAfter'] = pending
166
+ for step in steps:
167
+ step['incomplete'] = any(a['result'] is None for a in step['actions'])
168
+ status = 'success' if any(o['success'] is True for o in outcomes) else (
169
+ 'failed' if outcomes and any(r.get('ev') == 'end' and r.get('finished') is True for r in rows) else 'incomplete')
170
+ video = None
171
+ video_path = folder / 'rollout.mp4'
172
+ if video_path.is_file():
173
+ raw = video_path.read_bytes()
174
+ if len(raw) < 12 or raw[4:8] != b'ftyp':
175
+ raise ValueError('rollout.mp4 is not an MP4 container')
176
+ key = 'video-' + hashlib.sha256(raw).hexdigest()[:24]
177
+ assets[key] = 'data:video/mp4;base64,' + base64.b64encode(raw).decode()
178
+ video = {'asset': key, 'name': 'rollout.mp4'}
179
+ return {'id': folder.name, 'video': video, 'task': server.get('task', folder.name),
180
+ 'taskText': task_text, 'seed': server.get('seed'), 'model': start.get('model', '未记录'),
181
+ 'perception': server.get('perception', '未记录'), 'feedback': server.get('feedback', '未记录'),
182
+ 'status': status, 'steps': steps, 'outcomes': outcomes,
183
+ 'warnings': sorted(set(warnings)), 'source': transcript.name,
184
+ 'actionCount': sum(len(s['actions']) for s in steps)}
185
+
186
+
187
+ def render(folders, output, sandbox_override=None):
188
+ assets = {}
189
+ runs = [build_run(folder, assets, sandbox_override) for folder in folders]
190
+ payload = json.dumps({'version': 1, 'runs': runs, 'assets': assets}, ensure_ascii=False)
191
+ # Logs are untrusted text, including strings containing HTML/script terminators.
192
+ payload = payload.replace('&', '\\u0026').replace('<', '\\u003c').replace('>', '\\u003e')
193
+ template = Path(__file__).with_name('viewer.html').read_text()
194
+ output = Path(output)
195
+ output.parent.mkdir(parents=True, exist_ok=True)
196
+ output.write_text(template.replace('/*__PAYLOAD__*/null', payload))
197
+ return runs
198
+
199
+
200
+ def main():
201
+ parser = argparse.ArgumentParser(description=__doc__)
202
+ parser.add_argument('--run', type=Path, action='append', required=True, help='Repeat to include multiple runs')
203
+ parser.add_argument('--out', type=Path, required=True)
204
+ parser.add_argument('--sandbox', type=Path, help='Relocated image directory for a single run')
205
+ args = parser.parse_args()
206
+ if args.sandbox and len(args.run) != 1:
207
+ parser.error('--sandbox requires exactly one --run')
208
+ try:
209
+ runs = render(args.run, args.out, args.sandbox)
210
+ except (ValueError, OSError, KeyError) as exc:
211
+ parser.exit(1, f'Export failed: {exc}\n')
212
+ print(json.dumps({'output': str(args.out.resolve()), 'runs': [
213
+ {'task': r['task'], 'steps': len(r['steps']), 'actions': r['actionCount'],
214
+ 'outcomes': [o['success'] for o in r['outcomes']], 'warnings': r['warnings']} for r in runs
215
+ ]}, ensure_ascii=False, indent=2))
216
+
217
+
218
+ if __name__ == '__main__':
219
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_viewer/live.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Read-only terminal viewer for active LFF-Bench runs (ANSI images or ASCII)."""
3
+ from __future__ import annotations
4
+ import argparse
5
+ import base64
6
+ import io
7
+ import json
8
+ import os
9
+ import re
10
+ import shutil
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+
15
+ # Strip terminal controls from untrusted logged text; only this program emits ANSI.
16
+ def clean(value):
17
+ return re.sub(r'[\x00-\x1f\x7f-\x9f]', ' ', str(value))
18
+
19
+
20
+ def read_json(path):
21
+ try:
22
+ return json.loads(Path(path).read_text())
23
+ except (OSError, ValueError):
24
+ return None
25
+
26
+
27
+ class Tail:
28
+ """Only consume complete JSONL records; tolerate concurrent append and rotation."""
29
+ def __init__(self, path):
30
+ self.path, self.offset, self.pending, self.identity = Path(path), 0, b'', None
31
+ self.errors = 0
32
+ self.generation = 0
33
+
34
+ def read(self):
35
+ try:
36
+ with self.path.open('rb') as stream:
37
+ stat = os.fstat(stream.fileno())
38
+ identity = (stat.st_dev, stat.st_ino)
39
+ if self.identity is not None and (identity != self.identity or stat.st_size < self.offset):
40
+ self.offset, self.pending = 0, b''
41
+ self.generation += 1
42
+ self.identity = identity
43
+ stream.seek(self.offset)
44
+ chunk = stream.read()
45
+ self.offset = stream.tell()
46
+ except OSError:
47
+ return []
48
+ lines = (self.pending + chunk).split(b'\n')
49
+ self.pending = lines.pop()
50
+ out = []
51
+ for line in lines:
52
+ if not line.strip():
53
+ continue
54
+ try:
55
+ row = json.loads(line)
56
+ if isinstance(row, dict):
57
+ out.append(row)
58
+ else:
59
+ self.errors += 1
60
+ except (ValueError, UnicodeDecodeError):
61
+ self.errors += 1
62
+ return out
63
+
64
+
65
+ class Run:
66
+ def __init__(self, path):
67
+ self.path = Path(path)
68
+ self.task = self.path.name
69
+ self.calls = 0
70
+ self.attempt = 1
71
+ self.outcomes = []
72
+ self.command = '等待工具调用'
73
+ self.command_at = None
74
+ self.view_paths = []
75
+ self.view_at = None
76
+ self.view_sequence = 0
77
+ self.embedded_sequence = 0
78
+ self.embedded_paths = []
79
+ self.embedded = []
80
+ self.summary = ''
81
+ self.status = '等待日志'
82
+ self.notice = ''
83
+ self.last_activity = None
84
+ names = ['events.jsonl', 'gateway_transcript.jsonl', 'mcp_transcript.jsonl',
85
+ 'transcript.jsonl', 'gpt_transcript.jsonl', 'codex_events.jsonl']
86
+ self.tails = {n: Tail(self.path / n) for n in names}
87
+ self.image_cache = {}
88
+
89
+ def update(self):
90
+ gateway = 'gateway_transcript.jsonl' if (self.path/'gateway_transcript.jsonl').exists() else 'mcp_transcript.jsonl'
91
+ api = 'transcript.jsonl' if (self.path/'transcript.jsonl').exists() else 'gpt_transcript.jsonl'
92
+ for name in ['events.jsonl', gateway, api, 'codex_events.jsonl']:
93
+ tail = self.tails[name]
94
+ generation = tail.generation
95
+ rows = tail.read()
96
+ if tail.generation != generation:
97
+ # Avoid mixing observations and counts across replaced/truncated runs.
98
+ self.__init__(self.path)
99
+ self.notice = '日志已轮转,重新读取'
100
+ return self.update()
101
+ for row in rows:
102
+ if row.get('t') is not None:
103
+ self.last_activity = max(self.last_activity or 0, row['t'])
104
+ if name == 'events.jsonl':
105
+ if row.get('ev') == 'session_start':
106
+ self.task = row.get('task', self.task)
107
+ self.status = '运行中'
108
+ elif row.get('ev') == 'call':
109
+ self.calls += 1
110
+ self.attempt = row.get('attempt', self.attempt)
111
+ self.command = row.get('cmd', '') + ' ' + json.dumps(row.get('args', {}), ensure_ascii=False)
112
+ self.command_at = row.get('t')
113
+ elif row.get('ev') == 'done':
114
+ self.outcomes.append((row.get('attempt'), row.get('success')))
115
+ elif name == gateway:
116
+ if row.get('ev') != 'tool':
117
+ continue
118
+ if row.get('finished'):
119
+ self.status = '任务已结束'
120
+ if row.get('name') == 'view_images' and not row.get('is_error') and row.get('images', 0) > 0:
121
+ paths = []
122
+ for output in row.get('output', []):
123
+ try:
124
+ obj = json.loads(output)
125
+ paths.extend(obj.get('attached', []))
126
+ except (ValueError, TypeError, AttributeError):
127
+ pass
128
+ # Only mark confirmed attachments as observed, not requested files.
129
+ if paths:
130
+ self.view_paths, self.view_at = paths, row.get('t')
131
+ self.view_sequence += 1
132
+ if row.get('name') == 'robot':
133
+ self.command = row.get('arguments', {}).get('command', self.command)
134
+ self.command_at = row.get('t')
135
+ elif name == api:
136
+ if row.get('ev') in ('user', 'tool') and row.get('images'):
137
+ self.view_paths, self.view_at = row['images'], row.get('t')
138
+ self.view_sequence += 1
139
+ if row.get('ev') == 'assistant':
140
+ self.summary = row.get('reasoning_summary') or row.get('text') or ''
141
+ if row.get('ev') in ('end', 'abort'):
142
+ self.status = '已结束' if row['ev'] == 'end' else '已中断'
143
+ elif name == 'codex_events.jsonl' and row.get('type') == 'item.completed':
144
+ item = row.get('item', {})
145
+ if item.get('type') in ('reasoning', 'agent_message'):
146
+ self.summary = item.get('text', '')
147
+ if item.get('type') == 'mcp_tool_call' and item.get('tool') == 'view_images' and not item.get('error'):
148
+ content = (item.get('result') or {}).get('content', [])
149
+ paths, raw = [], []
150
+ for c in content:
151
+ if c.get('type') == 'text':
152
+ try:
153
+ paths.extend(json.loads(c.get('text', '')).get('attached', []))
154
+ except (ValueError, AttributeError):
155
+ pass
156
+ elif c.get('type') == 'image':
157
+ try:
158
+ raw.append(base64.b64decode(c['data'], validate=True))
159
+ except (ValueError, KeyError):
160
+ pass
161
+ if raw and len(raw) == len(paths):
162
+ self.embedded_paths, self.embedded = paths, raw
163
+ self.embedded_sequence += 1
164
+ if not (self.path/gateway).exists():
165
+ self.view_paths = paths
166
+ self.view_sequence = self.embedded_sequence
167
+ self.notice = f'跳过 {sum(t.errors for t in self.tails.values())} 条损坏日志' if any(t.errors for t in self.tails.values()) else self.notice
168
+
169
+ def frames(self):
170
+ session = read_json(self.path/'session.json') or {}
171
+ roots = [self.path]
172
+ if session.get('sandbox'):
173
+ roots.append(Path(session['sandbox']))
174
+ result = []
175
+ for index, ref in enumerate(self.view_paths):
176
+ if not isinstance(ref, str):
177
+ continue
178
+ if self.embedded_sequence == self.view_sequence and self.embedded_paths == self.view_paths and index < len(self.embedded):
179
+ result.append((ref, self.embedded[index], '工具响应内嵌图片'))
180
+ continue
181
+ for root in roots:
182
+ target = (root/ref).resolve()
183
+ if not target.is_relative_to(root.resolve()) or not target.is_file():
184
+ continue
185
+ stat = target.stat()
186
+ if self.view_at is not None and stat.st_mtime > self.view_at + 0.1:
187
+ result.append((ref, None, '文件在观察后已修改,不能确认原图'))
188
+ break
189
+ key = (str(target), stat.st_mtime_ns, stat.st_size)
190
+ if key not in self.image_cache:
191
+ self.image_cache = {key: target.read_bytes()}
192
+ result.append((ref, self.image_cache[key], '日志引用文件(未校验原始字节)'))
193
+ break
194
+ else:
195
+ result.append((ref, None, '图片文件不可用'))
196
+ return result
197
+
198
+
199
+ def choose_run(batch):
200
+ data = read_json(Path(batch)/'manifest.json')
201
+ if not data:
202
+ return None, '批次清单暂不可读'
203
+ rows = data.get('runs', [])
204
+ counts = {key: sum(r.get('status') == key for r in rows) for key in ['done', 'running', 'pending']}
205
+ active = [r for r in rows if r.get('status') == 'running' and r.get('log')]
206
+ completed = [r for r in rows if r.get('log')]
207
+ row = active[0] if active else completed[-1] if completed else None
208
+ summary = ' / '.join(f'{key} {count}' for key, count in counts.items())
209
+ return row, summary
210
+
211
+
212
+ def image_lines(raw, columns, rows, color):
213
+ from PIL import Image, ImageOps
214
+ image = Image.open(io.BytesIO(raw)).convert('RGB')
215
+ width, height = columns, rows * 2
216
+ image = ImageOps.contain(image, (width, height))
217
+ pixels = image.load()
218
+ lines = []
219
+ ramp = ' .:-=+*#%@'
220
+ for y in range(0, image.height, 2):
221
+ line = ''
222
+ for x in range(image.width):
223
+ upper, lower = pixels[x,y], pixels[x,min(y+1,image.height-1)]
224
+ if color:
225
+ line += '\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm▀' % (*upper, *lower)
226
+ else:
227
+ value = (sum(upper) + sum(lower)) / 6
228
+ line += ramp[min(9, int(value/256*10))]
229
+ lines.append(line + ('\033[0m' if color else ''))
230
+ return lines
231
+
232
+
233
+ # Native image transports keep source pixels rather than quantizing to text cells.
234
+ KITTY_IMAGE_ID = 1987000000 + os.getpid() % 100000
235
+
236
+ def choose_renderer(requested, environ=None, tty=True):
237
+ env = os.environ if environ is None else environ
238
+ if not tty:
239
+ return 'ansi'
240
+ # This embedded terminal was observed to swallow OSC 1337 images, leaving
241
+ # the reserved rectangle blank. Keep a visible preview even for old commands.
242
+ if env.get('TERM_PROGRAM') == 'claude-desktop' and requested == 'iterm':
243
+ return 'ansi'
244
+ if requested != 'auto':
245
+ return requested
246
+ # Multiplexers need terminal-specific passthrough setup; keep auto conservative.
247
+ if env.get('TMUX') or env.get('STY'):
248
+ return 'ansi'
249
+ if env.get('KITTY_WINDOW_ID') or env.get('TERM') == 'xterm-kitty':
250
+ return 'kitty'
251
+ if env.get('TERM_PROGRAM') in ('iTerm.app', 'WezTerm'):
252
+ return 'iterm'
253
+ return 'ansi'
254
+
255
+
256
+ def native_image(raw_images, columns, rows, renderer):
257
+ from PIL import Image
258
+ decoded = [Image.open(io.BytesIO(raw)).convert('RGB') for raw in raw_images]
259
+ # Place full-resolution views side by side without resampling source pixels.
260
+ canvas = Image.new('RGB', (sum(im.width for im in decoded), max(im.height for im in decoded)))
261
+ x = 0
262
+ for im in decoded:
263
+ canvas.paste(im, (x, 0))
264
+ x += im.width
265
+ buf = io.BytesIO()
266
+ canvas.save(buf, format='PNG')
267
+ data = base64.b64encode(buf.getvalue()).decode()
268
+ if renderer == 'iterm':
269
+ sequence = f'\033]1337;File=inline=1;width={columns};height={rows};preserveAspectRatio=1:{data}\a'
270
+ else:
271
+ # Preserve aspect in the usual 1:2 text cells; don't stretch square inputs.
272
+ w = max(1, min(columns, int(rows * 2 * canvas.width / canvas.height)))
273
+ h = max(1, min(rows, round(w * canvas.height / canvas.width / 2)))
274
+ chunks = [data[i:i+4096] for i in range(0, len(data), 4096)]
275
+ sequence = ''
276
+ for n, chunk in enumerate(chunks):
277
+ meta = f'a=T,f=100,t=d,i={KITTY_IMAGE_ID},q=2,C=1,c={w},r={h},' if n == 0 else ''
278
+ sequence += f'\033_G{meta}m={int(n < len(chunks)-1)};{chunk}\033\\'
279
+ # Both protocols are given a reserved rectangle; restore before advancing.
280
+ return '\0337' + sequence + '\0338' + '\n' * (rows - 1)
281
+
282
+
283
+ def clear_native(renderer):
284
+ return f'\033_Ga=d,d=I,i={KITTY_IMAGE_ID},q=2\033\\' if renderer == 'kitty' else ''
285
+
286
+
287
+ def age(timestamp):
288
+ return f'{max(0,int(time.time()-timestamp))} 秒前' if timestamp else '时间未记录'
289
+
290
+
291
+ def render(run, label, width, rows, color, images, renderer="ansi", camera="all"):
292
+ lines = [clean(label)[:width], f'{clean(run.task)} | {clean(run.status)} | 尝试 {run.attempt} | 机器人动作 {run.calls}',
293
+ f'最近动作 ({age(run.command_at)}): {clean(run.command)[:max(15,width-22)]}',
294
+ f'最近返回给 Agent 的图片 ({age(run.view_at)}):按观察事件更新,不是连续视频']
295
+ frames = run.frames()
296
+ if camera != "all":
297
+ keyword = "agentview" if camera == "main" else "wrist"
298
+ frames = [f for f in frames if keyword in f[0]][-1:]
299
+ if not frames:
300
+ lines.append('尚未发现已返回给 Agent 的图片。')
301
+ if images and frames:
302
+ shown = frames[-2:]
303
+ cell = max(12,(width-3*(len(shown)-1))//len(shown))
304
+ columns = []
305
+ for ref, raw, source in shown:
306
+ display = ('字符缩略图' if renderer == 'ansi' else '原图像素') if raw else '不可用'
307
+ lines.append(f' {clean(ref)} · 来源:{source} · 显示:{display}')
308
+ try:
309
+ columns.append(image_lines(raw, cell, rows, color) if raw else ['[原图不可用]'])
310
+ except Exception as exc:
311
+ columns.append([f'[无法解码图片: {type(exc).__name__}]'])
312
+ if renderer in ('iterm', 'kitty') and any(raw for _, raw, _ in shown):
313
+ try:
314
+ lines.append(native_image([raw for _, raw, _ in shown if raw], width, rows, renderer))
315
+ columns = []
316
+ except Exception as exc:
317
+ lines.append(f'原图显示编码失败,使用字符预览: {type(exc).__name__}')
318
+ for y in range(max(map(len, columns), default=0)):
319
+ parts=[]
320
+ for c in columns:
321
+ part=c[y] if y<len(c) else ''
322
+ visible=len(re.sub(r'\033\[[0-9;]*m','',part))
323
+ parts.append(part+' '*max(0,cell-visible))
324
+ lines.append(' '.join(parts))
325
+ elif frames:
326
+ lines.extend('图片: '+clean(f[0]) for f in frames)
327
+ if run.summary:
328
+ lines.append('最近记录的摘要/说明: '+clean(run.summary)[:max(20,width-20)])
329
+ if run.outcomes:
330
+ lines.append('已提交结果: '+' · '.join(f'尝试 {a}: '+('成功' if ok else '失败') for a,ok in run.outcomes))
331
+ if run.notice:
332
+ lines.append(run.notice)
333
+ lines.append('最近日志活动: '+age(run.last_activity))
334
+ return '\n'.join(lines)
335
+
336
+
337
+ def main(argv=None):
338
+ parser=argparse.ArgumentParser(description=__doc__)
339
+ group=parser.add_mutually_exclusive_group(required=True)
340
+ group.add_argument('--batch',type=Path,help='Batch directory; follows the running task then the next one')
341
+ group.add_argument('--run',type=Path,help='One run directory')
342
+ parser.add_argument('--interval',type=float,default=6,help="Refresh interval in seconds (default: 6)")
343
+ parser.add_argument('--once',action='store_true')
344
+ parser.add_argument('--duration',type=float,help='Stop after N seconds (useful for verification)')
345
+ parser.add_argument('--ascii',action='store_true',help='Portable monochrome preview instead of truecolor blocks')
346
+ parser.add_argument('--no-images',action='store_true')
347
+ parser.add_argument('--renderer',choices=['auto','ansi','iterm','kitty'],default='auto',help='Native pixels: iterm (also VS Code with enableImages) or kitty; auto detects known terminals')
348
+ parser.add_argument('--camera',choices=['all','main','wrist'],default='all',help='Select one camera for a larger view')
349
+ parser.add_argument('--width',type=int,default=None)
350
+ parser.add_argument('--image-rows',type=int,default=None)
351
+ a=parser.parse_args(argv)
352
+ if a.interval<0.5:parser.error('--interval must be >= 0.5 seconds')
353
+ if a.width is not None and a.width<24:parser.error('--width must be >= 24')
354
+ if a.image_rows is not None and a.image_rows<2:parser.error('--image-rows must be >= 2')
355
+ if a.duration is not None and a.duration<=0:parser.error('--duration must be positive')
356
+ if not a.no_images:
357
+ try:import PIL
358
+ except ImportError:parser.error('Image preview needs Pillow; use the evaluation Python or --no-images')
359
+ renderer=choose_renderer('ansi' if a.ascii else a.renderer,tty=sys.stdout.isatty())
360
+ if a.no_images:renderer='ansi'
361
+ compatibility_notice = (
362
+ 'Claude 内置终端的 iTerm 图片模式未能显示;已切换为字符预览(非原图清晰度)。'
363
+ if os.environ.get('TERM_PROGRAM') == 'claude-desktop'
364
+ and a.renderer == 'iterm' and renderer == 'ansi'
365
+ and not a.ascii and not a.no_images and sys.stdout.isatty() else ''
366
+ )
367
+ interactive=sys.stdout.isatty() and not a.once
368
+ current=None
369
+ started=time.monotonic()
370
+ previous=None
371
+ try:
372
+ if interactive:print('\033[?1049h\033[?25l',end='',flush=True)
373
+ while True:
374
+ label='Agent Viewer · LIVE · Ctrl+C 退出'
375
+ path=a.run
376
+ if a.batch:
377
+ selected,summary=choose_run(a.batch)
378
+ path=Path(selected['log']) if selected else None
379
+ label=f'{a.batch.name} | {summary}'
380
+ if path is not None:
381
+ if current is None or current.path!=path:current=Run(path)
382
+ current.update()
383
+ if a.batch and selected:current.status=selected.get('status',current.status)
384
+ size=shutil.get_terminal_size((100,36))
385
+ width=a.width or max(24,size.columns-1)
386
+ rows=a.image_rows or max(3,size.lines-12-bool(compatibility_notice))
387
+ label += f' | 刷新 {a.interval:g}s · {renderer}'
388
+ output=render(current,label,width,rows,sys.stdout.isatty() and not a.ascii,not a.no_images,renderer,a.camera)
389
+ if compatibility_notice:
390
+ header, _, body = output.partition('\n')
391
+ output = header + '\n' + compatibility_notice + '\n' + body
392
+ else:output=label+'\n等待批次启动下一任务…'
393
+ if output!=previous:
394
+ if interactive:print(clear_native(renderer)+'\033[H\033[J'+output,end='',flush=True)
395
+ else:print(output,flush=True)
396
+ previous=output
397
+ if a.once or a.duration and time.monotonic()-started>=a.duration:break
398
+ delay=a.interval if a.duration is None else min(a.interval,max(0,a.duration-(time.monotonic()-started)))
399
+ time.sleep(delay)
400
+ except KeyboardInterrupt:
401
+ pass
402
+ finally:
403
+ if interactive:print(clear_native(renderer)+'\033[0m\033[?25h\033[?1049l',end='',flush=True)
404
+
405
+
406
+ if __name__=='__main__':main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/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_auto_001_opus/lff/source_closure/lffbench/tasks/__init__.py ADDED
File without changes
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l2_knock.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-A knock_restore: move the ketchup from the tray into the basket; everything else must stay on the tray.
2
+
3
+ Constructed L2 event: the first time the ketchup is lifted off the tray (grasped and raised 3 cm), one of
4
+ its two neighbours on the tray is "knocked" off the tray and lands upright on the table beside it. Which
5
+ neighbour and to which side of the tray (left / right in the camera image) it falls are hidden per-instance
6
+ variables; only the scene *after* the failure shows which item is missing and where it is. The main task itself still succeeds, so an agent that stops after
7
+ the main task fails; it has to notice the side effect and put the item back (within-episode recovery).
8
+
9
+ Protocols
10
+ within (default, `l2_knock_restore`) one episode; attempt 1 = the main task, every later attempt is one
11
+ corrective round chosen by the policy; the outcome (success + F2 text) is computed after each round.
12
+ cross (`l2_knock_restore_cross`) reset to the same instance between attempts; the knock happens again
13
+ on every attempt, so a learner must anticipate it. Validated strategy: restore the reported item
14
+ right after the main task. The rule also allows prevention (the knock only hits a neighbour that is
15
+ still within 12 cm of the ketchup's start spot), but picking a neighbour up in place is mostly blocked
16
+ by the tray's end wall (Panda hand), so prevention is not a validated strategy (see the task card).
17
+ """
18
+ import numpy as np
19
+
20
+ from .. import envs
21
+ from ..bddl import write_bddl
22
+ from ..skills import Skills
23
+ from ..task_base import LFFTask, register_task
24
+
25
+ TARGET = "ketchup_1"
26
+ NEIGHBOR_POOL = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
27
+ TRAY, BASKET = "wooden_tray_1", "basket_1"
28
+ PARK_XY = {"cream_cheese_1": (0.0, 1.2), "butter_1": (0.2, 1.2), "chocolate_pudding_1": (-0.2, 1.2)}
29
+
30
+ # wooden_tray collision geometry in its body frame (from the LIBERO MJCF; long axis = body x)
31
+ TRAY_IN_X = (-0.128, 0.143)
32
+ TRAY_IN_Y = (-0.081, 0.072)
33
+ TRAY_OUT_X = (-0.142, 0.156)
34
+ TRAY_OUT_Y = (-0.088, 0.080)
35
+ TRAY_CX, TRAY_CY = 0.0075, -0.0045 # centre of the inner floor
36
+ TRAY_FLOOR = 0.0072 # floor top above the tray's lowest point
37
+ BASKET_IN = 0.060 # half size of the basket's inner floor (square, centred on the body origin)
38
+ BASKET_RIM = 0.150 # rim height above the basket's lowest point
39
+ BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
40
+
41
+ NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
42
+ "chocolate_pudding_1": "chocolate pudding"}
43
+ DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
44
+ "chocolate_pudding_1": "brown box"}
45
+ SIDES = ("left", "right") # side of the tray in the agentview image: left = world -y, right = world +y
46
+
47
+
48
+ def _qz(a):
49
+ return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
50
+
51
+
52
+ def _wrap_half(a):
53
+ """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
54
+ return (a + np.pi / 2) % np.pi - np.pi / 2
55
+
56
+
57
+ class KnockSkills(Skills):
58
+ """Skills with a hook called after every control step (used for the failure injection)."""
59
+
60
+ def __init__(self, env, bias=None, recorder=None, hook=None):
61
+ super().__init__(env, bias=bias, recorder=recorder)
62
+ self.hook = hook
63
+
64
+ def _act(self, dpos, drot, grip):
65
+ super()._act(dpos, drot, grip)
66
+ if self.hook is not None:
67
+ self.hook()
68
+
69
+
70
+ @register_task
71
+ class KnockRestore(LFFTask):
72
+ name = "l2_knock_restore"
73
+ level = "L2"
74
+ category = "state_restoration"
75
+ capabilities = ("Perceive", "Plan")
76
+ protocol = "within"
77
+ instruction = "Move the ketchup from the tray into the basket. Everything else must stay on the tray."
78
+ instruction_indirect = ("Move the red bottle from the wooden tray into the wicker basket. "
79
+ "Everything else must stay on the tray.")
80
+ knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
81
+ knock_radius = 0.12 # only a victim still within this distance of the ketchup's start spot is knocked
82
+
83
+ def __init__(self, cam_res=None):
84
+ super().__init__(cam_res)
85
+ # upright orientations (wxyz), fixed here so the task does not depend on LIBERO's placement convention:
86
+ # the ketchup mesh is modelled lying down; tray / basket / boxes are upright in their mesh frame
87
+ # (identity => tray long axis along world x, as the TRAY_* constants assume).
88
+ self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
89
+ self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
90
+ self._inj = None
91
+ self.start = {}
92
+
93
+ # ------------------------------------------------------------ scene
94
+ def make_bddl(self):
95
+ names = [TARGET, *NEIGHBOR_POOL, TRAY, BASKET]
96
+ objs = []
97
+ for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
98
+ x0 = -0.30 + 0.13 * (i % 3)
99
+ y0 = -0.25 + 0.25 * (i // 3)
100
+ objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
101
+ return write_bddl(self.name, self.instruction, objs)
102
+
103
+ def sample_instance(self, seed):
104
+ rng = np.random.default_rng(seed)
105
+ nb = [str(x) for x in rng.choice(NEIGHBOR_POOL, size=2, replace=False)] # [robot side, far side]
106
+ victim = int(rng.integers(2))
107
+ side = str(rng.choice(SIDES))
108
+ return dict(seed=int(seed),
109
+ tray_xy=[float(rng.uniform(-0.07, 0.01)), float(rng.uniform(-0.11, -0.08))],
110
+ tray_yaw=float(rng.uniform(-0.10, 0.10)),
111
+ basket_xy=[float(rng.uniform(-0.08, 0.02)), float(rng.uniform(0.24, 0.26))],
112
+ target_dx=float(rng.uniform(-0.01, 0.01)),
113
+ target_yaw=float(np.pi / 2 + rng.uniform(-0.2, 0.2)),
114
+ neighbors=nb,
115
+ nb_gap=[float(rng.uniform(0.066, 0.078)) for _ in range(2)],
116
+ nb_dy=[float(rng.uniform(-0.012, 0.012)) for _ in range(2)],
117
+ nb_yaw=[float(np.pi / 2 + rng.uniform(-0.15, 0.15)) for _ in range(2)],
118
+ # hidden variables of the injected failure
119
+ victim=nb[victim], side=side,
120
+ land_gap=float(rng.uniform(0.015, 0.035 if side == "right" else 0.04)), # wall -> object
121
+ land_off=float(rng.uniform(-0.025, 0.025)), # along the wall, from the victim's spot
122
+ land_dyaw=float(rng.uniform(-0.35, 0.35)))
123
+
124
+ def _tray_frame(self):
125
+ p = envs.obj_pos(self.env, TRAY)
126
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, TRAY)].reshape(3, 3)
127
+ return p, R
128
+
129
+ def tray_yaw(self):
130
+ _, R = self._tray_frame()
131
+ return float(np.arctan2(R[1, 0], R[0, 0]))
132
+
133
+ def tray_to_world(self, lx, ly):
134
+ p, R = self._tray_frame()
135
+ return p[:2] + R[:2, :2] @ np.array([lx, ly])
136
+
137
+ def world_to_tray(self, xy):
138
+ p, R = self._tray_frame()
139
+ return R[:2, :2].T @ (np.asarray(xy[:2]) - p[:2])
140
+
141
+ def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
142
+ """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z."""
143
+ q = envs._quat_mul(_qz(yaw), self.q_up[name])
144
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
145
+ self.env.sim.forward()
146
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
147
+ qa, _ = envs.free_joint_addr(self.env, name)
148
+ self.env.sim.data.qpos[qa + 2] -= dz
149
+ self.env.sim.forward()
150
+
151
+ def apply_instance(self, inst):
152
+ env = self.env
153
+ envs.scale_mass(env, TRAY, 2.0) # heavy enough not to be dragged around by the gripper
154
+ envs.scale_mass(env, BASKET, 2.0)
155
+ for n in NEIGHBOR_POOL:
156
+ if n not in inst["neighbors"]:
157
+ self.place(n, PARK_XY[n], 0.0, surface_z=0.0) # unused neighbour: on the floor, out of view
158
+ self.place(TRAY, inst["tray_xy"], inst["tray_yaw"])
159
+ self.place(BASKET, inst["basket_xy"], 0.0)
160
+ floor = envs.TABLE_Z + TRAY_FLOOR
161
+ ty = inst["tray_yaw"]
162
+ cx = TRAY_CX + inst["target_dx"]
163
+ self.place(TARGET, self.tray_to_world(cx, TRAY_CY), ty + inst["target_yaw"], floor)
164
+ for i, n in enumerate(inst["neighbors"]): # in a row along the tray: [robot side, ketchup, far side]
165
+ lx = cx + (-1 if i == 0 else 1) * inst["nb_gap"][i]
166
+ self.place(n, self.tray_to_world(lx, TRAY_CY + inst["nb_dy"][i]), ty + inst["nb_yaw"][i], floor)
167
+ env.sim.forward()
168
+
169
+ def reset_instance(self, inst, recorder=None):
170
+ self.env.reset()
171
+ self.apply_instance(inst)
172
+ self.env.sim.forward()
173
+ envs.settle(self.env, 10)
174
+ self.start = {n: self.footprint(n) for n in [TARGET] + inst["neighbors"]}
175
+ self._inj = dict(inst=inst, done=False, knocked=False, step=None)
176
+ self.sk = KnockSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, hook=self._knock_hook)
177
+ return self.sk
178
+
179
+ # ------------------------------------------------------------ measurements
180
+ def footprint(self, name):
181
+ """Measured pose summary of an object: AABB centre, yaw of the long horizontal axis, half sizes, z range.
182
+ Scripted policies use it as a stand-in for perception."""
183
+ m, d = self.env.sim.model, self.env.sim.data
184
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
185
+ best = None
186
+ for g in envs.obj_geom_ids(self.env, name):
187
+ R = d.geom_xmat[g].reshape(3, 3)
188
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
189
+ e = np.abs(R) @ m.geom_aabb[g, 3:]
190
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
191
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
192
+ if best is None or vol > best[0]:
193
+ best = (vol, R, m.geom_aabb[g, 3:])
194
+ _, R, half = best
195
+ horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
196
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
197
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
198
+ half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
199
+
200
+ def _corners_tray(self, name):
201
+ """All collision-box corners of `name` in tray coordinates."""
202
+ m, d = self.env.sim.model, self.env.sim.data
203
+ pts = []
204
+ for g in envs.obj_geom_ids(self.env, name):
205
+ Rg = d.geom_xmat[g].reshape(3, 3)
206
+ c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
207
+ h = m.geom_aabb[g, 3:]
208
+ for sx in (-1, 1):
209
+ for sy in (-1, 1):
210
+ for sz in (-1, 1):
211
+ pts.append(self.world_to_tray(c + Rg @ (h * np.array([sx, sy, sz]))))
212
+ return np.array(pts)
213
+
214
+ # ------------------------------------------------------------ failure injection
215
+ def _knock_hook(self):
216
+ st = self._inj
217
+ if st is None or st["done"] or self.sk is None:
218
+ return
219
+ if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
220
+ return
221
+ if not self.sk.holding(TARGET):
222
+ return
223
+ st["done"] = True
224
+ inst = st["inst"]
225
+ vxy = np.array(self.footprint(inst["victim"])["center"][:2])
226
+ if np.linalg.norm(vxy - np.array(self.start[TARGET]["center"][:2])) > self.knock_radius:
227
+ return # the victim was moved out of the way beforehand: nothing happens
228
+ self.knock(inst)
229
+ st["knocked"] = True
230
+ st["step"] = self.sk.n_steps
231
+
232
+ def knock(self, inst):
233
+ """Teleport the victim off the tray onto the table beside the long wall on `side`: upright, long axis
234
+ roughly perpendicular to the wall (so a gripper closing along the wall can pick it up), nearest point
235
+ `land_gap` from the wall's outer face, `land_off` along the wall from where it stood.
236
+ (The robot-side end of the tray was tried too: the end wall hides a flat box there from agentview.)"""
237
+ v, side = inst["victim"], inst["side"]
238
+ loc = self.world_to_tray(self.footprint(v)["center"])
239
+ axis, sgn = 1, (1 if side == "right" else -1)
240
+ wall = TRAY_OUT_Y[1] if sgn > 0 else TRAY_OUT_Y[0]
241
+ self.place(v, self.tray_to_world(loc[0] + inst["land_off"], wall + sgn * 0.08),
242
+ self.tray_yaw() + np.pi / 2 + inst["land_dyaw"])
243
+ pts = self._corners_tray(v)
244
+ near = pts[:, axis].min() if sgn > 0 else pts[:, axis].max()
245
+ shift = (wall + sgn * inst["land_gap"]) - near
246
+ _, R = self._tray_frame()
247
+ qa, _ = envs.free_joint_addr(self.env, v)
248
+ self.env.sim.data.qpos[qa:qa + 2] += R[:2, axis] * shift
249
+ self.env.sim.forward()
250
+
251
+ # ------------------------------------------------------------ outcome
252
+ def where(self, name):
253
+ """Classify where an object is: 'tray', 'basket', 'gripper', 'table' or 'other'."""
254
+ f = self.footprint(name)
255
+ c = np.array(f["center"])
256
+ lt = self.world_to_tray(c)
257
+ if self.sk is not None and self.sk.holding(name) and f["zmin"] > envs.TABLE_Z + 0.02:
258
+ return "gripper", f
259
+ if (TRAY_IN_X[0] - 0.005 <= lt[0] <= TRAY_IN_X[1] + 0.005 and TRAY_IN_Y[0] - 0.005 <= lt[1] <= TRAY_IN_Y[1] + 0.005
260
+ and f["zmin"] > envs.obj_min_z(self.env, TRAY) + 0.002):
261
+ return "tray", f
262
+ bp = envs.obj_pos(self.env, BASKET)
263
+ if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM:
264
+ return "basket", f
265
+ if f["zmin"] < envs.TABLE_Z + 0.01:
266
+ return "table", f
267
+ return "other", f
268
+
269
+ def rel_to_tray(self, c):
270
+ """Where a point on the table is relative to the tray, in robot-centric words (never image left/right).
271
+ Distances are from the tray's outer edge to the object's centre."""
272
+ lt = self.world_to_tray(c)
273
+ dy = lt[1] - TRAY_OUT_Y[1] if lt[1] > TRAY_OUT_Y[1] else (lt[1] - TRAY_OUT_Y[0] if lt[1] < TRAY_OUT_Y[0] else 0.0)
274
+ dx = lt[0] - TRAY_OUT_X[1] if lt[0] > TRAY_OUT_X[1] else (lt[0] - TRAY_OUT_X[0] if lt[0] < TRAY_OUT_X[0] else 0.0)
275
+ # robot-centric words (tray yaw is within +-0.1 rad, so tray axes ~ world axes): +y = robot's left,
276
+ # +x = forward (away from the robot)
277
+ parts = []
278
+ if dy:
279
+ parts.append(f"{100 * abs(dy):.0f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'} of the tray")
280
+ if dx:
281
+ parts.append(f"{100 * abs(dx):.0f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'} "
282
+ f"of the tray")
283
+ return " and ".join(parts) if parts else "right next to the tray"
284
+
285
+ def _describe(self, inst, loc, names):
286
+ t_loc = loc[TARGET][0]
287
+ tn = names[TARGET]
288
+ msgs = []
289
+ if t_loc != "basket":
290
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
291
+ "tray": f"The {tn} is still on the tray, not in the basket.",
292
+ "table": f"The {tn} is on the table ({self.rel_to_tray(loc[TARGET][1]['center'])}), "
293
+ "not in the basket."}.get(t_loc, f"The {tn} is not in the basket."))
294
+ for n in inst["neighbors"]:
295
+ l, f = loc[n]
296
+ if l == "tray":
297
+ continue
298
+ msgs.append({"table": f"The {names[n]} is no longer on the tray: it is on the table "
299
+ f"{self.rel_to_tray(f['center'])}.",
300
+ "basket": f"The {names[n]} is no longer on the tray: it is in the basket.",
301
+ "gripper": f"The {names[n]} is no longer on the tray: it is still in the gripper."}
302
+ .get(l, f"The {names[n]} is no longer on the tray."))
303
+ if not msgs:
304
+ msgs.append(f"The {tn} is in the basket and everything else is on the tray.")
305
+ return " ".join(msgs)
306
+
307
+ def outcome(self, inst):
308
+ envs.settle(self.env, 30)
309
+ loc = {n: self.where(n) for n in [TARGET] + inst["neighbors"]}
310
+ off = [n for n in inst["neighbors"] if loc[n][0] != "tray"]
311
+ success = bool(loc[TARGET][0] == "basket" and not off)
312
+ return dict(success=success,
313
+ target_loc=loc[TARGET][0],
314
+ locations={n: l for n, (l, _) in loc.items()},
315
+ off_tray=off,
316
+ footprints={n: f for n, (_, f) in loc.items()},
317
+ knocked=bool(self._inj and self._inj["knocked"]),
318
+ detail=self._describe(inst, loc, NAMES),
319
+ detail_indirect=self._describe(inst, loc, DESCR))
320
+
321
+ def feedback(self, inst, out, level="F2", indirect=False):
322
+ """F0: nothing, F1: success flag, F2: which item is where. `indirect` uses descriptive names."""
323
+ if indirect and level == "F2":
324
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
325
+ return super().feedback(inst, out, level)
326
+
327
+ # ------------------------------------------------------------ scripted motions
328
+ def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.012, fp=None,
329
+ travel_z=1.15):
330
+ """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
331
+ object bottom `clearance` above `support_z` at dest_xy. Moves between places at `travel_z` (above the
332
+ basket rim) so the arm does not sweep through the scene."""
333
+ sk = self.sk
334
+ f = fp or self.footprint(name)
335
+ c = np.array(f["center"])
336
+ h = f["zmax"] - f["zmin"]
337
+ gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
338
+ if name == TARGET:
339
+ zg = f["zmax"] - 0.035
340
+ else:
341
+ zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # fingertips reach ~1.3 cm below the grip site
342
+ sk.set_gripper(False, steps=6)
343
+ p = sk.eef_pos()
344
+ if p[2] < travel_z - 0.02:
345
+ sk.move_to([p[0], p[1], travel_z])
346
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
347
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
348
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
349
+ sk.set_gripper(True, steps=12)
350
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
351
+ gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
352
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
353
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.004, speed=0.25,
354
+ max_steps=120)
355
+ sk.set_gripper(False, steps=10)
356
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
357
+
358
+ def main_task(self, fp=None):
359
+ """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
360
+ b = envs.obj_pos(self.env, BASKET)
361
+ floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
362
+ self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
363
+
364
+ def restore_spot(self, name, inst):
365
+ """A free spot on the tray for `name`: the ketchup's start spot or `name`'s own start spot, whichever
366
+ is further from everything else currently on the tray."""
367
+ others = [n for n in [TARGET] + inst["neighbors"] if n != name and self.where(n)[0] == "tray"]
368
+ best, best_d = None, -1.0
369
+ for cand in (TARGET, name):
370
+ xy = np.array(self.start[cand]["center"][:2])
371
+ dmin = min([np.linalg.norm(xy - np.array(self.footprint(o)["center"][:2])) for o in others] + [1.0])
372
+ if dmin > best_d + 0.01:
373
+ best, best_d = xy, dmin
374
+ return best
375
+
376
+ def restore(self, name, inst):
377
+ """Put `name` back onto the tray (long axis across the tray, fingers closing along the tray)."""
378
+ xy = self.restore_spot(name, inst)
379
+ self.pick_place(name, xy, envs.TABLE_Z + TRAY_FLOOR, dest_yaw=self.tray_yaw() + np.pi / 2, carry_z=1.08,
380
+ clearance=0.013)
381
+
382
+ def do(self, actions, inst):
383
+ for act in actions:
384
+ if act[0] == "ketchup_to_basket":
385
+ self.main_task(fp=act[1] if len(act) > 1 else None)
386
+ elif act[0] == "restore":
387
+ self.restore(act[1], inst)
388
+ else:
389
+ raise ValueError(act)
390
+
391
+ # ------------------------------------------------------------ scripted reference policies
392
+ def _plan(self, kind, inst, a, history, rng):
393
+ """Actions of one attempt. JSON-friendly lists: ["ketchup_to_basket"] / ["restore", name]."""
394
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind")):
395
+ return [["ketchup_to_basket"]]
396
+ if kind == "oracle": # knows the victim: restores it right after the main task, without feedback
397
+ return [["ketchup_to_basket"], ["restore", inst["victim"]]]
398
+ if kind == "adaptive": # F2 says what is wrong; perception (measured pose) says where it is
399
+ last = history[-1]["outcome"]
400
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
401
+ return acts + [["restore", n] for n in last["off_tray"]]
402
+ if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
403
+ fp = self.footprint(TARGET)
404
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
405
+ return [["ketchup_to_basket", fp]]
406
+ raise ValueError(kind)
407
+
408
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
409
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.
410
+ After every attempt the outcome (success + F2 detail) is measured; stops at success
411
+ (oracle / naive stop after attempt 1)."""
412
+ k = k or self.max_attempts
413
+ rng = np.random.default_rng(seed)
414
+ history = []
415
+ self.reset_instance(inst)
416
+ for a in range(k):
417
+ actions = self._plan(kind, inst, a, history, rng)
418
+ self.do(actions, inst)
419
+ out = self.outcome(inst)
420
+ params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
421
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
422
+ if on_attempt:
423
+ on_attempt(a, params, out)
424
+ if out["success"] or kind in ("oracle", "naive"):
425
+ break
426
+ return history
427
+
428
+
429
+ @register_task
430
+ class KnockRestoreCross(KnockRestore):
431
+ """Cross-attempt variant: reset to the same instance before every attempt; the knock happens again each
432
+ time. Learned behaviour: anticipate it (restore the reported item right after the main task)."""
433
+ name = "l2_knock_restore_cross"
434
+ protocol = "cross"
435
+
436
+ def _plan(self, kind, inst, a, history, rng):
437
+ if kind == "adaptive" and a > 0: # remembers which item(s) fell last time; finds them by looking
438
+ fallen = sorted({n for h in history for n in h["outcome"]["off_tray"]})
439
+ return [["ketchup_to_basket"]] + [["restore", n] for n in fallen]
440
+ return super()._plan(kind, inst, a, history, rng)
441
+
442
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
443
+ k = k or self.max_attempts
444
+ rng = np.random.default_rng(seed)
445
+ history = []
446
+ for a in range(k):
447
+ self.reset_instance(inst)
448
+ actions = self._plan(kind, inst, a, history, rng)
449
+ self.do(actions, inst)
450
+ out = self.outcome(inst)
451
+ params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
452
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
453
+ if on_attempt:
454
+ on_attempt(a, params, out)
455
+ if out["success"] or kind in ("oracle", "naive"):
456
+ break
457
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l6_sequence.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L6-C sequence_resume: weigh four items one by one in a given order; an emergency stop resets part of the work.
2
+
3
+ Scene: four grocery items (cream cheese, butter, chocolate pudding, popcorn -- small flat boxes), each on its
4
+ own round pad (four identical dark pads, flat markers), and a scale (grey square platform, static fixture).
5
+ Pad / scale positions and the order are random per instance.
6
+
7
+ Instruction: weigh the items one at a time in the given order. Weighing = put the item on the scale and let go;
8
+ the scale records a reading after the item has rested on it for 0.5 s and beeps. Then the item goes back on its
9
+ own pad before the next item is picked up. Every item must be weighed exactly once; the scale log cannot be
10
+ edited, so a second reading of an item or a reading out of turn is a terminal failure.
11
+
12
+ Interruption ("emergency stop", once per episode, inside attempt 1): while the robot carries an item, the gripper
13
+ opens, a safety routine puts that item back on its own pad and the arm returns to its home pose. Hidden: how
14
+ many items had been weighed when it happened, w in {1..4} (uniform), and the phase: the carried item was on its
15
+ way to the scale (not yet weighed, phase A) or on its way back (already weighed, phase B); w = 4 is always
16
+ phase B. After the stop every item sits on its pad and the arm is at home: the picture looks like the start of
17
+ the task. Which item comes next (order[w], or "nothing, call done" for w = 4) is only in the agent's own history
18
+ (what it carried, whether the scale had beeped).
19
+
20
+ Protocol: within (like l6_swap_interrupt). Events reported immediately (`drain_events`): the scale's beep after
21
+ every recorded reading, an error beep for a reading out of turn, and the emergency stop. F2 after `done` gives the
22
+ verdict, whether the log is complete, and which items are not on their pads (distance only), never how many
23
+ items have been weighed.
24
+
25
+ Scripted references (perception = simulator state):
26
+ oracle privileged scale log: always weighs order[len(log)] next.
27
+ adaptive keeps its own record of readings (an item counts as weighed when the scale beeped while it lay on
28
+ it); after the stop it resumes from order[len(record)] (redoes the interrupted item in phase A, goes on
29
+ with the next one in phase B, calls done when all four are recorded).
30
+ naive memoryless continuation (1 attempt): the picture after the stop shows no progress; it guesses how far
31
+ it got (uniform over 0..4 items weighed) and continues from there.
32
+ blind memoryless restart (k attempts): starts the sequence over from the first item -> a second reading of
33
+ an already weighed item (repeated step).
34
+ Extra control (not in the acceptance table): `skip` counts items it *started* to weigh (pick-ups) instead of
35
+ readings: correct after a phase-B stop, skips the interrupted item after a phase-A stop.
36
+ """
37
+ import numpy as np
38
+
39
+ from .. import envs
40
+ from ..bddl import write_bddl
41
+ from ..objects import _fmt, _wrap, register_generated
42
+ from ..skills import ROT_SCALE, _rot_err
43
+ from ..task_base import LFFTask, register_task
44
+ from .l6_swap import _pad_xml as _swap_pad_xml
45
+
46
+ ITEMS = ["cream_cheese_1", "butter_1", "chocolate_pudding_1", "popcorn_1"]
47
+ CATS = {"cream_cheese_1": "cream_cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate_pudding",
48
+ "popcorn_1": "popcorn"}
49
+ NAME = {"cream_cheese_1": "cream cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding",
50
+ "popcorn_1": "popcorn"}
51
+ DESCR = {"cream_cheese_1": "the pale blue box with the oval logo", "butter_1": "the red box with white lettering",
52
+ "chocolate_pudding_1": "the dark brown box", "popcorn_1": "the blue-and-yellow box"}
53
+ N_ITEMS = len(ITEMS)
54
+ PADS = [f"pad_{i + 1}" for i in range(N_ITEMS)]
55
+ PAD_R = 0.055
56
+ PAD_HALF_T = 0.0008
57
+
58
+ SCALE_HALF = 0.06 # platform half size (12 x 12 cm)
59
+ SCALE_BASE_HALF = 0.067
60
+ SCALE_TOP = 0.020 # platform top above the table
61
+ SCALE_BASE_H = 0.012
62
+ SCALE_RGBA = (0.78, 0.79, 0.80, 1.0)
63
+ SCALE_BASE_RGBA = (0.20, 0.20, 0.22, 1.0)
64
+
65
+ BASE_X = -0.66
66
+ REGION = (-0.27, 0.05, -0.27, 0.27)
67
+ REACH = 0.70
68
+ PAD_MIN = 0.16
69
+ SCALE_MIN = 0.175
70
+ SUCC_R = 0.04 # item centre within 4 cm of its pad centre
71
+ GRASP_DZ = 0.012 # gripper-site height above the support surface for a top-down grasp of the flat boxes
72
+ Z_CARRY = envs.TABLE_Z + 0.15
73
+ DWELL = 10 # control steps (0.5 s) at rest on the scale before a reading is recorded
74
+ LIFTED = 0.04
75
+
76
+
77
+ def scale_xml(model_name):
78
+ parts = [((0, 0, SCALE_BASE_H / 2), (SCALE_BASE_HALF, SCALE_BASE_HALF, SCALE_BASE_H / 2), SCALE_BASE_RGBA),
79
+ ((0, 0, (SCALE_BASE_H + SCALE_TOP) / 2), (SCALE_HALF, SCALE_HALF, (SCALE_TOP - SCALE_BASE_H) / 2),
80
+ SCALE_RGBA)]
81
+ g = []
82
+ for k, (pos, half, rgba) in enumerate(parts):
83
+ g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(half)}" '
84
+ f'rgba="{_fmt(rgba)}" density="1000" friction="1.0 0.005 0.0001" group="0" />')
85
+ g.append(f' <geom type="box" pos="{_fmt(pos)}" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
86
+ f'conaffinity="0" contype="0" group="1" />')
87
+ return _wrap(model_name, "\n".join(g), SCALE_TOP / 2, float(np.hypot(SCALE_BASE_HALF, SCALE_BASE_HALF)))
88
+
89
+
90
+ def _yaw_of(env, obj):
91
+ R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3)
92
+ yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x
93
+ return (yaw + np.pi / 2) % np.pi - np.pi / 2
94
+
95
+
96
+ @register_task
97
+ class SequenceResume(LFFTask):
98
+ name = "l6_sequence_resume"
99
+ level = "L6"
100
+ category = "procedural_memory"
101
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
102
+ protocol = "within"
103
+ agent_max_steps = 100 # robot commands per attempt for agents (a VLM needs ~60-75)
104
+ max_attempts = 5
105
+ _TEMPLATE = ("Weigh the four grocery items one at a time, in this order: {order}. To weigh an item, put it on "
106
+ "the grey scale and let go of it; the scale beeps when it has recorded the reading. Then put the "
107
+ "item back on its own round pad before you pick up the next item. Weigh every item exactly once: "
108
+ "the scale logs every reading, and the log cannot be edited.")
109
+ instruction = _TEMPLATE.format(order="(given per instance)")
110
+ instruction_indirect = instruction
111
+ inject = True
112
+ agent_object_names = [NAME[i] for i in ITEMS] + ["scale", "round pads"]
113
+
114
+ def agent_instruction(self, inst, variant="direct"):
115
+ names = DESCR if variant == "indirect" else NAME
116
+ order = [names[o] for o in inst["order"]]
117
+ return self._TEMPLATE.format(order=", ".join(order[:-1]) + ", then " + order[-1])
118
+
119
+ def __init__(self, cam_res=None):
120
+ super().__init__(cam_res)
121
+ self._mon = False
122
+ self._latch = None
123
+ orig_step = self.env.step
124
+
125
+ def step(action): # per-control-step monitor (also for attempts driven by the agent harness)
126
+ if self._latch is not None:
127
+ action = self._homing_action()
128
+ ret = orig_step(action)
129
+ if self._mon:
130
+ self._monitor()
131
+ return ret
132
+
133
+ self.env.step = step
134
+
135
+ # ------------------------------------------------------------ scene
136
+ def make_bddl(self):
137
+ pads = [register_generated(f"LffSeqPad{L}", _swap_pad_xml(f"lff_seq_pad_{L.lower()}")) for L in "ABCD"]
138
+ scale = register_generated("LffSeqScale", scale_xml("lff_seq_scale"), free=False)
139
+ objs = [(o, CATS[o], f"r{i}", (-0.26 + 0.15 * i - 0.01, -0.31, -0.26 + 0.15 * i + 0.01, -0.29))
140
+ for i, o in enumerate(ITEMS)]
141
+ objs += [(PADS[i], pads[i], f"p{i}", (-0.26 + 0.15 * i - 0.01, 0.29, -0.26 + 0.15 * i + 0.01, 0.31))
142
+ for i in range(N_ITEMS)]
143
+ fx = [("scale_1", scale, "scale_region", (0.19, -0.01, 0.21, 0.01))]
144
+ return write_bddl(self.name, "Weigh the four items one at a time in the given order", objs, fx) # no ; in BDDL
145
+
146
+ def sample_instance(self, seed):
147
+ rng = np.random.default_rng(seed)
148
+ for _ in range(5000):
149
+ pts = []
150
+ while len(pts) < N_ITEMS + 1:
151
+ p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])])
152
+ if np.hypot(p[0] - BASE_X, p[1]) > REACH:
153
+ continue
154
+ pts.append(p)
155
+ scale, pads = pts[0], np.array(pts[1:])
156
+ dp = [np.linalg.norm(pads[i] - pads[j]) for i in range(N_ITEMS) for j in range(i)]
157
+ if min(dp) >= PAD_MIN and min(np.linalg.norm(pads - scale, axis=1)) >= SCALE_MIN:
158
+ break
159
+ else:
160
+ raise RuntimeError("could not sample a layout")
161
+ order = [ITEMS[i] for i in rng.permutation(N_ITEMS)]
162
+ w = int(rng.integers(1, N_ITEMS + 1)) # items weighed when the stop happens
163
+ phase = "B" if w == N_ITEMS else str(rng.choice(["A", "B"]))
164
+ inst = dict(seed=int(seed), order=order, pads=pads.round(4).tolist(), scale_xy=scale.round(4).tolist(),
165
+ item_off=[[float(v) for v in rng.uniform(-0.008, 0.008, 2)] for _ in range(N_ITEMS)],
166
+ item_yaw=[float(v) for v in rng.uniform(-0.3, 0.3, N_ITEMS)],
167
+ stop_w=w, stop_phase=phase, trigger_dist=float(rng.uniform(0.05, 0.09)),
168
+ stop_off=[float(v) for v in rng.uniform(-0.008, 0.008, 2)],
169
+ stop_yaw=float(rng.uniform(-0.3, 0.3)))
170
+ inst["stop_item"] = order[w] if phase == "A" else order[w - 1]
171
+ self.instruction = self.agent_instruction(inst, "direct") # make_video prints task.instruction
172
+ self.instruction_indirect = self.agent_instruction(inst, "indirect")
173
+ return inst
174
+
175
+ def apply_instance(self, inst):
176
+ m = self.env.sim.model
177
+ for i, p in enumerate(inst["pads"]):
178
+ envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001])
179
+ bid = m.body_name2id(self.env.fixtures_dict["scale_1"].root_body)
180
+ m.body_pos[bid] = [inst["scale_xy"][0], inst["scale_xy"][1], envs.TABLE_Z]
181
+ m.body_quat[bid] = [1, 0, 0, 0]
182
+ for i, o in enumerate(ITEMS):
183
+ p = np.asarray(inst["pads"][i]) + inst["item_off"][i]
184
+ envs.place_upright(self.env, o, p, inst["item_yaw"][i])
185
+ self.env.sim.forward()
186
+ self._inst = inst
187
+ self.pad_of = {o: i for i, o in enumerate(ITEMS)} # item i starts on pad i (pad positions are random)
188
+ self.log = [] # scale readings (item names)
189
+ self.error = None
190
+ self.stop = None
191
+ self.events = []
192
+ self._event_cursor = 0
193
+ self._outcome_cursor = 0
194
+ self._dwell = {o: 0 for o in ITEMS}
195
+ self._visit = {o: False for o in ITEMS}
196
+ self._prev = {}
197
+ self._latch = None
198
+ self._mon = False
199
+
200
+ def reset_instance(self, inst, recorder=None):
201
+ self._mon = False
202
+ self._latch = None
203
+ sk = super().reset_instance(inst, recorder=recorder)
204
+ self._home = sk.eef_pos()
205
+ self.rest_dz = {o: float(envs.obj_pos(self.env, o)[2] - envs.TABLE_Z) for o in ITEMS}
206
+ self._prev = {o: envs.obj_pos(self.env, o) for o in ITEMS}
207
+ self._mon = True
208
+ return sk
209
+
210
+ def go_home(self):
211
+ p = self.sk.eef_pos()
212
+ self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
213
+ self.sk.move_to(self._home)
214
+
215
+ # ------------------------------------------------------------ helpers
216
+ def scale_xy(self):
217
+ return np.asarray(self._inst["scale_xy"], float)
218
+
219
+ def pad_xy(self, o):
220
+ return np.asarray(self._inst["pads"][self.pad_of[o]], float)
221
+
222
+ def on_scale(self, o, p=None):
223
+ p = envs.obj_pos(self.env, o) if p is None else p
224
+ d = np.abs(p[:2] - self.scale_xy())
225
+ return bool(d.max() <= SCALE_HALF and abs(p[2] - (envs.TABLE_Z + SCALE_TOP + self.rest_dz[o])) < 0.008)
226
+
227
+ def on_own_pad(self, o):
228
+ p = envs.obj_pos(self.env, o)
229
+ return bool(np.linalg.norm(p[:2] - self.pad_xy(o)) <= SUCC_R
230
+ and abs(p[2] - (envs.TABLE_Z + self.rest_dz[o])) < 0.01 and not self.sk.holding(o))
231
+
232
+ # ------------------------------------------------------------ monitor: scale readings + emergency stop
233
+ def _monitor(self):
234
+ env = self.env
235
+ if self._latch is not None:
236
+ if len(self.sk.log) > self._latch and np.linalg.norm(self.sk.eef_pos() - self._home) < 0.01:
237
+ self._latch = None
238
+ for o in ITEMS:
239
+ p = envs.obj_pos(env, o)
240
+ still = np.linalg.norm(p - self._prev[o]) < 0.0008
241
+ self._prev[o] = p
242
+ if self.on_scale(o, p):
243
+ if still and not self.sk.holding(o):
244
+ self._dwell[o] += 1
245
+ if self._dwell[o] >= DWELL and not self._visit[o]:
246
+ self._visit[o] = True
247
+ self._record(o)
248
+ else:
249
+ self._dwell[o] = 0
250
+ else:
251
+ self._dwell[o] = 0
252
+ if np.abs(p[:2] - self.scale_xy()).max() > SCALE_HALF or \
253
+ p[2] > envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + 0.02:
254
+ self._visit[o] = False
255
+ if self.inject and self.stop is None:
256
+ self._maybe_stop()
257
+
258
+ def _record(self, o):
259
+ self.log.append(o)
260
+ k = len(self.log)
261
+ ok = self.log == self._inst["order"][:k]
262
+ if ok:
263
+ self.events.append(dict(step=int(self.sk.n_steps), kind="beep", obj=o,
264
+ text="The scale beeped: reading recorded."))
265
+ else:
266
+ if self.error is None:
267
+ self.error = dict(item=o, position=k, step=int(self.sk.n_steps),
268
+ kind="repeat" if self.log.count(o) > 1 else "out_of_order")
269
+ self.events.append(dict(step=int(self.sk.n_steps), kind="error", obj=o,
270
+ text="The scale beeped three times: error, this reading does not follow the "
271
+ "requested order. The log cannot be edited."))
272
+
273
+ def _maybe_stop(self):
274
+ inst = self._inst
275
+ o, w = inst["stop_item"], inst["stop_w"]
276
+ if self.log != inst["order"][:w]:
277
+ return
278
+ p = envs.obj_pos(self.env, o)
279
+ if inst["stop_phase"] == "A":
280
+ if p[2] < envs.TABLE_Z + self.rest_dz[o] + LIFTED:
281
+ return
282
+ if np.linalg.norm(p[:2] - self.pad_xy(o)) < inst["trigger_dist"]:
283
+ return
284
+ else:
285
+ if p[2] < envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + LIFTED:
286
+ return
287
+ if np.linalg.norm(p[:2] - self.scale_xy()) < inst["trigger_dist"]:
288
+ return
289
+ if not self.sk.holding(o):
290
+ return
291
+ self._do_stop(o)
292
+
293
+ def _do_stop(self, o):
294
+ inst = self._inst
295
+ xy = self.pad_xy(o) + np.asarray(inst["stop_off"])
296
+ envs.place_upright(self.env, o, xy, inst["stop_yaw"])
297
+ self.sk.grip = -1.0
298
+ self.sk.yaw = 0.0
299
+ self._latch = len(self.sk.log) # drive the arm home until the current primitive has returned
300
+ self._prev[o] = envs.obj_pos(self.env, o)
301
+ self.env.sim.forward()
302
+ text = ("Emergency stop! The gripper opened, the safety routine put the item the robot was holding back on "
303
+ "its pad and moved the arm to its home pose. You may continue the task.")
304
+ self.stop = dict(item=o, phase=inst["stop_phase"], weighed=len(self.log), step=int(self.sk.n_steps))
305
+ self.events.append(dict(step=int(self.sk.n_steps), kind="stop", obj=o, text=text))
306
+
307
+ def _homing_action(self):
308
+ sk = self.sk
309
+ a = np.zeros(self.env.action_dim)
310
+ a[:3] = np.clip((self._home - sk.eef_pos()) / sk.pos_scale, -1, 1)
311
+ a[3:6] = np.clip(_rot_err(sk.R0, sk.eef_mat()) / ROT_SCALE, -1, 1)
312
+ a[6] = -1.0
313
+ return a
314
+
315
+ def drain_events(self):
316
+ ev = self.events[self._event_cursor:]
317
+ self._event_cursor = len(self.events)
318
+ return [e["text"] for e in ev]
319
+
320
+ # ------------------------------------------------------------ outcome
321
+ def outcome(self, inst):
322
+ envs.settle(self.env, 20)
323
+ order = inst["order"]
324
+ complete = self.log == order
325
+ terminal = self.error is not None
326
+ off = [o for o in ITEMS if not self.on_own_pad(o)]
327
+ success = bool(complete and not off and not terminal)
328
+ if success:
329
+ head = "All four items were weighed once, in the requested order, and are back on their pads."
330
+ elif terminal:
331
+ head = ("The scale log does not follow the requested order (an item was weighed a second time or out "
332
+ "of turn). The log cannot be edited, so the task can no longer be completed.")
333
+ elif complete:
334
+ head = "Every item has been weighed, but not every item is back on its own pad."
335
+ else:
336
+ head = "Not every item has been weighed yet."
337
+ parts = []
338
+ if not success and not terminal:
339
+ for o in off:
340
+ p = envs.obj_pos(self.env, o)
341
+ if self.sk.holding(o):
342
+ parts.append(f"the {NAME[o]} is still in the gripper")
343
+ elif self.on_scale(o, p):
344
+ parts.append(f"the {NAME[o]} is on the scale")
345
+ else:
346
+ d = np.linalg.norm(p[:2] - self.pad_xy(o))
347
+ parts.append(f"the {NAME[o]} is {100 * d:.0f} cm from the centre of its pad")
348
+ detail = head + (" Also: " + "; ".join(parts) + "." if parts else "")
349
+ new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "stop"]
350
+ self._outcome_cursor = len(self.events)
351
+ if new:
352
+ detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail
353
+ return dict(success=success, terminal=terminal, log=[NAME[o] for o in self.log], n_weighed=len(self.log),
354
+ complete=complete, error=self.error, stop=self.stop,
355
+ off_pad=[NAME[o] for o in off], detail=detail)
356
+
357
+ # ------------------------------------------------------------ motion (scripted policies)
358
+ def _support_z(self, o):
359
+ p = envs.obj_pos(self.env, o)
360
+ return envs.TABLE_Z + (SCALE_TOP if self.on_scale(o, p) or
361
+ (np.abs(p[:2] - self.scale_xy()).max() < SCALE_HALF) else 0.0)
362
+
363
+ def _n_stops(self):
364
+ return sum(e["kind"] == "stop" for e in self.events)
365
+
366
+ def _pick(self, o):
367
+ sk = self.sk
368
+ for _ in range(2):
369
+ p = envs.obj_pos(self.env, o)
370
+ sk.grasp_at(p[:2], self._support_z(o) + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=0.12)
371
+ if sk.holding(o):
372
+ return True
373
+ sk.set_gripper(False, steps=8)
374
+ sk.move_to([p[0], p[1], self._support_z(o) + GRASP_DZ + 0.12])
375
+ return False
376
+
377
+ def _carry_to(self, o, xy, z_support):
378
+ """Carry the held item to xy and put it down. Returns False if an emergency stop happened."""
379
+ sk = self.sk
380
+ n0 = self._n_stops()
381
+ sk.move_to([xy[0], xy[1], Z_CARRY])
382
+ if self._n_stops() > n0:
383
+ return False
384
+ sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.004], tol=0.004)
385
+ sk.set_gripper(False, steps=12)
386
+ sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.10])
387
+ return self._n_stops() == n0
388
+
389
+ def _weigh(self, o):
390
+ """Weigh one item (pad -> scale -> pad). Returns (status, beeped): status 'ok' / 'stop_A' / 'stop_B' /
391
+ 'no_grasp'; beeped = the scale beeped while the item lay on it (what the agent hears)."""
392
+ n_beep = sum(e["kind"] in ("beep", "error") for e in self.events)
393
+ if not self._pick(o):
394
+ return "no_grasp", False
395
+ if not self._carry_to(o, self.scale_xy(), envs.TABLE_Z + SCALE_TOP):
396
+ return "stop_A", False
397
+ self.sk.hold(6)
398
+ beeped = sum(e["kind"] in ("beep", "error") for e in self.events) > n_beep
399
+ if not self._pick(o):
400
+ return "no_grasp", beeped
401
+ if not self._carry_to(o, self.pad_xy(o), envs.TABLE_Z):
402
+ return "stop_B", beeped
403
+ return "ok", beeped
404
+
405
+ def _fix_pads(self, log):
406
+ for o in ITEMS:
407
+ if not self.on_own_pad(o) and not self.on_scale(o):
408
+ if self._pick(o):
409
+ self._carry_to(o, self.pad_xy(o), envs.TABLE_Z)
410
+ log.append((NAME[o], "back to pad"))
411
+
412
+ def _run_from(self, k, record, log, stop_on_stop=False):
413
+ """Weigh order[k:] in turn, keeping `record` (the policy's own list of readings it heard)."""
414
+ order = self._inst["order"]
415
+ i = k
416
+ guard = 0
417
+ while i < len(order) and guard < 10 and self.error is None:
418
+ guard += 1
419
+ o = order[i]
420
+ st, beeped = self._weigh(o)
421
+ log.append((NAME[o], st, beeped))
422
+ if beeped:
423
+ record.append(o)
424
+ if st == "no_grasp":
425
+ continue
426
+ if st.startswith("stop"):
427
+ if stop_on_stop:
428
+ return "stopped"
429
+ i = len(record) # resume from the own record
430
+ continue
431
+ i += 1
432
+ return "ok"
433
+
434
+ # ------------------------------------------------------------ scripted references (within protocol)
435
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
436
+ k = k or self.max_attempts
437
+ rng = np.random.default_rng(seed + 104729)
438
+ self.reset_instance(inst)
439
+ order = inst["order"]
440
+ history = []
441
+ record = [] # adaptive's Save: readings it heard
442
+ for a in range(k):
443
+ log = []
444
+ plan = dict(kind=kind, steps=log)
445
+ if a == 0:
446
+ if kind == "oracle":
447
+ while len(self.log) < len(order) and self.error is None and len(log) < 12:
448
+ o = order[len(self.log)] # privileged scale log
449
+ st, _ = self._weigh(o)
450
+ log.append((NAME[o], st))
451
+ plan["recovery"] = "oracle: privileged scale log"
452
+ elif kind == "adaptive":
453
+ self._run_from(0, record, log)
454
+ plan["recovery"] = "own record of readings: resume from order[len(record)]"
455
+ elif kind == "skip":
456
+ started = []
457
+ i = 0
458
+ while i < len(order) and self.error is None and len(log) < 12:
459
+ o = order[i]
460
+ st, beeped = self._weigh(o)
461
+ log.append((NAME[o], st, beeped))
462
+ if st == "no_grasp":
463
+ continue
464
+ started.append(o)
465
+ i = len(started) # counts started items, not readings
466
+ plan["recovery"] = "counts items it started to weigh (the interrupted one too)"
467
+ else: # memoryless after the stop
468
+ r = self._run_from(0, record, log, stop_on_stop=True)
469
+ if r == "stopped":
470
+ if kind == "naive":
471
+ g = int(rng.integers(0, len(order) + 1))
472
+ plan["recovery"] = f"memoryless: guesses {g} items already weighed"
473
+ self._run_from(g, [], log)
474
+ elif kind == "blind":
475
+ plan["recovery"] = "memoryless restart from the first item"
476
+ self._run_from(0, [], log)
477
+ else:
478
+ raise ValueError(kind)
479
+ else:
480
+ plan["recovery"] = "none (no stop)"
481
+ else:
482
+ if kind in ("adaptive", "oracle", "skip"):
483
+ plan["recovery"] = "memory + F2: put items back on their pads / finish from own record"
484
+ if kind == "adaptive" and len(record) < len(order):
485
+ self._run_from(len(record), record, log)
486
+ if kind == "skip" and not history[-1]["outcome"]["complete"]:
487
+ # F2 says the log is incomplete: with memory, the item carried at the stop was not weighed
488
+ stopped = [s[0] for h in history for s in h["params"]["steps"] if str(s[1]).startswith("stop")]
489
+ if stopped:
490
+ o = next(i for i in ITEMS if NAME[i] == stopped[-1])
491
+ st, _ = self._weigh(o)
492
+ log.append((NAME[o], st))
493
+ plan["recovery"] = "memory + F2 'not every item weighed': weigh the item carried at the stop"
494
+ self._fix_pads(log)
495
+ elif kind == "blind":
496
+ plan["recovery"] = "memoryless restart from the first item"
497
+ self._run_from(0, [], log)
498
+ else:
499
+ raise ValueError(kind)
500
+ self.go_home()
501
+ out = self.outcome(inst)
502
+ history.append(dict(attempt=a + 1, params=plan, outcome=out))
503
+ if on_attempt:
504
+ on_attempt(a, plan, out)
505
+ if out["success"] or out["terminal"] or kind in ("oracle", "naive"):
506
+ break
507
+ return history
508
+
509
+ def default_params(self, inst):
510
+ return dict(policy="naive")
511
+
512
+ def oracle_params(self, inst):
513
+ return dict(policy="oracle")
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L7 hidden_mechanism: open a small cabinet door whose opening mechanism is hidden.
2
+
3
+ Category: failed_interaction_inference ("why did this contact not do what I expected?").
4
+
5
+ Scene: a small wooden cabinet (14 x 24 x 10 cm) whose door faces away from the robot (towards the front
6
+ camera), with a black knob post in the middle of the door. The robot reaches over the cabinet, grasps the
7
+ knob from above and pulls.
8
+
9
+ Hidden variable: the door's mechanism, one of four (uniform): swings on a hinge at its left edge (HL) or at
10
+ its right edge (HR), or slides to the left (SL) or to the right (SR). The door, the knob and the cabinet look
11
+ exactly the same for all four (hinge pins and slide rails are not modelled visually).
12
+
13
+ Rule (stated in the instruction and enforced): one pull per attempt -- grasp the knob, ONE straight move_to
14
+ while holding it, release. A "pull" is any move_to that starts with the knob held, moves the door, or pushes
15
+ against the door / knob sideways. Without this rule an agent could probe the door with small wiggles inside
16
+ one attempt and the task would no longer test what is learnt across attempts.
17
+
18
+ Why the prior fails (measured): the natural pull is straight out from the door (forward, +x), 12 cm.
19
+ hinged: the knob has to follow a circle around the hinge; the door swings open 31-36 deg and the knob is
20
+ pulled out of the fingers. The knob ends ~6 cm forward and ~4.5 cm towards the hinge side.
21
+ sliding: nothing moves; the fingers slide off the knob.
22
+ Success needs >= 60 deg (hinged) or >= 12 cm (sliding).
23
+
24
+ What must be learned: from how the knob / door moved (F2 gives the knob's displacement relative to where it
25
+ started, plus the images) -> which mechanism -> the pull direction that opens it:
26
+ hinged on the left: pull forward-left (~55 deg from forward), ~22 cm -> 70-88 deg (measured)
27
+ hinged on the right: pull forward-right -> 70-88 deg
28
+ sliding: pull sideways ~18 cm (18 cm); after "nothing moved" the side is not observable,
29
+ so a learner needs one more attempt in the worst case (left fails -> right).
30
+ Straight pulls at 30 / 45 deg towards the hinge give 44 / ~62 deg; diagonal pulls on a slider give 2-4 cm.
31
+ """
32
+ import mujoco
33
+ import numpy as np
34
+
35
+ from .. import envs
36
+ from ..bddl import write_bddl
37
+ from ..objects import _SOLID, _fmt, register_generated
38
+ from ..skills import Skills
39
+ from ..task_base import LFFTask, register_task
40
+
41
+ CAB = "cab_1"
42
+ MODEL = "lff_l7_mech_cabinet"
43
+ # cabinet frame: origin at the centre of the footprint, z = 0 on the table; the open side faces +x
44
+ D, W, H, T = 0.14, 0.24, 0.10, 0.01 # depth (x), width (y), height, wall thickness
45
+ DW, DH, DT = 0.232, 0.09, 0.012 # door width, height, thickness
46
+ GAP = 0.002
47
+ KZ = 0.045 # knob stem height above the table
48
+ STEM_L, STEM_R = 0.032, 0.005
49
+ POST_R, POST_H = 0.009, 0.038
50
+ POST_TOP = KZ - 0.006 + POST_H # 7.7 cm above the table
51
+ Z_GRIP = envs.TABLE_Z + 0.075 # grasp-point height for grasping the knob (verified across cabinet positions)
52
+ MECHS = ("HL", "HR", "SL", "SR")
53
+ HINGE_OK = np.radians(60.0)
54
+ SLIDE_OK = 0.12
55
+ SLIDE_RANGE = 0.22
56
+ PULL_SPEED = 0.10
57
+
58
+
59
+ def cabinet_xml(name, rgba=(0.45, 0.32, 0.22, 1.0), door_rgba=(0.80, 0.70, 0.55, 1.0), knob_rgba=(0.12, 0.12, 0.13, 1.0)):
60
+ hx, hy = D / 2, W / 2
61
+ shell = [((-hx + T / 2, 0, H / 2), (T / 2, hy, H / 2)), ((0, hy - T / 2, H / 2), (hx, T / 2, H / 2)),
62
+ ((0, -hy + T / 2, H / 2), (hx, T / 2, H / 2)), ((0, 0, H - T / 2), (hx, hy, T / 2)),
63
+ ((0, 0, T / 2), (hx, hy, T / 2))]
64
+ g = []
65
+ for k, (p, s) in enumerate(shell):
66
+ g.append(f'<geom name="{name}_s{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(rgba)}" '
67
+ f'friction="0.6 0.005 0.0001" {_SOLID} group="0"/>')
68
+ g.append(f'<geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
69
+ dx = hx + GAP + DT / 2
70
+ dz = 0.005 + DH / 2
71
+ door = [f'<inertial pos="0 0 0" mass="0.35" diaginertia="0.0004 0.0016 0.0016"/>',
72
+ # placeholder joint: type, axis, anchor and range are set per instance (apply_instance)
73
+ f'<joint name="{name}_door_joint" type="hinge" axis="0 0 1" pos="0 0 0" limited="true" range="-0.01 0.01" '
74
+ f'damping="0.2" frictionloss="0.02"/>',
75
+ f'<geom name="{name}_panel" type="box" size="{_fmt((DT / 2, DW / 2, DH / 2))}" rgba="{_fmt(door_rgba)}" '
76
+ f'friction="0.6 0.005 0.0001" {_SOLID} group="0"/>',
77
+ f'<geom type="box" size="{_fmt((DT / 2, DW / 2, DH / 2))}" rgba="{_fmt(door_rgba)}" contype="0" conaffinity="0" group="1"/>']
78
+ sz = KZ - dz
79
+ stem_p = (DT / 2 + STEM_L / 2, 0, sz)
80
+ post_p = (DT / 2 + STEM_L, 0, sz - 0.006 + POST_H / 2)
81
+ for tag, typ, p, s in (("stem", "box", stem_p, (STEM_L / 2 + 0.002, STEM_R, STEM_R)),
82
+ ("post", "cylinder", post_p, (POST_R, POST_H / 2))):
83
+ door.append(f'<geom name="{name}_{tag}" type="{typ}" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(knob_rgba)}" '
84
+ f'friction="1.0 0.005 0.0001" {_SOLID} group="0"/>')
85
+ door.append(f'<geom type="{typ}" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(knob_rgba)}" contype="0" conaffinity="0" group="1"/>')
86
+ body = ("\n ".join(g) + f'\n <body name="door" pos="{_fmt((dx, 0, dz))}">\n '
87
+ + "\n ".join(door) + "\n </body>")
88
+ return f"""<mujoco model="{name}">
89
+ <worldbody>
90
+ <body>
91
+ <body name="object">
92
+ {body}
93
+ </body>
94
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
95
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {H:.4f}" name="top_site" />
96
+ <site rgba="0 0 0 0" size="0.005" pos="{D / 2:.4f} {W / 2:.4f} 0" name="horizontal_radius_site" />
97
+ </body>
98
+ </worldbody>
99
+ </mujoco>"""
100
+
101
+
102
+ def _lr(v):
103
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
104
+
105
+
106
+ def _fb(v):
107
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
108
+
109
+
110
+ class MechSkills(Skills):
111
+ """Skills that log, for whoever drives them (scripted policy or agent): door pulls, the first grasp of the
112
+ knob, and how the knob moved during the first pull."""
113
+
114
+ def __init__(self, env, task, recorder=None):
115
+ super().__init__(env, recorder=recorder)
116
+ self.task = task
117
+ m = env.sim.model
118
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
119
+ self._door_geoms = task.door_geom_ids
120
+ self.knob0 = task.knob_xyz()
121
+ self.pulls = [] # one entry per move_to that counts as a pull
122
+ self.closes = [] # close_gripper events: gripper centre relative to the knob, held afterwards?
123
+ self._touch = False
124
+ self.touch_since_report = False
125
+
126
+ def holding_knob(self):
127
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.task.knob_geom_names))
128
+
129
+ def _touching_door(self):
130
+ d = self.env.sim.data
131
+ g = set(self._grip_geoms)
132
+ dg = set(self._door_geoms)
133
+ for i in range(d.ncon):
134
+ c = d.contact[i]
135
+ if (c.geom1 in g and c.geom2 in dg) or (c.geom2 in g and c.geom1 in dg):
136
+ return True
137
+ return False
138
+
139
+ def _act(self, dpos, drot, grip):
140
+ super()._act(dpos, drot, grip)
141
+ if self._touching_door():
142
+ self._touch = True # per move_to (pull detection)
143
+ self.touch_since_report = True # per agent command (report field)
144
+
145
+ def move_to(self, target, *args, **kwargs):
146
+ q0 = self.task.door_q()
147
+ hold0 = self.holding_knob()
148
+ p0 = self.eef_pos()
149
+ k0 = self.task.knob_xyz()
150
+ self._touch = False
151
+ rep = super().move_to(target, *args, **kwargs)
152
+ dq = abs(self.task.door_q() - q0)
153
+ moved = dq > (np.radians(1.0) if self.task.hinged else 0.003)
154
+ horiz = float(np.linalg.norm(np.asarray(target, float)[:2] - p0[:2]))
155
+ if hold0 or moved or (self._touch and horiz >= 0.015):
156
+ k1 = self.task.knob_xyz()
157
+ self.pulls.append(dict(step=self.n_steps, held_at_start=bool(hold0), held_at_end=self.holding_knob(),
158
+ knob_start=k0.tolist(), knob_end=k1.tolist(), door_moved=bool(moved),
159
+ gripper_move=(np.asarray(target, float)[:2] - p0[:2]).round(4).tolist()))
160
+ return rep
161
+
162
+ def set_gripper(self, close, steps=15):
163
+ was_open = self.grip < 0
164
+ rep = super().set_gripper(close, steps)
165
+ if close and was_open:
166
+ off = self.eef_pos() - self.task.knob_xyz()
167
+ self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_knob(),
168
+ width=round(self.gripper_width(), 4)))
169
+ return rep
170
+
171
+
172
+ @register_task
173
+ class HiddenMechanism(LFFTask):
174
+ name = "l7_hidden_mechanism"
175
+ level = "L7"
176
+ category = "failed_interaction_inference"
177
+ capabilities = ("Perceive", "Reason", "Plan")
178
+ protocol = "cross"
179
+ instruction = ("Open the door of the small wooden cabinet wide (a door that swings must end at least 60 degrees "
180
+ "open, a door that slides at least 12 cm). The door faces away from you; grasp its black knob from "
181
+ "above. Only one pull is allowed per attempt: grasp the knob, move the gripper with ONE straight "
182
+ "move command while holding it, then release it. Pushing the door or the knob counts as a pull "
183
+ "too.")
184
+ instruction_indirect = ("Open the front panel of the small brown box wide (a panel that swings must end at least 60 "
185
+ "degrees open, a panel that slides at least 12 cm). The panel faces away from you; grasp the "
186
+ "small black handle on it from above. Only one pull is allowed per attempt: grasp the handle, "
187
+ "move the gripper with ONE straight move command while holding it, then release it. "
188
+ "Pushing the panel or the handle counts as a pull too.")
189
+
190
+ # ------------------------------------------------------------ scene
191
+ def make_bddl(self):
192
+ cab = register_generated("LffL7MechCabinet", cabinet_xml(MODEL), free=False)
193
+ return write_bddl(self.name, "open the cabinet door", [],
194
+ fixtures=[(CAB, cab, "cab_region", (-0.14, -0.01, -0.12, 0.01))])
195
+
196
+ def __init__(self, cam_res=None):
197
+ super().__init__(cam_res)
198
+ m = self.env.sim.model
199
+ pre = f"{CAB}_{MODEL}"
200
+ self.jid = m.joint_name2id(pre + "_door_joint")
201
+ self.dof = m.jnt_dofadr[self.jid]
202
+ self.qa = m.jnt_qposadr[self.jid]
203
+ self.cab_bid = m.body_name2id(self.env.fixtures_dict[CAB].root_body)
204
+ self.post_gid = m.geom_name2id(pre + "_post")
205
+ self.knob_geom_names = [pre + "_post", pre + "_stem"]
206
+ self.door_geom_ids = [m.geom_name2id(pre + s) for s in ("_post", "_stem", "_panel")]
207
+ self.hinged = True
208
+
209
+ # agent-facing hooks -------------------------------------------------------
210
+ def on_agent_tool(self, inst, name, args, report):
211
+ """The cabinet is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never
212
+ see the knob or the door; add an explicit `holding_knob` field and count door contacts as touches."""
213
+ if self.sk is None or not isinstance(report, dict):
214
+ return
215
+ touched = self.sk.touch_since_report
216
+ self.sk.touch_since_report = False
217
+ if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"):
218
+ report["holding_knob"] = self.sk.holding_knob()
219
+ if touched and "touched_object" in report:
220
+ report["touched_object"] = True
221
+
222
+ # ------------------------------------------------------------ state helpers
223
+ def door_q(self):
224
+ return float(self.env.sim.data.qpos[self.qa])
225
+
226
+ def knob_xyz(self):
227
+ return self.env.sim.data.geom_xpos[self.post_gid].copy()
228
+
229
+ def sample_instance(self, seed):
230
+ rng = np.random.default_rng(seed)
231
+ return dict(seed=int(seed), mech=MECHS[int(rng.integers(4))],
232
+ cab_xy=[float(rng.uniform(-0.15, -0.10)), float(rng.uniform(-0.07, 0.07))])
233
+
234
+ def apply_instance(self, inst):
235
+ m, d = self.env.sim.model, self.env.sim.data
236
+ cx, cy = inst["cab_xy"]
237
+ m.body_pos[self.cab_bid] = [cx, cy, envs.TABLE_Z]
238
+ m.body_quat[self.cab_bid] = [1.0, 0.0, 0.0, 0.0]
239
+ mech = inst["mech"]
240
+ jid, dof = self.jid, self.dof
241
+ self.hinged = mech in ("HL", "HR")
242
+ if self.hinged:
243
+ s = 1 if mech == "HL" else -1
244
+ m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_HINGE
245
+ m.jnt_axis[jid] = [0, 0, 1]
246
+ m.jnt_pos[jid] = [-DT / 2, s * DW / 2, 0] # back face of the door, at its left / right edge
247
+ m.jnt_range[jid] = [0.0, 1.9] if s > 0 else [-1.9, 0.0]
248
+ m.dof_damping[dof] = 0.05
249
+ m.dof_frictionloss[dof] = 0.03
250
+ else:
251
+ s = 1 if mech == "SL" else -1
252
+ m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_SLIDE
253
+ m.jnt_axis[jid] = [0, s, 0]
254
+ m.jnt_pos[jid] = [0, 0, 0]
255
+ m.jnt_range[jid] = [0.0, SLIDE_RANGE]
256
+ m.dof_damping[dof] = 2.0
257
+ m.dof_frictionloss[dof] = 0.5
258
+ # MuJoCo scales constraint softness (here: the joint limits) with dof_invweight0, computed once at compile
259
+ # time for the placeholder hinge through the door's centre. Changing the joint type without updating it
260
+ # made the slide limit ~200x too soft: a slider pulled the wrong way moved 17 cm past its stop (measured).
261
+ door_mass, door_izz = 0.35, 0.0016
262
+ m.dof_invweight0[dof] = (1.0 / (door_izz + door_mass * (DW / 2) ** 2)) if self.hinged else 1.0 / door_mass
263
+ m.jnt_solref[jid] = [0.004, 1.0] # stiff stops (default 0.02 let a hard pull push a slider 8 mm past its stop)
264
+ d.qpos[self.qa] = 0.0
265
+ d.qvel[dof] = 0.0
266
+
267
+ def reset_instance(self, inst, recorder=None):
268
+ self.env.reset()
269
+ self.apply_instance(inst)
270
+ self.env.sim.forward()
271
+ envs.settle(self.env, 10)
272
+ self.sk = MechSkills(self.env, self, recorder=recorder)
273
+ return self.sk
274
+
275
+ def opening(self):
276
+ """Hinge: degrees open (>= 0); slide: cm open (>= 0)."""
277
+ q = abs(self.door_q())
278
+ return float(np.degrees(q)) if self.hinged else 100.0 * q
279
+
280
+ # ------------------------------------------------------------ outcome
281
+ def outcome(self, inst):
282
+ envs.settle(self.env, 20)
283
+ sk = self.sk
284
+ q = abs(self.door_q())
285
+ is_open = q >= (HINGE_OK if self.hinged else SLIDE_OK)
286
+ n_pulls = len(sk.pulls)
287
+ success = bool(is_open and n_pulls <= 1)
288
+ kd = self.knob_xyz() - sk.knob0
289
+ out = dict(success=success, door_open=bool(is_open), opening=round(self.opening(), 1), n_pulls=n_pulls,
290
+ knob_disp=kd.round(4).tolist(), pulls=sk.pulls, closes=sk.closes, first_pull_disp=None,
291
+ lost_hold=None)
292
+ parts = []
293
+ grasp_txt = ""
294
+ if sk.closes:
295
+ c = sk.closes[0]
296
+ o = c["offset"]
297
+ below = (envs.TABLE_Z + POST_TOP) - (o[2] + sk.knob0[2]) # knob top minus gripper centre height
298
+ grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the knob's "
299
+ f"centre and {100 * below:.1f} cm below the top of the knob; it "
300
+ + ("was holding the knob." if c["held"] else "did not get hold of the knob."))
301
+ if success:
302
+ out["failure"] = None
303
+ parts.append("The door is open wide.")
304
+ elif n_pulls == 0:
305
+ out["failure"] = "no_pull"
306
+ parts.append("The door did not open: the knob was never pulled.")
307
+ else:
308
+ out["failure"] = "several_pulls" if n_pulls > 1 else "not_open"
309
+ if n_pulls > 1:
310
+ parts.append(f"The door or knob was pulled or pushed in {n_pulls} separate moves; only one pull is "
311
+ f"allowed per attempt, so this attempt failed.")
312
+ elif is_open:
313
+ parts.append("The door is open wide.")
314
+ else:
315
+ parts.append("The door did not open wide enough.")
316
+ p = sk.pulls[0]
317
+ # net effect of the first pull once things came to rest: up to the start of the next pull, or now
318
+ k_after = np.array(sk.pulls[1]["knob_start"]) if n_pulls > 1 else self.knob_xyz()
319
+ disp = k_after - np.array(p["knob_start"])
320
+ out["first_pull_disp"] = disp.round(4).tolist()
321
+ out["lost_hold"] = bool(p["held_at_start"] and not p["held_at_end"])
322
+ if np.linalg.norm(disp[:2]) < 0.003:
323
+ txt = "During your (first) pull the knob did not move at all (less than 0.3 cm)"
324
+ else:
325
+ txt = f"During your (first) pull the knob moved {_fb(disp[0])} and {_lr(disp[1])}"
326
+ if p["held_at_start"]:
327
+ txt += ("; the gripper lost hold of the knob during the pull." if out["lost_hold"]
328
+ else "; the gripper still held the knob at the end of the pull.")
329
+ else:
330
+ txt += "; the gripper was not holding the knob when that move started."
331
+ parts.append(txt)
332
+ if grasp_txt and not success:
333
+ parts.append(grasp_txt)
334
+ out["detail"] = " ".join(parts)
335
+ return out
336
+
337
+ # ------------------------------------------------------------ scripted execution (cross protocol)
338
+ def execute(self, inst, params):
339
+ """Grasp the knob from above (yaw 0), one straight pull in direction `alpha` (deg from forward, + = left)
340
+ over `dist` metres, release, lift."""
341
+ sk = self.sk
342
+ p = self.knob_xyz() # perfect perception of the current scene
343
+ sk.set_gripper(False, steps=8)
344
+ sk.move_to([p[0], p[1], Z_GRIP + 0.08], yaw=0.0)
345
+ sk.move_to([p[0], p[1], Z_GRIP], tol=0.003)
346
+ sk.set_gripper(True, steps=15)
347
+ a = np.radians(float(params["alpha"]))
348
+ dist = float(params["dist"])
349
+ sk.move_to([p[0] + dist * np.cos(a), p[1] + dist * np.sin(a), Z_GRIP], speed=PULL_SPEED, tol=0.004,
350
+ max_steps=300)
351
+ sk.set_gripper(False, steps=8)
352
+ e = sk.eef_pos()
353
+ sk.move_to([e[0], e[1], Z_GRIP + 0.10])
354
+
355
+ def default_params(self, inst):
356
+ return dict(alpha=0.0, dist=0.12)
357
+
358
+ ORACLE = dict(HL=(55.0, 0.22), HR=(-55.0, 0.22), SL=(90.0, 0.18), SR=(-90.0, 0.18))
359
+
360
+ def oracle_params(self, inst):
361
+ a, dist = self.ORACLE[inst["mech"]]
362
+ return dict(alpha=a, dist=dist)
363
+
364
+ def adapt_params(self, inst, history):
365
+ """Scripted F2 learner using the knob's displacement during the (first) pull of each earlier attempt:
366
+ moved forward and sideways -> it swings on a hinge on that side -> pull ~55 deg towards that side
367
+ (more if a hinge pull already fell short)
368
+ moved only sideways -> it slides that way -> pull sideways
369
+ did not move -> not a hinge; it must slide: try left, then right."""
370
+ hinge_side, slide_side = 0, 0
371
+ tried_still = set() # pull directions (sign of alpha, only for sideways pulls) after which nothing moved
372
+ hinge_tries = 0
373
+ for h in history:
374
+ o = h["outcome"]
375
+ d = o.get("first_pull_disp")
376
+ a = h["params"]["alpha"]
377
+ if d is None:
378
+ continue
379
+ dx, dy = d[0], d[1]
380
+ if dx >= 0.01 and abs(dy) >= 0.01:
381
+ hinge_side = int(np.sign(dy))
382
+ if abs(a) >= 50:
383
+ hinge_tries += 1
384
+ elif abs(dy) >= 0.01:
385
+ slide_side = int(np.sign(dy))
386
+ elif abs(a) >= 80:
387
+ tried_still.add(int(np.sign(a)))
388
+ if hinge_side:
389
+ a = 55.0 + 5.0 * min(hinge_tries, 2)
390
+ return dict(alpha=hinge_side * a, dist=0.22 + 0.02 * min(hinge_tries, 2))
391
+ if slide_side:
392
+ return dict(alpha=90.0 * slide_side, dist=0.18)
393
+ side = 1 if 1 not in tried_still else -1
394
+ return dict(alpha=90.0 * side, dist=0.18)
395
+
396
+ def blind_params(self, inst, attempt, rng):
397
+ """Same plan (pull straight out) with small random variation; no history."""
398
+ return dict(alpha=float(rng.normal(0.0, 8.0)), dist=float(np.clip(rng.normal(0.12, 0.02), 0.06, 0.2)))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH pantry_relatch: breakfast prep. Take the bread out of a hinged pantry box and put it on the plate, then put the
2
+ butter into the (now empty) box and close it.
3
+
4
+ New mechanism (not a repeat of lh_lid_box / lh_shelf_droop / lh_false_bottom_lid): the box's closing catch is not a
5
+ static per-instance draw, it is a counter of how many times the box has already been closed in this attempt. A weak
6
+ spring (`OPEN_BIAS`) constantly nudges the lid open; a catch (`qfrc_applied`, same idiom as lh_shelf_droop's bracket)
7
+ counters it near the closed angle. The FIRST close always holds (LATCH0 beats the spring) even with a quick swing-and
8
+ -release. After one full open/close cycle the catch's holding strength is reduced (`DECAY`); a second quick-release
9
+ close is no longer enough and the lid creeps back open by itself during the mandatory settle window, with nothing
10
+ else touching it. The fix is not "close it again the same way" (that decays again); it is a firm press-and-hold
11
+ (`dwell`) at the closed angle before letting go, which engages a separate, non-decaying friction seat
12
+ (`SEAT_LATCH`) regardless of cycle count.
13
+
14
+ Geometry/skills are reused unmodified from lh_lid_box.py (box_lid_xml, LidSkills): only the hinge's spring/latch
15
+ torques and the Python cycle counter are new. Protocol: cross, k = 5.
16
+ """
17
+ import numpy as np
18
+
19
+ from .. import envs
20
+ from ..bddl import write_bddl
21
+ from ..objects import box_xml, register_generated
22
+ from ..task_base import LFFTask, register_task
23
+ from .lh_lid_box import (BOX_D, BOX_W, WALL_H, WALL_T, FLOOR_T, LID_T, LID_MASS, IN_X, IN_Y, HINGE_DAMP, box_lid_xml,
24
+ LidSkills)
25
+
26
+ G = 9.81
27
+ BOX = "box_1"
28
+ BOX_MODEL = "lff_pantry_box"
29
+
30
+ BREAD_HALF = (0.032, 0.022, 0.011) # 6.4 x 4.4 x 2.2 cm flat loaf, fits the 3.2 cm interior height
31
+ BUTTER_HALF = (0.013, 0.013, 0.013) # 2.6 cm cube
32
+ BREAD_DENS, BUTTER_DENS = 400.0, 600.0
33
+
34
+ # ---------------------------------------------------------------- latch-fatigue mechanism
35
+ CLOSE_DEG = 4.0 # lid angle (deg) counted as "closed" for the final judge
36
+ BAND_DEG = 100.0 # angle range (deg) over which gravity is cancelled and the open bias/catch act (wide, so
37
+ # an unlatched lid drifts smoothly all the way open instead of sticking at a cutoff edge)
38
+ OPEN_BIAS = 0.05 # N*m: net torque pushing the lid open within the band, once gravity is cancelled
39
+ LATCH0 = 0.14 # N*m: catch strength on the FIRST close (always beats OPEN_BIAS)
40
+ DECAY = 0.30 # catch strength multiplier from the SECOND close on, if not seated
41
+ SEAT_LATCH = 0.18 # N*m: non-decaying strength if the close was seated (dwell-pressed)
42
+ DWELL_MIN = 20 # control steps (closed, knob held, no further motion) needed to seat a close
43
+ EXTRA_DAMP = 0.12 # N*m*s/rad added to the hinge dof so an unlatched drift takes a few seconds, not instant
44
+ GRAVITY_LEVER = BOX_D / 2 # lid's centre of mass offset from the hinge (box_lid_xml convention)
45
+ T_GRAV0 = LID_MASS * G * GRAVITY_LEVER
46
+
47
+ SETTLE_MIN, SETTLE_MAX = 300, 600 # 15-30 s simulated, same convention as lh_shelf_droop
48
+
49
+
50
+ def _fb(v):
51
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
52
+
53
+
54
+ def _lr(v):
55
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
56
+
57
+
58
+ class RelatchSkills(LidSkills):
59
+ """LidSkills plus a dwell counter: control steps spent holding the knob still at the closed angle while latched.
60
+ `monitor_step` (run every control step via LidSkills._act, before this class's own _act resets the counter)
61
+ reads it at the instant the gripper opens near the closed angle to decide whether this close is 'seated'."""
62
+
63
+ def __init__(self, env, task, recorder=None):
64
+ super().__init__(env, task, recorder=recorder)
65
+ self.dwell = 0
66
+
67
+ def _act(self, dpos, drot, grip):
68
+ super()._act(dpos, drot, grip) # LidSkills._act calls self.task.monitor_step() before returning here
69
+ if self.latched:
70
+ # the agent (or scripted policy) is actively holding the knob: never let the artificial drift fight
71
+ # that grasp (it caused the knob to wander off mid-regrasp during prototyping).
72
+ self.task.drift_active = False
73
+ if self.task.lid_deg() < CLOSE_DEG:
74
+ self.dwell += 1
75
+ else:
76
+ self.dwell = 0
77
+ else:
78
+ self.dwell = 0
79
+
80
+
81
+ @register_task
82
+ class PantryRelatch(LFFTask):
83
+ name = "lh_pantry_relatch"
84
+ level = "L2"
85
+ category = "state_restoration"
86
+ capabilities = ("Perceive", "Reason", "Plan", "Restore")
87
+ protocol = "cross"
88
+ max_attempts = 5
89
+ agent_max_steps = 130
90
+ instruction = ("Open the lid of the wooden pantry box (lift it by the black knob) and take the bread out; put it "
91
+ "on the plate. Then open the box again, put the butter inside it, and close the lid. At the end "
92
+ "the bread must be on the plate, the butter inside the box, the lid closed, the gripper open and "
93
+ "clear, and the scene still.")
94
+ instruction_indirect = ("Lift the lid of the flat wooden case by its black ball knob and take out the little "
95
+ "loaf; set it on the round plate. Then open the case again, put the small pale cube "
96
+ "inside it, and shut the lid. Finish with the loaf on the plate, the cube inside the "
97
+ "case, the lid down, the gripper open, and nothing moving.")
98
+ agent_object_names = ["bread (small loaf)", "butter (small pale cube)", "wooden pantry box", "lid knob", "plate"]
99
+
100
+ # ------------------------------------------------------------ scene
101
+ def make_bddl(self):
102
+ box = register_generated("LffPantryBox", box_lid_xml(BOX_MODEL), free=False)
103
+ bread = register_generated("LffPantryBread", box_xml("lff_pantry_bread", BREAD_HALF, (0.74, 0.52, 0.22, 1.0),
104
+ density=BREAD_DENS, friction=(0.7, 0.005, 0.0001)))
105
+ butter = register_generated("LffPantryButter", box_xml("lff_pantry_butter", BUTTER_HALF, (0.95, 0.92, 0.70, 1.0),
106
+ density=BUTTER_DENS, friction=(0.5, 0.005, 0.0001)))
107
+ objs = [("bread_1", bread, "bread_region", (-0.31, -0.01, -0.29, 0.01)),
108
+ ("butter_1", butter, "butter_region", (-0.31, 0.24, -0.29, 0.26)),
109
+ ("plate_1", "plate", "plate_region", (0.02, -0.26, 0.04, -0.24))]
110
+ fx = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))]
111
+ return write_bddl(self.name, "take the bread out, put it on the plate, put the butter in the box, close it",
112
+ objs, fx)
113
+
114
+ def __init__(self, cam_res=None):
115
+ super().__init__(cam_res)
116
+ m = self.env.sim.model
117
+ pre = f"{BOX}_{BOX_MODEL}"
118
+ self.jid = m.joint_name2id(pre + "_hinge")
119
+ self.qa = int(m.jnt_qposadr[self.jid])
120
+ self.dof = int(m.jnt_dofadr[self.jid])
121
+ self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
122
+ self.knob_geom_name = pre + "_knob"
123
+ self.knob_geom_names = [pre + "_knob", pre + "_stem"]
124
+ self.knob_gid = m.geom_name2id(self.knob_geom_name)
125
+ sim = self.env.sim
126
+ if not getattr(sim, "_lhpr_wrapped", False):
127
+ orig = sim.step
128
+
129
+ def step(*a, **k):
130
+ orig(*a, **k)
131
+ t = getattr(sim, "_lhpr_task", None)
132
+ if t is not None:
133
+ t._bracket()
134
+
135
+ sim.step = step
136
+ sim._lhpr_wrapped = True
137
+ sim._lhpr_task = self
138
+ self.inst = None
139
+ self.mon = None
140
+ self.active_latch = LATCH0
141
+ self.closes_done = 0
142
+ self.drift_active = False
143
+
144
+ def sample_instance(self, seed):
145
+ rng = np.random.default_rng(seed)
146
+ bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03))
147
+ plate_xy = [float(rng.uniform(0.0, 0.06)), float(rng.uniform(-0.27, -0.23))]
148
+ bread_xy = [bx + float(rng.uniform(-0.01, 0.01)), by + float(rng.uniform(-0.01, 0.01))]
149
+ butter_xy = [float(rng.uniform(-0.32, -0.28)), float(rng.uniform(0.22, 0.28))]
150
+ return dict(seed=int(seed), box_xy=[bx, by], plate_xy=plate_xy, bread_xy=bread_xy, butter_xy=butter_xy,
151
+ bread_yaw=float(rng.uniform(-0.2, 0.2)), latch=True)
152
+
153
+ def apply_instance(self, inst):
154
+ self.inst = inst
155
+ m, d = self.env.sim.model, self.env.sim.data
156
+ bx, by = inst["box_xy"]
157
+ m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z]
158
+ m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
159
+ m.jnt_range[self.jid] = [0.0, np.radians(150.0)]
160
+ d.qpos[self.qa] = 0.0
161
+ d.qvel[self.dof] = 0.0
162
+ d.qfrc_applied[self.dof] = 0.0
163
+ m.dof_damping[self.dof] = HINGE_DAMP + EXTRA_DAMP # absolute, not cumulative across repeated resets
164
+ self._move_keep_orientation("plate_1", inst["plate_xy"])
165
+ envs.set_obj_pose(self.env, "bread_1", [bx, by, envs.TABLE_Z + FLOOR_T + BREAD_HALF[2] + 0.001],
166
+ yaw=inst["bread_yaw"])
167
+ envs.set_obj_pose(self.env, "butter_1", [*inst["butter_xy"], envs.TABLE_Z + BUTTER_HALF[2] + 0.0005])
168
+ self.closes_done = 0
169
+ self.active_latch = LATCH0
170
+ self.drift_active = False
171
+
172
+ def _move_keep_orientation(self, name, xy, clearance=0.002):
173
+ qa, da = envs.free_joint_addr(self.env, name)
174
+ d = self.env.sim.data
175
+ d.qpos[qa:qa + 2] = xy
176
+ d.qvel[da:da + 6] = 0.0
177
+ self.env.sim.forward()
178
+ d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance)
179
+ self.env.sim.forward()
180
+
181
+ def reset_instance(self, inst, recorder=None):
182
+ self.env.reset()
183
+ self.apply_instance(inst)
184
+ self.env.sim.forward()
185
+ envs.settle(self.env, 10)
186
+ self.mon = dict(events=[], lid_open_max=0.0, armed=False)
187
+ self.sk = RelatchSkills(self.env, self, recorder=recorder)
188
+ return self.sk
189
+
190
+ # ------------------------------------------------------------ latch physics
191
+ def lid_q(self):
192
+ return float(self.env.sim.data.qpos[self.qa])
193
+
194
+ def lid_deg(self):
195
+ return float(np.degrees(self.lid_q()))
196
+
197
+ def knob_xyz(self):
198
+ return self.env.sim.data.geom_xpos[self.knob_gid].copy()
199
+
200
+ def hinge_xz(self):
201
+ return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H
202
+
203
+ def _bracket(self):
204
+ """Every MuJoCo substep. Only active between a just-finished, under-latched close and the next time the
205
+ agent actually grasps the knob again (self.drift_active, cleared the instant the knob is latched -- see
206
+ RelatchSkills._act): within BAND_DEG of closed, cancel gravity's closing pull and add a small constant
207
+ opening bias, net positive because the catch is too weak (self.active_latch < OPEN_BIAS whenever
208
+ drift_active is set True in the first place). A held-firmly close needs no artificial force at all: plain
209
+ gravity already keeps box_lid_xml's lid shut on its own, same as lh_lid_box."""
210
+ d = self.env.sim.data
211
+ if not self.inst.get("latch", True) or not self.drift_active:
212
+ d.qfrc_applied[self.dof] = 0.0 # never leave a stale value applied once the drift is no longer armed
213
+ return
214
+ th = float(d.qpos[self.qa])
215
+ # the closed rest angle overshoots the joint limit by a hair (contact softness), so the lower edge of the
216
+ # band must tolerate a small negative theta -- a strict "th >= 0" guard left qfrc_applied permanently 0 at
217
+ # the resting pose and the catch never engaged at all (measured during prototyping).
218
+ if np.radians(-3.0) <= th < np.radians(BAND_DEG):
219
+ grav = T_GRAV0 * max(np.cos(th), 0.0)
220
+ d.qfrc_applied[self.dof] = grav + OPEN_BIAS - self.active_latch
221
+ else:
222
+ d.qfrc_applied[self.dof] = 0.0
223
+
224
+ def _register_close(self, seated):
225
+ """Called once a close-then-release is detected. Decides the catch strength that will apply to THIS closed
226
+ state from now on (until the lid is reopened and closed again), and whether the artificial drift-open force
227
+ is armed (only when the catch is too weak to hold on its own)."""
228
+ if self.closes_done == 0:
229
+ self.active_latch = LATCH0
230
+ elif seated:
231
+ self.active_latch = SEAT_LATCH
232
+ else:
233
+ self.active_latch = LATCH0 * DECAY
234
+ self.closes_done += 1
235
+ self.drift_active = self.active_latch < OPEN_BIAS
236
+ self.mon["events"].append(dict(ev="closed", n=self.closes_done, seated=bool(seated),
237
+ active_latch=round(self.active_latch, 4), drift_armed=self.drift_active))
238
+
239
+ def monitor_step(self):
240
+ """Runs every control step (via LidSkills._act, for the scripted policies below and for a real agent's own
241
+ move_to/set_gripper calls alike). One-shot edge detector: 'armed' once the lid has been meaningfully open
242
+ (> 20 deg); the first step afterwards where it is back near closed AND the gripper is open counts as a
243
+ close event, scored seated/unseated from the dwell counter at that exact instant (before RelatchSkills._act
244
+ resets it for this same step -- see the call order note there)."""
245
+ mon = self.mon
246
+ if mon is None:
247
+ return
248
+ q = self.lid_deg()
249
+ mon["lid_open_max"] = max(mon["lid_open_max"], q)
250
+ if q > 20.0:
251
+ mon["armed"] = True
252
+ if mon.get("armed") and q <= CLOSE_DEG and self.sk.grip < 0:
253
+ mon["armed"] = False
254
+ self._register_close(self.sk.dwell >= DWELL_MIN)
255
+
256
+ # ------------------------------------------------------------ predicates
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 bread_on_plate(self):
261
+ p = envs.obj_pos(self.env, "bread_1")
262
+ d = np.linalg.norm(p[:2] - np.asarray(self.inst["plate_xy"]))
263
+ return bool(d < 0.05 and p[2] < envs.TABLE_Z + 0.06 and not self.held("bread_1"))
264
+
265
+ def butter_in_box(self):
266
+ p = envs.obj_pos(self.env, "butter_1")
267
+ rel = p[:2] - np.asarray(self.inst["box_xy"])
268
+ return bool(abs(rel[0]) <= IN_X - 0.004 and abs(rel[1]) <= IN_Y - 0.004 and p[2] < envs.TABLE_Z + WALL_H
269
+ and not self.held("butter_1"))
270
+
271
+ def lid_closed(self):
272
+ return self.lid_q() <= np.radians(CLOSE_DEG)
273
+
274
+ def stage_values(self):
275
+ return dict(bread_on_plate=self.bread_on_plate(), butter_in_box=self.butter_in_box(), lid_closed=self.lid_closed())
276
+
277
+ # ------------------------------------------------------------ scripted primitives
278
+ def pick_place(self, name, dest_xy, z_rel, z_carry=0.14, dest_yaw=0.0):
279
+ sk = self.sk
280
+ Z = envs.TABLE_Z
281
+ p = envs.obj_pos(self.env, name)
282
+ zg = p[2] - Z
283
+ sk.set_gripper(False, steps=8)
284
+ sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=0.0)
285
+ sk.move_to([p[0], p[1], Z + zg], tol=0.003)
286
+ sk.set_gripper(True, steps=15)
287
+ sk.move_to([p[0], p[1], Z + z_carry], speed=0.3)
288
+ self.monitor_step()
289
+ if not self.held(name):
290
+ sk.set_gripper(False, steps=8)
291
+ return False
292
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=dest_yaw)
293
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003)
294
+ sk.set_gripper(False, steps=12)
295
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry])
296
+ self.monitor_step()
297
+ return True
298
+
299
+ def take_bread(self):
300
+ return self.pick_place("bread_1", self.inst["plate_xy"], BREAD_HALF[2] + 0.004)
301
+
302
+ def put_butter(self):
303
+ # placed closer to the hinge side and off to one side of the box centre, clear of where the far (knob) end
304
+ # of the lid sweeps most when re-opened for a repair (measured during prototyping: a butter cube resting
305
+ # under the box centre was occasionally grazed by that swing).
306
+ bx, by = self.inst["box_xy"]
307
+ target = [bx + 0.6 * IN_X, by + 0.5 * IN_Y]
308
+ return self.pick_place("butter_1", target, FLOOR_T + BUTTER_HALF[2] + 0.006, z_carry=0.12)
309
+
310
+ def _grasp_knob(self):
311
+ sk = self.sk
312
+ k = self.knob_xyz()
313
+ sk.set_gripper(False, steps=8)
314
+ sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0)
315
+ sk.move_to([k[0], k[1], k[2]], tol=0.003)
316
+ sk.set_gripper(True, steps=15)
317
+ return k
318
+
319
+ def open_lid(self, back=0.03, up=0.16):
320
+ sk = self.sk
321
+ k = self._grasp_knob()
322
+ hx, hz = self.hinge_xz()
323
+ sk.move_to([k[0], k[1], k[2] + 0.10])
324
+ sk.move_to([hx + back, k[1], hz + up])
325
+ sk.set_gripper(False, steps=10)
326
+ e = sk.eef_pos()
327
+ sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06])
328
+ sk.hold(20)
329
+ self.monitor_step()
330
+
331
+ def close_lid(self, dwell=False):
332
+ """grasp the knob, carry it down the hinge's arc to the closed angle (the compliant knob-hold mechanism
333
+ clamps the physical joint limit at 0 deg, so a target far past closed just drives it fully shut); if dwell,
334
+ hold there (gripper still closed on the knob) for DWELL_MIN+ steps before releasing (seats the friction
335
+ catch); otherwise release immediately."""
336
+ sk = self.sk
337
+ k = self._grasp_knob()
338
+ hx, hz = self.hinge_xz()
339
+ sk.move_to([k[0], k[1], k[2] + 0.10])
340
+ far_x = hx - (BOX_D + 0.20)
341
+ low_z = envs.TABLE_Z + 0.02
342
+ for _ in range(4):
343
+ if self.lid_deg() <= CLOSE_DEG:
344
+ break
345
+ sk.move_to([far_x, sk.eef_pos()[1], low_z], tol=0.01, max_steps=150)
346
+ if dwell:
347
+ sk.hold(DWELL_MIN + 8)
348
+ sk.set_gripper(False, steps=10)
349
+ e = sk.eef_pos()
350
+ sk.move_to([e[0], e[1], e[2] + 0.06])
351
+ sk.hold(20)
352
+ self.monitor_step()
353
+
354
+ # ------------------------------------------------------------ outcome
355
+ def _static(self):
356
+ d = self.env.sim.data
357
+ for name in ("bread_1", "butter_1"):
358
+ _, da = envs.free_joint_addr(self.env, name)
359
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
360
+ return False
361
+ return abs(float(d.qvel[self.dof])) < 0.2
362
+
363
+ def outcome(self, inst):
364
+ sk = self.sk
365
+ n = 0
366
+ while n < SETTLE_MAX:
367
+ sk.hold(10)
368
+ n += 10
369
+ if n >= SETTLE_MIN and self._static():
370
+ break
371
+ vals = self.stage_values()
372
+ held = [n for n in ("bread_1", "butter_1") if self.held(n)]
373
+ static = self._static()
374
+ success = bool(all(vals.values()) and static and not held)
375
+ if success:
376
+ failure = None
377
+ detail = "Bread is on the plate, butter is in the box, and the lid is closed."
378
+ else:
379
+ failure = ("bread" if not vals["bread_on_plate"] else "butter" if not vals["butter_in_box"] else
380
+ "lid_open" if not vals["lid_closed"] else "held" if held else "not_static")
381
+ parts = []
382
+ if not vals["bread_on_plate"]:
383
+ p = envs.obj_pos(self.env, "bread_1")
384
+ rel = p[:2] - np.asarray(inst["plate_xy"])
385
+ parts.append("The bread is still held." if self.held("bread_1") else
386
+ f"The bread is not on the plate: {_fb(rel[0])} and {_lr(rel[1])} of the plate's centre.")
387
+ if not vals["butter_in_box"]:
388
+ p = envs.obj_pos(self.env, "butter_1")
389
+ rel = p[:2] - np.asarray(inst["box_xy"])
390
+ parts.append("The butter is still held." if self.held("butter_1") else
391
+ f"The butter is not in the box: {_fb(rel[0])} and {_lr(rel[1])} of the box's centre.")
392
+ if not vals["lid_closed"]:
393
+ parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees). It had been closed "
394
+ f"{self.closes_done} time(s) in this attempt; it did not stay shut on its own.")
395
+ if held:
396
+ parts.append(f"Still held: {', '.join(held)}.")
397
+ if not static and all(vals.values()):
398
+ parts.append("Something was still moving.")
399
+ detail = " ".join(parts)
400
+ return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
401
+ lid_final_deg=round(self.lid_deg(), 1), lid_open_max=round(self.mon["lid_open_max"], 1),
402
+ closes_done=self.closes_done, active_latch=round(self.active_latch, 4),
403
+ events=list(self.mon["events"]), detail=detail)
404
+
405
+ # ------------------------------------------------------------ execution + scripted policies
406
+ def execute(self, inst, params):
407
+ self.open_lid()
408
+ if not self.take_bread():
409
+ return
410
+ self.close_lid(dwell=params.get("dwell1", False))
411
+ self.open_lid()
412
+ if not self.put_butter():
413
+ return
414
+ self.close_lid(dwell=params.get("dwell2", False))
415
+ if params.get("check", False):
416
+ # look back before finishing: wait long enough (same order as the final settle window) for an
417
+ # under-latched close to reveal itself, then fix it with a firm dwell close if it did -- a genuine
418
+ # same-attempt recovery, not just a cross-attempt change of technique.
419
+ n = 0
420
+ while n < SETTLE_MIN and self.lid_closed():
421
+ self.sk.hold(10)
422
+ n += 10
423
+ if not self.lid_closed():
424
+ self.open_lid()
425
+ self.close_lid(dwell=True)
426
+ self.sk.hold(5)
427
+
428
+ def default_params(self, inst):
429
+ return dict(dwell1=False, dwell2=False, check=False)
430
+
431
+ def oracle_params(self, inst):
432
+ return dict(dwell1=False, dwell2=True, check=False)
433
+
434
+ def adapt_params(self, inst, history):
435
+ """From attempt 2 on (if attempt 1's own same-attempt check-and-repair somehow still fell short): close
436
+ every time with a firm dwell from the start, and keep checking before finishing."""
437
+ return dict(dwell1=True, dwell2=True, check=True)
438
+
439
+ def blind_params(self, inst, attempt, rng):
440
+ return dict(dwell1=False, dwell2=bool(rng.random() < 0.5), check=False)
441
+
442
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
443
+ k = k or self.max_attempts
444
+ rng = np.random.default_rng(seed)
445
+ history = []
446
+ for a in range(k):
447
+ self.reset_instance(inst)
448
+ if kind == "oracle":
449
+ params = self.oracle_params(inst)
450
+ elif kind == "naive":
451
+ params = self.default_params(inst)
452
+ elif kind == "adaptive":
453
+ # attempt 1: naive technique plus a final look-back-and-repair (genuine same-attempt recovery);
454
+ # only if that still were not enough would later attempts switch technique from the start.
455
+ params = (dict(self.default_params(inst), check=True) if a == 0
456
+ else self.adapt_params(inst, history))
457
+ elif kind == "blind":
458
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
459
+ else:
460
+ raise ValueError(kind)
461
+ self.execute(inst, params)
462
+ out = self.outcome(inst)
463
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
464
+ if on_attempt:
465
+ on_attempt(a, params, out)
466
+ if out["success"] or kind in ("oracle", "naive"):
467
+ break
468
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_split_calibration.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Two-workstation packing: calibration transfer, collateral damage, geometric fit.
2
+
3
+ A repeatable command-coordinate calibration varies with workstation (sign of y),
4
+ not with phase or policy. No object poses are written after reset. Learning a
5
+ far-workstation correction and blindly reusing it at the near destination can
6
+ undo the earlier placement. A long module must also be aligned with its tray.
7
+ """
8
+ import numpy as np
9
+ import xml.etree.ElementTree as ET
10
+ from .. import envs
11
+ from ..bddl import write_bddl
12
+ from ..objects import box_xml,bin_xml,register_generated
13
+ from ..skills import Skills
14
+ from ..task_base import LFFTask,register_task
15
+ from .lh_shelf_droop import jar_xml,JAR_H,KNOB_Z
16
+ from .lh_lid_box import mark_xml
17
+
18
+ RED='module_red_1';BLUE='module_blue_1';HALF=np.array([.045,.012,.012])
19
+ class SplitSkills(Skills):
20
+ def __init__(self,env,task,recorder=None):
21
+ super().__init__(env,recorder=recorder);self.task=task;self.correction=np.zeros(3)
22
+ def move_to(self,target,*a,**kw):
23
+ q=np.array(target)-self.correction
24
+ self.bias=np.array(self.task.inst['far_bias'] if q[1]>.04 else self.task.inst['near_bias'])
25
+ rep=super().move_to(q,*a,**kw);rep['pos']=np.round(self.reported_eef_pos(),4).tolist();return rep
26
+ def reported_eef_pos(self):return self.eef_pos()-self.bias
27
+ def _act(self,dpos,drot,grip):
28
+ super()._act(dpos,drot,grip);self.task.monitor_step()
29
+
30
+ @register_task
31
+ class SplitCalibration(LFFTask):
32
+ name='lh_split_calibration';level='L1';category='system_identification';failure_causes=('L1','L2','L4');failure_types=failure_causes
33
+ protocol='cross';max_attempts=5;agent_max_steps=240
34
+ instruction=('Prepare the two modules for handover: stand the red module on its red square, and fit the entire '
35
+ 'long blue module inside the narrow tray. Leave both released and stable, with the gripper open '
36
+ 'and clear. The red module has a graspable top knob. The work areas are on opposite sides of the desk.')
37
+ instruction_indirect=('Stand the tall module with the round top on its matching square, and fit the entire elongated module inside the narrow open tray. Leave both released and stable, with the gripper open and clear.');capabilities=('Perceive','Reason','Plan','Restore')
38
+ def make_bddl(self):
39
+ rr=ET.fromstring(jar_xml('split_red',(.8,.15,.1,1)))
40
+ for g in rr.findall('.//geom'):
41
+ if g.get('type')=='box':
42
+ sz=np.fromstring(g.get('size'),sep=' ');sz[:2]*=.6;g.set('size',' '.join(map(str,sz)))
43
+ r=register_generated('LffSplitRed',ET.tostring(rr,encoding='unicode'))
44
+ b=register_generated('LffSplitBlue',box_xml('split_blue',HALF,(.1,.3,.85,1),density=1000))
45
+ tray=register_generated('LffSplitTray',bin_xml('split_tray',(.051,.019),.022),free=False)
46
+ mark=register_generated('LffSplitMark',mark_xml('split_mark',(.8,.1,.1,1)),free=False)
47
+ return write_bddl(self.name,self.instruction,[(RED,r,'red_region',(-.36,-.16,-.35,-.15)),(BLUE,b,'blue_region',(-.17,.23,-.16,.24))],
48
+ [('tray_1',tray,'tray_region',(.2,-.3,.21,-.29)),('mark_1',mark,'mark_region',(.2,.3,.21,.31))])
49
+ def sample_instance(self,seed):
50
+ rng=np.random.default_rng(seed);v=float(rng.uniform(.053,.057))
51
+ return dict(seed=seed,near_bias=[0,-v,0],far_bias=[0,v,0],red_xy=[-.35,-.12],blue_xy=[-.16,.24],red_goal=[-.22,-.24],blue_goal=[-.21,-.13])
52
+ def apply_instance(self,i):
53
+ self.inst=i;m=self.env.sim.model
54
+ envs.set_obj_pose(self.env,RED,[*i['red_xy'],envs.TABLE_Z+JAR_H/2+.001]);envs.scale_mass(self.env,RED,.08)
55
+ envs.set_obj_pose(self.env,BLUE,[*i['blue_xy'],envs.TABLE_Z+HALF[2]+.001],yaw=np.pi/2)
56
+ for name,xy,z in [('tray_1',i['blue_goal'],.914),('mark_1',i['red_goal'],.901)]:
57
+ m.body_pos[m.body_name2id(self.env.fixtures_dict[name].root_body)]=[*xy,z]
58
+ def reset_instance(self,i,recorder=None):
59
+ np.random.seed(i['seed']);self.mon=None;self.env.reset();self.apply_instance(i);self.env.sim.forward();envs.settle(self.env,10)
60
+ self.sk=SplitSkills(self.env,self,recorder);self.trace=[];self.phase_hook=None;self.traps={k:False for k in self.failure_causes};self.recovered=self.traps.copy()
61
+ self.mon=dict(red_ever=False,red_lost=False,red_restored=False);return self.sk
62
+ def red_ok(self):
63
+ p=envs.obj_pos(self.env,RED);R=self.env.sim.data.body_xmat[envs.body_id(self.env,RED)].reshape(3,3)
64
+ return bool(np.linalg.norm(p[:2]-self.inst['red_goal'])<.022 and R[2,2]>.96 and abs(p[2]-(.9+JAR_H/2))<.008 and not self.sk.holding(RED))
65
+ def blue_ok(self):
66
+ p=envs.obj_pos(self.env,BLUE);R=self.env.sim.data.body_xmat[envs.body_id(self.env,BLUE)].reshape(3,3)
67
+ corners=np.array([p+R@(HALF*[a,b,c]) for a in (-1,1) for b in (-1,1) for c in (-1,1)])
68
+ return bool(np.all(np.abs(corners[:,:2]-self.inst['blue_goal'])<[.052,.020]) and corners[:,2].max()<.936 and corners[:,2].min()>.903 and not self.sk.holding(BLUE))
69
+ def monitor_step(self):
70
+ if self.mon is None:return
71
+ ok=self.red_ok()
72
+ if ok:
73
+ if self.mon['red_lost']:self.mon['red_restored']=True
74
+ self.mon['red_ever']=True
75
+ elif self.mon['red_ever'] and not self.sk.holding(RED):self.mon['red_lost']=True
76
+ def label(self,text):
77
+ r=dict(text=text,step=self.sk.n_steps,red_ok=self.red_ok(),blue_ok=self.blue_ok(),red_xyz=envs.obj_pos(self.env,RED).tolist(),blue_xyz=envs.obj_pos(self.env,BLUE).tolist());self.trace.append(r)
78
+ if self.phase_hook:self.phase_hook(text,r)
79
+ def observe_offset(self,xy):
80
+ s=self.sk;q=np.array([*xy,1.18]);s.move_to(q);return (s.eef_pos()-q+s.correction)*[1,1,0]
81
+ def pick(self,name,yaw=None):
82
+ s=self.sk;p=envs.obj_pos(self.env,name);R=self.env.sim.data.body_xmat[envs.body_id(self.env,name)].reshape(3,3)
83
+ if name==RED:
84
+ goal=p+R@np.array([0,0,KNOB_Z-JAR_H/2]);yaw=float(np.arctan2(R[1,2],R[0,2])) if R[2,2]<.7 else 0
85
+ else:
86
+ goal=p.copy();yaw=float(np.arctan2(R[1,0],R[0,0])) if yaw is None else yaw
87
+ s.set_gripper(False,8);s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=150);s.set_gripper(True,20)
88
+ s.move_to([*goal[:2],1.20],speed=.1);s.hold(20);return bool(s.holding(name))
89
+ def place(self,name,xy,z,yaw):
90
+ s=self.sk;off=envs.obj_pos(self.env,name)-s.eef_pos();s.move_to([*s.eef_pos()[:2],1.20],yaw=yaw)
91
+ # Update the held offset after rotating the module.
92
+ off=envs.obj_pos(self.env,name)-s.eef_pos();goal=np.array([*xy,z])-off
93
+ s.move_to([*goal[:2],1.20],yaw=yaw);s.move_to(goal,yaw=yaw,speed=.08,max_steps=160)
94
+ s.set_gripper(False,12);s.move_to([*goal[:2],1.23]);s.hold(40)
95
+ def execute(self,i,p):
96
+ mode=p.get('mode','adaptive');s=self.sk
97
+ if mode=='blind':s.correction=np.array(p.get('jitter',[0,0,0]))
98
+ self.label('Two workstations: preserve earlier placements')
99
+ if mode=='oracle':near=np.array(i['near_bias'])
100
+ else:
101
+ near=self.observe_offset(i['red_xy']);ok=self.pick(RED);self.traps['L1']=not ok;self.label('L1: near-workstation grasp missed')
102
+ if mode in ('naive','blind') and not ok:return
103
+ if mode not in ('naive','blind'):s.correction=near
104
+ if not self.pick(RED):self.label('Red pickup failed');return
105
+ self.recovered['L1']=True;self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.label('Red module placed correctly')
106
+ if mode=='oracle':far=np.array(i['far_bias'])
107
+ else:
108
+ ok=self.pick(BLUE);self.label('L1 transfer: near correction fails at the far workstation')
109
+ if mode in ('naive','blind'):
110
+ if not ok:return
111
+ self.place(BLUE,i['blue_goal'],.922,np.pi/2);return
112
+ far=self.observe_offset(i['blue_xy'])
113
+ s.correction=far
114
+ if not self.pick(BLUE):self.label('Far pickup failed');return
115
+ if mode!='oracle':
116
+ self.place(BLUE,i['blue_goal'],.922,np.pi/2);self.traps['L2']=bool(not self.red_ok());self.label('L2: reusing far correction disturbed the red module')
117
+ s.correction=near
118
+ if not self.pick(RED):self.label('Red restoration pickup failed');return
119
+ self.place(RED,[-.40,-.28],.9+JAR_H/2+.003,0);self.label('Clear the disturbed red module before recovering the blue module')
120
+ if not self.pick(BLUE):self.label('Blue recovery pickup failed');return
121
+ self.place(BLUE,i['blue_goal'],.922,np.pi/2);self.traps['L4']=not self.blue_ok();self.label('L4: the long module bridges the narrow tray')
122
+ if not self.pick(RED):return
123
+ self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);self.recovered['L2']=self.red_ok();self.label('L2 recovery: restored red using the near-workstation correction')
124
+ if not self.pick(BLUE):self.label('Blue alignment pickup failed');return
125
+ s.correction=near;self.place(BLUE,i['blue_goal'],.920,0);self.recovered['L4']=self.blue_ok();self.label('Aligned module fits; recheck both completed placements')
126
+ if not self.red_ok():
127
+ if self.pick(RED):self.place(RED,i['red_goal'],.9+JAR_H/2+.003,0)
128
+ s.set_gripper(False,8);s.move_to([-.40,-.05,1.25]);s.hold(30)
129
+ def outcome(self,i):
130
+ self.sk.hold(100);stages=dict(red_on_mark=self.red_ok(),blue_in_tray=self.blue_ok(),gripper_open=bool(self.sk.grip<0),gripper_clear=bool(self.sk.eef_pos()[2]>1.13))
131
+ static=all(np.linalg.norm(self.env.sim.data.qvel[envs.free_joint_addr(self.env,n)[1]:envs.free_joint_addr(self.env,n)[1]+6])<.06 for n in (RED,BLUE))
132
+ return dict(success=bool(all(stages.values()) and static),stages=stages,static=bool(static),traps=self.traps.copy(),recovered=self.recovered.copy(),detail=str(stages))
133
+ def default_params(self,i):return {'mode':'naive'}
134
+ def oracle_params(self,i):return {'mode':'oracle'}
135
+ def adapt_params(self,i,h):return {'mode':'adaptive'}
136
+ def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None):
137
+ hist=[]
138
+ for n in range((k or 5) if kind=='blind' else 1):
139
+ self.reset_instance(inst);params={'mode':kind};self.execute(inst,params);o=self.outcome(inst);hist.append(dict(attempt=n+1,params=params,outcome=o))
140
+ if on_attempt:on_attempt(n+1,self.env,o)
141
+ if o['success']:break
142
+ return hist
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/batches.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "remaining_lh_auto_001_sonnet": {
3
+ "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source/runs/api/remaining_lh_auto_001_sonnet/manifest.json",
4
+ "supplement": true,
5
+ "selected_runs": 4,
6
+ "exported_runs": 4,
7
+ "note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config."
8
+ }
9
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/rejected.json ADDED
@@ -0,0 +1 @@
 
 
1
+ []
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/client/pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lffbench-client"
7
+ version = "0.1.0"
8
+ description = "LFF-Bench agent tools (robot / shell / view_images) for robot harness frameworks, via the episode's tool gateway"
9
+ requires-python = ">=3.8"
10
+ dependencies = []
11
+
12
+ [tool.setuptools]
13
+ packages = ["lffbench_client"]
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/evaluation_tool_caps.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "lh_desk_organizer": 460,
3
+ "lh_split_calibration": 340,
4
+ "lh_shim_relay": 600
5
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """LFF-Bench: a learn-from-failure benchmark for robot agents on LIBERO."""