PeterXie666 commited on
Commit
05ee179
·
verified ·
1 Parent(s): 28db670

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_000051_wrist_image.png +3 -0
  2. leaf/final/episode_000142.npz +3 -0
  3. leaf/final/episode_000316.npz +3 -0
  4. leaf/final/episode_000329.npz +3 -0
  5. leaf/final/episode_000354_image.png +3 -0
  6. leaf/final/episode_000562_image.png +3 -0
  7. leaf/final/episode_000565.npz +3 -0
  8. leaf/final/episode_000607_image.png +3 -0
  9. leaf/final/episode_000637_wrist_image.png +3 -0
  10. leaf/final/episode_001092_image.png +3 -0
  11. leaf/final/episode_001113_image.png +3 -0
  12. leaf/final/episode_001125_wrist_image.png +3 -0
  13. leaf/final/episode_001128_wrist_image.png +3 -0
  14. leaf/final/episode_001160.npz +3 -0
  15. leaf/final/episode_001170_wrist_image.png +3 -0
  16. leaf/final/episode_001238.npz +3 -0
  17. leaf/final/episode_001344.npz +3 -0
  18. leaf/final/episode_001403.npz +3 -0
  19. leaf/final/episode_001614_wrist_image.png +3 -0
  20. leaf/final/episode_001617.npz +3 -0
  21. leaf/final/episode_002054_wrist_image.png +3 -0
  22. leaf/final/episode_002113.npz +3 -0
  23. leaf/final/episode_002116_wrist_image.png +3 -0
  24. leaf/final/episode_002184.npz +3 -0
  25. leaf/final/episode_002429_image.png +3 -0
  26. leaf/final/episode_002492_image.png +3 -0
  27. leaf/final/episode_002531_wrist_image.png +3 -0
  28. leaf/final/episode_002555_image.png +3 -0
  29. leaf/final/episode_002559_image.png +3 -0
  30. leaf/final/episode_002615.npz +3 -0
  31. leaf/final/episode_002667.npz +3 -0
  32. leaf/final/episode_002758_image.png +3 -0
  33. leaf/final/episode_002940_wrist_image.png +3 -0
  34. leaf/final/episode_002964_image.png +3 -0
  35. leaf/final/episode_002989_image.png +3 -0
  36. leaf/final/episode_003282_wrist_image.png +3 -0
  37. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/batches.json +9 -0
  38. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/rejected.json +1 -0
  39. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/release/image_stats.json +1063 -0
  40. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/client/pyproject.toml +13 -0
  41. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/evaluation_tool_caps.json +5 -0
  42. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/__init__.py +1 -0
  43. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/bddl.py +66 -0
  44. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/envs.py +325 -0
  45. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/objects.py +98 -0
  46. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/skills.py +156 -0
  47. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/task_base.py +129 -0
  48. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/vla.py +293 -0
  49. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_cost.py +77 -0
  50. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/api_batch.py +709 -0
leaf/final/episode_000051_wrist_image.png ADDED

Git LFS Details

  • SHA256: 7a1d8cc31ceddc2dcf8966d9767d097083973a639bfce42a5ab455c0d84f3a2a
  • Pointer size: 130 Bytes
  • Size of remote file: 39.3 kB
leaf/final/episode_000142.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6c0702b573480a82846674d9b92131b95ad1c0ba51bda7e426526620d5493910
3
+ size 4046
leaf/final/episode_000316.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bbe26773b28a22fe79ce11b2eb07fb1ac86b870af9bc21e52fbd1338a74bbba
3
+ size 3630
leaf/final/episode_000329.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66d0ee14a46f9e5e2e75dd4a75728856b674a0a5f8d7408142f91e7efb7349dc
3
+ size 3734
leaf/final/episode_000354_image.png ADDED

Git LFS Details

  • SHA256: 3c1435df46665527fb3d4cb49687a35f77d2f22daf0ce687d62a3983569c7763
  • Pointer size: 130 Bytes
  • Size of remote file: 53.9 kB
leaf/final/episode_000562_image.png ADDED

Git LFS Details

  • SHA256: 1541a449c6643016b9ce5e0692afa02be1fc80ea55f8ee5b0152f6e09027a70e
  • Pointer size: 130 Bytes
  • Size of remote file: 60.3 kB
leaf/final/episode_000565.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee72f3b7f3a6b485167bb591550dec507cace9c1db0730dc19f3f928777567a0
3
+ size 3942
leaf/final/episode_000607_image.png ADDED

Git LFS Details

  • SHA256: 053a14585ba195c4c7d36bbc68918d533edcdfffc76968f4d4383041a2b8187e
  • Pointer size: 130 Bytes
  • Size of remote file: 54.4 kB
leaf/final/episode_000637_wrist_image.png ADDED

Git LFS Details

  • SHA256: ed45ff42421e983edd592325689f1ca279a6e4f493b35186a704fa5f937eb240
  • Pointer size: 130 Bytes
  • Size of remote file: 40.6 kB
leaf/final/episode_001092_image.png ADDED

Git LFS Details

  • SHA256: 27d568a9975b8ddcb441de3ccfdf307a6a80a45e63e54250c874a68ab93081cb
  • Pointer size: 130 Bytes
  • Size of remote file: 53.4 kB
leaf/final/episode_001113_image.png ADDED

Git LFS Details

  • SHA256: 5421b1ae6b7049e7eb984248649e3eacc2530b5d7a2c5c836847fd9729900d2e
  • Pointer size: 130 Bytes
  • Size of remote file: 58.7 kB
leaf/final/episode_001125_wrist_image.png ADDED

Git LFS Details

  • SHA256: e175ce23d94469abc910b772f7d26465cf50c11429fe7769bc65cf13bcc78d81
  • Pointer size: 130 Bytes
  • Size of remote file: 41 kB
leaf/final/episode_001128_wrist_image.png ADDED

Git LFS Details

  • SHA256: 13629b856b63224583fd5f14e9fef68c18f2ddc659bc9dd8a36c4b5f60d7d923
  • Pointer size: 130 Bytes
  • Size of remote file: 42.5 kB
leaf/final/episode_001160.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:650f758dea9edd93f199ef951c05635acb27f19d0056cf2dbd6563e349f0dc1f
3
+ size 3958
leaf/final/episode_001170_wrist_image.png ADDED

Git LFS Details

  • SHA256: 710c3c5f04685101ff8d36ef3ee551402e4a124863b69982bcc2aa0e82b4b6d8
  • Pointer size: 130 Bytes
  • Size of remote file: 26.3 kB
leaf/final/episode_001238.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:075753b508a33d4dfcb0876744a19d9eeed0f4fccef3fa8d562d6853acd371b1
3
+ size 4046
leaf/final/episode_001344.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4259a07d8d33057f1e673d789b46fb113502e55718734eb1caecadc4b4e0a0ac
3
+ size 3734
leaf/final/episode_001403.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9ae8d9c819c0ec64a93c103ed90f7b9f2d6c4eb1ca800f0faf04679fd75524c9
3
+ size 4046
leaf/final/episode_001614_wrist_image.png ADDED

Git LFS Details

  • SHA256: 69372b69c8e09fd62c7ddb2e50a1e240b78f1bf3306c9de4dea2622e83b8246b
  • Pointer size: 130 Bytes
  • Size of remote file: 38.9 kB
leaf/final/episode_001617.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8464240539704440ee6daa170b8c09369632952b5b5d6a6138f41edeb4cbafa
3
+ size 3958
leaf/final/episode_002054_wrist_image.png ADDED

Git LFS Details

  • SHA256: a0c72dc17f2239144f1964f2b07b1ef8c4dc8ee32d0d4a81dba2bc7d50e1bb9c
  • Pointer size: 130 Bytes
  • Size of remote file: 36.4 kB
leaf/final/episode_002113.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d1458ddfedd859d3b8f1d373ed1c64f863770faf76a6535defa9613336778f6
3
+ size 3734
leaf/final/episode_002116_wrist_image.png ADDED

Git LFS Details

  • SHA256: d52056cefb61bdcdefdfac48a4e3a140d752c7e748a25bbcb584f64e42fb4d35
  • Pointer size: 130 Bytes
  • Size of remote file: 37.7 kB
leaf/final/episode_002184.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26a45ff3680cd6969231931a28f68eea94e2e368cd980f5e01da518f5dcdd58e
3
+ size 3734
leaf/final/episode_002429_image.png ADDED

Git LFS Details

  • SHA256: 3e13d76cf5059263b7081bb20d8e73bc0a9b9707881159721552aa99c09d2604
  • Pointer size: 130 Bytes
  • Size of remote file: 58.3 kB
leaf/final/episode_002492_image.png ADDED

Git LFS Details

  • SHA256: 180458fea11888be52b214407294afc7e38b6fe578a033edc0bc67b7bbc302ef
  • Pointer size: 130 Bytes
  • Size of remote file: 57.6 kB
leaf/final/episode_002531_wrist_image.png ADDED

Git LFS Details

  • SHA256: b425f5c461b9408db726bb94d47132c98ec947bc554ea8bf4d09bfc9adbbe0b1
  • Pointer size: 130 Bytes
  • Size of remote file: 39.8 kB
leaf/final/episode_002555_image.png ADDED

Git LFS Details

  • SHA256: 28acca03e6af636067b0220ae66320220dc05555397093fe2d29741e81612418
  • Pointer size: 130 Bytes
  • Size of remote file: 60.6 kB
leaf/final/episode_002559_image.png ADDED

Git LFS Details

  • SHA256: 336b44574207078cb5a7a57dddd648a4bfebaff9073b0680729a90de6f996337
  • Pointer size: 130 Bytes
  • Size of remote file: 55.8 kB
leaf/final/episode_002615.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6376e0a0cb191777a75eba5a726859d1a91c47b0272da81888448e4b1b399f57
3
+ size 4046
leaf/final/episode_002667.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba38ecf14eb4fd86ac83cbc37b504cd5f6af5de93c9479e4ba042e42c30e6579
3
+ size 3630
leaf/final/episode_002758_image.png ADDED

Git LFS Details

  • SHA256: 450a7a6d4bca9977e9a5370058169ebc7dfe553db8b30631c7fb3c0bd1b1b0d2
  • Pointer size: 130 Bytes
  • Size of remote file: 53.6 kB
leaf/final/episode_002940_wrist_image.png ADDED

Git LFS Details

  • SHA256: 011c3a1a937efed64020d276dd0b311ed6daf1607f985f864b67595b7e23ca8b
  • Pointer size: 130 Bytes
  • Size of remote file: 49.4 kB
leaf/final/episode_002964_image.png ADDED

Git LFS Details

  • SHA256: 99b6ace42234c6bb391adbef1edf27d3ed6c58932e65d66af436deb4146f1331
  • Pointer size: 130 Bytes
  • Size of remote file: 56.6 kB
leaf/final/episode_002989_image.png ADDED

Git LFS Details

  • SHA256: 9be517d0c12019203b29e0df8517db145d37f7b6ca285bcee27d65fd11b7bd69
  • Pointer size: 130 Bytes
  • Size of remote file: 56 kB
leaf/final/episode_003282_wrist_image.png ADDED

