PeterXie666 commited on
Commit
3752d7f
·
verified ·
1 Parent(s): e31d057

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_000001_wrist_image.png +3 -0
  2. leaf/final/episode_000037_wrist_image.png +3 -0
  3. leaf/final/episode_000148_wrist_image.png +3 -0
  4. leaf/final/episode_000174_image.png +3 -0
  5. leaf/final/episode_000497_image.png +3 -0
  6. leaf/final/episode_000616.npz +3 -0
  7. leaf/final/episode_000756.npz +3 -0
  8. leaf/final/episode_000795.npz +3 -0
  9. leaf/final/episode_000919.npz +3 -0
  10. leaf/final/episode_000969_wrist_image.png +3 -0
  11. leaf/final/episode_001009.npz +3 -0
  12. leaf/final/episode_001140_wrist_image.png +3 -0
  13. leaf/final/episode_001181_image.png +3 -0
  14. leaf/final/episode_001613_image.png +3 -0
  15. leaf/final/episode_001617_image.png +3 -0
  16. leaf/final/episode_001657.npz +3 -0
  17. leaf/final/episode_002097.npz +3 -0
  18. leaf/final/episode_002127_wrist_image.png +3 -0
  19. leaf/final/episode_002453_wrist_image.png +3 -0
  20. leaf/final/episode_002825.npz +3 -0
  21. leaf/final/episode_002997.npz +3 -0
  22. leaf/final/episode_003258_image.png +3 -0
  23. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py +61 -0
  24. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/batches.json +9 -0
  25. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/rejected.json +1 -0
  26. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/base.py +364 -0
  27. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/check_setup.py +175 -0
  28. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/cs_ir_report.py +87 -0
  29. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/gptpolicy_player.sh +37 -0
  30. leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/run_agent.py +220 -0
  31. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/__init__.py +53 -0
  32. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/l3_under_table_tool.py +50 -0
  33. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py +61 -0
  34. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/l7_key_turn.py +34 -0
  35. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/jail.py +228 -0
  36. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json +15 -0
  37. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json +23 -0
  38. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json +23 -0
  39. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json +36 -0
  40. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l3_tool.py +549 -0
  41. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_fence.py +1030 -0
  42. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_viewer/export.py +219 -0
  43. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/start_real_session.sh +30 -0
  44. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/__init__.py +1 -0
  45. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/images.py +47 -0
  46. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/replay.py +59 -0
  47. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/robot_server.py +966 -0
  48. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/tools.py +392 -0
  49. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/scripts/agent_compare.py +40 -0
  50. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/scripts/api_batch.py +709 -0
leaf/final/episode_000001_wrist_image.png ADDED

Git LFS Details

  • SHA256: 8b075bf76d8f29c2759bba6b5a617127a9c3370c7482f0335ce708df42d50ca4
  • Pointer size: 130 Bytes
  • Size of remote file: 40 kB
leaf/final/episode_000037_wrist_image.png ADDED

Git LFS Details

  • SHA256: 023dcdf07d9ceb8b78a3f62b446b8fa44106b7ec28a4bead8bc03567c585b40f
  • Pointer size: 130 Bytes
  • Size of remote file: 42.6 kB
leaf/final/episode_000148_wrist_image.png ADDED

Git LFS Details

  • SHA256: 25332191f84d63c78ed6d8d4d19d0c47440fd39c83ddc49d13c9659b40677375
  • Pointer size: 130 Bytes
  • Size of remote file: 40.5 kB
leaf/final/episode_000174_image.png ADDED

Git LFS Details

  • SHA256: 96d22c2282bf0d54d94cf1a21cee49580aaae050b2b46849ffd0ab430c8cd705
  • Pointer size: 130 Bytes
  • Size of remote file: 53.9 kB
leaf/final/episode_000497_image.png ADDED

Git LFS Details

  • SHA256: d4ab30692041248a002e26fb15e6166fc4c9a38ca0338e1d277eced2f7c292dd
  • Pointer size: 130 Bytes
  • Size of remote file: 55 kB
leaf/final/episode_000616.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72266971401994016b74c4d8739e2e61ddfd89aa88364c0d1a628e77f2e3a4db
3
+ size 4062
leaf/final/episode_000756.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75ddae55af875229ac3ab72a692ce24826fcb9bbea8fbc8463dd18335098b51a
3
+ size 3942
leaf/final/episode_000795.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cad1b2463d4f6dbf929c15aeda4f39ab2710cb0fac06a7225b5c7ba7c37a3843
3
+ size 3942
leaf/final/episode_000919.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ad279630e4f98985b6580836ce03a40aae453d839a15b2bd1bc839e36cf710b
3
+ size 4046
leaf/final/episode_000969_wrist_image.png ADDED

Git LFS Details

  • SHA256: 881db1e22cc77087ce8b593b89e8aed98aaac3e0499638baf85eea37102ea54b
  • Pointer size: 130 Bytes
  • Size of remote file: 38.9 kB
leaf/final/episode_001009.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:59728dc5dcfcb31ae051250aa3e5a0f2dbeaeef23fc713a3b18c4eb405b51704
3
+ size 3942
leaf/final/episode_001140_wrist_image.png ADDED

Git LFS Details

  • SHA256: 13bdb212237ae3994836279883fd3b226a53ce8a6bdef76c10a32f9fe47308a4
  • Pointer size: 130 Bytes
  • Size of remote file: 31 kB
leaf/final/episode_001181_image.png ADDED

Git LFS Details

  • SHA256: 159630dd07a472f23506c64b426829739fd0b6a601b404ec1bf0177dc0382cd7
  • Pointer size: 130 Bytes
  • Size of remote file: 55.8 kB
leaf/final/episode_001613_image.png ADDED

Git LFS Details

  • SHA256: 1e517837cd5d0afc009e492a1db4dc66c320b1823160e811d4d5d392f79fdbfd
  • Pointer size: 130 Bytes
  • Size of remote file: 55.3 kB
leaf/final/episode_001617_image.png ADDED

Git LFS Details

  • SHA256: fd8eeeff4289d4ca21c5da9993400761817063130b17711d73fbae78194acd54
  • Pointer size: 130 Bytes
  • Size of remote file: 56.2 kB
leaf/final/episode_001657.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c570a39b7554890f60428dbada8601255eac79e9dbaed2e515a4e8591df6b77
3
+ size 3630
leaf/final/episode_002097.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8fc05d846b92226e55fc2f6ba01a0cc15ba69adb378efe850176c2e889b26d71
3
+ size 3734
leaf/final/episode_002127_wrist_image.png ADDED

Git LFS Details

  • SHA256: 34f8cb6e28dc49b00bf7cbf259580e74729de2bb8f0671ed62a83076d3f9ea11
  • Pointer size: 130 Bytes
  • Size of remote file: 28.8 kB
leaf/final/episode_002453_wrist_image.png ADDED

Git LFS Details

  • SHA256: 83def609004292cac968d55a70fb6da2e4cc0f4c51a5472c6c00f63cf70766f1
  • Pointer size: 130 Bytes
  • Size of remote file: 45.6 kB
leaf/final/episode_002825.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a82f59a5a75a28f477d1db9284a0f154425836d84222c17d380c2cfcf3815e5
3
+ size 3838
leaf/final/episode_002997.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22c1e743966626301d374fac9a0fbe58c621abf39a1f8a68d676599e27b80abb
3
+ size 3942
leaf/final/episode_003258_image.png ADDED

