PeterXie666 commited on
Commit
96d3f8b
·
verified ·
1 Parent(s): 9214593

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/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/__init__.py +1 -0
  2. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/camera.py +100 -0
  3. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/robot_server.py +966 -0
  4. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/base.py +364 -0
  5. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/codex.py +687 -0
  6. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py +542 -0
  7. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json +23 -0
  8. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json +23 -0
  9. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json +36 -0
  10. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
  11. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/reference.py +143 -0
  12. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_height.py +448 -0
  13. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_yaw.py +439 -0
  14. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l2_turntable.py +469 -0
  15. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_card_shelf.py +587 -0
  16. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l4_fit.py +574 -0
  17. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l5_iterative.py +136 -0
  18. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l6_count.py +562 -0
  19. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_key_turn.py +461 -0
  20. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_offcenter_push.py +613 -0
  21. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_breakfast_service.py +546 -0
  22. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py +830 -0
  23. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_fence.py +1030 -0
  24. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_parts_cart.py +253 -0
  25. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_wobbly_table.py +1177 -0
  26. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/agent_cost.py +77 -0
  27. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/check_breakfast_geometry.py +41 -0
  28. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/gptpolicy_player.sh +37 -0
  29. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/headroom_parts_cart.py +19 -0
  30. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/lerobot_export.py +431 -0
  31. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/make_dossier.py +103 -0
  32. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/mismatch_plan.py +149 -0
  33. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/vla_eval.py +224 -0
  34. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/audit_state.py +79 -0
  35. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py +18 -0
  36. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/embodied_evo.py +135 -0
  37. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/api_player.py +446 -0
  38. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/full_report.py +89 -0
  39. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/ladder_gpt_plan.py +95 -0
  40. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/real_check_driver.py +163 -0
  41. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/record_breakfast_service.py +89 -0
  42. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/__init__.py +21 -0
  43. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/anthropic_messages.py +202 -0
  44. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/base.py +82 -0
  45. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/chat_completions.py +150 -0
  46. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/gemini.py +206 -0
  47. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py +240 -0
  48. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/scripted.py +210 -0
  49. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l4_fit_container.py +61 -0
  50. leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py +39 -0
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/camera.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map.
2
+
3
+ Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's
4
+ bottom-up buffer to an upright image):
5
+ u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image.
6
+ Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils.
7
+ """
8
+ import numpy as np
9
+ from robosuite.utils import camera_utils as CU
10
+
11
+ from .. import envs
12
+
13
+ # agent-facing camera name -> MuJoCo camera name
14
+ CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"}
15
+
16
+
17
+ def mj_cam(name):
18
+ if name in CAMERAS:
19
+ return CAMERAS[name]
20
+ if name in CAMERAS.values():
21
+ return name
22
+ raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}")
23
+
24
+
25
+ def intrinsics(env, cam, res):
26
+ return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res)
27
+
28
+
29
+ def cam_to_world(env, cam):
30
+ """4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward)."""
31
+ return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam))
32
+
33
+
34
+ def render_depth(env, cam, res):
35
+ """Metric depth (distance along the optical axis, metres), upright (res, res)."""
36
+ _, d = envs.render(env, mj_cam(cam), res, depth=True)
37
+ return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0))
38
+
39
+
40
+ def world_to_pixel(env, cam, xyz, res):
41
+ """Project a world point; returns (u, v) floats (u = column, v = row) and the depth."""
42
+ K = intrinsics(env, cam, res)
43
+ T = np.linalg.inv(cam_to_world(env, cam))
44
+ p = T @ np.append(np.asarray(xyz, float), 1.0)
45
+ uvw = K @ p[:3]
46
+ return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2])
47
+
48
+
49
+ def pixel_ray(env, cam, u, v, res):
50
+ """Unit ray direction (world) through pixel (u, v) and the camera origin."""
51
+ K = intrinsics(env, cam, res)
52
+ E = cam_to_world(env, cam)
53
+ d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0])
54
+ d = E[:3, :3] @ d_cam
55
+ return E[:3, 3].copy(), d / np.linalg.norm(d)
56
+
57
+
58
+ def pixel_to_world(env, cam, u, v, res, depth=None):
59
+ """Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict."""
60
+ if depth is None:
61
+ depth = render_depth(env, cam, res)
62
+ iu, iv = int(round(u)), int(round(v))
63
+ if not (0 <= iu < res and 0 <= iv < res):
64
+ raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image")
65
+ z = float(depth[iv, iu])
66
+ K = intrinsics(env, cam, res)
67
+ E = cam_to_world(env, cam)
68
+ p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0])
69
+ p = E @ p_cam
70
+ far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent
71
+ return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far))
72
+
73
+
74
+ def image_axes(env, cam, res, plane_z=envs.TABLE_Z):
75
+ """World directions of image-right and image-down at the image centre, projected onto the table
76
+ plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y)."""
77
+ o, d = pixel_ray(env, cam, res / 2, res / 2, res)
78
+ if abs(d[2]) < 1e-6:
79
+ return None
80
+ t = (plane_z - o[2]) / d[2]
81
+ c = o + t * d
82
+ out = []
83
+ for du, dv in ((8, 0), (0, 8)):
84
+ o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res)
85
+ t2 = (plane_z - o2[2]) / d2[2]
86
+ w = (o2 + t2 * d2 - c)[:2]
87
+ out.append(w / max(np.linalg.norm(w), 1e-9))
88
+ return out
89
+
90
+
91
+ def describe_axes(env, cam, res):
92
+ """Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign)."""
93
+ ax = image_axes(env, cam, res)
94
+ if ax is None:
95
+ return None
96
+ names = []
97
+ for w in ax:
98
+ i = int(np.argmax(np.abs(w)))
99
+ names.append(("+" if w[i] > 0 else "-") + "xy"[i])
100
+ return dict(right=names[0], down=names[1])
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/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/breakfast-v2-20261103-breakfast_v2_20261103_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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/codex.py ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Codex CLI as a native harness (arm F; flags measured in research_notes/harness接入调研/02 §2.3, Codex 0.156).
2
+
3
+ Launch: process env exactly the whitelist (env -i equivalent), a brand-new empty CODEX_HOME and HOME (one-time, under
4
+ /tmp/lffstate/<hex>), work dir /tmp/lffrun/<12 hex>, `codex exec --json --skip-git-repo-check --ignore-user-config
5
+ --ignore-rules -s read-only`, ~20 features disabled, project docs / permissions / environment context /
6
+ collaboration-mode / skills instructions off, web search off, and only our MCP server with
7
+ default_tools_approval_mode="approve" (otherwise exec mode silently denies MCP calls).
8
+
9
+ Early exit: `codex exec` ends when the model replies without a tool call, also when the episode is not over (measured
10
+ 2026-10-19, cx_pilot6b: gpt-6-astra stopped after a failed first attempt, "I stopped after the one authorized
11
+ attempt", although the finish reply said attempt 2 of 3 starts now). scripts/harness_run.py then sends the reference
12
+ driver's nudge as a user turn with `codex exec resume <thread>` (resume_argv), at most api_player.MAX_NO_TOOL times in
13
+ a row. Hence no --ephemeral: the session is kept in the one-time CODEX_HOME (memories off; removed after the run).
14
+ Measured with 0.163 against the fake server: the resumed request has the same developer messages, tools, model and
15
+ parameters as the first, then the earlier turns and the nudge as a user message.
16
+
17
+ The model API is a custom Responses provider "lffapi", so the preflight can point exactly the same config at a local
18
+ fake server by changing only base_url. Two ways to authenticate (auth=):
19
+ apikey env_key OPENAI_API_KEY (api_env), default endpoint the official API
20
+ chatgpt a ChatGPT subscription login (no API key; same as RPent's codex planner reusing `codex login`): the
21
+ provider gets requires_openai_auth=true (requests carry the login's bearer + chatgpt-account-id), default
22
+ endpoint the ChatGPT Codex backend; a copy of auth.json from the source CODEX_HOME is put into the one-time
23
+ CODEX_HOME (the only file allowed there at launch). If Codex refreshes the login during a run, the refreshed
24
+ auth.json is written back to the source (refresh tokens rotate), unless the source changed meanwhile.
25
+ Launch is refused when the source login is close to its refresh (parallel copies would each rotate it).
26
+ Measured with 0.163 against the fake server: same body keys and headers in both modes plus chatgpt-account-id; the
27
+ preset differs (exec tool description), so pins are per auth mode (pin name codex-chatgpt).
28
+ The calling environment's HTTP(S) proxy is passed through (base.proxy_env; NO_PROXY = loopback only).
29
+
30
+ Model configuration (catalog=, user 2026-10-20): Codex picks the system prompt, tool form and context window per
31
+ model from its model catalog. We always pass an explicit model_catalog_json written into the one-time CODEX_HOME, so
32
+ nothing depends on the catalog the subscription backend serves on the day:
33
+ generic (main table, every model) one entry built from codex_catalogs/generic_<version>.json: what Codex sends for a
34
+ model it has no entry for (its generic Codex CLI prompt, plain function tools, no code mode); per model only
35
+ slug, input modalities and reasoning levels. Measured with 0.163 against the fake server: the request equals
36
+ the no-catalog fallback for an unknown slug apart from message ids.
37
+ native (control) codex_catalogs/native_<version>.json = `codex debug models --bundled` of that binary: the request
38
+ equals the one without any catalog (GPT: code mode, its own prompt). The pins of before 10-20 stay valid.
39
+ Pins are per catalog (pin name codex[-chatgpt][-generic]).
40
+
41
+ Known, accepted differences in native (code mode) catalogs (reported, not fixable by config in 0.156):
42
+ - code mode: the model sees one `exec` tool (JavaScript in a V8 isolate without fs / network); our tools are nested
43
+ and listed only in ALL_TOOLS; MCP images reach the model only if the model's JS calls image(...)
44
+ - apply_patch (blocked by the read-only sandbox), clock, 3 MCP-resource tools (our server has no resources),
45
+ request_user_input, and 6 collaboration.* sub-agent tools cannot be removed; a sub-agent call is an audit violation
46
+ - --json has tokens but no dollar cost
47
+ Fail-closed launch: the preflight checks the top-level tools, the exec nested-tool list (ALL_TOOLS, printed by a
48
+ scripted exec call), the developer (preset) messages and request parameters against the pin.
49
+ """
50
+ import base64
51
+ import datetime
52
+ import fcntl
53
+ import json
54
+ import os
55
+ import re
56
+ import shutil
57
+ import sqlite3
58
+ import subprocess
59
+ import sys
60
+ import time
61
+
62
+ from . import contract as C
63
+ from . import pins
64
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
65
+ new_run_dir, proxy_env, snapshot_tree)
66
+ from .fakeapi import FakeResponses
67
+ from .trajectory import TrajWriter
68
+
69
+ ROOT = C.ROOT
70
+ MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
71
+ BASE_PATH = "/usr/bin:/bin"
72
+ OFFICIAL_API = "https://api.openai.com/v1"
73
+ CHATGPT_BACKEND = "https://chatgpt.com/backend-api/codex"
74
+ AUTH_FILE = "auth.json"
75
+ AUTH_LOCK = "/tmp/lffstate/.codex_auth.lock"
76
+ MAX_LOGIN_AGE_H = 8 * 24 # codex-rs TOKEN_REFRESH_INTERVAL (8 days, from the source, not measured here): a login
77
+ # older than this is refreshed at start, by every parallel copy
78
+ MIN_ACCESS_LEFT_H = 24 # an access token expiring during a run makes the run's copy refresh it
79
+
80
+
81
+ def _jwt_claims(tok):
82
+ try:
83
+ p = tok.split(".")[1]
84
+ return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
85
+ except (IndexError, ValueError, AttributeError):
86
+ return {}
87
+
88
+
89
+ def chatgpt_login_status(home):
90
+ """-> dict(ok, problem, last_refresh_h, access_token_valid_h) of the ChatGPT login in home/auth.json. No secret
91
+ leaves this function."""
92
+ src = os.path.join(home, AUTH_FILE)
93
+ try:
94
+ with open(src) as f:
95
+ a = json.load(f)
96
+ except (OSError, ValueError) as e:
97
+ return dict(ok=False, problem=f"cannot read {src}: {type(e).__name__}")
98
+ tok = a.get("tokens") or {}
99
+ if a.get("auth_mode") != "chatgpt" or not tok.get("access_token") or not tok.get("refresh_token"):
100
+ return dict(ok=False, problem=f"{src} is not a ChatGPT login (auth_mode={a.get('auth_mode')!r})")
101
+ now = time.time()
102
+ try:
103
+ lr = datetime.datetime.fromisoformat(str(a.get("last_refresh")).replace("Z", "+00:00")).timestamp()
104
+ age_h = (now - lr) / 3600
105
+ except ValueError:
106
+ age_h = float("inf")
107
+ left_h = (float(_jwt_claims(tok["access_token"]).get("exp") or 0) - now) / 3600
108
+ out = dict(ok=True, problem=None, last_refresh_h=round(age_h, 1), access_token_valid_h=round(left_h, 1))
109
+ if age_h >= MAX_LOGIN_AGE_H or left_h < MIN_ACCESS_LEFT_H:
110
+ out.update(ok=False, problem=f"the ChatGPT login in {home} is due for a refresh (last refresh {age_h:.0f} h ago, "
111
+ f"access token valid {left_h:.0f} h): refresh it once outside the benchmark (use "
112
+ f"codex with CODEX_HOME={home}), so that parallel runs do not each rotate it")
113
+ return out
114
+ DISABLE = ["shell_tool", "unified_exec", "view_image", "multi_agent", "multi_agent_v2", "apps", "browser_use",
115
+ "browser_use_external", "computer_use", "image_generation", "plugins", "hooks", "skill_search",
116
+ "tool_suggest", "goals", "sleep_tool", "in_app_browser", "memories", "skill_mcp_dependency_install",
117
+ "realtime_conversation"]
118
+ # what remains in 0.156 after the lock-down (measured): anything else is refused at launch
119
+ EXPECTED_TOP = ["collaboration.followup_task", "collaboration.interrupt_agent", "collaboration.list_agents",
120
+ "collaboration.send_message", "collaboration.spawn_agent", "collaboration.wait_agent",
121
+ "functions.exec", "functions.request_user_input", "functions.request_user_input_async",
122
+ "functions.wait"]
123
+ EXPECTED_ALL_TOOLS = ["apply_patch", "clock__curr_time", "list_mcp_resource_templates", "list_mcp_resources",
124
+ "mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images", "read_mcp_resource"]
125
+ # generic catalog (no code mode), measured with 0.163: our tools are plain functions in the mcp__lff namespace
126
+ EXPECTED_TOP_GENERIC = ["list_mcp_resource_templates", "list_mcp_resources", "mcp__lff.robot", "mcp__lff.shell",
127
+ "mcp__lff.view_images", "read_mcp_resource", "request_user_input"]
128
+ CATALOG_DIR = os.path.join(ROOT, "lffbench", "harnesses", "codex_catalogs")
129
+ CATALOG_FILE = "lff_model_catalog.json" # written into the one-time CODEX_HOME before launch
130
+ CATALOGS = ("generic", "native")
131
+ # generic catalog: the per-model fields (input modalities; the run's reasoning level is always listed)
132
+ TEXT_ONLY_MODELS = {"deepseek-v4-pro": ["text"]} # DeepSeek's Codex guide (read 2026-10-20): v4-pro takes no images
133
+ DEEPSEEK_URL = "https://api.deepseek.com/" # same guide: base_url, wire_api = "responses"
134
+ OPENCODE_GO_URL = "https://opencode.ai/inference/go/openai/v1" # OpenCode Go, Responses API (checked 2026-10-29)
135
+ MCP_TOOLS = ["robot", "shell", "view_images"]
136
+ OK_ITEMS = ("agent_message", "reasoning", "mcp_tool_call", "error")
137
+ PREFLIGHT_JS = "text(JSON.stringify(ALL_TOOLS));"
138
+
139
+
140
+ def codex_bin():
141
+ return os.environ.get("LFF_CODEX_BIN") or shutil.which("codex") or "codex"
142
+
143
+
144
+ def toml_str(s):
145
+ return json.dumps(s) # a JSON string literal is a valid TOML basic string
146
+
147
+
148
+ def _norm(s, cwd):
149
+ s = s.replace(cwd, "<CWD>")
150
+ s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
151
+ s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
152
+ s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
153
+ s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "<UUID>", s)
154
+ return s
155
+
156
+
157
+ def _walk_tools(ts, prefix=""):
158
+ out = []
159
+ for t in ts or []:
160
+ if t.get("type") == "namespace":
161
+ out += _walk_tools(t.get("tools"), prefix + t.get("name", "") + ".")
162
+ else:
163
+ out.append(dict(name=prefix + (t.get("name") or t.get("type") or "?"), type=t.get("type"),
164
+ description=t.get("description"), parameters=t.get("parameters"), format=t.get("format")))
165
+ return out
166
+
167
+
168
+ def request_fingerprint(body, cwd, first_message, expected_top=None):
169
+ problems = []
170
+ items = body.get("input") or []
171
+ top = _walk_tools(body.get("tools"))
172
+ dev, users = [], []
173
+ for it in items:
174
+ if it.get("type") == "additional_tools":
175
+ top += _walk_tools(it.get("tools"))
176
+ elif it.get("type") == "message" and it.get("role") in ("developer", "system"):
177
+ dev.append(_norm("\n".join(c.get("text", "") for c in it.get("content") or []), cwd))
178
+ elif it.get("type") == "message" and it.get("role") == "user":
179
+ users.append(it)
180
+ names = sorted(t["name"] for t in top)
181
+ expected_top = EXPECTED_TOP if expected_top is None else expected_top
182
+ if names != expected_top:
183
+ problems.append(f"top-level tools {names} != expected {expected_top}")
184
+ texts = [c.get("text") for u in users for c in u.get("content") or []]
185
+ if texts != [first_message]:
186
+ problems.append(f"user input is not exactly our first message ({len(texts)} user text blocks)")
187
+ for t in top:
188
+ if t.get("description"):
189
+ t["description"] = _norm(t["description"], cwd)
190
+ params = {k: body.get(k) for k in ("model", "reasoning", "parallel_tool_calls", "store", "include", "text",
191
+ "tool_choice", "instructions", "max_output_tokens", "temperature")}
192
+ meta = body.get("client_metadata") or {}
193
+ try:
194
+ turn_meta = json.loads(meta.get("x-codex-turn-metadata") or "{}")
195
+ except ValueError:
196
+ turn_meta = {}
197
+ sandbox = {k: turn_meta.get(k) for k in ("sandbox", "sandbox_mode")}
198
+ if sandbox.get("sandbox_mode") != "read-only":
199
+ problems.append(f"sandbox {sandbox}")
200
+ fp = dict(tools=sorted(top, key=lambda t: t["name"]), developer=dev, params=params, sandbox=sandbox,
201
+ developer_chars=sum(len(d) for d in dev))
202
+ return fp, problems
203
+
204
+
205
+ def model_catalog(mode, version, model, modalities=None, effort=None):
206
+ """-> (catalog dict for model_catalog_json, source file). Refuses (fail-closed) when the version has no catalog
207
+ file or, for native, when the model has no entry."""
208
+ if mode not in CATALOGS:
209
+ raise ValueError(f"catalog must be one of {CATALOGS}, not {mode!r}")
210
+ src = os.path.join(CATALOG_DIR, f"{mode}_{version}.json")
211
+ if not os.path.exists(src):
212
+ raise HarnessRefused(f"no {mode} model catalog for Codex {version} ({os.path.relpath(src, ROOT)})")
213
+ d = json.load(open(src))
214
+ if mode == "native":
215
+ if not any(m.get("slug") == model for m in d.get("models") or []):
216
+ raise HarnessRefused(f"native catalog {os.path.basename(src)} has no entry for {model}")
217
+ return d, src
218
+ e = dict(d["entry"], slug=model, display_name=model)
219
+ modalities = modalities or TEXT_ONLY_MODELS.get(model)
220
+ if modalities:
221
+ e["input_modalities"] = list(modalities)
222
+ levels = [dict(x) for x in e.get("supported_reasoning_levels") or []]
223
+ if effort and effort not in [x.get("effort") for x in levels]:
224
+ levels.append(dict(effort=effort, description=effort))
225
+ e["supported_reasoning_levels"] = levels
226
+ return dict(models=[e]), src
227
+
228
+
229
+ def all_tools_from(body):
230
+ """The ALL_TOOLS list printed by the preflight exec call (in the second request)."""
231
+ for it in body.get("input") or []:
232
+ if it.get("type") == "custom_tool_call_output":
233
+ out = it.get("output")
234
+ parts = out if isinstance(out, list) else [dict(text=out)]
235
+ for p in parts:
236
+ t = (p.get("text") or "").strip()
237
+ if t.startswith("["):
238
+ try:
239
+ return json.loads(t)
240
+ except ValueError:
241
+ pass
242
+ return None
243
+
244
+
245
+ class Codex(HarnessAdapter):
246
+ name = "codex"
247
+ uses_mcp = True
248
+ can_resume = True
249
+ clean_dirs = ("home", "codex_home", "tmp")
250
+ ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
251
+ capabilities = dict(
252
+ only_benchmark_tools=Cap("partial", "preflight", "generic catalog: our 3 MCP tools as functions + residual "
253
+ "resource×3 / request_user_input; native (code mode): reachable only via exec(JS), "
254
+ "residual apply_patch(blocked) / clock / resource×3 / request_user_input / "
255
+ "collaboration×6"),
256
+ images_reach_model=Cap("partial", "probe", "generic: MCP images go to the model; native (code mode): only if "
257
+ "the model's JS calls image(); bytes unchanged either way"),
258
+ non_persistent_session=Cap("yes", "probe", "only this run's thread, in the one-time CODEX_HOME (for exec "
259
+ "resume), removed after the run; memories off"),
260
+ pinned_version=Cap("yes", "launch", "codex --version + binary sha256 in harness.json; pin per version"),
261
+ machine_readable_events=Cap("yes", "stream", "exec --json (items + usage, no cost)"),
262
+ tool_calls_logged=Cap("yes", "stream", "mcp_tool_call items + mcp_transcript + events.jsonl"),
263
+ model_and_effort=Cap("yes", "preflight", "-m / model_reasoning_effort; request reasoning.effort checked"),
264
+ persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; canaries absent"),
265
+ instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0 + empty CODEX_HOME (AGENTS.md)"),
266
+ web_access=Cap("absent", "probe", "web_search disabled; exec isolate has no fetch"),
267
+ host_file_read=Cap("absent", "probe", "shell / unified_exec / view_image off; exec has no require; "
268
+ "read-only sandbox"),
269
+ builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
270
+ subagent_delegation=Cap("partial", "preflight", "collaboration.* tools cannot be disabled in 0.156; any use "
271
+ "is an audit violation"),
272
+ background_execution=Cap("partial", "preflight", "functions.wait / long exec yields exist; audited"),
273
+ )
274
+
275
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
276
+ python=None, extra_args=None, jail=False, auth="apikey", auth_home=None, catalog="generic",
277
+ modalities=None):
278
+ """api_env: {"OPENAI_API_KEY": ...} (the provider's env_key, auth="apikey"); base_url: Responses endpoint
279
+ (default: official API / ChatGPT Codex backend by auth). auth="chatgpt": a ChatGPT login copied from
280
+ auth_home (default LFF_CODEX_AUTH_HOME, else the calling CODEX_HOME, else ~/.codex), no API key.
281
+ jail: run the CLI in the native-harness jail (lffbench/harnesses/jail.py, static /proc).
282
+ catalog: "generic" (shared configuration of the main table) or "native" (Codex's own entry for the model);
283
+ modalities: input modalities of a generic entry (default text + image)."""
284
+ if catalog not in CATALOGS:
285
+ raise ValueError(f"catalog must be one of {CATALOGS}, not {catalog!r}")
286
+ self.catalog, self.modalities = catalog, (list(modalities) if modalities else None)
287
+ self._catalog_sha = {} # one-time CODEX_HOME -> sha256 of the catalog written there
288
+ if auth not in ("apikey", "chatgpt"):
289
+ raise ValueError(f"auth must be apikey or chatgpt, not {auth!r}")
290
+ if jail:
291
+ from .jail import HarnessJail
292
+ self.jail = HarnessJail(codex_bin(), proc="static")
293
+ self.auth = auth
294
+ self.auth_home = None
295
+ self._auth_copies = {} # one-time CODEX_HOME -> sha256 of the auth.json copied into it
296
+ if auth == "chatgpt":
297
+ self.auth_home = os.path.abspath(auth_home or os.environ.get("LFF_CODEX_AUTH_HOME")
298
+ or os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"))
299
+ self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
300
+ self.api_env = dict(api_env or {}) if auth == "apikey" else {}
301
+ self.base_url = base_url or (OFFICIAL_API if auth == "apikey" else CHATGPT_BACKEND)
302
+ self.proxy = proxy_env()
303
+ self.timeout_s = timeout_s
304
+ self.pins_dir = pins_dir
305
+ self.allow_unpinned = allow_unpinned
306
+ self.python = python or sys.executable
307
+ self.extra_args = list(extra_args or [])
308
+ self._version = None
309
+
310
+ # ------------------------------------------------------------------------------------------------ auth
311
+ def auth_info(self):
312
+ if self.auth == "apikey":
313
+ return dict(mode="apikey", keys=sorted(self.api_env))
314
+ st = chatgpt_login_status(self.auth_home)
315
+ return dict(mode="chatgpt", source=self.auth_home, **{k: v for k, v in st.items() if k != "ok"})
316
+
317
+ def config_info(self):
318
+ """For harness.json: which model catalog the run used."""
319
+ return dict(catalog=self.catalog, modalities=self.modalities)
320
+
321
+ def _install_catalog(self, codex_home, ep):
322
+ """Write the run's model catalog into the one-time CODEX_HOME (the only file besides auth.json allowed there
323
+ at launch). -> (path, sha256, source file, code mode)."""
324
+ cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, self.modalities, ep.effort)
325
+ path = os.path.join(codex_home, CATALOG_FILE)
326
+ with open(path, "w") as f:
327
+ json.dump(cat, f)
328
+ sha = C.sha256_file(path)
329
+ self._catalog_sha[codex_home] = sha
330
+ entry = next(m for m in cat["models"] if m.get("slug") == ep.model)
331
+ return path, sha, os.path.relpath(src, ROOT), entry.get("tool_mode") == "code_mode_only"
332
+
333
+ def _install_auth(self, codex_home):
334
+ """auth="chatgpt": copy the source login into a one-time CODEX_HOME (refused if it is due for a refresh)."""
335
+ if self.auth != "chatgpt":
336
+ return
337
+ st = chatgpt_login_status(self.auth_home)
338
+ if not st["ok"]:
339
+ raise HarnessRefused("ChatGPT login: " + st["problem"])
340
+ dst = os.path.join(codex_home, AUTH_FILE)
341
+ with open(os.path.join(self.auth_home, AUTH_FILE), "rb") as f:
342
+ data = f.read()
343
+ fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
344
+ with os.fdopen(fd, "wb") as f:
345
+ f.write(data)
346
+ self._auth_copies[codex_home] = C.sha256_file(dst)
347
+
348
+ def _sync_auth_back(self, codex_home):
349
+ """After a run: if Codex refreshed the login in the run's copy, write it back to the source (refresh tokens
350
+ rotate, the source's old one may no longer work), unless the source changed since the copy. -> note or None."""
351
+ copied = self._auth_copies.pop(codex_home, None)
352
+ p = os.path.join(codex_home, AUTH_FILE)
353
+ if copied is None or not os.path.exists(p) or C.sha256_file(p) == copied:
354
+ return None
355
+ try:
356
+ with open(p, "rb") as f:
357
+ data = f.read()
358
+ new = json.loads(data)
359
+ except (OSError, ValueError):
360
+ return "auth.json in the run's CODEX_HOME changed and is unreadable: not written back"
361
+ if new.get("auth_mode") != "chatgpt" or not (new.get("tokens") or {}).get("refresh_token"):
362
+ return "auth.json in the run's CODEX_HOME changed but holds no ChatGPT login: not written back"
363
+ src = os.path.join(self.auth_home, AUTH_FILE)
364
+ os.makedirs(os.path.dirname(AUTH_LOCK), exist_ok=True)
365
+ with open(AUTH_LOCK, "a") as lk:
366
+ fcntl.flock(lk, fcntl.LOCK_EX)
367
+ if C.sha256_file(src) != copied:
368
+ return "the run refreshed its login copy, but the source auth.json changed meanwhile: not written back"
369
+ tmp = src + ".lff-tmp"
370
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
371
+ with os.fdopen(fd, "wb") as f:
372
+ f.write(data)
373
+ os.replace(tmp, src)
374
+ return "the run refreshed the ChatGPT login: refreshed auth.json written back to the source"
375
+
376
+ def version(self):
377
+ if self._version is None:
378
+ b = codex_bin()
379
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
380
+ CODEX_HOME="/nonexistent"),
381
+ capture_output=True, text=True, timeout=60)
382
+ v = (out.stdout.strip().split() or ["?"])[-1]
383
+ self._version = dict(version=v, binary=binary_info(b))
384
+ return self._version
385
+
386
+ def pin_key(self, ep):
387
+ v = self.version()
388
+ name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
389
+ name += "" if self.catalog == "native" else f"-{self.catalog}"
390
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
391
+
392
+ # ------------------------------------------------------------------------------------------------ prepare
393
+ def config_args(self, ep, session_path, base_url, codex_home):
394
+ mcp_cmd, mcp_args = self.mcp_server_command(self.python, MCP_SCRIPT, ["--session", session_path] if session_path
395
+ else ["--schema-only"])
396
+ c = ["model_reasoning_effort=" + toml_str(ep.effort),
397
+ "project_doc_max_bytes=0", "include_permissions_instructions=false", "include_environment_context=false",
398
+ "include_collaboration_mode_instructions=false", "skills.include_instructions=false",
399
+ "skills.bundled.enabled=false", 'web_search="disabled"',
400
+ 'model_provider="lffapi"', 'model_providers.lffapi.name="lffapi"',
401
+ "model_providers.lffapi.base_url=" + toml_str(base_url), 'model_providers.lffapi.wire_api="responses"',
402
+ ('model_providers.lffapi.env_key="OPENAI_API_KEY"' if self.auth == "apikey"
403
+ else "model_providers.lffapi.requires_openai_auth=true"),
404
+ "mcp_servers.lff.command=" + toml_str(mcp_cmd),
405
+ "mcp_servers.lff.args=[" + ",".join(toml_str(x) for x in mcp_args) + "]",
406
+ "mcp_servers.lff.env={PATH=" + toml_str(BASE_PATH) + "}",
407
+ 'mcp_servers.lff.enabled_tools=["robot","shell","view_images"]',
408
+ 'mcp_servers.lff.default_tools_approval_mode="approve"', "mcp_servers.lff.required=true",
409
+ "mcp_servers.lff.startup_timeout_sec=60", "mcp_servers.lff.tool_timeout_sec=900",
410
+ "model_catalog_json=" + toml_str(os.path.join(codex_home, CATALOG_FILE))]
411
+ return c
412
+
413
+ def argv(self, ep, session_path, base_url, first_message, codex_home):
414
+ a = [codex_bin(), "exec", "--json", "--skip-git-repo-check", "--ignore-user-config",
415
+ "--ignore-rules", "-s", "read-only", "-m", ep.model]
416
+ for f in DISABLE:
417
+ a += ["--disable", f]
418
+ for c in self.config_args(ep, session_path, base_url, codex_home):
419
+ a += ["-c", c]
420
+ return a + self.extra_args + [first_message]
421
+
422
+ @staticmethod
423
+ def thread_id(stdout_path):
424
+ t = None
425
+ for line in open(stdout_path, encoding="utf-8", errors="replace"):
426
+ if line.startswith("{") and '"thread.started"' in line:
427
+ t = json.loads(line).get("thread_id") or t
428
+ return t
429
+
430
+ def resume_argv(self, h, message):
431
+ """`codex exec resume <thread> <message>` with the launch's flags and config; resume has no -s, so the
432
+ sandbox goes in as sandbox_mode."""
433
+ thread = self.thread_id(h.spec.stdout_path)
434
+ if not thread:
435
+ raise HarnessRefused("resume: no thread id in the event stream")
436
+ a = list(h.spec.argv[:-1]) # without the first message
437
+ i = a.index("exec")
438
+ rest = a[i + 1:]
439
+ j = rest.index("-s")
440
+ mode = rest[j + 1]
441
+ del rest[j:j + 2]
442
+ return a[:i + 1] + ["resume"] + rest + ["-c", "sandbox_mode=" + toml_str(mode), thread, message]
443
+
444
+ def env(self, state):
445
+ e = dict(PATH=BASE_PATH, HOME=state["home"], CODEX_HOME=state["codex_home"], TMPDIR=state["tmp"],
446
+ LANG="C.UTF-8")
447
+ e.update(self.proxy)
448
+ e.update(self.api_env)
449
+ return e
450
+
451
+ def _state_dirs(self, hexname=None):
452
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
453
+ os.makedirs(root, exist_ok=True)
454
+ state = dict(state=root, home=os.path.join(root, "home"), codex_home=os.path.join(root, "codex_home"),
455
+ tmp=os.path.join(root, "tmp"))
456
+ for k in ("home", "codex_home", "tmp"):
457
+ os.makedirs(state[k], exist_ok=True)
458
+ return state
459
+
460
+ def prepare(self, ep, first_message, reuse_state=None):
461
+ work = new_run_dir("/tmp/lffrun")
462
+ state = reuse_state or self._state_dirs(os.path.basename(work))
463
+ if self.jail is not None:
464
+ self.jail.stderr_dir = ep.log_dir
465
+ if not reuse_state and os.listdir(state["codex_home"]):
466
+ raise HarnessRefused("CODEX_HOME is not empty")
467
+ cat_path, cat_sha, cat_src, code_mode = self._install_catalog(state["codex_home"], ep)
468
+ argv = self.argv(ep, ep.session_path, self.base_url, first_message, state["codex_home"])
469
+ return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
470
+ first_message=first_message, stdout_path=os.path.join(ep.log_dir, "codex_events.jsonl"),
471
+ stderr_path=os.path.join(ep.log_dir, "codex_stderr.txt"),
472
+ redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
473
+ config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
474
+ catalog=self.catalog, code_mode=code_mode)),
475
+ timeout_s=self.timeout_s)
476
+
477
+ def launch(self, spec, ep, skip_preflight=False):
478
+ self._install_auth(spec.state_dirs["codex_home"])
479
+ return super().launch(spec, ep, skip_preflight=skip_preflight)
480
+
481
+ def cleanup(self, spec):
482
+ self._sync_auth_back(spec.state_dirs.get("codex_home", ""))
483
+ super().cleanup(spec)
484
+
485
+ def config_sha256(self, spec, ep):
486
+ """Hash of everything configurable (argv without the first message, env values except keys / one-time dirs)."""
487
+ argv = [re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", a.replace(ep.session_path, "<SESSION>"))
488
+ .replace(spec.state_dirs["codex_home"], "<CODEX_HOME>") for a in self.logged_argv(spec)[1:-1]]
489
+ env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
490
+ if k not in ("HOME", "CODEX_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
491
+ cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
492
+ return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat))
493
+
494
+ # ------------------------------------------------------------------------------------------------ preflight
495
+ def preflight(self, spec, ep, record_dir=None):
496
+ t0 = time.time()
497
+ code_mode = (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True)
498
+ script = [[("exec", PREFLIGHT_JS)], [("text", "preflight ok")]] if code_mode else [[("text", "preflight ok")]]
499
+ fake = FakeResponses(script, record_dir=record_dir).start()
500
+ pre = self._state_dirs()
501
+ try:
502
+ self._install_auth(pre["codex_home"])
503
+ self._install_catalog(pre["codex_home"], ep)
504
+ argv = self.argv(ep, None, fake.base_url, spec.first_message, pre["codex_home"])
505
+ env = self.env(pre)
506
+ if self.auth == "apikey":
507
+ env["OPENAI_API_KEY"] = "sk-preflight-not-a-key"
508
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
509
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
510
+ reqs = fake.model_requests()
511
+ if len(reqs) < (2 if code_mode else 1):
512
+ raise HarnessRefused(f"preflight: {len(reqs)} model requests (rc={r.returncode}): "
513
+ f"{r.stderr.decode('utf-8', 'replace')[-800:]}")
514
+ fp, problems = request_fingerprint(reqs[0][1], spec.cwd, spec.first_message,
515
+ EXPECTED_TOP if code_mode else EXPECTED_TOP_GENERIC)
516
+ at_names = None
517
+ if code_mode: # our tools are nested in exec: the scripted exec call prints them
518
+ at = all_tools_from(reqs[1][1])
519
+ if at is None:
520
+ problems.append("exec preflight did not print ALL_TOOLS")
521
+ at = []
522
+ at_names = sorted(t.get("name") if isinstance(t, dict) else str(t) for t in at)
523
+ if at_names != EXPECTED_ALL_TOOLS:
524
+ problems.append(f"ALL_TOOLS {at_names} != expected {EXPECTED_ALL_TOOLS}")
525
+ fp["all_tools"] = [({k: (_norm(v, spec.cwd) if isinstance(v, str) else v) for k, v in t.items()}
526
+ if isinstance(t, dict) else t) for t in sorted(at, key=lambda t: json.dumps(t))]
527
+ effort = (fp["params"].get("reasoning") or {}).get("effort")
528
+ if effort != ep.effort:
529
+ problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
530
+ if os.listdir(spec.cwd):
531
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
532
+ fp_sha = C.sha256_json(fp)
533
+ out = dict(fingerprint_sha256=fp_sha, developer_chars=fp["developer_chars"], n_requests=len(reqs),
534
+ top_tools=[t["name"] for t in fp["tools"]], all_tools=at_names, code_mode=code_mode,
535
+ catalog=self.catalog, effort_in_request=effort,
536
+ model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], dt_s=round(time.time() - t0, 1),
537
+ problems=problems)
538
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
539
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
540
+ out["fingerprint"] = fp
541
+ if problems:
542
+ raise HarnessRefused("preflight: " + "; ".join(problems))
543
+ if pin is None:
544
+ if not self.allow_unpinned:
545
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
546
+ f"with --write-pins after the self-check passes)")
547
+ out["pin_status"] = "unpinned (allowed)"
548
+ elif pin["fingerprint_sha256"] != fp_sha:
549
+ raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
550
+ f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
551
+ else:
552
+ out["pin_status"] = "match"
553
+ return out
554
+ finally:
555
+ fake.stop()
556
+ self._sync_auth_back(pre["codex_home"])
557
+ shutil.rmtree(pre["state"], ignore_errors=True)
558
+
559
+ # ------------------------------------------------------------------------------------------------ collect
560
+ def collect(self, h):
561
+ spec, ep = h.spec, h.ep
562
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
563
+ thread, usage, items, errors = None, dict(input=0, cached=0, output=0, reasoning=0), [], []
564
+ for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
565
+ if not line.startswith("{"):
566
+ continue
567
+ d = json.loads(line)
568
+ t = d.get("type")
569
+ if t == "thread.started":
570
+ thread = d.get("thread_id")
571
+ elif t == "turn.completed":
572
+ u = d.get("usage") or {}
573
+ usage["input"] += u.get("input_tokens") or 0
574
+ usage["cached"] += u.get("cached_input_tokens") or 0
575
+ usage["output"] += u.get("output_tokens") or 0
576
+ usage["reasoning"] += u.get("reasoning_output_tokens") or 0
577
+ elif t in ("error", "turn.failed"):
578
+ errors.append(d)
579
+ elif t == "item.completed":
580
+ it = d.get("item") or {}
581
+ items.append(it.get("type"))
582
+ if it.get("type") == "agent_message":
583
+ tw.add_step("agent", message=it.get("text", ""))
584
+ elif it.get("type") == "reasoning":
585
+ tw.add_step("agent", reasoning=it.get("text", ""))
586
+ else:
587
+ name = it.get("tool") if it.get("type") == "mcp_tool_call" else it.get("type")
588
+ args = it.get("arguments") if it.get("type") == "mcp_tool_call" else {
589
+ k: v for k, v in it.items() if k not in ("id", "type", "status")}
590
+ st = tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
591
+ native_name=f"{it.get('server', '')}.{name}"
592
+ if it.get("type") == "mcp_tool_call" else name,
593
+ item_type=it.get("type"), arguments=args)])
594
+ res = it.get("result") or {}
595
+ texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
596
+ imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
597
+ tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
598
+ bool(it.get("error")) or it.get("status") == "failed", imgs)
599
+ del st
600
+ v = self.version()
601
+ tw.set_header(session_id=thread, source=os.path.basename(spec.stdout_path),
602
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
603
+ tools=EXPECTED_ALL_TOOLS if (spec.config_files.get("model_catalog_json") or {}).get(
604
+ "code_mode", True) else EXPECTED_TOP_GENERIC)
605
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items))),
606
+ total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
607
+ total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
608
+ tw.write()
609
+ h.info.update(items=items, traj=tw, thread=thread, errors=errors)
610
+ return tw
611
+
612
+ # ------------------------------------------------------------------------------------------------ audit
613
+ @staticmethod
614
+ def sqlite_rows(path, table):
615
+ """Row count of `table`, read from a copy (the db may be in WAL mode and still open)."""
616
+ import tempfile
617
+ try:
618
+ with tempfile.TemporaryDirectory() as td:
619
+ for suf in ("", "-wal", "-shm"):
620
+ if os.path.exists(path + suf):
621
+ shutil.copy(path + suf, os.path.join(td, "db.sqlite" + suf))
622
+ con = sqlite3.connect(os.path.join(td, "db.sqlite"))
623
+ n = con.execute(f"select count(*) from {table}").fetchone()[0]
624
+ con.close()
625
+ return n
626
+ except (sqlite3.Error, OSError) as e:
627
+ return f"n/a ({e})"
628
+
629
+ def audit(self, h):
630
+ spec, ep = h.spec, h.ep
631
+ v, notes = [], []
632
+ items = h.info.get("items") or []
633
+ bad = sorted({i for i in items if i not in OK_ITEMS})
634
+ if bad:
635
+ v.append(f"non-MCP items in the event stream: {bad}")
636
+ tw = h.info.get("traj")
637
+ residual = []
638
+ for st in (tw.steps if tw else []):
639
+ for tc in st["tool_calls"]:
640
+ if tc.get("item_type") != "mcp_tool_call":
641
+ continue
642
+ if tc["native_name"].startswith("lff.") and tc["function_name"] in MCP_TOOLS:
643
+ continue
644
+ if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
645
+ residual.append(tc["function_name"]) # our server has no resources: always empty
646
+ else:
647
+ v.append(f"unexpected MCP call {tc['native_name']}")
648
+ if residual:
649
+ notes.append(f"residual MCP-resource tool calls (empty, our server has no resources): {residual}")
650
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
651
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
652
+ ch = spec.state_dirs["codex_home"]
653
+ note = self._sync_auth_back(ch)
654
+ if note:
655
+ notes.append(note)
656
+ left = dict(codex_home=snapshot_tree(ch), home=snapshot_tree(spec.state_dirs["home"]),
657
+ work=snapshot_tree(spec.cwd))
658
+ threads = None
659
+ for f in left["codex_home"]:
660
+ if re.match(r"state_\d+\.sqlite$", f):
661
+ threads = self.sqlite_rows(os.path.join(ch, f), "threads")
662
+ if isinstance(threads, int) and threads > 1:
663
+ v.append(f"{threads} threads persisted in CODEX_HOME (only this run's one is expected)")
664
+ thread = h.info.get("thread")
665
+ sessions = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))]
666
+ foreign = [f for f in sessions if not (thread and f.startswith("sessions/") and f.endswith(f"-{thread}.jsonl"))]
667
+ if foreign:
668
+ v.append(f"session files other than this run's thread: {foreign}")
669
+ if h.info.get("resumes"):
670
+ notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
671
+ f"episode was over)")
672
+ if left["work"]:
673
+ v.append(f"files in the work dir: {left['work']}")
674
+ if (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True):
675
+ notes.append("image forwarding (model calls image()) is not visible in --json; needs the model proxy (P1)")
676
+ mcp_env = None
677
+ mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
678
+ if os.path.exists(mt):
679
+ for line in open(mt):
680
+ d = json.loads(line)
681
+ if d.get("ev") == "start" and "env_keys" in d:
682
+ mcp_env = d["env_keys"]
683
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, threads_rows=threads,
684
+ mcp_server_env_keys=mcp_env, item_types=sorted(set(items)), errors=h.info.get("errors"), ok=not v)
685
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
686
+ json.dump(out, f, indent=1)
687
+ return out
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared launcher for robot frameworks using a native Codex backend.
2
+
3
+ The external integration contract is Session.first_message(), Session.tool_specs(),
4
+ and Session.call(name, arguments). This launcher owns isolation, model configuration,
5
+ pins, trajectory collection and audits; framework plugins own their native loop.
6
+ Based on the validated RPent launcher; RPent's historical launcher remains frozen.
7
+ """
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import time
14
+
15
+ from . import contract as C
16
+ from . import pins
17
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
18
+ gateway_env, new_run_dir, proxy_env, snapshot_tree)
19
+ from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
20
+ request_fingerprint, toml_str)
21
+ from .fakeapi import FakeResponses
22
+ from .trajectory import TrajWriter
23
+
24
+ ROOT = C.ROOT
25
+ JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework"
26
+ BASE_PATH = "/usr/bin:/bin"
27
+ MCP_SERVER = "lff"
28
+ MCP_TOOLS = ["robot", "shell", "view_images"]
29
+ TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"}
30
+
31
+
32
+
33
+ def tree_sha256(root, skip=TREE_SKIP):
34
+ """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
35
+ h = hashlib.sha256()
36
+ for dp, dn, fn in os.walk(root):
37
+ dn[:] = sorted(d for d in dn if d not in skip)
38
+ for f in sorted(fn):
39
+ if f.endswith(".pyc"):
40
+ continue
41
+ p = os.path.join(dp, f)
42
+ rel = os.path.relpath(p, root)
43
+ if os.path.islink(p):
44
+ h.update(f"L {rel} {os.readlink(p)}\n".encode())
45
+ else:
46
+ h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
47
+ return h.hexdigest()
48
+
49
+
50
+ def runtime_info(home):
51
+ """The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
52
+ src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
53
+ for d in (src, venv):
54
+ if not os.path.isdir(d):
55
+ raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)")
56
+
57
+ def git(*a):
58
+ r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
59
+ return r.stdout.strip() if r.returncode == 0 else None
60
+ commit = git("rev-parse", "HEAD")
61
+ patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
62
+ untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
63
+ return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
64
+ untracked=sorted(u for u in untracked if "__pycache__" not in u),
65
+ tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
66
+
67
+
68
+ def jail_runtime_copy(home, tree):
69
+ """A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not)."""
70
+ dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}")
71
+ stamp = os.path.join(dst, ".tree_sha256")
72
+ if os.path.exists(stamp) and open(stamp).read().strip() == tree:
73
+ return dst
74
+ os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True)
75
+ tmp = dst + ".tmp-" + os.urandom(3).hex()
76
+ shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
77
+ ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
78
+ shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
79
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
80
+ got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
81
+ ).hexdigest()
82
+ if got != tree:
83
+ shutil.rmtree(tmp, ignore_errors=True)
84
+ raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
85
+ for dp, dn, fn in os.walk(tmp):
86
+ os.chmod(dp, 0o755)
87
+ for f in fn:
88
+ p = os.path.join(dp, f)
89
+ if not os.path.islink(p):
90
+ os.chmod(p, os.stat(p).st_mode | 0o444)
91
+ with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
92
+ f.write(tree)
93
+ if os.path.exists(dst):
94
+ shutil.rmtree(dst)
95
+ os.rename(tmp, dst)
96
+ return dst
97
+
98
+
99
+ def codex_overrides(effort, catalog_path):
100
+ """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
101
+ overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process)."""
102
+ return (["model_reasoning_effort=" + toml_str(effort),
103
+ "include_permissions_instructions=false", "include_environment_context=false",
104
+ "include_collaboration_mode_instructions=false", "skills.include_instructions=false",
105
+ "skills.bundled.enabled=false", 'web_search="disabled"',
106
+ f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
107
+ f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
108
+ f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
109
+ f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
110
+ "model_catalog_json=" + toml_str(catalog_path)]
111
+ + [f"features.{f}=false" for f in DISABLE])
112
+
113
+
114
+ def _items(stream_path):
115
+ """Codex app-server notifications of one robot framework session (robot framework writes them as JSONL)."""
116
+ out = []
117
+ if not os.path.exists(stream_path):
118
+ return out
119
+ for line in open(stream_path, encoding="utf-8", errors="replace"):
120
+ try:
121
+ out.append(json.loads(line))
122
+ except ValueError:
123
+ continue
124
+ return out
125
+
126
+
127
+ def _item_of(ev):
128
+ it = (ev.get("payload") or {}).get("item") or {}
129
+ return it.get("root", it) if isinstance(it, dict) else {}
130
+
131
+
132
+ class RobotFrameworkCodex(HarnessAdapter):
133
+ name = "framework_codex"
134
+ runtime_home = "/nonexistent"
135
+ runtime_module = "lff_integration.run"
136
+ default_steps = 500
137
+ uses_mcp = False
138
+ uses_gateway = True
139
+ can_resume = False
140
+ clean_dirs = ("home", "codex_home", "tmp", "out")
141
+ clean_allowed = {"codex_home": (CATALOG_FILE,)}
142
+ ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
143
+ capabilities = dict(
144
+ only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
145
+ "mcp__lff functions + residual resource×3 / request_user_input; robot framework registers "
146
+ "no tool of its own (no file tools, no finish)"),
147
+ images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, "
148
+ "JPEG with its own MIME type"),
149
+ non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the "
150
+ "run; no preloaded or cross-episode framework memory"),
151
+ pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in "
152
+ "harness.json; pin per version and tree"),
153
+ machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session "
154
+ "(codex.out.stream.jsonl) + robot framework run.json"),
155
+ tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"),
156
+ model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
157
+ persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not "
158
+ "constructed"),
159
+ instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
160
+ web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
161
+ host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
162
+ builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
163
+ subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
164
+ background_execution=Cap("absent", "preflight", "no background tool in the request"),
165
+ )
166
+
167
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
168
+ jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500,
169
+ home=None, provider=None, auth_home=None):
170
+ """Common controlled Codex SDK launcher.
171
+
172
+ The plugin entrypoint interprets its declared loop options. For SenseNova,
173
+ max_turns is the upstream SDK-step limit, not a provider-response count.
174
+ Robot commands, simulation time and tool budgets are always server-owned.
175
+ """
176
+ if auth not in ("apikey", "chatgpt"):
177
+ raise ValueError("framework_codex auth must be apikey or chatgpt")
178
+ if catalog not in CATALOGS:
179
+ raise ValueError(f"catalog must be one of {CATALOGS}")
180
+ self.auth, self.catalog = auth, catalog
181
+ self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog)
182
+ self.api_env = self._auth_manager.api_env
183
+ self.base_url = self._auth_manager.base_url
184
+ self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
185
+ self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
186
+ self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
187
+ int(max_turns)
188
+ self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home
189
+ self.proxy = proxy_env()
190
+ self._version = None
191
+ self._runtime = None
192
+ self.runtime_dir = self.home
193
+ if jail:
194
+ from .jail import HarnessJail
195
+ self.jail = HarnessJail(codex_bin(), proc="static")
196
+
197
+ # ------------------------------------------------------------------------------------------------ identity
198
+ def runtime(self):
199
+ if self._runtime is None:
200
+ self._runtime = runtime_info(self.home)
201
+ if self.jail is not None:
202
+ self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
203
+ return self._runtime
204
+
205
+ def version(self):
206
+ if self._version is None:
207
+ b = codex_bin()
208
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
209
+ CODEX_HOME="/nonexistent"),
210
+ capture_output=True, text=True, timeout=60)
211
+ v = (out.stdout.strip().split() or ["?"])[-1]
212
+ rt = self.runtime()
213
+ self._version = dict(version=v, binary=binary_info(b),
214
+ framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
215
+ tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
216
+ return self._version
217
+
218
+ def pin_key(self, ep):
219
+ v = self.version()
220
+ mode = "" if self.auth == "apikey" else "-chatgpt"
221
+ name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}"
222
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
223
+
224
+ def anchor_pin_key(self, ep):
225
+ """The main table's codex pin for the same model / effort (apikey, same catalog)."""
226
+ v = self.version()
227
+ name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}")
228
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
229
+
230
+ def auth_info(self):
231
+ if self.auth == "chatgpt":
232
+ return self._auth_manager.auth_info()
233
+ return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
234
+ "OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
235
+
236
+ def config_info(self):
237
+ return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
238
+ max_turns=self.max_turns, framework=self.version()["framework"])
239
+
240
+ # ------------------------------------------------------------------------------------------------ prepare
241
+ def _state_dirs(self, hexname=None):
242
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
243
+ os.makedirs(root, exist_ok=True)
244
+ state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
245
+ for k in ("home", "codex_home", "tmp", "out"):
246
+ os.makedirs(state[k], exist_ok=True)
247
+ return state
248
+
249
+ def _install_catalog(self, codex_home, ep):
250
+ cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
251
+ path = os.path.join(codex_home, CATALOG_FILE)
252
+ with open(path, "w") as f:
253
+ json.dump(cat, f)
254
+ return path, C.sha256_file(path), os.path.relpath(src, ROOT)
255
+
256
+ def argv(self, ep, out_dir, sessions=None, preflight=False):
257
+ py = os.path.join(self.runtime_dir, "venv", "bin", "python")
258
+ return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
259
+ "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
260
+ "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
261
+ + (["--no-continue"] if preflight else [])
262
+
263
+ def env(self, state, ep, base_url, work):
264
+ e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
265
+ CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
266
+ CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER,
267
+ FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
268
+ ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
269
+ FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
270
+ PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
271
+ if self.auth == "chatgpt":
272
+ # The native API provider declares env_key. Codex app-server still requires that
273
+ # variable even with requires_openai_auth=true, so select a separate provider
274
+ # with no env_key. Do not inject a dummy key or modify the upstream runtime.
275
+ provider_id = "lffsubscription"
276
+ overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"])
277
+ overrides += ["model_provider=" + toml_str(provider_id),
278
+ f"model_providers.{provider_id}.name=" + toml_str(provider_id),
279
+ f"model_providers.{provider_id}.wire_api=\"responses\"",
280
+ f"model_providers.{provider_id}.base_url=" + toml_str(base_url),
281
+ f"model_providers.{provider_id}.requires_openai_auth=true"]
282
+ e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides)
283
+ e.update(self.proxy)
284
+ if self.api_env.get("OPENAI_API_KEY"):
285
+ e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
286
+ return e
287
+
288
+ def prepare(self, ep, first_message, reuse_state=None):
289
+ self.version()
290
+ work = new_run_dir("/tmp/lffrun")
291
+ state = reuse_state or self._state_dirs(os.path.basename(work))
292
+ if self.jail is not None:
293
+ self.jail.stderr_dir = ep.log_dir
294
+ if not reuse_state and os.listdir(state["codex_home"]):
295
+ raise HarnessRefused("CODEX_HOME is not empty")
296
+ cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
297
+ return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
298
+ run_dir=work, state_dirs=state, first_message=first_message,
299
+ stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"),
300
+ stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"),
301
+ config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
302
+ catalog=self.catalog, code_mode=False)),
303
+ timeout_s=self.timeout_s)
304
+
305
+ def config_sha256(self, spec, ep):
306
+ argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<FRAMEWORK>")
307
+ for a in spec.argv]
308
+ hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH",
309
+ "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
310
+ env = {k: v for k, v in spec.env.items() if k not in hidden}
311
+ env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace(
312
+ spec.state_dirs["codex_home"], "<CODEX_HOME>")
313
+ cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
314
+ return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
315
+ framework_tree_sha256=self.version()["framework"]["tree_sha256"]))
316
+
317
+ # ------------------------------------------------------------------------------------------------ launch
318
+ def launch(self, spec, ep, skip_preflight=False):
319
+ """harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
320
+ self._auth_manager._install_auth(spec.state_dirs["codex_home"])
321
+ spec.env.update(gateway_env(ep.log_dir))
322
+ return super().launch(spec, ep, skip_preflight=skip_preflight)
323
+
324
+ def cleanup(self, spec):
325
+ self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", ""))
326
+ super().cleanup(spec)
327
+
328
+ def preflight(self, spec, ep, record_dir=None):
329
+ """The same framework process, one session, against a local fake Responses server that answers with text
330
+ only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
331
+ sandbox, robot framework's prefix + our first message) against the pins."""
332
+ t0 = time.time()
333
+ fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
334
+ pre = self._state_dirs()
335
+ try:
336
+ self._auth_manager._install_auth(pre["codex_home"])
337
+ self._install_catalog(pre["codex_home"], ep)
338
+ env = self.env(pre, ep, fake.base_url, spec.cwd)
339
+ if self.auth == "apikey":
340
+ env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
341
+ env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
342
+ argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
343
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
344
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
345
+ reqs = fake.model_requests()
346
+ if not reqs:
347
+ # Native planners may record failures only in run.json, with empty stdout/stderr.
348
+ record = os.path.join(pre["out"], "run.json")
349
+ detail = ""
350
+ if os.path.isfile(record):
351
+ with open(record) as f:
352
+ failed_run = json.load(f)
353
+ detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error"))
354
+ raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
355
+ f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}")
356
+ body = reqs[0][1]
357
+ fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
358
+ problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
359
+ users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
360
+ and it.get("role") == "user" for c in it.get("content") or []]
361
+ prefix = None
362
+ if len(users) != 1 or not users[0].endswith(spec.first_message):
363
+ problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
364
+ else:
365
+ prefix = users[0][:-len(spec.first_message)]
366
+ effort = (fp["params"].get("reasoning") or {}).get("effort")
367
+ if effort != ep.effort:
368
+ problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
369
+ if fp["params"].get("model") != ep.model:
370
+ problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
371
+ if os.listdir(spec.cwd):
372
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
373
+ mid_sha = C.sha256_json(fp)
374
+ full = dict(middle=fp, framework_prefix=prefix)
375
+ fp_sha = C.sha256_json(full)
376
+ anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
377
+ out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
378
+ framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
379
+ framework_prefix_chars=len(prefix) if prefix is not None else None,
380
+ developer_chars=fp["developer_chars"], n_requests=len(reqs),
381
+ top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
382
+ model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
383
+ dt_s=round(time.time() - t0, 1), problems=problems,
384
+ anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
385
+ if anchor is None:
386
+ out["anchor_status"] = "no main-table pin for this model / effort"
387
+ elif anchor["fingerprint_sha256"] != mid_sha:
388
+ problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
389
+ f"({anchor['key']}): the middle layer is not the main table's")
390
+ else:
391
+ out["anchor_status"] = "match"
392
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
393
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
394
+ out["fingerprint"] = full
395
+ if problems:
396
+ raise HarnessRefused("preflight: " + "; ".join(problems))
397
+ if pin is None:
398
+ if not self.allow_unpinned:
399
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
400
+ f"with --write-pins after the self-check passes)")
401
+ out["pin_status"] = "unpinned (allowed)"
402
+ elif pin["fingerprint_sha256"] != fp_sha:
403
+ raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
404
+ f"({pin['key']})")
405
+ else:
406
+ out["pin_status"] = "match"
407
+ return out
408
+ finally:
409
+ fake.stop()
410
+ self._auth_manager._sync_auth_back(pre["codex_home"])
411
+ shutil.rmtree(pre["state"], ignore_errors=True)
412
+
413
+ # ------------------------------------------------------------------------------------------------ collect
414
+ def collect(self, h):
415
+ spec, ep = h.spec, h.ep
416
+ dst = os.path.join(ep.log_dir, "framework")
417
+ if os.path.isdir(spec.state_dirs["out"]):
418
+ shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
419
+ run = {}
420
+ if os.path.exists(os.path.join(dst, "run.json")):
421
+ run = json.load(open(os.path.join(dst, "run.json")))
422
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
423
+ usage = dict(input=0, cached=0, output=0, reasoning=0)
424
+ items, threads, errors = [], [], []
425
+ for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
426
+ else []:
427
+ last = None
428
+ for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
429
+ m = ev.get("method") or ev.get("type")
430
+ p = ev.get("payload") or {}
431
+ if m == "thread/tokenUsage/updated":
432
+ last = (p.get("token_usage") or {}).get("total") or last
433
+ if p.get("thread_id") and p["thread_id"] not in threads:
434
+ threads.append(p["thread_id"])
435
+ elif m in ("error", "fatal", "timeout"):
436
+ errors.append(ev)
437
+ elif m == "item/completed":
438
+ it = _item_of(ev)
439
+ t = it.get("type")
440
+ items.append(t)
441
+ if t == "agentMessage":
442
+ tw.add_step("agent", message=it.get("text", ""))
443
+ elif t == "reasoning":
444
+ tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
445
+ elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
446
+ name = it.get("tool") or t
447
+ tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
448
+ native_name=f"{it.get('server', '')}.{name}",
449
+ item_type=t, arguments=it.get("arguments"),
450
+ session=sdir)])
451
+ res = it.get("result") or {}
452
+ texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
453
+ imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
454
+ tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
455
+ bool(it.get("error")) or it.get("status") == "failed", imgs)
456
+ if last:
457
+ usage["input"] += last.get("input_tokens") or 0
458
+ usage["cached"] += last.get("cached_input_tokens") or 0
459
+ usage["output"] += last.get("output_tokens") or 0
460
+ usage["reasoning"] += last.get("reasoning_output_tokens") or 0
461
+ # Framework close-out uses the same counted gateway shell, outside
462
+ # the model stream. Keep it visible in trajectories and tool totals.
463
+ session_record = next((s for s in run.get("sessions", [])
464
+ if sdir == f"session_{s['number']:03d}"), {})
465
+ handoff = session_record.get("handoff") or {}
466
+ if handoff:
467
+ call_id = f"framework-handoff-{sdir}"
468
+ tw.add_step("framework", tool_calls=[dict(
469
+ tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
470
+ item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
471
+ tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
472
+ if c.get("type") == "text"))
473
+ v = self.version()
474
+ tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl",
475
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
476
+ framework=v["framework"]), tools=EXPECTED_TOP_GENERIC)
477
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
478
+ run={k: run.get(k) for k in ("stop", "finished",
479
+ "attempts_failed", "tool_calls")},
480
+ sessions=len(run.get("sessions") or [])),
481
+ total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
482
+ total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
483
+ tw.write()
484
+ h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
485
+ return tw
486
+
487
+ # ------------------------------------------------------------------------------------------------ audit
488
+ def audit(self, h):
489
+ spec, ep = h.spec, h.ep
490
+ v, notes = [], []
491
+ items = h.info.get("items") or []
492
+ bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
493
+ "plan", "hookPrompt")})
494
+ if bad:
495
+ v.append(f"items other than messages / reasoning / MCP calls: {bad}")
496
+ residual = []
497
+ tw = h.info.get("traj")
498
+ for st in (tw.steps if tw else []):
499
+ for tc in st["tool_calls"]:
500
+ if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
501
+ continue
502
+ if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
503
+ residual.append(tc["function_name"])
504
+ else:
505
+ v.append(f"unexpected tool call {tc['native_name']}")
506
+ if residual:
507
+ notes.append(f"residual MCP-resource tool calls (empty): {residual}")
508
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
509
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
510
+ run = h.info.get("run") or {}
511
+ nsess = len(run.get("sessions") or [])
512
+ if len(h.info.get("threads") or []) > max(1, nsess):
513
+ v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions")
514
+ if nsess > 1:
515
+ notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)")
516
+ if run.get("stop") not in (None, "episode over"):
517
+ notes.append(f"robot framework stopped: {run.get('stop')}")
518
+ left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
519
+ work=snapshot_tree(spec.cwd))
520
+ if left["work"]:
521
+ v.append(f"files in the work dir: {left['work']}")
522
+ foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
523
+ and not any(t in f for t in (h.info.get("threads") or []))]
524
+ if foreign:
525
+ v.append(f"session files other than this run's threads: {foreign}")
526
+ gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
527
+ faces = set()
528
+ if os.path.exists(gt):
529
+ for line in open(gt):
530
+ try:
531
+ d = json.loads(line)
532
+ except ValueError:
533
+ continue
534
+ if d.get("ev") == "tool" and d.get("face"):
535
+ faces.add(d["face"])
536
+ if faces - {self.name}:
537
+ v.append(f"gateway calls from other access paths: {sorted(faces)}")
538
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
539
+ item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
540
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
541
+ json.dump(out, f, indent=1)
542
+ return out
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|medium",
3
+ "fingerprint_sha256": "ae30000e0db69f6b50aefe798b87406f633e414e071a66fd0f5e85b006d8b0ea",
4
+ "written": "2026-10-20 02:33:27",
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": "medium",
17
+ "model_in_request": "gpt-6-astra",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-v4.1-flash|high",
3
+ "fingerprint_sha256": "52d7de20832981196514c20e91635e50a2dc6241fa45a1bbfd863d08dc8cc740",
4
+ "written": "2026-10-29 16:15:13",
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-v4.1-flash",
18
+ "sandbox": {
19
+ "sandbox": "seccomp",
20
+ "sandbox_mode": "read-only"
21
+ }
22
+ }
23
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|high",
3
+ "fingerprint_sha256": "e999df1acbc0c137d1922832262b7b326df0ac8240b9647761158a1c368486c2",
4
+ "written": "2026-10-13 04:13:13",
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": "high",
30
+ "model_in_request": "gpt-6-astra",
31
+ "sandbox": {
32
+ "sandbox": "seccomp",
33
+ "sandbox_mode": "read-only"
34
+ }
35
+ }
36
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/redteam.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adversarial acceptance (red-team) runs: an agent told to get "Attempt succeeded." without doing the task.
2
+
3
+ Embodied First Exam merges a benchmark only after such a trial scored 0 on its tasks (PROTOCOL Appendix H.1). Here a
4
+ red-team run is an ordinary native-harness run whose first message starts with RED_TEAM_TEXT; everything else (task,
5
+ instance, tools, budgets, jail, model gateway) is unchanged. harness_run.py --red-team writes the marker file
6
+ red_team.json into the run's log dir before the contract is built, and contract.build_contract adds the key
7
+ "red_team" only for such runs, so their contract_sha256 never equals a normal run's and no table can mix them
8
+ (normal contracts are unchanged). scripts/redteam_report.py lists every success and every flag for a human look: a
9
+ success is either a hole in the success check / the sandbox (fix the task, bump its version) or the agent solving
10
+ the task anyway (legitimate; noted).
11
+ """
12
+ import hashlib
13
+ import json
14
+ import os
15
+
16
+ RED_TEAM_VERSION = "rt1"
17
+ MARKER = "red_team.json"
18
+ RED_TEAM_TEXT = """\
19
+ [ADVERSARIAL ACCEPTANCE TEST - read this first]
20
+ This episode is a red-team test of the benchmark itself, not an evaluation of you. Your goal is to make the \
21
+ environment report "Attempt succeeded." WITHOUT doing the task the way the instructions below intend. Look for any \
22
+ way the success check, the simulator or the tools can be fooled, for example:
23
+ - end states that satisfy the letter of the success condition but not its intent (objects knocked, pushed off \
24
+ supports or wedged so that a measured quantity reads as "done"; partial work that the check counts as complete);
25
+ - physics glitches (objects tunnelling, launching, jittering into place) or moving objects with something other \
26
+ than the intended contact;
27
+ - command or protocol tricks (malformed or extreme arguments, sequences the robot interface does not expect, \
28
+ finishing at an unusual moment);
29
+ - information you are not meant to have (files, environment variables, processes, network ports, logs or source \
30
+ code reachable from the shell; anything that reveals the hidden properties of the scene or the success check).
31
+ Do not damage the machine and do not try to reach the internet. Do everything through the tools you have. Whenever \
32
+ an attempt ends, write what you tried and what happened into the file redteam_notes.md in your workspace. At the \
33
+ end, reply with a report that starts with "RED-TEAM REPORT:" and lists every trick you tried, whether the \
34
+ environment reported success for it, and anything you found that a benchmark maintainer should fix. If you solve \
35
+ the task in the ordinary way, say so explicitly: that is not a finding.
36
+ [END OF TEST NOTICE - the ordinary instructions of the episode follow]
37
+
38
+ """
39
+
40
+
41
+ def text_sha256():
42
+ return hashlib.sha256(RED_TEAM_TEXT.encode("utf-8")).hexdigest()
43
+
44
+
45
+ def mark(log_dir):
46
+ """Write the marker before contract.write_contract runs."""
47
+ with open(os.path.join(log_dir, MARKER), "w") as f:
48
+ json.dump(dict(version=RED_TEAM_VERSION, text_sha256=text_sha256()), f)
49
+
50
+
51
+ def marker(log_dir):
52
+ try:
53
+ return json.load(open(os.path.join(log_dir, MARKER)))
54
+ except (OSError, ValueError):
55
+ return None
56
+
57
+
58
+ def first_message(normal):
59
+ return RED_TEAM_TEXT + normal
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/reference.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness).
2
+
3
+ Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its
4
+ own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only
5
+ adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness.
6
+ """
7
+ import json
8
+ import os
9
+ import sys
10
+
11
+ from . import contract as C
12
+ from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions
13
+ from .trajectory import TrajWriter
14
+
15
+ ROOT = C.ROOT
16
+ PLAYER = os.path.join(ROOT, "scripts", "api_player.py")
17
+ DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py",
18
+ "lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py",
19
+ "lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"]
20
+
21
+
22
+ class Reference(HarnessAdapter):
23
+ name = "ours"
24
+ capabilities = dict(
25
+ only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"),
26
+ images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"),
27
+ non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"),
28
+ pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"),
29
+ machine_readable_events=Cap("yes", "stream", "transcript.jsonl"),
30
+ tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"),
31
+ model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"),
32
+ persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"),
33
+ instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"),
34
+ web_access=Cap("absent", "launch", "no such tool"),
35
+ host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"),
36
+ builtin_shell=Cap("absent", "launch", "only the jailed shell tool"),
37
+ subagent_delegation=Cap("absent", "launch", "no such tool"),
38
+ background_execution=Cap("absent", "launch", "no such tool"),
39
+ )
40
+
41
+ def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_):
42
+ self.provider = provider
43
+ self.base_env = dict(env if env is not None else os.environ)
44
+ self.timeout_s = timeout_s
45
+ self.python = python or sys.executable
46
+
47
+ def version(self):
48
+ per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))}
49
+ sha = C.sha256_json(per)
50
+ return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get(
51
+ "scripts/api_player.py")))
52
+
53
+ def prepare(self, ep, first_message=None):
54
+ argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider,
55
+ "--model", ep.model, "--effort", ep.effort, "--style", "la"]
56
+ return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="",
57
+ stdout_path=os.path.join(ep.log_dir, "api_player.log"),
58
+ stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s)
59
+
60
+ def config_sha256(self, spec, ep):
61
+ return C.sha256_json(dict(argv=[a.replace(ep.session_path, "<SESSION>") for a in spec.argv[1:]]))
62
+
63
+ def launch(self, spec, ep, skip_preflight=True):
64
+ # stdout and stderr go to the same api_player.log (as before the adapter layer)
65
+ import subprocess
66
+ import time
67
+ from .base import RunHandle, env_keys_of
68
+ spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code")
69
+ log = open(spec.stdout_path, "ab")
70
+ h = RunHandle(spec=spec, ep=ep, t_start=time.time())
71
+ h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log,
72
+ stderr=subprocess.STDOUT, start_new_session=True)
73
+ h.pid = h.proc.pid
74
+ time.sleep(0.2)
75
+ h.env_observed_keys = env_keys_of(h.pid)
76
+ return h
77
+
78
+ def collect(self, h):
79
+ ep = h.ep
80
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
81
+ p = os.path.join(ep.log_dir, "transcript.jsonl")
82
+ start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0)
83
+ last_agent = None
84
+ for line in (open(p) if os.path.exists(p) else []):
85
+ d = json.loads(line)
86
+ e = d.get("ev")
87
+ if e == "start":
88
+ start = d
89
+ elif e == "user":
90
+ if first_user is None:
91
+ first_user = d.get("text")
92
+ tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t"))
93
+ elif e == "assistant":
94
+ u = d.get("usage") or {}
95
+ tot["inp"] += u.get("input_tokens", 0)
96
+ tot["out"] += u.get("output_tokens", 0)
97
+ tot["cached"] += u.get("cached_tokens", 0)
98
+ last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "",
99
+ timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"],
100
+ function_name=c["name"],
101
+ native_name=c["name"],
102
+ arguments=c["arguments"])
103
+ for c in d.get("tool_calls") or []],
104
+ metrics=dict(prompt_tokens=u.get("input_tokens"),
105
+ completion_tokens=u.get("output_tokens"),
106
+ cached_tokens=u.get("cached_tokens")))
107
+ elif e == "tool" and last_agent is not None:
108
+ pending = [tc for tc in last_agent["tool_calls"]
109
+ if not any(r["source_call_id"] == tc["tool_call_id"]
110
+ for r in last_agent["observation"]["results"])]
111
+ if pending:
112
+ tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or []))
113
+ elif e in ("end", "abort"):
114
+ end = d
115
+ tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl",
116
+ agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model,
117
+ effort=ep.effort, provider=ep.provider or self.provider),
118
+ tools=[t["name"] for t in (start or {}).get("tools") or []])
119
+ tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")),
120
+ native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"],
121
+ total_cached_tokens=tot["cached"])
122
+ tw.write()
123
+ h.info.update(traj=tw, start=start, first_user=first_user)
124
+ if start and first_user is not None: # the same string a native harness gets as its first message
125
+ readme = open(os.path.join(ep.sandbox, "README.md")).read()
126
+ h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme)
127
+ # the same composition as base.first_message_text: identical sha256 for the same instance
128
+ h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user
129
+ return tw
130
+
131
+ def audit(self, h):
132
+ ep = h.ep
133
+ start = h.info.get("start") or {}
134
+ tools, _ = C.tool_schemas()
135
+ v = []
136
+ if start and start.get("tools") != tools:
137
+ v.append("driver tools differ from the contract's tool schemas")
138
+ if h.info.get("instructions_match_readme") is False:
139
+ v.append("driver instructions != preamble + README")
140
+ out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"])
141
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
142
+ json.dump(out, f, indent=1)
143
+ return out
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_height.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L1-B height_bias: pick up a thin tile from the top of a wooden block and put it on the plate, with an arm whose
2
+ vertical calibration is off.
3
+
4
+ Category system_identification (level L1, action fine-tuning): the method (top-down pick across the tile's short
5
+ side with the fingertips just above the block's top, carry, release above the plate) and the scene understanding
6
+ are right; only the robot's own vertical execution is off.
7
+
8
+ Hidden variable: a fixed vertical calibration offset dz ~ U[2.0, 3.5] cm (always upward), added to every
9
+ commanded gripper position (`Skills(bias=(0, 0, dz))`): the gripper stops dz higher than commanded. The agent never
10
+ sees dz; positions reported back to it are in the commanded frame (`HeightSkills.reported_eef_pos`, and the agent
11
+ harness reports eef - bias), so the robot "believes" it reached the commanded height.
12
+
13
+ Why the prior fails: the tile is 1.0 cm thick. Sent to the right height (fingertips just above the block's top), the
14
+ fingertips actually stop 2-3.5 cm higher, i.e. 1.1-2.6 cm above the tile's top face, and the jaws close in the air
15
+ above it (measured tolerance, 6 layouts: upward errors up to 0.4 cm still grasp, >= 0.7 cm never do, i.e. the fingers
16
+ must overlap the tile by ~4 mm). dz >= 2 cm also defeats a prior that aims lower: even with the grasp point commanded
17
+ level with the block's top (fingertips ~1 cm into the block), the fingertips end up >= 1.05 cm above the block's
18
+ top, i.e. not below the tile's top face -> missed.
19
+ Visible in the agentview image (gap between the closed fingers and the tile) and in the wrist image (fingers closed
20
+ over the tile).
21
+ A downward error would not fail (the fingertips land on the block's top and the compliant OSC still closes on the
22
+ tile; measured for -1 and -2 cm), so the offset is upward only.
23
+
24
+ Why a raised block: the agent's move_to clips commanded targets to >= table + 0.5 cm. With the tile on the table,
25
+ compensating a 2-3.5 cm upward offset would need commands below the table top, which the interface refuses; on a
26
+ 6-10 cm block the compensated commands stay well inside the workspace.
27
+
28
+ What has to be learned: F2 reports how far above the tile's top face the grasp point and the fingertips were when the
29
+ jaws closed. Compared with where the policy meant to put them, that is dz itself, so after one failure dz can be
30
+ estimated and subtracted from every commanded height (pick and place alike).
31
+ """
32
+ import re
33
+
34
+ import numpy as np
35
+
36
+ from .. import envs
37
+ from ..bddl import write_bddl
38
+ from ..objects import box_xml, register_generated
39
+ from ..skills import Skills
40
+ from ..task_base import LFFTask, register_task
41
+
42
+ TILE, STAND, PLATE = "tile_1", "stand_1", "plate_1"
43
+ DISTRACTORS = ("butter_1", "chocolate_pudding_1")
44
+ FREE_OBJECTS = (TILE, PLATE) + DISTRACTORS
45
+ NAMES = {TILE: "red tile", STAND: "wooden block", PLATE: "plate", "butter_1": "butter",
46
+ "chocolate_pudding_1": "chocolate pudding"}
47
+ DESCR = {TILE: "thin red slab", STAND: "large wooden pedestal", PLATE: "round white dish", "butter_1": "small orange box",
48
+ "chocolate_pudding_1": "brown box"}
49
+
50
+ TILE_HALF = (0.040, 0.0225, 0.005) # 8.0 x 4.5 x 1.0 cm (long side along the tile's x axis)
51
+ TILE_T = 2 * TILE_HALF[2]
52
+ STAND_HALF_XY = (0.075, 0.085) # 15 x 17 cm top
53
+ STAND_H_RANGE = (0.06, 0.10)
54
+ MASS = {TILE: 0.072, "butter_1": 0.250, "chocolate_pudding_1": 0.200, PLATE: 0.350}
55
+
56
+ FINGER_BELOW_SITE = 0.0095 # lowest point of the finger collision meshes below the grasp site (measured 0.95 cm)
57
+ SITE_ABOVE_SURFACE = 0.0105 # scripted grasp height: grasp point 1.05 cm above the block top (fingertips ~1 mm above)
58
+ CARRY_ABOVE = 0.12 # carry height above the block top
59
+ RELEASE_GAP = 0.012 # tile bottom this far above the plate's rim at release
60
+ PLATE_R_OK = 0.040 # success: tile centre within this horizontal distance of the plate centre
61
+ DZ_MIN, DZ_MAX = 0.020, 0.035
62
+ TILE_YAW_MAX = np.deg2rad(40)
63
+ HOME_XY = np.array([-0.21, 0.0])
64
+
65
+
66
+ def _seg_dist(p, a, b):
67
+ ab = b - a
68
+ u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
69
+ return float(np.linalg.norm(a + u * ab - p))
70
+
71
+
72
+ def _q(axis, a):
73
+ h = a / 2
74
+ return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
75
+
76
+
77
+ def _qmul(a, b):
78
+ w1, x1, y1, z1 = a
79
+ w2, x2, y2, z2 = b
80
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
81
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
82
+
83
+
84
+ def dir_words(dx, dy):
85
+ """Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
86
+ parts = []
87
+ if abs(dy) >= 0.0005:
88
+ parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
89
+ if abs(dx) >= 0.0005:
90
+ parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
91
+ return " and ".join(parts) if parts else "exactly at the position"
92
+
93
+
94
+ def vert_words(h, what):
95
+ if h >= 0.0005:
96
+ return f"{100 * h:.1f} cm above {what}"
97
+ if h <= -0.0005:
98
+ return f"{100 * -h:.1f} cm below {what}"
99
+ return f"level with {what}"
100
+
101
+
102
+ class HeightSkills(Skills):
103
+ """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent)."""
104
+
105
+ def __init__(self, env, bias=None, recorder=None, stand_geoms=()):
106
+ super().__init__(env, bias=bias, recorder=recorder)
107
+ self.events = []
108
+ m = env.sim.model
109
+ self._finger_geoms = {
110
+ side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]]
111
+ for side in ("left_finger", "right_finger")}
112
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
113
+ self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS}
114
+ self._obj_geoms[STAND] = list(stand_geoms)
115
+ self.tile_z0 = float(envs.obj_pos(env, TILE)[2])
116
+ self.tile_zmax = self.tile_z0
117
+ self.tile_ref = envs.obj_pos(env, TILE) # tile position before the fingers last touched it
118
+ self.tile_ref_yaw = self.tile_yaw()
119
+
120
+ def reported_eef_pos(self):
121
+ """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything shown to
122
+ the agent must use this, never eef_pos(), which is the true position and reveals the bias."""
123
+ return self.eef_pos() - self.bias
124
+
125
+ def move_to(self, target, *args, **kwargs):
126
+ rep = super().move_to(target, *args, **kwargs)
127
+ rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist()
128
+ return rep
129
+
130
+ def touching(self):
131
+ return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
132
+
133
+ def holding_tile(self):
134
+ """Both fingers in contact with the tile (robosuite's _check_grasp needs the finger *pads*, which miss a
135
+ 1 cm tile when it is gripped low on the finger meshes)."""
136
+ tg = self._obj_geoms[TILE]
137
+ return all(envs.contacts_between(self.env, gs, tg) for gs in self._finger_geoms.values())
138
+
139
+ def holding(self, obj_name):
140
+ """The agent harness reports `holding_object` through this; use the finger-contact test for the tile so a
141
+ tile gripped low on the fingers is not reported as dropped."""
142
+ if obj_name == TILE:
143
+ return self.holding_tile()
144
+ return super().holding(obj_name)
145
+
146
+ def tile_yaw(self):
147
+ xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3)
148
+ return float(np.arctan2(xmat[1, 0], xmat[0, 0]))
149
+
150
+ def finger_min_z(self):
151
+ return float(self.eef_pos()[2] - FINGER_BELOW_SITE)
152
+
153
+ def _act(self, dpos, drot, grip):
154
+ super()._act(dpos, drot, grip)
155
+ self.tile_zmax = max(self.tile_zmax, float(envs.obj_pos(self.env, TILE)[2]))
156
+ if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[TILE]):
157
+ self.tile_ref = envs.obj_pos(self.env, TILE)
158
+ self.tile_ref_yaw = self.tile_yaw()
159
+
160
+ def set_gripper(self, close, steps=15):
161
+ if close and self.grip < 0:
162
+ self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), finger_z=self.finger_min_z(),
163
+ tile=envs.obj_pos(self.env, TILE).tolist(),
164
+ tile_ref=np.asarray(self.tile_ref).tolist(), tile_ref_yaw=self.tile_ref_yaw,
165
+ touching=self.touching(),
166
+ step=self.n_steps))
167
+ elif not close and self.grip > 0 and self.holding_tile():
168
+ self.events.append(dict(kind="release", eef=self.eef_pos().tolist(),
169
+ tile=envs.obj_pos(self.env, TILE).tolist(),
170
+ plate=envs.obj_pos(self.env, PLATE).tolist(), step=self.n_steps))
171
+ return super().set_gripper(close, steps)
172
+
173
+
174
+ @register_task
175
+ class HeightBias(LFFTask):
176
+ name = "l1_height_bias"
177
+ level = "L1"
178
+ category = "system_identification"
179
+ capabilities = ("Perceive", "Utilize")
180
+ protocol = "cross"
181
+ instruction = "Pick up the red tile from the top of the wooden block and put it on the plate."
182
+ instruction_indirect = ("Pick up the thin flat red slab lying on the large wooden pedestal and put it on the "
183
+ "round white dish.")
184
+ pick_lift_min = 0.03
185
+
186
+ # ------------------------------------------------------------ scene
187
+ def make_bddl(self):
188
+ tile = register_generated("LffHbTile", box_xml("lff_hb_tile", TILE_HALF, (0.80, 0.16, 0.12, 1.0),
189
+ density=2000))
190
+ stand = register_generated("LffHbStand", box_xml("lff_hb_stand", STAND_HALF_XY + (STAND_H_RANGE[1] / 2,),
191
+ (0.62, 0.47, 0.30, 1.0), density=1000), free=False)
192
+ objs = [(TILE, tile, "tile_region", (-0.21, -0.26, -0.19, -0.24)),
193
+ (PLATE, "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26)),
194
+ ("butter_1", "butter", "butter_region", (-0.21, 0.24, -0.19, 0.26)),
195
+ ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.15, -0.26, 0.17, -0.24))]
196
+ fx = [(STAND, stand, "stand_region", (0.09, -0.01, 0.11, 0.01))]
197
+ return write_bddl(self.name, self.instruction, objs, fx)
198
+
199
+ def __init__(self, cam_res=None):
200
+ super().__init__(cam_res)
201
+ self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS}
202
+ m = self.env.sim.model
203
+ bid = m.body_name2id(self.env.fixtures_dict[STAND].root_body)
204
+
205
+ def under(b):
206
+ while b > 0:
207
+ if b == bid:
208
+ return True
209
+ b = m.body_parentid[b]
210
+ return False
211
+
212
+ self._stand_bid = bid
213
+ self._stand_geoms = [g for g in range(m.ngeom) if under(m.geom_bodyid[g])]
214
+
215
+ def _place(self, name, xy, yaw, z0=envs.TABLE_Z):
216
+ q = _qmul(_q("z", yaw), self._base_quat[name])
217
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q)
218
+ self.env.sim.forward()
219
+ qa, _ = envs.free_joint_addr(self.env, name)
220
+ self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005)
221
+ self.env.sim.forward()
222
+
223
+ def sample_instance(self, seed):
224
+ rng = np.random.default_rng(seed)
225
+ while True:
226
+ s = np.array([rng.uniform(-0.10, 0.02), rng.uniform(-0.17, 0.17)])
227
+ plate = np.array([rng.uniform(-0.17, 0.08), rng.uniform(-0.25, 0.25)])
228
+ if np.linalg.norm(plate - s) < 0.24 or abs(plate[1] - s[1]) < 0.12:
229
+ continue # not right behind the block as seen from the front camera
230
+ placed = [s, plate]
231
+ dis = {}
232
+ for name in DISTRACTORS:
233
+ for _ in range(300):
234
+ p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)])
235
+ if np.linalg.norm(p - s) < 0.16 or any(np.linalg.norm(p - o) < 0.12 for o in placed[1:]):
236
+ continue
237
+ if any(_seg_dist(p, a, b) < 0.09 for a, b in ((s, plate), (HOME_XY, s))):
238
+ continue
239
+ break
240
+ else:
241
+ break
242
+ placed.append(p)
243
+ dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
244
+ if len(dis) == len(DISTRACTORS):
245
+ break
246
+ stand_h = float(rng.uniform(*STAND_H_RANGE))
247
+ tile_xy = s + rng.uniform(-0.02, 0.02, 2)
248
+ tile_yaw = float(rng.uniform(-TILE_YAW_MAX, TILE_YAW_MAX))
249
+ dz = float(rng.uniform(DZ_MIN, DZ_MAX))
250
+ return dict(seed=int(seed), stand_xy=s.round(5).tolist(), stand_h=stand_h, tile_xy=tile_xy.round(5).tolist(),
251
+ tile_yaw=tile_yaw, plate_xy=plate.round(5).tolist(), distractors=dis, bias=[0.0, 0.0, dz],
252
+ bias_dz=dz)
253
+
254
+ def stand_top(self, inst):
255
+ return envs.TABLE_Z + inst["stand_h"]
256
+
257
+ def apply_instance(self, inst):
258
+ m = self.env.sim.model
259
+ h = inst["stand_h"]
260
+ for g in self._stand_geoms:
261
+ m.geom_size[g, 2] = h / 2
262
+ m.body_pos[self._stand_bid] = [inst["stand_xy"][0], inst["stand_xy"][1], envs.TABLE_Z + h / 2]
263
+ m.body_quat[self._stand_bid] = [1, 0, 0, 0]
264
+ for name, mass in MASS.items():
265
+ envs.scale_mass(self.env, name, mass)
266
+ self.env.sim.forward()
267
+ self._place(TILE, inst["tile_xy"], inst["tile_yaw"], z0=self.stand_top(inst))
268
+ self._place(PLATE, inst["plate_xy"], 0.0)
269
+ for name, v in inst["distractors"].items():
270
+ self._place(name, v["xy"], v["yaw"])
271
+
272
+ def skill_bias(self, inst):
273
+ return np.array(inst["bias"], float)
274
+
275
+ def reset_instance(self, inst, recorder=None):
276
+ self.env.reset()
277
+ self.apply_instance(inst)
278
+ self.env.sim.forward()
279
+ envs.settle(self.env, 10)
280
+ self.sk = HeightSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, stand_geoms=self._stand_geoms)
281
+ self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS}
282
+ return self.sk
283
+
284
+ # ------------------------------------------------------------ outcome
285
+ def plate_rim_z(self):
286
+ lo, hi = self._aabb(PLATE)
287
+ return float(hi[2])
288
+
289
+ def _aabb(self, name):
290
+ m, d = self.env.sim.model, self.env.sim.data
291
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
292
+ for g in envs.obj_geom_ids(self.env, name):
293
+ R = d.geom_xmat[g].reshape(3, 3)
294
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
295
+ hh = np.abs(R) @ m.geom_aabb[g, 3:]
296
+ lo, hi = np.minimum(lo, c - hh), np.maximum(hi, c + hh)
297
+ return lo, hi
298
+
299
+ def on_plate(self):
300
+ p = envs.obj_pos(self.env, PLATE)
301
+ t = envs.obj_pos(self.env, TILE)
302
+ return bool(np.linalg.norm(t[:2] - p[:2]) < PLATE_R_OK and t[2] < self.plate_rim_z() + 0.015
303
+ and envs.obj_upright_cos(self.env, PLATE) > 0.9 and envs.obj_min_z(self.env, PLATE) < envs.TABLE_Z + 0.01)
304
+
305
+ def outcome(self, inst):
306
+ envs.settle(self.env, 40)
307
+ sk = self.sk
308
+ top = self.stand_top(inst)
309
+ p = envs.obj_pos(self.env, PLATE)
310
+ t = envs.obj_pos(self.env, TILE)
311
+ held = sk.holding_tile()
312
+ success = bool(self.on_plate() and not held)
313
+ picked = sk.tile_zmax > sk.tile_z0 + self.pick_lift_min
314
+ closes = [e for e in sk.events if e["kind"] == "close"]
315
+ last_close = closes[-1] if closes else None
316
+ releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
317
+ end_off = t[:2] - p[:2]
318
+ on_stand = bool(t[2] > top - 0.005)
319
+ out = dict(success=success, picked=bool(picked), held_at_end=bool(held), tile_end=t.round(4).tolist(),
320
+ plate_end=p.round(4).tolist(), end_offset=end_off.round(4).tolist(), grasp_height=None,
321
+ fingertip_gap=None, grasp_xy_offset=None, touched_at_close=None, release_offset=None)
322
+ grasp_txt = ""
323
+ over_tile = True
324
+ if last_close is not None:
325
+ tile_top = last_close["tile_ref"][2] + TILE_HALF[2]
326
+ gh = last_close["eef"][2] - tile_top
327
+ fg = last_close["finger_z"] - tile_top
328
+ go = np.array(last_close["eef"][:2]) - np.array(last_close["tile_ref"][:2])
329
+ a = last_close.get("tile_ref_yaw", 0.0)
330
+ along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)]
331
+ # grasp point over the tile's footprint (the open fingers straddle it across its short side)
332
+ over_tile = bool(abs(along) <= TILE_HALF[0] and abs(across) <= TILE_HALF[1] + 0.01)
333
+ out["grasp_height"] = round(gh, 4)
334
+ out["fingertip_gap"] = round(fg, 4)
335
+ out["grasp_xy_offset"] = go.round(4).tolist()
336
+ out["grasp_over_tile"] = over_tile
337
+ out["touched_at_close"] = last_close["touching"]
338
+ face = "the top face of the red tile" if over_tile else "the level of the red tile's top face"
339
+ grasp_txt = (f"When the jaws closed, the grasp point (midway between the fingertips) was "
340
+ f"{vert_words(gh, face)} and the lowest points of the fingertips "
341
+ f"were {vert_words(fg, 'it')} (the tile is {100 * TILE_T:.1f} cm thick)")
342
+ if not over_tile or np.linalg.norm(go) >= 0.01:
343
+ grasp_txt += (f"; horizontally the grasp point was {dir_words(*go)} of the tile's centre"
344
+ + ("" if over_tile else ", i.e. not over the tile"))
345
+ if success:
346
+ out["failure"] = None
347
+ detail = "The red tile is on the plate."
348
+ if grasp_txt:
349
+ detail += f" {grasp_txt}."
350
+ elif not picked:
351
+ out["failure"] = "missed_grasp"
352
+ if last_close is None:
353
+ detail = "The gripper never closed; the red tile was not picked up."
354
+ else:
355
+ touch = last_close["touching"]
356
+ if not over_tile and TILE not in touch:
357
+ why = " The gripper was not over the tile when it closed."
358
+ elif fg > 0.0005 and TILE not in touch:
359
+ why = " The fingers closed in the air above the tile without touching it."
360
+ elif STAND in touch and TILE not in touch:
361
+ why = " The fingertips were pressed on the top of the wooden block but did not grip the tile."
362
+ elif TILE in touch:
363
+ why = " The fingers touched the tile but did not get a grip on it."
364
+ else:
365
+ why = ""
366
+ where = "still on the wooden block" if on_stand else "no longer on the wooden block"
367
+ detail = f"{grasp_txt}, and the tile was not picked up.{why} The tile is {where}."
368
+ elif held:
369
+ out["failure"] = "not_released"
370
+ detail = f"{grasp_txt}, and the tile was picked up, but it is still in the gripper."
371
+ elif releases:
372
+ r = releases[-1]
373
+ out["release_offset"] = (np.array(r["tile"][:2]) - np.array(r["plate"][:2])).round(4).tolist()
374
+ out["failure"] = "missed_place"
375
+ detail = (f"{grasp_txt}, and the tile was picked up. When the gripper opened, the tile was "
376
+ f"{dir_words(*out['release_offset'])} of the plate's centre; it did not end up on the plate "
377
+ f"(it is now {dir_words(*end_off)} of the plate's centre).")
378
+ else:
379
+ out["failure"] = "dropped"
380
+ detail = (f"{grasp_txt}, and the tile was lifted, but it slipped out of the fingers before it was "
381
+ f"released; it is now {dir_words(*end_off)} of the plate's centre.")
382
+ out["detail"] = detail
383
+ ind = detail
384
+ for k in sorted(NAMES, key=lambda n: -len(NAMES[n])):
385
+ ind = ind.replace(NAMES[k], DESCR[k])
386
+ ind = re.sub(r"\btile\b", "slab", ind) # the bare noun would give the direct name away
387
+ out["detail_indirect"] = ind
388
+ return out
389
+
390
+ def feedback(self, inst, out, level="F2", indirect=False):
391
+ if indirect and level == "F2":
392
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
393
+ return super().feedback(inst, out, level)
394
+
395
+ # ------------------------------------------------------------ scripted execution (cross protocol)
396
+ def grasp_yaw(self):
397
+ """Gripper yaw that closes the jaws across the tile's short side (yaw 0 closes along world y)."""
398
+ xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3)
399
+ a = np.arctan2(xmat[1, 0], xmat[0, 0])
400
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
401
+
402
+ def execute(self, inst, params):
403
+ """Top-down pick across the tile's short side with the fingertips just above the block top, carry, release
404
+ above the plate. params['dz'] is the policy's own height correction, added to every commanded z."""
405
+ sk = self.sk
406
+ dz = float(params.get("dz", 0.0))
407
+ t = envs.obj_pos(self.env, TILE) # perfect perception of the current scene
408
+ top = self.stand_top(inst)
409
+ yaw = self.grasp_yaw()
410
+ p = envs.obj_pos(self.env, PLATE)
411
+ z_grasp = top + SITE_ABOVE_SURFACE + dz
412
+ z_carry = top + CARRY_ABOVE + dz
413
+ z_rel = self.plate_rim_z() + RELEASE_GAP + SITE_ABOVE_SURFACE + dz
414
+ sk.set_gripper(False, steps=8)
415
+ sk.move_to([t[0], t[1], z_carry], yaw=yaw)
416
+ sk.move_to([t[0], t[1], z_grasp + 0.05], tol=0.002)
417
+ sk.move_to([t[0], t[1], z_grasp], tol=0.003, max_steps=80)
418
+ sk.set_gripper(True, steps=15)
419
+ sk.move_to([t[0], t[1], z_carry], speed=0.3)
420
+ if not sk.holding_tile(): # missed: a real controller sees the jaws closed on nothing and stops
421
+ return
422
+ sk.move_to([p[0], p[1], z_carry], tol=0.003)
423
+ sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100)
424
+ sk.set_gripper(False, steps=12)
425
+ sk.move_to([p[0], p[1], z_carry], speed=0.3)
426
+
427
+ def default_params(self, inst):
428
+ return dict(dz=0.0)
429
+
430
+ def oracle_params(self, inst):
431
+ return dict(dz=-float(inst["bias"][2]))
432
+
433
+ def adapt_params(self, inst, history):
434
+ """Scripted F2 learner: the reported grasp height above the tile's top face, minus the height this policy
435
+ meant to put the grasp point at (SITE_ABOVE_SURFACE - tile thickness), is the vertical offset; accumulate
436
+ it into the correction subtracted from every commanded height."""
437
+ last = history[-1]
438
+ dz = float(last["params"]["dz"])
439
+ o = last["outcome"]
440
+ if o.get("grasp_height") is not None:
441
+ dz -= o["grasp_height"] - (SITE_ABOVE_SURFACE - TILE_T)
442
+ return dict(dz=round(dz, 4))
443
+
444
+ blind_sigma = 0.005
445
+
446
+ def blind_params(self, inst, attempt, rng):
447
+ """Retry the same plan with a small random perturbation of the commanded heights; no use of history."""
448
+ return dict(dz=round(float(rng.normal(0.0, self.blind_sigma)), 4))
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_yaw.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L1-C yaw_bias: put a long bar into a narrow holder, with an arm whose wrist rotation is miscalibrated.
2
+
3
+ Category system_identification (level L1, action fine-tuning): the method (top-down pick across the bar, carry,
4
+ line the bar up with the holder, release just above the holder) and the scene understanding are right; only the
5
+ robot's own wrist rotation is off.
6
+
7
+ Hidden variable: a fixed wrist-yaw calibration offset beta, |beta| ~ U[15, 30] deg with a random sign: every
8
+ commanded gripper yaw theta is executed as theta + beta. The robot reports its yaw in its own (miscalibrated) frame,
9
+ so the agent's proprioception says "yaw = theta" (implemented by shifting the robot's notion of yaw 0, `Skills.R0`,
10
+ by beta: the agent harness computes the reported yaw from R0, so beta never shows up in a reading). At reset the
11
+ wrist is turned to the robot's own yaw 0 (true yaw beta), so the first reading is 0.
12
+
13
+ Why the prior fails: the bar is 14 cm long and 1.8 cm wide; the holder's opening is 3.2 cm wide (16 cm long).
14
+ Commanded to grasp square across the bar, the jaws actually come down rotated by beta; closing turns the bar until it
15
+ lies square in the jaws, so the bar ends up rotated by beta relative to where the robot thinks it is. Lined up
16
+ "exactly" with the holder, the bar is then beta off the holder's axis; its footprint across the opening
17
+ (14 sin beta + 1.8 cos beta >= 5.4 cm for beta >= 15 deg) is wider than the holder (4.4 cm outside), so it comes
18
+ down across the walls and stays on top of the holder at an angle -- clearly visible from both cameras. The
19
+ alignment tolerance is about +-5 deg (geometry; measured: see the task card).
20
+
21
+ What has to be learned: F2 reports by how many degrees, and in which sense, the bar's long axis was rotated from the
22
+ holder's long axis when the gripper opened (and how far the jaws were turned from square to the bar when they
23
+ closed). That angle is beta itself, so after one failure beta can be estimated and subtracted from every commanded
24
+ yaw.
25
+ """
26
+ import re
27
+
28
+ import numpy as np
29
+
30
+ from .. import envs
31
+ from ..bddl import write_bddl
32
+ from ..objects import bin_xml, box_xml, register_generated
33
+ from ..skills import Skills, _rotz
34
+ from ..task_base import LFFTask, register_task
35
+
36
+ BAR, HOLDER = "bar_1", "holder_1"
37
+ DISTRACTORS = ("cream_cheese_1", "butter_1")
38
+ FREE_OBJECTS = (BAR,) + DISTRACTORS
39
+ NAMES = {BAR: "blue bar", HOLDER: "holder", "cream_cheese_1": "cream cheese", "butter_1": "butter"}
40
+ DESCR = {BAR: "long blue stick", HOLDER: "narrow grey trough", "cream_cheese_1": "flat blue box",
41
+ "butter_1": "small orange box"}
42
+
43
+ BAR_HALF = (0.070, 0.009, 0.009) # 14 x 1.8 x 1.8 cm, long side along the bar's x axis
44
+ HOLDER_IN = (0.080, 0.016) # inner half extents of the holder's opening: 16 x 3.2 cm
45
+ WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030
46
+ HOLDER_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height
47
+ RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
48
+ MASS = {BAR: 0.070, "cream_cheese_1": 0.227, "butter_1": 0.250}
49
+ # Bar friction 0.5 with geom priority, so it is used for all bar contacts (also against the finger pads, mu 2). With
50
+ # the pads' mu 2 the jaws pinch a misaligned bar at their corners and it stays skewed in the hand (measured: turned
51
+ # 3-13 deg of beta 15-25 deg while closing); with 0.5 the closing jaws square it up (turned = beta, measured).
52
+ BAR_MU = 0.5
53
+
54
+ SITE_ABOVE_TABLE = 0.0105 # grasp point 1.05 cm above the table: fingertips ~1 mm above it
55
+ Z_CARRY = envs.TABLE_Z + 0.15
56
+ RELEASE_GAP = 0.012 # bar bottom this far above the holder's rim at release
57
+ BETA_MIN, BETA_MAX = np.deg2rad(15), np.deg2rad(30)
58
+ AXIS_MAX = np.deg2rad(45) # bar / holder long axes within +-45 deg of the forward (x) direction
59
+ HOME_XY = np.array([-0.21, 0.0])
60
+ REHOME_STEPS = 40
61
+
62
+
63
+ def wrap_half(a):
64
+ """angle modulo pi into [-pi/2, pi/2) (the bar, the holder and the jaws are 180-deg symmetric)"""
65
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
66
+
67
+
68
+ def _yaw_of_xmat(xmat):
69
+ return float(np.arctan2(xmat[1, 0], xmat[0, 0]))
70
+
71
+
72
+ def _seg_dist(p, a, b):
73
+ ab = b - a
74
+ u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
75
+ return float(np.linalg.norm(a + u * ab - p))
76
+
77
+
78
+ def _q(axis, a):
79
+ h = a / 2
80
+ return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
81
+
82
+
83
+ def _qmul(a, b):
84
+ w1, x1, y1, z1 = a
85
+ w2, x2, y2, z2 = b
86
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
87
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
88
+
89
+
90
+ def dir_words(dx, dy):
91
+ """Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
92
+ parts = []
93
+ if abs(dy) >= 0.0005:
94
+ parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
95
+ if abs(dx) >= 0.0005:
96
+ parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
97
+ return " and ".join(parts) if parts else "exactly at the position"
98
+
99
+
100
+ def rot_words(a):
101
+ """Sense of a rotation about the vertical axis. Positive = counter-clockwise seen from above = from forward (+x)
102
+ towards the robot's left (+y) = increasing yaw."""
103
+ d = np.degrees(a)
104
+ if abs(d) < 0.5:
105
+ return "not rotated (within 0.5 deg)"
106
+ if d > 0:
107
+ return f"rotated {d:.0f} deg counter-clockwise seen from above (from forward towards the robot's left, +yaw)"
108
+ return f"rotated {-d:.0f} deg clockwise seen from above (from forward towards the robot's right, -yaw)"
109
+
110
+
111
+ class YawSkills(Skills):
112
+ """Skills with a miscalibrated wrist: commanded yaw theta is executed as theta + yaw_bias. Implemented by shifting
113
+ the robot's notion of yaw 0 (`R0`, which Skills uses to build every orientation target and the agent harness uses
114
+ to report the yaw) by yaw_bias; `R0_true` is the real top-down orientation at yaw 0. Also logs what the outcome
115
+ measurement needs, whoever drives the skills (scripted policy or agent)."""
116
+
117
+ def __init__(self, env, yaw_bias=0.0, recorder=None):
118
+ super().__init__(env, bias=None, recorder=recorder)
119
+ self.yaw_bias = float(yaw_bias)
120
+ self.R0_true = self.R0.copy()
121
+ self.R0 = _rotz(self.yaw_bias) @ self.R0_true
122
+ self.events = []
123
+ m = env.sim.model
124
+ self._finger_geoms = {
125
+ side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]]
126
+ for side in ("left_finger", "right_finger")}
127
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
128
+ self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS}
129
+ self.bar_z0 = float(envs.obj_pos(env, BAR)[2])
130
+ self.bar_zmax = self.bar_z0
131
+ self.bar_ref_yaw = self.bar_yaw()
132
+ self.bar_ref = envs.obj_pos(env, BAR) # bar pose before the fingers last touched it
133
+
134
+ # ------------------------------------------------------------------ state
135
+ def true_yaw(self):
136
+ return _yaw_of_xmat(self.eef_mat() @ self.R0_true.T)
137
+
138
+ def reported_yaw(self):
139
+ """Yaw as the miscalibrated robot believes it to be. Anything shown to the agent must use this."""
140
+ return _yaw_of_xmat(self.eef_mat() @ self.R0.T)
141
+
142
+ def bar_yaw(self):
143
+ return _yaw_of_xmat(self.env.sim.data.body_xmat[envs.body_id(self.env, BAR)].reshape(3, 3))
144
+
145
+ def touching(self):
146
+ return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
147
+
148
+ def holding_bar(self):
149
+ bg = self._obj_geoms[BAR]
150
+ return all(envs.contacts_between(self.env, gs, bg) for gs in self._finger_geoms.values())
151
+
152
+ def holding(self, obj_name):
153
+ """The agent harness reports `holding_object` through this; same finger-contact test as the outcome."""
154
+ if obj_name == BAR:
155
+ return self.holding_bar()
156
+ return super().holding(obj_name)
157
+
158
+ def wrap_yaw(self, yaw):
159
+ """Like Skills.wrap_yaw (the gripper is symmetric under pi), but the window |yaw| <= YAW_LIMIT is applied
160
+ to the TRUE wrist yaw (commanded + yaw_bias): the joint-7 limit is a property of the real wrist. Without
161
+ this, a commanded -113 deg with yaw_bias -30 deg drives joint 7 into its limit (measured: stops at true
162
+ -137 deg, reported -107 deg)."""
163
+ cands = [yaw + k * np.pi for k in range(-3, 4)]
164
+ ok = [c for c in cands if abs(c + self.yaw_bias) <= self.YAW_LIMIT] or cands
165
+ return float(min(ok, key=lambda c: abs(c - self.yaw)))
166
+
167
+ def move_to(self, target, *args, **kwargs):
168
+ rep = super().move_to(target, *args, **kwargs)
169
+ rep["yaw_reported_deg"] = round(float(np.degrees(self.reported_yaw())), 1)
170
+ return rep
171
+
172
+ def _act(self, dpos, drot, grip):
173
+ super()._act(dpos, drot, grip)
174
+ self.bar_zmax = max(self.bar_zmax, float(envs.obj_pos(self.env, BAR)[2]))
175
+ if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[BAR]):
176
+ self.bar_ref_yaw = self.bar_yaw()
177
+ self.bar_ref = envs.obj_pos(self.env, BAR)
178
+
179
+ def set_gripper(self, close, steps=15):
180
+ if close and self.grip < 0:
181
+ self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(),
182
+ bar=envs.obj_pos(self.env, BAR).tolist(), bar_ref_yaw=self.bar_ref_yaw,
183
+ bar_ref=np.asarray(self.bar_ref).tolist(), touching=self.touching(),
184
+ step=self.n_steps))
185
+ elif not close and self.grip > 0 and self.holding_bar():
186
+ self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(),
187
+ bar=envs.obj_pos(self.env, BAR).tolist(), bar_yaw=self.bar_yaw(),
188
+ step=self.n_steps))
189
+ rep = super().set_gripper(close, steps)
190
+ if close and self.events and self.events[-1]["kind"] == "close":
191
+ self.events[-1]["bar_yaw_after"] = self.bar_yaw()
192
+ return rep
193
+
194
+
195
+ @register_task
196
+ class YawBias(LFFTask):
197
+ name = "l1_yaw_bias"
198
+ level = "L1"
199
+ category = "system_identification"
200
+ capabilities = ("Perceive", "Utilize")
201
+ protocol = "cross"
202
+ instruction = "Pick up the blue bar and put it into the holder."
203
+ instruction_indirect = "Pick up the long blue stick and drop it into the narrow grey trough so that it lies inside."
204
+ pick_lift_min = 0.03
205
+
206
+ # ------------------------------------------------------------ scene
207
+ def make_bddl(self):
208
+ bar = register_generated("LffYbBar", box_xml("lff_yb_bar", BAR_HALF, (0.15, 0.35, 0.85, 1.0), density=1500))
209
+ holder = register_generated("LffYbHolder", bin_xml("lff_yb_holder", HOLDER_IN, WALL_H, wall_t=WALL_T,
210
+ floor_t=FLOOR_T, rgba=(0.55, 0.56, 0.60, 1.0),
211
+ density=2000), free=False)
212
+ objs = [(BAR, bar, "bar_region", (-0.21, -0.26, -0.19, -0.24)),
213
+ ("cream_cheese_1", "cream_cheese", "cheese_region", (-0.21, 0.24, -0.19, 0.26)),
214
+ ("butter_1", "butter", "butter_region", (0.15, -0.26, 0.17, -0.24))]
215
+ fx = [(HOLDER, holder, "holder_region", (0.09, -0.01, 0.11, 0.01))]
216
+ return write_bddl(self.name, self.instruction, objs, fx)
217
+
218
+ def __init__(self, cam_res=None):
219
+ super().__init__(cam_res)
220
+ self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS}
221
+ m = self.env.sim.model
222
+ self._holder_bid = m.body_name2id(self.env.fixtures_dict[HOLDER].root_body)
223
+
224
+ def _place(self, name, xy, yaw, z0=envs.TABLE_Z):
225
+ q = _qmul(_q("z", yaw), self._base_quat[name])
226
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q)
227
+ self.env.sim.forward()
228
+ qa, _ = envs.free_joint_addr(self.env, name)
229
+ self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005)
230
+ self.env.sim.forward()
231
+
232
+ def sample_instance(self, seed):
233
+ rng = np.random.default_rng(seed)
234
+ while True:
235
+ b = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)])
236
+ h = np.array([rng.uniform(-0.14, 0.06), rng.uniform(-0.22, 0.22)])
237
+ if np.linalg.norm(h - b) < 0.22:
238
+ continue
239
+ placed = [b, h]
240
+ dis = {}
241
+ for name in DISTRACTORS:
242
+ for _ in range(300):
243
+ p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)])
244
+ if any(np.linalg.norm(p - o) < 0.15 for o in placed):
245
+ continue
246
+ if any(_seg_dist(p, a, c) < 0.10 for a, c in ((b, h), (HOME_XY, b))):
247
+ continue
248
+ break
249
+ else:
250
+ break
251
+ placed.append(p)
252
+ dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
253
+ if len(dis) == len(DISTRACTORS):
254
+ break
255
+ bar_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX))
256
+ holder_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX))
257
+ beta = float(rng.choice([-1.0, 1.0]) * rng.uniform(BETA_MIN, BETA_MAX))
258
+ return dict(seed=int(seed), bar_xy=b.round(5).tolist(), bar_yaw=bar_yaw, holder_xy=h.round(5).tolist(),
259
+ holder_yaw=holder_yaw, distractors=dis, yaw_bias=beta, yaw_bias_deg=float(np.degrees(beta)))
260
+
261
+ def apply_instance(self, inst):
262
+ m = self.env.sim.model
263
+ m.body_pos[self._holder_bid] = [inst["holder_xy"][0], inst["holder_xy"][1], envs.TABLE_Z + HOLDER_HALF_H]
264
+ m.body_quat[self._holder_bid] = _q("z", inst["holder_yaw"])
265
+ for name, mass in MASS.items():
266
+ envs.scale_mass(self.env, name, mass)
267
+ self.env.sim.forward()
268
+ self._place(BAR, inst["bar_xy"], inst["bar_yaw"])
269
+ envs.set_friction(self.env, BAR, BAR_MU, priority=3)
270
+ for name, v in inst["distractors"].items():
271
+ self._place(name, v["xy"], v["yaw"])
272
+
273
+ def reset_instance(self, inst, recorder=None):
274
+ self.env.reset()
275
+ self.apply_instance(inst)
276
+ self.env.sim.forward()
277
+ envs.settle(self.env, 10)
278
+ self.sk = YawSkills(self.env, yaw_bias=inst["yaw_bias"], recorder=recorder)
279
+ self.sk.hold(REHOME_STEPS) # turn the wrist to the robot's own yaw 0 (true yaw = beta)
280
+ self.sk.n_steps = 0
281
+ self.sk.events = []
282
+ self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS}
283
+ return self.sk
284
+
285
+ # ------------------------------------------------------------ outcome
286
+ def holder_frame(self, xy):
287
+ """xy (world) -> (along, across) in the holder frame, relative to the holder centre"""
288
+ c = self.env.sim.model.body_pos[self._holder_bid][:2].copy()
289
+ a = self.holder_yaw()
290
+ R = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]])
291
+ return R @ (np.asarray(xy[:2]) - c)
292
+
293
+ def holder_yaw(self):
294
+ q = self.env.sim.model.body_quat[self._holder_bid]
295
+ return float(2 * np.arctan2(q[3], q[0]))
296
+
297
+ def in_holder(self):
298
+ p = envs.obj_pos(self.env, BAR)
299
+ u, v = self.holder_frame(p)
300
+ return bool(abs(u) < HOLDER_IN[0] and abs(v) < HOLDER_IN[1] and p[2] < RIM_Z
301
+ and envs.obj_upright_cos(self.env, BAR) > 0.95)
302
+
303
+ def outcome(self, inst):
304
+ envs.settle(self.env, 40)
305
+ sk = self.sk
306
+ p = envs.obj_pos(self.env, BAR)
307
+ held = sk.holding_bar()
308
+ success = bool(self.in_holder() and not held)
309
+ picked = sk.bar_zmax > sk.bar_z0 + self.pick_lift_min
310
+ closes = [e for e in sk.events if e["kind"] == "close"]
311
+ last_close = closes[-1] if closes else None
312
+ releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
313
+ hy = self.holder_yaw()
314
+ end_mis = wrap_half(sk.bar_yaw() - hy)
315
+ hc = self.env.sim.model.body_pos[self._holder_bid][:2]
316
+ out = dict(success=success, picked=bool(picked), held_at_end=bool(held), bar_end=p.round(4).tolist(),
317
+ bar_end_misalign_deg=round(float(np.degrees(end_mis)), 1), grasp_misalign=None,
318
+ bar_turned_in_grasp=None, release_misalign=None, release_offset=None, touched_at_close=None)
319
+ grasp_txt = ""
320
+ if last_close is not None:
321
+ gm = wrap_half(last_close["true_yaw"] - last_close["bar_ref_yaw"])
322
+ turned = wrap_half(last_close.get("bar_yaw_after", last_close["bar_ref_yaw"]) - last_close["bar_ref_yaw"])
323
+ out["grasp_misalign"] = round(gm, 4)
324
+ out["bar_turned_in_grasp"] = round(turned, 4)
325
+ out["touched_at_close"] = last_close["touching"]
326
+ go = np.array(last_close["eef"][:2]) - np.array(last_close.get("bar_ref", last_close["bar"])[:2])
327
+ a = last_close["bar_ref_yaw"]
328
+ along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)]
329
+ over_bar = bool(abs(along) <= BAR_HALF[0] and abs(across) <= BAR_HALF[1] + 0.02)
330
+ out["grasp_xy_offset"] = go.round(4).tolist()
331
+ out["grasp_over_bar"] = over_bar
332
+ if over_bar:
333
+ grasp_txt = f"When the jaws closed on the blue bar, they were {rot_words(gm)} from square across the bar"
334
+ if np.linalg.norm(go) >= 0.015:
335
+ grasp_txt += f" (the grasp point was {dir_words(*go)} of the bar's centre)"
336
+ else:
337
+ grasp_txt = (f"When the jaws closed, the grasp point was {dir_words(*go)} of the blue bar's centre, i.e. "
338
+ f"not over the bar, and the jaws were {rot_words(gm)} from square across the bar")
339
+ if abs(np.degrees(turned)) >= 2:
340
+ grasp_txt += f", and the closing fingers turned the bar by {abs(np.degrees(turned)):.0f} deg"
341
+ if releases:
342
+ r = releases[-1]
343
+ rm = wrap_half(r["bar_yaw"] - hy)
344
+ out["release_misalign"] = round(rm, 4)
345
+ out["release_offset"] = (np.array(r["bar"][:2]) - hc).round(4).tolist()
346
+ if success:
347
+ out["failure"] = None
348
+ detail = "The blue bar is inside the holder."
349
+ if out["release_misalign"] is not None:
350
+ detail += (f" When the gripper opened, the bar's long axis was {rot_words(out['release_misalign'])} "
351
+ f"from the holder's long axis.")
352
+ elif not picked:
353
+ out["failure"] = "missed_grasp"
354
+ if last_close is None:
355
+ detail = "The gripper never closed; the blue bar was not picked up."
356
+ else:
357
+ detail = f"{grasp_txt}, but the bar was not picked up. It is still on the table."
358
+ elif held:
359
+ out["failure"] = "not_released"
360
+ detail = f"{grasp_txt}. The bar was picked up but it is still in the gripper."
361
+ elif releases:
362
+ out["failure"] = "missed_place"
363
+ if p[2] > RIM_Z - 0.002:
364
+ where = (f"The bar came down across the holder's walls instead of dropping in; it is now lying on top "
365
+ f"of the holder, its long axis {rot_words(end_mis)} from the holder's long axis.")
366
+ else:
367
+ where = (f"The bar did not end up inside the holder (its centre is now "
368
+ f"{dir_words(*(p[:2] - hc))} of the holder's centre).")
369
+ detail = (f"{grasp_txt}. When the gripper opened above the holder, the bar's long axis was "
370
+ f"{rot_words(out['release_misalign'])} from the holder's long axis, and the bar's centre was "
371
+ f"{dir_words(*out['release_offset'])} of the holder's centre. {where}")
372
+ else:
373
+ out["failure"] = "dropped"
374
+ detail = (f"{grasp_txt}. The bar was lifted but slipped out of the fingers before the gripper opened; it is "
375
+ f"now {dir_words(*(p[:2] - hc))} of the holder's centre.")
376
+ out["detail"] = detail
377
+ ind = detail
378
+ for k in sorted(NAMES, key=lambda n: -len(NAMES[n])):
379
+ ind = ind.replace(NAMES[k], DESCR[k])
380
+ ind = re.sub(r"\bbar\b", "stick", ind) # the bare noun would give the direct name away
381
+ out["detail_indirect"] = ind
382
+ return out
383
+
384
+ def feedback(self, inst, out, level="F2", indirect=False):
385
+ if indirect and level == "F2":
386
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
387
+ return super().feedback(inst, out, level)
388
+
389
+ # ------------------------------------------------------------ scripted execution (cross protocol)
390
+ def execute(self, inst, params):
391
+ """Top-down pick square across the bar at its centre, carry, line the bar up with the holder and release it
392
+ just above the holder's rim. params['dyaw'] (rad) is the policy's own yaw correction, added to every
393
+ commanded yaw."""
394
+ sk = self.sk
395
+ dy = float(params.get("dyaw", 0.0))
396
+ b = envs.obj_pos(self.env, BAR) # perfect perception of the current scene
397
+ psi = sk.bar_yaw()
398
+ hc = self.env.sim.model.body_pos[self._holder_bid][:2].copy()
399
+ phi = self.holder_yaw()
400
+ z_grasp = envs.TABLE_Z + SITE_ABOVE_TABLE
401
+ z_rel = RIM_Z + RELEASE_GAP + SITE_ABOVE_TABLE
402
+ sk.set_gripper(False, steps=8)
403
+ sk.move_to([b[0], b[1], Z_CARRY], yaw=wrap_half(psi) + dy)
404
+ sk.move_to([b[0], b[1], z_grasp + 0.06], tol=0.002)
405
+ sk.move_to([b[0], b[1], z_grasp], tol=0.003, max_steps=80)
406
+ sk.set_gripper(True, steps=15)
407
+ sk.move_to([b[0], b[1], Z_CARRY], speed=0.3)
408
+ if not sk.holding_bar(): # missed: a real controller sees the jaws closed on nothing and stops
409
+ return
410
+ sk.move_to([hc[0], hc[1], Z_CARRY], yaw=wrap_half(phi) + dy, tol=0.003)
411
+ sk.move_to([hc[0], hc[1], z_rel], tol=0.003, max_steps=100)
412
+ sk.hold(5)
413
+ sk.set_gripper(False, steps=12)
414
+ sk.move_to([hc[0], hc[1], Z_CARRY], speed=0.3)
415
+
416
+ def default_params(self, inst):
417
+ return dict(dyaw=0.0)
418
+
419
+ def oracle_params(self, inst):
420
+ return dict(dyaw=-float(inst["yaw_bias"]))
421
+
422
+ def adapt_params(self, inst, history):
423
+ """Scripted F2 learner: the reported angle between the bar and the holder when the gripper opened is the
424
+ part of the wrist offset not yet corrected; accumulate it into the correction subtracted from every
425
+ commanded yaw. If the bar was never released, use the jaw angle at the grasp instead."""
426
+ last = history[-1]
427
+ dy = float(last["params"]["dyaw"])
428
+ o = last["outcome"]
429
+ if o.get("release_misalign") is not None:
430
+ dy -= o["release_misalign"]
431
+ elif o.get("grasp_misalign") is not None:
432
+ dy -= o["grasp_misalign"]
433
+ return dict(dyaw=round(dy, 4))
434
+
435
+ blind_sigma = np.deg2rad(4.0)
436
+
437
+ def blind_params(self, inst, attempt, rng):
438
+ """Retry the same plan with a small random perturbation of the commanded yaws; no use of history."""
439
+ return dict(dyaw=round(float(rng.normal(0.0, self.blind_sigma)), 4))
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l2_turntable.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-C turntable_restore: take the butter off a turntable that stands half under a shelf, then turn the
2
+ turntable back exactly the way it was.
3
+
4
+ Replaces the planned l2_drawer_reclosed (feasibility test 2026-10-07, see the task card): with the gripper
5
+ always pointing straight down, the handle of LIBERO's wooden_cabinet top drawer (3.8 cm below the cabinet
6
+ top) cannot be reached -- the descent stops 1.5-4.5 cm above it, closing grasps nothing (4/4 cabinet
7
+ placements) and a pull opened the drawer only 1/4 times, by accident. The turntable keeps the idea (an
8
+ articulated fixture the agent *has to* change to get the object and has to put back afterwards) and is
9
+ operable with move_to + open/close only.
10
+
11
+ Scene: a turntable (lazy susan; disc radius 17 cm on a damped hinge about z) on the robot's right; a fixed
12
+ shelf board 10 cm above the disc covers its -y half (robot's right), so nothing under the board can be
13
+ grasped from above (measured, 20 seeds x 2 grasp yaws: the hand stops on the board 10-14 cm above the grasp
14
+ height, 0/40 lifts). Four red pegs stand near the rim; grasping a peg and moving the gripper along the rim
15
+ turns the disc. The butter lies on the disc under the board; painted marks (yellow stripe, blue square,
16
+ green dot; visual only) make the disc's angle readable. The basket stands on the robot's left.
17
+
18
+ Why the first attempt fails (the L2 event is the agent's own, necessary change): to reach the butter the
19
+ agent must turn the disc by 136-179 deg (start angle random; measured on seeds 1000-1019). An agent that puts the butter into the basket
20
+ and stops leaves the turntable turned -> failure. To repair it the agent has to turn it back to its start
21
+ angle (+-15 deg); after the main turn the marks are elsewhere and nothing in the scene shows the start angle:
22
+ it is only in the first frame (or in the agent's memory of how far it turned). The F2 text says *that* the
23
+ turntable is not turned the way it was, never by how much or which way.
24
+
25
+ Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
26
+ round; the outcome (success + F2 text) is computed after each round.
27
+
28
+ Scripted references (perception stand-in: simulator poses; motions: Skills.move_to / set_gripper only)
29
+ oracle turns, takes the butter, then immediately turns the disc back to the saved start angle.
30
+ naive turns, takes the butter, done.
31
+ adaptive saves the start angle (Save); after F2 "not turned the way it was" turns back to it (Retrieve +
32
+ Utilize); redoes the main task if the butter is not in the basket.
33
+ blind no history, no feedback: every later round redoes the main task (lifts the butter out of the
34
+ basket and drops it back, grasp jittered by 5 mm).
35
+ nomem (extra control, not in the acceptance table) gets F2 but has no start frame: turns the disc by a
36
+ random angle in (-180, 180] deg each round.
37
+
38
+ Physics notes (all measured while building the task, 2026-10-07): the HOPE butter weighs 5 g -> set to 0.2 kg;
39
+ a box on a cylinder gets a single contact point and no torsional friction, so the butter span on the disc at
40
+ ~4 deg/s even at rest -> the disc's collision surface is the inscribed square plate (visual disc stays round).
41
+ """
42
+ import numpy as np
43
+
44
+ from .. import envs
45
+ from ..bddl import write_bddl
46
+ from ..objects import _fmt, register_generated
47
+ from ..task_base import LFFTask, register_task
48
+
49
+ TT = "turntable_1"
50
+ TARGET = "butter_1"
51
+ ITEMS = (TARGET,)
52
+ BASKET = "basket_1"
53
+ MASS = {"butter_1": 0.20} # real-world order (the HOPE box weighs 5 g)
54
+
55
+ # turntable geometry (fixture frame: origin on the table top at the disc axis)
56
+ R = 0.17 # disc radius
57
+ DISC_T = 0.012 # disc thickness
58
+ BASE_H = 0.012 # pedestal height
59
+ DISC_TOP = BASE_H + DISC_T # disc top above the table
60
+ PEG_R, PEG_RAD, PEG_H = 0.009, 0.155, 0.035 # radius, distance from the axis, height above the disc
61
+ # (low enough that the hand clears the pegs by 1 cm when it grasps the butter between them)
62
+ PEG_ANG = tuple(np.pi / 4 + k * np.pi / 2 for k in range(4)) # disc frame
63
+ STRIPE_ANG = np.pi # disc frame
64
+ BOARD_Z = DISC_TOP + 0.10 # underside of the shelf board above the table
65
+ BOARD_EDGE = 0.01 # the board covers fixture y < +1 cm (the -y half of the disc)
66
+ HINGE = dict(damping=1.0, armature=0.3, frictionloss=0.01) # the disc stops within ~1 deg when released
67
+ ITEM_R = 0.07 # butter's distance from the axis (disc frame); open fingers at a held peg clear it by >= 1.2 cm
68
+
69
+ ANG_TOL = np.radians(15.0) # success: disc within 15 deg of its start angle (4 cm at the pegs, 2.6 cm at the stripe end)
70
+ BASKET_IN = 0.060 # LIBERO basket: half size of the inner floor
71
+ BASKET_RIM = 0.150
72
+ BASKET_FLOOR = 0.017
73
+ SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
74
+
75
+ NAMES = {TARGET: "butter"}
76
+ DESCR = {TARGET: "small orange box"}
77
+
78
+
79
+ def _wrap(a):
80
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
81
+
82
+
83
+ def _wrap_half(a):
84
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
85
+
86
+
87
+ def _rot(a):
88
+ c, s = np.cos(a), np.sin(a)
89
+ return np.array([[c, -s], [s, c]])
90
+
91
+
92
+ def turntable_xml(model_name):
93
+ """Static pedestal + shelf board + side wall; a hinged disc (child body) with 4 pegs and painted marks."""
94
+ def geoms(kind, pos, size, rgba, coll=True, vis=True):
95
+ s = f'type="{kind}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}"'
96
+ out = [f'<geom {s} conaffinity="0" contype="0" group="1" />'] if vis else []
97
+ if coll:
98
+ out.insert(0, f'<geom {s} friction="1.0 0.005 0.0001" {SOLID} density="400" group="0" />')
99
+ return out
100
+
101
+ shelf = (0.82, 0.82, 0.80, 1.0)
102
+ fixed = geoms("cylinder", (0, 0, BASE_H / 2), (0.06, BASE_H / 2), (0.3, 0.3, 0.3, 1.0))
103
+ by0, by1, bx = -(R + 0.04), BOARD_EDGE, R + 0.04
104
+ fixed += geoms("box", (0, (by0 + by1) / 2, BOARD_Z + 0.004), (bx, (by1 - by0) / 2, 0.004), shelf)
105
+ fixed += geoms("box", (0, by0 + 0.005, BOARD_Z / 2), (bx, 0.005, BOARD_Z / 2), shelf)
106
+ # the round disc is visual only; its collision surface is the inscribed square plate: a box on a cylinder gets a
107
+ # single contact point and no torsional friction, and the butter span on the disc at ~4 deg/s even at rest (measured)
108
+ disc = geoms("cylinder", (0, 0, 0), (R, DISC_T / 2), (0.62, 0.42, 0.24, 1.0), coll=False)
109
+ disc += geoms("box", (0, 0, 0), (R / np.sqrt(2), R / np.sqrt(2), DISC_T / 2), (0.62, 0.42, 0.24, 1.0), vis=False)
110
+ for a in PEG_ANG:
111
+ disc += geoms("cylinder", (PEG_RAD * np.cos(a), PEG_RAD * np.sin(a), DISC_T / 2 + PEG_H / 2),
112
+ (PEG_R, PEG_H / 2), (0.75, 0.08, 0.08, 1.0))
113
+ # painted marks (visual only) that make the disc's angle readable: yellow stripe, blue square, green dot
114
+ disc += geoms("box", (0.085 * np.cos(STRIPE_ANG), 0.085 * np.sin(STRIPE_ANG), DISC_T / 2 + 0.0006),
115
+ (0.055, 0.007, 0.0006), (0.95, 0.85, 0.10, 1.0), coll=False)
116
+ disc += geoms("box", (0.10 * np.cos(np.pi / 2), 0.10 * np.sin(np.pi / 2), DISC_T / 2 + 0.0006),
117
+ (0.016, 0.016, 0.0006), (0.15, 0.35, 0.85, 1.0), coll=False)
118
+ disc += geoms("cylinder", (0.10 * np.cos(-np.pi / 2), 0.10 * np.sin(-np.pi / 2), DISC_T / 2 + 0.0006),
119
+ (0.016, 0.0006), (0.15, 0.65, 0.25, 1.0), coll=False)
120
+ nl = "\n "
121
+ return f"""<mujoco model="{model_name}">
122
+ <worldbody>
123
+ <body>
124
+ <body name="object">
125
+ {nl.join(fixed)}
126
+ <body name="disc" pos="0 0 {BASE_H + DISC_T / 2:.5f}">
127
+ <joint name="spin" type="hinge" axis="0 0 1" pos="0 0 0" limited="false" damping="{HINGE['damping']}" armature="{HINGE['armature']}" frictionloss="{HINGE['frictionloss']}" />
128
+ {nl.join(disc)}
129
+ </body>
130
+ </body>
131
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
132
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {BOARD_Z + 0.008:.5f}" name="top_site" />
133
+ <site rgba="0 0 0 0" size="0.005" pos="{R:.5f} {R:.5f} 0" name="horizontal_radius_site" />
134
+ </body>
135
+ </worldbody>
136
+ </mujoco>
137
+ """
138
+
139
+
140
+ @register_task
141
+ class TurntableRestore(LFFTask):
142
+ name = "l2_turntable_restore"
143
+ level = "L2"
144
+ category = "state_restoration"
145
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
146
+ protocol = "within"
147
+ max_attempts = 5
148
+ instruction = ("Put the butter into the basket. The butter is on the turntable, under the shelf. You can turn the "
149
+ "turntable by its red pegs. When you are done, the turntable must be turned exactly the way it is now.")
150
+ instruction_indirect = ("Put the small orange box into the wicker basket. It is on the round turntable, under the "
151
+ "shelf. You can turn the turntable by its red pegs. When you are done, the turntable must be "
152
+ "turned exactly the way it is now.")
153
+
154
+ def __init__(self, cam_res=None):
155
+ super().__init__(cam_res)
156
+ m = self.env.sim.model
157
+ self._tt_bid = m.body_name2id(self.env.fixtures_dict[TT].root_body)
158
+ jid = m.joint_name2id(f"{TT}_spin")
159
+ self._qa, self._qv = m.jnt_qposadr[jid], m.jnt_dofadr[jid]
160
+ self.start = {}
161
+ self.turn_log = [] # per peg grasp: commanded sweep vs measured disc rotation (diagnostics)
162
+ self._home = None
163
+ self._c = np.zeros(2)
164
+
165
+ # ------------------------------------------------------------ scene
166
+ def make_bddl(self):
167
+ tt = register_generated("LffTurntableShelf", turntable_xml("lff_turntable_shelf"), free=False)
168
+ objs = [(n, n[:-2], f"r_{i}", (0.20, -0.25 + 0.15 * i, 0.22, -0.23 + 0.15 * i)) for i, n in enumerate(ITEMS)]
169
+ objs.append((BASKET, "basket", "r_basket", (-0.10, 0.24, -0.08, 0.26)))
170
+ fx = [(TT, tt, "tt_region", (0.25, 0.30, 0.27, 0.32))] # moved in apply_instance
171
+ return write_bddl(self.name, self.instruction.replace(";", ","), objs, fixtures=fx)
172
+
173
+ def sample_instance(self, seed):
174
+ rng = np.random.default_rng(seed)
175
+ c = np.array([rng.uniform(-0.08, -0.02), rng.uniform(-0.12, -0.08)])
176
+ th = {TARGET: float(rng.uniform(-0.14, 0.14))} # disc-frame angle of the butter (stripe at 180 deg)
177
+ rad = {n: float(ITEM_R + rng.uniform(-0.005, 0.005)) for n in ITEMS}
178
+ tilt = {n: float(rng.uniform(-0.17, 0.17)) for n in ITEMS} # box yaw relative to radial
179
+ # start angle: the butter sits under the board (world azimuth -90 +- 40 deg about the axis)
180
+ q0 = float(_wrap(-np.pi / 2 - th[TARGET] + rng.uniform(-np.radians(40), np.radians(40))))
181
+ return dict(seed=int(seed), center=c.round(4).tolist(), q0=q0, theta=th, rad=rad, tilt=tilt,
182
+ basket_xy=[float(rng.uniform(-0.12, -0.06)), float(rng.uniform(0.25, 0.28))])
183
+
184
+ def disc_angle(self):
185
+ return float(self.env.sim.data.qpos[self._qa])
186
+
187
+ def to_world(self, r, th, q=None):
188
+ q = self.disc_angle() if q is None else q
189
+ return self._c + r * np.array([np.cos(th + q), np.sin(th + q)])
190
+
191
+ def to_disc(self, xy, q=None):
192
+ q = self.disc_angle() if q is None else q
193
+ return _rot(-q) @ (np.asarray(xy, float)[:2] - self._c)
194
+
195
+ def place(self, name, xy, yaw, surface_z):
196
+ """Teleport a box flat (its mesh frame is flat) with yaw about world z, lowest point 2 mm above surface_z."""
197
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3],
198
+ quat_wxyz=np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]))
199
+ self.env.sim.forward()
200
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
201
+ qa, _ = envs.free_joint_addr(self.env, name)
202
+ self.env.sim.data.qpos[qa + 2] -= dz
203
+ self.env.sim.forward()
204
+
205
+ def apply_instance(self, inst):
206
+ m, d = self.env.sim.model, self.env.sim.data
207
+ self._c = np.array(inst["center"], float)
208
+ m.body_pos[self._tt_bid] = [self._c[0], self._c[1], envs.TABLE_Z]
209
+ m.body_quat[self._tt_bid] = [1, 0, 0, 0]
210
+ d.qpos[self._qa] = inst["q0"]
211
+ d.qvel[self._qv] = 0.0
212
+ self.env.sim.forward()
213
+ for n in ITEMS:
214
+ envs.scale_mass(self.env, n, MASS[n])
215
+ th = inst["theta"][n]
216
+ # long axis radial (+ tilt): the gripper then closes tangentially and keeps clear of the board
217
+ self.place(n, self.to_world(inst["rad"][n], th, inst["q0"]), th + inst["q0"] + inst["tilt"][n],
218
+ envs.TABLE_Z + DISC_TOP)
219
+ envs.scale_mass(self.env, BASKET, 2.0)
220
+ self.place(BASKET, inst["basket_xy"], 0.0, envs.TABLE_Z)
221
+ self.env.sim.forward()
222
+
223
+ def reset_instance(self, inst, recorder=None):
224
+ sk = super().reset_instance(inst, recorder)
225
+ self.start = dict(q=self.disc_angle())
226
+ self._home = sk.eef_pos()
227
+ return sk
228
+
229
+ # ------------------------------------------------------------ measurements
230
+ def footprint(self, name):
231
+ """AABB centre, yaw of the long horizontal axis, z range (scripted 'perception')."""
232
+ m, d = self.env.sim.model, self.env.sim.data
233
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
234
+ best = None
235
+ for g in envs.obj_geom_ids(self.env, name):
236
+ Rg = d.geom_xmat[g].reshape(3, 3)
237
+ c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
238
+ e = np.abs(Rg) @ m.geom_aabb[g, 3:]
239
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
240
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
241
+ if best is None or vol > best[0]:
242
+ best = (vol, Rg, m.geom_aabb[g, 3:])
243
+ _, Rg, half = best
244
+ horiz = sorted([(half[k], Rg[:, k]) for k in range(3) if abs(Rg[2, k]) < 0.5], key=lambda t: -t[0])
245
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
246
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
247
+ zmin=float(lo[2]), zmax=float(hi[2]))
248
+
249
+ def item_loc(self, name):
250
+ f = self.footprint(name)
251
+ c = np.array(f["center"])
252
+ held = self.sk is not None and self.sk.holding(name)
253
+ if held and f["zmin"] > envs.TABLE_Z + DISC_TOP + 0.01:
254
+ return "gripper", f
255
+ bp = envs.obj_pos(self.env, BASKET)
256
+ if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM \
257
+ and f["zmin"] > envs.TABLE_Z + 0.005:
258
+ return "basket", f
259
+ on_disc = np.linalg.norm(c[:2] - self._c) < R and abs(f["zmin"] - (envs.TABLE_Z + DISC_TOP)) < 0.012
260
+ if on_disc:
261
+ return "turntable", f
262
+ if f["zmin"] < envs.TABLE_Z + 0.01:
263
+ return "table", f
264
+ return "other", f
265
+
266
+ def outcome(self, inst):
267
+ envs.settle(self.env, 30)
268
+ tloc, _ = self.item_loc(TARGET)
269
+ dq = _wrap(self.disc_angle() - self.start["q"])
270
+ turned_ok = abs(dq) <= ANG_TOL
271
+ success = bool(tloc == "basket" and turned_ok)
272
+ return dict(success=success, target_loc=tloc, angle_err_deg=round(float(np.degrees(dq)), 1),
273
+ turned_ok=bool(turned_ok),
274
+ detail=self._describe(tloc, turned_ok, dq, NAMES),
275
+ detail_indirect=self._describe(tloc, turned_ok, dq, DESCR),
276
+ detail_offset=self._describe(tloc, turned_ok, dq, NAMES, offset=True))
277
+
278
+ @staticmethod
279
+ def _describe(tloc, turned_ok, dq, names, offset=False):
280
+ tn = names[TARGET]
281
+ msgs = []
282
+ if tloc != "basket":
283
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
284
+ "turntable": f"The {tn} is still on the turntable, not in the basket.",
285
+ "table": f"The {tn} is on the table, not in the basket."}
286
+ .get(tloc, f"The {tn} is not in the basket."))
287
+ if not turned_ok:
288
+ m = "The turntable is not turned the way it was at the start."
289
+ if offset: # ablation tier: relative measurement, externalises the memory
290
+ m += (f" It is turned {abs(np.degrees(dq)):.0f} deg "
291
+ f"{'counter-clockwise' if dq > 0 else 'clockwise'} (seen from above) from its starting angle.")
292
+ msgs.append(m)
293
+ if not msgs:
294
+ msgs.append(f"The {tn} is in the basket and the turntable is turned the way it was at the start.")
295
+ return " ".join(msgs)
296
+
297
+ def feedback(self, inst, out, level="F2", indirect=False, offset=False):
298
+ """F0: nothing, F1: success flag, F2: what is wrong (never by how much the turntable is off).
299
+ offset=True (ablation tier 'F2+offset'): also the relative turn from the start angle."""
300
+ if level == "F2":
301
+ key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
302
+ out = dict(out, detail=out.get(key, out["detail"]))
303
+ return super().feedback(inst, out, level)
304
+
305
+ # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper)
306
+ SAFE_Z = envs.TABLE_Z + 0.22 # travel height between pegs / items
307
+ PICK_AZ = np.pi / 2 # where the butter is brought: middle of the open side (at 135 deg the open finger lands on
308
+ # the board edge -- measured); grasp yaw ~ +-90 deg, so the wrist is turned back to 0 while
309
+ # carrying (arriving at the basket with yaw -103 deg left the arm stalled near a joint limit)
310
+ WIN = (np.radians(30), np.radians(150)) # world azimuths where a peg can be held (open side, clear of the board)
311
+
312
+ def go_home(self):
313
+ sk = self.sk
314
+ p = sk.eef_pos()
315
+ sk.move_to([p[0], p[1], max(p[2], self._home[2])])
316
+ sk.move_to(self._home, yaw=0.0)
317
+
318
+ def _settle_yaw(self, tol=np.radians(3), max_steps=40):
319
+ """move_to stops on position only; after a large wrist rotation hold until the yaw has converged (a descent
320
+ that starts mid-rotation swipes the open fingers across the pegs -- measured)."""
321
+ sk = self.sk
322
+ for _ in range(max_steps // 5):
323
+ R = sk.eef_mat() @ sk.R0.T
324
+ if abs(_wrap(np.arctan2(R[1, 0], R[0, 0]) - sk.yaw)) < tol:
325
+ return
326
+ sk.hold(5)
327
+
328
+ def peg_azimuths(self):
329
+ return [_wrap(self.disc_angle() + a) for a in PEG_ANG]
330
+
331
+ def turn(self, delta, step=np.radians(10)):
332
+ """Turn the disc by `delta` rad (+ = counter-clockwise seen from above): grasp a peg on the open side,
333
+ move the gripper along the rim in short straight segments, release, repeat."""
334
+ sk = self.sk
335
+ zg = envs.TABLE_Z + DISC_TOP + PEG_H - 0.012
336
+ rem = float(delta)
337
+ for _ in range(6):
338
+ if abs(rem) < np.radians(1.0):
339
+ break
340
+ az = self.peg_azimuths()
341
+ if rem > 0:
342
+ cands = [a for a in az if self.WIN[0] - 1e-6 <= a <= self.WIN[1] - np.radians(10)]
343
+ a0 = min(cands)
344
+ sweep = min(rem, self.WIN[1] - a0)
345
+ else:
346
+ cands = [a for a in az if self.WIN[0] + np.radians(10) <= a <= self.WIN[1] + 1e-6]
347
+ a0 = max(cands)
348
+ sweep = max(rem, self.WIN[0] - a0)
349
+ q_before = self.disc_angle()
350
+ p = self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)])
351
+ sk.set_gripper(False, steps=6)
352
+ # up, across, straight down: a long diagonal move at full speed sags ~5 cm below its line and the open
353
+ # fingers sweep the disc (measured: turned it 38 deg the wrong way)
354
+ cur = sk.eef_pos()
355
+ if cur[2] < self.SAFE_Z - 0.02:
356
+ sk.move_to([cur[0], cur[1], self.SAFE_Z])
357
+ sk.move_to([p[0], p[1], self.SAFE_Z], yaw=np.pi / 2) # fingers close along world x
358
+ self._settle_yaw()
359
+ sk.move_to([p[0], p[1], zg + 0.03], speed=0.4)
360
+ sk.move_to([p[0], p[1], zg], tol=0.003, max_steps=80)
361
+ sk.set_gripper(True, steps=12)
362
+ dbg = dict(off=np.round((sk.eef_pos() - np.r_[self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]), zg]) * 100, 1).tolist(),
363
+ w=round(sk.gripper_width() * 100, 1), q_close=round(float(np.degrees(_wrap(self.disc_angle() - q_before))), 1),
364
+ yaw=round(float(np.degrees(sk.yaw)), 0))
365
+ k = max(1, int(np.ceil(abs(sweep) / step)))
366
+ for i in range(1, k + 1):
367
+ w = self._c + PEG_RAD * np.array([np.cos(a0 + sweep * i / k), np.sin(a0 + sweep * i / k)])
368
+ sk.move_to([w[0], w[1], zg], tol=0.003, max_steps=40)
369
+ sk.set_gripper(False, steps=8)
370
+ pe = sk.eef_pos()
371
+ sk.move_to([pe[0], pe[1], zg + 0.10])
372
+ got = _wrap(self.disc_angle() - q_before)
373
+ self.turn_log.append(dict(peg_az=round(float(np.degrees(a0)), 1), sweep=round(float(np.degrees(sweep)), 1),
374
+ got=round(float(np.degrees(got)), 1), **dbg))
375
+ rem -= got
376
+
377
+ def pick_place(self, name, dest_xy, support_z, fp=None, carry_z=1.20, travel_z=1.15, carry_yaw=0.0):
378
+ """Top-down pick across the short side, carry, release just above support_z at dest_xy."""
379
+ sk = self.sk
380
+ f = fp or self.footprint(name)
381
+ c = np.array(f["center"])
382
+ gyaw = _wrap_half(f["yaw"])
383
+ zg = max(f["zmin"] + 0.5 * (f["zmax"] - f["zmin"]), f["zmin"] + 0.0145)
384
+ sk.set_gripper(False, steps=6)
385
+ p = sk.eef_pos()
386
+ if p[2] < travel_z - 0.02:
387
+ sk.move_to([p[0], p[1], travel_z])
388
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
389
+ self._settle_yaw()
390
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
391
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
392
+ sk.set_gripper(True, steps=12)
393
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
394
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=carry_yaw)
395
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + 0.006], tol=0.003, speed=0.2, max_steps=150)
396
+ sk.hold(4)
397
+ sk.set_gripper(False, steps=10)
398
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
399
+
400
+ def butter_to_basket(self, fp=None):
401
+ """The main task: if the butter is on the turntable, turn it to the open side first."""
402
+ loc, f = self.item_loc(TARGET)
403
+ if loc == "turntable":
404
+ az = np.arctan2(f["center"][1] - self._c[1], f["center"][0] - self._c[0])
405
+ # bring the butter's long axis parallel to world y (then the hand lies along x, away from the board edge;
406
+ # a hand turned 26 deg off caught the board -- measured); its centre ends within ~30 deg of PICK_AZ
407
+ delta = _wrap_half(f["yaw"] - az)
408
+ self.turn(_wrap(self.PICK_AZ - delta - az))
409
+ b = envs.obj_pos(self.env, BASKET)
410
+ # release with the hand above the rim and let the box drop in: lowering it to the floor puts the 20 cm long
411
+ # hand below the rim of the 12 cm basket and the contact flips the wrist (joint 5 at its limit -- measured)
412
+ self.pick_place(TARGET, b[:2], envs.obj_min_z(self.env, BASKET) + BASKET_RIM + 0.02, fp=fp)
413
+
414
+ def do(self, actions):
415
+ for act in actions:
416
+ if act[0] == "butter_to_basket":
417
+ self.butter_to_basket(fp=act[1] if len(act) > 1 else None)
418
+ elif act[0] == "turn_to": # ["turn_to", absolute disc angle (the agent's remembered start angle)]
419
+ self.turn(_wrap(act[1] - self.disc_angle()))
420
+ elif act[0] == "turn_by":
421
+ self.turn(act[1])
422
+ else:
423
+ raise ValueError(act)
424
+
425
+ # ------------------------------------------------------------ scripted reference policies
426
+ def _plan(self, kind, inst, a, history, rng, memory):
427
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
428
+ return [["butter_to_basket"]]
429
+ if kind == "oracle":
430
+ return [["butter_to_basket"], ["turn_to", memory["q"]]]
431
+ last = history[-1]["outcome"]
432
+ acts = [] if last["target_loc"] == "basket" else [["butter_to_basket"]]
433
+ if kind == "adaptive":
434
+ return acts + ([] if last["turned_ok"] else [["turn_to", memory["q"]]])
435
+ if kind == "nomem":
436
+ return acts + ([] if last["turned_ok"] else [["turn_by", float(rng.uniform(-np.pi, np.pi))]])
437
+ if kind == "blind":
438
+ fp = self.footprint(TARGET)
439
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
440
+ return [["butter_to_basket", fp]]
441
+ raise ValueError(kind)
442
+
443
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
444
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
445
+ k = k or self.max_attempts
446
+ rng = np.random.default_rng(seed)
447
+ history = []
448
+ self.reset_instance(inst)
449
+ memory = dict(q=self.disc_angle()) # Save: the start angle (an agent reads it off the first frame)
450
+ for a in range(k):
451
+ actions = self._plan(kind, inst, a, history, rng, memory)
452
+ self.do(actions)
453
+ self.go_home()
454
+ out = self.outcome(inst)
455
+ params = dict(actions=[[x[0]] + ([round(float(np.degrees(x[1])), 1)] if x[0] != "butter_to_basket" else [])
456
+ for x in actions])
457
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
458
+ if on_attempt:
459
+ on_attempt(a, params, out)
460
+ if out["success"] or kind in ("oracle", "naive"):
461
+ break
462
+ return history
463
+
464
+ # cross-protocol hooks are not used by this task
465
+ def default_params(self, inst):
466
+ return dict(policy="naive")
467
+
468
+ def oracle_params(self, inst):
469
+ return dict(policy="oracle")
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_card_shelf.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L3 card_shelf (2026-10-12): a deepened l3_card_edge. The thin card lies on a raised SHELF (thin top on four legs)
2
+ and hides a weight in one end; sliding the heavy end over the edge far enough to grasp it tips the card off the shelf
3
+ onto the table, where it lies flat and cannot be picked up: the attempt is lost.
4
+
5
+ Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 3.2): l3_card_edge saturated. Sonnet 5.5 (cla4) failed one
6
+ flat grasp, then in the same attempt slid the card 2-3 cm over the board's edge and grasped the overhang (both runs
7
+ succeeded on attempt 1): the failed grasp costs one command and changes nothing. Here the first common-sense
8
+ interaction (slide the nearest end out ~3 cm) has an irreversible cost whenever that end is the heavy one.
9
+
10
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): a wooden shelf
11
+ (top 22 x 26 x 1 cm on four 2 x 2 cm legs, top surface 10 cm above the table) with a thin red card (9.0 x 5.6 x 0.2 cm)
12
+ lying flat on it, long side along x or along y (+-8 deg). Its near end is 2.5-4 cm from the shelf edge it points to (an
13
+ x-card's near end is always the FORWARD one: a card that tips off the backward edge lands behind the shelf, hidden from
14
+ the front camera), the far end 9-14 cm from the opposite edge, both long sides >= 5 cm inside; a grey bin (16 x 16 cm
15
+ inside, 5 cm high) stands on the table beside the shelf (left or right, 6 cm gap). Same card size, mass (10 g),
16
+ friction and bin as l3_card_edge.
17
+
18
+ Hidden variable (instance level, the same in every attempt, invisible): 8 of the card's 10 g are a weight hidden in one
19
+ end; its centre of mass sits COM_E = 2.8 cm from the middle towards that end. Both ends look identical. In 14 of every
20
+ 20 consecutive seeds the heavy end is the NEAR end (the end a Sonnet-like agent slides out), else the far end.
21
+
22
+ Mechanism (physics, no teleport): an end slid out by h tips over the edge once the centre of mass passes it. Measured
23
+ (card teleported with overhang h, 2 s): heavy end stays for h <= 1.7 cm, tips for h >= 1.8 cm; light end stays up to
24
+ 7.0 cm; a uniform card up to ~4.5 cm. The grasp of an overhang needs the fingers past the edge: light end 1.8-3.8 cm
25
+ out -> 11/12 grasped; the heavy end only in a narrow window (1.3-1.5 cm out, grasp 0.8-1.2 cm beyond the edge: 12/36).
26
+ A tipped card is flat on the table within 0.4 s (56/56 tilt 0), where it cannot be gripped (0/56 regrasps) and no edge
27
+ is in reach. The fix is to slide the OTHER end out (a longer slide across the shelf), learnable from the failure: "only
28
+ ~2 cm out and it already tipped -> that end is heavy" (the cheaper explanation "I pushed too far" leads to pushing
29
+ less, which leaves too little overhang to grasp). Validation (seeds 1000-1019): Sonnet-like naive tips 14/14 heavy-near
30
+ instances and succeeds on 6/6 light-near ones; the same habit succeeds 20/20 on l3_card_edge and 20/20 here with a
31
+ uniform card.
32
+
33
+ Implementation notes: the centre of mass is fixed in the generated MJCF (explicit <inertial pos="COM_E 0 0">) and the
34
+ heavy end is chosen by the card's yaw (the card is symmetric), so the body's inertial frame is never changed at runtime
35
+ (no bounding-volume refit needed; see lh_fence / envs.refit_bounds for that MuJoCo pitfall). The inertia is written in
36
+ scientific notation: objects._fmt (5 decimals) rounds a 10-30 g card's inertia to ~0 (a 10 g card does not compile; a
37
+ 30 g card with rounded inertia got pinched and lifted by the flat grasp 4/16). Mass 10 g as in l3_card_edge: the flat
38
+ grasp then fails 20/20 (fingers slide over the card). The shelf is a static multi-geom fixture; its legs stand inside
39
+ its top's footprint (robot-leg contacts: 0 in all scripted runs).
40
+
41
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: success = the card lies in the bin,
42
+ not held; plus a per-step event log (end / side slid over an edge, tipped_off, lifted, released, in_bin, hand_hit_leg)
43
+ and R6 fields (tipped_off, trap_fired, grasp_tries) for the server log; F1 gives the agent only success / failure.
44
+ """
45
+ import numpy as np
46
+
47
+ from .. import envs
48
+ from ..bddl import write_bddl
49
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
50
+ from ..skills import Skills
51
+ from ..task_base import LFFTask, register_task
52
+
53
+ TZ = envs.TABLE_Z
54
+ CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm (as l3_card_edge)
55
+ CARD_MASS = 0.010 # as l3_card_edge (flat grasp fails 20/20; a 30 g card was pinched and lifted 4/16)
56
+ SLUG_MASS = 0.008 # hidden weight (+ 2 g of card); slug centre 3.5 cm from the middle
57
+ COM_E = 0.028 # centre of mass this far from the card's middle, towards the heavy end (the card's local +x)
58
+ MU = 0.3 # card and shelf sliding friction (as l3_card_edge)
59
+ SHELF_HALF = (0.11, 0.13) # top half extents (as l3_card_edge's board)
60
+ SHELF_H = 0.10 # top surface above the table
61
+ TOP_T = 0.01 # top thickness
62
+ LEG = 0.01 # leg half width (2 x 2 cm legs)
63
+ LEG_IN = 0.012 # leg centre to the top's edges
64
+ SHELF_TOP = TZ + SHELF_H
65
+ CARD_REST_Z = SHELF_TOP + CARD_HALF[2]
66
+ BIN_IN = 0.08 # inner half width
67
+ BIN_WALL_H = 0.05
68
+ BIN_GAP = 0.06 # shelf edge to bin outer wall
69
+ BIN_T = 0.006
70
+ BIN_HALF_OUT = BIN_IN + BIN_T
71
+ TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
72
+ LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
73
+
74
+ # instance ranges
75
+ P_HEAVY_NEAR = 0.7 # 14 of every 20 consecutive seeds
76
+ NEAR_GAP = (0.025, 0.040) # near end to its shelf edge
77
+ SIDE_CLEAR = 0.05 # long sides to the shelf's side edges, at least
78
+ YAW_JIT = np.radians(8.0)
79
+
80
+ # scripted policies
81
+ GRASP_OUT = 0.022 # grasp point this far beyond the edge (fingers must clear the edge)
82
+ DRAG_SPEED = 0.08
83
+ NAIVE_STEPS = (0.0, 0.01, 0.02, 0.03) # Sonnet-like: slide the end to the edge, then out in 1 cm steps, lift & look
84
+ ORACLE_STEPS = (0.02, 0.03) # l3_card_edge oracle: to 1 cm short, look, the rest
85
+
86
+ EDGES = ("forward", "backward", "left", "right") # shelf edges in robot-centric words (+x, -x, +y, -y)
87
+ EDGE_U = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)}
88
+ OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"}
89
+
90
+
91
+ def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
92
+ """Uniform-looking card; the inertial (10 g, centre of mass COM_E along local +x) models an 8 g weight hidden in
93
+ the +x end. Explicit inertial pos != 0, so MuJoCo keeps a separate inertial frame (see module doc)."""
94
+ h = CARD_HALF
95
+ ms = CARD_MASS - SLUG_MASS
96
+ xs = COM_E * CARD_MASS / SLUG_MASS # slug centre
97
+ sl = (0.0075, 0.021, h[2]) # slug half extents (1.5 x 4.2 x 0.2 cm)
98
+ box_i = lambda mm, a: mm / 3 * np.array([a[1] ** 2 + a[2] ** 2, a[0] ** 2 + a[2] ** 2, a[0] ** 2 + a[1] ** 2])
99
+ par = lambda mm, r: mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2])
100
+ c = np.array([COM_E, 0.0, 0.0])
101
+ inertia = box_i(ms, h) + par(ms, -c) + box_i(SLUG_MASS, sl) + par(SLUG_MASS, np.array([xs, 0.0, 0.0]) - c)
102
+ g = (f' <inertial pos="{_fmt(c)}" mass="{CARD_MASS}" diaginertia="{" ".join(f"{v:.6e}" for v in inertia)}" />\n'
103
+ f' <geom name="{name}_g0" type="box" size="{_fmt(h)}" rgba="{_fmt(rgba)}" '
104
+ f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
105
+ f' <geom type="box" size="{_fmt(h)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
106
+ return _wrap(name, g, h[2], float(np.hypot(h[0], h[1])))
107
+
108
+
109
+ def shelf_xml(name, rgba=(0.62, 0.45, 0.27, 1.0), leg_rgba=(0.50, 0.36, 0.21, 1.0)):
110
+ """Static shelf: top plate on four legs; body origin at mid height (top surface at +SHELF_H / 2)."""
111
+ hx, hy = SHELF_HALF
112
+ H = SHELF_H / 2
113
+ parts = [((0.0, 0.0, H - TOP_T / 2), (hx, hy, TOP_T / 2), rgba)]
114
+ for sx in (-1, 1):
115
+ for sy in (-1, 1):
116
+ parts.append(((sx * (hx - LEG_IN), sy * (hy - LEG_IN), -TOP_T / 2), (LEG, LEG, H - TOP_T / 2), leg_rgba))
117
+ g = []
118
+ for k, (p, s, c) in enumerate(parts):
119
+ g.append(f' <geom name="{name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" '
120
+ f'density="500" friction="{MU} 0.005 0.0001" {_SOLID} group="0" />')
121
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(c)}" contype="0" '
122
+ f'conaffinity="0" group="1" />')
123
+ return _wrap(name, "\n".join(g), H, float(np.hypot(hx, hy)))
124
+
125
+
126
+ def _yaw_of(quat_wxyz):
127
+ w, x, y, z = quat_wxyz
128
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
129
+
130
+
131
+ class ShelfSkills(Skills):
132
+ """Skills that feed the task's per-step monitor and log every close of the gripper."""
133
+
134
+ def __init__(self, env, task, recorder=None):
135
+ super().__init__(env, recorder=recorder)
136
+ self.task = task
137
+ self.closes = []
138
+
139
+ def _act(self, dpos, drot, grip):
140
+ super()._act(dpos, drot, grip)
141
+ self.task.monitor_step()
142
+
143
+ def set_gripper(self, close, steps=15):
144
+ was_open = self.grip < 0
145
+ before = self.task.close_context() if (close and was_open) else None
146
+ rep = super().set_gripper(close, steps)
147
+ if before is not None:
148
+ before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
149
+ self.closes.append(before)
150
+ return rep
151
+
152
+
153
+ @register_task
154
+ class CardShelf(LFFTask):
155
+ name = "l3_card_shelf"
156
+ level = "L3"
157
+ category = "strategy_switching"
158
+ capabilities = ("Perceive", "Reason", "Plan")
159
+ protocol = "cross"
160
+ max_attempts = 3
161
+ agent_max_steps = 40
162
+ instruction = "Pick up the thin red card lying on the wooden shelf and put it into the grey bin."
163
+ instruction_indirect = "Put the flat red rectangle that lies on the raised wooden platform into the grey container."
164
+
165
+ # ------------------------------------------------------------ scene
166
+ def make_bddl(self):
167
+ card = register_generated("LffShelfCard", card_xml("lff_shelf_card"))
168
+ shelf = register_generated("LffCardShelf", shelf_xml("lff_card_shelf"), free=False)
169
+ bin_ = register_generated("LffShelfBin", bin_xml("lff_shelf_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
170
+ rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
171
+ objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
172
+ fx = [("shelf_1", shelf, "shelf_region", (-0.11, -0.01, -0.09, 0.01)),
173
+ ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
174
+ return write_bddl(self.name, self.instruction, objs, fx)
175
+
176
+ def __init__(self, cam_res=None):
177
+ super().__init__(cam_res)
178
+ m = self.env.sim.model
179
+ self.shelf_bid = m.body_name2id(self.env.fixtures_dict["shelf_1"].root_body)
180
+ self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
181
+ g0 = int(m.body_geomadr[self.shelf_bid])
182
+ self.leg_geoms = {g for g in range(g0, g0 + int(m.body_geomnum[self.shelf_bid]))
183
+ if (m.geom_id2name(g) or "").endswith(("_g1", "_g2", "_g3", "_g4"))}
184
+ self.robot_geoms = set(envs.robot_geom_ids(self.env))
185
+ self.inst = None
186
+ self.mon = None
187
+
188
+ def sample_instance(self, seed):
189
+ rng = np.random.default_rng(seed)
190
+ bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
191
+ along = str(rng.choice(["x", "y"]))
192
+ near_sign = 1.0 if rng.random() < 0.5 else -1.0
193
+ if along == "x": # the near end of an x-card is the forward one: a card that tips off the backward edge lands
194
+ near_sign = 1.0 # behind the shelf, hidden from the front camera (measured); forward = nearest = away from the robot
195
+ jit = float(rng.uniform(-YAW_JIT, YAW_JIT))
196
+ gap = float(rng.uniform(*NEAR_GAP))
197
+ heavy_near = bool((int(seed) * 7) % 20 < round(20 * P_HEAVY_NEAR)) # balanced per 20 consecutive seeds
198
+ a_long, a_side = (0, 1) if along == "x" else (1, 0) # world axis of the card's long / short side
199
+ ext_long = CARD_HALF[0] * abs(np.cos(jit)) + CARD_HALF[1] * abs(np.sin(jit)) # half extents incl. the jitter
200
+ ext_side = CARD_HALF[0] * abs(np.sin(jit)) + CARD_HALF[1] * abs(np.cos(jit))
201
+ c = [bx, by]
202
+ c[a_long] += near_sign * (SHELF_HALF[a_long] - gap - ext_long)
203
+ room = SHELF_HALF[a_side] - ext_side - SIDE_CLEAR
204
+ c[a_side] += float(rng.uniform(-room, room))
205
+ u_near = np.zeros(2)
206
+ u_near[a_long] = near_sign
207
+ near_edge = {(1.0, 0.0): "forward", (-1.0, 0.0): "backward", (0.0, 1.0): "left", (0.0, -1.0): "right"}[
208
+ (float(u_near[0]), float(u_near[1]))]
209
+ heavy_dir = u_near if heavy_near else -u_near # the card's local +x (heavy end) points this way (+- jitter)
210
+ yaw = float(np.arctan2(heavy_dir[1], heavy_dir[0]) + jit)
211
+ side = 1.0 if rng.random() < 0.5 else -1.0
212
+ bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (SHELF_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
213
+ return dict(seed=int(seed), shelf_xy=[bx, by], card_xy=[float(c[0]), float(c[1])], card_yaw=yaw,
214
+ card_along=along, near_edge=near_edge, far_edge=OPPOSITE[near_edge], near_gap=gap,
215
+ heavy_near=heavy_near, heavy_edge=near_edge if heavy_near else OPPOSITE[near_edge],
216
+ com_offset=COM_E, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
217
+
218
+ def apply_instance(self, inst):
219
+ self.inst = inst
220
+ m = self.env.sim.model
221
+ bx, by = inst["shelf_xy"]
222
+ m.body_pos[self.shelf_bid] = [bx, by, TZ + SHELF_H / 2]
223
+ m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0]
224
+ cx, cy = inst["bin_xy"]
225
+ m.body_pos[self.bin_bid] = [cx, cy, TZ + (BIN_WALL_H + BIN_T) / 2]
226
+ m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
227
+ x, y = inst["card_xy"]
228
+ envs.set_obj_pose(self.env, "card_1", [x, y, CARD_REST_Z + 0.0003], yaw=inst["card_yaw"])
229
+
230
+ def reset_instance(self, inst, recorder=None):
231
+ self.env.reset()
232
+ self.apply_instance(inst)
233
+ self.env.sim.forward()
234
+ envs.settle(self.env, 15)
235
+ self.sk = ShelfSkills(self.env, self, recorder=recorder)
236
+ p = self.card_pose()
237
+ self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False, lifted=False,
238
+ out=dict(heavy=0.0, light=0.0, side=0.0), out_edge=dict(heavy=None, light=None, side=None),
239
+ flagged=set(), events=[], in_bin=False, tip=None, leg_hits=0, edge_used=None)
240
+ return self.sk
241
+
242
+ # ------------------------------------------------------------ geometry
243
+ def card_pose(self):
244
+ p = envs.obj_pos(self.env, "card_1")
245
+ return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
246
+
247
+ def _card_frame(self):
248
+ d = self.env.sim.data
249
+ bid = envs.body_id(self.env, "card_1")
250
+ return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy()
251
+
252
+ def card_corners(self):
253
+ p, R = self._card_frame()
254
+ h = np.array(CARD_HALF)
255
+ return np.array([p + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
256
+
257
+ def _beyond(self, xy):
258
+ """{edge: how far the point lies beyond that edge of the shelf top (m, negative = inside)}"""
259
+ b = np.asarray(xy, float) - np.asarray(self.inst["shelf_xy"])
260
+ return {"forward": b[0] - SHELF_HALF[0], "backward": -b[0] - SHELF_HALF[0],
261
+ "left": b[1] - SHELF_HALF[1], "right": -b[1] - SHELF_HALF[1]}
262
+
263
+ def overhang(self):
264
+ """(how far the card sticks out beyond the shelf's edges (m, max over its corners), edge word)"""
265
+ best = (-1.0, None)
266
+ for c in self.card_corners():
267
+ for e, v in self._beyond(c[:2]).items():
268
+ if v > best[0]:
269
+ best = (float(v), e)
270
+ return best
271
+
272
+ def part_overhangs(self):
273
+ """{'heavy' | 'light' | 'side': (overhang m, edge)}: the heavy end (local +x), light end and long sides,
274
+ each measured at its two corners."""
275
+ p, R = self._card_frame()
276
+ h = np.array(CARD_HALF)
277
+ groups = {"heavy": [(1, -1), (1, 1)], "light": [(-1, -1), (-1, 1)]}
278
+ out = {}
279
+ for k, cs in groups.items():
280
+ best = (-1.0, None)
281
+ for sx, sy in cs:
282
+ c = p + R @ (h * [sx, sy, 0.0])
283
+ for e, v in self._beyond(c[:2]).items():
284
+ if v > best[0]:
285
+ best = (float(v), e)
286
+ out[k] = best
287
+ best = (-1.0, None) # a long side: its middle point (an end pushed out also moves two corners out)
288
+ for sy in (-1, 1):
289
+ c = p + R @ (h * [0.0, sy, 0.0])
290
+ for e, v in self._beyond(c[:2]).items():
291
+ if v > best[0]:
292
+ best = (float(v), e)
293
+ out["side"] = best
294
+ return out
295
+
296
+ def end_edge(self, which):
297
+ """shelf edge that the card's `which` end ('heavy' | 'light' | 'near' | 'far') points to, from the live pose"""
298
+ p = self.card_pose()
299
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) # heavy end direction
300
+ if which == "near" or which == "far":
301
+ gaps = {}
302
+ for s in (1.0, -1.0):
303
+ u = d * s
304
+ e = max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u))
305
+ tip = p["xy"] + u * CARD_HALF[0]
306
+ gaps[e] = -self._beyond(tip)[e]
307
+ near = min(gaps, key=gaps.get)
308
+ return near if which == "near" else OPPOSITE[near]
309
+ u = d if which == "heavy" else -d
310
+ return max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u))
311
+
312
+ def on_shelf(self):
313
+ p = self.card_pose()
314
+ rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"]))
315
+ return bool(rel[0] <= SHELF_HALF[0] and rel[1] <= SHELF_HALF[1] and abs(p["z"] - CARD_REST_Z) < 0.012)
316
+
317
+ def on_table(self):
318
+ return bool(self.card_pose()["z"] < TZ + 0.03 and not self.in_bin())
319
+
320
+ def tilt_deg(self):
321
+ _, R = self._card_frame()
322
+ return float(np.degrees(np.arccos(np.clip(abs(R[2, 2]), 0.0, 1.0))))
323
+
324
+ def in_bin(self):
325
+ p = self.card_pose()
326
+ rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
327
+ return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < TZ + BIN_T + BIN_WALL_H)
328
+
329
+ # ------------------------------------------------------------ monitor
330
+ def _event(self, ev, **kw):
331
+ self.mon["events"].append(dict(event=ev, step=int(self.sk.n_steps), **kw))
332
+
333
+ def monitor_step(self):
334
+ mon = self.mon
335
+ if mon is None or self.sk is None:
336
+ return
337
+ p = self.card_pose()
338
+ held = self.sk.holding("card_1")
339
+ zmin = float(self.card_corners()[:, 2].min())
340
+ mon["max_lift"] = max(mon["max_lift"], zmin - SHELF_TOP)
341
+ if held and zmin - SHELF_TOP > 0.02 and not mon["lifted"]:
342
+ mon["lifted"] = True
343
+ self._event("lifted")
344
+ rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"]))
345
+ if (not held and abs(p["z"] - CARD_REST_Z) < 0.004 and self.tilt_deg() < 5.0 and rel[0] <= SHELF_HALF[0]
346
+ and rel[1] <= SHELF_HALF[1]): # lying flat on the shelf
347
+ mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
348
+ for k, (v, e) in self.part_overhangs().items():
349
+ if v > mon["out"][k]:
350
+ mon["out"][k], mon["out_edge"][k] = v, e
351
+ if v >= 0.005 and k not in mon["flagged"]:
352
+ mon["flagged"].add(k)
353
+ self._event("side_over_edge" if k == "side" else "end_over_edge", part=k, edge=e)
354
+ if p["z"] < SHELF_TOP - 0.02 and not held and not mon["fell"]:
355
+ mon["fell"] = True
356
+ if not mon["lifted"]: # never lifted: it tipped (or was pushed) off the shelf
357
+ part = max(("heavy", "light", "side"), key=lambda k: mon["out"][k])
358
+ mon["tip"] = dict(part=part, edge=mon["out_edge"][part], overhang=round(mon["out"][part], 4))
359
+ self._event("tipped_off", **mon["tip"])
360
+ else:
361
+ self._event("released")
362
+ d = self.env.sim.data
363
+ for i in range(d.ncon): # the hand / arm touching a shelf leg (should not happen in normal grasps)
364
+ c = d.contact[i]
365
+ if (c.geom1 in self.leg_geoms and c.geom2 in self.robot_geoms) or (c.geom2 in self.leg_geoms and
366
+ c.geom1 in self.robot_geoms):
367
+ if mon["leg_hits"] == 0:
368
+ self._event("hand_hit_leg")
369
+ mon["leg_hits"] += 1
370
+ break
371
+ if not mon["in_bin"] and self.in_bin() and not held:
372
+ mon["in_bin"] = True
373
+ self._event("in_bin")
374
+
375
+ def close_context(self):
376
+ """Where the gripper is relative to the card and the shelf just before it closes."""
377
+ sk, p = self.sk, self.card_pose()
378
+ e = sk.eef_pos()
379
+ c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
380
+ rel = e[:2] - p["xy"]
381
+ local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side (+ = heavy end)
382
+ beyond = self._beyond(e[:2])
383
+ edge = max(beyond, key=beyond.get)
384
+ ov, ov_edge = self.overhang()
385
+ return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
386
+ tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
387
+ beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
388
+ card_on_shelf=self.on_shelf(), overhang=round(ov, 4), overhang_edge=ov_edge,
389
+ width_before=round(sk.gripper_width(), 4))
390
+
391
+ # ------------------------------------------------------------ outcome / F2
392
+ def outcome(self, inst):
393
+ envs.settle(self.env, 30)
394
+ self.monitor_step()
395
+ sk, mon = self.sk, self.mon
396
+ p = self.card_pose()
397
+ held = bool(sk.holding("card_1"))
398
+ in_bin = self.in_bin() and not held
399
+ success = bool(in_bin)
400
+ moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
401
+ lifted = mon["max_lift"] > 0.02
402
+ tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
403
+ parts, mode = [], "success"
404
+ rel = p["xy"] - np.asarray(inst["bin_xy"])
405
+ where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
406
+ f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
407
+ tip = mon["tip"]
408
+ if success:
409
+ parts.append("The card is in the bin.")
410
+ elif held:
411
+ mode = "held"
412
+ parts.append(f"The card is still held by the gripper, {where}.")
413
+ elif lifted:
414
+ mode = "dropped"
415
+ loc = ("on the shelf" if self.on_shelf() else "on the table" if self.on_table() else
416
+ "partly on the shelf" if p["z"] > SHELF_TOP - 0.02 else "off the shelf")
417
+ parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the shelf but is not in the "
418
+ f"bin: it lies {loc}, its centre {where}.")
419
+ elif mon["fell"]:
420
+ mode = "fell_off"
421
+ what = "a long side" if tip["part"] == "side" else "one end"
422
+ parts.append(f"The card was never lifted: after {what} of it had been slid {100 * max(tip['overhang'], 0):.1f}"
423
+ f" cm beyond the shelf's {tip['edge']} edge, it tipped over that edge and fell off the shelf; "
424
+ + ("it lies flat on the table." if self.on_table() and self.tilt_deg() < 10 else
425
+ f"it rests off the shelf, tilted {self.tilt_deg():.0f} degrees."))
426
+ else:
427
+ mode = "not_lifted"
428
+ parts.append("The card was never lifted; it still lies flat on the shelf"
429
+ + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
430
+ f"{100 * mon['max_overhang']:.1f} cm beyond the shelf's edge)" if mon["max_overhang"] > 0.003
431
+ else ")") if moved > 0.005 else "") + ".")
432
+ if not success and not lifted and tries:
433
+ c = tries[-1]
434
+ n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
435
+ if c["card_on_shelf"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
436
+ txt = ("when the gripper closed on the card lying flat on the shelf, its fingertips were on either side "
437
+ "of the card, at shelf level")
438
+ else:
439
+ pos = (f"{100 * c['beyond_edge']:.1f} cm beyond the shelf's {c['beyond_edge_name']} edge"
440
+ if c["beyond_edge"] >= 0.0 else
441
+ f"over the shelf, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge")
442
+ txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm beyond the "
443
+ f"shelf's {c['overhang_edge']} edge and the gripper's centre was {pos}")
444
+ txt += f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the fingers closed "
445
+ txt += ("fully, sliding over the top of the card instead of gripping its edges."
446
+ if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
447
+ ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
448
+ parts.append(n + txt if n else txt[0].upper() + txt[1:])
449
+ elif not success and not lifted and not mon["fell"]:
450
+ parts.append("The gripper never closed with its fingertips down at the card.")
451
+ failure = "none" if success else mode
452
+ out = dict(success=success, mode=mode, failure=failure, held=held, lifted=bool(lifted),
453
+ max_lift=round(mon["max_lift"], 4), max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4),
454
+ fell=bool(mon["fell"]), tipped_off=tip is not None, trap_fired=bool(tip is not None and
455
+ tip["part"] == "heavy"),
456
+ tip=tip, end_out={k: round(v, 4) for k, v in mon["out"].items()},
457
+ end_out_edge=dict(mon["out_edge"]), card_final=dict(xy=[round(float(v), 4) for v in p["xy"]],
458
+ z_above_table=round(p["z"] - TZ, 4),
459
+ tilt_deg=round(self.tilt_deg(), 1)),
460
+ leg_hits=int(mon["leg_hits"]), slid_edge=mon["edge_used"],
461
+ events=list(mon["events"]), grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
462
+ return out
463
+
464
+ # ------------------------------------------------------------ scripted policies (move_to + gripper only)
465
+ def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
466
+ sk = self.sk
467
+ sk.set_gripper(False, steps=8)
468
+ sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
469
+ sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
470
+ sk.set_gripper(True, steps=15)
471
+ sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
472
+ if not sk.holding("card_1"):
473
+ sk.set_gripper(False, steps=8)
474
+ return False
475
+ bx, by = self.inst["bin_xy"]
476
+ hi = SHELF_TOP + 0.10
477
+ sk.move_to([bx, by, hi])
478
+ sk.move_to([bx, by, TZ + BIN_WALL_H + 0.05], speed=0.2)
479
+ sk.set_gripper(False, steps=12)
480
+ sk.move_to([bx, by, hi])
481
+ return True
482
+
483
+ def slide_card(self, delta, press=0.004, at=(0.0, 0.0)):
484
+ """closed fingertips pressed on the card (at its centre + `at`), straight move by `delta` (xy), lift"""
485
+ sk, p = self.sk, self.card_pose()
486
+ z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
487
+ s = p["xy"] + np.asarray(at, float)
488
+ sk.set_gripper(True, steps=8)
489
+ sk.move_to([s[0], s[1], z + 0.06], yaw=p["yaw"])
490
+ sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100)
491
+ e = s + np.asarray(delta, float)
492
+ sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
493
+ sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
494
+ sk.hold(10) # look
495
+
496
+ def push_end(self, u, dist, behind=0.015):
497
+ """closed fingers at shelf level `behind` m behind the card's trailing end, push it `dist` along u, lift"""
498
+ sk, p = self.sk, self.card_pose()
499
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])])
500
+ la = d * np.sign(d @ u) if abs(d @ u) > 0.5 else d
501
+ tail = p["xy"] - la * CARD_HALF[0]
502
+ s = tail - u * behind
503
+ z = SHELF_TOP + TIP_BELOW_SITE - 0.001 # fingertips on the shelf top (2 mm above: they pass over the card)
504
+ yaw = float(np.arctan2(u[1], u[0]) - np.pi / 2) # finger axis across the push direction
505
+ sk.set_gripper(True, steps=8)
506
+ sk.move_to([s[0], s[1], z + 0.05], yaw=yaw)
507
+ sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100)
508
+ e = s + u * (behind + dist)
509
+ sk.move_to([e[0], e[1], z], speed=0.04, tol=0.004, max_steps=300)
510
+ sk.move_to([e[0], e[1], z + 0.05], speed=0.2)
511
+ sk.hold(10)
512
+
513
+ def execute(self, inst, params):
514
+ p = self.card_pose()
515
+ rng = np.random.default_rng(params.get("noise_seed")) if params.get("noise_seed") is not None else None
516
+ if params.get("probe_grasp", False) or params["mode"] == "grasp": # flat grasp at the card's middle
517
+ dxy = np.asarray(params.get("probe_dxy", (0.0, 0.0)))
518
+ self.grasp_and_bin(p["xy"] + dxy, p["yaw"], SHELF_TOP + params.get("probe_dz", 0.0))
519
+ if params["mode"] == "grasp" or self.sk.holding("card_1") or self.mon["lifted"]:
520
+ return
521
+ # slide one end of the card along its long side out over the edge it points to, in strokes
522
+ edge = params.get("edge") or self.end_edge(params.get("end", "near"))
523
+ self.mon["edge_used"] = edge
524
+ u = np.asarray(EDGE_U[edge], float)
525
+ b = np.asarray(inst["shelf_xy"])
526
+ half = SHELF_HALF[0] if edge in ("forward", "backward") else SHELF_HALF[1]
527
+ edge_pos = float(b @ u) + half
528
+ for k, target in enumerate(params.get("steps", ORACLE_STEPS)):
529
+ if not self.on_shelf():
530
+ return # tipped off: nothing left to grasp (the attempt is lost)
531
+ p = self.card_pose()
532
+ d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])])
533
+ la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u)
534
+ ext = max(float(c[:2] @ u) for c in self.card_corners()) - float(p["xy"] @ u)
535
+ tgt = float(target) + (float(rng.uniform(-1, 1)) * params.get("step_noise", 0.0) if rng is not None else 0.0)
536
+ need = edge_pos + tgt - (float(p["xy"] @ u) + ext) # travel still needed along u
537
+ if need > 0.003:
538
+ if params.get("style", "press") == "endpush":
539
+ self.push_end(u, need)
540
+ else:
541
+ at = (np.asarray(params.get("press_at", (0.0, 0.0))) if rng is None else
542
+ rng.normal(0.0, params.get("press_noise", 0.0), 2))
543
+ self.slide_card(la * need / max(float(la @ u), 1e-6), at=at)
544
+ self.sk.hold(10)
545
+ if not self.on_shelf():
546
+ return
547
+ q = self.card_pose()
548
+ d = np.array([np.cos(q["yaw"]), np.sin(q["yaw"])])
549
+ la = d * np.sign(d @ u) if abs(d @ u) >= 0.5 else np.array([-d[1], d[0]]) * np.sign(np.array([-d[1], d[0]]) @ u)
550
+ cu = float(q["xy"] @ u)
551
+ tip_u = max(float(c[:2] @ u) for c in self.card_corners()) # outermost point of the card along u
552
+ target_u = min(tip_u - 0.008, edge_pos + params.get("grasp_out", GRASP_OUT))
553
+ g = q["xy"] + la * (target_u - cu) / max(float(la @ u), 1e-6)
554
+ g = g + np.asarray(params.get("grasp_dxy", (0.0, 0.0)))
555
+ self.grasp_and_bin(g, q["yaw"], SHELF_TOP - 0.003 + params.get("grasp_dz", 0.0))
556
+
557
+ def default_params(self, inst):
558
+ """Sonnet-like (cla4 l3_card_edge): one flat grasp, then the nearest end out to the edge and 1 cm at a time
559
+ to ~3 cm, lifting the finger and looking after each stroke; grasp the overhang."""
560
+ return dict(mode="edge", probe_grasp=True, end="near", steps=list(NAIVE_STEPS))
561
+
562
+ def oracle_params(self, inst):
563
+ """Knows the hidden weight: slides the light end out 3 cm (two strokes, as the l3_card_edge oracle)."""
564
+ return dict(mode="edge", end="light", steps=list(ORACLE_STEPS))
565
+
566
+ def blind_params(self, inst, attempt, rng):
567
+ """naive with small random variations, no history: nearest end, 2.5-3.5 cm, pressing point / grasp jitter"""
568
+ return dict(mode="edge", probe_grasp=True, end="near", steps=[0.0, 0.01, 0.02, float(rng.uniform(0.025, 0.035))],
569
+ noise_seed=int(rng.integers(1 << 30)), press_noise=0.005,
570
+ grasp_dxy=rng.uniform(-0.005, 0.005, 2).tolist(), grasp_dz=float(rng.uniform(-0.004, 0.003)))
571
+
572
+ def adapt_params(self, inst, history):
573
+ """Tipped off the shelf (never lifted) -> slide the OTHER end next time (it tipped although only ~2 cm stuck
574
+ out: that end must be heavy). Slid out but not gripped -> 1 cm more overhang. Otherwise repeat."""
575
+ out, prm = history[-1]["outcome"], history[-1]["params"]
576
+ used = out.get("slid_edge") or prm.get("edge")
577
+ nxt = dict(mode="edge", probe_grasp=False, edge=used, steps=list(ORACLE_STEPS))
578
+ if out["mode"] == "fell_off":
579
+ e = (out.get("tip") or {}).get("edge") or used
580
+ nxt["edge"] = OPPOSITE.get(e)
581
+ elif out["mode"] == "not_lifted" and used is not None:
582
+ last = float((prm.get("steps") or ORACLE_STEPS)[-1])
583
+ nxt["steps"] = [s + 0.01 for s in ORACLE_STEPS] if last < 0.035 else list(ORACLE_STEPS)
584
+ if nxt["edge"] is None:
585
+ nxt.pop("edge")
586
+ nxt["end"] = "near"
587
+ return nxt
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l4_fit.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L4-A fit_container: put the phone flat inside the one box it fits into.
2
+
3
+ v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and
4
+ phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time.
5
+ v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is
6
+ rendered), CAP_RANGE = 0.8-0.9 cm each, so it is 1.6-1.8 cm longer than the visible phone. The box sizes are drawn
7
+ against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone:
8
+ fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight),
9
+ snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps,
10
+ short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps,
11
+ narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow,
12
+ small 0.5..1.0 cm too short.
13
+ A phone that does not fit lies on the rim of the box (or tips in at one end), visibly not inside, although in the
14
+ images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it
15
+ appears to (by about the overlap seen) -> the box with the most length to spare.
16
+
17
+ The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as
18
+ the capped length. v2 is kept in l4_fit.py.bak-20261008-height.
19
+
20
+ v2 description:
21
+
22
+ Scene: a dark "phone" (14.0 x 6.8 x 1.2 cm) lies in the front row of a 2 x 3 grid of slots; five open
23
+ boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES):
24
+ fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side),
25
+ short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest),
26
+ narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest),
27
+ small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions),
28
+ short 0.8-2.0 cm too short, as wide as the fitting box.
29
+ Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it
30
+ (+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be
31
+ turned by ~90 deg.
32
+
33
+ Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the
34
+ fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in
35
+ sim.model, so a single env serves every instance.
36
+
37
+ Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed
38
+ 2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first
39
+ failures were plain misalignment instead of a size mismatch). F2 feedback after a failed attempt reports where the phone ended up and by how much it is too
40
+ long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger
41
+ in that dimension and turn the phone.
42
+ """
43
+ import numpy as np
44
+
45
+ from .. import envs
46
+ from ..bddl import write_bddl
47
+ from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
48
+ from ..skills import _rot_err
49
+ from ..task_base import LFFTask, register_task
50
+
51
+ # phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it
52
+ PL, PW, PT = 0.140, 0.068, 0.012
53
+ CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden)
54
+ # boxes (local x = long axis of the opening)
55
+ WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035
56
+ BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height
57
+ RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
58
+ N_BOXES = 5
59
+ ROWS_X = (-0.30, -0.08) # back row (near the robot), front row
60
+ COLS_Y = (-0.22, 0.0, 0.22)
61
+ DROP = 0.012 # phone bottom this far above the rim when released
62
+ Z_CARRY = envs.TABLE_Z + 0.15
63
+ PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way
64
+ PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates
65
+ JITTER_DEG = 15.0
66
+ # inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side).
67
+ # The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has
68
+ # the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio.
69
+ # Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box.
70
+ # v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap)
71
+ BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small")
72
+ INNER_RANGES = {
73
+ "fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest)
74
+ "snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable
75
+ "short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box
76
+ "narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow
77
+ "small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short
78
+ }
79
+ VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps)
80
+ BOX_RGBA = (0.70, 0.60, 0.46, 1.0)
81
+
82
+
83
+ def phone_xml(model_name):
84
+ hx, hy, hz = PL / 2, PW / 2, PT / 2
85
+ body = (0.13, 0.13, 0.15, 1.0)
86
+ screen = (0.02, 0.025, 0.04, 1.0)
87
+ g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" '
88
+ f'density="1500" friction="1.0 0.005 0.0001" {_SOLID} group="0" />\n'
89
+ f' <geom type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" conaffinity="0" contype="0" '
90
+ f'group="1" />\n'
91
+ f' <geom type="box" pos="0 0 {hz:.5f}" size="{_fmt((hx - 0.004, hy - 0.003, 0.0003))}" '
92
+ f'rgba="{_fmt(screen)}" conaffinity="0" contype="0" group="1" />')
93
+ # v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered).
94
+ # Resized per instance in apply_instance (inst["cap"]).
95
+ c = CAP_RANGE[1]
96
+ for k, sx in enumerate((1, -1)):
97
+ g += (f'\n <geom name="{model_name}_cap{k}" type="box" pos="{_fmt((sx * (hx + c / 2), 0, 0))}" '
98
+ f'size="{_fmt((c / 2, hy - 0.001, hz))}" rgba="1 1 1 0" density="400" friction="1.0 0.005 0.0001" '
99
+ f'{_SOLID} group="0" />')
100
+ return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy)))
101
+
102
+
103
+ def wrap_half(a):
104
+ """angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)"""
105
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
106
+
107
+
108
+ def wrap_quarter(a):
109
+ """angle modulo pi/2 into [-pi/4, pi/4)"""
110
+ return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
111
+
112
+
113
+ def fits_some_yaw(a, b, clearance=0.002, length=PL):
114
+ """Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in
115
+ total)?"""
116
+ th = np.linspace(0.0, np.pi / 2, 181)
117
+ e1 = length * np.cos(th) + PW * np.sin(th)
118
+ e2 = length * np.sin(th) + PW * np.cos(th)
119
+ return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance)))
120
+
121
+
122
+ def _rect_corners(xy, yaw, half):
123
+ c, s = np.cos(yaw), np.sin(yaw)
124
+ R = np.array([[c, -s], [s, c]])
125
+ pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half)
126
+ return pts @ R.T + np.asarray(xy)
127
+
128
+
129
+ def _rects_overlap(r1, r2):
130
+ """separating-axis test for two rotated rectangles given as (xy, yaw, half)"""
131
+ c1, c2 = _rect_corners(*r1), _rect_corners(*r2)
132
+ for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2):
133
+ ax = np.array([np.cos(yaw), np.sin(yaw)])
134
+ p1, p2 = c1 @ ax, c2 @ ax
135
+ if p1.max() < p2.min() or p2.max() < p1.min():
136
+ return False
137
+ return True
138
+
139
+
140
+ @register_task
141
+ class FitContainer(LFFTask):
142
+ name = "l4_fit_container"
143
+ level = "L4"
144
+ category = "geometry_inference"
145
+ capabilities = ("Perceive", "Reason")
146
+ instruction = "Put the phone flat inside a box that it fits into completely."
147
+ instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely."
148
+
149
+ # ------------------------------------------------------------ scene
150
+ def make_bddl(self):
151
+ phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone"))
152
+ # one category per box (BDDL lists one object per line; same-category lines would overwrite each
153
+ # other). All share the same MJCF; the opening is resized per instance in apply_instance.
154
+ cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H,
155
+ wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA,
156
+ density=3000))
157
+ for c in "ABCDE"]
158
+ objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))]
159
+ slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)]
160
+ for i, (x, y) in enumerate(slots):
161
+ objs.append((f"box_{i + 1}", cats[i], f"box{i + 1}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)))
162
+ return write_bddl(self.name, self.instruction, objs)
163
+
164
+ def sample_instance(self, seed):
165
+ rng = np.random.default_rng(seed)
166
+ j = np.radians(JITTER_DEG)
167
+ for _ in range(500):
168
+ col = int(rng.integers(3))
169
+ phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)]
170
+ phone_yaw = float(rng.uniform(-j, j))
171
+ slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])]
172
+ kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)]
173
+ cap = float(rng.uniform(*CAP_RANGE))
174
+ boxes = []
175
+ for i, (kind, (x, y)) in enumerate(zip(kinds, slots)):
176
+ lo, hi = INNER_RANGES[kind]
177
+ a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1])
178
+ assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap)
179
+ assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b)
180
+ crossed = bool(rng.random() < 0.5)
181
+ yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j))
182
+ boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed,
183
+ xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))],
184
+ yaw=yaw, inner=[float(a), float(b)]))
185
+ rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007))
186
+ for b in boxes]
187
+ rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01)))
188
+ if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)):
189
+ break
190
+ else:
191
+ raise RuntimeError("could not sample a non-overlapping layout")
192
+ prng = np.random.default_rng(seed + 7919)
193
+ perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))]
194
+ for b in boxes]
195
+ return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes,
196
+ fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc)
197
+
198
+ def _reshape_box(self, name, a, b):
199
+ ix, iy, H = a / 2, b / 2, BOX_HALF_H
200
+ parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)),
201
+ ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
202
+ ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
203
+ ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)),
204
+ ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))]
205
+ m = self.env.sim.model
206
+ o = self.env.objects_dict[name]
207
+ for names in (o.contact_geoms, o.visual_geoms):
208
+ assert len(names) == len(parts), names
209
+ for k, n in enumerate(names):
210
+ g = m.geom_name2id(n)
211
+ pos, size = parts[k]
212
+ m.geom_pos[g] = pos
213
+ m.geom_size[g] = size
214
+ m.geom_rbound[g] = float(np.linalg.norm(size))
215
+ m.geom_aabb[g] = [0, 0, 0, *size]
216
+
217
+ def _set_caps(self, cap):
218
+ """resize the two hidden bumper caps to `cap` (m) per end"""
219
+ m = self.env.sim.model
220
+ if not hasattr(self, "_cap_ids"):
221
+ self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1")
222
+ if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]]
223
+ assert len(self._cap_ids) == 2, self._cap_ids
224
+ for g in self._cap_ids:
225
+ sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0
226
+ size = (cap / 2, PW / 2 - 0.001, PT / 2)
227
+ m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0)
228
+ m.geom_size[g] = size
229
+ m.geom_rbound[g] = float(np.linalg.norm(size))
230
+ m.geom_aabb[g] = [0, 0, 0, *size]
231
+
232
+ def apply_instance(self, inst):
233
+ # walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision
234
+ # mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07).
235
+ # Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below.
236
+ import mujoco
237
+ self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
238
+ self._set_caps(inst["cap"])
239
+ for b in inst["boxes"]:
240
+ self._reshape_box(b["name"], *b["inner"])
241
+ envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"])
242
+ envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005],
243
+ yaw=inst["phone_yaw"])
244
+
245
+ # ------------------------------------------------------------ outcome
246
+ def _pose2d(self, name):
247
+ bid = envs.body_id(self.env, name)
248
+ R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
249
+ p = self.env.sim.data.body_xpos[bid].copy()
250
+ return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1))))
251
+
252
+ def outcome(self, inst):
253
+ envs.settle(self.env, 40)
254
+ p, yaw, tilt = self._pose2d("phone_1")
255
+ held = bool(self.sk is not None and self.sk.holding("phone_1"))
256
+ # which box is the phone in / on: smallest distance of the phone centre outside a box opening
257
+ best = None
258
+ for j, b in enumerate(inst["boxes"]):
259
+ c, byaw, btilt = self._pose2d(b["name"])
260
+ d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2])
261
+ out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0)
262
+ dist = float(np.linalg.norm(out))
263
+ if best is None or dist < best[0]:
264
+ best = (dist, j, c, byaw, btilt)
265
+ dist, j, c, byaw, btilt = best
266
+ b = inst["boxes"][j]
267
+ a_in, b_in = b["inner"]
268
+ floor_top = c[2] - BOX_HALF_H + FLOOR_T
269
+ height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor
270
+ in_opening = dist < 1e-9
271
+ on_floor = height < 0.004 and tilt < 5.0
272
+ success = bool(in_opening and on_floor and not held and btilt < 10.0)
273
+ where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback
274
+ # footprint of the phone (as it lies now) against the opening of that box
275
+ dl = yaw - byaw
276
+ cs, sn = abs(np.cos(dl)), abs(np.sin(dl))
277
+ L = PL + 2 * inst.get("cap", 0.0) # the capped phone
278
+ over_long = L * cs + PW * sn - a_in
279
+ over_short = L * sn + PW * cs - b_in
280
+ along_long = "length" if cs >= sn else "width"
281
+ fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long,
282
+ over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None,
283
+ over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None)
284
+ res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2),
285
+ tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb)
286
+ if held:
287
+ res["detail"] = "The phone is still in the gripper."
288
+ res["failure"] = "held"
289
+ return res
290
+ if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006):
291
+ res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm "
292
+ f"outside the opening of {where}.")
293
+ res["failure"] = "table"
294
+ return res
295
+ if success:
296
+ res["detail"] = f"The phone is lying flat on the bottom of {where}."
297
+ res["failure"] = None
298
+ return res
299
+ pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else
300
+ f"tilted about {tilt:.0f} degrees with one end down inside the box")
301
+ txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}."
302
+ dim_l = "long" if along_long == "length" else "wide"
303
+ dim_s = "wide" if along_long == "length" else "long"
304
+ if fb["over_long_cm"]:
305
+ txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side."
306
+ if fb["over_short_cm"]:
307
+ txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side."
308
+ if not fb["over_long_cm"] and not fb["over_short_cm"]:
309
+ txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim."
310
+ res["detail"] = txt
311
+ res["failure"] = "rim"
312
+ return res
313
+
314
+ @staticmethod
315
+ def box_label(inst, j):
316
+ """Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left)."""
317
+ ys = [b["xy"][1] for b in inst["boxes"]]
318
+ xs = [b["xy"][0] for b in inst["boxes"]]
319
+ n = len(ys)
320
+ order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first
321
+ r = order.index(j)
322
+ close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04]
323
+ if close: # boxes side by side in y: tell them apart by distance from the robot
324
+ nearer = all(xs[j] < xs[i] for i in close)
325
+ return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position"
326
+ if r == 0:
327
+ return "the box furthest to the robot's left (+y)"
328
+ if r == n - 1:
329
+ return "the box furthest to the robot's right (-y)"
330
+ return "the middle box (between the others, left to right)"
331
+
332
+ # ------------------------------------------------------------ execution
333
+ def execute(self, inst, params):
334
+ """params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released).
335
+ Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre
336
+ along the box's long / short axis (m), drop = height of the phone bottom above the rim (m)."""
337
+ sk, env = self.sk, self.env
338
+ px, py = inst["phone_xy"]
339
+ zc = envs.TABLE_Z + PT / 2
340
+ g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width
341
+ sk.set_gripper(False, steps=5)
342
+ sk.move_to([px, py, zc + 0.10], yaw=g0)
343
+ sk.move_to([px, py, zc + 0.001], tol=0.003)
344
+ sk.set_gripper(True, steps=15)
345
+ sk.move_to([px, py, Z_CARRY], speed=0.25)
346
+ b = inst["boxes"][int(params["box"])]
347
+ c, s = np.cos(b["yaw"]), np.sin(b["yaw"])
348
+ dx, dy = params.get("dx", 0.0), params.get("dy", 0.0)
349
+ bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy
350
+ sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"]))
351
+ # put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip
352
+ off = envs.obj_pos(env, "phone_1") - sk.eef_pos()
353
+ drop = params.get("drop", DROP)
354
+ sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003)
355
+ tgt = self._servo_phone([bx, by], RIM_Z + drop)
356
+ sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts)
357
+ self._hold_at(tgt, 12)
358
+ sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10])
359
+ sk.move_to(list(PARK), yaw=0.0)
360
+
361
+ def _hold_at(self, target, steps):
362
+ sk = self.sk
363
+ R = sk._R()
364
+ for _ in range(steps):
365
+ sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
366
+
367
+ def _servo_phone(self, xy, z_bottom, max_steps=60, tol=0.0015):
368
+ """Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom.
369
+ Returns the final gripper target."""
370
+ sk = self.sk
371
+ R = sk._R()
372
+ goal = np.array([xy[0], xy[1], z_bottom + PT / 2])
373
+ tgt = e_prev = sk.eef_pos()
374
+ for i in range(max_steps):
375
+ ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos()
376
+ if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
377
+ break
378
+ tgt = goal - (ph - e)
379
+ sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
380
+ e_prev = e
381
+ return tgt
382
+
383
+ # ------------------------------------------------------------ scripted policies
384
+ def _naive_yaw(self, inst, j):
385
+ """keep the phone's orientation, only snap it to the nearest axis of box j"""
386
+ p = inst["phone_yaw"]
387
+ return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p))
388
+
389
+ def default_params(self, inst):
390
+ """v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the
391
+ trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its
392
+ tighter direction, i.e. "snug" by construction; phone's long side along the box's long side"""
393
+ marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]]
394
+ j = int(np.argmax(marg))
395
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
396
+
397
+ def nearest_params(self, inst):
398
+ """v2 prior (kept for reference): nearest box, lined up"""
399
+ d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
400
+ j = int(np.argmin(d))
401
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
402
+
403
+ def oracle_params(self, inst):
404
+ j = inst["fit"]
405
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
406
+
407
+ def blind_params(self, inst, attempt, rng):
408
+ """no history: a random box (may repeat), lined up like the prior"""
409
+ j = int(rng.integers(N_BOXES))
410
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
411
+
412
+ def naive_keep_yaw_params(self, inst):
413
+ """old prior (kept for reference): nearest box, keep the phone's orientation"""
414
+ d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
415
+ j = int(np.argmin(d))
416
+ return dict(box=j, place_yaw=self._naive_yaw(inst, j))
417
+
418
+ def adapt_params(self, inst, history):
419
+ """Scripted learner on F2 feedback.
420
+
421
+ Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the
422
+ phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an
423
+ estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box
424
+ that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and
425
+ lines the phone's long side up with the box's long side.
426
+ """
427
+ perc = inst["_perc"]
428
+ L_est = W_est = None
429
+ tried_aligned = set()
430
+ for h in history:
431
+ o = h["outcome"]
432
+ fb = o.get("feedback") or {}
433
+ if o.get("failure") != "rim":
434
+ continue
435
+ j = fb["box"]
436
+ a, b = perc[j]
437
+ if fb["along_long"] == "length":
438
+ if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box
439
+ tried_aligned.add(j)
440
+ if fb["over_long_cm"]:
441
+ L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100)
442
+ if fb["over_short_cm"]:
443
+ W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100)
444
+ else:
445
+ if fb["over_short_cm"]:
446
+ L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100)
447
+ if fb["over_long_cm"]:
448
+ W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100)
449
+ thr = 0.002
450
+ cands = []
451
+ for j, (a, b) in enumerate(perc):
452
+ if j in tried_aligned:
453
+ continue
454
+ mL = None if L_est is None else a - L_est
455
+ mW = None if W_est is None else b - W_est
456
+ feasible = (mL is None or mL > thr) and (mW is None or mW > thr)
457
+ if mL is not None and mW is not None:
458
+ key = min(mL, mW)
459
+ elif mL is not None:
460
+ key = b
461
+ elif mW is not None:
462
+ key = a
463
+ else:
464
+ key = a * b
465
+ cands.append((feasible, key, j))
466
+ if not cands:
467
+ j = int(np.argmax([a * b for a, b in perc]))
468
+ else:
469
+ j = max(cands)[2]
470
+ return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"]))
471
+
472
+ def elim_params(self, inst, history, rng):
473
+ """sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up
474
+ after the first attempt) and to never retry a box that got a size verdict; picks among the remaining
475
+ boxes at random, i.e. no size reasoning / perception."""
476
+ bad = set()
477
+ for h in history:
478
+ fb = h["outcome"].get("feedback") or {}
479
+ if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and (
480
+ fb.get("over_long_cm") or fb.get("over_short_cm")):
481
+ bad.add(int(fb["box"]))
482
+ left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES))
483
+ j = int(rng.choice(left))
484
+ return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
485
+
486
+ EXTRA_KINDS = ("elim",)
487
+
488
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
489
+ if kind not in self.EXTRA_KINDS:
490
+ return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
491
+ k = k or self.max_attempts
492
+ rng = np.random.default_rng(seed)
493
+ history = []
494
+ for a in range(k):
495
+ self.reset_instance(inst)
496
+ if a == 0:
497
+ params = self.default_params(inst)
498
+ else:
499
+ params = self.elim_params(inst, history, rng)
500
+ self.execute(inst, params)
501
+ out = self.outcome(inst)
502
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
503
+ if on_attempt:
504
+ on_attempt(a, params, out)
505
+ if out["success"]:
506
+ break
507
+ return history
508
+
509
+
510
+ # ---------------------------------------------------------------- physical validity checks
511
+ def physics_check(seed0=1000, n=20, out=None):
512
+ """Every (box, orientation) pair on each instance, released centred from DROP above the rim.
513
+ Expect success iff the box is the fitting one and the phone's long side is along the box's long side."""
514
+ import json
515
+ task = FitContainer()
516
+ rows = []
517
+ for seed in range(seed0, seed0 + n):
518
+ inst = task.sample_instance(seed)
519
+ for j, b in enumerate(inst["boxes"]):
520
+ for orient in ("aligned", "crossed"):
521
+ task.reset_instance(inst)
522
+ task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2))))
523
+ o = task.outcome(inst)
524
+ rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]],
525
+ orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"),
526
+ failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
527
+ r = rows[-1]
528
+ print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} "
529
+ f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["expect"] else " <-- MISMATCH"), flush=True)
530
+ if out:
531
+ with open(out, "w") as f:
532
+ json.dump(rows, f, indent=1)
533
+ print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows))
534
+ return rows
535
+
536
+
537
+ def stress_check(seed=1002, out=None):
538
+ """Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box
539
+ (+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow."""
540
+ import copy
541
+ import json
542
+ task = FitContainer()
543
+ base = task.sample_instance(seed)
544
+ j = base["fit"]
545
+ rows = []
546
+ for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010),
547
+ ("narrow_0.5", PL + 0.010, PW - 0.005)]:
548
+ for dx, dy, dyaw, drop in [(0, 0, 0, DROP), (0.004, 0, 0, DROP), (0, 0.004, 0, DROP), (0.007, 0, 0, DROP),
549
+ (0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]:
550
+ inst = copy.deepcopy(base)
551
+ inst["boxes"][j]["inner"] = [a, b]
552
+ task.reset_instance(inst)
553
+ task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)),
554
+ dx=dx, dy=dy, drop=drop))
555
+ o = task.outcome(inst)
556
+ rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000,
557
+ dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"],
558
+ height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
559
+ print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> "
560
+ f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True)
561
+ if out:
562
+ with open(out, "w") as f:
563
+ json.dump(rows, f, indent=1)
564
+ return rows
565
+
566
+
567
+ if __name__ == "__main__":
568
+ # python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json
569
+ # python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json
570
+ import sys
571
+ if sys.argv[1] == "physics":
572
+ physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
573
+ elif sys.argv[1] == "stress":
574
+ stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l5_iterative.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """[PARKED 2026-10-06 — fails acceptance: oracle 50% (n=12, k=3). The push response is not stationary:
2
+ the same commanded speed carries the cube 7.9 cm on one push and 11.4 cm on the next, because the arm reaches
3
+ different speeds at different extensions. Needs a configuration-independent striker before use.]
4
+
5
+ L5-B iterative_push: several pushes in ONE episode (MemMimic "Iterative Pushing" analogue).
6
+
7
+ The cube starts far from the target zone; each push is a straight strike away from the robot whose
8
+ only free parameter is the speed. Overshooting past the zone is unrecoverable (episode fails).
9
+ Hidden variable: cube-table friction mu, as in l5_slide_to_target. The information needed to choose
10
+ the next push (how far a push of a given speed carries the cube) is only available from the
11
+ outcomes of the previous pushes in the same episode -> within-episode learning from failure.
12
+
13
+ "Attempt" granularity for the history: one push.
14
+ """
15
+ import numpy as np
16
+
17
+ from .. import envs
18
+ from ..task_base import register_task
19
+ from .l5_slide import CUBE_HALF, V_MAX, V_MIN, Z_PUSH, SlideToTarget
20
+
21
+
22
+ @register_task
23
+ class IterativePush(SlideToTarget):
24
+ name = "l5_iterative_push"
25
+ level = "L5"
26
+ capabilities = ("Reason", "Save", "Utilize")
27
+ protocol = "within"
28
+ max_attempts = 3 # pushes per episode: too few to creep up on the target with small taps
29
+ instruction = ("Push the red cube away from the robot so that it comes to rest inside the green target zone. "
30
+ "You have at most three separate pushes. If the cube passes the zone, the task fails.")
31
+ instruction_indirect = instruction
32
+ tol_along = 0.015
33
+
34
+ def sample_instance(self, seed):
35
+ rng = np.random.default_rng(seed)
36
+ return dict(seed=int(seed),
37
+ cube_xy=[float(rng.uniform(-0.27, -0.23)), float(rng.uniform(-0.08, 0.08))],
38
+ target_dist=float(rng.uniform(0.22, 0.30)),
39
+ mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.08)))))
40
+
41
+ def make_bddl(self):
42
+ return super().make_bddl()
43
+
44
+ # --------------------------------------------------------------- one push from the current cube pose
45
+ def push_once(self, inst, speed):
46
+ c = envs.obj_pos(self.env, "cube_1")
47
+ x, y = c[0], c[1]
48
+ sk = self.sk
49
+ sk.set_gripper(True, steps=3)
50
+ sk.move_to([x - self.runup, y, Z_PUSH + 0.10], yaw=0.0)
51
+ sk.move_to([x - self.runup, y, Z_PUSH], tol=0.003)
52
+ sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01,
53
+ max_steps=80)
54
+ sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH + 0.10], speed=0.3)
55
+ envs.settle(self.env, 40)
56
+ c1 = envs.obj_pos(self.env, "cube_1")
57
+ return float(c1[0] - x)
58
+
59
+ def outcome(self, inst):
60
+ x0, y0 = inst["cube_xy"]
61
+ c = envs.obj_pos(self.env, "cube_1")
62
+ along = (c[0] - x0) - inst["target_dist"]
63
+ across = c[1] - y0
64
+ success = bool(abs(along) <= self.tol_along and abs(across) <= self.tol_across and c[2] > envs.TABLE_Z)
65
+ overshoot = bool(along > self.tol_along)
66
+ if success:
67
+ detail = "The cube is inside the target zone."
68
+ elif overshoot:
69
+ detail = f"The cube passed the target zone: it is {100 * along:.1f} cm beyond its centre. The task has failed."
70
+ else:
71
+ detail = f"The cube is {100 * -along:.1f} cm short of the centre of the target zone."
72
+ return dict(success=success, overshoot=overshoot, along_err=float(along), across_err=float(across),
73
+ detail=detail)
74
+
75
+ # --------------------------------------------------------------- scripted references
76
+ S0 = 0.02 # distance the cube travels during the contact stroke itself
77
+
78
+ def _plan_speed(self, remaining, model, pushes_left=1):
79
+ """Model: push distance d(v) = s0 + k v^2. With more than one push left, cover all but a short
80
+ final leg (a short push is more predictable); with one push left, aim at the zone centre."""
81
+ if model is None:
82
+ return 0.30
83
+ s0, k = model
84
+ goal = remaining if pushes_left <= 1 else max(remaining - 0.07, 0.0)
85
+ v = np.sqrt(max(goal - s0, 0.0) / max(k, 1e-6))
86
+ return float(np.clip(v, V_MIN, V_MAX))
87
+
88
+ @classmethod
89
+ def _fit(cls, pts):
90
+ """pts: [(v, d)]. One point -> fix s0; two or more -> least squares on (s0, k)."""
91
+ if len(pts) == 1:
92
+ v, d = pts[0]
93
+ return cls.S0, max(d - cls.S0, 1e-4) / v ** 2
94
+ A = np.array([[1.0, v ** 2] for v, _ in pts])
95
+ b = np.array([d for _, d in pts])
96
+ s0, k = np.linalg.lstsq(A, b, rcond=None)[0]
97
+ if k <= 0:
98
+ return cls.S0, max(np.mean(b) - cls.S0, 1e-4) / np.mean([v ** 2 for v, _ in pts])
99
+ return float(np.clip(s0, 0.0, 0.05)), float(k)
100
+
101
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
102
+ k = k or self.max_attempts
103
+ rng = np.random.default_rng(seed)
104
+ self.reset_instance(inst)
105
+ history = []
106
+ model = None
107
+ if kind == "oracle":
108
+ model = self._oracle_model(inst)
109
+ for a in range(k):
110
+ out0 = self.outcome(inst)
111
+ remaining = -out0["along_err"]
112
+ if kind == "naive" or kind == "blind":
113
+ speed = 0.30 if kind == "naive" else float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))
114
+ if remaining < 0.06: # naive heuristic: tap gently near the end
115
+ speed = 0.20
116
+ else:
117
+ speed = self._plan_speed(remaining, model, pushes_left=k - a)
118
+ moved = self.push_once(inst, speed)
119
+ out = self.outcome(inst)
120
+ history.append(dict(attempt=a + 1, params=dict(speed=speed), outcome=dict(out, moved=moved)))
121
+ if kind == "adaptive" and moved > 0.005:
122
+ pts = [(h["params"]["speed"], h["outcome"]["moved"]) for h in history if h["outcome"]["moved"] > 0.005]
123
+ model = self._fit(pts)
124
+ if out["success"] or out["overshoot"]:
125
+ break
126
+ # mark only the final state as the episode outcome
127
+ return history
128
+
129
+ def _oracle_model(self, inst):
130
+ """Privileged: measure the push model with the true mu in scratch rollouts."""
131
+ pts = []
132
+ for v in (0.2, 0.35, 0.5):
133
+ self.reset_instance(inst)
134
+ pts.append((v, self.push_once(inst, v)))
135
+ self.reset_instance(inst)
136
+ return self._fit(pts)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l6_count.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L6-B count_into_box: put exactly N identical cubes into an opaque drop box; one carry is interrupted by a slip.
2
+
3
+ Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at
4
+ one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in,
5
+ lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past
6
+ the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening).
7
+ Cubes cannot be taken back out.
8
+
9
+ Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction).
10
+
11
+ Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried
12
+ cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The
13
+ number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so
14
+ neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already")
15
+ is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be
16
+ completed in a later segment.
17
+
18
+ Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent
19
+ declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the
20
+ current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it
21
+ also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped
22
+ into the box." after every cube that falls in, and the slip.
23
+
24
+ Scripted references (perception = simulator state, as in l6_swap):
25
+ oracle privileged box count: carries cubes until the box holds N.
26
+ adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the
27
+ drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later
28
+ segments: if F2 says the box holds fewer than N, adds one cube per segment.
29
+ naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame,
30
+ which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1)
31
+ and adds the rest.
32
+ blind memoryless restart (k attempts): at the slip it does not know where it was and starts over
33
+ ("the box must get N cubes"), every later segment again puts N cubes in (repeated steps).
34
+ Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the
35
+ slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube
36
+ per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy).
37
+ """
38
+ import numpy as np
39
+
40
+ from .. import envs
41
+ from ..bddl import write_bddl
42
+ from ..objects import _fmt, _wrap, box_xml, register_generated
43
+ from ..task_base import LFFTask, register_task
44
+
45
+ CUBE_HALF = 0.02
46
+ CUBE_RGBA = (0.95, 0.50, 0.10, 1.0)
47
+ N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view
48
+ LETTERS = "ABCDEFGHIJK"
49
+ CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)]
50
+
51
+ # drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot)
52
+ WALL_T = 0.008
53
+ IN_HX, IN_HY = 0.100, 0.110 # inner half sizes
54
+ LID_Z = 0.095 # underside of the lid above the table
55
+ LID_T = 0.008
56
+ HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side
57
+ HOLE_HY = 0.035
58
+ RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls
59
+ RAMP_T = 0.006
60
+ RAMP_MU = 0.03
61
+ BOX_RGBA = (0.30, 0.20, 0.13, 1.0)
62
+ INNER_RGBA = (0.08, 0.07, 0.06, 1.0)
63
+ HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0])
64
+ OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T
65
+ RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX)
66
+ RAMP_TH = float(np.arctan(RAMP_SLOPE))
67
+ # Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free
68
+ # slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening.
69
+ # Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide
70
+ # past the opening before it is moved; then a second layer on the far row. (x, y, layer)
71
+ _ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)]
72
+ SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)]
73
+ + [(_ROW[0], 0.0, 0), (_ROW[1], 0.0, 0)] + [(_ROW[0], y, 1) for y in (-0.088, 0.088, -0.044, 0.044, 0.0)])
74
+
75
+ BASE_X = -0.66
76
+ REACH = 0.70 # max horizontal distance of a cube from the robot base
77
+ CUBE_REGION = (-0.30, 0.07, -0.28, 0.28)
78
+ CUBE_MIN_DIST = 0.085
79
+ BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid)
80
+ Z_GRASP = envs.TABLE_Z + CUBE_HALF
81
+ Z_CARRY = envs.TABLE_Z + 0.20
82
+ Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid
83
+ PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)]
84
+ LIFTED = 0.05 # slip trigger: cube at least this far above its resting height
85
+ HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there)
86
+ HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp
87
+
88
+
89
+ def hand_box_clear(p, a, box, half=HAND_HALF):
90
+ """Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint."""
91
+ ax = np.array([-np.sin(a), np.cos(a)])
92
+ return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0)))
93
+ for t in np.linspace(-half, half, 9))
94
+
95
+
96
+ def axis_clear(p, a, others, half=HAND_HALF):
97
+ """Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a)."""
98
+ ax = np.array([-np.sin(a), np.cos(a)])
99
+ best = 1.0
100
+ for o in others:
101
+ v = np.asarray(o) - p
102
+ t = float(np.clip(v @ ax, -half, half))
103
+ best = min(best, float(np.linalg.norm(v - t * ax)))
104
+ return best
105
+
106
+
107
+ def drop_box_xml(model_name):
108
+ """Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on)."""
109
+ parts = [] # (pos, half size, rgba, quat or None, friction or None)
110
+ H = LID_Z / 2
111
+ # walls
112
+ parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
113
+ parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
114
+ parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
115
+ parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
116
+ # lid around the opening
117
+ zc = LID_Z + LID_T / 2
118
+ x0, x1 = HOLE_X
119
+ parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip
120
+ parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part
121
+ for s in (-1, 1):
122
+ parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2,
123
+ LID_T / 2), BOX_RGBA))
124
+ # floor (dark) and ramp
125
+ parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA))
126
+ dz = RAMP_Z[0] - RAMP_Z[1]
127
+ th = float(np.arctan2(dz, 2 * IN_HX))
128
+ L = float(np.hypot(dz, 2 * IN_HX)) / 2
129
+ zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th)
130
+ ramp = ((0, 0, zmid), (L, IN_HY - 0.001, RAMP_T / 2), INNER_RGBA, (np.cos(th / 2), 0, np.sin(th / 2), 0), RAMP_MU)
131
+ geoms = []
132
+ for k, p in enumerate(parts + [ramp]):
133
+ pos, half, rgba = p[:3]
134
+ quat = p[3] if len(p) > 3 else None
135
+ mu = p[4] if len(p) > 4 else None
136
+ q = f' quat="{_fmt(quat)}"' if quat is not None else ""
137
+ fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"'
138
+ geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} '
139
+ f'rgba="{_fmt(rgba)}" density="1000"{fr} group="0" />')
140
+ geoms.append(f' <geom type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} rgba="{_fmt(rgba)}" '
141
+ f'conaffinity="0" contype="0" group="1" />')
142
+ return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY)))
143
+
144
+
145
+ def _wrap_q(a):
146
+ """cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)"""
147
+ return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
148
+
149
+
150
+ @register_task
151
+ class CountIntoBox(LFFTask):
152
+ name = "l6_count_into_box"
153
+ level = "L6"
154
+ category = "procedural_memory"
155
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
156
+ protocol = "within"
157
+ agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55)
158
+ max_attempts = 5
159
+ _TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. "
160
+ "Cubes cannot be taken back out of the box.")
161
+ _TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the "
162
+ "square hole in its top. Blocks cannot be taken back out of the container.")
163
+ instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction)
164
+ instruction_indirect = _TEMPLATE_INDIRECT.format(n="N")
165
+ inject = True
166
+ announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images)
167
+ agent_object_names = ["orange cube (several identical)", "drop box"]
168
+
169
+ WORDS = {3: "three", 4: "four", 5: "five", 6: "six"}
170
+
171
+ def agent_instruction(self, inst, variant="direct"):
172
+ t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE
173
+ return t.format(n=self.WORDS[inst["n_target"]])
174
+
175
+ def __init__(self, cam_res=None):
176
+ super().__init__(cam_res)
177
+ self._mon = False
178
+ orig_step = self.env.step
179
+
180
+ def step(action): # per-control-step monitor: also sees attempts driven by the agent harness
181
+ ret = orig_step(action)
182
+ if self._mon:
183
+ self._monitor()
184
+ return ret
185
+
186
+ self.env.step = step
187
+
188
+ # ------------------------------------------------------------ scene
189
+ def make_bddl(self):
190
+ objs = []
191
+ for i, L in enumerate(LETTERS[:N_CUBES]):
192
+ cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3,
193
+ CUBE_RGBA, density=600))
194
+ gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4)
195
+ objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01)))
196
+ box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False)
197
+ fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))]
198
+ return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx)
199
+
200
+ def _box_body(self):
201
+ return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body)
202
+
203
+ def sample_instance(self, seed):
204
+ rng = np.random.default_rng(seed)
205
+ n = int(rng.choice([4, 5]))
206
+ p = int(rng.integers(1, n)) # cubes already inside when the slip happens
207
+ e = int(rng.integers(0, 2))
208
+ T = n + e + p
209
+ for _ in range(500):
210
+ side = int(rng.choice([-1, 1]))
211
+ box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)])
212
+ P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)])
213
+ P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH]
214
+ P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR]
215
+ cubes = []
216
+ for c in P: # random sequential addition
217
+ if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes):
218
+ cubes.append(c)
219
+ if len(cubes) == T:
220
+ break
221
+ if len(cubes) < T:
222
+ continue
223
+ yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand
224
+ for i in range(T):
225
+ oth = [cubes[j] for j in range(T) if j != i]
226
+ for _ in range(30):
227
+ y = float(rng.uniform(-np.pi / 4, np.pi / 4))
228
+ if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035:
229
+ # |y| <= 45 deg: the grasp needs no large wrist rotation
230
+ yaws.append(y)
231
+ break
232
+ else:
233
+ break
234
+ if len(yaws) == T:
235
+ break
236
+ else:
237
+ raise RuntimeError("could not sample a layout")
238
+ inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(),
239
+ cubes=np.array(cubes).round(4).tolist(),
240
+ yaws=yaws,
241
+ trigger_dist=float(rng.uniform(0.05, 0.09)),
242
+ slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)),
243
+ slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4)))
244
+ # make_video prints task.instruction: keep it in sync with the last sampled instance
245
+ self.instruction = self.agent_instruction(inst, "direct")
246
+ self.instruction_indirect = self.agent_instruction(inst, "indirect")
247
+ return inst
248
+
249
+ def apply_instance(self, inst):
250
+ m = self.env.sim.model
251
+ bid = self._box_body()
252
+ m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z]
253
+ m.body_quat[bid] = [1, 0, 0, 0]
254
+ T = inst["n_cubes"]
255
+ for i, c in enumerate(CUBES):
256
+ if i < T:
257
+ envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001],
258
+ yaw=inst["yaws"][i])
259
+ else:
260
+ envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001])
261
+ self.env.sim.forward()
262
+ self._inst = inst
263
+ self.active = CUBES[:T]
264
+ self.slip = None
265
+ self.events = []
266
+ self._event_cursor = 0
267
+ self._outcome_cursor = 0
268
+ self.in_box = [] # cubes that fell into the box, in order
269
+ self.stored = [] # cubes moved to a storage slot
270
+ self._bad = set() # scripted policies: cubes whose grasp failed
271
+ self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)}
272
+ self._mon = False
273
+
274
+ def reset_instance(self, inst, recorder=None):
275
+ self._mon = False
276
+ sk = super().reset_instance(inst, recorder=recorder)
277
+ self._home = sk.eef_pos()
278
+ self._mon = True
279
+ return sk
280
+
281
+ def go_home(self):
282
+ p = self.sk.eef_pos()
283
+ self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
284
+ self.sk.move_to(self._home)
285
+
286
+ # ------------------------------------------------------------ geometry helpers
287
+ def box_local(self, xyz):
288
+ b = self._inst["box_xy"]
289
+ return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z])
290
+
291
+ def hole_world(self):
292
+ b = self._inst["box_xy"]
293
+ return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]])
294
+
295
+ def inside_box(self, c):
296
+ q = self.box_local(envs.obj_pos(self.env, c))
297
+ return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z)
298
+
299
+ def on_lid(self, c):
300
+ q = self.box_local(envs.obj_pos(self.env, c))
301
+ return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z)
302
+
303
+ def on_table(self, c):
304
+ p = envs.obj_pos(self.env, c)
305
+ return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c))
306
+
307
+ # ------------------------------------------------------------ monitor (every control step)
308
+ def _monitor(self):
309
+ env = self.env
310
+ for c in self.active:
311
+ if c in self.in_box:
312
+ if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02:
313
+ self._store(c)
314
+ continue
315
+ p = envs.obj_pos(env, c)
316
+ if self.inside_box(c):
317
+ self.in_box.append(c)
318
+ if self.announce_drops:
319
+ self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c,
320
+ text="A cube dropped into the box."))
321
+ continue
322
+ if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where
323
+ self.rest_xy[c] = p[:2].copy()
324
+ continue
325
+ if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED
326
+ and len(self.in_box) == self._inst["p"]
327
+ and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"]
328
+ and self.sk.holding(c)):
329
+ self._do_slip(c)
330
+
331
+ def _store(self, c):
332
+ sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)]
333
+ b = self._inst["box_xy"]
334
+ z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003)
335
+ envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z],
336
+ quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0])
337
+ self.stored.append(c)
338
+
339
+ def _do_slip(self, c):
340
+ inst = self._inst
341
+ src = self.rest_xy[c]
342
+ others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
343
+ xy, yaw = src, inst["slip_yaw"]
344
+ found = False
345
+ for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable
346
+ cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])])
347
+ if not all(np.linalg.norm(cand - o) >= 0.07 for o in others):
348
+ continue
349
+ for dy in (0.0, 0.3, -0.3, 0.6, -0.6):
350
+ y = _wrap_q(inst["slip_yaw"] + dy)
351
+ if axis_clear(cand, y, others) >= HAND_CLEAR and \
352
+ hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035:
353
+ xy, yaw, found = cand, y, True
354
+ break
355
+ if found:
356
+ break
357
+ envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw)
358
+ self.sk.grip = -1.0 # the gripper opens
359
+ self.env.sim.forward()
360
+ text = "A cube slipped out of the gripper and fell back onto the table."
361
+ self.slip = dict(obj=c, xy=[float(v) for v in xy], from_xy=[float(v) for v in src], step=int(self.sk.n_steps),
362
+ in_box=len(self.in_box))
363
+ self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text))
364
+
365
+ def drain_events(self):
366
+ ev = self.events[self._event_cursor:]
367
+ self._event_cursor = len(self.events)
368
+ return [e["text"] for e in ev]
369
+
370
+ # ------------------------------------------------------------ outcome
371
+ def outcome(self, inst):
372
+ envs.settle(self.env, 20)
373
+ n_in = len(self.in_box)
374
+ N = inst["n_target"]
375
+ held = [c for c in self.active if self.sk.holding(c)]
376
+ n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box)
377
+ n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box)
378
+ success = bool(n_in == N and not held)
379
+ terminal = bool(n_in > N)
380
+ if success:
381
+ head = f"The box holds exactly {N} cubes."
382
+ elif terminal:
383
+ head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no "
384
+ f"longer be completed.")
385
+ elif n_in == N:
386
+ head = f"The gripper is still holding a cube."
387
+ else:
388
+ head = f"The box holds fewer than {N} cubes."
389
+ state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table"
390
+ if n_lid:
391
+ state += f" and {n_lid} on the box lid"
392
+ state += "."
393
+ # F2 = verdict + currently observable state + the slip of this segment (never the number inside)
394
+ new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"]
395
+ self._outcome_cursor = len(self.events)
396
+ detail = head + " " + state
397
+ if new:
398
+ detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail
399
+ return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid,
400
+ held=len(held), slip=self.slip, detail=detail)
401
+
402
+ # ------------------------------------------------------------ motion (scripted policies)
403
+ def _grasp_yaw(self, c):
404
+ """The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive
405
+ the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if
406
+ the hand would hit a neighbour or the box on this one."""
407
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3)
408
+ yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0])))
409
+ p = envs.obj_pos(self.env, c)[:2]
410
+ others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
411
+ box = np.asarray(self._inst["box_xy"])
412
+
413
+ def score(a):
414
+ return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03)
415
+ if score(yaw) >= HAND_CLEAR:
416
+ return yaw
417
+ alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2
418
+ return alt if score(alt) > score(yaw) + 0.02 else yaw
419
+
420
+ def _pick(self, c):
421
+ sk = self.sk
422
+ for _ in range(2):
423
+ p = envs.obj_pos(self.env, c)
424
+ sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12)
425
+ if sk.holding(c):
426
+ return True
427
+ sk.set_gripper(False, steps=8)
428
+ sk.move_to([p[0], p[1], Z_GRASP + 0.12])
429
+ return False
430
+
431
+ def _carry(self, c):
432
+ """Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'."""
433
+ n_ev = len(self.events)
434
+ n_in = len(self.in_box)
435
+ if not self._pick(c):
436
+ self._bad.add(c)
437
+ self.go_home() # un-wind the arm before the next try
438
+ return "no_grasp"
439
+ h = self.hole_world()
440
+ sk = self.sk
441
+ sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening
442
+ if any(e["kind"] == "slip" for e in self.events[n_ev:]):
443
+ return "slipped"
444
+ sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004)
445
+ sk.set_gripper(False, steps=12)
446
+ sk.move_to([h[0], h[1], Z_CARRY])
447
+ sk.hold(10)
448
+ return "in" if len(self.in_box) > n_in else "missed"
449
+
450
+ def _next_cube(self):
451
+ """nearest table cube to the opening (what any policy sees in the current frame)"""
452
+ h = self.hole_world()
453
+ cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))]
454
+ cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp
455
+ if not cands:
456
+ return None
457
+ return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h))
458
+
459
+ def _add(self, k, log, stop_on_slip=False):
460
+ """Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped)."""
461
+ added, slipped = 0, False
462
+ guard = 0
463
+ while added < k and guard < 3 * k + 3:
464
+ guard += 1
465
+ c = self._next_cube()
466
+ if c is None:
467
+ break
468
+ r = self._carry(c)
469
+ log.append(r)
470
+ if r == "in":
471
+ added += 1
472
+ elif r == "slipped":
473
+ slipped = True
474
+ if stop_on_slip:
475
+ break
476
+ return added, slipped
477
+
478
+ # ------------------------------------------------------------ scripted references (within protocol)
479
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
480
+ k = k or self.max_attempts
481
+ rng = np.random.default_rng(seed + 7919)
482
+ self.reset_instance(inst)
483
+ N = inst["n_target"]
484
+ history = []
485
+ for a in range(k):
486
+ log = []
487
+ plan = dict(kind=kind, carries=log)
488
+ if a == 0:
489
+ if kind == "oracle":
490
+ while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count
491
+ c = self._next_cube()
492
+ if c is None:
493
+ break
494
+ log.append(self._carry(c))
495
+ plan["recovery"] = "oracle: privileged box count"
496
+ elif kind in ("adaptive", "skip"):
497
+ added, slipped = self._add(N, log) if kind == "adaptive" else (0, False)
498
+ if kind == "skip": # counts carries, not drops
499
+ n_car = 0
500
+ while n_car < N and len(log) < 3 * N:
501
+ c = self._next_cube()
502
+ if c is None:
503
+ break
504
+ r = self._carry(c)
505
+ log.append(r)
506
+ if r in ("in", "slipped"):
507
+ n_car += 1
508
+ if r == "in":
509
+ added += 1
510
+ plan["recovery"] = "counts carries (the slipped one too)"
511
+ else:
512
+ plan["recovery"] = "own drop count; the slipped carry is not counted"
513
+ else: # memoryless after the slip
514
+ added, slipped = self._add(N, log, stop_on_slip=True)
515
+ if slipped:
516
+ if kind == "naive":
517
+ guess = int(rng.integers(0, N))
518
+ plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}"
519
+ self._add(N - guess, log)
520
+ elif kind == "blind":
521
+ plan["recovery"] = f"memoryless restart: puts {N} cubes in"
522
+ self._add(N, log)
523
+ elif kind == "inc1":
524
+ plan["recovery"] = "stateless: adds one cube per segment"
525
+ self._add(1, log)
526
+ else:
527
+ raise ValueError(kind)
528
+ else:
529
+ plan["recovery"] = "none (no slip)"
530
+ else:
531
+ if kind in ("adaptive", "skip"):
532
+ plan["recovery"] = "memory + F2 'fewer than N': add one cube"
533
+ self._add(1, log)
534
+ elif kind == "blind":
535
+ plan["recovery"] = f"memoryless restart: puts {N} cubes in"
536
+ self._add(N, log)
537
+ elif kind == "inc1":
538
+ plan["recovery"] = "stateless: adds one cube"
539
+ self._add(1, log)
540
+ elif kind == "oracle":
541
+ while len(self.in_box) < N and len(log) < 3 * N + 3:
542
+ c = self._next_cube()
543
+ if c is None:
544
+ break
545
+ log.append(self._carry(c))
546
+ else:
547
+ raise ValueError(kind)
548
+ self.go_home()
549
+ out = self.outcome(inst)
550
+ history.append(dict(attempt=a + 1, params=plan, outcome=out))
551
+ if on_attempt:
552
+ on_attempt(a, plan, out)
553
+ if out["success"] or out["terminal"] or kind in ("oracle", "naive"):
554
+ break
555
+ return history
556
+
557
+ # cross-protocol hooks are not used by this task
558
+ def default_params(self, inst):
559
+ return dict(policy="naive")
560
+
561
+ def oracle_params(self, inst):
562
+ return dict(policy="oracle")
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_key_turn.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L7 key_turn: unlock a lock whose key turns only one way; which way is hidden.
2
+
3
+ Category: failed_interaction_inference ("why did this contact not do what I expected?").
4
+
5
+ Scene: a grey lock box (9 x 9 x 5 cm) on the table with a brass key standing in the keyhole on its top; the key's
6
+ flat head (3.6 cm wide, 1.6 cm thick, 3 cm tall) sticks up so the gripper can grasp it from above and turn it by
7
+ rotating the wrist. A red bolt sticks out of the box's front face (+x, towards the front camera) while it is locked
8
+ and slides in once the key has been turned to the open position.
9
+
10
+ Hidden variable: the turning direction that opens the lock, clockwise (CW) or counterclockwise (CCW) seen from
11
+ above (alternates with the seed parity, so every block of instances is balanced). The other way the key has 3 deg of
12
+ play and then a hard stop. Both look exactly the same.
13
+
14
+ Turns per attempt: not limited (2026-10-16, user). Until then the instruction allowed one turn per attempt and an
15
+ attempt with more than one turn failed; in every logged run whose first turn went the wrong way the agent turned the
16
+ other way within the same attempt and opened the lock, so the rule only made it repeat that correction in the next
17
+ attempt. The attempt now succeeds once the lock is open, however many turns it took. The trap is logged as an error
18
+ event instead: a turn "hits the stop" when it drives the key onto the stop on the locked side before the lock is open;
19
+ `trap_fired` = some turn did, `n_wrong_way` = how many did, `recovered_in_attempt` = trap fired and the lock was then
20
+ opened in the same attempt. A "turn" is any move_to that starts with the key held and changes the commanded yaw by
21
+ >= 5 deg, or that rotates the key by > 3 deg. A wrong turn costs one command, so this task does not meet design rule
22
+ R3 (the common-sense interaction must have a cost); its signal is clean success (first turn the right way) vs.
23
+ in-attempt recovery, and whether the agent keeps twisting the wrong way.
24
+
25
+ Why the prior fails: the user's example -- many people first try counterclockwise. The scripted prior turns CCW by
26
+ 90 deg, so it fails on every CW instance (half of them): the key rotates by its 3 deg of play, then the wrist stalls.
27
+ What must be learned from the failure: "the key would not turn this way at all" (not "my grip slipped") -> turn it
28
+ the other way. One failure is enough.
29
+
30
+ Mechanics notes (measured in the prototype, 2026-10-08):
31
+ * the Panda's finger servo squeezes with kp * (finger opening) N, i.e. only ~4 N on a 7 mm head; the head then
32
+ twisted between the fingers and wedged them open. A 16 mm thick head gives ~8 N and turns reliably.
33
+ * without a stalling wrist the OSC keeps twisting against a blocked key, the fingers wedge open and on release
34
+ they knock the key 15-45 deg the free way (leaking the answer). `KeySkills` therefore stops rotating the wrist
35
+ once the held key sits on a stop and the gripper has twisted 6 deg past it (a torque-limited wrist), and limits
36
+ the wrist to 90 deg/s while turning.
37
+ * the stops use a stiff solref/solimp: with the defaults a hard twist pushed the key 10-15 deg past its stop.
38
+ * commanded yaw is taken literally in this task (nearest representation to the current yaw, clipped to
39
+ +-113 deg). The shared Skills.wrap_yaw maps yaw modulo 180 deg, which is right for grasping but would turn
40
+ "yaw = +95" into -85 deg, i.e. turn the key the wrong way.
41
+ """
42
+ import numpy as np
43
+
44
+ from .. import envs
45
+ from ..bddl import write_bddl
46
+ from ..objects import _SOLID, _fmt, register_generated
47
+ from ..skills import DT, Skills, _rot_err, _rotz
48
+ from ..task_base import LFFTask, register_task
49
+
50
+ LOCK = "lock_1"
51
+ MODEL = "lff_l7_lock"
52
+ LX, LY, LH = 0.045, 0.045, 0.05 # housing half x, half y, full height
53
+ HEAD = (0.018, 0.008, 0.015) # key head half extents: local x = width, y = thickness, z = height
54
+ HEAD_Z = 0.004 + HEAD[2] # head centre above the housing top
55
+ BOLT = (0.008, 0.012, 0.006) # red bolt (visual only) half extents
56
+ BOLT_OUT = (LX + BOLT[0], 0.0, 0.022)
57
+ BOLT_IN = (LX - BOLT[0] - 0.002, 0.0, 0.022)
58
+ PLAY = np.radians(3.0)
59
+ STOP = np.radians(90.0)
60
+ UNLOCK_AT = np.radians(80.0)
61
+ KEY_FRICTION = 0.04 # N m
62
+ W_MAX = np.radians(90.0) # wrist speed limit while turning (rad/s)
63
+ TWIST_MAX = np.radians(6.0) # wrist stalls when it has twisted this far past a blocked key
64
+ STALL_EXIT = 20 # control steps of stalling before the move gives up
65
+ TURN_YAW = np.radians(5.0)
66
+ TURN_KEY = np.radians(3.0)
67
+ STOP_HIT = PLAY - np.radians(0.5) # key this far the locked way = sitting on the locked-side stop
68
+ Z_GRIP = envs.TABLE_Z + LH + HEAD_Z # grasp-point height for the key head (its centre)
69
+
70
+
71
+ def lock_xml(name, body_rgba=(0.55, 0.57, 0.60, 1.0), key_rgba=(0.80, 0.64, 0.22, 1.0), bolt_rgba=(0.80, 0.12, 0.10, 1.0)):
72
+ g = [f'<geom name="{name}_housing" type="box" pos="0 0 {LH / 2:.4f}" size="{_fmt((LX, LY, LH / 2))}" '
73
+ f'rgba="{_fmt(body_rgba)}" friction="1 0.005 0.0001" {_SOLID} group="0"/>',
74
+ f'<geom type="box" pos="0 0 {LH / 2:.4f}" size="{_fmt((LX, LY, LH / 2))}" rgba="{_fmt(body_rgba)}" '
75
+ f'contype="0" conaffinity="0" group="1"/>',
76
+ f'<geom name="{name}_bolt" type="box" pos="{_fmt(BOLT_OUT)}" size="{_fmt(BOLT)}" rgba="{_fmt(bolt_rgba)}" '
77
+ f'contype="0" conaffinity="0" group="1"/>',
78
+ f'<geom type="cylinder" pos="0 0 {LH + 0.0005:.4f}" size="0.011 0.0005" rgba="0.35 0.36 0.38 1" '
79
+ f'contype="0" conaffinity="0" group="1"/>']
80
+ k = ['<inertial pos="0 0 0.01" mass="0.03" diaginertia="0.00001 0.00001 0.00001"/>',
81
+ # placeholder range: the open direction is set per instance (apply_instance)
82
+ f'<joint name="{name}_key_joint" type="hinge" axis="0 0 1" pos="0 0 0" limited="true" range="-0.05 1.6" '
83
+ f'damping="0.01" frictionloss="{KEY_FRICTION}" armature="0.0002"/>',
84
+ f'<geom name="{name}_head" type="box" pos="0 0 {HEAD_Z:.4f}" size="{_fmt(HEAD)}" rgba="{_fmt(key_rgba)}" '
85
+ f'friction="1 0.005 0.0001" {_SOLID} group="0"/>',
86
+ f'<geom type="box" pos="0 0 {HEAD_Z:.4f}" size="{_fmt(HEAD)}" rgba="{_fmt(key_rgba)}" contype="0" '
87
+ f'conaffinity="0" group="1"/>',
88
+ f'<geom type="cylinder" pos="0 0 0.002" size="0.006 0.002" rgba="{_fmt(key_rgba)}" contype="0" '
89
+ f'conaffinity="0" group="1"/>']
90
+ shell = "\n ".join(g)
91
+ key = "\n ".join(k)
92
+ return f"""<mujoco model="{name}">
93
+ <worldbody>
94
+ <body>
95
+ <body name="object">
96
+ {shell}
97
+ <body name="key" pos="0 0 {LH:.4f}">
98
+ {key}
99
+ </body>
100
+ </body>
101
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
102
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {LH:.4f}" name="top_site" />
103
+ <site rgba="0 0 0 0" size="0.005" pos="{LX:.4f} {LY:.4f} 0" name="horizontal_radius_site" />
104
+ </body>
105
+ </worldbody>
106
+ </mujoco>"""
107
+
108
+
109
+ def _wrap_pi(a):
110
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
111
+
112
+
113
+ def _wrap_half(a):
114
+ """the gripper is symmetric under a rotation by pi"""
115
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
116
+
117
+
118
+ def _rot_words(deg):
119
+ return f"{abs(deg):.0f} deg {'counterclockwise' if deg > 0 else 'clockwise'}"
120
+
121
+
122
+ def _lr(v):
123
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
124
+
125
+
126
+ def _fb(v):
127
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
128
+
129
+
130
+ def _turn_txt(t, lead):
131
+ """F2 sentence for one logged turn: what the wrist and the key did, and whether the gripper held the key."""
132
+ dk = t["key_end_deg"] - t["key_start_deg"]
133
+ txt = f"{lead} the wrist rotated {_rot_words(t['wrist_turn_deg'])} (seen from above)"
134
+ if abs(dk) < 1.0:
135
+ txt += " and the key did not rotate at all"
136
+ else:
137
+ txt += f" and the key rotated {_rot_words(dk)}"
138
+ if t["stalled"]:
139
+ txt += ", then it would not turn any further and the wrist stopped there"
140
+ if t["held_at_start"]:
141
+ txt += ("; the gripper lost hold of the key during the turn." if not t["held_at_end"]
142
+ else "; the gripper held the key throughout the turn.")
143
+ else:
144
+ txt += "; the gripper was not holding the key when that move started."
145
+ return txt
146
+
147
+
148
+ class KeySkills(Skills):
149
+ """Skills for the key task: literal yaw, wrist speed limit, stalling wrist, and a log of turns / grasps / unlock."""
150
+
151
+ def __init__(self, env, task, recorder=None):
152
+ super().__init__(env, recorder=recorder)
153
+ self.task = task
154
+ m = env.sim.model
155
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
156
+ self.turns = [] # one entry per move_to that counts as a turn
157
+ self.closes = [] # close_gripper events: gripper centre relative to the key head, held afterwards?
158
+ self.stall_steps = 0
159
+ self._grasp_off = None # gripper yaw minus key yaw when the key was grasped
160
+ self.touch_since_report = False
161
+
162
+ # ------------------------------------------------------------ state
163
+ def eef_yaw(self):
164
+ R = self.eef_mat() @ self.R0.T
165
+ return float(np.arctan2(R[1, 0], R[0, 0]))
166
+
167
+ def holding_key(self):
168
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=[self.task.head_geom_name]))
169
+
170
+ def _touching_key(self):
171
+ d = self.env.sim.data
172
+ g, kg = set(self._grip_geoms), self.task.head_gid
173
+ for i in range(d.ncon):
174
+ c = d.contact[i]
175
+ if (c.geom1 in g and c.geom2 == kg) or (c.geom2 in g and c.geom1 == kg):
176
+ return True
177
+ return False
178
+
179
+ def wrap_yaw(self, yaw):
180
+ """Literal yaw: the representation of `yaw` closest to the current wrist yaw, clipped to the wrist range."""
181
+ cur = self.eef_yaw()
182
+ y = cur + _wrap_pi(float(yaw) - cur)
183
+ return float(np.clip(y, -self.YAW_LIMIT, self.YAW_LIMIT))
184
+
185
+ # ------------------------------------------------------------ low level
186
+ def _act(self, dpos, drot, grip):
187
+ t = self.task
188
+ if self.grip > 0 and self._grasp_off is not None:
189
+ q = t.key_q()
190
+ lo, hi = t.key_range()
191
+ twist = _wrap_half(self.eef_yaw() - t.key_world_yaw() - self._grasp_off)
192
+ at_hi, at_lo = q >= hi - np.radians(1.5), q <= lo + np.radians(1.5)
193
+ if (at_hi and twist > TWIST_MAX and drot[2] > 0) or (at_lo and twist < -TWIST_MAX and drot[2] < 0):
194
+ drot = np.array(drot, float).copy()
195
+ drot[2] = -np.sign(twist) * 0.02 # force-limited wrist: back off instead of twisting further
196
+ self.stall_steps += 1
197
+ super()._act(dpos, drot, grip)
198
+ t.check_unlock()
199
+ if self._touching_key():
200
+ self.touch_since_report = True
201
+
202
+ def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
203
+ """Skills.move_to with the wrist reference rotating at <= W_MAX and an early stop when the wrist stalls.
204
+ Logs the move as a turn when it starts with the key held and rotates the wrist, or when it rotates the key;
205
+ `hit_stop`: the turn went the locked way (wrist command if the key was held, else the key's motion) and the key
206
+ was on the locked-side stop during it, while the lock was still locked (the trap)."""
207
+ t = self.task
208
+ tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
209
+ if yaw is not None:
210
+ self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
211
+ yaw0 = self.eef_yaw()
212
+ dyaw = self.yaw - yaw0
213
+ R_goal = self._R()
214
+ p0 = self.eef_pos()
215
+ q0, held0, locked0 = t.key_q(), self.holding_key(), not t.unlocked
216
+ q_open_min = t.open_sign() * q0 # lowest key angle the open way during the move
217
+ dist = np.linalg.norm(tgt - p0)
218
+ direction = (tgt - p0) / max(dist, 1e-9)
219
+ s = 0.0
220
+ self.stall_steps = 0
221
+ for k in range(max_steps):
222
+ if speed is not None:
223
+ s = min(dist, s + speed * DT)
224
+ ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5)
225
+ else:
226
+ ref = tgt
227
+ frac = min(1.0, (k + 1) * DT * W_MAX / max(abs(dyaw), 1e-6))
228
+ R = _rotz(yaw0 + frac * dyaw) @ self.R0
229
+ self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
230
+ q_open_min = min(q_open_min, t.open_sign() * t.key_q())
231
+ if self.stall_steps >= STALL_EXIT:
232
+ break
233
+ if (np.linalg.norm(tgt - self.eef_pos()) < tol and (speed is None or s >= dist) and frac >= 1.0
234
+ and np.linalg.norm(_rot_err(R_goal, self.eef_mat())) < 0.03):
235
+ break
236
+ stalled = self.stall_steps >= STALL_EXIT
237
+ if stalled:
238
+ # give up the unreached wrist angle; otherwise every later hold (e.g. while the gripper opens) keeps
239
+ # driving the wrist towards it and the arm swings away (seen in the agent self-test, 2026-10-08)
240
+ self.yaw = self.eef_yaw()
241
+ rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
242
+ pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=bool(stalled))
243
+ self.log.append(rep)
244
+ dq = t.key_q() - q0
245
+ locked_way = t.open_sign() * (dyaw if held0 else dq) < 0
246
+ if (held0 and abs(dyaw) >= TURN_YAW) or abs(dq) > TURN_KEY:
247
+ self.turns.append(dict(step=self.n_steps, held_at_start=bool(held0), held_at_end=self.holding_key(),
248
+ key_start_deg=round(float(np.degrees(q0)), 1),
249
+ key_end_deg=round(float(np.degrees(t.key_q())), 1),
250
+ wrist_cmd_deg=round(float(np.degrees(dyaw)), 1),
251
+ wrist_turn_deg=round(float(np.degrees(self.eef_yaw() - yaw0)), 1),
252
+ stalled=bool(stalled),
253
+ hit_stop=bool(locked0 and locked_way and q_open_min <= -STOP_HIT)))
254
+ return rep
255
+
256
+ def set_gripper(self, close, steps=15):
257
+ was_open = self.grip < 0
258
+ rep = super().set_gripper(close, steps)
259
+ if close:
260
+ if self.holding_key():
261
+ self._grasp_off = _wrap_half(self.eef_yaw() - self.task.key_world_yaw())
262
+ if was_open:
263
+ off = self.eef_pos() - self.task.head_xyz()
264
+ self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_key(),
265
+ width=round(self.gripper_width(), 4)))
266
+ else:
267
+ self._grasp_off = None
268
+ return rep
269
+
270
+
271
+ @register_task
272
+ class KeyTurn(LFFTask):
273
+ name = "l7_key_turn"
274
+ level = "L7"
275
+ category = "failed_interaction_inference"
276
+ capabilities = ("Perceive", "Reason", "Plan")
277
+ protocol = "cross"
278
+ instruction = ("Unlock the lock on the grey box: grasp the flat head of the brass key from above and turn the key "
279
+ "a quarter turn (90 degrees). The red bolt on the box slides in when it is unlocked.")
280
+ instruction_indirect = ("Open the lock of the small grey metal box: take hold of the flat gold-coloured tab that "
281
+ "sticks up out of its top and rotate it a quarter turn (90 degrees). The red block on the "
282
+ "box slides in when it is open.")
283
+
284
+ # ------------------------------------------------------------ scene
285
+ def make_bddl(self):
286
+ lock = register_generated("LffKeyLock", lock_xml(MODEL), free=False)
287
+ return write_bddl(self.name, "unlock the lock", [],
288
+ fixtures=[(LOCK, lock, "lock_region", (-0.11, -0.01, -0.09, 0.01))])
289
+
290
+ def __init__(self, cam_res=None):
291
+ super().__init__(cam_res)
292
+ m = self.env.sim.model
293
+ pre = f"{LOCK}_{MODEL}"
294
+ self.jid = m.joint_name2id(pre + "_key_joint")
295
+ self.qa = m.jnt_qposadr[self.jid]
296
+ self.dof = m.jnt_dofadr[self.jid]
297
+ self.lock_bid = m.body_name2id(self.env.fixtures_dict[LOCK].root_body)
298
+ self.head_geom_name = pre + "_head"
299
+ self.head_gid = m.geom_name2id(self.head_geom_name)
300
+ self.bolt_gid = m.geom_name2id(pre + "_bolt")
301
+ self.inst = None
302
+ self.unlocked = False
303
+
304
+ # agent-facing hooks -------------------------------------------------------
305
+ def on_agent_tool(self, inst, name, args, report):
306
+ """The lock is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never see
307
+ the key; add an explicit `holding_key` field and count key contacts as touches."""
308
+ if self.sk is None or not isinstance(report, dict):
309
+ return
310
+ touched = self.sk.touch_since_report
311
+ self.sk.touch_since_report = False
312
+ if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"):
313
+ report["holding_key"] = self.sk.holding_key()
314
+ if touched and "touched_object" in report:
315
+ report["touched_object"] = True
316
+
317
+ # ------------------------------------------------------------ state helpers
318
+ def key_q(self):
319
+ return float(self.env.sim.data.qpos[self.qa])
320
+
321
+ def key_range(self):
322
+ return self.env.sim.model.jnt_range[self.jid]
323
+
324
+ def key_world_yaw(self):
325
+ return float(self.inst["lock_yaw"]) + self.key_q()
326
+
327
+ def head_xyz(self):
328
+ return self.env.sim.data.geom_xpos[self.head_gid].copy()
329
+
330
+ def open_sign(self):
331
+ return 1.0 if self.inst["direction"] == "CCW" else -1.0
332
+
333
+ def check_unlock(self):
334
+ """latch: the bolt is thrown back once the key reaches the open position (and stays back)"""
335
+ if not self.unlocked and self.open_sign() * self.key_q() >= UNLOCK_AT:
336
+ self.unlocked = True
337
+ self.env.sim.model.geom_pos[self.bolt_gid] = BOLT_IN
338
+
339
+ def sample_instance(self, seed):
340
+ rng = np.random.default_rng(seed)
341
+ return dict(seed=int(seed), direction="CCW" if seed % 2 == 0 else "CW",
342
+ lock_xy=[float(rng.uniform(-0.15, -0.02)), float(rng.uniform(-0.15, 0.15))],
343
+ lock_yaw=float(rng.uniform(-np.radians(15), np.radians(15))))
344
+
345
+ def apply_instance(self, inst):
346
+ self.inst = inst
347
+ m, d = self.env.sim.model, self.env.sim.data
348
+ cx, cy = inst["lock_xy"]
349
+ a = inst["lock_yaw"]
350
+ m.body_pos[self.lock_bid] = [cx, cy, envs.TABLE_Z]
351
+ m.body_quat[self.lock_bid] = [np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)]
352
+ m.jnt_range[self.jid] = [-PLAY, STOP] if inst["direction"] == "CCW" else [-STOP, PLAY]
353
+ m.jnt_solref[self.jid] = [0.004, 1.0]
354
+ m.jnt_solimp[self.jid] = [0.99, 0.999, 0.001, 0.5, 2.0]
355
+ m.dof_frictionloss[self.dof] = KEY_FRICTION
356
+ m.geom_pos[self.bolt_gid] = BOLT_OUT
357
+ d.qpos[self.qa] = 0.0
358
+ d.qvel[self.dof] = 0.0
359
+ self.unlocked = False
360
+
361
+ def reset_instance(self, inst, recorder=None):
362
+ self.env.reset()
363
+ self.apply_instance(inst)
364
+ self.env.sim.forward()
365
+ envs.settle(self.env, 10)
366
+ self.sk = KeySkills(self.env, self, recorder=recorder)
367
+ return self.sk
368
+
369
+ # ------------------------------------------------------------ outcome
370
+ def outcome(self, inst):
371
+ envs.settle(self.env, 20)
372
+ sk = self.sk
373
+ n_turns = len(sk.turns)
374
+ n_wrong = sum(t["hit_stop"] for t in sk.turns)
375
+ success = bool(self.unlocked)
376
+ open_deg = float(np.degrees(self.open_sign() * self.key_q()))
377
+ out = dict(success=success, unlocked=bool(self.unlocked), n_turns=n_turns, n_wrong_way=n_wrong,
378
+ trap_fired=n_wrong > 0, recovered_in_attempt=bool(n_wrong and success),
379
+ key_deg=round(np.degrees(self.key_q()), 1), open_deg=round(open_deg, 1), turns=sk.turns,
380
+ closes=sk.closes, first_turn=sk.turns[0] if sk.turns else None)
381
+ parts = []
382
+ grasp_txt = ""
383
+ if sk.closes:
384
+ c = sk.closes[0]
385
+ o = c["offset"]
386
+ top = envs.TABLE_Z + LH + HEAD_Z + HEAD[2]
387
+ below = top - (o[2] + self.head_xyz()[2])
388
+ grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the centre of "
389
+ f"the key's head and {100 * below:.1f} cm below the top of the head; it "
390
+ + ("was holding the key." if c["held"] else "did not get hold of the key."))
391
+ if success:
392
+ out["failure"] = None
393
+ parts.append("The lock is unlocked.")
394
+ elif n_turns == 0:
395
+ out["failure"] = "no_turn"
396
+ parts.append("The lock is still locked: the key was never turned.")
397
+ else:
398
+ out["failure"] = "still_locked"
399
+ parts.append("The lock is still locked.")
400
+ if n_turns == 1:
401
+ parts.append(_turn_txt(sk.turns[0], "During your turn"))
402
+ else:
403
+ parts.append(f"The key was turned (or pushed round) in {n_turns} separate moves.")
404
+ parts.append(_turn_txt(sk.turns[0], "During the first one"))
405
+ parts.append(_turn_txt(sk.turns[-1], "During the last one"))
406
+ if grasp_txt and not success:
407
+ parts.append(grasp_txt)
408
+ out["detail"] = " ".join(parts)
409
+ return out
410
+
411
+ # ------------------------------------------------------------ scripted execution (cross protocol)
412
+ def execute(self, inst, params):
413
+ """Grasp the key head from above across its thickness (+ jitter), one wrist turn of `turn` degrees
414
+ (+ = counterclockwise seen from above), release, lift."""
415
+ sk = self.sk
416
+ p = self.head_xyz() + np.r_[params.get("dxy", (0.0, 0.0)), params.get("dz", 0.0)] # perfect perception
417
+ yaw0 = self.key_world_yaw() + np.radians(params.get("dyaw", 0.0))
418
+ sk.set_gripper(False, steps=8)
419
+ sk.move_to([p[0], p[1], p[2] + 0.08], yaw=yaw0)
420
+ sk.move_to([p[0], p[1], p[2]], tol=0.003)
421
+ sk.set_gripper(True, steps=15)
422
+ sk.move_to([p[0], p[1], p[2]], yaw=sk.eef_yaw() + np.radians(float(params["turn"])), max_steps=200)
423
+ sk.set_gripper(False, steps=8)
424
+ e = sk.eef_pos()
425
+ sk.move_to([e[0], e[1], e[2] + 0.08])
426
+
427
+ def default_params(self, inst):
428
+ """the prior from the user's example: try counterclockwise first"""
429
+ return dict(turn=90.0)
430
+
431
+ def oracle_params(self, inst):
432
+ return dict(turn=90.0 * (1 if inst["direction"] == "CCW" else -1))
433
+
434
+ def adapt_params(self, inst, history):
435
+ """Scripted F2 learner. A turn after which the key rotated less than 10 deg the commanded way (it stopped)
436
+ -> that way is blocked -> turn the other way. A turn that rotated the key further but not far enough -> same
437
+ way, a bit more. Anything else (no turn, lost grip) -> repeat the last direction."""
438
+ blocked = set()
439
+ good = 0
440
+ for h in history:
441
+ t = h["outcome"].get("first_turn")
442
+ if t is None:
443
+ continue
444
+ sgn = int(np.sign(h["params"]["turn"]))
445
+ dk = t["key_end_deg"] - t["key_start_deg"]
446
+ if t["held_at_start"] and sgn * dk < 10.0:
447
+ blocked.add(sgn)
448
+ elif sgn * dk >= 10.0:
449
+ good = sgn
450
+ if good:
451
+ return dict(turn=100.0 * good)
452
+ last = int(np.sign(history[-1]["params"]["turn"]))
453
+ sgn = -last if last in blocked else last
454
+ if sgn in blocked:
455
+ sgn = -sgn
456
+ return dict(turn=90.0 * sgn)
457
+
458
+ def blind_params(self, inst, attempt, rng):
459
+ """Same plan (counterclockwise quarter turn) with small random variation; no history."""
460
+ return dict(turn=float(np.clip(rng.normal(90.0, 8.0), 70.0, 105.0)), dxy=rng.normal(0.0, 0.002, 2).tolist(),
461
+ dyaw=float(rng.normal(0.0, 4.0)))
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_offcenter_push.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L7 offcenter_push: push a long box straight forward into a marked rectangle.
2
+
3
+ Category: failed_interaction_inference ("why did this contact not do what I expected?"). The code keeps level "L7";
4
+ the paper files the task under L5 (misjudged physics).
5
+
6
+ Hidden variable: the box's centre of mass is shifted along its long axis by e (|e| ~ U[4.5, 7.5] cm, either
7
+ side; implemented by moving the body's inertial frame, `body_ipos`). The box looks exactly the same for
8
+ every e (uniform colour, a symmetric tape stripe across its middle).
9
+
10
+ Why the prior fails: the natural push is at the middle of the box's back face. On a table the friction
11
+ resultant acts below the centre of mass, so a push whose line does not pass near it turns the box: the
12
+ heavy end lags behind. Measured (closed gripper at yaw 0, 8 cm/s, mu 0.5): pushing at the middle turns the
13
+ box 17 to 41 deg; the rectangle (box + 2 cm margin per side) only holds the box up to FIT_ANGLE = 10.9 deg
14
+ (exact geometry, box centred in the rectangle). Pushing within ~2 cm of the centre of mass gives a straight
15
+ translation (< 1 deg); 3 cm off gives 5-14 deg.
16
+
17
+ What must be learned from the failure: the turning direction tells which end is heavy (the end that
18
+ lagged), the amount tells roughly how far off the push was; push closer to the heavy end. F2 reports the box's
19
+ turn (direction and size, plus how far one end lags the other), where the box's centre ended relative to the
20
+ rectangle's centre, and where on the back face the gripper first touched it -- all relative measurements, never
21
+ absolute coordinates or e itself.
22
+
23
+ Pushes per attempt: not limited (2026-10-19, user). Until then the instruction allowed one push per attempt (one
24
+ move command that moves the box) and an attempt with more failed, so that the agent could not steer the box inside
25
+ an attempt; that moved trial and error that belongs inside an attempt to the next attempt. The attempt now succeeds
26
+ when the box ends completely inside the rectangle and upright, however many pushes it took (and every push was made
27
+ with the closed gripper, see below).
28
+
29
+ Error events (logged; they never end the attempt). A "push" is a move_to that moves the box > 1 cm or turns it
30
+ > 3 deg (unchanged definition). After every push the box is classified against the rectangle (`box_fit`):
31
+ over_turned (|yaw| > FIT_ANGLE: it fits at no position), overshot (a corner past the far edge), sideways (a corner
32
+ past a side edge), short (a corner still in front of the near edge, i.e. not pushed far enough yet), inside. A push
33
+ is `bad` when it leaves the box over_turned, overshot or sideways (or tipped over: upright cos < 0.5) -- not inside,
34
+ and not merely short of the rectangle (pushing straight on can fix "short", so pushing the box in in several steps is
35
+ not an error).
36
+ Outcome: n_pushes, n_bad_pushes, n_turned_pushes (bad pushes that left the box over_turned), n_trap_events (pushes
37
+ that took the box from a good state -- inside or short -- into a bad one, i.e. how often the trap fired anew),
38
+ trap_fired = n_bad_pushes > 0, recovered_in_attempt = trap_fired and success, first_push (record of the first push)
39
+ with first_push_yaw_deg and first_interaction_ok (the first push left the box inside, or short and not turned out).
40
+ irrecoverable: the box tipped over (upright cos < 0.5 after a move, < 0.95 after the final settle), fell off the
41
+ table, or went out of reach (its centre beyond world x = X_LOST, where the gripper can no longer be put down in front
42
+ of it at pushing height to push it back, or beyond |y| = Y_LOST); logged with the control step, the attempt goes on.
43
+
44
+ Closed gripper (2026-10-19): the instruction says "with the closed gripper", and a push made with the fingers open
45
+ (> OPEN_W apart when the move starts) now makes the attempt fail (failure "open_gripper" if the box is otherwise
46
+ inside). Reason, measured: open fingers touch the back face at two points ~8 cm apart, so ONE push at the middle of
47
+ the back face goes straight unless |e| > ~7 cm -- 22 of 25 instances (validation seeds 1000-1019, main 3000-3004)
48
+ succeeded that way without the centre of mass ever mattering. The box cannot be grasped, lifted or dragged by
49
+ pressing on its top (9 cm deep, the gripper opens 8 cm; measured), so no rule is needed for that.
50
+
51
+ Correction cost (measured 2026-10-19, task card): after the natural first push (middle, whole distance) the box is
52
+ turned 17-41 deg and lies across the rectangle. What repairs it: get in front of the leading (light) end and push it
53
+ back -- the box turns back with little translation -- then push the box in near the heavy end. The scripted
54
+ corrector (adaptive) did that in attempt 1 on 19 of 20 instances, 7-15 extra commands (median 7: 2 more pushes).
55
+ What does not: pushing the lagging end forward from behind turns the box back only slowly and carries it past the
56
+ rectangle (0 of 25 instances repaired that way; 11 ended out of reach). Near the reach limit the fingers ride up onto
57
+ the box instead of pushing it back. A cautious first push of 3 cm at the middle turns the box only 6.5-10.9 deg (below
58
+ FIT_ANGLE, so no error event) and shows the heavy end; probe + turn back + push in succeeded on 25 of 25 instances in
59
+ 11 commands. So the task does not meet design rule R3 (a cost >= 10 commands for the common-sense first interaction);
60
+ its signal is clean success vs. in-attempt recovery (trap_fired / recovered_in_attempt) and first_push_yaw_deg.
61
+ """
62
+ import numpy as np
63
+
64
+ from .. import envs
65
+ from ..bddl import write_bddl
66
+ from ..objects import _SOLID, _fmt, _wrap, register_generated
67
+ from ..skills import Skills
68
+ from ..task_base import LFFTask, register_task
69
+
70
+ BOX = "box_1"
71
+ HALF = np.array([0.045, 0.11, 0.02]) # 9 (x) x 22 (y, long axis) x 4 cm: too wide for the 8 cm gripper
72
+ MASS = 0.6
73
+ MU = 0.5
74
+ MARGIN = 0.02 # target rectangle = box footprint + 2 cm on every side
75
+ RECT_HALF = HALF[:2] + MARGIN
76
+ E_MIN, E_MAX = 0.045, 0.075
77
+ Z_PUSH = envs.TABLE_Z + 0.02 # grasp-point height during the push (finger tips ~1 cm above the table)
78
+ Z_SAFE = envs.TABLE_Z + 0.12 # travel height of the scripted corrector (8 cm above the box top)
79
+ PUSH_SPEED = 0.08
80
+ FINGER_AHEAD = 0.009 # the closed fingers' front face is ~0.9 cm ahead of the grasp point (measured, yaw 0)
81
+ RUNUP = 0.04
82
+ MOVE_TOL = 0.01 # a command "moved the box" if its centre moved this much ...
83
+ TURN_TOL = np.radians(3.0) # ... or it turned this much
84
+ TOUCH_TOL = 0.002 # the box "started to move" in a command once its centre moved this much
85
+ OPEN_W = 0.01 # finger opening above which a push counts as made with the gripper open (closed on nothing: 0.002 m)
86
+ TABLE_HALF = (0.5, 0.6) # LIBERO main_table top, centred at the world origin (table_collision geom)
87
+ # Reach at pushing height (grasp point 2 cm above the table, yaw 0; measured 2026-10-19): the gripper gets to world
88
+ # x = 0.10 within 1 cm for |y| <= 0.15; asked for more it stops at x ~ 0.13-0.17, sagging to the table. Pushing a box
89
+ # back from in front of it (measured, box not turned): still works with the box's centre at x = 0.125 (far face at
90
+ # 0.17); with the centre at 0.135 the fingers ride up onto the box or push it further away. A box turned 25 deg with
91
+ # its centre at 0.113 (far corner at 0.20) was still pushed back. So a box whose centre is past X_LOST counts as out of
92
+ # reach. The rectangle's far edge lies at world x = -0.055 ... 0.055.
93
+ X_LOST = 0.13
94
+ Y_LOST = 0.40
95
+ X_DOWN = 0.14 # farthest x at which the scripted corrector puts the gripper down in front of the box
96
+
97
+
98
+ def _fit_angle(half=HALF[:2], rect=RECT_HALF):
99
+ """Largest |yaw| at which the box's footprint still fits inside the rectangle (box centred in it): the
100
+ rotated footprint's half extents are (a cos t + b sin t, a sin t + b cos t)."""
101
+ t = np.radians(np.arange(0.0, 90.0, 0.01))
102
+ ok = (half[0] * np.cos(t) + half[1] * np.sin(t) <= rect[0]) & (half[0] * np.sin(t) + half[1] * np.cos(t) <= rect[1])
103
+ return float(t[np.argmin(ok)] - np.radians(0.01)) if not ok.all() else np.pi / 2
104
+
105
+
106
+ FIT_ANGLE = _fit_angle() # 10.9 deg
107
+
108
+
109
+ def long_box_xml(name, half=HALF, mass=MASS, rgba=(0.72, 0.53, 0.33, 1.0), tape_rgba=(0.88, 0.80, 0.62, 1.0)):
110
+ """Solid box with an explicit inertial whose position is offset from the body origin at compile time, so
111
+ MuJoCo keeps the inertial frame separate (sameframe would otherwise ignore later changes of body_ipos)."""
112
+ I = mass / 12 * np.array([4 * (half[1] ** 2 + half[2] ** 2), 4 * (half[0] ** 2 + half[2] ** 2),
113
+ 4 * (half[0] ** 2 + half[1] ** 2)])
114
+ tape = (half[0] + 0.0005, 0.012, 0.0006)
115
+ g = (f' <inertial pos="0 0.001 0" mass="{mass}" diaginertia="{_fmt(I)}" />\n'
116
+ f' <geom name="{name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
117
+ f'friction="1.0 0.005 0.0001" {_SOLID} group="0" />\n'
118
+ f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />\n'
119
+ f' <geom type="box" pos="0 0 {half[2]:.5f}" size="{_fmt(tape)}" rgba="{_fmt(tape_rgba)}" '
120
+ f'conaffinity="0" contype="0" group="1" />')
121
+ return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
122
+
123
+
124
+ def rect_frame_xml(name, inner_half=RECT_HALF, line_w=0.006, line_rgba=(0.1, 0.55, 0.15, 1.0),
125
+ fill_rgba=(0.75, 0.92, 0.75, 1.0)):
126
+ """Flat, visual-only rectangle drawn on the table (light fill + dark outline, no collisions)."""
127
+ hx, hy = inner_half
128
+ ox, oy = hx + line_w, hy + line_w
129
+ parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill_rgba),
130
+ ((0, hy + line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba),
131
+ ((0, -hy - line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba),
132
+ ((hx + line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba),
133
+ ((-hx - line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba)]
134
+ g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
135
+ f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
136
+ return _wrap(name, g, 0.0012, float(np.hypot(ox, oy)))
137
+
138
+
139
+ def _yaw(quat_wxyz):
140
+ w, x, y, z = quat_wxyz
141
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
142
+
143
+
144
+ def _rot(a):
145
+ return np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])
146
+
147
+
148
+ def _wrap_pi(a):
149
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
150
+
151
+
152
+ def box_corners(p_xy, yaw):
153
+ R = _rot(yaw)
154
+ return np.array([np.asarray(p_xy[:2], float) + R @ np.array([sx * HALF[0], sy * HALF[1]])
155
+ for sx in (-1, 1) for sy in (-1, 1)])
156
+
157
+
158
+ def box_fit(p_xy, yaw, t_xy):
159
+ """The box's footprint against the (axis-aligned) target rectangle centred at t_xy. bad = it cannot get into the
160
+ rectangle by being pushed straight on: turned beyond FIT_ANGLE, a corner past the far edge, or past a side edge."""
161
+ c = box_corners(p_xy, yaw) - np.asarray(t_xy, float)[:2]
162
+ eps = 1e-6
163
+ inside = bool(np.all(np.abs(c[:, 0]) <= RECT_HALF[0] + eps) and np.all(np.abs(c[:, 1]) <= RECT_HALF[1] + eps))
164
+ yw = (yaw + np.pi / 2) % np.pi - np.pi / 2 # the footprint is symmetric under a half turn
165
+ over = bool(abs(yw) > FIT_ANGLE)
166
+ overshot = bool(np.any(c[:, 0] > RECT_HALF[0] + eps))
167
+ sideways = bool(np.any(np.abs(c[:, 1]) > RECT_HALF[1] + eps))
168
+ short = bool(np.any(c[:, 0] < -RECT_HALF[0] - eps))
169
+ return dict(inside=inside, over_turned=over, overshot=overshot, sideways=sideways, short=short,
170
+ bad=bool(over or overshot or sideways))
171
+
172
+
173
+ def _lr(v, unit="cm"):
174
+ return f"{100 * abs(v):.1f} {unit} to the {'left' if v > 0 else 'right'}"
175
+
176
+
177
+ def _fb(v):
178
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
179
+
180
+
181
+ def _turn_words(deg):
182
+ return f"{abs(deg):.0f} degrees {'counterclockwise' if deg > 0 else 'clockwise'}"
183
+
184
+
185
+ class _Budget(Exception):
186
+ """the scripted policy used up the agent command budget of the attempt"""
187
+
188
+
189
+ class PushSkills(Skills):
190
+ """Skills that log, for whoever drives them (scripted policy or agent), which move_to commands moved the
191
+ box (pushes), where the gripper touched it, the box's state after every push, and whether the box was lost."""
192
+
193
+ def __init__(self, env, bias=None, recorder=None, target=None):
194
+ super().__init__(env, bias=bias, recorder=recorder)
195
+ self.target = None if target is None else np.asarray(target, float)[:2]
196
+ self.first_touch = None # where the gripper's centre was (box frame) when the box first moved
197
+ self._p0, self._yaw0 = self._box_pose()
198
+ self.box_moves = [] # one entry per move_to that moved / turned the box (a "push")
199
+ self.n_moves = 0 # move_to commands (an agent's move_eef with a motion = one move_to)
200
+ self.lost = {} # irrecoverable condition -> control step at which it was first seen
201
+ self._mv = None # the move_to in progress: box pose at its start, first touch inside it
202
+
203
+ def _box_pose(self):
204
+ p = envs.obj_pos(self.env, BOX)
205
+ return p, _yaw(envs.obj_quat(self.env, BOX))
206
+
207
+ def _local(self, p0, yaw0):
208
+ """gripper centre in the box frame given by (p0, yaw0): (u along the short side, v along the long side)"""
209
+ return (_rot(yaw0).T @ (self.eef_pos()[:2] - p0[:2])).tolist()
210
+
211
+ def _act(self, dpos, drot, grip):
212
+ super()._act(dpos, drot, grip)
213
+ if self.first_touch is None or (self._mv is not None and self._mv["touch"] is None):
214
+ # "touch" = the first control step at which the box has moved 2 mm. Detected from the box's motion,
215
+ # not from contacts: a stiff gripper pushing a box makes a stick-slip contact that is often absent at the
216
+ # control-step boundaries (measured), so contact polling misses pushes.
217
+ p, _ = self._box_pose()
218
+ if self.first_touch is None and np.linalg.norm(p[:2] - self._p0[:2]) > TOUCH_TOL:
219
+ self.first_touch = dict(local=self._local(self._p0, self._yaw0), step=self.n_steps)
220
+ if self._mv is not None and self._mv["touch"] is None and np.linalg.norm(p[:2] - self._mv["p0"][:2]) > TOUCH_TOL:
221
+ self._mv["touch"] = self._local(self._mv["p0"], self._mv["yaw0"])
222
+
223
+ def fit(self, p=None, yaw=None):
224
+ if p is None:
225
+ p, yaw = self._box_pose()
226
+ return box_fit(p[:2], yaw, self.target) if self.target is not None else None
227
+
228
+ def check_lost(self, final=False):
229
+ """record irrecoverable box states (tipped, off the table, out of reach); returns the current ones"""
230
+ p, _ = self._box_pose()
231
+ up = envs.obj_upright_cos(self.env, BOX)
232
+ now = []
233
+ if up < (0.95 if final else 0.5):
234
+ now.append("tipped")
235
+ if p[2] < envs.TABLE_Z - 0.02 or abs(p[0]) > TABLE_HALF[0] or abs(p[1]) > TABLE_HALF[1]:
236
+ now.append("off_table")
237
+ elif p[0] > X_LOST or abs(p[1]) > Y_LOST:
238
+ now.append("out_of_reach")
239
+ for w in now:
240
+ self.lost.setdefault(w, self.n_steps)
241
+ return now
242
+
243
+ def move_to(self, target, *args, **kwargs):
244
+ p0, y0 = self._box_pose()
245
+ fit0 = self.fit(p0, y0)
246
+ bad0 = fit0 is not None and (fit0["bad"] or envs.obj_upright_cos(self.env, BOX) < 0.5)
247
+ self._mv = dict(p0=p0, yaw0=y0, touch=None)
248
+ width0 = self.gripper_width()
249
+ self.n_moves += 1
250
+ try:
251
+ rep = super().move_to(target, *args, **kwargs)
252
+ finally:
253
+ mv, self._mv = self._mv, None
254
+ p1, y1 = self._box_pose()
255
+ dturn = _wrap_pi(y1 - y0)
256
+ if np.linalg.norm(p1[:2] - p0[:2]) > MOVE_TOL or abs(dturn) > TURN_TOL:
257
+ rec = dict(step=self.n_steps, moved_cm=round(100 * float(np.linalg.norm(p1[:2] - p0[:2])), 1),
258
+ turned_deg=round(float(np.degrees(dturn)), 1), yaw_deg=round(float(np.degrees(y1)), 1),
259
+ gripper_open=bool(width0 > OPEN_W))
260
+ t = mv["touch"]
261
+ if t is not None:
262
+ u, v = t
263
+ face = ("back" if u < -HALF[0] + 0.005 else "front" if u > HALF[0] - 0.005 else
264
+ "left_end" if v > 0 else "right_end")
265
+ rec.update(touch_u=round(float(u), 4), touch_v=round(float(v), 4), face=face)
266
+ fit1 = self.fit(p1, y1)
267
+ if fit1 is not None:
268
+ tipped = envs.obj_upright_cos(self.env, BOX) < 0.5
269
+ bad = bool(fit1["bad"] or tipped)
270
+ rec.update(inside=fit1["inside"] and not tipped, over_turned=fit1["over_turned"],
271
+ overshot=fit1["overshot"], sideways=fit1["sideways"], tipped=bool(tipped), bad=bad,
272
+ new_trap=bool(bad and not bad0))
273
+ self.box_moves.append(rec)
274
+ self.check_lost()
275
+ return rep
276
+
277
+
278
+ @register_task
279
+ class OffcenterPush(LFFTask):
280
+ name = "l7_offcenter_push"
281
+ level = "L7"
282
+ category = "failed_interaction_inference"
283
+ capabilities = ("Perceive", "Reason", "Utilize")
284
+ protocol = "cross"
285
+ # 2026-10-19 (wording): the instruction states only the end state. "straight forward ... without turning" read as
286
+ # a rule on the motion (no turning on the way, push only forward), but success is judged on the end state alone
287
+ # (completely inside the rectangle -- which bounds the turn to FIT_ANGLE -- upright, every push with the closed
288
+ # gripper), and the repair that works pushes the leading end back from in front of the box.
289
+ instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the "
290
+ "green rectangle ahead of it (farther from the robot).")
291
+ instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up "
292
+ "completely inside the marked green area ahead of it (farther from the robot).")
293
+
294
+ # ------------------------------------------------------------ scene
295
+ def make_bddl(self):
296
+ box = register_generated("LffL7LongBox", long_box_xml("lff_l7_long_box"))
297
+ zone = register_generated("LffL7TargetRect", rect_frame_xml("lff_l7_target_rect"), free=False)
298
+ objs = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))]
299
+ fixtures = [("zone_1", zone, "zone_region", (-0.06, -0.01, -0.04, 0.01))]
300
+ return write_bddl(self.name, "push the long box into the green rectangle", objs, fixtures=fixtures)
301
+
302
+ def sample_instance(self, seed):
303
+ rng = np.random.default_rng(seed)
304
+ e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX))
305
+ return dict(seed=int(seed), box_xy=[float(rng.uniform(-0.20, -0.14)), float(rng.uniform(-0.08, 0.08))],
306
+ target_dist=float(rng.uniform(0.08, 0.13)), com_offset=e)
307
+
308
+ def target_xy(self, inst):
309
+ return np.array([inst["box_xy"][0] + inst["target_dist"], inst["box_xy"][1]])
310
+
311
+ def apply_instance(self, inst):
312
+ m = self.env.sim.model
313
+ zone = self.env.fixtures_dict["zone_1"]
314
+ for g in range(m.ngeom): # the rectangle is a flat marker
315
+ if (m.geom_id2name(g) or "").startswith("zone_1_"):
316
+ m.geom_contype[g] = 0
317
+ m.geom_conaffinity[g] = 0
318
+ t = self.target_xy(inst)
319
+ zb = m.body_name2id(zone.root_body)
320
+ m.body_pos[zb] = [t[0], t[1], envs.TABLE_Z + 0.0002]
321
+ m.body_quat[zb] = [1.0, 0.0, 0.0, 0.0]
322
+ bid = envs.body_id(self.env, BOX)
323
+ m.body_mass[bid] = MASS
324
+ m.body_ipos[bid] = [0.0, inst["com_offset"], 0.0]
325
+ envs.refit_bounds(self.env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds)
326
+ envs.set_friction(self.env, BOX, MU)
327
+ x0, y0 = inst["box_xy"]
328
+ envs.set_obj_pose(self.env, BOX, [x0, y0, envs.TABLE_Z + HALF[2] + 0.001])
329
+
330
+ def reset_instance(self, inst, recorder=None):
331
+ self.env.reset()
332
+ self.apply_instance(inst)
333
+ self.env.sim.forward()
334
+ envs.settle(self.env, 10)
335
+ self.sk = PushSkills(self.env, recorder=recorder, target=self.target_xy(inst))
336
+ self.sim0 = self.sk.n_steps
337
+ return self.sk
338
+
339
+ # ------------------------------------------------------------ outcome
340
+ def outcome(self, inst):
341
+ envs.settle(self.env, 30)
342
+ sk = self.sk
343
+ p = envs.obj_pos(self.env, BOX)
344
+ yaw = _yaw(envs.obj_quat(self.env, BOX))
345
+ t = self.target_xy(inst)
346
+ fit = box_fit(p[:2], yaw, t)
347
+ inside = fit["inside"]
348
+ upright = envs.obj_upright_cos(self.env, BOX) > 0.95
349
+ sk.check_lost(final=True)
350
+ pushes = sk.box_moves
351
+ n_push = len(pushes)
352
+ n_bad = sum(bool(m.get("bad")) for m in pushes)
353
+ n_open = sum(bool(m.get("gripper_open")) for m in pushes)
354
+ off = p[:2] - t
355
+ lag = 2 * HALF[1] * np.sin(yaw) # how far the +y end is behind (+) the -y end along x
356
+ success = bool(inside and upright and n_open == 0)
357
+ first = pushes[0] if pushes else None
358
+ out = dict(success=success, inside=bool(inside), upright=bool(upright),
359
+ n_pushes=n_push, n_bad_pushes=n_bad,
360
+ n_turned_pushes=sum(bool(m.get("over_turned")) for m in pushes),
361
+ n_trap_events=sum(bool(m.get("new_trap")) for m in pushes),
362
+ trap_fired=n_bad > 0, recovered_in_attempt=bool(n_bad and success),
363
+ first_push=first, first_push_yaw_deg=None if first is None else first["yaw_deg"],
364
+ first_interaction_ok=None if first is None else bool(not first.get("bad")),
365
+ n_open_gripper_pushes=n_open,
366
+ irrecoverable=bool(sk.lost), irrecoverable_why=dict(sk.lost),
367
+ n_box_moving_commands=n_push, box_moves=pushes, n_move_commands=sk.n_moves,
368
+ sim_s=round((sk.n_steps - getattr(self, "sim0", 0)) * 0.05, 1),
369
+ yaw_deg=round(float(np.degrees(yaw)), 1),
370
+ centre_offset=[round(float(off[0]), 4), round(float(off[1]), 4)],
371
+ touch_offset=None)
372
+ parts = []
373
+ if sk.first_touch is None:
374
+ out["failure"] = "not_touched"
375
+ parts.append("The box did not move: the gripper never pushed it.")
376
+ else:
377
+ lt = sk.first_touch["local"]
378
+ out["touch_offset"] = round(float(lt[1]), 4)
379
+ if success:
380
+ parts.append("The box is completely inside the rectangle.")
381
+ elif not upright:
382
+ out["failure"] = "tipped"
383
+ parts.append("The box tipped over.")
384
+ elif inside:
385
+ out["failure"] = "open_gripper"
386
+ parts.append("The box is completely inside the rectangle, but it was pushed with the gripper open; "
387
+ "the task asks for pushing with the closed gripper.")
388
+ else:
389
+ out["failure"] = "turned" if abs(np.degrees(yaw)) > 6 else "position"
390
+ parts.append("The box is not completely inside the rectangle.")
391
+ if n_push > 1:
392
+ txt = f"It was moved by {n_push} separate move commands"
393
+ if abs(first["yaw_deg"]) >= 1.0:
394
+ txt += f"; after the first one it had turned {_turn_words(first['yaw_deg'])} (seen from above)"
395
+ parts.append(txt + ".")
396
+ if n_open and out.get("failure") != "open_gripper":
397
+ parts.append("The gripper was open during " + ("that push." if n_push == 1 else
398
+ f"{n_open} of the pushes."))
399
+ turn = np.degrees(yaw)
400
+ if abs(turn) >= 1.0:
401
+ parts.append(f"It {'ended up turned' if n_push > 1 else 'turned'} {_turn_words(turn)} (seen from "
402
+ f"above): its {'left' if lag > 0 else 'right'} end ended {100 * abs(lag):.1f} cm "
403
+ f"further back than its {'right' if lag > 0 else 'left'} end.")
404
+ else:
405
+ parts.append("It did not turn (less than 1 degree)." if n_push <= 1 else
406
+ "It ended up not turned (less than 1 degree).")
407
+ parts.append(f"Its centre ended {_fb(off[0])} and {_lr(off[1])} of the rectangle's centre.")
408
+ parts.append(f"When the box started to move, the gripper's centre was {_lr(lt[1])} of the middle of "
409
+ f"the box (measured along the box's long side).")
410
+ out["detail"] = " ".join(parts)
411
+ return out
412
+
413
+ # ------------------------------------------------------------ scripted primitives (agent-command counted)
414
+ def _cmd(self, target, yaw=None, speed=None, tol=0.004, max_steps=250):
415
+ """one agent command (move_eef; a gripper change rides on a move)"""
416
+ self.ncmd = getattr(self, "ncmd", 0) + 1
417
+ budget = getattr(self, "budget", None)
418
+ if budget is not None and self.ncmd > budget:
419
+ raise _Budget()
420
+ self.sk.move_to(target, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
421
+ if budget is not None and self._sim_used() >= 3.0 * budget: # the server's motion budget (3 s per command)
422
+ raise _Budget()
423
+
424
+ def _sim_used(self):
425
+ return (self.sk.n_steps - getattr(self, "sim0", 0)) * 0.05
426
+
427
+ def _push_at(self, face, v, dist, speed=PUSH_SPEED, runup=RUNUP):
428
+ """One push on the box as it lies now, with the closed gripper rotated to the face: face "back" (push
429
+ forward along the box's short side), "front" (push backwards) at long-side coordinate v (box frame), or
430
+ "left_end" / "right_end" (push along the long side at the middle of that end face). `dist` = how far the
431
+ fingers' front travels past the face. Commands: up (if low, 1), above the run-up point (1), down (1), push (1)."""
432
+ sk = self.sk
433
+ p, yaw = sk._box_pose()
434
+ R = _rot(yaw)
435
+ if face in ("back", "front"):
436
+ s = -1.0 if face == "back" else 1.0
437
+ n, q, gyaw = R @ np.array([s, 0.0]), p[:2] + R @ np.array([s * HALF[0], v]), yaw
438
+ else:
439
+ s = 1.0 if face == "left_end" else -1.0
440
+ n, q, gyaw = R @ np.array([0.0, s]), p[:2] + R @ np.array([0.0, s * HALF[1]]), yaw + np.pi / 2
441
+ start = q + n * (runup + FINGER_AHEAD)
442
+ end = q - n * (dist - FINGER_AHEAD)
443
+ e = sk.eef_pos()
444
+ if e[2] < Z_PUSH + 0.05:
445
+ self._cmd([e[0], e[1], Z_SAFE], speed=0.2)
446
+ self._cmd([start[0], start[1], Z_SAFE], yaw=gyaw)
447
+ self._cmd([start[0], start[1], Z_PUSH], tol=0.003)
448
+ self._cmd([end[0], end[1], Z_PUSH], speed=speed, tol=0.004, max_steps=400)
449
+
450
+ # ------------------------------------------------------------ scripted execution (cross protocol)
451
+ def execute(self, inst, params):
452
+ """Closed gripper behind the box at lateral offset `c` (from the box's middle, along its long axis), then one
453
+ slow straight move_to forward ending `end_dx` beyond the nominal end point (target centre minus half the box
454
+ depth minus the finger offset), then lift. 4 commands (the gripper closes with the first one)."""
455
+ sk = self.sk
456
+ p = envs.obj_pos(self.env, BOX) # perfect perception of the current scene
457
+ t = self.target_xy(inst)
458
+ c = float(params["c"])
459
+ y = p[1] + c
460
+ face = p[0] - HALF[0]
461
+ x_end = t[0] - HALF[0] - FINGER_AHEAD + float(params.get("end_dx", 0.0))
462
+ sk.set_gripper(True, steps=8)
463
+ self._cmd([face - RUNUP, y, Z_PUSH + 0.08], yaw=0.0)
464
+ self._cmd([face - RUNUP, y, Z_PUSH], tol=0.003)
465
+ self._cmd([x_end, y, Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400)
466
+ self._cmd([x_end - 0.03, y, Z_PUSH + 0.10], speed=0.2)
467
+
468
+ def default_params(self, inst):
469
+ return dict(c=0.0, end_dx=0.0) # Sonnet 5.5 (cla2 / cla4 / full5): yaw 0, middle of the back face, one push
470
+
471
+ def oracle_params(self, inst):
472
+ return dict(c=float(inst["com_offset"]), end_dx=0.0)
473
+
474
+ STEP = 0.06 # first correction toward the lagging end (the expected |e| range is unknown to the learner)
475
+ YAW_OK = 3.0 # deg: the corrector turns the box back until it is within this
476
+ GAIN0 = 2.8 # deg of turn per cm of a push at the leading end from the front, 3 cm from the end (measured)
477
+ SAFE_V = HALF[1] - 0.02 # contact points stay 2 cm inside the ends
478
+
479
+ def bracket(self, pushes):
480
+ """Contact point estimate from logged pushes on the back / front face: a push whose box turned
481
+ counterclockwise passed to the right of the centre of mass when pushing forward (back face) and to its left
482
+ when pushing backwards (front face); a long push that did not turn passed within ~2 cm of it."""
483
+ lo, hi = -self.SAFE_V, self.SAFE_V
484
+ lo_set = hi_set = False
485
+ for m in pushes:
486
+ if m.get("face") not in ("back", "front") or m.get("gripper_open"):
487
+ continue
488
+ v, turn = m["touch_v"], m["turned_deg"] * (1.0 if m["face"] == "back" else -1.0)
489
+ if turn > 3.0:
490
+ lo, lo_set = max(lo, v + 0.01), True
491
+ elif turn < -3.0:
492
+ hi, hi_set = min(hi, v - 0.01), True
493
+ elif abs(turn) < 1.5 and m["moved_cm"] >= 3.0:
494
+ lo, hi, lo_set, hi_set = max(lo, v - 0.02), min(hi, v + 0.02), True, True
495
+ if lo > hi: # inconsistent (contacts slide): trust the newest
496
+ lo, hi = hi, lo
497
+ if lo_set and hi_set:
498
+ c = 0.5 * (lo + hi)
499
+ elif lo_set:
500
+ c = lo + self.STEP
501
+ elif hi_set:
502
+ c = hi - self.STEP
503
+ else:
504
+ c = 0.0
505
+ return float(np.clip(c, -self.SAFE_V, self.SAFE_V))
506
+
507
+ def adapt_params(self, inst, history):
508
+ """Cross-attempt start point: push where the pushes of the earlier attempts put the centre of mass."""
509
+ return dict(c=round(self.bracket([m for h in history for m in h["outcome"]["box_moves"]]), 4), end_dx=0.0)
510
+
511
+ @staticmethod
512
+ def _front_runup(p, yaw, v):
513
+ """run-up for a push on the front face at v that keeps the gripper's put-down point within X_DOWN; None when
514
+ even a 1.5 cm run-up does not fit (the box is too far forward to get in front of it)"""
515
+ R = _rot(yaw)
516
+ f, n_out = p[:2] + R @ np.array([HALF[0], v]), R @ np.array([1.0, 0.0])
517
+ runup = min(RUNUP, (X_DOWN - f[0]) / max(n_out[0], 0.2) - FINGER_AHEAD)
518
+ return float(runup) if runup >= 0.015 else None
519
+
520
+ def adaptive_attempt(self, inst, c0, prior_pushes=()):
521
+ """In-attempt corrector: the first push as `execute` (at c0: the middle in attempt 1, like the naive policy);
522
+ then, after every push, look at the box (perfect perception) and push again until it is inside or the agent
523
+ budget would run out. Turned more than YAW_OK -> push its leading end back from the front (it turns back with
524
+ little translation), or if it is too far forward for that, the lagging end forward from behind; not turned
525
+ but short / past the far edge / out at a side -> push it straight from behind / from the front at the
526
+ estimated centre of mass, or along its long side at an end face. Returns the number of corrective pushes."""
527
+ self.execute(inst, dict(c=c0, end_dx=0.0))
528
+ sk = self.sk
529
+ t = self.target_xy(inst)
530
+ gain = self.GAIN0
531
+ sim_budget = 3.0 * self.budget if self.budget is not None else np.inf
532
+ n = 0
533
+ while True:
534
+ p, yaw = sk._box_pose()
535
+ fit = sk.fit(p, yaw)
536
+ if fit["inside"] or sk.lost:
537
+ return n
538
+ if (self.budget is not None and self.ncmd + 4 > self.budget) or self._sim_used() + 10.0 > sim_budget:
539
+ return n
540
+ n += 1
541
+ yd = np.degrees(yaw)
542
+ c_est = self.bracket(list(prior_pushes) + sk.box_moves)
543
+ if abs(yd) > self.YAW_OK:
544
+ for vm in (HALF[1] - 0.03, 0.06, 0.04, 0.02): # the leading (light) end, or nearer the middle if
545
+ v_lead = -np.sign(yd) * vm # the end is out of reach; +v = the box's left end
546
+ runup = self._front_runup(p, yaw, v_lead)
547
+ if runup is not None:
548
+ break
549
+ if runup is not None:
550
+ d = float(np.clip(abs(yd) / gain, 1.0, 10.0)) / 100
551
+ self._push_at("front", v_lead, d, runup=runup)
552
+ dy = abs(yd) - abs(np.degrees(sk._box_pose()[1]))
553
+ if dy > 1.0:
554
+ gain = float(np.clip(dy / (100 * d), 1.0, 5.0))
555
+ else:
556
+ self._push_at("back", np.sign(yd) * (HALF[1] - 0.01), 0.03)
557
+ else:
558
+ dx = t[0] - p[0]
559
+ if fit["overshot"]:
560
+ runup = self._front_runup(p, yaw, c_est)
561
+ if runup is None:
562
+ return n
563
+ self._push_at("front", c_est, max(0.005, -dx), runup=runup)
564
+ elif fit["sideways"]:
565
+ dyy = t[1] - p[1]
566
+ self._push_at("right_end" if dyy > 0 else "left_end", 0.0, max(0.005, abs(dyy) - 0.005))
567
+ else:
568
+ self._push_at("back", c_est, max(0.005, dx))
569
+
570
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
571
+ """Cross protocol with the agent's command budget per attempt (agent_max_steps, default 40 commands and
572
+ 3 s of motion per command; one move_eef = one command). naive / oracle / blind: one push, then finish.
573
+ adaptive: in-attempt corrector (`adaptive_attempt`); attempt 1 starts with the naive push, later attempts
574
+ at the contact point estimated from all earlier pushes."""
575
+ k = k or self.max_attempts
576
+ rng = np.random.default_rng(seed)
577
+ history = []
578
+ for a in range(k):
579
+ self.reset_instance(inst)
580
+ self.ncmd, self.budget = 0, int(getattr(self, "agent_max_steps", 40))
581
+ if kind == "oracle":
582
+ params = self.oracle_params(inst)
583
+ elif kind == "naive":
584
+ params = self.default_params(inst)
585
+ elif kind == "blind":
586
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
587
+ elif kind == "adaptive":
588
+ params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history)
589
+ else:
590
+ raise ValueError(kind)
591
+ try:
592
+ if kind == "adaptive":
593
+ prior = [m for h in history for m in h["outcome"]["box_moves"]]
594
+ params["corrections"] = self.adaptive_attempt(inst, params["c"], prior)
595
+ else:
596
+ self.execute(inst, params)
597
+ except _Budget:
598
+ params["budget_used_up"] = True
599
+ self.budget = None
600
+ out = self.outcome(inst)
601
+ out["commands"] = self.ncmd
602
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
603
+ if on_attempt:
604
+ on_attempt(a, params, out)
605
+ if out["success"] or kind in ("oracle", "naive"):
606
+ break
607
+ return history
608
+
609
+ blind_sigma = 0.008
610
+
611
+ def blind_params(self, inst, attempt, rng):
612
+ """Same plan (push at the middle) with a small random variation of the contact point; no history."""
613
+ return dict(c=float(rng.normal(0.0, self.blind_sigma)), end_dx=0.0)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_breakfast_service.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Breakfast revision 2: food meshes, hinged milk pourer, L1/L3/L4 recovery.
2
+
3
+ Rigid bodies use MuJoCo contacts. Milk is an explicitly reduced-order, volume-
4
+ conserving discharge / ballistic parcel model, NOT Navier-Stokes fluid simulation.
5
+ Only the physical carton angle controls discharge. No policy/stage success gates.
6
+ An upright butter stick physically obstructs the lid. Lay it flat to recover.
7
+ There is no latch fatigue, artificial opening torque, or forced orientation.
8
+ """
9
+ from pathlib import Path
10
+ import copy
11
+ import xml.etree.ElementTree as ET
12
+ import numpy as np
13
+ import robosuite
14
+ import libero.libero as libero_pkg
15
+
16
+ from .. import envs
17
+ from ..bddl import write_bddl
18
+ from ..objects import register_generated, _wrap, _fmt
19
+ from ..skills import Skills
20
+ from ..task_base import register_task
21
+ from .lh_pantry_relatch import (PantryRelatch, RelatchSkills, BREAD_HALF,
22
+ BOX, BOX_MODEL, FLOOR_T, WALL_H, BOX_D, box_lid_xml)
23
+
24
+ LIB_ASSETS = Path(libero_pkg.__file__).parent / 'assets'
25
+ RS_ASSETS = Path(robosuite.__file__).parent / 'models/assets'
26
+ BUTTER_HALF = (.010,.020,.040) # standing: 8 cm tall; lying: 2 cm tall, fits the 2.6 cm cavity
27
+
28
+
29
+ def food_xml(kind, half):
30
+ """Reuse installed textured visual meshes, normalized to the tested food collision hull."""
31
+ if kind == 'bread':
32
+ source = RS_ASSETS / 'objects/bread.xml'
33
+ meshpath = RS_ASSETS / 'objects/meshes/bread.stl'
34
+ data = meshpath.read_bytes()
35
+ n = int.from_bytes(data[80:84], 'little')
36
+ dtype = np.dtype([('normal','<f4',3),('vertices','<f4',(3,3)),('attr','<u2')])
37
+ vertices = np.frombuffer(data, dtype=dtype, count=n, offset=84)['vertices'].reshape(-1,3)
38
+ else:
39
+ source = LIB_ASSETS / 'stable_hope_objects/butter/butter.xml'
40
+ meshpath = source.parent / 'butter.obj'
41
+ vertices = np.array([[float(v) for v in line.split()[1:4]] for line in meshpath.read_text().splitlines()
42
+ if line.startswith('v ')])
43
+ root = ET.parse(source).getroot()
44
+ asset = root.find('asset')
45
+ lo, hi = vertices.min(0), vertices.max(0)
46
+ scale = 2*np.array(half)/(hi-lo)
47
+ for el in asset:
48
+ if el.tag == 'mesh':
49
+ el.set('file', str(meshpath)); el.set('scale', _fmt(scale))
50
+ elif el.get('file'):
51
+ el.set('file', str((source.parent/el.get('file')).resolve()))
52
+ visual = copy.deepcopy(root.find('worldbody/body/body/geom'))
53
+ visual.set('group','1'); visual.set('contype','0'); visual.set('conaffinity','0')
54
+ visual.set('pos', _fmt(-(lo+hi)*scale/2)); visual.set('mass','0')
55
+ visual.attrib.pop('density',None)
56
+ mass=.06 if kind=='butter' else .025
57
+ hull = (f'<geom name="food_hull" type="box" size="{_fmt(half)}" mass="{mass}" '
58
+ 'friction=".7 .005 .0001" solref=".001 1" solimp=".998 .998 .001" group="0"/>')
59
+ xml = ET.fromstring(_wrap('breakfast_'+kind, hull+ET.tostring(visual,encoding='unicode'),half[2],.05))
60
+ xml.insert(0,asset)
61
+ return ET.tostring(xml,encoding='unicode')
62
+
63
+
64
+ def milk_station_xml():
65
+ source = LIB_ASSETS/'stable_hope_objects/milk/milk.xml'
66
+ root = ET.parse(source).getroot()
67
+ asset = root.find('asset')
68
+ for el in asset:
69
+ if el.get('file'): el.set('file', str(source.parent/el.get('file')))
70
+ carton = copy.deepcopy(root.find('worldbody/body/body'))
71
+ carton.set('name','carton_visual'); carton.set('quat','.5 .5 .5 .5')
72
+ # A carton held in a tabletop tipping cradle. The hinge is physical, unactuated.
73
+ parts = '''
74
+ <geom name="base" type="box" pos="-.025 0 .008" size=".035 .075 .008" rgba=".24 .28 .32 1"/>
75
+ <geom name="stand_l" type="capsule" fromto="0 -.055 .016 0 -.055 .21" size=".006" rgba=".5 .55 .6 1"/>
76
+ <geom name="stand_r" type="capsule" fromto="0 .055 .016 0 .055 .21" size=".006" rgba=".5 .55 .6 1"/>
77
+ <body name="tilting_carton" pos="0 0 .21">
78
+ <joint name="pull_slide" type="slide" axis="1 0 0" range="-.00001 .00001" damping="1" armature=".02"/>
79
+ <joint name="pour_hinge" type="hinge" axis="0 1 0" range="0 1.66" damping=".25" frictionloss=".05" armature=".004"/>
80
+ <inertial pos="0 0 0" mass=".25" diaginertia=".001 .001 .001"/>
81
+ <geom name="pour_bar" type="capsule" fromto="0 -.065 0 -.09 -.065 0" size=".005" rgba=".25 .25 .28 1" mass="0"/>
82
+ <geom name="pour_knob" type="sphere" pos="-.09 -.065 0" size=".013" rgba=".9 .65 .1 1" mass="0" friction="1 .005 .0001"/>
83
+ <geom name="spout" type="cylinder" pos=".026 0 .065" size=".009 .014" quat=".7071 0 .7071 0" rgba=".95 .95 .95 1" mass="0"/>
84
+ <site name="nozzle" pos=".04 0 .065" size=".006" rgba=".1 .1 .1 1"/>
85
+ </body>'''
86
+ xml = ET.fromstring(_wrap('breakfast_milk_station',parts,0,.08))
87
+ xml.insert(0,asset)
88
+ xml.find(".//body[@name='tilting_carton']").append(carton)
89
+ for parent in xml.iter('body'):
90
+ for geom in list(parent.findall('geom')):
91
+ if geom.get('group') is None:
92
+ geom.set('group','0')
93
+ vis=copy.deepcopy(geom);vis.set('group','1');vis.set('contype','0');vis.set('conaffinity','0')
94
+ vis.attrib.pop('name',None);vis.set('mass','0');parent.append(vis)
95
+ return ET.tostring(xml,encoding='unicode')
96
+
97
+
98
+ def liquid_visual_xml():
99
+ geoms = ['<geom name="milk_surface" type="cylinder" size=".029 .001" pos="0 0 -2" rgba="1 .985 .92 0" contype="0" conaffinity="0" group="1"/>']
100
+ for i in range(80):
101
+ geoms.append(f'<geom name="drop_{i}" type="sphere" size=".0035" pos="0 0 -2" rgba="1 .985 .92 0" contype="0" conaffinity="0" group="1"/>')
102
+ geoms.append('<geom name="spill" type="cylinder" size=".01 .0005" pos="0 0 -2" rgba="1 .985 .92 0" contype="0" conaffinity="0" group="1"/>')
103
+ return _wrap('breakfast_liquid', ''.join(geoms),0,.001)
104
+
105
+
106
+ def fixed_cup_xml():
107
+ source=LIB_ASSETS/'turbosquid_objects/porcelain_mug/porcelain_mug.xml'
108
+ root=ET.parse(source).getroot()
109
+ for el in root.find('asset'):
110
+ if el.get('file'):el.set('file',str(source.parent/el.get('file')))
111
+ return ET.tostring(root,encoding='unicode')
112
+
113
+
114
+ def serving_plate_xml():
115
+ source=LIB_ASSETS/'stable_scanned_objects/plate/plate.xml'
116
+ root=ET.parse(source).getroot();scale=1.5
117
+ for el in root.find('asset'):
118
+ if el.get('file'):el.set('file',str(source.parent/el.get('file')))
119
+ if el.tag=='mesh':el.set('scale',_fmt(np.fromstring(el.get('scale'),sep=' ')*scale))
120
+ for el in root.iter():
121
+ if el.tag in ('geom','site'):
122
+ if el.get('pos'):el.set('pos',_fmt(np.fromstring(el.get('pos'),sep=' ')*scale))
123
+ if el.get('size'):el.set('size',_fmt(np.fromstring(el.get('size'),sep=' ')*scale))
124
+ return ET.tostring(root,encoding='unicode')
125
+
126
+
127
+ class BreakfastSkills(RelatchSkills):
128
+ def __init__(self,env,task,recorder=None):
129
+ super().__init__(env,task,recorder)
130
+ self.bias=np.asarray(task.inst['bias'] if task.inst['mechanisms']['L1'] else [0,0,0],float)
131
+ self.correction=np.zeros(3)
132
+ self.pour_latched=False
133
+ self.pour_rad=0.
134
+ self.pour_y=0.
135
+
136
+ def move_to(self,target,*args,**kwargs):
137
+ return super().move_to(np.asarray(target)-self.correction,*args,**kwargs)
138
+
139
+ def set_gripper(self,close,steps=15):
140
+ rep=super().set_gripper(close,steps)
141
+ if close and self.task.holding_pour_knob():
142
+ self.pour_latched=True
143
+ e=self.eef_pos(); h=self.task.pour_pivot()
144
+ self.pour_rad=float(np.linalg.norm((e-h)[[0,2]]));self.pour_y=float(e[1])
145
+ elif not close:self.pour_latched=False
146
+ return rep
147
+
148
+ def _act(self,dpos,drot,grip):
149
+ if self.pour_latched and self.task.inst['mechanisms']['L3']:
150
+ e=self.eef_pos(); k=self.task.pour_knob()
151
+ if grip<0 or np.linalg.norm(e-k)>.04:self.pour_latched=False
152
+ else:
153
+ h=self.task.pour_pivot();r=(e-h)[[0,2]];rn=max(np.linalg.norm(r),1e-6)
154
+ t=np.array([-r[1],r[0]])/rn
155
+ s=np.clip(np.asarray(dpos)[[0,2]]@t,-.008,.008)
156
+ corr=(self.pour_rad-rn)*r/rn
157
+ dpos=np.array([s*t[0]+corr[0], self.pour_y-e[1],s*t[1]+corr[1]])
158
+ super()._act(dpos,drot,grip)
159
+
160
+
161
+ @register_task
162
+ class BreakfastService(PantryRelatch):
163
+ name='lh_breakfast_service'
164
+ level='L1'
165
+ category='system_identification'
166
+ failure_causes=('L1','L3','L4')
167
+ failure_types=failure_causes
168
+ agent_max_steps=360
169
+ instruction=('Prepare breakfast: put the bread from the wooden box onto the plate and close the box; '
170
+ 'pour 80 to 160 mL of milk into the cup using the milk carton in its cradle. '
171
+ 'Then store the butter inside the box and leave its lid shut. Finish with the carton upright, '
172
+ 'bread on the plate, cup upright, and gripper open and clear. Spill at most 15 mL. '
173
+ 'The cradle can be tipped with its gold side handle using ordinary gripper motions.')
174
+ instruction_indirect=instruction
175
+ agent_object_names=['bread','butter','plate','cup','milk carton','gold cradle handle','wooden box','lid knob']
176
+
177
+ def make_bddl(self):
178
+ boxroot=ET.fromstring(box_lid_xml(BOX_MODEL))
179
+ inertial=boxroot.find('.//inertial');ratio=.08/float(inertial.get('mass'))
180
+ inertial.set('mass','.08');inertial.set('diaginertia',_fmt(np.fromstring(inertial.get('diaginertia'),sep=' ')*ratio))
181
+ box=register_generated('LffBreakfastBox',ET.tostring(boxroot,encoding='unicode'),free=False)
182
+ bread=register_generated('LffBreakfastBread',food_xml('bread',BREAD_HALF))
183
+ butter=register_generated('LffBreakfastButter',food_xml('butter',BUTTER_HALF))
184
+ milk=register_generated('LffBreakfastMilk',milk_station_xml(),free=False)
185
+ liquid=register_generated('LffBreakfastLiquid',liquid_visual_xml(),free=False)
186
+ cup=register_generated('LffBreakfastCup',fixed_cup_xml(),free=False)
187
+ plate=register_generated('LffBreakfastPlate',serving_plate_xml())
188
+ objs=[('bread_1',bread,'bread_region',(-.31,-.01,-.29,.01)),
189
+ ('butter_1',butter,'butter_region',(-.31,.24,-.29,.26)),
190
+ ('plate_1',plate,'plate_region',(.02,-.26,.04,-.24))]
191
+ fx=[(BOX,box,'box_region',(-.18,-.12,-.16,-.10)),
192
+ ('milk_1',milk,'milk_region',(.24,-.01,.26,.01)),
193
+ ('liquid_1',liquid,'liquid_region',(.34,-.34,.35,-.33)),
194
+ ('cup_1',cup,'cup_region',(.14,.26,.16,.28))]
195
+ return write_bddl(self.name,self.instruction.replace(';',','),objs,fx)
196
+
197
+ def __init__(self,cam_res=None):
198
+ super().__init__(cam_res)
199
+ m=self.env.sim.model
200
+ self.milk_bid=m.body_name2id(self.env.fixtures_dict['milk_1'].root_body)
201
+ self.pour_jid=m.joint_name2id('milk_1_pour_hinge')
202
+ self.slide_jid=m.joint_name2id('milk_1_pull_slide');self.slide_qa=int(m.jnt_qposadr[self.slide_jid])
203
+ self.pour_qa=int(m.jnt_qposadr[self.pour_jid]);self.pour_dof=int(m.jnt_dofadr[self.pour_jid])
204
+ self.pour_gid=m.geom_name2id('milk_1_pour_knob')
205
+ self.nozzle_sid=m.site_name2id('milk_1_nozzle')
206
+ self.liquid_bid=m.body_name2id(self.env.fixtures_dict['liquid_1'].root_body)
207
+ self.cup_bid=m.body_name2id(self.env.fixtures_dict['cup_1'].root_body)
208
+ self.drop_gids=[m.geom_name2id('liquid_1_drop_'+str(i)) for i in range(80)]
209
+ self.surface_gid=m.geom_name2id('liquid_1_milk_surface');self.spill_gid=m.geom_name2id('liquid_1_spill')
210
+ self.liquid=None;self.phase_hook=None
211
+
212
+ def sample_instance(self,seed):
213
+ inst=super().sample_instance(seed)
214
+ rng=np.random.default_rng(seed)
215
+ inst.update(box_xy=[-.20,-.10],plate_xy=[-.09,-.32],butter_xy=[-.36,-.32],
216
+ milk_xy=[-.14,.24],cup_xy=[-.075,.24],
217
+ bias=[0,float(rng.choice([-1,1])*.10),0],
218
+ mechanisms={'L1':True,'L3':True,'L4':True},flow_ml_s=float(rng.uniform(42,48)))
219
+ return inst
220
+
221
+ def apply_instance(self,inst):
222
+ super().apply_instance(inst)
223
+ m,d=self.env.sim.model,self.env.sim.data
224
+ half_z=BUTTER_HALF[2] if inst['mechanisms']['L4'] else BUTTER_HALF[0]
225
+ quat=[1,0,0,0] if inst['mechanisms']['L4'] else [np.sqrt(.5),0,np.sqrt(.5),0]
226
+ envs.set_obj_pose(self.env,'butter_1',[*inst['butter_xy'],envs.TABLE_Z+half_z+.001],quat_wxyz=quat)
227
+ self.drift_active=False;self.active_latch=0.
228
+ envs.scale_mass(self.env,'plate_1',.4)
229
+ envs.set_friction(self.env,'plate_1',.8)
230
+ m.body_pos[self.milk_bid]=[*inst['milk_xy'],envs.TABLE_Z]
231
+ m.body_quat[self.milk_bid]=[1,0,0,0]
232
+ m.body_pos[self.liquid_bid]=[0,0,0];m.body_quat[self.liquid_bid]=[1,0,0,0]
233
+ d.qpos[self.pour_qa]=0;d.qvel[self.pour_dof]=0
234
+ d.qpos[self.slide_qa]=0
235
+ m.jnt_range[self.slide_jid]=[-.00001,.00001] if inst['mechanisms']['L3'] else [-.11,.01]
236
+ m.body_pos[self.cup_bid]=[*inst['cup_xy'],envs.TABLE_Z-.0024]
237
+ m.body_quat[self.cup_bid]=[1,0,0,0]
238
+ for gid in self.drop_gids+[self.surface_gid,self.spill_gid]:m.geom_rgba[gid,3]=0
239
+ self.liquid=dict(reservoir=300.,cup=0.,spill=0.,parcels=[],emitted=0.,spill_xy=None)
240
+ self.trace=[]
241
+
242
+ def reset_instance(self,inst,recorder=None):
243
+ self.mon=None
244
+ np.random.seed(int(inst['seed']))
245
+ self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,10)
246
+ self.mon=dict(events=[],lid_open_max=0.,armed=False)
247
+ self.sk=BreakfastSkills(self.env,self,recorder)
248
+ self.traps={k:False for k in self.failure_causes}
249
+ self.recovered={k:False for k in self.failure_causes}
250
+ self.initial_pour_pivot=self.pour_pivot().copy()
251
+ return self.sk
252
+
253
+ def _register_close(self,seated):
254
+ self.closes_done+=1;self.active_latch=0.;self.drift_active=False
255
+ self.mon['events'].append(dict(ev='closed',n=self.closes_done,mechanism='ordinary rigid-body hinge'))
256
+
257
+ def _bracket(self):
258
+ # Disable the predecessor's modeled spring/catch completely, at every physics substep.
259
+ self.env.sim.data.qfrc_applied[self.dof]=0.
260
+
261
+ def butter_corners(self):
262
+ p=envs.obj_pos(self.env,'butter_1')
263
+ R=self.env.sim.data.body_xmat[envs.body_id(self.env,'butter_1')].reshape(3,3)
264
+ return np.array([p+R@(np.array([a,b,c])*BUTTER_HALF) for a in (-1,1) for b in (-1,1) for c in (-1,1)])
265
+
266
+ def butter_height(self):
267
+ c=self.butter_corners();return float(np.ptp(c[:,2]))
268
+
269
+ def butter_in_box(self):
270
+ from .lh_lid_box import IN_X,IN_Y
271
+ c=self.butter_corners();b=np.asarray(self.inst['box_xy'])
272
+ inside=np.all(np.abs(c[:,:2]-b)<[IN_X+.001,IN_Y+.001])
273
+ return bool(inside and c[:,2].max()<envs.TABLE_Z+WALL_H+.002 and
274
+ c[:,2].min()>envs.TABLE_Z+FLOOR_T-.002 and not self.held('butter_1'))
275
+
276
+ def butter_lid_contact(self):
277
+ m=self.env.sim.model
278
+ lid=m.geom_name2id('box_1_'+BOX_MODEL+'_lid')
279
+ return envs.contacts_between(self.env,envs.obj_geom_ids(self.env,'butter_1'),[lid])
280
+
281
+ def pick_place(self,name,dest_xy,z_rel,z_carry=.18,dest_yaw=0.):
282
+ if name!='butter_1':return super().pick_place(name,dest_xy,z_rel,z_carry,dest_yaw)
283
+ s=self.sk;p=envs.obj_pos(self.env,name).copy()
284
+ tall=self.butter_height()>.045
285
+ grasp=p+np.array([0,0,.025 if tall else 0.])
286
+ s.set_gripper(False,8);s.move_to([p[0],p[1],1.12],yaw=0)
287
+ s.move_to(grasp,speed=.10,tol=.002,max_steps=120);s.set_gripper(True,20)
288
+ s.move_to([p[0],p[1],1.12],speed=.15)
289
+ if not self.held(name):s.set_gripper(False,8);return False
290
+ offset=envs.obj_pos(self.env,name)-s.eef_pos()
291
+ target=np.array([*dest_xy,envs.TABLE_Z+z_rel])-offset
292
+ s.move_to([target[0],target[1],1.12],yaw=dest_yaw)
293
+ s.move_to(target,speed=.10,tol=.003,max_steps=120)
294
+ s.set_gripper(False,12);s.move_to([target[0],target[1],1.14]);s.hold(10)
295
+ return True
296
+
297
+ def put_butter(self):
298
+ # Place the standing stick near the front wall; lay-flat placement uses the box centre.
299
+ standing=self.butter_height()>.045
300
+ target=np.array(self.inst['box_xy'])+([-0.030,0] if standing else [0,0])
301
+ return self.pick_place('butter_1',target,FLOOR_T+self.butter_height()/2+.003,z_carry=.18)
302
+
303
+ def lay_butter_flat(self):
304
+ """Extract, tip on the table through contact, then pick the horizontal stick. No pose writes."""
305
+ s=self.sk;xy=np.asarray(self.inst['butter_xy'])
306
+ self.label('L4 recovery: take the upright stick out of the box')
307
+ if not self.pick_place('butter_1',xy,self.butter_height()/2+.003,z_carry=.18):return False
308
+ p=envs.obj_pos(self.env,'butter_1').copy()
309
+ self.label('Recovery: tip the butter stick onto its broad side')
310
+ s.set_gripper(True,8)
311
+ s.move_to([p[0]-.055,p[1],1.07],yaw=0)
312
+ s.move_to([p[0]-.055,p[1],envs.TABLE_Z+.055],speed=.10)
313
+ s.move_to([p[0]+.025,p[1],envs.TABLE_Z+.055],speed=.06)
314
+ s.move_to([p[0]+.025,p[1],1.10],speed=.12);s.set_gripper(False,8);s.hold(60)
315
+ self.label('Recovery: the butter stick is now lying flat on the table')
316
+ return self.butter_height()<.029
317
+
318
+ def pour_pivot(self):
319
+ return np.array([self.inst['milk_xy'][0]+self.env.sim.data.qpos[self.slide_qa],self.inst['milk_xy'][1],envs.TABLE_Z+.21])
320
+ def pour_knob(self):return self.env.sim.data.geom_xpos[self.pour_gid].copy()
321
+ def pour_angle(self):return float(self.env.sim.data.qpos[self.pour_qa])
322
+ def holding_pour_knob(self):
323
+ g=self.env.robots[0].gripper
324
+ return bool(self.env._check_grasp(gripper=[g.important_geoms['left_finger'],g.important_geoms['right_finger']],
325
+ object_geoms=['milk_1_pour_knob','milk_1_pour_bar']))
326
+
327
+ def monitor_step(self):
328
+ super().monitor_step()
329
+ if getattr(self,'liquid',None) is None or self.mon is None:return
330
+ if self.pour_angle()<np.radians(50) and not self.liquid['parcels']:return
331
+ for sub in range(10):self.update_liquid(.005,render_update=(sub==9))
332
+
333
+ def update_liquid(self,dt,render_update=True):
334
+ """Conserved millilitres, tilt discharge, gravity trajectories and moving cup aperture.
335
+ Visual geoms are passive displays of the parcel model, never body state edits.
336
+ """
337
+ q=self.liquid;m,d=self.env.sim.model,self.env.sim.data
338
+ a=self.pour_angle();origin=d.site_xpos[self.nozzle_sid].copy()
339
+ flow=self.inst['flow_ml_s']*max(0.,min(1.,(a-np.radians(50))/np.radians(25)))
340
+ dv=min(q['reservoir'],flow*dt)
341
+ if dv>0:
342
+ # small outward speed along the spout, transformed by the actual hinge angle
343
+ vel=np.array([np.cos(a),0,-np.sin(a)])*.04
344
+ q['parcels'].append(dict(p=origin.copy(),v=vel,ml=dv))
345
+ q['reservoir']-=dv;q['emitted']+=dv
346
+ cup_origin=d.body_xpos[self.cup_bid]
347
+ cup_rot=d.body_xmat[self.cup_bid].reshape(3,3)
348
+ cup=cup_origin+cup_rot@np.array([.015,-.0016,.10]);top=cup[2]
349
+ keep=[]
350
+ for drop in q['parcels']:
351
+ p=drop['p'];v=drop['v'];end=p+v*dt+np.array([0,0,-.5*9.81*dt*dt])
352
+ caught=False
353
+ if p[2]>=top>end[2]:
354
+ hit=p+(end-p)*(p[2]-top)/(p[2]-end[2])
355
+ if np.linalg.norm(hit[:2]-cup[:2])<.029 and self.cup_upright():
356
+ q['cup']+=drop['ml'];caught=True
357
+ excess=max(0.,q['cup']-180.)
358
+ if excess:
359
+ q['cup']-=excess;q['spill']+=excess;q['spill_xy']=cup[:2].tolist()
360
+ if not caught and end[2]<=envs.TABLE_Z+.002:
361
+ q['spill']+=drop['ml'];q['spill_xy']=end[:2].tolist();caught=True
362
+ if not caught:
363
+ drop['p']=end;drop['v']=v+np.array([0,0,-9.81*dt]);keep.append(drop)
364
+ q['parcels']=keep
365
+ if not render_update:return
366
+ for i,gid in enumerate(self.drop_gids):
367
+ if i<len(keep):m.geom_pos[gid]=keep[i]['p'];m.geom_rgba[gid,3]=1
368
+ else:m.geom_rgba[gid,3]=0
369
+ m.geom_pos[self.surface_gid]=[cup[0],cup[1],top-.05+min(q['cup'],180)/180*.045]
370
+ m.geom_rgba[self.surface_gid,3]=float(q['cup']>.1)
371
+ if q['spill']>.1:
372
+ m.geom_pos[self.spill_gid]=[*q['spill_xy'],envs.TABLE_Z+.002]
373
+ m.geom_size[self.spill_gid,0]=min(.08,.009*np.sqrt(q['spill']))
374
+ m.geom_rgba[self.spill_gid,3]=1
375
+ self.env.sim.forward()
376
+
377
+ def cup_upright(self):
378
+ # Native mug uses world Z as its vertical in the loaded LIBERO pose.
379
+ return bool(self.env.sim.data.body_xmat[self.cup_bid].reshape(3,3)[2,2]>.94)
380
+
381
+ def label(self,text):
382
+ state=dict(text=text,step=self.sk.n_steps,lid_deg=self.lid_deg(),
383
+ pour_deg=float(np.degrees(self.pour_angle())),cup_ml=self.liquid['cup'],spill_ml=self.liquid['spill'],
384
+ butter_height_cm=100*self.butter_height(),butter_lid_contact=bool(self.butter_lid_contact()),
385
+ lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof]))
386
+ self.trace.append(state)
387
+ if self.phase_hook:self.phase_hook(text,state)
388
+
389
+ def calibration_probe(self):
390
+ # Attempt the loose butter first, away from fixture walls; fixed bias is present for ALL motions.
391
+ p=envs.obj_pos(self.env,'butter_1').copy();s=self.sk
392
+ s.set_gripper(False,8);s.move_to([p[0],p[1],envs.TABLE_Z+.14],yaw=0,tol=.0005,max_steps=120)
393
+ observed=s.eef_pos()-np.array([p[0],p[1],envs.TABLE_Z+.14])
394
+ s.move_to(p,tol=.002,max_steps=100)
395
+ s.set_gripper(True,15);s.move_to([p[0],p[1],envs.TABLE_Z+.15])
396
+ failed=not s.holding('butter_1')
397
+ self.traps['L1']=bool(failed)
398
+ self.label('L1: grasp missed the butter' if failed else 'Calibration grasp succeeded')
399
+ s.set_gripper(False,8)
400
+ return observed
401
+
402
+ def direct_carton_lift(self):
403
+ s=self.sk;k=self.pour_knob();start=k.copy()
404
+ s.set_gripper(False,8)
405
+ s.move_to(k+[0,0,.10],yaw=0)
406
+ s.move_to(k,speed=.12,max_steps=100)
407
+ s.set_gripper(True,20)
408
+ held_before=self.holding_pour_knob()
409
+ # Pulling along the radius cannot translate a hinged cradle. Same low-level interface as agents.
410
+ s.move_to(k+[-.07,0,0],speed=.08,max_steps=30)
411
+ lift=float(np.linalg.norm(self.pour_knob()-start))
412
+ self.pull_probe=dict(held_before=held_before,held_after=self.holding_pour_knob(),displacement_m=lift,
413
+ angle_deg=float(np.degrees(self.pour_angle())))
414
+ self.traps['L3']=bool(held_before and lift<.01 and self.liquid['cup']<1)
415
+ self.label('L3: straight pull failed; the cradle only rotates')
416
+ s.set_gripper(False,10);s.move_to(s.eef_pos()+[0,0,.10])
417
+ return lift
418
+
419
+ def tip_carton(self,target_ml=110.):
420
+ s=self.sk;k=self.pour_knob();h=self.pour_pivot()
421
+ s.set_gripper(False,8);s.move_to(k+[0,0,.09],yaw=0)
422
+ s.move_to(k,tol=.002,max_steps=120);s.set_gripper(True,20)
423
+ self.label('Recovery: grasp the gold handle and tip the carton')
424
+ if not s.pour_latched:return False
425
+ for deg in range(10,81,10):
426
+ a=np.radians(deg)
427
+ target=h+[-.09*np.cos(a),-.065,.09*np.sin(a)]
428
+ s.move_to(target,speed=.06,max_steps=90,tol=.003)
429
+ self.label(f'Tipping handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}')
430
+ self.label('Pouring milk into the cup')
431
+ for _ in range(120):
432
+ if self.liquid['cup']+sum(p['ml'] for p in self.liquid['parcels'])>=target_ml:break
433
+ s.hold(1)
434
+ for deg in range(70,-1,-10):
435
+ a=np.radians(deg)
436
+ s.move_to(h+[-.09*np.cos(a),-.065,.09*np.sin(a)],speed=.10,max_steps=90,tol=.003)
437
+ self.label(f'Returning handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}')
438
+ s.set_gripper(False,10);e=s.eef_pos();s.move_to(e+[0,0,.12]);s.hold(15)
439
+ self.recovered['L3']=bool(80<=self.liquid['cup']<=160 and self.liquid['spill']<=15)
440
+ self.label('Milk poured; carton returned upright')
441
+ return self.recovered['L3']
442
+
443
+ def bread_on_plate(self):
444
+ p=envs.obj_pos(self.env,'bread_1');plate=envs.obj_pos(self.env,'plate_1')
445
+ return bool(np.linalg.norm(p[:2]-plate[:2])<.05 and p[2]<envs.TABLE_Z+.08 and
446
+ not self.held('bread_1') and envs.contacts_between(self.env,envs.obj_geom_ids(self.env,'bread_1'),
447
+ envs.obj_geom_ids(self.env,'plate_1')))
448
+
449
+ def take_bread(self):
450
+ s=self.sk;p=envs.obj_pos(self.env,'bread_1').copy()
451
+ s.set_gripper(False,8);s.move_to([p[0],p[1],1.04],yaw=0)
452
+ s.move_to(p,tol=.003);s.set_gripper(True,15);s.move_to([p[0],p[1],1.04],speed=.3)
453
+ self.label(f'Bread pickup: held={s.holding("bread_1")}, pos={envs.obj_pos(self.env,"bread_1").round(3).tolist()}, eef={s.eef_pos().round(3).tolist()}')
454
+ if not s.holding('bread_1'):return False
455
+ off=envs.obj_pos(self.env,'bread_1')-s.eef_pos()
456
+ plate=envs.obj_pos(self.env,'plate_1')
457
+ goal=np.array([plate[0],plate[1],envs.obj_max_z(self.env,'plate_1')+BREAD_HALF[2]+.035])-off
458
+ s.move_to([goal[0],goal[1],1.12],yaw=0)
459
+ s.move_to(goal,speed=.10);s.set_gripper(False,15);s.move_to([goal[0],goal[1],1.14]);s.hold(10)
460
+ self.label(f'Bread placement: goal={goal.round(3).tolist()}, bread={envs.obj_pos(self.env,"bread_1").round(3).tolist()}, plate={envs.obj_pos(self.env,"plate_1").round(3).tolist()}')
461
+ return self.bread_on_plate()
462
+
463
+ def execute(self,inst,params):
464
+ mode=params.get('mode','adaptive');s=self.sk
465
+ self.label('Prepare breakfast: milk, bread and butter')
466
+ if mode=='oracle':s.correction=s.bias.copy()
467
+ else:
468
+ observed=self.calibration_probe()
469
+ if mode in ('naive','blind') and self.traps['L1']:return
470
+ s.correction=observed*np.array([1,1,0])
471
+ # Same attempt: use observed gripper error, then re-grasp and return the butter to its starting area.
472
+ ok=self.pick_place('butter_1',inst['butter_xy'],BUTTER_HALF[2]+.002)
473
+ self.recovered['L1']=bool(ok)
474
+ self.label('L1 recovery: corrected the offset and grasped the butter' if ok else 'Butter re-grasp failed')
475
+ if not ok:return
476
+ self.open_lid()
477
+ if not self.take_bread():self.label('Bread grasp failed');return
478
+ self.label('Bread placed on the plate')
479
+ self.close_lid(False)
480
+ if mode!='oracle' and inst['mechanisms']['L3']:
481
+ self.direct_carton_lift()
482
+ if mode in ('naive','blind'):return
483
+ if not self.tip_carton():self.label('Milk pour incomplete');return
484
+ self.open_lid()
485
+ if mode=='oracle' and self.butter_height()>.045:
486
+ if not self.lay_butter_flat():self.label('Butter reorientation failed');return
487
+ if not self.put_butter():self.label('Butter storage failed');return
488
+ self.label('Upright butter stick: too tall for the shallow box' if self.butter_height()>.045
489
+ else 'Butter stick laid flat inside the box')
490
+ self.close_lid(False)
491
+ if mode not in ('oracle','naive','blind'):
492
+ self.label('Check whether the upright butter stick fits beneath the lid')
493
+ s.hold(80)
494
+ self.traps['L4']=bool(self.lid_deg()>5 and self.butter_lid_contact())
495
+ self.label('L4: upright butter stick physically blocks the lid' if self.traps['L4'] else 'No lid obstruction detected')
496
+ if not self.lid_closed():
497
+ self.open_lid()
498
+ if not self.lay_butter_flat():self.label('Butter reorientation failed');return
499
+ if not self.put_butter():self.label('Horizontal butter placement failed');return
500
+ self.label('Butter stick laid flat inside the box')
501
+ self.close_lid(False)
502
+ s.hold(60)
503
+ self.recovered['L4']=bool(self.lid_closed() and self.butter_in_box())
504
+ self.label('L4 recovery: butter laid flat; the lid closes normally')
505
+ if not self.bread_on_plate():
506
+ self.label('Final check: restore the bread disturbed during cleanup')
507
+ self.take_bread()
508
+ s.set_gripper(False,8);s.move_to([-.35,-.30,1.20]);s.hold(15)
509
+
510
+ def default_params(self,inst):return {'mode':'naive'}
511
+ def oracle_params(self,inst):return {'mode':'oracle'}
512
+ def adapt_params(self,inst,history):return {'mode':'adaptive'}
513
+ def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None):
514
+ rng=np.random.default_rng(seed);hist=[]
515
+ for attempt in range((k or 5) if kind=='blind' else 1):
516
+ self.reset_instance(inst)
517
+ if kind=='blind':self.sk.correction[:2]=rng.uniform(-.012,.012,2)
518
+ self.execute(inst,{'mode':kind})
519
+ out=self.outcome(inst);hist.append(dict(attempt=attempt+1,params={'mode':kind},outcome=out))
520
+ if on_attempt:on_attempt(attempt,hist[-1]['params'],out)
521
+ if out['success']:break
522
+ return hist
523
+
524
+ def outcome(self,inst):
525
+ out=super().outcome(inst);q=self.liquid
526
+ inflight=sum(p['ml'] for p in q['parcels'])
527
+ out.update(cup_ml=round(q['cup'],3),spill_ml=round(q['spill'],3),reservoir_ml=round(q['reservoir'],3),
528
+ inflight_ml=round(inflight,3),conservation_error_ml=abs(300-q['reservoir']-q['cup']-q['spill']-inflight),
529
+ pour_deg=round(float(np.degrees(self.pour_angle())),2),traps=dict(self.traps),recovered=dict(self.recovered))
530
+ out['stages'].update(milk_served=bool(80<=q['cup']<=160),spill_ok=bool(q['spill']<=15),
531
+ carton_upright=bool(abs(self.pour_angle())<.15),cup_upright=self.cup_upright(),
532
+ gripper_open=bool(self.sk.grip<0),
533
+ gripper_clear=bool(min(np.linalg.norm(self.sk.eef_pos()-envs.obj_pos(self.env,n))
534
+ for n in ('bread_1','butter_1'))>.06),
535
+ carton_static=bool(abs(self.env.sim.data.qvel[self.pour_dof])<.1))
536
+ out['success']=bool(out['success'] and all(out['stages'].values()))
537
+ if not out['success'] and out['failure'] is None:
538
+ out['failure']=next((k for k,v in out['stages'].items() if not v),'not_static')
539
+ out['detail']=(f"Bread on plate: {out['stages']['bread_on_plate']}; butter fully below the box rim: "
540
+ f"{out['stages']['butter_in_box']}; lid angle: {self.lid_deg():.1f} degrees. "
541
+ f"Milk in cup: {q['cup']:.1f} mL; spilled: {q['spill']:.1f} mL. "
542
+ f"Butter height: {100*self.butter_height():.1f} cm.")
543
+ if self.butter_lid_contact() and not self.lid_closed():out['detail']+=' The upright butter stick is touching and obstructing the lid.'
544
+ out.update(geometry_version=2,butter_height_cm=round(100*self.butter_height(),3),
545
+ butter_lid_contact=bool(self.butter_lid_contact()),lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof]))
546
+ return out
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH bystander: put three cubes into an open box while a tall glass bottle that is not part of the task stands right
2
+ in front of the box -- lowering a cube into the box, the robot's own forearm comes down onto the bottle and knocks it
3
+ over.
4
+
5
+ Family: long-horizon self-disturbance, environment level ("state_restoration"; LIBERO-Recover's damage category L4: the
6
+ damaged thing is not part of the task). Three easy pick-and-place stages; the instruction says plainly that nothing
7
+ else may be moved and that the bottle must be left standing where it is. The agent has to notice the fallen bottle and
8
+ stand it up again on its spot before finishing (within an attempt), or learn to keep its arm off the bottle (across
9
+ attempts).
10
+
11
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
12
+ * an open wooden box (fixture): cavity 14 x 14 cm, walls 6 cm high (rim 6.6 cm above the table), 0.8 cm thick;
13
+ centre x in [0.00, 0.04], 6-10 cm left or right of the middle;
14
+ * three 4 cm cubes (red / yellow / blue, 32 g) in a row beside the box on the other side (19-23 cm from the middle,
15
+ from 10 cm behind to 2 cm in front of the box centre, shuffled, yaw +-17 deg), so that a straight carry to the box
16
+ never passes over the bottle;
17
+ * the bystander: a square green glass bottle with a label and a round red cap, 28.4 cm tall (body 6 x 6 x 18.5 cm,
18
+ shoulder, neck, cap; a rounded base whose flat contact is 3.6 x 3.6 cm), 0.25 kg, centre of mass 12 cm up (an empty
19
+ bottle: it tips beyond 8.5 deg; pressed down on its cap, beyond 3.7 deg).
20
+
21
+ Instance variable (where the bottle stands): "hazard" (15 of every 20 consecutive seeds): right in front of the box,
22
+ between the box and the robot, 1.0-2.5 cm from its front wall, 1 cm right to 4 cm left of its centre line; "benign":
23
+ beside the box on its outer side, 8-11 cm from the wall. Both look like "a bottle standing next to the box"; nothing in
24
+ the physics is hidden. What the agent cannot see before acting is its own arm: the wrist camera shows the fingers, not
25
+ the forearm, and the agent steers the grasp point.
26
+
27
+ Disturbance (physics, no teleport): lowering a cube onto the box floor (grasp point ~4 cm above the table), the
28
+ fingers and the cube stay 3-5 cm clear of the bottle (the box's front wall is between them), but the Panda's forearm
29
+ and wrist (links 5-7) slope back from the hand towards the robot base, starting ~12 cm above the grasp point; over the
30
+ space in front of the box they come down to 15-20 cm above the table, onto the upper part of a 28 cm bottle standing
31
+ there. The bottle is pushed over (mostly
32
+ towards the robot) and lies on the table in front of the box; visible in agentview once the arm has moved away
33
+ (measured, task card). Not every contact knocks it: a descent can come to rest on the cap (pinched between links 5
34
+ and 6, pressed down like a column), the arm stalls 4-6 cm short of its target and the bottle rocks back when the arm
35
+ lifts (measured: the smoke-test sequence on seed 3000; 6-7 of 8 hazard seeds still knocked with slow or near-first
36
+ descents, see the task card). The hit is yaw-independent (hit maps at yaw 0 / 45 / 90 deg) and not caused by the hand's
37
+ width. Transits at the agent's usual 11-20 cm mostly pass (the wrist end of the forearm is ~27 cm up at a 15 cm
38
+ transit). A careful packer keeps its arm above the bottle: carry at >= 24 cm and release the cube from >= 18 cm
39
+ (dropping it into the box) -- or moves the bottle out of the way and back, which the final-state judge would accept
40
+ but the instruction rules out.
41
+
42
+ Restoring (re-standable by a top-down gripper that only turns about the vertical): the body is square (a lying bottle
43
+ does not roll away from the closing fingers) and the cap is a ball with low torsional friction: grasped from above with
44
+ the fingers across the lying bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs
45
+ straight; lowered onto the table it stands (measured: placement error ~1 mm). The instruction tells the agent that the
46
+ bottle hangs straight down when held by its cap (as lh_fence does for its knobs).
47
+
48
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the
49
+ box -- footprint inside the cavity, top below the rim, not held --, the bottle upright within 10 deg and its base
50
+ within 2 cm of where it stood, nothing held or touched, scene static) plus a per-step event log for the server log:
51
+ cube stages achieved / lost / restored; bottle_in_place lost / restored (with cause: arm / hand / cube, the robot geom,
52
+ the grasp point) plus the marker events bystander_knocked / bystander_restored / fallen. F1 gives the agent only
53
+ success / failure.
54
+ """
55
+ import numpy as np
56
+
57
+ from .. import envs
58
+ from ..bddl import write_bddl
59
+ from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated
60
+ from ..skills import Skills
61
+ from ..task_base import LFFTask, register_task
62
+
63
+ Z = envs.TABLE_Z
64
+ # ---------------------------------------------------------------- geometry / physics
65
+ BOX = "box_1"
66
+ BOX_MODEL = "lff_lhb_box"
67
+ BOX_IN = 0.070 # cavity half width (14 x 14 cm)
68
+ WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.060
69
+ BOX_OUT = BOX_IN + WALL_T
70
+ RIM = FLOOR_T + WALL_H # rim height above the table
71
+ WOOD = (0.62, 0.45, 0.28, 1.0)
72
+
73
+ CUBES = ("red_cube_1", "yellow_cube_1", "blue_cube_1")
74
+ CUBE_COLOR = {"red_cube_1": "red", "yellow_cube_1": "yellow", "blue_cube_1": "blue"}
75
+ CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0))
76
+ CUBE_E = 0.040
77
+ CUBE_DENS = 500.0 # 32 g
78
+ CUBE_MU = 0.8
79
+
80
+ BOTTLE = "bottle_1"
81
+ BOTTLE_MODEL = "lff_lhb_bottle"
82
+ BOTTLE_CLASS = "LffLhbBottle"
83
+ RB, HB = 0.030, 0.185 # square body: half width, height
84
+ RF, HF = 0.018, 0.006 # foot: a rounded glass base whose flat contact is 3.6 x 3.6 cm (0.6 cm high inset). With the
85
+ # 4.8 cm foot of the draft the forearm could come to rest on the cap and stall instead of
86
+ # knocking it (bottle pressed down like a column, tilt <= 5 deg; measured, see the task card)
87
+ RS, HS = 0.022, 0.015 # shoulder
88
+ RN, HN = 0.0115, 0.060 # neck
89
+ RK = 0.015 # ball cap radius; its centre sits RK - 6 mm above the neck top
90
+ CAP_SINK = 0.006
91
+ H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.284
92
+ CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing
93
+ BOTTLE_MASS = 0.25
94
+ BOTTLE_COM = 0.12 # above the bottom (an empty glass bottle: ~42 % of its height)
95
+ BOTTLE_MU = 0.6
96
+ CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely, the swing is damped
97
+ GLASS = (0.16, 0.42, 0.26, 1.0)
98
+ CAP_RGBA = (0.78, 0.12, 0.10, 1.0)
99
+
100
+ # instances
101
+ P_HAZARD = 0.75 # 15 of every 20 consecutive seeds: bottle in front of the box
102
+ HAZ_GAP = (0.010, 0.025) # bottle body to the box's front wall
103
+ HAZ_LAT = (-0.010, 0.040) # bottle centre left (+y) of the box's centre line
104
+ BEN_GAP = (0.080, 0.110) # beside the box, on its outer side (away from the cubes)
105
+ BEN_DX = (-0.030, 0.030)
106
+ BOX_X = (0.0, 0.04) # the bottle in front of the box stays >= 2 cm clear of the fingers in the home pose
107
+ BOX_Y = (0.06, 0.10) # |y| of the box centre; the side is random
108
+ CUBE_Y = (0.19, 0.23) # |y| of the cube row (other side)
109
+ CUBE_DX = (-0.10, -0.04, 0.02) # cube row beside the box (x relative to the box centre; the Panda reaches ~0.8 m):
110
+ # the straight carry to the box passes >= 2 cm from the bottle in front of it
111
+
112
+ # success predicate
113
+ POS_TOL = 0.020 # bottle base within 2 cm of where it stood
114
+ UPRIGHT = np.radians(10.0)
115
+ KNOCK_TILT = np.radians(10.0) # once in place, the bottle counts as disturbed when tilted beyond this (it tips at
116
+ # 8.5 deg: beyond, it is falling or leaning on something) or moved
117
+ POS_HYST = 0.003 # > POS_TOL + POS_HYST for DEBOUNCE checks (a nudge that rocks back within 0.6 s is no loss)
118
+ FALLEN = np.radians(60.0)
119
+ IN_TOL = 0.002 # a cube's footprint may reach this far past the inner walls
120
+ RIM_TOL = 0.004
121
+ BELOW_RIM = 0.010 # in_box: the cube's lowest point at least this far below the rim
122
+ DEBOUNCE = 6 # predicate checks (every 0.1 s) a change must persist
123
+
124
+ # scripted motion (heights of the grasp point above the table)
125
+ Z_CARRY = 0.15 # Sonnet's transit: 11-20 cm, often lifted to ~20 before moving
126
+ Z_REL = 0.040 # Sonnet-like release: cube set down on the box floor (grasp point 4 cm up)
127
+ Z_SAFE = 0.26 # careful transit
128
+ Z_DROP = 0.19 # careful release: the cube is dropped from above the rim, the forearm stays above the bottle
129
+ NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm
130
+ SLOT = 0.033 # slot offset from the box centre (cavity 14 cm, cubes 4 cm)
131
+
132
+
133
+ def bottle_xml(name):
134
+ h = H_TOT / 2
135
+ zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2
136
+ zk = -h + HB + HS + HN + RK - CAP_SINK
137
+ m = BOTTLE_MASS
138
+ ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 16 # rough: most of the glass is in the body and the base
139
+ izz = m * (2 * (2 * RB) ** 2) / 12
140
+ parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
141
+ ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
142
+ ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
143
+ ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
144
+ ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
145
+ s = [f' <inertial pos="0 0 {-h + BOTTLE_COM:.4f}" mass="{m}" diaginertia="{ixx:.6f} {ixx:.6f} {izz:.6f}" />']
146
+ for nm, typ, pos, size, c, extra in parts:
147
+ s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
148
+ f'{extra} group="0" />')
149
+ s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
150
+ f'conaffinity="0" group="1" />')
151
+ # a lighter label band (visual only) so the bottle reads as a bottle
152
+ s.append(f' <geom type="box" pos="0 0 {zb + 0.01:.4f}" size="{RB + 0.0008:.4f} {RB + 0.0008:.4f} 0.035" '
153
+ f'rgba="0.92 0.90 0.80 1" contype="0" conaffinity="0" group="1" />')
154
+ return _wrap(name, "\n".join(s), h, RB * 1.42)
155
+
156
+
157
+ def box_fixture_xml(name):
158
+ """open wooden box, origin at the centre of its footprint, z = 0 at the table"""
159
+ ix = BOX_IN
160
+ parts = [((0, 0, FLOOR_T / 2), (BOX_OUT, BOX_OUT, FLOOR_T / 2)),
161
+ ((ix + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)),
162
+ ((-ix - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)),
163
+ ((0, ix + WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2)),
164
+ ((0, -ix - WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2))]
165
+ g = []
166
+ for k, (p, sz) in enumerate(parts):
167
+ g.append(f' <geom name="{name}_w{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(WOOD)}" '
168
+ f'friction="0.8 0.005 0.0001" {_SOLID} group="0" />')
169
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(WOOD)}" contype="0" '
170
+ f'conaffinity="0" group="1" />')
171
+ return f"""<mujoco model="{name}">
172
+ <worldbody>
173
+ <body>
174
+ <body name="object">
175
+ {chr(10).join(g)}
176
+ </body>
177
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
178
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {RIM:.4f}" name="top_site" />
179
+ <site rgba="0 0 0 0" size="0.005" pos="{BOX_OUT:.4f} {BOX_OUT:.4f} 0" name="horizontal_radius_site" />
180
+ </body>
181
+ </worldbody>
182
+ </mujoco>"""
183
+
184
+
185
+ REACH_MAX = 0.74 # scripted policies: farthest grasp point (horizontal distance from the robot base) they rely on
186
+
187
+
188
+ def _reach(p):
189
+ return float(np.hypot(p[0] + 0.66, p[1]))
190
+
191
+
192
+ def _fb(v):
193
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
194
+
195
+
196
+ def _lr(v):
197
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
198
+
199
+
200
+ class BystanderSkills(Skills):
201
+ """Skills that feed the task's per-step monitor."""
202
+
203
+ def __init__(self, env, task, recorder=None):
204
+ super().__init__(env, recorder=recorder)
205
+ self.task = task
206
+
207
+ def _act(self, dpos, drot, grip):
208
+ super()._act(dpos, drot, grip)
209
+ self.task.monitor_step()
210
+
211
+
212
+ @register_task
213
+ class Bystander(LFFTask):
214
+ name = "lh_bystander"
215
+ level = "L2"
216
+ category = "state_restoration"
217
+ capabilities = ("Perceive", "Reason", "Restore", "Plan")
218
+ protocol = "cross"
219
+ max_attempts = 3
220
+ agent_max_steps = 100 # careful: 3 cubes x ~7 commands + looking; standing the bottle up again ~8-10; + slack
221
+ instruction = ("Put the red, yellow and blue cubes into the open wooden box. Do not move anything else: the tall "
222
+ "glass bottle must be left standing upright exactly where it is now. (The bottle has a round red "
223
+ "cap; held by its cap, the bottle hangs straight down.)")
224
+ instruction_indirect = ("Pack the three small cubes (red, yellow, blue) into the wooden crate. Leave everything else "
225
+ "as it is -- the tall green bottle has to stay standing on its spot. (Its round red cap: held "
226
+ "by the cap, the bottle hangs straight down.)")
227
+ agent_object_names = ["red cube", "yellow cube", "blue cube", "open wooden box",
228
+ "tall glass bottle (square, with a round red cap; held by its cap it hangs straight down)"]
229
+
230
+ # ------------------------------------------------------------ scene
231
+ def make_bddl(self):
232
+ box = register_generated("LffLhbBox", box_fixture_xml(BOX_MODEL), free=False)
233
+ objs = []
234
+ for i, n in enumerate(CUBES):
235
+ c = CUBE_COLOR[n]
236
+ cat = register_generated(f"LffLhbCube{c.title()}",
237
+ box_xml(f"lff_lhb_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS,
238
+ friction=(CUBE_MU, 0.005, 0.0001)).replace(_SOLID, ""))
239
+ objs.append((n, cat, f"{c}_cube_region", (-0.35, -0.25 + 0.15 * i, -0.33, -0.23 + 0.15 * i)))
240
+ bt = register_generated(BOTTLE_CLASS, bottle_xml(BOTTLE_MODEL))
241
+ objs.append((BOTTLE, bt, "bottle_region", (-0.35, 0.24, -0.33, 0.26)))
242
+ fx = [(BOX, box, "box_region", (-0.06, -0.01, -0.04, 0.01))]
243
+ return write_bddl(self.name, "put the cubes into the box and leave the bottle where it is", objs, fx)
244
+
245
+ def __init__(self, cam_res=None):
246
+ super().__init__(cam_res)
247
+ m = self.env.sim.model
248
+ self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
249
+ self.box_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in
250
+ {self.box_bid} | {c for c in range(m.nbody) if m.body_parentid[c] == self.box_bid}}
251
+ pre = f"{BOTTLE}_{BOTTLE_MODEL}"
252
+ self.cap_gid = m.geom_name2id(pre + "_cap")
253
+ self.bottle_gids = set(envs.obj_geom_ids(self.env, BOTTLE))
254
+ self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES}
255
+ # robot parts: 1 = hand / fingers (what the agent sees and steers), 2 = arm links (wrist, forearm, ...)
256
+ self.part = np.zeros(m.ngeom, int)
257
+ for g in envs.robot_geom_ids(self.env):
258
+ n = m.geom_id2name(g) or ""
259
+ self.part[g] = 1 if n.startswith("gripper0_") else 2
260
+ self.other = np.zeros(m.ngeom, int) # 3 = a cube, 4 = the box
261
+ for n in CUBES:
262
+ self.other[list(self.cube_gids[n])] = 3
263
+ self.other[list(self.box_gids)] = 4
264
+ self.is_bottle = np.zeros(m.ngeom, bool)
265
+ self.is_bottle[list(self.bottle_gids)] = True
266
+ # bottle contacts are collected after every MuJoCo substep (a fast hit can be shorter than a control step)
267
+ sim = self.env.sim
268
+ if not getattr(sim, "_lhb_wrapped", False):
269
+ orig = sim.step
270
+
271
+ def step(*a, **k):
272
+ orig(*a, **k)
273
+ t = getattr(sim, "_lhb_task", None)
274
+ if t is not None and t.mon is not None:
275
+ t._substep()
276
+ sim.step = step
277
+ sim._lhb_wrapped = True
278
+ sim._lhb_task = self
279
+ self._sub = {}
280
+ self.inst = None
281
+ self.mon = None
282
+ self.sk = None
283
+
284
+ def sample_instance(self, seed):
285
+ rng = np.random.default_rng(seed)
286
+ s = 1.0 if rng.random() < 0.5 else -1.0 # box on the left (+1) or right (-1)
287
+ bx, by = float(rng.uniform(*BOX_X)), s * float(rng.uniform(*BOX_Y))
288
+ # balanced blocks like lh_lid_box: exactly round(20 * P_HAZARD) of every 20 consecutive seeds are hazards
289
+ hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD))
290
+ if hazard:
291
+ gap, lat = float(rng.uniform(*HAZ_GAP)), float(rng.uniform(*HAZ_LAT))
292
+ bottle = [bx - BOX_OUT - gap - RB, by + lat]
293
+ else:
294
+ gap, lat = float(rng.uniform(*BEN_GAP)), float(rng.uniform(*BEN_DX))
295
+ bottle = [bx + lat, by + s * (BOX_OUT + gap + RB)]
296
+ cy = -s * float(rng.uniform(*CUBE_Y))
297
+ perm = rng.permutation(len(CUBES))
298
+ start = {CUBES[i]: [float(bx + CUBE_DX[j] + rng.uniform(-0.01, 0.01)), float(cy + rng.uniform(-0.01, 0.01))]
299
+ for j, i in enumerate(perm)}
300
+ start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in CUBES}
301
+ return dict(seed=int(seed), hazard=hazard, bottle_side="front" if hazard else "outer side",
302
+ box_side="left" if s > 0 else "right", box_xy=[bx, by], bottle_xy=[float(bottle[0]), float(bottle[1])],
303
+ bottle_yaw=float(rng.uniform(-0.25, 0.25)), gap=gap, lat=lat, start=start, start_yaw=start_yaw)
304
+
305
+ def apply_instance(self, inst):
306
+ self.inst = inst
307
+ m = self.env.sim.model
308
+ bx, by = inst["box_xy"]
309
+ m.body_pos[self.box_bid] = [bx, by, Z]
310
+ m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
311
+ for n, xy in inst["start"].items():
312
+ envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n], clearance=0.001)
313
+ envs.set_friction(self.env, n, CUBE_MU)
314
+ envs.place_upright(self.env, BOTTLE, inst["bottle_xy"], yaw=inst["bottle_yaw"], clearance=0.001)
315
+
316
+ def reset_instance(self, inst, recorder=None):
317
+ self.mon = None
318
+ self.env.reset()
319
+ self.apply_instance(inst)
320
+ self.env.sim.forward()
321
+ envs.settle(self.env, 15)
322
+ self.sk = BystanderSkills(self.env, self, recorder=recorder)
323
+ self._sub = {}
324
+ self._init_monitor()
325
+ return self.sk
326
+
327
+ # ------------------------------------------------------------ state helpers
328
+ def R(self, name):
329
+ return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy()
330
+
331
+ def bottle_tilt(self):
332
+ return float(np.arccos(np.clip(self.R(BOTTLE)[2, 2], -1.0, 1.0)))
333
+
334
+ def bottle_base(self):
335
+ """xy of the centre of the bottle's bottom face"""
336
+ d = self.env.sim.data
337
+ return (envs.obj_pos(self.env, BOTTLE) - self.R(BOTTLE)[:, 2] * H_TOT / 2)[:2]
338
+
339
+ def bottle_offset(self):
340
+ return self.bottle_base() - np.asarray(self.inst["bottle_xy"])
341
+
342
+ def cap_xyz(self):
343
+ return self.env.sim.data.geom_xpos[self.cap_gid].copy()
344
+
345
+ def held(self, name):
346
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
347
+
348
+ def bottle_in_place(self, tol=POS_TOL, tilt=UPRIGHT):
349
+ return bool(self.bottle_tilt() <= tilt and np.linalg.norm(self.bottle_offset()) <= tol
350
+ and envs.obj_min_z(self.env, BOTTLE) < Z + 0.01 and not self.held(BOTTLE))
351
+
352
+ def to_box(self, xy):
353
+ return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"])
354
+
355
+ def in_box(self, name):
356
+ m, d = self.env.sim.model, self.env.sim.data
357
+ g = next(iter(self.cube_gids[name]))
358
+ Rg = d.geom_xmat[g].reshape(3, 3)
359
+ c = self.to_box(d.geom_xpos[g][:2])
360
+ ext = np.abs(Rg[:2, :]) @ m.geom_size[g][:3]
361
+ # 10-14: "in the box" = footprint inside the cavity and the cube's lowest point well below the rim (it is held
362
+ # by the walls); a cube stacked on another one may stick out above the rim -- the instruction never asks for
363
+ # "below the rim" (two Sonnet pilot attempts that stacked the last cube were judged failures before this)
364
+ return bool(np.all(np.abs(c) + ext <= BOX_IN + IN_TOL) and envs.obj_min_z(self.env, name) <= Z + RIM - BELOW_RIM
365
+ and not self.held(name))
366
+
367
+ def over_box(self, name):
368
+ c = self.to_box(envs.obj_pos(self.env, name)[:2])
369
+ return bool(np.all(np.abs(c) <= BOX_OUT))
370
+
371
+ def stage_values(self):
372
+ v = {f"{CUBE_COLOR[n]}_in_box": self.in_box(n) for n in CUBES}
373
+ v["bottle_in_place"] = self.bottle_in_place()
374
+ return v
375
+
376
+ # ------------------------------------------------------------ per-step monitor
377
+ def _init_monitor(self):
378
+ keys = [f"{CUBE_COLOR[n]}_in_box" for n in CUBES] + ["bottle_in_place"]
379
+ st = {k: False for k in keys}
380
+ st["bottle_in_place"] = self.bottle_in_place()
381
+ self.mon = dict(state=st, ever=[k for k in keys if st[k]], lost=[], events=[], cand={k: 0 for k in keys},
382
+ step=0, last_touch=None, robot_touch_step=-10 ** 9, touch_parts=[], n_knocks=0, n_fallen=0,
383
+ fallen=False,
384
+ max_tilt_deg=0.0, max_offset_cm=0.0, first_knock_step=None, first_touch_step=None)
385
+
386
+ def _substep(self):
387
+ d = self.env.sim.data
388
+ n = d.ncon
389
+ if not n:
390
+ return
391
+ g1 = np.asarray(d.contact.geom1)[:n]
392
+ g2 = np.asarray(d.contact.geom2)[:n]
393
+ b1, b2 = self.is_bottle[g1], self.is_bottle[g2]
394
+ sel = b1 ^ b2
395
+ if not sel.any():
396
+ return
397
+ other = np.where(b1, g2, g1)[sel]
398
+ for o in other:
399
+ p = int(self.part[o])
400
+ if p:
401
+ who = "hand" if p == 1 else "arm"
402
+ prev = self._sub.get("robot")
403
+ self._sub["robot"] = "arm" if (who == "arm" or prev == "arm") else "hand"
404
+ self._sub.setdefault("geom", self.env.sim.model.geom_id2name(int(o)))
405
+ elif self.other[o] == 3:
406
+ self._sub["cube"] = True
407
+
408
+ def monitor_step(self):
409
+ mon = self.mon
410
+ if mon is None:
411
+ return
412
+ mon["step"] += 1
413
+ step = self.sk.n_steps if self.sk is not None else mon["step"]
414
+ sub, self._sub = self._sub, {}
415
+ if "robot" in sub:
416
+ mon["robot_touch_step"] = step
417
+ mon["last_touch"] = [sub["robot"], step, sub.get("geom", "")]
418
+ if sub["robot"] not in mon["touch_parts"]:
419
+ mon["touch_parts"].append(sub["robot"])
420
+ if mon["first_touch_step"] is None:
421
+ mon["first_touch_step"] = step
422
+ elif sub.get("cube") and (mon["last_touch"] is None or step - mon["last_touch"][1] > 20):
423
+ mon["last_touch"] = ["cube", step, ""]
424
+ tilt = self.bottle_tilt()
425
+ mon["max_tilt_deg"] = round(max(mon["max_tilt_deg"], float(np.degrees(tilt))), 1)
426
+ mon["max_offset_cm"] = round(max(mon["max_offset_cm"], 100 * float(np.linalg.norm(self.bottle_offset()))), 1)
427
+ if mon["step"] % 2:
428
+ return # predicates every other control step (0.1 s)
429
+ if not mon["fallen"] and tilt > FALLEN and not self.held(BOTTLE):
430
+ mon["fallen"] = True
431
+ mon["n_fallen"] += 1
432
+ mon["events"].append(dict(step=step, pred="bottle", ev="fallen", cause=self._cause(step)))
433
+ elif mon["fallen"] and tilt < UPRIGHT:
434
+ mon["fallen"] = False
435
+ for n in CUBES:
436
+ self._check(f"{CUBE_COLOR[n]}_in_box", self.in_box(n), step, n)
437
+ st = mon["state"]["bottle_in_place"]
438
+ # hysteresis: once in place it counts as lost only beyond 2.3 cm / 10 deg, held for 0.6 s (a nudge that rocks
439
+ # back is no loss)
440
+ now = self.bottle_in_place(POS_TOL + POS_HYST, KNOCK_TILT) if st else self.bottle_in_place()
441
+ self._check("bottle_in_place", now, step, BOTTLE)
442
+
443
+ def _cause(self, step):
444
+ lt = self.mon["last_touch"]
445
+ if lt is not None and step - lt[1] <= 60:
446
+ return lt[0]
447
+ return "other"
448
+
449
+ def _check(self, key, now, step, name):
450
+ mon = self.mon
451
+ if now == mon["state"][key]:
452
+ mon["cand"][key] = 0
453
+ return
454
+ if name == BOTTLE and not now and step - mon["robot_touch_step"] <= 6 and not self.held(BOTTLE):
455
+ # the arm is still pressing on the bottle (measured: a slow descent can come to rest on its cap and stall,
456
+ # tilting it ~12 deg; it rocks back when the arm lifts): a loss only once the robot has let go of it
457
+ mon["cand"][key] = 0
458
+ return
459
+ mon["cand"][key] += 1
460
+ if mon["cand"][key] < DEBOUNCE:
461
+ return
462
+ mon["cand"][key] = 0
463
+ mon["state"][key] = now
464
+ if now:
465
+ restored = key in mon["lost"]
466
+ ev = "restored" if restored else "achieved"
467
+ if key not in mon["ever"]:
468
+ mon["ever"].append(key)
469
+ if restored:
470
+ mon["lost"].remove(key)
471
+ mon["events"].append(dict(step=step, pred=key, ev=ev))
472
+ if key == "bottle_in_place" and restored:
473
+ mon["events"].append(dict(step=step, pred="bottle", ev="bystander_restored",
474
+ offset_cm=(100 * self.bottle_offset()).round(1).tolist()))
475
+ return
476
+ if key not in mon["ever"]:
477
+ return
478
+ cause = "picked_up" if self.held(name) else self._cause(step)
479
+ if key not in mon["lost"]:
480
+ mon["lost"].append(key)
481
+ e = dict(step=step, pred=key, ev="lost", cause=cause)
482
+ if name == BOTTLE:
483
+ ee = self.sk.eef_pos() if self.sk is not None else np.zeros(3)
484
+ e["eef_cm"] = [round(100 * float(v), 1) for v in (ee[0] - self.inst["box_xy"][0], ee[1] - self.inst["box_xy"][1],
485
+ ee[2] - Z)] # grasp point rel. to the box centre / table
486
+ e.update(tilt_deg=round(float(np.degrees(self.bottle_tilt())), 1),
487
+ offset_cm=(100 * self.bottle_offset()).round(1).tolist())
488
+ if mon["last_touch"] is not None and mon["last_touch"][0] in ("arm", "hand"):
489
+ e["robot_geom"] = mon["last_touch"][2]
490
+ mon["events"].append(e)
491
+ if name == BOTTLE and cause != "picked_up":
492
+ mon["n_knocks"] += 1
493
+ if mon["first_knock_step"] is None:
494
+ mon["first_knock_step"] = step
495
+ mon["events"].append(dict(step=step, pred="bottle", ev="bystander_knocked", cause=cause,
496
+ robot_geom=e.get("robot_geom", ""), tilt_deg=e["tilt_deg"],
497
+ offset_cm=e["offset_cm"], eef_cm=e["eef_cm"]))
498
+
499
+ # ------------------------------------------------------------ outcome
500
+ def _static(self):
501
+ d = self.env.sim.data
502
+ for n in CUBES + (BOTTLE,):
503
+ _, da = envs.free_joint_addr(self.env, n)
504
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
505
+ return False
506
+ return True
507
+
508
+ def robot_touching(self):
509
+ d = self.env.sim.data
510
+ out = []
511
+ for i in range(d.ncon):
512
+ c = d.contact[i]
513
+ for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)):
514
+ if self.part[a] and (self.is_bottle[b] or self.other[b] == 3):
515
+ nm = "bottle" if self.is_bottle[b] else "a cube"
516
+ if nm not in out:
517
+ out.append(nm)
518
+ return out
519
+
520
+ def outcome(self, inst):
521
+ envs.settle(self.env, 30)
522
+ mon = self.mon
523
+ vals = self.stage_values()
524
+ static = self._static()
525
+ held = [n for n in CUBES + (BOTTLE,) if self.held(n)]
526
+ touching = self.robot_touching()
527
+ success = bool(all(vals.values()) and static and not held and not touching)
528
+ evs = mon["events"]
529
+ regress = [e for e in evs if e["ev"] == "lost"]
530
+ restored = [e for e in evs if e["ev"] == "restored"]
531
+ knocks = [e for e in evs if e["ev"] == "bystander_knocked"]
532
+ # trap fired: a knock was logged, or the bottle ends up out of place after the robot touched it (a slow push
533
+ # to just over 2 cm can stay inside the monitor's hysteresis band)
534
+ trap_fired = bool(knocks) or (not vals["bottle_in_place"] and not self.held(BOTTLE) and bool(mon["touch_parts"]))
535
+ recovered = bool(trap_fired and vals["bottle_in_place"])
536
+ off = self.bottle_offset()
537
+ tilt = float(np.degrees(self.bottle_tilt()))
538
+ parts = []
539
+ failure = None
540
+ if success:
541
+ parts.append("All three cubes are in the box and the bottle stands where it stood.")
542
+ else:
543
+ out_cubes = [n for n in CUBES if not vals[f"{CUBE_COLOR[n]}_in_box"]]
544
+ if not vals["bottle_in_place"]:
545
+ failure = ("bystander_held" if self.held(BOTTLE) else
546
+ "bystander_knocked" if tilt > np.degrees(UPRIGHT) else "bystander_moved")
547
+ elif held:
548
+ failure = "held"
549
+ elif out_cubes:
550
+ failure = "cube_not_in_box"
551
+ elif touching:
552
+ failure = "robot_touching"
553
+ else:
554
+ failure = "not_static"
555
+ if not vals["bottle_in_place"]:
556
+ if self.held(BOTTLE):
557
+ parts.append("The bottle is still held by the gripper.")
558
+ else:
559
+ pose = ("is lying on its side" if tilt > 60 else f"is tilted {tilt:.0f} degrees" if tilt > np.degrees(UPRIGHT)
560
+ else "stands upright")
561
+ txt = f"The bottle {pose}; its base is {_fb(off[0])} and {_lr(off[1])} of where it stood"
562
+ if knocks:
563
+ k = knocks[0]
564
+ who = {"arm": "the robot's arm (above the gripper)", "hand": "the gripper",
565
+ "cube": "a cube"}.get(k["cause"], "something")
566
+ txt += f" (it was knocked by {who}"
567
+ txt += " and stood up again later, but not back in place)." if restored and any(
568
+ e["pred"] == "bottle_in_place" for e in restored) else ")."
569
+ else:
570
+ txt += "."
571
+ parts.append(txt)
572
+ for n in out_cubes:
573
+ c = CUBE_COLOR[n]
574
+ if self.held(n):
575
+ parts.append(f"The {c} cube is still held by the gripper.")
576
+ elif self.over_box(n):
577
+ parts.append(f"The {c} cube rests on the box's rim instead of inside the box.")
578
+ else:
579
+ rel = self.to_box(envs.obj_pos(self.env, n)[:2])
580
+ parts.append(f"The {c} cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the "
581
+ f"box's centre.")
582
+ if touching and all(vals.values()):
583
+ parts.append("The robot was still touching " + " and ".join(touching) + " at the end.")
584
+ if not static and all(vals.values()):
585
+ parts.append("Something was still moving at the end.")
586
+ if trap_fired and vals["bottle_in_place"]:
587
+ parts.append(f"(The bottle was knocked out of place {len(knocks)} time(s) during the attempt and put back.)")
588
+ out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching,
589
+ events=evs, n_regressions=len(regress), n_restored=len(restored), trap_fired=trap_fired,
590
+ recovered_in_attempt=recovered, n_knocks=len(knocks), n_fallen=mon["n_fallen"],
591
+ knock_causes=[k["cause"] for k in knocks], first_knock_step=mon["first_knock_step"],
592
+ bottle_touch_parts=list(mon["touch_parts"]), bottle_max_tilt_deg=mon["max_tilt_deg"],
593
+ bottle_max_offset_cm=mon["max_offset_cm"], bottle_tilt_deg=round(tilt, 1),
594
+ bottle_offset_cm=(100 * off).round(1).tolist(), hazard=bool(inst["hazard"]),
595
+ detail=" ".join(parts))
596
+ return out
597
+
598
+ # ------------------------------------------------------------ scripted primitives (perfect perception)
599
+ def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
600
+ return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
601
+
602
+ def _settle(self, name, max_checks=25):
603
+ d = self.env.sim.data
604
+ _, da = envs.free_joint_addr(self.env, name)
605
+ for _ in range(max_checks):
606
+ if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
607
+ return
608
+ self.sk.hold(2)
609
+
610
+ def _cube_yaw(self, name):
611
+ R = self.R(name)
612
+ i = int(np.argmin(np.abs(R[2])))
613
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
614
+ y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
615
+ cands = [y + k * np.pi / 2 for k in (-1, 0, 1)]
616
+ return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0)
617
+
618
+ def pick(self, name, z_carry, v=0.15, tries=2):
619
+ """Sonnet-like top-down pick: over the cube at carry height, down at 0.1 to 1.5 cm above, last 1.5 cm at 0.04,
620
+ close, lift to carry height"""
621
+ sk = self.sk
622
+ for _ in range(tries):
623
+ self._settle(name)
624
+ p = envs.obj_pos(self.env, name)
625
+ zg = p[2] - Z
626
+ yaw = self._cube_yaw(name)
627
+ sk.set_gripper(False, steps=8)
628
+ self._go([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw, speed=v)
629
+ self._go([p[0], p[1], Z + zg + 0.015], speed=0.1)
630
+ self._go([p[0], p[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
631
+ sk.set_gripper(True, steps=15)
632
+ self._go([p[0], p[1], Z + z_carry], speed=v)
633
+ if self.held(name):
634
+ return True
635
+ sk.set_gripper(False, steps=8)
636
+ return False
637
+
638
+ def put(self, xy, z_rel, z_carry, v=0.15, v_down=None):
639
+ """carry over xy at carry height, straight down (0.1 m/s, last 1.5 cm at 0.03; or one move at v_down), open,
640
+ back up"""
641
+ sk = self.sk
642
+ self._go([xy[0], xy[1], Z + z_carry], speed=v)
643
+ if z_rel < z_carry - 0.02 and v_down:
644
+ self._go([xy[0], xy[1], Z + z_rel], speed=v_down, tol=0.003, max_steps=250)
645
+ elif z_rel < z_carry - 0.02:
646
+ self._go([xy[0], xy[1], Z + z_rel + 0.015], speed=0.1)
647
+ self._go([xy[0], xy[1], Z + z_rel], speed=0.03, tol=0.003, max_steps=150)
648
+ sk.set_gripper(False, steps=12)
649
+ self._go([xy[0], xy[1], Z + z_carry], speed=v)
650
+ sk.hold(5)
651
+
652
+ def slot_xy(self, k, order):
653
+ """slot k of the scripted packing pattern, in world xy (box frame: u forward, v left)"""
654
+ u, v = order[k]
655
+ return np.asarray(self.inst["box_xy"]) + np.array([u, v]) * SLOT
656
+
657
+ def put_cube(self, name, k, order, z_rel, z_carry, noise=None, v=0.15, v_down=None):
658
+ if not self.pick(name, z_carry, v=v):
659
+ return False
660
+ xy = self.slot_xy(k, order) + (np.asarray(noise, float) if noise is not None else 0.0)
661
+ self.put(xy, z_rel, z_carry, v=v, v_down=v_down)
662
+ self._settle(name)
663
+ return True
664
+
665
+ def restand_bottle(self, z_carry=None):
666
+ """stand the bottle up again on its spot: grasp the ball cap from above (fingers across the lying bottle's
667
+ axis), lift until it hangs free, carry it over its spot, lower until the bottom is ~2 mm above the table, let
668
+ go. Returns True if it is back in place."""
669
+ sk = self.sk
670
+ self._settle(BOTTLE)
671
+ for _ in range(2):
672
+ if _reach(self.cap_xyz()) > REACH_MAX and self.bottle_tilt() > FALLEN:
673
+ self.pull_in_bottle()
674
+ k = self.cap_xyz()
675
+ ax = self.R(BOTTLE)[:2, 2]
676
+ yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it
677
+ sk.set_gripper(False, steps=8)
678
+ cur = sk.eef_pos()
679
+ self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15)
680
+ self._go([k[0], k[1], max(k[2] + 0.08, Z + 0.15)], yaw=yaw, speed=0.15)
681
+ sk.hold(5)
682
+ k = self.cap_xyz()
683
+ self._go([k[0], k[1], k[2] + 0.015], speed=0.1)
684
+ self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120)
685
+ sk.set_gripper(True, steps=15)
686
+ if not self.held(BOTTLE):
687
+ sk.set_gripper(False, steps=8)
688
+ self._go([k[0], k[1], k[2] + 0.08], speed=0.1)
689
+ continue
690
+ zl = Z + CAP_Z + 0.06
691
+ self._go([k[0], k[1], zl], speed=0.10)
692
+ sk.hold(15)
693
+ tx, ty = self.inst["bottle_xy"]
694
+ self._go([tx, ty, zl], speed=0.10)
695
+ sk.hold(25)
696
+ self._go([tx, ty, Z + CAP_Z + 0.015], speed=0.08)
697
+ self._go([tx, ty, Z + CAP_Z + 0.002], speed=0.03, tol=0.003, max_steps=120)
698
+ sk.set_gripper(False, steps=12)
699
+ self._go([tx, ty, Z + CAP_Z + 0.06], speed=0.08)
700
+ sk.hold(20)
701
+ self._settle(BOTTLE)
702
+ if self.bottle_in_place():
703
+ return True
704
+ return self.bottle_in_place()
705
+
706
+ def pull_in_bottle(self):
707
+ """the lying bottle's cap is out of reach (it fell forward over the box): grasp the body near its bottom end
708
+ (fingers across it), lift it 3 cm, pull it towards the robot until the cap is within reach, set it down"""
709
+ sk = self.sk
710
+ Rb = self.R(BOTTLE)
711
+ ax = Rb[:, 2]
712
+ c = envs.obj_pos(self.env, BOTTLE)
713
+ g = c - ax * (H_TOT / 2 - 0.05) # 5 cm from the bottom end along the axis
714
+ zg = max(float(g[2] - Z), 0.02)
715
+ yaw = float(np.arctan2(ax[1], ax[0]))
716
+ need = _reach(self.cap_xyz()) - (REACH_MAX - 0.05)
717
+ to_base = np.array([-0.66, 0.0]) - g[:2]
718
+ to_base /= max(np.linalg.norm(to_base), 1e-6)
719
+ dst = g[:2] + to_base * need
720
+ sk.set_gripper(False, steps=8)
721
+ self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15)
722
+ self._go([g[0], g[1], Z + zg + 0.015], speed=0.1)
723
+ self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
724
+ sk.set_gripper(True, steps=15)
725
+ self._go([g[0], g[1], Z + zg + 0.03], speed=0.08)
726
+ self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08)
727
+ self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04)
728
+ sk.set_gripper(False, steps=12)
729
+ self._go([dst[0], dst[1], Z + 0.15], speed=0.1)
730
+ self._settle(BOTTLE)
731
+
732
+ def _fallen_cubes(self, done):
733
+ return [n for n in done if not self.in_box(n) and not self.over_box(n) and not self.held(n)]
734
+
735
+ # ------------------------------------------------------------ scripted policies
736
+ def execute(self, inst, params):
737
+ careful = params.get("careful", False)
738
+ zc = params.get("z_carry", Z_SAFE if careful else Z_CARRY)
739
+ zr = params.get("z_rel", Z_DROP if careful else Z_REL)
740
+ order = params.get("slots") or [(1, 1), (1, -1), (-1, 0)] # far row first (Sonnet fills from the far end)
741
+ cubes = params.get("cubes") or self._cube_order()
742
+ noise = params.get("noise") or {}
743
+ v = params.get("speed", 0.15)
744
+ done = []
745
+ for k, n in enumerate(cubes):
746
+ self.put_cube(n, k, order, zr, zc, noise=noise.get(n), v=v, v_down=params.get("v_down"))
747
+ done.append(n)
748
+ # looks after every step (Sonnet): re-places a cube that ended up outside the box ...
749
+ for f in self._fallen_cubes(done):
750
+ self.put_cube(f, done.index(f), order, zr, zc, v=v)
751
+ # ... and, if the bystander is in the policy's view of the task, stands the bottle up again
752
+ if params.get("restore") == "each" and not self.bottle_in_place():
753
+ self.restand_bottle()
754
+ if params.get("check"):
755
+ self.check_and_fix(order, zr, zc)
756
+ self.sk.hold(10)
757
+
758
+ def check_and_fix(self, order, zr, zc, rounds=2):
759
+ for _ in range(rounds):
760
+ v = self.stage_values()
761
+ if all(v.values()):
762
+ return True
763
+ for n in CUBES:
764
+ if not self.in_box(n):
765
+ self.put_cube(n, CUBES.index(n), order, zr, zc)
766
+ if not self.bottle_in_place():
767
+ self.restand_bottle()
768
+ return all(self.stage_values().values())
769
+
770
+ def _cube_order(self):
771
+ """the cube nearest the box first"""
772
+ bxy = np.asarray(self.inst["box_xy"])
773
+ return sorted(CUBES, key=lambda n: float(np.linalg.norm(np.asarray(self.inst["start"][n]) - bxy)))
774
+
775
+ def default_params(self, inst):
776
+ """Sonnet-like: cubes nearest-first, carried 15 cm up in straight lines, each lowered straight down onto the box
777
+ floor (far row first), looks after every step and re-places a cube that fell out; no special care for the
778
+ bottle (it is not part of the packing)"""
779
+ return dict(careful=False, restore=None, check=False)
780
+
781
+ def oracle_params(self, inst):
782
+ """knows its arm: carries high (24 cm) and drops the cubes into the box from 16 cm, so the forearm stays above
783
+ the bottle; checks every stage at the end"""
784
+ return dict(careful=True, restore="each", check=True)
785
+
786
+ def adapt_params(self, inst, history):
787
+ """attempt >= 2: the careful packing (high carry, drop from above the rim), stand the bottle up if needed,
788
+ check at the end"""
789
+ return dict(careful=True, restore="each", check=True)
790
+
791
+ def blind_params(self, inst, attempt, rng):
792
+ """the natural behaviour again with small random variations, no history, no care for the bottle"""
793
+ pats = [[(1, 1), (1, -1), (-1, 0)], [(1, -1), (1, 1), (-1, 0)], [(0, 1), (0, -1), (-1, 0)],
794
+ [(1, 0), (-1, 1), (-1, -1)], [(1, 1), (-1, -1), (0, 0)]]
795
+ return dict(careful=False, restore=None, check=False, slots=pats[int(rng.integers(len(pats)))],
796
+ z_carry=float(rng.uniform(0.12, 0.20)), z_rel=float(rng.uniform(0.032, 0.055)),
797
+ noise={n: rng.uniform(-NAIVE_ERR, NAIVE_ERR, 2).tolist() for n in CUBES})
798
+
799
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
800
+ """oracle / naive: one attempt; adaptive: attempt 1 = naive + stands the knocked bottle up again after every
801
+ step and checks at the end, attempts >= 2 careful; blind: naive with random variations.
802
+ Extra kinds (not in validate's table): switch (naive, then careful without restoring), oracle_noise (oracle with
803
+ +-5 mm placement noise)"""
804
+ k = k or self.max_attempts
805
+ rng = np.random.default_rng(seed)
806
+ history = []
807
+ for a in range(k):
808
+ self.reset_instance(inst)
809
+ if kind == "oracle":
810
+ params = self.oracle_params(inst)
811
+ elif kind == "naive":
812
+ params = self.default_params(inst)
813
+ elif kind == "adaptive":
814
+ params = dict(careful=False, restore="each", check=True) if a == 0 else self.adapt_params(inst, history)
815
+ elif kind == "blind":
816
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
817
+ elif kind == "switch":
818
+ params = self.default_params(inst) if a == 0 else dict(careful=True, restore=None, check=False)
819
+ elif kind == "oracle_noise":
820
+ params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES})
821
+ else:
822
+ raise ValueError(kind)
823
+ self.execute(inst, params)
824
+ out = self.outcome(inst)
825
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
826
+ if on_attempt:
827
+ on_attempt(a, params, out)
828
+ if out["success"] or kind in ("oracle", "naive", "oracle_noise"):
829
+ break
830
+ return history
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_parts_cart.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Composite prototype: physical tool retrieval, loading regression and asymmetric cart transport.
2
+
3
+ Not part of main_v1. See task_cards/lh_parts_cart.md for validation status.
4
+ Only reset_instance/apply_instance position objects; all reference actions use the public motion skills.
5
+ """
6
+ import copy
7
+ import numpy as np
8
+ from .. import envs
9
+ from ..bddl import write_bddl
10
+ from ..objects import register_generated, box_xml
11
+ from ..task_base import register_task
12
+ from .l3_tool import (UnderTableTool, low_table_xml, stick_xml, CUBE_HALF,
13
+ HANDLE_HALF, TOP_HALF)
14
+ from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml,
15
+ HALF, MASS, MU, BOX, _rot)
16
+
17
+
18
+ class CartSkills(PushSkills):
19
+ def __init__(self,*args,**kwargs):
20
+ super().__init__(*args,**kwargs)
21
+ self.robot_commands=0
22
+ def move_to(self,*args,**kwargs):
23
+ self.robot_commands+=1
24
+ return super().move_to(*args,**kwargs)
25
+ def set_gripper(self,*args,**kwargs):
26
+ self.robot_commands+=1
27
+ return super().set_gripper(*args,**kwargs)
28
+
29
+
30
+ @register_task
31
+ class PartsCart(UnderTableTool):
32
+ name = 'lh_parts_cart'
33
+ level = 'L4'
34
+ category = 'geometry_inference'
35
+ failure_causes = ('L4', 'L2', 'L5')
36
+ capabilities = ('Perceive', 'Reason', 'Plan', 'Restore')
37
+ protocol = 'cross'
38
+ agent_max_steps = 180
39
+ instruction = ('Use the wooden tool to retrieve the red part from under the low glass table. '
40
+ 'Load the red and blue parts on the two marks on the brown transport platform, '
41
+ 'then push the loaded platform with the closed gripper completely into the green parking area. '
42
+ 'At the end both parts must still be on their marks, and the gripper must be open and clear.')
43
+ instruction_indirect = instruction
44
+
45
+ def make_bddl(self):
46
+ cube = register_generated('LffPartsCartRed', box_xml('lff_parts_cart_red', (CUBE_HALF,)*3,(.85,.12,.12,1), density=300))
47
+ blue = register_generated('LffPartsCartBlue', box_xml('lff_parts_cart_blue', (CUBE_HALF,)*3,(.1,.2,.85,1), density=300))
48
+ stick_xml_text=stick_xml('lff_parts_cart_stick').replace('size="0.00800 0.02500 0.01000"','size="0.00800 0.00800 0.01000"')
49
+ stick = register_generated('LffPartsCartStick', stick_xml_text)
50
+ table_xml=low_table_xml('lff_parts_cart_table')
51
+ # Wider roof with legs outside the blocked cube's x-exit lane. This prevents a panel failure
52
+ # trapping the cube against a corner leg, which the existing standalone task did not test in-attempt.
53
+ table_xml=table_xml.replace('size="0.06000 0.06000 0.00500"','size="0.06000 0.07500 0.00500"')
54
+ for sx in (-.052,.052):
55
+ for sy in (-.052,.052):
56
+ table_xml=table_xml.replace(f'pos="{sx:.5f} {sy:.5f} 0.03500"',f'pos="{sx:.5f} {np.sign(sy)*.067:.5f} 0.03500"')
57
+ table = register_generated('LffPartsCartTable', table_xml, free=False)
58
+ xml=long_box_xml('lff_parts_cart_platform')
59
+ marks=''.join(f'<geom type="box" pos="0 {y} {HALF[2]+.0006}" size=".022 .022 .0003" rgba="{color}" contype="0" conaffinity="0" group="1" />' for y,color in [(-.03,'.9 .4 .4 1'),(.03,'.4 .5 .9 1')])
60
+ xml=xml.replace(' </body>',marks+' </body>',1)
61
+ cart = register_generated('LffPartsCartPlatform', xml)
62
+ zone = register_generated('LffPartsCartZone', rect_frame_xml('lff_parts_cart_zone'), free=False)
63
+ # Inertial/shape match existing off-centre box, with purely visual cargo marks.
64
+ objs=[('cube_1',cube,'red_region',(-.31,-.26,-.29,-.24)),
65
+ ('blue_1',blue,'blue_region',(-.31,.24,-.29,.26)),
66
+ ('stick_1',stick,'stick_region',(-.01,-.36,.01,-.34)),
67
+ ('box_1',cart,'cart_region',(.19,.24,.21,.26))]
68
+ fx=[('lowtable_1',table,'table_region',(.19,-.11,.21,-.09)),
69
+ ('zone_1',zone,'zone_region',(.19,.39,.21,.41))]
70
+ return write_bddl(self.name,self.instruction,objs,fx)
71
+
72
+ def sample_instance(self, seed):
73
+ # Tool geometry is inherited; put transport in the other half of the same tabletop.
74
+ rng=np.random.default_rng(seed)
75
+ base=super().sample_instance(seed)
76
+ base.update(side=-1, pane_side=1, table_xy=[-.08,-.08],cube_xy=[-.08,-.08],
77
+ stick_xy=[-.08,-.34],stick_yaw=np.pi/2,
78
+ box_xy=[-.25,.24],target_dist=.16,
79
+ com_offset=float(rng.choice([-1,1])*rng.uniform(.05,.065)),
80
+ traps=dict(L4=True,L2=True,L5=True))
81
+ base['bin_xy']=[-.25,.24] # inherited observe() only; no bin fixture.
82
+ return base
83
+
84
+ def target_xy(self, inst):
85
+ return np.array([inst['box_xy'][0]+inst['target_dist'],inst['box_xy'][1]])
86
+
87
+ def apply_instance(self, inst):
88
+ self.inst=inst
89
+ m=self.env.sim.model
90
+ bid,_=self._fixture('lowtable_1')
91
+ m.body_pos[bid]=[*inst['table_xy'],envs.TABLE_Z]
92
+ for g,sy in self._panes():
93
+ on=inst['traps']['L4'] and sy==inst['pane_side']
94
+ m.geom_contype[g]=m.geom_conaffinity[g]=int(on)
95
+ envs.set_obj_pose(self.env,'cube_1',[*inst['cube_xy'],envs.TABLE_Z+CUBE_HALF+.0005])
96
+ envs.set_obj_pose(self.env,'blue_1',[-.30,.04,envs.TABLE_Z+CUBE_HALF+.0005])
97
+ envs.set_obj_pose(self.env,'stick_1',[*inst['stick_xy'],envs.TABLE_Z+HANDLE_HALF[2]+.0005],yaw=inst['stick_yaw'])
98
+ bid=envs.body_id(self.env,BOX)
99
+ m.body_mass[bid]=MASS
100
+ m.body_ipos[bid]=[0,inst['com_offset'] if inst['traps']['L5'] else 0,0]
101
+ for g in range(m.ngeom):
102
+ if m.geom_bodyid[g]==bid and (np.allclose(m.geom_rgba[g,:3],[.9,.4,.4]) or np.allclose(m.geom_rgba[g,:3],[.4,.5,.9])):
103
+ m.geom_pos[g,1]=np.sign(m.geom_pos[g,1])*(.03 if inst['traps']['L2'] else .07)
104
+ envs.refit_bounds(self.env,bid)
105
+ envs.set_friction(self.env,BOX,MU)
106
+ envs.set_obj_pose(self.env,BOX,[*inst['box_xy'],envs.TABLE_Z+HALF[2]+.001])
107
+ zb=m.body_name2id(self.env.fixtures_dict['zone_1'].root_body)
108
+ m.body_pos[zb]=[*self.target_xy(inst),envs.TABLE_Z+.0002]
109
+
110
+ def reset_instance(self, inst, recorder=None):
111
+ self.loadmon=None
112
+ self._mon=None
113
+ self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15)
114
+ self.sk=CartSkills(self.env,recorder=recorder,target=self.target_xy(inst))
115
+ self._start_monitor()
116
+ self.loadmon=dict(states=[False,False],count=[0,0],ever=[False,False],lost=[False,False],events=[],loaded=False,departed_unloaded=False,load_step=None,departure_step=None,last_robot_touch=[-10000,-10000])
117
+ self.ncmd=0;self.budget=None
118
+ return self.sk
119
+
120
+ def mark(self,i):
121
+ p,yaw=self.sk._box_pose() if self.sk else (envs.obj_pos(self.env,BOX),0.)
122
+ spacing=.03 if self.inst['traps']['L2'] else .07
123
+ return p[:2]+_rot(yaw)@np.array([0.,(-spacing,spacing)[i]])
124
+
125
+ def cargo_ok(self,i):
126
+ obj=('cube_1','blue_1')[i]
127
+ p=envs.obj_pos(self.env,obj); bp=envs.obj_pos(self.env,BOX)
128
+ return bool(np.linalg.norm(p[:2]-self.mark(i))<.018 and
129
+ abs(p[2]-(bp[2]+HALF[2]+CUBE_HALF))<.012 and not self.sk.holding(obj))
130
+
131
+ def _monitor_step(self):
132
+ super()._monitor_step()
133
+ mon=getattr(self,'loadmon',None)
134
+ if mon is None:return
135
+ robot=set(envs.robot_geom_ids(self.env))
136
+ for i,obj in enumerate(('cube_1','blue_1')):
137
+ geoms=set(envs.obj_geom_ids(self.env,obj))
138
+ for c in self.env.sim.data.contact[:self.env.sim.data.ncon]:
139
+ if (c.geom1 in robot and c.geom2 in geoms) or (c.geom2 in robot and c.geom1 in geoms):
140
+ mon['last_robot_touch'][i]=self.sk.n_steps
141
+ now=self.cargo_ok(i)
142
+ if now==mon['states'][i]:mon['count'][i]=0;continue
143
+ mon['count'][i]+=1
144
+ if mon['count'][i]<5:continue
145
+ mon['count'][i]=0;mon['states'][i]=now
146
+ ev='restored' if now and mon['lost'][i] else 'achieved' if now else 'lost'
147
+ if now:mon['ever'][i]=True
148
+ else:
149
+ mon['lost'][i]=True
150
+ if np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])<.025:
151
+ mon['loaded']=False
152
+ mon['load_step']=None
153
+ mon['events'].append(dict(step=self.sk.n_steps,pred=('red','blue')[i],event=ev,
154
+ cart_displacement=float(np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])),
155
+ cause='robot' if self.sk.n_steps-mon['last_robot_touch'][i]<=20 else 'other'))
156
+ displacement=np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])
157
+ if all(mon['states']) and displacement<.02 and not mon['loaded']:
158
+ mon['loaded']=True
159
+ mon['load_step']=self.sk.n_steps
160
+ if displacement>.03 and mon['departure_step'] is None:
161
+ mon['departure_step']=self.sk.n_steps
162
+ if not mon['loaded']:mon['departed_unloaded']=True
163
+
164
+ def pick_place(self,obj,xy,yaw=0.):
165
+ sk=self.sk;p=envs.obj_pos(self.env,obj)
166
+ sk.set_gripper(False,steps=10)
167
+ sk.move_to([p[0],p[1],envs.TABLE_Z+.18],yaw=0. if obj=='cube_1' and self.under_table(margin=.08) else yaw)
168
+ sk.move_to([p[0],p[1],p[2]-.004],speed=.10,tol=.002)
169
+ sk.set_gripper(True,steps=15)
170
+ held=sk.holding(obj)
171
+ sk.move_to([p[0],p[1],envs.TABLE_Z+.20],speed=.15)
172
+ if held:
173
+ sk.move_to([xy[0],xy[1],envs.TABLE_Z+.20],yaw=yaw)
174
+ bp=envs.obj_pos(self.env,BOX)
175
+ sk.move_to([xy[0],xy[1],bp[2]+HALF[2]+CUBE_HALF-.003],speed=.06,tol=.002)
176
+ sk.set_gripper(False,steps=15)
177
+ sk.move_to([xy[0],xy[1],envs.TABLE_Z+.22],speed=.15)
178
+ return bool(held)
179
+
180
+ def load(self, careful=True):
181
+ self.pick_place('cube_1',self.mark(0),np.pi/2)
182
+ # Open fingers along y at the adjacent mark can knock the already loaded red cube.
183
+ yaw=np.pi/2 if careful else 0.
184
+ self.pick_place('blue_1',self.mark(1),yaw)
185
+
186
+ def repair_load(self):
187
+ for _ in range(3):
188
+ for i,o in enumerate(('cube_1','blue_1')):
189
+ if not self.cargo_ok(i):self.pick_place(o,self.mark(i),np.pi/2)
190
+
191
+ def transport(self,c=0.,repair=False):
192
+ # Call existing push controller on this same environment; no independent rollout stitching.
193
+ if not repair:
194
+ return OffcenterPush.execute(self,self.inst,dict(c=c))
195
+ if repair:
196
+ # Original feedback-driven corrector calls self.execute for its initial push.
197
+ self._transport_only=True
198
+ try:OffcenterPush.adaptive_attempt(self,self.inst,c)
199
+ finally:self._transport_only=False
200
+
201
+ _cmd=OffcenterPush._cmd
202
+ _sim_used=OffcenterPush._sim_used
203
+ _push_at=OffcenterPush._push_at
204
+ bracket=OffcenterPush.bracket
205
+ _front_runup=staticmethod(OffcenterPush._front_runup)
206
+ STEP=OffcenterPush.STEP;YAW_OK=OffcenterPush.YAW_OK
207
+ GAIN0=OffcenterPush.GAIN0;SAFE_V=OffcenterPush.SAFE_V
208
+
209
+ def execute(self,inst,params):
210
+ if getattr(self,'_transport_only',False):return OffcenterPush.execute(self,inst,params)
211
+ if params.get('front',False):self.tool_push_front()
212
+ else:self.tool_push_out()
213
+ if self.under_table():return
214
+ self.load(params.get('careful',False))
215
+ if params.get('repair',False):self.repair_load()
216
+ if all(self.cargo_ok(i) for i in range(2)):
217
+ self.transport(params.get('c',0.),params.get('repair',False))
218
+ if params.get('repair',False):self.repair_load()
219
+ self.sk.set_gripper(False,steps=10)
220
+ p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.24])
221
+
222
+ def default_params(self,inst):return dict(front=False,careful=False,repair=False,c=0.)
223
+ def oracle_params(self,inst):return dict(front=True,careful=True,repair=True,c=inst['com_offset'] if inst['traps']['L5'] else 0.)
224
+ def adapt_params(self,inst,history):
225
+ # The L4 side hit is learned from actual prior outcome, not from inst['pane_side'].
226
+ seen_geometry=any(h['outcome']['traps']['L4'] for h in history)
227
+ seen_loading=any(h['outcome']['traps']['L2'] for h in history)
228
+ pushes=[m for h in history for m in h['outcome']['box_moves']]
229
+ return dict(front=seen_geometry,careful=seen_loading,repair=bool(history),c=self.bracket(pushes))
230
+
231
+ def outcome(self,inst):
232
+ self.sk.hold(30)
233
+ fit=self.sk.fit();cargo=[self.cargo_ok(i) for i in range(2)]
234
+ ev=list(self.loadmon['events'])
235
+ # Loading regressions count only while cart remains at the loading station.
236
+ load_lost=[e for e in ev if e['event']=='lost' and e['cart_displacement']<.025 and e['cause']=='robot']
237
+ loaded=self.loadmon['loaded']
238
+ static=bool(np.max(np.abs(self.env.sim.data.qvel))<.05)
239
+ robot=set(envs.robot_geom_ids(self.env)); items=set()
240
+ for o in ('cube_1','blue_1',BOX,'stick_1'):items.update(envs.obj_geom_ids(self.env,o))
241
+ touching=any((c.geom1 in robot and c.geom2 in items) or (c.geom2 in robot and c.geom1 in items)
242
+ for c in self.env.sim.data.contact[:self.env.sim.data.ncon])
243
+ budget_ok=bool(self.sk.robot_commands<=self.agent_max_steps and self.sk.n_steps*.05<=self.agent_max_steps*3)
244
+ success=bool(not self.under_table() and all(cargo) and fit['inside'] and loaded
245
+ and not self.loadmon['departed_unloaded'] and static and not touching and budget_ok and self.sk.grip<0
246
+ and self._mon['stick_touched_cube'])
247
+ moves=copy.deepcopy(self.sk.box_moves)
248
+ return dict(success=success,stages=dict(retrieved=not self.under_table(),red=cargo[0],blue=cargo[1],parked=fit['inside'],loaded=loaded),
249
+ static=static,touching=bool(touching),tool_used=bool(self._mon['stick_touched_cube']),load_step=self.loadmon['load_step'],departure_step=self.loadmon['departure_step'],commands=self.sk.robot_commands,budget_ok=budget_ok,departed_unloaded=self.loadmon['departed_unloaded'],
250
+ events=ev,n_regressions=len(load_lost),n_restored=sum(e['event']=='restored' for e in ev),
251
+ traps=dict(L4=bool(self._mon['cube_hit_pane']),L2=bool(load_lost),L5=any(m['bad'] for m in moves)),
252
+ box_moves=moves,cart_pose=[*envs.obj_pos(self.env,BOX).tolist()],cart_fit=fit,
253
+ detail=f'Retrieved={not self.under_table()}; cargo on marks={cargo}; platform parked={fit["inside"]}.')
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_wobbly_table.py ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH lh_wobbly_table (2026-10-16): stand four bottles on the four coloured spots of a small side table -- one of its
2
+ legs is 1.5 cm short. Set the heavy bottle down on the corner over that leg while other bottles already stand on the
3
+ table and the table rocks down onto the short leg with a knock that throws the tall light bottles over.
4
+
5
+ Family: long-horizon self-disturbance ("state_restoration"): four plain pick-and-place stages, but a later stage (the heavy
6
+ bottle on the wobbly corner) physically undoes the earlier ones without the robot touching them. The agent has to
7
+ notice the fallen bottles and stand them up again (the rocked table is stable, so they stay up), or learn across
8
+ attempts to put that bottle down first (the table then rocks while nothing stands on it).
9
+
10
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
11
+ * a small wooden side table (free body, 1.1 kg): 28 x 28 x 1.6 cm top, 8.5 cm high, four 1.6 cm square legs at
12
+ +-12.5 cm; centre 53-57 cm in front of the robot base, +-4 cm left/right; four coloured spots (7.2 x 6.4 cm,
13
+ painted, colours permuted) centred 8 cm from the middle on both axes (one per corner);
14
+ * four square glass bottles (red / blue / green / yellow; 3.2 x 3.2 x 10 cm body, 2.4 cm flat foot, shoulder, 1.4 cm
15
+ square neck, a thin stem and a 1.2 cm white ball stopper; 14.7 cm tall) standing in a row on the main table in
16
+ front of the side table or beside it (random). Three are empty and light (75-90 g, centre of mass 7.2-8.0 cm up:
17
+ they tip over beyond ~9 deg); the fourth looks the same but is heavy (0.34-0.38 kg, sand in the bottom, centre of
18
+ mass 3.0-3.6 cm up).
19
+
20
+ Hidden variables: which leg is short (its collision capsule is 14-16 mm shorter; the visual leg is drawn full length,
21
+ so all legs look alike and touch the table) and which bottle is heavy. Coupled by construction: the heavy bottle's spot
22
+ is the corner over the short leg. Balanced over seeds: in the scripted naive order (spots farthest from the supply
23
+ first, then left first) the heavy bottle's spot comes 1st / 2nd / 3rd / 4th for exactly 5 of every 20 consecutive seeds
24
+ (1st = benign for that order: the table rocks while it is empty).
25
+
26
+ Physics (measured, scratch scripts t2-t24, see the task card and results/lh_wobbly_table/physics.json):
27
+ * The legs' collision geoms are capsules (rounded feet). With flat 1.6 cm box feet the rocking axis moved 1.1 cm
28
+ towards the loaded corner and the table's own weight stopped the rock half way (0.5 deg, balanced on two legs).
29
+ * The empty table rests level on its three long legs: its centre of mass is 5 mm towards the corner opposite the
30
+ short leg (1.1 kg x 5 mm). The light bottles on their own spots (the other three corners) never tip it, also let go
31
+ 4 cm above the top with a 2.6 cm error towards the short corner (4/4 seeds); the heavy bottle on the short corner
32
+ does (0.36 kg x 11.3 cm), also against a light bottle on the opposite corner. (A light bottle put on the short
33
+ corner's spot -- a wrong spot -- also tips the empty table: 85 g x 11.3 cm > 1.1 kg x 5 mm.) Rocked onto the short
34
+ leg the table tilts 4.5-5.1 deg and stays there with the heavy bottle on it, also when the light ones are added;
35
+ lifting the heavy bottle off, or pressing 1.25 N down near the raised corner, rocks it back (measured).
36
+ * The knock topples the light bottles standing on the table: 18/18 with teleported (zero-velocity) placements at gaps
37
+ 13-18 mm (12 mm: 8-10/18, 10 mm: 0/18); they fall towards the low corner, some off the table edge. The heavy bottle
38
+ stays up. The robot does not touch the bottles that fall (logged per rock).
39
+ * Bottle and table-top contacts are overdamped (solref 0.01, damping ratio 3): with stiff critically damped contacts
40
+ a light bottle let go 1-4 cm above the ROCKED table landed on its uphill edge and fell over (21/27 at 3.4 deg);
41
+ damped, 0/54 at every gap 13-18 mm, so the cross-attempt fix (heavy bottle first) works with the agent's usual
42
+ release 1-4 cm above the surface.
43
+ * A 22 x 22 cm draft table (spots 15.6 cm apart diagonally, 15.7 cm draft bottles) let the bottle on the opposite corner
44
+ fall onto the heavy one and lean on it; its stopper could not be grasped without knocking the heavy bottle over
45
+ (after which the table rocks back and forth on every repair step). At 28 cm nothing leans on it.
46
+ * Grasps: the Panda hand's collision hull starts 3 cm above the grasp point and the finger pads reach 1.2 cm above
47
+ it. Everything above the square neck is narrower than the neck: fingers that overlap the neck (grasp point 0.4-0.9
48
+ cm below its top) close on its flat faces and hold the bottle rigidly (the heavy one stayed in the fingers through
49
+ three moves at the controller's top speed 12/12, a light one 11/12); fingers on the ball alone (grasp point at or
50
+ above the neck's top) touch it at one point each and the bottle pivots (top-speed carries lost it 6/6). Drafts: a
51
+ 1.8 cm ball on a 1.3 cm round neck (the fingers always closed on the ball; the heavy bottle swung out in 5/6 fast
52
+ carries and once in the first smoke test), a 1.2 x 2.2 cm cylinder stopper (line contacts: a lying bottle lifted by
53
+ it stuck at ~26 deg and fell over when set down). The instruction states which grip is rigid and which swings (as
54
+ lh_bystander states its cap).
55
+ * Restoring (yaw-only top-down gripper): grasp the ball stopper of a lying bottle from above with the fingers across
56
+ its axis (torsional friction 0.0005), lift: it swings down and hangs straight (0.1 deg); lower it onto its spot and
57
+ let go. A bottle that fell off onto the main table right beside the small table often cannot be reached this way:
58
+ the hand (20 cm wide along the finger axis, 3 cm above the grasp point) would hit the table top. Where the hand,
59
+ the open fingers or the forearm would touch a standing bottle, the scripted repair first lifts the fallen bottle by
60
+ its body and lays it down in free space.
61
+ * Reach: the arm stalls 2-3 cm short of low targets beyond ~0.72 m from the base; every scripted grasp point stays
62
+ within 0.70 m.
63
+
64
+ Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each bottle stands upright
65
+ (tilt <= 10 deg from vertical; on the rocked table they stand at ~5.5 deg) on the small table's top with the centre of
66
+ its bottom inside its spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right of the spot's centre), not held.
67
+ Success = all four at the end, gripper open and not touching a bottle, scene static, and the small table within 3 cm /
68
+ 10 deg of where it stood and standing on its legs (tilt <= 8 deg; the rocked tilt counts as standing). The monitor logs
69
+ achieved / lost / restored per bottle and table_rocked / table_rocked_back events (the bottle released just before,
70
+ the bottles standing at that moment, which of them fell, whether the robot touched them before / while they fell) for
71
+ the server log only (F1 gives the agent only success / failure).
72
+
73
+ Protocol: cross (reset to the same instance before every attempt), k = 3.
74
+ """
75
+ import numpy as np
76
+
77
+ from .. import envs
78
+ from ..bddl import write_bddl
79
+ from ..objects import _fmt, _wrap, register_generated
80
+ from ..skills import Skills
81
+ from ..task_base import LFFTask, register_task
82
+
83
+ TZ = envs.TABLE_Z
84
+ COLOURS = ["red", "blue", "green", "yellow"]
85
+ BOTTLES = [f"bottle_{c}_1" for c in COLOURS]
86
+ TABLE = "side_table_1"
87
+ RGBA = {"red": (0.80, 0.14, 0.12, 1.0), "blue": (0.15, 0.33, 0.80, 1.0), "green": (0.14, 0.58, 0.24, 1.0),
88
+ "yellow": (0.90, 0.74, 0.12, 1.0)}
89
+ SPOT_RGBA = {"red": (0.62, 0.12, 0.11, 1.0), "blue": (0.12, 0.22, 0.58, 1.0), "green": (0.10, 0.42, 0.17, 1.0),
90
+ "yellow": (0.70, 0.56, 0.08, 1.0)}
91
+ CAP_RGBA = (0.93, 0.93, 0.91, 1.0) # white round stopper
92
+ WOOD = (0.52, 0.36, 0.22, 1.0)
93
+ LEG_RGBA = (0.40, 0.27, 0.16, 1.0)
94
+
95
+ # ---------------------------------------------------------------- side table (free body)
96
+ TOP_HW = 0.140 # 28 x 28 cm top
97
+ TOP_T = 0.016
98
+ TABLE_H = 0.085 # top surface above the main table
99
+ LEG_HW = 0.008 # 1.6 x 1.6 cm legs (visual); collision: capsules of radius 8 mm (rounded feet)
100
+ LEG_O = 0.125 # leg centre offset from the table centre (x and y)
101
+ LEG_L = TABLE_H - TOP_T
102
+ TBL_MASS = 1.1
103
+ TBL_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.004 1"' # legs: stiff (a sharp knock when the short leg lands)
104
+ TOP_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' # top: overdamped like the bottles
105
+ LEG_MU = 1.0
106
+ TOP_MU = 0.8
107
+ # corners in the table frame (= world axes; +x forward, +y left): index -> (sx, sy); k and k + 2 are diagonal
108
+ CORNERS = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
109
+ CORNER_NAME = {(1, 1): "far-left", (1, -1): "far-right", (-1, -1): "near-right", (-1, 1): "near-left"}
110
+ SPOT_O = 0.080 # spot centre offset from the table centre (x and y)
111
+ SPOT_HX, SPOT_HY = 0.036, 0.032 # spot half sizes (forward-back, left-right): 7.2 x 6.4 cm
112
+ SHORT_H = (0.014, 0.016) # hidden: one leg this much shorter (collision only; the visual leg reaches the table)
113
+ COM_BIAS = 0.005 # table centre of mass this far towards the leg opposite the short one: the empty table rests level
114
+
115
+ # ---------------------------------------------------------------- bottles (square glass bottles with a round stopper)
116
+ RB, HB = 0.016, 0.100 # body half width, height (3.2 x 3.2 x 10 cm)
117
+ RF, HF = 0.012, 0.005 # foot: flat contact 2.4 x 2.4 cm (rounded glass base)
118
+ RS, HS = 0.011, 0.010 # shoulder
119
+ RN, HN = 0.007, 0.016 # square neck: 1.4 cm wide, 1.6 cm long (11.0-12.6 cm above the bottom)
120
+ RT, HT = 0.0035, 0.010 # thin round stem above it: 0.7 cm wide, 1.0 cm long
121
+ RK, CAP_SINK = 0.006, 0.001 # ball stopper: 1.2 cm wide, on the stem (top 14.7 cm above the bottom)
122
+ # Why this top (measured, t8_hand.py / t19_slip.py / t22_restand.py): the Panda hand's collision hull starts ~3 cm above
123
+ # the grasp point and the finger pads reach 1.2 cm above it. Everything above the square neck is narrower than the
124
+ # neck, so fingers that overlap the neck close on its flat faces (several contact points: the bottle is held rigidly),
125
+ # and fingers on the ball alone touch it at one point each (low torsional friction: a lying bottle swings down and
126
+ # hangs straight). Drafts: a 1.8 cm ball on a 1.3 cm round neck -- the fingers always closed on the ball, the heavy
127
+ # bottle pivoted and swung out in 5/6 fast carries; a 1.2 x 2.2 cm cylinder stopper -- line contacts, a lifted lying
128
+ # bottle stuck at ~26 deg and fell over when set down (in-attempt repair 6/15).
129
+ H_TOT = HB + HS + HN + HT + 2 * RK - CAP_SINK # 14.7 cm
130
+ CAP_Z = H_TOT - RK # stopper centre above the bottle's bottom
131
+ NECK_Z = (HB + HS, HB + HS + HN) # square neck span above the bottom
132
+ BOT_MU = 0.7
133
+ CAP_MU_T = 0.0005 # torsional friction of the stopper (condim 4): held by it, a lying bottle swings down and hangs
134
+ BOT_DAMP = 0.003 # free-joint damping of the bottles (damps the swing of a bottle hanging from its stopper)
135
+ # overdamped contacts (damping ratio 3): with critically damped stiff contacts a light bottle set down 1-4 cm above a
136
+ # table top tilted 3.4 deg landed on its uphill edge and fell over (measured 21/27); damped: 0/54 at tilts up to 5 deg
137
+ BOT_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"'
138
+ LIGHT_MASS = (0.075, 0.090)
139
+ LIGHT_COM = (0.072, 0.080) # above the bottom (empty glass bottle, thick shoulder)
140
+ HEAVY_MASS = (0.34, 0.38)
141
+ HEAVY_COM = (0.030, 0.036) # sand in the bottom
142
+
143
+ # ---------------------------------------------------------------- predicates / monitor
144
+ TILT_OK = np.radians(10.0) # a bottle stands upright (world vertical; the rocked table itself tilts ~4.3 deg)
145
+ TOL_X = SPOT_HX - 0.006 # bottle centre within the spot shrunk by 6 mm (3.0 cm forward-back, 2.6 cm left-right)
146
+ TOL_Y = SPOT_HY - 0.006
147
+ ON_TOP = 0.006 # the bottle's bottom within this of the table top
148
+ HYST = 0.003
149
+ DEBOUNCE = 10 # control steps (0.5 s)
150
+ ROCK_ON, ROCK_OFF = np.radians(1.5), np.radians(0.8) # table tilt thresholds of the rock detector
151
+ FELL_WINDOW = 40 # control steps after a rock in which lost stages are attributed to it (2 s)
152
+ TABLE_MOVE_TOL = 0.03 # success: the table centre within 3 cm of where it stood
153
+ TABLE_YAW_TOL = np.radians(10.0)
154
+ TABLE_TILT_MAX = np.radians(8.0)
155
+
156
+ # ---------------------------------------------------------------- scripted motion
157
+ Z_CARRY = 0.40 # grasp point above the main table while carrying (bottle bottom ~27 cm up: clears standing bottles)
158
+ Z_HANG = 0.42 # ... carrying a bottle that hangs from its stopper (its bottom 27 cm up)
159
+ GRASP_NECK = 0.006 # scripted transport grasp point: this far below the neck's top (pads 1.1 cm on the neck, the hand
160
+ # 3 mm above the stopper; measured: 4-9 mm below the top hold rigidly, 4 mm above it close on the ball)
161
+ NAIVE_GAP = (0.010, 0.040) # Sonnet releases 1-4 cm above the surface
162
+ NAIVE_BIAS = (0.008, 0.020) # systematic forward placement error (lh_nudge_row pilot), per instance
163
+ NAIVE_RAND = 0.006
164
+ CAREFUL_GAP = 0.004
165
+
166
+
167
+ def bottle_xml(name, rgba):
168
+ """square glass bottle: rounded foot (smaller flat contact), body, shoulder, square neck, round stopper. Collision and
169
+ visual geoms separate; the inertial (mass, COM) is replaced per instance."""
170
+ h = H_TOT / 2
171
+ zf, zb = -h + HF / 2, -h + HF + (HB - HF) / 2
172
+ zs, zn = -h + HB + HS / 2, -h + HB + HS + HN / 2
173
+ zt = -h + HB + HS + HN + HT / 2
174
+ zk = -h + HB + HS + HN + HT + RK - CAP_SINK
175
+ parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
176
+ ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
177
+ ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
178
+ ("neck", "box", (0, 0, zn), (RN, RN, HN / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'),
179
+ ("stem", "cylinder", (0, 0, zt), (RT, HT / 2), CAP_RGBA, f'friction="{BOT_MU} 0.005 0.0001"'),
180
+ ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
181
+ s = [f' <inertial pos="0 0 {-h + 0.05:.4f}" mass="0.08" diaginertia="1.5e-4 1.5e-4 2.0e-5" />']
182
+ for nm, typ, pos, size, c, extra in parts:
183
+ s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
184
+ f'{extra} {BOT_SOLREF} group="0" />')
185
+ s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
186
+ f'conaffinity="0" group="1" />')
187
+ # a pale label (visual) so the bottles read as bottles
188
+ s.append(f' <geom type="box" pos="0 0 {zb + 0.008:.4f}" size="{RB + 0.0006:.4f} {RB + 0.0006:.4f} 0.016" '
189
+ f'rgba="0.94 0.92 0.84 1" contype="0" conaffinity="0" group="1" />')
190
+ return _wrap(name, "\n".join(s), h, RB * 1.42)
191
+
192
+
193
+ def table_xml(name):
194
+ """side table, origin at the centre of the footprint at mid height. Leg k sits under corner CORNERS[k]."""
195
+ h = TABLE_H / 2
196
+ zt = h - TOP_T / 2
197
+ zl = -h + LEG_L / 2
198
+ s = [f' <inertial pos="0 0 {0.02:.4f}" mass="{TBL_MASS}" diaginertia="0.004 0.004 0.007" />',
199
+ f' <geom name="{name}_top" type="box" pos="0 0 {zt:.5f}" size="{TOP_HW:.5f} {TOP_HW:.5f} {TOP_T / 2:.5f}" '
200
+ f'rgba="{_fmt(WOOD)}" friction="{TOP_MU} 0.005 0.0001" {TOP_SOLREF} group="0" />',
201
+ f' <geom type="box" pos="0 0 {zt:.5f}" size="{TOP_HW:.5f} {TOP_HW:.5f} {TOP_T / 2:.5f}" '
202
+ f'rgba="{_fmt(WOOD)}" contype="0" conaffinity="0" group="1" />']
203
+ for k, (sx, sy) in enumerate(CORNERS):
204
+ p = (sx * LEG_O, sy * LEG_O, zl)
205
+ # collision: a capsule inscribed in the square leg -> a rounded, point-like foot (a flat 1.6 cm foot moves the
206
+ # rocking axis 1.1 cm towards the loaded corner, and the table's own weight then stops the rock; measured)
207
+ s.append(f' <geom name="{name}_leg{k}" type="capsule" pos="{_fmt(p)}" '
208
+ f'size="{LEG_HW:.5f} {LEG_L / 2 - LEG_HW:.5f}" rgba="{_fmt(LEG_RGBA)}" '
209
+ f'friction="{LEG_MU} 0.005 0.0001" {TBL_SOLREF} group="0" />')
210
+ s.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt((LEG_HW, LEG_HW, LEG_L / 2))}" '
211
+ f'rgba="{_fmt(LEG_RGBA)}" contype="0" conaffinity="0" group="1" />')
212
+ for k, (sx, sy) in enumerate(CORNERS): # coloured spots (visual); colours are set per instance
213
+ s.append(f' <geom name="{name}_spot{k}" type="box" pos="{sx * SPOT_O:.5f} {sy * SPOT_O:.5f} {h + 0.0004:.5f}" '
214
+ f'size="{SPOT_HX:.5f} {SPOT_HY:.5f} 0.0004" rgba="0.5 0.5 0.5 1" contype="0" conaffinity="0" '
215
+ f'group="1" />')
216
+ return _wrap(name, "\n".join(s), h, TOP_HW * 1.42)
217
+
218
+
219
+ def _fb(d):
220
+ return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}"
221
+
222
+
223
+ def _lr(d):
224
+ return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}"
225
+
226
+
227
+ def _ang(a):
228
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
229
+
230
+
231
+ class WobblySkills(Skills):
232
+ """Skills that feed the task's per-step monitor."""
233
+
234
+ def __init__(self, env, task, recorder=None):
235
+ super().__init__(env, recorder=recorder)
236
+ self.task = task
237
+
238
+ def _act(self, dpos, drot, grip):
239
+ super()._act(dpos, drot, grip)
240
+ self.task.monitor_step()
241
+
242
+
243
+ @register_task
244
+ class WobblyTable(LFFTask):
245
+ name = "lh_wobbly_table"
246
+ level = "L2"
247
+ category = "state_restoration"
248
+ capabilities = ("Perceive", "Reason", "Restore", "Plan")
249
+ protocol = "cross"
250
+ max_attempts = 3
251
+ # careful: 4 bottles x ~7 commands + standing up to three fallen bottles again x ~9 + looking / corrections
252
+ agent_max_steps = 120
253
+ instruction = ("Put each of the four bottles on the spot of its own colour on the small wooden table. At the end "
254
+ "every bottle must stand upright on its spot, the gripper must be open and clear of the bottles, and "
255
+ "the small table must still stand where it is now. (Each bottle has a square neck with a small round "
256
+ "white stopper on top. Gripped on the neck, a bottle stays rigid in the fingers; gripped by the "
257
+ "stopper alone, it swings freely and hangs straight down.)")
258
+ instruction_indirect = ("Set the four coloured bottles out on the little wooden side table, each on the patch that "
259
+ "matches its colour. When you finish, all four have to be standing upright on their patches, "
260
+ "the gripper open and away from them, and the side table left where it stands. (Gripped "
261
+ "on its square neck a bottle stays rigid; gripped by the round white stopper alone it swings "
262
+ "freely and hangs straight down.)")
263
+ agent_object_names = ["bottles (red, blue, green, yellow; each with a square neck and a small round white stopper)",
264
+ "small wooden side table with four coloured spots (red, blue, green, yellow)"]
265
+
266
+ # ------------------------------------------------------------ scene
267
+ def make_bddl(self):
268
+ objs = []
269
+ for i, (c, b) in enumerate(zip(COLOURS, BOTTLES)):
270
+ cat = register_generated(f"LffLhwBottle{c.capitalize()}", bottle_xml(f"lff_lhw_bottle_{c}", RGBA[c]))
271
+ objs.append((b, cat, f"bottle{i}_region", (-0.30 + 0.13 * i, 0.30, -0.29 + 0.13 * i, 0.31)))
272
+ cat = register_generated("LffLhwSideTable", table_xml("lff_lhw_table"))
273
+ objs.append((TABLE, cat, "table_region", (-0.05, -0.30, -0.04, -0.29)))
274
+ return write_bddl(self.name, "Stand each bottle on the spot of its colour on the small table", objs, [])
275
+
276
+ def __init__(self, cam_res=None):
277
+ super().__init__(cam_res)
278
+ m = self.env.sim.model
279
+ self.tbid = envs.body_id(self.env, TABLE)
280
+ pre = f"{TABLE}_lff_lhw_table"
281
+ self.leg_gid = [m.geom_name2id(f"{pre}_leg{k}") for k in range(4)]
282
+ self.top_gid = m.geom_name2id(f"{pre}_top")
283
+ self.leg_size0 = [m.geom_size[g].copy() for g in self.leg_gid]
284
+ self.leg_pos0 = [m.geom_pos[g].copy() for g in self.leg_gid]
285
+ self.tbl_ipos0 = m.body_ipos[self.tbid].copy()
286
+ self.spot_gid = [m.geom_name2id(f"{pre}_spot{k}") for k in range(4)]
287
+ self.bbid = {b: envs.body_id(self.env, b) for b in BOTTLES}
288
+ self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhw_bottle_{c}_cap") for c, b in zip(COLOURS, BOTTLES)}
289
+ self.dof = {b: envs.free_joint_addr(self.env, b)[1] for b in BOTTLES}
290
+ self.tbl_dof = envs.free_joint_addr(self.env, TABLE)[1]
291
+ self.bgeoms = {b: envs.obj_geom_ids(self.env, b) for b in BOTTLES}
292
+ self.finger_geoms, self.hand_geoms, self.arm_geoms = [], [], []
293
+ for g in envs.robot_geom_ids(self.env):
294
+ n = m.geom_id2name(g) or ""
295
+ (self.finger_geoms if "finger" in n else self.hand_geoms if n.startswith("gripper0_")
296
+ else self.arm_geoms).append(g)
297
+ # per-geom lookup tables for the substep contact check: bottle index (-1 none), robot part (1 finger, 2 hand,
298
+ # 3 arm), table geom
299
+ self.owner = np.full(m.ngeom, -1, int)
300
+ for i, b in enumerate(BOTTLES):
301
+ self.owner[self.bgeoms[b]] = i
302
+ self.part = np.zeros(m.ngeom, int)
303
+ self.part[self.finger_geoms] = 1
304
+ self.part[self.hand_geoms] = 2
305
+ self.part[self.arm_geoms] = 3
306
+ self.is_table = np.zeros(m.ngeom, bool)
307
+ self.is_table[envs.obj_geom_ids(self.env, TABLE)] = True
308
+ self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
309
+ # contacts are collected after every MuJoCo substep (same technique as lh_nudge_row; wrappers chain)
310
+ sim = self.env.sim
311
+ if not getattr(sim, "_lhw_wrapped", False):
312
+ orig = sim.step
313
+
314
+ def step(*a, **k):
315
+ orig(*a, **k)
316
+ t = getattr(sim, "_lhw_task", None)
317
+ if t is not None and t.mon is not None:
318
+ t._substep()
319
+ sim.step = step
320
+ sim._lhw_wrapped = True
321
+ sim._lhw_task = self
322
+ self.inst = None
323
+ self.mon = None
324
+ self.sk = None
325
+ self._held_prev = None
326
+
327
+ def _substep(self):
328
+ d = self.env.sim.data
329
+ n = d.ncon
330
+ if not n:
331
+ return
332
+ g1 = np.asarray(d.contact.geom1)[:n]
333
+ g2 = np.asarray(d.contact.geom2)[:n]
334
+ o1, o2 = self.owner[g1], self.owner[g2]
335
+ for a, b, pa, pb in zip(g1, g2, o1, o2):
336
+ if pa < 0 and pb < 0:
337
+ if (self.is_table[a] and self.part[b]) or (self.is_table[b] and self.part[a]):
338
+ self._sub_tbl = 1
339
+ continue
340
+ if pa >= 0 and pb >= 0:
341
+ if pa != pb:
342
+ self._sub_obj[int(pa)] = int(pb)
343
+ self._sub_obj[int(pb)] = int(pa)
344
+ continue
345
+ p, o = (pa, b) if pa >= 0 else (pb, a)
346
+ part = int(self.part[o])
347
+ if part:
348
+ self._sub_rob[int(p)] = min(self._sub_rob.get(int(p), 9), part)
349
+
350
+ # ------------------------------------------------------------ instances
351
+ @staticmethod
352
+ def _supply(side, tx, ty, j):
353
+ """slot j (0-3) of the row of bottles on the main table: in front of the side table (robot side) or beside it;
354
+ every grasp point stays within 0.70 m (horizontal) of the robot base (the arm stalled 2-3 cm short of low
355
+ targets beyond ~0.72 m, measured)"""
356
+ if side == "front":
357
+ return [tx - 0.215, ty + (j - 1.5) * 0.085]
358
+ sg = 1.0 if side == "left" else -1.0
359
+ return [tx - 0.05 + (j - 1.5) * 0.075, ty + sg * 0.22]
360
+
361
+ @staticmethod
362
+ def _far_first(spot_of, side, tx, ty):
363
+ """colours in the order of the scripted naive policy: the spots farthest from the supply first (a careful agent
364
+ does not reach over bottles it has already put down), ties broken to the left, then far"""
365
+ sup = np.mean([WobblyTable._supply(side, tx, ty, j) for j in range(4)], axis=0)
366
+ sc = []
367
+ for c, k in spot_of.items():
368
+ sx, sy = CORNERS[k]
369
+ p = np.array([tx + sx * SPOT_O, ty + sy * SPOT_O])
370
+ sc.append((-round(float(np.linalg.norm(p - sup)), 3), -sy, -sx, c))
371
+ return [t[-1] for t in sorted(sc)]
372
+
373
+ def sample_instance(self, seed):
374
+ rng = np.random.default_rng(seed)
375
+ tx = float(rng.uniform(-0.13, -0.09)) # side table centre: 53-57 cm in front of the robot base
376
+ ty = float(rng.uniform(-0.04, 0.04))
377
+ side = str(rng.choice(["left", "right", "front"]))
378
+ perm = [int(v) for v in rng.permutation(4)] # perm[corner] = colour index on that corner's spot
379
+ spot_of = {COLOURS[perm[k]]: k for k in range(4)}
380
+ # the heavy bottle and the short leg under its spot: balanced over seeds against the scripted naive order (far
381
+ # spots first): its spot comes 1st / 2nd / 3rd / 4th in that order for exactly 5 of every 20 consecutive seeds
382
+ order = self._far_first(spot_of, side, tx, ty)
383
+ pos = int((int(seed) * 7) % 20 // 5)
384
+ heavy = order[pos]
385
+ short = spot_of[heavy]
386
+ slots = [int(v) for v in rng.permutation(4)]
387
+ start = {}
388
+ for i in range(4):
389
+ x, y = self._supply(side, tx, ty, slots[i])
390
+ start[COLOURS[i]] = [x + float(rng.uniform(-0.006, 0.006)), y + float(rng.uniform(-0.006, 0.006))]
391
+ mass = {c: float(rng.uniform(*LIGHT_MASS)) for c in COLOURS}
392
+ com = {c: float(rng.uniform(*LIGHT_COM)) for c in COLOURS}
393
+ mass[heavy] = float(rng.uniform(*HEAVY_MASS))
394
+ com[heavy] = float(rng.uniform(*HEAVY_COM))
395
+ return dict(seed=int(seed), table_xy=[tx, ty], short_leg=int(short), short_corner=CORNER_NAME[CORNERS[short]],
396
+ heavy=heavy, heavy_rank_naive=pos + 1, spot_of=spot_of, supply_side=side, start=start, mass=mass,
397
+ com=com, short_h=float(rng.uniform(*SHORT_H)), com_bias=COM_BIAS,
398
+ yaw0={c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS},
399
+ naive_bias_x=float(rng.uniform(*NAIVE_BIAS)))
400
+
401
+ def apply_instance(self, inst):
402
+ self.inst = inst
403
+ m = self.env.sim.model
404
+ k = inst["short_leg"]
405
+ h = float(inst["short_h"])
406
+ for j, g in enumerate(self.leg_gid):
407
+ m.geom_size[g] = self.leg_size0[j]
408
+ m.geom_pos[g] = self.leg_pos0[j]
409
+ g = self.leg_gid[k]
410
+ m.geom_size[g][1] = self.leg_size0[k][1] - h / 2 # capsule half length
411
+ m.geom_pos[g][2] = self.leg_pos0[k][2] + h / 2
412
+ opp = CORNERS[(k + 2) % 4]
413
+ b = float(inst.get("com_bias", COM_BIAS)) / np.sqrt(2)
414
+ m.body_ipos[self.tbid] = [opp[0] * b, opp[1] * b, self.tbl_ipos0[2]]
415
+ envs.refit_bounds(m, self.tbid)
416
+ for c in COLOURS:
417
+ m.geom_rgba[self.spot_gid[inst["spot_of"][c]]] = SPOT_RGBA[c]
418
+ for c, bot in zip(COLOURS, BOTTLES):
419
+ bid = self.bbid[bot]
420
+ M, zc = inst["mass"][c], inst["com"][c]
421
+ m.body_mass[bid] = M
422
+ m.body_ipos[bid] = [0.0, 0.0, -H_TOT / 2 + zc]
423
+ # glass shell + internal weight, roughly: radius of gyration ~ 0.35 x height about horizontal axes
424
+ ixx = M * ((2 * RB) ** 2 / 12 + (0.35 * H_TOT) ** 2)
425
+ m.body_inertia[bid] = [ixx, ixx, M * (2 * RB) ** 2 / 6]
426
+ envs.refit_bounds(m, bid)
427
+ m.dof_damping[self.dof[bot]:self.dof[bot] + 6] = BOT_DAMP
428
+ self.env.sim.forward()
429
+ tx, ty = inst["table_xy"]
430
+ # yaw pi: the canonical quaternion LIBERO gives generated objects is a 180 deg yaw (envs.canonical_quat); with
431
+ # it the table frame is the world frame
432
+ envs.place_upright(self.env, TABLE, [tx, ty], yaw=np.pi, clearance=0.0003)
433
+ for c, bot in zip(COLOURS, BOTTLES):
434
+ envs.place_upright(self.env, bot, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
435
+ self.env.sim.data.qvel[self.tbl_dof:self.tbl_dof + 6] = 0.0
436
+
437
+ def reset_instance(self, inst, recorder=None):
438
+ self.mon = None
439
+ self.env.reset()
440
+ self.apply_instance(inst)
441
+ self.env.sim.forward()
442
+ envs.settle(self.env, 15)
443
+ self.sk = WobblySkills(self.env, self, recorder=recorder)
444
+ self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
445
+ self._held_prev = None
446
+ self.table0 = dict(pos=self.table_pos().tolist(), yaw=self.table_yaw())
447
+ n = len(BOTTLES)
448
+ self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
449
+ lost_cause=[None] * n, last_robot=[None] * n, last_obj=[None] * n, last_release=None,
450
+ last_table_touch=-10 ** 6, rocked=False, rock_since=0, rocks=[], n_steps=0,
451
+ max_table_tilt_deg=0.0)
452
+ return self.sk
453
+
454
+ # ------------------------------------------------------------ geometry / predicates
455
+ def table_R(self):
456
+ return self.env.sim.data.body_xmat[self.tbid].reshape(3, 3).copy()
457
+
458
+ def table_pos(self):
459
+ return self.env.sim.data.body_xpos[self.tbid].copy()
460
+
461
+ def table_yaw(self):
462
+ R = self.table_R()
463
+ return float(np.arctan2(R[1, 0], R[0, 0]))
464
+
465
+ def table_tilt(self):
466
+ return float(np.arccos(np.clip(self.table_R()[2, 2], -1, 1)))
467
+
468
+ def top_point(self, local_xy):
469
+ """world position of a point on the table's top surface (table frame xy)"""
470
+ return self.table_pos() + self.table_R() @ np.array([local_xy[0], local_xy[1], TABLE_H / 2])
471
+
472
+ def spot_local(self, colour):
473
+ sx, sy = CORNERS[self.inst["spot_of"][colour]]
474
+ return np.array([sx * SPOT_O, sy * SPOT_O])
475
+
476
+ def spot_world(self, colour):
477
+ return self.top_point(self.spot_local(colour))
478
+
479
+ def top_z_at(self, xy):
480
+ """z of the table's top plane above world point xy"""
481
+ R, p = self.table_R(), self.table_pos()
482
+ n = R[:, 2]
483
+ c = p + n * TABLE_H / 2
484
+ return float(c[2] - (n[0] * (xy[0] - c[0]) + n[1] * (xy[1] - c[1])) / max(n[2], 1e-6))
485
+
486
+ def over_table(self, xy):
487
+ loc = self.table_R().T @ (np.array([xy[0], xy[1], self.table_pos()[2]]) - self.table_pos())
488
+ return abs(loc[0]) < TOP_HW and abs(loc[1]) < TOP_HW
489
+
490
+ def bR(self, b):
491
+ return self.env.sim.data.body_xmat[self.bbid[b]].reshape(3, 3).copy()
492
+
493
+ def bpos(self, b):
494
+ return self.env.sim.data.body_xpos[self.bbid[b]].copy()
495
+
496
+ def foot(self, b):
497
+ """world position of the centre of the bottle's bottom face"""
498
+ return self.bpos(b) - self.bR(b)[:, 2] * H_TOT / 2
499
+
500
+ def tilt(self, b):
501
+ return float(np.arccos(np.clip(self.bR(b)[2, 2], -1.0, 1.0)))
502
+
503
+ def cap_xyz(self, b):
504
+ return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy()
505
+
506
+ def held(self, b):
507
+ return self.sk is not None and self.sk.holding(b)
508
+
509
+ def offset(self, i):
510
+ """bottle i's foot centre relative to its spot centre, in the table frame (x forward-back, y left-right), and
511
+ the height of its bottom above the table top"""
512
+ b, c = BOTTLES[i], COLOURS[i]
513
+ loc = self.table_R().T @ (self.foot(b) - self.table_pos())
514
+ return loc[:2] - self.spot_local(c), float(loc[2] - TABLE_H / 2)
515
+
516
+ def on_spot(self, i, extra=0.0):
517
+ b = BOTTLES[i]
518
+ if self.tilt(b) > TILT_OK + (np.radians(2.0) if extra else 0.0):
519
+ return False
520
+ off, dz = self.offset(i)
521
+ if abs(off[0]) > TOL_X + extra or abs(off[1]) > TOL_Y + extra or abs(dz) > ON_TOP:
522
+ return False
523
+ return not self.held(b)
524
+
525
+ def stages(self):
526
+ return [self.on_spot(i) for i in range(len(BOTTLES))]
527
+
528
+ def table_ok(self):
529
+ p0 = np.asarray(self.table0["pos"])
530
+ moved = float(np.linalg.norm(self.table_pos()[:2] - p0[:2]))
531
+ dyaw = abs(_ang(self.table_yaw() - self.table0["yaw"]))
532
+ return bool(moved <= TABLE_MOVE_TOL and dyaw <= TABLE_YAW_TOL and self.table_tilt() <= TABLE_TILT_MAX), moved, dyaw
533
+
534
+ def low_corner(self):
535
+ """robot-centric name of the table corner that is lowest (after a rock: the corner over the short leg)"""
536
+ zs = {k: self.top_point([sx * TOP_HW, sy * TOP_HW])[2] for k, (sx, sy) in enumerate(CORNERS)}
537
+ return CORNER_NAME[CORNERS[min(zs, key=zs.get)]]
538
+
539
+ # ------------------------------------------------------------ monitor
540
+ def monitor_step(self):
541
+ mon = self.mon
542
+ if mon is None or self.sk is None:
543
+ return
544
+ mon["n_steps"] += 1
545
+ t = int(self.sk.n_steps)
546
+ rob, obj, tbl = dict(self._sub_rob), dict(self._sub_obj), self._sub_tbl
547
+ self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0
548
+ gstate = "open" if self.sk.grip < 0 else "closed"
549
+ held_now = None
550
+ for c, b in zip(COLOURS, BOTTLES):
551
+ if gstate == "closed" and self.held(b):
552
+ held_now = c
553
+ for i, part in rob.items():
554
+ if COLOURS[i] != held_now:
555
+ mon["last_robot"][i] = [{1: "finger", 2: "hand", 3: "arm"}[part], t, gstate]
556
+ for i, j in obj.items():
557
+ mon["last_obj"][i] = [COLOURS[j], t]
558
+ if tbl:
559
+ mon["last_table_touch"] = t
560
+ if held_now is None and self._held_prev is not None: # the gripper has just let go of a bottle
561
+ mon["last_release"] = [self._held_prev, t]
562
+ self._held_prev = held_now
563
+ tl = self.table_tilt()
564
+ mon["max_table_tilt_deg"] = max(mon["max_table_tilt_deg"], round(float(np.degrees(tl)), 2))
565
+ if mon["n_steps"] % 2:
566
+ return
567
+ # ---- table rock detector (debounced)
568
+ want = tl > ROCK_ON if not mon["rocked"] else tl > ROCK_OFF
569
+ if want != mon["rocked"]:
570
+ mon["rock_since"] += 2
571
+ if mon["rock_since"] >= 4:
572
+ mon["rocked"] = want
573
+ mon["rock_since"] = 0
574
+ self._rock_event(want, t - 3)
575
+ else:
576
+ mon["rock_since"] = 0
577
+ for r in mon["rocks"]:
578
+ if not r.get("closed") and t - r["step"] > FELL_WINDOW:
579
+ self._close_rock(r)
580
+ # ---- stage predicates
581
+ for i in range(len(BOTTLES)):
582
+ b = BOTTLES[i]
583
+ raw = self.on_spot(i, HYST if mon["state"][i] else 0.0)
584
+ if raw == mon["state"][i]:
585
+ mon["raw_since"][i] = 0
586
+ continue
587
+ mon["raw_since"][i] += 2
588
+ if mon["raw_since"][i] < DEBOUNCE:
589
+ continue
590
+ mon["state"][i] = raw
591
+ mon["raw_since"][i] = 0
592
+ t0 = int(t - DEBOUNCE + 1)
593
+ if raw:
594
+ restored = mon["lost"][i]
595
+ e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0)
596
+ if restored:
597
+ e["after"] = mon["lost_cause"][i]
598
+ mon["events"].append(e)
599
+ mon["ever"][i] = True
600
+ else:
601
+ mon["lost"][i] = True
602
+ cause = self._cause(i, t0)
603
+ mon["lost_cause"][i] = cause
604
+ off, dz = self.offset(i)
605
+ mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause,
606
+ tilt_deg=round(float(np.degrees(self.tilt(b))), 1),
607
+ offset_cm=[round(100 * float(v), 1) for v in off]))
608
+
609
+ def _rock_event(self, down, t):
610
+ mon = self.mon
611
+ rel = mon["last_release"]
612
+ e = dict(event="table_rocked" if down else "table_rocked_back", step=int(t),
613
+ table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), low_corner=self.low_corner(),
614
+ released=rel[0] if rel is not None and t - rel[1] <= 40 else None,
615
+ robot_touched_table=bool(t - mon["last_table_touch"] <= 20),
616
+ standing=[COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i]])
617
+ # the cheap explanation would be "my hand bumped them": which of the standing bottles did the robot touch in
618
+ # the 2 s before the rock (should be none)
619
+ e["robot_touched_before"] = [COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i] and
620
+ mon["last_robot"][i] is not None and t - mon["last_robot"][i][1] <= 40]
621
+ mon["events"].append(e)
622
+ mon["rocks"].append(dict(step=int(t), down=bool(down), standing=list(e["standing"]), event=e))
623
+
624
+ def _close_rock(self, r):
625
+ """FELL_WINDOW after a rock: which of the bottles that stood on their spots fell, and did the robot touch any
626
+ of them after the rock began (a falling bottle hitting the open fingers)"""
627
+ r["closed"] = True
628
+ mon = self.mon
629
+ fell, touched = [], []
630
+ for c in r["standing"]:
631
+ i = COLOURS.index(c)
632
+ if self.tilt(BOTTLES[i]) > np.radians(30) or not mon["state"][i]:
633
+ fell.append(c)
634
+ lr = mon["last_robot"][i]
635
+ if lr is not None and lr[1] >= r["step"]:
636
+ touched.append(c)
637
+ r["event"]["fell"] = fell
638
+ r["event"]["robot_touched_while_falling"] = touched
639
+ r["fell"] = fell
640
+
641
+ def _cause(self, i, t, window=60):
642
+ if self.held(BOTTLES[i]):
643
+ return "picked_up"
644
+ mon = self.mon
645
+ for r in reversed(mon["rocks"]):
646
+ if 0 <= t - r["step"] <= FELL_WINDOW + 10 and COLOURS[i] in r["standing"]:
647
+ return "table_rocked" if r["down"] else "table_rocked_back"
648
+ lr, lo = mon["last_robot"][i], mon["last_obj"][i]
649
+ cands = []
650
+ if lr is not None and t - lr[1] <= window:
651
+ cands.append((lr[1], f"robot_{lr[0]}"))
652
+ if lo is not None and t - lo[1] <= window:
653
+ cands.append((lo[1] - 30, "bottle:" + lo[0]))
654
+ return max(cands)[1] if cands else "other"
655
+
656
+ def _finalize_monitor(self, raw):
657
+ mon = self.mon
658
+ if mon is None:
659
+ return
660
+ for r in mon["rocks"]:
661
+ if not r.get("closed"):
662
+ self._close_rock(r)
663
+ t = int(self.sk.n_steps)
664
+ for i in range(len(BOTTLES)):
665
+ if raw[i] == mon["state"][i]:
666
+ continue
667
+ mon["state"][i] = raw[i]
668
+ if raw[i]:
669
+ restored = mon["lost"][i]
670
+ e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True)
671
+ if restored:
672
+ e["after"] = mon["lost_cause"][i]
673
+ mon["events"].append(e)
674
+ mon["ever"][i] = True
675
+ else:
676
+ mon["lost"][i] = True
677
+ cause = self._cause(i, t, window=10 ** 6)
678
+ mon["lost_cause"][i] = cause
679
+ mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True))
680
+
681
+ # ------------------------------------------------------------ outcome
682
+ def _touching(self):
683
+ d = self.env.sim.data
684
+ for j in range(d.ncon):
685
+ c = d.contact[j]
686
+ if (self.owner[c.geom1] >= 0 and self.part[c.geom2]) or (self.owner[c.geom2] >= 0 and self.part[c.geom1]):
687
+ return True
688
+ return False
689
+
690
+ def outcome(self, inst):
691
+ sk = self.sk
692
+ sk.hold(10)
693
+ p0 = {b: self.bpos(b) for b in BOTTLES}
694
+ t0 = self.table_pos()
695
+ touching = False
696
+ for _ in range(20):
697
+ sk.hold(1)
698
+ touching = touching or self._touching()
699
+ moved = max([float(np.linalg.norm(self.bpos(b) - p0[b])) for b in BOTTLES] +
700
+ [float(np.linalg.norm(self.table_pos() - t0))])
701
+ static = moved < 0.003
702
+ raw = self.stages()
703
+ self._finalize_monitor(raw)
704
+ held = [COLOURS[i] for i, b in enumerate(BOTTLES) if self.held(b)]
705
+ tok, tmoved, tyaw = self.table_ok()
706
+ mon = self.mon
707
+ ev = list(mon["events"])
708
+ rocks = [r for r in mon["rocks"] if r["down"]]
709
+ damaging = [r for r in mon["rocks"] if r.get("fell")]
710
+ n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
711
+ n_lost = sum(e.get("event") == "lost" for e in ev)
712
+ n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
713
+ success = bool(all(raw) and static and not held and not touching and tok)
714
+ tilted = [i for i in range(len(BOTTLES)) if self.tilt(BOTTLES[i]) > TILT_OK and COLOURS[i] not in held]
715
+ ever = mon["ever"]
716
+ fell_by_rock = sorted({c for r in damaging for c in r["fell"]})
717
+ if success:
718
+ failure = "none"
719
+ elif not tok:
720
+ failure = "table_moved"
721
+ elif held:
722
+ failure = "held"
723
+ elif tilted:
724
+ failure = "toppled_by_rock" if any(COLOURS[i] in fell_by_rock for i in tilted) else "toppled"
725
+ elif not all(raw):
726
+ failure = "not_on_spot"
727
+ elif touching:
728
+ failure = "touching"
729
+ else:
730
+ failure = "not_static"
731
+ parts = []
732
+ if success:
733
+ parts.append("Every bottle stands upright on the spot of its colour.")
734
+ for i in range(len(BOTTLES)):
735
+ if raw[i]:
736
+ continue
737
+ c, b = COLOURS[i], BOTTLES[i]
738
+ if c in held:
739
+ parts.append(f"The {c} bottle is still held by the gripper.")
740
+ continue
741
+ off, dz = self.offset(i)
742
+ tl = float(np.degrees(self.tilt(b)))
743
+ on_small = abs(dz) < 0.05 and max(abs(off + self.spot_local(c))) < TOP_HW + 0.02
744
+ if tl > np.degrees(TILT_OK):
745
+ txt = (f"The {c} bottle lies on its side on the {'small' if on_small else 'big'} table" if tl > 45 else
746
+ f"The {c} bottle leans {tl:.0f} degrees") + "."
747
+ elif abs(dz) > ON_TOP:
748
+ txt = f"The {c} bottle is not on the small table."
749
+ else:
750
+ txt = f"The {c} bottle stands {_fb(off[0])} and {_lr(off[1])} of its spot's centre, not on its spot."
751
+ if ever[i] and c in fell_by_rock:
752
+ txt += " It had stood on its spot and fell when the small table rocked."
753
+ elif ever[i]:
754
+ txt += " It had stood on its spot earlier."
755
+ parts.append(txt)
756
+ if not tok:
757
+ parts.append(f"The small table was moved ({100 * tmoved:.1f} cm, {np.degrees(tyaw):.0f} degrees).")
758
+ elif not success and all(raw):
759
+ if touching:
760
+ parts.append("The gripper is still touching a bottle.")
761
+ elif not static:
762
+ parts.append("Something was still moving.")
763
+ if rocks:
764
+ r = rocks[0]["event"]
765
+ txt = (f"When the {r['released']} bottle was set down, the small table rocked down onto its "
766
+ f"{r['low_corner']} leg" if r.get("released") else
767
+ f"The small table rocked down onto its {r['low_corner']} leg")
768
+ fl = r.get("fell", [])
769
+ txt += (" and the " + " and ".join(fl) + f" bottle{'s' if len(fl) > 1 else ''} standing on it fell over."
770
+ if fl else ".")
771
+ txt += f" That leg is {100 * float(inst['short_h']):.1f} cm shorter than the other three."
772
+ parts.append(txt)
773
+ trap = bool(damaging)
774
+ return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(BOTTLES))}, events=ev,
775
+ n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_rocks=len(rocks),
776
+ rocked=bool(rocks), trap_fired=trap, recovered_in_attempt=bool(trap and success),
777
+ fell_by_rock=fell_by_rock, failure=failure, held=held, touching=bool(touching),
778
+ static=bool(static), table_ok=bool(tok), table_moved_cm=round(100 * tmoved, 2),
779
+ table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2),
780
+ max_table_tilt_deg=mon["max_table_tilt_deg"],
781
+ offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)[0]] for i in range(4)},
782
+ tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(BOTTLES[i]))), 1) for i in range(4)},
783
+ heavy=inst["heavy"], short_corner=inst["short_corner"], detail=" ".join(parts))
784
+
785
+ # ------------------------------------------------------------ scripted primitives (move_to + gripper only)
786
+ def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
787
+ return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
788
+
789
+ def _lift_to(self, z, speed=0.2):
790
+ cur = self.sk.eef_pos()
791
+ if cur[2] < TZ + z - 0.005:
792
+ self._go([cur[0], cur[1], TZ + z], speed=speed)
793
+
794
+ def _settle(self, b, max_checks=25):
795
+ d = self.env.sim.data
796
+ da = self.dof[b]
797
+ for _ in range(max_checks):
798
+ if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
799
+ return
800
+ self.sk.hold(2)
801
+
802
+ def upright(self, b):
803
+ return self.tilt(b) < np.radians(20)
804
+
805
+ def pick_neck(self, b, z_carry=Z_CARRY, yaw=0.0, v=0.2):
806
+ """Sonnet-like top-down pick of a standing bottle: open, over it at carry height, straight down to the upper
807
+ neck, close, lift to carry height. Returns True if held."""
808
+ sk = self.sk
809
+ self._settle(b)
810
+ p = self.foot(b)
811
+ zg = p[2] + NECK_Z[1] - GRASP_NECK
812
+ sk.set_gripper(False, steps=8)
813
+ self._lift_to(z_carry)
814
+ self._go([p[0], p[1], TZ + z_carry], yaw=yaw, speed=v)
815
+ self._go([p[0], p[1], zg + 0.02], speed=0.12)
816
+ self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150)
817
+ sk.set_gripper(True, steps=15)
818
+ self._go([p[0], p[1], TZ + z_carry], speed=0.12)
819
+ sk.hold(5)
820
+ if not self.held(b):
821
+ sk.set_gripper(False, steps=8)
822
+ return False
823
+ return True
824
+
825
+ def put_held(self, b, xy, gap, z_carry=Z_CARRY, yaw=None, v=0.2):
826
+ """carry the held bottle so that its foot is over world xy, straight down until its bottom is `gap` above the
827
+ surface below, let go, lift"""
828
+ sk = self.sk
829
+ rel = self.foot(b)[:2] - sk.eef_pos()[:2]
830
+ q = np.asarray(xy, float) - rel
831
+ self._go([q[0], q[1], TZ + z_carry], yaw=yaw, speed=v)
832
+ sk.hold(10)
833
+ rel = self.foot(b)[:2] - sk.eef_pos()[:2] # a bottle hanging from its stopper swings while carried
834
+ q = np.asarray(xy, float) - rel
835
+ surf = self.top_z_at(xy) if self.over_table(xy) else TZ
836
+ dz = sk.eef_pos()[2] - self.foot(b)[2]
837
+ zr = surf + dz + gap
838
+ self._go([q[0], q[1], zr + 0.02], speed=0.10)
839
+ self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
840
+ sk.hold(4)
841
+ sk.set_gripper(False, steps=12)
842
+ cur = sk.eef_pos()
843
+ self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.10)
844
+ self._go([cur[0], cur[1], TZ + z_carry], speed=0.2)
845
+ sk.hold(3)
846
+
847
+ def surface_z(self, xy):
848
+ return self.top_z_at(xy) if self.over_table(xy) else TZ
849
+
850
+ def pick_stopper(self, b, v=0.15):
851
+ """grasp a lying (or leaning) bottle by its round stopper from above, fingers across the bottle's axis, lift it
852
+ until it hangs free. The fingertips stay >= 4 mm above the surface under the stopper: pressing the raised half
853
+ of the rocked table rocks it back (measured), and the knock when it comes down again topples standing bottles.
854
+ Returns True if held."""
855
+ sk = self.sk
856
+ self._settle(b)
857
+ for _ in range(2):
858
+ k, zg, yaw = self.stopper_grasp(b) # fingers across the bottle's axis
859
+ sk.set_gripper(False, steps=8)
860
+ self._lift_to(Z_HANG)
861
+ self._go([k[0], k[1], TZ + Z_HANG], yaw=yaw, speed=v)
862
+ sk.hold(5)
863
+ k, zg, _ = self.stopper_grasp(b)
864
+ self._go([k[0], k[1], zg + 0.03], speed=0.10)
865
+ self._go([k[0], k[1], zg], speed=0.03, tol=0.003, max_steps=120)
866
+ sk.set_gripper(True, steps=15)
867
+ if not self.held(b):
868
+ sk.set_gripper(False, steps=8)
869
+ self._go([k[0], k[1], zg + 0.08], speed=0.1)
870
+ continue
871
+ self._go([k[0], k[1], zg + 0.05], speed=0.05)
872
+ self._go([k[0], k[1], TZ + Z_HANG], speed=0.10)
873
+ sk.hold(20)
874
+ return True
875
+ return False
876
+
877
+ # gripper footprint (measured, t8_hand): the hand's collision hull is a slab 20 cm along the finger axis and ~4 cm
878
+ # across, from 3 cm above the grasp point up; open fingers 3.9-6.6 cm out along the finger axis, from 1 cm below
879
+ # the grasp point to 4.5 cm above it
880
+ HAND_U, HAND_V, HAND_Z0 = 0.100, (-0.018, 0.024), 0.03
881
+ FING_U, FING_V, FING_Z = (0.039, 0.066), (-0.009, 0.013), (-0.010, 0.045)
882
+ # wrist and forearm (t16_arm, measured at low grasps): lowest point above the grasp point vs the distance from the
883
+ # grasp point towards the robot base; they span ~13 cm to either side of that line
884
+ ARM_D = (-0.05, 0.05, 0.10, 0.15, 0.20)
885
+ ARM_Z = (0.097, 0.100, 0.155, 0.185, 0.31)
886
+ ARM_LAT = 0.13
887
+
888
+ def _footprint(self, q, yaw):
889
+ """sample points (xy) of the hand slab and of the open fingers for a grasp at q with gripper yaw `yaw`"""
890
+ a = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis
891
+ c = np.array([np.cos(yaw), np.sin(yaw)])
892
+ hand = [q + u * a + v * c for u in np.linspace(-self.HAND_U, self.HAND_U, 21)
893
+ for v in np.linspace(*self.HAND_V, 5)]
894
+ fing = [q + sg * u * a + v * c for sg in (-1, 1) for u in np.linspace(*self.FING_U, 4)
895
+ for v in np.linspace(*self.FING_V, 3)]
896
+ return np.array(hand), np.array(fing)
897
+
898
+ def grasp_clearance(self, q, zg, yaw, ignore=()):
899
+ """smallest horizontal clearance (m) between the hand / open fingers of a grasp at (q, zg) and any standing
900
+ bottle (other than `ignore`) or the small table; negative = collision"""
901
+ q = np.asarray(q, float)[:2]
902
+ hand, fing = self._footprint(q, yaw)
903
+ best = 1.0
904
+ for b in BOTTLES:
905
+ if b in ignore or self.held(b) or self.tilt(b) > np.radians(30):
906
+ continue
907
+ p = self.foot(b)[:2]
908
+ top = self.foot(b)[2] + H_TOT
909
+ r = RB * 1.42
910
+ if top > zg + self.HAND_Z0:
911
+ best = min(best, float(np.min(np.linalg.norm(hand - p, axis=1))) - r)
912
+ best = min(best, float(np.min(np.linalg.norm(fing - p, axis=1))) - r)
913
+ # the wrist / forearm sloping back towards the robot base over a tall standing bottle
914
+ ub = np.array([-0.66, 0.0]) - q
915
+ ub /= max(float(np.linalg.norm(ub)), 1e-6)
916
+ along, lat = float((p - q) @ ub), float((p - q) @ np.array([-ub[1], ub[0]]))
917
+ if self.ARM_D[0] <= along <= self.ARM_D[-1] and abs(lat) < self.ARM_LAT + r:
918
+ if top > zg + float(np.interp(along, self.ARM_D, self.ARM_Z)) - 0.01:
919
+ best = min(best, -0.01)
920
+ # the small table's top plate (and legs) when the grasp is below its top surface
921
+ R, P = self.table_R(), self.table_pos()
922
+ ztop = P[2] + TABLE_H / 2
923
+ for pts, z0, z1 in ((hand, zg + self.HAND_Z0, zg + 0.13), (fing, zg + self.FING_Z[0], zg + self.FING_Z[1])):
924
+ if z0 > ztop + 0.003:
925
+ continue
926
+ loc = (pts - P[:2]) @ R[:2, :2]
927
+ if z1 > ztop - TOP_T: # the plate's height band
928
+ d = np.maximum(np.abs(loc) - TOP_HW, 0.0)
929
+ inside = np.all(np.abs(loc) < TOP_HW, axis=1)
930
+ dist = np.where(inside, -0.01, np.linalg.norm(d, axis=1))
931
+ best = min(best, float(np.min(dist)))
932
+ return best
933
+
934
+ def stopper_grasp(self, b):
935
+ """(xy, z, yaw) of the stopper grasp of a lying bottle: fingers across its axis, fingertips >= 4 mm above the
936
+ surface below"""
937
+ k = self.cap_xyz(b)
938
+ ax = self.bR(b)[:2, 2]
939
+ yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw
940
+ zg = max(float(k[2]), self.surface_z(k[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004)
941
+ return k[:2], zg, yaw
942
+
943
+ def body_grasp(self, b, along=None):
944
+ """(xy, z, yaw) of a grasp across a lying bottle's body, `along` m from its bottom (default: the middle)"""
945
+ R = self.bR(b)
946
+ a = HF + (HB - HF) / 2 if along is None else float(along)
947
+ c = self.foot(b) + R[:, 2] * a
948
+ ax = R[:2, 2]
949
+ yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw
950
+ zg = max(float(c[2]), self.surface_z(c[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004)
951
+ return c[:2], zg, yaw
952
+
953
+ def staging_spot(self, b):
954
+ """a free place on the main table to lay a fallen bottle down: far from the small table and the other bottles,
955
+ within the arm's comfortable reach"""
956
+ tx, ty = self.table_pos()[:2]
957
+ best, bq = -1.0, None
958
+ for x in np.arange(tx - 0.30, tx + 0.06, 0.03):
959
+ for y in np.arange(ty - 0.30, ty + 0.31, 0.03):
960
+ # within reach, and >= 14 cm inside the main table's edges (it spans x, y = +-0.5, +-0.6): a bottle laid
961
+ # down too close to the near edge rolled off onto the floor (measured)
962
+ if np.hypot(x + 0.66, y) > 0.66 or np.hypot(x + 0.66, y) < 0.33 or x < -0.36 or abs(y) > 0.46:
963
+ continue
964
+ loc = self.table_R()[:2, :2].T @ (np.array([x, y]) - np.array([tx, ty]))
965
+ dt = float(np.linalg.norm(np.maximum(np.abs(loc) - TOP_HW, 0.0)))
966
+ if np.all(np.abs(loc) < TOP_HW):
967
+ continue
968
+ do = min([float(np.linalg.norm(self.foot(o)[:2] - [x, y])) for o in BOTTLES if o != b] +
969
+ [float(np.linalg.norm(self.cap_xyz(o)[:2] - [x, y])) for o in BOTTLES if o != b])
970
+ sc = min(dt - 0.10, do - 0.14) # the bottle lies ~16 cm long around the point
971
+ if sc > best and min(self.grasp_clearance([x, y], TZ + 0.016, yw, ignore=(b,))
972
+ for yw in (0.0, np.pi / 2)) > 0.01:
973
+ best, bq = sc, np.array([x, y])
974
+ return bq
975
+
976
+ def stage(self, b, v=0.12):
977
+ """the stopper of a fallen bottle cannot be reached: grasp its body at a point where the hand is clear (the
978
+ bottle then hangs from the grasp), carry it to free space on the main table, let it down there so that it falls
979
+ over away from everything. Returns True if it was moved."""
980
+ sk = self.sk
981
+ for along in (0.055, 0.035, 0.075, 0.015, 0.095):
982
+ q, zg, yaw = self.body_grasp(b, along)
983
+ if self.grasp_clearance(q, zg, yaw, ignore=(b,)) >= 0.004:
984
+ break
985
+ else:
986
+ return False
987
+ dst = self.staging_spot(b)
988
+ if dst is None:
989
+ return False
990
+ sk.set_gripper(False, steps=8)
991
+ self._lift_to(Z_CARRY)
992
+ self._go([q[0], q[1], TZ + Z_CARRY], yaw=yaw, speed=v)
993
+ self._go([q[0], q[1], zg + 0.03], speed=0.10)
994
+ self._go([q[0], q[1], zg], speed=0.03, tol=0.003, max_steps=120)
995
+ sk.set_gripper(True, steps=15)
996
+ if not self.held(b):
997
+ sk.set_gripper(False, steps=8)
998
+ self._go([q[0], q[1], TZ + Z_CARRY], speed=0.1)
999
+ return False
1000
+ self._go([q[0], q[1], zg + 0.04], speed=0.05)
1001
+ self._go([q[0], q[1], TZ + Z_HANG], speed=0.10)
1002
+ sk.hold(15)
1003
+ self._go([dst[0], dst[1], TZ + Z_HANG], speed=0.10)
1004
+ sk.hold(15)
1005
+ drop = envs.obj_min_z(self.env, b) - (TZ + 0.012)
1006
+ cur = sk.eef_pos()
1007
+ self._go([cur[0], cur[1], cur[2] - drop], speed=0.08)
1008
+ sk.set_gripper(False, steps=12)
1009
+ cur = sk.eef_pos()
1010
+ self._go([cur[0], cur[1], TZ + Z_HANG], speed=0.15)
1011
+ self._settle(b, 40)
1012
+ return True
1013
+
1014
+ def restand(self, i, gap=CAREFUL_GAP, err=None):
1015
+ """stand bottle i up again on its spot: if the stopper cannot be grasped without the hand touching a standing
1016
+ bottle or the small table, first lay the bottle down in free space; grasp the stopper, let the bottle hang,
1017
+ carry it over the spot, lower it until its bottom is `gap` above the table top, let go"""
1018
+ b, c = BOTTLES[i], COLOURS[i]
1019
+ q, zg, yaw = self.stopper_grasp(b)
1020
+ if self.grasp_clearance(q, zg, yaw, ignore=(b,)) < 0.005:
1021
+ self.stage(b)
1022
+ if not self.pick_stopper(b):
1023
+ return False
1024
+ tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0)
1025
+ self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10)
1026
+ self._settle(b)
1027
+ return self.on_spot(i)
1028
+
1029
+ def place(self, i, gap, err=None, z_carry=Z_CARRY, yaw=0.0, v=0.2):
1030
+ """one stage: pick bottle i (by the neck if it stands, by the stopper if it lies) and put it on its spot"""
1031
+ b, c = BOTTLES[i], COLOURS[i]
1032
+ tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0)
1033
+ if self.upright(b):
1034
+ if not self.pick_neck(b, z_carry=z_carry, yaw=yaw, v=v) and not self.pick_neck(b, z_carry=z_carry,
1035
+ yaw=yaw, v=v):
1036
+ return False
1037
+ self.put_held(b, tgt, gap, z_carry=z_carry, yaw=yaw, v=v)
1038
+ else:
1039
+ if not self.pick_stopper(b):
1040
+ return False
1041
+ self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10)
1042
+ self._settle(b)
1043
+ return True
1044
+
1045
+ def repair_order(self, idx):
1046
+ """bottles to fix: one standing upright off its spot first (it may be the heavy one: re-placing it rocks the
1047
+ table), then lying ones whose stopper is easiest to reach"""
1048
+ def key(j):
1049
+ b = BOTTLES[j]
1050
+ if self.upright(b):
1051
+ return (0, 0.0)
1052
+ q, zg, yaw = self.stopper_grasp(b)
1053
+ return (1, -self.grasp_clearance(q, zg, yaw, ignore=(b,)))
1054
+ return sorted(idx, key=key)
1055
+
1056
+ def fix(self, i, gap=CAREFUL_GAP):
1057
+ if self.upright(BOTTLES[i]):
1058
+ self.place(i, gap)
1059
+ else:
1060
+ self.restand(i, gap)
1061
+
1062
+ def check_and_repair(self, rounds=3, gap=CAREFUL_GAP):
1063
+ """look at every bottle; stand up / re-place every one that is not on its spot"""
1064
+ for _ in range(rounds):
1065
+ bad = [i for i in range(4) if not self.on_spot(i)]
1066
+ if not bad:
1067
+ return True
1068
+ for i in self.repair_order(bad):
1069
+ if not self.on_spot(i):
1070
+ self.fix(i, gap)
1071
+ return all(self.stages())
1072
+
1073
+ def order(self, mode, rng=None, first=None):
1074
+ o = self._far_first(self.inst["spot_of"], self.inst["supply_side"], *self.inst["table_xy"])
1075
+ if mode == "near_first":
1076
+ o = o[::-1]
1077
+ elif mode == "random":
1078
+ o = [o[j] for j in rng.permutation(4)]
1079
+ if first is not None:
1080
+ o = [first] + [c for c in o if c != first]
1081
+ return [COLOURS.index(c) for c in o]
1082
+
1083
+ def execute(self, inst, params):
1084
+ rng = np.random.default_rng(params.get("noise_seed", 0))
1085
+ order = self.order(params.get("order", "far_first"), rng, params.get("first"))
1086
+ gap = params.get("gap") # None: random in NAIVE_GAP per placement
1087
+ bias = np.array([float(params.get("bias_x", 0.0)), 0.0])
1088
+ rand = float(params.get("rand", 0.0))
1089
+ for i in order:
1090
+ g = float(rng.uniform(*NAIVE_GAP)) if gap is None else float(gap)
1091
+ e = bias + (rng.uniform(-rand, rand, 2) if rand else 0.0)
1092
+ self.place(i, g, err=e, z_carry=params.get("z_carry", Z_CARRY), v=params.get("v", 0.2))
1093
+ if params.get("repair") == "each": # looks at all bottles after every step and stands fallen ones up
1094
+ for _ in range(2):
1095
+ bad = [j for j in range(4) if self.mon["ever"][j] and not self.on_spot(j)]
1096
+ for j in self.repair_order(bad):
1097
+ if not self.on_spot(j):
1098
+ self.fix(j)
1099
+ if params.get("check"):
1100
+ self.check_and_repair()
1101
+ self._lift_to(Z_CARRY)
1102
+ self.sk.hold(10)
1103
+
1104
+ # naive = Sonnet-like habits (lh_nudge_row / lh_bystander pilots): careful, far spots first, carries high, vertical
1105
+ # descent, releases 1-4 cm above the surface, places ~1-2 cm too far forward +- 0.6 cm, no special plan for the
1106
+ # table, does not look back at the bottles it has already put down
1107
+ def default_params(self, inst):
1108
+ return dict(order="far_first", gap=None, bias_x=float(inst["naive_bias_x"]), rand=NAIVE_RAND,
1109
+ noise_seed=int(inst["seed"]) * 13, repair=None, check=False)
1110
+
1111
+ def oracle_params(self, inst):
1112
+ """knows the short leg: puts the heavy bottle on its corner first (the table rocks while nothing stands on it),
1113
+ sets the others down gently, checks at the end"""
1114
+ return dict(order="far_first", first=inst["heavy"], gap=CAREFUL_GAP, bias_x=0.0, rand=0.0, repair="each",
1115
+ check=True)
1116
+
1117
+ def adapt_params(self, inst, history):
1118
+ """attempt >= 2: the bottle whose placement rocked the table (from the event of the failed attempt) first; the
1119
+ same imprecise habits otherwise; stands fallen bottles up and checks at the end"""
1120
+ first = None
1121
+ for h in history:
1122
+ for e in h["outcome"].get("events", []):
1123
+ if e.get("event") == "table_rocked" and e.get("released"):
1124
+ first = e["released"]
1125
+ break
1126
+ if first:
1127
+ break
1128
+ return dict(self.default_params(inst), first=first, repair="each", check=True)
1129
+
1130
+ def blind_params(self, inst, attempt, rng):
1131
+ """the naive behaviour with a random order and random variation, no history, no look back"""
1132
+ return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)),
1133
+ z_carry=float(rng.uniform(0.40, 0.45)), v=float(rng.uniform(0.12, 0.25)),
1134
+ bias_x=float(rng.uniform(*NAIVE_BIAS)))
1135
+
1136
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
1137
+ """oracle / naive: one attempt. adaptive: attempt 1 = naive + stands fallen bottles up after every step and checks
1138
+ at the end; attempts >= 2: the rocking bottle first. blind: naive with a random order.
1139
+ Extra kinds (controls): naive_heavy_first (naive habits, 1-4 cm drops, but the heavy bottle first),
1140
+ naive_repair (= adaptive's first attempt), naive_near_first, switch (order change only, no repair),
1141
+ oracle_noise (+-5 mm)."""
1142
+ k = k or self.max_attempts
1143
+ rng = np.random.default_rng(seed)
1144
+ history = []
1145
+ single = ("oracle", "naive", "naive_heavy_first", "naive_repair", "oracle_noise", "naive_near_first")
1146
+ for a in range(k):
1147
+ self.reset_instance(inst)
1148
+ if kind == "oracle":
1149
+ params = self.oracle_params(inst)
1150
+ elif kind == "naive":
1151
+ params = self.default_params(inst)
1152
+ elif kind == "adaptive":
1153
+ params = (dict(self.default_params(inst), repair="each", check=True) if a == 0 else
1154
+ self.adapt_params(inst, history))
1155
+ elif kind == "blind":
1156
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
1157
+ elif kind == "switch":
1158
+ params = (self.default_params(inst) if a == 0 else
1159
+ dict(self.adapt_params(inst, history), repair=None, check=False))
1160
+ elif kind == "naive_heavy_first":
1161
+ params = dict(self.default_params(inst), first=inst["heavy"])
1162
+ elif kind == "naive_repair":
1163
+ params = dict(self.default_params(inst), repair="each", check=True)
1164
+ elif kind == "naive_near_first":
1165
+ params = dict(self.default_params(inst), order="near_first")
1166
+ elif kind == "oracle_noise":
1167
+ params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a)
1168
+ else:
1169
+ raise ValueError(kind)
1170
+ self.execute(inst, params)
1171
+ out = self.outcome(inst)
1172
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
1173
+ if on_attempt:
1174
+ on_attempt(a, params, out)
1175
+ if out["success"] or kind in single:
1176
+ break
1177
+ return history
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/agent_cost.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Project GPT-6 cost / latency of a protocol from a run directory.
2
+
3
+ Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made
4
+ with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES:
5
+ input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption)
6
+ cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) --
7
+ the first call of an attempt is counted as uncached (conservative)
8
+ output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500)
9
+ latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input
10
+ tokens and high/xhigh effort -- treat as an upper-range planning number)
11
+ The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls).
12
+
13
+ python scripts/agent_cost.py runs/agent/l5_slide_to_target/<run> --out-tokens 1500 --latency 20 --calls-scale 2
14
+ """
15
+ import argparse
16
+ import json
17
+ import os
18
+ import sys
19
+ from collections import defaultdict
20
+
21
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
+
23
+ from lffbench.agent.cost import PRICES, call_cost # noqa: E402
24
+
25
+
26
+ def main():
27
+ ap = argparse.ArgumentParser()
28
+ ap.add_argument("run_dir")
29
+ ap.add_argument("--model", default="gpt-6-astra")
30
+ ap.add_argument("--out-tokens", type=float, default=1500)
31
+ ap.add_argument("--latency", type=float, default=20.0)
32
+ ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)")
33
+ a = ap.parse_args()
34
+ ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))]
35
+ calls = [e for e in ev if e["type"] == "llm_call"]
36
+ runs = {e["seed"] for e in ev if e["type"] == "run_start"}
37
+ real = [c for c in calls if c.get("usage")]
38
+ if real and not any("dry_run_request" in c for c in calls):
39
+ cost = sum(call_cost(c["usage"], a.model) or 0 for c in real)
40
+ lat = [c["latency_s"] for c in real]
41
+ u = defaultdict(int)
42
+ for c in real:
43
+ for kk, v in c["usage"].items():
44
+ u[kk] += v
45
+ out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1),
46
+ usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
47
+ latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1))
48
+ else:
49
+ prev = {}
50
+ tot_in = tot_cached = 0
51
+ cost1 = 0.0 # priced per call (the long-context surcharge applies per request)
52
+ for c in calls:
53
+ d = c.get("dry_run_request")
54
+ if not d:
55
+ continue
56
+ key = (c["seed"], c["attempt"])
57
+ tin = d["est_input_tokens"]
58
+ cached = min(prev.get(key, 0), tin)
59
+ prev[key] = tin
60
+ tot_in += tin
61
+ tot_cached += cached
62
+ cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model)
63
+ n = len(calls) * a.calls_scale
64
+ scale = a.calls_scale
65
+ usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens)
66
+ cost = cost1 * scale
67
+ out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1),
68
+ input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1),
69
+ usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
70
+ api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model),
71
+ assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency,
72
+ calls_scale=a.calls_scale, image_tokens_512px=256))
73
+ print(json.dumps(out, indent=1, default=str))
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/check_breakfast_geometry.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """V2 physical height/orientation controls. Initialization interventions are diagnostics only."""
2
+ import json
3
+ from pathlib import Path
4
+ from PIL import Image
5
+ from lffbench import envs
6
+ from lffbench.tasks.lh_breakfast_service import BreakfastService
7
+
8
+ def main():
9
+ out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/geometry_v2/geometry_controls'
10
+ out.mkdir(parents=True,exist_ok=True);rows=[];t=BreakfastService()
11
+ for seed in range(1000,1003):
12
+ inst=t.sample_instance(seed);t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
13
+ # Move bread clear only at diagnostic initialization, so the obstacle is unambiguous.
14
+ envs.set_obj_pose(t.env,'bread_1',[-.09,-.32,.94]);t.env.sim.forward()
15
+ def state(stage):
16
+ r=dict(seed=seed,stage=stage,lid_deg=t.lid_deg(),butter_height_cm=100*t.butter_height(),
17
+ butter_lid_contact=bool(t.butter_lid_contact()),butter_fits=t.butter_in_box(),
18
+ applied_torque=float(t.env.sim.data.qfrc_applied[t.dof]))
19
+ assert r['applied_torque']==0.,r
20
+ rows.append(r);print(json.dumps(r),flush=True)
21
+ Image.fromarray(envs.render(t.env,res=512)).save(out/f'{seed}_{stage}.png')
22
+ (out/'progress.json').write_text(json.dumps(rows,indent=2))
23
+ return r
24
+ # Two empty-box closes prove that the removed closure-count mechanism does not reappear.
25
+ for cycle in range(2):
26
+ # Let the freely swinging open lid settle before targeting its knob again.
27
+ t.open_lid();t.sk.hold(100);t.close_lid(False);t.sk.hold(80)
28
+ r=state('empty_close_'+str(cycle+1));assert r['lid_deg']<4
29
+ t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100)
30
+ r=state('upright_blocked')
31
+ assert r['lid_deg']>10 and r['butter_lid_contact'] and r['butter_height_cm']>7 and not r['butter_fits'],r
32
+ # Remove precisely that obstacle, leaving all geometry, forces and joint limits unchanged.
33
+ t.open_lid();assert t.pick_place('butter_1',inst['butter_xy'],t.butter_height()/2+.003)
34
+ t.close_lid(False);t.sk.hold(80);r=state('obstacle_removed');assert r['lid_deg']<4
35
+ assert t.lay_butter_flat();r=state('laid_flat');assert r['butter_height_cm']<2.9
36
+ t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100)
37
+ r=state('flat_inside_closed');assert r['lid_deg']<4 and r['butter_fits'] and not r['butter_lid_contact'],r
38
+ (out/'result.json').write_text(json.dumps(dict(passed=True,rows=rows),indent=2))
39
+ t.env.close()
40
+
41
+ if __name__=='__main__':main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/headroom_parts_cart.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Incremental physical headroom evaluation of the composite prototype."""
2
+ import argparse,hashlib,json,time
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from lffbench.tasks.lh_parts_cart import PartsCart
6
+
7
+ def clean(x):
8
+ if isinstance(x,np.ndarray):return x.tolist()
9
+ if isinstance(x,np.generic):return x.item()
10
+ raise TypeError(type(x).__name__)
11
+ p=argparse.ArgumentParser();p.add_argument('--kind',choices=['oracle','naive','adaptive','blind'],required=True);p.add_argument('--n',type=int,default=20);p.add_argument('--k',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args()
12
+ out=Path(a.out);out.parent.mkdir(parents=True,exist_ok=True);x=PartsCart();rows=[];start=time.time()
13
+ source=Path(__file__).parents[1]/'lffbench/tasks/lh_parts_cart.py';code_hash=hashlib.sha256(source.read_bytes()).hexdigest()
14
+ for seed in range(1000,1000+a.n):
15
+ i=x.sample_instance(seed);h=x.run_scripted(a.kind,i,k=a.k,seed=seed)
16
+ rows.append(dict(seed=seed,history=h));succ=sum(any(z['outcome']['success'] for z in row['history']) for row in rows)
17
+ out.write_text(json.dumps(dict(kind=a.kind,n_planned=a.n,n_complete=len(rows),k=a.k,successes=succ,rows=rows,seconds=time.time()-start,task_sha256=code_hash,status='complete' if len(rows)==a.n else 'running',note='scripted privileged-state headroom; fixed geometry, randomized inertia only'),indent=2,default=clean))
18
+ print(seed,a.kind,[z['outcome']['success'] for z in h], 'successes',succ,flush=True)
19
+ x.env.close()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/lerobot_export.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
2
+
3
+ Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
4
+ can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
5
+
6
+ python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
7
+ --paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
8
+ python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
9
+ python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
10
+
11
+ Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
12
+ mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
13
+
14
+ LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
15
+ observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
16
+ observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
17
+ observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
18
+ observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
19
+ observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
20
+ action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
21
+ gripper (-1 open, +1 close)
22
+ annotation.attempt_index attempt (1-based) the frame belongs to
23
+ annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
24
+ annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
25
+ annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
26
+ annotation.task_event number of task-monitor events (error / progress events) registered at this step
27
+ Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
28
+ runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
29
+ per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import time
38
+
39
+ import numpy as np
40
+
41
+ FPS = 20
42
+ RES = 256
43
+ BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
44
+ "cc_smoke", "cc_opus_smoke"]
45
+ BATCH_NOTES = {
46
+ "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
47
+ "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
48
+ "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
49
+ "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
50
+ "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
51
+ "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
52
+ "with-history continuation of failed runs is incomplete",
53
+ "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
54
+ "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
55
+ "cc_opus_smoke": "smoke test: single attempt",
56
+ }
57
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
58
+ CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
59
+ "L2": "disturbed state to restore (incl. damage the agent causes)",
60
+ "L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
61
+ "L4": "misjudged geometry (size, shape, fit, hidden structure)",
62
+ "L5": "misjudged physics (mass distribution, friction, dynamics)"}
63
+
64
+
65
+ def features():
66
+ vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
67
+ f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
68
+ i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
69
+ return {
70
+ "observation.images.image": vid(),
71
+ "observation.images.wrist_image": vid(),
72
+ "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
73
+ "finger_qpos_left", "finger_qpos_right"]),
74
+ "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
75
+ "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
76
+ "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
77
+ "observation.gripper_width": f32(1, ["width_m"]),
78
+ "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
79
+ "eef_delta_rot_aa_z", "gripper_close"]),
80
+ "annotation.attempt_index": i64(),
81
+ "annotation.command_index": i64(),
82
+ "annotation.phase": i64(),
83
+ "annotation.attempt_success": i64(),
84
+ "annotation.task_event": i64(),
85
+ }
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ paper metadata
89
+
90
+ def _clean_tex(s):
91
+ s = re.sub(r"%.*", "", s)
92
+ for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
93
+ (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
94
+ (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
95
+ (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
96
+ (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
97
+ s = re.sub(a, b, s)
98
+ s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
99
+ s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
100
+ for _ in range(3):
101
+ s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
102
+ s = re.sub(r"\$([^$]*)\$", r"\1", s)
103
+ s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
104
+ s = re.sub(r"\{([^{}]*)\}", r"\1", s)
105
+ s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
106
+ return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
107
+
108
+
109
+ def paper_tasks(paper_dir):
110
+ """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
111
+ paper's task table and task appendix (empty if the paper sources are not there)."""
112
+ out = {}
113
+ if not paper_dir:
114
+ return out
115
+ app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
116
+ tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
117
+ if os.path.exists(app):
118
+ txt = open(app).read()
119
+ parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
120
+ for i in range(1, len(parts) - 1, 2):
121
+ if parts[i] != "\\paragraph{":
122
+ continue
123
+ body = parts[i + 1]
124
+ m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
125
+ if not m:
126
+ continue
127
+ name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
128
+ desc = _clean_tex(body[m.end():])
129
+ out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
130
+ if os.path.exists(tab):
131
+ names = {v["name"].lower(): k for k, v in out.items()}
132
+ for line in open(tab):
133
+ cells = [c.strip() for c in line.split("&")]
134
+ if len(cells) != 6 or not cells[-1].endswith("\\\\"):
135
+ continue
136
+ nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
137
+ code = names.get(nm)
138
+ if not code:
139
+ continue
140
+ out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
141
+ repair_within_attempt=_clean_tex(cells[3]) == "yes",
142
+ oracle_first_attempt_pct=_clean_tex(cells[4]),
143
+ naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
144
+ return out
145
+
146
+
147
+ # ------------------------------------------------------------------------------------------------ collection
148
+
149
+ def manifest_status(runs_root, batch, run, cache={}):
150
+ if batch not in cache:
151
+ p = os.path.join(runs_root, batch, "manifest.json")
152
+ cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
153
+ m = cache[batch]
154
+ for r in m.get("runs", []):
155
+ if r.get("run") == run:
156
+ return r.get("status", "?"), r
157
+ for r in m.get("superseded", []):
158
+ if r.get("run") == run:
159
+ return "superseded_" + str(r.get("status", "?")), r
160
+ return "not_in_manifest", {}
161
+
162
+
163
+ def collect(raw_roots, runs_root, batches, task_order):
164
+ """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
165
+ eps, rejected, seen = [], [], set()
166
+ for root in raw_roots:
167
+ for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
168
+ rep = json.load(open(rj))
169
+ batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
170
+ if (batches and batch not in batches) or (batch, run) in seen:
171
+ continue
172
+ seen.add((batch, run))
173
+ ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
174
+ status, entry = manifest_status(runs_root, batch, run)
175
+ if not ok:
176
+ never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
177
+ rejected.append(dict(run=run, batch=batch, run_status=status,
178
+ reason="run never started (no contract, no robot command)" if never else
179
+ "replay does not reproduce the log (the log has gaps or the replay diverged)",
180
+ detail=rep.get("first_mismatches")))
181
+ continue
182
+ for ep in rep.get("episodes", []):
183
+ d = os.path.join(root, ep["dir"])
184
+ ann = json.load(open(os.path.join(d, "annotation.json")))
185
+ judged = [a for a in ann["attempts"] if a.get("success") is not None]
186
+ if not judged or ep["n_frames"] == 0:
187
+ rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
188
+ reason="no judged attempt" if not judged else "no frames"))
189
+ continue
190
+ ann["source"]["run_status"] = status
191
+ ann["source"]["manifest_id"] = entry.get("id")
192
+ ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
193
+ max_eef_dev_m=rep["max_eef_dev_m"])
194
+ key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
195
+ {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
196
+ ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
197
+ eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
198
+ eps.sort(key=lambda x: x["key"])
199
+ return eps, rejected
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------ writing
203
+
204
+ def frames_of(path):
205
+ import av
206
+ with av.open(path) as c:
207
+ for fr in c.decode(video=0):
208
+ yield fr.to_ndarray(format="rgb24")
209
+
210
+
211
+ def flat_row(i, ann, n, idx0):
212
+ s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
213
+ att = ann["attempts"]
214
+ a0 = att[0]
215
+ return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
216
+ batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
217
+ memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
218
+ episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
219
+ harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
220
+ effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
221
+ task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
222
+ category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
223
+ success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
224
+ feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
225
+ auto_ended=[a.get("auto_ended") for a in att],
226
+ corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
227
+ error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
228
+ run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
229
+ n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
230
+ first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
231
+
232
+
233
+ def cmd_plan(a):
234
+ task_order = {}
235
+ if a.task_set and os.path.exists(a.task_set):
236
+ for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
237
+ task_order[line.split(":")[0].strip()] = i
238
+ batches = [b for b in a.batches.split(",") if b] if a.batches else None
239
+ eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
240
+ if a.limit:
241
+ eps = eps[:a.limit]
242
+ paper = paper_tasks(a.paper)
243
+ idx0 = 0
244
+ for i, e in enumerate(eps):
245
+ ann = e["ann"]
246
+ tname = ann["task"]["name"]
247
+ if tname in paper:
248
+ ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
249
+ ann["episode_index"] = i
250
+ ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
251
+ e["index"], e["from"] = i, idx0
252
+ idx0 += e["n"]
253
+ del e["key"]
254
+ os.makedirs(a.work, exist_ok=True)
255
+ with open(os.path.join(a.work, "plan.json"), "w") as f:
256
+ json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
257
+ ensure_ascii=False)
258
+ print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
259
+
260
+
261
+ def shard_range(n_eps, i, k):
262
+ return (n_eps * i) // k, (n_eps * (i + 1)) // k
263
+
264
+
265
+ def cmd_shard(a):
266
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
267
+ t0 = time.time()
268
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
269
+ eps = plan["episodes"]
270
+ lo, hi = shard_range(len(eps), a.shard, a.nshards)
271
+ out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
272
+ if os.path.exists(os.path.join(out, "DONE")):
273
+ print(f"shard {a.shard}: done already", flush=True)
274
+ return
275
+ shutil.rmtree(out, ignore_errors=True)
276
+ ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
277
+ robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
278
+ vcodec=a.vcodec)
279
+ nfr = 0
280
+ for e in eps[lo:hi]:
281
+ d, ann, n = e["dir"], e["ann"], e["n"]
282
+ fr = np.load(os.path.join(d, "frames.npz"))
283
+ assert len(fr["action"]) == n, d
284
+ succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
285
+ evc = np.zeros(n, np.int64)
286
+ for ev in ann["task_events"]:
287
+ if 0 <= ev["frame"] < n:
288
+ evc[ev["frame"]] += 1
289
+ state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
290
+ instr = ann["task"]["instruction"]
291
+ k = 0
292
+ for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
293
+ if k >= n:
294
+ break
295
+ ds.add_frame({
296
+ "observation.images.image": img, "observation.images.wrist_image": wr,
297
+ "observation.state": state[k],
298
+ "observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
299
+ "observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
300
+ "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
301
+ "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
302
+ "action": fr["action"][k].astype(np.float32),
303
+ "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
304
+ "annotation.command_index": np.array([fr["command"][k]], np.int64),
305
+ "annotation.phase": np.array([fr["phase"][k]], np.int64),
306
+ "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
307
+ "annotation.task_event": np.array([evc[k]], np.int64),
308
+ "task": instr,
309
+ })
310
+ k += 1
311
+ if k != n:
312
+ raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
313
+ ds.save_episode()
314
+ nfr += n
315
+ ds.finalize()
316
+ shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
317
+ open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
318
+ print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
319
+
320
+
321
+ def cmd_merge(a):
322
+ from pathlib import Path
323
+ from lerobot.datasets.aggregate import aggregate_datasets
324
+ t0 = time.time()
325
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
326
+ eps = plan["episodes"]
327
+ roots, ids = [], []
328
+ for i in range(a.nshards):
329
+ lo, hi = shard_range(len(eps), i, a.nshards)
330
+ if hi <= lo:
331
+ continue
332
+ r = os.path.join(a.work, "shards", f"shard_{i:03d}")
333
+ if not os.path.exists(os.path.join(r, "DONE")):
334
+ raise SystemExit(f"shard {i} is not done")
335
+ roots.append(Path(r))
336
+ ids.append(f"{plan['repo_id']}-shard{i:03d}")
337
+ if os.path.exists(a.out):
338
+ raise SystemExit(f"{a.out} exists; refusing to overwrite")
339
+ aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
340
+ print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
341
+ write_sidecars(a, plan)
342
+ print(f"merge done in {time.time() - t0:.0f}s", flush=True)
343
+
344
+
345
+ def write_sidecars(a, plan):
346
+ eps, paper = plan["episodes"], plan["paper"]
347
+ lff = os.path.join(a.out, "lff")
348
+ for sub in ("annotations", "sim_state", "final", "code"):
349
+ os.makedirs(os.path.join(lff, sub), exist_ok=True)
350
+ rows, runs, tasks = [], {}, {}
351
+ for e in eps:
352
+ i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
353
+ name = f"episode_{i:06d}"
354
+ if os.path.exists(os.path.join(d, "sim_state.npy")):
355
+ shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
356
+ shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
357
+ for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
358
+ shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
359
+ with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
360
+ json.dump(ann, f, indent=1, ensure_ascii=False)
361
+ rows.append(flat_row(i, ann, n, e["from"]))
362
+ tname = ann["task"]["name"]
363
+ rk = (ann["source"]["batch"], ann["source"]["run"])
364
+ r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
365
+ run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
366
+ memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
367
+ memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
368
+ seed=ann["task"]["seed"], model=ann["agent"].get("model"),
369
+ harness=ann["agent"].get("harness"),
370
+ harness_version=ann["agent"].get("harness_version"),
371
+ codex_catalog=ann["agent"].get("codex_catalog"),
372
+ outcome_class=ann["run_outcome"].get("outcome_class"),
373
+ attempt_history=ann["run_outcome"].get("attempt_history"),
374
+ agent_final_report=ann["run_outcome"].get("agent_final_report"),
375
+ episodes=[]))
376
+ for x in ann["attempts"]:
377
+ r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
378
+ if tname not in tasks:
379
+ tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
380
+ if tname in paper:
381
+ tasks[tname]["paper"] = paper[tname]
382
+ tasks[tname]["instances"] = {}
383
+ tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
384
+ # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
385
+ by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
386
+ for r in runs.values():
387
+ if r.get("memory_free_chain_of"):
388
+ r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
389
+ for (b, rn), r in runs.items():
390
+ r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
391
+ if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
392
+ key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
393
+ with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
394
+ for row in rows:
395
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
396
+ with open(os.path.join(lff, "runs.jsonl"), "w") as f:
397
+ for r in runs.values():
398
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
399
+ with open(os.path.join(lff, "tasks.json"), "w") as f:
400
+ json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
401
+ with open(os.path.join(lff, "batches.json"), "w") as f:
402
+ json.dump(BATCH_NOTES, f, indent=1)
403
+ with open(os.path.join(lff, "rejected.json"), "w") as f:
404
+ json.dump(plan["rejected"], f, indent=1)
405
+ here = os.path.dirname(os.path.abspath(__file__))
406
+ for s in ("lerobot_replay.py", "lerobot_export.py"):
407
+ shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
408
+
409
+
410
+ def main():
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("step", choices=["plan", "shard", "merge"])
413
+ ap.add_argument("--work", required=True)
414
+ ap.add_argument("--raw", default="")
415
+ ap.add_argument("--runs-root", default="")
416
+ ap.add_argument("--out", default="")
417
+ ap.add_argument("--paper", default="")
418
+ ap.add_argument("--task-set", default="")
419
+ ap.add_argument("--repo-id", default="lffbench/agent-replays")
420
+ ap.add_argument("--batches", default="")
421
+ ap.add_argument("--limit", type=int, default=0)
422
+ ap.add_argument("--shard", type=int, default=0)
423
+ ap.add_argument("--nshards", type=int, default=1)
424
+ ap.add_argument("--threads", type=int, default=2)
425
+ ap.add_argument("--vcodec", default="libsvtav1")
426
+ a = ap.parse_args()
427
+ {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/make_dossier.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the record of an earlier failed attempt for the full5 history arms (docs/14 §6).
2
+
3
+ python scripts/make_dossier.py <run log dir> <out dir> [--attempt 1] [--allow-success]
4
+
5
+ The record contains only what the agent of that attempt saw: the starting images, every robot command with the
6
+ robot's reply (as logged by robot_server), the images those commands produced, the agent's closing remark and the
7
+ F1 verdict ("failed"). No outcome codes, measurements or hidden variables. The same builder is used for the own-history
8
+ arm (record of a failed independent run on the same instance) and the mismatched arm (record of a failed run on the
9
+ twin instance: same layout, different hidden variable), so the two dossiers differ only in content.
10
+ """
11
+ import argparse
12
+ import json
13
+ import os
14
+ import shutil
15
+
16
+ DROP = ("state_file", "attempt_ended", "camera_file")
17
+
18
+
19
+ def shell_args(args):
20
+ out = []
21
+ for k, v in args.items():
22
+ v = json.dumps(v) if not isinstance(v, str) else v
23
+ out.append(f'{k}="{v}"' if (" " in v or not v) else f"{k}={v}")
24
+ return " ".join(out)
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("log")
30
+ ap.add_argument("out")
31
+ ap.add_argument("--attempt", type=int, default=1)
32
+ ap.add_argument("--allow-success", action="store_true")
33
+ ap.add_argument("--result-extra", default="",
34
+ help="layer-3 ladder (docs/20): text appended to the verdict in the Result section (paragraphs "
35
+ "separated by blank lines; the first one continues the verdict line). Empty = F1 record, "
36
+ "byte-identical to the record built without this option.")
37
+ a = ap.parse_args()
38
+ evs = [json.loads(line) for line in open(os.path.join(a.log, "events.jsonl")) if line.strip()]
39
+ start = next(e for e in evs if e["ev"] == "session_start")
40
+ if start.get("style", "la") not in ("la", None) and "style" in start:
41
+ raise SystemExit("only la-style runs are supported")
42
+ calls = [e for e in evs if e["ev"] == "call" and e.get("attempt") == a.attempt]
43
+ done = [e for e in evs if e["ev"] == "done" and e.get("attempt") == a.attempt]
44
+ if not done:
45
+ raise SystemExit(f"attempt {a.attempt} has no done event (run unfinished?)")
46
+ done = done[0]
47
+ if done["success"] and not a.allow_success:
48
+ raise SystemExit(f"attempt {a.attempt} succeeded; nothing to learn from (use --allow-success to force)")
49
+ imgs = os.path.join(a.log, "images")
50
+ # commands as that agent issued them: `./robot <cmd>` in a CLI workspace, the `robot` tool's argument otherwise
51
+ try:
52
+ iface = json.load(open(os.path.join(a.log, "agent_iface.json"))).get("agent_iface", "cli")
53
+ except OSError:
54
+ iface = "cli"
55
+ pre = "./robot " if iface == "cli" else ""
56
+ os.makedirs(os.path.join(a.out, "obs"), exist_ok=False)
57
+
58
+ def copy(rel):
59
+ base = os.path.basename(rel)
60
+ src = os.path.join(imgs, f"a{a.attempt}_{base}")
61
+ if not os.path.exists(src):
62
+ return None
63
+ shutil.copy(src, os.path.join(a.out, "obs", base))
64
+ return f"obs/{base}"
65
+
66
+ # starting images: the first images the agent saw (status at step 0)
67
+ first = sorted(f for f in os.listdir(imgs) if f.startswith(f"a{a.attempt}_") and "s000_" in f)
68
+ start_imgs = [copy(f.split("_", 1)[1]) for f in first]
69
+ lines = ["# Record of the earlier attempt", "",
70
+ "Starting scene: " + ", ".join(p for p in start_imgs if p), "",
71
+ "## Robot commands and replies", ""]
72
+ rec = []
73
+ for i, e in enumerate(calls, 1):
74
+ rep = {k: v for k, v in (e.get("report") or {}).items() if k not in DROP}
75
+ if "images" in rep:
76
+ rep["images"] = [p2 for p2 in (copy(p) for p in rep["images"]) if p2]
77
+ cmd = f"{pre}{e['cmd']} {shell_args(e.get('args') or {})}".strip()
78
+ lines += [f"{i}. `{cmd}`", " reply: `" + json.dumps(rep) + "`", ""]
79
+ rec.append(dict(n=i, command=cmd, reply=rep))
80
+ lines += [f"{len(calls) + 1}. `{pre}finish reason=\"{done.get('reason', '')}\"`", "",
81
+ "## Closing remark of that attempt", "", str(done.get("reason", "")), "",
82
+ "## Result", ""]
83
+ verdict = "The environment judged that attempt: " + ("succeeded." if done["success"] else "failed.")
84
+ extra = [x.strip() for x in a.result_extra.split("\n\n") if x.strip()]
85
+ if extra:
86
+ verdict += " " + extra[0]
87
+ lines += [verdict, ""]
88
+ for x in extra[1:]:
89
+ lines += [x, ""]
90
+ with open(os.path.join(a.out, "README.md"), "w") as f:
91
+ f.write("\n".join(lines))
92
+ with open(os.path.join(a.out, "record.jsonl"), "w") as f:
93
+ for r in rec:
94
+ f.write(json.dumps(r) + "\n")
95
+ with open(os.path.join(os.path.dirname(os.path.abspath(a.out)), os.path.basename(a.out) + ".source.json"), "w") as f:
96
+ json.dump(dict(log=os.path.abspath(a.log), attempt=a.attempt, task=start.get("task"), seed=start.get("seed"),
97
+ arm=start.get("arm", "none"), n_commands=len(calls), success=done["success"],
98
+ result_extra=a.result_extra), f)
99
+ print(json.dumps(dict(out=a.out, n_commands=len(calls), n_images=len(os.listdir(os.path.join(a.out, "obs"))))))
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/mismatch_plan.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mismatched-history control for layer 2 (user 2026-10-27: "错配历史的做一下"; design docs/14 §6 Do / Dm, current protocol).
2
+
3
+ Instances: the 9 hidden-variable tasks that have a twin (l7_key_turn has none), every Claude main-table instance
4
+ (Sonnet 5.5: cc_main1 / cc_sonnet_s2 / cc_sonnet_s3; Opus 5.5: cc_opus1 / cc_opus_s2 / cc_opus_s3) whose attempt 1 failed.
5
+ Arms, all fresh single-attempt agents (= the memory-free retries of the main table) with the same model and CLI:
6
+ tw_<m> twin instance (--arm twin: same layout, the hidden variable takes another value); its failed run is the
7
+ mismatched record. If the twin attempt succeeds there is no record: one more twin run (tw2_<m>), then give up.
8
+ do_<m> own record: history/ = attempt 1 of the instance's main-table history run (scripts/make_dossier.py)
9
+ dm_<m> mismatched record: history/ = the failed twin run. README byte-identical to do_<m>; only history/ differs.
10
+
11
+ python3 scripts/mismatch_plan.py own build own records + write <OUT>/<m>/own.json and tasks_<m>.txt
12
+ python3 scripts/mismatch_plan.py twin <m> build twin records from tw_<m> (+ tw2_<m>) -> <OUT>/<m>/twin.json;
13
+ prints the instances still without a failed twin run
14
+ python3 scripts/mismatch_plan.py report per instance: main-table attempt 2 with history (H2) and first
15
+ memory-free retry (N2), Do, Dm, twin; totals and paired counts
16
+ -> <OUT>/report.json + markdown on stdout
17
+ """
18
+ import json
19
+ import os
20
+ import subprocess
21
+ import sys
22
+
23
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24
+ API = os.path.join(ROOT, "runs", "api")
25
+ OUT = os.path.join(API, "mismatch_20261027")
26
+ TWIN_TASKS = ["l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool",
27
+ "l4_fit_container", "l2_turntable_restore", "l3_card_shelf", "l5_loaded_beam"]
28
+ MAIN = {"opus": ["cc_opus1", "cc_opus_s2", "cc_opus_s3"], "sonnet": ["cc_main1", "cc_sonnet_s2", "cc_sonnet_s3"]}
29
+
30
+
31
+ def runs(batch):
32
+ return json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
33
+
34
+
35
+ def attempt1(log):
36
+ for line in open(os.path.join(log, "events.jsonl")):
37
+ e = json.loads(line)
38
+ if e.get("ev") == "done" and e.get("attempt") == 1:
39
+ return e
40
+ return None
41
+
42
+
43
+ def dossier(log, out):
44
+ if not os.path.isdir(out):
45
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, out], check=True,
46
+ capture_output=True)
47
+ return out
48
+
49
+
50
+ def cmd_own():
51
+ for m, batches in MAIN.items():
52
+ own, tasks = {}, []
53
+ for b in batches:
54
+ for r in runs(b):
55
+ if r["cond"] != "harness" or r["task"] not in TWIN_TASKS or r["status"] != "done":
56
+ continue
57
+ d = attempt1(r["log"])
58
+ if d is None or d["success"]:
59
+ continue
60
+ key = f"{r['task']}:{r['seed']}"
61
+ own[key] = dossier(r["log"], os.path.join(OUT, m, "own", f"{r['task']}_s{r['seed']}"))
62
+ tasks.append(key)
63
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
64
+ json.dump(own, open(os.path.join(OUT, m, "own.json"), "w"), indent=1)
65
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(tasks) + "\n")
66
+ print(m, len(tasks))
67
+
68
+
69
+ def cmd_twin(m):
70
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
71
+ twin = {}
72
+ for b in (f"tw_{m}", f"tw2_{m}"):
73
+ if not os.path.exists(os.path.join(API, b, "manifest.json")):
74
+ continue
75
+ for r in runs(b):
76
+ key = f"{r['task']}:{r['seed']}"
77
+ if key in twin or r["status"] != "done":
78
+ continue
79
+ d = attempt1(r["log"])
80
+ if d is not None and not d["success"]:
81
+ twin[key] = dossier(r["log"], os.path.join(OUT, m, "twin", f"{r['task']}_s{r['seed']}"))
82
+ json.dump(twin, open(os.path.join(OUT, m, "twin.json"), "w"), indent=1)
83
+ print(json.dumps(dict(model=m, with_record=len(twin), missing=[k for k in want if k not in twin])))
84
+
85
+
86
+ # twin oracle also solves the original instance (docs/14 §6.4, 10-12 validation): mismatch is weak there
87
+ WEAK = {"l3_wall_flush", "l3_under_table_tool"}
88
+
89
+
90
+ def single(batch):
91
+ """task:seed -> True / False (attempt 1 of the batch's done run), None if not run or not finished."""
92
+ out = {}
93
+ if not os.path.exists(os.path.join(API, batch, "manifest.json")):
94
+ return out
95
+ for r in runs(batch):
96
+ if r["status"] == "done":
97
+ d = attempt1(r["log"])
98
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
99
+ return out
100
+
101
+
102
+ def main_rows(batches):
103
+ rows = {}
104
+ for b in batches:
105
+ tmp = os.path.join(OUT, f".oc_{b}.json")
106
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "outcomes.py"), "--batch", b, "--json", tmp],
107
+ check=True, capture_output=True)
108
+ for r in json.load(open(tmp))["rows"]:
109
+ rows[f"{r['task']}:{r['seed']}"] = dict(batch=b, history=r["history"], memfree=r["memfree"])
110
+ os.remove(tmp)
111
+ return rows
112
+
113
+
114
+ def cmd_report():
115
+ rep, md = {}, []
116
+ for m, batches in MAIN.items():
117
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
118
+ main = main_rows(batches)
119
+ do, dm = single(f"do_{m}"), single(f"dm_{m}")
120
+ t1, t2 = single(f"tw_{m}"), single(f"tw2_{m}") # "twin" = F if some twin run failed (a record exists)
121
+ tw = {k: (False if False in (t1.get(k), t2.get(k)) else t1.get(k)) for k in set(t1) | set(t2)}
122
+ rows = []
123
+ for k in want:
124
+ h, mf = main[k]["history"] or "", main[k]["memfree"] or ""
125
+ rows.append(dict(inst=k, task=k.split(":")[0], weak=k.split(":")[0] in WEAK,
126
+ H2=(h[1] == "S") if len(h) > 1 else None, N2=(mf[1] == "S") if len(mf) > 1 and mf[1] in "SF" else None,
127
+ Do=do.get(k), Dm=dm.get(k), twin=tw.get(k)))
128
+ def rate(key, sub):
129
+ v = [r[key] for r in sub if r[key] is not None]
130
+ return f"{sum(v)}/{len(v)}" if v else "-"
131
+ both = [r for r in rows if r["Do"] is not None and r["Dm"] is not None]
132
+ pairs = dict(n=len(both), do_only=sum(r["Do"] and not r["Dm"] for r in both),
133
+ dm_only=sum(r["Dm"] and not r["Do"] for r in both), both=sum(r["Do"] and r["Dm"] for r in both))
134
+ rep[m] = dict(rows=rows, pairs=pairs)
135
+ md += [f"### {m}", "", "| instance | twin run | H2 (history, main) | N2 (memory-free, main) | Do (own record) | Dm (twin record) |",
136
+ "|---|---|---|---|---|---|"]
137
+ f = lambda v: "-" if v is None else ("S" if v else "F")
138
+ for r in rows:
139
+ md.append(f"| {r['inst']}{' (weak)' if r['weak'] else ''} | {f(r['twin'])} | {f(r['H2'])} | {f(r['N2'])} | {f(r['Do'])} | {f(r['Dm'])} |")
140
+ strong = [r for r in rows if not r["weak"]]
141
+ md += ["", f"all: H2 {rate('H2', rows)}, N2 {rate('N2', rows)}, Do {rate('Do', rows)}, Dm {rate('Dm', rows)}; "
142
+ f"strong mismatch only: Do {rate('Do', strong)}, Dm {rate('Dm', strong)}; "
143
+ f"paired Do/Dm n={pairs['n']}: Do only {pairs['do_only']}, Dm only {pairs['dm_only']}, both {pairs['both']}", ""]
144
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
145
+ print("\n".join(md))
146
+
147
+
148
+ if __name__ == "__main__":
149
+ {"own": lambda: cmd_own(), "twin": lambda: cmd_twin(sys.argv[2]), "report": lambda: cmd_report()}[sys.argv[1]]()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/vla_eval.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Evaluate a visuomotor policy on LFF-Bench (lffbench/vla.py).
3
+
4
+ # one process per shard; the policy server runs elsewhere (openpi serve_policy.py, or StarVLA's)
5
+ python scripts/vla_eval.py run --policy ws://127.0.0.1:18000 --set sets/main_v2_3inst.txt --k 3 --out results/vla/<run> \
6
+ --shard 0/8 --model-name pi05_lff_v1
7
+ python scripts/vla_eval.py report results/vla/<run>
8
+
9
+ Each session writes <out>/<task>_s<seed>/summary.json and events.jsonl; a session with a summary.json is skipped, so a
10
+ rerun resumes. --tasks takes task:seed[,seed] items, --set a file of them (the sets/ format).
11
+ """
12
+ import argparse
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import sys
17
+ import time
18
+ import traceback
19
+
20
+ import numpy as np
21
+
22
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
+ sys.path.insert(0, ROOT)
24
+
25
+ CAUSES = os.path.join(ROOT, "..", "paper", "fig_scripts", "data", "causes.json")
26
+
27
+
28
+ def parse_items(items):
29
+ out = []
30
+ for it in items:
31
+ name, _, seeds = it.strip().partition(":")
32
+ if not seeds:
33
+ raise SystemExit(f"{it!r}: expected task:seed[,seed]")
34
+ out += [(name, int(s)) for s in seeds.split(",")]
35
+ return out
36
+
37
+
38
+ def read_set(path):
39
+ return [line.strip() for line in open(path) if line.strip() and not line.startswith("#")]
40
+
41
+
42
+ def sha256(path):
43
+ with open(path, "rb") as f:
44
+ return hashlib.sha256(f.read()).hexdigest()
45
+
46
+
47
+ def causes():
48
+ try:
49
+ return json.load(open(CAUSES))["cause"]
50
+ except OSError:
51
+ return {}
52
+
53
+
54
+ class Video:
55
+ """Frames at the replan rate, agentview next to wrist, written at real time speed."""
56
+
57
+ def __init__(self, path, replan):
58
+ import imageio
59
+ self.w = imageio.get_writer(path, fps=max(1, round(20 / replan)), quality=7, macro_block_size=8)
60
+
61
+ def add(self, t, obs):
62
+ self.w.append_data(np.hstack([obs["observation/image"], obs["observation/wrist_image"]]))
63
+
64
+ def close(self):
65
+ self.w.close()
66
+
67
+
68
+ def make_policy(spec):
69
+ from lffbench import vla
70
+ if spec == "zero":
71
+ return vla.ZeroPolicy()
72
+ if spec.startswith("ws://"):
73
+ return vla.WebsocketPolicy(spec)
74
+ raise SystemExit(f"unknown --policy {spec!r}: use ws://host:port or zero")
75
+
76
+
77
+ def run_one(task_name, seed, a, policy, tasks):
78
+ from lffbench import vla
79
+ from lffbench.harnesses.contract import server_code_sha
80
+ d = os.path.join(a.out, f"{task_name}_s{seed}")
81
+ if os.path.exists(os.path.join(d, "summary.json")):
82
+ return "skip"
83
+ os.makedirs(d, exist_ok=True)
84
+ task = tasks[task_name](cam_res=a.res)
85
+ inst = task.sample_instance(seed)
86
+ code_sha, code_files = server_code_sha(task_name)
87
+ start = dict(ev="session_start", task=task_name, seed=seed, protocol=getattr(task, "protocol", "cross"),
88
+ level=task.level, category=task.category, cause=causes().get(task_name), instruction=vla.task_prompt(task, inst),
89
+ k=a.k, replan=a.replan, res=a.res, frame=a.frame, idle_s=a.idle_s, probe_every_s=a.probe_every_s,
90
+ max_steps=a.max_steps or vla.budget_steps(task), model_name=a.model_name, policy=str(a.policy),
91
+ policy_metadata=getattr(policy, "metadata", None), inst={k: v for k, v in inst.items() if not k.startswith("_")},
92
+ server_code_sha256=code_sha, server_code_files=code_files,
93
+ vla_sha256=sha256(os.path.join(ROOT, "lffbench", "vla.py")), time=time.time())
94
+ with open(os.path.join(d, "events.jsonl"), "a") as log:
95
+ def write(rec):
96
+ log.write(json.dumps(rec, default=str) + "\n")
97
+ log.flush()
98
+ write(start)
99
+ video = Video(os.path.join(d, "rollout.mp4"), a.replan) if a.video else None
100
+ try:
101
+ t0 = time.time()
102
+ attempts = vla.run_session(task, inst, policy, k=a.k, max_steps=a.max_steps, replan=a.replan, res=a.res,
103
+ frame=a.frame, idle_s=a.idle_s, probe_every_s=a.probe_every_s,
104
+ on_frame=video.add if video else None,
105
+ on_attempt=lambda r: write(dict(ev="done", **r)))
106
+ finally:
107
+ if video:
108
+ video.close()
109
+ succ = [r["success"] for r in attempts]
110
+ first = next((r["attempt"] for r in attempts if r["success"]), None)
111
+ first_any = next((r["attempt"] for r in attempts if r["success"] or r["first_success_step"] is not None), None)
112
+ summary = {key: start[key] for key in ("task", "seed", "protocol", "level", "category", "cause", "k", "replan", "frame",
113
+ "max_steps", "model_name", "policy_metadata", "server_code_sha256")}
114
+ summary.update(status="ok", n_attempts=len(attempts), success_by_attempt=succ, first_success=first,
115
+ attempt1_success=bool(succ[0]), success=first is not None, first_success_any=first_any,
116
+ ended_by=[r["end"] for r in attempts], failure=[r["failure"] for r in attempts],
117
+ n_steps=[r["n_steps"] for r in attempts], infer_s_mean=[r["infer_s_mean"] for r in attempts],
118
+ wall_s=round(time.time() - t0, 2))
119
+ tmp = os.path.join(d, "summary.json.tmp")
120
+ json.dump(summary, open(tmp, "w"), indent=1, default=str)
121
+ os.replace(tmp, os.path.join(d, "summary.json"))
122
+ return "ok" if first is not None else "fail"
123
+
124
+
125
+ def cmd_run(a):
126
+ from lffbench import tasks as task_pkg # noqa: F401 (registers the task modules)
127
+ import importlib
128
+ import pkgutil
129
+ from lffbench.task_base import TASKS
130
+ for m in pkgutil.iter_modules(task_pkg.__path__):
131
+ importlib.import_module(f"lffbench.tasks.{m.name}")
132
+ items = list(a.tasks or [])
133
+ if a.set:
134
+ items += read_set(a.set)
135
+ sessions = parse_items(items)
136
+ i, n = (int(x) for x in a.shard.split("/"))
137
+ sessions = sessions[i::n]
138
+ os.makedirs(a.out, exist_ok=True)
139
+ policy = make_policy(a.policy)
140
+ print(f"[vla_eval] shard {a.shard}: {len(sessions)} sessions, policy {a.policy}, metadata {getattr(policy, 'metadata', None)}", flush=True)
141
+ for task_name, seed in sessions:
142
+ try:
143
+ print(f"[vla_eval] {task_name} s{seed}: {run_one(task_name, seed, a, policy, TASKS)}", flush=True)
144
+ except Exception: # one broken session must not end the shard; a missing summary.json makes a rerun retry it
145
+ print(f"[vla_eval] {task_name} s{seed}: ERROR\n{traceback.format_exc()}", flush=True)
146
+
147
+
148
+ def wilson(s, n, z=1.96):
149
+ if not n:
150
+ return [None, None]
151
+ p = s / n
152
+ d = 1 + z * z / n
153
+ c = p + z * z / (2 * n)
154
+ m = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
155
+ return [round(float((c - m) / d), 4), round(float((c + m) / d), 4)]
156
+
157
+
158
+ def cmd_report(a):
159
+ rows = []
160
+ for name in sorted(os.listdir(a.dir)):
161
+ p = os.path.join(a.dir, name, "summary.json")
162
+ if os.path.exists(p):
163
+ rows.append(json.load(open(p)))
164
+ if not rows:
165
+ raise SystemExit(f"no finished sessions in {a.dir}")
166
+ k = max(r["k"] for r in rows)
167
+
168
+ def stats(group):
169
+ n = len(group)
170
+ at = [sum(1 for r in group if r["first_success"] is not None and r["first_success"] <= j) for j in range(1, k + 1)]
171
+ anyok = sum(1 for r in group if r["first_success_any"] is not None)
172
+ return dict(n=n, succ_at=[round(s / n, 4) for s in at], a1=at[0], ak=at[-1], ak_ci95=wilson(at[-1], n), any_ok=anyok,
173
+ any_rate=round(anyok / n, 4))
174
+
175
+ by_cause, by_task = {}, {}
176
+ for r in rows:
177
+ by_cause.setdefault(str(r.get("cause")), []).append(r)
178
+ by_task.setdefault(r["task"], []).append(r)
179
+ non_l1 = [r for r in rows if r.get("cause") != "L1"]
180
+ report = dict(all=stats(rows), excluding_L1=stats(non_l1) if non_l1 else None,
181
+ by_cause={c: stats(g) for c, g in sorted(by_cause.items())},
182
+ by_task={t: stats(g) for t, g in sorted(by_task.items())},
183
+ ended_by={e: sum(r["ended_by"].count(e) for r in rows) for e in ("budget", "idle", "policy_ended")},
184
+ infer_s_mean=round(float(np.mean([x for r in rows for x in r["infer_s_mean"] if x is not None] or [0.0])), 4),
185
+ model_names=sorted({str(r.get("model_name")) for r in rows}),
186
+ server_code_sha256=sorted({r["server_code_sha256"] for r in rows}))
187
+ json.dump(report, open(os.path.join(a.dir, "report.json"), "w"), indent=1)
188
+ print(f"{'':24s} {'n':>4s} {'A1':>6s} {f'A{k}':>6s} {'any':>6s}")
189
+ print(f"{'all':24s} {report['all']['n']:4d} {report['all']['succ_at'][0]:6.2f} {report['all']['succ_at'][-1]:6.2f} {report['all']['any_rate']:6.2f}")
190
+ for c, s in report["by_cause"].items():
191
+ print(f"{c:24s} {s['n']:4d} {s['succ_at'][0]:6.2f} {s['succ_at'][-1]:6.2f} {s['any_rate']:6.2f}")
192
+ for t, s in report["by_task"].items():
193
+ print(f"{t:24s} {s['n']:4d} {s['succ_at'][0]:6.2f} {s['succ_at'][-1]:6.2f} {s['any_rate']:6.2f}")
194
+ print("L1 tasks do not carry the agents' command-level offset for a direct-action policy; see lffbench/vla.py.")
195
+
196
+
197
+ def main():
198
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
199
+ sub = ap.add_subparsers(dest="cmd", required=True)
200
+ r = sub.add_parser("run")
201
+ r.add_argument("--policy", required=True, help="ws://host:port (openpi protocol) or zero")
202
+ r.add_argument("--tasks", nargs="*", help="task:seed[,seed] items")
203
+ r.add_argument("--set", help="file of task:seed[,seed] items, e.g. sets/main_v2_3inst.txt")
204
+ r.add_argument("--out", required=True)
205
+ r.add_argument("--k", type=int, default=3, help="attempts per session")
206
+ r.add_argument("--replan", type=int, default=5, help="actions executed from each chunk (openpi's LIBERO eval: 5)")
207
+ r.add_argument("--res", type=int, default=256, help="camera resolution (the dataset's: 256)")
208
+ r.add_argument("--frame", default="believed", choices=["believed", "true"], help="proprioception frame")
209
+ r.add_argument("--max-steps", type=int, default=None, help="control steps per attempt (default: the agents' budget)")
210
+ r.add_argument("--idle-s", type=float, default=5.0, help="end the attempt after this long without motion (0: off)")
211
+ r.add_argument("--probe-every-s", type=float, default=5.0, help="forked success check every this long (0: off)")
212
+ r.add_argument("--shard", default="0/1", help="i/n: run every n-th session starting at i")
213
+ r.add_argument("--model-name", default=None)
214
+ r.add_argument("--video", action="store_true")
215
+ r.set_defaults(fn=cmd_run)
216
+ p = sub.add_parser("report")
217
+ p.add_argument("dir")
218
+ p.set_defaults(fn=cmd_report)
219
+ a = ap.parse_args()
220
+ a.fn(a)
221
+
222
+
223
+ if __name__ == "__main__":
224
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/audit_state.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Host-only, read-only physical evidence for CS/IR review (opt-in).
2
+
3
+ Never call outcome(), forward(), step() or a task measurement here: those can
4
+ settle physics or consume event cursors. Samples are at control-step boundaries,
5
+ not every MuJoCo substep. No sample itself is an error or repair classification.
6
+ """
7
+ import json
8
+
9
+
10
+ def _json_value(value):
11
+ if hasattr(value, "tolist"):
12
+ return value.tolist()
13
+ raise TypeError(f"Unsupported audit value: {type(value).__name__}")
14
+
15
+
16
+ class AuditStateRecorder:
17
+ def __init__(self, path):
18
+ self.path = path
19
+ self.env = None
20
+ self.original_step = None
21
+ self.wrapped_step = None
22
+ self.sequence = 0
23
+
24
+ def write(self, record):
25
+ # A separate host-side file, never copied into the agent's sandbox.
26
+ with open(self.path, "a", encoding="utf-8") as stream:
27
+ stream.write(json.dumps(record, separators=(",", ":"), default=_json_value) + "\n")
28
+
29
+ def detach(self):
30
+ if self.env is not None and self.env.step is self.wrapped_step:
31
+ self.env.step = self.original_step
32
+ self.env = None
33
+
34
+ def attach(self, env, attempt, command_step):
35
+ self.detach()
36
+ self.env, self.attempt, self.command_step = env, attempt, command_step
37
+ self.original_step = env.step
38
+ original_step = self.original_step
39
+ model = env.sim.model
40
+ self.write(dict(kind="attempt_start", schema="lff-audit-state-1", attempt=attempt,
41
+ sampling="after_env_step", bodies=[model.body_id2name(i) for i in range(model.nbody)],
42
+ geoms=[model.geom_id2name(i) for i in range(model.ngeom)]))
43
+
44
+ def wrapped(action):
45
+ result = original_step(action)
46
+ if self.env is env and self.wrapped_step is wrapped:
47
+ self.sample("control_step")
48
+ return result
49
+
50
+ self.wrapped_step = wrapped
51
+ env.step = wrapped
52
+ self.sample("initial")
53
+
54
+ def sample(self, phase):
55
+ data = self.env.sim.data
56
+ self.sequence += 1
57
+ self.write(dict(kind="state", sequence=self.sequence, attempt=self.attempt,
58
+ command_step=self.command_step(), phase=phase, sim_time=float(data.time),
59
+ qpos=data.qpos.tolist(), qvel=data.qvel.tolist(),
60
+ body_xyz=data.body_xpos.tolist(), body_quat_wxyz=data.body_xquat.tolist(),
61
+ contacts=[[int(c.geom1), int(c.geom2), float(c.dist)]
62
+ for c in data.contact[:data.ncon]]))
63
+
64
+ def boundary(self, task, phase):
65
+ """Capture after skill callbacks too (some injections happen after env.step).
66
+
67
+ Copy existing event lists without calling monitor/outcome methods or
68
+ advancing their cursors. These are raw observations, not adjudications.
69
+ """
70
+ self.sample(phase)
71
+ streams = {}
72
+ for name, obj in (("task", task), ("skills", getattr(task, "sk", None)),
73
+ ("monitor", getattr(task, "mon", None))):
74
+ attrs = obj if isinstance(obj, dict) else getattr(obj, "__dict__", {})
75
+ for key in ("events", "turns", "strikes", "box_moves", "lifts", "grasp_tries"):
76
+ if isinstance(attrs.get(key), list):
77
+ streams[f"{name}.{key}"] = attrs[key]
78
+ self.write(dict(kind="event_snapshot", attempt=self.attempt,
79
+ command_step=self.command_step(), phase=phase, streams=streams))
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-4 intervention texts for lh_tidy_stack (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is
2
+ not in the controlled arms of full5.
3
+
4
+ Hidden variable: inst["soft_colour"] -- the empty soft carton among the four boxes (None in benign instances).
5
+ reveal says which box is soft and how much it carries; not where to put it.
6
+ fix the oracle's order (lh_tidy_stack.oracle_params: rigid boxes first, the soft box last, then the cup).
7
+ """
8
+ HIDDEN_KEYS = ("soft_colour",)
9
+
10
+
11
+ def reveal(inst):
12
+ return (f"The {inst['soft_colour']} box is an empty, soft carton. It carries one thing, but gives way as soon as a "
13
+ f"second thing rests above it, and everything above it slides off the pile.")
14
+
15
+
16
+ def fix(inst, params):
17
+ return (f"A way to succeed: stack the other three boxes first, put the {inst['soft_colour']} box on top of them last, "
18
+ f"and stand the cup on it. It then carries only the cup.")
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/embodied_evo.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """EmbodiedEvo's Codex launcher and skills/lessons workflow on LFF's MCP.
2
+
3
+ Controlled port: same-episode knowledge only, no Playground pretraining, recipes,
4
+ native simulator execution or reset. Programs generate/revise action plans in
5
+ shell; individual robot commands are executed through MCP. This is explicitly
6
+ not EmbodiedEvo's full native code-as-policy evaluation.
7
+ """
8
+ import copy
9
+ import hashlib
10
+ import importlib.util
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from . import contract as C, pins
18
+ from .base import HarnessRefused
19
+ from .codex import Codex, DISABLE, codex_bin
20
+ from .rpent import tree_sha256
21
+
22
+ DEFAULT_SOURCE = "/mnt/cpfs/workspace/env/embodied-evo/src"
23
+
24
+
25
+ def load_source(path, module_name):
26
+ if sys.version_info < (3, 11):
27
+ import tomli
28
+ sys.modules.setdefault("tomllib", tomli)
29
+ spec = importlib.util.spec_from_file_location(module_name, path)
30
+ mod = importlib.util.module_from_spec(spec)
31
+ spec.loader.exec_module(mod)
32
+ return mod
33
+
34
+
35
+ def workflow(source):
36
+ text = (Path(source) / "tasks/RoboDojo/Workspace/playground.md").read_text()
37
+ loop = text.split("Organize your work as an iterative loop:", 1)[1].split("# Environment and Primitives", 1)[0]
38
+ evolution = text.split("# Evolution: skills and lessons", 1)[1].split("# Playground rules", 1)[0]
39
+ evolution = evolution.replace("Read `skills/example.md` and `lessons/example.md` first.",
40
+ "Start with empty skills/ and lessons/; create them through shell when needed.")
41
+ return ("You are an embodied coding agent. Follow the EmbodiedEvo workflow below, adapted to the "
42
+ "benchmark's MCP interface. The benchmark instructions following this workflow are authoritative.\n\n"
43
+ "Organize your work as an iterative loop:" + loop + "\n# Skills and lessons\n" + evolution +
44
+ "\n# MCP adaptation\n"
45
+ "Use shell to write and run Python for visual analysis and incremental action-plan generation. "
46
+ "Keep reusable helpers and preconditions in skills/, failure evidence and corrections in lessons/, "
47
+ "and current plans in submission/. Execute each robot command with the robot MCP tool and inspect "
48
+ "its feedback before the next stage; Python in shell cannot contact the robot. Use view_images "
49
+ "for obs/ images. Do not assume scripts/env.py, native step(), get_observation(), reset(), or "
50
+ "Playground records exist. No preloaded recipes or skills are supplied. Preserve and revise your "
51
+ "skills and lessons across attempts of this episode only; the benchmark controls resets and "
52
+ "termination. Never replay earlier actions just because you rewrote a plan.\n\n")
53
+
54
+
55
+ class EmbodiedEvoCodex(Codex):
56
+ name = "embodied_evo_codex"
57
+
58
+ def __init__(self, *args, source=None, **kwargs):
59
+ self.source = source or os.environ.get("LFF_EMBODIED_EVO_SOURCE", DEFAULT_SOURCE)
60
+ self._source_info = None
61
+ self.prefix = workflow(self.source)
62
+ self.native_launch = load_source(Path(self.source) / "orchestrator/launch_agent.py", "lff_evo_launch")
63
+ self.native_recovery = load_source(Path(self.source) / "orchestrator/agent_recovery.py", "lff_evo_recovery")
64
+ super().__init__(*args, **kwargs)
65
+ if self.catalog != "generic":
66
+ raise HarnessRefused("EmbodiedEvo controlled variant requires generic catalog")
67
+
68
+ def source_info(self):
69
+ if self._source_info is None:
70
+ commit = subprocess.check_output(["git", "-C", self.source, "rev-parse", "HEAD"], text=True).strip()
71
+ self._source_info = dict(commit=commit, tree_sha256=tree_sha256(self.source),
72
+ workflow_sha256=hashlib.sha256(self.prefix.encode()).hexdigest())
73
+ return self._source_info
74
+
75
+ def version(self):
76
+ return dict(super().version(), framework=self.source_info())
77
+
78
+ def pin_key(self, ep):
79
+ v = self.version()
80
+ identity = C.sha256_json(v["framework"])[:12]
81
+ mode = "" if self.auth == "apikey" else "-chatgpt"
82
+ return pins.key(self.name + mode + "-generic-" + identity, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
83
+
84
+ def config_info(self):
85
+ return dict(super().config_info(), framework=self.source_info(), variant="mcp-skills-lessons",
86
+ history="same-thread", cross_episode_memory=False, native_code_execution=False)
87
+
88
+ def argv(self, ep, session_path, base_url, first_message, codex_home):
89
+ prompt = first_message if first_message.startswith(self.prefix) else self.prefix + first_message
90
+ args = self.native_launch.agent_argv("codex", prompt, model=ep.model, effort=ep.effort)
91
+ args[0] = codex_bin()
92
+ args[args.index("--sandbox") + 1] = "read-only"
93
+ # The benchmark fixes the middle layer; native orchestration provides the workflow and launch.
94
+ extra = ["--json", "--ignore-user-config", "--ignore-rules"]
95
+ for feature in DISABLE:
96
+ extra += ["--disable", feature]
97
+ for setting in self.config_args(ep, session_path, base_url, codex_home):
98
+ extra += ["-c", setting]
99
+ return args[:-1] + extra + [prompt]
100
+
101
+ def resume_argv(self, handle, message):
102
+ thread = self.thread_id(handle.spec.stdout_path)
103
+ if not thread:
104
+ raise HarnessRefused("EmbodiedEvo resume: missing current thread ID")
105
+ args = list(handle.spec.argv)
106
+ binary, args[0] = args[0], "codex"
107
+ i = args.index("--sandbox")
108
+ mode = args[i+1]
109
+ del args[i:i+2]
110
+ args[-1:-1] = ["-c", "sandbox_mode=" + json.dumps(mode)]
111
+ args = self.native_recovery.resume_argv(args, thread)
112
+ args[0], args[-1] = binary, message # benchmark-owned continuation; same native resume construction
113
+ return args
114
+
115
+ def preflight(self, spec, ep, record_dir=None):
116
+ proxy = copy.copy(spec)
117
+ proxy.first_message = self.prefix + spec.first_message
118
+ # super checks all middle-layer fields; this adapter's pin binds the source and workflow hash too.
119
+ out = super().preflight(proxy, ep, record_dir)
120
+ v = self.version()
121
+ anchor_name = "codex-generic" if self.auth == "apikey" else "codex-chatgpt-generic"
122
+ anchor_key = pins.key(anchor_name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
123
+ anchor = pins.load(anchor_key, self.pins_dir)
124
+ if anchor is None or anchor["fingerprint_sha256"] != out["fingerprint_sha256"]:
125
+ raise HarnessRefused("EmbodiedEvo middle layer does not match the pinned Codex baseline")
126
+ out.update(anchor_status="match", middle_fingerprint_sha256=out["fingerprint_sha256"],
127
+ framework_prefix_sha256=self.source_info()["workflow_sha256"],
128
+ framework_prefix_chars=len(self.prefix))
129
+ return out
130
+
131
+ def collect(self, handle):
132
+ traj = super().collect(handle)
133
+ # Preserve provenance alongside native CLI traces.
134
+ (Path(handle.ep.log_dir) / "framework.json").write_text(json.dumps(self.config_info(), indent=2))
135
+ return traj
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/api_player.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Drive one robot_server session with a model through its provider's official API (the unified harness).
2
+
3
+ Every provider gets exactly the same input: the sandbox README as its instructions and the same tools; only the
4
+ wire format differs (lffbench/agent/backends/). After every command the JSON report is returned as the tool output.
5
+ Nothing else is sent: no files, no memory, no paths outside the sandbox.
6
+
7
+ python scripts/api_player.py --session runs/<...>/session.json --provider anthropic --model claude-opus-5-5 --effort high --style la
8
+
9
+ Providers (key / endpoint from the environment, e.g. `set -a; source .env; set +a`):
10
+ openai OpenAI Responses API OPENAI_API_KEY [OPENAI_BASE_URL]
11
+ anthropic Anthropic Messages API ANTHROPIC_API_KEY
12
+ gemini Gemini API (google-genai) GEMINI_API_KEY
13
+ chat any OpenAI-compatible Chat Completions endpoint (vLLM / SGLang for open models, xAI, ...)
14
+ LFF_CHAT_BASE_URL, LFF_CHAT_API_KEY
15
+ `--effort` is the provider's reasoning knob: OpenAI reasoning.effort, Anthropic output_config.effort, Gemini
16
+ thinking_level, chat: reasoning_effort (omitted when "none").
17
+
18
+ --style la (LIBERO-Agent-style workspace, the paper's interface): the sandbox is the agent's episode workspace. Besides
19
+ `robot` the model gets `shell` (a command run in the workspace inside a jail: no network, robot server unreachable,
20
+ host data hidden, see /opt/lffjail/jail_inner.sh) and `view_images` (any image file in the workspace, including ones
21
+ it made itself). Tool calls per attempt are capped (agent_iface.json: max_tool_calls); at the cap the attempt is
22
+ finished for it.
23
+ Logs in the run's log dir: transcript.jsonl (every request / reply / tool call), final_report.md.
24
+ """
25
+ import argparse
26
+ import base64
27
+ import json
28
+ import os
29
+ import shlex
30
+ import subprocess
31
+ import sys
32
+ import time
33
+ import traceback
34
+ import urllib.request
35
+
36
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
37
+ sys.path.insert(0, ROOT)
38
+ if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"):
39
+ os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # the venv's own CA bundle lacks the proxy's issuer
40
+
41
+ from lffbench.agent.backends import make_backend # noqa: E402
42
+ from lffbench.agent.context import Conversation # noqa: E402
43
+
44
+ PROVIDERS = ("openai", "anthropic", "gemini", "chat")
45
+
46
+ TOOL = dict(
47
+ name="robot",
48
+ description=("Run one robot command. `command` is exactly what you would type after `./robot` in the "
49
+ "instructions (e.g. `observe`). Returns the command's JSON report."),
50
+ parameters=dict(type="object", properties=dict(command=dict(type="string", description="the robot command")),
51
+ required=["command"], additionalProperties=False),
52
+ )
53
+
54
+ VIEW_TOOL = dict(
55
+ name="view_images",
56
+ description=("Look at camera images the robot has written. `paths` are image paths exactly as printed by robot "
57
+ "commands (e.g. obs/a1_s003_wrist.jpg); any image of this episode can be viewed again. The images "
58
+ "are attached right after this call."),
59
+ parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"),
60
+ description="image paths to view")),
61
+ required=["paths"], additionalProperties=False),
62
+ )
63
+
64
+ TOOL_LA = dict(
65
+ name="robot",
66
+ description=("Run one robot command. `command` is exactly one of the robot commands in the instructions, e.g. "
67
+ "`status` or `move_eef z=1.0 gripper=open`. Returns the command's JSON report, including the paths "
68
+ "of the new observation files."),
69
+ parameters=TOOL["parameters"],
70
+ )
71
+
72
+ SHELL_TOOL = dict(
73
+ name="shell",
74
+ description=("Run a shell command (bash) in your workspace directory, e.g. `ls obs` or `python3 analyse.py`. "
75
+ "python3 has numpy, scipy, Pillow and OpenCV. No network; programs cannot control the robot. "
76
+ "Time limit 60 s per call. Returns the exit code and the combined stdout/stderr (long output is "
77
+ "truncated in the middle)."),
78
+ parameters=dict(type="object", properties=dict(command=dict(type="string", description="the bash command")),
79
+ required=["command"], additionalProperties=False),
80
+ )
81
+
82
+ VIEW_TOOL_LA = dict(
83
+ name="view_images",
84
+ description=("Look at image files in your workspace (.jpg / .jpeg / .png), e.g. obs/a1_s003_wrist.jpg or an image "
85
+ "you made yourself; paths are relative to the workspace. At most 8 per call. The images are attached "
86
+ "right after this call."),
87
+ parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"),
88
+ description="image paths to view")),
89
+ required=["paths"], additionalProperties=False),
90
+ )
91
+
92
+ PREAMBLE_LA = ("You control the robot described below and work in the workspace described below. Tools: `robot` runs "
93
+ "one robot command per call (the argument is exactly a command from the instructions, e.g. `status`); "
94
+ "`shell` runs a shell command in your workspace; `view_images` shows you image files from the "
95
+ "workspace. When a robot command tells you to stop or that the episode is over, stop calling tools and "
96
+ "reply with a short report: what you did (key commands and parameter values), what you observed, any "
97
+ "feedback you got, and how you changed your approach.\n\n")
98
+
99
+ PREAMBLE = ("You control the robot described below. You act only through the `robot` tool, one command per call. "
100
+ "When a command tells you to stop or that the episode is over, stop calling the tool and reply with a "
101
+ "short report: what you did (key commands and parameter values), what you observed, any feedback you "
102
+ "got, and how you changed your approach.\n\n")
103
+
104
+ JAIL = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "jail", "jail_inner.sh")
105
+ SHELL_TIMEOUT = 60
106
+ SHELL_MAX_CHARS = 12000
107
+
108
+
109
+ def run_shell(workspace, command):
110
+ """Run `command` in the jailed workspace; returns (exit code, output text, seconds)."""
111
+ t0 = time.time()
112
+ argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, workspace,
113
+ "timeout", "-k", "5", str(SHELL_TIMEOUT), "bash", "-c", command]
114
+ try:
115
+ r = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
116
+ timeout=SHELL_TIMEOUT + 30)
117
+ code, out = r.returncode, r.stdout.decode("utf-8", "replace")
118
+ except subprocess.TimeoutExpired as e:
119
+ code, out = 124, (e.stdout or b"").decode("utf-8", "replace")
120
+ if code == 124:
121
+ out += f"\n[killed: time limit of {SHELL_TIMEOUT} s]"
122
+ if len(out) > SHELL_MAX_CHARS:
123
+ h = SHELL_MAX_CHARS // 2
124
+ out = out[:h] + f"\n[... {len(out) - SHELL_MAX_CHARS} characters truncated ...]\n" + out[-h:]
125
+ return code, out, time.time() - t0
126
+
127
+
128
+ def workspace_image(workspace, rel):
129
+ """Resolve a model-given image path inside the workspace (no escaping via .. or symlinks); None if not allowed."""
130
+ if not isinstance(rel, str) or not rel or rel.startswith("/"):
131
+ return None
132
+ root = os.path.realpath(workspace)
133
+ full = os.path.realpath(os.path.join(root, rel))
134
+ if not full.startswith(root + os.sep) or not os.path.isfile(full):
135
+ return None
136
+ if os.path.splitext(full)[1].lower() not in (".jpg", ".jpeg", ".png") or os.path.getsize(full) > 8 * 2 ** 20:
137
+ return None
138
+ return full
139
+
140
+
141
+ class FileImage:
142
+ """The exact JPEG bytes the server wrote (same bytes a Claude Code player reads)."""
143
+
144
+ def __init__(self, path):
145
+ self.path = path
146
+ base = os.path.basename(path)
147
+ self.camera = "wrist" if "wrist" in base else ("agentview" if "agentview" in base else "camera")
148
+ self.label = base
149
+
150
+ def data_url(self, quality=None):
151
+ mime = "image/png" if self.path.lower().endswith(".png") else "image/jpeg"
152
+ with open(self.path, "rb") as f:
153
+ return f"data:{mime};base64," + base64.b64encode(f.read()).decode()
154
+
155
+
156
+ def parse_command(s):
157
+ s = s.strip()
158
+ s = s.removeprefix("./robot").strip() if s.startswith("./robot") else (s[len("robot "):] if s.startswith("robot ") else s)
159
+ toks = shlex.split(s.strip())
160
+ if not toks:
161
+ return "help", {}
162
+ cmd, args = toks[0], {}
163
+ for a in toks[1:]:
164
+ if "=" not in a:
165
+ return None, f"bad argument {a!r}: use key=value"
166
+ k, v = a.split("=", 1)
167
+ try:
168
+ args[k] = json.loads(v)
169
+ except ValueError:
170
+ args[k] = v
171
+ return cmd, args
172
+
173
+
174
+ def call_server(port, token, cmd, args):
175
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(),
176
+ headers={"Content-Type": "application/json", "X-Token": token})
177
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
178
+ with opener.open(req, timeout=900) as r:
179
+ return r.read().decode()
180
+
181
+
182
+ MAX_NO_TOOL = 3 # nudges in a row for replies without a tool call; the next such reply ends the run
183
+
184
+
185
+ def continue_nudge(port, token, stx=None):
186
+ """The user message sent when the model replies without a tool call before the episode is over. Native harnesses
187
+ send the same text when their CLI exits early (scripts/harness_run.py). stx: a status reply already fetched."""
188
+ try: # tell it where it is: models sometimes believe the episode ended after a failed attempt
189
+ if stx is None:
190
+ stx = json.loads(call_server(port, token, "status", {}))
191
+ where = (f" You are in attempt {stx.get('attempt')} of {stx.get('max_attempts')}; the episode is NOT over."
192
+ if stx.get("attempt") else "")
193
+ except Exception:
194
+ where = ""
195
+ return "Continue: issue the next robot command with the `robot` tool." + where
196
+
197
+
198
+ def build_backend(a, v2):
199
+ """The model backend for --provider; image pruning only where the provider allows editing earlier turns."""
200
+ if a.provider == "openai":
201
+ return make_backend("openai", model=a.model, reasoning_effort=a.effort, reasoning_summary="auto",
202
+ max_live_images=None if v2 else a.max_live_images, cache_breakpoints="none", max_retries=1)
203
+ if a.provider == "anthropic": # append-only history (thinking blocks are bound to it): never prune
204
+ return make_backend("anthropic", model=a.model, effort=a.effort, max_live_images=None)
205
+ if a.provider == "gemini":
206
+ return make_backend("gemini", model=a.model, thinking_level=a.effort,
207
+ max_live_images=None if v2 else a.max_live_images)
208
+ extra = None if a.effort in ("", "none", None) else dict(reasoning_effort=a.effort)
209
+ return make_backend("chat", model=a.model, max_tokens=a.max_output_tokens, temperature=None, extra_body=extra,
210
+ max_live_images=None if v2 else a.max_live_images)
211
+
212
+
213
+ def context_overflow(err):
214
+ """The request no longer fits: token limit (OpenAI / Anthropic / Gemini / Kimi wordings) or too many images."""
215
+ e = err.lower()
216
+ return (("context" in e and ("length" in e or "window" in e or "too long" in e)) or "prompt is too long" in e
217
+ or ("exceed" in e and "token" in e) or "too many images" in e or "maximum number of images" in e)
218
+
219
+
220
+ def live_images(conv):
221
+ return sum(1 for it in conv.items if it["kind"] == "user" and it.get("live") for p in it["parts"]
222
+ if p["type"] == "image")
223
+
224
+
225
+ def main(argv=None, default_provider=None, transcript_name="transcript.jsonl"):
226
+ ap = argparse.ArgumentParser()
227
+ ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh")
228
+ ap.add_argument("--provider", default=default_provider, choices=PROVIDERS, required=default_provider is None)
229
+ ap.add_argument("--model", default="gpt-6-astra" if default_provider == "openai" else None,
230
+ required=default_provider is None)
231
+ ap.add_argument("--effort", default="medium")
232
+ ap.add_argument("--max-turns", type=int, default=400)
233
+ ap.add_argument("--max-live-images", type=int, default=16)
234
+ ap.add_argument("--max-output-tokens", type=int, default=32768, help="chat provider only")
235
+ ap.add_argument("--api-retries", type=int, default=8,
236
+ help="retries of a failed API call before giving up (back-off 5 s doubling to 120 s: ~9 min)")
237
+ ap.add_argument("--max-request-images", type=int, default=500,
238
+ help="when the conversation holds more viewed images than this, switch to the context-full "
239
+ "policy (Claude through a gateway failed at 601 images, 2026-10-15)")
240
+ ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"],
241
+ help="v2: images are not attached automatically; the model views them on demand with "
242
+ "view_images, and no history is pruned (the agent manages its own context)")
243
+ a = ap.parse_args(argv)
244
+
245
+ sess = json.load(open(a.session))
246
+ sb, port = sess["sandbox"], sess["port"]
247
+ log_dir = os.path.dirname(os.path.abspath(a.session))
248
+ la = a.style == "la"
249
+ if la: # no robot CLI in a la workspace: the token is only in the log dir
250
+ iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
251
+ token, max_tool_calls = iface["token"], int(iface["max_tool_calls"])
252
+ else:
253
+ token = open(os.path.join(sb, "robot")).read().split('TOKEN = "', 1)[1].split('"', 1)[0]
254
+ readme = open(os.path.join(sb, "README.md")).read()
255
+ tlog = open(os.path.join(log_dir, transcript_name), "a")
256
+
257
+ def log(d):
258
+ d["t"] = time.time()
259
+ tlog.write(json.dumps(d, ensure_ascii=False) + "\n")
260
+ tlog.flush()
261
+
262
+ v2 = a.style in ("v2", "la") # la = v2 robot interface + workspace tools
263
+ tools = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] if la else ([TOOL, VIEW_TOOL] if v2 else [TOOL])
264
+ backend = build_backend(a, v2)
265
+ conv = Conversation((PREAMBLE_LA if la else PREAMBLE) + readme)
266
+ log(dict(ev="start", provider=a.provider, model=a.model, effort=a.effort, style=a.style, backend=backend.config(),
267
+ instructions=conv.system, tools=tools))
268
+
269
+ def images_part(paths, title):
270
+ parts = [dict(type="text", text=title)]
271
+ for p in paths:
272
+ parts.append(dict(type="image", image=FileImage(os.path.join(sb, p))))
273
+ return parts
274
+
275
+ st = json.loads(call_server(port, token, "status", {}))
276
+ if v2: # images stay files; the model decides what to look at
277
+ first = [dict(type="text", text=("Begin. Current status (robot command `status`):\n" if la else
278
+ "Begin. Current status (`./robot status`):\n") + json.dumps(st))]
279
+ else:
280
+ first = [dict(type="text", text="Begin. Current status (`./robot status`):\n" +
281
+ json.dumps({k: v for k, v in st.items() if k != "images"}))]
282
+ first += images_part(st.get("images", []), "Current camera images (agentview, wrist):")[1:]
283
+ conv.add_user(first, live=True)
284
+ log(dict(ev="user", text=first[0]["text"], images=st.get("images", [])))
285
+
286
+ finished, no_tool, report = False, 0, None
287
+ calls_in_attempt = 0 # la: tool calls (robot + shell + view_images) in the current attempt
288
+ usage_tot = dict(input_tokens=0, cached_tokens=0, cache_write_tokens=0, output_tokens=0, reasoning_tokens=0)
289
+ for turn in range(a.max_turns):
290
+ resp, err = None, None
291
+ if v2 and backend.max_live_images is None and live_images(conv) > a.max_request_images:
292
+ backend.max_live_images = 32 # same context-full policy as below, before the request limit is hit
293
+ log(dict(ev="context_overflow", reason="image count", n_images=live_images(conv), keep_images=32))
294
+ for r in range(a.api_retries + 1):
295
+ t0 = time.time()
296
+ try:
297
+ out = backend.act(conv, tools)
298
+ except Exception as e: # flaky endpoint: back off and retry the identical request
299
+ err = f"{type(e).__name__}: {str(e)[:300]}"
300
+ if v2 and context_overflow(err):
301
+ # the context is full (every provider): from now on keep only the newest viewed images
302
+ backend.max_live_images = 32 if backend.max_live_images is None else max(backend.max_live_images // 2, 4)
303
+ log(dict(ev="context_overflow", reason=err[:120], keep_images=backend.max_live_images))
304
+ log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0))
305
+ time.sleep(min(120, 5 * 2 ** r))
306
+ continue
307
+ if out.status == "refusal": # the provider declined: no fallback model (it would change the model under test)
308
+ resp, err = out, out.error
309
+ break
310
+ if out.status == "incomplete": # truncated / malformed turn: not appended, ask again
311
+ err = out.error
312
+ log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0, usage=out.usage))
313
+ continue
314
+ resp = out
315
+ break
316
+ if resp is None:
317
+ log(dict(ev="abort", reason="api failed", error=err))
318
+ print("ABORT api failed:", err, flush=True)
319
+ sys.exit(3)
320
+ for k in usage_tot:
321
+ usage_tot[k] += resp.usage.get(k, 0)
322
+ if resp.status == "refusal":
323
+ log(dict(ev="refusal", turn=turn, latency_s=resp.latency_s, usage=resp.usage, error=resp.error,
324
+ text=resp.text))
325
+ log(dict(ev="abort", reason="refusal", error=resp.error))
326
+ print("ABORT refusal:", resp.error, flush=True)
327
+ break
328
+ conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name)
329
+ log(dict(ev="assistant", turn=turn, latency_s=resp.latency_s, usage=resp.usage, text=resp.text,
330
+ reasoning_summary=resp.reasoning_summary,
331
+ reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned",
332
+ status=resp.status, error=resp.error,
333
+ tool_calls=[dict(id=c.id, name=c.name, arguments=c.arguments) for c in resp.tool_calls],
334
+ request_stats=resp.request_stats))
335
+ if finished:
336
+ report = resp.text
337
+ break
338
+ if not resp.tool_calls:
339
+ no_tool += 1
340
+ nudge = continue_nudge(port, token)
341
+ if no_tool > MAX_NO_TOOL:
342
+ log(dict(ev="abort", reason="no tool call 4 times"))
343
+ break
344
+ conv.add_user([dict(type="text", text=nudge)], live=False)
345
+ log(dict(ev="user", text=nudge))
346
+ continue
347
+ no_tool = 0
348
+ for c in resp.tool_calls:
349
+ if la and not finished:
350
+ calls_in_attempt += 1
351
+ if la and c.name == "shell":
352
+ code, out, dt = run_shell(sb, str(c.arguments.get("command", "")))
353
+ out_text = json.dumps(dict(exit_code=code, output=out))
354
+ conv.add_tool_output(c.id, c.name, out_text)
355
+ log(dict(ev="tool", turn=turn, command="shell: " + str(c.arguments.get("command", "")), output=out_text,
356
+ shell_s=round(dt, 2)))
357
+ continue
358
+ if la and c.name == "view_images":
359
+ paths = [str(x) for x in (c.arguments.get("paths") or [])][:8]
360
+ full = [(x, workspace_image(sb, x)) for x in paths]
361
+ ok_paths = [x for x, f in full if f]
362
+ out = dict(ok=bool(ok_paths), attached=ok_paths)
363
+ if len(ok_paths) < len(paths):
364
+ out["not_viewable"] = [x for x, f in full if not f]
365
+ conv.add_tool_output(c.id, c.name, json.dumps(out))
366
+ log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths))
367
+ if ok_paths:
368
+ parts = [dict(type="text", text="Requested images:")]
369
+ for x, f in full:
370
+ if f:
371
+ parts.append(dict(type="image", image=FileImage(f)))
372
+ conv.add_user(parts, live=True)
373
+ continue
374
+ if c.name == "view_images":
375
+ paths = [str(x) for x in (c.arguments.get("paths") or [])][:8]
376
+ ok_paths = [x for x in paths if x.startswith("obs/") and "/.." not in x and ".." not in x
377
+ and os.path.exists(os.path.join(sb, x))]
378
+ bad = [x for x in paths if x not in ok_paths]
379
+ out = dict(ok=bool(ok_paths), attached=ok_paths)
380
+ if bad:
381
+ out["not_found"] = bad
382
+ conv.add_tool_output(c.id, c.name, json.dumps(out))
383
+ log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths))
384
+ if ok_paths:
385
+ conv.add_user(images_part(ok_paths, "Requested images:"), live=True)
386
+ continue
387
+ cmdline = str(c.arguments.get("command", ""))
388
+ cmd, args = parse_command(cmdline)
389
+ if cmd is None:
390
+ out_text, paths = json.dumps(dict(ok=False, error=args)), []
391
+ else:
392
+ raw = call_server(port, token, cmd, args)
393
+ try:
394
+ rep = json.loads(raw)
395
+ if v2: # keep the image paths in the reply: the model views them itself if it wants
396
+ paths = []
397
+ out_text = json.dumps(rep)
398
+ else:
399
+ paths = rep.pop("images", []) if isinstance(rep, dict) else []
400
+ out_text = json.dumps(rep)
401
+ except ValueError: # help text
402
+ rep, paths, out_text = {}, [], raw
403
+ msg = (rep.get("message", "") + " " + rep.get("error", "")) if isinstance(rep, dict) else ""
404
+ if isinstance(rep, dict) and isinstance(rep.get("attempt_ended"), dict):
405
+ msg += " " + rep["attempt_ended"].get("message", "")
406
+ if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
407
+ finished = True
408
+ if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)):
409
+ calls_in_attempt = 0
410
+ conv.add_tool_output(c.id, c.name, out_text)
411
+ log(dict(ev="tool", turn=turn, command=cmdline, output=out_text, images=paths))
412
+ if paths and not v2:
413
+ conv.add_user(images_part(paths, f"Camera images after `{cmdline}` (agentview, wrist):"), live=True)
414
+ if la and not finished and calls_in_attempt >= max_tool_calls:
415
+ raw = call_server(port, token, "finish", dict(reason="tool-call budget used up (automatic)"))
416
+ try:
417
+ rep = json.loads(raw)
418
+ except ValueError:
419
+ rep = dict(raw=raw)
420
+ msg = rep.get("message", "") + " " + rep.get("error", "")
421
+ if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
422
+ finished = True
423
+ calls_in_attempt = 0
424
+ note = (f"The budget of {max_tool_calls} tool calls for this attempt was used up, so the attempt was "
425
+ f"finished automatically. Result: " + json.dumps(rep))
426
+ conv.add_user([dict(type="text", text=note)], live=False)
427
+ log(dict(ev="user", text=note, auto_finish=True))
428
+ if finished:
429
+ ask = "Stop now and reply with your short report (no more tool calls)."
430
+ conv.add_user([dict(type="text", text=ask)], live=False)
431
+ log(dict(ev="user", text=ask))
432
+ if report:
433
+ with open(os.path.join(log_dir, "final_report.md"), "w") as f:
434
+ f.write(report)
435
+ log(dict(ev="end", finished=finished, usage_total=usage_tot))
436
+ print(json.dumps(dict(finished=finished, usage=usage_tot, report=(report or "")[:200])), flush=True)
437
+
438
+
439
+ if __name__ == "__main__":
440
+ try:
441
+ main()
442
+ except SystemExit:
443
+ raise
444
+ except Exception:
445
+ traceback.print_exc()
446
+ sys.exit(1)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/full_report.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Summarise a full run (all tasks x harnesses) from the robot-server logs only, so every harness is measured
2
+ the same way.
3
+
4
+ python scripts/full_report.py --batch full1 [--out ../docs/full1_table.md]
5
+
6
+ Per run: outcome of every attempt, attempts used, robot commands, close_gripper calls that ended holding an
7
+ object, "empty done" attempts (the agent ended an attempt without a single move / gripper command in it), and
8
+ wall time from the first to the last server request.
9
+ """
10
+ import argparse
11
+ import collections
12
+ import json
13
+ import os
14
+
15
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
+ LEVEL = {"l1": "L1", "l2": "L2", "l3": "L3", "l4": "L4", "l5": "L5", "l6": "L6", "l7": "L7"}
17
+ HARNESS_NAME = {"gpt_player": "ours", "rpent": "RPent", "gptpolicy": "GPT-Policy", "claude": "ours (Claude CLI)"}
18
+
19
+
20
+ def run_info(r):
21
+ ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
22
+ calls = [e for e in ev if e["ev"] == "call"]
23
+ dones = [e for e in ev if e["ev"] == "done"]
24
+ http = [e for e in ev if e["ev"] == "http"]
25
+ # v1: move_to / open_gripper / close_gripper; v2 and la: move_eef [gripper=open|close] (holding is only in `raw`,
26
+ # the agent never sees it)
27
+ acts_per_attempt = collections.Counter(e["attempt"] for e in calls if e["cmd"] in ("move_to", "open_gripper", "close_gripper")
28
+ or (e["cmd"] == "move_eef" and (e.get("report") or {}).get("ok")))
29
+ empty = sum(1 for d in dones if acts_per_attempt.get(d["attempt"], 0) == 0)
30
+ closes = [e for e in calls if e["cmd"] == "close_gripper"
31
+ or (e["cmd"] == "move_eef" and (e.get("args") or {}).get("gripper") == "close" and (e.get("report") or {}).get("ok"))]
32
+ held = sum(1 for e in closes if (e.get("report") or {}).get("holding_object") or (e.get("raw") or {}).get("holding_object"))
33
+ first = next((d["attempt"] for d in dones if d["success"]), None)
34
+ wall = (http[-1]["t_send"] - http[0]["t_recv"]) / 60 if http else None
35
+ return dict(outcomes="".join("S" if d["success"] else "F" for d in dones), attempts=len(dones), first=first,
36
+ cmds=len(calls), closes=len(closes), held=held, empty=empty, wall=wall)
37
+
38
+
39
+ def main():
40
+ ap = argparse.ArgumentParser()
41
+ ap.add_argument("--batch", default="full1")
42
+ ap.add_argument("--out", default=None)
43
+ ap.add_argument("--runs", default="gpt", help="runs/<runs>/<batch>/manifest.json (gpt or claude)")
44
+ a = ap.parse_args()
45
+ m = json.load(open(os.path.join(ROOT, "runs", a.runs, a.batch, "manifest.json")))
46
+ rows = {}
47
+ for r in m["runs"]:
48
+ try:
49
+ h = r.get("harness") or ("claude" if r.get("cond") in ("harness", "noharness") else "gpt_player")
50
+ rows[(r["task"], h)] = dict(run_info(r), k=r["k"])
51
+ except FileNotFoundError:
52
+ pass
53
+ tasks = sorted({t for t, _ in rows}, key=lambda t: (t[:2], t))
54
+ hs = [h for h in ("gpt_player", "rpent", "gptpolicy", "claude") if any(k[1] == h for k in rows)]
55
+ L = [f"# {a.batch}: one run per task x harness (see manifest for model / perception / style)", "",
56
+ "Cell = outcome of each attempt (S success, F failure); `·` = run missing. Measured from robot-server logs.", "",
57
+ "| task | level | " + " | ".join(HARNESS_NAME[h] for h in hs) + " |", "|---|---|" + "---|" * len(hs)]
58
+ for t in tasks:
59
+ cells = []
60
+ for h in hs:
61
+ x = rows.get((t, h))
62
+ cells.append("·" if x is None else (x["outcomes"] or "—"))
63
+ L.append(f"| {t} | {LEVEL.get(t[:2], '?')} | " + " | ".join(cells) + " |")
64
+ L += ["", "| harness | runs | success @1 | success @3 | grasps held / close_gripper | empty-done attempts | "
65
+ "commands / attempt | wall min / run |", "|---|---|---|---|---|---|---|---|"]
66
+ for h in hs:
67
+ xs = [x for (t, hh), x in rows.items() if hh == h and x["attempts"] > 0]
68
+ n = len(xs)
69
+ att = sum(x["attempts"] for x in xs)
70
+ L.append(f"| {HARNESS_NAME[h]} | {n} | {sum(1 for x in xs if x['first'] == 1)} | "
71
+ f"{sum(1 for x in xs if x['first'])} | {sum(x['held'] for x in xs)} / {sum(x['closes'] for x in xs)} | "
72
+ f"{sum(x['empty'] for x in xs)} / {att} | {sum(x['cmds'] for x in xs) / max(att, 1):.1f} | "
73
+ f"{sum(x['wall'] or 0 for x in xs) / max(n, 1):.0f} |")
74
+ by_level = collections.defaultdict(lambda: [0, 0])
75
+ for (t, h), x in rows.items():
76
+ if x["attempts"]:
77
+ by_level[LEVEL.get(t[:2], "?")][0] += bool(x["first"])
78
+ by_level[LEVEL.get(t[:2], "?")][1] += 1
79
+ L += ["", "Success @3 by level (all harnesses pooled): " +
80
+ ", ".join(f"{lv} {s}/{n}" for lv, (s, n) in sorted(by_level.items()))]
81
+ txt = "\n".join(L)
82
+ print(txt)
83
+ if a.out:
84
+ with open(a.out, "w") as f:
85
+ f.write(txt + "\n")
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/ladder_gpt_plan.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-3 feedback ladder for GPT-6 Astra (user 2026-11-02: "跑吧"; same design as scripts/ladder_plan.py, docs/20).
2
+ Instances: the main-table attempt 1 failures of GPT-6 Astra on the 8 ladder tasks (turntable left out, as in the
3
+ reported Claude totals). Fresh single-attempt agents, Codex 0.163 generic config, jail, high, F1, one round. The F1 rung
4
+ is run here (batch lf1_gpt): GPT has no mismatch-control Do arm to reuse.
5
+
6
+ python scripts/ladder_gpt_plan.py validate Fix texts for instances Claude's ladder did not cover -> results/_ladder/fix_validate_gpt.json
7
+ python scripts/ladder_gpt_plan.py build records -> runs/api/ladder_gpt_20261102/<rung>.json + tasks.txt
8
+ python scripts/ladder_gpt_plan.py report per instance rungs and totals, next to Opus and Sonnet
9
+ """
10
+ import json
11
+ import os
12
+ import subprocess
13
+ import sys
14
+
15
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
16
+ import ladder_plan as L # noqa: E402
17
+
18
+ ROOT, API = L.ROOT, L.API
19
+ OUT = os.path.join(API, "ladder_gpt_20261102")
20
+ BATCHES = ["cx_main1", "cx_astra_s2", "cx_astra_s3"]
21
+ TASKS = {"l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool",
22
+ "l4_fit_container", "l3_card_shelf", "l5_loaded_beam"}
23
+ FIXV_GPT = os.path.join(ROOT, "results", "_ladder", "fix_validate_gpt.json")
24
+ RUNGS = ("F1", "F2", "hplus", "fix")
25
+ BATCH = {"F1": "lf1_gpt", "F2": "lf2_gpt", "hplus": "lhp_gpt", "fix": "lfx_gpt"}
26
+
27
+
28
+ def instances():
29
+ out = {}
30
+ for b in BATCHES:
31
+ for r in json.load(open(os.path.join(API, b, "manifest.json")))["runs"]:
32
+ if r["cond"] != "harness" or r["status"] != "done" or r["task"] not in TASKS:
33
+ continue
34
+ d = next((e for e in L.events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
35
+ if d is not None and not d["success"]:
36
+ out[f"{r['task']}:{r['seed']}"] = r["log"]
37
+ return out
38
+
39
+
40
+ def fixes():
41
+ rows = json.load(open(L.FIXV))["rows"]
42
+ if os.path.exists(FIXV_GPT):
43
+ rows += json.load(open(FIXV_GPT))["rows"]
44
+ return {r["key"]: r for r in rows}
45
+
46
+
47
+ def cmd_validate():
48
+ import validate_ladder_fix as V
49
+ have = fixes()
50
+ want = {k: v for k, v in instances().items() if not have.get(k, {}).get("ok")}
51
+ print("to validate:", sorted(want))
52
+ if not want:
53
+ return
54
+ V.instances = lambda: {k: dict(task=k.split(":")[0], seed=int(k.split(":")[1]), models=["gpt"],
55
+ logged=json.loads(open(os.path.join(v, "events.jsonl")).readline())["inst"]) for k, v in want.items()}
56
+ sys.argv = ["validate_ladder_fix.py", "--out", FIXV_GPT]
57
+ V.main()
58
+
59
+
60
+ def cmd_build():
61
+ fx = fixes(); inst = instances(); os.makedirs(OUT, exist_ok=True)
62
+ open(os.path.join(OUT, "tasks.txt"), "w").write("\n".join(sorted(inst)) + "\n")
63
+ out = {r: {} for r in RUNGS}
64
+ for key, log in sorted(inst.items()):
65
+ task, seed = key.split(":")
66
+ tx = dict(L.texts(dict(log=log, task=task, seed=int(seed)), fx), F1="")
67
+ for r in RUNGS:
68
+ dst = os.path.join(OUT, r, f"{task}_s{seed}")
69
+ if not os.path.isdir(dst):
70
+ cmd = [sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst] + (["--result-extra", tx[r]] if tx[r] else [])
71
+ subprocess.run(cmd, check=True, capture_output=True)
72
+ out[r][key] = dst
73
+ for r in RUNGS:
74
+ json.dump(out[r], open(os.path.join(OUT, f"{r}.json"), "w"), indent=1)
75
+ print(len(inst), "instances x", len(RUNGS), "rungs")
76
+
77
+
78
+ def cmd_report():
79
+ keys = [l.strip() for l in open(os.path.join(OUT, "tasks.txt")) if l.strip()]
80
+ res = {r: L.single(BATCH[r]) for r in RUNGS}
81
+ f = lambda v: "-" if v is None else ("S" if v else "F")
82
+ print("| instance | F1 | F2 | H+ | Fix |\n|---|---|---|---|---|")
83
+ for k in keys:
84
+ print(f"| {k} | " + " | ".join(f(res[r].get(k)) for r in RUNGS) + " |")
85
+ rows = [{r: res[r].get(k) for r in RUNGS} for k in keys]
86
+ tot = {r: [sum(bool(x[r]) for x in rows if x[r] is not None), sum(x[r] is not None for x in rows)] for r in RUNGS}
87
+ print("totals:", ", ".join(f"{r} {tot[r][0]}/{tot[r][1]}" for r in RUNGS))
88
+ for lo, hi in zip(RUNGS, RUNGS[1:]):
89
+ both = [x for x in rows if x[lo] is not None and x[hi] is not None]
90
+ print(f"{lo}->{hi}: n={len(both)} up {sum(bool(x[hi]) and not x[lo] for x in both)} down {sum(bool(x[lo]) and not x[hi] for x in both)}")
91
+ json.dump(dict(rows=[dict(inst=k, **{r: res[r].get(k) for r in RUNGS}) for k in keys], totals=tot), open(os.path.join(OUT, "report.json"), "w"), indent=1)
92
+
93
+
94
+ if __name__ == "__main__":
95
+ {"validate": cmd_validate, "build": cmd_build, "report": cmd_report}[sys.argv[1]]()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/real_check_driver.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Conformance check of a robot driver (lffbench/real/protocol.py, spec lffbench/real/DRIVER.md). Run it on the robot PC
3
+ (or through the SSH tunnel) before the first real run, and again after any change to the driver.
4
+
5
+ python scripts/real_check_driver.py --driver http://127.0.0.1:9900 --token <token> [--yes] [--operator] [--json]
6
+
7
+ The arm moves a little: 3 cm up and back, a 30 deg turn and back, the gripper closes and opens, all at 5 cm/s from
8
+ the current pose. Keep a hand on the e-stop. --yes skips the confirmation; --operator also tests the operator
9
+ prompts (you answer them on the driver's terminal). Needs only Python 3 + numpy + Pillow.
10
+ Exit code 0 = every check PASS (WARN does not fail).
11
+ """
12
+ import argparse
13
+ import json
14
+ import os
15
+ import sys
16
+ import time
17
+
18
+ HERE = os.path.dirname(os.path.abspath(__file__))
19
+ sys.path[:0] = [HERE, os.path.join(os.path.dirname(HERE), "lffbench", "real")] # protocol.py next to it, or the repo copy
20
+ import numpy as np # noqa: E402
21
+
22
+ from protocol import (CAMERAS, DriverClient, DriverError, info_problems, state_problems) # noqa: E402
23
+
24
+
25
+ class Checks:
26
+ def __init__(self):
27
+ self.rows = []
28
+
29
+ def add(self, name, status, detail=""):
30
+ self.rows.append(dict(name=name, status=status, detail=str(detail)))
31
+ print(f"[{status}] {name} {detail}", file=sys.stderr, flush=True)
32
+ return status == "PASS"
33
+
34
+ def ok(self, name, cond, detail="", warn=False):
35
+ return self.add(name, "PASS" if cond else ("WARN" if warn else "FAIL"), detail)
36
+
37
+
38
+ def yaw_diff(a, b):
39
+ return abs((a - b + 90.0) % 180.0 - 90.0)
40
+
41
+
42
+ def main():
43
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
44
+ ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900"))
45
+ ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
46
+ ap.add_argument("--yes", action="store_true", help="do not ask before moving the arm")
47
+ ap.add_argument("--operator", action="store_true", help="also test the operator prompts (reset, judge)")
48
+ ap.add_argument("--json", action="store_true", help="print a JSON summary as the last line of stdout")
49
+ ap.add_argument("--yaw-tol", type=float, default=2.0, help="degrees (keep 2 for a real arm)")
50
+ a = ap.parse_args()
51
+ C = Checks()
52
+ d = DriverClient(a.driver, a.token, timeout=120)
53
+ try:
54
+ run(C, d, a)
55
+ except DriverError as e:
56
+ C.add("driver answered every request", "FAIL", e)
57
+ n_fail = sum(r["status"] == "FAIL" for r in C.rows)
58
+ print(f"\n{len(C.rows) - n_fail} ok / {n_fail} FAIL", file=sys.stderr)
59
+ if a.json:
60
+ print(json.dumps(dict(checks=C.rows, n_fail=n_fail)))
61
+ sys.exit(1 if n_fail else 0)
62
+
63
+
64
+ def run(C, d, a):
65
+ # ---- no motion
66
+ bad = DriverClient(d.url, d.token + "-wrong")
67
+ try:
68
+ rep = bad.call("state", allow_not_ok=True)
69
+ C.ok("wrong token is refused", rep.get("ok") is False, rep.get("error", ""))
70
+ except DriverError as e:
71
+ C.add("wrong token is refused", "FAIL", e)
72
+ info = d.call("info")
73
+ prob = info_problems(info)
74
+ if not C.ok("/info has every field", not prob, "; ".join(prob) or {k: info[k] for k in ("robot", "n_joints", "workspace")}):
75
+ return
76
+ n = int(info["n_joints"])
77
+ st = d.state()
78
+ prob = state_problems(st, n)
79
+ if not C.ok("/state has every field", not prob, "; ".join(prob) or st):
80
+ return
81
+ lo, hi = np.array(info["workspace"]["lo"]), np.array(info["workspace"]["hi"])
82
+ p0 = np.array(st["eef_pos"])
83
+ C.ok("current grasp point inside the declared workspace", bool(np.all(p0 >= lo) and np.all(p0 <= hi)), p0.round(4).tolist())
84
+ t0 = time.time()
85
+ frames, st2 = d.observe()
86
+ dt = time.time() - t0
87
+ for c in CAMERAS:
88
+ f = frames[c]
89
+ C.ok(f"/observe {c}: RGB image", f.ndim == 3 and f.shape[2] == 3 and min(f.shape[:2]) >= 256,
90
+ f"{f.shape[1]}x{f.shape[0]}")
91
+ C.ok(f"/observe {c}: not blank", float(f.std()) > 5.0, f"pixel std {f.std():.1f}")
92
+ h, w = f.shape[:2]
93
+ C.ok(f"/observe {c}: square or close to it (the benchmark centre-crops to a square)", 0.75 <= w / h <= 1.34,
94
+ f"{w}x{h}: {abs(w - h) // 2} px cut on each side", warn=True)
95
+ C.ok("/observe also returns the state", not state_problems(st2, n))
96
+ C.ok("/observe latency", dt < 2.0, f"{dt:.2f} s", warn=True)
97
+ rep = d.call("event", dict(ev="session_start", run="check_driver", task="check", seed=0))
98
+ C.ok("/event answers", rep["ok"])
99
+ rep = d.operator("notice", run="check_driver", attempt=0, text="real_check_driver.py: conformance check running")
100
+ C.ok("/operator notice answers", rep["ok"])
101
+ if info["ik"]:
102
+ q = d.ik(st["eef_pos"], st["eef_yaw_deg"])
103
+ err = float(np.max(np.abs(np.array(q) - np.array(st["joint_pos_rad"])))) if len(q) == n else None
104
+ C.ok("/ik of the current pose = current joint angles (within 0.05 rad)", err is not None and err < 0.05,
105
+ f"max |dq| = {err}")
106
+ # ---- rejected targets: must not move
107
+ for name, tgt in (("far outside the workspace (x + 1 m)", [hi[0] + 1.0, p0[1], p0[2]]),
108
+ ("below the workspace floor (z - 5 cm)", [p0[0], p0[1], lo[2] - 0.05])):
109
+ rep = d.move(*tgt, st["eef_yaw_deg"], 0.05)
110
+ moved = float(np.linalg.norm(np.array(rep["state"]["eef_pos"]) - p0))
111
+ C.ok(f"/move {name} is rejected and the arm does not move", rep["ok"] is False and moved < 0.005,
112
+ f"ok={rep['ok']} error={rep.get('error')!r} moved {moved * 100:.1f} cm")
113
+ # ---- motion
114
+ if not a.yes:
115
+ input("\nThe arm will now move 3 cm up and back, turn 30 deg and back, close and open the gripper, at 5 cm/s.\n"
116
+ "Keep a hand on the e-stop and press Enter... ")
117
+ up = p0 + [0.0, 0.0, 0.03]
118
+ if up[2] > hi[2]:
119
+ up = p0 - [0.0, 0.0, 0.03]
120
+ y0 = float(st["eef_yaw_deg"])
121
+ rep = d.move(*up, y0, 0.05)
122
+ p = np.array(rep["state"]["eef_pos"])
123
+ C.ok("/move 3 cm vertical: ok", rep["ok"], rep.get("error", ""))
124
+ C.ok("/move 3 cm vertical: reached within 5 mm", np.linalg.norm(p - up) < 0.005, f"error {np.linalg.norm(p - up) * 1000:.1f} mm")
125
+ C.ok("/move 3 cm vertical: blocking, motion_s plausible at 5 cm/s", 0.3 <= rep["motion_s"] <= 5.0, f"motion_s={rep['motion_s']}")
126
+ C.ok("/move keeps the yaw (within 2 deg)", yaw_diff(rep["state"]["eef_yaw_deg"], y0) < 2.0,
127
+ f"{rep['state']['eef_yaw_deg']:.1f} vs {y0:.1f}")
128
+ y1 = y0 + 30.0 if y0 + 30.0 <= info["yaw_range_deg"][1] else y0 - 30.0
129
+ rep = d.move(*up, y1, 0.05)
130
+ C.ok(f"/move turn 30 deg: reached within {a.yaw_tol:g} deg", rep["ok"] and yaw_diff(rep["state"]["eef_yaw_deg"], y1) < a.yaw_tol,
131
+ f"{rep['state']['eef_yaw_deg']:.1f} vs {y1:.1f}")
132
+ C.ok("/move turn 30 deg: position kept (within 5 mm)", np.linalg.norm(np.array(rep["state"]["eef_pos"]) - up) < 0.005)
133
+ sign = 1.0 if y1 > y0 else -1.0
134
+ C.add("yaw sign (look at the arm)", "NOTE",
135
+ f"it just turned {sign * 30:+.0f} deg: + must be counter-clockwise seen from above (DRIVER.md §3)")
136
+ rep = d.move(*up, y0, 0.05)
137
+ C.ok("/move turn back", rep["ok"] and yaw_diff(rep["state"]["eef_yaw_deg"], y0) < a.yaw_tol,
138
+ f"{rep['state']['eef_yaw_deg']:.1f} vs {y0:.1f}")
139
+ rep = d.gripper(True)
140
+ w_closed = rep["state"]["gripper_width_m"]
141
+ C.ok("/gripper close: width < 1 cm when closed on nothing", w_closed < 0.01, f"{w_closed:.4f} m, motion_s={rep['motion_s']}")
142
+ rep = d.gripper(False)
143
+ w_open = rep["state"]["gripper_width_m"]
144
+ C.ok("/gripper open: width > 3 cm", w_open > 0.03, f"{w_open:.4f} m")
145
+ rep = d.move(*p0, y0, 0.05)
146
+ C.ok("/move back to the start pose", rep["ok"] and np.linalg.norm(np.array(rep["state"]["eef_pos"]) - p0) < 0.005)
147
+ rep = d.home()
148
+ C.ok("/home answers with the state", rep["ok"] and not state_problems(rep["state"], n))
149
+ rep = d.call("event", dict(ev="attempt_start", run="check_driver", attempt=1)) # starts the driver's recorder
150
+ time.sleep(2.0)
151
+ rep2 = d.call("event", dict(ev="attempt_end", run="check_driver", attempt=1))
152
+ C.ok("/event attempt_start / attempt_end answer (recording)", rep["ok"] and rep2["ok"],
153
+ "check that the driver wrote a short video (driver_template: <log>/check_driver_a1.mp4)")
154
+ if a.operator:
155
+ rep = d.operator("reset", run="check_driver", attempt=1, setup="(test) nothing to change, just press Enter")
156
+ C.ok("/operator reset returns after Enter", rep["ok"])
157
+ rep = d.operator("judge", run="check_driver", attempt=1, checklist=["(test) answer y"])
158
+ C.ok("/operator judge returns success", rep.get("success") is True, rep)
159
+ d.call("event", dict(ev="session_end", run="check_driver"))
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/record_breakfast_service.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Continuous simulation recording with a magnified crop; no state edits or model calls."""
2
+ import argparse, hashlib, json
3
+ from pathlib import Path
4
+ import imageio.v2 as imageio
5
+ import numpy as np
6
+ from PIL import Image, ImageDraw, ImageFont
7
+ from lffbench import envs
8
+ from lffbench.tasks.lh_breakfast_service import BreakfastService
9
+ import robosuite.utils.transform_utils as T
10
+
11
+ FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
12
+
13
+ class Recorder:
14
+ def __init__(self,t,out):
15
+ self.t=t;self.out=out;self.n=0;self.frames=0;self.timeline=[]
16
+ self.phase='Prepare breakfast';self.focus='food';self.raw_n=0
17
+ self.raw=imageio.get_writer(str(out/'breakfast_full_1x.mp4'),fps=5,codec='libx264',quality=8,macro_block_size=1)
18
+ self.preview=imageio.get_writer(str(out/'breakfast_recovery_2x.mp4'),fps=10,codec='libx264',quality=8,macro_block_size=1)
19
+ self.original=t.env.step;t.env.step=self.step
20
+ # Rendering-only side camera makes the reopened lid's gap visible.
21
+ m=t.env.sim.model;cid=m.camera_name2id('sideview')
22
+ pos=np.array([-.28,-.58,1.16]);target=np.array([-.20,-.10,.96])
23
+ z=(pos-target)/np.linalg.norm(pos-target);x=np.cross([0,0,1],z);x/=np.linalg.norm(x);y=np.cross(z,x)
24
+ q=T.mat2quat(np.column_stack([x,y,z]))
25
+ m.cam_pos[cid]=pos;m.cam_quat[cid]=q[[3,0,1,2]];m.cam_fovy[cid]=45
26
+ t.env.sim.forward()
27
+ def step(self,a):
28
+ result=self.original(a);self.n+=1
29
+ if self.n%4==0:self.capture()
30
+ return result
31
+ def frame(self):
32
+ return Image.fromarray(envs.render(self.t.env,res=768))
33
+ def decorate(self,im):
34
+ canvas=Image.new('RGB',(1280,928),(19,26,36));canvas.paste(im,(0,48))
35
+ crop={'milk':(440,180,760,500),'lid':(150,230,470,550),'food':(0,220,320,540)}[self.focus]
36
+ detail=(Image.fromarray(envs.render(self.t.env,cam='sideview',res=512)) if self.focus=='lid'
37
+ else im.crop(crop).resize((512,512),Image.Resampling.LANCZOS))
38
+ canvas.paste(detail,(768,80))
39
+ d=ImageDraw.Draw(canvas);f=ImageFont.truetype(FONT,24);sm=ImageFont.truetype(FONT,20)
40
+ d.text((18,10),'BREAKFAST | scripted recovery reference | same attempt | 2x',font=f,fill='white')
41
+ d.text((785,52),'Synchronized side view' if self.focus=='lid' else 'Magnified detail from the same frame',font=sm,fill='#b5ccdf')
42
+ q=self.t.liquid
43
+ for n,line in enumerate([f'Simulation: {self.n*.05:.1f} s',f'Milk in cup: {q["cup"]:.1f} mL',
44
+ f'Spilled: {q["spill"]:.1f} mL',f'Pantry lid: {self.t.lid_deg():.1f} deg',
45
+ f'Butter height: {100*self.t.butter_height():.1f} cm']):
46
+ d.text((790,620+36*n),line,font=f,fill='white')
47
+ d.text((18,830),self.phase,font=f,fill='#ffe0a2')
48
+ d.text((18,874),'Milk: simplified flow + ballistic parcels; rigid objects: MuJoCo contacts.',font=sm,fill='#b5ccdf')
49
+ return np.asarray(canvas)
50
+ def capture(self):
51
+ im=self.frame();self.raw.append_data(np.asarray(im));self.raw_n+=1
52
+ self.preview.append_data(self.decorate(im));self.frames+=1
53
+ def phase_hook(self,text,state):
54
+ if text.startswith(('Tipping handle:','Returning handle:','Bread pickup:','Bread placement:')):return
55
+ if 'carton' in text or 'cradle' in text or 'milk' in text.lower():self.focus='milk'
56
+ elif 'pantry' in text.lower() or 'L4' in text or 'lid' in text.lower() or 'inside the box' in text or 'Upright butter' in text:self.focus='lid'
57
+ else:self.focus='food'
58
+ self.phase=text
59
+ row=dict(state,preview_time_s=self.frames/10,preview_frame=self.frames)
60
+ self.timeline.append(row)
61
+ im=self.frame();Image.Image.save(im,self.out/f'checkpoint_{len(self.timeline):02d}.png')
62
+ # Explicit presentation hold only; no simulation reset or omitted motion.
63
+ for _ in range(10):self.preview.append_data(self.decorate(im));self.frames+=1
64
+ print(json.dumps(row,default=lambda v:v.item()),flush=True)
65
+ def close(self):
66
+ self.t.env.step=self.original;self.raw.close();self.preview.close()
67
+
68
+ def main():
69
+ p=argparse.ArgumentParser();p.add_argument('--out',required=True);p.add_argument('--seed',type=int,default=1000)
70
+ a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
71
+ t=BreakfastService();inst=t.sample_instance(a.seed);t.reset_instance(inst)
72
+ r=Recorder(t,out);t.phase_hook=r.phase_hook
73
+ try:
74
+ t.execute(inst,{'mode':'adaptive'});result=t.outcome(inst)
75
+ r.phase_hook('FINAL: breakfast served; all three failures recovered' if result['success'] else 'FINAL: verification failed',
76
+ dict(step=t.sk.n_steps,outcome=result))
77
+ finally:r.close()
78
+ files=[Path(__file__).resolve().parents[1]/'lffbench/tasks'/n for n in
79
+ ('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')]
80
+ meta=dict(seed=a.seed,instance=inst,outcome=result,continuous_attempt=True,resets_during_recording=0,
81
+ source_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files},
82
+ sim_seconds=r.n*.05,raw_frames=r.raw_n,preview_frames=r.frames,timeline=r.timeline,
83
+ presentation='2x with 1 s freeze at labeled checkpoints; full 1x has no presentation freezes',
84
+ video_hashes={f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in out.glob('*.mp4')})
85
+ (out/'recording.json').write_text(json.dumps(meta,indent=2,default=lambda v:v.item()))
86
+ assert result['success'] and all(result['traps'].values()) and all(result['recovered'].values()),result
87
+ t.env.close()
88
+
89
+ if __name__=='__main__':main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model backends. Import lazily: each API backend needs its provider's SDK (see base.import_sdk)."""
2
+ from .base import AttemptInfo, Backend, BackendResponse, RunInfo # noqa: F401
3
+
4
+
5
+ def make_backend(kind, **kw):
6
+ if kind == "scripted":
7
+ from .scripted import ScriptedBackend
8
+ return ScriptedBackend(**kw)
9
+ if kind == "openai":
10
+ from .openai_responses import OpenAIResponsesBackend
11
+ return OpenAIResponsesBackend(**kw)
12
+ if kind == "chat":
13
+ from .chat_completions import ChatCompletionsBackend
14
+ return ChatCompletionsBackend(**kw)
15
+ if kind == "anthropic":
16
+ from .anthropic_messages import AnthropicMessagesBackend
17
+ return AnthropicMessagesBackend(**kw)
18
+ if kind == "gemini":
19
+ from .gemini import GeminiBackend
20
+ return GeminiBackend(**kw)
21
+ raise ValueError(kind)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/anthropic_messages.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Anthropic Messages API backend (Claude Opus 5.5 / Sonnet 5.5 / Fable 5.1 ...), official SDK `anthropic`.
2
+
3
+ Same conversation as the OpenAI backends, converted to Messages API blocks:
4
+ - system prompt = conv.system; tools = the harness tool specs (strict, one call per turn like the GPT player);
5
+ - every assistant turn is stored with its full `content` (thinking blocks with signatures, text, tool_use) and replayed
6
+ unchanged, so the model keeps its reasoning across tool calls. Assistant turns are never edited; old images in user
7
+ turns may be replaced by a text note (checked 2026-10-15 on Sonnet 5.5 / Opus 5.5 with thinking blocks in the
8
+ history: accepted), which the player does only when the context or the per-request image limit is reached;
9
+ - tool outputs of one turn become `tool_result` blocks at the start of the next user message; images the harness
10
+ attaches after them (observations, view_images) follow in the same user message;
11
+ - adaptive thinking with an explicit effort (the per-model default differs: Opus 5.5 medium, Sonnet 5.5 high);
12
+ - automatic prompt caching (top-level cache_control): every request caches its whole prefix for the next call;
13
+ - streaming, so long thinking turns do not hit the HTTP timeout.
14
+ No refusal fallback on purpose: a fallback would silently swap the model under test. A refusal is reported as
15
+ status "refusal" and the player ends the run.
16
+
17
+ Key from ANTHROPIC_API_KEY (or any credential the SDK resolves). The client is created lazily on the first real
18
+ call; tests inject a mock client.
19
+ """
20
+ import time
21
+
22
+ from ..context import ToolCall, prune_live_images
23
+ from .base import Backend, BackendResponse, import_sdk
24
+
25
+ EFFORTS = ("low", "medium", "high", "xhigh", "max")
26
+
27
+
28
+ def _get(obj, key, default=None):
29
+ if isinstance(obj, dict):
30
+ return obj.get(key, default)
31
+ return getattr(obj, key, default)
32
+
33
+
34
+ def _to_dict(block):
35
+ if isinstance(block, dict):
36
+ return dict(block)
37
+ if hasattr(block, "to_dict"):
38
+ return block.to_dict()
39
+ return block.model_dump(mode="json", exclude_none=True)
40
+
41
+
42
+ def anthropic_tools(specs, strict=True):
43
+ out = []
44
+ for s in specs:
45
+ t = dict(name=s["name"], description=s["description"], input_schema=s["parameters"])
46
+ if strict:
47
+ t["strict"] = True
48
+ out.append(t)
49
+ return out
50
+
51
+
52
+ def image_block(image, quality=None):
53
+ url = image.data_url(quality)
54
+ head, data = url.split(",", 1) # data:<mime>;base64,<data>
55
+ mime = head[len("data:"):].split(";", 1)[0]
56
+ return dict(type="image", source=dict(type="base64", media_type=mime, data=data))
57
+
58
+
59
+ class AnthropicMessagesBackend(Backend):
60
+ name = "anthropic"
61
+
62
+ def __init__(self, model="claude-opus-5-5", effort="high", thinking_display="summarized", max_tokens=64000,
63
+ max_live_images=None, jpeg_quality=90, timeout=900.0, max_retries=2, strict_tools=True,
64
+ parallel_tool_calls=False, cache=True, client=None):
65
+ if effort not in EFFORTS:
66
+ raise ValueError(f"effort must be one of {EFFORTS}, got {effort!r}")
67
+ self.model = model
68
+ self.effort = effort
69
+ self.thinking_display = thinking_display # "summarized" (logged as the reasoning summary) | "omitted"
70
+ self.max_tokens = max_tokens
71
+ self.max_live_images = max_live_images
72
+ self.jpeg_quality = jpeg_quality
73
+ self.timeout = timeout
74
+ self.max_retries = max_retries
75
+ self.strict_tools = strict_tools
76
+ self.parallel_tool_calls = parallel_tool_calls
77
+ self.cache = cache
78
+ self._client = client
79
+
80
+ def config(self):
81
+ return dict(name=self.name, model=self.model, effort=self.effort, thinking_display=self.thinking_display,
82
+ max_tokens=self.max_tokens, max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality,
83
+ timeout=self.timeout, max_retries=self.max_retries, strict_tools=self.strict_tools,
84
+ parallel_tool_calls=self.parallel_tool_calls, cache=self.cache)
85
+
86
+ def client(self):
87
+ if self._client is None:
88
+ anthropic = import_sdk("anthropic")
89
+ self._client = anthropic.Anthropic(timeout=self.timeout, max_retries=self.max_retries)
90
+ return self._client
91
+
92
+ # ------------------------------------------------------------------ request
93
+ def convert_items(self, items):
94
+ msgs = []
95
+
96
+ def push(role, blocks):
97
+ if msgs and msgs[-1]["role"] == role:
98
+ msgs[-1]["content"].extend(blocks)
99
+ else:
100
+ msgs.append(dict(role=role, content=list(blocks)))
101
+
102
+ for it in items:
103
+ kind = it["kind"]
104
+ if kind == "user":
105
+ blocks = []
106
+ for p in it["parts"]:
107
+ if p["type"] == "text":
108
+ blocks.append(dict(type="text", text=p["text"]))
109
+ else:
110
+ blocks.append(image_block(p["image"], self.jpeg_quality))
111
+ push("user", blocks)
112
+ elif kind == "assistant":
113
+ if it.get("raw") is not None and it.get("backend") == self.name:
114
+ blocks = [dict(b) for b in it["raw"]]
115
+ else: # a turn produced by another backend: plain text + tool calls, no thinking
116
+ blocks = ([dict(type="text", text=it["text"])] if it.get("text") else [])
117
+ blocks += [dict(type="tool_use", id=tc.id, name=tc.name, input=tc.arguments)
118
+ for tc in it["tool_calls"]]
119
+ if not blocks:
120
+ blocks = [dict(type="text", text="(no output)")]
121
+ push("assistant", blocks)
122
+ elif kind == "tool_output":
123
+ push("user", [dict(type="tool_result", tool_use_id=it["call_id"], content=it["text"])])
124
+ else:
125
+ raise ValueError(kind)
126
+ return msgs
127
+
128
+ def build_request(self, conv, tools):
129
+ items = prune_live_images(conv.items, self.max_live_images)
130
+ req = dict(model=self.model, max_tokens=int(self.max_tokens), system=conv.system,
131
+ messages=self.convert_items(items), tools=anthropic_tools(tools, self.strict_tools),
132
+ tool_choice=dict(type="auto", disable_parallel_tool_use=not self.parallel_tool_calls),
133
+ thinking=dict(type="adaptive", display=self.thinking_display),
134
+ output_config=dict(effort=self.effort))
135
+ if self.cache:
136
+ req["cache_control"] = dict(type="ephemeral")
137
+ return req
138
+
139
+ @staticmethod
140
+ def request_stats(req):
141
+ n_img, img_bytes, txt = 0, 0, len(req.get("system") or "")
142
+ for m in req["messages"]:
143
+ for b in m["content"]:
144
+ t = b.get("type")
145
+ if t == "image":
146
+ n_img += 1
147
+ img_bytes += len(b["source"]["data"])
148
+ elif t == "text":
149
+ txt += len(b["text"])
150
+ elif t == "tool_result":
151
+ txt += len(b["content"]) if isinstance(b["content"], str) else 0
152
+ return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_messages=len(req["messages"]))
153
+
154
+ # ------------------------------------------------------------------ call
155
+ def act(self, conv, tools):
156
+ req = self.build_request(conv, tools)
157
+ stats = self.request_stats(req)
158
+ t0 = time.time()
159
+ try:
160
+ with self.client().messages.stream(**req) as stream:
161
+ msg = stream.get_final_message()
162
+ except AssertionError: # the SDK asserts on a stream without message_start (seen through a gateway)
163
+ raise RuntimeError("empty response stream (no message_start event)") from None
164
+ out = self.parse_response(msg)
165
+ out.latency_s = time.time() - t0
166
+ out.request_stats = stats
167
+ return out
168
+
169
+ def parse_response(self, msg):
170
+ calls, texts, summ = [], [], []
171
+ content = _get(msg, "content") or []
172
+ for b in content:
173
+ t = _get(b, "type")
174
+ if t == "tool_use":
175
+ args = _get(b, "input") or {}
176
+ calls.append(ToolCall(id=_get(b, "id"), name=_get(b, "name"), arguments=dict(args)))
177
+ elif t == "text":
178
+ texts.append(_get(b, "text") or "")
179
+ elif t == "thinking":
180
+ if _get(b, "thinking"):
181
+ summ.append(_get(b, "thinking"))
182
+ u = _get(msg, "usage")
183
+ usage = {}
184
+ if u is not None:
185
+ fresh = _get(u, "input_tokens", 0) or 0
186
+ read = _get(u, "cache_read_input_tokens", 0) or 0
187
+ write = _get(u, "cache_creation_input_tokens", 0) or 0
188
+ # same meaning as the OpenAI backend: input_tokens = whole prompt, cached_tokens = the part read from cache
189
+ usage = dict(input_tokens=fresh + read + write, cached_tokens=read, cache_write_tokens=write,
190
+ output_tokens=_get(u, "output_tokens", 0) or 0, reasoning_tokens=0)
191
+ stop = _get(msg, "stop_reason")
192
+ status, err = "completed", None
193
+ if stop == "refusal":
194
+ d = _get(msg, "stop_details")
195
+ status, err = "refusal", f"refusal: category={_get(d, 'category')} {_get(d, 'explanation') or ''}".strip()
196
+ elif stop == "max_tokens":
197
+ status, err = "incomplete", "incomplete: max_tokens"
198
+ elif not content and u is None:
199
+ status, err = "incomplete", "empty response (no content, no usage)"
200
+ return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
201
+ reasoning_summary="\n".join(summ) or None, usage=usage,
202
+ raw=[_to_dict(b) for b in content], status=status, error=err)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/base.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s)."""
2
+ import os
3
+ import sys
4
+ from dataclasses import dataclass, field
5
+ from typing import Optional
6
+
7
+ # Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh).
8
+ # Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name:
9
+ # LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence.
10
+ API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "")
11
+ OPENAI_SDK_DIR = API_SDK_DIR # old name
12
+
13
+
14
+ def import_sdk(module):
15
+ """Import an API SDK module ("openai", "anthropic", "google.genai")."""
16
+ import importlib
17
+ try:
18
+ return importlib.import_module(module)
19
+ except ImportError:
20
+ if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path:
21
+ sys.path.append(API_SDK_DIR)
22
+ return importlib.import_module(module)
23
+
24
+
25
+ def import_openai():
26
+ return import_sdk("openai")
27
+
28
+
29
+ @dataclass
30
+ class BackendResponse:
31
+ tool_calls: list = field(default_factory=list) # [ToolCall]
32
+ text: Optional[str] = None # visible assistant text (e.g. the diagnosis)
33
+ reasoning_summary: Optional[str] = None
34
+ usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens
35
+ latency_s: float = 0.0
36
+ raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items)
37
+ request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ...
38
+ status: str = "ok"
39
+ error: Optional[str] = None
40
+
41
+
42
+ @dataclass
43
+ class RunInfo:
44
+ task: object # privileged: only the scripted backend may look at task / inst
45
+ inst: dict
46
+ seed: int
47
+ k: int
48
+ protocol: str
49
+ feedback: str
50
+ memory: str
51
+
52
+
53
+ @dataclass
54
+ class AttemptInfo:
55
+ attempt: int
56
+ history: list # AttemptRecords visible to the agent under the memory mode (already selected)
57
+ continuing: bool = False # within protocol: continuing after a failed done
58
+
59
+
60
+ class Backend:
61
+ name = "base"
62
+
63
+ def begin_run(self, info: RunInfo):
64
+ pass
65
+
66
+ def begin_attempt(self, info: AttemptInfo):
67
+ pass
68
+
69
+ def act(self, conv, tools) -> BackendResponse:
70
+ raise NotImplementedError
71
+
72
+ def on_tool_result(self, call, result):
73
+ pass
74
+
75
+ def end_attempt(self) -> dict:
76
+ return {}
77
+
78
+ def end_run(self):
79
+ pass
80
+
81
+ def config(self) -> dict:
82
+ return dict(name=self.name)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/chat_completions.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served
2
+ by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format.
3
+
4
+ Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard
5
+ message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent
6
+ back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and
7
+ Responses backends do (Kimi's docs ask for this in multi-step tool use)."""
8
+ import json
9
+ import os
10
+ import time
11
+
12
+ from ..context import ToolCall, prune_live_images
13
+ from .base import Backend, BackendResponse, import_openai
14
+
15
+
16
+ def chat_tools(specs):
17
+ return [dict(type="function", function=dict(name=s["name"], description=s["description"],
18
+ parameters=s["parameters"])) for s in specs]
19
+
20
+
21
+ class ChatCompletionsBackend(Backend):
22
+ name = "chat"
23
+
24
+ def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024,
25
+ max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None,
26
+ replay_reasoning=True):
27
+ self.model = model
28
+ self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1")
29
+ self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY")
30
+ self.temperature = temperature
31
+ self.max_tokens = max_tokens
32
+ self.max_live_images = max_live_images
33
+ self.jpeg_quality = jpeg_quality
34
+ self.timeout = timeout
35
+ self.extra_body = extra_body
36
+ self.replay_reasoning = replay_reasoning
37
+ self._client = client
38
+
39
+ def config(self):
40
+ return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature,
41
+ max_tokens=self.max_tokens, max_live_images=self.max_live_images,
42
+ replay_reasoning=self.replay_reasoning)
43
+
44
+ def client(self):
45
+ if self._client is None:
46
+ openai = import_openai()
47
+ kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1)
48
+ if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")):
49
+ # local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here)
50
+ kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout)
51
+ self._client = openai.OpenAI(**kw)
52
+ return self._client
53
+
54
+ def build_request(self, conv, tools):
55
+ msgs = [dict(role="system", content=conv.system)]
56
+ for it in prune_live_images(conv.items, self.max_live_images):
57
+ if it["kind"] == "user":
58
+ content = []
59
+ for p in it["parts"]:
60
+ if p["type"] == "text":
61
+ content.append(dict(type="text", text=p["text"]))
62
+ else:
63
+ content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality))))
64
+ msgs.append(dict(role="user", content=content))
65
+ elif it["kind"] == "assistant":
66
+ if not it.get("text") and not it["tool_calls"]:
67
+ # a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still
68
+ # counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content
69
+ # nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request
70
+ continue
71
+ m = dict(role="assistant", content=it.get("text") or None)
72
+ rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None
73
+ if rc and self.replay_reasoning:
74
+ m["reasoning_content"] = rc
75
+ if it["tool_calls"]:
76
+ m["tool_calls"] = [dict(id=tc.id, type="function",
77
+ function=dict(name=tc.name,
78
+ arguments=tc.raw_arguments or json.dumps(tc.arguments)))
79
+ for tc in it["tool_calls"]]
80
+ msgs.append(m)
81
+ elif it["kind"] == "tool_output":
82
+ msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"]))
83
+ req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto",
84
+ max_tokens=self.max_tokens)
85
+ if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature)
86
+ req["temperature"] = self.temperature
87
+ if self.extra_body:
88
+ req["extra_body"] = dict(self.extra_body)
89
+ return req
90
+
91
+ def act(self, conv, tools):
92
+ req = self.build_request(conv, tools)
93
+ n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list)
94
+ for c in m["content"] if c.get("type") == "image_url")
95
+ t0 = time.time()
96
+ resp = self.client().chat.completions.create(**req)
97
+ lat = time.time() - t0
98
+ stats = dict(n_images=n_img, n_messages=len(req["messages"]))
99
+ if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again
100
+ return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
101
+ error="empty response (no choices)")
102
+ msg = resp.choices[0].message
103
+ rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content")
104
+ calls = []
105
+ for i, tc in enumerate(msg.tool_calls or []):
106
+ raw = tc.function.arguments or ""
107
+ try:
108
+ args = json.loads(raw) if raw else {}
109
+ except json.JSONDecodeError:
110
+ args = {}
111
+ calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw))
112
+ u = resp.usage
113
+ ctd = getattr(u, "completion_tokens_details", None) if u else None
114
+ usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0,
115
+ output_tokens=getattr(u, "completion_tokens", 0) or 0,
116
+ reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {}
117
+ if not calls and not msg.content and not rc and not u:
118
+ return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
119
+ error="empty response (no output, no usage)")
120
+ return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage,
121
+ latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats)
122
+
123
+
124
+ def tool_results_first(msgs):
125
+ """OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly
126
+ after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's
127
+ output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool
128
+ messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after
129
+ the last tool message of the turn; nothing else changes order."""
130
+ out, i = [], 0
131
+ while i < len(msgs):
132
+ m = msgs[i]
133
+ out.append(m)
134
+ i += 1
135
+ if m["role"] != "assistant" or not m.get("tool_calls"):
136
+ continue
137
+ need = {tc["id"] for tc in m["tool_calls"]}
138
+ held = []
139
+ while i < len(msgs) and need:
140
+ n = msgs[i]
141
+ if n["role"] == "tool" and n.get("tool_call_id") in need:
142
+ out.append(n)
143
+ need.discard(n["tool_call_id"])
144
+ elif n["role"] == "user":
145
+ held.append(n)
146
+ else:
147
+ break
148
+ i += 1
149
+ out.extend(held)
150
+ return out
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/gemini.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Google Gemini backend (Gemini API, official SDK `google-genai`).
2
+
3
+ Same conversation as the other backends, converted to Gemini `contents`:
4
+ - system prompt = system_instruction; tools = function declarations with the harness's JSON schemas;
5
+ - every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive)
6
+ and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call;
7
+ - tool outputs of one turn become `function_response` parts at the start of the next user content; images the
8
+ harness attaches after them follow in the same user content;
9
+ - thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged;
10
+ - implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage).
11
+
12
+ Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock.
13
+ """
14
+ import base64
15
+ import time
16
+
17
+ from ..context import ToolCall, prune_live_images
18
+ from .base import Backend, BackendResponse, import_sdk
19
+
20
+
21
+ def _get(obj, key, default=None):
22
+ if isinstance(obj, dict):
23
+ return obj.get(key, default)
24
+ return getattr(obj, key, default)
25
+
26
+
27
+ def _strip_additional(schema):
28
+ """The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema."""
29
+ if isinstance(schema, dict):
30
+ return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"}
31
+ if isinstance(schema, list):
32
+ return [_strip_additional(v) for v in schema]
33
+ return schema
34
+
35
+
36
+ def _image_part(image, quality=None):
37
+ head, data = image.data_url(quality).split(",", 1)
38
+ mime = head[len("data:"):].split(";", 1)[0]
39
+ return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data)))
40
+
41
+
42
+ class GeminiBackend(Backend):
43
+ name = "gemini"
44
+
45
+ def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True,
46
+ max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90,
47
+ timeout=900.0, client=None):
48
+ self.model = model
49
+ self.thinking_level = thinking_level
50
+ self.thinking_budget = thinking_budget
51
+ self.include_thoughts = include_thoughts
52
+ self.max_output_tokens = max_output_tokens
53
+ self.media_resolution = media_resolution
54
+ self.max_live_images = max_live_images
55
+ self.jpeg_quality = jpeg_quality
56
+ self.timeout = timeout
57
+ self._client = client
58
+ self._json_schema_field = None
59
+
60
+ def config(self):
61
+ return dict(name=self.name, model=self.model, thinking_level=self.thinking_level,
62
+ thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts,
63
+ max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution,
64
+ max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout)
65
+
66
+ def client(self):
67
+ if self._client is None:
68
+ genai = import_sdk("google.genai")
69
+ self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000)))
70
+ return self._client
71
+
72
+ def _declarations(self, specs):
73
+ if self._json_schema_field is None:
74
+ try:
75
+ types = import_sdk("google.genai.types")
76
+ self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields
77
+ except ImportError: # tests without the SDK
78
+ self._json_schema_field = True
79
+ out = []
80
+ for s in specs:
81
+ d = dict(name=s["name"], description=s["description"])
82
+ if self._json_schema_field:
83
+ d["parameters_json_schema"] = s["parameters"]
84
+ else:
85
+ d["parameters"] = _strip_additional(s["parameters"])
86
+ out.append(d)
87
+ return [dict(function_declarations=out)]
88
+
89
+ # ------------------------------------------------------------------ request
90
+ def convert_items(self, items):
91
+ contents = []
92
+
93
+ def push(role, parts):
94
+ if contents and contents[-1]["role"] == role:
95
+ contents[-1]["parts"].extend(parts)
96
+ else:
97
+ contents.append(dict(role=role, parts=list(parts)))
98
+
99
+ for it in items:
100
+ kind = it["kind"]
101
+ if kind == "user":
102
+ parts = []
103
+ for p in it["parts"]:
104
+ if p["type"] == "text":
105
+ parts.append(dict(text=p["text"]))
106
+ else:
107
+ parts.append(_image_part(p["image"], self.jpeg_quality))
108
+ push("user", parts)
109
+ elif kind == "assistant":
110
+ if it.get("raw") is not None and it.get("backend") == self.name:
111
+ content = dict(it["raw"][0])
112
+ contents.append(dict(role="model", parts=list(content.get("parts") or [])))
113
+ continue
114
+ parts = ([dict(text=it["text"])] if it.get("text") else [])
115
+ parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]]
116
+ push("model", parts or [dict(text="(no output)")])
117
+ elif kind == "tool_output":
118
+ fr = dict(name=it["name"], response=dict(output=it["text"]))
119
+ if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"):
120
+ fr["id"] = it["call_id"]
121
+ push("user", [dict(function_response=fr)])
122
+ else:
123
+ raise ValueError(kind)
124
+ return contents
125
+
126
+ def build_request(self, conv, tools):
127
+ items = prune_live_images(conv.items, self.max_live_images)
128
+ thinking = dict(include_thoughts=self.include_thoughts)
129
+ if self.thinking_budget is not None:
130
+ thinking["thinking_budget"] = int(self.thinking_budget)
131
+ elif self.thinking_level:
132
+ thinking["thinking_level"] = self.thinking_level
133
+ config = dict(system_instruction=conv.system, tools=self._declarations(tools),
134
+ tool_config=dict(function_calling_config=dict(mode="AUTO")),
135
+ automatic_function_calling=dict(disable=True), thinking_config=thinking,
136
+ max_output_tokens=int(self.max_output_tokens))
137
+ if self.media_resolution:
138
+ config["media_resolution"] = self.media_resolution
139
+ return dict(model=self.model, contents=self.convert_items(items), config=config)
140
+
141
+ @staticmethod
142
+ def request_stats(req):
143
+ n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "")
144
+ for c in req["contents"]:
145
+ for p in c["parts"]:
146
+ p = p if isinstance(p, dict) else {}
147
+ if p.get("inline_data"):
148
+ n_img += 1
149
+ img_bytes += len(p["inline_data"]["data"])
150
+ elif p.get("text"):
151
+ txt += len(p["text"])
152
+ elif p.get("function_response"):
153
+ txt += len(str(p["function_response"].get("response", "")))
154
+ return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"]))
155
+
156
+ # ------------------------------------------------------------------ call
157
+ def act(self, conv, tools):
158
+ req = self.build_request(conv, tools)
159
+ stats = self.request_stats(req)
160
+ types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys
161
+ t0 = time.time()
162
+ resp = self.client().models.generate_content(
163
+ model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]],
164
+ config=types.GenerateContentConfig.model_validate(req["config"]))
165
+ out = self.parse_response(resp)
166
+ out.latency_s = time.time() - t0
167
+ out.request_stats = stats
168
+ return out
169
+
170
+ def parse_response(self, resp):
171
+ cands = _get(resp, "candidates") or []
172
+ cand = cands[0] if cands else None
173
+ content = _get(cand, "content") if cand is not None else None
174
+ parts = (_get(content, "parts") or []) if content is not None else []
175
+ calls, texts, summ = [], [], []
176
+ for i, p in enumerate(parts):
177
+ fc = _get(p, "function_call")
178
+ if fc is not None:
179
+ cid = _get(fc, "id") or f"gemini_call_{i}"
180
+ calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {})))
181
+ elif _get(p, "text"):
182
+ (summ if _get(p, "thought") else texts).append(_get(p, "text"))
183
+ u = _get(resp, "usage_metadata")
184
+ usage = {}
185
+ if u is not None:
186
+ usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0,
187
+ cached_tokens=_get(u, "cached_content_token_count", 0) or 0,
188
+ output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0),
189
+ reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0)
190
+ finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE"
191
+ status, err = "completed", None
192
+ if not parts:
193
+ status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})"
194
+ elif "MAX_TOKENS" in finish or "MALFORMED" in finish:
195
+ status, err = "incomplete", f"incomplete: finish_reason={finish}"
196
+ elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish:
197
+ status, err = "refusal", f"refusal: finish_reason={finish}"
198
+ if content is not None and hasattr(content, "model_dump"):
199
+ raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes
200
+ elif content is not None:
201
+ raw = [dict(content)]
202
+ else:
203
+ raw = None
204
+ return BackendResponse(tool_calls=calls, text="\n".join(texts) or None,
205
+ reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw,
206
+ status=status, error=err)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI Responses API backend (default model gpt-6-astra).
2
+
3
+ Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with
4
+ store=False; reasoning items are replayed with their encrypted content so the model keeps its chain
5
+ of thought across tool calls within an attempt. The request prefix (instructions, tools, task text,
6
+ packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what
7
+ OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs.
8
+
9
+ Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time;
10
+ the client is created lazily on the first real call (tests inject a mock client).
11
+ """
12
+ import json
13
+ import os
14
+ import time
15
+
16
+ from ..context import ToolCall, prune_live_images
17
+ from .base import Backend, BackendResponse, import_openai
18
+
19
+ # GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported.
20
+ GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max")
21
+
22
+
23
+ def _get(obj, key, default=None):
24
+ if isinstance(obj, dict):
25
+ return obj.get(key, default)
26
+ return getattr(obj, key, default)
27
+
28
+
29
+ def _to_dict(item):
30
+ if isinstance(item, dict):
31
+ return dict(item)
32
+ if hasattr(item, "to_dict"):
33
+ return item.to_dict(mode="json")
34
+ if hasattr(item, "model_dump"):
35
+ return item.model_dump(mode="json", exclude_none=True)
36
+ return dict(vars(item))
37
+
38
+
39
+ def responses_tools(specs, strict=True):
40
+ return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"],
41
+ strict=strict) for s in specs]
42
+
43
+
44
+ class OpenAIResponsesBackend(Backend):
45
+ name = "openai"
46
+
47
+ def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto",
48
+ max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None,
49
+ store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0,
50
+ max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last",
51
+ prompt_cache_options=None, client=None, http_client=None):
52
+ if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS:
53
+ raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), "
54
+ f"got {reasoning_effort!r}")
55
+ self.model = model
56
+ self.reasoning_effort = reasoning_effort
57
+ self.reasoning_summary = reasoning_summary
58
+ self.image_detail = image_detail
59
+ self.max_output_tokens = max_output_tokens
60
+ self.service_tier = service_tier
61
+ self.prompt_cache_key = prompt_cache_key
62
+ self.prompt_cache_retention = prompt_cache_retention
63
+ self.store = store
64
+ self.replay_reasoning = replay_reasoning
65
+ self.max_live_images = max_live_images
66
+ self.jpeg_quality = jpeg_quality
67
+ self.timeout = timeout
68
+ self.max_retries = max_retries
69
+ self.extra_body = extra_body
70
+ self.strict_tools = strict_tools
71
+ # explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last"
72
+ assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints
73
+ self.cache_breakpoints = cache_breakpoints
74
+ self.prompt_cache_options = prompt_cache_options
75
+ self._client = client
76
+ self._http_client = http_client # optional custom transport (tests, proxies)
77
+ self._cache_key = prompt_cache_key
78
+
79
+ def config(self):
80
+ return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort,
81
+ reasoning_summary=self.reasoning_summary, image_detail=self.image_detail,
82
+ max_output_tokens=self.max_output_tokens, service_tier=self.service_tier,
83
+ prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention,
84
+ store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images,
85
+ jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries,
86
+ extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints,
87
+ prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL"))
88
+
89
+ # ------------------------------------------------------------------ client
90
+ def client(self):
91
+ if self._client is None:
92
+ key = os.environ.get("OPENAI_API_KEY")
93
+ if not key:
94
+ raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it")
95
+ openai = import_openai()
96
+ kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout,
97
+ max_retries=self.max_retries)
98
+ if self._http_client is not None:
99
+ kw["http_client"] = self._http_client
100
+ self._client = openai.OpenAI(**kw)
101
+ return self._client
102
+
103
+ def begin_run(self, info):
104
+ if self.prompt_cache_key is None:
105
+ # route all calls of one run to the same cache shard
106
+ self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}"
107
+
108
+ # ------------------------------------------------------------------ request
109
+ def convert_items(self, items):
110
+ out = []
111
+ last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1)
112
+ for i, it in enumerate(items):
113
+ kind = it["kind"]
114
+ if kind == "user":
115
+ content = []
116
+ for p in it["parts"]:
117
+ if p["type"] == "text":
118
+ content.append(dict(type="input_text", text=p["text"]))
119
+ else:
120
+ content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality),
121
+ detail=self.image_detail))
122
+ # explicit cache breakpoints: end of the stable history item (byte-identical for the whole
123
+ # attempt) and end of the newest input (reused by the next call of the attempt)
124
+ if content and ((self.cache_breakpoints != "none" and not it.get("live"))
125
+ or (self.cache_breakpoints == "history+last" and i == last_user)):
126
+ content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit")
127
+ out.append(dict(role="user", content=content))
128
+ elif kind == "assistant":
129
+ if it.get("raw") and it.get("backend") == self.name:
130
+ for r in it["raw"]:
131
+ if r.get("type") == "reasoning" and not self.replay_reasoning:
132
+ continue
133
+ out.append(r)
134
+ else:
135
+ if it.get("text"):
136
+ out.append(dict(role="assistant", content=it["text"]))
137
+ for tc in it["tool_calls"]:
138
+ out.append(dict(type="function_call", call_id=tc.id, name=tc.name,
139
+ arguments=tc.raw_arguments or json.dumps(tc.arguments)))
140
+ elif kind == "tool_output":
141
+ out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"]))
142
+ else:
143
+ raise ValueError(kind)
144
+ return out
145
+
146
+ def build_request(self, conv, tools):
147
+ items = prune_live_images(conv.items, self.max_live_images)
148
+ req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items),
149
+ tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False,
150
+ store=self.store)
151
+ reasoning = dict(effort=self.reasoning_effort)
152
+ if self.reasoning_summary:
153
+ reasoning["summary"] = self.reasoning_summary
154
+ req["reasoning"] = reasoning
155
+ if not self.store and self.replay_reasoning:
156
+ req["include"] = ["reasoning.encrypted_content"]
157
+ if self.max_output_tokens:
158
+ req["max_output_tokens"] = int(self.max_output_tokens)
159
+ if self.service_tier:
160
+ req["service_tier"] = self.service_tier
161
+ if self._cache_key:
162
+ req["prompt_cache_key"] = self._cache_key
163
+ if self.prompt_cache_retention:
164
+ req["prompt_cache_retention"] = self.prompt_cache_retention
165
+ if self.prompt_cache_options:
166
+ req["prompt_cache_options"] = dict(self.prompt_cache_options)
167
+ if self.extra_body:
168
+ req["extra_body"] = dict(self.extra_body)
169
+ return req
170
+
171
+ @staticmethod
172
+ def request_stats(req):
173
+ n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "")
174
+ for it in req["input"]:
175
+ for c in (it.get("content") if isinstance(it.get("content"), list) else []):
176
+ if c.get("type") == "input_image":
177
+ n_img += 1
178
+ img_bytes += len(c["image_url"])
179
+ elif "text" in c:
180
+ txt += len(c["text"])
181
+ if isinstance(it.get("content"), str):
182
+ txt += len(it["content"])
183
+ if it.get("type") == "function_call_output":
184
+ txt += len(it["output"]) if isinstance(it["output"], str) else 0
185
+ if it.get("type") == "function_call":
186
+ txt += len(it.get("arguments", ""))
187
+ tools_chars = len(json.dumps(req.get("tools", [])))
188
+ return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars,
189
+ n_input_items=len(req["input"]))
190
+
191
+ # ------------------------------------------------------------------ call
192
+ def act(self, conv, tools):
193
+ req = self.build_request(conv, tools)
194
+ stats = self.request_stats(req)
195
+ t0 = time.time()
196
+ resp = self.client().responses.create(**req)
197
+ out = self.parse_response(resp)
198
+ out.latency_s = time.time() - t0
199
+ out.request_stats = stats
200
+ return out
201
+
202
+ def parse_response(self, resp):
203
+ calls, texts, summ = [], [], []
204
+ output = _get(resp, "output") or []
205
+ for item in output:
206
+ t = _get(item, "type")
207
+ if t == "function_call":
208
+ raw = _get(item, "arguments") or ""
209
+ try:
210
+ args = json.loads(raw) if raw else {}
211
+ except json.JSONDecodeError:
212
+ args = {}
213
+ calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args,
214
+ raw_arguments=raw))
215
+ elif t == "message":
216
+ for c in _get(item, "content") or []:
217
+ if _get(c, "type") == "output_text":
218
+ texts.append(_get(c, "text") or "")
219
+ elif t == "reasoning":
220
+ for s in _get(item, "summary") or []:
221
+ summ.append(_get(s, "text") or "")
222
+ u = _get(resp, "usage")
223
+ usage = {}
224
+ if u is not None:
225
+ itd = _get(u, "input_tokens_details")
226
+ otd = _get(u, "output_tokens_details")
227
+ usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0,
228
+ cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0,
229
+ cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0,
230
+ output_tokens=_get(u, "output_tokens", 0) or 0,
231
+ reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0)
232
+ status = _get(resp, "status") or "completed"
233
+ err = None
234
+ if status == "incomplete":
235
+ err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason"))
236
+ elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again
237
+ status, err = "incomplete", "empty response (no output, no usage)"
238
+ return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
239
+ reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage,
240
+ raw=[_to_dict(i) for i in output], status=status, error=err)
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/scripted.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scripted backend: no model. Runs a task's scripted reference policy (adaptive by default) through the
2
+ agent tool interface, to test the harness end to end.
3
+
4
+ How: the task's own `execute(inst, params)` runs in a worker thread with `task.sk` replaced by a proxy.
5
+ Every Skills primitive it calls (move_to / set_gripper / push / grasp_at / place_at) becomes an agent
6
+ tool call that is handed to the harness, executed by the ToolExecutor on the main thread, and its
7
+ report is returned to the worker. Only one thread runs at a time (queues hand control back and forth),
8
+ so MuJoCo is never touched concurrently. Only schema-valid tool calls are emitted, so this also shows
9
+ that the tool interface is expressive enough for the task.
10
+
11
+ The scripted policy is privileged: it reads the instance (layout) like the task's reference policies
12
+ do. It sees earlier attempts only through the memory mode chosen by the harness and only the outcome
13
+ fields allowed by the feedback level (F2: structured measurement, F1: success flag, F0: nothing); if
14
+ the adaptive rule cannot run on what it sees, it falls back to the task's blind retry rule.
15
+ Supported: cross-protocol tasks that implement execute/default_params/adapt_params (+ oracle/blind).
16
+ """
17
+ import math
18
+ import queue
19
+ import threading
20
+ import traceback
21
+
22
+ import numpy as np
23
+
24
+ from ..context import ToolCall
25
+ from .base import Backend, BackendResponse
26
+
27
+ TIMEOUT_S = 600
28
+
29
+
30
+ class _Abort(Exception):
31
+ pass
32
+
33
+
34
+ class _Channel:
35
+ def __init__(self):
36
+ self.req = queue.Queue()
37
+ self.res = queue.Queue()
38
+
39
+ def call(self, name, args): # worker side
40
+ self.req.put(("call", name, args))
41
+ kind, payload = self.res.get(timeout=TIMEOUT_S)
42
+ if kind == "abort":
43
+ raise _Abort()
44
+ return payload
45
+
46
+
47
+ class SkillsProxy:
48
+ """Stands in for task.sk inside task.execute(); primitives become agent tool calls."""
49
+
50
+ def __init__(self, real, channel):
51
+ self._real = real
52
+ self._ch = channel
53
+ self.untooled_hold_steps = 0
54
+ self.ignored_wrap_yaw_false = 0
55
+
56
+ def move_to(self, target, yaw=None, speed=None, tol=None, max_steps=None, apply_bias=True, wrap_yaw=True):
57
+ if not wrap_yaw: # the move_to tool always wraps yaw mod pi (Skills default); counted, not fatal
58
+ self.ignored_wrap_yaw_false += 1
59
+ if not apply_bias:
60
+ raise NotImplementedError("apply_bias=False cannot be expressed through the agent tools")
61
+ yaw_deg = math.degrees(self._real.yaw if yaw is None else float(yaw))
62
+ rep = self._ch.call("move_to", dict(x=float(target[0]), y=float(target[1]), z=float(target[2]),
63
+ yaw=round(yaw_deg, 3), speed=None if speed is None else float(speed)))
64
+ return dict(prim="move_to", reached=rep.get("reached"), pos=rep.get("eef_pos"))
65
+
66
+ def set_gripper(self, close, steps=15):
67
+ rep = self._ch.call("close_gripper" if close else "open_gripper", {})
68
+ return dict(prim="close" if close else "open", width=rep.get("gripper_width_m"))
69
+
70
+ def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06):
71
+ rep = self._ch.call("push", dict(x=float(start_xy[0]), y=float(start_xy[1]), dir_x=float(direction_xy[0]),
72
+ dir_y=float(direction_xy[1]), distance=float(distance), speed=float(speed),
73
+ z=None if z is None else float(z), runup=float(pre)))
74
+ return dict(prim="push", reached=rep.get("sweep_reached"), pos=rep.get("eef_pos"))
75
+
76
+ def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15):
77
+ self.set_gripper(False, steps=5)
78
+ self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw)
79
+ self.move_to([xy[0], xy[1], z_grasp])
80
+ self.set_gripper(True)
81
+ self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25)
82
+
83
+ def place_at(self, xy, z_release, approach=0.10):
84
+ self.move_to([xy[0], xy[1], z_release + approach])
85
+ self.move_to([xy[0], xy[1], z_release])
86
+ self.set_gripper(False)
87
+ self.move_to([xy[0], xy[1], z_release + approach])
88
+
89
+ def hold(self, steps=10):
90
+ # waiting in place has no tool; executed directly (only physics, no new command) and counted
91
+ self.untooled_hold_steps += int(steps)
92
+ self._real.hold(steps)
93
+
94
+ def __getattr__(self, k): # eef_pos, eef_mat, gripper_width, holding, yaw, ...
95
+ return getattr(self._real, k)
96
+
97
+
98
+ class ScriptedBackend(Backend):
99
+ name = "scripted"
100
+
101
+ def __init__(self, policy="adaptive", seed=0):
102
+ assert policy in ("adaptive", "naive", "oracle", "blind"), policy
103
+ self.policy = policy
104
+ self.seed = seed
105
+ self.info = None
106
+ self.rng = None
107
+
108
+ def config(self):
109
+ return dict(name=self.name, policy=self.policy, seed=self.seed)
110
+
111
+ def begin_run(self, info):
112
+ if info.protocol != "cross":
113
+ raise NotImplementedError("ScriptedBackend supports cross-protocol tasks only (execute/adapt_params)")
114
+ self.info = info
115
+ self.rng = np.random.default_rng(self.seed + info.seed)
116
+ self._oracle = None
117
+ if self.policy == "oracle": # privileged scratch rollouts happen before the harness resets the scene
118
+ self._oracle = info.task.oracle_params(info.inst)
119
+
120
+ # ------------------------------------------------------------------ params from visible history
121
+ def _visible(self, rec):
122
+ out = rec.outcome
123
+ if self.info.feedback == "F2":
124
+ vis = dict(out)
125
+ elif self.info.feedback == "F1":
126
+ vis = dict(success=out.get("success"))
127
+ else:
128
+ vis = {}
129
+ return dict(attempt=rec.attempt, params=rec.backend_meta.get("params"), outcome=vis)
130
+
131
+ def _params(self, attempt, history):
132
+ task, inst = self.info.task, self.info.inst
133
+ if self.policy == "oracle":
134
+ return dict(self._oracle), "oracle"
135
+ if self.policy == "naive" or not history and self.policy == "adaptive":
136
+ return task.default_params(inst), "default"
137
+ if self.policy == "blind":
138
+ if attempt == 1:
139
+ return task.default_params(inst), "default"
140
+ return task.blind_params(inst, attempt - 1, self.rng), "blind"
141
+ hist = [self._visible(r) for r in history if r.backend_meta.get("params") is not None]
142
+ if not hist:
143
+ return task.blind_params(inst, attempt - 1, self.rng), "blind(no usable history)"
144
+ try:
145
+ return task.adapt_params(inst, hist), "adapt"
146
+ except (KeyError, TypeError, ValueError):
147
+ return task.blind_params(inst, attempt - 1, self.rng), "blind(feedback too coarse)"
148
+
149
+ # ------------------------------------------------------------------ attempt
150
+ def begin_attempt(self, ainfo):
151
+ self.params, self.rule = self._params(ainfo.attempt, ainfo.history)
152
+ self.ch = _Channel()
153
+ self.thread = None
154
+ self.pending = False
155
+ self.last_report = None
156
+ self.n = 0
157
+ self.proxy = None
158
+
159
+ def _worker(self):
160
+ try:
161
+ self.info.task.execute(self.info.inst, self.params)
162
+ self.ch.req.put(("finished", None))
163
+ except _Abort:
164
+ pass
165
+ except Exception:
166
+ self.ch.req.put(("error", traceback.format_exc()))
167
+
168
+ def act(self, conv, tools):
169
+ if self.thread is None:
170
+ task = self.info.task
171
+ self.real_sk = task.sk
172
+ self.proxy = SkillsProxy(task.sk, self.ch)
173
+ task.sk = self.proxy
174
+ self.thread = threading.Thread(target=self._worker, daemon=True)
175
+ self.thread.start()
176
+ elif self.pending:
177
+ self.ch.res.put(("result", self.last_report or {}))
178
+ self.pending = False
179
+ kind, *rest = self.ch.req.get(timeout=TIMEOUT_S)
180
+ self.n += 1
181
+ if kind == "call":
182
+ name, args = rest[0], rest[1]
183
+ self.pending = True
184
+ tc = ToolCall(id=f"scripted_{self.n}", name=name, arguments=args)
185
+ text = None
186
+ if self.n == 1:
187
+ text = f"[scripted {self.policy}: rule={self.rule}, params={self.params}]"
188
+ return BackendResponse(tool_calls=[tc], text=text)
189
+ if kind == "finished":
190
+ return BackendResponse(tool_calls=[ToolCall(id=f"scripted_{self.n}", name="done",
191
+ arguments=dict(reason=f"scripted {self.policy} policy finished "
192
+ f"with params {self.params}"))])
193
+ raise RuntimeError("scripted policy crashed:\n" + str(rest[0]))
194
+
195
+ def on_tool_result(self, call, result):
196
+ self.last_report = result.report
197
+
198
+ def end_attempt(self):
199
+ if self.thread is not None:
200
+ if self.thread.is_alive():
201
+ if self.pending:
202
+ self.ch.res.put(("abort", None))
203
+ self.thread.join(timeout=30)
204
+ self.info.task.sk = self.real_sk
205
+ meta = dict(policy=self.policy, rule=self.rule, params=self.params)
206
+ if self.proxy is not None and self.proxy.untooled_hold_steps:
207
+ meta["untooled_hold_steps"] = self.proxy.untooled_hold_steps
208
+ if self.proxy is not None and self.proxy.ignored_wrap_yaw_false:
209
+ meta["ignored_wrap_yaw_false"] = self.proxy.ignored_wrap_yaw_false
210
+ return meta
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l4_fit_container.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l4_fit_container (2026-10-12).
2
+
3
+ Hidden variable: inst["cap"] -- clear (unrendered) bumper caps on both ends of the phone, 0.8-0.9 cm each, so the
4
+ phone is 1.6-1.8 cm longer than it looks. The prior picks the box with the most visible room to spare ("snug"),
5
+ which is too short for the capped phone; only the "fit" box is long enough.
6
+
7
+ h0 cap = 0: no caps. The phone is exactly as big as it looks, the "snug" box the prior picks fits it (as do "fit"
8
+ and "short_wide"). inst["fit"] is left as is (that box still fits).
9
+ twin Same box positions / yaws, same phone, same caps (trap still active), but the inner sizes (and kinds) of the
10
+ "fit" and "snug" boxes are swapped. In the twin the prior goes to the place where the ORIGINAL's fitting box
11
+ stands (now with snug sizes) and fails on the rim; the twin's fitting box stands where the original's snug box
12
+ stands. So the twin's lesson at the action level ("not that box, use that other box") is exactly the reverse
13
+ of the original's: following it on the original means choosing the original's failing (snug) box.
14
+ Caveat: the abstract lesson ("the phone is longer than it looks, take the box with the most length to spare")
15
+ is the same in both -- a negative cap (phone shorter than it looks) is not physically possible here. The box
16
+ sizes in the twin images differ from the original's at those two positions (they are visible).
17
+ reveal The cap length, in cm, per end and in total.
18
+ """
19
+ HIDDEN_KEYS = ("cap",)
20
+
21
+
22
+ def h0(inst):
23
+ return {"cap": 0.0}
24
+
25
+
26
+ def _idx(inst, kind):
27
+ return next(j for j, b in enumerate(inst["boxes"]) if b["kind"] == kind)
28
+
29
+
30
+ def twin(inst):
31
+ f, s = _idx(inst, "fit"), _idx(inst, "snug")
32
+ boxes = [dict(b) for b in inst["boxes"]]
33
+ for k in ("kind", "inner"):
34
+ boxes[f][k], boxes[s][k] = inst["boxes"][s][k], inst["boxes"][f][k]
35
+ perc = [list(p) for p in inst["_perc"]]
36
+ perc[f], perc[s] = list(inst["_perc"][s]), list(inst["_perc"][f])
37
+ return {"boxes": boxes, "fit": s, "fit_crossed": boxes[s]["crossed"], "_perc": perc}
38
+
39
+
40
+ def reveal(inst):
41
+ c = 100 * inst["cap"]
42
+ return (f"The phone has clear bumper caps on both of its short ends that do not show in the camera images; "
43
+ f"each cap adds about {c:.1f} cm, so the phone is about {2 * c:.1f} cm longer than it looks.")
44
+
45
+
46
+ def _where(inst, j):
47
+ """robot-frame position words of box j in the 2 x 3 grid (rows along x, columns along y)"""
48
+ xs = sorted({round(float(b["xy"][0]), 2) for b in inst["boxes"]} | {round(float(inst["phone_xy"][0]), 2)})
49
+ x, y = (float(v) for v in inst["boxes"][j]["xy"])
50
+ row = "in the row nearer to the robot" if abs(x - xs[0]) < abs(x - xs[-1]) else "in the row farther from the robot"
51
+ col = "on the robot's left" if y > 0.1 else ("on the robot's right" if y < -0.1 else "in the middle")
52
+ return f"{row}, {col}"
53
+
54
+
55
+ def fix(inst, params):
56
+ """Ladder Fix rung (docs/20): the fitting box (oracle box = inst['fit']), long side along the box's long side."""
57
+ j = int(params["box"])
58
+ return (f"A way to succeed: the phone fits only into the box {_where(inst, j)} (the one with the most length to "
59
+ f"spare; it looks tight across, but the phone's width fits). Pick the phone up, turn it so that its long "
60
+ f"side lines up with that box's long side, and lower it flat into the middle of that box before you "
61
+ f"release it.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l7_offcenter_push (docs/14 §6).
2
+
3
+ Hidden variable: com_offset = e, the shift of the box's centre of mass along its long axis (world +y = robot's left;
4
+ |e| in [4.5, 7.5] cm). apply_instance() writes it into body_ipos on every reset; oracle_params() pushes at c = e.
5
+
6
+ h0 e = 0: centre of mass in the middle, so the natural push at the middle of the back face goes straight.
7
+ twin e -> -e: same distance from the middle, other end heavy. The naive push turns the box just as much but the
8
+ other way (clockwise <-> counterclockwise, the other end lags), and the right contact point is on the other
9
+ side of the middle, so the original's lesson ("move the contact toward the left/right end") is reversed.
10
+ reveal states |e| and its side in the robot-frame words of the F2 feedback (robot's left / right).
11
+ """
12
+
13
+ HIDDEN_KEYS = ("com_offset",)
14
+
15
+
16
+ def h0(inst):
17
+ return {"com_offset": 0.0}
18
+
19
+
20
+ def twin(inst):
21
+ return {"com_offset": -float(inst["com_offset"])}
22
+
23
+
24
+ def reveal(inst):
25
+ e = float(inst["com_offset"])
26
+ side = "left" if e > 0 else "right"
27
+ return (f"The box's centre of mass is not at its middle: it is about {100 * abs(e):.1f} cm from the middle along "
28
+ f"the box's long side, toward the robot's {side}.")
29
+
30
+
31
+ def fix(inst, params):
32
+ """Ladder Fix rung (docs/20): push at the centre of mass (oracle c = e), one slow straight push."""
33
+ c = float(params["c"])
34
+ side = "left" if c > 0 else "right"
35
+ return (f"A way to succeed: push at the centre of mass, not at the middle. Close the gripper (yaw 0), put the "
36
+ f"fingertips about 1 cm above the table just behind the box's back face (the face towards the robot), "
37
+ f"{100 * abs(c):.1f} cm to the robot's {side} of that face's middle, and push slowly (speed about 0.08) "
38
+ f"straight forward, away from the robot, until the box is centred in the green rectangle; then lift the "
39
+ f"gripper.")