Git LFS Details

  • SHA256: 262bab19583fe23bebe177849a2d3c89c691f0916fa57def5155cd125f14a11f
  • Pointer size: 130 Bytes
  • Size of remote file: 39.3 kB
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/batches.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "remaining_lh_20261103_gpt": {
3
+ "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source/runs/api/remaining_lh_20261103_gpt/manifest.json",
4
+ "supplement": true,
5
+ "selected_runs": 16,
6
+ "exported_runs": 16,
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_20261103_gpt/lff/rejected.json ADDED
@@ -0,0 +1 @@
 
 
1
+ []
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/release/image_stats.json ADDED
@@ -0,0 +1,1063 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "pass",
3
+ "created": "2026-11-05T05:38:37.731347+00:00",
4
+ "method": "Full RGB pixel histograms from distinct floor(n/4), floor(n/2), floor(3n/4) frames per episode; float64 moments and exact histogram quantiles. Samples are stratified by episode, not a full-frame census.",
5
+ "sample_frames_per_camera": {
6
+ "observation.images.image": 69,
7
+ "observation.images.wrist_image": 69
8
+ },
9
+ "old_zero_std_episode_camera_pairs": 46,
10
+ "old_global_image_stats": {
11
+ "observation.images.image": {
12
+ "min": [
13
+ [
14
+ [
15
+ 0.00392156862745098
16
+ ]
17
+ ],
18
+ [
19
+ [
20
+ 0.0
21
+ ]
22
+ ],
23
+ [
24
+ [
25
+ 0.0
26
+ ]
27
+ ]
28
+ ],
29
+ "max": [
30
+ [
31
+ [
32
+ 1.0
33
+ ]
34
+ ],
35
+ [
36
+ [
37
+ 1.0
38
+ ]
39
+ ],
40
+ [
41
+ [
42
+ 1.0
43
+ ]
44
+ ]
45
+ ],
46
+ "mean": [
47
+ [
48
+ [
49
+ 0.5518337354664362
50
+ ]
51
+ ],
52
+ [
53
+ [
54
+ 0.5110225017792045
55
+ ]
56
+ ],
57
+ [
58
+ [
59
+ 0.4641507158103812
60
+ ]
61
+ ]
62
+ ],
63
+ "std": [
64
+ [
65
+ [
66
+ 0.008071512139896393
67
+ ]
68
+ ],
69
+ [
70
+ [
71
+ 0.00846308103092671
72
+ ]
73
+ ],
74
+ [
75
+ [
76
+ 0.010837850185378806
77
+ ]
78
+ ]
79
+ ],
80
+ "count": [
81
+ 13136
82
+ ],
83
+ "q01": [
84
+ [
85
+ [
86
+ 0.08555295202553163
87
+ ]
88
+ ],
89
+ [
90
+ [
91
+ 0.08811258418705974
92
+ ]
93
+ ],
94
+ [
95
+ [
96
+ 0.07407058543164063
97
+ ]
98
+ ]
99
+ ],
100
+ "q10": [
101
+ [
102
+ [
103
+ 0.3721573133260667
104
+ ]
105
+ ],
106
+ [
107
+ [
108
+ 0.34241750221396283
109
+ ]
110
+ ],
111
+ [
112
+ [
113
+ 0.24073702702942446
114
+ ]
115
+ ]
116
+ ],
117
+ "q50": [
118
+ [
119
+ [
120
+ 0.5713821777070321
121
+ ]
122
+ ],
123
+ [
124
+ [
125
+ 0.5246511904054232
126
+ ]
127
+ ],
128
+ [
129
+ [
130
+ 0.4786213575653072
131
+ ]
132
+ ]
133
+ ],
134
+ "q90": [
135
+ [
136
+ [
137
+ 0.7529000708324947
138
+ ]
139
+ ],
140
+ [
141
+ [
142
+ 0.6867050300742843
143
+ ]
144
+ ],
145
+ [
146
+ [
147
+ 0.6195650053907398
148
+ ]
149
+ ]
150
+ ],
151
+ "q99": [
152
+ [
153
+ [
154
+ 0.7871652705844749
155
+ ]
156
+ ],
157
+ [
158
+ [
159
+ 0.7221066469966779
160
+ ]
161
+ ],
162
+ [
163
+ [
164
+ 0.6634723876291312
165
+ ]
166
+ ]
167
+ ]
168
+ },
169
+ "observation.images.wrist_image": {
170
+ "min": [
171
+ [
172
+ [
173
+ 0.0
174
+ ]
175
+ ],
176
+ [
177
+ [
178
+ 0.0
179
+ ]
180
+ ],
181
+ [
182
+ [
183
+ 0.0
184
+ ]
185
+ ]
186
+ ],
187
+ "max": [
188
+ [
189
+ [
190
+ 1.0
191
+ ]
192
+ ],
193
+ [
194
+ [
195
+ 1.0
196
+ ]
197
+ ],
198
+ [
199
+ [
200
+ 1.0
201
+ ]
202
+ ]
203
+ ],
204
+ "mean": [
205
+ [
206
+ [
207
+ 0.581883063442413
208
+ ]
209
+ ],
210
+ [
211
+ [
212
+ 0.5208961042948215
213
+ ]
214
+ ],
215
+ [
216
+ [
217
+ 0.4373016889252863
218
+ ]
219
+ ]
220
+ ],
221
+ "std": [
222
+ [
223
+ [
224
+ 0.0150755872245458
225
+ ]
226
+ ],
227
+ [
228
+ [
229
+ 0.014670793375984969
230
+ ]
231
+ ],
232
+ [
233
+ [
234
+ 0.04725642736713211
235
+ ]
236
+ ]
237
+ ],
238
+ "count": [
239
+ 13136
240
+ ],
241
+ "q01": [
242
+ [
243
+ [
244
+ 0.05036454952016912
245
+ ]
246
+ ],
247
+ [
248
+ [
249
+ 0.048966695573603905
250
+ ]
251
+ ],
252
+ [
253
+ [
254
+ 0.03381626569217841
255
+ ]
256
+ ]
257
+ ],
258
+ "q10": [
259
+ [
260
+ [
261
+ 0.1608971040539028
262
+ ]
263
+ ],
264
+ [
265
+ [
266
+ 0.15988876717846842
267
+ ]
268
+ ],
269
+ [
270
+ [
271
+ 0.13280998265533417
272
+ ]
273
+ ]
274
+ ],
275
+ "q50": [
276
+ [
277
+ [
278
+ 0.7077335785842285
279
+ ]
280
+ ],
281
+ [
282
+ [
283
+ 0.6293251874339659
284
+ ]
285
+ ],
286
+ [
287
+ [
288
+ 0.5329467558867387
289
+ ]
290
+ ]
291
+ ],
292
+ "q90": [
293
+ [
294
+ [
295
+ 0.7777316015318392
296
+ ]
297
+ ],
298
+ [
299
+ [
300
+ 0.70816676409485
301
+ ]
302
+ ],
303
+ [
304
+ [
305
+ 0.6374599276734542
306
+ ]
307
+ ]
308
+ ],
309
+ "q99": [
310
+ [
311
+ [
312
+ 0.8324987865827171
313
+ ]
314
+ ],
315
+ [
316
+ [
317
+ 0.7548791907102623
318
+ ]
319
+ ],
320
+ [
321
+ [
322
+ 0.7063756412177741
323
+ ]
324
+ ]
325
+ ]
326
+ }
327
+ },
328
+ "new_global_image_stats": {
329
+ "observation.images.image": {
330
+ "count": [
331
+ 69
332
+ ],
333
+ "mean": [
334
+ [
335
+ [
336
+ 0.5545126886522272
337
+ ]
338
+ ],
339
+ [
340
+ [
341
+ 0.513611042773937
342
+ ]
343
+ ],
344
+ [
345
+ [
346
+ 0.4668434830340651
347
+ ]
348
+ ]
349
+ ],
350
+ "std": [
351
+ [
352
+ [
353
+ 0.16925766986209442
354
+ ]
355
+ ],
356
+ [
357
+ [
358
+ 0.1493408020724704
359
+ ]
360
+ ],
361
+ [
362
+ [
363
+ 0.13791802835577766
364
+ ]
365
+ ]
366
+ ],
367
+ "min": [
368
+ [
369
+ [
370
+ 0.00392156862745098
371
+ ]
372
+ ],
373
+ [
374
+ [
375
+ 0.00392156862745098
376
+ ]
377
+ ],
378
+ [
379
+ [
380
+ 0.00392156862745098
381
+ ]
382
+ ]
383
+ ],
384
+ "max": [
385
+ [
386
+ [
387
+ 1.0
388
+ ]
389
+ ],
390
+ [
391
+ [
392
+ 1.0
393
+ ]
394
+ ],
395
+ [
396
+ [
397
+ 1.0
398
+ ]
399
+ ]
400
+ ],
401
+ "q01": [
402
+ [
403
+ [
404
+ 0.08627450980392157
405
+ ]
406
+ ],
407
+ [
408
+ [
409
+ 0.09019607843137255
410
+ ]
411
+ ],
412
+ [
413
+ [
414
+ 0.0784313725490196
415
+ ]
416
+ ]
417
+ ],
418
+ "q10": [
419
+ [
420
+ [
421
+ 0.3843137254901961
422
+ ]
423
+ ],
424
+ [
425
+ [
426
+ 0.33725490196078434
427
+ ]
428
+ ],
429
+ [
430
+ [
431
+ 0.23529411764705882
432
+ ]
433
+ ]
434
+ ],
435
+ "q50": [
436
+ [
437
+ [
438
+ 0.5803921568627451
439
+ ]
440
+ ],
441
+ [
442
+ [
443
+ 0.5294117647058824
444
+ ]
445
+ ],
446
+ [
447
+ [
448
+ 0.4823529411764706
449
+ ]
450
+ ]
451
+ ],
452
+ "q90": [
453
+ [
454
+ [
455
+ 0.7529411764705882
456
+ ]
457
+ ],
458
+ [
459
+ [
460
+ 0.6862745098039216
461
+ ]
462
+ ],
463
+ [
464
+ [
465
+ 0.6196078431372549
466
+ ]
467
+ ]
468
+ ],
469
+ "q99": [
470
+ [
471
+ [
472
+ 0.7843137254901961
473
+ ]
474
+ ],
475
+ [
476
+ [
477
+ 0.7215686274509804
478
+ ]
479
+ ],
480
+ [
481
+ [
482
+ 0.6588235294117647
483
+ ]
484
+ ]
485
+ ]
486
+ },
487
+ "observation.images.wrist_image": {
488
+ "count": [
489
+ 69
490
+ ],
491
+ "mean": [
492
+ [
493
+ [
494
+ 0.5788789099270256
495
+ ]
496
+ ],
497
+ [
498
+ [
499
+ 0.5180312863193002
500
+ ]
501
+ ],
502
+ [
503
+ [
504
+ 0.437770133033399
505
+ ]
506
+ ]
507
+ ],
508
+ "std": [
509
+ [
510
+ [
511
+ 0.2428978534127171
512
+ ]
513
+ ],
514
+ [
515
+ [
516
+ 0.2145116570343384
517
+ ]
518
+ ],
519
+ [
520
+ [
521
+ 0.20944515262886976
522
+ ]
523
+ ]
524
+ ],
525
+ "min": [
526
+ [
527
+ [
528
+ 0.0
529
+ ]
530
+ ],
531
+ [
532
+ [
533
+ 0.0
534
+ ]
535
+ ],
536
+ [
537
+ [
538
+ 0.0
539
+ ]
540
+ ]
541
+ ],
542
+ "max": [
543
+ [
544
+ [
545
+ 1.0
546
+ ]
547
+ ],
548
+ [
549
+ [
550
+ 1.0
551
+ ]
552
+ ],
553
+ [
554
+ [
555
+ 1.0
556
+ ]
557
+ ]
558
+ ],
559
+ "q01": [
560
+ [
561
+ [
562
+ 0.050980392156862744
563
+ ]
564
+ ],
565
+ [
566
+ [
567
+ 0.047058823529411764
568
+ ]
569
+ ],
570
+ [
571
+ [
572
+ 0.03137254901960784
573
+ ]
574
+ ]
575
+ ],
576
+ "q10": [
577
+ [
578
+ [
579
+ 0.1803921568627451
580
+ ]
581
+ ],
582
+ [
583
+ [
584
+ 0.1843137254901961
585
+ ]
586
+ ],
587
+ [
588
+ [
589
+ 0.10588235294117647
590
+ ]
591
+ ]
592
+ ],
593
+ "q50": [
594
+ [
595
+ [
596
+ 0.7058823529411765
597
+ ]
598
+ ],
599
+ [
600
+ [
601
+ 0.6352941176470588
602
+ ]
603
+ ],
604
+ [
605
+ [
606
+ 0.5647058823529412
607
+ ]
608
+ ]
609
+ ],
610
+ "q90": [
611
+ [
612
+ [
613
+ 0.7764705882352941
614
+ ]
615
+ ],
616
+ [
617
+ [
618
+ 0.7058823529411765
619
+ ]
620
+ ],
621
+ [
622
+ [
623
+ 0.6352941176470588
624
+ ]
625
+ ]
626
+ ],
627
+ "q99": [
628
+ [
629
+ [
630
+ 0.8235294117647058
631
+ ]
632
+ ],
633
+ [
634
+ [
635
+ 0.7372549019607844
636
+ ]
637
+ ],
638
+ [
639
+ [
640
+ 0.7098039215686275
641
+ ]
642
+ ]
643
+ ]
644
+ }
645
+ },
646
+ "samples": [
647
+ {
648
+ "camera": "observation.images.image",
649
+ "episode_index": 0,
650
+ "frame_indices": [
651
+ 1546,
652
+ 3093,
653
+ 4639
654
+ ]
655
+ },
656
+ {
657
+ "camera": "observation.images.wrist_image",
658
+ "episode_index": 0,
659
+ "frame_indices": [
660
+ 1546,
661
+ 3093,
662
+ 4639
663
+ ]
664
+ },
665
+ {
666
+ "camera": "observation.images.image",
667
+ "episode_index": 1,
668
+ "frame_indices": [
669
+ 2005,
670
+ 4011,
671
+ 6017
672
+ ]
673
+ },
674
+ {
675
+ "camera": "observation.images.wrist_image",
676
+ "episode_index": 1,
677
+ "frame_indices": [
678
+ 2005,
679
+ 4011,
680
+ 6017
681
+ ]
682
+ },
683
+ {
684
+ "camera": "observation.images.image",
685
+ "episode_index": 2,
686
+ "frame_indices": [
687
+ 3002,
688
+ 6005,
689
+ 9007
690
+ ]
691
+ },
692
+ {
693
+ "camera": "observation.images.wrist_image",
694
+ "episode_index": 2,
695
+ "frame_indices": [
696
+ 3002,
697
+ 6005,
698
+ 9007
699
+ ]
700
+ },
701
+ {
702
+ "camera": "observation.images.image",
703
+ "episode_index": 3,
704
+ "frame_indices": [
705
+ 563,
706
+ 1127,
707
+ 1690
708
+ ]
709
+ },
710
+ {
711
+ "camera": "observation.images.wrist_image",
712
+ "episode_index": 3,
713
+ "frame_indices": [
714
+ 563,
715
+ 1127,
716
+ 1690
717
+ ]
718
+ },
719
+ {
720
+ "camera": "observation.images.image",
721
+ "episode_index": 4,
722
+ "frame_indices": [
723
+ 515,
724
+ 1030,
725
+ 1545
726
+ ]
727
+ },
728
+ {
729
+ "camera": "observation.images.wrist_image",
730
+ "episode_index": 4,
731
+ "frame_indices": [
732
+ 515,
733
+ 1030,
734
+ 1545
735
+ ]
736
+ },
737
+ {
738
+ "camera": "observation.images.image",
739
+ "episode_index": 5,
740
+ "frame_indices": [
741
+ 267,
742
+ 534,
743
+ 801
744
+ ]
745
+ },
746
+ {
747
+ "camera": "observation.images.wrist_image",
748
+ "episode_index": 5,
749
+ "frame_indices": [
750
+ 267,
751
+ 534,
752
+ 801
753
+ ]
754
+ },
755
+ {
756
+ "camera": "observation.images.image",
757
+ "episode_index": 6,
758
+ "frame_indices": [
759
+ 346,
760
+ 693,
761
+ 1040
762
+ ]
763
+ },
764
+ {
765
+ "camera": "observation.images.wrist_image",
766
+ "episode_index": 6,
767
+ "frame_indices": [
768
+ 346,
769
+ 693,
770
+ 1040
771
+ ]
772
+ },
773
+ {
774
+ "camera": "observation.images.image",
775
+ "episode_index": 7,
776
+ "frame_indices": [
777
+ 333,
778
+ 667,
779
+ 1001
780
+ ]
781
+ },
782
+ {
783
+ "camera": "observation.images.wrist_image",
784
+ "episode_index": 7,
785
+ "frame_indices": [
786
+ 333,
787
+ 667,
788
+ 1001
789
+ ]
790
+ },
791
+ {
792
+ "camera": "observation.images.image",
793
+ "episode_index": 8,
794
+ "frame_indices": [
795
+ 1382,
796
+ 2765,
797
+ 4148
798
+ ]
799
+ },
800
+ {
801
+ "camera": "observation.images.wrist_image",
802
+ "episode_index": 8,
803
+ "frame_indices": [
804
+ 1382,
805
+ 2765,
806
+ 4148
807
+ ]
808
+ },
809
+ {
810
+ "camera": "observation.images.image",
811
+ "episode_index": 9,
812
+ "frame_indices": [
813
+ 918,
814
+ 1837,
815
+ 2756
816
+ ]
817
+ },
818
+ {
819
+ "camera": "observation.images.wrist_image",
820
+ "episode_index": 9,
821
+ "frame_indices": [
822
+ 918,
823
+ 1837,
824
+ 2756
825
+ ]
826
+ },
827
+ {
828
+ "camera": "observation.images.image",
829
+ "episode_index": 10,
830
+ "frame_indices": [
831
+ 212,
832
+ 425,
833
+ 638
834
+ ]
835
+ },
836
+ {
837
+ "camera": "observation.images.wrist_image",
838
+ "episode_index": 10,
839
+ "frame_indices": [
840
+ 212,
841
+ 425,
842
+ 638
843
+ ]
844
+ },
845
+ {
846
+ "camera": "observation.images.image",
847
+ "episode_index": 11,
848
+ "frame_indices": [
849
+ 1269,
850
+ 2539,
851
+ 3809
852
+ ]
853
+ },
854
+ {
855
+ "camera": "observation.images.wrist_image",
856
+ "episode_index": 11,
857
+ "frame_indices": [
858
+ 1269,
859
+ 2539,
860
+ 3809
861
+ ]
862
+ },
863
+ {
864
+ "camera": "observation.images.image",
865
+ "episode_index": 12,
866
+ "frame_indices": [
867
+ 224,
868
+ 449,
869
+ 674
870
+ ]
871
+ },
872
+ {
873
+ "camera": "observation.images.wrist_image",
874
+ "episode_index": 12,
875
+ "frame_indices": [
876
+ 224,
877
+ 449,
878
+ 674
879
+ ]
880
+ },
881
+ {
882
+ "camera": "observation.images.image",
883
+ "episode_index": 13,
884
+ "frame_indices": [
885
+ 5177,
886
+ 10355,
887
+ 15533
888
+ ]
889
+ },
890
+ {
891
+ "camera": "observation.images.wrist_image",
892
+ "episode_index": 13,
893
+ "frame_indices": [
894
+ 5177,
895
+ 10355,
896
+ 15533
897
+ ]
898
+ },
899
+ {
900
+ "camera": "observation.images.image",
901
+ "episode_index": 14,
902
+ "frame_indices": [
903
+ 2049,
904
+ 4098,
905
+ 6147
906
+ ]
907
+ },
908
+ {
909
+ "camera": "observation.images.wrist_image",
910
+ "episode_index": 14,
911
+ "frame_indices": [
912
+ 2049,
913
+ 4098,
914
+ 6147
915
+ ]
916
+ },
917
+ {
918
+ "camera": "observation.images.image",
919
+ "episode_index": 15,
920
+ "frame_indices": [
921
+ 294,
922
+ 589,
923
+ 883
924
+ ]
925
+ },
926
+ {
927
+ "camera": "observation.images.wrist_image",
928
+ "episode_index": 15,
929
+ "frame_indices": [
930
+ 294,
931
+ 589,
932
+ 883
933
+ ]
934
+ },
935
+ {
936
+ "camera": "observation.images.image",
937
+ "episode_index": 16,
938
+ "frame_indices": [
939
+ 3748,
940
+ 7497,
941
+ 11246
942
+ ]
943
+ },
944
+ {
945
+ "camera": "observation.images.wrist_image",
946
+ "episode_index": 16,
947
+ "frame_indices": [
948
+ 3748,
949
+ 7497,
950
+ 11246
951
+ ]
952
+ },
953
+ {
954
+ "camera": "observation.images.image",
955
+ "episode_index": 17,
956
+ "frame_indices": [
957
+ 1550,
958
+ 3101,
959
+ 4652
960
+ ]
961
+ },
962
+ {
963
+ "camera": "observation.images.wrist_image",
964
+ "episode_index": 17,
965
+ "frame_indices": [
966
+ 1550,
967
+ 3101,
968
+ 4652
969
+ ]
970
+ },
971
+ {
972
+ "camera": "observation.images.image",
973
+ "episode_index": 18,
974
+ "frame_indices": [
975
+ 614,
976
+ 1229,
977
+ 1844
978
+ ]
979
+ },
980
+ {
981
+ "camera": "observation.images.wrist_image",
982
+ "episode_index": 18,
983
+ "frame_indices": [
984
+ 614,
985
+ 1229,
986
+ 1844
987
+ ]
988
+ },
989
+ {
990
+ "camera": "observation.images.image",
991
+ "episode_index": 19,
992
+ "frame_indices": [
993
+ 2292,
994
+ 4584,
995
+ 6876
996
+ ]
997
+ },
998
+ {
999
+ "camera": "observation.images.wrist_image",
1000
+ "episode_index": 19,
1001
+ "frame_indices": [
1002
+ 2292,
1003
+ 4584,
1004
+ 6876
1005
+ ]
1006
+ },
1007
+ {
1008
+ "camera": "observation.images.image",
1009
+ "episode_index": 20,
1010
+ "frame_indices": [
1011
+ 342,
1012
+ 684,
1013
+ 1026
1014
+ ]
1015
+ },
1016
+ {
1017
+ "camera": "observation.images.wrist_image",
1018
+ "episode_index": 20,
1019
+ "frame_indices": [
1020
+ 342,
1021
+ 684,
1022
+ 1026
1023
+ ]
1024
+ },
1025
+ {
1026
+ "camera": "observation.images.image",
1027
+ "episode_index": 21,
1028
+ "frame_indices": [
1029
+ 794,
1030
+ 1589,
1031
+ 2383
1032
+ ]
1033
+ },
1034
+ {
1035
+ "camera": "observation.images.wrist_image",
1036
+ "episode_index": 21,
1037
+ "frame_indices": [
1038
+ 794,
1039
+ 1589,
1040
+ 2383
1041
+ ]
1042
+ },
1043
+ {
1044
+ "camera": "observation.images.image",
1045
+ "episode_index": 22,
1046
+ "frame_indices": [
1047
+ 670,
1048
+ 1341,
1049
+ 2012
1050
+ ]
1051
+ },
1052
+ {
1053
+ "camera": "observation.images.wrist_image",
1054
+ "episode_index": 22,
1055
+ "frame_indices": [
1056
+ 670,
1057
+ 1341,
1058
+ 2012
1059
+ ]
1060
+ }
1061
+ ],
1062
+ "wall_seconds": 9.705127477645874
1063
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/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_20261103_gpt/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_20261103_gpt/lff/source_closure/lffbench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """LFF-Bench: a learn-from-failure benchmark for robot agents on LIBERO."""
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/bddl.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tiny BDDL writer for tabletop problems. Layout is overridden at reset by the task, so the
2
+ regions here only need to be valid placement areas."""
3
+ import os
4
+
5
+ from .objects import GEN_DIR
6
+
7
+
8
+ def region(name, x0, y0, x1, y1, yaw=None):
9
+ s = f""" ({name}
10
+ (:target main_table)
11
+ (:ranges (
12
+ ({x0} {y0} {x1} {y1})
13
+ )
14
+ )"""
15
+ if yaw is not None:
16
+ s += f"""
17
+ (:yaw_rotation (
18
+ ({yaw} {yaw})
19
+ )
20
+ )"""
21
+ return s + "\n )\n"
22
+
23
+
24
+ def write_bddl(task_name, language, objects, fixtures=(), extra_regions="", goal="(And)"):
25
+ """objects / fixtures: list of (instance_name, category, region_name, (x0,y0,x1,y1))."""
26
+ regs = ""
27
+ for inst, cat, rname, box in list(objects) + list(fixtures):
28
+ regs += region(rname, *box)
29
+ regs += extra_regions
30
+ fx = "\n".join(f" {i} - {c}" for i, c, _, _ in fixtures)
31
+ ob = "\n".join(f" {i} - {c}" for i, c, _, _ in objects)
32
+ init = "\n".join(f" (On {i} main_table_{r})" for i, _, r, _ in list(objects) + list(fixtures))
33
+ text = f"""(define (problem LIBERO_Tabletop_Manipulation)
34
+ (:domain robosuite)
35
+ (:language {language})
36
+ (:regions
37
+ {regs} )
38
+
39
+ (:fixtures
40
+ main_table - table
41
+ {fx}
42
+ )
43
+
44
+ (:objects
45
+ {ob}
46
+ )
47
+
48
+ (:obj_of_interest
49
+ )
50
+
51
+ (:init
52
+ {init}
53
+ )
54
+
55
+ (:goal
56
+ {goal}
57
+ )
58
+
59
+ )
60
+ """
61
+ path = os.path.join(GEN_DIR, f"{task_name}.bddl")
62
+ tmp = f"{path}.{os.getpid()}.tmp" # atomic: concurrent builders must never read a half-written file
63
+ with open(tmp, "w") as f:
64
+ f.write(text)
65
+ os.replace(tmp, path)
66
+ return path
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/envs.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Environment construction and low-level sim helpers on top of LIBERO / robosuite."""
2
+ import os
3
+
4
+ os.environ.setdefault("MUJOCO_GL", "osmesa")
5
+ os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
6
+ # LIBERO reads its paths from <LIBERO_CONFIG_PATH>/config.yaml (written by setup/install.sh into <repo>/.libero)
7
+ os.environ.setdefault("LIBERO_CONFIG_PATH", os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".libero"))
8
+
9
+ import numpy as np
10
+
11
+ TABLE_Z = 0.90 # LIBERO main_table top surface (table_offset z)
12
+ # Upper limit of the Panda elbow (robot0_joint4; stock -0.0698). The arm is fully stretched at about -0.47 rad; a fast
13
+ # move out of a far pose could carry the elbow past that into (-0.47, -0.07], where the OSC's only way to shorten the
14
+ # arm runs into the stock limit and every later move stops 4-17 cm short for the rest of the attempt (measured
15
+ # 2026-10-19: 50 of 160 targets of the workspace box; 44 of 714 logged LA attempts). Capping the joint keeps the elbow
16
+ # on the normal side: reach is unchanged, and no scripted oracle / naive run of the main set goes above -0.73.
17
+ ELBOW_Q4_MAX = -0.55
18
+
19
+
20
+ def make_env(bddl_path, cam_res=256, cams=("agentview", "robot0_eye_in_hand"), depth=False, controller=None):
21
+ """Build a LIBERO env from a BDDL file without camera rendering on every step.
22
+
23
+ Images are rendered on demand with `render(env, cam)`.
24
+ """
25
+ import robosuite as suite
26
+ import libero.libero.envs.bddl_utils as BDDLUtils
27
+ from libero.libero.envs import TASK_MAPPING
28
+
29
+ cfg = suite.load_controller_config(default_controller="OSC_POSE")
30
+ if controller is None:
31
+ from .skills import CONTROLLER
32
+ controller = CONTROLLER
33
+ if controller:
34
+ cfg.update(controller)
35
+ info = BDDLUtils.get_problem_info(bddl_path)
36
+ env = TASK_MAPPING[info["problem_name"]](
37
+ bddl_path,
38
+ robots=["Panda"],
39
+ controller_configs=cfg,
40
+ gripper_types="default",
41
+ initialization_noise=None,
42
+ use_camera_obs=False,
43
+ has_renderer=False,
44
+ has_offscreen_renderer=True,
45
+ render_camera="frontview",
46
+ render_collision_mesh=False,
47
+ render_visual_mesh=True,
48
+ render_gpu_device_id=-1,
49
+ control_freq=20,
50
+ horizon=10 ** 7,
51
+ ignore_done=True,
52
+ hard_reset=False,
53
+ camera_names=list(cams),
54
+ camera_heights=cam_res,
55
+ camera_widths=cam_res,
56
+ camera_depths=depth,
57
+ camera_segmentations=None,
58
+ renderer="mujoco",
59
+ renderer_config=None,
60
+ )
61
+ env.lff_language = info["language_instruction"]
62
+ m = env.sim.model # hard_reset=False: the model (and this limit) survives env.reset()
63
+ m.jnt_range[m.joint_name2id("robot0_joint4"), 1] = ELBOW_Q4_MAX
64
+ return env
65
+
66
+
67
+ def render(env, cam="agentview", res=256, depth=False):
68
+ """Render an RGB image (H, W, 3, uint8), upright."""
69
+ out = env.sim.render(camera_name=cam, width=res, height=res, depth=depth)
70
+ if depth:
71
+ rgb, d = out
72
+ return rgb[::-1].copy(), d[::-1].copy()
73
+ return out[::-1].copy()
74
+
75
+
76
+ # ---------------------------------------------------------------- object state helpers
77
+
78
+ def body_id(env, obj_name):
79
+ return env.sim.model.body_name2id(env.objects_dict[obj_name].root_body)
80
+
81
+
82
+ def obj_pos(env, obj_name):
83
+ return env.sim.data.body_xpos[body_id(env, obj_name)].copy()
84
+
85
+
86
+ def obj_quat(env, obj_name):
87
+ """wxyz"""
88
+ return env.sim.data.body_xquat[body_id(env, obj_name)].copy()
89
+
90
+
91
+ def obj_upright_cos(env, obj_name):
92
+ """cos of the angle between the object's z axis and world z."""
93
+ xmat = env.sim.data.body_xmat[body_id(env, obj_name)].reshape(3, 3)
94
+ return float(xmat[2, 2])
95
+
96
+
97
+ def free_joint_addr(env, obj_name):
98
+ jname = env.objects_dict[obj_name].joints[0]
99
+ jid = env.sim.model.joint_name2id(jname)
100
+ return env.sim.model.jnt_qposadr[jid], env.sim.model.jnt_dofadr[jid]
101
+
102
+
103
+ def set_obj_pose(env, obj_name, pos, yaw=0.0, quat_wxyz=None):
104
+ """Teleport a free-joint object (used only at reset / by the protocol, never by agents)."""
105
+ qa, da = free_joint_addr(env, obj_name)
106
+ if quat_wxyz is None:
107
+ quat_wxyz = np.array([np.cos(yaw / 2), 0, 0, np.sin(yaw / 2)])
108
+ env.sim.data.qpos[qa:qa + 3] = pos
109
+ env.sim.data.qpos[qa + 3:qa + 7] = quat_wxyz
110
+ env.sim.data.qvel[da:da + 6] = 0.0
111
+
112
+
113
+ def obj_geom_ids(env, obj_name):
114
+ return [env.sim.model.geom_name2id(g) for g in env.objects_dict[obj_name].contact_geoms]
115
+
116
+
117
+ def set_friction(env, obj_name, mu, priority=2):
118
+ """Set sliding friction of an object's collision geoms and give them priority so their
119
+ friction is used in contacts (MuJoCo otherwise takes the max of the two geoms)."""
120
+ for g in obj_geom_ids(env, obj_name):
121
+ env.sim.model.geom_friction[g, 0] = mu
122
+ env.sim.model.geom_priority[g] = priority
123
+
124
+
125
+ def scale_mass(env, obj_name, mass):
126
+ bid = body_id(env, obj_name)
127
+ m0 = env.sim.model.body_mass[bid]
128
+ env.sim.model.body_mass[bid] = mass
129
+ env.sim.model.body_inertia[bid] *= mass / max(m0, 1e-9)
130
+
131
+
132
+ def settle(env, steps=20):
133
+ """Let physics settle while holding the arm still."""
134
+ for _ in range(steps):
135
+ env.step(np.zeros(env.action_dim))
136
+
137
+
138
+ def contacts_between(env, geoms_a, geoms_b):
139
+ a, b = set(geoms_a), set(geoms_b)
140
+ d = env.sim.data
141
+ for i in range(d.ncon):
142
+ c = d.contact[i]
143
+ if (c.geom1 in a and c.geom2 in b) or (c.geom1 in b and c.geom2 in a):
144
+ return True
145
+ return False
146
+
147
+
148
+ def robot_geom_ids(env):
149
+ m = env.sim.model
150
+ ids = []
151
+ for g in range(m.ngeom):
152
+ n = m.geom_id2name(g) or ""
153
+ if n.startswith("robot0_") or n.startswith("gripper0_"):
154
+ ids.append(g)
155
+ return ids
156
+
157
+
158
+ # ---------------------------------------------------------------- upright placement (added 2026-10-06)
159
+
160
+ def _quat_mul(a, b):
161
+ """wxyz quaternion product a*b"""
162
+ w1, x1, y1, z1 = a
163
+ w2, x2, y2, z2 = b
164
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
165
+ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
166
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
167
+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
168
+
169
+
170
+ def canonical_quat(env, obj_name):
171
+ """The orientation LIBERO's own placement gives an object, with any random yaw set to 0 (wxyz).
172
+
173
+ Reproduces LIBERO exactly, including its convention bug: TableRegionSampler._sample_quat builds an
174
+ xyzw quaternion, multiplies it with obj.init_quat (xyzw), and bddl_base_domain writes that array
175
+ straight into the wxyz qpos slot. E.g. scanned objects (plate, bowls, basket; rotation (pi/2, pi/2)
176
+ about x) therefore end up yawed by 90 deg, not rolled; HOPE groceries (dict rotation) come out
177
+ as (0.5, 0.5, 0.5, 0.5), which is the same under both readings. (Fixed 2026-10-06 after the L3
178
+ developer found plates being stood on edge.)"""
179
+ from robosuite.utils.transform_utils import quat_multiply
180
+
181
+ o = env.objects_dict[obj_name]
182
+ rot = getattr(o, "rotation", None)
183
+ ax = getattr(o, "rotation_axis", None) or "z"
184
+
185
+ def xyzw(axis, a):
186
+ h = a / 2
187
+ return {"x": np.array([np.sin(h), 0.0, 0.0, np.cos(h)]),
188
+ "y": np.array([0.0, np.sin(h), 0.0, np.cos(h)]),
189
+ "z": np.array([0.0, 0.0, np.sin(h), np.cos(h)])}[axis]
190
+
191
+ def fixed(r): # a random range means a free angle -> use 0 (only yaw ranges occur in practice)
192
+ return float(r[0]) if float(min(r)) == float(max(r)) else 0.0
193
+
194
+ if isinstance(rot, dict):
195
+ q = np.array([0.0, 0.0, 0.0, 1.0])
196
+ for axis, r in rot.items():
197
+ q = quat_multiply(xyzw(axis, fixed(r)), q)
198
+ else:
199
+ if rot is None:
200
+ a = 0.0
201
+ elif isinstance(rot, (tuple, list)):
202
+ a = fixed(rot)
203
+ else:
204
+ a = float(rot)
205
+ q = xyzw(ax, a)
206
+ init = np.array(getattr(o, "init_quat", [0.0, 0.0, 0.0, 1.0]), dtype=float)
207
+ q = quat_multiply(q, init)
208
+ return np.array(q, dtype=float) # used directly as wxyz, like LIBERO does
209
+
210
+
211
+ def obj_min_z(env, obj_name):
212
+ """Lowest world z of the object's collision geoms (exact for boxes, AABB bound for meshes)."""
213
+ m, d = env.sim.model, env.sim.data
214
+ zmin = np.inf
215
+ for g in obj_geom_ids(env, obj_name):
216
+ R = d.geom_xmat[g].reshape(3, 3)
217
+ c_local = m.geom_aabb[g, :3]
218
+ half = m.geom_aabb[g, 3:]
219
+ cz = d.geom_xpos[g][2] + R[2] @ c_local
220
+ zmin = min(zmin, cz - np.abs(R[2]) @ half)
221
+ return float(zmin)
222
+
223
+
224
+ def obj_max_z(env, obj_name):
225
+ """Highest world z of the object's collision geoms (exact for boxes, AABB bound for meshes)."""
226
+ m, d = env.sim.model, env.sim.data
227
+ zmax = -np.inf
228
+ for g in obj_geom_ids(env, obj_name):
229
+ R = d.geom_xmat[g].reshape(3, 3)
230
+ cz = d.geom_xpos[g][2] + R[2] @ m.geom_aabb[g, :3]
231
+ zmax = max(zmax, cz + np.abs(R[2]) @ m.geom_aabb[g, 3:])
232
+ return float(zmax)
233
+
234
+
235
+ FINGERTIP_BELOW_SITE = 0.0095 # lowest point of the Panda finger collision meshes below the grasp site (measured)
236
+
237
+
238
+ def place_upright(env, obj_name, xy, yaw=0.0, surface_z=TABLE_Z, clearance=0.002):
239
+ """Teleport an object upright (LIBERO canonical orientation, then `yaw` about world z) so that its
240
+ lowest collision point sits `clearance` above `surface_z`. Call env.sim.forward() / settle after."""
241
+ q = _quat_mul(np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]), canonical_quat(env, obj_name))
242
+ set_obj_pose(env, obj_name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
243
+ env.sim.forward()
244
+ dz = obj_min_z(env, obj_name) - (surface_z + clearance)
245
+ qa, _ = free_joint_addr(env, obj_name)
246
+ env.sim.data.qpos[qa + 2] -= dz
247
+ env.sim.forward()
248
+
249
+
250
+ # ---------------------------------------------------------------- collision bounds after runtime edits (2026-10-12)
251
+
252
+ def _quat2mat(q):
253
+ w, x, y, z = q
254
+ return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
255
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
256
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
257
+
258
+
259
+ def _prim_bounds(m, g):
260
+ """(half extents in the geom frame, bounding-sphere radius) of a primitive geom from geom_size; None otherwise"""
261
+ t, s = int(m.geom_type[g]), m.geom_size[g]
262
+ if t == 6: # box
263
+ return np.array(s[:3], float), float(np.linalg.norm(s[:3]))
264
+ if t == 4: # ellipsoid
265
+ return np.array(s[:3], float), float(max(s[:3]))
266
+ if t == 2: # sphere
267
+ return np.full(3, float(s[0])), float(s[0])
268
+ if t == 5: # cylinder
269
+ return np.array([s[0], s[0], s[1]], float), float(np.hypot(s[0], s[1]))
270
+ if t == 3: # capsule
271
+ return np.array([s[0], s[0], s[0] + s[1]], float), float(s[0] + s[1])
272
+ return None
273
+
274
+
275
+ def refit_bounds(model, bodies, margin=0.0, geoms=True):
276
+ """Make the collision bounds of `bodies` (body id or ids) consistent again after runtime edits of their geoms
277
+ (geom_size / geom_pos / geom_quat) or of their inertial frame (body_ipos / body_iquat). `model`: an env, a
278
+ robosuite MjModel wrapper or a raw mujoco.MjModel.
279
+
280
+ MuJoCo (3.2.3) computes these bounds at compile time and never updates them: geom_aabb / geom_rbound (geom
281
+ frame; broad phase and geom-pair filters) and the per-body bounding-volume hierarchy bvh_aabb, stored in the
282
+ body's INERTIAL frame and used by the mid-phase whenever one of the two bodies of a pair has >= 2 collision
283
+ geoms. Stale boxes make MuJoCo silently skip contacts (lh_fence v1: a post whose centre of mass was raised sank
284
+ 2.2 cm into the table; measured 2026-10-12: a body with a single collision geom whose COM moved 6 cm missed every
285
+ contact with a 2-geom body beyond the shifted box). With geoms=True the primitive geoms' geom_aabb / geom_rbound
286
+ are recomputed from geom_size (meshes keep theirs); then every BVH node becomes the union of its leaf geoms'
287
+ boxes (+ margin) in the runtime inertial frame, following body_sameframe / geom_sameframe like mj_kinematics
288
+ (on a pristine model this reproduces the compiled bvh_aabb exactly).
289
+ Also note: a runtime body_ipos is ignored by MuJoCo if the compiled inertial pos is the body origin
290
+ (body_sameframe = 1); bodies whose centre of mass is moved at runtime need a non-zero compiled inertial pos."""
291
+ if hasattr(model, "sim"):
292
+ model = model.sim.model
293
+ m = getattr(model, "_model", model)
294
+ for b in np.atleast_1d(bodies):
295
+ b = int(b)
296
+ if geoms:
297
+ for g in range(int(m.body_geomadr[b]), int(m.body_geomadr[b] + m.body_geomnum[b])):
298
+ pb = _prim_bounds(m, g)
299
+ if pb is not None:
300
+ m.geom_aabb[g] = [0.0, 0.0, 0.0, *pb[0]]
301
+ m.geom_rbound[g] = pb[1]
302
+ a, n = int(m.body_bvhadr[b]), int(m.body_bvhnum[b])
303
+ if a < 0 or n < 1:
304
+ continue
305
+ sf = int(m.body_sameframe[b]) # 1: inertial frame = body frame, 3: same orientation as the body
306
+ ip = np.zeros(3) if sf == 1 else np.array(m.body_ipos[b], float)
307
+ iR = np.eye(3) if sf in (1, 3) else _quat2mat(m.body_iquat[b])
308
+
309
+ def rec(i):
310
+ g = int(m.bvh_nodeid[i])
311
+ if g >= 0:
312
+ gsf = int(m.geom_sameframe[g]) # 1: body frame, 2: inertial frame, 3/4: their orientation
313
+ gp = np.zeros(3) if gsf == 1 else ip if gsf == 2 else np.array(m.geom_pos[g], float)
314
+ gR = np.eye(3) if gsf in (1, 3) else iR if gsf in (2, 4) else _quat2mat(m.geom_quat[g])
315
+ R = iR.T @ gR
316
+ c = iR.T @ (gp - ip) + R @ np.asarray(m.geom_aabb[g, :3])
317
+ h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:])
318
+ lo, hi = c - h, c + h
319
+ else:
320
+ l1, h1 = rec(a + int(m.bvh_child[i][0]))
321
+ l2, h2 = rec(a + int(m.bvh_child[i][1]))
322
+ lo, hi = np.minimum(l1, l2), np.maximum(h1, h2)
323
+ m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin])
324
+ return lo, hi
325
+ rec(a)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/objects.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Procedurally generated objects for LFF-Bench, registered into LIBERO's object registry.
2
+
3
+ Each generated object is an MJCF file with the layout robosuite's MujocoXMLObject expects
4
+ (an outer body containing body "object" plus bottom/top/horizontal_radius sites).
5
+ """
6
+ import os
7
+ import re
8
+
9
+ import numpy as np
10
+ from robosuite.models.objects import MujocoXMLObject
11
+
12
+ from libero.libero.envs.base_object import OBJECTS_DICT, register_object
13
+
14
+ GEN_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets_gen")
15
+ os.makedirs(GEN_DIR, exist_ok=True)
16
+
17
+ _SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
18
+
19
+
20
+ def _fmt(v):
21
+ return " ".join(f"{x:.5f}" for x in v)
22
+
23
+
24
+ def _wrap(model_name, geoms_xml, half_height, radius):
25
+ return f"""<mujoco model="{model_name}">
26
+ <worldbody>
27
+ <body>
28
+ <body name="object">
29
+ {geoms_xml}
30
+ </body>
31
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {-half_height:.5f}" name="bottom_site" />
32
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {half_height:.5f}" name="top_site" />
33
+ <site rgba="0 0 0 0" size="0.005" pos="{radius:.5f} {radius:.5f} 0" name="horizontal_radius_site" />
34
+ </body>
35
+ </worldbody>
36
+ </mujoco>
37
+ """
38
+
39
+
40
+ def box_xml(model_name, half, rgba, density=500.0, friction=(1.0, 0.005, 0.0001)):
41
+ """Solid box; one geom used for both collision and rendering."""
42
+ g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
43
+ f'density="{density}" friction="{_fmt(friction)}" {_SOLID} group="0" />\n'
44
+ f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
45
+ return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1])))
46
+
47
+
48
+ def bin_xml(model_name, inner_half_xy, wall_h, wall_t=0.006, floor_t=0.006, rgba=(0.6, 0.6, 0.65, 1.0),
49
+ density=800.0):
50
+ """Open-top box. Origin at the center of the outer footprint, z=0 at mid height."""
51
+ ix, iy = inner_half_xy
52
+ H = (wall_h + floor_t) / 2.0
53
+ geoms = []
54
+ parts = [
55
+ ((0, 0, -H + floor_t / 2), (ix + wall_t, iy + wall_t, floor_t / 2)), # floor
56
+ ((ix + wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # +x wall
57
+ ((-ix - wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # -x wall
58
+ ((0, iy + wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # +y wall
59
+ ((0, -iy - wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # -y wall
60
+ ]
61
+ for k, (p, s) in enumerate(parts):
62
+ geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" '
63
+ f'rgba="{_fmt(rgba)}" density="{density}" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
64
+ geoms.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(rgba)}" '
65
+ f'conaffinity="0" contype="0" group="1" />')
66
+ return _wrap(model_name, "\n".join(geoms), H, float(np.hypot(ix + wall_t, iy + wall_t)))
67
+
68
+
69
+ def _key(class_name):
70
+ return "_".join(re.sub(r"([A-Z0-9])", r" \1", class_name).split()).lower()
71
+
72
+
73
+ def register_generated(class_name, xml_text, free=True):
74
+ """Write the MJCF and register a LIBERO object class. Returns the BDDL category name."""
75
+ key = _key(class_name)
76
+ path = os.path.join(GEN_DIR, f"{key}.xml")
77
+ # write to a private temp file and rename atomically: several servers / validators may build the same task at
78
+ # once, and a reader must never see a half-written file (seen 2026-10-09 by the lh_* builders)
79
+ tmp = f"{path}.{os.getpid()}.tmp"
80
+ with open(tmp, "w") as f:
81
+ f.write(xml_text)
82
+ os.replace(tmp, path)
83
+ if key in OBJECTS_DICT:
84
+ return key
85
+
86
+ default_joints = [dict(type="free", damping="0.0005")] if free else None
87
+
88
+ def __init__(self, name=key, joints="default"):
89
+ j = default_joints if joints == "default" else joints
90
+ MujocoXMLObject.__init__(self, path, name=name, joints=j, obj_type="all", duplicate_collision_geoms=False)
91
+ self.category_name = key
92
+ self.rotation = (0.0, 0.0)
93
+ self.rotation_axis = "z"
94
+ self.object_properties = {"vis_site_names": {}}
95
+
96
+ cls = type(class_name, (MujocoXMLObject,), {"__init__": __init__})
97
+ register_object(cls)
98
+ return key
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/skills.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Motion primitives executed with robosuite's OSC_POSE controller.
2
+
3
+ All positions are world-frame metres (LIBERO table top is z = TABLE_Z = 0.90).
4
+ `bias` is a hidden calibration error added to every commanded position (used by L1 tasks);
5
+ agents never see it.
6
+ """
7
+ import numpy as np
8
+ import robosuite.utils.transform_utils as T
9
+
10
+ from .envs import TABLE_Z
11
+
12
+ DT = 0.05 # control period (20 Hz)
13
+ ROT_SCALE = 0.5
14
+ # Faster OSC than LIBERO's default (default caps the end effector at ~0.25 m/s; this reaches ~0.6 m/s).
15
+ CONTROLLER = dict(kp=300, output_max=[0.1, 0.1, 0.1, 0.5, 0.5, 0.5], output_min=[-0.1, -0.1, -0.1, -0.5, -0.5, -0.5])
16
+
17
+
18
+ def _rotz(a):
19
+ c, s = np.cos(a), np.sin(a)
20
+ return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
21
+
22
+
23
+ def _rot_err(R_target, R_cur):
24
+ """axis-angle (world frame) rotating R_cur to R_target"""
25
+ R = R_target @ R_cur.T
26
+ q = T.mat2quat(R) # xyzw
27
+ return T.quat2axisangle(q)
28
+
29
+
30
+ class Skills:
31
+ def __init__(self, env, bias=None, recorder=None):
32
+ self.env = env
33
+ self.pos_scale = float(env.robots[0].controller.output_max[0])
34
+ self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
35
+ self.grip = -1.0 # -1 open, +1 closed
36
+ self.R0 = self.eef_mat().copy() # top-down orientation at reset == yaw 0
37
+ self.yaw = 0.0
38
+ self.recorder = recorder # callable(env) invoked every `record_every` control steps
39
+ self.record_every = 4
40
+ self.n_steps = 0
41
+ self.log = []
42
+
43
+ # ------------------------------------------------------------------ state
44
+ def eef_pos(self):
45
+ return self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id].copy()
46
+
47
+ def eef_mat(self):
48
+ return self.env.sim.data.site_xmat[self.env.robots[0].eef_site_id].reshape(3, 3).copy()
49
+
50
+ def gripper_width(self):
51
+ g = self.env.robots[0].gripper
52
+ q = [self.env.sim.data.qpos[self.env.sim.model.joint_name2id(j)] for j in g.joints]
53
+ return float(abs(q[0] - q[1]))
54
+
55
+ def holding(self, obj_name):
56
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper,
57
+ object_geoms=self.env.objects_dict[obj_name]))
58
+
59
+ # ------------------------------------------------------------------ low level
60
+ def _act(self, dpos, drot, grip):
61
+ a = np.zeros(7)
62
+ a[:3] = np.clip(dpos / self.pos_scale, -1, 1)
63
+ a[3:6] = np.clip(drot / ROT_SCALE, -1, 1)
64
+ a[6] = grip
65
+ self.env.step(a)
66
+ self.n_steps += 1
67
+ if self.recorder is not None and self.n_steps % self.record_every == 0:
68
+ self.recorder(self.env)
69
+
70
+ def hold(self, steps=10):
71
+ p, R = self.eef_pos(), self._R()
72
+ for _ in range(steps):
73
+ self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
74
+
75
+ def _R(self, yaw=None):
76
+ return _rotz(self.yaw if yaw is None else yaw) @ self.R0
77
+
78
+ # ------------------------------------------------------------------ primitives
79
+ YAW_LIMIT = np.pi / 2 + 0.4
80
+
81
+ def wrap_yaw(self, yaw):
82
+ """A parallel-jaw gripper is symmetric under a rotation by pi, so pick the equivalent yaw closest
83
+ to the current one inside |yaw| <= pi/2 + 0.4. Without this, asking for ~180 deg of wrist rotation
84
+ makes the OSC (whose axis-angle error is ambiguous at pi) wind the arm into its joint limits and
85
+ it never recovers (found by the L3 developer: push towards -y -> 0/6 success, 2026-10-06)."""
86
+ cands = [yaw + k * np.pi for k in range(-3, 4)]
87
+ ok = [c for c in cands if abs(c) <= self.YAW_LIMIT] or cands
88
+ return float(min(ok, key=lambda c: abs(c - self.yaw)))
89
+
90
+ def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
91
+ """Move the gripper site to `target` (world xyz). If `speed` (m/s) is given the reference
92
+ moves along a straight line at that speed; otherwise go as fast as the controller allows.
93
+ `yaw` is wrapped to the closest gripper-symmetric equivalent unless wrap_yaw=False.
94
+ Returns a report dict."""
95
+ tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
96
+ if yaw is not None:
97
+ self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
98
+ R = self._R()
99
+ p0 = self.eef_pos()
100
+ dist = np.linalg.norm(tgt - p0)
101
+ direction = (tgt - p0) / max(dist, 1e-9)
102
+ s = 0.0
103
+ for k in range(max_steps):
104
+ if speed is not None:
105
+ s = min(dist, s + speed * DT)
106
+ ref = p0 + direction * s
107
+ # lead the reference a little so the OSC lag does not throttle the speed
108
+ ref = ref + direction * min(dist - s, speed * DT * 1.5)
109
+ else:
110
+ ref = tgt
111
+ cur = self.eef_pos()
112
+ self._act(ref - cur, _rot_err(R, self.eef_mat()), self.grip)
113
+ err = np.linalg.norm(tgt - self.eef_pos())
114
+ if err < tol and (speed is None or s >= dist):
115
+ break
116
+ rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
117
+ pos=self.eef_pos().round(4).tolist(), steps=k + 1)
118
+ self.log.append(rep)
119
+ return rep
120
+
121
+ def set_gripper(self, close, steps=15):
122
+ self.grip = 1.0 if close else -1.0
123
+ self.hold(steps)
124
+ rep = dict(prim="close" if close else "open", width=round(self.gripper_width(), 4))
125
+ self.log.append(rep)
126
+ return rep
127
+
128
+ def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15):
129
+ """Composite: above -> descend -> close -> lift. For scripted policies."""
130
+ self.set_gripper(False, steps=5)
131
+ self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw)
132
+ self.move_to([xy[0], xy[1], z_grasp], tol=0.003)
133
+ self.set_gripper(True, steps=15)
134
+ self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25)
135
+
136
+ def place_at(self, xy, z_release, approach=0.10):
137
+ self.move_to([xy[0], xy[1], z_release + approach])
138
+ self.move_to([xy[0], xy[1], z_release], tol=0.004)
139
+ self.set_gripper(False, steps=12)
140
+ self.move_to([xy[0], xy[1], z_release + approach])
141
+
142
+ def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06):
143
+ """Straight-line push: go to `pre` m behind the start point at height z with the gripper closed,
144
+ then sweep `pre + distance` along direction at `speed`, stop, and lift away."""
145
+ d = np.asarray(direction_xy, float)
146
+ d = d / np.linalg.norm(d)
147
+ z = TABLE_Z + 0.02 if z is None else z
148
+ s = np.asarray(start_xy, float) - d * pre
149
+ self.set_gripper(True, steps=5)
150
+ self.move_to([s[0], s[1], z + 0.12], yaw=np.arctan2(d[1], d[0]) - np.pi / 2)
151
+ self.move_to([s[0], s[1], z], tol=0.003)
152
+ e = s + d * (pre + distance)
153
+ rep = self.move_to([e[0], e[1], z], speed=speed, tol=0.01, max_steps=400)
154
+ self.hold(2)
155
+ self.move_to([e[0], e[1], z + 0.12], speed=0.3)
156
+ return rep
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/task_base.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task interface shared by all LFF-Bench tasks.
2
+
3
+ A task = a LIBERO scene + an instance sampler (layout and hidden variables) + a success / outcome
4
+ measurement + scripted reference policies used to validate that the task really requires learning
5
+ from failure:
6
+
7
+ oracle knows the hidden variables; should succeed on attempt 1
8
+ naive acts on the prior (what an agent would do without the failure information)
9
+ adaptive scripted learner that updates its parameters from structured (F2) feedback
10
+ blind repeats the naive behaviour with small random variation, no history
11
+
12
+ Tasks whose policies can be expressed as "execute(params)" get the cross-attempt protocol for free.
13
+ Tasks that need within-episode recovery override `run_scripted`.
14
+ """
15
+ import numpy as np
16
+
17
+ from . import envs
18
+ from .skills import Skills
19
+
20
+ TASKS = {}
21
+
22
+
23
+ def register_task(cls):
24
+ TASKS[cls.name] = cls
25
+ return cls
26
+
27
+
28
+ class LFFTask:
29
+ name = "base"
30
+ level = "L?"
31
+ # the user's 7 categories (2026-10-06): hidden information -> required capability -> adapted action
32
+ category = "" # system_identification | dynamics_adaptation | failed_interaction_inference |
33
+ # state_restoration | procedural_memory | strategy_switching | geometry_inference
34
+ capabilities = ()
35
+ max_attempts = 5
36
+ protocol = "cross" # "cross": reset between attempts; "within": one episode, recover in place
37
+ instruction = "" # direct reference
38
+ instruction_indirect = "" # descriptive reference (perception / semantic reasoning variant)
39
+ cam_res = 256
40
+
41
+ def __init__(self, cam_res=None):
42
+ if cam_res:
43
+ self.cam_res = cam_res
44
+ self.bddl_path = self.make_bddl()
45
+ self.env = envs.make_env(self.bddl_path, cam_res=self.cam_res)
46
+ self.env.reset()
47
+ self.sk = None
48
+
49
+ # ------------------------------------------------------------ to implement
50
+ def make_bddl(self):
51
+ raise NotImplementedError
52
+
53
+ def sample_instance(self, seed):
54
+ """Return a JSON-serialisable dict with layout + hidden variables."""
55
+ raise NotImplementedError
56
+
57
+ def apply_instance(self, inst):
58
+ """Place objects / set hidden physics after env.reset()."""
59
+ raise NotImplementedError
60
+
61
+ def outcome(self, inst):
62
+ """dict with at least {'success': bool}; may contain structured measurements."""
63
+ raise NotImplementedError
64
+
65
+ def feedback(self, inst, out, level="F2"):
66
+ """Text the agent receives after an attempt. F0: nothing, F1: success flag, F2: measurement."""
67
+ if level == "F0":
68
+ return ""
69
+ s = "Attempt succeeded." if out["success"] else "Attempt failed."
70
+ if level == "F1":
71
+ return s
72
+ return s + (" " + out["detail"] if out.get("detail") else "")
73
+
74
+ def skill_bias(self, inst):
75
+ return None
76
+
77
+ # scripted references (cross protocol) ----------------------------------
78
+ def default_params(self, inst):
79
+ raise NotImplementedError
80
+
81
+ def oracle_params(self, inst):
82
+ raise NotImplementedError
83
+
84
+ def adapt_params(self, inst, history):
85
+ raise NotImplementedError
86
+
87
+ def blind_params(self, inst, attempt, rng):
88
+ return self.default_params(inst)
89
+
90
+ def execute(self, inst, params):
91
+ raise NotImplementedError
92
+
93
+ # ------------------------------------------------------------ shared
94
+ def reset_instance(self, inst, recorder=None):
95
+ self.env.reset()
96
+ self.apply_instance(inst)
97
+ self.env.sim.forward()
98
+ envs.settle(self.env, 10)
99
+ self.sk = Skills(self.env, bias=self.skill_bias(inst), recorder=recorder)
100
+ return self.sk
101
+
102
+ def snapshot(self, cam="agentview", res=None):
103
+ return envs.render(self.env, cam, res or self.cam_res)
104
+
105
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
106
+ """Cross-attempt protocol with a scripted policy. Returns the per-attempt history."""
107
+ k = k or self.max_attempts
108
+ rng = np.random.default_rng(seed)
109
+ history = []
110
+ for a in range(k):
111
+ self.reset_instance(inst)
112
+ if kind == "oracle":
113
+ params = self.oracle_params(inst)
114
+ elif kind == "naive":
115
+ params = self.default_params(inst)
116
+ elif kind == "adaptive":
117
+ params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history)
118
+ elif kind == "blind":
119
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
120
+ else:
121
+ raise ValueError(kind)
122
+ self.execute(inst, params)
123
+ out = self.outcome(inst)
124
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
125
+ if on_attempt:
126
+ on_attempt(a, params, out)
127
+ if out["success"] or kind in ("oracle", "naive"):
128
+ break
129
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/vla.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate a visuomotor policy (VLA, e.g. pi0.5) on LFF-Bench instances.
2
+
3
+ A VLA sends 7-D OSC actions at 20 Hz instead of the agents' robot commands. Everything else is the benchmark's own:
4
+ task scenes and instances, per-attempt budgets, attempt transitions (cross = reset, within = continue in place) and
5
+ task.outcome(). The observation has the layout of the LeRobot replay dataset (scripts/lerobot_replay.py, Recorder.state),
6
+ so a policy trained on that dataset needs no adapter. Driver: scripts/vla_eval.py.
7
+
8
+ What differs from the agents' interface, and why:
9
+ - Actions go through sk._act, not env.step: the tasks' per-step monitors and failure injections live there.
10
+ - sk.grip and sk.yaw are kept in step with the policy, because outcome() and go_home() use them (Skills.hold holds
11
+ sk.yaw, not the current orientation) and set_gripper hooks run with steps=0 once the fingers have settled.
12
+ - The hidden offset of L1 tasks is applied in Skills.move_to / YawSkills.R0, which direct actions bypass. The policy still
13
+ reads its proprioception in the robot's believed frame (frame="believed"), as the agents do, but an L1 result does not
14
+ measure the same trap as for an agent: report those tasks separately.
15
+ - There is no `finish`: an attempt ends when its simulated-time budget runs out or the arm has been idle for idle_s.
16
+ """
17
+ import os
18
+ import select
19
+ import time
20
+
21
+ import msgpack
22
+ import numpy as np
23
+
24
+ from . import envs
25
+ from .agent import camera as C
26
+ from .skills import ROT_SCALE
27
+
28
+ CONTROL_HZ = 20
29
+ GRIP_SETTLE = 15 # control steps the fingers get before the set_gripper hooks fire (Skills.set_gripper's default)
30
+ IDLE_EEF_M = 0.001 # the grasp point moved less than this over idle_s, with the gripper command unchanged
31
+
32
+
33
+ def _rotz(a):
34
+ c, s = np.cos(a), np.sin(a)
35
+ return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
36
+
37
+
38
+ def read_state(env, sk, frame="believed"):
39
+ """8-D state: eef position (world, m), eef orientation (axis-angle), two finger joints -- the dataset's layout.
40
+ frame="believed" applies the hidden calibration errors the way everything shown to an agent does (Skills.bias,
41
+ YawSkills.yaw_bias; robot_server._believed_pose); without such an error it equals frame="true"."""
42
+ import robosuite.utils.transform_utils as T
43
+ d, rob = env.sim.data, env.robots[0]
44
+ pos = np.array(d.site_xpos[rob.eef_site_id], np.float64)
45
+ quat = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
46
+ if frame == "believed":
47
+ pos = pos - np.asarray(sk.bias, np.float64)
48
+ beta = float(getattr(sk, "yaw_bias", 0.0))
49
+ if beta:
50
+ quat = T.mat2quat(_rotz(-beta) @ T.quat2mat(quat))
51
+ elif frame != "true":
52
+ raise ValueError(f"unknown proprioception frame {frame!r}")
53
+ grip = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
54
+ return np.concatenate([pos, np.asarray(T.quat2axisangle(quat), np.float64), grip]).astype(np.float32)
55
+
56
+
57
+ def task_prompt(task, inst):
58
+ """The instruction an agent gets for this instance (robot_server.instruction): some tasks build it per instance."""
59
+ hook = getattr(task, "agent_instruction", None)
60
+ return hook(inst, "direct") if hook is not None else task.instruction
61
+
62
+
63
+ def read_obs(task, inst, res=256, frame="believed"):
64
+ """The observation a policy receives, in the openpi request format. Images are uint8 HWC, upright."""
65
+ env = task.env
66
+ return {"observation/image": envs.render(env, C.mj_cam("agentview"), res),
67
+ "observation/wrist_image": envs.render(env, C.mj_cam("wrist"), res),
68
+ "observation/state": read_state(env, task.sk, frame),
69
+ "prompt": task_prompt(task, inst)}
70
+
71
+
72
+ class PolicyActuator:
73
+ """Applies one policy action to the task's Skills. a = (dpos, drot, gripper) in [-1, 1], scaled like Skills._act;
74
+ gripper > 0 closes (dataset convention: -1 open, +1 close)."""
75
+
76
+ def __init__(self, task):
77
+ self.task = task
78
+ self.sk = task.sk
79
+ self.close = self.sk.grip > 0
80
+ self.wait = 0
81
+
82
+ def _sync_yaw(self):
83
+ sk = self.sk
84
+ R = sk.eef_mat() @ sk.R0.T
85
+ sk.yaw = float(np.arctan2(R[1, 0], R[0, 0]))
86
+
87
+ def step(self, action):
88
+ sk = self.sk
89
+ a = np.clip(np.asarray(action, np.float64), -1.0, 1.0)
90
+ close = bool(a[6] > 0)
91
+ if (sk.grip > 0) != self.close: # the task moved the jaws itself (l6_sequence_resume's emergency stop)
92
+ self.close, self.wait = sk.grip > 0, 0
93
+ if getattr(self.task, "_latch", None) is not None:
94
+ # The task is driving the arm (env.step ignores the action) until "the current primitive has returned" and
95
+ # the arm is home. A policy has no primitives, so only the arm reaching home ends the routine.
96
+ sk.log.append(dict(prim="vla_step"))
97
+ elif close != self.close:
98
+ self.close, self.wait = close, GRIP_SETTLE
99
+ sk.grip = 1.0 if close else -1.0
100
+ sk._act(a[:3] * sk.pos_scale, a[3:6] * ROT_SCALE, sk.grip)
101
+ self._sync_yaw()
102
+ if self.wait:
103
+ self.wait -= 1
104
+ if not self.wait:
105
+ sk.set_gripper(self.close, steps=0)
106
+
107
+
108
+ def probe_success(task, inst, timeout=120.0):
109
+ """Would outcome() call this a success right now? outcome() steps the simulator and changes the task's monitors, so
110
+ it runs in a forked copy of this process; the attempt in the parent is untouched."""
111
+ r, w = os.pipe()
112
+ pid = os.fork()
113
+ if pid == 0:
114
+ code = 1
115
+ try:
116
+ os.close(r)
117
+ os.write(w, b"1" if task.outcome(inst)["success"] else b"0")
118
+ code = 0
119
+ finally:
120
+ os._exit(code)
121
+ os.close(w)
122
+ ready = select.select([r], [], [], timeout)[0]
123
+ got = os.read(r, 1) if ready else b""
124
+ os.close(r)
125
+ if not ready:
126
+ os.kill(pid, 9)
127
+ os.waitpid(pid, 0)
128
+ return got == b"1"
129
+
130
+
131
+ # ---------------------------------------------------------------- policies
132
+ class PolicyEnded(Exception):
133
+ """The policy has no more actions (a replayed recording ran out)."""
134
+
135
+
136
+ class ZeroPolicy:
137
+ """Holds still with the gripper open. Smoke tests only."""
138
+ metadata = dict(policy="zero")
139
+
140
+ def reset(self):
141
+ pass
142
+
143
+ def infer(self, obs):
144
+ a = np.zeros((10, 7), np.float32)
145
+ a[:, 6] = -1.0
146
+ return a
147
+
148
+
149
+ class ReplayPolicy:
150
+ """Replays recorded actions open loop, ignoring the observation. Used to test the evaluator against the recorded
151
+ verdicts (scripts/vla_acceptance.py)."""
152
+ metadata = dict(policy="replay")
153
+
154
+ def __init__(self, actions, chunk=5, on_obs=None):
155
+ self.actions, self.chunk, self.on_obs = actions, int(chunk), on_obs
156
+ self.t = 0
157
+
158
+ def reset(self):
159
+ pass
160
+
161
+ def infer(self, obs):
162
+ if self.t >= len(self.actions):
163
+ raise PolicyEnded()
164
+ if self.on_obs is not None:
165
+ self.on_obs(self.t, obs)
166
+ chunk = self.actions[self.t:self.t + self.chunk]
167
+ self.t += len(chunk)
168
+ return chunk
169
+
170
+
171
+ def _pack(o):
172
+ if isinstance(o, np.ndarray):
173
+ return {b"__ndarray__": True, b"data": o.tobytes(), b"dtype": o.dtype.str, b"shape": o.shape}
174
+ if isinstance(o, np.generic):
175
+ return {b"__npgeneric__": True, b"data": o.item(), b"dtype": o.dtype.str}
176
+ return o
177
+
178
+
179
+ def _unpack(o):
180
+ if b"__ndarray__" in o:
181
+ return np.ndarray(buffer=o[b"data"], dtype=np.dtype(o[b"dtype"]), shape=o[b"shape"])
182
+ if b"__npgeneric__" in o:
183
+ return np.dtype(o[b"dtype"]).type(o[b"data"])
184
+ return o
185
+
186
+
187
+ class WebsocketPolicy:
188
+ """Client of a policy server speaking the openpi websocket protocol (openpi scripts/serve_policy.py; StarVLA's
189
+ WebsocketPolicyServer, which wraps the reply in {"status", "data"})."""
190
+
191
+ def __init__(self, url, open_timeout=300):
192
+ from websockets.sync.client import connect
193
+ # No keepalive pings: the server cannot answer them while it runs a request, and the first one compiles the model
194
+ # for minutes on PPU.
195
+ self.ws = connect(url, compression=None, max_size=None, open_timeout=open_timeout, ping_interval=None)
196
+ self.metadata = msgpack.unpackb(self.ws.recv(), object_hook=_unpack)
197
+
198
+ def reset(self):
199
+ pass
200
+
201
+ def infer(self, obs):
202
+ self.ws.send(msgpack.packb(obs, default=_pack))
203
+ out = self.ws.recv()
204
+ if isinstance(out, str): # openpi sends the server's traceback as text
205
+ raise RuntimeError(f"policy server error: {out}")
206
+ out = msgpack.unpackb(out, object_hook=_unpack)
207
+ if out.get("status") == "error":
208
+ raise RuntimeError(f"policy server error: {out.get('error')}")
209
+ return np.asarray(out.get("data", out)["actions"])
210
+
211
+ def close(self):
212
+ self.ws.close()
213
+
214
+
215
+ # ---------------------------------------------------------------- attempts
216
+ def budget_steps(task):
217
+ """Control steps per attempt: the agents' simulated-time budget (robot_server._sim_budget) at 20 Hz."""
218
+ return int(round(3.0 * int(getattr(task, "agent_max_steps", 40)) * CONTROL_HZ))
219
+
220
+
221
+ def run_attempt(task, inst, policy, max_steps, replan=5, res=256, frame="believed", idle_s=5.0, probe_every_s=5.0,
222
+ on_frame=None):
223
+ """Drive the policy until the budget or an idle arm ends the attempt. Returns timing and the first time a forked
224
+ outcome() check saw success (what an evaluator stopping at first success would have counted)."""
225
+ sk = task.sk
226
+ act = PolicyActuator(task)
227
+ step0 = sk.n_steps
228
+ idle_steps = int(idle_s * CONTROL_HZ) if idle_s else 0
229
+ probe_steps = int(probe_every_s * CONTROL_HZ) if probe_every_s else 0
230
+ infer_s, render_s = [], 0.0
231
+ first_ok = None
232
+ end = "budget"
233
+ ref_pos, ref_close, ref_t = sk.eef_pos(), act.close, 0
234
+ t = 0
235
+ done = False
236
+ while t < max_steps and not done:
237
+ t0 = time.time()
238
+ obs = read_obs(task, inst, res, frame)
239
+ t1 = time.time()
240
+ try:
241
+ chunk = np.asarray(policy.infer(obs), np.float64)
242
+ except PolicyEnded:
243
+ end = "policy_ended"
244
+ break
245
+ t2 = time.time()
246
+ render_s += t1 - t0
247
+ infer_s.append(t2 - t1)
248
+ if chunk.ndim != 2 or chunk.shape[1] < 7 or not np.isfinite(chunk[:, :7]).all():
249
+ raise ValueError(f"bad action chunk from the policy: shape {chunk.shape}")
250
+ if on_frame is not None:
251
+ on_frame(t, obs)
252
+ for a in chunk[:replan]:
253
+ if t >= max_steps:
254
+ break
255
+ act.step(a[:7])
256
+ t += 1
257
+ if probe_steps and first_ok is None and t % probe_steps == 0 and probe_success(task, inst):
258
+ first_ok = t
259
+ if idle_steps:
260
+ if np.linalg.norm(sk.eef_pos() - ref_pos) > IDLE_EEF_M or act.close != ref_close:
261
+ ref_pos, ref_close, ref_t = sk.eef_pos(), act.close, t
262
+ elif t - ref_t >= idle_steps:
263
+ end, done = "idle", True
264
+ break
265
+ return dict(end=end, n_steps=int(sk.n_steps - step0), first_success_step=first_ok,
266
+ n_infer=len(infer_s), infer_s_mean=float(np.mean(infer_s)) if infer_s else None,
267
+ infer_s_p95=float(np.percentile(infer_s, 95)) if infer_s else None, render_s=round(render_s, 2))
268
+
269
+
270
+ def run_session(task, inst, policy, k=3, max_steps=None, on_attempt=None, **kw):
271
+ """Up to k attempts on one instance with the benchmark's attempt transitions; stops at the first success or a
272
+ terminal failure. The policy gets no feedback and no history: a retry only differs by its sampling noise."""
273
+ max_steps = budget_steps(task) if max_steps is None else int(max_steps)
274
+ protocol = getattr(task, "protocol", "cross")
275
+ attempts = []
276
+ for attempt in range(1, k + 1):
277
+ if attempt == 1 or protocol == "cross":
278
+ task.reset_instance(inst)
279
+ policy.reset()
280
+ t0 = time.time()
281
+ rec = run_attempt(task, inst, policy, max_steps, **kw)
282
+ n0 = task.sk.n_steps
283
+ out = task.outcome(inst)
284
+ rec.update(attempt=attempt, success=bool(out["success"]), failure=out.get("failure"), detail=out.get("detail"),
285
+ terminal=bool(out.get("terminal")), judge_steps=int(task.sk.n_steps - n0),
286
+ wall_s=round(time.time() - t0, 2))
287
+ rec["outcome"] = {key: v for key, v in out.items() if key not in ("feedback", "detail")}
288
+ attempts.append(rec)
289
+ if on_attempt is not None:
290
+ on_attempt(rec)
291
+ if rec["success"] or rec["terminal"]:
292
+ break
293
+ return attempts
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/agent_cost.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Project GPT-6 cost / latency of a protocol from a run directory.
2
+
3
+ Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made
4
+ with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES:
5
+ input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption)
6
+ cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) --
7
+ the first call of an attempt is counted as uncached (conservative)
8
+ output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500)
9
+ latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input
10
+ tokens and high/xhigh effort -- treat as an upper-range planning number)
11
+ The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls).
12
+
13
+ python scripts/agent_cost.py runs/agent/l5_slide_to_target/<run> --out-tokens 1500 --latency 20 --calls-scale 2
14
+ """
15
+ import argparse
16
+ import json
17
+ import os
18
+ import sys
19
+ from collections import defaultdict
20
+
21
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
+
23
+ from lffbench.agent.cost import PRICES, call_cost # noqa: E402
24
+
25
+
26
+ def main():
27
+ ap = argparse.ArgumentParser()
28
+ ap.add_argument("run_dir")
29
+ ap.add_argument("--model", default="gpt-6-astra")
30
+ ap.add_argument("--out-tokens", type=float, default=1500)
31
+ ap.add_argument("--latency", type=float, default=20.0)
32
+ ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)")
33
+ a = ap.parse_args()
34
+ ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))]
35
+ calls = [e for e in ev if e["type"] == "llm_call"]
36
+ runs = {e["seed"] for e in ev if e["type"] == "run_start"}
37
+ real = [c for c in calls if c.get("usage")]
38
+ if real and not any("dry_run_request" in c for c in calls):
39
+ cost = sum(call_cost(c["usage"], a.model) or 0 for c in real)
40
+ lat = [c["latency_s"] for c in real]
41
+ u = defaultdict(int)
42
+ for c in real:
43
+ for kk, v in c["usage"].items():
44
+ u[kk] += v
45
+ out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1),
46
+ usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
47
+ latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1))
48
+ else:
49
+ prev = {}
50
+ tot_in = tot_cached = 0
51
+ cost1 = 0.0 # priced per call (the long-context surcharge applies per request)
52
+ for c in calls:
53
+ d = c.get("dry_run_request")
54
+ if not d:
55
+ continue
56
+ key = (c["seed"], c["attempt"])
57
+ tin = d["est_input_tokens"]
58
+ cached = min(prev.get(key, 0), tin)
59
+ prev[key] = tin
60
+ tot_in += tin
61
+ tot_cached += cached
62
+ cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model)
63
+ n = len(calls) * a.calls_scale
64
+ scale = a.calls_scale
65
+ usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens)
66
+ cost = cost1 * scale
67
+ out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1),
68
+ input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1),
69
+ usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
70
+ api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model),
71
+ assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency,
72
+ calls_scale=a.calls_scale, image_tokens_512px=256))
73
+ print(json.dumps(out, indent=1, default=str))
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/scripts/api_batch.py ADDED
@@ -0,0 +1,709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch of runs with a concurrency limit: the runner for the paper's main table (reference driver scripts/api_player.py)
2
+ and, with --harness, for native agent harnesses (side table, docs/15).
3
+
4
+ start python scripts/api_batch.py start --batch m1_opus --provider anthropic --model claude-opus-5-5 --effort high \
5
+ --tasks l1_height_bias:3000,3001 lh_bridge:3000 --k 3 --concurrency 6 --video
6
+ -> writes runs/api/<batch>/manifest.json (one entry per run, status "pending") and starts a background
7
+ runner that keeps at most --concurrency runs going (robot server + api_player each) and stops each
8
+ server when its player exits.
9
+ status python scripts/api_batch.py status --batch m1_opus
10
+ table python scripts/api_batch.py table --batch m1_opus [--batch ...] (same table as claude_batch + tokens)
11
+ stop python scripts/api_batch.py stop --batch m1_opus (runner, players, servers; runs -> "stopped")
12
+ retry python scripts/api_batch.py retry --batch m1_opus [--runs <run> ...] (default: every failed / stopped / timeout run;
13
+ old logs stay, listed under "superseded"; starts the runner again)
14
+ followup python scripts/api_batch.py followup --batch m1_opus (switch a batch started before 2026-10-19 to
15
+ --memfree followup: plans the memory-free retries due for its finished history runs; then `retry` starts them)
16
+ contract python scripts/api_batch.py contract --batch b1 [--batch b2 ...] (contract_sha256 per instance and condition;
17
+ flags instances whose hash differs between batches: those cells must not share a table)
18
+ pause touch runs/api/<batch>/PAUSE: the runner launches no new run while the file exists; the runs going on finish
19
+ and are recorded as usual (rm the file to go on). Used by quota watchers to stay below a usage window.
20
+
21
+ --harness (default ours): which agent harness drives each run, through scripts/harness_run.py (lffbench/harnesses):
22
+ ours scripts/api_player.py, unchanged (--provider as before)
23
+ claude_code Claude Code CLI --bare, only our MCP tools, one-time config dirs (arm B; provider anthropic)
24
+ claude_code_full Claude Code CLI without --bare (full system prompt), otherwise the same (arm B');
25
+ --claude-auth oauth (default): the subscription token of `claude setup-token` (LFF_CLAUDE_OAUTH_FILE),
26
+ apikey: ANTHROPIC_API_KEY (claude_code takes only apikey)
27
+ codex Codex CLI exec --ephemeral, empty CODEX_HOME, only our MCP tools reachable (arm F; provider openai);
28
+ --codex-auth chatgpt (default): the ChatGPT subscription login, apikey: OPENAI_API_KEY
29
+ dsh DeepSeek Harness headless, only our MCP tools, one-time dirs (lffbench/harnesses/dsh.py; provider
30
+ deepseek, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)
31
+ Native harnesses are refused at launch (status "refused") unless their preset prompt / tool list matches the pin
32
+ written by tests/harness_selfcheck (--allow-unpinned to launch anyway; the preflight still runs). Every run gets
33
+ harness.json, contract.json, trajectory.jsonl and harness_audit.json in its log dir.
34
+
35
+ Conditions (same as claude_batch): harness = memory full, k attempts in one agent; noharness = independent single-attempt
36
+ agents (memory none, k=1). History runs use --hide-k (README and status say 1 attempt, byte-identical to an independent
37
+ run; more attempts are announced only after a failure; --no-hide-k to show k).
38
+ --memfree, how the memory-free retries (pass@k without history) are run:
39
+ followup (default, 2026-10-19): one history run per instance. Its attempt 1 is also the first memory-free attempt,
40
+ since under --hide-k it sees exactly what a fresh agent sees. Only if attempt 1 fails does the runner add a
41
+ fresh single-attempt agent (noharness rep 1, "chain" = the history run's id); if that one fails too, the
42
+ next (rep 2), up to k-1 of them; the first success ends the chain. An instance solved on attempt 1 thus
43
+ costs one attempt in all. Not for tasks whose scene persists between attempts (task protocol "within"):
44
+ a fresh agent would start from the initial scene, the history run's attempt 2 from the failed one, so the
45
+ two conditions would differ; these tasks are reported without memory-free retries (user 2026-10-20).
46
+ upfront the 2026-10-11 protocol: --indep-reps independent runs per instance (default k, all of them run), all
47
+ before the history runs (--conds order; --no-barrier to mix the phases).
48
+ none history runs only.
49
+ --seeds-per-task N keeps the first N seeds of each task:seeds (e.g. 1 = one instance per task).
50
+ API keys come from LFF_ENV_FILE (default <repo>/.env, KEY=value lines) or the environment.
51
+ """
52
+ import argparse
53
+ import json
54
+ import os
55
+ import re
56
+ import shlex
57
+ import signal
58
+ import subprocess
59
+ import sys
60
+ import threading
61
+ import time
62
+
63
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
64
+ sys.path.insert(0, os.path.join(ROOT, "scripts"))
65
+ import claude_batch # noqa: E402
66
+
67
+ RUNS = os.path.join(ROOT, "runs", "api")
68
+ ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
69
+ ACTIVE = ("starting", "running")
70
+ RETRYABLE = ("failed", "stopped", "timeout", "server_failed")
71
+ sys.path.insert(0, ROOT)
72
+ from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER as HARNESS_PROVIDER
73
+
74
+
75
+
76
+ def bdir(batch):
77
+ return os.path.join(RUNS, batch)
78
+
79
+
80
+ def mpath(batch):
81
+ return os.path.join(bdir(batch), "manifest.json")
82
+
83
+
84
+ def load(batch):
85
+ with open(mpath(batch)) as f:
86
+ return json.load(f)
87
+
88
+
89
+ def save(batch, m):
90
+ os.makedirs(bdir(batch), exist_ok=True)
91
+ tmp = mpath(batch) + ".tmp"
92
+ with open(tmp, "w") as f:
93
+ json.dump(m, f, indent=1)
94
+ os.replace(tmp, mpath(batch))
95
+
96
+
97
+ def alive(pid):
98
+ try:
99
+ os.kill(int(pid), 0)
100
+ return True
101
+ except (ProcessLookupError, PermissionError, TypeError, ValueError):
102
+ return False
103
+
104
+
105
+ def runner_alive(batch):
106
+ p = os.path.join(bdir(batch), "runner.pid")
107
+ return os.path.exists(p) and alive(open(p).read().strip())
108
+
109
+
110
+ def launch_runner(batch):
111
+ log = open(os.path.join(bdir(batch), "runner.log"), "a")
112
+ p = subprocess.Popen([sys.executable, os.path.abspath(__file__), "_runner", "--batch", batch], cwd=ROOT,
113
+ start_new_session=True, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
114
+ with open(os.path.join(bdir(batch), "runner.pid"), "w") as f:
115
+ f.write(str(p.pid))
116
+ return p.pid
117
+
118
+
119
+ def next_id(m):
120
+ return f"{max((int(r['id']) for r in m['runs']), default=-1) + 1:04d}"
121
+
122
+
123
+ # ------------------------------------------------------------------------------------------------- memory-free chains
124
+ # --memfree followup: per instance, history run (cond harness, followup=True) -> noharness rep 1 -> ... -> rep k-1,
125
+ # each link planned only after the previous attempts all failed. Attempt 1 of the history run is the chain's first
126
+ # attempt (--hide-k makes it identical to a fresh agent's), so the memory-free pass@k of an instance is: attempt 1 of
127
+ # the history run, or any of its chain runs, succeeded.
128
+ PLAN_KEYS = ("task", "seed", "provider", "agent_harness", "api_base_url", "max_budget_usd", "allow_unpinned", "jail",
129
+ "codex_auth", "claude_auth", "codex_catalog", "codex_provider",
130
+ "rpent_sessions", "rpent_attempts_per_session", "rpent_max_turns",
131
+ "model", "effort", "perception", "video", "style", "feedback", "phase", "nominal", "red_team")
132
+
133
+
134
+ def attempt_results(log):
135
+ """[success of attempt 1, of attempt 2, ...] from the robot server log ([] if there is none)."""
136
+ p = os.path.join(log or "", "events.jsonl")
137
+ if not os.path.exists(p):
138
+ return []
139
+ res = {}
140
+ for line in open(p):
141
+ e = json.loads(line)
142
+ if e.get("ev") == "done":
143
+ res[e["attempt"]] = bool(e["success"])
144
+ return [res[i] for i in sorted(res)]
145
+
146
+
147
+ def episode_protocol(log):
148
+ """The task's attempt protocol ("cross": reset between attempts, "within": the scene persists) from the robot
149
+ server log's session_start line; None if unknown."""
150
+ p = os.path.join(log or "", "events.jsonl")
151
+ if os.path.exists(p):
152
+ for line in open(p):
153
+ e = json.loads(line)
154
+ if e.get("ev") == "session_start":
155
+ return e.get("protocol")
156
+ return None
157
+
158
+
159
+ def plan_followup(m, r):
160
+ """Run r has finished: append the next memory-free retry of its instance if one is due; returns it or None."""
161
+ if r["status"] != "done":
162
+ return None
163
+ if r["cond"] == "harness" and r.get("followup"):
164
+ if episode_protocol(r.get("log")) == "within": # no like-for-like fresh agent (module docstring)
165
+ return None
166
+ root, nxt, res = r, 1, attempt_results(r.get("log"))[:1]
167
+ elif r.get("chain"):
168
+ root = next((x for x in m["runs"] if x["id"] == r["chain"]), None)
169
+ nxt, res = r["rep"] + 1, attempt_results(r.get("log"))
170
+ else:
171
+ return None
172
+ if root is None or not res or any(res) or nxt >= root["k"]:
173
+ return None
174
+ if any(x.get("chain") == root["id"] and x["rep"] == nxt for x in m["runs"]):
175
+ return None
176
+ new = {k: root.get(k) for k in PLAN_KEYS}
177
+ new.update(id=next_id(m), cond="noharness", rep=nxt, k=1, mem="none", hide_k=False, chain=root["id"],
178
+ status="pending")
179
+ m["runs"].append(new)
180
+ return new
181
+
182
+
183
+ def memfree_chain(m, root):
184
+ """Table rows for the memory-free retries of root's instance: its attempt 1 (rep 0, only_attempt=1) and the chain
185
+ runs after it. [] while the chain has not ended (a success, or k attempts)."""
186
+ first = attempt_results(root.get("log"))[:1]
187
+ if not first:
188
+ return []
189
+ rows = [dict(root, cond="noharness", rep=0, k=1, only_attempt=1)]
190
+ if first[0]:
191
+ return rows
192
+ chain = {x["rep"]: x for x in m["runs"] if x.get("chain") == root["id"] and x["status"] == "done" and x.get("log")}
193
+ for rep in range(1, root["k"]):
194
+ if rep not in chain:
195
+ return []
196
+ rows.append(dict(chain[rep]))
197
+ if any(attempt_results(chain[rep]["log"])):
198
+ break
199
+ return rows
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------------------ start
203
+ def cmd_start(a):
204
+ a.codex_auth = a.codex_auth or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt")
205
+ if a.harness == "rpent_codex" and a.codex_auth != "apikey":
206
+ sys.exit("Historical RPent adapter supports apikey only")
207
+ if runner_alive(a.batch):
208
+ sys.exit(f"batch {a.batch}: runner already running; stop it first or use another batch name")
209
+ m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[], superseded=[])
210
+ m.update(concurrency=a.concurrency, barrier=not a.no_barrier, port0=a.port0, run_timeout_s=a.run_timeout)
211
+ reps = a.k if a.indep_reps is None else a.indep_reps
212
+ if a.harness != "ours":
213
+ need = HARNESS_PROVIDER[a.harness]
214
+ if a.provider and a.provider != need:
215
+ sys.exit(f"--harness {a.harness} drives {need} models only (got --provider {a.provider})")
216
+ a.provider = need
217
+ elif not a.provider:
218
+ sys.exit("--provider is required with --harness ours")
219
+ claude_auth = None
220
+ if a.harness.startswith("claude_code"):
221
+ claude_auth = a.claude_auth or ("apikey" if a.harness == "claude_code" else "oauth")
222
+ if claude_auth == "oauth" and a.harness == "claude_code":
223
+ sys.exit("--harness claude_code (--bare) takes only an API key; use claude_code_full for a subscription")
224
+ elif a.claude_auth:
225
+ sys.exit("--claude-auth is for --harness claude_code / claude_code_full")
226
+ if a.jail and a.harness == "ours":
227
+ sys.exit("--jail is for native harnesses (the reference driver runs our own code)")
228
+ if a.red_team and a.harness == "ours":
229
+ sys.exit("--red-team is for native harnesses (lffbench/harnesses/redteam.py)")
230
+ if a.memfree == "upfront":
231
+ conds = [c.strip() for c in (a.conds or "noharness,harness").split(",") if c.strip()]
232
+ else:
233
+ if a.conds and a.conds.replace(" ", "") != "harness":
234
+ sys.exit(f"--conds is for --memfree upfront (--memfree {a.memfree} plans history runs only)")
235
+ if a.memfree == "followup" and a.no_hide_k:
236
+ sys.exit("--memfree followup shares attempt 1 of the history run with the memory-free retries: needs --hide-k")
237
+ conds = ["harness"]
238
+ dossiers = json.load(open(a.dossiers)) if a.dossiers else None
239
+ if dossiers is not None: # task:seed -> record dir (scripts/make_dossier.py); every planned instance needs one
240
+ miss = [f"{spec.split(':')[0]}:{sd}" for spec in a.tasks for sd in spec.split(":")[1].split(",")[:a.seeds_per_task]
241
+ if f"{spec.split(':')[0]}:{sd}" not in dossiers]
242
+ if miss:
243
+ sys.exit(f"--dossiers has no record for {miss}")
244
+ bad = [d for d in dossiers.values() if not os.path.isfile(os.path.join(d, "README.md")) or any(c.isspace() for c in d)]
245
+ if bad:
246
+ sys.exit(f"--dossiers: not a record dir (or path with spaces): {bad}")
247
+ n0 = len(m["runs"])
248
+ for cond in conds: # the order of --conds is the order of the phases
249
+ for spec in a.tasks:
250
+ task, seeds = spec.split(":")
251
+ for seed in seeds.split(",")[:a.seeds_per_task]:
252
+ plan = [("harness", "full", a.k, 0)] if cond == "harness" else \
253
+ [("noharness", "none", 1, i) for i in range(reps)]
254
+ for c, mem, k, rep in plan:
255
+ m["runs"].append(dict(id=next_id(m), task=task, seed=int(seed), provider=a.provider,
256
+ agent_harness=a.harness, api_base_url=a.api_base_url,
257
+ max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned,
258
+ jail=a.jail, codex_auth=(("apikey" if a.codex_provider in ("deepseek", "opencode") else a.codex_auth)
259
+ if a.harness in ("codex", *ROBOT_HARNESSES) else None),
260
+ claude_auth=claude_auth,
261
+ codex_catalog=(a.codex_catalog if a.harness in ("codex", *ROBOT_HARNESSES)
262
+ else None),
263
+ **(dict(rpent_sessions=a.rpent_sessions,
264
+ rpent_attempts_per_session=a.rpent_attempts_per_session,
265
+ rpent_max_turns=a.rpent_max_turns)
266
+ if a.harness == "rpent_codex" else {}),
267
+ codex_provider=(a.codex_provider if a.harness == "codex" else None),
268
+ model=a.model, effort=a.effort, cond=c, rep=rep, k=k, mem=mem,
269
+ hide_k=(c == "harness" and not a.no_hide_k), perception=a.perception,
270
+ video=a.video, style="la", feedback=a.feedback, phase=conds.index(cond),
271
+ nominal=a.nominal, followup=(c == "harness" and a.memfree == "followup"),
272
+ arm=a.arm, red_team=a.red_team, dossier=(os.path.abspath(dossiers[f"{task}:{seed}"]) if dossiers else None),
273
+ status="pending"))
274
+ save(a.batch, m)
275
+ print(f"{len(m['runs']) - n0} runs planned ({', '.join(conds)}, --memfree {a.memfree}); manifest {mpath(a.batch)}")
276
+ if a.memfree == "followup":
277
+ print("memory-free retries are added while the batch runs, for instances whose attempt 1 failed")
278
+ print("runner pid", launch_runner(a.batch))
279
+
280
+
281
+ # ------------------------------------------------------------------------------------------------------------ runner
282
+ class Runner:
283
+ def __init__(self, batch):
284
+ self.batch = batch
285
+ self.lock = threading.Lock()
286
+ self.m = load(batch)
287
+ self.used_ports = set()
288
+ self.stop = False
289
+
290
+ def update(self, r, **kw):
291
+ with self.lock:
292
+ r.update(kw)
293
+ save(self.batch, self.m)
294
+
295
+ def next_run(self):
296
+ with self.lock:
297
+ runs = self.m["runs"]
298
+ pending = [r for r in runs if r["status"] == "pending"]
299
+ if not pending:
300
+ # a run still going may yet add a memory-free retry (--memfree followup)
301
+ if any(r["status"] in ACTIVE and (r.get("followup") or r.get("chain")) for r in runs):
302
+ return "wait"
303
+ return None
304
+ if self.m.get("barrier", True):
305
+ phase = min(r["phase"] for r in pending)
306
+ if any(r["status"] in ACTIVE and r["phase"] < phase for r in runs):
307
+ return "wait"
308
+ pending = [r for r in pending if r["phase"] == phase]
309
+ if os.path.exists(os.path.join(bdir(self.batch), "PAUSE")):
310
+ return "wait"
311
+ r = pending[0]
312
+ r["status"] = "starting"
313
+ save(self.batch, self.m)
314
+ return r
315
+
316
+ def port(self):
317
+ with self.lock:
318
+ p = int(self.m.get("port0", 14000))
319
+ while p in self.used_ports or not claude_batch.port_free(p):
320
+ p += 1
321
+ self.used_ports.add(p)
322
+ return p
323
+
324
+ def run_one(self, r):
325
+ port = self.port()
326
+ model_tag = re.sub(r"[^A-Za-z0-9.-]+", "-", r["model"])[:40]
327
+ ah = r.get("agent_harness", "ours")
328
+ if ah != "ours":
329
+ model_tag += "-" + ah.replace("_", "")
330
+ tag = (f"{self.batch}-{model_tag}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}"
331
+ + ("-hidek" if r["hide_k"] else "") + ("-nominal" if r.get("nominal") else "")
332
+ + (f"-{r['arm']}" if r.get("arm", "none") != "none" else "") + ("-dossier" if r.get("dossier") else "")
333
+ + ("-redteam" if r.get("red_team") else ""))
334
+ extra = (" --hide-k" if r["hide_k"] else "") + (" --nominal" if r.get("nominal") else "")
335
+ # docs/14 §6 arms (robot_server --arm / --dossier); LFF_EXTRA_ARGS is word-split, so no spaces in the path
336
+ extra += (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "") + (f" --dossier {r['dossier']}" if r.get("dossier") else "")
337
+ # Frozen, explicit per-task total tool budgets for this evaluation only.
338
+ with open(os.path.join(ROOT, "evaluation_tool_caps.json")) as budget_file:
339
+ task_tool_cap = int(json.load(budget_file)[r["task"]])
340
+ assert task_tool_cap > 0
341
+ extra += f" --max-tool-calls {task_tool_cap}"
342
+ t0 = time.time()
343
+ try:
344
+ sb, log = claude_batch.start_one(r["task"], r["seed"], r["mem"], r["k"], port, tag, r["perception"],
345
+ r["video"], r["style"], extra.strip(), r["feedback"])
346
+ except Exception as e: # server did not come up
347
+ self.update(r, status="server_failed", error=str(e)[-500:], port=port)
348
+ with self.lock:
349
+ self.used_ports.discard(port)
350
+ return
351
+ self.update(r, status="running", port=port, sandbox=sb, log=log, run=os.path.basename(log), t_start=t0)
352
+ opts = ""
353
+ if r.get("api_base_url"):
354
+ opts += f" --api-base-url {shlex.quote(r['api_base_url'])}"
355
+ if r.get("max_budget_usd"):
356
+ opts += f" --max-budget-usd {r['max_budget_usd']}"
357
+ if r.get("allow_unpinned"):
358
+ opts += " --allow-unpinned"
359
+ if r.get("jail"):
360
+ opts += " --jail"
361
+ if r.get("red_team"):
362
+ opts += " --red-team"
363
+ if r.get("codex_auth"):
364
+ opts += f" --codex-auth {r['codex_auth']}"
365
+ if r.get("claude_auth"):
366
+ opts += f" --claude-auth {r['claude_auth']}"
367
+ if r.get("agent_harness") in ("codex", *ROBOT_HARNESSES) and r.get("agent_harness") != "rpent_codex": # runs planned before 10-20 have no catalog: Codex's native one
368
+ opts += f" --codex-catalog {r.get('codex_catalog') or 'native'}"
369
+ if r.get("codex_provider") in ("deepseek", "opencode"):
370
+ opts += f" --codex-provider {r['codex_provider']}"
371
+ if r.get("agent_harness") == "rpent_codex":
372
+ opts += (f" --codex-catalog {r.get('codex_catalog') or 'generic'}"
373
+ f" --rpent-sessions {r.get('rpent_sessions') or 5}"
374
+ f" --rpent-attempts-per-session {r.get('rpent_attempts_per_session', 1)}"
375
+ f" --rpent-max-turns {r.get('rpent_max_turns') or 100}")
376
+ # every harness (also ours: api_player.py with the same arguments as before, its output still in
377
+ # api_player.log) goes through the adapter layer, which adds harness.json / contract.json / trajectory.jsonl
378
+ player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && "
379
+ f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && "
380
+ f"exec python scripts/harness_run.py --harness {ah} --session {log}/session.json "
381
+ f"--provider {r['provider']} --model {shlex.quote(r['model'])} --effort {r['effort']} "
382
+ f"--timeout {int(self.m.get('run_timeout_s', 28800))}{opts} > {log}/harness_run.log 2>&1")
383
+ p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL,
384
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
385
+ self.update(r, player_pid=p.pid)
386
+ status = None
387
+ try:
388
+ code = p.wait(timeout=self.m.get("run_timeout_s", 28800))
389
+ except subprocess.TimeoutExpired:
390
+ os.killpg(p.pid, signal.SIGTERM)
391
+ code, status = p.wait(), "timeout"
392
+ self.stop_server(log)
393
+ if status is None:
394
+ status = "stopped" if self.stop else ("done" if code == 0 else "refused" if code == 2 else "failed")
395
+ self.update(r, status=status, exit_code=code, t_end=time.time(), wall_s=round(time.time() - t0, 1))
396
+ with self.lock:
397
+ self.used_ports.discard(port)
398
+ if plan_followup(self.m, r):
399
+ save(self.batch, self.m)
400
+
401
+ @staticmethod
402
+ def stop_server(log):
403
+ pf = os.path.join(log, "server.pid")
404
+ if not os.path.exists(pf):
405
+ return
406
+ pid = int(open(pf).read())
407
+ try:
408
+ os.kill(pid, signal.SIGTERM) # the server closes rollout.mp4 first
409
+ except ProcessLookupError:
410
+ return
411
+ for _ in range(120):
412
+ if not alive(pid):
413
+ return
414
+ time.sleep(0.5)
415
+
416
+ def worker(self):
417
+ while not self.stop:
418
+ r = self.next_run()
419
+ if r is None:
420
+ return
421
+ if r == "wait":
422
+ time.sleep(5)
423
+ continue
424
+ try:
425
+ self.run_one(r)
426
+ except Exception as e: # keep the other workers going
427
+ self.update(r, status="failed", error=f"runner: {type(e).__name__}: {e}"[:500])
428
+
429
+ def main(self):
430
+ os.environ["LFF_RUNS_DIR"] = bdir(self.batch) # claude_batch.start_one puts the run logs here
431
+ for r in self.m["runs"]: # a previous runner died: its half-started runs go back to pending
432
+ if r["status"] in ACTIVE:
433
+ r["status"] = "pending"
434
+ for r in list(self.m["runs"]): # memory-free retries due but not yet planned (runner died, `followup`)
435
+ plan_followup(self.m, r)
436
+ save(self.batch, self.m)
437
+
438
+ def on_term(*_):
439
+ self.stop = True
440
+ with self.lock:
441
+ for r in self.m["runs"]:
442
+ if r["status"] == "running" and r.get("player_pid"):
443
+ try:
444
+ os.killpg(r["player_pid"], signal.SIGTERM)
445
+ except ProcessLookupError:
446
+ pass
447
+ signal.signal(signal.SIGTERM, on_term)
448
+ ths = [threading.Thread(target=self.worker, daemon=True) for _ in range(int(self.m.get("concurrency", 4)))]
449
+ for t in ths:
450
+ t.start()
451
+ time.sleep(2) # stagger server start-ups
452
+ for t in ths:
453
+ t.join()
454
+ print(time.strftime("%F %T"), "runner finished", flush=True)
455
+
456
+
457
+ def cmd_runner(a):
458
+ Runner(a.batch).main()
459
+
460
+
461
+ # ------------------------------------------------------------------------------------------------------------ views
462
+ def transcript_usage(log):
463
+ tot = dict(calls=0, input_tokens=0, cached_tokens=0, output_tokens=0, api_errors=0, end=None)
464
+ p = os.path.join(log or "", "transcript.jsonl")
465
+ if not os.path.exists(p): # native harness: totals from the unified trajectory
466
+ sys.path.insert(0, ROOT)
467
+ from lffbench.harnesses.trajectory import usage_summary
468
+ u = usage_summary(log)
469
+ if u:
470
+ tot.update(calls=u.get("calls", 0), input_tokens=u.get("total_prompt_tokens") or 0,
471
+ cached_tokens=u.get("total_cached_tokens") or 0,
472
+ output_tokens=u.get("total_completion_tokens") or 0, end=u.get("exit_reason"),
473
+ cost_usd=u.get("total_cost_usd"))
474
+ return tot
475
+ for line in open(p):
476
+ d = json.loads(line)
477
+ if d["ev"] == "assistant":
478
+ tot["calls"] += 1
479
+ for k in ("input_tokens", "cached_tokens", "output_tokens"):
480
+ tot[k] += (d.get("usage") or {}).get(k, 0)
481
+ elif d["ev"] == "api_error":
482
+ tot["api_errors"] += 1
483
+ elif d["ev"] in ("end", "abort"):
484
+ tot["end"] = d["ev"] if d["ev"] == "end" else "abort: " + d.get("reason", "")
485
+ return tot
486
+
487
+
488
+ def cmd_status(a):
489
+ m = load(a.batch)
490
+ counts = {}
491
+ for r in m["runs"]:
492
+ counts[r["status"]] = counts.get(r["status"], 0) + 1
493
+ att = ""
494
+ if r.get("log") and os.path.exists(os.path.join(r["log"], "events.jsonl")):
495
+ ev = [json.loads(line) for line in open(os.path.join(r["log"], "events.jsonl"))]
496
+ att = "".join("S" if e["success"] else "F" for e in ev if e["ev"] == "done")
497
+ u = transcript_usage(r.get("log"))
498
+ print(f"{r['id']} {r['status']:13s} {r.get('agent_harness', 'ours'):16s} "
499
+ f"{r['cond']:9s}{r['rep'] if r['cond'] == 'noharness' else '':1} "
500
+ f"{r['task']:24s} s{r['seed']} {att:4s} calls={u['calls']:3d} api_err={u['api_errors']} "
501
+ f"in={u['input_tokens'] / 1e6:.2f}M out={u['output_tokens'] / 1e3:.0f}k {u['end'] or ''}"
502
+ + (f" (memory-free attempt {r['rep'] + 1} after {r['chain']})" if r.get("chain") else ""))
503
+ print("runner", "alive" if runner_alive(a.batch) else "not running", "|", counts)
504
+
505
+
506
+ def cmd_table(a):
507
+ def done_runs(b):
508
+ m = load(b)
509
+ runs = []
510
+ for r in m["runs"]:
511
+ if not (r.get("log") and r["status"] == "done") or r.get("chain"):
512
+ continue
513
+ runs.append(dict(r))
514
+ if r["cond"] == "harness" and r.get("followup"): # its memory-free chain, once finished
515
+ runs += memfree_chain(m, r)
516
+ for r in runs: # the harness is part of the table's "model" column (claude_batch groups by task, model)
517
+ if r.get("agent_harness", "ours") != "ours":
518
+ r["model"] = f"{r['model']} @ {r['agent_harness']}"
519
+ return dict(m, runs=runs)
520
+ claude_batch.load = done_runs # same manifest fields (task, seed, model, cond, rep, k, log): reuse its table
521
+ # token totals: every run once (the rep-0 row of a chain is attempt 1 of a history run, already counted)
522
+ rows = [r for b in a.batch for r in done_runs(b)["runs"] if not r.get("only_attempt")]
523
+ claude_batch.cmd_table(argparse.Namespace(batch=a.batch))
524
+ by = {}
525
+ for r in rows:
526
+ u = transcript_usage(r["log"])
527
+ t = by.setdefault((r.get("agent_harness", "ours"), r["provider"], r["model"], r["effort"]), [0, 0, 0, 0, 0])
528
+ t[0] += 1
529
+ t[1] += u["calls"]
530
+ t[2] += u["input_tokens"]
531
+ t[3] += u["cached_tokens"]
532
+ t[4] += u["output_tokens"]
533
+ print("\n| harness | provider | model | effort | runs done | model calls | input tokens (M) | of which cached (M) | output tokens (M) |")
534
+ print("|---|---|---|---|---|---|---|---|---|")
535
+ for (h, p, mo, e), t in sorted(by.items()):
536
+ print(f"| {h} | {p} | {mo} | {e} | {t[0]} | {t[1]} | {t[2] / 1e6:.1f} | {t[3] / 1e6:.1f} | {t[4] / 1e6:.2f} |")
537
+
538
+
539
+ def cmd_contract(a):
540
+ """contract_sha256 per (task, seed, cond) and batch; an instance whose hash differs between batches is flagged."""
541
+ import collections
542
+ seen = collections.defaultdict(dict)
543
+ for b in a.batch:
544
+ for r in load(b)["runs"]:
545
+ p = os.path.join(r.get("log") or "", "contract.json")
546
+ if r.get("log") and os.path.exists(p):
547
+ sha = json.load(open(p))["contract_sha256"]
548
+ seen[(r["task"], r["seed"], r["cond"])].setdefault(b, set()).add(sha)
549
+ bad = 0
550
+ print("| task | seed | cond | " + " | ".join(a.batch) + " | same |")
551
+ print("|---|---|---|" + "---|" * len(a.batch) + "---|")
552
+ for (task, seed, cond), per in sorted(seen.items()):
553
+ shas = set().union(*per.values())
554
+ same = len(shas) == 1
555
+ bad += not same
556
+ cells = [",".join(sorted(x[:12] for x in per.get(b, []))) or "-" for b in a.batch]
557
+ print(f"| {task} | {seed} | {cond} | " + " | ".join(cells) + f" | {'yes' if same else '**NO**'} |")
558
+ print(f"\n{len(seen)} instance/condition rows, {bad} with differing contracts")
559
+
560
+
561
+ def cmd_stop(a):
562
+ pf = os.path.join(bdir(a.batch), "runner.pid")
563
+ if os.path.exists(pf) and alive(open(pf).read().strip()):
564
+ os.kill(int(open(pf).read().strip()), signal.SIGTERM) # the runner stops its players and servers
565
+ for _ in range(240):
566
+ if not runner_alive(a.batch):
567
+ break
568
+ time.sleep(0.5)
569
+ m = load(a.batch)
570
+ for r in m["runs"]: # anything left over (runner killed hard)
571
+ if r["status"] in ACTIVE:
572
+ if r.get("player_pid"):
573
+ try:
574
+ os.killpg(r["player_pid"], signal.SIGTERM)
575
+ except ProcessLookupError:
576
+ pass
577
+ if r.get("log"):
578
+ Runner.stop_server(r["log"])
579
+ r["status"] = "stopped"
580
+ save(a.batch, m)
581
+ print("stopped")
582
+
583
+
584
+ def cmd_retry(a):
585
+ if runner_alive(a.batch):
586
+ sys.exit("runner still running: stop it first")
587
+ m = load(a.batch)
588
+ reset = []
589
+ for r in m["runs"]:
590
+ if (a.runs and (r.get("run") in a.runs or r["id"] in a.runs)) or (not a.runs and r["status"] in RETRYABLE):
591
+ if r.get("log"):
592
+ m.setdefault("superseded", []).append(dict(r))
593
+ for k in ("port", "sandbox", "log", "run", "player_pid", "exit_code", "t_start", "t_end", "wall_s", "error"):
594
+ r.pop(k, None)
595
+ r["status"] = "pending"
596
+ reset.append(r)
597
+ # memory-free retries planned after a run that is now re-run were based on attempts that no longer count
598
+ stale = [x for x in m["runs"] if x.get("chain") and all(x is not y for y in reset) and any(
599
+ x["chain"] == y["id"] or (x["chain"] == y.get("chain") and x["rep"] > y["rep"]) for y in reset)]
600
+ for x in stale:
601
+ m["runs"].remove(x)
602
+ if x.get("log"):
603
+ m.setdefault("superseded", []).append(dict(x, superseded_because="earlier attempt of its chain re-run"))
604
+ save(a.batch, m)
605
+ print(len(reset), "runs reset to pending" + (f", {len(stale)} memory-free retries after them dropped" if stale else "")
606
+ + "; runner pid", launch_runner(a.batch))
607
+
608
+
609
+ def cmd_followup(a):
610
+ """Switch a batch to --memfree followup: mark its --hide-k history runs and plan the memory-free retries due for
611
+ those already done. `retry` then starts the runner (and re-runs failed / stopped runs)."""
612
+ if runner_alive(a.batch):
613
+ sys.exit("runner still running: stop it first")
614
+ m = load(a.batch)
615
+ marked = left = 0
616
+ for r in m["runs"]:
617
+ if r["cond"] == "harness" and not r.get("followup"):
618
+ if r.get("hide_k"):
619
+ r["followup"] = True
620
+ marked += 1
621
+ else:
622
+ left += 1
623
+ new = [x for r in list(m["runs"]) for x in [plan_followup(m, r)] if x]
624
+ save(a.batch, m)
625
+ print(f"{marked} history runs switched to --memfree followup"
626
+ + (f" ({left} without --hide-k left out: their attempt 1 is not a fresh agent's)" if left else "")
627
+ + f"; {len(new)} memory-free retries planned")
628
+ print(f"start the runner with: python scripts/api_batch.py retry --batch {a.batch}")
629
+
630
+
631
+ def main():
632
+ ap = argparse.ArgumentParser()
633
+ sub = ap.add_subparsers(dest="cmd", required=True)
634
+ s = sub.add_parser("start")
635
+ s.add_argument("--batch", required=True)
636
+ s.add_argument("--harness", default="ours", choices=NAMES,
637
+ help="agent harness (docs/15); native harnesses imply the provider; rpent_codex = RPent on Codex "
638
+ "(docs/18), OpenAI API key only (LFF_OPENAI_API_KEY)")
639
+ s.add_argument("--provider", default=None, choices=["openai", "anthropic", "gemini", "chat"],
640
+ help="required for --harness ours")
641
+ s.add_argument("--api-base-url", default=None, help="native harnesses: model API endpoint (see harness_run.py)")
642
+ s.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: per-run dollar cap")
643
+ s.add_argument("--allow-unpinned", action="store_true", help="native harnesses: launch without a pin")
644
+ s.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"],
645
+ help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. "
646
+ "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only")
647
+ s.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"],
648
+ help="claude_code*: subscription token (default for claude_code_full) or ANTHROPIC_API_KEY "
649
+ "(claude_code, --bare: apikey only)")
650
+ s.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"],
651
+ help="codex: model provider; deepseek / opencode (OpenCode Go) imply --codex-auth apikey "
652
+ "(see harness_run.py)")
653
+ s.add_argument("--codex-catalog", default="generic", choices=["generic", "native"],
654
+ help="codex: model configuration, the main table's shared one (default) or Codex's native one "
655
+ "(control; see lffbench/harnesses/codex.py)")
656
+ s.add_argument("--rpent-sessions", type=int, default=5, help="rpent_codex: planner sessions per episode")
657
+ s.add_argument("--rpent-attempts-per-session", type=int, default=1,
658
+ help="rpent_codex: attempts one session may use (1 = variant H, default; 0 = no limit)")
659
+ s.add_argument("--rpent-max-turns", type=int, default=100, help="rpent_codex: model responses per session")
660
+ s.add_argument("--jail", action="store_true",
661
+ help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4, lffbench/harnesses/jail.py)")
662
+ s.add_argument("--model", required=True)
663
+ s.add_argument("--effort", default="high")
664
+ s.add_argument("--tasks", nargs="+", required=True, help="task:seed,seed ...")
665
+ s.add_argument("--k", type=int, default=3)
666
+ s.add_argument("--seeds-per-task", type=int, default=None, help="only the first N seeds of each task:seeds")
667
+ s.add_argument("--memfree", default="followup", choices=["followup", "upfront", "none"],
668
+ help="memory-free retries: followup (default) = fresh single-attempt agents only after the history "
669
+ "run's attempt 1 failed, one at a time, up to k attempts in all, stop at the first success; "
670
+ "upfront = --indep-reps independent runs per instance before the history runs; none = no "
671
+ "memory-free retries (see the module docstring)")
672
+ s.add_argument("--indep-reps", type=int, default=None, help="--memfree upfront: independent runs per instance (default k)")
673
+ s.add_argument("--conds", default=None, help="--memfree upfront: conditions in phase order (default noharness,harness)")
674
+ s.add_argument("--no-barrier", action="store_true", help="do not wait for one phase to finish before the next")
675
+ s.add_argument("--no-hide-k", action="store_true", help="history runs: README / status show all k attempts")
676
+ s.add_argument("--concurrency", type=int, default=4)
677
+ s.add_argument("--port0", type=int, default=14000)
678
+ s.add_argument("--run-timeout", type=int, default=28800,
679
+ help="seconds per run before the player is killed (default 8 h: a long-horizon history run can need 300+ model calls)")
680
+ s.add_argument("--perception", default="rgb", choices=["rgb", "rgbd"])
681
+ s.add_argument("--video", action="store_true")
682
+ s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
683
+ s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
684
+ s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
685
+ help="docs/14 §6 controlled arm for every run: twin = same layout, other value of the hidden variable")
686
+ s.add_argument("--red-team", action="store_true",
687
+ help="adversarial acceptance runs (lffbench/harnesses/redteam.py): the agent is told to get a success "
688
+ "without doing the task; own contract; read with scripts/redteam_report.py")
689
+ s.add_argument("--dossiers", default=None,
690
+ help="JSON {\"task:seed\": record dir from scripts/make_dossier.py}: each run gets that record in "
691
+ "history/ and a README section saying an earlier attempt failed (own vs mismatched history)")
692
+ r = sub.add_parser("_runner")
693
+ r.add_argument("--batch", required=True)
694
+ for name in ("status", "stop", "followup"):
695
+ sub.add_parser(name).add_argument("--batch", required=True)
696
+ t = sub.add_parser("table")
697
+ t.add_argument("--batch", nargs="+", required=True)
698
+ ct = sub.add_parser("contract")
699
+ ct.add_argument("--batch", nargs="+", required=True)
700
+ rt = sub.add_parser("retry")
701
+ rt.add_argument("--batch", required=True)
702
+ rt.add_argument("--runs", nargs="*", default=[])
703
+ a = ap.parse_args()
704
+ dict(start=cmd_start, _runner=cmd_runner, status=cmd_status, table=cmd_table, stop=cmd_stop, retry=cmd_retry,
705
+ contract=cmd_contract, followup=cmd_followup)[a.cmd](a)
706
+
707
+
708
+ if __name__ == "__main__":
709
+ main()