Git LFS Details

  • SHA256: 39328bc231434fe7da1e3c7102f8ca68744db1df347703171499b7b2ade942c2
  • Pointer size: 130 Bytes
  • Size of remote file: 55.9 kB
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l5_tablecloth_pull (docs/14 §6).
2
+
3
+ Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset,
4
+ oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled
5
+ from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu.
6
+
7
+ Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed
8
+ up to ~0.8 m/s (0.8 and 1.0 m/s give identical results: the controller saturates). The naive policy yanks at 0.6 m/s.
9
+ Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull
10
+ slower".
11
+
12
+ h0 mu at which the 0.6 m/s yank lands the cube on the band's centre line (calibrated per full5 seed by a
13
+ simulated sweep; a linear fit in band_d for other seeds).
14
+ twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot
15
+ (err +1.5 .. +2.7 cm), so the lesson is "pull faster" (the twin's oracle pulls at 0.64-0.79 m/s; agents can
16
+ command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short.
17
+ The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the
18
+ twin's naive error is only ~1.5-2.7 cm (similar size to the original's short-fall) and the twin's oracle is
19
+ within 0.2-0.5 cm of the band tolerance on some seeds. Calibrated per seed; for other seeds 1.2 x the H0 mu.
20
+ reveal states the cube's friction coefficient (the only fact that differs between instances).
21
+ """
22
+
23
+ HIDDEN_KEYS = ("mu",)
24
+
25
+ # Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim).
26
+ # seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm])
27
+ _CAL = {
28
+ 3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60
29
+ 3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47
30
+ 3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78
31
+ 3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44
32
+ 3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51
33
+ }
34
+
35
+
36
+ def _h0_mu(inst):
37
+ c = _CAL.get(int(inst.get("seed", -1)))
38
+ return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"])
39
+
40
+
41
+ def h0(inst):
42
+ return {"mu": float(_h0_mu(inst))}
43
+
44
+
45
+ def twin(inst):
46
+ c = _CAL.get(int(inst.get("seed", -1)))
47
+ return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))}
48
+
49
+
50
+ def reveal(inst):
51
+ return (f"The red cube's friction coefficient (against the board and against the table) is about "
52
+ f"{float(inst['mu']):.3f}.")
53
+
54
+
55
+ def fix(inst, params):
56
+ """Ladder Fix rung (docs/20): one pull of 25 cm at the oracle speed (bisection with the true mu), as
57
+ l5_tablecloth_pull.execute; move_eef speed = Skills.move_to speed."""
58
+ v = float(params["speed"])
59
+ return (f"A way to succeed: pull at the right speed. Grasp the black handle (jaws closing across its 4 cm width), "
60
+ f"then in one move_eef command pull the board straight towards the robot by 25 cm at speed {v:.2f}; then "
61
+ f"open the gripper and lift. The cube then lands in the green band.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/batches.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "clh_20261102_gpt": {
3
+ "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source/runs/api/clh_20261102_gpt/manifest.json",
4
+ "supplement": true,
5
+ "selected_runs": 18,
6
+ "exported_runs": 18,
7
+ "note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config."
8
+ }
9
+ }
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/rejected.json ADDED
@@ -0,0 +1 @@
 
 
1
+ []
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/base.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness adapter interface (docs/15 §3).
2
+
3
+ An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log
4
+ dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations).
5
+ Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server /
6
+ reference driver enforce them identically for every harness.
7
+
8
+ name stable harness name (the "harness" column of a table)
9
+ capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source;
10
+ a missing item makes the class definition fail (so the import fails)
11
+ version() the actual installed version (probed before launch)
12
+ prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env
13
+ launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle
14
+ collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason
15
+ audit(h) tool list, preset prompt, memory, state left behind, violations
16
+ """
17
+ import dataclasses
18
+ import json
19
+ import os
20
+ import secrets
21
+ import shutil
22
+ import signal
23
+ import subprocess
24
+ import time
25
+
26
+ from . import contract as C
27
+
28
+ EVIDENCE = ("launch", "stream", "server", "probe", "preflight")
29
+
30
+ REQUIRED = {
31
+ "only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use",
32
+ "images_reach_model": "view_images returns the image bytes to the model unchanged",
33
+ "non_persistent_session": "nothing of the session is written to disk for later runs",
34
+ "pinned_version": "the harness version (and binary hash) is recorded and pinned",
35
+ "machine_readable_events": "a machine-readable event stream of the whole run",
36
+ "tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)",
37
+ "model_and_effort": "model and reasoning effort can be set and are visible in the request",
38
+ }
39
+ FORBIDDEN = {
40
+ "persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)",
41
+ "instruction_file_injection": "instruction files picked up from the work / config / home dir",
42
+ "web_access": "web search / fetch",
43
+ "host_file_read": "reading host files outside the episode workspace",
44
+ "builtin_shell": "a shell of the harness itself (outside our jailed shell tool)",
45
+ "subagent_delegation": "spawning sub-agents",
46
+ "background_execution": "background tasks that outlive a tool call",
47
+ }
48
+
49
+
50
+ @dataclasses.dataclass(frozen=True)
51
+ class Cap:
52
+ status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial"
53
+ evidence: str # one of EVIDENCE
54
+ note: str = ""
55
+
56
+
57
+ PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")
58
+ NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
59
+ NO_PROXY_LOCAL = "127.0.0.1,localhost,::1"
60
+
61
+
62
+ def proxy_env(environ=None):
63
+ """The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines
64
+ that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list.
65
+ Not part of config_sha256 (machine plumbing, not harness configuration)."""
66
+ environ = os.environ if environ is None else environ
67
+ e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)}
68
+ if e:
69
+ e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS})
70
+ return e
71
+
72
+
73
+ class CapabilityError(TypeError):
74
+ pass
75
+
76
+
77
+ def check_capabilities(name, caps):
78
+ if not isinstance(caps, dict):
79
+ raise CapabilityError(f"{name}: capabilities must be a dict")
80
+ missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps]
81
+ extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN]
82
+ if missing or extra:
83
+ raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}")
84
+ for k, c in caps.items():
85
+ if not isinstance(c, Cap) or c.evidence not in EVIDENCE:
86
+ raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})")
87
+ ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial")
88
+ if c.status not in ok:
89
+ raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}")
90
+
91
+
92
+ class HarnessRefused(RuntimeError):
93
+ """Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one."""
94
+
95
+
96
+ @dataclasses.dataclass
97
+ class EpisodeSpec:
98
+ session_path: str
99
+ log_dir: str
100
+ sandbox: str
101
+ port: int
102
+ token: str
103
+ max_tool_calls: int
104
+ model: str
105
+ effort: str
106
+ provider: str = ""
107
+ task: str = ""
108
+ seed: int = 0
109
+ extra: dict = dataclasses.field(default_factory=dict)
110
+
111
+ @classmethod
112
+ def from_session(cls, session_path, model, effort, provider="", **extra):
113
+ session_path = os.path.abspath(session_path)
114
+ log_dir = os.path.dirname(session_path)
115
+ sess = json.load(open(session_path))
116
+ iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
117
+ st = C.session_start(log_dir)
118
+ return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]),
119
+ token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort,
120
+ provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra)
121
+
122
+
123
+ @dataclasses.dataclass
124
+ class LaunchSpec:
125
+ argv: list # full argv (the first message may be one element)
126
+ env: dict # the complete environment of the harness process (nothing else is inherited)
127
+ cwd: str
128
+ run_dir: str = "" # one-time dir tree, removed after audit
129
+ state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...)
130
+ first_message: str = ""
131
+ config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote
132
+ stdout_path: str = ""
133
+ stderr_path: str = ""
134
+ redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log
135
+ preflight: dict = dataclasses.field(default_factory=dict)
136
+ timeout_s: float = 10800
137
+
138
+
139
+ @dataclasses.dataclass
140
+ class RunHandle:
141
+ spec: LaunchSpec
142
+ ep: EpisodeSpec
143
+ proc: object = None
144
+ pid: int = 0
145
+ t_start: float = 0.0
146
+ t_end: float = 0.0
147
+ exit_code: int = None
148
+ exit_reason: str = ""
149
+ env_observed_keys: list = None # read from /proc/<pid>/environ right after the start
150
+ info: dict = dataclasses.field(default_factory=dict)
151
+
152
+
153
+ def env_keys_of(pid):
154
+ try:
155
+ raw = open(f"/proc/{pid}/environ", "rb").read()
156
+ except OSError:
157
+ return None
158
+ return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv})
159
+
160
+
161
+ def new_run_dir(root="/tmp/lffrun"):
162
+ """/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses)."""
163
+ os.makedirs(root, exist_ok=True)
164
+ while True:
165
+ d = os.path.join(root, secrets.token_hex(6))
166
+ try:
167
+ os.mkdir(d, 0o700)
168
+ return d
169
+ except FileExistsError:
170
+ continue
171
+
172
+
173
+ def binary_info(path):
174
+ real = os.path.realpath(path)
175
+ return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None)
176
+
177
+
178
+ class HarnessAdapter:
179
+ name = None
180
+ capabilities = None
181
+ uses_mcp = False
182
+ uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for
183
+ # this adapter: MCP adapters through the MCP server, framework adapters
184
+ # (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN
185
+ clean_dirs = () # keys of spec.state_dirs that must be empty at launch
186
+ clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json)
187
+ ancestor_files = () # instruction files that must not exist in the work dir or any ancestor
188
+ unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read)
189
+ jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4)
190
+ can_resume = False # resume(): the CLI can continue its session with one more user message
191
+
192
+ def clean_state_problems(self, spec):
193
+ """Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an
194
+ ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md)."""
195
+ p = []
196
+ if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd):
197
+ p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}")
198
+ for k in self.clean_dirs:
199
+ d = spec.state_dirs.get(k)
200
+ left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else []
201
+ if left:
202
+ p.append(f"{k} dir not empty: {sorted(left)[:5]}")
203
+ d = spec.cwd
204
+ while d and d != "/":
205
+ d = os.path.dirname(d)
206
+ for f in self.ancestor_files:
207
+ if os.path.exists(os.path.join(d, f)):
208
+ p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}")
209
+ return p
210
+
211
+ def __init_subclass__(cls, **kw):
212
+ super().__init_subclass__(**kw)
213
+ if cls.name is None:
214
+ raise CapabilityError(f"{cls.__name__}: no name")
215
+ check_capabilities(cls.name, cls.capabilities)
216
+
217
+ # -------------------------------------------------------------------------------------------- interface
218
+ def version(self):
219
+ raise NotImplementedError
220
+
221
+ def prepare(self, ep, first_message):
222
+ raise NotImplementedError
223
+
224
+ def preflight(self, spec, ep):
225
+ """Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused."""
226
+ return dict(skipped=True)
227
+
228
+ def collect(self, h):
229
+ raise NotImplementedError
230
+
231
+ def audit(self, h):
232
+ raise NotImplementedError
233
+
234
+ # -------------------------------------------------------------------------------------------- shared
235
+ def mcp_server_command(self, python, script, args):
236
+ """(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it."""
237
+ if self.jail is not None:
238
+ return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"})
239
+ return python, [script] + list(args)
240
+
241
+ def jailed_argv(self, argv, env, cwd, dirs):
242
+ """argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back."""
243
+ return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv)
244
+
245
+ def jail_info(self):
246
+ return self.jail.info() if self.jail is not None else dict(enabled=False)
247
+
248
+ def auth_info(self):
249
+ """How the harness authenticates to the model API (for harness.json; never a secret)."""
250
+ return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {}))
251
+
252
+ def launch(self, spec, ep, skip_preflight=False):
253
+ if not self.unsafe_skip_clean_check:
254
+ probs = self.clean_state_problems(spec)
255
+ if probs:
256
+ spec.preflight = dict(problems=probs)
257
+ raise HarnessRefused("clean-state check: " + "; ".join(probs))
258
+ spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep)
259
+ out = open(spec.stdout_path, "wb")
260
+ err = open(spec.stderr_path, "wb")
261
+ h = RunHandle(spec=spec, ep=ep, t_start=time.time())
262
+ argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
263
+ h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
264
+ stderr=err, start_new_session=True)
265
+ h.pid = h.proc.pid
266
+ for _ in range(20): # the exec has happened once /proc/<pid>/environ differs from ours
267
+ keys = env_keys_of(h.pid)
268
+ if keys is not None and set(keys) == set(spec.env):
269
+ break
270
+ time.sleep(0.05)
271
+ h.env_observed_keys = env_keys_of(h.pid)
272
+ return h
273
+
274
+ def resume_argv(self, h, message):
275
+ """argv that continues the run's session with one more user message (adapters with can_resume)."""
276
+ raise NotImplementedError
277
+
278
+ def resume(self, h, message):
279
+ """Continue the run's session with one more user message, after the CLI exited before the episode was over
280
+ (scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output
281
+ is appended to the same stdout / stderr files."""
282
+ spec = h.spec
283
+ argv = self.resume_argv(h, message)
284
+ out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab")
285
+ jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
286
+ h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
287
+ stderr=err, start_new_session=True)
288
+ h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, ""
289
+ keys = None
290
+ for _ in range(20):
291
+ keys = env_keys_of(h.pid)
292
+ if keys is not None and set(keys) == set(spec.env):
293
+ break
294
+ time.sleep(0.05)
295
+ h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message,
296
+ argv=[("<message>" if x == message else x) for x in argv],
297
+ env_observed_keys=keys))
298
+ return h
299
+
300
+ def wait(self, h, timeout=None):
301
+ try:
302
+ h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s)
303
+ h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}"
304
+ except subprocess.TimeoutExpired:
305
+ self.kill(h)
306
+ h.exit_reason = "timeout"
307
+ h.t_end = time.time()
308
+ return h
309
+
310
+ @staticmethod
311
+ def kill(h):
312
+ try:
313
+ os.killpg(h.proc.pid, signal.SIGTERM)
314
+ h.exit_code = h.proc.wait(timeout=20)
315
+ except ProcessLookupError:
316
+ pass
317
+ except subprocess.TimeoutExpired:
318
+ os.killpg(h.proc.pid, signal.SIGKILL)
319
+ h.exit_code = h.proc.wait()
320
+
321
+ def logged_argv(self, spec):
322
+ return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)]
323
+
324
+ def cleanup(self, spec):
325
+ if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir):
326
+ shutil.rmtree(spec.run_dir, ignore_errors=True)
327
+ for d in spec.state_dirs.values():
328
+ if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d):
329
+ shutil.rmtree(d, ignore_errors=True)
330
+ if self.jail is not None:
331
+ self.jail.close()
332
+
333
+
334
+ def gateway_env(log_dir):
335
+ """{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose
336
+ process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before
337
+ launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the
338
+ gateway's, never robot_server's."""
339
+ d = json.load(open(os.path.join(log_dir, "gateway.json")))
340
+ return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]}
341
+
342
+
343
+ def snapshot_tree(root):
344
+ """Relative paths of all files under root (to list what a harness left behind)."""
345
+ out = []
346
+ for dp, dn, fn in os.walk(root):
347
+ for f in fn:
348
+ out.append(os.path.relpath(os.path.join(dp, f), root))
349
+ return sorted(out)
350
+
351
+
352
+ def first_message_text(readme, status_json):
353
+ """What a native harness gets as its first user message: the reference driver's instructions (preamble + README,
354
+ byte-identical) followed by its first user turn (the status report). The reference driver sends the same two
355
+ strings as system prompt and first user message; native harnesses keep their own system prompt."""
356
+ from .contract import tool_schemas
357
+ _, preamble = tool_schemas()
358
+ return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json
359
+
360
+
361
+ def reference_instructions(readme):
362
+ from .contract import tool_schemas
363
+ _, preamble = tool_schemas()
364
+ return preamble + readme
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/check_setup.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check that this machine can run LFF-Bench. Run after `source run_env.sh`:
2
+
3
+ python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail
4
+ python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY /
5
+ # OPENAI_BASE_URL from the environment or from .env); costs a few tokens
6
+ python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail
7
+
8
+ Exit code 0 when every check that ran passed.
9
+ """
10
+ import argparse
11
+ import os
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ import time
16
+
17
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18
+ sys.path.insert(0, ROOT)
19
+ JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py
20
+
21
+ results = []
22
+
23
+
24
+ def report(name, ok, detail=""):
25
+ results.append(ok)
26
+ print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True)
27
+ return ok
28
+
29
+
30
+ def check_packages():
31
+ report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0])
32
+ from lffbench.agent.backends.base import import_openai
33
+ for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"):
34
+ try:
35
+ m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"])
36
+ report(f"import {mod}", True, getattr(m, "__version__", ""))
37
+ except Exception as e: # noqa: BLE001
38
+ report(f"import {mod}", False, f"{type(e).__name__}: {e}")
39
+ cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml")
40
+ if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")):
41
+ import yaml
42
+ assets = yaml.safe_load(open(cfg)).get("assets", "")
43
+ report("LIBERO assets", os.path.isdir(assets), assets)
44
+ report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}")
45
+
46
+
47
+ def check_sim(task_name, seed):
48
+ import importlib
49
+ import pkgutil
50
+
51
+ try:
52
+ import lffbench.tasks as task_pkg
53
+ from lffbench.task_base import TASKS
54
+ except Exception as e: # noqa: BLE001
55
+ report("import lffbench", False, f"{type(e).__name__}: {e}")
56
+ return
57
+ try:
58
+ for m in pkgutil.iter_modules(task_pkg.__path__):
59
+ importlib.import_module(f"lffbench.tasks.{m.name}")
60
+ except Exception as e: # noqa: BLE001
61
+ report("import tasks", False, f"{type(e).__name__}: {e}")
62
+ return
63
+ report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks")
64
+ t0 = time.time()
65
+ try:
66
+ task = TASKS[task_name]()
67
+ inst = task.sample_instance(seed)
68
+ task.reset_instance(inst)
69
+ img = task.snapshot()
70
+ out = task.outcome(inst)
71
+ except Exception as e: # noqa: BLE001
72
+ report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}")
73
+ return
74
+ ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0
75
+ report(f"simulate + render {task_name}", ok,
76
+ f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s")
77
+
78
+
79
+ def check_jail():
80
+ if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"),
81
+ JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"):
82
+ return
83
+ probe = r'''
84
+ echo "pwd=$(pwd)"
85
+ python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1
86
+ echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)"
87
+ python3 -c "
88
+ import socket
89
+ s = socket.socket(); s.settimeout(3)
90
+ try:
91
+ s.connect(('1.1.1.1', 443)); print('net=open')
92
+ except OSError as e:
93
+ print('net=blocked')
94
+ "
95
+ touch made_in_jail && echo "write=ok"
96
+ '''
97
+ with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws:
98
+ argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws,
99
+ "timeout", "-k", "5", "60", "bash", "-c", probe]
100
+ r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
101
+ kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l)
102
+ if r.returncode != 0 and not kv:
103
+ hint = ""
104
+ if "Operation not permitted" in r.stdout or "uid_map" in r.stdout:
105
+ hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: "
106
+ "sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0")
107
+ report("jail runs", False, r.stdout.strip()[-400:] + hint)
108
+ return
109
+ report("jail runs", True, f"workdir {kv.get('pwd')}")
110
+ report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:]))
111
+ report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0",
112
+ f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}")
113
+ report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?"))
114
+ report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail")))
115
+
116
+
117
+ def load_env_file():
118
+ path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
119
+ if not os.path.isfile(path):
120
+ return None
121
+ for line in open(path):
122
+ line = line.strip()
123
+ if line and not line.startswith("#") and "=" in line:
124
+ k, v = line.split("=", 1)
125
+ os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\""))
126
+ return path
127
+
128
+
129
+ def check_api(model, effort):
130
+ src = load_env_file()
131
+ if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"):
132
+ os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # same as scripts/gpt_player.py
133
+ if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")),
134
+ f"from {src}" if src else "from the environment (no .env)"):
135
+ return
136
+ base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)"
137
+ from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend
138
+ t0 = time.time()
139
+ try:
140
+ client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client()
141
+ resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping",
142
+ reasoning=dict(effort=effort), store=False, max_output_tokens=256)
143
+ text = (resp.output_text or "").strip()
144
+ u = resp.usage
145
+ report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, "
146
+ f"tokens in {u.input_tokens} / out {u.output_tokens}")
147
+ except Exception as e: # noqa: BLE001
148
+ report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}")
149
+
150
+
151
+ def main():
152
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
153
+ ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint")
154
+ ap.add_argument("--model", default="gpt-6-astra")
155
+ ap.add_argument("--effort", default="low")
156
+ ap.add_argument("--task", default="l5_slide_to_target")
157
+ ap.add_argument("--seed", type=int, default=1000)
158
+ ap.add_argument("--skip-sim", action="store_true")
159
+ ap.add_argument("--skip-jail", action="store_true")
160
+ a = ap.parse_args()
161
+ os.environ.setdefault("OMP_NUM_THREADS", "1")
162
+ check_packages()
163
+ if not a.skip_sim:
164
+ check_sim(a.task, a.seed)
165
+ if not a.skip_jail:
166
+ check_jail()
167
+ if a.api:
168
+ check_api(a.model, a.effort)
169
+ n_bad = results.count(False)
170
+ print(f"\n{len(results) - n_bad}/{len(results)} checks passed")
171
+ sys.exit(1 if n_bad else 0)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/cs_ir_report.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reproduce the CS/IR audit tables from read-only manifests and hash-bound evidence."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import api_batch
7
+ import outcomes
8
+ from outcome_audit import load_audit, sha256
9
+
10
+ GROUPS = {"GPT": ["cx_main1"], "Sonnet": ["cc_main1"], "Opus": ["cc_opus1"],
11
+ "DeepSeek": ["ds_cx1", "ds_cx1b"]}
12
+
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument("--runs-root", required=True)
17
+ parser.add_argument("--audit", required=True)
18
+ parser.add_argument("--out", required=True)
19
+ args = parser.parse_args()
20
+ api_batch.RUNS = str(Path(args.runs_root).resolve())
21
+ audit = load_audit(args.audit)
22
+ output = Path(args.out)
23
+ output.mkdir(parents=True, exist_ok=True)
24
+ all_rows, models, manifests, coverage = [], {}, {}, {}
25
+ for model, batches in GROUPS.items():
26
+ old, new = [], []
27
+ for batch in batches:
28
+ manifest = api_batch.load(batch)
29
+ manifests[batch] = sha256(api_batch.mpath(batch))
30
+ old += outcomes.instance_rows(manifest, batch=batch)
31
+ new += outcomes.instance_rows(manifest, audit=audit, batch=batch)
32
+ for run in manifest["runs"]:
33
+ if not (run["cond"] == "harness" and run.get("followup") and run["status"] == "done"):
34
+ continue
35
+ attempts = outcomes.attempts(run["log"])
36
+ if attempts:
37
+ coverage.setdefault(run["task"], set()).update(
38
+ k for k in outcomes.ERROR_FLAGS + outcomes.ERROR_COUNTS if k in attempts[0][2])
39
+ before, after = outcomes.summary(old), outcomes.summary(new)
40
+ for key in ("n", "A1", "A3", "XR", "F", "n_paired", "A3_paired", "passk_paired", "delta_paired"):
41
+ assert before[key] == after[key], f"Audit unexpectedly changed {model} {key}"
42
+ assert len({(r["task"], r["seed"]) for r in new}) == len(new), "duplicate model/task/seed"
43
+ models[model] = dict(before=before, after=after)
44
+ all_rows += [dict(r, model=model) for r in new]
45
+ payload = dict(schema="lff-cs-ir-report-1", source_manifests_sha256=manifests,
46
+ audit_sha256=sha256(args.audit), models=models, rows=all_rows,
47
+ legacy_counter_coverage={k: sorted(v) for k, v in coverage.items()})
48
+ (output / "summary.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
49
+ lines = ["# CS / IR 证据审计表(2026-10-24)", "",
50
+ "本表由 `scripts/cs_ir_report.py` 生成;定义、局限、合并说明见同目录 `README.md`。",
51
+ "旧口径是 task counter heuristic;新口径是逐 run 的物理失败 + 主动修复证据审计。",
52
+ "A1、A3、XR、F、配对样本及 Δ_hist 均逐项断言保持不变。", "",
53
+ "| 模型 | 旧 CS / IR / S? | 审计 CS / IR / S? | 原 S? 已补 | A1 | A3 |",
54
+ "|---|---|---|---|---|---|"]
55
+ for model, pair in models.items():
56
+ b, a = pair["before"], pair["after"]
57
+ resolved = sum(r["model"] == model and r["legacy_cls"] == "S?" and r["cls"] != "S?" for r in all_rows)
58
+ lines.append(f"| {model} | {b['CS']} / {b['IR']} / {b['S?']} | {a['CS']} / {a['IR']} / {a['S?']} | "
59
+ f"{resolved}/{b['S?']} | {a['A1']}/{a['n']} | {a['A3']}/{a['n']} |")
60
+ lines += ["", "## 每任务新旧分类与原统一字段覆盖", "",
61
+ "`旧→新`;只有一个标签表示未变。`缺失` 不是没有错误;有字段也不代表覆盖抓空/掉落等全部失败。", "",
62
+ "| 任务 | GPT | Sonnet | Opus | DeepSeek | 原统一错误字段 |", "|---|---|---|---|---|---|"]
63
+ for task, counters in coverage.items():
64
+ cells = []
65
+ for model in GROUPS:
66
+ row = next(r for r in all_rows if r["model"] == model and r["task"] == task)
67
+ cells.append(row["cls"] if row["cls"] == row["legacy_cls"] else f"{row['legacy_cls']}→{row['cls']}")
68
+ lines.append("| " + " | ".join([task] + cells + [", ".join(sorted(counters)) or "缺失"]) + " |")
69
+ lines += ["", "## 首次成功的证据链", "", "行号均指原 run 文件,E 为 events.jsonl,T 为 trajectory.jsonl;s 为机器人命令序号。", ""]
70
+ for row in all_rows:
71
+ if not row["a1"]:
72
+ continue
73
+ entry = audit.get((row["batch"], row["run_id"]))
74
+ manifest = api_batch.load(row["batch"])
75
+ run = next(r for r in manifest["runs"] if r["id"] == row["run_id"])
76
+ lines += [f"### {row['model']} · {row['task']} · {row['legacy_cls']} → {row['cls']}", "",
77
+ row["audit_basis"], "", f"[原 events.jsonl]({run['log']}/events.jsonl) · "
78
+ f"[原 trajectory.jsonl]({run['log']}/trajectory.jsonl)", ""]
79
+ if entry:
80
+ lines += [f"证据索引:{entry.get('evidence', '')}", "",
81
+ f"归因范围:`{entry.get('failure_scope', 'not_adjudicated')}`。", ""]
82
+ (output / "TABLES.md").write_text("\n".join(lines) + "\n")
83
+ print(json.dumps(models, ensure_ascii=False, indent=2))
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/gptpolicy_player.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Drive one robot_server session with the GPT-Policy harness (frameworks/gpt-policy, simulated
3
+ # lffbench_sim adapter + OpenAI Responses provider, GPT-6 Astra, reasoning effort medium).
4
+ #
5
+ # usage: scripts/gptpolicy_player.sh <LOG>/session.json [extra gpt-policy-lffbench options]
6
+ # e.g. LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10340 direct 3 gptpolicy rgb 1
7
+ # scripts/gptpolicy_player.sh runs/claude/gptpolicy_l1_bias_place_s3000_..._p10340/session.json
8
+ # The robot_server interface (v1 / v2) is detected from the first status reply.
9
+ #
10
+ # Writes into the session's LOG directory: gptpolicy_transcript.jsonl (every model request/response,
11
+ # images as file paths + sha256, every robot-server call), final_report.md, gptpolicy_player.log and
12
+ # GPT-Policy's own recording gptpolicy_run_*/. The robot server writes events.jsonl and rollout.mp4.
13
+ # The server is stopped at the end (it has finished the episode, and rollout.mp4 is closed by then).
14
+ set -uo pipefail
15
+ [ $# -ge 1 ] || { echo "usage: $0 <LOG>/session.json [options]"; exit 2; }
16
+ SESSION=$(readlink -f "$1"); shift
17
+ LOG=$(dirname "$SESSION")
18
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
19
+ [ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh"
20
+ # GPT-Policy checkout + venv from integrations/gpt-policy/setup.sh (override: GPTPOLICY_VENV)
21
+ VENV=${GPTPOLICY_VENV:-$ROOT/third_party/gpt-policy/.venv}
22
+ ENVF=${LFF_ENV_FILE:-$ROOT/.env}
23
+ [ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } # OPENAI_API_KEY / OPENAI_BASE_URL / SSL_CERT_FILE (never echoed)
24
+ export PYTHONUNBUFFERED=1
25
+ stop_server() { # also on abnormal exit; SIGTERM makes the server close rollout.mp4 first
26
+ if [ "${GPTPOLICY_KEEP_SERVER:-0}" != "1" ] && [ -f "$LOG/server.pid" ]; then
27
+ kill "$(cat "$LOG/server.pid")" 2>/dev/null || true
28
+ fi
29
+ }
30
+ trap stop_server EXIT
31
+ trap 'exit 143' TERM INT HUP
32
+ cd /tmp # neutral working directory; the model has no file access anyway
33
+ "$VENV/bin/gpt-policy-lffbench" --session "$SESSION" --model "${GPTPOLICY_MODEL:-gpt-6-astra}" \
34
+ --effort "${GPTPOLICY_EFFORT:-medium}" "$@" 2>&1 | tee -a "$LOG/gptpolicy_player.log"
35
+ RC=${PIPESTATUS[0]}
36
+ echo "gptpolicy_player.sh: gpt-policy-lffbench exit code $RC" >> "$LOG/gptpolicy_player.log"
37
+ exit $RC
leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/scripts/run_agent.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run an agent backend on an LFF-Bench task and log everything.
2
+
3
+ source run_env.sh && export OMP_NUM_THREADS=1
4
+ python scripts/run_agent.py --task l5_slide_to_target --backend scripted --memory full --feedback F2 --n 3 --k 5
5
+ python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory full --n 20 --k 5
6
+
7
+ Writes runs/agent/<task>/<timestamp>_<backend>_<memory>_<feedback>/ with config.json, events.jsonl
8
+ (every LLM call with tokens + latency, every tool call with its report, every attempt's outcome and
9
+ feedback), images/ (every image the model saw, as the exact JPEG sent) and summary.json (succ@k per run,
10
+ first-success attempt, ΔICL fields, tokens / cost / latency).
11
+ """
12
+ import argparse
13
+ import importlib
14
+ import json
15
+ import os
16
+ import pkgutil
17
+ import sys
18
+ import time
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+
23
+
24
+ def load_tasks():
25
+ import lffbench.tasks as task_pkg
26
+ from lffbench.task_base import TASKS
27
+ for m in pkgutil.iter_modules(task_pkg.__path__):
28
+ try:
29
+ importlib.import_module(f"lffbench.tasks.{m.name}")
30
+ except Exception as e: # other people's task files may be mid-edit; do not let them break this run
31
+ print(f"[warn] could not import lffbench.tasks.{m.name}: {e!r}", file=sys.stderr)
32
+ return TASKS
33
+
34
+
35
+ def parse(argv=None):
36
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
37
+ ap.add_argument("--task", required=True)
38
+ ap.add_argument("--backend", choices=["scripted", "openai", "chat"], default="scripted")
39
+ ap.add_argument("--memory", choices=["none", "full", "last", "mismatched"], default="full")
40
+ ap.add_argument("--feedback", choices=["F0", "F1", "F2"], default="F2")
41
+ ap.add_argument("--n", type=int, default=3, help="number of instances (runs)")
42
+ ap.add_argument("--k", type=int, default=None, help="attempts per run (default: task.max_attempts)")
43
+ ap.add_argument("--seed0", type=int, default=1000, help="first instance seed (dev seeds 1000+, use 5000+ for test)")
44
+ ap.add_argument("--seeds", default=None, help="explicit comma-separated seeds (overrides --seed0/--n)")
45
+ ap.add_argument("--out", default=os.path.join(ROOT, "runs", "agent"))
46
+ ap.add_argument("--tag", default="")
47
+ # harness
48
+ ap.add_argument("--instruction", choices=["direct", "indirect"], default="direct")
49
+ ap.add_argument("--privileged-locate", action="store_true", help="ablation: add locate(object_name)")
50
+ ap.add_argument("--image-res", type=int, default=512)
51
+ ap.add_argument("--keyframe-res", type=int, default=None)
52
+ ap.add_argument("--keyframes", type=int, default=4)
53
+ ap.add_argument("--max-steps", type=int, default=30, help="tool calls per attempt")
54
+ ap.add_argument("--no-auto-obs", action="store_true", help="send images only on get_observation")
55
+ ap.add_argument("--grasp-report", choices=["bool", "name", "none"], default="bool")
56
+ ap.add_argument("--early-stop", choices=["auto", "yes", "no"], default="auto")
57
+ ap.add_argument("--jpeg-quality", type=int, default=90)
58
+ ap.add_argument("--no-save-images", action="store_true")
59
+ # mismatched memory
60
+ ap.add_argument("--donor-run", default=None, help="run dir whose attempts serve as mismatched histories")
61
+ ap.add_argument("--donor-offset", type=int, default=10000,
62
+ help="without --donor-run: donor instance seed = seed + offset, generated with memory=full")
63
+ # scripted
64
+ ap.add_argument("--scripted-policy", choices=["adaptive", "naive", "oracle", "blind"], default="adaptive")
65
+ ap.add_argument("--dry-run-payload", action="store_true",
66
+ help="for non-openai backends: also build the GPT-6 request for every call and log its size")
67
+ ap.add_argument("--dump-requests", type=int, default=0,
68
+ help="write the first N OpenAI requests (images elided) to requests/ for inspection")
69
+ # openai
70
+ ap.add_argument("--model", default="gpt-6-astra")
71
+ ap.add_argument("--effort", default="medium", help="reasoning effort: low|medium|high|xhigh|max")
72
+ ap.add_argument("--reasoning-summary", default="auto", choices=["auto", "concise", "detailed", "none"],
73
+ help="request and log model-returned summaries by default; none disables the request")
74
+ ap.add_argument("--image-detail", default="auto", help="low|high|original|auto")
75
+ ap.add_argument("--max-output-tokens", type=int, default=None)
76
+ ap.add_argument("--service-tier", default=None)
77
+ ap.add_argument("--prompt-cache-retention", default=None, help="in-memory | 24h")
78
+ ap.add_argument("--max-live-images", type=int, default=16)
79
+ ap.add_argument("--extra-body", default=None, help="JSON merged into the request body (new API fields)")
80
+ ap.add_argument("--cache-breakpoints", choices=["none", "history", "history+last"], default="history+last",
81
+ help="explicit prompt_cache_breakpoint markers (set none if a gateway rejects the field)")
82
+ ap.add_argument("--prompt-cache-options", default=None, help='JSON, e.g. {"ttl": "30m"}')
83
+ # chat (OpenAI-compatible local server)
84
+ ap.add_argument("--chat-base-url", default=None)
85
+ ap.add_argument("--chat-model", default="qwen3-vl-8b")
86
+ ap.add_argument("--chat-max-tokens", type=int, default=1024)
87
+ return ap.parse_args(argv)
88
+
89
+
90
+ def redact_request(req):
91
+ """Copy of a request with base64 images replaced by a short marker."""
92
+ def red(o):
93
+ if isinstance(o, dict):
94
+ return {k: (f"<data url, {len(v)} chars>" if k in ("image_url", "url") and isinstance(v, str)
95
+ and v.startswith("data:") else red(v)) for k, v in o.items()}
96
+ if isinstance(o, list):
97
+ return [red(v) for v in o]
98
+ if isinstance(o, str) and len(o) > 2000 and o.startswith("gAAAA"): # encrypted reasoning
99
+ return f"<encrypted, {len(o)} chars>"
100
+ return o
101
+ return red(req)
102
+
103
+
104
+ def build_backend(args):
105
+ from lffbench.agent.backends import make_backend
106
+ if args.backend == "scripted":
107
+ return make_backend("scripted", policy=args.scripted_policy)
108
+ if args.backend == "openai":
109
+ if not os.environ.get("OPENAI_API_KEY"):
110
+ sys.exit("OPENAI_API_KEY is not set (and OPENAI_BASE_URL if you use a proxy / gateway).")
111
+ return make_backend("openai", model=args.model, reasoning_effort=args.effort,
112
+ reasoning_summary=None if args.reasoning_summary == "none" else args.reasoning_summary,
113
+ image_detail=args.image_detail,
114
+ max_output_tokens=args.max_output_tokens, service_tier=args.service_tier,
115
+ prompt_cache_retention=args.prompt_cache_retention, max_live_images=args.max_live_images,
116
+ jpeg_quality=args.jpeg_quality, cache_breakpoints=args.cache_breakpoints,
117
+ prompt_cache_options=json.loads(args.prompt_cache_options) if args.prompt_cache_options
118
+ else None, extra_body=json.loads(args.extra_body) if args.extra_body else None)
119
+ return make_backend("chat", model=args.chat_model, base_url=args.chat_base_url, max_tokens=args.chat_max_tokens,
120
+ max_live_images=min(args.max_live_images, 4), jpeg_quality=args.jpeg_quality)
121
+
122
+
123
+ def main(argv=None):
124
+ args = parse(argv)
125
+ from lffbench.agent.harness import AgentHarness, HarnessConfig, config_dict
126
+ from lffbench.agent.metrics import aggregate
127
+ from lffbench.agent.replay import derange, load_records
128
+ from lffbench.agent.runlog import RunLogger
129
+
130
+ tasks = load_tasks()
131
+ if args.task not in tasks:
132
+ sys.exit(f"unknown task {args.task}; known: {sorted(tasks)}")
133
+ backend = build_backend(args)
134
+ seeds = [int(s) for s in args.seeds.split(",")] if args.seeds else list(range(args.seed0, args.seed0 + args.n))
135
+ cfg = HarnessConfig(memory=args.memory, feedback=args.feedback, k=args.k, image_res=args.image_res,
136
+ keyframe_res=args.keyframe_res, n_keyframes=args.keyframes, auto_obs=not args.no_auto_obs,
137
+ max_steps=args.max_steps, privileged_locate=args.privileged_locate,
138
+ grasp_report=args.grasp_report, instruction=args.instruction, early_stop=args.early_stop,
139
+ jpeg_quality=args.jpeg_quality, save_images=not args.no_save_images,
140
+ model_for_cost=args.model if args.backend == "openai" else "none")
141
+ stamp = time.strftime("%Y%m%d-%H%M%S")
142
+ name = f"{stamp}_{args.backend}{'-' + args.scripted_policy if args.backend == 'scripted' else ''}_{args.memory}_" \
143
+ f"{args.feedback}" + (f"_{args.tag}" if args.tag else "")
144
+ run_dir = os.path.join(args.out, args.task, name)
145
+ os.makedirs(run_dir, exist_ok=True)
146
+ log = RunLogger(run_dir, save_images=cfg.save_images, jpeg_quality=cfg.jpeg_quality)
147
+
148
+ t0 = time.time()
149
+ task = tasks[args.task]()
150
+ print(f"[run_agent] env built in {time.time() - t0:.1f}s -> {run_dir}", flush=True)
151
+ k = args.k or task.max_attempts
152
+
153
+ probe = None
154
+ if args.backend == "openai":
155
+ probe = None
156
+ elif args.dry_run_payload or args.dump_requests:
157
+ from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend
158
+ probe = OpenAIResponsesBackend(model=args.model, reasoning_effort=args.effort, image_detail=args.image_detail,
159
+ max_live_images=args.max_live_images, jpeg_quality=args.jpeg_quality,
160
+ cache_breakpoints=args.cache_breakpoints, client=object())
161
+ if args.dump_requests:
162
+ os.makedirs(os.path.join(run_dir, "requests"), exist_ok=True)
163
+ dumped = [0]
164
+ target = backend if args.backend == "openai" else probe
165
+ orig = target.build_request
166
+
167
+ def build_and_dump(conv, tools, _orig=orig):
168
+ req = _orig(conv, tools)
169
+ if dumped[0] < args.dump_requests:
170
+ dumped[0] += 1
171
+ with open(os.path.join(run_dir, "requests", f"request_{dumped[0]:03d}.json"), "w") as f:
172
+ json.dump(redact_request(req), f, indent=1)
173
+ return req
174
+ target.build_request = build_and_dump
175
+
176
+ log.write_json("config.json", dict(argv=sys.argv, args=vars(args), harness=config_dict(cfg),
177
+ backend=backend.config(), task=dict(name=task.name, level=task.level,
178
+ protocol=task.protocol, k=k,
179
+ capabilities=list(task.capabilities))))
180
+ harness = AgentHarness(task, backend, cfg, log, payload_probe=probe if args.backend != "openai" else None)
181
+
182
+ donors = {}
183
+ if args.memory == "mismatched":
184
+ if args.donor_run:
185
+ pool = load_records(args.donor_run, task=task, feedback=args.feedback)
186
+ m = derange(seeds, pool)
187
+ donors = {s: pool[m[s]] for s in seeds}
188
+ else:
189
+ dlog = RunLogger(os.path.join(run_dir, "donors"), save_images=True, jpeg_quality=cfg.jpeg_quality)
190
+ dcfg = HarnessConfig(**{**config_dict(cfg), "memory": "full", "early_stop": "auto"})
191
+ dh = AgentHarness(task, backend, dcfg, dlog)
192
+ for s in seeds:
193
+ _, recs = dh.run_instance(s + args.donor_offset)
194
+ donors[s] = recs
195
+ print(f"[donor] seed={s + args.donor_offset} first_success="
196
+ f"{next((r.attempt for r in recs if r.success), None)}", flush=True)
197
+ dlog.close()
198
+
199
+ runs = []
200
+ for i, s in enumerate(seeds):
201
+ summ, recs = harness.run_instance(s, donor=donors.get(s))
202
+ runs.append(summ)
203
+ print(f"[{i + 1}/{len(seeds)}] seed={s} first_success={summ['first_success']} attempts={summ['n_attempts']} "
204
+ f"status={summ['status']} llm_calls={summ['n_llm_calls']} tool_calls={summ['n_tool_calls']} "
205
+ f"({time.time() - t0:.0f}s)", flush=True)
206
+ agg = aggregate(runs, k)
207
+ log.write_json("summary.json", dict(task=args.task, backend=backend.config(), memory=args.memory,
208
+ feedback=args.feedback, k=k, seeds=seeds, aggregate=agg,
209
+ runs=[{kk: v for kk, v in r.items() if not kk.startswith("_")} for r in runs]))
210
+ log.close()
211
+ print(json.dumps({kk: agg[kk] for kk in ("n_runs", "n_error_runs", "succ_at", "attempt1_success",
212
+ "mean_first_success", "pass_at_k_iid_analytic", "repeated_action_rate",
213
+ "llm_calls_per_run", "tool_calls_per_run", "sim_wall_per_run_s")},
214
+ default=str))
215
+ print(f"[run_agent] done -> {run_dir}")
216
+ return run_dir, agg, runs
217
+
218
+
219
+ if __name__ == "__main__":
220
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-task specs for the controlled arms of full5 (2026-10-12, docs/14 §6).
2
+
3
+ One module per task, named exactly like the task (lffbench/arm_specs/<task_name>.py), defining:
4
+
5
+ HIDDEN_KEYS : tuple of instance keys that carry the hidden variable(s)
6
+ h0(inst) -> dict overrides for the H0 twin: same layout, hidden variable at its "ordinary" value, so the
7
+ common-sense first attempt succeeds (scripted naive succeeds)
8
+ twin(inst) -> dict overrides for the mismatched-history source: same layout, the trap is still active (scripted
9
+ naive still fails, visibly) but the right correction is different from the original instance's,
10
+ ideally opposite (e.g. centre of mass on the other side)
11
+ reveal(inst)-> str H+ text appended to the task instruction: the hidden variable stated plainly in robot-frame
12
+ words a careful human could act on, without prescribing the solution
13
+
14
+ All three take the ORIGINAL sampled instance and return only the keys to change (JSON-serialisable). The server
15
+ applies them with dict.update() after sample_instance(); reset_instance() must honour them.
16
+ """
17
+ import importlib
18
+
19
+
20
+ def load(task_name):
21
+ """The spec module for task_name, or None if the task has no controlled-arm spec."""
22
+ try:
23
+ return importlib.import_module(f"{__name__}.{task_name}")
24
+ except ModuleNotFoundError as e:
25
+ if e.name == f"{__name__}.{task_name}":
26
+ return None
27
+ raise
28
+
29
+
30
+ def overrides(task_name, arm, inst):
31
+ """Instance overrides for arm in (h0, twin); {} for other arms."""
32
+ if arm not in ("h0", "twin"):
33
+ return {}
34
+ spec = load(task_name)
35
+ if spec is None:
36
+ raise SystemExit(f"--arm {arm}: no spec in lffbench/arm_specs/{task_name}.py")
37
+ return getattr(spec, arm)(inst)
38
+
39
+
40
+ def reveal(task_name, inst):
41
+ spec = load(task_name)
42
+ if spec is None:
43
+ raise SystemExit(f"--arm hplus: no spec in lffbench/arm_specs/{task_name}.py")
44
+ return spec.reveal(inst)
45
+
46
+
47
+ def fix(task_name, inst, params):
48
+ """Fix-rung text of the layer-3 feedback ladder (docs/20): how to succeed on this instance, in robot-frame words,
49
+ built from the task's oracle parameters `params` (task.oracle_params(inst), computed by the caller with the sim)."""
50
+ spec = load(task_name)
51
+ if spec is None or not hasattr(spec, "fix"):
52
+ raise SystemExit(f"ladder fix: no fix() in lffbench/arm_specs/{task_name}.py")
53
+ return spec.fix(inst, params)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/l3_under_table_tool.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l3_under_table_tool (2026-10-12).
2
+
3
+ Hidden variable: inst["pane_side"] -- the y side of the low glass table that is closed by an invisible clear acrylic
4
+ panel (+1 = robot's left, -1 = right; sampled as -side, i.e. the side away from the stick, where the bin stands).
5
+ apply_instance turns on the collision of the panel whose side equals pane_side (inst.get("pane_side", -side)); a
6
+ value matching neither side (0) leaves both panels off.
7
+
8
+ h0 pane_side = 0: no panel. The prior (slide the stick in and push the cube straight across, out towards the bin)
9
+ gets the cube out on the bin's side, then grasps it and drops it in the bin.
10
+ twin pane_side = side: the panel closes the OTHER y side -- the side the stick lies on -- instead of the bin's side.
11
+ The prior still fails visibly, but differently: the stick's head runs into the panel at the table edge and
12
+ the cube is not touched / stays under the glass (original: the cube is pushed across and stops against the
13
+ panel at the bin's side). The blocked side is the opposite one. Measured (seeds 3000-3004): twin naive fails
14
+ 5/5 with F2 mode "blocked" (stick stopped at the panel, the hand ran into the glass edge, cube did not move).
15
+ Limitation: with a single panel on a y side, the reference correction is the same in both (push the cube out
16
+ of the open FRONT side from behind the table; oracle_params ignores the instance), so the cross check
17
+ "twin oracle on the original" succeeds (measured 5/5). A twin whose correction fails on the original would need a second
18
+ panel / panels on the front or back side plus a new scripted push (task-file change); not done.
19
+ reveal Which side is closed, in the words of the task's F2 feedback.
20
+ """
21
+ HIDDEN_KEYS = ("pane_side",)
22
+
23
+
24
+ def _pane_side(inst):
25
+ return int(inst.get("pane_side", -inst["side"]))
26
+
27
+
28
+ def h0(inst):
29
+ return {"pane_side": 0}
30
+
31
+
32
+ def twin(inst):
33
+ return {"pane_side": -_pane_side(inst)}
34
+
35
+
36
+ def reveal(inst):
37
+ ps = _pane_side(inst)
38
+ lr = "the robot's left" if ps > 0 else "the robot's right"
39
+ return (f"A clear acrylic panel, invisible in the camera images, closes the side of the low glass table on {lr} "
40
+ f"(between its two legs, from the tabletop up to the glass); nothing can pass under the table edge on that "
41
+ f"side.")
42
+
43
+
44
+ def fix(inst, params):
45
+ """Ladder Fix rung (docs/20): oracle mode front -- push the cube out of the low table's front side with the stick."""
46
+ return ("A way to succeed: do not push the cube out on the panel's side. Pick the stick up, turn it in the air so "
47
+ "that it points forward (away from the robot), put it down on the table behind the low table (on the "
48
+ "robot's side), in line with the cube. Grasp it again near its handle end and slide it straight forward "
49
+ "under the glass top so that its head pushes the cube out of the low table's front side (the side away "
50
+ "from the robot). Then pull the stick back, put it down, grasp the cube and put it into the bin.")
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l3_wall_flush (2026-10-12).
2
+
3
+ Hidden variable: inst["gap"] -- the box-wall gap, 0-3 mm (below camera resolution), far less than the ~1.2 cm a
4
+ finger needs, so the wall-side finger lands on the wall top. sample_instance caches the wall position derived from it
5
+ (wall_x = box_x + side * (wall half thickness + box half width + gap)) and apply_instance reads only inst["wall_xy"],
6
+ so every override below sets wall_xy as well.
7
+
8
+ h0 gap = 5 cm: box, plate, wall length and wall y unchanged, the wall moved 4.7-5 cm away from the box (on the
9
+ same side). There is room for the whole finger and the prior (grasp across the width where the box lies) works.
10
+ (2.5 cm was not enough: the open fingers reach 6.6 cm from the grasp centre, so with the wall on the far side
11
+ the outer edge of the finger still caught the wall top and the box slipped out on the way, seeds 3000 / 3003.)
12
+ twin Gap unchanged (box still flush, trap active), box / plate / wall length / wall x unchanged, but the wall slid
13
+ along y so that the box sits near the OTHER end of the wall, 2 cm of wall beyond the box's end (the sampler's
14
+ extreme). The original's nearer wall end is +y (or -y); the twin's is -y (or +y): the push that clears the
15
+ wall goes the opposite way, and is the shortest possible push (about 10 + 4.5 cm).
16
+ Note: pushing the original's box towards its FAR end also clears the wall (just a longer push), so the cross
17
+ check "twin oracle on the original" succeeds (measured 5/5, seeds 3000-3004; results/l3_wall_flush/arms/
18
+ validate.json). The twin changes which way to push, not whether pushing works.
19
+ reveal The gap, and on which side of the box the wall is, in the task's F2 frame words.
20
+ """
21
+ BOX_HALF_X, BOX_HALF_Y, WALL_HALF_T = 0.03, 0.08, 0.015
22
+ H0_GAP = 0.05
23
+
24
+ HIDDEN_KEYS = ("gap",)
25
+
26
+
27
+ def _wall_x(inst, gap):
28
+ return inst["box_xy"][0] + inst["side"] * (WALL_HALF_T + BOX_HALF_X + gap)
29
+
30
+
31
+ def h0(inst):
32
+ return {"gap": H0_GAP, "wall_xy": [_wall_x(inst, H0_GAP), inst["wall_xy"][1]]}
33
+
34
+
35
+ def twin(inst):
36
+ wy, by = inst["wall_xy"][1], inst["box_xy"][1]
37
+ u_max = inst["wall_hl"] - BOX_HALF_Y - 0.02
38
+ nearer = 1 if by - wy > 0 else -1 # same rule as WallFlush._nearer_end
39
+ u_twin = -nearer * u_max # box offset from the wall centre in the twin: near the other end
40
+ return {"wall_xy": [inst["wall_xy"][0], by - u_twin]}
41
+
42
+
43
+ def reveal(inst):
44
+ side = "far side (away from the robot)" if inst["side"] > 0 else "near side (toward the robot)"
45
+ return (f"The long box is pressed against the wall on its {side} along its whole length: the gap between box "
46
+ f"and wall is only about {max(100 * inst['gap'], 0.1):.1f} cm.")
47
+
48
+
49
+ def fix(inst, params):
50
+ """Ladder Fix rung (docs/20): push the box along the wall past its nearer end (oracle end, margin 4.5 cm), then
51
+ grasp across the width and place."""
52
+ end, margin = int(params["end"]), float(params["margin"])
53
+ wy, hl, by = float(inst["wall_xy"][1]), float(inst["wall_hl"]), float(inst["box_xy"][1])
54
+ wall_end = wy + hl if end > 0 else wy - hl
55
+ dist = max(0.0, end * (wall_end + end * margin - by))
56
+ side, other = ("left", "right") if end > 0 else ("right", "left")
57
+ return (f"A way to succeed: first get the box away from the wall, then grasp it. With the gripper closed and the "
58
+ f"fingertips about 1 cm above the table, push on the box's end face on the robot's {other} side and slide "
59
+ f"the box slowly (speed about 0.08) along the wall towards the robot's {side}, about {100 * dist:.0f} cm, "
60
+ f"until the whole box is past the end of the wall (its centre about {100 * margin:.1f} cm beyond the "
61
+ f"wall's end). Then lift, open the gripper, grasp the box across its 6 cm width and put it on the plate.")
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/l7_key_turn.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled-arm spec for l7_key_turn (2026-10-12).
2
+
3
+ Hidden variable: inst["direction"], the way the key opens the lock ("CCW" or "CW", seen from above). apply_instance()
4
+ derives the joint range and outcome()/check_unlock()/oracle_params() derive the open sign from it on every reset, so
5
+ overriding "direction" alone is enough (nothing is cached at sampling time).
6
+
7
+ The scripted prior (naive) turns counterclockwise, so the trap exists only on CW locks -- all full5 instances are CW.
8
+
9
+ h0 -> direction = "CCW": same lock position / yaw, the key opens the common-sense way, naive succeeds.
10
+ twin -> {} (no valid twin). The task has a single binary hidden variable and the trap exists only for one of its two
11
+ values: a twin with the trap still active must be CW again, i.e. need exactly the same correction ("turn
12
+ clockwise"), and the sign-flipped twin (CCW) is the H0 twin, where naive succeeds. There is no second hidden
13
+ constraint (the required angle is the fixed quarter turn named in the instruction). The mismatched-history
14
+ arm therefore has to take another instance's history -- note that every trap instance's history teaches the
15
+ same correction, so for this task a mismatched history is not misleading about the direction.
16
+ reveal -> states which way the key turns and that the other way stops after ~3 deg (the words "clockwise",
17
+ "counterclockwise", "seen from above" are those of the task's F2 feedback).
18
+ """
19
+
20
+ HIDDEN_KEYS = ("direction",)
21
+
22
+
23
+ def h0(inst):
24
+ return {"direction": "CCW"}
25
+
26
+
27
+ def twin(inst):
28
+ return {}
29
+
30
+
31
+ def reveal(inst):
32
+ ok, other = (("counterclockwise", "clockwise") if inst["direction"] == "CCW" else ("clockwise", "counterclockwise"))
33
+ return (f"Note: this lock opens only when the key is turned {ok} (seen from above); turned {other} the key moves "
34
+ f"about 3 degrees and then hits a hard stop.")
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/jail.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Jail for native harness processes (docs/15 §3.4): the harness sees no host path at all, instead of only "having no
2
+ tool that reads files".
3
+
4
+ Without it, Claude Code / Codex run as root on the host with /mnt visible (task code with the hidden-variable rules,
5
+ task cards, earlier runs' logs, .secrets); isolation then rests on every built-in tool being switched off. With it
6
+ (adapter option jail=True, `harness_run.py --jail`, `api_batch.py start --jail`):
7
+ - the harness runs as the unprivileged host user nobody (uid 65534) in new user + mount namespaces
8
+ (jail/harness_jail_inner.sh, installed under /opt/lffjail/hjail by jail/setup_harness_jail.sh): /mnt /home /root
9
+ /tmp /run/secrets /etc/dsw are empty tmpfs, system dirs read-only, all capabilities dropped; the network stays
10
+ (model API);
11
+ - /proc: "static" (Codex) = a read-only tmpfs with static copies of host-wide files (CPU, memory, kernel version) and
12
+ the process's own self/ entries, no other pid; "host" (Claude Code, a Bun executable that aborts without a real
13
+ procfs; a fresh procfs cannot be mounted in this container because its /proc has locked submounts) = the host
14
+ procfs, where as uid 65534 the harness can list processes and read their command lines but not their environ, fd,
15
+ cwd or root (checked in tests/harness_selfcheck/jail_probe.py);
16
+ - visible again, at their original paths: the one-time work dir, the one-time state dir and the socket dir of the
17
+ MCP relay (chowned to uid 65534); the harness binary runs from a verified copy of its release dir under
18
+ /opt/lffjail/hjail/bin (the original lives under 0700 dirs in /mnt);
19
+ - the MCP server (scripts/mcp_robot_server.py) runs outside the jail; the harness starts the relay
20
+ /opt/lffjail/hjail/mcp_fwd.py, which connects to a Unix socket served here: every connection gets its own MCP
21
+ server process with stdin / stdout on the socket and the environment {PATH} only.
22
+ The harness command line (except argv[0] = the copy), its environment (exact whitelist) and the paths it sees are
23
+ unchanged; only the MCP server entry of its config points to the relay.
24
+ """
25
+ import hashlib
26
+ import os
27
+ import secrets
28
+ import shutil
29
+ import socket
30
+ import subprocess
31
+ import threading
32
+
33
+ JAIL_DIR = "/opt/lffjail/hjail"
34
+ INNER = os.path.join(JAIL_DIR, "inner.sh")
35
+ RELAY = os.path.join(JAIL_DIR, "mcp_fwd.py")
36
+ BIN_DIR = os.path.join(JAIL_DIR, "bin")
37
+ RELAY_PYTHON = "/usr/bin/python3"
38
+ SOCK_ROOT = "/tmp/lffsock"
39
+ JAIL_UID = 65534
40
+ MAX_BINDS = 16
41
+
42
+
43
+ class JailError(RuntimeError):
44
+ pass
45
+
46
+
47
+ def installed_problems():
48
+ p = []
49
+ for f in (INNER, RELAY):
50
+ if not os.path.exists(f):
51
+ p.append(f"{f} missing (sudo bash jail/setup_harness_jail.sh)")
52
+ if not os.path.isdir(os.path.join(JAIL_DIR, "stage", str(MAX_BINDS - 1))):
53
+ p.append(f"{JAIL_DIR}/stage/0..{MAX_BINDS - 1} missing (sudo bash jail/setup_harness_jail.sh)")
54
+ if not os.access(RELAY_PYTHON, os.X_OK):
55
+ p.append(f"{RELAY_PYTHON} missing")
56
+ for t in ("unshare", "setpriv"):
57
+ if not shutil.which(t):
58
+ p.append(f"{t} not found")
59
+ return p
60
+
61
+
62
+ def sha256_file(path):
63
+ h = hashlib.sha256()
64
+ with open(path, "rb") as f:
65
+ for b in iter(lambda: f.read(1 << 20), b""):
66
+ h.update(b)
67
+ return h.hexdigest()
68
+
69
+
70
+ def _outermost(dirs):
71
+ """Drop directories that lie inside another one of the list (one bind mount covers them)."""
72
+ ds = sorted({os.path.realpath(d) for d in dirs if d}, key=len)
73
+ out = []
74
+ for d in ds:
75
+ if not any(d == o or d.startswith(o.rstrip("/") + "/") for o in out):
76
+ out.append(d)
77
+ return out
78
+
79
+
80
+ def _chown_tree(root, uid):
81
+ os.chown(root, uid, uid)
82
+ for dp, dn, fn in os.walk(root):
83
+ for n in dn + fn:
84
+ try:
85
+ os.lchown(os.path.join(dp, n), uid, uid)
86
+ except FileNotFoundError:
87
+ pass
88
+
89
+
90
+ def binary_copy(binary):
91
+ """A verified copy of the binary's release dir under /opt/lffjail/hjail/bin (readable by uid 65534); returns
92
+ (path of the binary in the copy, info). The release dir is the binary's dir, or its parent if that is a bin/."""
93
+ real = os.path.realpath(binary)
94
+ if not os.path.isfile(real):
95
+ raise JailError(f"harness binary {binary} -> {real} not found")
96
+ sha = sha256_file(real)
97
+ rel_root = os.path.dirname(real)
98
+ if os.path.basename(rel_root) == "bin":
99
+ rel_root = os.path.dirname(rel_root)
100
+ dst_root = os.path.join(BIN_DIR, f"{os.path.basename(rel_root)}-{sha[:12]}")
101
+ dst = os.path.join(dst_root, os.path.relpath(real, rel_root))
102
+ if not (os.path.isfile(dst) and sha256_file(dst) == sha):
103
+ os.makedirs(BIN_DIR, mode=0o755, exist_ok=True)
104
+ tmp = dst_root + ".tmp-" + secrets.token_hex(3)
105
+ shutil.copytree(rel_root, tmp, symlinks=True)
106
+ for dp, dn, fn in os.walk(tmp):
107
+ os.chmod(dp, 0o755)
108
+ if os.path.exists(dst_root):
109
+ shutil.rmtree(dst_root)
110
+ os.rename(tmp, dst_root)
111
+ if sha256_file(dst) != sha:
112
+ raise JailError(f"copy of {real} does not match its sha256")
113
+ return dst, dict(original=real, copy=dst, sha256=sha)
114
+
115
+
116
+ class _Relay:
117
+ """Serves one Unix socket; each connection gets a fresh MCP server process attached to it."""
118
+
119
+ def __init__(self, sock_path, argv, env, stderr_path, uid):
120
+ self.path, self.argv, self.env, self.stderr_path = sock_path, argv, env, stderr_path
121
+ self.procs = []
122
+ self.closed = False
123
+ self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
124
+ self.srv.bind(sock_path)
125
+ os.chown(sock_path, uid, uid)
126
+ os.chmod(sock_path, 0o600)
127
+ self.srv.listen(8)
128
+ self.t = threading.Thread(target=self._serve, daemon=True)
129
+ self.t.start()
130
+
131
+ def _serve(self):
132
+ while not self.closed:
133
+ try:
134
+ conn, _ = self.srv.accept()
135
+ except OSError:
136
+ return
137
+ try:
138
+ err = open(self.stderr_path, "ab") if self.stderr_path else subprocess.DEVNULL
139
+ p = subprocess.Popen(self.argv, stdin=conn.fileno(), stdout=conn.fileno(), stderr=err, env=self.env,
140
+ cwd="/", start_new_session=True)
141
+ self.procs.append(p)
142
+ if err is not subprocess.DEVNULL:
143
+ err.close()
144
+ finally:
145
+ conn.close()
146
+
147
+ def close(self):
148
+ self.closed = True
149
+ try:
150
+ self.srv.close()
151
+ except OSError:
152
+ pass
153
+ for p in self.procs:
154
+ if p.poll() is None:
155
+ p.terminate()
156
+ for p in self.procs:
157
+ try:
158
+ p.wait(timeout=10)
159
+ except subprocess.TimeoutExpired:
160
+ p.kill()
161
+
162
+
163
+ class HarnessJail:
164
+ """One per adapter instance. mcp_command() registers a real MCP server command and returns the relay command for
165
+ the harness config; wrap() turns the harness argv into the jailed one; close() stops relays and removes sockets."""
166
+
167
+ def __init__(self, binary, proc="static", uid=JAIL_UID, stderr_dir=None):
168
+ probs = installed_problems()
169
+ if probs:
170
+ raise JailError("; ".join(probs))
171
+ if proc not in ("static", "host"):
172
+ raise JailError(f"proc must be static or host, not {proc!r}")
173
+ self.binary_real = os.path.realpath(binary)
174
+ self.binary_jailed, self.binary_info = binary_copy(binary)
175
+ self.proc, self.uid = proc, uid
176
+ self.sock_dir = None
177
+ self.relays = []
178
+ self.stderr_dir = stderr_dir
179
+
180
+ def info(self):
181
+ return dict(enabled=True, uid=self.uid, proc=self.proc, binary=self.binary_info, inner=INNER,
182
+ inner_sha256=sha256_file(INNER), relay=RELAY)
183
+
184
+ def _sock_dir(self):
185
+ if self.sock_dir is None:
186
+ os.makedirs(SOCK_ROOT, mode=0o711, exist_ok=True)
187
+ os.chmod(SOCK_ROOT, 0o711)
188
+ d = os.path.join(SOCK_ROOT, secrets.token_hex(6))
189
+ os.mkdir(d, 0o700)
190
+ os.chown(d, self.uid, self.uid)
191
+ self.sock_dir = d
192
+ return self.sock_dir
193
+
194
+ def mcp_command(self, real_argv, env=None, label="mcp"):
195
+ """-> (command, args) for the harness's MCP config: the relay on a new socket served by real_argv."""
196
+ d = self._sock_dir()
197
+ path = os.path.join(d, f"{label}-{len(self.relays)}.sock")
198
+ err = os.path.join(self.stderr_dir, f"jail_{label}_stderr.log") if self.stderr_dir else None
199
+ self.relays.append(_Relay(path, list(real_argv), dict(env or {"PATH": "/usr/bin:/bin"}), err, self.uid))
200
+ return RELAY_PYTHON, [RELAY, path]
201
+
202
+ def wrap(self, argv, env, cwd, rw_dirs):
203
+ """The jailed argv. Popen it with the same env: the jail forwards exactly those variables. Chowns the
204
+ directories that are mounted back (one-time dirs only) to the jail uid."""
205
+ rw = _outermost(list(rw_dirs) + ([self.sock_dir] if self.sock_dir else []) + ([cwd] if cwd else []))
206
+ if len(rw) > MAX_BINDS:
207
+ raise JailError(f"too many bind mounts ({len(rw)} > {MAX_BINDS})")
208
+ for d in rw:
209
+ if not os.path.isdir(d):
210
+ raise JailError(f"bind source {d} is not a directory")
211
+ if not d.startswith(("/tmp/lffrun/", "/tmp/lffstate/", SOCK_ROOT + "/")):
212
+ raise JailError(f"refusing to mount {d} into the jail (only one-time dirs)")
213
+ _chown_tree(d, self.uid)
214
+ cmd = [self.binary_jailed if os.path.realpath(argv[0]) == self.binary_real else argv[0]] + list(argv[1:])
215
+ out = ["setpriv", f"--reuid={self.uid}", f"--regid={self.uid}", "--clear-groups", "--",
216
+ "unshare", "--user", "--map-root-user", "--mount", "--fork", "--kill-child",
217
+ INNER, "--keep", ",".join(sorted(env)), "--proc", self.proc]
218
+ for d in rw:
219
+ out += ["--rw", d]
220
+ return out + ["--cwd", cwd or "/", "--exe", self.binary_jailed, "--"] + cmd
221
+
222
+ def close(self):
223
+ for r in self.relays:
224
+ r.close()
225
+ self.relays = []
226
+ if self.sock_dir and self.sock_dir.startswith(SOCK_ROOT + "/"):
227
+ shutil.rmtree(self.sock_dir, ignore_errors=True)
228
+ self.sock_dir = None
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-fable-5-1|high",
3
+ "fingerprint_sha256": "f44d5ded7b8b847b934c86d8f7b51fa90ae396a1f33bca51e1c946f09da1031b",
4
+ "written": "2026-10-21 05:19:35",
5
+ "summary": {
6
+ "system_chars": 11701,
7
+ "tools": [
8
+ "mcp__lff__robot",
9
+ "mcp__lff__shell",
10
+ "mcp__lff__view_images"
11
+ ],
12
+ "effort_in_request": "high",
13
+ "model_in_request": "claude-fable-5-1"
14
+ }
15
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|high",
3
+ "fingerprint_sha256": "41fecee198c38459b5fae54c29ebf99c368e60381b3f11418dea02590bba5222",
4
+ "written": "2026-10-20 02:33:15",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "gpt-6-astra",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-flash_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-flash|high",
3
+ "fingerprint_sha256": "c998aa8a7624948e949f21c563d129e964416edc94f9e22b0237a9d8c46dbe47",
4
+ "written": "2026-10-20 02:36:39",
5
+ "summary": {
6
+ "developer_chars": 16979,
7
+ "top_tools": [
8
+ "list_mcp_resource_templates",
9
+ "list_mcp_resources",
10
+ "mcp__lff.robot",
11
+ "mcp__lff.shell",
12
+ "mcp__lff.view_images",
13
+ "read_mcp_resource",
14
+ "request_user_input"
15
+ ],
16
+ "effort_in_request": "high",
17
+ "model_in_request": "deepseek-flash",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|medium",
3
+ "fingerprint_sha256": "cdffdbedeb4b110f1f29227ee9459940be8175df4ca71546690ff6db0cccbd6a",
4
+ "written": "2026-10-13 04:13:35",
5
+ "summary": {
6
+ "developer_chars": 23961,
7
+ "top_tools": [
8
+ "collaboration.followup_task",
9
+ "collaboration.interrupt_agent",
10
+ "collaboration.list_agents",
11
+ "collaboration.send_message",
12
+ "collaboration.spawn_agent",
13
+ "collaboration.wait_agent",
14
+ "functions.exec",
15
+ "functions.request_user_input",
16
+ "functions.request_user_input_async",
17
+ "functions.wait"
18
+ ],
19
+ "all_tools": [
20
+ "apply_patch",
21
+ "clock__curr_time",
22
+ "list_mcp_resource_templates",
23
+ "list_mcp_resources",
24
+ "mcp__lff__robot",
25
+ "mcp__lff__shell",
26
+ "mcp__lff__view_images",
27
+ "read_mcp_resource"
28
+ ],
29
+ "effort_in_request": "medium",
30
+ "model_in_request": "gpt-6-astra",
31
+ "sandbox": {
32
+ "sandbox": "seccomp",
33
+ "sandbox_mode": "read-only"
34
+ }
35
+ }
36
+ }
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l3_tool.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L3-C under_table_tool: a cube sits under a low glass side table; put it into the bin (tool use).
2
+
3
+ v2 (2026-10-08, user review of cla2): in v1 the hidden information was "the hand does not fit under the glass top".
4
+ Every Sonnet run (4/4) saw the T-shaped stick lying next to the low table and used it straight away, i.e. the task
5
+ was solved by reasoning before acting and nothing had to be learned from a failure. v2 keeps the scene and moves the
6
+ hidden information to something no image shows:
7
+
8
+ Hidden: the side of the low table AWAY from the stick is closed by a clear acrylic panel (between the two legs,
9
+ tabletop to glass top; collision only, nothing is rendered). The bin stands on that side, beyond the panel. The other
10
+ three sides are open.
11
+
12
+ Why the prior fails: the stick lies on one side with its head pointing at the low table, and the bin is on the
13
+ opposite side, so the obvious plan is "slide the stick in and push the cube straight across, out towards the bin".
14
+ The cube then stops against the invisible panel, still completely under the glass top (the hand cannot reach it
15
+ there: the glass is 7 cm above the tabletop). Pushing harder or again from the same side fails the same way.
16
+
17
+ What must be learned from the failure (F1: from the images -- the cube stopped at the edge and did not come out):
18
+ something blocks that side -> change the push: put the stick down behind the low table (the robot's side) pointing
19
+ forward, push the cube out of the FRONT side (away from the robot), then grasp it and carry it to the bin.
20
+
21
+ Layout (randomised per instance): position of the low table, cube position under it (+-1 cm around the centre),
22
+ the stick lying beside the low table (left or right) with its head pointing at it (+-10 deg), the panel and the bin
23
+ on the other side.
24
+
25
+ Protocol: cross (reset to the same instance before every attempt), k = 5. v1 is kept in l3_tool.py.bak-20261008-pane.
26
+ """
27
+ import numpy as np
28
+
29
+ from .. import envs
30
+ from ..bddl import write_bddl
31
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated
32
+ from ..skills import DT, _rot_err
33
+ from ..task_base import LFFTask, register_task
34
+
35
+ CUBE_HALF = 0.02
36
+ TOP_HALF = (0.06, 0.06, 0.005) # glass top 12 x 12 cm, 1 cm thick
37
+ TOP_UNDER = 0.07 # underside of the glass top above the tabletop
38
+ LEG_HALF = 0.008
39
+ HANDLE_HALF = (0.12, 0.008, 0.01) # stick handle 24 x 1.6 x 2 cm, along local x
40
+ HEAD_HALF = (0.008, 0.025, 0.01) # crossbar 1.6 x 5 x 2 cm at the +x end
41
+ BIN_IN = (0.06, 0.06)
42
+ BIN_WALL_H = 0.05
43
+ GRIP_END = 0.035 # scripted grasp point: this far from the free end of the handle
44
+ GRIP_FRONT = 0.07 # v2 front push: grasp this far from the free end (keeps the hand clear of the glass edge)
45
+ Z_STICK = envs.TABLE_Z + 0.0125 # site height when grasping / sliding the stick (pads 0.75-2.4 cm above the table)
46
+ TIP_BELOW_SITE = 0.0095
47
+ # clear acrylic panel between the two legs of one y side, tabletop to glass underside (collision only, invisible)
48
+ PANE_HALF = (TOP_HALF[0] - 2 * LEG_HALF, 0.002, TOP_UNDER / 2)
49
+ PANE_Y = TOP_HALF[1] - LEG_HALF # in the plane of the leg centres
50
+ STICK_COM = 0.0221 # the stick's centre of mass is this far from the handle centre, towards the head
51
+ BIN_GAP = (0.04, 0.06) # tabletop gap between the low table's far side and the bin's outer wall
52
+
53
+
54
+ def low_table_xml(model_name):
55
+ glass, leg = (0.70, 0.85, 0.95, 0.30), (0.35, 0.25, 0.18, 1.0)
56
+ z_top = TOP_UNDER + TOP_HALF[2]
57
+ parts = [((0, 0, z_top), TOP_HALF, glass)]
58
+ for sx in (-1, 1):
59
+ for sy in (-1, 1):
60
+ parts.append(((sx * (TOP_HALF[0] - LEG_HALF), sy * (TOP_HALF[1] - LEG_HALF), TOP_UNDER / 2),
61
+ (LEG_HALF, LEG_HALF, TOP_UNDER / 2), leg))
62
+ g = []
63
+ for k, (p, s, c) in enumerate(parts):
64
+ g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
65
+ f'density="800" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
66
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
67
+ f'contype="0" group="1" />')
68
+ # acrylic panels on both y sides; apply_instance turns the collision of the one next to the stick off.
69
+ # Fully transparent (rgba alpha 0) and no visual twin: nothing is rendered.
70
+ for k, sy in enumerate((1, -1)):
71
+ g.append(f' <geom name="{model_name}_pane{k}" type="box" pos="{_fmt((0, sy * PANE_Y, PANE_HALF[2]))}" '
72
+ f'size="{_fmt(PANE_HALF)}" rgba="1 1 1 0" density="800" friction="0.6 0.005 0.0001" {_SOLID} '
73
+ f'group="0" />')
74
+ # origin at the tabletop (z = 0 is the bottom of the legs)
75
+ return _wrap(model_name, "\n".join(g), 0.0, float(np.hypot(TOP_HALF[0], TOP_HALF[1])))
76
+
77
+
78
+ def stick_xml(model_name):
79
+ c = (0.80, 0.62, 0.30, 1.0)
80
+ parts = [((0, 0, 0), HANDLE_HALF), ((HANDLE_HALF[0] + HEAD_HALF[0], 0, 0), HEAD_HALF)]
81
+ g = []
82
+ for k, (p, s) in enumerate(parts):
83
+ g.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
84
+ f'density="600" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
85
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" conaffinity="0" '
86
+ f'contype="0" group="1" />')
87
+ return _wrap(model_name, "\n".join(g), HANDLE_HALF[2], HANDLE_HALF[0] + 2 * HEAD_HALF[0])
88
+
89
+
90
+ def _yaw_of(quat_wxyz):
91
+ w, x, y, z = quat_wxyz
92
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
93
+
94
+
95
+ @register_task
96
+ class UnderTableTool(LFFTask):
97
+ name = "l3_under_table_tool"
98
+ level = "L3"
99
+ category = "strategy_switching"
100
+ capabilities = ("Perceive", "Reason", "Plan")
101
+ protocol = "cross"
102
+ instruction = "Put the red cube into the gray bin."
103
+ instruction_indirect = "Put the small red block that is under the low glass table into the gray container."
104
+
105
+ def __init__(self, cam_res=None):
106
+ super().__init__(cam_res)
107
+ self._mon = None
108
+ self.inst = None
109
+ orig_step = self.env.step
110
+
111
+ def step(action):
112
+ ret = orig_step(action)
113
+ if self._mon is not None:
114
+ self._monitor_step()
115
+ return ret
116
+
117
+ self.env.step = step
118
+
119
+ # ------------------------------------------------------------ scene
120
+ def make_bddl(self):
121
+ cube = register_generated("LffBenchCube", box_xml("lff_bench_cube", (CUBE_HALF,) * 3, (0.85, 0.12, 0.12, 1.0),
122
+ density=800))
123
+ stick = register_generated("LffBenchStick", stick_xml("lff_bench_stick"))
124
+ table = register_generated("LffLowGlassTable", low_table_xml("lff_low_glass_table"), free=False)
125
+ tray = register_generated("LffBenchBin", bin_xml("lff_bench_bin", BIN_IN, BIN_WALL_H), free=False)
126
+ objs = [("cube_1", cube, "cube_region", (-0.21, -0.26, -0.19, -0.24)),
127
+ ("stick_1", stick, "stick_region", (-0.01, 0.24, 0.01, 0.26))]
128
+ fx = [("lowtable_1", table, "lowtable_region", (0.19, -0.01, 0.21, 0.01)),
129
+ ("bin_1", tray, "bin_region", (0.19, 0.29, 0.21, 0.31))]
130
+ return write_bddl(self.name, self.instruction, objs, fx)
131
+
132
+ def _fixture(self, name):
133
+ if not hasattr(self, "_fx"):
134
+ self._fx = {}
135
+ if name not in self._fx:
136
+ m = self.env.sim.model
137
+ bid = m.body_name2id(self.env.fixtures_dict[name].root_body)
138
+
139
+ def under(b):
140
+ while b > 0:
141
+ if b == bid:
142
+ return True
143
+ b = m.body_parentid[b]
144
+ return False
145
+
146
+ self._fx[name] = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])])
147
+ return self._fx[name]
148
+
149
+ def _panes(self):
150
+ """[(geom id, +1 / -1 = which y side of the low table)] of the two acrylic panel geoms"""
151
+ if not hasattr(self, "_pane_ids"):
152
+ m = self.env.sim.model
153
+ self._pane_ids = [(g, int(np.sign(m.geom_pos[g][1]))) for g in self._fixture("lowtable_1")[1]
154
+ if np.allclose(m.geom_size[g], PANE_HALF, atol=1e-6)]
155
+ assert len(self._pane_ids) == 2, self._pane_ids
156
+ return self._pane_ids
157
+
158
+ def sample_instance(self, seed):
159
+ rng = np.random.default_rng(seed)
160
+ side = int(rng.choice([-1, 1])) # the stick lies on the left (+1) or right (-1) of the low table
161
+ # v2: 4 cm further from the robot than v1 (-0.16..-0.10), so that a stick pushed forward from behind the
162
+ # low table is within reach (gripper about 25 cm in front of the robot base at the start of that push)
163
+ t_xy = np.array([rng.uniform(-0.12, -0.06), -side * rng.uniform(0.04, 0.07)])
164
+ cube_xy = t_xy + rng.uniform(-0.01, 0.01, 2)
165
+ # the stick lies beside the low table, its head pointing roughly at it (+-10 deg), 2.5-4.5 cm from its edge
166
+ yaw = -side * np.pi / 2 + float(rng.uniform(-np.radians(10), np.radians(10)))
167
+ d = np.array([np.cos(yaw), np.sin(yaw)])
168
+ head_front = np.array([cube_xy[0] + rng.uniform(-0.01, 0.01), t_xy[1] + side * (TOP_HALF[1] + rng.uniform(0.025, 0.045))])
169
+ stick_xy = head_front - d * (HANDLE_HALF[0] + 2 * HEAD_HALF[0])
170
+ # v2: the bin stands on the far side (the panel's side), so pushing the cube straight across looks like the
171
+ # way to the bin
172
+ gap = rng.uniform(*BIN_GAP)
173
+ bin_xy = np.array([t_xy[0] + rng.uniform(-0.02, 0.02),
174
+ t_xy[1] - side * (TOP_HALF[1] + gap + BIN_IN[1] + 0.006)])
175
+ return dict(seed=int(seed), table_xy=t_xy.tolist(), cube_xy=cube_xy.tolist(), side=side, pane_side=-side,
176
+ stick_xy=stick_xy.tolist(), stick_yaw=float(yaw), bin_xy=bin_xy.tolist())
177
+
178
+ def apply_instance(self, inst):
179
+ self.inst = inst
180
+ m = self.env.sim.model
181
+ bid, _ = self._fixture("lowtable_1")
182
+ m.body_pos[bid] = [inst["table_xy"][0], inst["table_xy"][1], envs.TABLE_Z]
183
+ m.body_quat[bid] = [1, 0, 0, 0]
184
+ for g, sy in self._panes(): # only the panel on the far side (away from the stick) collides
185
+ on = sy == inst.get("pane_side", -inst["side"])
186
+ m.geom_contype[g] = 1 if on else 0
187
+ m.geom_conaffinity[g] = 1 if on else 0
188
+ bbid, _ = self._fixture("bin_1")
189
+ m.body_pos[bbid] = [inst["bin_xy"][0], inst["bin_xy"][1], envs.TABLE_Z + (BIN_WALL_H + 0.006) / 2]
190
+ m.body_quat[bbid] = [1, 0, 0, 0]
191
+ cx, cy = inst["cube_xy"]
192
+ envs.set_obj_pose(self.env, "cube_1", [cx, cy, envs.TABLE_Z + CUBE_HALF + 0.0005])
193
+ sx, sy = inst["stick_xy"]
194
+ envs.set_obj_pose(self.env, "stick_1", [sx, sy, envs.TABLE_Z + HANDLE_HALF[2] + 0.0005], yaw=inst["stick_yaw"])
195
+
196
+ def reset_instance(self, inst, recorder=None):
197
+ self._mon = None
198
+ sk = super().reset_instance(inst, recorder=recorder)
199
+ self._start_monitor()
200
+ return sk
201
+
202
+ # ------------------------------------------------------------ state
203
+ def stick_pose(self):
204
+ d = self.env.sim.data
205
+ bid = envs.body_id(self.env, "stick_1")
206
+ return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
207
+
208
+ def observe(self):
209
+ p, R = self.stick_pose()
210
+ ax = R[:2, 0] / max(np.linalg.norm(R[:2, 0]), 1e-9)
211
+ return dict(cube=envs.obj_pos(self.env, "cube_1"), table_xy=np.array(self.inst["table_xy"]),
212
+ bin_xy=np.array(self.inst["bin_xy"]), stick_xy=p[:2], stick_dir=ax,
213
+ free_end=p[:2] - ax * HANDLE_HALF[0], head=p[:2] + ax * (HANDLE_HALF[0] + HEAD_HALF[0]))
214
+
215
+ def under_table(self, xy=None, margin=0.0):
216
+ """is the cube's footprint (any part) under the glass top?"""
217
+ xy = envs.obj_pos(self.env, "cube_1")[:2] if xy is None else np.asarray(xy)
218
+ rel = np.abs(xy - np.array(self.inst["table_xy"]))
219
+ return bool((rel < np.array(TOP_HALF[:2]) + CUBE_HALF + margin).all())
220
+
221
+ def outside_dist(self):
222
+ """how far the cube's footprint is outside the glass top (m, < 0: still partly under it)"""
223
+ rel = np.abs(envs.obj_pos(self.env, "cube_1")[:2] - np.array(self.inst["table_xy"]))
224
+ return float(max(rel - np.array(TOP_HALF[:2]) - CUBE_HALF))
225
+
226
+ def in_bin(self):
227
+ p = envs.obj_pos(self.env, "cube_1")
228
+ rel = np.abs(p[:2] - np.array(self.inst["bin_xy"]))
229
+ return bool(p[2] < envs.TABLE_Z + BIN_WALL_H and (rel < np.array(BIN_IN)).all())
230
+
231
+ # ------------------------------------------------------------ contacts / monitor
232
+ def _groups(self):
233
+ if not hasattr(self, "_gg"):
234
+ m = self.env.sim.model
235
+ robot = set(envs.robot_geom_ids(self.env))
236
+ tbl = self._fixture("lowtable_1")[1]
237
+ top = {g for g in tbl if m.geom_contype[g] and abs(m.geom_size[g, 0] - TOP_HALF[0]) < 1e-6}
238
+ self._gg = (robot, set(tbl), top, set(envs.obj_geom_ids(self.env, "stick_1")),
239
+ set(envs.obj_geom_ids(self.env, "cube_1")))
240
+ return self._gg
241
+
242
+ def _robot_contacts(self):
243
+ """labels of what the robot touches: 'glass_top', 'pane', 'table_leg', 'stick', 'cube'"""
244
+ robot, tbl, top, stick, cube = self._groups()
245
+ panes = {g for g, _ in self._panes()}
246
+ d = self.env.sim.data
247
+ out = set()
248
+ for i in range(d.ncon):
249
+ c = d.contact[i]
250
+ if c.geom1 in robot:
251
+ o = c.geom2
252
+ elif c.geom2 in robot:
253
+ o = c.geom1
254
+ else:
255
+ continue
256
+ if o in top:
257
+ out.add("glass_top")
258
+ elif o in panes:
259
+ out.add("pane")
260
+ elif o in tbl:
261
+ out.add("table_leg")
262
+ elif o in stick:
263
+ out.add("stick")
264
+ elif o in cube:
265
+ out.add("cube")
266
+ return out
267
+
268
+ def _start_monitor(self):
269
+ c = envs.obj_pos(self.env, "cube_1")
270
+ self._mon = dict(start=c.copy(), top_hit=None, stick_held=False, stick_touched_cube=False, max_cube_dz=0.0,
271
+ cube_out=not self.under_table(), cube_hit_pane=False, stick_hit_pane=False,
272
+ robot_hit_pane=False)
273
+
274
+ def _monitor_step(self):
275
+ mon, sk = self._mon, self.sk
276
+ if sk is None:
277
+ return
278
+ hits = self._robot_contacts()
279
+ if "glass_top" in hits:
280
+ e = sk.eef_pos()
281
+ rel = np.abs(e[:2] - np.array(self.inst["table_xy"]))
282
+ mon["top_hit"] = dict(above=bool((rel < np.array(TOP_HALF[:2])).all()),
283
+ tip=float(e[2] - TIP_BELOW_SITE - envs.TABLE_Z),
284
+ outside=float(max(rel - np.array(TOP_HALF[:2]))))
285
+ if sk.holding("stick_1"):
286
+ mon["stick_held"] = True
287
+ if "pane" in hits:
288
+ mon["robot_hit_pane"] = True
289
+ robot, tbl, top, stick, cube = self._groups()
290
+ panes = {g for g, _ in self._panes()}
291
+ d = self.env.sim.data
292
+ for i in range(d.ncon):
293
+ c = d.contact[i]
294
+ pair = (c.geom1, c.geom2)
295
+ if (pair[0] in stick and pair[1] in cube) or (pair[1] in stick and pair[0] in cube):
296
+ mon["stick_touched_cube"] = True
297
+ if (pair[0] in panes and pair[1] in cube) or (pair[1] in panes and pair[0] in cube):
298
+ mon["cube_hit_pane"] = True
299
+ if (pair[0] in panes and pair[1] in stick) or (pair[1] in panes and pair[0] in stick):
300
+ mon["stick_hit_pane"] = True
301
+ p = envs.obj_pos(self.env, "cube_1")
302
+ mon["max_cube_dz"] = max(mon["max_cube_dz"], float(p[2] - mon["start"][2]))
303
+ if not self.under_table():
304
+ mon["cube_out"] = True
305
+
306
+ # ------------------------------------------------------------ outcome / F2
307
+ def outcome(self, inst):
308
+ envs.settle(self.env, 30)
309
+ mon = self._mon or {}
310
+ p = envs.obj_pos(self.env, "cube_1")
311
+ held = bool(self.sk.holding("cube_1")) if self.sk is not None else False
312
+ success = bool(self.in_bin() and not held)
313
+ moved = float(np.linalg.norm(p[:2] - mon.get("start", p)[:2]))
314
+ under = self.under_table()
315
+ brel = p[:2] - np.array(inst["bin_xy"])
316
+ parts, mode = [], "success"
317
+ top = mon.get("top_hit")
318
+ if success:
319
+ parts.append("The cube is in the bin.")
320
+ elif p[2] < envs.TABLE_Z - 0.05:
321
+ mode = "fell_off"
322
+ parts.append("The cube fell off the table.")
323
+ elif held:
324
+ mode = "held"
325
+ parts.append("The cube is still held by the gripper; it was not released into the bin.")
326
+ elif under:
327
+ mode = "under"
328
+ if top is not None and not mon.get("stick_touched_cube"):
329
+ mode = "blocked"
330
+ if top["above"]:
331
+ parts.append(f"The gripper came down on the glass top of the low table: its fingertips stopped "
332
+ f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, while the cube is underneath "
333
+ f"the glass (the glass underside is {100 * TOP_UNDER:.1f} cm above the tabletop), so the "
334
+ f"gripper never got to the cube.")
335
+ else:
336
+ parts.append(f"The hand ran into the edge of the glass top of the low table (fingertips "
337
+ f"{100 * max(top['tip'], 0.0):.1f} cm above the tabletop, gripper "
338
+ f"{100 * max(top['outside'], 0.0):.1f} cm outside the edge) and could not move in "
339
+ f"under the glass.")
340
+ if mon.get("cube_hit_pane"):
341
+ mode = "pane"
342
+ parts.append(f"The cube was pushed against a clear acrylic panel that closes the "
343
+ f"{'left' if inst.get('pane_side', -inst['side']) > 0 else 'right'} side of the low "
344
+ f"table (between its two legs, from the tabletop up to the glass); it cannot leave the "
345
+ f"low table on that side.")
346
+ if moved > 0.01:
347
+ parts.append(f"The cube was moved {100 * moved:.1f} cm but is still under the low table "
348
+ f"({100 * -self.outside_dist():.1f} cm from getting completely out from under it).")
349
+ else:
350
+ parts.append("The cube did not move; it is still under the low table.")
351
+ else:
352
+ mode = "out_not_in_bin"
353
+ lifted = mon.get("max_cube_dz", 0.0) > 0.03
354
+ parts.append(("The cube was lifted but ended outside the bin" if lifted else
355
+ "The cube is out from under the low table but not in the bin") +
356
+ f": it is {100 * abs(brel[0]):.1f} cm {'forward' if brel[0] > 0 else 'backward'} and "
357
+ f"{100 * abs(brel[1]):.1f} cm {'left' if brel[1] > 0 else 'right'} of the bin's centre.")
358
+ out = dict(success=success, mode=mode, moved=moved, under=under, cube_rel_bin=[float(brel[0]), float(brel[1])],
359
+ stick_used=bool(mon.get("stick_held")), terminal=bool(p[2] < envs.TABLE_Z - 0.05),
360
+ cube_hit_pane=bool(mon.get("cube_hit_pane")), stick_hit_pane=bool(mon.get("stick_hit_pane")),
361
+ robot_hit_pane=bool(mon.get("robot_hit_pane")), detail=" ".join(parts))
362
+ self._start_monitor()
363
+ return out
364
+
365
+ # ------------------------------------------------------------ primitives for the scripted policies
366
+ def _yaw_near(self, yaw):
367
+ cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)]
368
+ cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands
369
+ return float(min(cands, key=lambda c: abs(c - self.sk.yaw)))
370
+
371
+ def _align(self, tol=0.03, max_steps=60):
372
+ sk = self.sk
373
+ for _ in range(max_steps):
374
+ R = sk._R() @ sk.eef_mat().T
375
+ if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol:
376
+ break
377
+ sk.hold(1)
378
+
379
+ def _guarded_descent(self, xyz, speed=0.12, max_steps=80):
380
+ sk = self.sk
381
+ p0 = sk.eef_pos()
382
+ tgt = np.asarray(xyz, float)
383
+ dist = max(np.linalg.norm(tgt - p0), 1e-6)
384
+ R = sk._R()
385
+ for k in range(max_steps):
386
+ ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist)
387
+ sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
388
+ if self._robot_contacts() - {"cube"} and sk.eef_pos()[2] > tgt[2] + 0.005:
389
+ break
390
+ if np.linalg.norm(tgt - sk.eef_pos()) < 0.003:
391
+ break
392
+ sk.hold(4)
393
+
394
+ def grasp_cube_and_bin(self, dxy=(0.0, 0.0), dyaw=0.0):
395
+ """Top-down grasp of the cube where it is (+ offsets); if held, drop it into the bin."""
396
+ sk, o = self.sk, self.observe()
397
+ c = o["cube"]
398
+ gx, gy = c[0] + dxy[0], c[1] + dxy[1]
399
+ # the hand is 20 cm long along the closing direction: keep that direction parallel to the low table's edge
400
+ v = c[:2] - o["table_xy"]
401
+ yaw = (np.pi / 2 if abs(v[1]) > abs(v[0]) else 0.0) + dyaw
402
+ sk.set_gripper(False, steps=8)
403
+ sk.move_to([gx, gy, envs.TABLE_Z + 0.15], yaw=self._yaw_near(yaw))
404
+ self._align()
405
+ self._guarded_descent([gx, gy, envs.TABLE_Z + 0.017])
406
+ sk.set_gripper(True, steps=15)
407
+ e = sk.eef_pos()
408
+ sk.move_to([e[0], e[1], envs.TABLE_Z + 0.16], speed=0.25)
409
+ if sk.holding("cube_1"):
410
+ bx, by = o["bin_xy"]
411
+ sk.move_to([bx, by, envs.TABLE_Z + 0.16])
412
+ sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05])
413
+ sk.set_gripper(False, steps=12)
414
+ sk.move_to([bx, by, envs.TABLE_Z + 0.16])
415
+ else:
416
+ sk.set_gripper(False, steps=6)
417
+
418
+ def tool_push_out(self, extra=0.0):
419
+ """Pick the stick up by the end of its handle (it already points at the low table), lift it a few mm and slide
420
+ it along its own axis under the glass top so that its head pushes the cube out on the far side; put it down."""
421
+ sk, o = self.sk, self.observe()
422
+ ax = o["stick_dir"]
423
+ g = o["free_end"] + ax * GRIP_END
424
+ sk.set_gripper(False, steps=8)
425
+ sk.move_to([g[0], g[1], Z_STICK + 0.08], yaw=self._yaw_near(float(np.arctan2(ax[1], ax[0]))))
426
+ self._align()
427
+ sk.move_to([g[0], g[1], Z_STICK], tol=0.003)
428
+ sk.set_gripper(True, steps=15)
429
+ sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05)
430
+ o2 = self.observe()
431
+ c, t_xy = o2["cube"][:2], o2["table_xy"]
432
+ n = np.array([0.0, -float(self.inst["side"])]) # push straight across the low table (normal of its far edge)
433
+ perp = np.array([-n[1], n[0]])
434
+ head = o2["head"]
435
+ # line the head up with the cube by sliding the stick sideways (no turning: a turned stick slips in the grasp)
436
+ lat = float((c - head) @ perp)
437
+ e = sk.eef_pos()
438
+ sk.move_to([e[0] + perp[0] * lat, e[1] + perp[1] * lat, e[2]], speed=0.05)
439
+ o3 = self.observe()
440
+ head_front = float((o3["head"] + o3["stick_dir"] * HEAD_HALF[0]) @ n)
441
+ gap = max(float(c @ n) - CUBE_HALF - head_front, 0.0)
442
+ need = (TOP_HALF[1] + CUBE_HALF + 0.05 + extra) - float((c - t_xy) @ n) # cube travel until it is clear
443
+ e = sk.eef_pos()
444
+ tgt = e[:2] + n * (gap + need)
445
+ sk.move_to([tgt[0], tgt[1], e[2]], speed=0.08, tol=0.004, max_steps=500)
446
+ sk.hold(3)
447
+ for _ in range(3): # still (partly) under the glass top: push on a little
448
+ if not self.under_table() or not sk.holding("stick_1"):
449
+ break
450
+ e = sk.eef_pos()
451
+ tgt = e[:2] + n * 0.025
452
+ sk.move_to([tgt[0], tgt[1], e[2]], speed=0.06, tol=0.004, max_steps=100)
453
+ sk.hold(3)
454
+ ax = n
455
+ back = sk.eef_pos()[:2] - ax * 0.05
456
+ sk.move_to([back[0], back[1], e[2]], speed=0.08)
457
+ sk.set_gripper(False, steps=10)
458
+ sk.move_to([back[0], back[1], envs.TABLE_Z + 0.12], speed=0.2)
459
+
460
+ def tool_push_front(self, extra=0.0):
461
+ """v2 reference solution. Pick the stick up at its centre of mass, turn it to point forward (+x, away from the
462
+ robot) in the air, put it down behind the low table in line with the cube, re-grasp it GRIP_FRONT from its
463
+ free end and slide it forward under the glass top so that its head pushes the cube out of the FRONT side;
464
+ pull the stick back a little and put it down.
465
+
466
+ Reach: the re-grasp point is about 25 cm in front of the robot base at the start of the push; it stays
467
+ >= 3 cm behind the glass top's back edge at the end (the hand is about 4-13 cm above the fingertips and
468
+ would hit the glass edge)."""
469
+ sk, o = self.sk, self.observe()
470
+ ax = o["stick_dir"]
471
+ com = o["stick_xy"] + ax * STICK_COM
472
+ phi = float(np.arctan2(ax[1], ax[0])) # the stick points this way (handle -> head); about +-90 deg
473
+ sk.set_gripper(False, steps=8)
474
+ # grasp with gripper yaw = phi (not phi +- pi), so that turning the stick to point forward is a wrist turn to
475
+ # yaw 0, inside the wrist's range
476
+ sk.move_to([com[0], com[1], Z_STICK + 0.08], yaw=phi, wrap_yaw=False)
477
+ self._align()
478
+ sk.move_to([com[0], com[1], Z_STICK], tol=0.003)
479
+ sk.set_gripper(True, steps=15)
480
+ sk.move_to([com[0], com[1], Z_STICK + 0.10], speed=0.15)
481
+ c, t_xy = o["cube"][:2], o["table_xy"]
482
+ head_front_x = t_xy[0] - TOP_HALF[0] - 0.006 # just outside the glass top's back edge
483
+ put_x = head_front_x - (HANDLE_HALF[0] + 2 * HEAD_HALF[0]) + STICK_COM
484
+ e = sk.eef_pos()
485
+ sk.move_to([e[0], e[1], e[2]], yaw=0.0, wrap_yaw=False)
486
+ self._align()
487
+ sk.move_to([put_x, c[1], Z_STICK + 0.10], speed=0.2)
488
+ sk.move_to([put_x, c[1], Z_STICK + 0.004], speed=0.08, tol=0.003)
489
+ sk.set_gripper(False, steps=10)
490
+ sk.move_to([put_x, c[1], Z_STICK + 0.06], speed=0.15)
491
+ # re-grasp near the free end
492
+ o2 = self.observe()
493
+ ax2 = o2["stick_dir"]
494
+ g = o2["free_end"] + ax2 * GRIP_FRONT
495
+ sk.move_to([g[0], g[1], Z_STICK + 0.06], yaw=self._yaw_near(float(np.arctan2(ax2[1], ax2[0]))))
496
+ self._align()
497
+ sk.move_to([g[0], g[1], Z_STICK], tol=0.003)
498
+ sk.set_gripper(True, steps=15)
499
+ sk.move_to([g[0], g[1], Z_STICK + 0.006], speed=0.05)
500
+ # line the head up with the cube (sideways slide), then push forward
501
+ o3 = self.observe()
502
+ lat = float(c[1] - o3["head"][1])
503
+ e = sk.eef_pos()
504
+ sk.move_to([e[0], e[1] + lat, e[2]], speed=0.05)
505
+ o4 = self.observe()
506
+ head_front = float(o4["head"][0] + HEAD_HALF[0])
507
+ cube_tgt = t_xy[0] + TOP_HALF[0] + CUBE_HALF + 0.03 + extra
508
+ travel = (cube_tgt - CUBE_HALF) - head_front
509
+ e = sk.eef_pos()
510
+ sk.move_to([e[0] + travel, e[1], e[2]], speed=0.08, tol=0.004, max_steps=500)
511
+ sk.hold(3)
512
+ e = sk.eef_pos()
513
+ sk.move_to([e[0] - 0.05, e[1], e[2]], speed=0.08)
514
+ sk.set_gripper(False, steps=10)
515
+ e = sk.eef_pos()
516
+ sk.move_to([e[0], e[1], envs.TABLE_Z + 0.12], speed=0.2)
517
+
518
+ def execute(self, inst, params):
519
+ if params["mode"] == "tool":
520
+ self.tool_push_out(params.get("extra", 0.0))
521
+ elif params["mode"] == "front":
522
+ self.tool_push_front(params.get("extra", 0.0))
523
+ self.grasp_cube_and_bin(params.get("dxy", (0.0, 0.0)), params.get("dyaw", 0.0))
524
+
525
+ # ------------------------------------------------------------ scripted references
526
+ def default_params(self, inst):
527
+ """v2 prior: what every cla2 Sonnet run did -- take the stick and push the cube straight across (towards
528
+ the bin, which is now behind the hidden panel)"""
529
+ return dict(mode="tool")
530
+
531
+ def oracle_params(self, inst):
532
+ return dict(mode="front")
533
+
534
+ def blind_params(self, inst, attempt, rng):
535
+ """no history: the prior with a random extra push length"""
536
+ return dict(mode="tool", extra=float(abs(rng.normal(0, 0.03))))
537
+
538
+ def adapt_params(self, inst, history):
539
+ """v2: the cube stayed under the low table after a push across -> something blocks that side: push it out of
540
+ the front instead. Hand grasp blocked by the glass -> use the stick (the v1 lesson). Front push that did not
541
+ get it out -> push further."""
542
+ out, prm = history[-1]["outcome"], history[-1]["params"]
543
+ if prm["mode"] == "grasp":
544
+ return dict(mode="tool") if out["mode"] in ("blocked", "under") else dict(prm)
545
+ if prm["mode"] == "tool":
546
+ return dict(mode="front") if out["mode"] in ("pane", "under", "blocked") else dict(prm)
547
+ if out["mode"] in ("under", "blocked"):
548
+ return dict(prm, extra=prm.get("extra", 0.0) + 0.02)
549
+ return dict(prm)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/lh_fence.py ADDED
@@ -0,0 +1,1030 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH lh_fence (v2, 2026-10-11): build a small fence -- three square posts on square marks and two flat panels on the
2
+ strips between them, end to end in one line. Letting go of a panel with the fingers along the fence line knocks over
3
+ the post next to it (when the posts are light); the fallen post must be stood up again before finishing.
4
+
5
+ Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically
6
+ break the earlier ones; the agent has to notice and restore them (within an attempt) or learn to place without
7
+ disturbing them (across attempts).
8
+
9
+ Why v2 (measured, ../docs/11 sec. 9): in v1 the panels stood like dominoes (thickness along the row) and the hazard was
10
+ opening the fingers along the row. Sonnet 5.5 always turned the hand so that its long axis (= the finger axis) lay
11
+ along the panel's long horizontal side, which in v1 is across the row = the safe orientation, and it filled the row
12
+ from the far end: 3/3 pilot runs succeeded first time with zero disturbances. v2 turns the panels by 90 deg into a real
13
+ fence (panels end to end along the line, posts between them), so the same habit now opens the fingers ALONG the
14
+ line, towards the posts.
15
+
16
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
17
+ * a straight fence line, left-right or forward-back: 3 dark square marks (posts) alternating with 2 dark strips
18
+ (panels), slot pitch (post centre to post centre) w + 2 g + b;
19
+ * 3 posts: square b = 1.55-1.65 cm, height = the panels' height, dark wood, ball knob (r 1.0 cm, 10 g) on a 0.8 cm
20
+ stem; 2 panels: thickness t 1.4-1.6 cm (across the line), width w 4.0-4.6 cm (along it), height h 7-8 cm, light
21
+ wood, same knob. A placed panel leaves a gap g = 1.3-1.5 cm to each post (knob to knob D = w/2 + g + b/2 =
22
+ 4.1-4.6 cm);
23
+ * the 5 objects stand in a 2 x 3 supply grid (11 cm pitch, 13-15 cm beside the line, shifted towards one end), the
24
+ panels with their width along the line (+-9 deg).
25
+
26
+ Hidden variable (instance level, consistent across attempts, invisible): the posts' mass distribution. "Light" posts
27
+ are plain wood (19-23 g incl. the knob; centre of mass 5.9-7.1 cm up, tips over beyond ~7 deg); "footed" posts carry a
28
+ hidden 100-140 g steel foot (centre of mass 1.5-1.8 cm up, tips over beyond 25-28 deg). They look identical. 13 of
29
+ every 20 consecutive seeds have light posts ("hazard"), 7 footed ("benign").
30
+
31
+ Disturbance (physics, no teleport): a panel is grasped by its knob; with the fingers along the panel's width (the
32
+ natural "hand along the board" grasp, and Sonnet's measured habit) the fingers lie along the fence line at the release
33
+ and, opening to 8 cm, sweep ~6 cm out from the grasp point: they hit the knob of each post that already stands next to
34
+ the panel (D 3.3-5.4 cm incl. a 0.8 cm placement error) and push it 6-18 deg. A light post falls over (away from the
35
+ panel; a middle post often ends up leaning on the panel on its other side); a footed post rocks back. Measured in the
36
+ prototype: light posts 16/16 fell for D <= 5.0 cm (2/4 at 5.5, 0/4 at 6.0), posts with a 0.12-0.25 kg foot 0/30 (max
37
+ tilt 18 deg); with the fingers across the line (along the panel's thickness) 0/9 contacts. A post set down with its
38
+ fingers along the line next to a standing panel tilts the panel <= 15 deg, which rocks back. Validation (seeds
39
+ 1000-1019): the Sonnet-like naive disturbs 13/13 light-post instances and 0/7 footed ones.
40
+
41
+ So the levers are under the agent's control and the hidden weight only decides whether its habit is punished: (1)
42
+ release a panel with the fingers across the fence line (Sonnet-like naive with only this change: 19/20), or, only
43
+ partly, (2) stand both panels before the posts (15/20: a post released next to a panel with its fingers along the line
44
+ rocks the panel, which can knock the new light post). Within an attempt:
45
+ look at the fence before finishing and stand fallen posts up again (lifted by its knob a fallen post swings down and
46
+ hangs upright; a fallen panel too).
47
+
48
+ Implementation notes (found while building v2): MuJoCo keeps each body's bounding-volume hierarchy in the body's
49
+ inertial frame, computed at compile time. Changing geom sizes or body_ipos at runtime therefore needs `refit_bvh`
50
+ (else contacts are missed: a light post whose centre of mass was moved up sank 2.2 cm into the table; one moved down
51
+ never touched the fingers), and runtime body_ipos is ignored altogether when the compiled inertial frame coincides with
52
+ the body frame (v1's knob-mass shift of the centre of mass was silently ignored); the generated XML therefore declares
53
+ an inertial pos of 1 mm. With the centre of mass right, v1's knob torsional friction (0.0015) held a lifted fallen light
54
+ post at 44-61 deg instead of letting it swing down; v2 uses 0.0005 (< 3 deg).
55
+
56
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every mark
57
+ carries an upright post, every strip an upright panel lined up with it, nothing held or touched, scene static) plus an
58
+ event log of every stage predicate (achieved / lost / restored, with step and cause) for the server log; F1 gives the
59
+ agent only success / failure.
60
+ """
61
+ import numpy as np
62
+
63
+ from .. import envs
64
+ from ..bddl import write_bddl
65
+ from ..objects import _fmt, _wrap, register_generated
66
+ from ..skills import Skills
67
+ from ..task_base import LFFTask, register_task
68
+
69
+ TZ = envs.TABLE_Z
70
+ POSTS = [f"post_{c}_1" for c in "abc"]
71
+ PANELS = [f"panel_{c}_1" for c in "ab"]
72
+ OBJS = POSTS + PANELS
73
+ MARKS = [f"postmark_{c}_1" for c in "abc"]
74
+ STRIPS = [f"strip_{c}_1" for c in "ab"]
75
+ SLOT_KIND = ["post", "panel", "post", "panel", "post"] # along the fence line (-u to +u)
76
+ WOOD = [(0.82, 0.66, 0.44, 1.0), (0.76, 0.60, 0.40, 1.0)]
77
+ POST_RGBA = [(0.46, 0.30, 0.18, 1.0), (0.44, 0.29, 0.17, 1.0), (0.48, 0.31, 0.19, 1.0)]
78
+ KNOB_RGBA = (0.20, 0.11, 0.06, 1.0)
79
+ STRIP_RGBA = (0.30, 0.10, 0.12, 1.0)
80
+ MARK_RGBA = (0.14, 0.14, 0.16, 1.0)
81
+ NOM_T, NOM_W, NOM_H = 0.015, 0.047, 0.075 # nominal panel (resized per instance)
82
+ NOM_B = 0.016 # nominal post width
83
+ KNOB_R, STEM_L, STEM_R = 0.010, 0.008, 0.0035
84
+ KNOB_MASS = 0.010
85
+ KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): damps the swing of a hanging object; 0.0015 (v1) holds a lifted fallen light post at 45-60 deg (measured)
86
+ STRIP_W = 0.006
87
+
88
+ # instance ranges
89
+ P_HAZARD = 0.65 # 13 of every 20 consecutive seeds: light posts
90
+ T_RANGE = (0.014, 0.016)
91
+ W_RANGE = (0.040, 0.046)
92
+ H_RANGE = (0.070, 0.080)
93
+ B_RANGE = (0.0155, 0.0165)
94
+ GAP_RANGE = (0.013, 0.015) # panel end to post face; 1.0-1.2 cm: a +-0.8 cm placement error let the panel end touch a light post (2/20 with the safe grasp)
95
+ DENS_RANGE = (450.0, 650.0)
96
+ MU_RANGE = (0.4, 0.8)
97
+ FOOT_RANGE = (0.10, 0.14) # hidden steel foot of a "footed" post (kg)
98
+ FOOT_H = 0.015 # height of the foot slug (its centre 7.5 mm above the post's bottom)
99
+ SUP_PITCH = (0.105, 0.115)
100
+ SUP_D = (0.13, 0.15)
101
+ X_FAR = -0.035
102
+
103
+ # success predicate
104
+ TOL_U = 0.010 # panel centre within 1 cm of the strip centre along the line, 1.5 cm across; post 1 cm both ways
105
+ TOL_V = 0.015
106
+ TOL_POST = 0.010
107
+ TILT_OK = np.radians(5.0)
108
+ YAW_TOL = np.radians(15.0)
109
+ HYST = 0.004
110
+ DEBOUNCE = 20 # a stage counts as lost / regained only after 1 s (a post or panel that is pushed and rocks back is not a loss)
111
+ FALLEN = np.radians(45.0)
112
+
113
+ # scripted motion (z = height of the grasp point above the table)
114
+ Z_SAFE = 0.25 # careful transit (a hanging object's bottom ~15 cm up)
115
+ Z_NAIVE = 0.21 # Sonnet's usual carry height: robot-frame z 0.20 (= 21 cm above the table), measured in lh2_fence
116
+ NAIVE_ERR = 0.008 # naive placement error, uniform per axis (Sonnet: 0.4-1.3 cm from the strip centre, lh2_fence)
117
+
118
+
119
+ def _wrap_h(a):
120
+ """wrap to [-pi/2, pi/2) (panel footprint and gripper are symmetric under 180 deg)"""
121
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
122
+
123
+
124
+ def _yaw_for_axis(a):
125
+ """gripper yaw whose finger axis (-sin yaw, cos yaw) is parallel to the horizontal direction a"""
126
+ return _wrap_h(float(np.arctan2(-a[0], a[1])))
127
+
128
+
129
+ def _quat2mat(q):
130
+ w, x, y, z = q
131
+ return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
132
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
133
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
134
+
135
+
136
+ def refit_bvh(m, b, margin=0.001):
137
+ """Recompute body b's bounding-volume hierarchy after runtime changes of its geoms or body_ipos. MuJoCo stores the
138
+ boxes in the body's inertial frame, computed at compile time; stale boxes make it miss contacts (see module doc).
139
+ Every node becomes the union of its leaf geoms' boxes (body_iquat must be identity)."""
140
+ a = int(m.body_bvhadr[b])
141
+ if a < 0:
142
+ return
143
+ ipos = np.asarray(m.body_ipos[b], float)
144
+
145
+ def rec(i):
146
+ g = int(m.bvh_nodeid[i])
147
+ if g >= 0:
148
+ R = _quat2mat(m.geom_quat[g])
149
+ c = np.asarray(m.geom_pos[g]) + R @ np.asarray(m.geom_aabb[g, :3]) - ipos
150
+ h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:])
151
+ lo, hi = c - h, c + h
152
+ else:
153
+ l1, h1 = rec(a + int(m.bvh_child[i][0]))
154
+ l2, h2 = rec(a + int(m.bvh_child[i][1]))
155
+ lo, hi = np.minimum(l1, l2), np.maximum(h1, h2)
156
+ m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin])
157
+ return lo, hi
158
+ rec(a)
159
+
160
+
161
+ def knobbed_xml(name, half, rgba):
162
+ """box + stem + ball knob. The inertial pos is 1 mm (not 0) so that MuJoCo does not mark the inertial frame as
163
+ identical to the body frame: then the centre of mass set at runtime (body_ipos) is used."""
164
+ geoms = [("board", "box", (0, 0, 0), half, rgba, 'friction="0.6 0.005 0.0001"'),
165
+ ("stem", "cylinder", (0, 0, half[2] + STEM_L / 2), (STEM_R, STEM_L / 2), KNOB_RGBA,
166
+ 'friction="1 0.005 0.0001"'),
167
+ ("knob", "sphere", (0, 0, half[2] + STEM_L + KNOB_R), (KNOB_R,), KNOB_RGBA,
168
+ f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')]
169
+ s = [' <inertial pos="0 0 0.001" mass="0.05" diaginertia="2e-5 2e-5 1e-5" />']
170
+ for nm, typ, pos, size, c, extra in geoms:
171
+ s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
172
+ f'{extra} group="0" />')
173
+ s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
174
+ f'conaffinity="0" group="1" />')
175
+ return _wrap(name, "\n".join(s), half[2], float(np.hypot(half[0], half[1])))
176
+
177
+
178
+ def flat_xml(name, half, rgba):
179
+ g = (f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1" />')
180
+ return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
181
+
182
+
183
+ class FenceSkills(Skills):
184
+ """Skills that feed the task's per-step stage monitor."""
185
+
186
+ def __init__(self, env, task, recorder=None):
187
+ super().__init__(env, recorder=recorder)
188
+ self.task = task
189
+
190
+ def _act(self, dpos, drot, grip):
191
+ super()._act(dpos, drot, grip)
192
+ self.task.monitor_step()
193
+
194
+
195
+ @register_task
196
+ class Fence(LFFTask):
197
+ name = "lh_fence"
198
+ level = "L2"
199
+ category = "state_restoration"
200
+ capabilities = ("Perceive", "Plan", "Reason", "Restore")
201
+ protocol = "cross"
202
+ max_attempts = 3
203
+ agent_max_steps = 120 # careful: ~10 commands per object (50) + standing up two fallen posts (~20) + looking
204
+ instruction = ("Build a small fence: stand one wooden post upright on each of the dark square marks on the table "
205
+ "and one wooden panel upright on each of the dark strips between them, the panel's long bottom edge "
206
+ "along its strip, so that posts and panels alternate in one straight line. Every post and panel "
207
+ "has a small round knob on top; an object lifted by its knob hangs straight down. At the end every "
208
+ "square mark must have one upright post and every strip one upright panel standing on it, with the "
209
+ "gripper open and clear of the fence.")
210
+ instruction_indirect = ("Put up the little fence: the thin square sticks go upright on the dark squares, the flat "
211
+ "boards upright on the dark lines between them, lengthwise along their lines, so that "
212
+ "sticks and boards take turns in one straight row. Every piece has a round knob on top; "
213
+ "held by its knob a piece hangs straight down. At the end every square must carry one "
214
+ "upright stick and every line one upright board, and the gripper must be open and away "
215
+ "from the fence.")
216
+ agent_object_names = ["wooden fence posts (square, each with a dark knob on top)",
217
+ "wooden fence panels (flat boards, each with a dark knob on top)",
218
+ "dark square marks and dark strips on the table"]
219
+
220
+ # ------------------------------------------------------------ scene
221
+ def make_bddl(self):
222
+ objs, fx = [], []
223
+ for i, p in enumerate(POSTS):
224
+ c = "abc"[i]
225
+ cat = register_generated(f"LffLhfPost{c.upper()}",
226
+ knobbed_xml(f"lff_lhf_post_{c}", (NOM_B / 2, NOM_B / 2, NOM_H / 2), POST_RGBA[i]))
227
+ objs.append((p, cat, f"post{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31)))
228
+ for i, p in enumerate(PANELS):
229
+ c = "ab"[i]
230
+ cat = register_generated(f"LffLhfPanel{c.upper()}",
231
+ knobbed_xml(f"lff_lhf_panel_{c}", (NOM_T / 2, NOM_W / 2, NOM_H / 2), WOOD[i]))
232
+ objs.append((p, cat, f"panel{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30)))
233
+ for i, k in enumerate(MARKS):
234
+ c = "abc"[i]
235
+ cat = register_generated(f"LffLhfPostmark{c.upper()}",
236
+ flat_xml(f"lff_lhf_postmark_{c}", (NOM_B / 2 + 0.003, NOM_B / 2 + 0.003, 0.0005),
237
+ MARK_RGBA), free=False)
238
+ fx.append((k, cat, f"mark{i}_region", (-0.30 + 0.12 * i, 0.10, -0.29 + 0.12 * i, 0.11)))
239
+ for i, k in enumerate(STRIPS):
240
+ c = "ab"[i]
241
+ cat = register_generated(f"LffLhfStrip{c.upper()}",
242
+ flat_xml(f"lff_lhf_strip_{c}", (STRIP_W / 2, NOM_W / 2 + 0.005, 0.0005),
243
+ STRIP_RGBA), free=False)
244
+ fx.append((k, cat, f"strip{i}_region", (-0.30 + 0.12 * i, -0.11, -0.29 + 0.12 * i, -0.10)))
245
+ return write_bddl(self.name, "Build a small fence from the posts and panels", objs, fx)
246
+
247
+ def __init__(self, cam_res=None):
248
+ super().__init__(cam_res)
249
+ m = self.env.sim.model
250
+ self.fix_bid, self.fix_vis = {}, {}
251
+ for k in MARKS + STRIPS:
252
+ b = m.body_name2id(self.env.fixtures_dict[k].root_body)
253
+ self.fix_bid[k] = b
254
+ self.fix_vis[k] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in
255
+ {b} | {c for c in range(m.nbody) if m.body_parentid[c] == b} and m.geom_type[g] == 6]
256
+ self.gid, self.vis, self.pbody = {}, {}, {}
257
+ for p in OBJS:
258
+ kind, c = p.split("_")[0], p.split("_")[1]
259
+ self.gid[p] = {nm: m.geom_name2id(f"{p}_lff_lhf_{kind}_{c}_{nm}") for nm in ("board", "stem", "knob")}
260
+ body = int(m.geom_bodyid[self.gid[p]["board"]])
261
+ self.pbody[p] = body
262
+ self.vis[p] = [g for g in range(m.ngeom) if m.geom_bodyid[g] == body and m.geom_contype[g] == 0
263
+ and m.geom_conaffinity[g] == 0]
264
+ self.geom_owner = {}
265
+ for p in OBJS:
266
+ for g in self.gid[p].values():
267
+ self.geom_owner[g] = p
268
+ self.finger_geoms, self.hand_geoms = set(), set()
269
+ for g in envs.robot_geom_ids(self.env):
270
+ n = m.geom_id2name(g) or ""
271
+ (self.finger_geoms if "finger" in n else self.hand_geoms).add(g)
272
+ self.robot_geoms = self.finger_geoms | self.hand_geoms
273
+ # per-geom lookup tables for the substep contact check: object index (-1 none), robot part (1 finger, 2 hand)
274
+ self.owner = np.full(m.ngeom, -1, int)
275
+ for i, p in enumerate(OBJS):
276
+ self.owner[list(self.gid[p].values())] = i
277
+ self.part = np.zeros(m.ngeom, int)
278
+ self.part[list(self.finger_geoms)] = 1
279
+ self.part[list(self.hand_geoms)] = 2
280
+ self._sub_rob, self._sub_obj = {}, {}
281
+ # Contacts are collected after every MuJoCo substep: a fast hit (a finger flicking a knob, a hanging object
282
+ # sweeping past) can last less than one 25-substep control step (v1, measured). Wrappers chain.
283
+ sim = self.env.sim
284
+ if not getattr(sim, "_lhf_wrapped", False):
285
+ orig = sim.step
286
+
287
+ def step(*a, **k):
288
+ orig(*a, **k)
289
+ t = getattr(sim, "_lhf_task", None)
290
+ if t is not None and t.mon is not None:
291
+ t._substep()
292
+ sim.step = step
293
+ sim._lhf_wrapped = True
294
+ sim._lhf_task = self
295
+ self.inst = None
296
+ self.mon = None
297
+ self.sk = None
298
+
299
+ def _substep(self):
300
+ d = self.env.sim.data
301
+ n = d.ncon
302
+ if not n:
303
+ return
304
+ g1 = np.asarray(d.contact.geom1)[:n]
305
+ g2 = np.asarray(d.contact.geom2)[:n]
306
+ o1, o2 = self.owner[g1], self.owner[g2]
307
+ for a, b, pa, pb in zip(g1, g2, o1, o2):
308
+ if pa < 0 and pb < 0:
309
+ continue
310
+ if pa >= 0 and pb >= 0:
311
+ if pa != pb:
312
+ self._sub_obj[int(pa)] = int(pb)
313
+ self._sub_obj[int(pb)] = int(pa)
314
+ continue
315
+ p, o = (pa, b) if pa >= 0 else (pb, a)
316
+ part = self.part[o]
317
+ if part:
318
+ prev = self._sub_rob.get(int(p), 0)
319
+ self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2
320
+
321
+ # ------------------------------------------------------------ instances
322
+ def sample_instance(self, seed):
323
+ rng = np.random.default_rng(seed)
324
+ row = "lr" if rng.random() < 0.5 else "fb"
325
+ hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced: 13 of every 20 consecutive seeds
326
+ t, w, h = (float(rng.uniform(*T_RANGE)), float(rng.uniform(*W_RANGE)), float(rng.uniform(*H_RANGE)))
327
+ b = float(rng.uniform(*B_RANGE))
328
+ gap = float(rng.uniform(*GAP_RANGE))
329
+ dens_panel, dens_post = float(rng.uniform(*DENS_RANGE)), float(rng.uniform(*DENS_RANGE))
330
+ mu = float(rng.uniform(*MU_RANGE))
331
+ foot = 0.0 if hazard else float(rng.uniform(*FOOT_RANGE))
332
+ pitch = w + 2 * gap + b # post centre to post centre
333
+ if row == "lr":
334
+ c = np.array([rng.uniform(-0.12, -0.06), rng.uniform(-0.05, 0.05)])
335
+ u = np.array([0.0, 1.0])
336
+ v = np.array([-1.0, 0.0]) # supply side: towards the robot
337
+ else:
338
+ side = 1.0 if rng.random() < 0.5 else -1.0
339
+ c = np.array([rng.uniform(-0.16, -0.10), side * rng.uniform(0.09, 0.13)])
340
+ u = np.array([1.0, 0.0])
341
+ v = np.array([0.0, -side]) # supply side: towards the middle
342
+ phi = float(np.arctan2(u[1], u[0])) # direction of the fence line
343
+ pyaw = _wrap_h(phi - np.pi / 2) # panel yaw: body y (width) along the line, body x (thickness) across
344
+ g = float(rng.uniform(*SUP_PITCH))
345
+ d = float(rng.uniform(*SUP_D))
346
+ shift = float(rng.choice([-1.0, 1.0]) * rng.uniform(0.04, 0.07))
347
+ if row == "fb": # keep the farthest supply slot within ~63 cm of the robot base, the far post within ~66 cm
348
+ c[0] -= max(0.0, c[0] + shift + g - X_FAR)
349
+ c[0] -= max(0.0, c[0] + pitch - X_FAR - 0.03)
350
+ slots = [(c + u * (s - 2) * pitch / 2).tolist() for s in range(5)]
351
+ sup = [c + v * (d + j * g) + u * (shift + (k - 1) * g) for j in range(2) for k in range(3)]
352
+ pick = rng.permutation(6)[:5]
353
+ start = {OBJS[i]: (sup[j] + rng.uniform(-0.008, 0.008, 2)).tolist() for i, j in enumerate(pick)}
354
+ yaw0 = {p: pyaw + float(rng.uniform(-0.15, 0.15)) for p in OBJS}
355
+ return dict(seed=int(seed), row=row, hazard=hazard, posts="light" if hazard else "footed", foot_mass=foot,
356
+ t=t, w=w, h=h, b=b, gap=gap, pitch=pitch, density_panel=dens_panel, density_post=dens_post, mu=mu,
357
+ center=c.tolist(), u=u.tolist(), v=v.tolist(), phi=phi, pyaw=pyaw, slots=slots,
358
+ knob_dist=w / 2 + gap + b / 2, start=start, yaw0=yaw0, supply_shift=shift, supply_pitch=g,
359
+ supply_d=d)
360
+
361
+ def _set_body(self, p, half, density, foot=0.0):
362
+ """resize p's geoms, set mass / centre of mass / inertia (board + knob + optional hidden foot), refit BVH"""
363
+ m = self.env.sim.model
364
+ hx, hy, hz = half
365
+ spec = {"board": ([hx, hy, hz], [0, 0, 0], [hx, hy, hz]),
366
+ "stem": ([STEM_R, STEM_L / 2, 0], [0, 0, hz + STEM_L / 2], [STEM_R, STEM_R, STEM_L / 2]),
367
+ "knob": ([KNOB_R, 0, 0], [0, 0, hz + STEM_L + KNOB_R], [KNOB_R, KNOB_R, KNOB_R])}
368
+ for nm, g in self.gid[p].items():
369
+ sz, pos, aabb = spec[nm]
370
+ m.geom_size[g] = sz
371
+ m.geom_pos[g] = pos
372
+ m.geom_aabb[g] = [0, 0, 0] + aabb
373
+ m.geom_rbound[g] = float(np.linalg.norm(aabb))
374
+ for nm, g in zip(("board", "stem", "knob"), self.vis[p]):
375
+ m.geom_size[g] = spec[nm][0]
376
+ m.geom_pos[g] = spec[nm][1]
377
+ bd = self.pbody[p]
378
+ X, Y, Z = 2 * hx, 2 * hy, 2 * hz
379
+ mb = density * X * Y * Z
380
+ zk = hz + STEM_L + KNOB_R
381
+ zf = -hz + FOOT_H / 2
382
+ M = mb + KNOB_MASS + foot
383
+ zc = (KNOB_MASS * zk + foot * zf) / M
384
+ I = np.array([mb * (Y * Y + Z * Z) / 12, mb * (X * X + Z * Z) / 12, mb * (X * X + Y * Y) / 12])
385
+ if foot:
386
+ I += foot * np.array([(Y * Y + FOOT_H ** 2) / 12, (X * X + FOOT_H ** 2) / 12, (X * X + Y * Y) / 12])
387
+ par = mb * zc ** 2 + KNOB_MASS * (zk - zc) ** 2 + foot * (zf - zc) ** 2
388
+ I[:2] += par
389
+ m.body_mass[bd] = M
390
+ m.body_ipos[bd] = [0, 0, zc]
391
+ m.body_iquat[bd] = [1, 0, 0, 0]
392
+ m.body_inertia[bd] = I
393
+ refit_bvh(m, bd)
394
+ return dict(mass=float(M), com_above_bottom=float(zc + hz))
395
+
396
+ def apply_instance(self, inst):
397
+ self.inst = inst
398
+ m = self.env.sim.model
399
+ self.body_info = {}
400
+ for p in POSTS:
401
+ self.body_info[p] = self._set_body(p, (inst["b"] / 2, inst["b"] / 2, inst["h"] / 2), inst["density_post"],
402
+ inst["foot_mass"])
403
+ for p in PANELS:
404
+ self.body_info[p] = self._set_body(p, (inst["t"] / 2, inst["w"] / 2, inst["h"] / 2),
405
+ inst["density_panel"])
406
+ for p in OBJS:
407
+ envs.set_friction(self.env, p, inst["mu"]) # board / stem / knob sliding friction ...
408
+ m.geom_friction[self.gid[p]["knob"]] = [1.0, KNOB_MU_T, 0.0001] # ... except the knob (grip pivot)
409
+ m.geom_friction[self.gid[p]["stem"]] = [1.0, 0.005, 0.0001]
410
+ m.geom_priority[self.gid[p]["knob"]] = 2
411
+ m.geom_condim[self.gid[p]["knob"]] = 4
412
+ self.env.sim.forward()
413
+ q = [np.cos(inst["pyaw"] / 2), 0, 0, np.sin(inst["pyaw"] / 2)]
414
+ for s, kind in enumerate(SLOT_KIND):
415
+ k = MARKS[s // 2] if kind == "post" else STRIPS[s // 2]
416
+ x, y = inst["slots"][s]
417
+ m.body_pos[self.fix_bid[k]] = [x, y, TZ + 0.0006]
418
+ m.body_quat[self.fix_bid[k]] = q
419
+ for g in self.fix_vis[k]:
420
+ m.geom_size[g] = ([inst["b"] / 2 + 0.003, inst["b"] / 2 + 0.003, 0.0005] if kind == "post" else
421
+ [STRIP_W / 2, inst["w"] / 2 + 0.005, 0.0005])
422
+ for p in OBJS:
423
+ envs.place_upright(self.env, p, inst["start"][p], yaw=inst["yaw0"][p], clearance=0.001)
424
+
425
+ def reset_instance(self, inst, recorder=None):
426
+ self.mon = None
427
+ self.env.reset()
428
+ self.apply_instance(inst)
429
+ self.env.sim.forward()
430
+ envs.settle(self.env, 15)
431
+ self.sk = FenceSkills(self.env, self, recorder=recorder)
432
+ self._sub_rob, self._sub_obj = {}, {}
433
+ n = len(SLOT_KIND)
434
+ self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
435
+ last_robot={p: None for p in OBJS}, last_obj={p: None for p in OBJS},
436
+ fallen={p: False for p in OBJS}, occupant=[None] * n, n_steps=0)
437
+ return self.sk
438
+
439
+ # ------------------------------------------------------------ geometry / predicates
440
+ @staticmethod
441
+ def kind(p):
442
+ return "post" if p.startswith("post") else "panel"
443
+
444
+ def R(self, p):
445
+ return self.env.sim.data.body_xmat[envs.body_id(self.env, p)].reshape(3, 3).copy()
446
+
447
+ def pos(self, p):
448
+ return envs.obj_pos(self.env, p)
449
+
450
+ def tilt(self, p):
451
+ return float(np.arccos(np.clip(self.R(p)[2, 2], -1.0, 1.0)))
452
+
453
+ def knob_xyz(self, p):
454
+ return self.env.sim.data.geom_xpos[self.gid[p]["knob"]].copy()
455
+
456
+ def knob_stand_z(self):
457
+ """grasp-point height (world) of a knob centre when its object stands on the table (posts = panel height)"""
458
+ return TZ + self.inst["h"] + STEM_L + KNOB_R
459
+
460
+ def held(self, p):
461
+ return self.sk is not None and self.sk.holding(p)
462
+
463
+ def on_slot(self, p, s, extra=0.0):
464
+ """object p stands upright on fence slot s (right kind, lined up), resting on the table, not held"""
465
+ if self.kind(p) != SLOT_KIND[s]:
466
+ return False
467
+ R = self.R(p)
468
+ if R[2, 2] < np.cos(TILT_OK + (np.radians(1.0) if extra else 0.0)):
469
+ return False
470
+ rel = self.pos(p)[:2] - np.asarray(self.inst["slots"][s])
471
+ du = abs(rel @ np.asarray(self.inst["u"]))
472
+ dv = abs(rel @ np.asarray(self.inst["v"]))
473
+ if SLOT_KIND[s] == "post":
474
+ if max(du, dv) > TOL_POST + extra:
475
+ return False
476
+ else:
477
+ if du > TOL_U + extra or dv > TOL_V + extra:
478
+ return False
479
+ yaw = float(np.arctan2(R[1, 0], R[0, 0]))
480
+ if abs(_wrap_h(yaw - self.inst["pyaw"])) > YAW_TOL:
481
+ return False
482
+ if envs.obj_min_z(self.env, p) > TZ + 0.006:
483
+ return False
484
+ return not self.held(p)
485
+
486
+ def slot_occupant(self, s, extra=0.0):
487
+ return next((p for p in OBJS if self.on_slot(p, s, extra)), None)
488
+
489
+ def slot_filled(self, s, extra=0.0):
490
+ return self.slot_occupant(s, extra) is not None
491
+
492
+ def stages(self):
493
+ return [self.slot_filled(s) for s in range(len(SLOT_KIND))]
494
+
495
+ def stage_names(self):
496
+ out, kc = [], {"post": 0, "panel": 0}
497
+ for kind in SLOT_KIND:
498
+ kc[kind] += 1
499
+ out.append(f"{kind}{kc[kind]}")
500
+ return out
501
+
502
+ # ------------------------------------------------------------ monitor
503
+ def _contacts(self):
504
+ d = self.env.sim.data
505
+ rob, obj = {}, {}
506
+ for j in range(d.ncon):
507
+ c = d.contact[j]
508
+ a, b = c.geom1, c.geom2
509
+ pa, pb = self.geom_owner.get(a), self.geom_owner.get(b)
510
+ if pa is not None and pb is not None and pa != pb:
511
+ obj[pa], obj[pb] = pb, pa
512
+ for p, o in ((pa, b), (pb, a)):
513
+ if p is None:
514
+ continue
515
+ if o in self.finger_geoms:
516
+ rob[p] = "finger"
517
+ elif o in self.hand_geoms and rob.get(p) != "finger":
518
+ rob[p] = "hand"
519
+ return rob, obj
520
+
521
+ def monitor_step(self):
522
+ mon = self.mon
523
+ if mon is None or self.sk is None:
524
+ return
525
+ mon["n_steps"] += 1
526
+ t = self.sk.n_steps
527
+ rob = {OBJS[i]: ("finger" if v == 1 else "hand") for i, v in self._sub_rob.items()}
528
+ obj = {OBJS[i]: OBJS[j] for i, j in self._sub_obj.items()}
529
+ self._sub_rob, self._sub_obj = {}, {}
530
+ held = [p for p in OBJS if self.held(p)]
531
+ for p, part in rob.items():
532
+ if p not in held:
533
+ mon["last_robot"][p] = (part, t, "open" if self.sk.grip < 0 else "closed")
534
+ for p, q in obj.items():
535
+ if p not in held:
536
+ mon["last_obj"][p] = (q + (" (held)" if q in held else ""), t)
537
+ for p in OBJS:
538
+ f = self.tilt(p) > FALLEN
539
+ if f != mon["fallen"][p]:
540
+ mon["fallen"][p] = f
541
+ if f:
542
+ mon["events"].append(dict(object=p, event="toppled", step=int(t), cause=self._cause(p, t)))
543
+ else:
544
+ mon["events"].append(dict(object=p, event="stood_up", step=int(t)))
545
+ if mon["n_steps"] % 2:
546
+ return
547
+ names = self.stage_names()
548
+ for s in range(len(SLOT_KIND)):
549
+ occ = self.slot_occupant(s, HYST if mon["state"][s] else 0.0)
550
+ raw = occ is not None
551
+ if raw:
552
+ mon["occupant"][s] = occ
553
+ if raw == mon["state"][s]:
554
+ mon["raw_since"][s] = 0
555
+ continue
556
+ mon["raw_since"][s] += 2
557
+ if mon["raw_since"][s] < DEBOUNCE:
558
+ continue
559
+ mon["state"][s] = raw
560
+ mon["raw_since"][s] = 0
561
+ t0 = t - DEBOUNCE + 1
562
+ if raw:
563
+ ev = dict(stage=names[s], event="restored" if mon["lost"][s] else "achieved", step=int(t0))
564
+ mon["ever"][s] = True
565
+ else:
566
+ mon["lost"][s] = True
567
+ ev = dict(stage=names[s], event="lost", step=int(t0), cause=self._slot_cause(s, t))
568
+ mon["events"].append(ev)
569
+
570
+ def _cause(self, p, t):
571
+ if self.held(p):
572
+ return "picked_up"
573
+ lr, lo = self.mon["last_robot"][p], self.mon["last_obj"][p]
574
+ cands = []
575
+ if lr is not None and t - lr[1] <= 60:
576
+ cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else "")))
577
+ if lo is not None and t - lo[1] <= 60:
578
+ cands.append((lo[1] - 30, "object:" + lo[0])) # prefer the robot when both touched it recently
579
+ return max(cands)[1] if cands else "other"
580
+
581
+ def _slot_cause(self, s, t):
582
+ """why slot s lost its object: the cause recorded for the object that last stood on it"""
583
+ p = self.mon["occupant"][s]
584
+ if p is None:
585
+ c = np.asarray(self.inst["slots"][s])
586
+ p = min(OBJS, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c)))
587
+ return self._cause(p, t)
588
+
589
+ # ------------------------------------------------------------ outcome
590
+ def _slot_name(self, s):
591
+ kind = SLOT_KIND[s]
592
+ idx = [i for i in range(len(SLOT_KIND)) if SLOT_KIND[i] == kind]
593
+ n = len(idx)
594
+ k = idx.index(s) # 0-based along +u
595
+ if self.inst["row"] == "lr": # u = +y = robot's left: count from the robot's right
596
+ what = "square mark" if kind == "post" else "strip"
597
+ return f"{what} {k + 1} of {n} (counting from the robot's right)"
598
+ what = "square mark" if kind == "post" else "strip"
599
+ u = self.inst["u"]
600
+ return f"{what} {k + 1 if u[0] > 0 else n - k} of {n} (counting from the one nearest the robot)"
601
+
602
+ def _dir_words(self, d):
603
+ parts = []
604
+ if abs(d[0]) >= 0.01:
605
+ parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}")
606
+ if abs(d[1]) >= 0.01:
607
+ parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}")
608
+ return (" and ".join(parts) + " of") if parts else "right at"
609
+
610
+ def placed_objects(self):
611
+ return {p for p in OBJS if any(self.on_slot(p, s) for s in range(len(SLOT_KIND)))}
612
+
613
+ def outcome(self, inst):
614
+ sk = self.sk
615
+ sk.hold(10)
616
+ p0 = {p: self.pos(p) for p in OBJS}
617
+ touching = False
618
+ for _ in range(20):
619
+ sk.hold(1)
620
+ rob, _ = self._contacts()
621
+ touching = touching or any(p in rob for p in OBJS)
622
+ moved = max(float(np.linalg.norm(self.pos(p) - p0[p])) for p in OBJS)
623
+ static = moved < 0.004
624
+ raw = self.stages()
625
+ held = [p for p in OBJS if self.held(p)]
626
+ mon = self.mon
627
+ ev = list(mon["events"]) if mon else []
628
+ n_reg = sum(e["event"] == "lost" for e in ev)
629
+ n_res = sum(e["event"] == "restored" for e in ev)
630
+ n_top = sum(e["event"] == "toppled" for e in ev)
631
+ success = bool(all(raw) and static and not held and not touching)
632
+ names = self.stage_names()
633
+ parts = []
634
+ ever = mon["ever"] if mon else [False] * len(raw)
635
+ if success:
636
+ failure = "none"
637
+ parts.append("The fence is complete: every square mark carries an upright post and every strip an "
638
+ "upright panel lined up with it.")
639
+ else:
640
+ lost_final = [s for s in range(len(raw)) if not raw[s] and ever[s]]
641
+ never = [s for s in range(len(raw)) if not raw[s] and not ever[s]]
642
+ if held:
643
+ failure = "held"
644
+ elif touching:
645
+ failure = "touching"
646
+ elif lost_final:
647
+ failure = "regressed"
648
+ elif never:
649
+ failure = "incomplete"
650
+ else:
651
+ failure = "not_static"
652
+ placed = self.placed_objects()
653
+ described = set()
654
+ for s in range(len(raw)):
655
+ if raw[s]:
656
+ continue
657
+ kind = SLOT_KIND[s]
658
+ c = np.asarray(inst["slots"][s])
659
+ spare = [q for q in OBJS if self.kind(q) == kind and q not in placed and q not in described]
660
+ near = min(spare, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c))) if spare else None
661
+ dist = float(np.linalg.norm(self.pos(near)[:2] - c)) if near else 1.0
662
+ if near is None or (not ever[s] and dist > 0.06):
663
+ txt = f"{self._slot_name(s)} has no {kind} on it (none was put there)."
664
+ else:
665
+ described.add(near)
666
+ tl = np.degrees(self.tilt(near))
667
+ state = ("lies fallen" if tl > 45 else f"leans {tl:.0f} degrees" if tl > np.degrees(TILT_OK)
668
+ else "stands")
669
+ txt = (f"{self._slot_name(s)} has no upright {kind} on it: the nearest {kind} {state} "
670
+ f"{self._dir_words(self.pos(near)[:2] - c)} it.")
671
+ if ever[s]:
672
+ lost = [e for e in ev if e.get("stage") == names[s] and e["event"] == "lost"]
673
+ why = lost[-1]["cause"] if lost else "other"
674
+ txt += {"robot_finger_opening": f" The {kind} had stood there; a finger pushed it when the "
675
+ f"gripper opened.",
676
+ "robot_hand_opening": f" The {kind} had stood there; the hand pushed it.",
677
+ }.get(why, f" The {kind} had stood there and was knocked over later."
678
+ if why.startswith(("robot", "object")) else f" The {kind} had stood there earlier.")
679
+ parts.append(txt)
680
+ if all(raw) and held:
681
+ parts.append("The gripper still holds an object.")
682
+ elif touching:
683
+ parts.append("The gripper is still touching the fence.")
684
+ elif all(raw) and not static:
685
+ parts.append("Something was still moving.")
686
+ if n_reg:
687
+ parts.append(f"During the attempt objects on the fence line were knocked off {n_reg} time(s) and stood "
688
+ f"up again {n_res} time(s).")
689
+ if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")):
690
+ parts.append("(Forward = away from the robot.)")
691
+ return dict(success=success, stages={names[s]: bool(raw[s]) for s in range(len(raw))}, events=ev,
692
+ n_regressions=int(n_reg), n_restored=int(n_res), n_toppled=int(n_top), failure=failure,
693
+ held=held, touching=bool(touching), static=bool(static),
694
+ tilts_deg={p: round(float(np.degrees(self.tilt(p))), 1) for p in OBJS}, detail=" ".join(parts))
695
+
696
+ # ------------------------------------------------------------ scripted policies (move_to + gripper only)
697
+ def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
698
+ return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
699
+
700
+ def axis(self, p, i):
701
+ a = self.R(p)[:2, i]
702
+ return a / max(np.linalg.norm(a), 1e-9)
703
+
704
+ def grasp_yaw(self, p, mode):
705
+ """yaw for a top-down knob grasp. Lying object: fingers across its long axis (it swings up and hangs).
706
+ Panel: 'habit' = fingers along its width (hand along the board; along the fence line once placed),
707
+ 'thin' = fingers along its thickness (across the line). Post: 'thin' = fingers across the fence line, otherwise
708
+ the side direction needing the least rotation (a post's own orientation does not matter: square, round knob)."""
709
+ R = self.R(p)
710
+ if R[2, 2] < np.cos(np.radians(30)):
711
+ ax = R[:2, 2]
712
+ if np.linalg.norm(ax) > 1e-3:
713
+ return _yaw_for_axis(np.array([-ax[1], ax[0]]))
714
+ if self.kind(p) == "panel":
715
+ return _yaw_for_axis(self.axis(p, 1) if mode == "habit" else self.axis(p, 0))
716
+ if mode == "thin": # careful: a post's fingers across the fence line too (they reach nothing there)
717
+ return _yaw_for_axis(np.asarray(self.inst["v"]))
718
+ y0 = _yaw_for_axis(self.axis(p, 0))
719
+ return min((_wrap_h(y0), _wrap_h(y0 + np.pi / 2)), key=lambda y: abs(_wrap_h(y - self.sk.yaw)))
720
+
721
+ def obj_yaw(self, p):
722
+ R = self.R(p)
723
+ return float(np.arctan2(R[1, 0], R[0, 0]))
724
+
725
+ def pick(self, p, mode, careful, z_carry=None, noise=None, v=0.15):
726
+ """grasp p's knob and lift it; returns (object yaw - gripper yaw) or None if not held"""
727
+ sk = self.sk
728
+ k = self.knob_xyz(p)
729
+ if noise is not None:
730
+ k = k + np.array([noise[0], noise[1], 0.0])
731
+ yaw = self.grasp_yaw(p, mode)
732
+ zk = max(k[2], TZ + 0.006)
733
+ sk.set_gripper(False, steps=8)
734
+ if careful:
735
+ cur = sk.eef_pos()
736
+ if cur[2] < TZ + Z_SAFE - 0.01:
737
+ self._go([cur[0], cur[1], TZ + Z_SAFE])
738
+ self._go([k[0], k[1], TZ + Z_SAFE], yaw=yaw, speed=0.3)
739
+ self._go([k[0], k[1], zk + 0.04], speed=0.25)
740
+ self._go([k[0], k[1], zk], speed=0.1, tol=0.003, max_steps=150)
741
+ else: # Sonnet-like: over the knob at carry height, down at 0.1 to 1.5 cm above, last 1.5 cm at 0.04
742
+ zt = TZ + (Z_NAIVE if z_carry is None else z_carry)
743
+ cur = sk.eef_pos()
744
+ self._go([k[0], k[1], max(cur[2], zt, zk + 0.06)], yaw=yaw, speed=v)
745
+ self._go([k[0], k[1], zk + 0.015], speed=0.1)
746
+ self._go([k[0], k[1], zk], speed=0.04, tol=0.003, max_steps=150)
747
+ sk.set_gripper(True, steps=15)
748
+ if careful:
749
+ self._go([k[0], k[1], TZ + Z_SAFE], speed=0.25)
750
+ else:
751
+ self._go([k[0], k[1], TZ + (Z_NAIVE if z_carry is None else z_carry)], speed=0.08)
752
+ sk.hold(10)
753
+ if not self.held(p):
754
+ sk.set_gripper(False, steps=8) # already lifted: the fingers open well above the object
755
+ return None
756
+ return float(self.obj_yaw(p) - sk.yaw)
757
+
758
+ def release_z(self, p):
759
+ """grasp-point height at which the held object's bottom is 2 mm above the table (a heavy object's knob can
760
+ sit a few mm low in the fingers; pressing it onto the table would squeeze the knob out of the grip)"""
761
+ dz = float(self.sk.eef_pos()[2] - self.knob_xyz(p)[2]) if self.held(p) else 0.0
762
+ return self.knob_stand_z() + 0.002 + float(np.clip(dz, -0.005, 0.015))
763
+
764
+ def place_yaw(self, p, offset):
765
+ """gripper yaw that lines p up with the fence (panel: width along the line; post: sides along it)"""
766
+ if self.kind(p) == "panel":
767
+ return _wrap_h(self.inst["pyaw"] - offset)
768
+ cands = [_wrap_h(self.inst["pyaw"] + k * np.pi / 2 - offset) for k in range(4)]
769
+ return min(cands, key=lambda y: abs(_wrap_h(y - self.sk.yaw)))
770
+
771
+ def place(self, p, s, offset, careful, z_carry=None, noise=None, lift=None, v=0.15):
772
+ """carry the held object to fence slot s, lined up with the fence; set it down; let go"""
773
+ sk = self.sk
774
+ xy = np.asarray(self.inst["slots"][s], float) + (np.asarray(noise, float) if noise is not None else 0.0)
775
+ yaw = self.place_yaw(p, offset)
776
+ zr = self.release_z(p)
777
+ if careful:
778
+ cur = sk.eef_pos()
779
+ if cur[2] < TZ + Z_SAFE - 0.01:
780
+ self._go([cur[0], cur[1], TZ + Z_SAFE])
781
+ self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw, speed=0.3)
782
+ sk.hold(15)
783
+ zr = self.release_z(p)
784
+ self._go([xy[0], xy[1], zr + 0.03], speed=0.2)
785
+ self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=150)
786
+ sk.set_gripper(False, steps=12)
787
+ self._go([xy[0], xy[1], zr + 0.04], speed=0.1)
788
+ self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3)
789
+ else: # Sonnet-like: to above the slot at carry height, 0.1 m/s to 1.5 cm above, last 1.5 cm at 0.03, open
790
+ zt = TZ + (Z_NAIVE if z_carry is None else z_carry)
791
+ cur = sk.eef_pos()
792
+ self._go([xy[0], xy[1], max(cur[2], zt)], yaw=yaw, speed=v)
793
+ self._go([xy[0], xy[1], zr + 0.015], speed=0.1)
794
+ self._go([xy[0], xy[1], zr], speed=0.03, tol=0.003, max_steps=150)
795
+ sk.set_gripper(False, steps=12)
796
+ self._go([xy[0], xy[1], TZ + (Z_NAIVE if lift is None else lift)], speed=0.15)
797
+ sk.hold(5)
798
+
799
+ # orders ---------------------------------------------------------------
800
+ def supply_center(self):
801
+ return np.mean([self.inst["start"][p] for p in OBJS], axis=0)
802
+
803
+ def fence_order(self, far_first=True):
804
+ """slot indices from the end of the line farthest from the supply to the near end (or reversed)"""
805
+ sc = self.supply_center()
806
+ first, last = np.asarray(self.inst["slots"][0]), np.asarray(self.inst["slots"][-1])
807
+ idx = list(range(len(SLOT_KIND)))
808
+ near_first = idx if np.linalg.norm(first - sc) <= np.linalg.norm(last - sc) else idx[::-1]
809
+ return near_first[::-1] if far_first else near_first
810
+
811
+ def build(self, order, careful, panel_mode, noise_fn=lambda: None, z_carry=None, lift=None, noise_pick=False,
812
+ v=0.15):
813
+ """put an object on every slot that has none, in the given slot order; the object for each slot: an unused
814
+ one of the right kind, the nearest to the gripper (naive) / to the slot (careful). No looking back."""
815
+ fails = {}
816
+ used = set()
817
+ for s in order:
818
+ if self.slot_filled(s):
819
+ continue
820
+ for _ in range(2):
821
+ cand = [p for p in OBJS if self.kind(p) == SLOT_KIND[s] and p not in used and fails.get(p, 0) < 2
822
+ and p not in self.placed_objects()]
823
+ if not cand:
824
+ break
825
+ ref = np.asarray(self.inst["slots"][s]) if careful else self.sk.eef_pos()[:2]
826
+ p = min(cand, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - ref)))
827
+ mode = panel_mode if self.kind(p) == "panel" else ("thin" if careful else "any")
828
+ off = self.pick(p, mode, careful, z_carry=z_carry, noise=noise_fn() if noise_pick else None, v=v)
829
+ if off is None:
830
+ fails[p] = fails.get(p, 0) + 1
831
+ continue
832
+ used.add(p)
833
+ self.place(p, s, off, careful, z_carry=z_carry, noise=noise_fn(), lift=lift, v=v)
834
+ break
835
+
836
+ def footprint(self, p):
837
+ """sample points of p's collision box projected onto the table (corners, edge and face midpoints) + knob"""
838
+ R, c = self.R(p), self.pos(p)
839
+ if self.kind(p) == "panel":
840
+ h = np.array([self.inst["t"], self.inst["w"], self.inst["h"]]) / 2
841
+ else:
842
+ h = np.array([self.inst["b"], self.inst["b"], self.inst["h"]]) / 2
843
+ pts = [c + R @ (h * [a, b, z]) for a in (-1, 0, 1) for b in (-1, 0, 1) for z in (-1, 0, 1)]
844
+ pts.append(self.knob_xyz(p))
845
+ return np.array(pts)[:, :2]
846
+
847
+ def slot_blocked(self, s, ignore=()):
848
+ """an object that is not standing on a slot lies (partly) on slot s or right next to it"""
849
+ c = np.asarray(self.inst["slots"][s])
850
+ u, v = np.asarray(self.inst["u"]), np.asarray(self.inst["v"])
851
+ hu = (self.inst["w"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.003
852
+ hv = (self.inst["t"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.008
853
+ placed = self.placed_objects()
854
+ for q in OBJS:
855
+ if q in ignore or self.held(q) or q in placed: # objects standing on their own slots are fine
856
+ continue
857
+ d = self.footprint(q) - c
858
+ if np.any((np.abs(d @ u) < hu) & (np.abs(d @ v) < hv)):
859
+ return True
860
+ return False
861
+
862
+ def fingers_along_width(self, p):
863
+ """the held panel's width axis is (nearly) parallel to the finger axis"""
864
+ fa = np.array([-np.sin(self.sk.yaw), np.cos(self.sk.yaw)])
865
+ return abs(float(self.axis(p, 1) @ fa)) > 0.7
866
+
867
+ def repair(self, rounds=None):
868
+ """look at every slot; stand fallen / misplaced objects up again by their knobs (careful motions, panels
869
+ released with the fingers across the line). Order: an object resting on another first, then fallen / leaning
870
+ ones from the top of the pile down, then upright ones that are off their slots. A panel lifted with its
871
+ fingers along its width (a fallen panel can only be lifted that way) is first set down standing at a free spot
872
+ and re-grasped. Returns the number of objects moved."""
873
+ n = len(SLOT_KIND)
874
+ moved = 0
875
+ fails, moves = {}, {}
876
+ for _ in range(rounds or 16):
877
+ if all(self.stages()):
878
+ break
879
+ ok = self.placed_objects()
880
+ loose = [p for p in OBJS if p not in ok and fails.get(p, 0) < 2 and moves.get(p, 0) < 4]
881
+ if not loose:
882
+ break
883
+ on_other = [p for p in loose if envs.obj_min_z(self.env, p) > TZ + 0.006]
884
+ down = [p for p in loose if p not in on_other and self.tilt(p) > TILT_OK]
885
+ upright = [p for p in loose if p not in on_other and p not in down]
886
+ if on_other:
887
+ p = max(on_other, key=lambda q: self.knob_xyz(q)[2])
888
+ elif down:
889
+ p = max(down, key=lambda q: self.knob_xyz(q)[2])
890
+ else:
891
+ fit = {q: [s for s in range(n) if SLOT_KIND[s] == self.kind(q) and not self.slot_filled(s)
892
+ and not self.slot_blocked(s, ignore=(q,))] for q in upright}
893
+ fit = {q: js for q, js in fit.items() if js}
894
+ if not fit:
895
+ break
896
+ p = min(fit, key=lambda q: min(float(np.linalg.norm(self.pos(q)[:2] - np.asarray(
897
+ self.inst["slots"][s]))) for s in fit[q]))
898
+ off = self.pick(p, "thin", True)
899
+ if off is None:
900
+ fails[p] = fails.get(p, 0) + 1
901
+ continue
902
+ moved += 1
903
+ moves[p] = moves.get(p, 0) + 1
904
+ if self.kind(p) == "panel" and self.fingers_along_width(p):
905
+ self.place_at(p, self.free_spot(), off)
906
+ continue
907
+ clear = [s for s in range(n) if SLOT_KIND[s] == self.kind(p) and not self.slot_filled(s)
908
+ and not self.slot_blocked(s, ignore=(p,))]
909
+ if not clear:
910
+ self.place_at(p, self.free_spot(), off)
911
+ continue
912
+ here = self.sk.eef_pos()[:2]
913
+ s = min(clear, key=lambda j: float(np.linalg.norm(np.asarray(self.inst["slots"][j]) - here)))
914
+ self.place(p, s, off, True)
915
+ return moved
916
+
917
+ def free_spot(self):
918
+ """the reachable table spot (around the fence and the supply) farthest from every object and slot"""
919
+ c, v = np.asarray(self.inst["center"]), np.asarray(self.inst["v"])
920
+ u = np.asarray(self.inst["u"])
921
+ best, bc = None, -1.0
922
+ for a in np.linspace(-0.20, 0.20, 9):
923
+ for b in (-0.18, -0.12, 0.10, 0.20, 0.32):
924
+ q = c + v * b + u * a
925
+ if not (-0.40 < q[0] < 0.08 and -0.32 < q[1] < 0.32) or np.hypot(q[0] + 0.66, q[1]) > 0.60:
926
+ continue
927
+ cl = min(float(np.linalg.norm(self.pos(o)[:2] - q)) for o in OBJS)
928
+ cl = min(cl, min(float(np.linalg.norm(np.asarray(sl) - q)) for sl in self.inst["slots"]))
929
+ if cl > bc:
930
+ best, bc = q, cl
931
+ return best
932
+
933
+ def place_at(self, p, xy, offset):
934
+ """careful: set the held object down standing at a free spot"""
935
+ sk = self.sk
936
+ zr = self.release_z(p)
937
+ cur = sk.eef_pos()
938
+ if cur[2] < TZ + Z_SAFE - 0.01:
939
+ self._go([cur[0], cur[1], TZ + Z_SAFE])
940
+ self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=self.place_yaw(p, offset), speed=0.3)
941
+ sk.hold(15)
942
+ zr = self.release_z(p)
943
+ self._go([xy[0], xy[1], zr + 0.03], speed=0.2)
944
+ self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=200)
945
+ sk.set_gripper(False, steps=12)
946
+ self._go([xy[0], xy[1], zr + 0.04], speed=0.1)
947
+ self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3)
948
+
949
+ # ------------------------------------------------------------ policies
950
+ def execute(self, inst, params):
951
+ careful = params["careful"]
952
+ noise = params.get("noise", 0.0)
953
+ rng = np.random.default_rng(params.get("noise_seed", 0))
954
+ nf = (lambda: rng.uniform(-noise, noise, 2)) if noise else (lambda: None)
955
+ if params.get("order") == "panels_first":
956
+ fo = self.fence_order(True)
957
+ order = [s for s in fo if SLOT_KIND[s] == "panel"] + [s for s in fo if SLOT_KIND[s] == "post"]
958
+ elif params.get("order") == "posts_first":
959
+ fo = self.fence_order(True)
960
+ order = [s for s in fo if SLOT_KIND[s] == "post"] + [s for s in fo if SLOT_KIND[s] == "panel"]
961
+ else:
962
+ order = self.fence_order(params.get("far_first", True))
963
+ self.build(order, careful, params["panel_mode"], noise_fn=nf, z_carry=params.get("z_carry"),
964
+ lift=params.get("lift"), noise_pick=params.get("noise_pick", False), v=params.get("v", 0.15))
965
+ if params.get("check"):
966
+ self.repair()
967
+ cur = self.sk.eef_pos()
968
+ if cur[2] < TZ + 0.20:
969
+ self._go([cur[0], cur[1], TZ + 0.20], speed=0.3)
970
+ self.sk.hold(10)
971
+
972
+ # naive = Sonnet 5.5's habits measured in the lh2_fence pilot: hand (finger axis) along the board's long side, fill
973
+ # from the far end, carry 21 cm above the table at 0.15 m/s, slow last 1.5 cm, ~1 cm placement error, no re-check
974
+ NAIVE = dict(careful=False, panel_mode="habit", far_first=True, check=False, noise=NAIVE_ERR)
975
+ CAREFUL = dict(careful=True, panel_mode="thin", far_first=True, check=True)
976
+ V1_NAIVE = dict(careful=False, panel_mode="thin", far_first=False, check=False) # v1's scripted naive habits
977
+
978
+ def default_params(self, inst):
979
+ return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 11)
980
+
981
+ def oracle_params(self, inst):
982
+ return dict(self.CAREFUL)
983
+
984
+ def adapt_params(self, inst, history):
985
+ """from attempt 2 (after a failure): panels released with the fingers across the line, careful, final check"""
986
+ return dict(self.CAREFUL)
987
+
988
+ def blind_params(self, inst, attempt, rng):
989
+ """the naive behaviour with random variations, no history, no check"""
990
+ return dict(self.NAIVE, noise_seed=int(rng.integers(1 << 30)), z_carry=float(rng.uniform(0.15, 0.23)),
991
+ lift=float(rng.uniform(0.15, 0.23)), v=float(rng.uniform(0.08, 0.25)))
992
+
993
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
994
+ k = k or self.max_attempts
995
+ rng = np.random.default_rng(seed)
996
+ history = []
997
+ single = ("oracle", "naive", "oracle_noise", "v1_naive", "naive_thin", "naive_panels_first",
998
+ "naive_posts_first")
999
+ for a in range(k):
1000
+ self.reset_instance(inst)
1001
+ if kind == "oracle":
1002
+ params = self.oracle_params(inst)
1003
+ elif kind == "naive":
1004
+ params = self.default_params(inst)
1005
+ elif kind == "adaptive":
1006
+ params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
1007
+ elif kind == "blind":
1008
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
1009
+ elif kind == "switch": # control: cross-attempt learning only (careful from attempt 2), no check
1010
+ params = self.default_params(inst) if a == 0 else dict(self.CAREFUL, check=False)
1011
+ elif kind == "oracle_noise": # check: careful with +-5 mm (uniform, per axis) placement noise
1012
+ params = dict(self.CAREFUL, noise=0.005, noise_seed=int(seed) * 7 + a)
1013
+ elif kind == "v1_naive": # control: v1's scripted naive (fingers across the line, near end first)
1014
+ params = dict(self.V1_NAIVE)
1015
+ elif kind == "naive_thin": # control: Sonnet-like but panels released with the fingers across the line
1016
+ params = dict(self.default_params(inst), panel_mode="thin")
1017
+ elif kind == "naive_panels_first": # control: Sonnet-like grasp, both panels before the posts
1018
+ params = dict(self.default_params(inst), order="panels_first")
1019
+ elif kind == "naive_posts_first": # control: Sonnet-like grasp, all posts first (how fences are built)
1020
+ params = dict(self.default_params(inst), order="posts_first")
1021
+ else:
1022
+ raise ValueError(kind)
1023
+ self.execute(inst, params)
1024
+ out = self.outcome(inst)
1025
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
1026
+ if on_attempt:
1027
+ on_attempt(a, params, out)
1028
+ if out["success"] or kind in single:
1029
+ break
1030
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_viewer/export.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Export saved API-player runs as a portable, offline Agent Viewer.
2
+
3
+ No simulator/model calls are made. Original image bytes are embedded once.
4
+ Supports transcript.jsonl and gpt_transcript.jsonl (API-player event schema).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import base64
10
+ import hashlib
11
+ import json
12
+ import re
13
+ from pathlib import Path
14
+
15
+
16
+ def read_jsonl(path):
17
+ rows = []
18
+ for number, line in enumerate(path.read_text().splitlines(), 1):
19
+ if line.strip():
20
+ try:
21
+ rows.append(json.loads(line))
22
+ except json.JSONDecodeError as exc:
23
+ raise ValueError(f"{path.name}:{number}: malformed JSON; export a completed log") from exc
24
+ return rows
25
+
26
+
27
+ def parse_output(value):
28
+ if isinstance(value, dict):
29
+ return value
30
+ try:
31
+ parsed = json.loads(value)
32
+ return parsed if isinstance(parsed, dict) else {}
33
+ except (ValueError, TypeError):
34
+ return {}
35
+
36
+
37
+ def build_run(folder, assets, sandbox_override=None):
38
+ folder = Path(folder)
39
+ transcript = next((folder / name for name in ('transcript.jsonl', 'gpt_transcript.jsonl')
40
+ if (folder / name).exists()), None)
41
+ if not transcript:
42
+ raise ValueError(f"No supported API-player transcript in {folder}")
43
+ rows = read_jsonl(transcript)
44
+ if not any(row.get('ev') == 'assistant' for row in rows):
45
+ raise ValueError(f"No API-player assistant events in {transcript}")
46
+ session = json.loads((folder / 'session.json').read_text())
47
+ events = read_jsonl(folder / 'events.jsonl') if (folder / 'events.jsonl').exists() else []
48
+ start = next((r for r in rows if r.get('ev') == 'start'), {})
49
+ server = next((r for r in events if r.get('ev') == 'session_start'), {})
50
+ sandbox = Path(sandbox_override or session.get('sandbox', folder))
51
+ warnings, cache = [], {}
52
+
53
+ def images(refs, source, timestamp):
54
+ result = []
55
+ for ref in refs:
56
+ if not isinstance(ref, str):
57
+ raise ValueError('Expected image path strings in API-player transcript')
58
+ if ref not in cache:
59
+ relative = Path(ref)
60
+ roots = [folder, sandbox]
61
+ candidates = []
62
+ # Only export images within the explicitly selected run/sandbox.
63
+ for root in roots:
64
+ candidate = (root / relative).resolve()
65
+ if candidate.is_relative_to(root.resolve()):
66
+ candidates.append(candidate)
67
+ path = next((p for p in candidates if p.is_file()), None)
68
+ key = None
69
+ if path:
70
+ raw = path.read_bytes()
71
+ if raw.startswith(b'\xff\xd8\xff'):
72
+ mime = 'image/jpeg'
73
+ elif raw.startswith(b'\x89PNG\r\n\x1a\n'):
74
+ mime = 'image/png'
75
+ elif raw[:6] in (b'GIF87a', b'GIF89a'):
76
+ mime = 'image/gif'
77
+ elif raw[:4] == b'RIFF' and raw[8:12] == b'WEBP':
78
+ mime = 'image/webp'
79
+ else:
80
+ raise ValueError(f'Unsupported image bytes: {ref}')
81
+ key = hashlib.sha256(raw).hexdigest()[:24]
82
+ assets[key] = f'data:{mime};base64,' + base64.b64encode(raw).decode()
83
+ else:
84
+ warnings.append(f'图片缺失:{ref}')
85
+ name = relative.stem
86
+ camera = 'agentview' if 'agentview' in name else 'wrist' if 'wrist' in name else name
87
+ cache[ref] = {'asset': key, 'path': ref, 'camera': camera}
88
+ result.append({**cache[ref], 'source': source, 'at': timestamp})
89
+ return result
90
+
91
+ outcomes = [{'attempt': e.get('attempt'), 'success': e.get('success'),
92
+ 'feedback': e.get('feedback', ''), 'at': e.get('t')}
93
+ for e in events if e.get('ev') == 'done']
94
+ steps, pending, latest, latest_text = [], [], [], ''
95
+ attempt, origin, active, task_text = 1, rows[0].get('t', 0), None, ''
96
+ for line, row in enumerate(rows, 1):
97
+ kind = row.get('ev')
98
+ if kind == 'user':
99
+ latest_text = row.get('text', '')
100
+ if not task_text:
101
+ match = re.search(r'\{.*\}', latest_text, re.S)
102
+ task_text = parse_output(match.group() if match else '').get('task', latest_text)
103
+ if row.get('images'):
104
+ latest = images(row['images'], line, row.get('t'))
105
+ elif kind in ('api_error', 'abort'):
106
+ pending.append({'kind': kind, 'text': row.get('error', ''), 'at': row.get('t')})
107
+ elif kind == 'assistant':
108
+ calls = row.get('tool_calls', [])
109
+ active = {
110
+ 'index': len(steps), 'turn': row.get('turn'), 'attempt': attempt,
111
+ 'at': row.get('t'), 'elapsed': max(0, row.get('t', origin) - origin),
112
+ 'latency': row.get('latency_s'), 'before': list(latest),
113
+ 'inputText': latest_text, 'text': row.get('text') or '',
114
+ 'decisionSummary': row.get('reasoning_summary') or None,
115
+ 'decisionSummaryStatus': row.get('reasoning_summary_status', 'not_recorded'),
116
+ 'decisionSourceLine': line,
117
+ 'actions': [{'id': c.get('id'), 'name': c.get('name', 'tool'),
118
+ 'arguments': c.get('arguments', {}), 'result': None,
119
+ 'after': []} for c in calls],
120
+ 'notices': pending, 'verdict': None,
121
+ 'requestImages': row.get('request_stats', {}).get('n_images'),
122
+ }
123
+ pending = []
124
+ steps.append(active)
125
+ elif kind == 'tool':
126
+ if active is None:
127
+ warnings.append(f'第 {line} 行工具结果缺少前置调用')
128
+ continue
129
+ if row.get('turn') is not None and row.get('turn') != active['turn']:
130
+ raise ValueError(f'Tool turn mismatch at transcript line {line}')
131
+ unresolved = [a for a in active['actions'] if a['result'] is None]
132
+ call_id = row.get('call_id') or row.get('tool_call_id')
133
+ action = next((a for a in unresolved if call_id and a['id'] == call_id), None)
134
+ if call_id and action is None:
135
+ raise ValueError(f'Unknown tool call id at transcript line {line}')
136
+ if action is None:
137
+ action = next((a for a in unresolved if isinstance(a['arguments'], dict)
138
+ and a['arguments'].get('command') == row.get('command')), None)
139
+ if action is None and len(unresolved) == 1:
140
+ action = unresolved[0]
141
+ if action is None:
142
+ raise ValueError(f'Ambiguous tool result at transcript line {line}')
143
+ output = row.get('output', '')
144
+ action['result'] = output
145
+ action['at'] = row.get('t')
146
+ action['after'] = images(row.get('images', []), line, row.get('t'))
147
+ parsed = parse_output(output)
148
+ action['ok'] = parsed.get('ok')
149
+ latest_text = output if isinstance(output, str) else json.dumps(output, ensure_ascii=False)
150
+ if action['after']:
151
+ latest = list(action['after'])
152
+ command = row.get('command') or (action['arguments'].get('command', '')
153
+ if isinstance(action['arguments'], dict) else '')
154
+ if command.split(' ', 1)[0] == 'done':
155
+ verdict = next((o for o in outcomes if o['attempt'] == attempt), None)
156
+ if verdict:
157
+ active['verdict'] = verdict
158
+ # A failed done may immediately return RESET images for the next attempt.
159
+ message = parsed.get('message', '')
160
+ next_attempt = re.search(r'Attempt\s+(\d+)\s+of', message)
161
+ if next_attempt:
162
+ attempt = int(next_attempt.group(1))
163
+ action['resetToAttempt'] = attempt
164
+ if pending:
165
+ steps[-1]['noticesAfter'] = pending
166
+ for step in steps:
167
+ step['incomplete'] = any(a['result'] is None for a in step['actions'])
168
+ status = 'success' if any(o['success'] is True for o in outcomes) else (
169
+ 'failed' if outcomes and any(r.get('ev') == 'end' and r.get('finished') is True for r in rows) else 'incomplete')
170
+ video = None
171
+ video_path = folder / 'rollout.mp4'
172
+ if video_path.is_file():
173
+ raw = video_path.read_bytes()
174
+ if len(raw) < 12 or raw[4:8] != b'ftyp':
175
+ raise ValueError('rollout.mp4 is not an MP4 container')
176
+ key = 'video-' + hashlib.sha256(raw).hexdigest()[:24]
177
+ assets[key] = 'data:video/mp4;base64,' + base64.b64encode(raw).decode()
178
+ video = {'asset': key, 'name': 'rollout.mp4'}
179
+ return {'id': folder.name, 'video': video, 'task': server.get('task', folder.name),
180
+ 'taskText': task_text, 'seed': server.get('seed'), 'model': start.get('model', '未记录'),
181
+ 'perception': server.get('perception', '未记录'), 'feedback': server.get('feedback', '未记录'),
182
+ 'status': status, 'steps': steps, 'outcomes': outcomes,
183
+ 'warnings': sorted(set(warnings)), 'source': transcript.name,
184
+ 'actionCount': sum(len(s['actions']) for s in steps)}
185
+
186
+
187
+ def render(folders, output, sandbox_override=None):
188
+ assets = {}
189
+ runs = [build_run(folder, assets, sandbox_override) for folder in folders]
190
+ payload = json.dumps({'version': 1, 'runs': runs, 'assets': assets}, ensure_ascii=False)
191
+ # Logs are untrusted text, including strings containing HTML/script terminators.
192
+ payload = payload.replace('&', '\\u0026').replace('<', '\\u003c').replace('>', '\\u003e')
193
+ template = Path(__file__).with_name('viewer.html').read_text()
194
+ output = Path(output)
195
+ output.parent.mkdir(parents=True, exist_ok=True)
196
+ output.write_text(template.replace('/*__PAYLOAD__*/null', payload))
197
+ return runs
198
+
199
+
200
+ def main():
201
+ parser = argparse.ArgumentParser(description=__doc__)
202
+ parser.add_argument('--run', type=Path, action='append', required=True, help='Repeat to include multiple runs')
203
+ parser.add_argument('--out', type=Path, required=True)
204
+ parser.add_argument('--sandbox', type=Path, help='Relocated image directory for a single run')
205
+ args = parser.parse_args()
206
+ if args.sandbox and len(args.run) != 1:
207
+ parser.error('--sandbox requires exactly one --run')
208
+ try:
209
+ runs = render(args.run, args.out, args.sandbox)
210
+ except (ValueError, OSError, KeyError) as exc:
211
+ parser.exit(1, f'Export failed: {exc}\n')
212
+ print(json.dumps({'output': str(args.out.resolve()), 'runs': [
213
+ {'task': r['task'], 'steps': len(r['steps']), 'actions': r['actionCount'],
214
+ 'outcomes': [o['success'] for o in r['outcomes']], 'warnings': r['warnings']} for r in runs
215
+ ]}, ensure_ascii=False, indent=2))
216
+
217
+
218
+ if __name__ == '__main__':
219
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/start_real_session.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Start a REAL-robot server (lffbench/real/session.py) + workspace for one task instance; same output as
3
+ # scripts/start_robot_session.sh (SANDBOX=, LOG=, <LOG>/session.json), so harness_run.py / api_player.py run on it unchanged.
4
+ # usage: scripts/start_real_session.sh <task> <seed> <memory full|none> <feedback F0|F1> <port> [instruction direct|indirect] [k] [tag]
5
+ # The driver: $LFF_REAL_DRIVER (default http://127.0.0.1:9900, normally an SSH tunnel to the robot PC) and $LFF_DRIVER_TOKEN.
6
+ # Blocks until the operator has set up the scene for attempt 1 (up to $LFF_REAL_READY_WAIT s, default 3600).
7
+ set -e
8
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
9
+ TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}
10
+ RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT}
11
+ SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))')
12
+ LOG=${LFF_RUNS_DIR:-$ROOT/runs/real}/$RUN
13
+ mkdir -p "$SANDBOX" "$LOG"
14
+ cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1
15
+ KARG=""; [ -n "$K" ] && KARG="--k $K"
16
+ nohup python -m lffbench.real.session --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \
17
+ --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --run-name "$RUN" ${LFF_EXTRA_ARGS:-} $KARG \
18
+ > "$LOG/server.log" 2>&1 &
19
+ echo $! > "$LOG/server.pid"
20
+ WAIT=${LFF_REAL_READY_WAIT:-3600}
21
+ for i in $(seq 1 "$WAIT"); do
22
+ [ -f "$LOG/READY" ] && break
23
+ kill -0 "$(cat "$LOG/server.pid")" 2>/dev/null || break
24
+ [ $((i % 30)) -eq 0 ] && echo "waiting for the operator to set up the scene ($i s)" >&2
25
+ sleep 1
26
+ done
27
+ [ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; exit 1; }
28
+ echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json"
29
+ echo "SANDBOX=$SANDBOX"
30
+ echo "LOG=$LOG"
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """LFF-Bench agent harness: tool interface, context packing, model backends, protocol runner."""
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/images.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image references and encoding (JPEG bytes are what the model sees and what is saved to disk)."""
2
+ import base64
3
+ import io
4
+ from dataclasses import dataclass
5
+ from typing import Any, Optional
6
+
7
+ import numpy as np
8
+
9
+
10
+ @dataclass
11
+ class ImageRef:
12
+ camera: str # agent-facing camera name ("agentview" / "wrist")
13
+ array: Any = None # uint8 HxWx3
14
+ label: str = ""
15
+ path: Optional[str] = None # where the encoded image was saved
16
+ jpeg: Optional[bytes] = None # encoded bytes actually sent to the model
17
+
18
+ def encoded(self, quality=90):
19
+ if self.jpeg is None:
20
+ if self.array is None and self.path:
21
+ with open(self.path, "rb") as f:
22
+ self.jpeg = f.read()
23
+ else:
24
+ self.jpeg = encode_jpeg(self.array, quality)
25
+ return self.jpeg
26
+
27
+ def data_url(self, quality=90):
28
+ return "data:image/jpeg;base64," + base64.b64encode(self.encoded(quality)).decode("ascii")
29
+
30
+ @property
31
+ def size(self):
32
+ return None if self.array is None else tuple(np.asarray(self.array).shape[:2])
33
+
34
+
35
+ def encode_jpeg(arr, quality=90):
36
+ from PIL import Image
37
+ buf = io.BytesIO()
38
+ Image.fromarray(np.asarray(arr, dtype=np.uint8)).save(buf, format="JPEG", quality=int(quality))
39
+ return buf.getvalue()
40
+
41
+
42
+ def resize(arr, res):
43
+ from PIL import Image
44
+ arr = np.asarray(arr, dtype=np.uint8)
45
+ if arr.shape[0] == res and arr.shape[1] == res:
46
+ return arr
47
+ return np.asarray(Image.fromarray(arr).resize((res, res), Image.BILINEAR))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/replay.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rebuild AttemptRecords from a finished run directory (events.jsonl + images/), e.g. to use a full-memory
2
+ run as the donor pool of a mismatched-memory run without re-running (and re-paying for) it."""
3
+ import json
4
+ import os
5
+
6
+ from .context import AttemptRecord, StepRecord
7
+ from .images import ImageRef
8
+
9
+
10
+ def load_events(run_dir):
11
+ with open(os.path.join(run_dir, "events.jsonl")) as f:
12
+ return [json.loads(line) for line in f if line.strip()]
13
+
14
+
15
+ def load_records(run_dir, task=None, feedback="F2"):
16
+ """{seed: [AttemptRecord]} with keyframes loaded from disk. Feedback text is re-rendered at the
17
+ requested level with task.feedback() when a task is given (else the logged F2 text / '')."""
18
+ ev = load_events(run_dir)
19
+ insts, steps, out = {}, {}, {}
20
+ for e in ev:
21
+ t = e["type"]
22
+ if t == "run_start":
23
+ insts[e["seed"]] = e["inst"]
24
+ out[e["seed"]] = []
25
+ elif t == "tool_call":
26
+ steps.setdefault((e["seed"], e["attempt"]), []).append(
27
+ StepRecord(step=e["step"], name=e["name"], args=e["args"], report=e["report"], ok=e["ok"]))
28
+ elif t == "attempt_end":
29
+ seed, a = e["seed"], e["attempt"]
30
+ kfs = []
31
+ for cap, rel in e.get("keyframes") or []:
32
+ p = os.path.join(run_dir, rel)
33
+ with open(p, "rb") as f:
34
+ kfs.append((cap, ImageRef(camera="agentview", path=p, jpeg=f.read())))
35
+ o = e["outcome"]
36
+ if task is not None:
37
+ fb = task.feedback(insts.get(seed, {}), o, feedback)
38
+ else:
39
+ fb = {"F0": "", "F1": "Attempt succeeded." if e["success"] else "Attempt failed."}.get(
40
+ feedback, e.get("feedback_f2", ""))
41
+ out.setdefault(seed, []).append(AttemptRecord(
42
+ seed=seed, attempt=a, steps=steps.get((seed, a), []), keyframes=kfs, outcome=o,
43
+ success=bool(e["success"]), feedback=fb, done_reason=e.get("done_reason"),
44
+ diagnosis=e.get("diagnosis"), ended_by=e.get("ended_by", ""), backend_meta=e.get("backend_meta") or {}))
45
+ return out
46
+
47
+
48
+ def derange(target_seeds, donor_seeds):
49
+ """Map each target seed to a donor seed != itself (cyclic shift over the sorted donor pool)."""
50
+ pool = sorted(donor_seeds)
51
+ if not pool:
52
+ raise ValueError("empty donor pool")
53
+ m = {}
54
+ for i, s in enumerate(sorted(target_seeds)):
55
+ j = (pool.index(s) + 1) % len(pool) if s in pool else i % len(pool)
56
+ if pool[j] == s:
57
+ raise ValueError(f"cannot find a donor different from seed {s} (pool {pool})")
58
+ m[s] = pool[j]
59
+ return m
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/robot_server.py ADDED
@@ -0,0 +1,966 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Robot server for driving an LFF-Bench task from an isolated agent (e.g. a Claude Code subagent).
2
+
3
+ The server owns the simulator, the task instance and its hidden variables. The agent only gets a
4
+ sandbox directory containing a tiny `robot` CLI (talks to this server over localhost HTTP), a README
5
+ with the instructions, and the observation images the server writes into `<sandbox>/obs/`.
6
+ Nothing about the benchmark (code paths, hidden variables, success rule, scripted policies) is ever
7
+ written into the sandbox.
8
+
9
+ Attempt protocol (same semantics as harness.py):
10
+ cross `done` -> outcome is measured; if failed and attempts remain, the scene is reset to the same
11
+ initial state + hidden variables and the next attempt starts.
12
+ within `done` -> outcome is measured; if failed and done-calls remain, continue from the current state.
13
+ memory=none: every attempt is meant for a fresh agent; after `done` the server tells the agent to stop
14
+ (no feedback) and waits for the orchestrator to start a new agent (`./robot status` shows the state).
15
+
16
+ Run: python -m lffbench.agent.robot_server --task l5_slide_to_target --seed 1001 --sandbox <dir> --port 8765
17
+ """
18
+ import argparse
19
+ import importlib
20
+ import json
21
+ import os
22
+ import pkgutil
23
+ import shutil
24
+ import sys
25
+ import time
26
+ import traceback
27
+ from http.server import BaseHTTPRequestHandler, HTTPServer
28
+ import signal
29
+ import textwrap
30
+
31
+ import numpy as np
32
+
33
+ from .. import tasks as task_pkg
34
+ from ..task_base import TASKS
35
+ from . import camera as C
36
+ from .context import PromptBuilder
37
+ from .tools import ACTION_TOOLS, WS_HI, WS_LO, ToolExecutor, _json_default
38
+
39
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
40
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
41
+
42
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
43
+
44
+ SHELL_TEMPLATE = r'''#!/bin/bash
45
+ # Run a shell command inside this workspace, in the episode jail (no network, host data hidden):
46
+ # ./shell '<command>' or ./shell <<'EOF' ... EOF (command read from stdin)
47
+ WS="$(cd "$(dirname "$0")" && pwd)"
48
+ if [ $# -gt 0 ]; then CMD="$*"; else CMD="$(cat)"; fi
49
+ exec unshare --user --map-root-user --mount --net -- /opt/lffjail/jail_inner.sh "$WS" timeout -k 5 60 bash -c "$CMD"
50
+ '''
51
+
52
+ CLI_TEMPLATE = r'''#!/usr/bin/env python3
53
+ """Robot command-line interface. Usage: ./robot <command> [key=value ...] (./robot help)"""
54
+ import json, sys, urllib.request
55
+ PORT = __PORT__
56
+ TOKEN = "__TOKEN__"
57
+ def main():
58
+ if len(sys.argv) < 2:
59
+ sys.argv.append("help")
60
+ cmd, args = sys.argv[1], {}
61
+ for a in sys.argv[2:]:
62
+ if "=" not in a:
63
+ print(f"bad argument {a!r}: use key=value"); sys.exit(2)
64
+ k, v = a.split("=", 1)
65
+ try:
66
+ args[k] = json.loads(v)
67
+ except ValueError:
68
+ args[k] = v
69
+ req = urllib.request.Request(f"http://127.0.0.1:{PORT}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(),
70
+ headers={"Content-Type": "application/json", "X-Token": TOKEN})
71
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
72
+ with opener.open(req, timeout=600) as r:
73
+ print(r.read().decode())
74
+ main()
75
+ '''
76
+
77
+
78
+ def strip_axes(text):
79
+ """v2: keep the robot-centric words of the F2 feedback ("to the robot's left", "forward") but drop the explicit
80
+ coordinate-axis labels ("(+y)", "+x, ", "+yaw"), so the feedback does not hand over the axis convention that the
81
+ v2 instructions deliberately leave out."""
82
+ import re
83
+ t = re.sub(r"\s?\((?:[+-]?[xyz]|[+-]yaw)\)", "", text) # " (+y)", " (x)", " (-yaw)"
84
+ t = re.sub(r"\(([+-][xyz]|[+-]yaw), ", "(", t) # "(+x, away from the robot)"
85
+ t = re.sub(r", [+-](?:[xyz]|yaw)\)", ")", t) # "(... robot's left, +yaw)"
86
+ t = re.sub(r"\s{2,}", " ", t)
87
+ return t
88
+
89
+
90
+ class VideoRec:
91
+ """Records agentview | wrist while the simulator steps (one frame every `every` control steps, played at
92
+ `fps`, i.e. sped up by every * fps / 20). A header shows the attempt, the current robot command and the
93
+ report of the previous one; gripper commands and attempt outcomes get short freeze frames."""
94
+
95
+ BAND = 56
96
+
97
+ def __init__(self, path, env, res=320, every=3, fps=20, title=""):
98
+ import imageio
99
+ from . import camera as _C
100
+ self.env, self.res, self.every, self.fps, self.title = env, res, every, fps, title
101
+ self.cams = [_C.mj_cam("agentview"), _C.mj_cam("wrist")]
102
+ self.w = imageio.get_writer(path, fps=fps, quality=7, macro_block_size=8)
103
+ self.n = 0
104
+ self.lines = ["", "", ""]
105
+ self.last = None
106
+ orig = env.step
107
+
108
+ def step(a):
109
+ out = orig(a)
110
+ self.n += 1
111
+ if self.w is not None and self.n % self.every == 0:
112
+ self.grab()
113
+ return out
114
+
115
+ env.step = step
116
+
117
+ def _font(self, size):
118
+ from PIL import ImageFont
119
+ try:
120
+ return ImageFont.load_default(size=size)
121
+ except TypeError:
122
+ return ImageFont.load_default()
123
+
124
+ def grab(self):
125
+ from PIL import Image, ImageDraw
126
+ from .. import envs as _E
127
+ img = np.concatenate([_E.render(self.env, c, self.res) for c in self.cams], axis=1)
128
+ im = Image.new("RGB", (2 * self.res, self.res + self.BAND), (0, 0, 0))
129
+ im.paste(Image.fromarray(img), (0, self.BAND))
130
+ d = ImageDraw.Draw(im)
131
+ hdr = [self.title] + self.lines[:2]
132
+ for i, s_ in enumerate(hdr):
133
+ d.text((5, 3 + 17 * i), s_[:120], fill=(255, 255, 255) if i else (255, 220, 120), font=self._font(13))
134
+ self.last = np.asarray(im)
135
+ self.w.append_data(self.last)
136
+
137
+ def hold(self, secs):
138
+ if self.w is None:
139
+ return
140
+ self.grab()
141
+ for _ in range(int(secs * self.fps)):
142
+ self.w.append_data(self.last)
143
+
144
+ def card(self, lines, secs=3.0, color=(20, 20, 20)):
145
+ if self.w is None:
146
+ return
147
+ from PIL import Image, ImageDraw
148
+ im = Image.new("RGB", (2 * self.res, self.res + self.BAND), color)
149
+ d = ImageDraw.Draw(im)
150
+ y = 14
151
+ for s_ in lines:
152
+ for part in textwrap.wrap(s_, 62) or [""]:
153
+ d.text((14, y), part, fill=(255, 255, 255), font=self._font(15))
154
+ y += 19
155
+ y += 5
156
+ fr = np.asarray(im)
157
+ for _ in range(int(secs * self.fps)):
158
+ self.w.append_data(fr)
159
+
160
+ def close(self):
161
+ if self.w is not None:
162
+ self.w.close()
163
+ self.w = None
164
+
165
+
166
+ def _short(rep):
167
+ keys = ("touched_object", "holding_object", "gripper_width_m", "eef_pos", "eef_yaw_deg", "error")
168
+ return ", ".join(f"{k}={rep[k]}" for k in keys if k in rep)
169
+
170
+
171
+ class RobotSession:
172
+ def __init__(self, a):
173
+ self.a = a
174
+ self.task = TASKS[a.task](cam_res=a.image_res)
175
+ if a.max_steps is None: # long procedural tasks declare a larger per-attempt budget
176
+ a.max_steps = int(getattr(self.task, "agent_max_steps", 40))
177
+ self.inst = self.task.sample_instance(a.seed)
178
+ if getattr(a, "nominal", False):
179
+ # control condition: same scene, hidden calibration error removed (L1 tasks only) -> plain pick-and-place
180
+ hidden = [k for k in ("bias", "yaw_bias") if k in self.inst]
181
+ if not hidden:
182
+ raise SystemExit(f"--nominal is not supported for {a.task} (no bias / yaw_bias in the instance)")
183
+ for k in [k for k in self.inst if "bias" in k]: # bias, bias_r, yaw_bias, yaw_bias_deg, ...
184
+ v = self.inst[k]
185
+ if isinstance(v, (list, tuple)):
186
+ self.inst[k] = [0.0] * len(v)
187
+ elif isinstance(v, (int, float)):
188
+ self.inst[k] = 0.0
189
+ self.inst["nominal"] = True
190
+ # full5 controlled arms (docs/14 §6): h0 / twin override the hidden variable, hplus states it in the instruction
191
+ self.arm, self.arm_overrides, self.reveal_text = getattr(a, "arm", "none") or "none", {}, ""
192
+ if self.arm in ("h0", "twin"):
193
+ from .. import arm_specs
194
+ self.arm_overrides = arm_specs.overrides(a.task, self.arm, self.inst)
195
+ self.inst.update(self.arm_overrides)
196
+ elif self.arm == "hplus":
197
+ from .. import arm_specs
198
+ self.reveal_text = arm_specs.reveal(a.task, self.inst).strip()
199
+ if a.style in ("v2", "la"): # same rule as the F2 feedback: no axis labels such as "(+y)"
200
+ self.reveal_text = strip_axes(self.reveal_text)
201
+ self.n_mon_events = 0 # regression snapshots: monitor events already inspected
202
+ self.protocol = getattr(self.task, "protocol", "cross")
203
+ self.k = a.k or self.task.max_attempts
204
+ # --hide-k (memory=full): README and status say 1 attempt, exactly like an independent k=1 run, and the other
205
+ # attempts are announced only after a failure, so attempt 1 sees the same thing as the independent run.
206
+ self.k_shown = 1 if getattr(a, "hide_k", False) and a.memory == "full" else self.k
207
+ assert self.k_shown == self.k or a.style in ("v2", "la"), "--hide-k needs --style v2 or la"
208
+ self.sandbox = os.path.abspath(a.sandbox)
209
+ self.obs_dir = os.path.join(self.sandbox, "obs")
210
+ self.log_dir = os.path.abspath(a.log_dir)
211
+ os.makedirs(self.obs_dir, exist_ok=True)
212
+ os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True)
213
+ self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a")
214
+ import secrets
215
+ self.token = secrets.token_hex(8)
216
+ self.n_actions = 0 # robot commands in the current attempt (step budget)
217
+ self.attempt = 1
218
+ self.step = 0
219
+ self.finished = False
220
+ self.waiting_new_agent = False
221
+ self.history = []
222
+ self.last_send = None
223
+ cam_axes = {c: C.describe_axes(self.task.env, c, a.image_res) for c in C.CAMERAS}
224
+ names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
225
+ memory = "none" if a.memory == "none" else "full"
226
+ self.pb = PromptBuilder(self.task, self.protocol, self.k, memory, a.feedback, a.image_res, cam_axes,
227
+ object_names=names, cams=("agentview", "wrist"), depth_tool=a.perception == "depth")
228
+ self.video = None
229
+ if a.video:
230
+ self.video = VideoRec(a.video, self.task.env, every=a.video_every, fps=a.video_fps,
231
+ title=f"{a.task} seed={a.seed} perception={a.perception} (sped up x{a.video_every * a.video_fps // 20})")
232
+ self.video.card([f"Task: {a.task} seed {a.seed} memory={a.memory} feedback={a.feedback} k={self.k}",
233
+ "Instruction: " + self.instruction(),
234
+ "Left: agentview Right: wrist camera. Header: current robot command and the report of "
235
+ "the previous one."], 3)
236
+ self._start_attempt(reset=True)
237
+ # la: agent-facing positions are in the robot-base frame (LIBERO-Agent: "Coordinates are expressed in the
238
+ # robot-base frame and measured in metres"); the LIBERO base is axis-aligned with the world, so a translation
239
+ self.base_off = np.zeros(3)
240
+ if a.style == "la":
241
+ sim = self.task.env.sim
242
+ bid = sim.model.body_name2id("robot0_base")
243
+ assert np.allclose(sim.data.body_xmat[bid].reshape(3, 3), np.eye(3), atol=1e-6), "robot base is rotated"
244
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
245
+ self._write_sandbox()
246
+ self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol,
247
+ memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception,
248
+ inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm,
249
+ arm_overrides=self.arm_overrides, reveal=self.reveal_text, dossier=getattr(a, "dossier", "") or ""))
250
+
251
+ # ------------------------------------------------------------------ helpers
252
+ def log(self, d):
253
+ d["t"] = time.time()
254
+ self.events.write(json.dumps(d, default=_json_default) + "\n")
255
+ self.events.flush()
256
+
257
+ def instruction(self):
258
+ hook = getattr(self.task, "agent_instruction", None)
259
+ if hook is not None:
260
+ text = hook(self.inst, self.a.instruction)
261
+ elif self.a.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""):
262
+ text = self.task.instruction_indirect
263
+ else:
264
+ text = self.task.instruction
265
+ return text + (" " + self.reveal_text if getattr(self, "reveal_text", "") else "")
266
+
267
+ def feedback_text(self, out):
268
+ import inspect
269
+ fn = self.task.feedback
270
+ if "indirect" in inspect.signature(fn).parameters:
271
+ fb = fn(self.inst, out, self.a.feedback, indirect=self.a.instruction == "indirect")
272
+ else:
273
+ fb = fn(self.inst, out, self.a.feedback)
274
+ return strip_axes(fb) if self.a.style in ("v2", "la") else fb
275
+
276
+ def _start_attempt(self, reset):
277
+ self.n_actions = 0
278
+ if reset:
279
+ self.task.reset_instance(self.inst)
280
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.a.image_res, cams=("agentview", "wrist"))
281
+ self.step = 0
282
+ self.sim0 = self.task.sk.n_steps # v2: simulated-time budget is counted per attempt
283
+
284
+ def _save_obs(self, tag):
285
+ """Same bytes as the GPT harness sends (JPEG q90). Under memory=none the file names carry no
286
+ attempt number, so a fresh agent cannot tell it is a retry; --hide-k names attempt 1 the same way."""
287
+ from PIL import Image
288
+ paths = []
289
+ for ref in self.ex.observe(label=tag):
290
+ name = (f"s{self.step:03d}_{ref.camera}.jpg" if self.a.memory == "none" or (self.k_shown < self.k and self.attempt == 1)
291
+ else f"a{self.attempt}_s{self.step:03d}_{ref.camera}.jpg")
292
+ Image.fromarray(ref.array).save(os.path.join(self.obs_dir, name), quality=90)
293
+ shutil.copy(os.path.join(self.obs_dir, name), os.path.join(self.log_dir, "images", f"a{self.attempt}_{name}"))
294
+ paths.append(f"obs/{name}")
295
+ if self.a.style == "la":
296
+ self.last_files = self._write_la_files(f"a{self.attempt}_s{self.step:03d}")
297
+ return paths
298
+
299
+ def readme(self):
300
+ if self.a.style == "la":
301
+ return self.readme_la()
302
+ if self.a.style == "v2":
303
+ return self.readme_v2()
304
+ sp = self.pb.system_prompt()
305
+ sp = sp.replace("You act only by calling the provided tools, exactly one tool call per turn. Every action tool "
306
+ "returns an execution report; after each action you also receive new camera images and the "
307
+ "robot's proprioceptive state.",
308
+ "You act only through the `./robot` command in this directory (one robot command at a time). "
309
+ "Every action command prints an execution report and the paths of new camera images taken "
310
+ "after the action; look at them with your file-reading tool.")
311
+ sp = sp.replace("Finish by calling done(reason)", "Finish by running `./robot done reason=\"...\"`")
312
+ sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the "
313
+ "actions you executed and outcome feedback).",
314
+ "Each attempt ends when you run `./robot done`; that command prints the outcome feedback (if any) "
315
+ "and the images of the reset scene for the next attempt.")
316
+ sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the "
317
+ "actions you executed).",
318
+ "Each attempt ends when you run `./robot done`; that command prints the images of the reset "
319
+ "scene for the next attempt.")
320
+ sp = sp.replace("before your first tool call", "before your first robot command")
321
+ tools = "\n".join([
322
+ " ./robot help this text",
323
+ " ./robot status task, current images and proprioception",
324
+ " ./robot observe take new images (agentview + wrist) + proprioception",
325
+ " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)",
326
+ " ./robot open_gripper | ./robot close_gripper",
327
+ " ./robot pixel_to_world camera=agentview|wrist u=.. v=.. (pixel -> 3-D point via depth)",
328
+ " ./robot done reason=\"...\" end the attempt / segment",
329
+ ] if self.a.perception == "depth" else [
330
+ " ./robot help this text",
331
+ " ./robot status task, current images and proprioception",
332
+ " ./robot observe take new images (agentview + wrist) + proprioception",
333
+ " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)",
334
+ " ./robot open_gripper | ./robot close_gripper",
335
+ " ./robot done reason=\"...\" end the attempt / segment",
336
+ ])
337
+ return ("# Robot task\n\n" + sp + "\n\n## Commands\n" + tools +
338
+ "\n\nArguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.\n"
339
+ "Images are written to obs/ inside this directory. After every action, look at the new images "
340
+ "before deciding on the next command.\n"
341
+ f"Each attempt allows at most {self.a.max_steps} robot commands (help/status not counted); after that "
342
+ "the attempt ends automatically.\n\n## TASK\n" + self.instruction() + "\n")
343
+
344
+ def _write_sandbox(self):
345
+ os.makedirs(self.sandbox, exist_ok=True)
346
+ if self.a.style == "la":
347
+ with open(os.path.join(self.log_dir, "agent_iface.json"), "w") as f:
348
+ json.dump(dict(token=self.token, port=self.a.port, workspace=self.sandbox, agent_iface=self.a.agent_iface,
349
+ max_tool_calls=self.a.max_tool_calls, perception=self.a.perception), f)
350
+ with open(os.path.join(self.sandbox, "README.md"), "w") as f:
351
+ f.write(self.readme())
352
+ if getattr(self.a, "dossier", ""):
353
+ shutil.copytree(self.a.dossier, os.path.join(self.sandbox, "history"))
354
+ if self.a.agent_iface == "cli": # coding-agent harness (Claude Code): ./robot + ./shell in the workspace
355
+ for name, body in (("robot", CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)),
356
+ ("shell", SHELL_TEMPLATE)):
357
+ with open(os.path.join(self.sandbox, name), "w") as f:
358
+ f.write(body)
359
+ os.chmod(os.path.join(self.sandbox, name), 0o755)
360
+ return
361
+ cli = os.path.join(self.sandbox, "robot")
362
+ with open(cli, "w") as f:
363
+ f.write(CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token))
364
+ os.chmod(cli, 0o755)
365
+ with open(os.path.join(self.sandbox, "README.md"), "w") as f:
366
+ f.write(self.readme())
367
+
368
+ def status(self):
369
+ if self.a.memory == "none":
370
+ return dict(task=self.instruction(), finished=self.finished)
371
+ st = dict(task=self.instruction(), protocol=self.protocol, attempt=self.attempt, max_attempts=self.k,
372
+ finished=self.finished)
373
+ if self.waiting_new_agent:
374
+ st["note"] = "The previous agent finished its attempt. A new attempt is ready; the scene has been reset."
375
+ return st
376
+
377
+ # ------------------------------------------------------------------ dispatch
378
+ def handle(self, cmd, args):
379
+ if self.a.style in ("v2", "la"):
380
+ return self.handle_v2(cmd, args)
381
+ if cmd == "help":
382
+ return dict(text=self.readme())
383
+ if cmd == "status":
384
+ st = self.status()
385
+ st["images"] = self._save_obs("status")
386
+ st.update(self.ex.proprio())
387
+ self.waiting_new_agent = False
388
+ return st
389
+ if self.finished:
390
+ return dict(ok=False, error="The episode is over. Stop now.")
391
+ if self.waiting_new_agent:
392
+ return dict(ok=False, error="This attempt has ended. Stop now.")
393
+ if cmd in ("observe", "pixel_to_world", "move_to", "open_gripper", "close_gripper", "push"):
394
+ self.n_actions += 1
395
+ if self.n_actions > self.a.max_steps:
396
+ rep = self._done("step budget exhausted (automatic)")
397
+ rep["note"] = f"The step budget of {self.a.max_steps} commands for this attempt was used up."
398
+ return rep
399
+ if cmd == "observe":
400
+ self.step += 1
401
+ rep = dict(ok=True, images=self._save_obs("observe"))
402
+ rep.update(self.ex.proprio())
403
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
404
+ return rep
405
+ if cmd == "done":
406
+ return self._done(args.get("reason", ""))
407
+ allowed = tuple(t for t in ACTION_TOOLS if t != "push" or self.a.allow_push)
408
+ if self.a.perception == "depth":
409
+ allowed += ("pixel_to_world",)
410
+ if cmd not in allowed:
411
+ return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help")
412
+ self.step += 1
413
+ if self.video is not None:
414
+ argtxt = " ".join(f"{k}={v}" for k, v in args.items())
415
+ self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}"
416
+ res = self.ex.call(cmd, args)
417
+ rep = dict(res.report)
418
+ if self.video is not None:
419
+ self.video.lines[1] = f" -> {_short(rep)}"
420
+ if cmd in ("close_gripper", "open_gripper"):
421
+ self.video.hold(1.2)
422
+ if res.ok and cmd in ACTION_TOOLS:
423
+ rep["images"] = self._save_obs(cmd)
424
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep,
425
+ wall_s=res.wall_s, sim_steps=res.sim_steps))
426
+ return rep
427
+
428
+ def _done(self, reason):
429
+ out = self.task.outcome(self.inst)
430
+ succ = bool(out["success"])
431
+ fb = self.feedback_text(out)
432
+ self.history.append(dict(attempt=self.attempt, success=succ, feedback=fb, reason=reason))
433
+ self.log(dict(ev="done", attempt=self.attempt, step=self.step, reason=reason, success=succ, feedback=fb,
434
+ outcome={k: v for k, v in out.items() if k != "feedback"}))
435
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
436
+ if self.video is not None:
437
+ self.video.lines = [f"attempt {self.attempt}/{self.k}: done", f" reason: {reason}", ""]
438
+ self.video.hold(1.0)
439
+ self.video.card([f"Attempt {self.attempt}: {'SUCCESS' if succ else 'FAILED'}",
440
+ f"Commands used in this attempt: {self.n_actions}", "Agent's reason: " + str(reason)[:300],
441
+ "Feedback: " + (fb if self.a.memory != "none" and self.a.feedback != "F0" else "(not shown)")],
442
+ 3.5, (20, 50, 20) if succ else (60, 20, 20))
443
+ if last:
444
+ self.video.close()
445
+ else:
446
+ self.video.lines = ["", "", ""]
447
+ if self.a.memory == "none":
448
+ # independent attempts: no feedback to the agent; orchestrator starts a fresh agent
449
+ if last:
450
+ self.finished = True
451
+ else:
452
+ self.attempt += 1
453
+ self._start_attempt(reset=self.protocol == "cross")
454
+ self.waiting_new_agent = True
455
+ return dict(ok=True, ended=True, message="Attempt recorded. Stop now and report what you did.")
456
+ rep = dict(ok=True, ended=True)
457
+ if self.a.feedback != "F0":
458
+ rep["feedback"] = fb
459
+ if last and (succ or self.a.feedback != "F0"):
460
+ self.finished = True
461
+ rep["message"] = "The episode is over. Stop now and report."
462
+ return rep
463
+ if self.attempt >= self.k or out.get("terminal"):
464
+ self.finished = True
465
+ rep["message"] = ("The failure cannot be undone, so the episode is over. Stop now and report."
466
+ if out.get("terminal") else "No attempts left. The episode is over. Stop now and report.")
467
+ return rep
468
+ self.attempt += 1
469
+ reveal = ""
470
+ if self.k_shown < self.k: # --hide-k: first failure, announce the extra attempts now
471
+ self.k_shown = self.k
472
+ reveal = f"You get more attempts than README.md says: up to {self.k} in total. "
473
+ if self.protocol == "cross":
474
+ self._start_attempt(reset=True)
475
+ rep["message"] = reveal + (f"Attempt {self.attempt} of {self.k} starts now. The scene has been reset to exactly the "
476
+ f"same initial state.")
477
+ else:
478
+ self._start_attempt(reset=False)
479
+ rep["message"] = reveal + (f"Continue from the current state (segment {self.attempt}; you may call done at most "
480
+ f"{self.k} times in total).")
481
+ self.step += 1
482
+ rep["images"] = self._save_obs("attempt_start")
483
+ rep.update(self._la_files())
484
+ if self.a.style in ("v2", "la"):
485
+ rep.update(self._state_v2())
486
+ else:
487
+ rep.update(self.ex.proprio())
488
+ return rep
489
+
490
+
491
+ V2_DROP = ("holding", "touched", "events", "sim_time_s", "tool", "reached", "yaw_used_deg", "target_clipped_to")
492
+
493
+
494
+ class _V2:
495
+ """Interface v2 (2026-10-07, aligned with LIBERO-Agent / RoboDojo-L3 at the user's request):
496
+ - priors: only the task instruction, the attempt rules, the budgets and the command definitions (no axes,
497
+ table height, camera orientation or robot geometry);
498
+ - observations: two RGB images published as files after every command + end-effector state (position,
499
+ yaw, gripper width) + how far the arm stopped from the commanded target + budget left; no
500
+ held/touched flags and no per-step task events;
501
+ - action: move_eef = absolute target (omitted coordinates keep their value; gripper after the motion;
502
+ optional speed); unreachable targets are rejected and the arm does not move;
503
+ - an attempt ends with `finish` (alias `done`) or when a budget runs out; the environment judges it."""
504
+
505
+
506
+ def _readme_v2(self):
507
+ sec = self.sim_budget()
508
+ proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the "
509
+ f"same initial state." if self.protocol == "cross" else
510
+ f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a "
511
+ f"failed attempt you continue from the current state.")
512
+ return "\n".join([
513
+ "# Robot task", "",
514
+ "You control a robot arm with a two-finger gripper in a physics simulation, only through the `./robot` "
515
+ "command in this directory (one command at a time).", "",
516
+ "## Task", self.instruction(), "",
517
+ "## Attempts", proto + " An attempt ends when you run `./robot finish reason=\"...\"` or when its budget "
518
+ "is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the last "
519
+ "attempt.", "",
520
+ "## Budget (per attempt)",
521
+ f"- at most {self.a.max_steps} robot commands (status and help are free);",
522
+ f"- at most {sec:.0f} s of simulated robot motion.",
523
+ "Every reply shows what is left.", "",
524
+ "## Observations",
525
+ "Every command writes two new camera images into obs/ and prints their paths: 'agentview' (a fixed camera "
526
+ "looking at the table) and 'wrist' (a camera on the gripper). It also reports the end-effector state: "
527
+ "eef_pos = [x, y, z] of the gripper's grasp point in metres, eef_yaw_deg = rotation of the gripper about "
528
+ "the vertical axis in degrees, gripper_width_m = opening of the fingers in metres, and after a motion how "
529
+ "far the gripper stopped from your target.", "",
530
+ "## Commands",
531
+ " ./robot status task, attempt, budget, current state and images",
532
+ " ./robot observe new images and state without moving",
533
+ " ./robot move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]",
534
+ " move the grasp point to an absolute target in the same frame as eef_pos (metres; yaw in degrees);",
535
+ " omitted coordinates keep their current value; the gripper command is executed after the motion;",
536
+ " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.",
537
+ " ./robot finish reason=\"...\" end the current attempt",
538
+ "",
539
+ "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""])
540
+
541
+
542
+ def _sim_budget(self):
543
+ return 3.0 * self.a.max_steps # seconds of simulated motion per attempt
544
+
545
+
546
+ def _budget_left(self):
547
+ used = (self.task.sk.n_steps - self.sim0) * 0.05
548
+ return dict(commands=max(self.a.max_steps - self.n_actions, 0), sim_seconds=round(max(self.sim_budget() - used, 0.0), 1))
549
+
550
+
551
+ def _state_v2(self):
552
+ p = self.ex.proprio()
553
+ pos = p["eef_pos"]
554
+ if self.a.style == "la":
555
+ pos = [round(float(v), 4) for v in np.asarray(pos, float) - self.base_off]
556
+ st = dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
557
+ if self.a.style == "la": # read-only joint angles, as LIBERO-Agent (all levels) and RoboDojo give them
558
+ st["joint_pos_rad"] = [round(float(v), 4) for v in self._believed_joints()]
559
+ st["budget_left"] = self._budget_left()
560
+ return st
561
+
562
+
563
+ def _clean_v2(rep):
564
+ return {k: v for k, v in rep.items() if not k.startswith(V2_DROP)}
565
+
566
+
567
+ def _handle_v2(self, cmd, args):
568
+ if cmd == "help":
569
+ return dict(text=self.readme())
570
+ if cmd == "status":
571
+ st = dict(task=self.instruction(), attempt=self.attempt, max_attempts=self.k_shown, finished=self.finished)
572
+ st["images"] = self._save_obs("status")
573
+ st.update(self._la_files())
574
+ st.update(self._state_v2())
575
+ return st
576
+ if self.finished:
577
+ return dict(ok=False, error="The episode is over. Stop now.")
578
+ if cmd in ("finish", "done"):
579
+ return self._done(args.get("reason", ""))
580
+ if cmd not in ("observe", "move_eef"):
581
+ return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help")
582
+ self.n_actions += 1
583
+ if self.n_actions > self.a.max_steps:
584
+ rep = self._done("command budget used up (automatic)")
585
+ rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up."
586
+ return rep
587
+ self.step += 1
588
+ if cmd == "observe":
589
+ rep = dict(ok=True, images=self._save_obs("observe"))
590
+ rep.update(self._la_files())
591
+ rep.update(self._state_v2())
592
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
593
+ return rep
594
+ # ---------------- move_eef
595
+ p = self.ex.proprio()
596
+ unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}
597
+ if unknown:
598
+ rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed")
599
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
600
+ return rep
601
+ off = self.base_off # zero except la (robot-base frame)
602
+ try:
603
+ cur = np.asarray(p["eef_pos"], float) - off
604
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
605
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
606
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
607
+ except (TypeError, ValueError):
608
+ rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers")
609
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
610
+ return rep
611
+ grip = args.get("gripper")
612
+ if grip not in (None, "open", "close"):
613
+ rep = dict(ok=False, error="gripper must be open or close")
614
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
615
+ return rep
616
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
617
+ tgt_w = np.asarray(tgt) + off # simulator (world) frame
618
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
619
+ rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move")
620
+ rep.update(self._state_v2())
621
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
622
+ return rep
623
+ if self.video is not None:
624
+ argtxt = " ".join(f"{k}={v}" for k, v in args.items())
625
+ self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}"
626
+ left = self._budget_left()["sim_seconds"]
627
+ raw = {}
628
+ if moving:
629
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
630
+ if speed is not None:
631
+ mv["speed"] = speed
632
+ res = self.ex.call("move_to", mv)
633
+ raw.update(res.report)
634
+ if grip is not None:
635
+ res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {})
636
+ raw.update(res.report)
637
+ rep = dict(ok=bool(raw.get("ok", True)))
638
+ if raw.get("error"):
639
+ rep["error"] = raw["error"]
640
+ rep.update(self._state_v2())
641
+ if moving:
642
+ err = np.asarray(tgt) - np.asarray(rep["eef_pos"])
643
+ dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0
644
+ rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1))
645
+ if self.video is not None:
646
+ self.video.lines[1] = f" -> eef={rep['eef_pos']} width={rep['gripper_width_m']} {rep.get('stopped_from_target', '')}"
647
+ if grip is not None:
648
+ self.video.hold(1.2)
649
+ rep["images"] = self._save_obs(cmd)
650
+ rep.update(self._la_files())
651
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw))
652
+ self._snap_regressions()
653
+ if rep["budget_left"]["sim_seconds"] <= 0 and left > 0:
654
+ fin = self._done("motion budget used up (automatic)")
655
+ fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up."
656
+ rep["attempt_ended"] = fin
657
+ return rep
658
+
659
+
660
+ LOSS_EVENTS = ("lost", "toppled", "tipped", "load_fell", "load_displaced")
661
+
662
+
663
+ def _snap_regressions(self):
664
+ """Save the simulator state right after a command during which the task monitor registered a loss of earlier
665
+ progress (lost / toppled / tipped / load_fell ...), for the "self-inflicted vs handed-over" experiment (docs/14 §6).
666
+ Server-side only: snapshots go to <log>/snapshots/, never to the agent's workspace."""
667
+ try: # bookkeeping only: it must never change what the agent gets back
668
+ self._snap_regressions_inner()
669
+ except Exception:
670
+ self.log(dict(ev="snapshot_error", error=traceback.format_exc()[-1500:]))
671
+
672
+
673
+ def _snap_regressions_inner(self):
674
+ mon = getattr(self.task, "mon", None)
675
+ evs = mon.get("events") if isinstance(mon, dict) else None
676
+ if not isinstance(evs, list):
677
+ return
678
+ new = evs[self.n_mon_events:]
679
+ self.n_mon_events = len(evs)
680
+ loss = [e for e in new if isinstance(e, dict) and str(e.get("ev", e.get("event", ""))) in LOSS_EVENTS]
681
+ if not loss:
682
+ return
683
+ import copy
684
+ d = os.path.join(self.log_dir, "snapshots")
685
+ os.makedirs(d, exist_ok=True)
686
+ name = f"a{self.attempt}_s{self.step:03d}"
687
+ try:
688
+ flat = np.asarray(self.task.env.sim.get_state().flatten(), float)
689
+ except Exception: # keep the run going even if a simulator binding lacks get_state
690
+ flat = np.concatenate([self.task.env.sim.data.qpos, self.task.env.sim.data.qvel]).astype(float)
691
+ np.save(os.path.join(d, name + "_sim.npy"), flat)
692
+ meta = dict(attempt=self.attempt, step=self.step, n_actions=self.n_actions, sim_steps=int(self.task.sk.n_steps - self.sim0),
693
+ loss_events=loss, mon=copy.deepcopy(mon))
694
+ def _dflt(o): # task monitors keep sets (ever / lost / lid_hits ...)
695
+ return sorted(o, key=str) if isinstance(o, (set, frozenset)) else _json_default(o)
696
+ with open(os.path.join(d, name + "_meta.json"), "w") as f:
697
+ json.dump(meta, f, default=_dflt)
698
+ self.log(dict(ev="regression_snapshot", attempt=self.attempt, step=self.step, file=f"snapshots/{name}", n_loss=len(loss)))
699
+
700
+
701
+ def _la_files(self):
702
+ """la: paths of the non-image observation files written with the last images (empty for other styles)."""
703
+ return dict(self.last_files) if self.a.style == "la" and getattr(self, "last_files", None) else {}
704
+
705
+
706
+ def _believed_pose(self):
707
+ """4x4 pose of the grasp point as the ROBOT believes it (the frame of eef_pos / move_eef): the true pose shifted by
708
+ the task's hidden calibration errors (Skills.bias, and YawSkills.yaw_bias about the vertical axis). A real robot
709
+ computes its wrist-camera pose from its own (miscalibrated) kinematics, so the wrist calibration uses this pose."""
710
+ sk = self.task.sk
711
+ beta = float(getattr(sk, "yaw_bias", 0.0))
712
+ c, s_ = np.cos(-beta), np.sin(-beta)
713
+ Rz = np.array([[c, -s_, 0.0], [s_, c, 0.0], [0.0, 0.0, 1.0]])
714
+ T_true = np.eye(4)
715
+ T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos()
716
+ T_b = np.eye(4)
717
+ T_b[:3, :3], T_b[:3, 3] = Rz @ sk.eef_mat(), sk.eef_pos() - np.asarray(sk.bias, float)
718
+ return T_b, T_true
719
+
720
+
721
+ def _believed_joints(self, iters=30):
722
+ """The 7 arm joint angles as the robot's encoders report them. For tasks with a hidden calibration error (L1) these
723
+ are the angles consistent with the robot's own belief: standard forward kinematics of them gives exactly the
724
+ reported (believed) grasp pose, as on a real arm whose encoder offsets are miscalibrated; true joint angles would
725
+ hand the hidden error to anyone who runs the public Franka kinematics. Without a calibration error they are the true
726
+ angles. Solved by damped least squares on a scratch copy of the simulator state (2-3 iterations)."""
727
+ import mujoco
728
+ env, sk = self.task.env, self.task.sk
729
+ rob = env.robots[0]
730
+ idx, dof, site = np.array(rob._ref_joint_pos_indexes), np.array(rob._ref_joint_vel_indexes), rob.eef_site_id
731
+ m, d0 = env.sim.model._model, env.sim.data._data
732
+ T_b, _ = self._believed_pose()
733
+ if np.allclose(T_b[:3, 3], d0.site_xpos[site]) and np.allclose(T_b[:3, :3], d0.site_xmat[site].reshape(3, 3)):
734
+ return d0.qpos[idx].copy()
735
+ d = mujoco.MjData(m)
736
+ d.qpos[:] = d0.qpos
737
+ jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv))
738
+ for _ in range(iters):
739
+ mujoco.mj_kinematics(m, d)
740
+ mujoco.mj_comPos(m, d)
741
+ ep = T_b[:3, 3] - d.site_xpos[site]
742
+ Re = T_b[:3, :3] @ d.site_xmat[site].reshape(3, 3).T
743
+ er = 0.5 * np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
744
+ if np.linalg.norm(ep) < 1e-7 and np.linalg.norm(er) < 1e-7:
745
+ break
746
+ mujoco.mj_jacSite(m, d, jp, jr, site)
747
+ J = np.vstack([jp[:, dof], jr[:, dof]])
748
+ d.qpos[idx] += J.T @ np.linalg.solve(J @ J.T + 1e-6 * np.eye(6), np.concatenate([ep, er]))
749
+ return d.qpos[idx].copy()
750
+
751
+
752
+ def _write_la_files(self, prefix):
753
+ """la observation files besides the two JPEGs: <prefix>_state.json always; with --perception rgbd also metric
754
+ depth for both cameras (<prefix>_<cam>_depth.npy, float32 metres along the optical axis, same upright pixels as
755
+ the JPEG) and <prefix>_camera.json (K and cam_to_world in the eef_pos frame, OpenCV camera axes).
756
+ The fixed agentview camera is calibrated in the true frame; the wrist camera pose is computed from the robot's
757
+ believed gripper pose (so neither file reveals the hidden calibration error of the L1 tasks)."""
758
+ out = {}
759
+ st = self._state_v2()
760
+ st = dict(eef_pos=st["eef_pos"], eef_yaw_deg=st["eef_yaw_deg"], gripper_width_m=st["gripper_width_m"],
761
+ joint_pos_rad=st["joint_pos_rad"], attempt=self.attempt, step=self.step)
762
+ with open(os.path.join(self.obs_dir, f"{prefix}_state.json"), "w") as f:
763
+ json.dump(st, f, default=_json_default)
764
+ out["state_file"] = f"obs/{prefix}_state.json"
765
+ if self.a.perception == "rgbd":
766
+ res = self.a.image_res
767
+ cams, depth_files = {}, []
768
+ T_b, T_true = self._believed_pose()
769
+ for cam in ("agentview", "wrist"):
770
+ d = C.render_depth(self.task.env, cam, res).astype(np.float32)
771
+ np.save(os.path.join(self.obs_dir, f"{prefix}_{cam}_depth.npy"), d)
772
+ depth_files.append(f"obs/{prefix}_{cam}_depth.npy")
773
+ E = C.cam_to_world(self.task.env, cam)
774
+ if cam == "wrist":
775
+ E = T_b @ np.linalg.inv(T_true) @ E
776
+ E = E.copy()
777
+ E[:3, 3] -= self.base_off # robot-base frame
778
+ cams[cam] = dict(K=np.round(C.intrinsics(self.task.env, cam, res), 6).tolist(),
779
+ cam_to_base=np.round(E, 6).tolist(), width=res, height=res)
780
+ with open(os.path.join(self.obs_dir, f"{prefix}_camera.json"), "w") as f:
781
+ json.dump(cams, f)
782
+ out["depth_files"] = depth_files
783
+ out["camera_file"] = f"obs/{prefix}_camera.json"
784
+ return out
785
+
786
+
787
+
788
+ def _fb_sentence(level):
789
+ """README sentence for the feedback level. F1 (default since 2026-10-08): success / failure only, like
790
+ LIBERO-Agent's finish_episode outcome; F2 (measured error, e.g. "2.5 cm past the centre") is privileged
791
+ simulator information that neither LIBERO-Agent nor RoboDojo gives, kept only as an ablation."""
792
+ return {"F0": "The environment then checks the result.",
793
+ "F1": "The environment then checks the result and tells you only whether the attempt succeeded.",
794
+ "F2": "The environment then checks the result and tells you whether the attempt succeeded and, if not, "
795
+ "what went wrong."}[level]
796
+
797
+ def _readme_la(self):
798
+ """LIBERO-Agent-style instructions: the agent works in an episode workspace (observations are files, it can run
799
+ programs on them); the robot itself is driven only through the harness's `robot` tool."""
800
+ sec = self.sim_budget()
801
+ rgbd = self.a.perception == "rgbd"
802
+ cli = self.a.agent_iface == "cli"
803
+ pre = "./robot " if cli else ""
804
+ proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the "
805
+ f"same initial state." if self.protocol == "cross" else
806
+ f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a "
807
+ f"failed attempt you continue from the current state.")
808
+ files = [
809
+ "- obs/a<attempt>_s<step>_agentview.jpg and obs/a<attempt>_s<step>_wrist.jpg: 512x512 RGB images from "
810
+ "'agentview' (a fixed camera looking at the table) and 'wrist' (a camera on the gripper);",
811
+ "- obs/a<attempt>_s<step>_state.json: the end-effector state: eef_pos = [x, y, z] of the gripper's grasp "
812
+ "point (midway between the two fingers, about 1 cm above the fingertips), eef_yaw_deg = rotation of the gripper about the vertical axis in degrees, gripper_width_m = opening "
813
+ "of the fingers in metres, joint_pos_rad = the 7 arm joint angles (radians, base to wrist; read-only).",
814
+ ]
815
+ if rgbd:
816
+ files += [
817
+ "- obs/a<attempt>_s<step>_agentview_depth.npy and obs/a<attempt>_s<step>_wrist_depth.npy: metric depth "
818
+ "(numpy float32 array, 512x512, metres along each camera's optical axis), pixel-aligned with the images "
819
+ "(row 0 = top of the image);",
820
+ "- obs/a<attempt>_s<step>_camera.json: for each camera, K (3x3 intrinsics of the 512x512 image) and "
821
+ "cam_to_base (4x4 pose of the camera in the robot-base frame; camera axes: x right, y down, z forward).",
822
+ ]
823
+ return "\n".join([
824
+ "# Robot task", "",
825
+ "You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics "
826
+ "simulation.", "",
827
+ "## Task", self.instruction(), "",
828
+ "## Attempts", proto + f" An attempt ends when you run the robot command `{pre}finish reason=\"...\"` or when its "
829
+ "budget is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the "
830
+ "last attempt.", "",
831
+ *(["## Earlier attempt",
832
+ "Before this episode, an earlier attempt at this task, starting from a scene that looked the same as yours, "
833
+ "failed. Its record is in history/: history/README.md lists every robot command of that attempt with the "
834
+ "robot's reply and its closing remark, and history/obs/ holds the camera images it produced.", ""]
835
+ if getattr(self.a, "dossier", "") else []),
836
+ "## Budget (per attempt)",
837
+ f"- at most {self.a.max_steps} robot commands (status and help are free);",
838
+ f"- at most {sec:.0f} s of simulated robot motion;",
839
+ *([] if cli else [f"- at most {self.a.max_tool_calls} tool calls in total (robot, shell and view_image together)."]),
840
+ "Every robot reply shows the robot budgets that are left.", "",
841
+ "## Coordinates",
842
+ "Coordinates are expressed in the robot-base frame and measured in metres; angles are in degrees.", "",
843
+ "## Workspace and observations",
844
+ "This directory is your workspace for the whole episode. Every robot command writes its observation into "
845
+ "obs/ and prints the paths of the new files:",
846
+ *files,
847
+ "Robot replies also include the end-effector state and, after a motion, how far the gripper stopped from your "
848
+ "target. " + ("You can look at any image with your file-reading tool, run shell commands and programs in this "
849
+ "workspace with `./shell '<command>'` (python3 with numpy, scipy, Pillow and OpenCV; no network; "
850
+ "programs cannot control the robot), and keep your own files and notes in this directory; they "
851
+ "persist across attempts." if cli else
852
+ "You can look at any image with view_image, run shell commands and programs here (python3 with "
853
+ "numpy, scipy, Pillow and OpenCV; no network; programs cannot control the robot), and keep your "
854
+ "own files and notes in this directory; they persist across attempts."), "",
855
+ "## Robot commands " + ("(run from this directory as `./robot <command>`, one command at a time)" if cli
856
+ else "(argument of the `robot` tool)"),
857
+ f" {pre}status task, attempt, budget, current state and observation files",
858
+ f" {pre}observe new observation without moving",
859
+ f" {pre}move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]",
860
+ " move the grasp point to an absolute target (robot-base frame, metres; yaw in degrees);",
861
+ " omitted coordinates keep their current value; the gripper command is executed after the motion;",
862
+ " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.",
863
+ f" {pre}finish reason=\"...\" end the current attempt",
864
+ "",
865
+ "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""])
866
+
867
+
868
+ for _n, _f in (("_believed_joints", _believed_joints), ("readme_la", _readme_la), ("_la_files", _la_files), ("_believed_pose", _believed_pose),
869
+ ("_write_la_files", _write_la_files), ("readme_v2", _readme_v2), ("sim_budget", _sim_budget), ("_budget_left", _budget_left),
870
+ ("_state_v2", _state_v2), ("handle_v2", _handle_v2), ("_snap_regressions", _snap_regressions),
871
+ ("_snap_regressions_inner", _snap_regressions_inner)):
872
+ setattr(RobotSession, _n, _f)
873
+ RobotSession._clean_v2 = staticmethod(_clean_v2)
874
+
875
+
876
+ def serve(a):
877
+ sess = RobotSession(a)
878
+
879
+ class H(BaseHTTPRequestHandler):
880
+ def log_message(self, *x):
881
+ pass
882
+
883
+ def do_POST(self):
884
+ t_recv = time.time()
885
+ cmd = ""
886
+ try:
887
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
888
+ cmd = body.get("cmd", "")
889
+ if self.headers.get("X-Token") != sess.token:
890
+ rep = dict(ok=False, error="unauthorised")
891
+ else:
892
+ rep = sess.handle(cmd, body.get("args", {}) or {})
893
+ except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent
894
+ sess.log(dict(ev="error", error=traceback.format_exc()))
895
+ rep = dict(ok=False, error=f"internal error: {type(e).__name__}")
896
+ data = json.dumps(rep, default=_json_default, indent=None).encode()
897
+ if "text" in rep:
898
+ data = rep["text"].encode()
899
+ self.send_response(200)
900
+ self.send_header("Content-Type", "application/json")
901
+ self.end_headers()
902
+ self.wfile.write(data)
903
+ t_send = time.time()
904
+ # think time = gap between the previous reply and this request (model inference + its own tool overhead)
905
+ sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send,
906
+ server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None))
907
+ sess.last_send = t_send
908
+
909
+ def _term(*_):
910
+ if sess.video is not None:
911
+ sess.video.close()
912
+ os._exit(0)
913
+
914
+ signal.signal(signal.SIGTERM, _term)
915
+ srv = HTTPServer(("127.0.0.1", a.port), H)
916
+ print(f"robot server ready on 127.0.0.1:{a.port} sandbox={sess.sandbox} log={sess.log_dir}", flush=True)
917
+ with open(os.path.join(sess.log_dir, "READY"), "w") as f:
918
+ f.write(str(os.getpid()))
919
+ srv.serve_forever()
920
+
921
+
922
+ def main():
923
+ ap = argparse.ArgumentParser()
924
+ ap.add_argument("--task", required=True)
925
+ ap.add_argument("--seed", type=int, required=True)
926
+ ap.add_argument("--k", type=int, default=None)
927
+ ap.add_argument("--memory", default="full", choices=["full", "none"])
928
+ ap.add_argument("--hide-k", action="store_true",
929
+ help="memory=full: README/status say 1 attempt (same as an independent k=1 run); the remaining "
930
+ "attempts are announced only after a failed attempt")
931
+ ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
932
+ ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"])
933
+ ap.add_argument("--image-res", type=int, default=512)
934
+ ap.add_argument("--port", type=int, default=8765)
935
+ ap.add_argument("--sandbox", required=True)
936
+ ap.add_argument("--log-dir", required=True)
937
+ ap.add_argument("--max-steps", type=int, default=None,
938
+ help="robot commands per attempt (default: the task's agent_max_steps, else 40)")
939
+ ap.add_argument("--allow-push", action="store_true", help="expose the composite push primitive (off by default)")
940
+ ap.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"],
941
+ help="rgb: images only (no pixel_to_world / depth); depth: adds the depth back-projection tool "
942
+ "(v1); rgbd (la): also writes metric depth and camera calibration files")
943
+ ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"],
944
+ help="v2: LIBERO-Agent / RoboDojo-aligned interface (see _V2); la: v2 + LIBERO-Agent workspace "
945
+ "(observation files, programs in the workspace, robot only through the harness tool)")
946
+ ap.add_argument("--nominal", action="store_true",
947
+ help="control: remove the hidden calibration error of an L1 task (bias / yaw_bias = 0)")
948
+ ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"],
949
+ help="la: tools = harness tools (robot / shell / view_images, our GPT driver); cli = ./robot and "
950
+ "./shell in the workspace for a coding agent such as Claude Code")
951
+ ap.add_argument("--max-tool-calls", type=int, default=100,
952
+ help="la: tool calls per attempt (robot + shell + view_image), enforced by the harness")
953
+ ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
954
+ help="full5 controlled arms (lffbench/arm_specs/<task>.py): h0 = hidden variable at its ordinary value; "
955
+ "hplus = hidden variable stated in the instruction; twin = mismatched-history source instance")
956
+ ap.add_argument("--dossier", default="",
957
+ help="la: copy this directory into the workspace as history/ (record of an earlier failed attempt, "
958
+ "made by scripts/make_dossier.py) and say so in README.md")
959
+ ap.add_argument("--video", default="", help="record agentview|wrist mp4 to this path")
960
+ ap.add_argument("--video-every", type=int, default=3, help="one frame every N control steps (20 Hz)")
961
+ ap.add_argument("--video-fps", type=int, default=20)
962
+ serve(ap.parse_args())
963
+
964
+
965
+ if __name__ == "__main__":
966
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/lffbench/agent/tools.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent-facing tool interface on top of `Skills`.
2
+
3
+ Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps
4
+ acting on every commanded position. Proprioception is reported in the robot's own (possibly
5
+ miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the
6
+ commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and
7
+ the privileged `locate` tool are in the true world frame.
8
+
9
+ Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in
10
+ `required`, optional ones nullable, no additional properties).
11
+ """
12
+ import json
13
+ import math
14
+ import time
15
+ from dataclasses import dataclass, field
16
+
17
+ import numpy as np
18
+
19
+ from .. import envs
20
+ from . import camera as C
21
+ from .images import ImageRef
22
+
23
+ TABLE_Z = envs.TABLE_Z
24
+ # Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are
25
+ # clipped and the report says so.
26
+ WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005])
27
+ WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50])
28
+ SPEED_RANGE = (0.02, 1.0)
29
+ PUSH_DIST_RANGE = (0.0, 0.40)
30
+ RUNUP_RANGE = (0.02, 0.30)
31
+
32
+ ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push")
33
+
34
+
35
+ def _num(desc):
36
+ return {"type": "number", "description": desc}
37
+
38
+
39
+ def _opt_num(desc):
40
+ return {"type": ["number", "null"], "description": desc}
41
+
42
+
43
+ def _fn(name, desc, props=None):
44
+ props = props or {}
45
+ return dict(name=name, description=desc,
46
+ parameters={"type": "object", "properties": props, "required": list(props),
47
+ "additionalProperties": False})
48
+
49
+
50
+ def tool_specs(privileged_locate=False, object_names=None, image_res=512):
51
+ """Backend-neutral tool list: [{name, description, parameters}]."""
52
+ specs = [
53
+ _fn("move_to",
54
+ "Move the gripper's grasp point (midway between the fingertips) in a straight line to the world "
55
+ "position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper "
56
+ "opening is not changed. Returns whether the target was reached, the end-effector position, gripper "
57
+ "width, whether an object is held and whether the arm touched an object during the motion.",
58
+ {"x": _num("target x, metres (world frame; +x away from the robot)"),
59
+ "y": _num("target y, metres (world frame; +y to the robot's left)"),
60
+ "z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"),
61
+ "yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world "
62
+ "y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger "
63
+ "gripper is symmetric): the controller uses the equivalent angle closest to the current "
64
+ "yaw within +-113 deg; the report gives the yaw actually used"),
65
+ "speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows "
66
+ "(about 0.6 m/s)")}),
67
+ _fn("open_gripper", "Open the gripper fully (the arm holds its position)."),
68
+ _fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."),
69
+ _fn("push",
70
+ "Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres "
71
+ "behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) "
72
+ "through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The "
73
+ "gripper is rotated automatically to a fixed orientation relative to the push direction.",
74
+ {"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"),
75
+ "y": _num("y of that point, m"),
76
+ "dir_x": _num("x component of the push direction (normalised internally)"),
77
+ "dir_y": _num("y component of the push direction"),
78
+ "distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"),
79
+ "speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"),
80
+ "z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} "
81
+ "(2 cm above the table)"),
82
+ "runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer "
83
+ "run-up lets the gripper reach the commanded speed before contact.")}),
84
+ _fn("get_observation",
85
+ "Return the current camera images (agentview and wrist) and the robot's proprioceptive state."),
86
+ _fn("pixel_to_world",
87
+ f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel "
88
+ f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the "
89
+ f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that "
90
+ f"pixel and its height above the table.",
91
+ {"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"},
92
+ "u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}),
93
+ _fn("done",
94
+ "Finish the current attempt. Call this when you believe the task is complete (or you want to stop). "
95
+ "Give a short reason: what you did and whether you think it worked.",
96
+ {"reason": {"type": "string", "description": "short explanation"}}),
97
+ ]
98
+ if privileged_locate:
99
+ names = list(object_names or [])
100
+ prop = {"type": "string", "description": "object name"}
101
+ if names:
102
+ prop["enum"] = names
103
+ specs.insert(-1, _fn("locate",
104
+ "PRIVILEGED (ablation): return the true world position of an object's origin and its "
105
+ "axis-aligned bounding box.", {"object_name": prop}))
106
+ return specs
107
+
108
+
109
+ @dataclass
110
+ class ToolResult:
111
+ name: str
112
+ args: dict
113
+ ok: bool
114
+ report: dict
115
+ images: list = field(default_factory=list)
116
+ ended: bool = False
117
+ wall_s: float = 0.0
118
+ sim_steps: int = 0
119
+
120
+ def text(self):
121
+ return json.dumps(self.report, separators=(", ", ": "), default=_json_default)
122
+
123
+
124
+ def _json_default(o):
125
+ if isinstance(o, (np.floating,)):
126
+ return float(o)
127
+ if isinstance(o, (np.integer,)):
128
+ return int(o)
129
+ if isinstance(o, np.ndarray):
130
+ return o.tolist()
131
+ if isinstance(o, (np.bool_,)):
132
+ return bool(o)
133
+ raise TypeError(type(o))
134
+
135
+
136
+ def _r(v, nd=4):
137
+ return [round(float(x), nd) for x in v]
138
+
139
+
140
+ class ContactTracker:
141
+ """Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control
142
+ step is 25 substeps; a fast push touches the object for less than one control step, so checking only at
143
+ control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the
144
+ wrapper only reads contacts and dispatches to the currently active tracker."""
145
+
146
+ def __init__(self, env):
147
+ self.env = env
148
+ m = env.sim.model
149
+ self.is_robot = np.zeros(m.ngeom, bool)
150
+ self.is_robot[envs.robot_geom_ids(env)] = True
151
+ self.names = []
152
+ self.obj_of = np.full(m.ngeom, -1, int)
153
+ for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}):
154
+ try:
155
+ ids = envs.obj_geom_ids(env, name)
156
+ except Exception: # fixtures without contact geoms
157
+ continue
158
+ self.obj_of[ids] = len(self.names)
159
+ self.names.append(name)
160
+ self.touched = set()
161
+ sim = env.sim
162
+ if not getattr(sim, "_lff_step_wrapped", False):
163
+ orig = sim.step
164
+
165
+ def step(*a, **k):
166
+ orig(*a, **k)
167
+ t = getattr(sim, "_lff_tracker", None)
168
+ if t is not None:
169
+ t.check()
170
+ sim.step = step
171
+ sim._lff_step_wrapped = True
172
+ sim._lff_tracker = self
173
+
174
+ def reset(self):
175
+ self.touched = set()
176
+
177
+ def check(self):
178
+ d = self.env.sim.data
179
+ n = d.ncon
180
+ if not n:
181
+ return
182
+ g1 = np.asarray(d.contact.geom1)[:n]
183
+ g2 = np.asarray(d.contact.geom2)[:n]
184
+ hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]])
185
+ for i in set(hit[hit >= 0].tolist()):
186
+ self.touched.add(self.names[i])
187
+
188
+
189
+ def parse_args(raw):
190
+ if raw is None:
191
+ return {}
192
+ if isinstance(raw, dict):
193
+ return dict(raw)
194
+ raw = raw.strip()
195
+ return json.loads(raw) if raw else {}
196
+
197
+
198
+ class ToolExecutor:
199
+ """Executes agent tool calls on a task whose instance has just been reset (task.sk is live)."""
200
+
201
+ def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False,
202
+ grasp_report="bool", jpeg_quality=90, image_sink=None):
203
+ self.task = task
204
+ self.inst = inst
205
+ self.env = task.env
206
+ self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy
207
+ self.image_res = int(image_res)
208
+ self.cams = tuple(cams)
209
+ self.privileged_locate = privileged_locate
210
+ self.grasp_report = grasp_report # "bool" | "name" | "none"
211
+ self.jpeg_quality = jpeg_quality
212
+ self.image_sink = image_sink # callable(ImageRef) -> path (saves the image)
213
+ self.objects = list(self.env.objects_dict)
214
+ self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched
215
+ self._depth_cache = {}
216
+ self.n_calls = 0
217
+
218
+ # ------------------------------------------------------------------ state
219
+ def eef_yaw_deg(self):
220
+ R = self.sk.eef_mat() @ self.sk.R0.T
221
+ return math.degrees(math.atan2(R[1, 0], R[0, 0]))
222
+
223
+ def held(self):
224
+ names = [o for o in self.objects if self.sk.holding(o)]
225
+ return names
226
+
227
+ def _holding_field(self, names):
228
+ if self.grasp_report == "name":
229
+ return names[0] if names else None
230
+ if self.grasp_report == "none":
231
+ return None
232
+ return bool(names)
233
+
234
+ def proprio(self):
235
+ believed = self.sk.eef_pos() - self.sk.bias
236
+ p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1),
237
+ gripper="closed" if self.sk.grip > 0 else "open",
238
+ gripper_width_m=round(self.sk.gripper_width(), 4))
239
+ if self.grasp_report != "none":
240
+ p["holding_object"] = self._holding_field(self.held())
241
+ return p
242
+
243
+ def render(self, cam, res=None):
244
+ res = res or self.image_res
245
+ return envs.render(self.env, C.mj_cam(cam), res)
246
+
247
+ def observe(self, label=""):
248
+ imgs = []
249
+ for cam in self.cams:
250
+ ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip())
251
+ if self.image_sink is not None:
252
+ self.image_sink(ref)
253
+ imgs.append(ref)
254
+ self._depth_cache = {}
255
+ return imgs
256
+
257
+ # ------------------------------------------------------------------ dispatch
258
+ def call(self, name, raw_args):
259
+ t0 = time.time()
260
+ n0 = self.sk.n_steps
261
+ self.n_calls += 1
262
+ try:
263
+ args = parse_args(raw_args)
264
+ except Exception as e:
265
+ return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"),
266
+ wall_s=time.time() - t0)
267
+ fn = getattr(self, f"_t_{name}", None)
268
+ if fn is None or (name == "locate" and not self.privileged_locate):
269
+ return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
270
+ try:
271
+ res = fn(**args)
272
+ except TypeError as e:
273
+ res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}"))
274
+ except ValueError as e:
275
+ res = ToolResult(name, args, False, dict(ok=False, error=str(e)))
276
+ res.args = args
277
+ res.wall_s = time.time() - t0
278
+ res.sim_steps = self.sk.n_steps - n0
279
+ if res.sim_steps:
280
+ self._depth_cache = {}
281
+ hook = getattr(self.task, "on_agent_tool", None)
282
+ if hook is not None:
283
+ hook(self.inst, name, args, res.report)
284
+ drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped)
285
+ if drain is not None:
286
+ ev = drain()
287
+ if ev:
288
+ res.report["events"] = list(ev)
289
+ return res
290
+
291
+ # ------------------------------------------------------------------ helpers
292
+ def _clip_xyz(self, xyz):
293
+ xyz = np.asarray(xyz, float)
294
+ if not np.all(np.isfinite(xyz)):
295
+ raise ValueError("non-finite coordinates")
296
+ c = np.clip(xyz, WS_LO, WS_HI)
297
+ return c, (None if np.allclose(c, xyz) else _r(c))
298
+
299
+ @staticmethod
300
+ def _clip(v, lo_hi, what):
301
+ v = float(v)
302
+ if not math.isfinite(v):
303
+ raise ValueError(f"{what} must be finite")
304
+ return float(np.clip(v, *lo_hi))
305
+
306
+ def _action_report(self, name, extra=None):
307
+ names = self.held()
308
+ rep = dict(ok=True, tool=name)
309
+ if extra:
310
+ rep.update(extra)
311
+ rep.update(self.proprio())
312
+ if self.grasp_report == "name":
313
+ rep["touched_objects"] = sorted(self.tracker.touched)
314
+ elif self.grasp_report == "bool":
315
+ rep["touched_object"] = bool(self.tracker.touched)
316
+ rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2)
317
+ return rep
318
+
319
+ # ------------------------------------------------------------------ tools
320
+ def _t_move_to(self, x, y, z, yaw, speed=None):
321
+ tgt, clipped = self._clip_xyz([x, y, z])
322
+ spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed")
323
+ self.tracker.reset()
324
+ rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi
325
+ extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1))
326
+ if clipped:
327
+ extra["target_clipped_to"] = clipped
328
+ return ToolResult("move_to", {}, True, self._action_report("move_to", extra))
329
+
330
+ def _t_open_gripper(self):
331
+ self.tracker.reset()
332
+ self.sk.set_gripper(False)
333
+ return ToolResult("open_gripper", {}, True, self._action_report("open_gripper"))
334
+
335
+ def _t_close_gripper(self):
336
+ self.tracker.reset()
337
+ self.sk.set_gripper(True)
338
+ return ToolResult("close_gripper", {}, True, self._action_report("close_gripper"))
339
+
340
+ def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None):
341
+ d = np.array([float(dir_x), float(dir_y)])
342
+ if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6:
343
+ raise ValueError("push direction must be a non-zero vector")
344
+ start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z])
345
+ dist = self._clip(distance, PUSH_DIST_RANGE, "distance")
346
+ spd = self._clip(speed, SPEED_RANGE, "speed")
347
+ pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup")
348
+ self.tracker.reset()
349
+ rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre)
350
+ extra = dict(sweep_reached=bool(rep["reached"]))
351
+ if clipped:
352
+ extra["start_clipped_to"] = clipped
353
+ return ToolResult("push", {}, True, self._action_report("push", extra))
354
+
355
+ def _t_get_observation(self):
356
+ imgs = self.observe(label="requested")
357
+ return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()),
358
+ images=imgs)
359
+
360
+ def _t_pixel_to_world(self, camera, u, v):
361
+ cam = str(camera)
362
+ if cam not in C.CAMERAS:
363
+ raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}")
364
+ if cam not in self._depth_cache:
365
+ self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res)
366
+ r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam])
367
+ rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]),
368
+ height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4))
369
+ if not r["valid"]:
370
+ rep["warning"] = "pixel shows the far background; the point is unreliable"
371
+ return ToolResult("pixel_to_world", {}, True, rep)
372
+
373
+ def _t_locate(self, object_name):
374
+ if object_name not in self.env.objects_dict:
375
+ raise ValueError(f"unknown object {object_name!r}; known: {self.objects}")
376
+ lo, hi = self._aabb(object_name)
377
+ p = envs.obj_pos(self.env, object_name)
378
+ return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo),
379
+ bbox_max=_r(hi)))
380
+
381
+ def _aabb(self, name):
382
+ m, d = self.env.sim.model, self.env.sim.data
383
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
384
+ for g in envs.obj_geom_ids(self.env, name):
385
+ R = d.geom_xmat[g].reshape(3, 3)
386
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
387
+ h = np.abs(R) @ m.geom_aabb[g, 3:]
388
+ lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h)
389
+ return lo, hi
390
+
391
+ def _t_done(self, reason=""):
392
+ return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/lff/source_closure/scripts/agent_compare.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ΔICL between two agent run directories on the same seeds.
2
+
3
+ python scripts/agent_compare.py --with runs/agent/<task>/<full-memory run> --iid runs/agent/<task>/<memory-none run>
4
+
5
+ ΔICL = succ@k(with history) - pass@k_iid(independent retries), paired by instance seed, with a paired
6
+ bootstrap 95% interval. Also prints the analytic i.i.d. reference 1-(1-p1)^k from the 'with' run.
7
+ """
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
14
+
15
+ from lffbench.agent.metrics import paired_delta # noqa: E402
16
+
17
+
18
+ def load(d):
19
+ with open(os.path.join(d, "summary.json")) as f:
20
+ return json.load(f)
21
+
22
+
23
+ def main():
24
+ ap = argparse.ArgumentParser()
25
+ ap.add_argument("--with", dest="with_", required=True)
26
+ ap.add_argument("--iid", required=True)
27
+ ap.add_argument("--k", type=int, default=None)
28
+ a = ap.parse_args()
29
+ w, i = load(a.with_), load(a.iid)
30
+ k = a.k or min(w["k"], i["k"])
31
+ res = paired_delta(w["runs"], i["runs"], k)
32
+ res["k"] = k
33
+ res["with"] = dict(memory=w["memory"], feedback=w["feedback"], attempt1=w["aggregate"]["attempt1_success"],
34
+ pass_at_k_iid_analytic=w["aggregate"]["pass_at_k_iid_analytic"])
35
+ res["iid"] = dict(memory=i["memory"], feedback=i["feedback"])
36
+ print(json.dumps(res, indent=1))
37
+
38
+
39
+ if __name__ == "__main__":
40
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_sonnet/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()