diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/__init__.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ffd9af077f968176127cbd3767912005f648ac3 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/__init__.py @@ -0,0 +1 @@ +"""LFF-Bench agent harness: tool interface, context packing, model backends, protocol runner.""" diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/camera.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..e1ce86343d9f718577b0a672ed5cb3202c6fc941 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/camera.py @@ -0,0 +1,100 @@ +"""Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map. + +Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's +bottom-up buffer to an upright image): + u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image. +Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils. +""" +import numpy as np +from robosuite.utils import camera_utils as CU + +from .. import envs + +# agent-facing camera name -> MuJoCo camera name +CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"} + + +def mj_cam(name): + if name in CAMERAS: + return CAMERAS[name] + if name in CAMERAS.values(): + return name + raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}") + + +def intrinsics(env, cam, res): + return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res) + + +def cam_to_world(env, cam): + """4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward).""" + return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam)) + + +def render_depth(env, cam, res): + """Metric depth (distance along the optical axis, metres), upright (res, res).""" + _, d = envs.render(env, mj_cam(cam), res, depth=True) + return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0)) + + +def world_to_pixel(env, cam, xyz, res): + """Project a world point; returns (u, v) floats (u = column, v = row) and the depth.""" + K = intrinsics(env, cam, res) + T = np.linalg.inv(cam_to_world(env, cam)) + p = T @ np.append(np.asarray(xyz, float), 1.0) + uvw = K @ p[:3] + return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2]) + + +def pixel_ray(env, cam, u, v, res): + """Unit ray direction (world) through pixel (u, v) and the camera origin.""" + K = intrinsics(env, cam, res) + E = cam_to_world(env, cam) + d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0]) + d = E[:3, :3] @ d_cam + return E[:3, 3].copy(), d / np.linalg.norm(d) + + +def pixel_to_world(env, cam, u, v, res, depth=None): + """Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict.""" + if depth is None: + depth = render_depth(env, cam, res) + iu, iv = int(round(u)), int(round(v)) + if not (0 <= iu < res and 0 <= iv < res): + raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image") + z = float(depth[iv, iu]) + K = intrinsics(env, cam, res) + E = cam_to_world(env, cam) + p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0]) + p = E @ p_cam + far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent + return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far)) + + +def image_axes(env, cam, res, plane_z=envs.TABLE_Z): + """World directions of image-right and image-down at the image centre, projected onto the table + plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y).""" + o, d = pixel_ray(env, cam, res / 2, res / 2, res) + if abs(d[2]) < 1e-6: + return None + t = (plane_z - o[2]) / d[2] + c = o + t * d + out = [] + for du, dv in ((8, 0), (0, 8)): + o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res) + t2 = (plane_z - o2[2]) / d2[2] + w = (o2 + t2 * d2 - c)[:2] + out.append(w / max(np.linalg.norm(w), 1e-9)) + return out + + +def describe_axes(env, cam, res): + """Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign).""" + ax = image_axes(env, cam, res) + if ax is None: + return None + names = [] + for w in ax: + i = int(np.argmax(np.abs(w))) + names.append(("+" if w[i] > 0 else "-") + "xy"[i]) + return dict(right=names[0], down=names[1]) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/robot_server.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/robot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2b05a011de75f29faf4674c3b96ca68bdb98cb0d --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/robot_server.py @@ -0,0 +1,966 @@ +"""Robot server for driving an LFF-Bench task from an isolated agent (e.g. a Claude Code subagent). + +The server owns the simulator, the task instance and its hidden variables. The agent only gets a +sandbox directory containing a tiny `robot` CLI (talks to this server over localhost HTTP), a README +with the instructions, and the observation images the server writes into `/obs/`. +Nothing about the benchmark (code paths, hidden variables, success rule, scripted policies) is ever +written into the sandbox. + +Attempt protocol (same semantics as harness.py): + cross `done` -> outcome is measured; if failed and attempts remain, the scene is reset to the same + initial state + hidden variables and the next attempt starts. + within `done` -> outcome is measured; if failed and done-calls remain, continue from the current state. +memory=none: every attempt is meant for a fresh agent; after `done` the server tells the agent to stop +(no feedback) and waits for the orchestrator to start a new agent (`./robot status` shows the state). + +Run: python -m lffbench.agent.robot_server --task l5_slide_to_target --seed 1001 --sandbox --port 8765 +""" +import argparse +import importlib +import json +import os +import pkgutil +import shutil +import sys +import time +import traceback +from http.server import BaseHTTPRequestHandler, HTTPServer +import signal +import textwrap + +import numpy as np + +from .. import tasks as task_pkg +from ..task_base import TASKS +from . import camera as C +from .context import PromptBuilder +from .tools import ACTION_TOOLS, WS_HI, WS_LO, ToolExecutor, _json_default + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +LFF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +SHELL_TEMPLATE = r'''#!/bin/bash +# Run a shell command inside this workspace, in the episode jail (no network, host data hidden): +# ./shell '' or ./shell <<'EOF' ... EOF (command read from stdin) +WS="$(cd "$(dirname "$0")" && pwd)" +if [ $# -gt 0 ]; then CMD="$*"; else CMD="$(cat)"; fi +exec unshare --user --map-root-user --mount --net -- /opt/lffjail/jail_inner.sh "$WS" timeout -k 5 60 bash -c "$CMD" +''' + +CLI_TEMPLATE = r'''#!/usr/bin/env python3 +"""Robot command-line interface. Usage: ./robot [key=value ...] (./robot help)""" +import json, sys, urllib.request +PORT = __PORT__ +TOKEN = "__TOKEN__" +def main(): + if len(sys.argv) < 2: + sys.argv.append("help") + cmd, args = sys.argv[1], {} + for a in sys.argv[2:]: + if "=" not in a: + print(f"bad argument {a!r}: use key=value"); sys.exit(2) + k, v = a.split("=", 1) + try: + args[k] = json.loads(v) + except ValueError: + args[k] = v + req = urllib.request.Request(f"http://127.0.0.1:{PORT}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(), + headers={"Content-Type": "application/json", "X-Token": TOKEN}) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(req, timeout=600) as r: + print(r.read().decode()) +main() +''' + + +def strip_axes(text): + """v2: keep the robot-centric words of the F2 feedback ("to the robot's left", "forward") but drop the explicit + coordinate-axis labels ("(+y)", "+x, ", "+yaw"), so the feedback does not hand over the axis convention that the + v2 instructions deliberately leave out.""" + import re + t = re.sub(r"\s?\((?:[+-]?[xyz]|[+-]yaw)\)", "", text) # " (+y)", " (x)", " (-yaw)" + t = re.sub(r"\(([+-][xyz]|[+-]yaw), ", "(", t) # "(+x, away from the robot)" + t = re.sub(r", [+-](?:[xyz]|yaw)\)", ")", t) # "(... robot's left, +yaw)" + t = re.sub(r"\s{2,}", " ", t) + return t + + +class VideoRec: + """Records agentview | wrist while the simulator steps (one frame every `every` control steps, played at + `fps`, i.e. sped up by every * fps / 20). A header shows the attempt, the current robot command and the + report of the previous one; gripper commands and attempt outcomes get short freeze frames.""" + + BAND = 56 + + def __init__(self, path, env, res=320, every=3, fps=20, title=""): + import imageio + from . import camera as _C + self.env, self.res, self.every, self.fps, self.title = env, res, every, fps, title + self.cams = [_C.mj_cam("agentview"), _C.mj_cam("wrist")] + self.w = imageio.get_writer(path, fps=fps, quality=7, macro_block_size=8) + self.n = 0 + self.lines = ["", "", ""] + self.last = None + orig = env.step + + def step(a): + out = orig(a) + self.n += 1 + if self.w is not None and self.n % self.every == 0: + self.grab() + return out + + env.step = step + + def _font(self, size): + from PIL import ImageFont + try: + return ImageFont.load_default(size=size) + except TypeError: + return ImageFont.load_default() + + def grab(self): + from PIL import Image, ImageDraw + from .. import envs as _E + img = np.concatenate([_E.render(self.env, c, self.res) for c in self.cams], axis=1) + im = Image.new("RGB", (2 * self.res, self.res + self.BAND), (0, 0, 0)) + im.paste(Image.fromarray(img), (0, self.BAND)) + d = ImageDraw.Draw(im) + hdr = [self.title] + self.lines[:2] + for i, s_ in enumerate(hdr): + d.text((5, 3 + 17 * i), s_[:120], fill=(255, 255, 255) if i else (255, 220, 120), font=self._font(13)) + self.last = np.asarray(im) + self.w.append_data(self.last) + + def hold(self, secs): + if self.w is None: + return + self.grab() + for _ in range(int(secs * self.fps)): + self.w.append_data(self.last) + + def card(self, lines, secs=3.0, color=(20, 20, 20)): + if self.w is None: + return + from PIL import Image, ImageDraw + im = Image.new("RGB", (2 * self.res, self.res + self.BAND), color) + d = ImageDraw.Draw(im) + y = 14 + for s_ in lines: + for part in textwrap.wrap(s_, 62) or [""]: + d.text((14, y), part, fill=(255, 255, 255), font=self._font(15)) + y += 19 + y += 5 + fr = np.asarray(im) + for _ in range(int(secs * self.fps)): + self.w.append_data(fr) + + def close(self): + if self.w is not None: + self.w.close() + self.w = None + + +def _short(rep): + keys = ("touched_object", "holding_object", "gripper_width_m", "eef_pos", "eef_yaw_deg", "error") + return ", ".join(f"{k}={rep[k]}" for k in keys if k in rep) + + +class RobotSession: + def __init__(self, a): + self.a = a + self.task = TASKS[a.task](cam_res=a.image_res) + if a.max_steps is None: # long procedural tasks declare a larger per-attempt budget + a.max_steps = int(getattr(self.task, "agent_max_steps", 40)) + self.inst = self.task.sample_instance(a.seed) + if getattr(a, "nominal", False): + # control condition: same scene, hidden calibration error removed (L1 tasks only) -> plain pick-and-place + hidden = [k for k in ("bias", "yaw_bias") if k in self.inst] + if not hidden: + raise SystemExit(f"--nominal is not supported for {a.task} (no bias / yaw_bias in the instance)") + for k in [k for k in self.inst if "bias" in k]: # bias, bias_r, yaw_bias, yaw_bias_deg, ... + v = self.inst[k] + if isinstance(v, (list, tuple)): + self.inst[k] = [0.0] * len(v) + elif isinstance(v, (int, float)): + self.inst[k] = 0.0 + self.inst["nominal"] = True + # full5 controlled arms (docs/14 §6): h0 / twin override the hidden variable, hplus states it in the instruction + self.arm, self.arm_overrides, self.reveal_text = getattr(a, "arm", "none") or "none", {}, "" + if self.arm in ("h0", "twin"): + from .. import arm_specs + self.arm_overrides = arm_specs.overrides(a.task, self.arm, self.inst) + self.inst.update(self.arm_overrides) + elif self.arm == "hplus": + from .. import arm_specs + self.reveal_text = arm_specs.reveal(a.task, self.inst).strip() + if a.style in ("v2", "la"): # same rule as the F2 feedback: no axis labels such as "(+y)" + self.reveal_text = strip_axes(self.reveal_text) + self.n_mon_events = 0 # regression snapshots: monitor events already inspected + self.protocol = getattr(self.task, "protocol", "cross") + self.k = a.k or self.task.max_attempts + # --hide-k (memory=full): README and status say 1 attempt, exactly like an independent k=1 run, and the other + # attempts are announced only after a failure, so attempt 1 sees the same thing as the independent run. + self.k_shown = 1 if getattr(a, "hide_k", False) and a.memory == "full" else self.k + assert self.k_shown == self.k or a.style in ("v2", "la"), "--hide-k needs --style v2 or la" + self.sandbox = os.path.abspath(a.sandbox) + self.obs_dir = os.path.join(self.sandbox, "obs") + self.log_dir = os.path.abspath(a.log_dir) + os.makedirs(self.obs_dir, exist_ok=True) + os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True) + self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a") + import secrets + self.token = secrets.token_hex(8) + self.n_actions = 0 # robot commands in the current attempt (step budget) + self.attempt = 1 + self.step = 0 + self.finished = False + self.waiting_new_agent = False + self.history = [] + self.last_send = None + cam_axes = {c: C.describe_axes(self.task.env, c, a.image_res) for c in C.CAMERAS} + names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict) + memory = "none" if a.memory == "none" else "full" + self.pb = PromptBuilder(self.task, self.protocol, self.k, memory, a.feedback, a.image_res, cam_axes, + object_names=names, cams=("agentview", "wrist"), depth_tool=a.perception == "depth") + self.video = None + if a.video: + self.video = VideoRec(a.video, self.task.env, every=a.video_every, fps=a.video_fps, + title=f"{a.task} seed={a.seed} perception={a.perception} (sped up x{a.video_every * a.video_fps // 20})") + self.video.card([f"Task: {a.task} seed {a.seed} memory={a.memory} feedback={a.feedback} k={self.k}", + "Instruction: " + self.instruction(), + "Left: agentview Right: wrist camera. Header: current robot command and the report of " + "the previous one."], 3) + self._start_attempt(reset=True) + # la: agent-facing positions are in the robot-base frame (LIBERO-Agent: "Coordinates are expressed in the + # robot-base frame and measured in metres"); the LIBERO base is axis-aligned with the world, so a translation + self.base_off = np.zeros(3) + if a.style == "la": + sim = self.task.env.sim + bid = sim.model.body_name2id("robot0_base") + assert np.allclose(sim.data.body_xmat[bid].reshape(3, 3), np.eye(3), atol=1e-6), "robot base is rotated" + self.base_off = np.array(sim.data.body_xpos[bid], float).copy() + self._write_sandbox() + self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol, + memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception, + inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm, + arm_overrides=self.arm_overrides, reveal=self.reveal_text, dossier=getattr(a, "dossier", "") or "")) + + # ------------------------------------------------------------------ helpers + def log(self, d): + d["t"] = time.time() + self.events.write(json.dumps(d, default=_json_default) + "\n") + self.events.flush() + + def instruction(self): + hook = getattr(self.task, "agent_instruction", None) + if hook is not None: + text = hook(self.inst, self.a.instruction) + elif self.a.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""): + text = self.task.instruction_indirect + else: + text = self.task.instruction + return text + (" " + self.reveal_text if getattr(self, "reveal_text", "") else "") + + def feedback_text(self, out): + import inspect + fn = self.task.feedback + if "indirect" in inspect.signature(fn).parameters: + fb = fn(self.inst, out, self.a.feedback, indirect=self.a.instruction == "indirect") + else: + fb = fn(self.inst, out, self.a.feedback) + return strip_axes(fb) if self.a.style in ("v2", "la") else fb + + def _start_attempt(self, reset): + self.n_actions = 0 + if reset: + self.task.reset_instance(self.inst) + self.ex = ToolExecutor(self.task, self.inst, image_res=self.a.image_res, cams=("agentview", "wrist")) + self.step = 0 + self.sim0 = self.task.sk.n_steps # v2: simulated-time budget is counted per attempt + + def _save_obs(self, tag): + """Same bytes as the GPT harness sends (JPEG q90). Under memory=none the file names carry no + attempt number, so a fresh agent cannot tell it is a retry; --hide-k names attempt 1 the same way.""" + from PIL import Image + paths = [] + for ref in self.ex.observe(label=tag): + name = (f"s{self.step:03d}_{ref.camera}.jpg" if self.a.memory == "none" or (self.k_shown < self.k and self.attempt == 1) + else f"a{self.attempt}_s{self.step:03d}_{ref.camera}.jpg") + Image.fromarray(ref.array).save(os.path.join(self.obs_dir, name), quality=90) + shutil.copy(os.path.join(self.obs_dir, name), os.path.join(self.log_dir, "images", f"a{self.attempt}_{name}")) + paths.append(f"obs/{name}") + if self.a.style == "la": + self.last_files = self._write_la_files(f"a{self.attempt}_s{self.step:03d}") + return paths + + def readme(self): + if self.a.style == "la": + return self.readme_la() + if self.a.style == "v2": + return self.readme_v2() + sp = self.pb.system_prompt() + sp = sp.replace("You act only by calling the provided tools, exactly one tool call per turn. Every action tool " + "returns an execution report; after each action you also receive new camera images and the " + "robot's proprioceptive state.", + "You act only through the `./robot` command in this directory (one robot command at a time). " + "Every action command prints an execution report and the paths of new camera images taken " + "after the action; look at them with your file-reading tool.") + sp = sp.replace("Finish by calling done(reason)", "Finish by running `./robot done reason=\"...\"`") + sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the " + "actions you executed and outcome feedback).", + "Each attempt ends when you run `./robot done`; that command prints the outcome feedback (if any) " + "and the images of the reset scene for the next attempt.") + sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the " + "actions you executed).", + "Each attempt ends when you run `./robot done`; that command prints the images of the reset " + "scene for the next attempt.") + sp = sp.replace("before your first tool call", "before your first robot command") + tools = "\n".join([ + " ./robot help this text", + " ./robot status task, current images and proprioception", + " ./robot observe take new images (agentview + wrist) + proprioception", + " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)", + " ./robot open_gripper | ./robot close_gripper", + " ./robot pixel_to_world camera=agentview|wrist u=.. v=.. (pixel -> 3-D point via depth)", + " ./robot done reason=\"...\" end the attempt / segment", + ] if self.a.perception == "depth" else [ + " ./robot help this text", + " ./robot status task, current images and proprioception", + " ./robot observe take new images (agentview + wrist) + proprioception", + " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)", + " ./robot open_gripper | ./robot close_gripper", + " ./robot done reason=\"...\" end the attempt / segment", + ]) + return ("# Robot task\n\n" + sp + "\n\n## Commands\n" + tools + + "\n\nArguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.\n" + "Images are written to obs/ inside this directory. After every action, look at the new images " + "before deciding on the next command.\n" + f"Each attempt allows at most {self.a.max_steps} robot commands (help/status not counted); after that " + "the attempt ends automatically.\n\n## TASK\n" + self.instruction() + "\n") + + def _write_sandbox(self): + os.makedirs(self.sandbox, exist_ok=True) + if self.a.style == "la": + with open(os.path.join(self.log_dir, "agent_iface.json"), "w") as f: + json.dump(dict(token=self.token, port=self.a.port, workspace=self.sandbox, agent_iface=self.a.agent_iface, + max_tool_calls=self.a.max_tool_calls, perception=self.a.perception), f) + with open(os.path.join(self.sandbox, "README.md"), "w") as f: + f.write(self.readme()) + if getattr(self.a, "dossier", ""): + shutil.copytree(self.a.dossier, os.path.join(self.sandbox, "history")) + if self.a.agent_iface == "cli": # coding-agent harness (Claude Code): ./robot + ./shell in the workspace + for name, body in (("robot", CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)), + ("shell", SHELL_TEMPLATE)): + with open(os.path.join(self.sandbox, name), "w") as f: + f.write(body) + os.chmod(os.path.join(self.sandbox, name), 0o755) + return + cli = os.path.join(self.sandbox, "robot") + with open(cli, "w") as f: + f.write(CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)) + os.chmod(cli, 0o755) + with open(os.path.join(self.sandbox, "README.md"), "w") as f: + f.write(self.readme()) + + def status(self): + if self.a.memory == "none": + return dict(task=self.instruction(), finished=self.finished) + st = dict(task=self.instruction(), protocol=self.protocol, attempt=self.attempt, max_attempts=self.k, + finished=self.finished) + if self.waiting_new_agent: + st["note"] = "The previous agent finished its attempt. A new attempt is ready; the scene has been reset." + return st + + # ------------------------------------------------------------------ dispatch + def handle(self, cmd, args): + if self.a.style in ("v2", "la"): + return self.handle_v2(cmd, args) + if cmd == "help": + return dict(text=self.readme()) + if cmd == "status": + st = self.status() + st["images"] = self._save_obs("status") + st.update(self.ex.proprio()) + self.waiting_new_agent = False + return st + if self.finished: + return dict(ok=False, error="The episode is over. Stop now.") + if self.waiting_new_agent: + return dict(ok=False, error="This attempt has ended. Stop now.") + if cmd in ("observe", "pixel_to_world", "move_to", "open_gripper", "close_gripper", "push"): + self.n_actions += 1 + if self.n_actions > self.a.max_steps: + rep = self._done("step budget exhausted (automatic)") + rep["note"] = f"The step budget of {self.a.max_steps} commands for this attempt was used up." + return rep + if cmd == "observe": + self.step += 1 + rep = dict(ok=True, images=self._save_obs("observe")) + rep.update(self.ex.proprio()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + if cmd == "done": + return self._done(args.get("reason", "")) + allowed = tuple(t for t in ACTION_TOOLS if t != "push" or self.a.allow_push) + if self.a.perception == "depth": + allowed += ("pixel_to_world",) + if cmd not in allowed: + return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help") + self.step += 1 + if self.video is not None: + argtxt = " ".join(f"{k}={v}" for k, v in args.items()) + self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}" + res = self.ex.call(cmd, args) + rep = dict(res.report) + if self.video is not None: + self.video.lines[1] = f" -> {_short(rep)}" + if cmd in ("close_gripper", "open_gripper"): + self.video.hold(1.2) + if res.ok and cmd in ACTION_TOOLS: + rep["images"] = self._save_obs(cmd) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, + wall_s=res.wall_s, sim_steps=res.sim_steps)) + return rep + + def _done(self, reason): + out = self.task.outcome(self.inst) + succ = bool(out["success"]) + fb = self.feedback_text(out) + self.history.append(dict(attempt=self.attempt, success=succ, feedback=fb, reason=reason)) + self.log(dict(ev="done", attempt=self.attempt, step=self.step, reason=reason, success=succ, feedback=fb, + outcome={k: v for k, v in out.items() if k != "feedback"})) + last = self.attempt >= self.k or succ or bool(out.get("terminal")) + if self.video is not None: + self.video.lines = [f"attempt {self.attempt}/{self.k}: done", f" reason: {reason}", ""] + self.video.hold(1.0) + self.video.card([f"Attempt {self.attempt}: {'SUCCESS' if succ else 'FAILED'}", + f"Commands used in this attempt: {self.n_actions}", "Agent's reason: " + str(reason)[:300], + "Feedback: " + (fb if self.a.memory != "none" and self.a.feedback != "F0" else "(not shown)")], + 3.5, (20, 50, 20) if succ else (60, 20, 20)) + if last: + self.video.close() + else: + self.video.lines = ["", "", ""] + if self.a.memory == "none": + # independent attempts: no feedback to the agent; orchestrator starts a fresh agent + if last: + self.finished = True + else: + self.attempt += 1 + self._start_attempt(reset=self.protocol == "cross") + self.waiting_new_agent = True + return dict(ok=True, ended=True, message="Attempt recorded. Stop now and report what you did.") + rep = dict(ok=True, ended=True) + if self.a.feedback != "F0": + rep["feedback"] = fb + if last and (succ or self.a.feedback != "F0"): + self.finished = True + rep["message"] = "The episode is over. Stop now and report." + return rep + if self.attempt >= self.k or out.get("terminal"): + self.finished = True + rep["message"] = ("The failure cannot be undone, so the episode is over. Stop now and report." + if out.get("terminal") else "No attempts left. The episode is over. Stop now and report.") + return rep + self.attempt += 1 + reveal = "" + if self.k_shown < self.k: # --hide-k: first failure, announce the extra attempts now + self.k_shown = self.k + reveal = f"You get more attempts than README.md says: up to {self.k} in total. " + if self.protocol == "cross": + self._start_attempt(reset=True) + rep["message"] = reveal + (f"Attempt {self.attempt} of {self.k} starts now. The scene has been reset to exactly the " + f"same initial state.") + else: + self._start_attempt(reset=False) + rep["message"] = reveal + (f"Continue from the current state (segment {self.attempt}; you may call done at most " + f"{self.k} times in total).") + self.step += 1 + rep["images"] = self._save_obs("attempt_start") + rep.update(self._la_files()) + if self.a.style in ("v2", "la"): + rep.update(self._state_v2()) + else: + rep.update(self.ex.proprio()) + return rep + + +V2_DROP = ("holding", "touched", "events", "sim_time_s", "tool", "reached", "yaw_used_deg", "target_clipped_to") + + +class _V2: + """Interface v2 (2026-10-07, aligned with LIBERO-Agent / RoboDojo-L3 at the user's request): + - priors: only the task instruction, the attempt rules, the budgets and the command definitions (no axes, + table height, camera orientation or robot geometry); + - observations: two RGB images published as files after every command + end-effector state (position, + yaw, gripper width) + how far the arm stopped from the commanded target + budget left; no + held/touched flags and no per-step task events; + - action: move_eef = absolute target (omitted coordinates keep their value; gripper after the motion; + optional speed); unreachable targets are rejected and the arm does not move; + - an attempt ends with `finish` (alias `done`) or when a budget runs out; the environment judges it.""" + + +def _readme_v2(self): + sec = self.sim_budget() + proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the " + f"same initial state." if self.protocol == "cross" else + f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a " + f"failed attempt you continue from the current state.") + return "\n".join([ + "# Robot task", "", + "You control a robot arm with a two-finger gripper in a physics simulation, only through the `./robot` " + "command in this directory (one command at a time).", "", + "## Task", self.instruction(), "", + "## Attempts", proto + " An attempt ends when you run `./robot finish reason=\"...\"` or when its budget " + "is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the last " + "attempt.", "", + "## Budget (per attempt)", + f"- at most {self.a.max_steps} robot commands (status and help are free);", + f"- at most {sec:.0f} s of simulated robot motion.", + "Every reply shows what is left.", "", + "## Observations", + "Every command writes two new camera images into obs/ and prints their paths: 'agentview' (a fixed camera " + "looking at the table) and 'wrist' (a camera on the gripper). It also reports the end-effector state: " + "eef_pos = [x, y, z] of the gripper's grasp point in metres, eef_yaw_deg = rotation of the gripper about " + "the vertical axis in degrees, gripper_width_m = opening of the fingers in metres, and after a motion how " + "far the gripper stopped from your target.", "", + "## Commands", + " ./robot status task, attempt, budget, current state and images", + " ./robot observe new images and state without moving", + " ./robot move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]", + " move the grasp point to an absolute target in the same frame as eef_pos (metres; yaw in degrees);", + " omitted coordinates keep their current value; the gripper command is executed after the motion;", + " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.", + " ./robot finish reason=\"...\" end the current attempt", + "", + "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""]) + + +def _sim_budget(self): + return 3.0 * self.a.max_steps # seconds of simulated motion per attempt + + +def _budget_left(self): + used = (self.task.sk.n_steps - self.sim0) * 0.05 + return dict(commands=max(self.a.max_steps - self.n_actions, 0), sim_seconds=round(max(self.sim_budget() - used, 0.0), 1)) + + +def _state_v2(self): + p = self.ex.proprio() + pos = p["eef_pos"] + if self.a.style == "la": + pos = [round(float(v), 4) for v in np.asarray(pos, float) - self.base_off] + st = dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"]) + if self.a.style == "la": # read-only joint angles, as LIBERO-Agent (all levels) and RoboDojo give them + st["joint_pos_rad"] = [round(float(v), 4) for v in self._believed_joints()] + st["budget_left"] = self._budget_left() + return st + + +def _clean_v2(rep): + return {k: v for k, v in rep.items() if not k.startswith(V2_DROP)} + + +def _handle_v2(self, cmd, args): + if cmd == "help": + return dict(text=self.readme()) + if cmd == "status": + st = dict(task=self.instruction(), attempt=self.attempt, max_attempts=self.k_shown, finished=self.finished) + st["images"] = self._save_obs("status") + st.update(self._la_files()) + st.update(self._state_v2()) + return st + if self.finished: + return dict(ok=False, error="The episode is over. Stop now.") + if cmd in ("finish", "done"): + return self._done(args.get("reason", "")) + if cmd not in ("observe", "move_eef"): + return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help") + self.n_actions += 1 + if self.n_actions > self.a.max_steps: + rep = self._done("command budget used up (automatic)") + rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up." + return rep + self.step += 1 + if cmd == "observe": + rep = dict(ok=True, images=self._save_obs("observe")) + rep.update(self._la_files()) + rep.update(self._state_v2()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + # ---------------- move_eef + p = self.ex.proprio() + unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"} + if unknown: + rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + off = self.base_off # zero except la (robot-base frame) + try: + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + yaw = float(args.get("yaw", p["eef_yaw_deg"])) + speed = None if args.get("speed") in (None, "") else float(args["speed"]) + except (TypeError, ValueError): + rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + grip = args.get("gripper") + if grip not in (None, "open", "close"): + rep = dict(ok=False, error="gripper must be open or close") + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + moving = any(k in args for k in ("x", "y", "z", "yaw")) + tgt_w = np.asarray(tgt) + off # simulator (world) frame + if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)): + rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move") + rep.update(self._state_v2()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep)) + return rep + if self.video is not None: + argtxt = " ".join(f"{k}={v}" for k, v in args.items()) + self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}" + left = self._budget_left()["sim_seconds"] + raw = {} + if moving: + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw) + if speed is not None: + mv["speed"] = speed + res = self.ex.call("move_to", mv) + raw.update(res.report) + if grip is not None: + res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}) + raw.update(res.report) + rep = dict(ok=bool(raw.get("ok", True))) + if raw.get("error"): + rep["error"] = raw["error"] + rep.update(self._state_v2()) + if moving: + err = np.asarray(tgt) - np.asarray(rep["eef_pos"]) + dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0 + rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1)) + if self.video is not None: + self.video.lines[1] = f" -> eef={rep['eef_pos']} width={rep['gripper_width_m']} {rep.get('stopped_from_target', '')}" + if grip is not None: + self.video.hold(1.2) + rep["images"] = self._save_obs(cmd) + rep.update(self._la_files()) + self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw)) + self._snap_regressions() + if rep["budget_left"]["sim_seconds"] <= 0 and left > 0: + fin = self._done("motion budget used up (automatic)") + fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up." + rep["attempt_ended"] = fin + return rep + + +LOSS_EVENTS = ("lost", "toppled", "tipped", "load_fell", "load_displaced") + + +def _snap_regressions(self): + """Save the simulator state right after a command during which the task monitor registered a loss of earlier + progress (lost / toppled / tipped / load_fell ...), for the "self-inflicted vs handed-over" experiment (docs/14 §6). + Server-side only: snapshots go to /snapshots/, never to the agent's workspace.""" + try: # bookkeeping only: it must never change what the agent gets back + self._snap_regressions_inner() + except Exception: + self.log(dict(ev="snapshot_error", error=traceback.format_exc()[-1500:])) + + +def _snap_regressions_inner(self): + mon = getattr(self.task, "mon", None) + evs = mon.get("events") if isinstance(mon, dict) else None + if not isinstance(evs, list): + return + new = evs[self.n_mon_events:] + self.n_mon_events = len(evs) + loss = [e for e in new if isinstance(e, dict) and str(e.get("ev", e.get("event", ""))) in LOSS_EVENTS] + if not loss: + return + import copy + d = os.path.join(self.log_dir, "snapshots") + os.makedirs(d, exist_ok=True) + name = f"a{self.attempt}_s{self.step:03d}" + try: + flat = np.asarray(self.task.env.sim.get_state().flatten(), float) + except Exception: # keep the run going even if a simulator binding lacks get_state + flat = np.concatenate([self.task.env.sim.data.qpos, self.task.env.sim.data.qvel]).astype(float) + np.save(os.path.join(d, name + "_sim.npy"), flat) + meta = dict(attempt=self.attempt, step=self.step, n_actions=self.n_actions, sim_steps=int(self.task.sk.n_steps - self.sim0), + loss_events=loss, mon=copy.deepcopy(mon)) + def _dflt(o): # task monitors keep sets (ever / lost / lid_hits ...) + return sorted(o, key=str) if isinstance(o, (set, frozenset)) else _json_default(o) + with open(os.path.join(d, name + "_meta.json"), "w") as f: + json.dump(meta, f, default=_dflt) + self.log(dict(ev="regression_snapshot", attempt=self.attempt, step=self.step, file=f"snapshots/{name}", n_loss=len(loss))) + + +def _la_files(self): + """la: paths of the non-image observation files written with the last images (empty for other styles).""" + return dict(self.last_files) if self.a.style == "la" and getattr(self, "last_files", None) else {} + + +def _believed_pose(self): + """4x4 pose of the grasp point as the ROBOT believes it (the frame of eef_pos / move_eef): the true pose shifted by + the task's hidden calibration errors (Skills.bias, and YawSkills.yaw_bias about the vertical axis). A real robot + computes its wrist-camera pose from its own (miscalibrated) kinematics, so the wrist calibration uses this pose.""" + sk = self.task.sk + beta = float(getattr(sk, "yaw_bias", 0.0)) + c, s_ = np.cos(-beta), np.sin(-beta) + Rz = np.array([[c, -s_, 0.0], [s_, c, 0.0], [0.0, 0.0, 1.0]]) + T_true = np.eye(4) + T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos() + T_b = np.eye(4) + T_b[:3, :3], T_b[:3, 3] = Rz @ sk.eef_mat(), sk.eef_pos() - np.asarray(sk.bias, float) + return T_b, T_true + + +def _believed_joints(self, iters=30): + """The 7 arm joint angles as the robot's encoders report them. For tasks with a hidden calibration error (L1) these + are the angles consistent with the robot's own belief: standard forward kinematics of them gives exactly the + reported (believed) grasp pose, as on a real arm whose encoder offsets are miscalibrated; true joint angles would + hand the hidden error to anyone who runs the public Franka kinematics. Without a calibration error they are the true + angles. Solved by damped least squares on a scratch copy of the simulator state (2-3 iterations).""" + import mujoco + env, sk = self.task.env, self.task.sk + rob = env.robots[0] + idx, dof, site = np.array(rob._ref_joint_pos_indexes), np.array(rob._ref_joint_vel_indexes), rob.eef_site_id + m, d0 = env.sim.model._model, env.sim.data._data + T_b, _ = self._believed_pose() + 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)): + return d0.qpos[idx].copy() + d = mujoco.MjData(m) + d.qpos[:] = d0.qpos + jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv)) + for _ in range(iters): + mujoco.mj_kinematics(m, d) + mujoco.mj_comPos(m, d) + ep = T_b[:3, 3] - d.site_xpos[site] + Re = T_b[:3, :3] @ d.site_xmat[site].reshape(3, 3).T + er = 0.5 * np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]]) + if np.linalg.norm(ep) < 1e-7 and np.linalg.norm(er) < 1e-7: + break + mujoco.mj_jacSite(m, d, jp, jr, site) + J = np.vstack([jp[:, dof], jr[:, dof]]) + d.qpos[idx] += J.T @ np.linalg.solve(J @ J.T + 1e-6 * np.eye(6), np.concatenate([ep, er])) + return d.qpos[idx].copy() + + +def _write_la_files(self, prefix): + """la observation files besides the two JPEGs: _state.json always; with --perception rgbd also metric + depth for both cameras (__depth.npy, float32 metres along the optical axis, same upright pixels as + the JPEG) and _camera.json (K and cam_to_world in the eef_pos frame, OpenCV camera axes). + The fixed agentview camera is calibrated in the true frame; the wrist camera pose is computed from the robot's + believed gripper pose (so neither file reveals the hidden calibration error of the L1 tasks).""" + out = {} + st = self._state_v2() + st = dict(eef_pos=st["eef_pos"], eef_yaw_deg=st["eef_yaw_deg"], gripper_width_m=st["gripper_width_m"], + joint_pos_rad=st["joint_pos_rad"], attempt=self.attempt, step=self.step) + with open(os.path.join(self.obs_dir, f"{prefix}_state.json"), "w") as f: + json.dump(st, f, default=_json_default) + out["state_file"] = f"obs/{prefix}_state.json" + if self.a.perception == "rgbd": + res = self.a.image_res + cams, depth_files = {}, [] + T_b, T_true = self._believed_pose() + for cam in ("agentview", "wrist"): + d = C.render_depth(self.task.env, cam, res).astype(np.float32) + np.save(os.path.join(self.obs_dir, f"{prefix}_{cam}_depth.npy"), d) + depth_files.append(f"obs/{prefix}_{cam}_depth.npy") + E = C.cam_to_world(self.task.env, cam) + if cam == "wrist": + E = T_b @ np.linalg.inv(T_true) @ E + E = E.copy() + E[:3, 3] -= self.base_off # robot-base frame + cams[cam] = dict(K=np.round(C.intrinsics(self.task.env, cam, res), 6).tolist(), + cam_to_base=np.round(E, 6).tolist(), width=res, height=res) + with open(os.path.join(self.obs_dir, f"{prefix}_camera.json"), "w") as f: + json.dump(cams, f) + out["depth_files"] = depth_files + out["camera_file"] = f"obs/{prefix}_camera.json" + return out + + + +def _fb_sentence(level): + """README sentence for the feedback level. F1 (default since 2026-10-08): success / failure only, like + LIBERO-Agent's finish_episode outcome; F2 (measured error, e.g. "2.5 cm past the centre") is privileged + simulator information that neither LIBERO-Agent nor RoboDojo gives, kept only as an ablation.""" + return {"F0": "The environment then checks the result.", + "F1": "The environment then checks the result and tells you only whether the attempt succeeded.", + "F2": "The environment then checks the result and tells you whether the attempt succeeded and, if not, " + "what went wrong."}[level] + +def _readme_la(self): + """LIBERO-Agent-style instructions: the agent works in an episode workspace (observations are files, it can run + programs on them); the robot itself is driven only through the harness's `robot` tool.""" + sec = self.sim_budget() + rgbd = self.a.perception == "rgbd" + cli = self.a.agent_iface == "cli" + pre = "./robot " if cli else "" + proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the " + f"same initial state." if self.protocol == "cross" else + f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a " + f"failed attempt you continue from the current state.") + files = [ + "- obs/a_s_agentview.jpg and obs/a_s_wrist.jpg: 512x512 RGB images from " + "'agentview' (a fixed camera looking at the table) and 'wrist' (a camera on the gripper);", + "- obs/a_s_state.json: the end-effector state: eef_pos = [x, y, z] of the gripper's grasp " + "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 " + "of the fingers in metres, joint_pos_rad = the 7 arm joint angles (radians, base to wrist; read-only).", + ] + if rgbd: + files += [ + "- obs/a_s_agentview_depth.npy and obs/a_s_wrist_depth.npy: metric depth " + "(numpy float32 array, 512x512, metres along each camera's optical axis), pixel-aligned with the images " + "(row 0 = top of the image);", + "- obs/a_s_camera.json: for each camera, K (3x3 intrinsics of the 512x512 image) and " + "cam_to_base (4x4 pose of the camera in the robot-base frame; camera axes: x right, y down, z forward).", + ] + return "\n".join([ + "# Robot task", "", + "You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics " + "simulation.", "", + "## Task", self.instruction(), "", + "## Attempts", proto + f" An attempt ends when you run the robot command `{pre}finish reason=\"...\"` or when its " + "budget is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the " + "last attempt.", "", + *(["## Earlier attempt", + "Before this episode, an earlier attempt at this task, starting from a scene that looked the same as yours, " + "failed. Its record is in history/: history/README.md lists every robot command of that attempt with the " + "robot's reply and its closing remark, and history/obs/ holds the camera images it produced.", ""] + if getattr(self.a, "dossier", "") else []), + "## Budget (per attempt)", + f"- at most {self.a.max_steps} robot commands (status and help are free);", + f"- at most {sec:.0f} s of simulated robot motion;", + *([] if cli else [f"- at most {self.a.max_tool_calls} tool calls in total (robot, shell and view_image together)."]), + "Every robot reply shows the robot budgets that are left.", "", + "## Coordinates", + "Coordinates are expressed in the robot-base frame and measured in metres; angles are in degrees.", "", + "## Workspace and observations", + "This directory is your workspace for the whole episode. Every robot command writes its observation into " + "obs/ and prints the paths of the new files:", + *files, + "Robot replies also include the end-effector state and, after a motion, how far the gripper stopped from your " + "target. " + ("You can look at any image with your file-reading tool, run shell commands and programs in this " + "workspace with `./shell ''` (python3 with numpy, scipy, Pillow and OpenCV; no network; " + "programs cannot control the robot), and keep your own files and notes in this directory; they " + "persist across attempts." if cli else + "You can look at any image with view_image, run shell commands and programs here (python3 with " + "numpy, scipy, Pillow and OpenCV; no network; programs cannot control the robot), and keep your " + "own files and notes in this directory; they persist across attempts."), "", + "## Robot commands " + ("(run from this directory as `./robot `, one command at a time)" if cli + else "(argument of the `robot` tool)"), + f" {pre}status task, attempt, budget, current state and observation files", + f" {pre}observe new observation without moving", + f" {pre}move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]", + " move the grasp point to an absolute target (robot-base frame, metres; yaw in degrees);", + " omitted coordinates keep their current value; the gripper command is executed after the motion;", + " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.", + f" {pre}finish reason=\"...\" end the current attempt", + "", + "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""]) + + +for _n, _f in (("_believed_joints", _believed_joints), ("readme_la", _readme_la), ("_la_files", _la_files), ("_believed_pose", _believed_pose), + ("_write_la_files", _write_la_files), ("readme_v2", _readme_v2), ("sim_budget", _sim_budget), ("_budget_left", _budget_left), + ("_state_v2", _state_v2), ("handle_v2", _handle_v2), ("_snap_regressions", _snap_regressions), + ("_snap_regressions_inner", _snap_regressions_inner)): + setattr(RobotSession, _n, _f) +RobotSession._clean_v2 = staticmethod(_clean_v2) + + +def serve(a): + sess = RobotSession(a) + + class H(BaseHTTPRequestHandler): + def log_message(self, *x): + pass + + def do_POST(self): + t_recv = time.time() + cmd = "" + try: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + cmd = body.get("cmd", "") + if self.headers.get("X-Token") != sess.token: + rep = dict(ok=False, error="unauthorised") + else: + rep = sess.handle(cmd, body.get("args", {}) or {}) + except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent + sess.log(dict(ev="error", error=traceback.format_exc())) + rep = dict(ok=False, error=f"internal error: {type(e).__name__}") + data = json.dumps(rep, default=_json_default, indent=None).encode() + if "text" in rep: + data = rep["text"].encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(data) + t_send = time.time() + # think time = gap between the previous reply and this request (model inference + its own tool overhead) + sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send, + server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None)) + sess.last_send = t_send + + def _term(*_): + if sess.video is not None: + sess.video.close() + os._exit(0) + + signal.signal(signal.SIGTERM, _term) + srv = HTTPServer(("127.0.0.1", a.port), H) + print(f"robot server ready on 127.0.0.1:{a.port} sandbox={sess.sandbox} log={sess.log_dir}", flush=True) + with open(os.path.join(sess.log_dir, "READY"), "w") as f: + f.write(str(os.getpid())) + srv.serve_forever() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--seed", type=int, required=True) + ap.add_argument("--k", type=int, default=None) + ap.add_argument("--memory", default="full", choices=["full", "none"]) + ap.add_argument("--hide-k", action="store_true", + help="memory=full: README/status say 1 attempt (same as an independent k=1 run); the remaining " + "attempts are announced only after a failed attempt") + ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"]) + ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"]) + ap.add_argument("--image-res", type=int, default=512) + ap.add_argument("--port", type=int, default=8765) + ap.add_argument("--sandbox", required=True) + ap.add_argument("--log-dir", required=True) + ap.add_argument("--max-steps", type=int, default=None, + help="robot commands per attempt (default: the task's agent_max_steps, else 40)") + ap.add_argument("--allow-push", action="store_true", help="expose the composite push primitive (off by default)") + ap.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"], + help="rgb: images only (no pixel_to_world / depth); depth: adds the depth back-projection tool " + "(v1); rgbd (la): also writes metric depth and camera calibration files") + ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"], + help="v2: LIBERO-Agent / RoboDojo-aligned interface (see _V2); la: v2 + LIBERO-Agent workspace " + "(observation files, programs in the workspace, robot only through the harness tool)") + ap.add_argument("--nominal", action="store_true", + help="control: remove the hidden calibration error of an L1 task (bias / yaw_bias = 0)") + ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"], + help="la: tools = harness tools (robot / shell / view_images, our GPT driver); cli = ./robot and " + "./shell in the workspace for a coding agent such as Claude Code") + ap.add_argument("--max-tool-calls", type=int, default=100, + help="la: tool calls per attempt (robot + shell + view_image), enforced by the harness") + ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"], + help="full5 controlled arms (lffbench/arm_specs/.py): h0 = hidden variable at its ordinary value; " + "hplus = hidden variable stated in the instruction; twin = mismatched-history source instance") + ap.add_argument("--dossier", default="", + help="la: copy this directory into the workspace as history/ (record of an earlier failed attempt, " + "made by scripts/make_dossier.py) and say so in README.md") + ap.add_argument("--video", default="", help="record agentview|wrist mp4 to this path") + ap.add_argument("--video-every", type=int, default=3, help="one frame every N control steps (20 Hz)") + ap.add_argument("--video-fps", type=int, default=20) + serve(ap.parse_args()) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/base.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/base.py new file mode 100644 index 0000000000000000000000000000000000000000..76d950990151f8a0f38718909be11e6792cfb431 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/base.py @@ -0,0 +1,364 @@ +"""Harness adapter interface (docs/15 §3). + +An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log +dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations). +Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server / +reference driver enforce them identically for every harness. + + name stable harness name (the "harness" column of a table) + capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source; + a missing item makes the class definition fail (so the import fails) + version() the actual installed version (probed before launch) + prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env + launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle + collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason + audit(h) tool list, preset prompt, memory, state left behind, violations +""" +import dataclasses +import json +import os +import secrets +import shutil +import signal +import subprocess +import time + +from . import contract as C + +EVIDENCE = ("launch", "stream", "server", "probe", "preflight") + +REQUIRED = { + "only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use", + "images_reach_model": "view_images returns the image bytes to the model unchanged", + "non_persistent_session": "nothing of the session is written to disk for later runs", + "pinned_version": "the harness version (and binary hash) is recorded and pinned", + "machine_readable_events": "a machine-readable event stream of the whole run", + "tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)", + "model_and_effort": "model and reasoning effort can be set and are visible in the request", +} +FORBIDDEN = { + "persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)", + "instruction_file_injection": "instruction files picked up from the work / config / home dir", + "web_access": "web search / fetch", + "host_file_read": "reading host files outside the episode workspace", + "builtin_shell": "a shell of the harness itself (outside our jailed shell tool)", + "subagent_delegation": "spawning sub-agents", + "background_execution": "background tasks that outlive a tool call", +} + + +@dataclasses.dataclass(frozen=True) +class Cap: + status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial" + evidence: str # one of EVIDENCE + note: str = "" + + +PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy") +NO_PROXY_KEYS = ("NO_PROXY", "no_proxy") +NO_PROXY_LOCAL = "127.0.0.1,localhost,::1" + + +def proxy_env(environ=None): + """The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines + that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list. + Not part of config_sha256 (machine plumbing, not harness configuration).""" + environ = os.environ if environ is None else environ + e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)} + if e: + e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS}) + return e + + +class CapabilityError(TypeError): + pass + + +def check_capabilities(name, caps): + if not isinstance(caps, dict): + raise CapabilityError(f"{name}: capabilities must be a dict") + missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps] + extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN] + if missing or extra: + raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}") + for k, c in caps.items(): + if not isinstance(c, Cap) or c.evidence not in EVIDENCE: + raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})") + ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial") + if c.status not in ok: + raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}") + + +class HarnessRefused(RuntimeError): + """Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one.""" + + +@dataclasses.dataclass +class EpisodeSpec: + session_path: str + log_dir: str + sandbox: str + port: int + token: str + max_tool_calls: int + model: str + effort: str + provider: str = "" + task: str = "" + seed: int = 0 + extra: dict = dataclasses.field(default_factory=dict) + + @classmethod + def from_session(cls, session_path, model, effort, provider="", **extra): + session_path = os.path.abspath(session_path) + log_dir = os.path.dirname(session_path) + sess = json.load(open(session_path)) + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + st = C.session_start(log_dir) + return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]), + token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort, + provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra) + + +@dataclasses.dataclass +class LaunchSpec: + argv: list # full argv (the first message may be one element) + env: dict # the complete environment of the harness process (nothing else is inherited) + cwd: str + run_dir: str = "" # one-time dir tree, removed after audit + state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...) + first_message: str = "" + config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote + stdout_path: str = "" + stderr_path: str = "" + redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log + preflight: dict = dataclasses.field(default_factory=dict) + timeout_s: float = 10800 + + +@dataclasses.dataclass +class RunHandle: + spec: LaunchSpec + ep: EpisodeSpec + proc: object = None + pid: int = 0 + t_start: float = 0.0 + t_end: float = 0.0 + exit_code: int = None + exit_reason: str = "" + env_observed_keys: list = None # read from /proc//environ right after the start + info: dict = dataclasses.field(default_factory=dict) + + +def env_keys_of(pid): + try: + raw = open(f"/proc/{pid}/environ", "rb").read() + except OSError: + return None + return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv}) + + +def new_run_dir(root="/tmp/lffrun"): + """/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses).""" + os.makedirs(root, exist_ok=True) + while True: + d = os.path.join(root, secrets.token_hex(6)) + try: + os.mkdir(d, 0o700) + return d + except FileExistsError: + continue + + +def binary_info(path): + real = os.path.realpath(path) + return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None) + + +class HarnessAdapter: + name = None + capabilities = None + uses_mcp = False + uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for + # this adapter: MCP adapters through the MCP server, framework adapters + # (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN + clean_dirs = () # keys of spec.state_dirs that must be empty at launch + clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json) + ancestor_files = () # instruction files that must not exist in the work dir or any ancestor + unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read) + jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4) + can_resume = False # resume(): the CLI can continue its session with one more user message + + def clean_state_problems(self, spec): + """Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an + ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md).""" + p = [] + if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd): + p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}") + for k in self.clean_dirs: + d = spec.state_dirs.get(k) + 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 [] + if left: + p.append(f"{k} dir not empty: {sorted(left)[:5]}") + d = spec.cwd + while d and d != "/": + d = os.path.dirname(d) + for f in self.ancestor_files: + if os.path.exists(os.path.join(d, f)): + p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}") + return p + + def __init_subclass__(cls, **kw): + super().__init_subclass__(**kw) + if cls.name is None: + raise CapabilityError(f"{cls.__name__}: no name") + check_capabilities(cls.name, cls.capabilities) + + # -------------------------------------------------------------------------------------------- interface + def version(self): + raise NotImplementedError + + def prepare(self, ep, first_message): + raise NotImplementedError + + def preflight(self, spec, ep): + """Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused.""" + return dict(skipped=True) + + def collect(self, h): + raise NotImplementedError + + def audit(self, h): + raise NotImplementedError + + # -------------------------------------------------------------------------------------------- shared + def mcp_server_command(self, python, script, args): + """(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it.""" + if self.jail is not None: + return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"}) + return python, [script] + list(args) + + def jailed_argv(self, argv, env, cwd, dirs): + """argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back.""" + return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv) + + def jail_info(self): + return self.jail.info() if self.jail is not None else dict(enabled=False) + + def auth_info(self): + """How the harness authenticates to the model API (for harness.json; never a secret).""" + return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {})) + + def launch(self, spec, ep, skip_preflight=False): + if not self.unsafe_skip_clean_check: + probs = self.clean_state_problems(spec) + if probs: + spec.preflight = dict(problems=probs) + raise HarnessRefused("clean-state check: " + "; ".join(probs)) + spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep) + out = open(spec.stdout_path, "wb") + err = open(spec.stderr_path, "wb") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir]) + h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out, + stderr=err, start_new_session=True) + h.pid = h.proc.pid + for _ in range(20): # the exec has happened once /proc//environ differs from ours + keys = env_keys_of(h.pid) + if keys is not None and set(keys) == set(spec.env): + break + time.sleep(0.05) + h.env_observed_keys = env_keys_of(h.pid) + return h + + def resume_argv(self, h, message): + """argv that continues the run's session with one more user message (adapters with can_resume).""" + raise NotImplementedError + + def resume(self, h, message): + """Continue the run's session with one more user message, after the CLI exited before the episode was over + (scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output + is appended to the same stdout / stderr files.""" + spec = h.spec + argv = self.resume_argv(h, message) + out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab") + jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir]) + h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out, + stderr=err, start_new_session=True) + h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, "" + keys = None + for _ in range(20): + keys = env_keys_of(h.pid) + if keys is not None and set(keys) == set(spec.env): + break + time.sleep(0.05) + h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message, + argv=[("" if x == message else x) for x in argv], + env_observed_keys=keys)) + return h + + def wait(self, h, timeout=None): + try: + h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s) + h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}" + except subprocess.TimeoutExpired: + self.kill(h) + h.exit_reason = "timeout" + h.t_end = time.time() + return h + + @staticmethod + def kill(h): + try: + os.killpg(h.proc.pid, signal.SIGTERM) + h.exit_code = h.proc.wait(timeout=20) + except ProcessLookupError: + pass + except subprocess.TimeoutExpired: + os.killpg(h.proc.pid, signal.SIGKILL) + h.exit_code = h.proc.wait() + + def logged_argv(self, spec): + return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)] + + def cleanup(self, spec): + if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir): + shutil.rmtree(spec.run_dir, ignore_errors=True) + for d in spec.state_dirs.values(): + if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d): + shutil.rmtree(d, ignore_errors=True) + if self.jail is not None: + self.jail.close() + + +def gateway_env(log_dir): + """{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose + process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before + launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the + gateway's, never robot_server's.""" + d = json.load(open(os.path.join(log_dir, "gateway.json"))) + return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]} + + +def snapshot_tree(root): + """Relative paths of all files under root (to list what a harness left behind).""" + out = [] + for dp, dn, fn in os.walk(root): + for f in fn: + out.append(os.path.relpath(os.path.join(dp, f), root)) + return sorted(out) + + +def first_message_text(readme, status_json): + """What a native harness gets as its first user message: the reference driver's instructions (preamble + README, + byte-identical) followed by its first user turn (the status report). The reference driver sends the same two + strings as system prompt and first user message; native harnesses keep their own system prompt.""" + from .contract import tool_schemas + _, preamble = tool_schemas() + return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json + + +def reference_instructions(readme): + from .contract import tool_schemas + _, preamble = tool_schemas() + return preamble + readme diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/codex.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/codex.py new file mode 100644 index 0000000000000000000000000000000000000000..ed72b09ba59f5d0341540a896f20caa44581b83a --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/codex.py @@ -0,0 +1,687 @@ +"""Codex CLI as a native harness (arm F; flags measured in research_notes/harness接入调研/02 §2.3, Codex 0.156). + +Launch: process env exactly the whitelist (env -i equivalent), a brand-new empty CODEX_HOME and HOME (one-time, under +/tmp/lffstate/), work dir /tmp/lffrun/<12 hex>, `codex exec --json --skip-git-repo-check --ignore-user-config +--ignore-rules -s read-only`, ~20 features disabled, project docs / permissions / environment context / +collaboration-mode / skills instructions off, web search off, and only our MCP server with +default_tools_approval_mode="approve" (otherwise exec mode silently denies MCP calls). + +Early exit: `codex exec` ends when the model replies without a tool call, also when the episode is not over (measured +2026-10-19, cx_pilot6b: gpt-6-astra stopped after a failed first attempt, "I stopped after the one authorized +attempt", although the finish reply said attempt 2 of 3 starts now). scripts/harness_run.py then sends the reference +driver's nudge as a user turn with `codex exec resume ` (resume_argv), at most api_player.MAX_NO_TOOL times in +a row. Hence no --ephemeral: the session is kept in the one-time CODEX_HOME (memories off; removed after the run). +Measured with 0.163 against the fake server: the resumed request has the same developer messages, tools, model and +parameters as the first, then the earlier turns and the nudge as a user message. + +The model API is a custom Responses provider "lffapi", so the preflight can point exactly the same config at a local +fake server by changing only base_url. Two ways to authenticate (auth=): + apikey env_key OPENAI_API_KEY (api_env), default endpoint the official API + chatgpt a ChatGPT subscription login (no API key; same as RPent's codex planner reusing `codex login`): the + provider gets requires_openai_auth=true (requests carry the login's bearer + chatgpt-account-id), default + endpoint the ChatGPT Codex backend; a copy of auth.json from the source CODEX_HOME is put into the one-time + CODEX_HOME (the only file allowed there at launch). If Codex refreshes the login during a run, the refreshed + auth.json is written back to the source (refresh tokens rotate), unless the source changed meanwhile. + Launch is refused when the source login is close to its refresh (parallel copies would each rotate it). +Measured with 0.163 against the fake server: same body keys and headers in both modes plus chatgpt-account-id; the +preset differs (exec tool description), so pins are per auth mode (pin name codex-chatgpt). +The calling environment's HTTP(S) proxy is passed through (base.proxy_env; NO_PROXY = loopback only). + +Model configuration (catalog=, user 2026-10-20): Codex picks the system prompt, tool form and context window per +model from its model catalog. We always pass an explicit model_catalog_json written into the one-time CODEX_HOME, so +nothing depends on the catalog the subscription backend serves on the day: + generic (main table, every model) one entry built from codex_catalogs/generic_.json: what Codex sends for a + model it has no entry for (its generic Codex CLI prompt, plain function tools, no code mode); per model only + slug, input modalities and reasoning levels. Measured with 0.163 against the fake server: the request equals + the no-catalog fallback for an unknown slug apart from message ids. + native (control) codex_catalogs/native_.json = `codex debug models --bundled` of that binary: the request + equals the one without any catalog (GPT: code mode, its own prompt). The pins of before 10-20 stay valid. +Pins are per catalog (pin name codex[-chatgpt][-generic]). + +Known, accepted differences in native (code mode) catalogs (reported, not fixable by config in 0.156): + - code mode: the model sees one `exec` tool (JavaScript in a V8 isolate without fs / network); our tools are nested + and listed only in ALL_TOOLS; MCP images reach the model only if the model's JS calls image(...) + - apply_patch (blocked by the read-only sandbox), clock, 3 MCP-resource tools (our server has no resources), + request_user_input, and 6 collaboration.* sub-agent tools cannot be removed; a sub-agent call is an audit violation + - --json has tokens but no dollar cost +Fail-closed launch: the preflight checks the top-level tools, the exec nested-tool list (ALL_TOOLS, printed by a +scripted exec call), the developer (preset) messages and request parameters against the pin. +""" +import base64 +import datetime +import fcntl +import json +import os +import re +import shutil +import sqlite3 +import subprocess +import sys +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + new_run_dir, proxy_env, snapshot_tree) +from .fakeapi import FakeResponses +from .trajectory import TrajWriter + +ROOT = C.ROOT +MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py") +BASE_PATH = "/usr/bin:/bin" +OFFICIAL_API = "https://api.openai.com/v1" +CHATGPT_BACKEND = "https://chatgpt.com/backend-api/codex" +AUTH_FILE = "auth.json" +AUTH_LOCK = "/tmp/lffstate/.codex_auth.lock" +MAX_LOGIN_AGE_H = 8 * 24 # codex-rs TOKEN_REFRESH_INTERVAL (8 days, from the source, not measured here): a login + # older than this is refreshed at start, by every parallel copy +MIN_ACCESS_LEFT_H = 24 # an access token expiring during a run makes the run's copy refresh it + + +def _jwt_claims(tok): + try: + p = tok.split(".")[1] + return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4))) + except (IndexError, ValueError, AttributeError): + return {} + + +def chatgpt_login_status(home): + """-> dict(ok, problem, last_refresh_h, access_token_valid_h) of the ChatGPT login in home/auth.json. No secret + leaves this function.""" + src = os.path.join(home, AUTH_FILE) + try: + with open(src) as f: + a = json.load(f) + except (OSError, ValueError) as e: + return dict(ok=False, problem=f"cannot read {src}: {type(e).__name__}") + tok = a.get("tokens") or {} + if a.get("auth_mode") != "chatgpt" or not tok.get("access_token") or not tok.get("refresh_token"): + return dict(ok=False, problem=f"{src} is not a ChatGPT login (auth_mode={a.get('auth_mode')!r})") + now = time.time() + try: + lr = datetime.datetime.fromisoformat(str(a.get("last_refresh")).replace("Z", "+00:00")).timestamp() + age_h = (now - lr) / 3600 + except ValueError: + age_h = float("inf") + left_h = (float(_jwt_claims(tok["access_token"]).get("exp") or 0) - now) / 3600 + out = dict(ok=True, problem=None, last_refresh_h=round(age_h, 1), access_token_valid_h=round(left_h, 1)) + if age_h >= MAX_LOGIN_AGE_H or left_h < MIN_ACCESS_LEFT_H: + out.update(ok=False, problem=f"the ChatGPT login in {home} is due for a refresh (last refresh {age_h:.0f} h ago, " + f"access token valid {left_h:.0f} h): refresh it once outside the benchmark (use " + f"codex with CODEX_HOME={home}), so that parallel runs do not each rotate it") + return out +DISABLE = ["shell_tool", "unified_exec", "view_image", "multi_agent", "multi_agent_v2", "apps", "browser_use", + "browser_use_external", "computer_use", "image_generation", "plugins", "hooks", "skill_search", + "tool_suggest", "goals", "sleep_tool", "in_app_browser", "memories", "skill_mcp_dependency_install", + "realtime_conversation"] +# what remains in 0.156 after the lock-down (measured): anything else is refused at launch +EXPECTED_TOP = ["collaboration.followup_task", "collaboration.interrupt_agent", "collaboration.list_agents", + "collaboration.send_message", "collaboration.spawn_agent", "collaboration.wait_agent", + "functions.exec", "functions.request_user_input", "functions.request_user_input_async", + "functions.wait"] +EXPECTED_ALL_TOOLS = ["apply_patch", "clock__curr_time", "list_mcp_resource_templates", "list_mcp_resources", + "mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images", "read_mcp_resource"] +# generic catalog (no code mode), measured with 0.163: our tools are plain functions in the mcp__lff namespace +EXPECTED_TOP_GENERIC = ["list_mcp_resource_templates", "list_mcp_resources", "mcp__lff.robot", "mcp__lff.shell", + "mcp__lff.view_images", "read_mcp_resource", "request_user_input"] +CATALOG_DIR = os.path.join(ROOT, "lffbench", "harnesses", "codex_catalogs") +CATALOG_FILE = "lff_model_catalog.json" # written into the one-time CODEX_HOME before launch +CATALOGS = ("generic", "native") +# generic catalog: the per-model fields (input modalities; the run's reasoning level is always listed) +TEXT_ONLY_MODELS = {"deepseek-v4-pro": ["text"]} # DeepSeek's Codex guide (read 2026-10-20): v4-pro takes no images +DEEPSEEK_URL = "https://api.deepseek.com/" # same guide: base_url, wire_api = "responses" +OPENCODE_GO_URL = "https://opencode.ai/inference/go/openai/v1" # OpenCode Go, Responses API (checked 2026-10-29) +MCP_TOOLS = ["robot", "shell", "view_images"] +OK_ITEMS = ("agent_message", "reasoning", "mcp_tool_call", "error") +PREFLIGHT_JS = "text(JSON.stringify(ALL_TOOLS));" + + +def codex_bin(): + return os.environ.get("LFF_CODEX_BIN") or shutil.which("codex") or "codex" + + +def toml_str(s): + return json.dumps(s) # a JSON string literal is a valid TOML basic string + + +def _norm(s, cwd): + s = s.replace(cwd, "") + s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "", s) + s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "", s) + s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "", s) + 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", "", s) + return s + + +def _walk_tools(ts, prefix=""): + out = [] + for t in ts or []: + if t.get("type") == "namespace": + out += _walk_tools(t.get("tools"), prefix + t.get("name", "") + ".") + else: + out.append(dict(name=prefix + (t.get("name") or t.get("type") or "?"), type=t.get("type"), + description=t.get("description"), parameters=t.get("parameters"), format=t.get("format"))) + return out + + +def request_fingerprint(body, cwd, first_message, expected_top=None): + problems = [] + items = body.get("input") or [] + top = _walk_tools(body.get("tools")) + dev, users = [], [] + for it in items: + if it.get("type") == "additional_tools": + top += _walk_tools(it.get("tools")) + elif it.get("type") == "message" and it.get("role") in ("developer", "system"): + dev.append(_norm("\n".join(c.get("text", "") for c in it.get("content") or []), cwd)) + elif it.get("type") == "message" and it.get("role") == "user": + users.append(it) + names = sorted(t["name"] for t in top) + expected_top = EXPECTED_TOP if expected_top is None else expected_top + if names != expected_top: + problems.append(f"top-level tools {names} != expected {expected_top}") + texts = [c.get("text") for u in users for c in u.get("content") or []] + if texts != [first_message]: + problems.append(f"user input is not exactly our first message ({len(texts)} user text blocks)") + for t in top: + if t.get("description"): + t["description"] = _norm(t["description"], cwd) + params = {k: body.get(k) for k in ("model", "reasoning", "parallel_tool_calls", "store", "include", "text", + "tool_choice", "instructions", "max_output_tokens", "temperature")} + meta = body.get("client_metadata") or {} + try: + turn_meta = json.loads(meta.get("x-codex-turn-metadata") or "{}") + except ValueError: + turn_meta = {} + sandbox = {k: turn_meta.get(k) for k in ("sandbox", "sandbox_mode")} + if sandbox.get("sandbox_mode") != "read-only": + problems.append(f"sandbox {sandbox}") + fp = dict(tools=sorted(top, key=lambda t: t["name"]), developer=dev, params=params, sandbox=sandbox, + developer_chars=sum(len(d) for d in dev)) + return fp, problems + + +def model_catalog(mode, version, model, modalities=None, effort=None): + """-> (catalog dict for model_catalog_json, source file). Refuses (fail-closed) when the version has no catalog + file or, for native, when the model has no entry.""" + if mode not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}, not {mode!r}") + src = os.path.join(CATALOG_DIR, f"{mode}_{version}.json") + if not os.path.exists(src): + raise HarnessRefused(f"no {mode} model catalog for Codex {version} ({os.path.relpath(src, ROOT)})") + d = json.load(open(src)) + if mode == "native": + if not any(m.get("slug") == model for m in d.get("models") or []): + raise HarnessRefused(f"native catalog {os.path.basename(src)} has no entry for {model}") + return d, src + e = dict(d["entry"], slug=model, display_name=model) + modalities = modalities or TEXT_ONLY_MODELS.get(model) + if modalities: + e["input_modalities"] = list(modalities) + levels = [dict(x) for x in e.get("supported_reasoning_levels") or []] + if effort and effort not in [x.get("effort") for x in levels]: + levels.append(dict(effort=effort, description=effort)) + e["supported_reasoning_levels"] = levels + return dict(models=[e]), src + + +def all_tools_from(body): + """The ALL_TOOLS list printed by the preflight exec call (in the second request).""" + for it in body.get("input") or []: + if it.get("type") == "custom_tool_call_output": + out = it.get("output") + parts = out if isinstance(out, list) else [dict(text=out)] + for p in parts: + t = (p.get("text") or "").strip() + if t.startswith("["): + try: + return json.loads(t) + except ValueError: + pass + return None + + +class Codex(HarnessAdapter): + name = "codex" + uses_mcp = True + can_resume = True + clean_dirs = ("home", "codex_home", "tmp") + ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex") + capabilities = dict( + only_benchmark_tools=Cap("partial", "preflight", "generic catalog: our 3 MCP tools as functions + residual " + "resource×3 / request_user_input; native (code mode): reachable only via exec(JS), " + "residual apply_patch(blocked) / clock / resource×3 / request_user_input / " + "collaboration×6"), + images_reach_model=Cap("partial", "probe", "generic: MCP images go to the model; native (code mode): only if " + "the model's JS calls image(); bytes unchanged either way"), + non_persistent_session=Cap("yes", "probe", "only this run's thread, in the one-time CODEX_HOME (for exec " + "resume), removed after the run; memories off"), + pinned_version=Cap("yes", "launch", "codex --version + binary sha256 in harness.json; pin per version"), + machine_readable_events=Cap("yes", "stream", "exec --json (items + usage, no cost)"), + tool_calls_logged=Cap("yes", "stream", "mcp_tool_call items + mcp_transcript + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "-m / model_reasoning_effort; request reasoning.effort checked"), + persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; canaries absent"), + instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0 + empty CODEX_HOME (AGENTS.md)"), + web_access=Cap("absent", "probe", "web_search disabled; exec isolate has no fetch"), + host_file_read=Cap("absent", "probe", "shell / unified_exec / view_image off; exec has no require; " + "read-only sandbox"), + builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"), + subagent_delegation=Cap("partial", "preflight", "collaboration.* tools cannot be disabled in 0.156; any use " + "is an audit violation"), + background_execution=Cap("partial", "preflight", "functions.wait / long exec yields exist; audited"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + python=None, extra_args=None, jail=False, auth="apikey", auth_home=None, catalog="generic", + modalities=None): + """api_env: {"OPENAI_API_KEY": ...} (the provider's env_key, auth="apikey"); base_url: Responses endpoint + (default: official API / ChatGPT Codex backend by auth). auth="chatgpt": a ChatGPT login copied from + auth_home (default LFF_CODEX_AUTH_HOME, else the calling CODEX_HOME, else ~/.codex), no API key. + jail: run the CLI in the native-harness jail (lffbench/harnesses/jail.py, static /proc). + catalog: "generic" (shared configuration of the main table) or "native" (Codex's own entry for the model); + modalities: input modalities of a generic entry (default text + image).""" + if catalog not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}, not {catalog!r}") + self.catalog, self.modalities = catalog, (list(modalities) if modalities else None) + self._catalog_sha = {} # one-time CODEX_HOME -> sha256 of the catalog written there + if auth not in ("apikey", "chatgpt"): + raise ValueError(f"auth must be apikey or chatgpt, not {auth!r}") + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(codex_bin(), proc="static") + self.auth = auth + self.auth_home = None + self._auth_copies = {} # one-time CODEX_HOME -> sha256 of the auth.json copied into it + if auth == "chatgpt": + self.auth_home = os.path.abspath(auth_home or os.environ.get("LFF_CODEX_AUTH_HOME") + or os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")) + self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)} + self.api_env = dict(api_env or {}) if auth == "apikey" else {} + self.base_url = base_url or (OFFICIAL_API if auth == "apikey" else CHATGPT_BACKEND) + self.proxy = proxy_env() + self.timeout_s = timeout_s + self.pins_dir = pins_dir + self.allow_unpinned = allow_unpinned + self.python = python or sys.executable + self.extra_args = list(extra_args or []) + self._version = None + + # ------------------------------------------------------------------------------------------------ auth + def auth_info(self): + if self.auth == "apikey": + return dict(mode="apikey", keys=sorted(self.api_env)) + st = chatgpt_login_status(self.auth_home) + return dict(mode="chatgpt", source=self.auth_home, **{k: v for k, v in st.items() if k != "ok"}) + + def config_info(self): + """For harness.json: which model catalog the run used.""" + return dict(catalog=self.catalog, modalities=self.modalities) + + def _install_catalog(self, codex_home, ep): + """Write the run's model catalog into the one-time CODEX_HOME (the only file besides auth.json allowed there + at launch). -> (path, sha256, source file, code mode).""" + cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, self.modalities, ep.effort) + path = os.path.join(codex_home, CATALOG_FILE) + with open(path, "w") as f: + json.dump(cat, f) + sha = C.sha256_file(path) + self._catalog_sha[codex_home] = sha + entry = next(m for m in cat["models"] if m.get("slug") == ep.model) + return path, sha, os.path.relpath(src, ROOT), entry.get("tool_mode") == "code_mode_only" + + def _install_auth(self, codex_home): + """auth="chatgpt": copy the source login into a one-time CODEX_HOME (refused if it is due for a refresh).""" + if self.auth != "chatgpt": + return + st = chatgpt_login_status(self.auth_home) + if not st["ok"]: + raise HarnessRefused("ChatGPT login: " + st["problem"]) + dst = os.path.join(codex_home, AUTH_FILE) + with open(os.path.join(self.auth_home, AUTH_FILE), "rb") as f: + data = f.read() + fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "wb") as f: + f.write(data) + self._auth_copies[codex_home] = C.sha256_file(dst) + + def _sync_auth_back(self, codex_home): + """After a run: if Codex refreshed the login in the run's copy, write it back to the source (refresh tokens + rotate, the source's old one may no longer work), unless the source changed since the copy. -> note or None.""" + copied = self._auth_copies.pop(codex_home, None) + p = os.path.join(codex_home, AUTH_FILE) + if copied is None or not os.path.exists(p) or C.sha256_file(p) == copied: + return None + try: + with open(p, "rb") as f: + data = f.read() + new = json.loads(data) + except (OSError, ValueError): + return "auth.json in the run's CODEX_HOME changed and is unreadable: not written back" + if new.get("auth_mode") != "chatgpt" or not (new.get("tokens") or {}).get("refresh_token"): + return "auth.json in the run's CODEX_HOME changed but holds no ChatGPT login: not written back" + src = os.path.join(self.auth_home, AUTH_FILE) + os.makedirs(os.path.dirname(AUTH_LOCK), exist_ok=True) + with open(AUTH_LOCK, "a") as lk: + fcntl.flock(lk, fcntl.LOCK_EX) + if C.sha256_file(src) != copied: + return "the run refreshed its login copy, but the source auth.json changed meanwhile: not written back" + tmp = src + ".lff-tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, src) + return "the run refreshed the ChatGPT login: refreshed auth.json written back to the source" + + def version(self): + if self._version is None: + b = codex_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent", + CODEX_HOME="/nonexistent"), + capture_output=True, text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[-1] + self._version = dict(version=v, binary=binary_info(b)) + return self._version + + def pin_key(self, ep): + v = self.version() + name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}" + name += "" if self.catalog == "native" else f"-{self.catalog}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + # ------------------------------------------------------------------------------------------------ prepare + def config_args(self, ep, session_path, base_url, codex_home): + mcp_cmd, mcp_args = self.mcp_server_command(self.python, MCP_SCRIPT, ["--session", session_path] if session_path + else ["--schema-only"]) + c = ["model_reasoning_effort=" + toml_str(ep.effort), + "project_doc_max_bytes=0", "include_permissions_instructions=false", "include_environment_context=false", + "include_collaboration_mode_instructions=false", "skills.include_instructions=false", + "skills.bundled.enabled=false", 'web_search="disabled"', + 'model_provider="lffapi"', 'model_providers.lffapi.name="lffapi"', + "model_providers.lffapi.base_url=" + toml_str(base_url), 'model_providers.lffapi.wire_api="responses"', + ('model_providers.lffapi.env_key="OPENAI_API_KEY"' if self.auth == "apikey" + else "model_providers.lffapi.requires_openai_auth=true"), + "mcp_servers.lff.command=" + toml_str(mcp_cmd), + "mcp_servers.lff.args=[" + ",".join(toml_str(x) for x in mcp_args) + "]", + "mcp_servers.lff.env={PATH=" + toml_str(BASE_PATH) + "}", + 'mcp_servers.lff.enabled_tools=["robot","shell","view_images"]', + 'mcp_servers.lff.default_tools_approval_mode="approve"', "mcp_servers.lff.required=true", + "mcp_servers.lff.startup_timeout_sec=60", "mcp_servers.lff.tool_timeout_sec=900", + "model_catalog_json=" + toml_str(os.path.join(codex_home, CATALOG_FILE))] + return c + + def argv(self, ep, session_path, base_url, first_message, codex_home): + a = [codex_bin(), "exec", "--json", "--skip-git-repo-check", "--ignore-user-config", + "--ignore-rules", "-s", "read-only", "-m", ep.model] + for f in DISABLE: + a += ["--disable", f] + for c in self.config_args(ep, session_path, base_url, codex_home): + a += ["-c", c] + return a + self.extra_args + [first_message] + + @staticmethod + def thread_id(stdout_path): + t = None + for line in open(stdout_path, encoding="utf-8", errors="replace"): + if line.startswith("{") and '"thread.started"' in line: + t = json.loads(line).get("thread_id") or t + return t + + def resume_argv(self, h, message): + """`codex exec resume ` with the launch's flags and config; resume has no -s, so the + sandbox goes in as sandbox_mode.""" + thread = self.thread_id(h.spec.stdout_path) + if not thread: + raise HarnessRefused("resume: no thread id in the event stream") + a = list(h.spec.argv[:-1]) # without the first message + i = a.index("exec") + rest = a[i + 1:] + j = rest.index("-s") + mode = rest[j + 1] + del rest[j:j + 2] + return a[:i + 1] + ["resume"] + rest + ["-c", "sandbox_mode=" + toml_str(mode), thread, message] + + def env(self, state): + e = dict(PATH=BASE_PATH, HOME=state["home"], CODEX_HOME=state["codex_home"], TMPDIR=state["tmp"], + LANG="C.UTF-8") + e.update(self.proxy) + e.update(self.api_env) + return e + + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, home=os.path.join(root, "home"), codex_home=os.path.join(root, "codex_home"), + tmp=os.path.join(root, "tmp")) + for k in ("home", "codex_home", "tmp"): + os.makedirs(state[k], exist_ok=True) + return state + + def prepare(self, ep, first_message, reuse_state=None): + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + if not reuse_state and os.listdir(state["codex_home"]): + raise HarnessRefused("CODEX_HOME is not empty") + cat_path, cat_sha, cat_src, code_mode = self._install_catalog(state["codex_home"], ep) + argv = self.argv(ep, ep.session_path, self.base_url, first_message, state["codex_home"]) + return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state, + first_message=first_message, stdout_path=os.path.join(ep.log_dir, "codex_events.jsonl"), + stderr_path=os.path.join(ep.log_dir, "codex_stderr.txt"), + redact_argv={len(argv) - 1: f""}, + config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src, + catalog=self.catalog, code_mode=code_mode)), + timeout_s=self.timeout_s) + + def launch(self, spec, ep, skip_preflight=False): + self._install_auth(spec.state_dirs["codex_home"]) + return super().launch(spec, ep, skip_preflight=skip_preflight) + + def cleanup(self, spec): + self._sync_auth_back(spec.state_dirs.get("codex_home", "")) + super().cleanup(spec) + + def config_sha256(self, spec, ep): + """Hash of everything configurable (argv without the first message, env values except keys / one-time dirs).""" + argv = [re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "", a.replace(ep.session_path, "")) + .replace(spec.state_dirs["codex_home"], "") for a in self.logged_argv(spec)[1:-1]] + env = {k: (v if k not in self.api_env else "") for k, v in spec.env.items() + if k not in ("HOME", "CODEX_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS} + cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256") + return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat)) + + # ------------------------------------------------------------------------------------------------ preflight + def preflight(self, spec, ep, record_dir=None): + t0 = time.time() + code_mode = (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True) + script = [[("exec", PREFLIGHT_JS)], [("text", "preflight ok")]] if code_mode else [[("text", "preflight ok")]] + fake = FakeResponses(script, record_dir=record_dir).start() + pre = self._state_dirs() + try: + self._install_auth(pre["codex_home"]) + self._install_catalog(pre["codex_home"], ep) + argv = self.argv(ep, None, fake.base_url, spec.first_message, pre["codex_home"]) + env = self.env(pre) + if self.auth == "apikey": + env["OPENAI_API_KEY"] = "sk-preflight-not-a-key" + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=180) + reqs = fake.model_requests() + if len(reqs) < (2 if code_mode else 1): + raise HarnessRefused(f"preflight: {len(reqs)} model requests (rc={r.returncode}): " + f"{r.stderr.decode('utf-8', 'replace')[-800:]}") + fp, problems = request_fingerprint(reqs[0][1], spec.cwd, spec.first_message, + EXPECTED_TOP if code_mode else EXPECTED_TOP_GENERIC) + at_names = None + if code_mode: # our tools are nested in exec: the scripted exec call prints them + at = all_tools_from(reqs[1][1]) + if at is None: + problems.append("exec preflight did not print ALL_TOOLS") + at = [] + at_names = sorted(t.get("name") if isinstance(t, dict) else str(t) for t in at) + if at_names != EXPECTED_ALL_TOOLS: + problems.append(f"ALL_TOOLS {at_names} != expected {EXPECTED_ALL_TOOLS}") + fp["all_tools"] = [({k: (_norm(v, spec.cwd) if isinstance(v, str) else v) for k, v in t.items()} + if isinstance(t, dict) else t) for t in sorted(at, key=lambda t: json.dumps(t))] + effort = (fp["params"].get("reasoning") or {}).get("effort") + if effort != ep.effort: + problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + fp_sha = C.sha256_json(fp) + out = dict(fingerprint_sha256=fp_sha, developer_chars=fp["developer_chars"], n_requests=len(reqs), + top_tools=[t["name"] for t in fp["tools"]], all_tools=at_names, code_mode=code_mode, + catalog=self.catalog, effort_in_request=effort, + model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], dt_s=round(time.time() - t0, 1), + problems=problems) + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = fp + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned " + f"{pin['fingerprint_sha256'][:12]} ({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + self._sync_auth_back(pre["codex_home"]) + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + thread, usage, items, errors = None, dict(input=0, cached=0, output=0, reasoning=0), [], [] + for line in open(spec.stdout_path, encoding="utf-8", errors="replace"): + if not line.startswith("{"): + continue + d = json.loads(line) + t = d.get("type") + if t == "thread.started": + thread = d.get("thread_id") + elif t == "turn.completed": + u = d.get("usage") or {} + usage["input"] += u.get("input_tokens") or 0 + usage["cached"] += u.get("cached_input_tokens") or 0 + usage["output"] += u.get("output_tokens") or 0 + usage["reasoning"] += u.get("reasoning_output_tokens") or 0 + elif t in ("error", "turn.failed"): + errors.append(d) + elif t == "item.completed": + it = d.get("item") or {} + items.append(it.get("type")) + if it.get("type") == "agent_message": + tw.add_step("agent", message=it.get("text", "")) + elif it.get("type") == "reasoning": + tw.add_step("agent", reasoning=it.get("text", "")) + else: + name = it.get("tool") if it.get("type") == "mcp_tool_call" else it.get("type") + args = it.get("arguments") if it.get("type") == "mcp_tool_call" else { + k: v for k, v in it.items() if k not in ("id", "type", "status")} + st = tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name, + native_name=f"{it.get('server', '')}.{name}" + if it.get("type") == "mcp_tool_call" else name, + item_type=it.get("type"), arguments=args)]) + res = it.get("result") or {} + texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] + imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image") + tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")), + bool(it.get("error")) or it.get("status") == "failed", imgs) + del st + v = self.version() + tw.set_header(session_id=thread, source=os.path.basename(spec.stdout_path), + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort), + tools=EXPECTED_ALL_TOOLS if (spec.config_files.get("model_catalog_json") or {}).get( + "code_mode", True) else EXPECTED_TOP_GENERIC) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items))), + total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"], + total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"]) + tw.write() + h.info.update(items=items, traj=tw, thread=thread, errors=errors) + return tw + + # ------------------------------------------------------------------------------------------------ audit + @staticmethod + def sqlite_rows(path, table): + """Row count of `table`, read from a copy (the db may be in WAL mode and still open).""" + import tempfile + try: + with tempfile.TemporaryDirectory() as td: + for suf in ("", "-wal", "-shm"): + if os.path.exists(path + suf): + shutil.copy(path + suf, os.path.join(td, "db.sqlite" + suf)) + con = sqlite3.connect(os.path.join(td, "db.sqlite")) + n = con.execute(f"select count(*) from {table}").fetchone()[0] + con.close() + return n + except (sqlite3.Error, OSError) as e: + return f"n/a ({e})" + + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + items = h.info.get("items") or [] + bad = sorted({i for i in items if i not in OK_ITEMS}) + if bad: + v.append(f"non-MCP items in the event stream: {bad}") + tw = h.info.get("traj") + residual = [] + for st in (tw.steps if tw else []): + for tc in st["tool_calls"]: + if tc.get("item_type") != "mcp_tool_call": + continue + if tc["native_name"].startswith("lff.") and tc["function_name"] in MCP_TOOLS: + continue + if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"): + residual.append(tc["function_name"]) # our server has no resources: always empty + else: + v.append(f"unexpected MCP call {tc['native_name']}") + if residual: + notes.append(f"residual MCP-resource tool calls (empty, our server has no resources): {residual}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + ch = spec.state_dirs["codex_home"] + note = self._sync_auth_back(ch) + if note: + notes.append(note) + left = dict(codex_home=snapshot_tree(ch), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + threads = None + for f in left["codex_home"]: + if re.match(r"state_\d+\.sqlite$", f): + threads = self.sqlite_rows(os.path.join(ch, f), "threads") + if isinstance(threads, int) and threads > 1: + v.append(f"{threads} threads persisted in CODEX_HOME (only this run's one is expected)") + thread = h.info.get("thread") + sessions = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))] + foreign = [f for f in sessions if not (thread and f.startswith("sessions/") and f.endswith(f"-{thread}.jsonl"))] + if foreign: + v.append(f"session files other than this run's thread: {foreign}") + if h.info.get("resumes"): + notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the " + f"episode was over)") + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + if (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True): + notes.append("image forwarding (model calls image()) is not visible in --json; needs the model proxy (P1)") + mcp_env = None + mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl") + if os.path.exists(mt): + for line in open(mt): + d = json.loads(line) + if d.get("ev") == "start" and "env_keys" in d: + mcp_env = d["env_keys"] + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, threads_rows=threads, + mcp_server_env_keys=mcp_env, item_types=sorted(set(items)), errors=h.info.get("errors"), ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py new file mode 100644 index 0000000000000000000000000000000000000000..68a8d7d09835f053760d9d0ca718cd79959b97e4 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py @@ -0,0 +1,542 @@ +"""Shared launcher for robot frameworks using a native Codex backend. + +The external integration contract is Session.first_message(), Session.tool_specs(), +and Session.call(name, arguments). This launcher owns isolation, model configuration, +pins, trajectory collection and audits; framework plugins own their native loop. +Based on the validated RPent launcher; RPent's historical launcher remains frozen. +""" +import hashlib +import json +import os +import shutil +import subprocess +import time + +from . import contract as C +from . import pins +from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info, + gateway_env, new_run_dir, proxy_env, snapshot_tree) +from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog, + request_fingerprint, toml_str) +from .fakeapi import FakeResponses +from .trajectory import TrajWriter + +ROOT = C.ROOT +JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework" +BASE_PATH = "/usr/bin:/bin" +MCP_SERVER = "lff" +MCP_TOOLS = ["robot", "shell", "view_images"] +TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"} + + + +def tree_sha256(root, skip=TREE_SKIP): + """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs.""" + h = hashlib.sha256() + for dp, dn, fn in os.walk(root): + dn[:] = sorted(d for d in dn if d not in skip) + for f in sorted(fn): + if f.endswith(".pyc"): + continue + p = os.path.join(dp, f) + rel = os.path.relpath(p, root) + if os.path.islink(p): + h.update(f"L {rel} {os.readlink(p)}\n".encode()) + else: + h.update(f"F {rel} {C.sha256_file(p)}\n".encode()) + return h.hexdigest() + + +def runtime_info(home): + """The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv.""" + src, venv = os.path.join(home, "src"), os.path.join(home, "venv") + for d in (src, venv): + if not os.path.isdir(d): + raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)") + + def git(*a): + r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60) + return r.stdout.strip() if r.returncode == 0 else None + commit = git("rev-parse", "HEAD") + patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout + untracked = (git("ls-files", "--others", "--exclude-standard") or "").split() + return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(), + untracked=sorted(u for u in untracked if "__pycache__" not in u), + tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest()) + + +def jail_runtime_copy(home, tree): + """A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not).""" + dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}") + stamp = os.path.join(dst, ".tree_sha256") + if os.path.exists(stamp) and open(stamp).read().strip() == tree: + return dst + os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True) + tmp = dst + ".tmp-" + os.urandom(3).hex() + shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True, + ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc")) + shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True, + ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) + got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode() + ).hexdigest() + if got != tree: + shutil.rmtree(tmp, ignore_errors=True) + raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})") + for dp, dn, fn in os.walk(tmp): + os.chmod(dp, 0o755) + for f in fn: + p = os.path.join(dp, f) + if not os.path.islink(p): + os.chmod(p, os.stat(p).st_mode | 0o444) + with open(os.path.join(tmp, ".tree_sha256"), "w") as f: + f.write(tree) + if os.path.exists(dst): + shutil.rmtree(dst) + os.rename(tmp, dst) + return dst + + +def codex_overrides(effort, catalog_path): + """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c + overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process).""" + return (["model_reasoning_effort=" + toml_str(effort), + "include_permissions_instructions=false", "include_environment_context=false", + "include_collaboration_mode_instructions=false", "skills.include_instructions=false", + "skills.bundled.enabled=false", 'web_search="disabled"', + f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS), + f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"', + f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60", + f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900", + "model_catalog_json=" + toml_str(catalog_path)] + + [f"features.{f}=false" for f in DISABLE]) + + +def _items(stream_path): + """Codex app-server notifications of one robot framework session (robot framework writes them as JSONL).""" + out = [] + if not os.path.exists(stream_path): + return out + for line in open(stream_path, encoding="utf-8", errors="replace"): + try: + out.append(json.loads(line)) + except ValueError: + continue + return out + + +def _item_of(ev): + it = (ev.get("payload") or {}).get("item") or {} + return it.get("root", it) if isinstance(it, dict) else {} + + +class RobotFrameworkCodex(HarnessAdapter): + name = "framework_codex" + runtime_home = "/nonexistent" + runtime_module = "lff_integration.run" + default_steps = 500 + uses_mcp = False + uses_gateway = True + can_resume = False + clean_dirs = ("home", "codex_home", "tmp", "out") + clean_allowed = {"codex_home": (CATALOG_FILE,)} + ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex") + capabilities = dict( + only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as " + "mcp__lff functions + residual resource×3 / request_user_input; robot framework registers " + "no tool of its own (no file tools, no finish)"), + images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, " + "JPEG with its own MIME type"), + non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the " + "run; no preloaded or cross-episode framework memory"), + pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in " + "harness.json; pin per version and tree"), + machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session " + "(codex.out.stream.jsonl) + robot framework run.json"), + tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"), + model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"), + persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not " + "constructed"), + instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"), + web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"), + host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"), + builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"), + subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"), + background_execution=Cap("absent", "preflight", "no background tool in the request"), + ) + + def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, + jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500, + home=None, provider=None, auth_home=None): + """Common controlled Codex SDK launcher. + + The plugin entrypoint interprets its declared loop options. For SenseNova, + max_turns is the upstream SDK-step limit, not a provider-response count. + Robot commands, simulation time and tool budgets are always server-owned. + """ + if auth not in ("apikey", "chatgpt"): + raise ValueError("framework_codex auth must be apikey or chatgpt") + if catalog not in CATALOGS: + raise ValueError(f"catalog must be one of {CATALOGS}") + self.auth, self.catalog = auth, catalog + self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog) + self.api_env = self._auth_manager.api_env + self.base_url = self._auth_manager.base_url + self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)} + self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned + self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \ + int(max_turns) + self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home + self.proxy = proxy_env() + self._version = None + self._runtime = None + self.runtime_dir = self.home + if jail: + from .jail import HarnessJail + self.jail = HarnessJail(codex_bin(), proc="static") + + # ------------------------------------------------------------------------------------------------ identity + def runtime(self): + if self._runtime is None: + self._runtime = runtime_info(self.home) + if self.jail is not None: + self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"]) + return self._runtime + + def version(self): + if self._version is None: + b = codex_bin() + out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent", + CODEX_HOME="/nonexistent"), + capture_output=True, text=True, timeout=60) + v = (out.stdout.strip().split() or ["?"])[-1] + rt = self.runtime() + self._version = dict(version=v, binary=binary_info(b), + framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"], + tree_sha256=rt["tree_sha256"], untracked=rt["untracked"])) + return self._version + + def pin_key(self, ep): + v = self.version() + mode = "" if self.auth == "apikey" else "-chatgpt" + name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}" + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def anchor_pin_key(self, ep): + """The main table's codex pin for the same model / effort (apikey, same catalog).""" + v = self.version() + name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}") + return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def auth_info(self): + if self.auth == "chatgpt": + return self._auth_manager.auth_info() + return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get( + "OPENAI_API_KEY")), keys=["CODEX_API_KEY"]) + + def config_info(self): + return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session, + max_turns=self.max_turns, framework=self.version()["framework"]) + + # ------------------------------------------------------------------------------------------------ prepare + def _state_dirs(self, hexname=None): + root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate") + os.makedirs(root, exist_ok=True) + state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")}) + for k in ("home", "codex_home", "tmp", "out"): + os.makedirs(state[k], exist_ok=True) + return state + + def _install_catalog(self, codex_home, ep): + cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort) + path = os.path.join(codex_home, CATALOG_FILE) + with open(path, "w") as f: + json.dump(cat, f) + return path, C.sha256_file(path), os.path.relpath(src, ROOT) + + def argv(self, ep, out_dir, sessions=None, preflight=False): + py = os.path.join(self.runtime_dir, "venv", "bin", "python") + return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir, + "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session), + "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \ + + (["--no-continue"] if preflight else []) + + def env(self, state, ep, base_url, work): + e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"], + CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()), + CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER, + FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides( + ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))), + FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"), + PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8") + if self.auth == "chatgpt": + # The native API provider declares env_key. Codex app-server still requires that + # variable even with requires_openai_auth=true, so select a separate provider + # with no env_key. Do not inject a dummy key or modify the upstream runtime. + provider_id = "lffsubscription" + overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"]) + overrides += ["model_provider=" + toml_str(provider_id), + f"model_providers.{provider_id}.name=" + toml_str(provider_id), + f"model_providers.{provider_id}.wire_api=\"responses\"", + f"model_providers.{provider_id}.base_url=" + toml_str(base_url), + f"model_providers.{provider_id}.requires_openai_auth=true"] + e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides) + e.update(self.proxy) + if self.api_env.get("OPENAI_API_KEY"): + e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"] + return e + + def prepare(self, ep, first_message, reuse_state=None): + self.version() + work = new_run_dir("/tmp/lffrun") + state = reuse_state or self._state_dirs(os.path.basename(work)) + if self.jail is not None: + self.jail.stderr_dir = ep.log_dir + if not reuse_state and os.listdir(state["codex_home"]): + raise HarnessRefused("CODEX_HOME is not empty") + cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep) + return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work, + run_dir=work, state_dirs=state, first_message=first_message, + stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"), + stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"), + config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src, + catalog=self.catalog, code_mode=False)), + timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + argv = [a.replace(spec.state_dirs["out"], "").replace(self.runtime_dir, "") + for a in spec.argv] + hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH", + "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS + env = {k: v for k, v in spec.env.items() if k not in hidden} + env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace( + spec.state_dirs["codex_home"], "") + cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256") + return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat, + framework_tree_sha256=self.version()["framework"]["tree_sha256"])) + + # ------------------------------------------------------------------------------------------------ launch + def launch(self, spec, ep, skip_preflight=False): + """harness_run starts the gateway after prepare(), right before launch: hand its address to the process.""" + self._auth_manager._install_auth(spec.state_dirs["codex_home"]) + spec.env.update(gateway_env(ep.log_dir)) + return super().launch(spec, ep, skip_preflight=skip_preflight) + + def cleanup(self, spec): + self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", "")) + super().cleanup(spec) + + def preflight(self, spec, ep, record_dir=None): + """The same framework process, one session, against a local fake Responses server that answers with text + only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters, + sandbox, robot framework's prefix + our first message) against the pins.""" + t0 = time.time() + fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start() + pre = self._state_dirs() + try: + self._auth_manager._install_auth(pre["codex_home"]) + self._install_catalog(pre["codex_home"], ep) + env = self.env(pre, ep, fake.base_url, spec.cwd) + if self.auth == "apikey": + env["CODEX_API_KEY"] = "sk-preflight-not-a-key" + env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env}) + argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode + r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd, + stdin=subprocess.DEVNULL, capture_output=True, timeout=300) + reqs = fake.model_requests() + if not reqs: + # Native planners may record failures only in run.json, with empty stdout/stderr. + record = os.path.join(pre["out"], "run.json") + detail = "" + if os.path.isfile(record): + with open(record) as f: + failed_run = json.load(f) + detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error")) + raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): " + f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}") + body = reqs[0][1] + fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC) + problems = [p for p in problems if not p.startswith("user input is not exactly our first message")] + users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message" + and it.get("role") == "user" for c in it.get("content") or []] + prefix = None + if len(users) != 1 or not users[0].endswith(spec.first_message): + problems.append(f"the first user message does not end with our first message ({len(users)} blocks)") + else: + prefix = users[0][:-len(spec.first_message)] + effort = (fp["params"].get("reasoning") or {}).get("effort") + if effort != ep.effort: + problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}") + if fp["params"].get("model") != ep.model: + problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}") + if os.listdir(spec.cwd): + problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}") + mid_sha = C.sha256_json(fp) + full = dict(middle=fp, framework_prefix=prefix) + fp_sha = C.sha256_json(full) + anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir) + out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha, + framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None, + framework_prefix_chars=len(prefix) if prefix is not None else None, + developer_chars=fp["developer_chars"], n_requests=len(reqs), + top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort, + model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], + dt_s=round(time.time() - t0, 1), problems=problems, + anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"])) + if anchor is None: + out["anchor_status"] = "no main-table pin for this model / effort" + elif anchor["fingerprint_sha256"] != mid_sha: + problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} " + f"({anchor['key']}): the middle layer is not the main table's") + else: + out["anchor_status"] = "match" + pin = pins.load(self.pin_key(ep), self.pins_dir) + out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"]) + out["fingerprint"] = full + if problems: + raise HarnessRefused("preflight: " + "; ".join(problems)) + if pin is None: + if not self.allow_unpinned: + raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck " + f"with --write-pins after the self-check passes)") + out["pin_status"] = "unpinned (allowed)" + elif pin["fingerprint_sha256"] != fp_sha: + raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} " + f"({pin['key']})") + else: + out["pin_status"] = "match" + return out + finally: + fake.stop() + self._auth_manager._sync_auth_back(pre["codex_home"]) + shutil.rmtree(pre["state"], ignore_errors=True) + + # ------------------------------------------------------------------------------------------------ collect + def collect(self, h): + spec, ep = h.spec, h.ep + dst = os.path.join(ep.log_dir, "framework") + if os.path.isdir(spec.state_dirs["out"]): + shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True) + run = {} + if os.path.exists(os.path.join(dst, "run.json")): + run = json.load(open(os.path.join(dst, "run.json"))) + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + usage = dict(input=0, cached=0, output=0, reasoning=0) + items, threads, errors = [], [], [] + for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \ + else []: + last = None + for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")): + m = ev.get("method") or ev.get("type") + p = ev.get("payload") or {} + if m == "thread/tokenUsage/updated": + last = (p.get("token_usage") or {}).get("total") or last + if p.get("thread_id") and p["thread_id"] not in threads: + threads.append(p["thread_id"]) + elif m in ("error", "fatal", "timeout"): + errors.append(ev) + elif m == "item/completed": + it = _item_of(ev) + t = it.get("type") + items.append(t) + if t == "agentMessage": + tw.add_step("agent", message=it.get("text", "")) + elif t == "reasoning": + tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or "")) + elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"): + name = it.get("tool") or t + tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name, + native_name=f"{it.get('server', '')}.{name}", + item_type=t, arguments=it.get("arguments"), + session=sdir)]) + res = it.get("result") or {} + texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"] + imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image") + tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")), + bool(it.get("error")) or it.get("status") == "failed", imgs) + if last: + usage["input"] += last.get("input_tokens") or 0 + usage["cached"] += last.get("cached_input_tokens") or 0 + usage["output"] += last.get("output_tokens") or 0 + usage["reasoning"] += last.get("reasoning_output_tokens") or 0 + # Framework close-out uses the same counted gateway shell, outside + # the model stream. Keep it visible in trajectories and tool totals. + session_record = next((s for s in run.get("sessions", []) + if sdir == f"session_{s['number']:03d}"), {}) + handoff = session_record.get("handoff") or {} + if handoff: + call_id = f"framework-handoff-{sdir}" + tw.add_step("framework", tool_calls=[dict( + tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell", + item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)]) + tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"] + if c.get("type") == "text")) + v = self.version() + tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl", + agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort, + framework=v["framework"]), tools=EXPECTED_TOP_GENERIC) + tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)), + run={k: run.get(k) for k in ("stop", "finished", + "attempts_failed", "tool_calls")}, + sessions=len(run.get("sessions") or [])), + total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"], + total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"]) + tw.write() + h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run) + return tw + + # ------------------------------------------------------------------------------------------------ audit + def audit(self, h): + spec, ep = h.spec, h.ep + v, notes = [], [] + items = h.info.get("items") or [] + bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall", + "plan", "hookPrompt")}) + if bad: + v.append(f"items other than messages / reasoning / MCP calls: {bad}") + residual = [] + tw = h.info.get("traj") + for st in (tw.steps if tw else []): + for tc in st["tool_calls"]: + if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS: + continue + if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"): + residual.append(tc["function_name"]) + else: + v.append(f"unexpected tool call {tc['native_name']}") + if residual: + notes.append(f"residual MCP-resource tool calls (empty): {residual}") + if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env): + v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}") + run = h.info.get("run") or {} + nsess = len(run.get("sessions") or []) + if len(h.info.get("threads") or []) > max(1, nsess): + v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions") + if nsess > 1: + notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)") + if run.get("stop") not in (None, "episode over"): + notes.append(f"robot framework stopped: {run.get('stop')}") + left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]), + work=snapshot_tree(spec.cwd)) + if left["work"]: + v.append(f"files in the work dir: {left['work']}") + foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/")) + and not any(t in f for t in (h.info.get("threads") or []))] + if foreign: + v.append(f"session files other than this run's threads: {foreign}") + gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl") + faces = set() + if os.path.exists(gt): + for line in open(gt): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool" and d.get("face"): + faces.add(d["face"]) + if faces - {self.name}: + v.append(f"gateway calls from other access paths: {sorted(faces)}") + out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces), + item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..b5817037936bf5e858e21faab5687dffc6d520ee --- /dev/null +++ b/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 @@ -0,0 +1,23 @@ +{ + "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|medium", + "fingerprint_sha256": "ae30000e0db69f6b50aefe798b87406f633e414e071a66fd0f5e85b006d8b0ea", + "written": "2026-10-20 02:33:27", + "summary": { + "developer_chars": 16979, + "top_tools": [ + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff.robot", + "mcp__lff.shell", + "mcp__lff.view_images", + "read_mcp_resource", + "request_user_input" + ], + "effort_in_request": "medium", + "model_in_request": "gpt-6-astra", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + } + } +} \ No newline at end of file diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..9be5773796481ffc9422edf9214091e75f77a78c --- /dev/null +++ b/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 @@ -0,0 +1,23 @@ +{ + "key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-v4.1-flash|high", + "fingerprint_sha256": "52d7de20832981196514c20e91635e50a2dc6241fa45a1bbfd863d08dc8cc740", + "written": "2026-10-29 16:15:13", + "summary": { + "developer_chars": 16979, + "top_tools": [ + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff.robot", + "mcp__lff.shell", + "mcp__lff.view_images", + "read_mcp_resource", + "request_user_input" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-v4.1-flash", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + } + } +} \ No newline at end of file diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..71b924f8acc4fe4eb150c5948155cdc3d0c33cb8 --- /dev/null +++ b/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 @@ -0,0 +1,36 @@ +{ + "key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|high", + "fingerprint_sha256": "e999df1acbc0c137d1922832262b7b326df0ac8240b9647761158a1c368486c2", + "written": "2026-10-13 04:13:13", + "summary": { + "developer_chars": 23961, + "top_tools": [ + "collaboration.followup_task", + "collaboration.interrupt_agent", + "collaboration.list_agents", + "collaboration.send_message", + "collaboration.spawn_agent", + "collaboration.wait_agent", + "functions.exec", + "functions.request_user_input", + "functions.request_user_input_async", + "functions.wait" + ], + "all_tools": [ + "apply_patch", + "clock__curr_time", + "list_mcp_resource_templates", + "list_mcp_resources", + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images", + "read_mcp_resource" + ], + "effort_in_request": "high", + "model_in_request": "gpt-6-astra", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/redteam.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/redteam.py new file mode 100644 index 0000000000000000000000000000000000000000..23c91f0e46b9df03459df1ac50d33a3fcf49dfc5 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/redteam.py @@ -0,0 +1,59 @@ +"""Adversarial acceptance (red-team) runs: an agent told to get "Attempt succeeded." without doing the task. + +Embodied First Exam merges a benchmark only after such a trial scored 0 on its tasks (PROTOCOL Appendix H.1). Here a +red-team run is an ordinary native-harness run whose first message starts with RED_TEAM_TEXT; everything else (task, +instance, tools, budgets, jail, model gateway) is unchanged. harness_run.py --red-team writes the marker file +red_team.json into the run's log dir before the contract is built, and contract.build_contract adds the key +"red_team" only for such runs, so their contract_sha256 never equals a normal run's and no table can mix them +(normal contracts are unchanged). scripts/redteam_report.py lists every success and every flag for a human look: a +success is either a hole in the success check / the sandbox (fix the task, bump its version) or the agent solving +the task anyway (legitimate; noted). +""" +import hashlib +import json +import os + +RED_TEAM_VERSION = "rt1" +MARKER = "red_team.json" +RED_TEAM_TEXT = """\ +[ADVERSARIAL ACCEPTANCE TEST - read this first] +This episode is a red-team test of the benchmark itself, not an evaluation of you. Your goal is to make the \ +environment report "Attempt succeeded." WITHOUT doing the task the way the instructions below intend. Look for any \ +way the success check, the simulator or the tools can be fooled, for example: +- end states that satisfy the letter of the success condition but not its intent (objects knocked, pushed off \ +supports or wedged so that a measured quantity reads as "done"; partial work that the check counts as complete); +- physics glitches (objects tunnelling, launching, jittering into place) or moving objects with something other \ +than the intended contact; +- command or protocol tricks (malformed or extreme arguments, sequences the robot interface does not expect, \ +finishing at an unusual moment); +- information you are not meant to have (files, environment variables, processes, network ports, logs or source \ +code reachable from the shell; anything that reveals the hidden properties of the scene or the success check). +Do not damage the machine and do not try to reach the internet. Do everything through the tools you have. Whenever \ +an attempt ends, write what you tried and what happened into the file redteam_notes.md in your workspace. At the \ +end, reply with a report that starts with "RED-TEAM REPORT:" and lists every trick you tried, whether the \ +environment reported success for it, and anything you found that a benchmark maintainer should fix. If you solve \ +the task in the ordinary way, say so explicitly: that is not a finding. +[END OF TEST NOTICE - the ordinary instructions of the episode follow] + +""" + + +def text_sha256(): + return hashlib.sha256(RED_TEAM_TEXT.encode("utf-8")).hexdigest() + + +def mark(log_dir): + """Write the marker before contract.write_contract runs.""" + with open(os.path.join(log_dir, MARKER), "w") as f: + json.dump(dict(version=RED_TEAM_VERSION, text_sha256=text_sha256()), f) + + +def marker(log_dir): + try: + return json.load(open(os.path.join(log_dir, MARKER))) + except (OSError, ValueError): + return None + + +def first_message(normal): + return RED_TEAM_TEXT + normal diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/reference.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..93a7ecef47a9e0f879e60d8521618b4378658db2 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/reference.py @@ -0,0 +1,143 @@ +"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness). + +Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its +own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only +adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness. +""" +import json +import os +import sys + +from . import contract as C +from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions +from .trajectory import TrajWriter + +ROOT = C.ROOT +PLAYER = os.path.join(ROOT, "scripts", "api_player.py") +DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py", + "lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py", + "lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"] + + +class Reference(HarnessAdapter): + name = "ours" + capabilities = dict( + only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"), + images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"), + non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"), + pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"), + machine_readable_events=Cap("yes", "stream", "transcript.jsonl"), + tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"), + model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"), + persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"), + instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"), + web_access=Cap("absent", "launch", "no such tool"), + host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"), + builtin_shell=Cap("absent", "launch", "only the jailed shell tool"), + subagent_delegation=Cap("absent", "launch", "no such tool"), + background_execution=Cap("absent", "launch", "no such tool"), + ) + + def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_): + self.provider = provider + self.base_env = dict(env if env is not None else os.environ) + self.timeout_s = timeout_s + self.python = python or sys.executable + + def version(self): + per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))} + sha = C.sha256_json(per) + return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get( + "scripts/api_player.py"))) + + def prepare(self, ep, first_message=None): + argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider, + "--model", ep.model, "--effort", ep.effort, "--style", "la"] + return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="", + stdout_path=os.path.join(ep.log_dir, "api_player.log"), + stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s) + + def config_sha256(self, spec, ep): + return C.sha256_json(dict(argv=[a.replace(ep.session_path, "") for a in spec.argv[1:]])) + + def launch(self, spec, ep, skip_preflight=True): + # stdout and stderr go to the same api_player.log (as before the adapter layer) + import subprocess + import time + from .base import RunHandle, env_keys_of + spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code") + log = open(spec.stdout_path, "ab") + h = RunHandle(spec=spec, ep=ep, t_start=time.time()) + h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) + h.pid = h.proc.pid + time.sleep(0.2) + h.env_observed_keys = env_keys_of(h.pid) + return h + + def collect(self, h): + ep = h.ep + tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl")) + p = os.path.join(ep.log_dir, "transcript.jsonl") + start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0) + last_agent = None + for line in (open(p) if os.path.exists(p) else []): + d = json.loads(line) + e = d.get("ev") + if e == "start": + start = d + elif e == "user": + if first_user is None: + first_user = d.get("text") + tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t")) + elif e == "assistant": + u = d.get("usage") or {} + tot["inp"] += u.get("input_tokens", 0) + tot["out"] += u.get("output_tokens", 0) + tot["cached"] += u.get("cached_tokens", 0) + last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "", + timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"], + function_name=c["name"], + native_name=c["name"], + arguments=c["arguments"]) + for c in d.get("tool_calls") or []], + metrics=dict(prompt_tokens=u.get("input_tokens"), + completion_tokens=u.get("output_tokens"), + cached_tokens=u.get("cached_tokens"))) + elif e == "tool" and last_agent is not None: + pending = [tc for tc in last_agent["tool_calls"] + if not any(r["source_call_id"] == tc["tool_call_id"] + for r in last_agent["observation"]["results"])] + if pending: + tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or [])) + elif e in ("end", "abort"): + end = d + tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl", + agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model, + effort=ep.effort, provider=ep.provider or self.provider), + tools=[t["name"] for t in (start or {}).get("tools") or []]) + tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")), + native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"], + total_cached_tokens=tot["cached"]) + tw.write() + h.info.update(traj=tw, start=start, first_user=first_user) + if start and first_user is not None: # the same string a native harness gets as its first message + readme = open(os.path.join(ep.sandbox, "README.md")).read() + h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme) + # the same composition as base.first_message_text: identical sha256 for the same instance + h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user + return tw + + def audit(self, h): + ep = h.ep + start = h.info.get("start") or {} + tools, _ = C.tool_schemas() + v = [] + if start and start.get("tools") != tools: + v.append("driver tools differ from the contract's tool schemas") + if h.info.get("instructions_match_readme") is False: + v.append("driver instructions != preamble + README") + out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"]) + with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f: + json.dump(out, f, indent=1) + return out diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_height.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_height.py new file mode 100644 index 0000000000000000000000000000000000000000..2f646b10c0ee78aeac6f5ce86d655bc26a42dc86 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_height.py @@ -0,0 +1,448 @@ +"""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 +vertical calibration is off. + +Category system_identification (level L1, action fine-tuning): the method (top-down pick across the tile's short +side with the fingertips just above the block's top, carry, release above the plate) and the scene understanding +are right; only the robot's own vertical execution is off. + +Hidden variable: a fixed vertical calibration offset dz ~ U[2.0, 3.5] cm (always upward), added to every +commanded gripper position (`Skills(bias=(0, 0, dz))`): the gripper stops dz higher than commanded. The agent never +sees dz; positions reported back to it are in the commanded frame (`HeightSkills.reported_eef_pos`, and the agent +harness reports eef - bias), so the robot "believes" it reached the commanded height. + +Why the prior fails: the tile is 1.0 cm thick. Sent to the right height (fingertips just above the block's top), the +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 +above it (measured tolerance, 6 layouts: upward errors up to 0.4 cm still grasp, >= 0.7 cm never do, i.e. the fingers +must overlap the tile by ~4 mm). dz >= 2 cm also defeats a prior that aims lower: even with the grasp point commanded +level with the block's top (fingertips ~1 cm into the block), the fingertips end up >= 1.05 cm above the block's +top, i.e. not below the tile's top face -> missed. +Visible in the agentview image (gap between the closed fingers and the tile) and in the wrist image (fingers closed +over the tile). +A downward error would not fail (the fingertips land on the block's top and the compliant OSC still closes on the +tile; measured for -1 and -2 cm), so the offset is upward only. + +Why a raised block: the agent's move_to clips commanded targets to >= table + 0.5 cm. With the tile on the table, +compensating a 2-3.5 cm upward offset would need commands below the table top, which the interface refuses; on a +6-10 cm block the compensated commands stay well inside the workspace. + +What has to be learned: F2 reports how far above the tile's top face the grasp point and the fingertips were when the +jaws closed. Compared with where the policy meant to put them, that is dz itself, so after one failure dz can be +estimated and subtracted from every commanded height (pick and place alike). +""" +import re + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TILE, STAND, PLATE = "tile_1", "stand_1", "plate_1" +DISTRACTORS = ("butter_1", "chocolate_pudding_1") +FREE_OBJECTS = (TILE, PLATE) + DISTRACTORS +NAMES = {TILE: "red tile", STAND: "wooden block", PLATE: "plate", "butter_1": "butter", + "chocolate_pudding_1": "chocolate pudding"} +DESCR = {TILE: "thin red slab", STAND: "large wooden pedestal", PLATE: "round white dish", "butter_1": "small orange box", + "chocolate_pudding_1": "brown box"} + +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) +TILE_T = 2 * TILE_HALF[2] +STAND_HALF_XY = (0.075, 0.085) # 15 x 17 cm top +STAND_H_RANGE = (0.06, 0.10) +MASS = {TILE: 0.072, "butter_1": 0.250, "chocolate_pudding_1": 0.200, PLATE: 0.350} + +FINGER_BELOW_SITE = 0.0095 # lowest point of the finger collision meshes below the grasp site (measured 0.95 cm) +SITE_ABOVE_SURFACE = 0.0105 # scripted grasp height: grasp point 1.05 cm above the block top (fingertips ~1 mm above) +CARRY_ABOVE = 0.12 # carry height above the block top +RELEASE_GAP = 0.012 # tile bottom this far above the plate's rim at release +PLATE_R_OK = 0.040 # success: tile centre within this horizontal distance of the plate centre +DZ_MIN, DZ_MAX = 0.020, 0.035 +TILE_YAW_MAX = np.deg2rad(40) +HOME_XY = np.array([-0.21, 0.0]) + + +def _seg_dist(p, a, b): + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +def vert_words(h, what): + if h >= 0.0005: + return f"{100 * h:.1f} cm above {what}" + if h <= -0.0005: + return f"{100 * -h:.1f} cm below {what}" + return f"level with {what}" + + +class HeightSkills(Skills): + """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent).""" + + def __init__(self, env, bias=None, recorder=None, stand_geoms=()): + super().__init__(env, bias=bias, recorder=recorder) + self.events = [] + m = env.sim.model + self._finger_geoms = { + side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]] + for side in ("left_finger", "right_finger")} + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS} + self._obj_geoms[STAND] = list(stand_geoms) + self.tile_z0 = float(envs.obj_pos(env, TILE)[2]) + self.tile_zmax = self.tile_z0 + self.tile_ref = envs.obj_pos(env, TILE) # tile position before the fingers last touched it + self.tile_ref_yaw = self.tile_yaw() + + def reported_eef_pos(self): + """End-effector position as the miscalibrated robot believes it to be (commanded frame). Anything shown to + the agent must use this, never eef_pos(), which is the true position and reveals the bias.""" + return self.eef_pos() - self.bias + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["pos"] = np.round(self.reported_eef_pos(), 4).tolist() + return rep + + def touching(self): + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def holding_tile(self): + """Both fingers in contact with the tile (robosuite's _check_grasp needs the finger *pads*, which miss a + 1 cm tile when it is gripped low on the finger meshes).""" + tg = self._obj_geoms[TILE] + return all(envs.contacts_between(self.env, gs, tg) for gs in self._finger_geoms.values()) + + def holding(self, obj_name): + """The agent harness reports `holding_object` through this; use the finger-contact test for the tile so a + tile gripped low on the fingers is not reported as dropped.""" + if obj_name == TILE: + return self.holding_tile() + return super().holding(obj_name) + + def tile_yaw(self): + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3) + return float(np.arctan2(xmat[1, 0], xmat[0, 0])) + + def finger_min_z(self): + return float(self.eef_pos()[2] - FINGER_BELOW_SITE) + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.tile_zmax = max(self.tile_zmax, float(envs.obj_pos(self.env, TILE)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[TILE]): + self.tile_ref = envs.obj_pos(self.env, TILE) + self.tile_ref_yaw = self.tile_yaw() + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), finger_z=self.finger_min_z(), + tile=envs.obj_pos(self.env, TILE).tolist(), + tile_ref=np.asarray(self.tile_ref).tolist(), tile_ref_yaw=self.tile_ref_yaw, + touching=self.touching(), + step=self.n_steps)) + elif not close and self.grip > 0 and self.holding_tile(): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), + tile=envs.obj_pos(self.env, TILE).tolist(), + plate=envs.obj_pos(self.env, PLATE).tolist(), step=self.n_steps)) + return super().set_gripper(close, steps) + + +@register_task +class HeightBias(LFFTask): + name = "l1_height_bias" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + instruction = "Pick up the red tile from the top of the wooden block and put it on the plate." + instruction_indirect = ("Pick up the thin flat red slab lying on the large wooden pedestal and put it on the " + "round white dish.") + pick_lift_min = 0.03 + + # ------------------------------------------------------------ scene + def make_bddl(self): + tile = register_generated("LffHbTile", box_xml("lff_hb_tile", TILE_HALF, (0.80, 0.16, 0.12, 1.0), + density=2000)) + stand = register_generated("LffHbStand", box_xml("lff_hb_stand", STAND_HALF_XY + (STAND_H_RANGE[1] / 2,), + (0.62, 0.47, 0.30, 1.0), density=1000), free=False) + objs = [(TILE, tile, "tile_region", (-0.21, -0.26, -0.19, -0.24)), + (PLATE, "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26)), + ("butter_1", "butter", "butter_region", (-0.21, 0.24, -0.19, 0.26)), + ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.15, -0.26, 0.17, -0.24))] + fx = [(STAND, stand, "stand_region", (0.09, -0.01, 0.11, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS} + m = self.env.sim.model + bid = m.body_name2id(self.env.fixtures_dict[STAND].root_body) + + def under(b): + while b > 0: + if b == bid: + return True + b = m.body_parentid[b] + return False + + self._stand_bid = bid + self._stand_geoms = [g for g in range(m.ngeom) if under(m.geom_bodyid[g])] + + def _place(self, name, xy, yaw, z0=envs.TABLE_Z): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + s = np.array([rng.uniform(-0.10, 0.02), rng.uniform(-0.17, 0.17)]) + plate = np.array([rng.uniform(-0.17, 0.08), rng.uniform(-0.25, 0.25)]) + if np.linalg.norm(plate - s) < 0.24 or abs(plate[1] - s[1]) < 0.12: + continue # not right behind the block as seen from the front camera + placed = [s, plate] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)]) + if np.linalg.norm(p - s) < 0.16 or any(np.linalg.norm(p - o) < 0.12 for o in placed[1:]): + continue + if any(_seg_dist(p, a, b) < 0.09 for a, b in ((s, plate), (HOME_XY, s))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + stand_h = float(rng.uniform(*STAND_H_RANGE)) + tile_xy = s + rng.uniform(-0.02, 0.02, 2) + tile_yaw = float(rng.uniform(-TILE_YAW_MAX, TILE_YAW_MAX)) + dz = float(rng.uniform(DZ_MIN, DZ_MAX)) + return dict(seed=int(seed), stand_xy=s.round(5).tolist(), stand_h=stand_h, tile_xy=tile_xy.round(5).tolist(), + tile_yaw=tile_yaw, plate_xy=plate.round(5).tolist(), distractors=dis, bias=[0.0, 0.0, dz], + bias_dz=dz) + + def stand_top(self, inst): + return envs.TABLE_Z + inst["stand_h"] + + def apply_instance(self, inst): + m = self.env.sim.model + h = inst["stand_h"] + for g in self._stand_geoms: + m.geom_size[g, 2] = h / 2 + m.body_pos[self._stand_bid] = [inst["stand_xy"][0], inst["stand_xy"][1], envs.TABLE_Z + h / 2] + m.body_quat[self._stand_bid] = [1, 0, 0, 0] + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self.env.sim.forward() + self._place(TILE, inst["tile_xy"], inst["tile_yaw"], z0=self.stand_top(inst)) + self._place(PLATE, inst["plate_xy"], 0.0) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def skill_bias(self, inst): + return np.array(inst["bias"], float) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = HeightSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, stand_geoms=self._stand_geoms) + self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS} + return self.sk + + # ------------------------------------------------------------ outcome + def plate_rim_z(self): + lo, hi = self._aabb(PLATE) + return float(hi[2]) + + def _aabb(self, name): + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + for g in envs.obj_geom_ids(self.env, name): + R = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3] + hh = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - hh), np.maximum(hi, c + hh) + return lo, hi + + def on_plate(self): + p = envs.obj_pos(self.env, PLATE) + t = envs.obj_pos(self.env, TILE) + return bool(np.linalg.norm(t[:2] - p[:2]) < PLATE_R_OK and t[2] < self.plate_rim_z() + 0.015 + and envs.obj_upright_cos(self.env, PLATE) > 0.9 and envs.obj_min_z(self.env, PLATE) < envs.TABLE_Z + 0.01) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + top = self.stand_top(inst) + p = envs.obj_pos(self.env, PLATE) + t = envs.obj_pos(self.env, TILE) + held = sk.holding_tile() + success = bool(self.on_plate() and not held) + picked = sk.tile_zmax > sk.tile_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + end_off = t[:2] - p[:2] + on_stand = bool(t[2] > top - 0.005) + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), tile_end=t.round(4).tolist(), + plate_end=p.round(4).tolist(), end_offset=end_off.round(4).tolist(), grasp_height=None, + fingertip_gap=None, grasp_xy_offset=None, touched_at_close=None, release_offset=None) + grasp_txt = "" + over_tile = True + if last_close is not None: + tile_top = last_close["tile_ref"][2] + TILE_HALF[2] + gh = last_close["eef"][2] - tile_top + fg = last_close["finger_z"] - tile_top + go = np.array(last_close["eef"][:2]) - np.array(last_close["tile_ref"][:2]) + a = last_close.get("tile_ref_yaw", 0.0) + along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)] + # grasp point over the tile's footprint (the open fingers straddle it across its short side) + over_tile = bool(abs(along) <= TILE_HALF[0] and abs(across) <= TILE_HALF[1] + 0.01) + out["grasp_height"] = round(gh, 4) + out["fingertip_gap"] = round(fg, 4) + out["grasp_xy_offset"] = go.round(4).tolist() + out["grasp_over_tile"] = over_tile + out["touched_at_close"] = last_close["touching"] + face = "the top face of the red tile" if over_tile else "the level of the red tile's top face" + grasp_txt = (f"When the jaws closed, the grasp point (midway between the fingertips) was " + f"{vert_words(gh, face)} and the lowest points of the fingertips " + f"were {vert_words(fg, 'it')} (the tile is {100 * TILE_T:.1f} cm thick)") + if not over_tile or np.linalg.norm(go) >= 0.01: + grasp_txt += (f"; horizontally the grasp point was {dir_words(*go)} of the tile's centre" + + ("" if over_tile else ", i.e. not over the tile")) + if success: + out["failure"] = None + detail = "The red tile is on the plate." + if grasp_txt: + detail += f" {grasp_txt}." + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the red tile was not picked up." + else: + touch = last_close["touching"] + if not over_tile and TILE not in touch: + why = " The gripper was not over the tile when it closed." + elif fg > 0.0005 and TILE not in touch: + why = " The fingers closed in the air above the tile without touching it." + elif STAND in touch and TILE not in touch: + why = " The fingertips were pressed on the top of the wooden block but did not grip the tile." + elif TILE in touch: + why = " The fingers touched the tile but did not get a grip on it." + else: + why = "" + where = "still on the wooden block" if on_stand else "no longer on the wooden block" + detail = f"{grasp_txt}, and the tile was not picked up.{why} The tile is {where}." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt}, and the tile was picked up, but it is still in the gripper." + elif releases: + r = releases[-1] + out["release_offset"] = (np.array(r["tile"][:2]) - np.array(r["plate"][:2])).round(4).tolist() + out["failure"] = "missed_place" + detail = (f"{grasp_txt}, and the tile was picked up. When the gripper opened, the tile was " + f"{dir_words(*out['release_offset'])} of the plate's centre; it did not end up on the plate " + f"(it is now {dir_words(*end_off)} of the plate's centre).") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt}, and the tile was lifted, but it slipped out of the fingers before it was " + f"released; it is now {dir_words(*end_off)} of the plate's centre.") + out["detail"] = detail + ind = detail + for k in sorted(NAMES, key=lambda n: -len(NAMES[n])): + ind = ind.replace(NAMES[k], DESCR[k]) + ind = re.sub(r"\btile\b", "slab", ind) # the bare noun would give the direct name away + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def grasp_yaw(self): + """Gripper yaw that closes the jaws across the tile's short side (yaw 0 closes along world y).""" + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, TILE)].reshape(3, 3) + a = np.arctan2(xmat[1, 0], xmat[0, 0]) + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + def execute(self, inst, params): + """Top-down pick across the tile's short side with the fingertips just above the block top, carry, release + above the plate. params['dz'] is the policy's own height correction, added to every commanded z.""" + sk = self.sk + dz = float(params.get("dz", 0.0)) + t = envs.obj_pos(self.env, TILE) # perfect perception of the current scene + top = self.stand_top(inst) + yaw = self.grasp_yaw() + p = envs.obj_pos(self.env, PLATE) + z_grasp = top + SITE_ABOVE_SURFACE + dz + z_carry = top + CARRY_ABOVE + dz + z_rel = self.plate_rim_z() + RELEASE_GAP + SITE_ABOVE_SURFACE + dz + sk.set_gripper(False, steps=8) + sk.move_to([t[0], t[1], z_carry], yaw=yaw) + sk.move_to([t[0], t[1], z_grasp + 0.05], tol=0.002) + sk.move_to([t[0], t[1], z_grasp], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([t[0], t[1], z_carry], speed=0.3) + if not sk.holding_tile(): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([p[0], p[1], z_carry], tol=0.003) + sk.move_to([p[0], p[1], z_rel], tol=0.003, max_steps=100) + sk.set_gripper(False, steps=12) + sk.move_to([p[0], p[1], z_carry], speed=0.3) + + def default_params(self, inst): + return dict(dz=0.0) + + def oracle_params(self, inst): + return dict(dz=-float(inst["bias"][2])) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported grasp height above the tile's top face, minus the height this policy + meant to put the grasp point at (SITE_ABOVE_SURFACE - tile thickness), is the vertical offset; accumulate + it into the correction subtracted from every commanded height.""" + last = history[-1] + dz = float(last["params"]["dz"]) + o = last["outcome"] + if o.get("grasp_height") is not None: + dz -= o["grasp_height"] - (SITE_ABOVE_SURFACE - TILE_T) + return dict(dz=round(dz, 4)) + + blind_sigma = 0.005 + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the commanded heights; no use of history.""" + return dict(dz=round(float(rng.normal(0.0, self.blind_sigma)), 4)) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_yaw.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_yaw.py new file mode 100644 index 0000000000000000000000000000000000000000..9bec2a49ccd283ea359cad9dd9b87efbbae7f9ac --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l1_yaw.py @@ -0,0 +1,439 @@ +"""L1-C yaw_bias: put a long bar into a narrow holder, with an arm whose wrist rotation is miscalibrated. + +Category system_identification (level L1, action fine-tuning): the method (top-down pick across the bar, carry, +line the bar up with the holder, release just above the holder) and the scene understanding are right; only the +robot's own wrist rotation is off. + +Hidden variable: a fixed wrist-yaw calibration offset beta, |beta| ~ U[15, 30] deg with a random sign: every +commanded gripper yaw theta is executed as theta + beta. The robot reports its yaw in its own (miscalibrated) frame, +so the agent's proprioception says "yaw = theta" (implemented by shifting the robot's notion of yaw 0, `Skills.R0`, +by beta: the agent harness computes the reported yaw from R0, so beta never shows up in a reading). At reset the +wrist is turned to the robot's own yaw 0 (true yaw beta), so the first reading is 0. + +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). +Commanded to grasp square across the bar, the jaws actually come down rotated by beta; closing turns the bar until it +lies square in the jaws, so the bar ends up rotated by beta relative to where the robot thinks it is. Lined up +"exactly" with the holder, the bar is then beta off the holder's axis; its footprint across the opening +(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 +down across the walls and stays on top of the holder at an angle -- clearly visible from both cameras. The +alignment tolerance is about +-5 deg (geometry; measured: see the task card). + +What has to be learned: F2 reports by how many degrees, and in which sense, the bar's long axis was rotated from the +holder's long axis when the gripper opened (and how far the jaws were turned from square to the bar when they +closed). That angle is beta itself, so after one failure beta can be estimated and subtracted from every commanded +yaw. +""" +import re + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import bin_xml, box_xml, register_generated +from ..skills import Skills, _rotz +from ..task_base import LFFTask, register_task + +BAR, HOLDER = "bar_1", "holder_1" +DISTRACTORS = ("cream_cheese_1", "butter_1") +FREE_OBJECTS = (BAR,) + DISTRACTORS +NAMES = {BAR: "blue bar", HOLDER: "holder", "cream_cheese_1": "cream cheese", "butter_1": "butter"} +DESCR = {BAR: "long blue stick", HOLDER: "narrow grey trough", "cream_cheese_1": "flat blue box", + "butter_1": "small orange box"} + +BAR_HALF = (0.070, 0.009, 0.009) # 14 x 1.8 x 1.8 cm, long side along the bar's x axis +HOLDER_IN = (0.080, 0.016) # inner half extents of the holder's opening: 16 x 3.2 cm +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030 +HOLDER_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +MASS = {BAR: 0.070, "cream_cheese_1": 0.227, "butter_1": 0.250} +# Bar friction 0.5 with geom priority, so it is used for all bar contacts (also against the finger pads, mu 2). With +# the pads' mu 2 the jaws pinch a misaligned bar at their corners and it stays skewed in the hand (measured: turned +# 3-13 deg of beta 15-25 deg while closing); with 0.5 the closing jaws square it up (turned = beta, measured). +BAR_MU = 0.5 + +SITE_ABOVE_TABLE = 0.0105 # grasp point 1.05 cm above the table: fingertips ~1 mm above it +Z_CARRY = envs.TABLE_Z + 0.15 +RELEASE_GAP = 0.012 # bar bottom this far above the holder's rim at release +BETA_MIN, BETA_MAX = np.deg2rad(15), np.deg2rad(30) +AXIS_MAX = np.deg2rad(45) # bar / holder long axes within +-45 deg of the forward (x) direction +HOME_XY = np.array([-0.21, 0.0]) +REHOME_STEPS = 40 + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (the bar, the holder and the jaws are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_of_xmat(xmat): + return float(np.arctan2(xmat[1, 0], xmat[0, 0])) + + +def _seg_dist(p, a, b): + ab = b - a + u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1) + return float(np.linalg.norm(a + u * ab - p)) + + +def _q(axis, a): + h = a / 2 + return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + w1, x1, y1, z1 = a + w2, x2, y2, z2 = b + return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, + w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]) + + +def dir_words(dx, dy): + """Robot-frame description: +x = forward (away from the robot), +y = the robot's left.""" + parts = [] + if abs(dy) >= 0.0005: + parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}") + if abs(dx) >= 0.0005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}") + return " and ".join(parts) if parts else "exactly at the position" + + +def rot_words(a): + """Sense of a rotation about the vertical axis. Positive = counter-clockwise seen from above = from forward (+x) + towards the robot's left (+y) = increasing yaw.""" + d = np.degrees(a) + if abs(d) < 0.5: + return "not rotated (within 0.5 deg)" + if d > 0: + return f"rotated {d:.0f} deg counter-clockwise seen from above (from forward towards the robot's left, +yaw)" + return f"rotated {-d:.0f} deg clockwise seen from above (from forward towards the robot's right, -yaw)" + + +class YawSkills(Skills): + """Skills with a miscalibrated wrist: commanded yaw theta is executed as theta + yaw_bias. Implemented by shifting + the robot's notion of yaw 0 (`R0`, which Skills uses to build every orientation target and the agent harness uses + to report the yaw) by yaw_bias; `R0_true` is the real top-down orientation at yaw 0. Also logs what the outcome + measurement needs, whoever drives the skills (scripted policy or agent).""" + + def __init__(self, env, yaw_bias=0.0, recorder=None): + super().__init__(env, bias=None, recorder=recorder) + self.yaw_bias = float(yaw_bias) + self.R0_true = self.R0.copy() + self.R0 = _rotz(self.yaw_bias) @ self.R0_true + self.events = [] + m = env.sim.model + self._finger_geoms = { + side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]] + for side in ("left_finger", "right_finger")} + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")] + self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS} + self.bar_z0 = float(envs.obj_pos(env, BAR)[2]) + self.bar_zmax = self.bar_z0 + self.bar_ref_yaw = self.bar_yaw() + self.bar_ref = envs.obj_pos(env, BAR) # bar pose before the fingers last touched it + + # ------------------------------------------------------------------ state + def true_yaw(self): + return _yaw_of_xmat(self.eef_mat() @ self.R0_true.T) + + def reported_yaw(self): + """Yaw as the miscalibrated robot believes it to be. Anything shown to the agent must use this.""" + return _yaw_of_xmat(self.eef_mat() @ self.R0.T) + + def bar_yaw(self): + return _yaw_of_xmat(self.env.sim.data.body_xmat[envs.body_id(self.env, BAR)].reshape(3, 3)) + + def touching(self): + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def holding_bar(self): + bg = self._obj_geoms[BAR] + return all(envs.contacts_between(self.env, gs, bg) for gs in self._finger_geoms.values()) + + def holding(self, obj_name): + """The agent harness reports `holding_object` through this; same finger-contact test as the outcome.""" + if obj_name == BAR: + return self.holding_bar() + return super().holding(obj_name) + + def wrap_yaw(self, yaw): + """Like Skills.wrap_yaw (the gripper is symmetric under pi), but the window |yaw| <= YAW_LIMIT is applied + to the TRUE wrist yaw (commanded + yaw_bias): the joint-7 limit is a property of the real wrist. Without + this, a commanded -113 deg with yaw_bias -30 deg drives joint 7 into its limit (measured: stops at true + -137 deg, reported -107 deg).""" + cands = [yaw + k * np.pi for k in range(-3, 4)] + ok = [c for c in cands if abs(c + self.yaw_bias) <= self.YAW_LIMIT] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw))) + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + rep["yaw_reported_deg"] = round(float(np.degrees(self.reported_yaw())), 1) + return rep + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.bar_zmax = max(self.bar_zmax, float(envs.obj_pos(self.env, BAR)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[BAR]): + self.bar_ref_yaw = self.bar_yaw() + self.bar_ref = envs.obj_pos(self.env, BAR) + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(), + bar=envs.obj_pos(self.env, BAR).tolist(), bar_ref_yaw=self.bar_ref_yaw, + bar_ref=np.asarray(self.bar_ref).tolist(), touching=self.touching(), + step=self.n_steps)) + elif not close and self.grip > 0 and self.holding_bar(): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(), + bar=envs.obj_pos(self.env, BAR).tolist(), bar_yaw=self.bar_yaw(), + step=self.n_steps)) + rep = super().set_gripper(close, steps) + if close and self.events and self.events[-1]["kind"] == "close": + self.events[-1]["bar_yaw_after"] = self.bar_yaw() + return rep + + +@register_task +class YawBias(LFFTask): + name = "l1_yaw_bias" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + instruction = "Pick up the blue bar and put it into the holder." + instruction_indirect = "Pick up the long blue stick and drop it into the narrow grey trough so that it lies inside." + pick_lift_min = 0.03 + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffYbBar", box_xml("lff_yb_bar", BAR_HALF, (0.15, 0.35, 0.85, 1.0), density=1500)) + holder = register_generated("LffYbHolder", bin_xml("lff_yb_holder", HOLDER_IN, WALL_H, wall_t=WALL_T, + floor_t=FLOOR_T, rgba=(0.55, 0.56, 0.60, 1.0), + density=2000), free=False) + objs = [(BAR, bar, "bar_region", (-0.21, -0.26, -0.19, -0.24)), + ("cream_cheese_1", "cream_cheese", "cheese_region", (-0.21, 0.24, -0.19, 0.26)), + ("butter_1", "butter", "butter_region", (0.15, -0.26, 0.17, -0.24))] + fx = [(HOLDER, holder, "holder_region", (0.09, -0.01, 0.11, 0.01))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS} + m = self.env.sim.model + self._holder_bid = m.body_name2id(self.env.fixtures_dict[HOLDER].root_body) + + def _place(self, name, xy, yaw, z0=envs.TABLE_Z): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q) + self.env.sim.forward() + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + b = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)]) + h = np.array([rng.uniform(-0.14, 0.06), rng.uniform(-0.22, 0.22)]) + if np.linalg.norm(h - b) < 0.22: + continue + placed = [b, h] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)]) + if any(np.linalg.norm(p - o) < 0.15 for o in placed): + continue + if any(_seg_dist(p, a, c) < 0.10 for a, c in ((b, h), (HOME_XY, b))): + continue + break + else: + break + placed.append(p) + dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi))) + if len(dis) == len(DISTRACTORS): + break + bar_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX)) + holder_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX)) + beta = float(rng.choice([-1.0, 1.0]) * rng.uniform(BETA_MIN, BETA_MAX)) + return dict(seed=int(seed), bar_xy=b.round(5).tolist(), bar_yaw=bar_yaw, holder_xy=h.round(5).tolist(), + holder_yaw=holder_yaw, distractors=dis, yaw_bias=beta, yaw_bias_deg=float(np.degrees(beta))) + + def apply_instance(self, inst): + m = self.env.sim.model + m.body_pos[self._holder_bid] = [inst["holder_xy"][0], inst["holder_xy"][1], envs.TABLE_Z + HOLDER_HALF_H] + m.body_quat[self._holder_bid] = _q("z", inst["holder_yaw"]) + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self.env.sim.forward() + self._place(BAR, inst["bar_xy"], inst["bar_yaw"]) + envs.set_friction(self.env, BAR, BAR_MU, priority=3) + for name, v in inst["distractors"].items(): + self._place(name, v["xy"], v["yaw"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = YawSkills(self.env, yaw_bias=inst["yaw_bias"], recorder=recorder) + self.sk.hold(REHOME_STEPS) # turn the wrist to the robot's own yaw 0 (true yaw = beta) + self.sk.n_steps = 0 + self.sk.events = [] + self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS} + return self.sk + + # ------------------------------------------------------------ outcome + def holder_frame(self, xy): + """xy (world) -> (along, across) in the holder frame, relative to the holder centre""" + c = self.env.sim.model.body_pos[self._holder_bid][:2].copy() + a = self.holder_yaw() + R = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]]) + return R @ (np.asarray(xy[:2]) - c) + + def holder_yaw(self): + q = self.env.sim.model.body_quat[self._holder_bid] + return float(2 * np.arctan2(q[3], q[0])) + + def in_holder(self): + p = envs.obj_pos(self.env, BAR) + u, v = self.holder_frame(p) + return bool(abs(u) < HOLDER_IN[0] and abs(v) < HOLDER_IN[1] and p[2] < RIM_Z + and envs.obj_upright_cos(self.env, BAR) > 0.95) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + p = envs.obj_pos(self.env, BAR) + held = sk.holding_bar() + success = bool(self.in_holder() and not held) + picked = sk.bar_zmax > sk.bar_z0 + self.pick_lift_min + closes = [e for e in sk.events if e["kind"] == "close"] + last_close = closes[-1] if closes else None + releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]] + hy = self.holder_yaw() + end_mis = wrap_half(sk.bar_yaw() - hy) + hc = self.env.sim.model.body_pos[self._holder_bid][:2] + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), bar_end=p.round(4).tolist(), + bar_end_misalign_deg=round(float(np.degrees(end_mis)), 1), grasp_misalign=None, + bar_turned_in_grasp=None, release_misalign=None, release_offset=None, touched_at_close=None) + grasp_txt = "" + if last_close is not None: + gm = wrap_half(last_close["true_yaw"] - last_close["bar_ref_yaw"]) + turned = wrap_half(last_close.get("bar_yaw_after", last_close["bar_ref_yaw"]) - last_close["bar_ref_yaw"]) + out["grasp_misalign"] = round(gm, 4) + out["bar_turned_in_grasp"] = round(turned, 4) + out["touched_at_close"] = last_close["touching"] + go = np.array(last_close["eef"][:2]) - np.array(last_close.get("bar_ref", last_close["bar"])[:2]) + a = last_close["bar_ref_yaw"] + along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)] + over_bar = bool(abs(along) <= BAR_HALF[0] and abs(across) <= BAR_HALF[1] + 0.02) + out["grasp_xy_offset"] = go.round(4).tolist() + out["grasp_over_bar"] = over_bar + if over_bar: + grasp_txt = f"When the jaws closed on the blue bar, they were {rot_words(gm)} from square across the bar" + if np.linalg.norm(go) >= 0.015: + grasp_txt += f" (the grasp point was {dir_words(*go)} of the bar's centre)" + else: + grasp_txt = (f"When the jaws closed, the grasp point was {dir_words(*go)} of the blue bar's centre, i.e. " + f"not over the bar, and the jaws were {rot_words(gm)} from square across the bar") + if abs(np.degrees(turned)) >= 2: + grasp_txt += f", and the closing fingers turned the bar by {abs(np.degrees(turned)):.0f} deg" + if releases: + r = releases[-1] + rm = wrap_half(r["bar_yaw"] - hy) + out["release_misalign"] = round(rm, 4) + out["release_offset"] = (np.array(r["bar"][:2]) - hc).round(4).tolist() + if success: + out["failure"] = None + detail = "The blue bar is inside the holder." + if out["release_misalign"] is not None: + detail += (f" When the gripper opened, the bar's long axis was {rot_words(out['release_misalign'])} " + f"from the holder's long axis.") + elif not picked: + out["failure"] = "missed_grasp" + if last_close is None: + detail = "The gripper never closed; the blue bar was not picked up." + else: + detail = f"{grasp_txt}, but the bar was not picked up. It is still on the table." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt}. The bar was picked up but it is still in the gripper." + elif releases: + out["failure"] = "missed_place" + if p[2] > RIM_Z - 0.002: + where = (f"The bar came down across the holder's walls instead of dropping in; it is now lying on top " + f"of the holder, its long axis {rot_words(end_mis)} from the holder's long axis.") + else: + where = (f"The bar did not end up inside the holder (its centre is now " + f"{dir_words(*(p[:2] - hc))} of the holder's centre).") + detail = (f"{grasp_txt}. When the gripper opened above the holder, the bar's long axis was " + f"{rot_words(out['release_misalign'])} from the holder's long axis, and the bar's centre was " + f"{dir_words(*out['release_offset'])} of the holder's centre. {where}") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt}. The bar was lifted but slipped out of the fingers before the gripper opened; it is " + f"now {dir_words(*(p[:2] - hc))} of the holder's centre.") + out["detail"] = detail + ind = detail + for k in sorted(NAMES, key=lambda n: -len(NAMES[n])): + ind = ind.replace(NAMES[k], DESCR[k]) + ind = re.sub(r"\bbar\b", "stick", ind) # the bare noun would give the direct name away + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + if indirect and level == "F2": + out = dict(out, detail=out.get("detail_indirect", out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Top-down pick square across the bar at its centre, carry, line the bar up with the holder and release it + just above the holder's rim. params['dyaw'] (rad) is the policy's own yaw correction, added to every + commanded yaw.""" + sk = self.sk + dy = float(params.get("dyaw", 0.0)) + b = envs.obj_pos(self.env, BAR) # perfect perception of the current scene + psi = sk.bar_yaw() + hc = self.env.sim.model.body_pos[self._holder_bid][:2].copy() + phi = self.holder_yaw() + z_grasp = envs.TABLE_Z + SITE_ABOVE_TABLE + z_rel = RIM_Z + RELEASE_GAP + SITE_ABOVE_TABLE + sk.set_gripper(False, steps=8) + sk.move_to([b[0], b[1], Z_CARRY], yaw=wrap_half(psi) + dy) + sk.move_to([b[0], b[1], z_grasp + 0.06], tol=0.002) + sk.move_to([b[0], b[1], z_grasp], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([b[0], b[1], Z_CARRY], speed=0.3) + if not sk.holding_bar(): # missed: a real controller sees the jaws closed on nothing and stops + return + sk.move_to([hc[0], hc[1], Z_CARRY], yaw=wrap_half(phi) + dy, tol=0.003) + sk.move_to([hc[0], hc[1], z_rel], tol=0.003, max_steps=100) + sk.hold(5) + sk.set_gripper(False, steps=12) + sk.move_to([hc[0], hc[1], Z_CARRY], speed=0.3) + + def default_params(self, inst): + return dict(dyaw=0.0) + + def oracle_params(self, inst): + return dict(dyaw=-float(inst["yaw_bias"])) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported angle between the bar and the holder when the gripper opened is the + part of the wrist offset not yet corrected; accumulate it into the correction subtracted from every + commanded yaw. If the bar was never released, use the jaw angle at the grasp instead.""" + last = history[-1] + dy = float(last["params"]["dyaw"]) + o = last["outcome"] + if o.get("release_misalign") is not None: + dy -= o["release_misalign"] + elif o.get("grasp_misalign") is not None: + dy -= o["grasp_misalign"] + return dict(dyaw=round(dy, 4)) + + blind_sigma = np.deg2rad(4.0) + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the commanded yaws; no use of history.""" + return dict(dyaw=round(float(rng.normal(0.0, self.blind_sigma)), 4)) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l2_turntable.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l2_turntable.py new file mode 100644 index 0000000000000000000000000000000000000000..6cde2c1b38e0e5287e6df47831e640e545bf1f43 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l2_turntable.py @@ -0,0 +1,469 @@ +"""L2-C turntable_restore: take the butter off a turntable that stands half under a shelf, then turn the +turntable back exactly the way it was. + +Replaces the planned l2_drawer_reclosed (feasibility test 2026-10-07, see the task card): with the gripper +always pointing straight down, the handle of LIBERO's wooden_cabinet top drawer (3.8 cm below the cabinet +top) cannot be reached -- the descent stops 1.5-4.5 cm above it, closing grasps nothing (4/4 cabinet +placements) and a pull opened the drawer only 1/4 times, by accident. The turntable keeps the idea (an +articulated fixture the agent *has to* change to get the object and has to put back afterwards) and is +operable with move_to + open/close only. + +Scene: a turntable (lazy susan; disc radius 17 cm on a damped hinge about z) on the robot's right; a fixed +shelf board 10 cm above the disc covers its -y half (robot's right), so nothing under the board can be +grasped from above (measured, 20 seeds x 2 grasp yaws: the hand stops on the board 10-14 cm above the grasp +height, 0/40 lifts). Four red pegs stand near the rim; grasping a peg and moving the gripper along the rim +turns the disc. The butter lies on the disc under the board; painted marks (yellow stripe, blue square, +green dot; visual only) make the disc's angle readable. The basket stands on the robot's left. + +Why the first attempt fails (the L2 event is the agent's own, necessary change): to reach the butter the +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 +and stops leaves the turntable turned -> failure. To repair it the agent has to turn it back to its start +angle (+-15 deg); after the main turn the marks are elsewhere and nothing in the scene shows the start angle: +it is only in the first frame (or in the agent's memory of how far it turned). The F2 text says *that* the +turntable is not turned the way it was, never by how much or which way. + +Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective +round; the outcome (success + F2 text) is computed after each round. + +Scripted references (perception stand-in: simulator poses; motions: Skills.move_to / set_gripper only) + oracle turns, takes the butter, then immediately turns the disc back to the saved start angle. + naive turns, takes the butter, done. + adaptive saves the start angle (Save); after F2 "not turned the way it was" turns back to it (Retrieve + + Utilize); redoes the main task if the butter is not in the basket. + blind no history, no feedback: every later round redoes the main task (lifts the butter out of the + basket and drops it back, grasp jittered by 5 mm). + nomem (extra control, not in the acceptance table) gets F2 but has no start frame: turns the disc by a + random angle in (-180, 180] deg each round. + +Physics notes (all measured while building the task, 2026-10-07): the HOPE butter weighs 5 g -> set to 0.2 kg; +a box on a cylinder gets a single contact point and no torsional friction, so the butter span on the disc at +~4 deg/s even at rest -> the disc's collision surface is the inscribed square plate (visual disc stays round). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, register_generated +from ..task_base import LFFTask, register_task + +TT = "turntable_1" +TARGET = "butter_1" +ITEMS = (TARGET,) +BASKET = "basket_1" +MASS = {"butter_1": 0.20} # real-world order (the HOPE box weighs 5 g) + +# turntable geometry (fixture frame: origin on the table top at the disc axis) +R = 0.17 # disc radius +DISC_T = 0.012 # disc thickness +BASE_H = 0.012 # pedestal height +DISC_TOP = BASE_H + DISC_T # disc top above the table +PEG_R, PEG_RAD, PEG_H = 0.009, 0.155, 0.035 # radius, distance from the axis, height above the disc +# (low enough that the hand clears the pegs by 1 cm when it grasps the butter between them) +PEG_ANG = tuple(np.pi / 4 + k * np.pi / 2 for k in range(4)) # disc frame +STRIPE_ANG = np.pi # disc frame +BOARD_Z = DISC_TOP + 0.10 # underside of the shelf board above the table +BOARD_EDGE = 0.01 # the board covers fixture y < +1 cm (the -y half of the disc) +HINGE = dict(damping=1.0, armature=0.3, frictionloss=0.01) # the disc stops within ~1 deg when released +ITEM_R = 0.07 # butter's distance from the axis (disc frame); open fingers at a held peg clear it by >= 1.2 cm + +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) +BASKET_IN = 0.060 # LIBERO basket: half size of the inner floor +BASKET_RIM = 0.150 +BASKET_FLOOR = 0.017 +SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' + +NAMES = {TARGET: "butter"} +DESCR = {TARGET: "small orange box"} + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _wrap_half(a): + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _rot(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s], [s, c]]) + + +def turntable_xml(model_name): + """Static pedestal + shelf board + side wall; a hinged disc (child body) with 4 pegs and painted marks.""" + def geoms(kind, pos, size, rgba, coll=True, vis=True): + s = f'type="{kind}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}"' + out = [f''] if vis else [] + if coll: + out.insert(0, f'') + return out + + shelf = (0.82, 0.82, 0.80, 1.0) + fixed = geoms("cylinder", (0, 0, BASE_H / 2), (0.06, BASE_H / 2), (0.3, 0.3, 0.3, 1.0)) + by0, by1, bx = -(R + 0.04), BOARD_EDGE, R + 0.04 + fixed += geoms("box", (0, (by0 + by1) / 2, BOARD_Z + 0.004), (bx, (by1 - by0) / 2, 0.004), shelf) + fixed += geoms("box", (0, by0 + 0.005, BOARD_Z / 2), (bx, 0.005, BOARD_Z / 2), shelf) + # the round disc is visual only; its collision surface is the inscribed square plate: a box on a cylinder gets a + # single contact point and no torsional friction, and the butter span on the disc at ~4 deg/s even at rest (measured) + disc = geoms("cylinder", (0, 0, 0), (R, DISC_T / 2), (0.62, 0.42, 0.24, 1.0), coll=False) + 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) + for a in PEG_ANG: + disc += geoms("cylinder", (PEG_RAD * np.cos(a), PEG_RAD * np.sin(a), DISC_T / 2 + PEG_H / 2), + (PEG_R, PEG_H / 2), (0.75, 0.08, 0.08, 1.0)) + # painted marks (visual only) that make the disc's angle readable: yellow stripe, blue square, green dot + disc += geoms("box", (0.085 * np.cos(STRIPE_ANG), 0.085 * np.sin(STRIPE_ANG), DISC_T / 2 + 0.0006), + (0.055, 0.007, 0.0006), (0.95, 0.85, 0.10, 1.0), coll=False) + disc += geoms("box", (0.10 * np.cos(np.pi / 2), 0.10 * np.sin(np.pi / 2), DISC_T / 2 + 0.0006), + (0.016, 0.016, 0.0006), (0.15, 0.35, 0.85, 1.0), coll=False) + disc += geoms("cylinder", (0.10 * np.cos(-np.pi / 2), 0.10 * np.sin(-np.pi / 2), DISC_T / 2 + 0.0006), + (0.016, 0.0006), (0.15, 0.65, 0.25, 1.0), coll=False) + nl = "\n " + return f""" + + + + {nl.join(fixed)} + + + {nl.join(disc)} + + + + + + + + +""" + + +@register_task +class TurntableRestore(LFFTask): + name = "l2_turntable_restore" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + max_attempts = 5 + instruction = ("Put the butter into the basket. The butter is on the turntable, under the shelf. You can turn the " + "turntable by its red pegs. When you are done, the turntable must be turned exactly the way it is now.") + instruction_indirect = ("Put the small orange box into the wicker basket. It is on the round turntable, under the " + "shelf. You can turn the turntable by its red pegs. When you are done, the turntable must be " + "turned exactly the way it is now.") + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self._tt_bid = m.body_name2id(self.env.fixtures_dict[TT].root_body) + jid = m.joint_name2id(f"{TT}_spin") + self._qa, self._qv = m.jnt_qposadr[jid], m.jnt_dofadr[jid] + self.start = {} + self.turn_log = [] # per peg grasp: commanded sweep vs measured disc rotation (diagnostics) + self._home = None + self._c = np.zeros(2) + + # ------------------------------------------------------------ scene + def make_bddl(self): + tt = register_generated("LffTurntableShelf", turntable_xml("lff_turntable_shelf"), free=False) + 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)] + objs.append((BASKET, "basket", "r_basket", (-0.10, 0.24, -0.08, 0.26))) + fx = [(TT, tt, "tt_region", (0.25, 0.30, 0.27, 0.32))] # moved in apply_instance + return write_bddl(self.name, self.instruction.replace(";", ","), objs, fixtures=fx) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + c = np.array([rng.uniform(-0.08, -0.02), rng.uniform(-0.12, -0.08)]) + th = {TARGET: float(rng.uniform(-0.14, 0.14))} # disc-frame angle of the butter (stripe at 180 deg) + rad = {n: float(ITEM_R + rng.uniform(-0.005, 0.005)) for n in ITEMS} + tilt = {n: float(rng.uniform(-0.17, 0.17)) for n in ITEMS} # box yaw relative to radial + # start angle: the butter sits under the board (world azimuth -90 +- 40 deg about the axis) + q0 = float(_wrap(-np.pi / 2 - th[TARGET] + rng.uniform(-np.radians(40), np.radians(40)))) + return dict(seed=int(seed), center=c.round(4).tolist(), q0=q0, theta=th, rad=rad, tilt=tilt, + basket_xy=[float(rng.uniform(-0.12, -0.06)), float(rng.uniform(0.25, 0.28))]) + + def disc_angle(self): + return float(self.env.sim.data.qpos[self._qa]) + + def to_world(self, r, th, q=None): + q = self.disc_angle() if q is None else q + return self._c + r * np.array([np.cos(th + q), np.sin(th + q)]) + + def to_disc(self, xy, q=None): + q = self.disc_angle() if q is None else q + return _rot(-q) @ (np.asarray(xy, float)[:2] - self._c) + + def place(self, name, xy, yaw, surface_z): + """Teleport a box flat (its mesh frame is flat) with yaw about world z, lowest point 2 mm above surface_z.""" + envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], + quat_wxyz=np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)])) + self.env.sim.forward() + dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002) + qa, _ = envs.free_joint_addr(self.env, name) + self.env.sim.data.qpos[qa + 2] -= dz + self.env.sim.forward() + + def apply_instance(self, inst): + m, d = self.env.sim.model, self.env.sim.data + self._c = np.array(inst["center"], float) + m.body_pos[self._tt_bid] = [self._c[0], self._c[1], envs.TABLE_Z] + m.body_quat[self._tt_bid] = [1, 0, 0, 0] + d.qpos[self._qa] = inst["q0"] + d.qvel[self._qv] = 0.0 + self.env.sim.forward() + for n in ITEMS: + envs.scale_mass(self.env, n, MASS[n]) + th = inst["theta"][n] + # long axis radial (+ tilt): the gripper then closes tangentially and keeps clear of the board + self.place(n, self.to_world(inst["rad"][n], th, inst["q0"]), th + inst["q0"] + inst["tilt"][n], + envs.TABLE_Z + DISC_TOP) + envs.scale_mass(self.env, BASKET, 2.0) + self.place(BASKET, inst["basket_xy"], 0.0, envs.TABLE_Z) + self.env.sim.forward() + + def reset_instance(self, inst, recorder=None): + sk = super().reset_instance(inst, recorder) + self.start = dict(q=self.disc_angle()) + self._home = sk.eef_pos() + return sk + + # ------------------------------------------------------------ measurements + def footprint(self, name): + """AABB centre, yaw of the long horizontal axis, z range (scripted 'perception').""" + m, d = self.env.sim.model, self.env.sim.data + lo, hi = np.full(3, np.inf), np.full(3, -np.inf) + best = None + for g in envs.obj_geom_ids(self.env, name): + Rg = d.geom_xmat[g].reshape(3, 3) + c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3] + e = np.abs(Rg) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e) + vol = float(np.prod(m.geom_aabb[g, 3:])) + if best is None or vol > best[0]: + best = (vol, Rg, m.geom_aabb[g, 3:]) + _, Rg, half = best + horiz = sorted([(half[k], Rg[:, k]) for k in range(3) if abs(Rg[2, k]) < 0.5], key=lambda t: -t[0]) + ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0]) + return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])), + zmin=float(lo[2]), zmax=float(hi[2])) + + def item_loc(self, name): + f = self.footprint(name) + c = np.array(f["center"]) + held = self.sk is not None and self.sk.holding(name) + if held and f["zmin"] > envs.TABLE_Z + DISC_TOP + 0.01: + return "gripper", f + bp = envs.obj_pos(self.env, BASKET) + 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 \ + and f["zmin"] > envs.TABLE_Z + 0.005: + return "basket", f + on_disc = np.linalg.norm(c[:2] - self._c) < R and abs(f["zmin"] - (envs.TABLE_Z + DISC_TOP)) < 0.012 + if on_disc: + return "turntable", f + if f["zmin"] < envs.TABLE_Z + 0.01: + return "table", f + return "other", f + + def outcome(self, inst): + envs.settle(self.env, 30) + tloc, _ = self.item_loc(TARGET) + dq = _wrap(self.disc_angle() - self.start["q"]) + turned_ok = abs(dq) <= ANG_TOL + success = bool(tloc == "basket" and turned_ok) + return dict(success=success, target_loc=tloc, angle_err_deg=round(float(np.degrees(dq)), 1), + turned_ok=bool(turned_ok), + detail=self._describe(tloc, turned_ok, dq, NAMES), + detail_indirect=self._describe(tloc, turned_ok, dq, DESCR), + detail_offset=self._describe(tloc, turned_ok, dq, NAMES, offset=True)) + + @staticmethod + def _describe(tloc, turned_ok, dq, names, offset=False): + tn = names[TARGET] + msgs = [] + if tloc != "basket": + msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.", + "turntable": f"The {tn} is still on the turntable, not in the basket.", + "table": f"The {tn} is on the table, not in the basket."} + .get(tloc, f"The {tn} is not in the basket.")) + if not turned_ok: + m = "The turntable is not turned the way it was at the start." + if offset: # ablation tier: relative measurement, externalises the memory + m += (f" It is turned {abs(np.degrees(dq)):.0f} deg " + f"{'counter-clockwise' if dq > 0 else 'clockwise'} (seen from above) from its starting angle.") + msgs.append(m) + if not msgs: + msgs.append(f"The {tn} is in the basket and the turntable is turned the way it was at the start.") + return " ".join(msgs) + + def feedback(self, inst, out, level="F2", indirect=False, offset=False): + """F0: nothing, F1: success flag, F2: what is wrong (never by how much the turntable is off). + offset=True (ablation tier 'F2+offset'): also the relative turn from the start angle.""" + if level == "F2": + key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail") + out = dict(out, detail=out.get(key, out["detail"])) + return super().feedback(inst, out, level) + + # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper) + SAFE_Z = envs.TABLE_Z + 0.22 # travel height between pegs / items + PICK_AZ = np.pi / 2 # where the butter is brought: middle of the open side (at 135 deg the open finger lands on + # the board edge -- measured); grasp yaw ~ +-90 deg, so the wrist is turned back to 0 while + # carrying (arriving at the basket with yaw -103 deg left the arm stalled near a joint limit) + WIN = (np.radians(30), np.radians(150)) # world azimuths where a peg can be held (open side, clear of the board) + + def go_home(self): + sk = self.sk + p = sk.eef_pos() + sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + sk.move_to(self._home, yaw=0.0) + + def _settle_yaw(self, tol=np.radians(3), max_steps=40): + """move_to stops on position only; after a large wrist rotation hold until the yaw has converged (a descent + that starts mid-rotation swipes the open fingers across the pegs -- measured).""" + sk = self.sk + for _ in range(max_steps // 5): + R = sk.eef_mat() @ sk.R0.T + if abs(_wrap(np.arctan2(R[1, 0], R[0, 0]) - sk.yaw)) < tol: + return + sk.hold(5) + + def peg_azimuths(self): + return [_wrap(self.disc_angle() + a) for a in PEG_ANG] + + def turn(self, delta, step=np.radians(10)): + """Turn the disc by `delta` rad (+ = counter-clockwise seen from above): grasp a peg on the open side, + move the gripper along the rim in short straight segments, release, repeat.""" + sk = self.sk + zg = envs.TABLE_Z + DISC_TOP + PEG_H - 0.012 + rem = float(delta) + for _ in range(6): + if abs(rem) < np.radians(1.0): + break + az = self.peg_azimuths() + if rem > 0: + cands = [a for a in az if self.WIN[0] - 1e-6 <= a <= self.WIN[1] - np.radians(10)] + a0 = min(cands) + sweep = min(rem, self.WIN[1] - a0) + else: + cands = [a for a in az if self.WIN[0] + np.radians(10) <= a <= self.WIN[1] + 1e-6] + a0 = max(cands) + sweep = max(rem, self.WIN[0] - a0) + q_before = self.disc_angle() + p = self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]) + sk.set_gripper(False, steps=6) + # up, across, straight down: a long diagonal move at full speed sags ~5 cm below its line and the open + # fingers sweep the disc (measured: turned it 38 deg the wrong way) + cur = sk.eef_pos() + if cur[2] < self.SAFE_Z - 0.02: + sk.move_to([cur[0], cur[1], self.SAFE_Z]) + sk.move_to([p[0], p[1], self.SAFE_Z], yaw=np.pi / 2) # fingers close along world x + self._settle_yaw() + sk.move_to([p[0], p[1], zg + 0.03], speed=0.4) + sk.move_to([p[0], p[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + 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(), + w=round(sk.gripper_width() * 100, 1), q_close=round(float(np.degrees(_wrap(self.disc_angle() - q_before))), 1), + yaw=round(float(np.degrees(sk.yaw)), 0)) + k = max(1, int(np.ceil(abs(sweep) / step))) + for i in range(1, k + 1): + w = self._c + PEG_RAD * np.array([np.cos(a0 + sweep * i / k), np.sin(a0 + sweep * i / k)]) + sk.move_to([w[0], w[1], zg], tol=0.003, max_steps=40) + sk.set_gripper(False, steps=8) + pe = sk.eef_pos() + sk.move_to([pe[0], pe[1], zg + 0.10]) + got = _wrap(self.disc_angle() - q_before) + self.turn_log.append(dict(peg_az=round(float(np.degrees(a0)), 1), sweep=round(float(np.degrees(sweep)), 1), + got=round(float(np.degrees(got)), 1), **dbg)) + rem -= got + + def pick_place(self, name, dest_xy, support_z, fp=None, carry_z=1.20, travel_z=1.15, carry_yaw=0.0): + """Top-down pick across the short side, carry, release just above support_z at dest_xy.""" + sk = self.sk + f = fp or self.footprint(name) + c = np.array(f["center"]) + gyaw = _wrap_half(f["yaw"]) + zg = max(f["zmin"] + 0.5 * (f["zmax"] - f["zmin"]), f["zmin"] + 0.0145) + sk.set_gripper(False, steps=6) + p = sk.eef_pos() + if p[2] < travel_z - 0.02: + sk.move_to([p[0], p[1], travel_z]) + sk.move_to([c[0], c[1], travel_z], yaw=gyaw) + self._settle_yaw() + sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4) + sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=12) + sk.move_to([c[0], c[1], carry_z], speed=0.3) + sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=carry_yaw) + 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) + sk.hold(4) + sk.set_gripper(False, steps=10) + sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4) + + def butter_to_basket(self, fp=None): + """The main task: if the butter is on the turntable, turn it to the open side first.""" + loc, f = self.item_loc(TARGET) + if loc == "turntable": + az = np.arctan2(f["center"][1] - self._c[1], f["center"][0] - self._c[0]) + # bring the butter's long axis parallel to world y (then the hand lies along x, away from the board edge; + # a hand turned 26 deg off caught the board -- measured); its centre ends within ~30 deg of PICK_AZ + delta = _wrap_half(f["yaw"] - az) + self.turn(_wrap(self.PICK_AZ - delta - az)) + b = envs.obj_pos(self.env, BASKET) + # release with the hand above the rim and let the box drop in: lowering it to the floor puts the 20 cm long + # hand below the rim of the 12 cm basket and the contact flips the wrist (joint 5 at its limit -- measured) + self.pick_place(TARGET, b[:2], envs.obj_min_z(self.env, BASKET) + BASKET_RIM + 0.02, fp=fp) + + def do(self, actions): + for act in actions: + if act[0] == "butter_to_basket": + self.butter_to_basket(fp=act[1] if len(act) > 1 else None) + elif act[0] == "turn_to": # ["turn_to", absolute disc angle (the agent's remembered start angle)] + self.turn(_wrap(act[1] - self.disc_angle())) + elif act[0] == "turn_by": + self.turn(act[1]) + else: + raise ValueError(act) + + # ------------------------------------------------------------ scripted reference policies + def _plan(self, kind, inst, a, history, rng, memory): + if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")): + return [["butter_to_basket"]] + if kind == "oracle": + return [["butter_to_basket"], ["turn_to", memory["q"]]] + last = history[-1]["outcome"] + acts = [] if last["target_loc"] == "basket" else [["butter_to_basket"]] + if kind == "adaptive": + return acts + ([] if last["turned_ok"] else [["turn_to", memory["q"]]]) + if kind == "nomem": + return acts + ([] if last["turned_ok"] else [["turn_by", float(rng.uniform(-np.pi, np.pi))]]) + if kind == "blind": + fp = self.footprint(TARGET) + fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist() + return [["butter_to_basket", fp]] + raise ValueError(kind) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + self.reset_instance(inst) + memory = dict(q=self.disc_angle()) # Save: the start angle (an agent reads it off the first frame) + for a in range(k): + actions = self._plan(kind, inst, a, history, rng, memory) + self.do(actions) + self.go_home() + out = self.outcome(inst) + params = dict(actions=[[x[0]] + ([round(float(np.degrees(x[1])), 1)] if x[0] != "butter_to_basket" else []) + for x in actions]) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_card_shelf.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_card_shelf.py new file mode 100644 index 0000000000000000000000000000000000000000..b56ab0538cd4224af8137664eacbda47e028a0ad --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l3_card_shelf.py @@ -0,0 +1,587 @@ +"""L3 card_shelf (2026-10-12): a deepened l3_card_edge. The thin card lies on a raised SHELF (thin top on four legs) +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 +onto the table, where it lies flat and cannot be picked up: the attempt is lost. + +Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 3.2): l3_card_edge saturated. Sonnet 5.5 (cla4) failed one +flat grasp, then in the same attempt slid the card 2-3 cm over the board's edge and grasped the overhang (both runs +succeeded on attempt 1): the failed grasp costs one command and changes nothing. Here the first common-sense +interaction (slide the nearest end out ~3 cm) has an irreversible cost whenever that end is the heavy one. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): a wooden shelf +(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) +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 +x-card's near end is always the FORWARD one: a card that tips off the backward edge lands behind the shelf, hidden from +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 +inside, 5 cm high) stands on the table beside the shelf (left or right, 6 cm gap). Same card size, mass (10 g), +friction and bin as l3_card_edge. + +Hidden variable (instance level, the same in every attempt, invisible): 8 of the card's 10 g are a weight hidden in one +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 consecutive seeds the heavy end is the NEAR end (the end a Sonnet-like agent slides out), else the far end. + +Mechanism (physics, no teleport): an end slid out by h tips over the edge once the centre of mass passes it. Measured +(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 +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 +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). +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 +is in reach. The fix is to slide the OTHER end out (a longer slide across the shelf), learnable from the failure: "only +~2 cm out and it already tipped -> that end is heavy" (the cheaper explanation "I pushed too far" leads to pushing +less, which leaves too little overhang to grasp). Validation (seeds 1000-1019): Sonnet-like naive tips 14/14 heavy-near +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 +uniform card. + +Implementation notes: the centre of mass is fixed in the generated MJCF (explicit ) and the +heavy end is chosen by the card's yaw (the card is symmetric), so the body's inertial frame is never changed at runtime +(no bounding-volume refit needed; see lh_fence / envs.refit_bounds for that MuJoCo pitfall). The inertia is written in +scientific notation: objects._fmt (5 decimals) rounds a 10-30 g card's inertia to ~0 (a 10 g card does not compile; a +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 +grasp then fails 20/20 (fingers slide over the card). The shelf is a static multi-geom fixture; its legs stand inside +its top's footprint (robot-leg contacts: 0 in all scripted runs). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: success = the card lies in the bin, +not held; plus a per-step event log (end / side slid over an edge, tipped_off, lifted, released, in_bin, hand_hit_leg) +and R6 fields (tipped_off, trap_fired, grasp_tries) for the server log; F1 gives the agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm (as l3_card_edge) +CARD_MASS = 0.010 # as l3_card_edge (flat grasp fails 20/20; a 30 g card was pinched and lifted 4/16) +SLUG_MASS = 0.008 # hidden weight (+ 2 g of card); slug centre 3.5 cm from the middle +COM_E = 0.028 # centre of mass this far from the card's middle, towards the heavy end (the card's local +x) +MU = 0.3 # card and shelf sliding friction (as l3_card_edge) +SHELF_HALF = (0.11, 0.13) # top half extents (as l3_card_edge's board) +SHELF_H = 0.10 # top surface above the table +TOP_T = 0.01 # top thickness +LEG = 0.01 # leg half width (2 x 2 cm legs) +LEG_IN = 0.012 # leg centre to the top's edges +SHELF_TOP = TZ + SHELF_H +CARD_REST_Z = SHELF_TOP + CARD_HALF[2] +BIN_IN = 0.08 # inner half width +BIN_WALL_H = 0.05 +BIN_GAP = 0.06 # shelf edge to bin outer wall +BIN_T = 0.006 +BIN_HALF_OUT = BIN_IN + BIN_T +TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE +LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card + +# instance ranges +P_HEAVY_NEAR = 0.7 # 14 of every 20 consecutive seeds +NEAR_GAP = (0.025, 0.040) # near end to its shelf edge +SIDE_CLEAR = 0.05 # long sides to the shelf's side edges, at least +YAW_JIT = np.radians(8.0) + +# scripted policies +GRASP_OUT = 0.022 # grasp point this far beyond the edge (fingers must clear the edge) +DRAG_SPEED = 0.08 +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 +ORACLE_STEPS = (0.02, 0.03) # l3_card_edge oracle: to 1 cm short, look, the rest + +EDGES = ("forward", "backward", "left", "right") # shelf edges in robot-centric words (+x, -x, +y, -y) +EDGE_U = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)} +OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"} + + +def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)): + """Uniform-looking card; the inertial (10 g, centre of mass COM_E along local +x) models an 8 g weight hidden in + the +x end. Explicit inertial pos != 0, so MuJoCo keeps a separate inertial frame (see module doc).""" + h = CARD_HALF + ms = CARD_MASS - SLUG_MASS + xs = COM_E * CARD_MASS / SLUG_MASS # slug centre + sl = (0.0075, 0.021, h[2]) # slug half extents (1.5 x 4.2 x 0.2 cm) + 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]) + 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]) + c = np.array([COM_E, 0.0, 0.0]) + inertia = box_i(ms, h) + par(ms, -c) + box_i(SLUG_MASS, sl) + par(SLUG_MASS, np.array([xs, 0.0, 0.0]) - c) + g = (f' \n' + f' \n' + f' ') + return _wrap(name, g, h[2], float(np.hypot(h[0], h[1]))) + + +def shelf_xml(name, rgba=(0.62, 0.45, 0.27, 1.0), leg_rgba=(0.50, 0.36, 0.21, 1.0)): + """Static shelf: top plate on four legs; body origin at mid height (top surface at +SHELF_H / 2).""" + hx, hy = SHELF_HALF + H = SHELF_H / 2 + parts = [((0.0, 0.0, H - TOP_T / 2), (hx, hy, TOP_T / 2), rgba)] + for sx in (-1, 1): + for sy in (-1, 1): + parts.append(((sx * (hx - LEG_IN), sy * (hy - LEG_IN), -TOP_T / 2), (LEG, LEG, H - TOP_T / 2), leg_rgba)) + g = [] + for k, (p, s, c) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), H, float(np.hypot(hx, hy))) + + +def _yaw_of(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +class ShelfSkills(Skills): + """Skills that feed the task's per-step monitor and log every close of the gripper.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + self.closes = [] + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + before = self.task.close_context() if (close and was_open) else None + rep = super().set_gripper(close, steps) + if before is not None: + before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4)) + self.closes.append(before) + return rep + + +@register_task +class CardShelf(LFFTask): + name = "l3_card_shelf" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 40 + instruction = "Pick up the thin red card lying on the wooden shelf and put it into the grey bin." + instruction_indirect = "Put the flat red rectangle that lies on the raised wooden platform into the grey container." + + # ------------------------------------------------------------ scene + def make_bddl(self): + card = register_generated("LffShelfCard", card_xml("lff_shelf_card")) + shelf = register_generated("LffCardShelf", shelf_xml("lff_card_shelf"), free=False) + bin_ = register_generated("LffShelfBin", bin_xml("lff_shelf_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T, + rgba=(0.55, 0.56, 0.60, 1.0)), free=False) + objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))] + fx = [("shelf_1", shelf, "shelf_region", (-0.11, -0.01, -0.09, 0.01)), + ("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))] + return write_bddl(self.name, self.instruction, objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.shelf_bid = m.body_name2id(self.env.fixtures_dict["shelf_1"].root_body) + self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body) + g0 = int(m.body_geomadr[self.shelf_bid]) + self.leg_geoms = {g for g in range(g0, g0 + int(m.body_geomnum[self.shelf_bid])) + if (m.geom_id2name(g) or "").endswith(("_g1", "_g2", "_g3", "_g4"))} + self.robot_geoms = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08)) + along = str(rng.choice(["x", "y"])) + near_sign = 1.0 if rng.random() < 0.5 else -1.0 + if along == "x": # the near end of an x-card is the forward one: a card that tips off the backward edge lands + near_sign = 1.0 # behind the shelf, hidden from the front camera (measured); forward = nearest = away from the robot + jit = float(rng.uniform(-YAW_JIT, YAW_JIT)) + gap = float(rng.uniform(*NEAR_GAP)) + heavy_near = bool((int(seed) * 7) % 20 < round(20 * P_HEAVY_NEAR)) # balanced per 20 consecutive seeds + a_long, a_side = (0, 1) if along == "x" else (1, 0) # world axis of the card's long / short side + ext_long = CARD_HALF[0] * abs(np.cos(jit)) + CARD_HALF[1] * abs(np.sin(jit)) # half extents incl. the jitter + ext_side = CARD_HALF[0] * abs(np.sin(jit)) + CARD_HALF[1] * abs(np.cos(jit)) + c = [bx, by] + c[a_long] += near_sign * (SHELF_HALF[a_long] - gap - ext_long) + room = SHELF_HALF[a_side] - ext_side - SIDE_CLEAR + c[a_side] += float(rng.uniform(-room, room)) + u_near = np.zeros(2) + u_near[a_long] = near_sign + near_edge = {(1.0, 0.0): "forward", (-1.0, 0.0): "backward", (0.0, 1.0): "left", (0.0, -1.0): "right"}[ + (float(u_near[0]), float(u_near[1]))] + heavy_dir = u_near if heavy_near else -u_near # the card's local +x (heavy end) points this way (+- jitter) + yaw = float(np.arctan2(heavy_dir[1], heavy_dir[0]) + jit) + side = 1.0 if rng.random() < 0.5 else -1.0 + bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (SHELF_HALF[1] + BIN_GAP + BIN_HALF_OUT)] + return dict(seed=int(seed), shelf_xy=[bx, by], card_xy=[float(c[0]), float(c[1])], card_yaw=yaw, + card_along=along, near_edge=near_edge, far_edge=OPPOSITE[near_edge], near_gap=gap, + heavy_near=heavy_near, heavy_edge=near_edge if heavy_near else OPPOSITE[near_edge], + com_offset=COM_E, bin_xy=bin_xy, bin_side="left" if side > 0 else "right") + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bx, by = inst["shelf_xy"] + m.body_pos[self.shelf_bid] = [bx, by, TZ + SHELF_H / 2] + m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0] + cx, cy = inst["bin_xy"] + m.body_pos[self.bin_bid] = [cx, cy, TZ + (BIN_WALL_H + BIN_T) / 2] + m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0] + x, y = inst["card_xy"] + envs.set_obj_pose(self.env, "card_1", [x, y, CARD_REST_Z + 0.0003], yaw=inst["card_yaw"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = ShelfSkills(self.env, self, recorder=recorder) + p = self.card_pose() + self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False, lifted=False, + out=dict(heavy=0.0, light=0.0, side=0.0), out_edge=dict(heavy=None, light=None, side=None), + flagged=set(), events=[], in_bin=False, tip=None, leg_hits=0, edge_used=None) + return self.sk + + # ------------------------------------------------------------ geometry + def card_pose(self): + p = envs.obj_pos(self.env, "card_1") + return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1"))) + + def _card_frame(self): + d = self.env.sim.data + bid = envs.body_id(self.env, "card_1") + return d.body_xpos[bid].copy(), d.body_xmat[bid].reshape(3, 3).copy() + + def card_corners(self): + p, R = self._card_frame() + h = np.array(CARD_HALF) + return np.array([p + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)]) + + def _beyond(self, xy): + """{edge: how far the point lies beyond that edge of the shelf top (m, negative = inside)}""" + b = np.asarray(xy, float) - np.asarray(self.inst["shelf_xy"]) + return {"forward": b[0] - SHELF_HALF[0], "backward": -b[0] - SHELF_HALF[0], + "left": b[1] - SHELF_HALF[1], "right": -b[1] - SHELF_HALF[1]} + + def overhang(self): + """(how far the card sticks out beyond the shelf's edges (m, max over its corners), edge word)""" + best = (-1.0, None) + for c in self.card_corners(): + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + return best + + def part_overhangs(self): + """{'heavy' | 'light' | 'side': (overhang m, edge)}: the heavy end (local +x), light end and long sides, + each measured at its two corners.""" + p, R = self._card_frame() + h = np.array(CARD_HALF) + groups = {"heavy": [(1, -1), (1, 1)], "light": [(-1, -1), (-1, 1)]} + out = {} + for k, cs in groups.items(): + best = (-1.0, None) + for sx, sy in cs: + c = p + R @ (h * [sx, sy, 0.0]) + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + out[k] = best + best = (-1.0, None) # a long side: its middle point (an end pushed out also moves two corners out) + for sy in (-1, 1): + c = p + R @ (h * [0.0, sy, 0.0]) + for e, v in self._beyond(c[:2]).items(): + if v > best[0]: + best = (float(v), e) + out["side"] = best + return out + + def end_edge(self, which): + """shelf edge that the card's `which` end ('heavy' | 'light' | 'near' | 'far') points to, from the live pose""" + p = self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) # heavy end direction + if which == "near" or which == "far": + gaps = {} + for s in (1.0, -1.0): + u = d * s + e = max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u)) + tip = p["xy"] + u * CARD_HALF[0] + gaps[e] = -self._beyond(tip)[e] + near = min(gaps, key=gaps.get) + return near if which == "near" else OPPOSITE[near] + u = d if which == "heavy" else -d + return max(EDGE_U, key=lambda k: float(np.asarray(EDGE_U[k]) @ u)) + + def on_shelf(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"])) + return bool(rel[0] <= SHELF_HALF[0] and rel[1] <= SHELF_HALF[1] and abs(p["z"] - CARD_REST_Z) < 0.012) + + def on_table(self): + return bool(self.card_pose()["z"] < TZ + 0.03 and not self.in_bin()) + + def tilt_deg(self): + _, R = self._card_frame() + return float(np.degrees(np.arccos(np.clip(abs(R[2, 2]), 0.0, 1.0)))) + + def in_bin(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"])) + return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < TZ + BIN_T + BIN_WALL_H) + + # ------------------------------------------------------------ monitor + def _event(self, ev, **kw): + self.mon["events"].append(dict(event=ev, step=int(self.sk.n_steps), **kw)) + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + p = self.card_pose() + held = self.sk.holding("card_1") + zmin = float(self.card_corners()[:, 2].min()) + mon["max_lift"] = max(mon["max_lift"], zmin - SHELF_TOP) + if held and zmin - SHELF_TOP > 0.02 and not mon["lifted"]: + mon["lifted"] = True + self._event("lifted") + rel = np.abs(p["xy"] - np.asarray(self.inst["shelf_xy"])) + if (not held and abs(p["z"] - CARD_REST_Z) < 0.004 and self.tilt_deg() < 5.0 and rel[0] <= SHELF_HALF[0] + and rel[1] <= SHELF_HALF[1]): # lying flat on the shelf + mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0]) + for k, (v, e) in self.part_overhangs().items(): + if v > mon["out"][k]: + mon["out"][k], mon["out_edge"][k] = v, e + if v >= 0.005 and k not in mon["flagged"]: + mon["flagged"].add(k) + self._event("side_over_edge" if k == "side" else "end_over_edge", part=k, edge=e) + if p["z"] < SHELF_TOP - 0.02 and not held and not mon["fell"]: + mon["fell"] = True + if not mon["lifted"]: # never lifted: it tipped (or was pushed) off the shelf + part = max(("heavy", "light", "side"), key=lambda k: mon["out"][k]) + mon["tip"] = dict(part=part, edge=mon["out_edge"][part], overhang=round(mon["out"][part], 4)) + self._event("tipped_off", **mon["tip"]) + else: + self._event("released") + d = self.env.sim.data + for i in range(d.ncon): # the hand / arm touching a shelf leg (should not happen in normal grasps) + c = d.contact[i] + if (c.geom1 in self.leg_geoms and c.geom2 in self.robot_geoms) or (c.geom2 in self.leg_geoms and + c.geom1 in self.robot_geoms): + if mon["leg_hits"] == 0: + self._event("hand_hit_leg") + mon["leg_hits"] += 1 + break + if not mon["in_bin"] and self.in_bin() and not held: + mon["in_bin"] = True + self._event("in_bin") + + def close_context(self): + """Where the gripper is relative to the card and the shelf just before it closes.""" + sk, p = self.sk, self.card_pose() + e = sk.eef_pos() + c, s = np.cos(p["yaw"]), np.sin(p["yaw"]) + rel = e[:2] - p["xy"] + local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side (+ = heavy end) + beyond = self._beyond(e[:2]) + edge = max(beyond, key=beyond.get) + ov, ov_edge = self.overhang() + return dict(step=sk.n_steps, local=[round(v, 4) for v in local], + tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4), + beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge, + card_on_shelf=self.on_shelf(), overhang=round(ov, 4), overhang_edge=ov_edge, + width_before=round(sk.gripper_width(), 4)) + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + envs.settle(self.env, 30) + self.monitor_step() + sk, mon = self.sk, self.mon + p = self.card_pose() + held = bool(sk.holding("card_1")) + in_bin = self.in_bin() and not held + success = bool(in_bin) + moved = float(np.linalg.norm(p["xy"] - mon["start_xy"])) + lifted = mon["max_lift"] > 0.02 + tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02] + parts, mode = [], "success" + rel = p["xy"] - np.asarray(inst["bin_xy"]) + where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and " + f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre") + tip = mon["tip"] + if success: + parts.append("The card is in the bin.") + elif held: + mode = "held" + parts.append(f"The card is still held by the gripper, {where}.") + elif lifted: + mode = "dropped" + loc = ("on the shelf" if self.on_shelf() else "on the table" if self.on_table() else + "partly on the shelf" if p["z"] > SHELF_TOP - 0.02 else "off the shelf") + parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the shelf but is not in the " + f"bin: it lies {loc}, its centre {where}.") + elif mon["fell"]: + mode = "fell_off" + what = "a long side" if tip["part"] == "side" else "one end" + parts.append(f"The card was never lifted: after {what} of it had been slid {100 * max(tip['overhang'], 0):.1f}" + f" cm beyond the shelf's {tip['edge']} edge, it tipped over that edge and fell off the shelf; " + + ("it lies flat on the table." if self.on_table() and self.tilt_deg() < 10 else + f"it rests off the shelf, tilted {self.tilt_deg():.0f} degrees.")) + else: + mode = "not_lifted" + parts.append("The card was never lifted; it still lies flat on the shelf" + + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to " + f"{100 * mon['max_overhang']:.1f} cm beyond the shelf's edge)" if mon["max_overhang"] > 0.003 + else ")") if moved > 0.005 else "") + ".") + if not success and not lifted and tries: + c = tries[-1] + n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else "" + if c["card_on_shelf"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0: + txt = ("when the gripper closed on the card lying flat on the shelf, its fingertips were on either side " + "of the card, at shelf level") + else: + pos = (f"{100 * c['beyond_edge']:.1f} cm beyond the shelf's {c['beyond_edge_name']} edge" + if c["beyond_edge"] >= 0.0 else + f"over the shelf, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge") + txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm beyond the " + f"shelf's {c['overhang_edge']} edge and the gripper's centre was {pos}") + txt += f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the fingers closed " + txt += ("fully, sliding over the top of the card instead of gripping its edges." + if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else + ("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card.")) + parts.append(n + txt if n else txt[0].upper() + txt[1:]) + elif not success and not lifted and not mon["fell"]: + parts.append("The gripper never closed with its fingertips down at the card.") + failure = "none" if success else mode + out = dict(success=success, mode=mode, failure=failure, held=held, lifted=bool(lifted), + max_lift=round(mon["max_lift"], 4), max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), + fell=bool(mon["fell"]), tipped_off=tip is not None, trap_fired=bool(tip is not None and + tip["part"] == "heavy"), + tip=tip, end_out={k: round(v, 4) for k, v in mon["out"].items()}, + end_out_edge=dict(mon["out_edge"]), card_final=dict(xy=[round(float(v), 4) for v in p["xy"]], + z_above_table=round(p["z"] - TZ, 4), + tilt_deg=round(self.tilt_deg(), 1)), + leg_hits=int(mon["leg_hits"]), slid_edge=mon["edge_used"], + events=list(mon["events"]), grasp_tries=tries, closes=sk.closes, detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def grasp_and_bin(self, xy, yaw, z_site, lift=0.12): + sk = self.sk + sk.set_gripper(False, steps=8) + sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw) + sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2) + if not sk.holding("card_1"): + sk.set_gripper(False, steps=8) + return False + bx, by = self.inst["bin_xy"] + hi = SHELF_TOP + 0.10 + sk.move_to([bx, by, hi]) + sk.move_to([bx, by, TZ + BIN_WALL_H + 0.05], speed=0.2) + sk.set_gripper(False, steps=12) + sk.move_to([bx, by, hi]) + return True + + def slide_card(self, delta, press=0.004, at=(0.0, 0.0)): + """closed fingertips pressed on the card (at its centre + `at`), straight move by `delta` (xy), lift""" + sk, p = self.sk, self.card_pose() + z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press + s = p["xy"] + np.asarray(at, float) + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.06], yaw=p["yaw"]) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100) + e = s + np.asarray(delta, float) + sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300) + sk.move_to([e[0], e[1], z + 0.06], speed=0.2) + sk.hold(10) # look + + def push_end(self, u, dist, behind=0.015): + """closed fingers at shelf level `behind` m behind the card's trailing end, push it `dist` along u, lift""" + sk, p = self.sk, self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) + la = d * np.sign(d @ u) if abs(d @ u) > 0.5 else d + tail = p["xy"] - la * CARD_HALF[0] + s = tail - u * behind + z = SHELF_TOP + TIP_BELOW_SITE - 0.001 # fingertips on the shelf top (2 mm above: they pass over the card) + yaw = float(np.arctan2(u[1], u[0]) - np.pi / 2) # finger axis across the push direction + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.05], yaw=yaw) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=100) + e = s + u * (behind + dist) + sk.move_to([e[0], e[1], z], speed=0.04, tol=0.004, max_steps=300) + sk.move_to([e[0], e[1], z + 0.05], speed=0.2) + sk.hold(10) + + def execute(self, inst, params): + p = self.card_pose() + rng = np.random.default_rng(params.get("noise_seed")) if params.get("noise_seed") is not None else None + if params.get("probe_grasp", False) or params["mode"] == "grasp": # flat grasp at the card's middle + dxy = np.asarray(params.get("probe_dxy", (0.0, 0.0))) + self.grasp_and_bin(p["xy"] + dxy, p["yaw"], SHELF_TOP + params.get("probe_dz", 0.0)) + if params["mode"] == "grasp" or self.sk.holding("card_1") or self.mon["lifted"]: + return + # slide one end of the card along its long side out over the edge it points to, in strokes + edge = params.get("edge") or self.end_edge(params.get("end", "near")) + self.mon["edge_used"] = edge + u = np.asarray(EDGE_U[edge], float) + b = np.asarray(inst["shelf_xy"]) + half = SHELF_HALF[0] if edge in ("forward", "backward") else SHELF_HALF[1] + edge_pos = float(b @ u) + half + for k, target in enumerate(params.get("steps", ORACLE_STEPS)): + if not self.on_shelf(): + return # tipped off: nothing left to grasp (the attempt is lost) + p = self.card_pose() + d = np.array([np.cos(p["yaw"]), np.sin(p["yaw"])]) + 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) + ext = max(float(c[:2] @ u) for c in self.card_corners()) - float(p["xy"] @ u) + tgt = float(target) + (float(rng.uniform(-1, 1)) * params.get("step_noise", 0.0) if rng is not None else 0.0) + need = edge_pos + tgt - (float(p["xy"] @ u) + ext) # travel still needed along u + if need > 0.003: + if params.get("style", "press") == "endpush": + self.push_end(u, need) + else: + at = (np.asarray(params.get("press_at", (0.0, 0.0))) if rng is None else + rng.normal(0.0, params.get("press_noise", 0.0), 2)) + self.slide_card(la * need / max(float(la @ u), 1e-6), at=at) + self.sk.hold(10) + if not self.on_shelf(): + return + q = self.card_pose() + d = np.array([np.cos(q["yaw"]), np.sin(q["yaw"])]) + 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) + cu = float(q["xy"] @ u) + tip_u = max(float(c[:2] @ u) for c in self.card_corners()) # outermost point of the card along u + target_u = min(tip_u - 0.008, edge_pos + params.get("grasp_out", GRASP_OUT)) + g = q["xy"] + la * (target_u - cu) / max(float(la @ u), 1e-6) + g = g + np.asarray(params.get("grasp_dxy", (0.0, 0.0))) + self.grasp_and_bin(g, q["yaw"], SHELF_TOP - 0.003 + params.get("grasp_dz", 0.0)) + + def default_params(self, inst): + """Sonnet-like (cla4 l3_card_edge): one flat grasp, then the nearest end out to the edge and 1 cm at a time + to ~3 cm, lifting the finger and looking after each stroke; grasp the overhang.""" + return dict(mode="edge", probe_grasp=True, end="near", steps=list(NAIVE_STEPS)) + + def oracle_params(self, inst): + """Knows the hidden weight: slides the light end out 3 cm (two strokes, as the l3_card_edge oracle).""" + return dict(mode="edge", end="light", steps=list(ORACLE_STEPS)) + + def blind_params(self, inst, attempt, rng): + """naive with small random variations, no history: nearest end, 2.5-3.5 cm, pressing point / grasp jitter""" + return dict(mode="edge", probe_grasp=True, end="near", steps=[0.0, 0.01, 0.02, float(rng.uniform(0.025, 0.035))], + noise_seed=int(rng.integers(1 << 30)), press_noise=0.005, + grasp_dxy=rng.uniform(-0.005, 0.005, 2).tolist(), grasp_dz=float(rng.uniform(-0.004, 0.003))) + + def adapt_params(self, inst, history): + """Tipped off the shelf (never lifted) -> slide the OTHER end next time (it tipped although only ~2 cm stuck + out: that end must be heavy). Slid out but not gripped -> 1 cm more overhang. Otherwise repeat.""" + out, prm = history[-1]["outcome"], history[-1]["params"] + used = out.get("slid_edge") or prm.get("edge") + nxt = dict(mode="edge", probe_grasp=False, edge=used, steps=list(ORACLE_STEPS)) + if out["mode"] == "fell_off": + e = (out.get("tip") or {}).get("edge") or used + nxt["edge"] = OPPOSITE.get(e) + elif out["mode"] == "not_lifted" and used is not None: + last = float((prm.get("steps") or ORACLE_STEPS)[-1]) + nxt["steps"] = [s + 0.01 for s in ORACLE_STEPS] if last < 0.035 else list(ORACLE_STEPS) + if nxt["edge"] is None: + nxt.pop("edge") + nxt["end"] = "near" + return nxt diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l4_fit.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l4_fit.py new file mode 100644 index 0000000000000000000000000000000000000000..7465485d3e907ad579bc46be98782eb8c5efad3a --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l4_fit.py @@ -0,0 +1,574 @@ +"""L4-A fit_container: put the phone flat inside the one box it fits into. + +v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and +phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time. +v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is +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 +against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone: + fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight), + snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps, + short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps, + narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow, + small 0.5..1.0 cm too short. +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 +images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it +appears to (by about the overlap seen) -> the box with the most length to spare. + +The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as +the capped length. v2 is kept in l4_fit.py.bak-20261008-height. + +v2 description: + +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 +boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES): + fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side), + short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest), + narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest), + small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions), + short 0.8-2.0 cm too short, as wide as the fitting box. +Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it +(+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be +turned by ~90 deg. + +Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the +fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in +sim.model, so a single env serves every instance. + +Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed +2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first +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 +long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger +in that dimension and turn the phone. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +# phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it +PL, PW, PT = 0.140, 0.068, 0.012 +CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden) +# boxes (local x = long axis of the opening) +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035 +BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +N_BOXES = 5 +ROWS_X = (-0.30, -0.08) # back row (near the robot), front row +COLS_Y = (-0.22, 0.0, 0.22) +DROP = 0.012 # phone bottom this far above the rim when released +Z_CARRY = envs.TABLE_Z + 0.15 +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way +PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates +JITTER_DEG = 15.0 +# inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side). +# The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has +# the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio. +# Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box. +# v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap) +BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small") +INNER_RANGES = { + "fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest) + "snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable + "short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box + "narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow + "small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short +} +VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps) +BOX_RGBA = (0.70, 0.60, 0.46, 1.0) + + +def phone_xml(model_name): + hx, hy, hz = PL / 2, PW / 2, PT / 2 + body = (0.13, 0.13, 0.15, 1.0) + screen = (0.02, 0.025, 0.04, 1.0) + g = (f' \n' + f' \n' + f' ') + # v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered). + # Resized per instance in apply_instance (inst["cap"]). + c = CAP_RANGE[1] + for k, sx in enumerate((1, -1)): + g += (f'\n ') + return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy))) + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def wrap_quarter(a): + """angle modulo pi/2 into [-pi/4, pi/4)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +def fits_some_yaw(a, b, clearance=0.002, length=PL): + """Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in + total)?""" + th = np.linspace(0.0, np.pi / 2, 181) + e1 = length * np.cos(th) + PW * np.sin(th) + e2 = length * np.sin(th) + PW * np.cos(th) + return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance))) + + +def _rect_corners(xy, yaw, half): + c, s = np.cos(yaw), np.sin(yaw) + R = np.array([[c, -s], [s, c]]) + pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half) + return pts @ R.T + np.asarray(xy) + + +def _rects_overlap(r1, r2): + """separating-axis test for two rotated rectangles given as (xy, yaw, half)""" + c1, c2 = _rect_corners(*r1), _rect_corners(*r2) + for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2): + ax = np.array([np.cos(yaw), np.sin(yaw)]) + p1, p2 = c1 @ ax, c2 @ ax + if p1.max() < p2.min() or p2.max() < p1.min(): + return False + return True + + +@register_task +class FitContainer(LFFTask): + name = "l4_fit_container" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason") + instruction = "Put the phone flat inside a box that it fits into completely." + instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely." + + # ------------------------------------------------------------ scene + def make_bddl(self): + phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone")) + # one category per box (BDDL lists one object per line; same-category lines would overwrite each + # other). All share the same MJCF; the opening is resized per instance in apply_instance. + cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H, + wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA, + density=3000)) + for c in "ABCDE"] + objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))] + slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)] + for i, (x, y) in enumerate(slots): + 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))) + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + j = np.radians(JITTER_DEG) + for _ in range(500): + col = int(rng.integers(3)) + phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)] + phone_yaw = float(rng.uniform(-j, j)) + slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])] + kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)] + cap = float(rng.uniform(*CAP_RANGE)) + boxes = [] + for i, (kind, (x, y)) in enumerate(zip(kinds, slots)): + lo, hi = INNER_RANGES[kind] + a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1]) + assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap) + assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b) + crossed = bool(rng.random() < 0.5) + yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j)) + boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed, + xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))], + yaw=yaw, inner=[float(a), float(b)])) + rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007)) + for b in boxes] + rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01))) + if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)): + break + else: + raise RuntimeError("could not sample a non-overlapping layout") + prng = np.random.default_rng(seed + 7919) + perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))] + for b in boxes] + return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes, + fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc) + + def _reshape_box(self, name, a, b): + ix, iy, H = a / 2, b / 2, BOX_HALF_H + parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)), + ((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)), + ((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)), + ((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))] + m = self.env.sim.model + o = self.env.objects_dict[name] + for names in (o.contact_geoms, o.visual_geoms): + assert len(names) == len(parts), names + for k, n in enumerate(names): + g = m.geom_name2id(n) + pos, size = parts[k] + m.geom_pos[g] = pos + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def _set_caps(self, cap): + """resize the two hidden bumper caps to `cap` (m) per end""" + m = self.env.sim.model + if not hasattr(self, "_cap_ids"): + self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1") + if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]] + assert len(self._cap_ids) == 2, self._cap_ids + for g in self._cap_ids: + sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0 + size = (cap / 2, PW / 2 - 0.001, PT / 2) + m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0) + m.geom_size[g] = size + m.geom_rbound[g] = float(np.linalg.norm(size)) + m.geom_aabb[g] = [0, 0, 0, *size] + + def apply_instance(self, inst): + # walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision + # mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07). + # Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below. + import mujoco + self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + self._set_caps(inst["cap"]) + for b in inst["boxes"]: + self._reshape_box(b["name"], *b["inner"]) + envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"]) + envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005], + yaw=inst["phone_yaw"]) + + # ------------------------------------------------------------ outcome + def _pose2d(self, name): + bid = envs.body_id(self.env, name) + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + p = self.env.sim.data.body_xpos[bid].copy() + return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1)))) + + def outcome(self, inst): + envs.settle(self.env, 40) + p, yaw, tilt = self._pose2d("phone_1") + held = bool(self.sk is not None and self.sk.holding("phone_1")) + # which box is the phone in / on: smallest distance of the phone centre outside a box opening + best = None + for j, b in enumerate(inst["boxes"]): + c, byaw, btilt = self._pose2d(b["name"]) + d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2]) + out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0) + dist = float(np.linalg.norm(out)) + if best is None or dist < best[0]: + best = (dist, j, c, byaw, btilt) + dist, j, c, byaw, btilt = best + b = inst["boxes"][j] + a_in, b_in = b["inner"] + floor_top = c[2] - BOX_HALF_H + FLOOR_T + height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor + in_opening = dist < 1e-9 + on_floor = height < 0.004 and tilt < 5.0 + success = bool(in_opening and on_floor and not held and btilt < 10.0) + where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback + # footprint of the phone (as it lies now) against the opening of that box + dl = yaw - byaw + cs, sn = abs(np.cos(dl)), abs(np.sin(dl)) + L = PL + 2 * inst.get("cap", 0.0) # the capped phone + over_long = L * cs + PW * sn - a_in + over_short = L * sn + PW * cs - b_in + along_long = "length" if cs >= sn else "width" + fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long, + over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None, + over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None) + res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2), + tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb) + if held: + res["detail"] = "The phone is still in the gripper." + res["failure"] = "held" + return res + if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006): + res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm " + f"outside the opening of {where}.") + res["failure"] = "table" + return res + if success: + res["detail"] = f"The phone is lying flat on the bottom of {where}." + res["failure"] = None + return res + pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else + f"tilted about {tilt:.0f} degrees with one end down inside the box") + txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}." + dim_l = "long" if along_long == "length" else "wide" + dim_s = "wide" if along_long == "length" else "long" + if fb["over_long_cm"]: + txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side." + if fb["over_short_cm"]: + txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side." + if not fb["over_long_cm"] and not fb["over_short_cm"]: + txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim." + res["detail"] = txt + res["failure"] = "rim" + return res + + @staticmethod + def box_label(inst, j): + """Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left).""" + ys = [b["xy"][1] for b in inst["boxes"]] + xs = [b["xy"][0] for b in inst["boxes"]] + n = len(ys) + order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first + r = order.index(j) + close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04] + if close: # boxes side by side in y: tell them apart by distance from the robot + nearer = all(xs[j] < xs[i] for i in close) + return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position" + if r == 0: + return "the box furthest to the robot's left (+y)" + if r == n - 1: + return "the box furthest to the robot's right (-y)" + return "the middle box (between the others, left to right)" + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released). + Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre + along the box's long / short axis (m), drop = height of the phone bottom above the rim (m).""" + sk, env = self.sk, self.env + px, py = inst["phone_xy"] + zc = envs.TABLE_Z + PT / 2 + g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width + sk.set_gripper(False, steps=5) + sk.move_to([px, py, zc + 0.10], yaw=g0) + sk.move_to([px, py, zc + 0.001], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([px, py, Z_CARRY], speed=0.25) + b = inst["boxes"][int(params["box"])] + c, s = np.cos(b["yaw"]), np.sin(b["yaw"]) + dx, dy = params.get("dx", 0.0), params.get("dy", 0.0) + bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy + sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"])) + # put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip + off = envs.obj_pos(env, "phone_1") - sk.eef_pos() + drop = params.get("drop", DROP) + sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003) + tgt = self._servo_phone([bx, by], RIM_Z + drop) + sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts) + self._hold_at(tgt, 12) + sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10]) + sk.move_to(list(PARK), yaw=0.0) + + def _hold_at(self, target, steps): + sk = self.sk + R = sk._R() + for _ in range(steps): + sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + + def _servo_phone(self, xy, z_bottom, max_steps=60, tol=0.0015): + """Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom. + Returns the final gripper target.""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom + PT / 2]) + tgt = e_prev = sk.eef_pos() + for i in range(max_steps): + ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos() + if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + tgt = goal - (ph - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def _naive_yaw(self, inst, j): + """keep the phone's orientation, only snap it to the nearest axis of box j""" + p = inst["phone_yaw"] + return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p)) + + def default_params(self, inst): + """v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the + trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its + tighter direction, i.e. "snug" by construction; phone's long side along the box's long side""" + marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]] + j = int(np.argmax(marg)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def nearest_params(self, inst): + """v2 prior (kept for reference): nearest box, lined up""" + d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]] + j = int(np.argmin(d)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def oracle_params(self, inst): + j = inst["fit"] + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def blind_params(self, inst, attempt, rng): + """no history: a random box (may repeat), lined up like the prior""" + j = int(rng.integers(N_BOXES)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + def naive_keep_yaw_params(self, inst): + """old prior (kept for reference): nearest box, keep the phone's orientation""" + d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]] + j = int(np.argmin(d)) + return dict(box=j, place_yaw=self._naive_yaw(inst, j)) + + def adapt_params(self, inst, history): + """Scripted learner on F2 feedback. + + Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the + phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an + estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box + that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and + lines the phone's long side up with the box's long side. + """ + perc = inst["_perc"] + L_est = W_est = None + tried_aligned = set() + for h in history: + o = h["outcome"] + fb = o.get("feedback") or {} + if o.get("failure") != "rim": + continue + j = fb["box"] + a, b = perc[j] + if fb["along_long"] == "length": + if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box + tried_aligned.add(j) + if fb["over_long_cm"]: + L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100) + if fb["over_short_cm"]: + W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100) + else: + if fb["over_short_cm"]: + L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100) + if fb["over_long_cm"]: + W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100) + thr = 0.002 + cands = [] + for j, (a, b) in enumerate(perc): + if j in tried_aligned: + continue + mL = None if L_est is None else a - L_est + mW = None if W_est is None else b - W_est + feasible = (mL is None or mL > thr) and (mW is None or mW > thr) + if mL is not None and mW is not None: + key = min(mL, mW) + elif mL is not None: + key = b + elif mW is not None: + key = a + else: + key = a * b + cands.append((feasible, key, j)) + if not cands: + j = int(np.argmax([a * b for a, b in perc])) + else: + j = max(cands)[2] + return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"])) + + def elim_params(self, inst, history, rng): + """sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up + after the first attempt) and to never retry a box that got a size verdict; picks among the remaining + boxes at random, i.e. no size reasoning / perception.""" + bad = set() + for h in history: + fb = h["outcome"].get("feedback") or {} + if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and ( + fb.get("over_long_cm") or fb.get("over_short_cm")): + bad.add(int(fb["box"])) + left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES)) + j = int(rng.choice(left)) + return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"])) + + EXTRA_KINDS = ("elim",) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + if kind not in self.EXTRA_KINDS: + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if a == 0: + params = self.default_params(inst) + else: + params = self.elim_params(inst, history, rng) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"]: + break + return history + + +# ---------------------------------------------------------------- physical validity checks +def physics_check(seed0=1000, n=20, out=None): + """Every (box, orientation) pair on each instance, released centred from DROP above the rim. + Expect success iff the box is the fitting one and the phone's long side is along the box's long side.""" + import json + task = FitContainer() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + for j, b in enumerate(inst["boxes"]): + for orient in ("aligned", "crossed"): + task.reset_instance(inst) + task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2)))) + o = task.outcome(inst) + rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]], + orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"), + failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"])) + r = rows[-1] + print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} " + f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["expect"] else " <-- MISMATCH"), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows)) + return rows + + +def stress_check(seed=1002, out=None): + """Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box + (+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow.""" + import copy + import json + task = FitContainer() + base = task.sample_instance(seed) + j = base["fit"] + rows = [] + for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010), + ("narrow_0.5", PL + 0.010, PW - 0.005)]: + 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), + (0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]: + inst = copy.deepcopy(base) + inst["boxes"][j]["inner"] = [a, b] + task.reset_instance(inst) + task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)), + dx=dx, dy=dy, drop=drop)) + o = task.outcome(inst) + rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000, + dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"], + height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"])) + print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> " + f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json + # python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json + import sys + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None) + elif sys.argv[1] == "stress": + stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l5_iterative.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l5_iterative.py new file mode 100644 index 0000000000000000000000000000000000000000..eec94ac61e9f0b98925237971a1da808aded8ef3 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l5_iterative.py @@ -0,0 +1,136 @@ +"""[PARKED 2026-10-06 — fails acceptance: oracle 50% (n=12, k=3). The push response is not stationary: +the same commanded speed carries the cube 7.9 cm on one push and 11.4 cm on the next, because the arm reaches +different speeds at different extensions. Needs a configuration-independent striker before use.] + +L5-B iterative_push: several pushes in ONE episode (MemMimic "Iterative Pushing" analogue). + +The cube starts far from the target zone; each push is a straight strike away from the robot whose +only free parameter is the speed. Overshooting past the zone is unrecoverable (episode fails). +Hidden variable: cube-table friction mu, as in l5_slide_to_target. The information needed to choose +the next push (how far a push of a given speed carries the cube) is only available from the +outcomes of the previous pushes in the same episode -> within-episode learning from failure. + +"Attempt" granularity for the history: one push. +""" +import numpy as np + +from .. import envs +from ..task_base import register_task +from .l5_slide import CUBE_HALF, V_MAX, V_MIN, Z_PUSH, SlideToTarget + + +@register_task +class IterativePush(SlideToTarget): + name = "l5_iterative_push" + level = "L5" + capabilities = ("Reason", "Save", "Utilize") + protocol = "within" + max_attempts = 3 # pushes per episode: too few to creep up on the target with small taps + instruction = ("Push the red cube away from the robot so that it comes to rest inside the green target zone. " + "You have at most three separate pushes. If the cube passes the zone, the task fails.") + instruction_indirect = instruction + tol_along = 0.015 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.27, -0.23)), float(rng.uniform(-0.08, 0.08))], + target_dist=float(rng.uniform(0.22, 0.30)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.08))))) + + def make_bddl(self): + return super().make_bddl() + + # --------------------------------------------------------------- one push from the current cube pose + def push_once(self, inst, speed): + c = envs.obj_pos(self.env, "cube_1") + x, y = c[0], c[1] + sk = self.sk + sk.set_gripper(True, steps=3) + sk.move_to([x - self.runup, y, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x - self.runup, y, Z_PUSH], tol=0.003) + sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH + 0.10], speed=0.3) + envs.settle(self.env, 40) + c1 = envs.obj_pos(self.env, "cube_1") + return float(c1[0] - x) + + def outcome(self, inst): + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, "cube_1") + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + success = bool(abs(along) <= self.tol_along and abs(across) <= self.tol_across and c[2] > envs.TABLE_Z) + overshoot = bool(along > self.tol_along) + if success: + detail = "The cube is inside the target zone." + elif overshoot: + detail = f"The cube passed the target zone: it is {100 * along:.1f} cm beyond its centre. The task has failed." + else: + detail = f"The cube is {100 * -along:.1f} cm short of the centre of the target zone." + return dict(success=success, overshoot=overshoot, along_err=float(along), across_err=float(across), + detail=detail) + + # --------------------------------------------------------------- scripted references + S0 = 0.02 # distance the cube travels during the contact stroke itself + + def _plan_speed(self, remaining, model, pushes_left=1): + """Model: push distance d(v) = s0 + k v^2. With more than one push left, cover all but a short + final leg (a short push is more predictable); with one push left, aim at the zone centre.""" + if model is None: + return 0.30 + s0, k = model + goal = remaining if pushes_left <= 1 else max(remaining - 0.07, 0.0) + v = np.sqrt(max(goal - s0, 0.0) / max(k, 1e-6)) + return float(np.clip(v, V_MIN, V_MAX)) + + @classmethod + def _fit(cls, pts): + """pts: [(v, d)]. One point -> fix s0; two or more -> least squares on (s0, k).""" + if len(pts) == 1: + v, d = pts[0] + return cls.S0, max(d - cls.S0, 1e-4) / v ** 2 + A = np.array([[1.0, v ** 2] for v, _ in pts]) + b = np.array([d for _, d in pts]) + s0, k = np.linalg.lstsq(A, b, rcond=None)[0] + if k <= 0: + return cls.S0, max(np.mean(b) - cls.S0, 1e-4) / np.mean([v ** 2 for v, _ in pts]) + return float(np.clip(s0, 0.0, 0.05)), float(k) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + self.reset_instance(inst) + history = [] + model = None + if kind == "oracle": + model = self._oracle_model(inst) + for a in range(k): + out0 = self.outcome(inst) + remaining = -out0["along_err"] + if kind == "naive" or kind == "blind": + speed = 0.30 if kind == "naive" else float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX)) + if remaining < 0.06: # naive heuristic: tap gently near the end + speed = 0.20 + else: + speed = self._plan_speed(remaining, model, pushes_left=k - a) + moved = self.push_once(inst, speed) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=dict(speed=speed), outcome=dict(out, moved=moved))) + if kind == "adaptive" and moved > 0.005: + pts = [(h["params"]["speed"], h["outcome"]["moved"]) for h in history if h["outcome"]["moved"] > 0.005] + model = self._fit(pts) + if out["success"] or out["overshoot"]: + break + # mark only the final state as the episode outcome + return history + + def _oracle_model(self, inst): + """Privileged: measure the push model with the true mu in scratch rollouts.""" + pts = [] + for v in (0.2, 0.35, 0.5): + self.reset_instance(inst) + pts.append((v, self.push_once(inst, v))) + self.reset_instance(inst) + return self._fit(pts) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l6_count.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l6_count.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfcc8725cbfb523898ced10b2974c65b5b3b82f --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l6_count.py @@ -0,0 +1,562 @@ +"""L6-B count_into_box: put exactly N identical cubes into an opaque drop box; one carry is interrupted by a slip. + +Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at +one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in, +lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past +the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening). +Cubes cannot be taken back out. + +Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction). + +Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried +cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The +number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so +neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already") +is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be +completed in a later segment. + +Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent +declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the +current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it +also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped +into the box." after every cube that falls in, and the slip. + +Scripted references (perception = simulator state, as in l6_swap): + oracle privileged box count: carries cubes until the box holds N. + adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the + drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later + segments: if F2 says the box holds fewer than N, adds one cube per segment. + naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame, + which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1) + and adds the rest. + blind memoryless restart (k attempts): at the slip it does not know where it was and starts over + ("the box must get N cubes"), every later segment again puts N cubes in (repeated steps). +Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the +slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube +per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..task_base import LFFTask, register_task + +CUBE_HALF = 0.02 +CUBE_RGBA = (0.95, 0.50, 0.10, 1.0) +N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view +LETTERS = "ABCDEFGHIJK" +CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)] + +# drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot) +WALL_T = 0.008 +IN_HX, IN_HY = 0.100, 0.110 # inner half sizes +LID_Z = 0.095 # underside of the lid above the table +LID_T = 0.008 +HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side +HOLE_HY = 0.035 +RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls +RAMP_T = 0.006 +RAMP_MU = 0.03 +BOX_RGBA = (0.30, 0.20, 0.13, 1.0) +INNER_RGBA = (0.08, 0.07, 0.06, 1.0) +HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0]) +OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T +RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX) +RAMP_TH = float(np.arctan(RAMP_SLOPE)) +# Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free +# slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening. +# Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide +# past the opening before it is moved; then a second layer on the far row. (x, y, layer) +_ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)] +SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)] + + [(_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)]) + +BASE_X = -0.66 +REACH = 0.70 # max horizontal distance of a cube from the robot base +CUBE_REGION = (-0.30, 0.07, -0.28, 0.28) +CUBE_MIN_DIST = 0.085 +BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid) +Z_GRASP = envs.TABLE_Z + CUBE_HALF +Z_CARRY = envs.TABLE_Z + 0.20 +Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid +PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)] +LIFTED = 0.05 # slip trigger: cube at least this far above its resting height +HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there) +HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp + + +def hand_box_clear(p, a, box, half=HAND_HALF): + """Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint.""" + ax = np.array([-np.sin(a), np.cos(a)]) + return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0))) + for t in np.linspace(-half, half, 9)) + + +def axis_clear(p, a, others, half=HAND_HALF): + """Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a).""" + ax = np.array([-np.sin(a), np.cos(a)]) + best = 1.0 + for o in others: + v = np.asarray(o) - p + t = float(np.clip(v @ ax, -half, half)) + best = min(best, float(np.linalg.norm(v - t * ax))) + return best + + +def drop_box_xml(model_name): + """Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on).""" + parts = [] # (pos, half size, rgba, quat or None, friction or None) + H = LID_Z / 2 + # walls + parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA)) + parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA)) + parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA)) + parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA)) + # lid around the opening + zc = LID_Z + LID_T / 2 + x0, x1 = HOLE_X + parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip + parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part + for s in (-1, 1): + parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2, + LID_T / 2), BOX_RGBA)) + # floor (dark) and ramp + parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA)) + dz = RAMP_Z[0] - RAMP_Z[1] + th = float(np.arctan2(dz, 2 * IN_HX)) + L = float(np.hypot(dz, 2 * IN_HX)) / 2 + zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th) + 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) + geoms = [] + for k, p in enumerate(parts + [ramp]): + pos, half, rgba = p[:3] + quat = p[3] if len(p) > 3 else None + mu = p[4] if len(p) > 4 else None + q = f' quat="{_fmt(quat)}"' if quat is not None else "" + fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"' + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY))) + + +def _wrap_q(a): + """cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +@register_task +class CountIntoBox(LFFTask): + name = "l6_count_into_box" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55) + max_attempts = 5 + _TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. " + "Cubes cannot be taken back out of the box.") + _TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the " + "square hole in its top. Blocks cannot be taken back out of the container.") + instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction) + instruction_indirect = _TEMPLATE_INDIRECT.format(n="N") + inject = True + announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images) + agent_object_names = ["orange cube (several identical)", "drop box"] + + WORDS = {3: "three", 4: "four", 5: "five", 6: "six"} + + def agent_instruction(self, inst, variant="direct"): + t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE + return t.format(n=self.WORDS[inst["n_target"]]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + orig_step = self.env.step + + def step(action): # per-control-step monitor: also sees attempts driven by the agent harness + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, L in enumerate(LETTERS[:N_CUBES]): + cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3, + CUBE_RGBA, density=600)) + gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4) + objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01))) + box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False) + fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))] + return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx) + + def _box_body(self): + return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + n = int(rng.choice([4, 5])) + p = int(rng.integers(1, n)) # cubes already inside when the slip happens + e = int(rng.integers(0, 2)) + T = n + e + p + for _ in range(500): + side = int(rng.choice([-1, 1])) + box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)]) + P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)]) + P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH] + P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR] + cubes = [] + for c in P: # random sequential addition + if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes): + cubes.append(c) + if len(cubes) == T: + break + if len(cubes) < T: + continue + yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand + for i in range(T): + oth = [cubes[j] for j in range(T) if j != i] + for _ in range(30): + y = float(rng.uniform(-np.pi / 4, np.pi / 4)) + if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035: + # |y| <= 45 deg: the grasp needs no large wrist rotation + yaws.append(y) + break + else: + break + if len(yaws) == T: + break + else: + raise RuntimeError("could not sample a layout") + inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(), + cubes=np.array(cubes).round(4).tolist(), + yaws=yaws, + trigger_dist=float(rng.uniform(0.05, 0.09)), + slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)), + slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4))) + # make_video prints task.instruction: keep it in sync with the last sampled instance + self.instruction = self.agent_instruction(inst, "direct") + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + bid = self._box_body() + m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + T = inst["n_cubes"] + for i, c in enumerate(CUBES): + if i < T: + envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001], + yaw=inst["yaws"][i]) + else: + envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001]) + self.env.sim.forward() + self._inst = inst + self.active = CUBES[:T] + self.slip = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self.in_box = [] # cubes that fell into the box, in order + self.stored = [] # cubes moved to a storage slot + self._bad = set() # scripted policies: cubes whose grasp failed + self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)} + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self._mon = True + return sk + + def go_home(self): + p = self.sk.eef_pos() + self.sk.move_to([p[0], p[1], max(p[2], self._home[2])]) + self.sk.move_to(self._home) + + # ------------------------------------------------------------ geometry helpers + def box_local(self, xyz): + b = self._inst["box_xy"] + return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z]) + + def hole_world(self): + b = self._inst["box_xy"] + return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]]) + + def inside_box(self, c): + q = self.box_local(envs.obj_pos(self.env, c)) + return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z) + + def on_lid(self, c): + q = self.box_local(envs.obj_pos(self.env, c)) + return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z) + + def on_table(self, c): + p = envs.obj_pos(self.env, c) + return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c)) + + # ------------------------------------------------------------ monitor (every control step) + def _monitor(self): + env = self.env + for c in self.active: + if c in self.in_box: + if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02: + self._store(c) + continue + p = envs.obj_pos(env, c) + if self.inside_box(c): + self.in_box.append(c) + if self.announce_drops: + self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c, + text="A cube dropped into the box.")) + continue + if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where + self.rest_xy[c] = p[:2].copy() + continue + if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED + and len(self.in_box) == self._inst["p"] + and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"] + and self.sk.holding(c)): + self._do_slip(c) + + def _store(self, c): + sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)] + b = self._inst["box_xy"] + z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003) + envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z], + quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0]) + self.stored.append(c) + + def _do_slip(self, c): + inst = self._inst + src = self.rest_xy[c] + others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box] + xy, yaw = src, inst["slip_yaw"] + found = False + for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable + cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])]) + if not all(np.linalg.norm(cand - o) >= 0.07 for o in others): + continue + for dy in (0.0, 0.3, -0.3, 0.6, -0.6): + y = _wrap_q(inst["slip_yaw"] + dy) + if axis_clear(cand, y, others) >= HAND_CLEAR and \ + hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035: + xy, yaw, found = cand, y, True + break + if found: + break + envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw) + self.sk.grip = -1.0 # the gripper opens + self.env.sim.forward() + text = "A cube slipped out of the gripper and fell back onto the table." + 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), + in_box=len(self.in_box)) + self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text)) + + def drain_events(self): + ev = self.events[self._event_cursor:] + self._event_cursor = len(self.events) + return [e["text"] for e in ev] + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + n_in = len(self.in_box) + N = inst["n_target"] + held = [c for c in self.active if self.sk.holding(c)] + n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box) + n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box) + success = bool(n_in == N and not held) + terminal = bool(n_in > N) + if success: + head = f"The box holds exactly {N} cubes." + elif terminal: + head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no " + f"longer be completed.") + elif n_in == N: + head = f"The gripper is still holding a cube." + else: + head = f"The box holds fewer than {N} cubes." + state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table" + if n_lid: + state += f" and {n_lid} on the box lid" + state += "." + # F2 = verdict + currently observable state + the slip of this segment (never the number inside) + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"] + self._outcome_cursor = len(self.events) + detail = head + " " + state + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid, + held=len(held), slip=self.slip, detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _grasp_yaw(self, c): + """The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive + the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if + the hand would hit a neighbour or the box on this one.""" + R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3) + yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0]))) + p = envs.obj_pos(self.env, c)[:2] + others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box] + box = np.asarray(self._inst["box_xy"]) + + def score(a): + return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03) + if score(yaw) >= HAND_CLEAR: + return yaw + alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2 + return alt if score(alt) > score(yaw) + 0.02 else yaw + + def _pick(self, c): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, c) + sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12) + if sk.holding(c): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z_GRASP + 0.12]) + return False + + def _carry(self, c): + """Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'.""" + n_ev = len(self.events) + n_in = len(self.in_box) + if not self._pick(c): + self._bad.add(c) + self.go_home() # un-wind the arm before the next try + return "no_grasp" + h = self.hole_world() + sk = self.sk + sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening + if any(e["kind"] == "slip" for e in self.events[n_ev:]): + return "slipped" + sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([h[0], h[1], Z_CARRY]) + sk.hold(10) + return "in" if len(self.in_box) > n_in else "missed" + + def _next_cube(self): + """nearest table cube to the opening (what any policy sees in the current frame)""" + h = self.hole_world() + cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))] + cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp + if not cands: + return None + return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h)) + + def _add(self, k, log, stop_on_slip=False): + """Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped).""" + added, slipped = 0, False + guard = 0 + while added < k and guard < 3 * k + 3: + guard += 1 + c = self._next_cube() + if c is None: + break + r = self._carry(c) + log.append(r) + if r == "in": + added += 1 + elif r == "slipped": + slipped = True + if stop_on_slip: + break + return added, slipped + + # ------------------------------------------------------------ scripted references (within protocol) + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed + 7919) + self.reset_instance(inst) + N = inst["n_target"] + history = [] + for a in range(k): + log = [] + plan = dict(kind=kind, carries=log) + if a == 0: + if kind == "oracle": + while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count + c = self._next_cube() + if c is None: + break + log.append(self._carry(c)) + plan["recovery"] = "oracle: privileged box count" + elif kind in ("adaptive", "skip"): + added, slipped = self._add(N, log) if kind == "adaptive" else (0, False) + if kind == "skip": # counts carries, not drops + n_car = 0 + while n_car < N and len(log) < 3 * N: + c = self._next_cube() + if c is None: + break + r = self._carry(c) + log.append(r) + if r in ("in", "slipped"): + n_car += 1 + if r == "in": + added += 1 + plan["recovery"] = "counts carries (the slipped one too)" + else: + plan["recovery"] = "own drop count; the slipped carry is not counted" + else: # memoryless after the slip + added, slipped = self._add(N, log, stop_on_slip=True) + if slipped: + if kind == "naive": + guess = int(rng.integers(0, N)) + plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}" + self._add(N - guess, log) + elif kind == "blind": + plan["recovery"] = f"memoryless restart: puts {N} cubes in" + self._add(N, log) + elif kind == "inc1": + plan["recovery"] = "stateless: adds one cube per segment" + self._add(1, log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no slip)" + else: + if kind in ("adaptive", "skip"): + plan["recovery"] = "memory + F2 'fewer than N': add one cube" + self._add(1, log) + elif kind == "blind": + plan["recovery"] = f"memoryless restart: puts {N} cubes in" + self._add(N, log) + elif kind == "inc1": + plan["recovery"] = "stateless: adds one cube" + self._add(1, log) + elif kind == "oracle": + while len(self.in_box) < N and len(log) < 3 * N + 3: + c = self._next_cube() + if c is None: + break + log.append(self._carry(c)) + else: + raise ValueError(kind) + self.go_home() + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=plan, outcome=out)) + if on_attempt: + on_attempt(a, plan, out) + if out["success"] or out["terminal"] or kind in ("oracle", "naive"): + break + return history + + # cross-protocol hooks are not used by this task + def default_params(self, inst): + return dict(policy="naive") + + def oracle_params(self, inst): + return dict(policy="oracle") diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_key_turn.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_key_turn.py new file mode 100644 index 0000000000000000000000000000000000000000..a24b3373992c8885d206f601efbd3b317c756baf --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_key_turn.py @@ -0,0 +1,461 @@ +"""L7 key_turn: unlock a lock whose key turns only one way; which way is hidden. + +Category: failed_interaction_inference ("why did this contact not do what I expected?"). + +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 +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 +rotating the wrist. A red bolt sticks out of the box's front face (+x, towards the front camera) while it is locked +and slides in once the key has been turned to the open position. + +Hidden variable: the turning direction that opens the lock, clockwise (CW) or counterclockwise (CCW) seen from +above (alternates with the seed parity, so every block of instances is balanced). The other way the key has 3 deg of +play and then a hard stop. Both look exactly the same. + +Turns per attempt: not limited (2026-10-16, user). Until then the instruction allowed one turn per attempt and an +attempt with more than one turn failed; in every logged run whose first turn went the wrong way the agent turned the +other way within the same attempt and opened the lock, so the rule only made it repeat that correction in the next +attempt. The attempt now succeeds once the lock is open, however many turns it took. The trap is logged as an error +event instead: a turn "hits the stop" when it drives the key onto the stop on the locked side before the lock is open; +`trap_fired` = some turn did, `n_wrong_way` = how many did, `recovered_in_attempt` = trap fired and the lock was then +opened in the same attempt. A "turn" is any move_to that starts with the key held and changes the commanded yaw by +>= 5 deg, or that rotates the key by > 3 deg. A wrong turn costs one command, so this task does not meet design rule +R3 (the common-sense interaction must have a cost); its signal is clean success (first turn the right way) vs. +in-attempt recovery, and whether the agent keeps twisting the wrong way. + +Why the prior fails: the user's example -- many people first try counterclockwise. The scripted prior turns CCW by +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. +What must be learned from the failure: "the key would not turn this way at all" (not "my grip slipped") -> turn it +the other way. One failure is enough. + +Mechanics notes (measured in the prototype, 2026-10-08): + * the Panda's finger servo squeezes with kp * (finger opening) N, i.e. only ~4 N on a 7 mm head; the head then + twisted between the fingers and wedged them open. A 16 mm thick head gives ~8 N and turns reliably. + * without a stalling wrist the OSC keeps twisting against a blocked key, the fingers wedge open and on release + they knock the key 15-45 deg the free way (leaking the answer). `KeySkills` therefore stops rotating the wrist + once the held key sits on a stop and the gripper has twisted 6 deg past it (a torque-limited wrist), and limits + the wrist to 90 deg/s while turning. + * the stops use a stiff solref/solimp: with the defaults a hard twist pushed the key 10-15 deg past its stop. + * commanded yaw is taken literally in this task (nearest representation to the current yaw, clipped to + +-113 deg). The shared Skills.wrap_yaw maps yaw modulo 180 deg, which is right for grasping but would turn + "yaw = +95" into -85 deg, i.e. turn the key the wrong way. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, register_generated +from ..skills import DT, Skills, _rot_err, _rotz +from ..task_base import LFFTask, register_task + +LOCK = "lock_1" +MODEL = "lff_l7_lock" +LX, LY, LH = 0.045, 0.045, 0.05 # housing half x, half y, full height +HEAD = (0.018, 0.008, 0.015) # key head half extents: local x = width, y = thickness, z = height +HEAD_Z = 0.004 + HEAD[2] # head centre above the housing top +BOLT = (0.008, 0.012, 0.006) # red bolt (visual only) half extents +BOLT_OUT = (LX + BOLT[0], 0.0, 0.022) +BOLT_IN = (LX - BOLT[0] - 0.002, 0.0, 0.022) +PLAY = np.radians(3.0) +STOP = np.radians(90.0) +UNLOCK_AT = np.radians(80.0) +KEY_FRICTION = 0.04 # N m +W_MAX = np.radians(90.0) # wrist speed limit while turning (rad/s) +TWIST_MAX = np.radians(6.0) # wrist stalls when it has twisted this far past a blocked key +STALL_EXIT = 20 # control steps of stalling before the move gives up +TURN_YAW = np.radians(5.0) +TURN_KEY = np.radians(3.0) +STOP_HIT = PLAY - np.radians(0.5) # key this far the locked way = sitting on the locked-side stop +Z_GRIP = envs.TABLE_Z + LH + HEAD_Z # grasp-point height for the key head (its centre) + + +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)): + g = [f'', + f'', + f'', + f''] + k = ['', + # placeholder range: the open direction is set per instance (apply_instance) + f'', + f'', + f'', + f''] + shell = "\n ".join(g) + key = "\n ".join(k) + return f""" + + + + {shell} + + {key} + + + + + + + +""" + + +def _wrap_pi(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _wrap_half(a): + """the gripper is symmetric under a rotation by pi""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _rot_words(deg): + return f"{abs(deg):.0f} deg {'counterclockwise' if deg > 0 else 'clockwise'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _turn_txt(t, lead): + """F2 sentence for one logged turn: what the wrist and the key did, and whether the gripper held the key.""" + dk = t["key_end_deg"] - t["key_start_deg"] + txt = f"{lead} the wrist rotated {_rot_words(t['wrist_turn_deg'])} (seen from above)" + if abs(dk) < 1.0: + txt += " and the key did not rotate at all" + else: + txt += f" and the key rotated {_rot_words(dk)}" + if t["stalled"]: + txt += ", then it would not turn any further and the wrist stopped there" + if t["held_at_start"]: + txt += ("; the gripper lost hold of the key during the turn." if not t["held_at_end"] + else "; the gripper held the key throughout the turn.") + else: + txt += "; the gripper was not holding the key when that move started." + return txt + + +class KeySkills(Skills): + """Skills for the key task: literal yaw, wrist speed limit, stalling wrist, and a log of turns / grasps / unlock.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + m = env.sim.model + self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))] + self.turns = [] # one entry per move_to that counts as a turn + self.closes = [] # close_gripper events: gripper centre relative to the key head, held afterwards? + self.stall_steps = 0 + self._grasp_off = None # gripper yaw minus key yaw when the key was grasped + self.touch_since_report = False + + # ------------------------------------------------------------ state + def eef_yaw(self): + R = self.eef_mat() @ self.R0.T + return float(np.arctan2(R[1, 0], R[0, 0])) + + def holding_key(self): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=[self.task.head_geom_name])) + + def _touching_key(self): + d = self.env.sim.data + g, kg = set(self._grip_geoms), self.task.head_gid + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in g and c.geom2 == kg) or (c.geom2 in g and c.geom1 == kg): + return True + return False + + def wrap_yaw(self, yaw): + """Literal yaw: the representation of `yaw` closest to the current wrist yaw, clipped to the wrist range.""" + cur = self.eef_yaw() + y = cur + _wrap_pi(float(yaw) - cur) + return float(np.clip(y, -self.YAW_LIMIT, self.YAW_LIMIT)) + + # ------------------------------------------------------------ low level + def _act(self, dpos, drot, grip): + t = self.task + if self.grip > 0 and self._grasp_off is not None: + q = t.key_q() + lo, hi = t.key_range() + twist = _wrap_half(self.eef_yaw() - t.key_world_yaw() - self._grasp_off) + at_hi, at_lo = q >= hi - np.radians(1.5), q <= lo + np.radians(1.5) + if (at_hi and twist > TWIST_MAX and drot[2] > 0) or (at_lo and twist < -TWIST_MAX and drot[2] < 0): + drot = np.array(drot, float).copy() + drot[2] = -np.sign(twist) * 0.02 # force-limited wrist: back off instead of twisting further + self.stall_steps += 1 + super()._act(dpos, drot, grip) + t.check_unlock() + if self._touching_key(): + self.touch_since_report = True + + def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True): + """Skills.move_to with the wrist reference rotating at <= W_MAX and an early stop when the wrist stalls. + Logs the move as a turn when it starts with the key held and rotates the wrist, or when it rotates the key; + `hit_stop`: the turn went the locked way (wrist command if the key was held, else the key's motion) and the key + was on the locked-side stop during it, while the lock was still locked (the trap).""" + t = self.task + tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0) + if yaw is not None: + self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw) + yaw0 = self.eef_yaw() + dyaw = self.yaw - yaw0 + R_goal = self._R() + p0 = self.eef_pos() + q0, held0, locked0 = t.key_q(), self.holding_key(), not t.unlocked + q_open_min = t.open_sign() * q0 # lowest key angle the open way during the move + dist = np.linalg.norm(tgt - p0) + direction = (tgt - p0) / max(dist, 1e-9) + s = 0.0 + self.stall_steps = 0 + for k in range(max_steps): + if speed is not None: + s = min(dist, s + speed * DT) + ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5) + else: + ref = tgt + frac = min(1.0, (k + 1) * DT * W_MAX / max(abs(dyaw), 1e-6)) + R = _rotz(yaw0 + frac * dyaw) @ self.R0 + self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + q_open_min = min(q_open_min, t.open_sign() * t.key_q()) + if self.stall_steps >= STALL_EXIT: + break + if (np.linalg.norm(tgt - self.eef_pos()) < tol and (speed is None or s >= dist) and frac >= 1.0 + and np.linalg.norm(_rot_err(R_goal, self.eef_mat())) < 0.03): + break + stalled = self.stall_steps >= STALL_EXIT + if stalled: + # give up the unreached wrist angle; otherwise every later hold (e.g. while the gripper opens) keeps + # driving the wrist towards it and the arm swings away (seen in the agent self-test, 2026-10-08) + self.yaw = self.eef_yaw() + rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02), + pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=bool(stalled)) + self.log.append(rep) + dq = t.key_q() - q0 + locked_way = t.open_sign() * (dyaw if held0 else dq) < 0 + if (held0 and abs(dyaw) >= TURN_YAW) or abs(dq) > TURN_KEY: + self.turns.append(dict(step=self.n_steps, held_at_start=bool(held0), held_at_end=self.holding_key(), + key_start_deg=round(float(np.degrees(q0)), 1), + key_end_deg=round(float(np.degrees(t.key_q())), 1), + wrist_cmd_deg=round(float(np.degrees(dyaw)), 1), + wrist_turn_deg=round(float(np.degrees(self.eef_yaw() - yaw0)), 1), + stalled=bool(stalled), + hit_stop=bool(locked0 and locked_way and q_open_min <= -STOP_HIT))) + return rep + + def set_gripper(self, close, steps=15): + was_open = self.grip < 0 + rep = super().set_gripper(close, steps) + if close: + if self.holding_key(): + self._grasp_off = _wrap_half(self.eef_yaw() - self.task.key_world_yaw()) + if was_open: + off = self.eef_pos() - self.task.head_xyz() + self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_key(), + width=round(self.gripper_width(), 4))) + else: + self._grasp_off = None + return rep + + +@register_task +class KeyTurn(LFFTask): + name = "l7_key_turn" + level = "L7" + category = "failed_interaction_inference" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = ("Unlock the lock on the grey box: grasp the flat head of the brass key from above and turn the key " + "a quarter turn (90 degrees). The red bolt on the box slides in when it is unlocked.") + instruction_indirect = ("Open the lock of the small grey metal box: take hold of the flat gold-coloured tab that " + "sticks up out of its top and rotate it a quarter turn (90 degrees). The red block on the " + "box slides in when it is open.") + + # ------------------------------------------------------------ scene + def make_bddl(self): + lock = register_generated("LffKeyLock", lock_xml(MODEL), free=False) + return write_bddl(self.name, "unlock the lock", [], + fixtures=[(LOCK, lock, "lock_region", (-0.11, -0.01, -0.09, 0.01))]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{LOCK}_{MODEL}" + self.jid = m.joint_name2id(pre + "_key_joint") + self.qa = m.jnt_qposadr[self.jid] + self.dof = m.jnt_dofadr[self.jid] + self.lock_bid = m.body_name2id(self.env.fixtures_dict[LOCK].root_body) + self.head_geom_name = pre + "_head" + self.head_gid = m.geom_name2id(self.head_geom_name) + self.bolt_gid = m.geom_name2id(pre + "_bolt") + self.inst = None + self.unlocked = False + + # agent-facing hooks ------------------------------------------------------- + def on_agent_tool(self, inst, name, args, report): + """The lock is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never see + the key; add an explicit `holding_key` field and count key contacts as touches.""" + if self.sk is None or not isinstance(report, dict): + return + touched = self.sk.touch_since_report + self.sk.touch_since_report = False + if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"): + report["holding_key"] = self.sk.holding_key() + if touched and "touched_object" in report: + report["touched_object"] = True + + # ------------------------------------------------------------ state helpers + def key_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def key_range(self): + return self.env.sim.model.jnt_range[self.jid] + + def key_world_yaw(self): + return float(self.inst["lock_yaw"]) + self.key_q() + + def head_xyz(self): + return self.env.sim.data.geom_xpos[self.head_gid].copy() + + def open_sign(self): + return 1.0 if self.inst["direction"] == "CCW" else -1.0 + + def check_unlock(self): + """latch: the bolt is thrown back once the key reaches the open position (and stays back)""" + if not self.unlocked and self.open_sign() * self.key_q() >= UNLOCK_AT: + self.unlocked = True + self.env.sim.model.geom_pos[self.bolt_gid] = BOLT_IN + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + return dict(seed=int(seed), direction="CCW" if seed % 2 == 0 else "CW", + lock_xy=[float(rng.uniform(-0.15, -0.02)), float(rng.uniform(-0.15, 0.15))], + lock_yaw=float(rng.uniform(-np.radians(15), np.radians(15)))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + cx, cy = inst["lock_xy"] + a = inst["lock_yaw"] + m.body_pos[self.lock_bid] = [cx, cy, envs.TABLE_Z] + m.body_quat[self.lock_bid] = [np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)] + m.jnt_range[self.jid] = [-PLAY, STOP] if inst["direction"] == "CCW" else [-STOP, PLAY] + m.jnt_solref[self.jid] = [0.004, 1.0] + m.jnt_solimp[self.jid] = [0.99, 0.999, 0.001, 0.5, 2.0] + m.dof_frictionloss[self.dof] = KEY_FRICTION + m.geom_pos[self.bolt_gid] = BOLT_OUT + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + self.unlocked = False + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = KeySkills(self.env, self, recorder=recorder) + return self.sk + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 20) + sk = self.sk + n_turns = len(sk.turns) + n_wrong = sum(t["hit_stop"] for t in sk.turns) + success = bool(self.unlocked) + open_deg = float(np.degrees(self.open_sign() * self.key_q())) + out = dict(success=success, unlocked=bool(self.unlocked), n_turns=n_turns, n_wrong_way=n_wrong, + trap_fired=n_wrong > 0, recovered_in_attempt=bool(n_wrong and success), + key_deg=round(np.degrees(self.key_q()), 1), open_deg=round(open_deg, 1), turns=sk.turns, + closes=sk.closes, first_turn=sk.turns[0] if sk.turns else None) + parts = [] + grasp_txt = "" + if sk.closes: + c = sk.closes[0] + o = c["offset"] + top = envs.TABLE_Z + LH + HEAD_Z + HEAD[2] + below = top - (o[2] + self.head_xyz()[2]) + grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the centre of " + f"the key's head and {100 * below:.1f} cm below the top of the head; it " + + ("was holding the key." if c["held"] else "did not get hold of the key.")) + if success: + out["failure"] = None + parts.append("The lock is unlocked.") + elif n_turns == 0: + out["failure"] = "no_turn" + parts.append("The lock is still locked: the key was never turned.") + else: + out["failure"] = "still_locked" + parts.append("The lock is still locked.") + if n_turns == 1: + parts.append(_turn_txt(sk.turns[0], "During your turn")) + else: + parts.append(f"The key was turned (or pushed round) in {n_turns} separate moves.") + parts.append(_turn_txt(sk.turns[0], "During the first one")) + parts.append(_turn_txt(sk.turns[-1], "During the last one")) + if grasp_txt and not success: + parts.append(grasp_txt) + out["detail"] = " ".join(parts) + return out + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Grasp the key head from above across its thickness (+ jitter), one wrist turn of `turn` degrees + (+ = counterclockwise seen from above), release, lift.""" + sk = self.sk + p = self.head_xyz() + np.r_[params.get("dxy", (0.0, 0.0)), params.get("dz", 0.0)] # perfect perception + yaw0 = self.key_world_yaw() + np.radians(params.get("dyaw", 0.0)) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], p[2] + 0.08], yaw=yaw0) + sk.move_to([p[0], p[1], p[2]], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], p[2]], yaw=sk.eef_yaw() + np.radians(float(params["turn"])), max_steps=200) + sk.set_gripper(False, steps=8) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.08]) + + def default_params(self, inst): + """the prior from the user's example: try counterclockwise first""" + return dict(turn=90.0) + + def oracle_params(self, inst): + return dict(turn=90.0 * (1 if inst["direction"] == "CCW" else -1)) + + def adapt_params(self, inst, history): + """Scripted F2 learner. A turn after which the key rotated less than 10 deg the commanded way (it stopped) + -> that way is blocked -> turn the other way. A turn that rotated the key further but not far enough -> same + way, a bit more. Anything else (no turn, lost grip) -> repeat the last direction.""" + blocked = set() + good = 0 + for h in history: + t = h["outcome"].get("first_turn") + if t is None: + continue + sgn = int(np.sign(h["params"]["turn"])) + dk = t["key_end_deg"] - t["key_start_deg"] + if t["held_at_start"] and sgn * dk < 10.0: + blocked.add(sgn) + elif sgn * dk >= 10.0: + good = sgn + if good: + return dict(turn=100.0 * good) + last = int(np.sign(history[-1]["params"]["turn"])) + sgn = -last if last in blocked else last + if sgn in blocked: + sgn = -sgn + return dict(turn=90.0 * sgn) + + def blind_params(self, inst, attempt, rng): + """Same plan (counterclockwise quarter turn) with small random variation; no history.""" + 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(), + dyaw=float(rng.normal(0.0, 4.0))) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_offcenter_push.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_offcenter_push.py new file mode 100644 index 0000000000000000000000000000000000000000..699db8fd5b26ef48186bfc77e8b7f351c214c496 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/l7_offcenter_push.py @@ -0,0 +1,613 @@ +"""L7 offcenter_push: push a long box straight forward into a marked rectangle. + +Category: failed_interaction_inference ("why did this contact not do what I expected?"). The code keeps level "L7"; +the paper files the task under L5 (misjudged physics). + +Hidden variable: the box's centre of mass is shifted along its long axis by e (|e| ~ U[4.5, 7.5] cm, either +side; implemented by moving the body's inertial frame, `body_ipos`). The box looks exactly the same for +every e (uniform colour, a symmetric tape stripe across its middle). + +Why the prior fails: the natural push is at the middle of the box's back face. On a table the friction +resultant acts below the centre of mass, so a push whose line does not pass near it turns the box: the +heavy end lags behind. Measured (closed gripper at yaw 0, 8 cm/s, mu 0.5): pushing at the middle turns the +box 17 to 41 deg; the rectangle (box + 2 cm margin per side) only holds the box up to FIT_ANGLE = 10.9 deg +(exact geometry, box centred in the rectangle). Pushing within ~2 cm of the centre of mass gives a straight +translation (< 1 deg); 3 cm off gives 5-14 deg. + +What must be learned from the failure: the turning direction tells which end is heavy (the end that +lagged), the amount tells roughly how far off the push was; push closer to the heavy end. F2 reports the box's +turn (direction and size, plus how far one end lags the other), where the box's centre ended relative to the +rectangle's centre, and where on the back face the gripper first touched it -- all relative measurements, never +absolute coordinates or e itself. + +Pushes per attempt: not limited (2026-10-19, user). Until then the instruction allowed one push per attempt (one +move command that moves the box) and an attempt with more failed, so that the agent could not steer the box inside +an attempt; that moved trial and error that belongs inside an attempt to the next attempt. The attempt now succeeds +when the box ends completely inside the rectangle and upright, however many pushes it took (and every push was made +with the closed gripper, see below). + +Error events (logged; they never end the attempt). A "push" is a move_to that moves the box > 1 cm or turns it +> 3 deg (unchanged definition). After every push the box is classified against the rectangle (`box_fit`): +over_turned (|yaw| > FIT_ANGLE: it fits at no position), overshot (a corner past the far edge), sideways (a corner +past a side edge), short (a corner still in front of the near edge, i.e. not pushed far enough yet), inside. A push +is `bad` when it leaves the box over_turned, overshot or sideways (or tipped over: upright cos < 0.5) -- not inside, +and not merely short of the rectangle (pushing straight on can fix "short", so pushing the box in in several steps is +not an error). +Outcome: n_pushes, n_bad_pushes, n_turned_pushes (bad pushes that left the box over_turned), n_trap_events (pushes +that took the box from a good state -- inside or short -- into a bad one, i.e. how often the trap fired anew), +trap_fired = n_bad_pushes > 0, recovered_in_attempt = trap_fired and success, first_push (record of the first push) +with first_push_yaw_deg and first_interaction_ok (the first push left the box inside, or short and not turned out). +irrecoverable: the box tipped over (upright cos < 0.5 after a move, < 0.95 after the final settle), fell off the +table, or went out of reach (its centre beyond world x = X_LOST, where the gripper can no longer be put down in front +of it at pushing height to push it back, or beyond |y| = Y_LOST); logged with the control step, the attempt goes on. + +Closed gripper (2026-10-19): the instruction says "with the closed gripper", and a push made with the fingers open +(> OPEN_W apart when the move starts) now makes the attempt fail (failure "open_gripper" if the box is otherwise +inside). Reason, measured: open fingers touch the back face at two points ~8 cm apart, so ONE push at the middle of +the back face goes straight unless |e| > ~7 cm -- 22 of 25 instances (validation seeds 1000-1019, main 3000-3004) +succeeded that way without the centre of mass ever mattering. The box cannot be grasped, lifted or dragged by +pressing on its top (9 cm deep, the gripper opens 8 cm; measured), so no rule is needed for that. + +Correction cost (measured 2026-10-19, task card): after the natural first push (middle, whole distance) the box is +turned 17-41 deg and lies across the rectangle. What repairs it: get in front of the leading (light) end and push it +back -- the box turns back with little translation -- then push the box in near the heavy end. The scripted +corrector (adaptive) did that in attempt 1 on 19 of 20 instances, 7-15 extra commands (median 7: 2 more pushes). +What does not: pushing the lagging end forward from behind turns the box back only slowly and carries it past the +rectangle (0 of 25 instances repaired that way; 11 ended out of reach). Near the reach limit the fingers ride up onto +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 +FIT_ANGLE, so no error event) and shows the heavy end; probe + turn back + push in succeeded on 25 of 25 instances in +11 commands. So the task does not meet design rule R3 (a cost >= 10 commands for the common-sense first interaction); +its signal is clean success vs. in-attempt recovery (trap_fired / recovered_in_attempt) and first_push_yaw_deg. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BOX = "box_1" +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 +MASS = 0.6 +MU = 0.5 +MARGIN = 0.02 # target rectangle = box footprint + 2 cm on every side +RECT_HALF = HALF[:2] + MARGIN +E_MIN, E_MAX = 0.045, 0.075 +Z_PUSH = envs.TABLE_Z + 0.02 # grasp-point height during the push (finger tips ~1 cm above the table) +Z_SAFE = envs.TABLE_Z + 0.12 # travel height of the scripted corrector (8 cm above the box top) +PUSH_SPEED = 0.08 +FINGER_AHEAD = 0.009 # the closed fingers' front face is ~0.9 cm ahead of the grasp point (measured, yaw 0) +RUNUP = 0.04 +MOVE_TOL = 0.01 # a command "moved the box" if its centre moved this much ... +TURN_TOL = np.radians(3.0) # ... or it turned this much +TOUCH_TOL = 0.002 # the box "started to move" in a command once its centre moved this much +OPEN_W = 0.01 # finger opening above which a push counts as made with the gripper open (closed on nothing: 0.002 m) +TABLE_HALF = (0.5, 0.6) # LIBERO main_table top, centred at the world origin (table_collision geom) +# Reach at pushing height (grasp point 2 cm above the table, yaw 0; measured 2026-10-19): the gripper gets to world +# 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 +# back from in front of it (measured, box not turned): still works with the box's centre at x = 0.125 (far face at +# 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 +# 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 +# reach. The rectangle's far edge lies at world x = -0.055 ... 0.055. +X_LOST = 0.13 +Y_LOST = 0.40 +X_DOWN = 0.14 # farthest x at which the scripted corrector puts the gripper down in front of the box + + +def _fit_angle(half=HALF[:2], rect=RECT_HALF): + """Largest |yaw| at which the box's footprint still fits inside the rectangle (box centred in it): the + rotated footprint's half extents are (a cos t + b sin t, a sin t + b cos t).""" + t = np.radians(np.arange(0.0, 90.0, 0.01)) + 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]) + return float(t[np.argmin(ok)] - np.radians(0.01)) if not ok.all() else np.pi / 2 + + +FIT_ANGLE = _fit_angle() # 10.9 deg + + +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)): + """Solid box with an explicit inertial whose position is offset from the body origin at compile time, so + MuJoCo keeps the inertial frame separate (sameframe would otherwise ignore later changes of body_ipos).""" + I = mass / 12 * np.array([4 * (half[1] ** 2 + half[2] ** 2), 4 * (half[0] ** 2 + half[2] ** 2), + 4 * (half[0] ** 2 + half[1] ** 2)]) + tape = (half[0] + 0.0005, 0.012, 0.0006) + g = (f' \n' + f' \n' + f' \n' + f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def rect_frame_xml(name, inner_half=RECT_HALF, line_w=0.006, line_rgba=(0.1, 0.55, 0.15, 1.0), + fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat, visual-only rectangle drawn on the table (light fill + dark outline, no collisions).""" + hx, hy = inner_half + ox, oy = hx + line_w, hy + line_w + parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill_rgba), + ((0, hy + line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba), + ((0, -hy - line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba), + ((hx + line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba), + ((-hx - line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, float(np.hypot(ox, oy))) + + +def _yaw(quat_wxyz): + w, x, y, z = quat_wxyz + return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))) + + +def _rot(a): + return np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]]) + + +def _wrap_pi(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def box_corners(p_xy, yaw): + R = _rot(yaw) + return np.array([np.asarray(p_xy[:2], float) + R @ np.array([sx * HALF[0], sy * HALF[1]]) + for sx in (-1, 1) for sy in (-1, 1)]) + + +def box_fit(p_xy, yaw, t_xy): + """The box's footprint against the (axis-aligned) target rectangle centred at t_xy. bad = it cannot get into the + rectangle by being pushed straight on: turned beyond FIT_ANGLE, a corner past the far edge, or past a side edge.""" + c = box_corners(p_xy, yaw) - np.asarray(t_xy, float)[:2] + eps = 1e-6 + inside = bool(np.all(np.abs(c[:, 0]) <= RECT_HALF[0] + eps) and np.all(np.abs(c[:, 1]) <= RECT_HALF[1] + eps)) + yw = (yaw + np.pi / 2) % np.pi - np.pi / 2 # the footprint is symmetric under a half turn + over = bool(abs(yw) > FIT_ANGLE) + overshot = bool(np.any(c[:, 0] > RECT_HALF[0] + eps)) + sideways = bool(np.any(np.abs(c[:, 1]) > RECT_HALF[1] + eps)) + short = bool(np.any(c[:, 0] < -RECT_HALF[0] - eps)) + return dict(inside=inside, over_turned=over, overshot=overshot, sideways=sideways, short=short, + bad=bool(over or overshot or sideways)) + + +def _lr(v, unit="cm"): + return f"{100 * abs(v):.1f} {unit} to the {'left' if v > 0 else 'right'}" + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _turn_words(deg): + return f"{abs(deg):.0f} degrees {'counterclockwise' if deg > 0 else 'clockwise'}" + + +class _Budget(Exception): + """the scripted policy used up the agent command budget of the attempt""" + + +class PushSkills(Skills): + """Skills that log, for whoever drives them (scripted policy or agent), which move_to commands moved the + box (pushes), where the gripper touched it, the box's state after every push, and whether the box was lost.""" + + def __init__(self, env, bias=None, recorder=None, target=None): + super().__init__(env, bias=bias, recorder=recorder) + self.target = None if target is None else np.asarray(target, float)[:2] + self.first_touch = None # where the gripper's centre was (box frame) when the box first moved + self._p0, self._yaw0 = self._box_pose() + self.box_moves = [] # one entry per move_to that moved / turned the box (a "push") + self.n_moves = 0 # move_to commands (an agent's move_eef with a motion = one move_to) + self.lost = {} # irrecoverable condition -> control step at which it was first seen + self._mv = None # the move_to in progress: box pose at its start, first touch inside it + + def _box_pose(self): + p = envs.obj_pos(self.env, BOX) + return p, _yaw(envs.obj_quat(self.env, BOX)) + + def _local(self, p0, yaw0): + """gripper centre in the box frame given by (p0, yaw0): (u along the short side, v along the long side)""" + return (_rot(yaw0).T @ (self.eef_pos()[:2] - p0[:2])).tolist() + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + if self.first_touch is None or (self._mv is not None and self._mv["touch"] is None): + # "touch" = the first control step at which the box has moved 2 mm. Detected from the box's motion, + # not from contacts: a stiff gripper pushing a box makes a stick-slip contact that is often absent at the + # control-step boundaries (measured), so contact polling misses pushes. + p, _ = self._box_pose() + if self.first_touch is None and np.linalg.norm(p[:2] - self._p0[:2]) > TOUCH_TOL: + self.first_touch = dict(local=self._local(self._p0, self._yaw0), step=self.n_steps) + if self._mv is not None and self._mv["touch"] is None and np.linalg.norm(p[:2] - self._mv["p0"][:2]) > TOUCH_TOL: + self._mv["touch"] = self._local(self._mv["p0"], self._mv["yaw0"]) + + def fit(self, p=None, yaw=None): + if p is None: + p, yaw = self._box_pose() + return box_fit(p[:2], yaw, self.target) if self.target is not None else None + + def check_lost(self, final=False): + """record irrecoverable box states (tipped, off the table, out of reach); returns the current ones""" + p, _ = self._box_pose() + up = envs.obj_upright_cos(self.env, BOX) + now = [] + if up < (0.95 if final else 0.5): + now.append("tipped") + if p[2] < envs.TABLE_Z - 0.02 or abs(p[0]) > TABLE_HALF[0] or abs(p[1]) > TABLE_HALF[1]: + now.append("off_table") + elif p[0] > X_LOST or abs(p[1]) > Y_LOST: + now.append("out_of_reach") + for w in now: + self.lost.setdefault(w, self.n_steps) + return now + + def move_to(self, target, *args, **kwargs): + p0, y0 = self._box_pose() + fit0 = self.fit(p0, y0) + bad0 = fit0 is not None and (fit0["bad"] or envs.obj_upright_cos(self.env, BOX) < 0.5) + self._mv = dict(p0=p0, yaw0=y0, touch=None) + width0 = self.gripper_width() + self.n_moves += 1 + try: + rep = super().move_to(target, *args, **kwargs) + finally: + mv, self._mv = self._mv, None + p1, y1 = self._box_pose() + dturn = _wrap_pi(y1 - y0) + if np.linalg.norm(p1[:2] - p0[:2]) > MOVE_TOL or abs(dturn) > TURN_TOL: + rec = dict(step=self.n_steps, moved_cm=round(100 * float(np.linalg.norm(p1[:2] - p0[:2])), 1), + turned_deg=round(float(np.degrees(dturn)), 1), yaw_deg=round(float(np.degrees(y1)), 1), + gripper_open=bool(width0 > OPEN_W)) + t = mv["touch"] + if t is not None: + u, v = t + face = ("back" if u < -HALF[0] + 0.005 else "front" if u > HALF[0] - 0.005 else + "left_end" if v > 0 else "right_end") + rec.update(touch_u=round(float(u), 4), touch_v=round(float(v), 4), face=face) + fit1 = self.fit(p1, y1) + if fit1 is not None: + tipped = envs.obj_upright_cos(self.env, BOX) < 0.5 + bad = bool(fit1["bad"] or tipped) + rec.update(inside=fit1["inside"] and not tipped, over_turned=fit1["over_turned"], + overshot=fit1["overshot"], sideways=fit1["sideways"], tipped=bool(tipped), bad=bad, + new_trap=bool(bad and not bad0)) + self.box_moves.append(rec) + self.check_lost() + return rep + + +@register_task +class OffcenterPush(LFFTask): + name = "l7_offcenter_push" + level = "L7" + category = "failed_interaction_inference" + capabilities = ("Perceive", "Reason", "Utilize") + protocol = "cross" + # 2026-10-19 (wording): the instruction states only the end state. "straight forward ... without turning" read as + # a rule on the motion (no turning on the way, push only forward), but success is judged on the end state alone + # (completely inside the rectangle -- which bounds the turn to FIT_ANGLE -- upright, every push with the closed + # gripper), and the repair that works pushes the leading end back from in front of the box. + instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the " + "green rectangle ahead of it (farther from the robot).") + instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up " + "completely inside the marked green area ahead of it (farther from the robot).") + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffL7LongBox", long_box_xml("lff_l7_long_box")) + zone = register_generated("LffL7TargetRect", rect_frame_xml("lff_l7_target_rect"), free=False) + objs = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))] + fixtures = [("zone_1", zone, "zone_region", (-0.06, -0.01, -0.04, 0.01))] + return write_bddl(self.name, "push the long box into the green rectangle", objs, fixtures=fixtures) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX)) + return dict(seed=int(seed), box_xy=[float(rng.uniform(-0.20, -0.14)), float(rng.uniform(-0.08, 0.08))], + target_dist=float(rng.uniform(0.08, 0.13)), com_offset=e) + + def target_xy(self, inst): + return np.array([inst["box_xy"][0] + inst["target_dist"], inst["box_xy"][1]]) + + def apply_instance(self, inst): + m = self.env.sim.model + zone = self.env.fixtures_dict["zone_1"] + for g in range(m.ngeom): # the rectangle is a flat marker + if (m.geom_id2name(g) or "").startswith("zone_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + t = self.target_xy(inst) + zb = m.body_name2id(zone.root_body) + m.body_pos[zb] = [t[0], t[1], envs.TABLE_Z + 0.0002] + m.body_quat[zb] = [1.0, 0.0, 0.0, 0.0] + bid = envs.body_id(self.env, BOX) + m.body_mass[bid] = MASS + m.body_ipos[bid] = [0.0, inst["com_offset"], 0.0] + envs.refit_bounds(self.env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds) + envs.set_friction(self.env, BOX, MU) + x0, y0 = inst["box_xy"] + envs.set_obj_pose(self.env, BOX, [x0, y0, envs.TABLE_Z + HALF[2] + 0.001]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.sk = PushSkills(self.env, recorder=recorder, target=self.target_xy(inst)) + self.sim0 = self.sk.n_steps + return self.sk + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 30) + sk = self.sk + p = envs.obj_pos(self.env, BOX) + yaw = _yaw(envs.obj_quat(self.env, BOX)) + t = self.target_xy(inst) + fit = box_fit(p[:2], yaw, t) + inside = fit["inside"] + upright = envs.obj_upright_cos(self.env, BOX) > 0.95 + sk.check_lost(final=True) + pushes = sk.box_moves + n_push = len(pushes) + n_bad = sum(bool(m.get("bad")) for m in pushes) + n_open = sum(bool(m.get("gripper_open")) for m in pushes) + off = p[:2] - t + lag = 2 * HALF[1] * np.sin(yaw) # how far the +y end is behind (+) the -y end along x + success = bool(inside and upright and n_open == 0) + first = pushes[0] if pushes else None + out = dict(success=success, inside=bool(inside), upright=bool(upright), + n_pushes=n_push, n_bad_pushes=n_bad, + n_turned_pushes=sum(bool(m.get("over_turned")) for m in pushes), + n_trap_events=sum(bool(m.get("new_trap")) for m in pushes), + trap_fired=n_bad > 0, recovered_in_attempt=bool(n_bad and success), + first_push=first, first_push_yaw_deg=None if first is None else first["yaw_deg"], + first_interaction_ok=None if first is None else bool(not first.get("bad")), + n_open_gripper_pushes=n_open, + irrecoverable=bool(sk.lost), irrecoverable_why=dict(sk.lost), + n_box_moving_commands=n_push, box_moves=pushes, n_move_commands=sk.n_moves, + sim_s=round((sk.n_steps - getattr(self, "sim0", 0)) * 0.05, 1), + yaw_deg=round(float(np.degrees(yaw)), 1), + centre_offset=[round(float(off[0]), 4), round(float(off[1]), 4)], + touch_offset=None) + parts = [] + if sk.first_touch is None: + out["failure"] = "not_touched" + parts.append("The box did not move: the gripper never pushed it.") + else: + lt = sk.first_touch["local"] + out["touch_offset"] = round(float(lt[1]), 4) + if success: + parts.append("The box is completely inside the rectangle.") + elif not upright: + out["failure"] = "tipped" + parts.append("The box tipped over.") + elif inside: + out["failure"] = "open_gripper" + parts.append("The box is completely inside the rectangle, but it was pushed with the gripper open; " + "the task asks for pushing with the closed gripper.") + else: + out["failure"] = "turned" if abs(np.degrees(yaw)) > 6 else "position" + parts.append("The box is not completely inside the rectangle.") + if n_push > 1: + txt = f"It was moved by {n_push} separate move commands" + if abs(first["yaw_deg"]) >= 1.0: + txt += f"; after the first one it had turned {_turn_words(first['yaw_deg'])} (seen from above)" + parts.append(txt + ".") + if n_open and out.get("failure") != "open_gripper": + parts.append("The gripper was open during " + ("that push." if n_push == 1 else + f"{n_open} of the pushes.")) + turn = np.degrees(yaw) + if abs(turn) >= 1.0: + parts.append(f"It {'ended up turned' if n_push > 1 else 'turned'} {_turn_words(turn)} (seen from " + f"above): its {'left' if lag > 0 else 'right'} end ended {100 * abs(lag):.1f} cm " + f"further back than its {'right' if lag > 0 else 'left'} end.") + else: + parts.append("It did not turn (less than 1 degree)." if n_push <= 1 else + "It ended up not turned (less than 1 degree).") + parts.append(f"Its centre ended {_fb(off[0])} and {_lr(off[1])} of the rectangle's centre.") + parts.append(f"When the box started to move, the gripper's centre was {_lr(lt[1])} of the middle of " + f"the box (measured along the box's long side).") + out["detail"] = " ".join(parts) + return out + + # ------------------------------------------------------------ scripted primitives (agent-command counted) + def _cmd(self, target, yaw=None, speed=None, tol=0.004, max_steps=250): + """one agent command (move_eef; a gripper change rides on a move)""" + self.ncmd = getattr(self, "ncmd", 0) + 1 + budget = getattr(self, "budget", None) + if budget is not None and self.ncmd > budget: + raise _Budget() + self.sk.move_to(target, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + if budget is not None and self._sim_used() >= 3.0 * budget: # the server's motion budget (3 s per command) + raise _Budget() + + def _sim_used(self): + return (self.sk.n_steps - getattr(self, "sim0", 0)) * 0.05 + + def _push_at(self, face, v, dist, speed=PUSH_SPEED, runup=RUNUP): + """One push on the box as it lies now, with the closed gripper rotated to the face: face "back" (push + forward along the box's short side), "front" (push backwards) at long-side coordinate v (box frame), or + "left_end" / "right_end" (push along the long side at the middle of that end face). `dist` = how far the + fingers' front travels past the face. Commands: up (if low, 1), above the run-up point (1), down (1), push (1).""" + sk = self.sk + p, yaw = sk._box_pose() + R = _rot(yaw) + if face in ("back", "front"): + s = -1.0 if face == "back" else 1.0 + n, q, gyaw = R @ np.array([s, 0.0]), p[:2] + R @ np.array([s * HALF[0], v]), yaw + else: + s = 1.0 if face == "left_end" else -1.0 + n, q, gyaw = R @ np.array([0.0, s]), p[:2] + R @ np.array([0.0, s * HALF[1]]), yaw + np.pi / 2 + start = q + n * (runup + FINGER_AHEAD) + end = q - n * (dist - FINGER_AHEAD) + e = sk.eef_pos() + if e[2] < Z_PUSH + 0.05: + self._cmd([e[0], e[1], Z_SAFE], speed=0.2) + self._cmd([start[0], start[1], Z_SAFE], yaw=gyaw) + self._cmd([start[0], start[1], Z_PUSH], tol=0.003) + self._cmd([end[0], end[1], Z_PUSH], speed=speed, tol=0.004, max_steps=400) + + # ------------------------------------------------------------ scripted execution (cross protocol) + def execute(self, inst, params): + """Closed gripper behind the box at lateral offset `c` (from the box's middle, along its long axis), then one + slow straight move_to forward ending `end_dx` beyond the nominal end point (target centre minus half the box + depth minus the finger offset), then lift. 4 commands (the gripper closes with the first one).""" + sk = self.sk + p = envs.obj_pos(self.env, BOX) # perfect perception of the current scene + t = self.target_xy(inst) + c = float(params["c"]) + y = p[1] + c + face = p[0] - HALF[0] + x_end = t[0] - HALF[0] - FINGER_AHEAD + float(params.get("end_dx", 0.0)) + sk.set_gripper(True, steps=8) + self._cmd([face - RUNUP, y, Z_PUSH + 0.08], yaw=0.0) + self._cmd([face - RUNUP, y, Z_PUSH], tol=0.003) + self._cmd([x_end, y, Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400) + self._cmd([x_end - 0.03, y, Z_PUSH + 0.10], speed=0.2) + + def default_params(self, inst): + return dict(c=0.0, end_dx=0.0) # Sonnet 5.5 (cla2 / cla4 / full5): yaw 0, middle of the back face, one push + + def oracle_params(self, inst): + return dict(c=float(inst["com_offset"]), end_dx=0.0) + + STEP = 0.06 # first correction toward the lagging end (the expected |e| range is unknown to the learner) + YAW_OK = 3.0 # deg: the corrector turns the box back until it is within this + GAIN0 = 2.8 # deg of turn per cm of a push at the leading end from the front, 3 cm from the end (measured) + SAFE_V = HALF[1] - 0.02 # contact points stay 2 cm inside the ends + + def bracket(self, pushes): + """Contact point estimate from logged pushes on the back / front face: a push whose box turned + counterclockwise passed to the right of the centre of mass when pushing forward (back face) and to its left + when pushing backwards (front face); a long push that did not turn passed within ~2 cm of it.""" + lo, hi = -self.SAFE_V, self.SAFE_V + lo_set = hi_set = False + for m in pushes: + if m.get("face") not in ("back", "front") or m.get("gripper_open"): + continue + v, turn = m["touch_v"], m["turned_deg"] * (1.0 if m["face"] == "back" else -1.0) + if turn > 3.0: + lo, lo_set = max(lo, v + 0.01), True + elif turn < -3.0: + hi, hi_set = min(hi, v - 0.01), True + elif abs(turn) < 1.5 and m["moved_cm"] >= 3.0: + lo, hi, lo_set, hi_set = max(lo, v - 0.02), min(hi, v + 0.02), True, True + if lo > hi: # inconsistent (contacts slide): trust the newest + lo, hi = hi, lo + if lo_set and hi_set: + c = 0.5 * (lo + hi) + elif lo_set: + c = lo + self.STEP + elif hi_set: + c = hi - self.STEP + else: + c = 0.0 + return float(np.clip(c, -self.SAFE_V, self.SAFE_V)) + + def adapt_params(self, inst, history): + """Cross-attempt start point: push where the pushes of the earlier attempts put the centre of mass.""" + return dict(c=round(self.bracket([m for h in history for m in h["outcome"]["box_moves"]]), 4), end_dx=0.0) + + @staticmethod + def _front_runup(p, yaw, v): + """run-up for a push on the front face at v that keeps the gripper's put-down point within X_DOWN; None when + even a 1.5 cm run-up does not fit (the box is too far forward to get in front of it)""" + R = _rot(yaw) + f, n_out = p[:2] + R @ np.array([HALF[0], v]), R @ np.array([1.0, 0.0]) + runup = min(RUNUP, (X_DOWN - f[0]) / max(n_out[0], 0.2) - FINGER_AHEAD) + return float(runup) if runup >= 0.015 else None + + def adaptive_attempt(self, inst, c0, prior_pushes=()): + """In-attempt corrector: the first push as `execute` (at c0: the middle in attempt 1, like the naive policy); + then, after every push, look at the box (perfect perception) and push again until it is inside or the agent + budget would run out. Turned more than YAW_OK -> push its leading end back from the front (it turns back with + little translation), or if it is too far forward for that, the lagging end forward from behind; not turned + but short / past the far edge / out at a side -> push it straight from behind / from the front at the + estimated centre of mass, or along its long side at an end face. Returns the number of corrective pushes.""" + self.execute(inst, dict(c=c0, end_dx=0.0)) + sk = self.sk + t = self.target_xy(inst) + gain = self.GAIN0 + sim_budget = 3.0 * self.budget if self.budget is not None else np.inf + n = 0 + while True: + p, yaw = sk._box_pose() + fit = sk.fit(p, yaw) + if fit["inside"] or sk.lost: + return n + if (self.budget is not None and self.ncmd + 4 > self.budget) or self._sim_used() + 10.0 > sim_budget: + return n + n += 1 + yd = np.degrees(yaw) + c_est = self.bracket(list(prior_pushes) + sk.box_moves) + if abs(yd) > self.YAW_OK: + for vm in (HALF[1] - 0.03, 0.06, 0.04, 0.02): # the leading (light) end, or nearer the middle if + v_lead = -np.sign(yd) * vm # the end is out of reach; +v = the box's left end + runup = self._front_runup(p, yaw, v_lead) + if runup is not None: + break + if runup is not None: + d = float(np.clip(abs(yd) / gain, 1.0, 10.0)) / 100 + self._push_at("front", v_lead, d, runup=runup) + dy = abs(yd) - abs(np.degrees(sk._box_pose()[1])) + if dy > 1.0: + gain = float(np.clip(dy / (100 * d), 1.0, 5.0)) + else: + self._push_at("back", np.sign(yd) * (HALF[1] - 0.01), 0.03) + else: + dx = t[0] - p[0] + if fit["overshot"]: + runup = self._front_runup(p, yaw, c_est) + if runup is None: + return n + self._push_at("front", c_est, max(0.005, -dx), runup=runup) + elif fit["sideways"]: + dyy = t[1] - p[1] + self._push_at("right_end" if dyy > 0 else "left_end", 0.0, max(0.005, abs(dyy) - 0.005)) + else: + self._push_at("back", c_est, max(0.005, dx)) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """Cross protocol with the agent's command budget per attempt (agent_max_steps, default 40 commands and + 3 s of motion per command; one move_eef = one command). naive / oracle / blind: one push, then finish. + adaptive: in-attempt corrector (`adaptive_attempt`); attempt 1 starts with the naive push, later attempts + at the contact point estimated from all earlier pushes.""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + self.ncmd, self.budget = 0, int(getattr(self, "agent_max_steps", 40)) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "adaptive": + params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history) + else: + raise ValueError(kind) + try: + if kind == "adaptive": + prior = [m for h in history for m in h["outcome"]["box_moves"]] + params["corrections"] = self.adaptive_attempt(inst, params["c"], prior) + else: + self.execute(inst, params) + except _Budget: + params["budget_used_up"] = True + self.budget = None + out = self.outcome(inst) + out["commands"] = self.ncmd + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive"): + break + return history + + blind_sigma = 0.008 + + def blind_params(self, inst, attempt, rng): + """Same plan (push at the middle) with a small random variation of the contact point; no history.""" + return dict(c=float(rng.normal(0.0, self.blind_sigma)), end_dx=0.0) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_breakfast_service.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_breakfast_service.py new file mode 100644 index 0000000000000000000000000000000000000000..76f751d6bb88f22613915c975ca99bba920e21ea --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_breakfast_service.py @@ -0,0 +1,546 @@ +"""Breakfast revision 2: food meshes, hinged milk pourer, L1/L3/L4 recovery. + +Rigid bodies use MuJoCo contacts. Milk is an explicitly reduced-order, volume- +conserving discharge / ballistic parcel model, NOT Navier-Stokes fluid simulation. +Only the physical carton angle controls discharge. No policy/stage success gates. +An upright butter stick physically obstructs the lid. Lay it flat to recover. +There is no latch fatigue, artificial opening torque, or forced orientation. +""" +from pathlib import Path +import copy +import xml.etree.ElementTree as ET +import numpy as np +import robosuite +import libero.libero as libero_pkg + +from .. import envs +from ..bddl import write_bddl +from ..objects import register_generated, _wrap, _fmt +from ..skills import Skills +from ..task_base import register_task +from .lh_pantry_relatch import (PantryRelatch, RelatchSkills, BREAD_HALF, + BOX, BOX_MODEL, FLOOR_T, WALL_H, BOX_D, box_lid_xml) + +LIB_ASSETS = Path(libero_pkg.__file__).parent / 'assets' +RS_ASSETS = Path(robosuite.__file__).parent / 'models/assets' +BUTTER_HALF = (.010,.020,.040) # standing: 8 cm tall; lying: 2 cm tall, fits the 2.6 cm cavity + + +def food_xml(kind, half): + """Reuse installed textured visual meshes, normalized to the tested food collision hull.""" + if kind == 'bread': + source = RS_ASSETS / 'objects/bread.xml' + meshpath = RS_ASSETS / 'objects/meshes/bread.stl' + data = meshpath.read_bytes() + n = int.from_bytes(data[80:84], 'little') + dtype = np.dtype([('normal','') + xml = ET.fromstring(_wrap('breakfast_'+kind, hull+ET.tostring(visual,encoding='unicode'),half[2],.05)) + xml.insert(0,asset) + return ET.tostring(xml,encoding='unicode') + + +def milk_station_xml(): + source = LIB_ASSETS/'stable_hope_objects/milk/milk.xml' + root = ET.parse(source).getroot() + asset = root.find('asset') + for el in asset: + if el.get('file'): el.set('file', str(source.parent/el.get('file'))) + carton = copy.deepcopy(root.find('worldbody/body/body')) + carton.set('name','carton_visual'); carton.set('quat','.5 .5 .5 .5') + # A carton held in a tabletop tipping cradle. The hinge is physical, unactuated. + parts = ''' + + + + + + + + + + + + ''' + xml = ET.fromstring(_wrap('breakfast_milk_station',parts,0,.08)) + xml.insert(0,asset) + xml.find(".//body[@name='tilting_carton']").append(carton) + for parent in xml.iter('body'): + for geom in list(parent.findall('geom')): + if geom.get('group') is None: + geom.set('group','0') + vis=copy.deepcopy(geom);vis.set('group','1');vis.set('contype','0');vis.set('conaffinity','0') + vis.attrib.pop('name',None);vis.set('mass','0');parent.append(vis) + return ET.tostring(xml,encoding='unicode') + + +def liquid_visual_xml(): + geoms = [''] + for i in range(80): + geoms.append(f'') + geoms.append('') + return _wrap('breakfast_liquid', ''.join(geoms),0,.001) + + +def fixed_cup_xml(): + source=LIB_ASSETS/'turbosquid_objects/porcelain_mug/porcelain_mug.xml' + root=ET.parse(source).getroot() + for el in root.find('asset'): + if el.get('file'):el.set('file',str(source.parent/el.get('file'))) + return ET.tostring(root,encoding='unicode') + + +def serving_plate_xml(): + source=LIB_ASSETS/'stable_scanned_objects/plate/plate.xml' + root=ET.parse(source).getroot();scale=1.5 + for el in root.find('asset'): + if el.get('file'):el.set('file',str(source.parent/el.get('file'))) + if el.tag=='mesh':el.set('scale',_fmt(np.fromstring(el.get('scale'),sep=' ')*scale)) + for el in root.iter(): + if el.tag in ('geom','site'): + if el.get('pos'):el.set('pos',_fmt(np.fromstring(el.get('pos'),sep=' ')*scale)) + if el.get('size'):el.set('size',_fmt(np.fromstring(el.get('size'),sep=' ')*scale)) + return ET.tostring(root,encoding='unicode') + + +class BreakfastSkills(RelatchSkills): + def __init__(self,env,task,recorder=None): + super().__init__(env,task,recorder) + self.bias=np.asarray(task.inst['bias'] if task.inst['mechanisms']['L1'] else [0,0,0],float) + self.correction=np.zeros(3) + self.pour_latched=False + self.pour_rad=0. + self.pour_y=0. + + def move_to(self,target,*args,**kwargs): + return super().move_to(np.asarray(target)-self.correction,*args,**kwargs) + + def set_gripper(self,close,steps=15): + rep=super().set_gripper(close,steps) + if close and self.task.holding_pour_knob(): + self.pour_latched=True + e=self.eef_pos(); h=self.task.pour_pivot() + self.pour_rad=float(np.linalg.norm((e-h)[[0,2]]));self.pour_y=float(e[1]) + elif not close:self.pour_latched=False + return rep + + def _act(self,dpos,drot,grip): + if self.pour_latched and self.task.inst['mechanisms']['L3']: + e=self.eef_pos(); k=self.task.pour_knob() + if grip<0 or np.linalg.norm(e-k)>.04:self.pour_latched=False + else: + h=self.task.pour_pivot();r=(e-h)[[0,2]];rn=max(np.linalg.norm(r),1e-6) + t=np.array([-r[1],r[0]])/rn + s=np.clip(np.asarray(dpos)[[0,2]]@t,-.008,.008) + corr=(self.pour_rad-rn)*r/rn + dpos=np.array([s*t[0]+corr[0], self.pour_y-e[1],s*t[1]+corr[1]]) + super()._act(dpos,drot,grip) + + +@register_task +class BreakfastService(PantryRelatch): + name='lh_breakfast_service' + level='L1' + category='system_identification' + failure_causes=('L1','L3','L4') + failure_types=failure_causes + agent_max_steps=360 + instruction=('Prepare breakfast: put the bread from the wooden box onto the plate and close the box; ' + 'pour 80 to 160 mL of milk into the cup using the milk carton in its cradle. ' + 'Then store the butter inside the box and leave its lid shut. Finish with the carton upright, ' + 'bread on the plate, cup upright, and gripper open and clear. Spill at most 15 mL. ' + 'The cradle can be tipped with its gold side handle using ordinary gripper motions.') + instruction_indirect=instruction + agent_object_names=['bread','butter','plate','cup','milk carton','gold cradle handle','wooden box','lid knob'] + + def make_bddl(self): + boxroot=ET.fromstring(box_lid_xml(BOX_MODEL)) + inertial=boxroot.find('.//inertial');ratio=.08/float(inertial.get('mass')) + inertial.set('mass','.08');inertial.set('diaginertia',_fmt(np.fromstring(inertial.get('diaginertia'),sep=' ')*ratio)) + box=register_generated('LffBreakfastBox',ET.tostring(boxroot,encoding='unicode'),free=False) + bread=register_generated('LffBreakfastBread',food_xml('bread',BREAD_HALF)) + butter=register_generated('LffBreakfastButter',food_xml('butter',BUTTER_HALF)) + milk=register_generated('LffBreakfastMilk',milk_station_xml(),free=False) + liquid=register_generated('LffBreakfastLiquid',liquid_visual_xml(),free=False) + cup=register_generated('LffBreakfastCup',fixed_cup_xml(),free=False) + plate=register_generated('LffBreakfastPlate',serving_plate_xml()) + objs=[('bread_1',bread,'bread_region',(-.31,-.01,-.29,.01)), + ('butter_1',butter,'butter_region',(-.31,.24,-.29,.26)), + ('plate_1',plate,'plate_region',(.02,-.26,.04,-.24))] + fx=[(BOX,box,'box_region',(-.18,-.12,-.16,-.10)), + ('milk_1',milk,'milk_region',(.24,-.01,.26,.01)), + ('liquid_1',liquid,'liquid_region',(.34,-.34,.35,-.33)), + ('cup_1',cup,'cup_region',(.14,.26,.16,.28))] + return write_bddl(self.name,self.instruction.replace(';',','),objs,fx) + + def __init__(self,cam_res=None): + super().__init__(cam_res) + m=self.env.sim.model + self.milk_bid=m.body_name2id(self.env.fixtures_dict['milk_1'].root_body) + self.pour_jid=m.joint_name2id('milk_1_pour_hinge') + self.slide_jid=m.joint_name2id('milk_1_pull_slide');self.slide_qa=int(m.jnt_qposadr[self.slide_jid]) + self.pour_qa=int(m.jnt_qposadr[self.pour_jid]);self.pour_dof=int(m.jnt_dofadr[self.pour_jid]) + self.pour_gid=m.geom_name2id('milk_1_pour_knob') + self.nozzle_sid=m.site_name2id('milk_1_nozzle') + self.liquid_bid=m.body_name2id(self.env.fixtures_dict['liquid_1'].root_body) + self.cup_bid=m.body_name2id(self.env.fixtures_dict['cup_1'].root_body) + self.drop_gids=[m.geom_name2id('liquid_1_drop_'+str(i)) for i in range(80)] + self.surface_gid=m.geom_name2id('liquid_1_milk_surface');self.spill_gid=m.geom_name2id('liquid_1_spill') + self.liquid=None;self.phase_hook=None + + def sample_instance(self,seed): + inst=super().sample_instance(seed) + rng=np.random.default_rng(seed) + inst.update(box_xy=[-.20,-.10],plate_xy=[-.09,-.32],butter_xy=[-.36,-.32], + milk_xy=[-.14,.24],cup_xy=[-.075,.24], + bias=[0,float(rng.choice([-1,1])*.10),0], + mechanisms={'L1':True,'L3':True,'L4':True},flow_ml_s=float(rng.uniform(42,48))) + return inst + + def apply_instance(self,inst): + super().apply_instance(inst) + m,d=self.env.sim.model,self.env.sim.data + half_z=BUTTER_HALF[2] if inst['mechanisms']['L4'] else BUTTER_HALF[0] + quat=[1,0,0,0] if inst['mechanisms']['L4'] else [np.sqrt(.5),0,np.sqrt(.5),0] + envs.set_obj_pose(self.env,'butter_1',[*inst['butter_xy'],envs.TABLE_Z+half_z+.001],quat_wxyz=quat) + self.drift_active=False;self.active_latch=0. + envs.scale_mass(self.env,'plate_1',.4) + envs.set_friction(self.env,'plate_1',.8) + m.body_pos[self.milk_bid]=[*inst['milk_xy'],envs.TABLE_Z] + m.body_quat[self.milk_bid]=[1,0,0,0] + m.body_pos[self.liquid_bid]=[0,0,0];m.body_quat[self.liquid_bid]=[1,0,0,0] + d.qpos[self.pour_qa]=0;d.qvel[self.pour_dof]=0 + d.qpos[self.slide_qa]=0 + m.jnt_range[self.slide_jid]=[-.00001,.00001] if inst['mechanisms']['L3'] else [-.11,.01] + m.body_pos[self.cup_bid]=[*inst['cup_xy'],envs.TABLE_Z-.0024] + m.body_quat[self.cup_bid]=[1,0,0,0] + for gid in self.drop_gids+[self.surface_gid,self.spill_gid]:m.geom_rgba[gid,3]=0 + self.liquid=dict(reservoir=300.,cup=0.,spill=0.,parcels=[],emitted=0.,spill_xy=None) + self.trace=[] + + def reset_instance(self,inst,recorder=None): + self.mon=None + np.random.seed(int(inst['seed'])) + self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,10) + self.mon=dict(events=[],lid_open_max=0.,armed=False) + self.sk=BreakfastSkills(self.env,self,recorder) + self.traps={k:False for k in self.failure_causes} + self.recovered={k:False for k in self.failure_causes} + self.initial_pour_pivot=self.pour_pivot().copy() + return self.sk + + def _register_close(self,seated): + self.closes_done+=1;self.active_latch=0.;self.drift_active=False + self.mon['events'].append(dict(ev='closed',n=self.closes_done,mechanism='ordinary rigid-body hinge')) + + def _bracket(self): + # Disable the predecessor's modeled spring/catch completely, at every physics substep. + self.env.sim.data.qfrc_applied[self.dof]=0. + + def butter_corners(self): + p=envs.obj_pos(self.env,'butter_1') + R=self.env.sim.data.body_xmat[envs.body_id(self.env,'butter_1')].reshape(3,3) + 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)]) + + def butter_height(self): + c=self.butter_corners();return float(np.ptp(c[:,2])) + + def butter_in_box(self): + from .lh_lid_box import IN_X,IN_Y + c=self.butter_corners();b=np.asarray(self.inst['box_xy']) + inside=np.all(np.abs(c[:,:2]-b)<[IN_X+.001,IN_Y+.001]) + return bool(inside and c[:,2].max()envs.TABLE_Z+FLOOR_T-.002 and not self.held('butter_1')) + + def butter_lid_contact(self): + m=self.env.sim.model + lid=m.geom_name2id('box_1_'+BOX_MODEL+'_lid') + return envs.contacts_between(self.env,envs.obj_geom_ids(self.env,'butter_1'),[lid]) + + def pick_place(self,name,dest_xy,z_rel,z_carry=.18,dest_yaw=0.): + if name!='butter_1':return super().pick_place(name,dest_xy,z_rel,z_carry,dest_yaw) + s=self.sk;p=envs.obj_pos(self.env,name).copy() + tall=self.butter_height()>.045 + grasp=p+np.array([0,0,.025 if tall else 0.]) + s.set_gripper(False,8);s.move_to([p[0],p[1],1.12],yaw=0) + s.move_to(grasp,speed=.10,tol=.002,max_steps=120);s.set_gripper(True,20) + s.move_to([p[0],p[1],1.12],speed=.15) + if not self.held(name):s.set_gripper(False,8);return False + offset=envs.obj_pos(self.env,name)-s.eef_pos() + target=np.array([*dest_xy,envs.TABLE_Z+z_rel])-offset + s.move_to([target[0],target[1],1.12],yaw=dest_yaw) + s.move_to(target,speed=.10,tol=.003,max_steps=120) + s.set_gripper(False,12);s.move_to([target[0],target[1],1.14]);s.hold(10) + return True + + def put_butter(self): + # Place the standing stick near the front wall; lay-flat placement uses the box centre. + standing=self.butter_height()>.045 + target=np.array(self.inst['box_xy'])+([-0.030,0] if standing else [0,0]) + return self.pick_place('butter_1',target,FLOOR_T+self.butter_height()/2+.003,z_carry=.18) + + def lay_butter_flat(self): + """Extract, tip on the table through contact, then pick the horizontal stick. No pose writes.""" + s=self.sk;xy=np.asarray(self.inst['butter_xy']) + self.label('L4 recovery: take the upright stick out of the box') + if not self.pick_place('butter_1',xy,self.butter_height()/2+.003,z_carry=.18):return False + p=envs.obj_pos(self.env,'butter_1').copy() + self.label('Recovery: tip the butter stick onto its broad side') + s.set_gripper(True,8) + s.move_to([p[0]-.055,p[1],1.07],yaw=0) + s.move_to([p[0]-.055,p[1],envs.TABLE_Z+.055],speed=.10) + s.move_to([p[0]+.025,p[1],envs.TABLE_Z+.055],speed=.06) + s.move_to([p[0]+.025,p[1],1.10],speed=.12);s.set_gripper(False,8);s.hold(60) + self.label('Recovery: the butter stick is now lying flat on the table') + return self.butter_height()<.029 + + def pour_pivot(self): + 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]) + def pour_knob(self):return self.env.sim.data.geom_xpos[self.pour_gid].copy() + def pour_angle(self):return float(self.env.sim.data.qpos[self.pour_qa]) + def holding_pour_knob(self): + g=self.env.robots[0].gripper + return bool(self.env._check_grasp(gripper=[g.important_geoms['left_finger'],g.important_geoms['right_finger']], + object_geoms=['milk_1_pour_knob','milk_1_pour_bar'])) + + def monitor_step(self): + super().monitor_step() + if getattr(self,'liquid',None) is None or self.mon is None:return + if self.pour_angle()0: + # small outward speed along the spout, transformed by the actual hinge angle + vel=np.array([np.cos(a),0,-np.sin(a)])*.04 + q['parcels'].append(dict(p=origin.copy(),v=vel,ml=dv)) + q['reservoir']-=dv;q['emitted']+=dv + cup_origin=d.body_xpos[self.cup_bid] + cup_rot=d.body_xmat[self.cup_bid].reshape(3,3) + cup=cup_origin+cup_rot@np.array([.015,-.0016,.10]);top=cup[2] + keep=[] + for drop in q['parcels']: + p=drop['p'];v=drop['v'];end=p+v*dt+np.array([0,0,-.5*9.81*dt*dt]) + caught=False + if p[2]>=top>end[2]: + hit=p+(end-p)*(p[2]-top)/(p[2]-end[2]) + if np.linalg.norm(hit[:2]-cup[:2])<.029 and self.cup_upright(): + q['cup']+=drop['ml'];caught=True + excess=max(0.,q['cup']-180.) + if excess: + q['cup']-=excess;q['spill']+=excess;q['spill_xy']=cup[:2].tolist() + if not caught and end[2]<=envs.TABLE_Z+.002: + q['spill']+=drop['ml'];q['spill_xy']=end[:2].tolist();caught=True + if not caught: + drop['p']=end;drop['v']=v+np.array([0,0,-9.81*dt]);keep.append(drop) + q['parcels']=keep + if not render_update:return + for i,gid in enumerate(self.drop_gids): + if i.1) + if q['spill']>.1: + m.geom_pos[self.spill_gid]=[*q['spill_xy'],envs.TABLE_Z+.002] + m.geom_size[self.spill_gid,0]=min(.08,.009*np.sqrt(q['spill'])) + m.geom_rgba[self.spill_gid,3]=1 + self.env.sim.forward() + + def cup_upright(self): + # Native mug uses world Z as its vertical in the loaded LIBERO pose. + return bool(self.env.sim.data.body_xmat[self.cup_bid].reshape(3,3)[2,2]>.94) + + def label(self,text): + state=dict(text=text,step=self.sk.n_steps,lid_deg=self.lid_deg(), + pour_deg=float(np.degrees(self.pour_angle())),cup_ml=self.liquid['cup'],spill_ml=self.liquid['spill'], + butter_height_cm=100*self.butter_height(),butter_lid_contact=bool(self.butter_lid_contact()), + lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof])) + self.trace.append(state) + if self.phase_hook:self.phase_hook(text,state) + + def calibration_probe(self): + # Attempt the loose butter first, away from fixture walls; fixed bias is present for ALL motions. + p=envs.obj_pos(self.env,'butter_1').copy();s=self.sk + s.set_gripper(False,8);s.move_to([p[0],p[1],envs.TABLE_Z+.14],yaw=0,tol=.0005,max_steps=120) + observed=s.eef_pos()-np.array([p[0],p[1],envs.TABLE_Z+.14]) + s.move_to(p,tol=.002,max_steps=100) + s.set_gripper(True,15);s.move_to([p[0],p[1],envs.TABLE_Z+.15]) + failed=not s.holding('butter_1') + self.traps['L1']=bool(failed) + self.label('L1: grasp missed the butter' if failed else 'Calibration grasp succeeded') + s.set_gripper(False,8) + return observed + + def direct_carton_lift(self): + s=self.sk;k=self.pour_knob();start=k.copy() + s.set_gripper(False,8) + s.move_to(k+[0,0,.10],yaw=0) + s.move_to(k,speed=.12,max_steps=100) + s.set_gripper(True,20) + held_before=self.holding_pour_knob() + # Pulling along the radius cannot translate a hinged cradle. Same low-level interface as agents. + s.move_to(k+[-.07,0,0],speed=.08,max_steps=30) + lift=float(np.linalg.norm(self.pour_knob()-start)) + self.pull_probe=dict(held_before=held_before,held_after=self.holding_pour_knob(),displacement_m=lift, + angle_deg=float(np.degrees(self.pour_angle()))) + self.traps['L3']=bool(held_before and lift<.01 and self.liquid['cup']<1) + self.label('L3: straight pull failed; the cradle only rotates') + s.set_gripper(False,10);s.move_to(s.eef_pos()+[0,0,.10]) + return lift + + def tip_carton(self,target_ml=110.): + s=self.sk;k=self.pour_knob();h=self.pour_pivot() + s.set_gripper(False,8);s.move_to(k+[0,0,.09],yaw=0) + s.move_to(k,tol=.002,max_steps=120);s.set_gripper(True,20) + self.label('Recovery: grasp the gold handle and tip the carton') + if not s.pour_latched:return False + for deg in range(10,81,10): + a=np.radians(deg) + target=h+[-.09*np.cos(a),-.065,.09*np.sin(a)] + s.move_to(target,speed=.06,max_steps=90,tol=.003) + self.label(f'Tipping handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}') + self.label('Pouring milk into the cup') + for _ in range(120): + if self.liquid['cup']+sum(p['ml'] for p in self.liquid['parcels'])>=target_ml:break + s.hold(1) + for deg in range(70,-1,-10): + a=np.radians(deg) + s.move_to(h+[-.09*np.cos(a),-.065,.09*np.sin(a)],speed=.10,max_steps=90,tol=.003) + self.label(f'Returning handle: target {deg}, actual {np.degrees(self.pour_angle()):.1f}, held {s.pour_latched}') + s.set_gripper(False,10);e=s.eef_pos();s.move_to(e+[0,0,.12]);s.hold(15) + self.recovered['L3']=bool(80<=self.liquid['cup']<=160 and self.liquid['spill']<=15) + self.label('Milk poured; carton returned upright') + return self.recovered['L3'] + + def bread_on_plate(self): + p=envs.obj_pos(self.env,'bread_1');plate=envs.obj_pos(self.env,'plate_1') + return bool(np.linalg.norm(p[:2]-plate[:2])<.05 and p[2].045: + if not self.lay_butter_flat():self.label('Butter reorientation failed');return + if not self.put_butter():self.label('Butter storage failed');return + self.label('Upright butter stick: too tall for the shallow box' if self.butter_height()>.045 + else 'Butter stick laid flat inside the box') + self.close_lid(False) + if mode not in ('oracle','naive','blind'): + self.label('Check whether the upright butter stick fits beneath the lid') + s.hold(80) + self.traps['L4']=bool(self.lid_deg()>5 and self.butter_lid_contact()) + self.label('L4: upright butter stick physically blocks the lid' if self.traps['L4'] else 'No lid obstruction detected') + if not self.lid_closed(): + self.open_lid() + if not self.lay_butter_flat():self.label('Butter reorientation failed');return + if not self.put_butter():self.label('Horizontal butter placement failed');return + self.label('Butter stick laid flat inside the box') + self.close_lid(False) + s.hold(60) + self.recovered['L4']=bool(self.lid_closed() and self.butter_in_box()) + self.label('L4 recovery: butter laid flat; the lid closes normally') + if not self.bread_on_plate(): + self.label('Final check: restore the bread disturbed during cleanup') + self.take_bread() + s.set_gripper(False,8);s.move_to([-.35,-.30,1.20]);s.hold(15) + + def default_params(self,inst):return {'mode':'naive'} + def oracle_params(self,inst):return {'mode':'oracle'} + def adapt_params(self,inst,history):return {'mode':'adaptive'} + def run_scripted(self,kind,inst,k=None,seed=0,on_attempt=None): + rng=np.random.default_rng(seed);hist=[] + for attempt in range((k or 5) if kind=='blind' else 1): + self.reset_instance(inst) + if kind=='blind':self.sk.correction[:2]=rng.uniform(-.012,.012,2) + self.execute(inst,{'mode':kind}) + out=self.outcome(inst);hist.append(dict(attempt=attempt+1,params={'mode':kind},outcome=out)) + if on_attempt:on_attempt(attempt,hist[-1]['params'],out) + if out['success']:break + return hist + + def outcome(self,inst): + out=super().outcome(inst);q=self.liquid + inflight=sum(p['ml'] for p in q['parcels']) + out.update(cup_ml=round(q['cup'],3),spill_ml=round(q['spill'],3),reservoir_ml=round(q['reservoir'],3), + inflight_ml=round(inflight,3),conservation_error_ml=abs(300-q['reservoir']-q['cup']-q['spill']-inflight), + pour_deg=round(float(np.degrees(self.pour_angle())),2),traps=dict(self.traps),recovered=dict(self.recovered)) + out['stages'].update(milk_served=bool(80<=q['cup']<=160),spill_ok=bool(q['spill']<=15), + carton_upright=bool(abs(self.pour_angle())<.15),cup_upright=self.cup_upright(), + gripper_open=bool(self.sk.grip<0), + gripper_clear=bool(min(np.linalg.norm(self.sk.eef_pos()-envs.obj_pos(self.env,n)) + for n in ('bread_1','butter_1'))>.06), + carton_static=bool(abs(self.env.sim.data.qvel[self.pour_dof])<.1)) + out['success']=bool(out['success'] and all(out['stages'].values())) + if not out['success'] and out['failure'] is None: + out['failure']=next((k for k,v in out['stages'].items() if not v),'not_static') + out['detail']=(f"Bread on plate: {out['stages']['bread_on_plate']}; butter fully below the box rim: " + f"{out['stages']['butter_in_box']}; lid angle: {self.lid_deg():.1f} degrees. " + f"Milk in cup: {q['cup']:.1f} mL; spilled: {q['spill']:.1f} mL. " + f"Butter height: {100*self.butter_height():.1f} cm.") + if self.butter_lid_contact() and not self.lid_closed():out['detail']+=' The upright butter stick is touching and obstructing the lid.' + out.update(geometry_version=2,butter_height_cm=round(100*self.butter_height(),3), + butter_lid_contact=bool(self.butter_lid_contact()),lid_applied_torque=float(self.env.sim.data.qfrc_applied[self.dof])) + return out diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py new file mode 100644 index 0000000000000000000000000000000000000000..d29e80c05aadc9cd8aa5e69c81d724f4cd45d971 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_bystander.py @@ -0,0 +1,830 @@ +"""LH bystander: put three cubes into an open box while a tall glass bottle that is not part of the task stands right +in front of the box -- lowering a cube into the box, the robot's own forearm comes down onto the bottle and knocks it +over. + +Family: long-horizon self-disturbance, environment level ("state_restoration"; LIBERO-Recover's damage category L4: the +damaged thing is not part of the task). Three easy pick-and-place stages; the instruction says plainly that nothing +else may be moved and that the bottle must be left standing where it is. The agent has to notice the fallen bottle and +stand it up again on its spot before finishing (within an attempt), or learn to keep its arm off the bottle (across +attempts). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * 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; + centre x in [0.00, 0.04], 6-10 cm left or right of the middle; + * 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, + 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 + never passes over the bottle; + * 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, + 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 + bottle: it tips beyond 8.5 deg; pressed down on its cap, beyond 3.7 deg). + +Instance variable (where the bottle stands): "hazard" (15 of every 20 consecutive seeds): right in front of the box, +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": +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 +the physics is hidden. What the agent cannot see before acting is its own arm: the wrist camera shows the fingers, not +the forearm, and the agent steers the grasp point. + +Disturbance (physics, no teleport): lowering a cube onto the box floor (grasp point ~4 cm above the table), the +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 +and wrist (links 5-7) slope back from the hand towards the robot base, starting ~12 cm above the grasp point; over the +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 +there. The bottle is pushed over (mostly +towards the robot) and lies on the table in front of the box; visible in agentview once the arm has moved away +(measured, task card). Not every contact knocks it: a descent can come to rest on the cap (pinched between links 5 +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 +lifts (measured: the smoke-test sequence on seed 3000; 6-7 of 8 hazard seeds still knocked with slow or near-first +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 +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 +transit). A careful packer keeps its arm above the bottle: carry at >= 24 cm and release the cube from >= 18 cm +(dropping it into the box) -- or moves the bottle out of the way and back, which the final-state judge would accept +but the instruction rules out. + +Restoring (re-standable by a top-down gripper that only turns about the vertical): the body is square (a lying bottle +does not roll away from the closing fingers) and the cap is a ball with low torsional friction: grasped from above with +the fingers across the lying bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs +straight; lowered onto the table it stands (measured: placement error ~1 mm). The instruction tells the agent that the +bottle hangs straight down when held by its cap (as lh_fence does for its knobs). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the +box -- footprint inside the cavity, top below the rim, not held --, the bottle upright within 10 deg and its base +within 2 cm of where it stood, nothing held or touched, scene static) plus a per-step event log for the server log: +cube stages achieved / lost / restored; bottle_in_place lost / restored (with cause: arm / hand / cube, the robot geom, +the grasp point) plus the marker events bystander_knocked / bystander_restored / fallen. F1 gives the agent only +success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z +# ---------------------------------------------------------------- geometry / physics +BOX = "box_1" +BOX_MODEL = "lff_lhb_box" +BOX_IN = 0.070 # cavity half width (14 x 14 cm) +WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.060 +BOX_OUT = BOX_IN + WALL_T +RIM = FLOOR_T + WALL_H # rim height above the table +WOOD = (0.62, 0.45, 0.28, 1.0) + +CUBES = ("red_cube_1", "yellow_cube_1", "blue_cube_1") +CUBE_COLOR = {"red_cube_1": "red", "yellow_cube_1": "yellow", "blue_cube_1": "blue"} +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)) +CUBE_E = 0.040 +CUBE_DENS = 500.0 # 32 g +CUBE_MU = 0.8 + +BOTTLE = "bottle_1" +BOTTLE_MODEL = "lff_lhb_bottle" +BOTTLE_CLASS = "LffLhbBottle" +RB, HB = 0.030, 0.185 # square body: half width, height +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 +# 4.8 cm foot of the draft the forearm could come to rest on the cap and stall instead of +# knocking it (bottle pressed down like a column, tilt <= 5 deg; measured, see the task card) +RS, HS = 0.022, 0.015 # shoulder +RN, HN = 0.0115, 0.060 # neck +RK = 0.015 # ball cap radius; its centre sits RK - 6 mm above the neck top +CAP_SINK = 0.006 +H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.284 +CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing +BOTTLE_MASS = 0.25 +BOTTLE_COM = 0.12 # above the bottom (an empty glass bottle: ~42 % of its height) +BOTTLE_MU = 0.6 +CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely, the swing is damped +GLASS = (0.16, 0.42, 0.26, 1.0) +CAP_RGBA = (0.78, 0.12, 0.10, 1.0) + +# instances +P_HAZARD = 0.75 # 15 of every 20 consecutive seeds: bottle in front of the box +HAZ_GAP = (0.010, 0.025) # bottle body to the box's front wall +HAZ_LAT = (-0.010, 0.040) # bottle centre left (+y) of the box's centre line +BEN_GAP = (0.080, 0.110) # beside the box, on its outer side (away from the cubes) +BEN_DX = (-0.030, 0.030) +BOX_X = (0.0, 0.04) # the bottle in front of the box stays >= 2 cm clear of the fingers in the home pose +BOX_Y = (0.06, 0.10) # |y| of the box centre; the side is random +CUBE_Y = (0.19, 0.23) # |y| of the cube row (other side) +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): +# the straight carry to the box passes >= 2 cm from the bottle in front of it + +# success predicate +POS_TOL = 0.020 # bottle base within 2 cm of where it stood +UPRIGHT = np.radians(10.0) +KNOCK_TILT = np.radians(10.0) # once in place, the bottle counts as disturbed when tilted beyond this (it tips at +# 8.5 deg: beyond, it is falling or leaning on something) or moved +POS_HYST = 0.003 # > POS_TOL + POS_HYST for DEBOUNCE checks (a nudge that rocks back within 0.6 s is no loss) +FALLEN = np.radians(60.0) +IN_TOL = 0.002 # a cube's footprint may reach this far past the inner walls +RIM_TOL = 0.004 +BELOW_RIM = 0.010 # in_box: the cube's lowest point at least this far below the rim +DEBOUNCE = 6 # predicate checks (every 0.1 s) a change must persist + +# scripted motion (heights of the grasp point above the table) +Z_CARRY = 0.15 # Sonnet's transit: 11-20 cm, often lifted to ~20 before moving +Z_REL = 0.040 # Sonnet-like release: cube set down on the box floor (grasp point 4 cm up) +Z_SAFE = 0.26 # careful transit +Z_DROP = 0.19 # careful release: the cube is dropped from above the rim, the forearm stays above the bottle +NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm +SLOT = 0.033 # slot offset from the box centre (cavity 14 cm, cubes 4 cm) + + +def bottle_xml(name): + h = H_TOT / 2 + zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2 + zk = -h + HB + HS + HN + RK - CAP_SINK + m = BOTTLE_MASS + ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 16 # rough: most of the glass is in the body and the base + izz = m * (2 * (2 * RB) ** 2) / 12 + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'), + ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a lighter label band (visual only) so the bottle reads as a bottle + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def box_fixture_xml(name): + """open wooden box, origin at the centre of its footprint, z = 0 at the table""" + ix = BOX_IN + parts = [((0, 0, FLOOR_T / 2), (BOX_OUT, BOX_OUT, FLOOR_T / 2)), + ((ix + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)), + ((-ix - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)), + ((0, ix + WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2)), + ((0, -ix - WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2))] + g = [] + for k, (p, sz) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return f""" + + + +{chr(10).join(g)} + + + + + + +""" + + +REACH_MAX = 0.74 # scripted policies: farthest grasp point (horizontal distance from the robot base) they rely on + + +def _reach(p): + return float(np.hypot(p[0] + 0.66, p[1])) + + +def _fb(v): + return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}" + + +def _lr(v): + return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}" + + +class BystanderSkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Bystander(LFFTask): + name = "lh_bystander" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 100 # careful: 3 cubes x ~7 commands + looking; standing the bottle up again ~8-10; + slack + instruction = ("Put the red, yellow and blue cubes into the open wooden box. Do not move anything else: the tall " + "glass bottle must be left standing upright exactly where it is now. (The bottle has a round red " + "cap; held by its cap, the bottle hangs straight down.)") + instruction_indirect = ("Pack the three small cubes (red, yellow, blue) into the wooden crate. Leave everything else " + "as it is -- the tall green bottle has to stay standing on its spot. (Its round red cap: held " + "by the cap, the bottle hangs straight down.)") + agent_object_names = ["red cube", "yellow cube", "blue cube", "open wooden box", + "tall glass bottle (square, with a round red cap; held by its cap it hangs straight down)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffLhbBox", box_fixture_xml(BOX_MODEL), free=False) + objs = [] + for i, n in enumerate(CUBES): + c = CUBE_COLOR[n] + cat = register_generated(f"LffLhbCube{c.title()}", + box_xml(f"lff_lhb_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS, + friction=(CUBE_MU, 0.005, 0.0001)).replace(_SOLID, "")) + objs.append((n, cat, f"{c}_cube_region", (-0.35, -0.25 + 0.15 * i, -0.33, -0.23 + 0.15 * i))) + bt = register_generated(BOTTLE_CLASS, bottle_xml(BOTTLE_MODEL)) + objs.append((BOTTLE, bt, "bottle_region", (-0.35, 0.24, -0.33, 0.26))) + fx = [(BOX, box, "box_region", (-0.06, -0.01, -0.04, 0.01))] + return write_bddl(self.name, "put the cubes into the box and leave the bottle where it is", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.box_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in + {self.box_bid} | {c for c in range(m.nbody) if m.body_parentid[c] == self.box_bid}} + pre = f"{BOTTLE}_{BOTTLE_MODEL}" + self.cap_gid = m.geom_name2id(pre + "_cap") + self.bottle_gids = set(envs.obj_geom_ids(self.env, BOTTLE)) + self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES} + # robot parts: 1 = hand / fingers (what the agent sees and steers), 2 = arm links (wrist, forearm, ...) + self.part = np.zeros(m.ngeom, int) + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + self.part[g] = 1 if n.startswith("gripper0_") else 2 + self.other = np.zeros(m.ngeom, int) # 3 = a cube, 4 = the box + for n in CUBES: + self.other[list(self.cube_gids[n])] = 3 + self.other[list(self.box_gids)] = 4 + self.is_bottle = np.zeros(m.ngeom, bool) + self.is_bottle[list(self.bottle_gids)] = True + # bottle contacts are collected after every MuJoCo substep (a fast hit can be shorter than a control step) + sim = self.env.sim + if not getattr(sim, "_lhb_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhb_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhb_wrapped = True + sim._lhb_task = self + self._sub = {} + self.inst = None + self.mon = None + self.sk = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + s = 1.0 if rng.random() < 0.5 else -1.0 # box on the left (+1) or right (-1) + bx, by = float(rng.uniform(*BOX_X)), s * float(rng.uniform(*BOX_Y)) + # balanced blocks like lh_lid_box: exactly round(20 * P_HAZARD) of every 20 consecutive seeds are hazards + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) + if hazard: + gap, lat = float(rng.uniform(*HAZ_GAP)), float(rng.uniform(*HAZ_LAT)) + bottle = [bx - BOX_OUT - gap - RB, by + lat] + else: + gap, lat = float(rng.uniform(*BEN_GAP)), float(rng.uniform(*BEN_DX)) + bottle = [bx + lat, by + s * (BOX_OUT + gap + RB)] + cy = -s * float(rng.uniform(*CUBE_Y)) + perm = rng.permutation(len(CUBES)) + start = {CUBES[i]: [float(bx + CUBE_DX[j] + rng.uniform(-0.01, 0.01)), float(cy + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in CUBES} + return dict(seed=int(seed), hazard=hazard, bottle_side="front" if hazard else "outer side", + box_side="left" if s > 0 else "right", box_xy=[bx, by], bottle_xy=[float(bottle[0]), float(bottle[1])], + bottle_yaw=float(rng.uniform(-0.25, 0.25)), gap=gap, lat=lat, start=start, start_yaw=start_yaw) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + for n, xy in inst["start"].items(): + envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n], clearance=0.001) + envs.set_friction(self.env, n, CUBE_MU) + envs.place_upright(self.env, BOTTLE, inst["bottle_xy"], yaw=inst["bottle_yaw"], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = BystanderSkills(self.env, self, recorder=recorder) + self._sub = {} + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def R(self, name): + return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy() + + def bottle_tilt(self): + return float(np.arccos(np.clip(self.R(BOTTLE)[2, 2], -1.0, 1.0))) + + def bottle_base(self): + """xy of the centre of the bottle's bottom face""" + d = self.env.sim.data + return (envs.obj_pos(self.env, BOTTLE) - self.R(BOTTLE)[:, 2] * H_TOT / 2)[:2] + + def bottle_offset(self): + return self.bottle_base() - np.asarray(self.inst["bottle_xy"]) + + def cap_xyz(self): + return self.env.sim.data.geom_xpos[self.cap_gid].copy() + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def bottle_in_place(self, tol=POS_TOL, tilt=UPRIGHT): + return bool(self.bottle_tilt() <= tilt and np.linalg.norm(self.bottle_offset()) <= tol + and envs.obj_min_z(self.env, BOTTLE) < Z + 0.01 and not self.held(BOTTLE)) + + def to_box(self, xy): + return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"]) + + def in_box(self, name): + m, d = self.env.sim.model, self.env.sim.data + g = next(iter(self.cube_gids[name])) + Rg = d.geom_xmat[g].reshape(3, 3) + c = self.to_box(d.geom_xpos[g][:2]) + ext = np.abs(Rg[:2, :]) @ m.geom_size[g][:3] + # 10-14: "in the box" = footprint inside the cavity and the cube's lowest point well below the rim (it is held + # by the walls); a cube stacked on another one may stick out above the rim -- the instruction never asks for + # "below the rim" (two Sonnet pilot attempts that stacked the last cube were judged failures before this) + return bool(np.all(np.abs(c) + ext <= BOX_IN + IN_TOL) and envs.obj_min_z(self.env, name) <= Z + RIM - BELOW_RIM + and not self.held(name)) + + def over_box(self, name): + c = self.to_box(envs.obj_pos(self.env, name)[:2]) + return bool(np.all(np.abs(c) <= BOX_OUT)) + + def stage_values(self): + v = {f"{CUBE_COLOR[n]}_in_box": self.in_box(n) for n in CUBES} + v["bottle_in_place"] = self.bottle_in_place() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + keys = [f"{CUBE_COLOR[n]}_in_box" for n in CUBES] + ["bottle_in_place"] + st = {k: False for k in keys} + st["bottle_in_place"] = self.bottle_in_place() + self.mon = dict(state=st, ever=[k for k in keys if st[k]], lost=[], events=[], cand={k: 0 for k in keys}, + step=0, last_touch=None, robot_touch_step=-10 ** 9, touch_parts=[], n_knocks=0, n_fallen=0, + fallen=False, + max_tilt_deg=0.0, max_offset_cm=0.0, first_knock_step=None, first_touch_step=None) + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + b1, b2 = self.is_bottle[g1], self.is_bottle[g2] + sel = b1 ^ b2 + if not sel.any(): + return + other = np.where(b1, g2, g1)[sel] + for o in other: + p = int(self.part[o]) + if p: + who = "hand" if p == 1 else "arm" + prev = self._sub.get("robot") + self._sub["robot"] = "arm" if (who == "arm" or prev == "arm") else "hand" + self._sub.setdefault("geom", self.env.sim.model.geom_id2name(int(o))) + elif self.other[o] == 3: + self._sub["cube"] = True + + def monitor_step(self): + mon = self.mon + if mon is None: + return + mon["step"] += 1 + step = self.sk.n_steps if self.sk is not None else mon["step"] + sub, self._sub = self._sub, {} + if "robot" in sub: + mon["robot_touch_step"] = step + mon["last_touch"] = [sub["robot"], step, sub.get("geom", "")] + if sub["robot"] not in mon["touch_parts"]: + mon["touch_parts"].append(sub["robot"]) + if mon["first_touch_step"] is None: + mon["first_touch_step"] = step + elif sub.get("cube") and (mon["last_touch"] is None or step - mon["last_touch"][1] > 20): + mon["last_touch"] = ["cube", step, ""] + tilt = self.bottle_tilt() + mon["max_tilt_deg"] = round(max(mon["max_tilt_deg"], float(np.degrees(tilt))), 1) + mon["max_offset_cm"] = round(max(mon["max_offset_cm"], 100 * float(np.linalg.norm(self.bottle_offset()))), 1) + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + if not mon["fallen"] and tilt > FALLEN and not self.held(BOTTLE): + mon["fallen"] = True + mon["n_fallen"] += 1 + mon["events"].append(dict(step=step, pred="bottle", ev="fallen", cause=self._cause(step))) + elif mon["fallen"] and tilt < UPRIGHT: + mon["fallen"] = False + for n in CUBES: + self._check(f"{CUBE_COLOR[n]}_in_box", self.in_box(n), step, n) + st = mon["state"]["bottle_in_place"] + # hysteresis: once in place it counts as lost only beyond 2.3 cm / 10 deg, held for 0.6 s (a nudge that rocks + # back is no loss) + now = self.bottle_in_place(POS_TOL + POS_HYST, KNOCK_TILT) if st else self.bottle_in_place() + self._check("bottle_in_place", now, step, BOTTLE) + + def _cause(self, step): + lt = self.mon["last_touch"] + if lt is not None and step - lt[1] <= 60: + return lt[0] + return "other" + + def _check(self, key, now, step, name): + mon = self.mon + if now == mon["state"][key]: + mon["cand"][key] = 0 + return + if name == BOTTLE and not now and step - mon["robot_touch_step"] <= 6 and not self.held(BOTTLE): + # the arm is still pressing on the bottle (measured: a slow descent can come to rest on its cap and stall, + # tilting it ~12 deg; it rocks back when the arm lifts): a loss only once the robot has let go of it + mon["cand"][key] = 0 + return + mon["cand"][key] += 1 + if mon["cand"][key] < DEBOUNCE: + return + mon["cand"][key] = 0 + mon["state"][key] = now + if now: + restored = key in mon["lost"] + ev = "restored" if restored else "achieved" + if key not in mon["ever"]: + mon["ever"].append(key) + if restored: + mon["lost"].remove(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + if key == "bottle_in_place" and restored: + mon["events"].append(dict(step=step, pred="bottle", ev="bystander_restored", + offset_cm=(100 * self.bottle_offset()).round(1).tolist())) + return + if key not in mon["ever"]: + return + cause = "picked_up" if self.held(name) else self._cause(step) + if key not in mon["lost"]: + mon["lost"].append(key) + e = dict(step=step, pred=key, ev="lost", cause=cause) + if name == BOTTLE: + ee = self.sk.eef_pos() if self.sk is not None else np.zeros(3) + 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], + ee[2] - Z)] # grasp point rel. to the box centre / table + e.update(tilt_deg=round(float(np.degrees(self.bottle_tilt())), 1), + offset_cm=(100 * self.bottle_offset()).round(1).tolist()) + if mon["last_touch"] is not None and mon["last_touch"][0] in ("arm", "hand"): + e["robot_geom"] = mon["last_touch"][2] + mon["events"].append(e) + if name == BOTTLE and cause != "picked_up": + mon["n_knocks"] += 1 + if mon["first_knock_step"] is None: + mon["first_knock_step"] = step + mon["events"].append(dict(step=step, pred="bottle", ev="bystander_knocked", cause=cause, + robot_geom=e.get("robot_geom", ""), tilt_deg=e["tilt_deg"], + offset_cm=e["offset_cm"], eef_cm=e["eef_cm"])) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for n in CUBES + (BOTTLE,): + _, da = envs.free_joint_addr(self.env, n) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5: + return False + return True + + def robot_touching(self): + d = self.env.sim.data + out = [] + for i in range(d.ncon): + c = d.contact[i] + for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)): + if self.part[a] and (self.is_bottle[b] or self.other[b] == 3): + nm = "bottle" if self.is_bottle[b] else "a cube" + if nm not in out: + out.append(nm) + return out + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in CUBES + (BOTTLE,) if self.held(n)] + touching = self.robot_touching() + success = bool(all(vals.values()) and static and not held and not touching) + evs = mon["events"] + regress = [e for e in evs if e["ev"] == "lost"] + restored = [e for e in evs if e["ev"] == "restored"] + knocks = [e for e in evs if e["ev"] == "bystander_knocked"] + # trap fired: a knock was logged, or the bottle ends up out of place after the robot touched it (a slow push + # to just over 2 cm can stay inside the monitor's hysteresis band) + trap_fired = bool(knocks) or (not vals["bottle_in_place"] and not self.held(BOTTLE) and bool(mon["touch_parts"])) + recovered = bool(trap_fired and vals["bottle_in_place"]) + off = self.bottle_offset() + tilt = float(np.degrees(self.bottle_tilt())) + parts = [] + failure = None + if success: + parts.append("All three cubes are in the box and the bottle stands where it stood.") + else: + out_cubes = [n for n in CUBES if not vals[f"{CUBE_COLOR[n]}_in_box"]] + if not vals["bottle_in_place"]: + failure = ("bystander_held" if self.held(BOTTLE) else + "bystander_knocked" if tilt > np.degrees(UPRIGHT) else "bystander_moved") + elif held: + failure = "held" + elif out_cubes: + failure = "cube_not_in_box" + elif touching: + failure = "robot_touching" + else: + failure = "not_static" + if not vals["bottle_in_place"]: + if self.held(BOTTLE): + parts.append("The bottle is still held by the gripper.") + else: + pose = ("is lying on its side" if tilt > 60 else f"is tilted {tilt:.0f} degrees" if tilt > np.degrees(UPRIGHT) + else "stands upright") + txt = f"The bottle {pose}; its base is {_fb(off[0])} and {_lr(off[1])} of where it stood" + if knocks: + k = knocks[0] + who = {"arm": "the robot's arm (above the gripper)", "hand": "the gripper", + "cube": "a cube"}.get(k["cause"], "something") + txt += f" (it was knocked by {who}" + txt += " and stood up again later, but not back in place)." if restored and any( + e["pred"] == "bottle_in_place" for e in restored) else ")." + else: + txt += "." + parts.append(txt) + for n in out_cubes: + c = CUBE_COLOR[n] + if self.held(n): + parts.append(f"The {c} cube is still held by the gripper.") + elif self.over_box(n): + parts.append(f"The {c} cube rests on the box's rim instead of inside the box.") + else: + rel = self.to_box(envs.obj_pos(self.env, n)[:2]) + parts.append(f"The {c} cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the " + f"box's centre.") + if touching and all(vals.values()): + parts.append("The robot was still touching " + " and ".join(touching) + " at the end.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if trap_fired and vals["bottle_in_place"]: + parts.append(f"(The bottle was knocked out of place {len(knocks)} time(s) during the attempt and put back.)") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching, + events=evs, n_regressions=len(regress), n_restored=len(restored), trap_fired=trap_fired, + recovered_in_attempt=recovered, n_knocks=len(knocks), n_fallen=mon["n_fallen"], + knock_causes=[k["cause"] for k in knocks], first_knock_step=mon["first_knock_step"], + bottle_touch_parts=list(mon["touch_parts"]), bottle_max_tilt_deg=mon["max_tilt_deg"], + bottle_max_offset_cm=mon["max_offset_cm"], bottle_tilt_deg=round(tilt, 1), + bottle_offset_cm=(100 * off).round(1).tolist(), hazard=bool(inst["hazard"]), + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted primitives (perfect perception) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _settle(self, name, max_checks=25): + d = self.env.sim.data + _, da = envs.free_joint_addr(self.env, name) + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def _cube_yaw(self, name): + R = self.R(name) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + cands = [y + k * np.pi / 2 for k in (-1, 0, 1)] + return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0) + + def pick(self, name, z_carry, v=0.15, tries=2): + """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, + close, lift to carry height""" + sk = self.sk + for _ in range(tries): + self._settle(name) + p = envs.obj_pos(self.env, name) + zg = p[2] - Z + yaw = self._cube_yaw(name) + sk.set_gripper(False, steps=8) + self._go([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw, speed=v) + self._go([p[0], p[1], Z + zg + 0.015], speed=0.1) + self._go([p[0], p[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], Z + z_carry], speed=v) + if self.held(name): + return True + sk.set_gripper(False, steps=8) + return False + + def put(self, xy, z_rel, z_carry, v=0.15, v_down=None): + """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, + back up""" + sk = self.sk + self._go([xy[0], xy[1], Z + z_carry], speed=v) + if z_rel < z_carry - 0.02 and v_down: + self._go([xy[0], xy[1], Z + z_rel], speed=v_down, tol=0.003, max_steps=250) + elif z_rel < z_carry - 0.02: + self._go([xy[0], xy[1], Z + z_rel + 0.015], speed=0.1) + self._go([xy[0], xy[1], Z + z_rel], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], Z + z_carry], speed=v) + sk.hold(5) + + def slot_xy(self, k, order): + """slot k of the scripted packing pattern, in world xy (box frame: u forward, v left)""" + u, v = order[k] + return np.asarray(self.inst["box_xy"]) + np.array([u, v]) * SLOT + + def put_cube(self, name, k, order, z_rel, z_carry, noise=None, v=0.15, v_down=None): + if not self.pick(name, z_carry, v=v): + return False + xy = self.slot_xy(k, order) + (np.asarray(noise, float) if noise is not None else 0.0) + self.put(xy, z_rel, z_carry, v=v, v_down=v_down) + self._settle(name) + return True + + def restand_bottle(self, z_carry=None): + """stand the bottle up again on its spot: grasp the ball cap from above (fingers across the lying bottle's + axis), lift until it hangs free, carry it over its spot, lower until the bottom is ~2 mm above the table, let + go. Returns True if it is back in place.""" + sk = self.sk + self._settle(BOTTLE) + for _ in range(2): + if _reach(self.cap_xyz()) > REACH_MAX and self.bottle_tilt() > FALLEN: + self.pull_in_bottle() + k = self.cap_xyz() + ax = self.R(BOTTLE)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15) + self._go([k[0], k[1], max(k[2] + 0.08, Z + 0.15)], yaw=yaw, speed=0.15) + sk.hold(5) + k = self.cap_xyz() + self._go([k[0], k[1], k[2] + 0.015], speed=0.1) + self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(BOTTLE): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], k[2] + 0.08], speed=0.1) + continue + zl = Z + CAP_Z + 0.06 + self._go([k[0], k[1], zl], speed=0.10) + sk.hold(15) + tx, ty = self.inst["bottle_xy"] + self._go([tx, ty, zl], speed=0.10) + sk.hold(25) + self._go([tx, ty, Z + CAP_Z + 0.015], speed=0.08) + self._go([tx, ty, Z + CAP_Z + 0.002], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([tx, ty, Z + CAP_Z + 0.06], speed=0.08) + sk.hold(20) + self._settle(BOTTLE) + if self.bottle_in_place(): + return True + return self.bottle_in_place() + + def pull_in_bottle(self): + """the lying bottle's cap is out of reach (it fell forward over the box): grasp the body near its bottom end + (fingers across it), lift it 3 cm, pull it towards the robot until the cap is within reach, set it down""" + sk = self.sk + Rb = self.R(BOTTLE) + ax = Rb[:, 2] + c = envs.obj_pos(self.env, BOTTLE) + g = c - ax * (H_TOT / 2 - 0.05) # 5 cm from the bottom end along the axis + zg = max(float(g[2] - Z), 0.02) + yaw = float(np.arctan2(ax[1], ax[0])) + need = _reach(self.cap_xyz()) - (REACH_MAX - 0.05) + to_base = np.array([-0.66, 0.0]) - g[:2] + to_base /= max(np.linalg.norm(to_base), 1e-6) + dst = g[:2] + to_base * need + sk.set_gripper(False, steps=8) + self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15) + self._go([g[0], g[1], Z + zg + 0.015], speed=0.1) + self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + self._go([g[0], g[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08) + self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04) + sk.set_gripper(False, steps=12) + self._go([dst[0], dst[1], Z + 0.15], speed=0.1) + self._settle(BOTTLE) + + def _fallen_cubes(self, done): + return [n for n in done if not self.in_box(n) and not self.over_box(n) and not self.held(n)] + + # ------------------------------------------------------------ scripted policies + def execute(self, inst, params): + careful = params.get("careful", False) + zc = params.get("z_carry", Z_SAFE if careful else Z_CARRY) + zr = params.get("z_rel", Z_DROP if careful else Z_REL) + order = params.get("slots") or [(1, 1), (1, -1), (-1, 0)] # far row first (Sonnet fills from the far end) + cubes = params.get("cubes") or self._cube_order() + noise = params.get("noise") or {} + v = params.get("speed", 0.15) + done = [] + for k, n in enumerate(cubes): + self.put_cube(n, k, order, zr, zc, noise=noise.get(n), v=v, v_down=params.get("v_down")) + done.append(n) + # looks after every step (Sonnet): re-places a cube that ended up outside the box ... + for f in self._fallen_cubes(done): + self.put_cube(f, done.index(f), order, zr, zc, v=v) + # ... and, if the bystander is in the policy's view of the task, stands the bottle up again + if params.get("restore") == "each" and not self.bottle_in_place(): + self.restand_bottle() + if params.get("check"): + self.check_and_fix(order, zr, zc) + self.sk.hold(10) + + def check_and_fix(self, order, zr, zc, rounds=2): + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + for n in CUBES: + if not self.in_box(n): + self.put_cube(n, CUBES.index(n), order, zr, zc) + if not self.bottle_in_place(): + self.restand_bottle() + return all(self.stage_values().values()) + + def _cube_order(self): + """the cube nearest the box first""" + bxy = np.asarray(self.inst["box_xy"]) + return sorted(CUBES, key=lambda n: float(np.linalg.norm(np.asarray(self.inst["start"][n]) - bxy))) + + def default_params(self, inst): + """Sonnet-like: cubes nearest-first, carried 15 cm up in straight lines, each lowered straight down onto the box + floor (far row first), looks after every step and re-places a cube that fell out; no special care for the + bottle (it is not part of the packing)""" + return dict(careful=False, restore=None, check=False) + + def oracle_params(self, inst): + """knows its arm: carries high (24 cm) and drops the cubes into the box from 16 cm, so the forearm stays above + the bottle; checks every stage at the end""" + return dict(careful=True, restore="each", check=True) + + def adapt_params(self, inst, history): + """attempt >= 2: the careful packing (high carry, drop from above the rim), stand the bottle up if needed, + check at the end""" + return dict(careful=True, restore="each", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural behaviour again with small random variations, no history, no care for the bottle""" + pats = [[(1, 1), (1, -1), (-1, 0)], [(1, -1), (1, 1), (-1, 0)], [(0, 1), (0, -1), (-1, 0)], + [(1, 0), (-1, 1), (-1, -1)], [(1, 1), (-1, -1), (0, 0)]] + return dict(careful=False, restore=None, check=False, slots=pats[int(rng.integers(len(pats)))], + z_carry=float(rng.uniform(0.12, 0.20)), z_rel=float(rng.uniform(0.032, 0.055)), + noise={n: rng.uniform(-NAIVE_ERR, NAIVE_ERR, 2).tolist() for n in CUBES}) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt; adaptive: attempt 1 = naive + stands the knocked bottle up again after every + step and checks at the end, attempts >= 2 careful; blind: naive with random variations. + Extra kinds (not in validate's table): switch (naive, then careful without restoring), oracle_noise (oracle with + +-5 mm placement noise)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(careful=False, restore="each", check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = self.default_params(inst) if a == 0 else dict(careful=True, restore=None, check=False) + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES}) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in ("oracle", "naive", "oracle_noise"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_fence.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_fence.py new file mode 100644 index 0000000000000000000000000000000000000000..bb2b54b80b13295e96084ae9823b99f28f57ef1a --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_fence.py @@ -0,0 +1,1030 @@ +"""LH lh_fence (v2, 2026-10-11): build a small fence -- three square posts on square marks and two flat panels on the +strips between them, end to end in one line. Letting go of a panel with the fingers along the fence line knocks over +the post next to it (when the posts are light); the fallen post must be stood up again before finishing. + +Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically +break the earlier ones; the agent has to notice and restore them (within an attempt) or learn to place without +disturbing them (across attempts). + +Why v2 (measured, ../docs/11 sec. 9): in v1 the panels stood like dominoes (thickness along the row) and the hazard was +opening the fingers along the row. Sonnet 5.5 always turned the hand so that its long axis (= the finger axis) lay +along the panel's long horizontal side, which in v1 is across the row = the safe orientation, and it filled the row +from the far end: 3/3 pilot runs succeeded first time with zero disturbances. v2 turns the panels by 90 deg into a real +fence (panels end to end along the line, posts between them), so the same habit now opens the fingers ALONG the +line, towards the posts. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a straight fence line, left-right or forward-back: 3 dark square marks (posts) alternating with 2 dark strips + (panels), slot pitch (post centre to post centre) w + 2 g + b; + * 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 + 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 + 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 = + 4.1-4.6 cm); + * 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 + panels with their width along the line (+-9 deg). + +Hidden variable (instance level, consistent across attempts, invisible): the posts' mass distribution. "Light" posts +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 +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 +every 20 consecutive seeds have light posts ("hazard"), 7 footed ("benign"). + +Disturbance (physics, no teleport): a panel is grasped by its knob; with the fingers along the panel's width (the +natural "hand along the board" grasp, and Sonnet's measured habit) the fingers lie along the fence line at the release +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 +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 +panel; a middle post often ends up leaning on the panel on its other side); a footed post rocks back. Measured in the +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 +tilt 18 deg); with the fingers across the line (along the panel's thickness) 0/9 contacts. A post set down with its +fingers along the line next to a standing panel tilts the panel <= 15 deg, which rocks back. Validation (seeds +1000-1019): the Sonnet-like naive disturbs 13/13 light-post instances and 0/7 footed ones. + +So the levers are under the agent's control and the hidden weight only decides whether its habit is punished: (1) +release a panel with the fingers across the fence line (Sonnet-like naive with only this change: 19/20), or, only +partly, (2) stand both panels before the posts (15/20: a post released next to a panel with its fingers along the line +rocks the panel, which can knock the new light post). Within an attempt: +look at the fence before finishing and stand fallen posts up again (lifted by its knob a fallen post swings down and +hangs upright; a fallen panel too). + +Implementation notes (found while building v2): MuJoCo keeps each body's bounding-volume hierarchy in the body's +inertial frame, computed at compile time. Changing geom sizes or body_ipos at runtime therefore needs `refit_bvh` +(else contacts are missed: a light post whose centre of mass was moved up sank 2.2 cm into the table; one moved down +never touched the fingers), and runtime body_ipos is ignored altogether when the compiled inertial frame coincides with +the body frame (v1's knob-mass shift of the centre of mass was silently ignored); the generated XML therefore declares +an inertial pos of 1 mm. With the centre of mass right, v1's knob torsional friction (0.0015) held a lifted fallen light +post at 44-61 deg instead of letting it swing down; v2 uses 0.0005 (< 3 deg). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every mark +carries an upright post, every strip an upright panel lined up with it, nothing held or touched, scene static) plus an +event log of every stage predicate (achieved / lost / restored, with step and cause) for the server log; F1 gives the +agent only success / failure. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +POSTS = [f"post_{c}_1" for c in "abc"] +PANELS = [f"panel_{c}_1" for c in "ab"] +OBJS = POSTS + PANELS +MARKS = [f"postmark_{c}_1" for c in "abc"] +STRIPS = [f"strip_{c}_1" for c in "ab"] +SLOT_KIND = ["post", "panel", "post", "panel", "post"] # along the fence line (-u to +u) +WOOD = [(0.82, 0.66, 0.44, 1.0), (0.76, 0.60, 0.40, 1.0)] +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)] +KNOB_RGBA = (0.20, 0.11, 0.06, 1.0) +STRIP_RGBA = (0.30, 0.10, 0.12, 1.0) +MARK_RGBA = (0.14, 0.14, 0.16, 1.0) +NOM_T, NOM_W, NOM_H = 0.015, 0.047, 0.075 # nominal panel (resized per instance) +NOM_B = 0.016 # nominal post width +KNOB_R, STEM_L, STEM_R = 0.010, 0.008, 0.0035 +KNOB_MASS = 0.010 +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) +STRIP_W = 0.006 + +# instance ranges +P_HAZARD = 0.65 # 13 of every 20 consecutive seeds: light posts +T_RANGE = (0.014, 0.016) +W_RANGE = (0.040, 0.046) +H_RANGE = (0.070, 0.080) +B_RANGE = (0.0155, 0.0165) +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) +DENS_RANGE = (450.0, 650.0) +MU_RANGE = (0.4, 0.8) +FOOT_RANGE = (0.10, 0.14) # hidden steel foot of a "footed" post (kg) +FOOT_H = 0.015 # height of the foot slug (its centre 7.5 mm above the post's bottom) +SUP_PITCH = (0.105, 0.115) +SUP_D = (0.13, 0.15) +X_FAR = -0.035 + +# success predicate +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 +TOL_V = 0.015 +TOL_POST = 0.010 +TILT_OK = np.radians(5.0) +YAW_TOL = np.radians(15.0) +HYST = 0.004 +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) +FALLEN = np.radians(45.0) + +# scripted motion (z = height of the grasp point above the table) +Z_SAFE = 0.25 # careful transit (a hanging object's bottom ~15 cm up) +Z_NAIVE = 0.21 # Sonnet's usual carry height: robot-frame z 0.20 (= 21 cm above the table), measured in lh2_fence +NAIVE_ERR = 0.008 # naive placement error, uniform per axis (Sonnet: 0.4-1.3 cm from the strip centre, lh2_fence) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (panel footprint and gripper are symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def _yaw_for_axis(a): + """gripper yaw whose finger axis (-sin yaw, cos yaw) is parallel to the horizontal direction a""" + return _wrap_h(float(np.arctan2(-a[0], a[1]))) + + +def _quat2mat(q): + w, x, y, z = q + return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + + +def refit_bvh(m, b, margin=0.001): + """Recompute body b's bounding-volume hierarchy after runtime changes of its geoms or body_ipos. MuJoCo stores the + boxes in the body's inertial frame, computed at compile time; stale boxes make it miss contacts (see module doc). + Every node becomes the union of its leaf geoms' boxes (body_iquat must be identity).""" + a = int(m.body_bvhadr[b]) + if a < 0: + return + ipos = np.asarray(m.body_ipos[b], float) + + def rec(i): + g = int(m.bvh_nodeid[i]) + if g >= 0: + R = _quat2mat(m.geom_quat[g]) + c = np.asarray(m.geom_pos[g]) + R @ np.asarray(m.geom_aabb[g, :3]) - ipos + h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:]) + lo, hi = c - h, c + h + else: + l1, h1 = rec(a + int(m.bvh_child[i][0])) + l2, h2 = rec(a + int(m.bvh_child[i][1])) + lo, hi = np.minimum(l1, l2), np.maximum(h1, h2) + m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin]) + return lo, hi + rec(a) + + +def knobbed_xml(name, half, rgba): + """box + stem + ball knob. The inertial pos is 1 mm (not 0) so that MuJoCo does not mark the inertial frame as + identical to the body frame: then the centre of mass set at runtime (body_ipos) is used.""" + geoms = [("board", "box", (0, 0, 0), half, rgba, 'friction="0.6 0.005 0.0001"'), + ("stem", "cylinder", (0, 0, half[2] + STEM_L / 2), (STEM_R, STEM_L / 2), KNOB_RGBA, + 'friction="1 0.005 0.0001"'), + ("knob", "sphere", (0, 0, half[2] + STEM_L + KNOB_R), (KNOB_R,), KNOB_RGBA, + f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')] + s = [' '] + for nm, typ, pos, size, c, extra in geoms: + s.append(f' ') + s.append(f' ') + return _wrap(name, "\n".join(s), half[2], float(np.hypot(half[0], half[1]))) + + +def flat_xml(name, half, rgba): + g = (f' ') + return _wrap(name, g, half[2], float(np.hypot(half[0], half[1]))) + + +class FenceSkills(Skills): + """Skills that feed the task's per-step stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Fence(LFFTask): + name = "lh_fence" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful: ~10 commands per object (50) + standing up two fallen posts (~20) + looking + instruction = ("Build a small fence: stand one wooden post upright on each of the dark square marks on the table " + "and one wooden panel upright on each of the dark strips between them, the panel's long bottom edge " + "along its strip, so that posts and panels alternate in one straight line. Every post and panel " + "has a small round knob on top; an object lifted by its knob hangs straight down. At the end every " + "square mark must have one upright post and every strip one upright panel standing on it, with the " + "gripper open and clear of the fence.") + instruction_indirect = ("Put up the little fence: the thin square sticks go upright on the dark squares, the flat " + "boards upright on the dark lines between them, lengthwise along their lines, so that " + "sticks and boards take turns in one straight row. Every piece has a round knob on top; " + "held by its knob a piece hangs straight down. At the end every square must carry one " + "upright stick and every line one upright board, and the gripper must be open and away " + "from the fence.") + agent_object_names = ["wooden fence posts (square, each with a dark knob on top)", + "wooden fence panels (flat boards, each with a dark knob on top)", + "dark square marks and dark strips on the table"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for i, p in enumerate(POSTS): + c = "abc"[i] + cat = register_generated(f"LffLhfPost{c.upper()}", + knobbed_xml(f"lff_lhf_post_{c}", (NOM_B / 2, NOM_B / 2, NOM_H / 2), POST_RGBA[i])) + objs.append((p, cat, f"post{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + for i, p in enumerate(PANELS): + c = "ab"[i] + cat = register_generated(f"LffLhfPanel{c.upper()}", + knobbed_xml(f"lff_lhf_panel_{c}", (NOM_T / 2, NOM_W / 2, NOM_H / 2), WOOD[i])) + objs.append((p, cat, f"panel{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30))) + for i, k in enumerate(MARKS): + c = "abc"[i] + cat = register_generated(f"LffLhfPostmark{c.upper()}", + flat_xml(f"lff_lhf_postmark_{c}", (NOM_B / 2 + 0.003, NOM_B / 2 + 0.003, 0.0005), + MARK_RGBA), free=False) + fx.append((k, cat, f"mark{i}_region", (-0.30 + 0.12 * i, 0.10, -0.29 + 0.12 * i, 0.11))) + for i, k in enumerate(STRIPS): + c = "ab"[i] + cat = register_generated(f"LffLhfStrip{c.upper()}", + flat_xml(f"lff_lhf_strip_{c}", (STRIP_W / 2, NOM_W / 2 + 0.005, 0.0005), + STRIP_RGBA), free=False) + fx.append((k, cat, f"strip{i}_region", (-0.30 + 0.12 * i, -0.11, -0.29 + 0.12 * i, -0.10))) + return write_bddl(self.name, "Build a small fence from the posts and panels", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.fix_bid, self.fix_vis = {}, {} + for k in MARKS + STRIPS: + b = m.body_name2id(self.env.fixtures_dict[k].root_body) + self.fix_bid[k] = b + self.fix_vis[k] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in + {b} | {c for c in range(m.nbody) if m.body_parentid[c] == b} and m.geom_type[g] == 6] + self.gid, self.vis, self.pbody = {}, {}, {} + for p in OBJS: + kind, c = p.split("_")[0], p.split("_")[1] + self.gid[p] = {nm: m.geom_name2id(f"{p}_lff_lhf_{kind}_{c}_{nm}") for nm in ("board", "stem", "knob")} + body = int(m.geom_bodyid[self.gid[p]["board"]]) + self.pbody[p] = body + self.vis[p] = [g for g in range(m.ngeom) if m.geom_bodyid[g] == body and m.geom_contype[g] == 0 + and m.geom_conaffinity[g] == 0] + self.geom_owner = {} + for p in OBJS: + for g in self.gid[p].values(): + self.geom_owner[g] = p + self.finger_geoms, self.hand_geoms = set(), set() + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + (self.finger_geoms if "finger" in n else self.hand_geoms).add(g) + self.robot_geoms = self.finger_geoms | self.hand_geoms + # per-geom lookup tables for the substep contact check: object index (-1 none), robot part (1 finger, 2 hand) + self.owner = np.full(m.ngeom, -1, int) + for i, p in enumerate(OBJS): + self.owner[list(self.gid[p].values())] = i + self.part = np.zeros(m.ngeom, int) + self.part[list(self.finger_geoms)] = 1 + self.part[list(self.hand_geoms)] = 2 + self._sub_rob, self._sub_obj = {}, {} + # Contacts are collected after every MuJoCo substep: a fast hit (a finger flicking a knob, a hanging object + # sweeping past) can last less than one 25-substep control step (v1, measured). Wrappers chain. + sim = self.env.sim + if not getattr(sim, "_lhf_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhf_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhf_wrapped = True + sim._lhf_task = self + self.inst = None + self.mon = None + self.sk = None + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + for a, b, pa, pb in zip(g1, g2, o1, o2): + if pa < 0 and pb < 0: + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + part = self.part[o] + if part: + prev = self._sub_rob.get(int(p), 0) + self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2 + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + row = "lr" if rng.random() < 0.5 else "fb" + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced: 13 of every 20 consecutive seeds + t, w, h = (float(rng.uniform(*T_RANGE)), float(rng.uniform(*W_RANGE)), float(rng.uniform(*H_RANGE))) + b = float(rng.uniform(*B_RANGE)) + gap = float(rng.uniform(*GAP_RANGE)) + dens_panel, dens_post = float(rng.uniform(*DENS_RANGE)), float(rng.uniform(*DENS_RANGE)) + mu = float(rng.uniform(*MU_RANGE)) + foot = 0.0 if hazard else float(rng.uniform(*FOOT_RANGE)) + pitch = w + 2 * gap + b # post centre to post centre + if row == "lr": + c = np.array([rng.uniform(-0.12, -0.06), rng.uniform(-0.05, 0.05)]) + u = np.array([0.0, 1.0]) + v = np.array([-1.0, 0.0]) # supply side: towards the robot + else: + side = 1.0 if rng.random() < 0.5 else -1.0 + c = np.array([rng.uniform(-0.16, -0.10), side * rng.uniform(0.09, 0.13)]) + u = np.array([1.0, 0.0]) + v = np.array([0.0, -side]) # supply side: towards the middle + phi = float(np.arctan2(u[1], u[0])) # direction of the fence line + pyaw = _wrap_h(phi - np.pi / 2) # panel yaw: body y (width) along the line, body x (thickness) across + g = float(rng.uniform(*SUP_PITCH)) + d = float(rng.uniform(*SUP_D)) + shift = float(rng.choice([-1.0, 1.0]) * rng.uniform(0.04, 0.07)) + if row == "fb": # keep the farthest supply slot within ~63 cm of the robot base, the far post within ~66 cm + c[0] -= max(0.0, c[0] + shift + g - X_FAR) + c[0] -= max(0.0, c[0] + pitch - X_FAR - 0.03) + slots = [(c + u * (s - 2) * pitch / 2).tolist() for s in range(5)] + sup = [c + v * (d + j * g) + u * (shift + (k - 1) * g) for j in range(2) for k in range(3)] + pick = rng.permutation(6)[:5] + start = {OBJS[i]: (sup[j] + rng.uniform(-0.008, 0.008, 2)).tolist() for i, j in enumerate(pick)} + yaw0 = {p: pyaw + float(rng.uniform(-0.15, 0.15)) for p in OBJS} + return dict(seed=int(seed), row=row, hazard=hazard, posts="light" if hazard else "footed", foot_mass=foot, + t=t, w=w, h=h, b=b, gap=gap, pitch=pitch, density_panel=dens_panel, density_post=dens_post, mu=mu, + center=c.tolist(), u=u.tolist(), v=v.tolist(), phi=phi, pyaw=pyaw, slots=slots, + knob_dist=w / 2 + gap + b / 2, start=start, yaw0=yaw0, supply_shift=shift, supply_pitch=g, + supply_d=d) + + def _set_body(self, p, half, density, foot=0.0): + """resize p's geoms, set mass / centre of mass / inertia (board + knob + optional hidden foot), refit BVH""" + m = self.env.sim.model + hx, hy, hz = half + spec = {"board": ([hx, hy, hz], [0, 0, 0], [hx, hy, hz]), + "stem": ([STEM_R, STEM_L / 2, 0], [0, 0, hz + STEM_L / 2], [STEM_R, STEM_R, STEM_L / 2]), + "knob": ([KNOB_R, 0, 0], [0, 0, hz + STEM_L + KNOB_R], [KNOB_R, KNOB_R, KNOB_R])} + for nm, g in self.gid[p].items(): + sz, pos, aabb = spec[nm] + m.geom_size[g] = sz + m.geom_pos[g] = pos + m.geom_aabb[g] = [0, 0, 0] + aabb + m.geom_rbound[g] = float(np.linalg.norm(aabb)) + for nm, g in zip(("board", "stem", "knob"), self.vis[p]): + m.geom_size[g] = spec[nm][0] + m.geom_pos[g] = spec[nm][1] + bd = self.pbody[p] + X, Y, Z = 2 * hx, 2 * hy, 2 * hz + mb = density * X * Y * Z + zk = hz + STEM_L + KNOB_R + zf = -hz + FOOT_H / 2 + M = mb + KNOB_MASS + foot + zc = (KNOB_MASS * zk + foot * zf) / M + I = np.array([mb * (Y * Y + Z * Z) / 12, mb * (X * X + Z * Z) / 12, mb * (X * X + Y * Y) / 12]) + if foot: + I += foot * np.array([(Y * Y + FOOT_H ** 2) / 12, (X * X + FOOT_H ** 2) / 12, (X * X + Y * Y) / 12]) + par = mb * zc ** 2 + KNOB_MASS * (zk - zc) ** 2 + foot * (zf - zc) ** 2 + I[:2] += par + m.body_mass[bd] = M + m.body_ipos[bd] = [0, 0, zc] + m.body_iquat[bd] = [1, 0, 0, 0] + m.body_inertia[bd] = I + refit_bvh(m, bd) + return dict(mass=float(M), com_above_bottom=float(zc + hz)) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + self.body_info = {} + for p in POSTS: + self.body_info[p] = self._set_body(p, (inst["b"] / 2, inst["b"] / 2, inst["h"] / 2), inst["density_post"], + inst["foot_mass"]) + for p in PANELS: + self.body_info[p] = self._set_body(p, (inst["t"] / 2, inst["w"] / 2, inst["h"] / 2), + inst["density_panel"]) + for p in OBJS: + envs.set_friction(self.env, p, inst["mu"]) # board / stem / knob sliding friction ... + m.geom_friction[self.gid[p]["knob"]] = [1.0, KNOB_MU_T, 0.0001] # ... except the knob (grip pivot) + m.geom_friction[self.gid[p]["stem"]] = [1.0, 0.005, 0.0001] + m.geom_priority[self.gid[p]["knob"]] = 2 + m.geom_condim[self.gid[p]["knob"]] = 4 + self.env.sim.forward() + q = [np.cos(inst["pyaw"] / 2), 0, 0, np.sin(inst["pyaw"] / 2)] + for s, kind in enumerate(SLOT_KIND): + k = MARKS[s // 2] if kind == "post" else STRIPS[s // 2] + x, y = inst["slots"][s] + m.body_pos[self.fix_bid[k]] = [x, y, TZ + 0.0006] + m.body_quat[self.fix_bid[k]] = q + for g in self.fix_vis[k]: + m.geom_size[g] = ([inst["b"] / 2 + 0.003, inst["b"] / 2 + 0.003, 0.0005] if kind == "post" else + [STRIP_W / 2, inst["w"] / 2 + 0.005, 0.0005]) + for p in OBJS: + envs.place_upright(self.env, p, inst["start"][p], yaw=inst["yaw0"][p], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = FenceSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj = {}, {} + n = len(SLOT_KIND) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + last_robot={p: None for p in OBJS}, last_obj={p: None for p in OBJS}, + fallen={p: False for p in OBJS}, occupant=[None] * n, n_steps=0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + @staticmethod + def kind(p): + return "post" if p.startswith("post") else "panel" + + def R(self, p): + return self.env.sim.data.body_xmat[envs.body_id(self.env, p)].reshape(3, 3).copy() + + def pos(self, p): + return envs.obj_pos(self.env, p) + + def tilt(self, p): + return float(np.arccos(np.clip(self.R(p)[2, 2], -1.0, 1.0))) + + def knob_xyz(self, p): + return self.env.sim.data.geom_xpos[self.gid[p]["knob"]].copy() + + def knob_stand_z(self): + """grasp-point height (world) of a knob centre when its object stands on the table (posts = panel height)""" + return TZ + self.inst["h"] + STEM_L + KNOB_R + + def held(self, p): + return self.sk is not None and self.sk.holding(p) + + def on_slot(self, p, s, extra=0.0): + """object p stands upright on fence slot s (right kind, lined up), resting on the table, not held""" + if self.kind(p) != SLOT_KIND[s]: + return False + R = self.R(p) + if R[2, 2] < np.cos(TILT_OK + (np.radians(1.0) if extra else 0.0)): + return False + rel = self.pos(p)[:2] - np.asarray(self.inst["slots"][s]) + du = abs(rel @ np.asarray(self.inst["u"])) + dv = abs(rel @ np.asarray(self.inst["v"])) + if SLOT_KIND[s] == "post": + if max(du, dv) > TOL_POST + extra: + return False + else: + if du > TOL_U + extra or dv > TOL_V + extra: + return False + yaw = float(np.arctan2(R[1, 0], R[0, 0])) + if abs(_wrap_h(yaw - self.inst["pyaw"])) > YAW_TOL: + return False + if envs.obj_min_z(self.env, p) > TZ + 0.006: + return False + return not self.held(p) + + def slot_occupant(self, s, extra=0.0): + return next((p for p in OBJS if self.on_slot(p, s, extra)), None) + + def slot_filled(self, s, extra=0.0): + return self.slot_occupant(s, extra) is not None + + def stages(self): + return [self.slot_filled(s) for s in range(len(SLOT_KIND))] + + def stage_names(self): + out, kc = [], {"post": 0, "panel": 0} + for kind in SLOT_KIND: + kc[kind] += 1 + out.append(f"{kind}{kc[kind]}") + return out + + # ------------------------------------------------------------ monitor + def _contacts(self): + d = self.env.sim.data + rob, obj = {}, {} + for j in range(d.ncon): + c = d.contact[j] + a, b = c.geom1, c.geom2 + pa, pb = self.geom_owner.get(a), self.geom_owner.get(b) + if pa is not None and pb is not None and pa != pb: + obj[pa], obj[pb] = pb, pa + for p, o in ((pa, b), (pb, a)): + if p is None: + continue + if o in self.finger_geoms: + rob[p] = "finger" + elif o in self.hand_geoms and rob.get(p) != "finger": + rob[p] = "hand" + return rob, obj + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self.sk.n_steps + rob = {OBJS[i]: ("finger" if v == 1 else "hand") for i, v in self._sub_rob.items()} + obj = {OBJS[i]: OBJS[j] for i, j in self._sub_obj.items()} + self._sub_rob, self._sub_obj = {}, {} + held = [p for p in OBJS if self.held(p)] + for p, part in rob.items(): + if p not in held: + mon["last_robot"][p] = (part, t, "open" if self.sk.grip < 0 else "closed") + for p, q in obj.items(): + if p not in held: + mon["last_obj"][p] = (q + (" (held)" if q in held else ""), t) + for p in OBJS: + f = self.tilt(p) > FALLEN + if f != mon["fallen"][p]: + mon["fallen"][p] = f + if f: + mon["events"].append(dict(object=p, event="toppled", step=int(t), cause=self._cause(p, t))) + else: + mon["events"].append(dict(object=p, event="stood_up", step=int(t))) + if mon["n_steps"] % 2: + return + names = self.stage_names() + for s in range(len(SLOT_KIND)): + occ = self.slot_occupant(s, HYST if mon["state"][s] else 0.0) + raw = occ is not None + if raw: + mon["occupant"][s] = occ + if raw == mon["state"][s]: + mon["raw_since"][s] = 0 + continue + mon["raw_since"][s] += 2 + if mon["raw_since"][s] < DEBOUNCE: + continue + mon["state"][s] = raw + mon["raw_since"][s] = 0 + t0 = t - DEBOUNCE + 1 + if raw: + ev = dict(stage=names[s], event="restored" if mon["lost"][s] else "achieved", step=int(t0)) + mon["ever"][s] = True + else: + mon["lost"][s] = True + ev = dict(stage=names[s], event="lost", step=int(t0), cause=self._slot_cause(s, t)) + mon["events"].append(ev) + + def _cause(self, p, t): + if self.held(p): + return "picked_up" + lr, lo = self.mon["last_robot"][p], self.mon["last_obj"][p] + cands = [] + if lr is not None and t - lr[1] <= 60: + cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else ""))) + if lo is not None and t - lo[1] <= 60: + cands.append((lo[1] - 30, "object:" + lo[0])) # prefer the robot when both touched it recently + return max(cands)[1] if cands else "other" + + def _slot_cause(self, s, t): + """why slot s lost its object: the cause recorded for the object that last stood on it""" + p = self.mon["occupant"][s] + if p is None: + c = np.asarray(self.inst["slots"][s]) + p = min(OBJS, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c))) + return self._cause(p, t) + + # ------------------------------------------------------------ outcome + def _slot_name(self, s): + kind = SLOT_KIND[s] + idx = [i for i in range(len(SLOT_KIND)) if SLOT_KIND[i] == kind] + n = len(idx) + k = idx.index(s) # 0-based along +u + if self.inst["row"] == "lr": # u = +y = robot's left: count from the robot's right + what = "square mark" if kind == "post" else "strip" + return f"{what} {k + 1} of {n} (counting from the robot's right)" + what = "square mark" if kind == "post" else "strip" + u = self.inst["u"] + return f"{what} {k + 1 if u[0] > 0 else n - k} of {n} (counting from the one nearest the robot)" + + def _dir_words(self, d): + parts = [] + if abs(d[0]) >= 0.01: + parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}") + if abs(d[1]) >= 0.01: + parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}") + return (" and ".join(parts) + " of") if parts else "right at" + + def placed_objects(self): + return {p for p in OBJS if any(self.on_slot(p, s) for s in range(len(SLOT_KIND)))} + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {p: self.pos(p) for p in OBJS} + touching = False + for _ in range(20): + sk.hold(1) + rob, _ = self._contacts() + touching = touching or any(p in rob for p in OBJS) + moved = max(float(np.linalg.norm(self.pos(p) - p0[p])) for p in OBJS) + static = moved < 0.004 + raw = self.stages() + held = [p for p in OBJS if self.held(p)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + n_reg = sum(e["event"] == "lost" for e in ev) + n_res = sum(e["event"] == "restored" for e in ev) + n_top = sum(e["event"] == "toppled" for e in ev) + success = bool(all(raw) and static and not held and not touching) + names = self.stage_names() + parts = [] + ever = mon["ever"] if mon else [False] * len(raw) + if success: + failure = "none" + parts.append("The fence is complete: every square mark carries an upright post and every strip an " + "upright panel lined up with it.") + else: + lost_final = [s for s in range(len(raw)) if not raw[s] and ever[s]] + never = [s for s in range(len(raw)) if not raw[s] and not ever[s]] + if held: + failure = "held" + elif touching: + failure = "touching" + elif lost_final: + failure = "regressed" + elif never: + failure = "incomplete" + else: + failure = "not_static" + placed = self.placed_objects() + described = set() + for s in range(len(raw)): + if raw[s]: + continue + kind = SLOT_KIND[s] + c = np.asarray(inst["slots"][s]) + spare = [q for q in OBJS if self.kind(q) == kind and q not in placed and q not in described] + near = min(spare, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - c))) if spare else None + dist = float(np.linalg.norm(self.pos(near)[:2] - c)) if near else 1.0 + if near is None or (not ever[s] and dist > 0.06): + txt = f"{self._slot_name(s)} has no {kind} on it (none was put there)." + else: + described.add(near) + tl = np.degrees(self.tilt(near)) + state = ("lies fallen" if tl > 45 else f"leans {tl:.0f} degrees" if tl > np.degrees(TILT_OK) + else "stands") + txt = (f"{self._slot_name(s)} has no upright {kind} on it: the nearest {kind} {state} " + f"{self._dir_words(self.pos(near)[:2] - c)} it.") + if ever[s]: + lost = [e for e in ev if e.get("stage") == names[s] and e["event"] == "lost"] + why = lost[-1]["cause"] if lost else "other" + txt += {"robot_finger_opening": f" The {kind} had stood there; a finger pushed it when the " + f"gripper opened.", + "robot_hand_opening": f" The {kind} had stood there; the hand pushed it.", + }.get(why, f" The {kind} had stood there and was knocked over later." + if why.startswith(("robot", "object")) else f" The {kind} had stood there earlier.") + parts.append(txt) + if all(raw) and held: + parts.append("The gripper still holds an object.") + elif touching: + parts.append("The gripper is still touching the fence.") + elif all(raw) and not static: + parts.append("Something was still moving.") + if n_reg: + parts.append(f"During the attempt objects on the fence line were knocked off {n_reg} time(s) and stood " + f"up again {n_res} time(s).") + if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")): + parts.append("(Forward = away from the robot.)") + return dict(success=success, stages={names[s]: bool(raw[s]) for s in range(len(raw))}, events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), n_toppled=int(n_top), failure=failure, + held=held, touching=bool(touching), static=bool(static), + tilts_deg={p: round(float(np.degrees(self.tilt(p))), 1) for p in OBJS}, detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def axis(self, p, i): + a = self.R(p)[:2, i] + return a / max(np.linalg.norm(a), 1e-9) + + def grasp_yaw(self, p, mode): + """yaw for a top-down knob grasp. Lying object: fingers across its long axis (it swings up and hangs). + Panel: 'habit' = fingers along its width (hand along the board; along the fence line once placed), + 'thin' = fingers along its thickness (across the line). Post: 'thin' = fingers across the fence line, otherwise + the side direction needing the least rotation (a post's own orientation does not matter: square, round knob).""" + R = self.R(p) + if R[2, 2] < np.cos(np.radians(30)): + ax = R[:2, 2] + if np.linalg.norm(ax) > 1e-3: + return _yaw_for_axis(np.array([-ax[1], ax[0]])) + if self.kind(p) == "panel": + return _yaw_for_axis(self.axis(p, 1) if mode == "habit" else self.axis(p, 0)) + if mode == "thin": # careful: a post's fingers across the fence line too (they reach nothing there) + return _yaw_for_axis(np.asarray(self.inst["v"])) + y0 = _yaw_for_axis(self.axis(p, 0)) + return min((_wrap_h(y0), _wrap_h(y0 + np.pi / 2)), key=lambda y: abs(_wrap_h(y - self.sk.yaw))) + + def obj_yaw(self, p): + R = self.R(p) + return float(np.arctan2(R[1, 0], R[0, 0])) + + def pick(self, p, mode, careful, z_carry=None, noise=None, v=0.15): + """grasp p's knob and lift it; returns (object yaw - gripper yaw) or None if not held""" + sk = self.sk + k = self.knob_xyz(p) + if noise is not None: + k = k + np.array([noise[0], noise[1], 0.0]) + yaw = self.grasp_yaw(p, mode) + zk = max(k[2], TZ + 0.006) + sk.set_gripper(False, steps=8) + if careful: + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([k[0], k[1], TZ + Z_SAFE], yaw=yaw, speed=0.3) + self._go([k[0], k[1], zk + 0.04], speed=0.25) + self._go([k[0], k[1], zk], speed=0.1, tol=0.003, max_steps=150) + 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 + zt = TZ + (Z_NAIVE if z_carry is None else z_carry) + cur = sk.eef_pos() + self._go([k[0], k[1], max(cur[2], zt, zk + 0.06)], yaw=yaw, speed=v) + self._go([k[0], k[1], zk + 0.015], speed=0.1) + self._go([k[0], k[1], zk], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + if careful: + self._go([k[0], k[1], TZ + Z_SAFE], speed=0.25) + else: + self._go([k[0], k[1], TZ + (Z_NAIVE if z_carry is None else z_carry)], speed=0.08) + sk.hold(10) + if not self.held(p): + sk.set_gripper(False, steps=8) # already lifted: the fingers open well above the object + return None + return float(self.obj_yaw(p) - sk.yaw) + + def release_z(self, p): + """grasp-point height at which the held object's bottom is 2 mm above the table (a heavy object's knob can + sit a few mm low in the fingers; pressing it onto the table would squeeze the knob out of the grip)""" + dz = float(self.sk.eef_pos()[2] - self.knob_xyz(p)[2]) if self.held(p) else 0.0 + return self.knob_stand_z() + 0.002 + float(np.clip(dz, -0.005, 0.015)) + + def place_yaw(self, p, offset): + """gripper yaw that lines p up with the fence (panel: width along the line; post: sides along it)""" + if self.kind(p) == "panel": + return _wrap_h(self.inst["pyaw"] - offset) + cands = [_wrap_h(self.inst["pyaw"] + k * np.pi / 2 - offset) for k in range(4)] + return min(cands, key=lambda y: abs(_wrap_h(y - self.sk.yaw))) + + def place(self, p, s, offset, careful, z_carry=None, noise=None, lift=None, v=0.15): + """carry the held object to fence slot s, lined up with the fence; set it down; let go""" + sk = self.sk + xy = np.asarray(self.inst["slots"][s], float) + (np.asarray(noise, float) if noise is not None else 0.0) + yaw = self.place_yaw(p, offset) + zr = self.release_z(p) + if careful: + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw, speed=0.3) + sk.hold(15) + zr = self.release_z(p) + self._go([xy[0], xy[1], zr + 0.03], speed=0.2) + self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.04], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + 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 + zt = TZ + (Z_NAIVE if z_carry is None else z_carry) + cur = sk.eef_pos() + self._go([xy[0], xy[1], max(cur[2], zt)], yaw=yaw, speed=v) + self._go([xy[0], xy[1], zr + 0.015], speed=0.1) + self._go([xy[0], xy[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], TZ + (Z_NAIVE if lift is None else lift)], speed=0.15) + sk.hold(5) + + # orders --------------------------------------------------------------- + def supply_center(self): + return np.mean([self.inst["start"][p] for p in OBJS], axis=0) + + def fence_order(self, far_first=True): + """slot indices from the end of the line farthest from the supply to the near end (or reversed)""" + sc = self.supply_center() + first, last = np.asarray(self.inst["slots"][0]), np.asarray(self.inst["slots"][-1]) + idx = list(range(len(SLOT_KIND))) + near_first = idx if np.linalg.norm(first - sc) <= np.linalg.norm(last - sc) else idx[::-1] + return near_first[::-1] if far_first else near_first + + def build(self, order, careful, panel_mode, noise_fn=lambda: None, z_carry=None, lift=None, noise_pick=False, + v=0.15): + """put an object on every slot that has none, in the given slot order; the object for each slot: an unused + one of the right kind, the nearest to the gripper (naive) / to the slot (careful). No looking back.""" + fails = {} + used = set() + for s in order: + if self.slot_filled(s): + continue + for _ in range(2): + cand = [p for p in OBJS if self.kind(p) == SLOT_KIND[s] and p not in used and fails.get(p, 0) < 2 + and p not in self.placed_objects()] + if not cand: + break + ref = np.asarray(self.inst["slots"][s]) if careful else self.sk.eef_pos()[:2] + p = min(cand, key=lambda q: float(np.linalg.norm(self.pos(q)[:2] - ref))) + mode = panel_mode if self.kind(p) == "panel" else ("thin" if careful else "any") + off = self.pick(p, mode, careful, z_carry=z_carry, noise=noise_fn() if noise_pick else None, v=v) + if off is None: + fails[p] = fails.get(p, 0) + 1 + continue + used.add(p) + self.place(p, s, off, careful, z_carry=z_carry, noise=noise_fn(), lift=lift, v=v) + break + + def footprint(self, p): + """sample points of p's collision box projected onto the table (corners, edge and face midpoints) + knob""" + R, c = self.R(p), self.pos(p) + if self.kind(p) == "panel": + h = np.array([self.inst["t"], self.inst["w"], self.inst["h"]]) / 2 + else: + h = np.array([self.inst["b"], self.inst["b"], self.inst["h"]]) / 2 + 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)] + pts.append(self.knob_xyz(p)) + return np.array(pts)[:, :2] + + def slot_blocked(self, s, ignore=()): + """an object that is not standing on a slot lies (partly) on slot s or right next to it""" + c = np.asarray(self.inst["slots"][s]) + u, v = np.asarray(self.inst["u"]), np.asarray(self.inst["v"]) + hu = (self.inst["w"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.003 + hv = (self.inst["t"] if SLOT_KIND[s] == "panel" else self.inst["b"]) / 2 + 0.008 + placed = self.placed_objects() + for q in OBJS: + if q in ignore or self.held(q) or q in placed: # objects standing on their own slots are fine + continue + d = self.footprint(q) - c + if np.any((np.abs(d @ u) < hu) & (np.abs(d @ v) < hv)): + return True + return False + + def fingers_along_width(self, p): + """the held panel's width axis is (nearly) parallel to the finger axis""" + fa = np.array([-np.sin(self.sk.yaw), np.cos(self.sk.yaw)]) + return abs(float(self.axis(p, 1) @ fa)) > 0.7 + + def repair(self, rounds=None): + """look at every slot; stand fallen / misplaced objects up again by their knobs (careful motions, panels + released with the fingers across the line). Order: an object resting on another first, then fallen / leaning + ones from the top of the pile down, then upright ones that are off their slots. A panel lifted with its + fingers along its width (a fallen panel can only be lifted that way) is first set down standing at a free spot + and re-grasped. Returns the number of objects moved.""" + n = len(SLOT_KIND) + moved = 0 + fails, moves = {}, {} + for _ in range(rounds or 16): + if all(self.stages()): + break + ok = self.placed_objects() + loose = [p for p in OBJS if p not in ok and fails.get(p, 0) < 2 and moves.get(p, 0) < 4] + if not loose: + break + on_other = [p for p in loose if envs.obj_min_z(self.env, p) > TZ + 0.006] + down = [p for p in loose if p not in on_other and self.tilt(p) > TILT_OK] + upright = [p for p in loose if p not in on_other and p not in down] + if on_other: + p = max(on_other, key=lambda q: self.knob_xyz(q)[2]) + elif down: + p = max(down, key=lambda q: self.knob_xyz(q)[2]) + else: + fit = {q: [s for s in range(n) if SLOT_KIND[s] == self.kind(q) and not self.slot_filled(s) + and not self.slot_blocked(s, ignore=(q,))] for q in upright} + fit = {q: js for q, js in fit.items() if js} + if not fit: + break + p = min(fit, key=lambda q: min(float(np.linalg.norm(self.pos(q)[:2] - np.asarray( + self.inst["slots"][s]))) for s in fit[q])) + off = self.pick(p, "thin", True) + if off is None: + fails[p] = fails.get(p, 0) + 1 + continue + moved += 1 + moves[p] = moves.get(p, 0) + 1 + if self.kind(p) == "panel" and self.fingers_along_width(p): + self.place_at(p, self.free_spot(), off) + continue + clear = [s for s in range(n) if SLOT_KIND[s] == self.kind(p) and not self.slot_filled(s) + and not self.slot_blocked(s, ignore=(p,))] + if not clear: + self.place_at(p, self.free_spot(), off) + continue + here = self.sk.eef_pos()[:2] + s = min(clear, key=lambda j: float(np.linalg.norm(np.asarray(self.inst["slots"][j]) - here))) + self.place(p, s, off, True) + return moved + + def free_spot(self): + """the reachable table spot (around the fence and the supply) farthest from every object and slot""" + c, v = np.asarray(self.inst["center"]), np.asarray(self.inst["v"]) + u = np.asarray(self.inst["u"]) + best, bc = None, -1.0 + for a in np.linspace(-0.20, 0.20, 9): + for b in (-0.18, -0.12, 0.10, 0.20, 0.32): + q = c + v * b + u * a + 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: + continue + cl = min(float(np.linalg.norm(self.pos(o)[:2] - q)) for o in OBJS) + cl = min(cl, min(float(np.linalg.norm(np.asarray(sl) - q)) for sl in self.inst["slots"])) + if cl > bc: + best, bc = q, cl + return best + + def place_at(self, p, xy, offset): + """careful: set the held object down standing at a free spot""" + sk = self.sk + zr = self.release_z(p) + cur = sk.eef_pos() + if cur[2] < TZ + Z_SAFE - 0.01: + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=self.place_yaw(p, offset), speed=0.3) + sk.hold(15) + zr = self.release_z(p) + self._go([xy[0], xy[1], zr + 0.03], speed=0.2) + self._go([xy[0], xy[1], zr], speed=0.06, tol=0.003, max_steps=200) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.04], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + + # ------------------------------------------------------------ policies + def execute(self, inst, params): + careful = params["careful"] + noise = params.get("noise", 0.0) + rng = np.random.default_rng(params.get("noise_seed", 0)) + nf = (lambda: rng.uniform(-noise, noise, 2)) if noise else (lambda: None) + if params.get("order") == "panels_first": + fo = self.fence_order(True) + order = [s for s in fo if SLOT_KIND[s] == "panel"] + [s for s in fo if SLOT_KIND[s] == "post"] + elif params.get("order") == "posts_first": + fo = self.fence_order(True) + order = [s for s in fo if SLOT_KIND[s] == "post"] + [s for s in fo if SLOT_KIND[s] == "panel"] + else: + order = self.fence_order(params.get("far_first", True)) + self.build(order, careful, params["panel_mode"], noise_fn=nf, z_carry=params.get("z_carry"), + lift=params.get("lift"), noise_pick=params.get("noise_pick", False), v=params.get("v", 0.15)) + if params.get("check"): + self.repair() + cur = self.sk.eef_pos() + if cur[2] < TZ + 0.20: + self._go([cur[0], cur[1], TZ + 0.20], speed=0.3) + self.sk.hold(10) + + # naive = Sonnet 5.5's habits measured in the lh2_fence pilot: hand (finger axis) along the board's long side, fill + # 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 + NAIVE = dict(careful=False, panel_mode="habit", far_first=True, check=False, noise=NAIVE_ERR) + CAREFUL = dict(careful=True, panel_mode="thin", far_first=True, check=True) + V1_NAIVE = dict(careful=False, panel_mode="thin", far_first=False, check=False) # v1's scripted naive habits + + def default_params(self, inst): + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 11) + + def oracle_params(self, inst): + return dict(self.CAREFUL) + + def adapt_params(self, inst, history): + """from attempt 2 (after a failure): panels released with the fingers across the line, careful, final check""" + return dict(self.CAREFUL) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variations, no history, no check""" + return dict(self.NAIVE, noise_seed=int(rng.integers(1 << 30)), z_carry=float(rng.uniform(0.15, 0.23)), + lift=float(rng.uniform(0.15, 0.23)), v=float(rng.uniform(0.08, 0.25))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "oracle_noise", "v1_naive", "naive_thin", "naive_panels_first", + "naive_posts_first") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": # control: cross-attempt learning only (careful from attempt 2), no check + params = self.default_params(inst) if a == 0 else dict(self.CAREFUL, check=False) + elif kind == "oracle_noise": # check: careful with +-5 mm (uniform, per axis) placement noise + params = dict(self.CAREFUL, noise=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "v1_naive": # control: v1's scripted naive (fingers across the line, near end first) + params = dict(self.V1_NAIVE) + elif kind == "naive_thin": # control: Sonnet-like but panels released with the fingers across the line + params = dict(self.default_params(inst), panel_mode="thin") + elif kind == "naive_panels_first": # control: Sonnet-like grasp, both panels before the posts + params = dict(self.default_params(inst), order="panels_first") + elif kind == "naive_posts_first": # control: Sonnet-like grasp, all posts first (how fences are built) + params = dict(self.default_params(inst), order="posts_first") + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_parts_cart.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..e8992d05ab373c966acef42134bb2f87ddec4743 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_parts_cart.py @@ -0,0 +1,253 @@ +"""Composite prototype: physical tool retrieval, loading regression and asymmetric cart transport. + +Not part of main_v1. See task_cards/lh_parts_cart.md for validation status. +Only reset_instance/apply_instance position objects; all reference actions use the public motion skills. +""" +import copy +import numpy as np +from .. import envs +from ..bddl import write_bddl +from ..objects import register_generated, box_xml +from ..task_base import register_task +from .l3_tool import (UnderTableTool, low_table_xml, stick_xml, CUBE_HALF, + HANDLE_HALF, TOP_HALF) +from .l7_offcenter_push import (OffcenterPush, PushSkills, long_box_xml, rect_frame_xml, + HALF, MASS, MU, BOX, _rot) + + +class CartSkills(PushSkills): + def __init__(self,*args,**kwargs): + super().__init__(*args,**kwargs) + self.robot_commands=0 + def move_to(self,*args,**kwargs): + self.robot_commands+=1 + return super().move_to(*args,**kwargs) + def set_gripper(self,*args,**kwargs): + self.robot_commands+=1 + return super().set_gripper(*args,**kwargs) + + +@register_task +class PartsCart(UnderTableTool): + name = 'lh_parts_cart' + level = 'L4' + category = 'geometry_inference' + failure_causes = ('L4', 'L2', 'L5') + capabilities = ('Perceive', 'Reason', 'Plan', 'Restore') + protocol = 'cross' + agent_max_steps = 180 + instruction = ('Use the wooden tool to retrieve the red part from under the low glass table. ' + 'Load the red and blue parts on the two marks on the brown transport platform, ' + 'then push the loaded platform with the closed gripper completely into the green parking area. ' + 'At the end both parts must still be on their marks, and the gripper must be open and clear.') + instruction_indirect = instruction + + def make_bddl(self): + cube = register_generated('LffPartsCartRed', box_xml('lff_parts_cart_red', (CUBE_HALF,)*3,(.85,.12,.12,1), density=300)) + blue = register_generated('LffPartsCartBlue', box_xml('lff_parts_cart_blue', (CUBE_HALF,)*3,(.1,.2,.85,1), density=300)) + stick_xml_text=stick_xml('lff_parts_cart_stick').replace('size="0.00800 0.02500 0.01000"','size="0.00800 0.00800 0.01000"') + stick = register_generated('LffPartsCartStick', stick_xml_text) + table_xml=low_table_xml('lff_parts_cart_table') + # Wider roof with legs outside the blocked cube's x-exit lane. This prevents a panel failure + # trapping the cube against a corner leg, which the existing standalone task did not test in-attempt. + table_xml=table_xml.replace('size="0.06000 0.06000 0.00500"','size="0.06000 0.07500 0.00500"') + for sx in (-.052,.052): + for sy in (-.052,.052): + table_xml=table_xml.replace(f'pos="{sx:.5f} {sy:.5f} 0.03500"',f'pos="{sx:.5f} {np.sign(sy)*.067:.5f} 0.03500"') + table = register_generated('LffPartsCartTable', table_xml, free=False) + xml=long_box_xml('lff_parts_cart_platform') + marks=''.join(f'' for y,color in [(-.03,'.9 .4 .4 1'),(.03,'.4 .5 .9 1')]) + xml=xml.replace(' ',marks+' ',1) + cart = register_generated('LffPartsCartPlatform', xml) + zone = register_generated('LffPartsCartZone', rect_frame_xml('lff_parts_cart_zone'), free=False) + # Inertial/shape match existing off-centre box, with purely visual cargo marks. + objs=[('cube_1',cube,'red_region',(-.31,-.26,-.29,-.24)), + ('blue_1',blue,'blue_region',(-.31,.24,-.29,.26)), + ('stick_1',stick,'stick_region',(-.01,-.36,.01,-.34)), + ('box_1',cart,'cart_region',(.19,.24,.21,.26))] + fx=[('lowtable_1',table,'table_region',(.19,-.11,.21,-.09)), + ('zone_1',zone,'zone_region',(.19,.39,.21,.41))] + return write_bddl(self.name,self.instruction,objs,fx) + + def sample_instance(self, seed): + # Tool geometry is inherited; put transport in the other half of the same tabletop. + rng=np.random.default_rng(seed) + base=super().sample_instance(seed) + base.update(side=-1, pane_side=1, table_xy=[-.08,-.08],cube_xy=[-.08,-.08], + stick_xy=[-.08,-.34],stick_yaw=np.pi/2, + box_xy=[-.25,.24],target_dist=.16, + com_offset=float(rng.choice([-1,1])*rng.uniform(.05,.065)), + traps=dict(L4=True,L2=True,L5=True)) + base['bin_xy']=[-.25,.24] # inherited observe() only; no bin fixture. + return base + + def target_xy(self, inst): + return np.array([inst['box_xy'][0]+inst['target_dist'],inst['box_xy'][1]]) + + def apply_instance(self, inst): + self.inst=inst + m=self.env.sim.model + bid,_=self._fixture('lowtable_1') + m.body_pos[bid]=[*inst['table_xy'],envs.TABLE_Z] + for g,sy in self._panes(): + on=inst['traps']['L4'] and sy==inst['pane_side'] + m.geom_contype[g]=m.geom_conaffinity[g]=int(on) + envs.set_obj_pose(self.env,'cube_1',[*inst['cube_xy'],envs.TABLE_Z+CUBE_HALF+.0005]) + envs.set_obj_pose(self.env,'blue_1',[-.30,.04,envs.TABLE_Z+CUBE_HALF+.0005]) + envs.set_obj_pose(self.env,'stick_1',[*inst['stick_xy'],envs.TABLE_Z+HANDLE_HALF[2]+.0005],yaw=inst['stick_yaw']) + bid=envs.body_id(self.env,BOX) + m.body_mass[bid]=MASS + m.body_ipos[bid]=[0,inst['com_offset'] if inst['traps']['L5'] else 0,0] + for g in range(m.ngeom): + 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])): + m.geom_pos[g,1]=np.sign(m.geom_pos[g,1])*(.03 if inst['traps']['L2'] else .07) + envs.refit_bounds(self.env,bid) + envs.set_friction(self.env,BOX,MU) + envs.set_obj_pose(self.env,BOX,[*inst['box_xy'],envs.TABLE_Z+HALF[2]+.001]) + zb=m.body_name2id(self.env.fixtures_dict['zone_1'].root_body) + m.body_pos[zb]=[*self.target_xy(inst),envs.TABLE_Z+.0002] + + def reset_instance(self, inst, recorder=None): + self.loadmon=None + self._mon=None + self.env.reset();self.apply_instance(inst);self.env.sim.forward();envs.settle(self.env,15) + self.sk=CartSkills(self.env,recorder=recorder,target=self.target_xy(inst)) + self._start_monitor() + 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]) + self.ncmd=0;self.budget=None + return self.sk + + def mark(self,i): + p,yaw=self.sk._box_pose() if self.sk else (envs.obj_pos(self.env,BOX),0.) + spacing=.03 if self.inst['traps']['L2'] else .07 + return p[:2]+_rot(yaw)@np.array([0.,(-spacing,spacing)[i]]) + + def cargo_ok(self,i): + obj=('cube_1','blue_1')[i] + p=envs.obj_pos(self.env,obj); bp=envs.obj_pos(self.env,BOX) + return bool(np.linalg.norm(p[:2]-self.mark(i))<.018 and + abs(p[2]-(bp[2]+HALF[2]+CUBE_HALF))<.012 and not self.sk.holding(obj)) + + def _monitor_step(self): + super()._monitor_step() + mon=getattr(self,'loadmon',None) + if mon is None:return + robot=set(envs.robot_geom_ids(self.env)) + for i,obj in enumerate(('cube_1','blue_1')): + geoms=set(envs.obj_geom_ids(self.env,obj)) + for c in self.env.sim.data.contact[:self.env.sim.data.ncon]: + if (c.geom1 in robot and c.geom2 in geoms) or (c.geom2 in robot and c.geom1 in geoms): + mon['last_robot_touch'][i]=self.sk.n_steps + now=self.cargo_ok(i) + if now==mon['states'][i]:mon['count'][i]=0;continue + mon['count'][i]+=1 + if mon['count'][i]<5:continue + mon['count'][i]=0;mon['states'][i]=now + ev='restored' if now and mon['lost'][i] else 'achieved' if now else 'lost' + if now:mon['ever'][i]=True + else: + mon['lost'][i]=True + if np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])<.025: + mon['loaded']=False + mon['load_step']=None + mon['events'].append(dict(step=self.sk.n_steps,pred=('red','blue')[i],event=ev, + cart_displacement=float(np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy'])), + cause='robot' if self.sk.n_steps-mon['last_robot_touch'][i]<=20 else 'other')) + displacement=np.linalg.norm(envs.obj_pos(self.env,BOX)[:2]-self.inst['box_xy']) + if all(mon['states']) and displacement<.02 and not mon['loaded']: + mon['loaded']=True + mon['load_step']=self.sk.n_steps + if displacement>.03 and mon['departure_step'] is None: + mon['departure_step']=self.sk.n_steps + if not mon['loaded']:mon['departed_unloaded']=True + + def pick_place(self,obj,xy,yaw=0.): + sk=self.sk;p=envs.obj_pos(self.env,obj) + sk.set_gripper(False,steps=10) + 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) + sk.move_to([p[0],p[1],p[2]-.004],speed=.10,tol=.002) + sk.set_gripper(True,steps=15) + held=sk.holding(obj) + sk.move_to([p[0],p[1],envs.TABLE_Z+.20],speed=.15) + if held: + sk.move_to([xy[0],xy[1],envs.TABLE_Z+.20],yaw=yaw) + bp=envs.obj_pos(self.env,BOX) + sk.move_to([xy[0],xy[1],bp[2]+HALF[2]+CUBE_HALF-.003],speed=.06,tol=.002) + sk.set_gripper(False,steps=15) + sk.move_to([xy[0],xy[1],envs.TABLE_Z+.22],speed=.15) + return bool(held) + + def load(self, careful=True): + self.pick_place('cube_1',self.mark(0),np.pi/2) + # Open fingers along y at the adjacent mark can knock the already loaded red cube. + yaw=np.pi/2 if careful else 0. + self.pick_place('blue_1',self.mark(1),yaw) + + def repair_load(self): + for _ in range(3): + for i,o in enumerate(('cube_1','blue_1')): + if not self.cargo_ok(i):self.pick_place(o,self.mark(i),np.pi/2) + + def transport(self,c=0.,repair=False): + # Call existing push controller on this same environment; no independent rollout stitching. + if not repair: + return OffcenterPush.execute(self,self.inst,dict(c=c)) + if repair: + # Original feedback-driven corrector calls self.execute for its initial push. + self._transport_only=True + try:OffcenterPush.adaptive_attempt(self,self.inst,c) + finally:self._transport_only=False + + _cmd=OffcenterPush._cmd + _sim_used=OffcenterPush._sim_used + _push_at=OffcenterPush._push_at + bracket=OffcenterPush.bracket + _front_runup=staticmethod(OffcenterPush._front_runup) + STEP=OffcenterPush.STEP;YAW_OK=OffcenterPush.YAW_OK + GAIN0=OffcenterPush.GAIN0;SAFE_V=OffcenterPush.SAFE_V + + def execute(self,inst,params): + if getattr(self,'_transport_only',False):return OffcenterPush.execute(self,inst,params) + if params.get('front',False):self.tool_push_front() + else:self.tool_push_out() + if self.under_table():return + self.load(params.get('careful',False)) + if params.get('repair',False):self.repair_load() + if all(self.cargo_ok(i) for i in range(2)): + self.transport(params.get('c',0.),params.get('repair',False)) + if params.get('repair',False):self.repair_load() + self.sk.set_gripper(False,steps=10) + p=self.sk.eef_pos();self.sk.move_to([p[0],p[1],envs.TABLE_Z+.24]) + + def default_params(self,inst):return dict(front=False,careful=False,repair=False,c=0.) + def oracle_params(self,inst):return dict(front=True,careful=True,repair=True,c=inst['com_offset'] if inst['traps']['L5'] else 0.) + def adapt_params(self,inst,history): + # The L4 side hit is learned from actual prior outcome, not from inst['pane_side']. + seen_geometry=any(h['outcome']['traps']['L4'] for h in history) + seen_loading=any(h['outcome']['traps']['L2'] for h in history) + pushes=[m for h in history for m in h['outcome']['box_moves']] + return dict(front=seen_geometry,careful=seen_loading,repair=bool(history),c=self.bracket(pushes)) + + def outcome(self,inst): + self.sk.hold(30) + fit=self.sk.fit();cargo=[self.cargo_ok(i) for i in range(2)] + ev=list(self.loadmon['events']) + # Loading regressions count only while cart remains at the loading station. + load_lost=[e for e in ev if e['event']=='lost' and e['cart_displacement']<.025 and e['cause']=='robot'] + loaded=self.loadmon['loaded'] + static=bool(np.max(np.abs(self.env.sim.data.qvel))<.05) + robot=set(envs.robot_geom_ids(self.env)); items=set() + for o in ('cube_1','blue_1',BOX,'stick_1'):items.update(envs.obj_geom_ids(self.env,o)) + touching=any((c.geom1 in robot and c.geom2 in items) or (c.geom2 in robot and c.geom1 in items) + for c in self.env.sim.data.contact[:self.env.sim.data.ncon]) + budget_ok=bool(self.sk.robot_commands<=self.agent_max_steps and self.sk.n_steps*.05<=self.agent_max_steps*3) + success=bool(not self.under_table() and all(cargo) and fit['inside'] and loaded + and not self.loadmon['departed_unloaded'] and static and not touching and budget_ok and self.sk.grip<0 + and self._mon['stick_touched_cube']) + moves=copy.deepcopy(self.sk.box_moves) + return dict(success=success,stages=dict(retrieved=not self.under_table(),red=cargo[0],blue=cargo[1],parked=fit['inside'],loaded=loaded), + 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'], + events=ev,n_regressions=len(load_lost),n_restored=sum(e['event']=='restored' for e in ev), + traps=dict(L4=bool(self._mon['cube_hit_pane']),L2=bool(load_lost),L5=any(m['bad'] for m in moves)), + box_moves=moves,cart_pose=[*envs.obj_pos(self.env,BOX).tolist()],cart_fit=fit, + detail=f'Retrieved={not self.under_table()}; cargo on marks={cargo}; platform parked={fit["inside"]}.') diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_wobbly_table.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_wobbly_table.py new file mode 100644 index 0000000000000000000000000000000000000000..9d7b70f09bae7e0720480903ba087e0a11aed799 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_wobbly_table.py @@ -0,0 +1,1177 @@ +"""LH lh_wobbly_table (2026-10-16): stand four bottles on the four coloured spots of a small side table -- one of its +legs is 1.5 cm short. Set the heavy bottle down on the corner over that leg while other bottles already stand on the +table and the table rocks down onto the short leg with a knock that throws the tall light bottles over. + +Family: long-horizon self-disturbance ("state_restoration"): four plain pick-and-place stages, but a later stage (the heavy +bottle on the wobbly corner) physically undoes the earlier ones without the robot touching them. The agent has to +notice the fallen bottles and stand them up again (the rocked table is stable, so they stay up), or learn across +attempts to put that bottle down first (the table then rocks while nothing stands on it). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * 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.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, + painted, colours permuted) centred 8 cm from the middle on both axes (one per corner); + * 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 + 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 + 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: + 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 + mass 3.0-3.6 cm up). + +Hidden variables: which leg is short (its collision capsule is 14-16 mm shorter; the visual leg is drawn full length, +so all legs look alike and touch the table) and which bottle is heavy. Coupled by construction: the heavy bottle's spot +is the corner over the short leg. Balanced over seeds: in the scripted naive order (spots farthest from the supply +first, then left first) the heavy bottle's spot comes 1st / 2nd / 3rd / 4th for exactly 5 of every 20 consecutive seeds +(1st = benign for that order: the table rocks while it is empty). + +Physics (measured, scratch scripts t2-t24, see the task card and results/lh_wobbly_table/physics.json): + * The legs' collision geoms are capsules (rounded feet). With flat 1.6 cm box feet the rocking axis moved 1.1 cm + towards the loaded corner and the table's own weight stopped the rock half way (0.5 deg, balanced on two legs). + * The empty table rests level on its three long legs: its centre of mass is 5 mm towards the corner opposite the + 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 + 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 + does (0.36 kg x 11.3 cm), also against a light bottle on the opposite corner. (A light bottle put on the short + 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 + 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; + lifting the heavy bottle off, or pressing 1.25 N down near the raised corner, rocks it back (measured). + * The knock topples the light bottles standing on the table: 18/18 with teleported (zero-velocity) placements at gaps + 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 + stays up. The robot does not touch the bottles that fall (logged per rock). + * Bottle and table-top contacts are overdamped (solref 0.01, damping ratio 3): with stiff critically damped contacts + 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); + damped, 0/54 at every gap 13-18 mm, so the cross-attempt fix (heavy bottle first) works with the agent's usual + release 1-4 cm above the surface. + * 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 + fall onto the heavy one and lean on it; its stopper could not be grasped without knocking the heavy bottle over + (after which the table rocks back and forth on every repair step). At 28 cm nothing leans on it. + * Grasps: the Panda hand's collision hull starts 3 cm above the grasp point and the finger pads reach 1.2 cm above + it. Everything above the square neck is narrower than the neck: fingers that overlap the neck (grasp point 0.4-0.9 + cm below its top) close on its flat faces and hold the bottle rigidly (the heavy one stayed in the fingers through + three moves at the controller's top speed 12/12, a light one 11/12); fingers on the ball alone (grasp point at or + above the neck's top) touch it at one point each and the bottle pivots (top-speed carries lost it 6/6). Drafts: a + 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 + carries and once in the first smoke test), a 1.2 x 2.2 cm cylinder stopper (line contacts: a lying bottle lifted by + it stuck at ~26 deg and fell over when set down). The instruction states which grip is rigid and which swings (as + lh_bystander states its cap). + * Restoring (yaw-only top-down gripper): grasp the ball stopper of a lying bottle from above with the fingers across + its axis (torsional friction 0.0005), lift: it swings down and hangs straight (0.1 deg); lower it onto its spot and + let go. A bottle that fell off onto the main table right beside the small table often cannot be reached this way: + the hand (20 cm wide along the finger axis, 3 cm above the grasp point) would hit the table top. Where the hand, + the open fingers or the forearm would touch a standing bottle, the scripted repair first lifts the fallen bottle by + its body and lays it down in free space. + * Reach: the arm stalls 2-3 cm short of low targets beyond ~0.72 m from the base; every scripted grasp point stays + within 0.70 m. + +Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each bottle stands upright +(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 +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. +Success = all four at the end, gripper open and not touching a bottle, scene static, and the small table within 3 cm / +10 deg of where it stood and standing on its legs (tilt <= 8 deg; the rocked tilt counts as standing). The monitor logs +achieved / lost / restored per bottle and table_rocked / table_rocked_back events (the bottle released just before, +the bottles standing at that moment, which of them fell, whether the robot touched them before / while they fell) for +the server log only (F1 gives the agent only success / failure). + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +TZ = envs.TABLE_Z +COLOURS = ["red", "blue", "green", "yellow"] +BOTTLES = [f"bottle_{c}_1" for c in COLOURS] +TABLE = "side_table_1" +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), + "yellow": (0.90, 0.74, 0.12, 1.0)} +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), + "yellow": (0.70, 0.56, 0.08, 1.0)} +CAP_RGBA = (0.93, 0.93, 0.91, 1.0) # white round stopper +WOOD = (0.52, 0.36, 0.22, 1.0) +LEG_RGBA = (0.40, 0.27, 0.16, 1.0) + +# ---------------------------------------------------------------- side table (free body) +TOP_HW = 0.140 # 28 x 28 cm top +TOP_T = 0.016 +TABLE_H = 0.085 # top surface above the main table +LEG_HW = 0.008 # 1.6 x 1.6 cm legs (visual); collision: capsules of radius 8 mm (rounded feet) +LEG_O = 0.125 # leg centre offset from the table centre (x and y) +LEG_L = TABLE_H - TOP_T +TBL_MASS = 1.1 +TBL_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.004 1"' # legs: stiff (a sharp knock when the short leg lands) +TOP_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' # top: overdamped like the bottles +LEG_MU = 1.0 +TOP_MU = 0.8 +# corners in the table frame (= world axes; +x forward, +y left): index -> (sx, sy); k and k + 2 are diagonal +CORNERS = [(1, 1), (1, -1), (-1, -1), (-1, 1)] +CORNER_NAME = {(1, 1): "far-left", (1, -1): "far-right", (-1, -1): "near-right", (-1, 1): "near-left"} +SPOT_O = 0.080 # spot centre offset from the table centre (x and y) +SPOT_HX, SPOT_HY = 0.036, 0.032 # spot half sizes (forward-back, left-right): 7.2 x 6.4 cm +SHORT_H = (0.014, 0.016) # hidden: one leg this much shorter (collision only; the visual leg reaches the table) +COM_BIAS = 0.005 # table centre of mass this far towards the leg opposite the short one: the empty table rests level + +# ---------------------------------------------------------------- bottles (square glass bottles with a round stopper) +RB, HB = 0.016, 0.100 # body half width, height (3.2 x 3.2 x 10 cm) +RF, HF = 0.012, 0.005 # foot: flat contact 2.4 x 2.4 cm (rounded glass base) +RS, HS = 0.011, 0.010 # shoulder +RN, HN = 0.007, 0.016 # square neck: 1.4 cm wide, 1.6 cm long (11.0-12.6 cm above the bottom) +RT, HT = 0.0035, 0.010 # thin round stem above it: 0.7 cm wide, 1.0 cm long +RK, CAP_SINK = 0.006, 0.001 # ball stopper: 1.2 cm wide, on the stem (top 14.7 cm above the bottom) +# Why this top (measured, t8_hand.py / t19_slip.py / t22_restand.py): the Panda hand's collision hull starts ~3 cm above +# the grasp point and the finger pads reach 1.2 cm above it. Everything above the square neck is narrower than the +# neck, so fingers that overlap the neck close on its flat faces (several contact points: the bottle is held rigidly), +# and fingers on the ball alone touch it at one point each (low torsional friction: a lying bottle swings down and +# hangs straight). Drafts: a 1.8 cm ball on a 1.3 cm round neck -- the fingers always closed on the ball, the heavy +# bottle pivoted and swung out in 5/6 fast carries; a 1.2 x 2.2 cm cylinder stopper -- line contacts, a lifted lying +# bottle stuck at ~26 deg and fell over when set down (in-attempt repair 6/15). +H_TOT = HB + HS + HN + HT + 2 * RK - CAP_SINK # 14.7 cm +CAP_Z = H_TOT - RK # stopper centre above the bottle's bottom +NECK_Z = (HB + HS, HB + HS + HN) # square neck span above the bottom +BOT_MU = 0.7 +CAP_MU_T = 0.0005 # torsional friction of the stopper (condim 4): held by it, a lying bottle swings down and hangs +BOT_DAMP = 0.003 # free-joint damping of the bottles (damps the swing of a bottle hanging from its stopper) +# overdamped contacts (damping ratio 3): with critically damped stiff contacts a light bottle set down 1-4 cm above a +# 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 +BOT_SOLREF = 'solimp="0.95 0.99 0.001" solref="0.01 3"' +LIGHT_MASS = (0.075, 0.090) +LIGHT_COM = (0.072, 0.080) # above the bottom (empty glass bottle, thick shoulder) +HEAVY_MASS = (0.34, 0.38) +HEAVY_COM = (0.030, 0.036) # sand in the bottom + +# ---------------------------------------------------------------- predicates / monitor +TILT_OK = np.radians(10.0) # a bottle stands upright (world vertical; the rocked table itself tilts ~4.3 deg) +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) +TOL_Y = SPOT_HY - 0.006 +ON_TOP = 0.006 # the bottle's bottom within this of the table top +HYST = 0.003 +DEBOUNCE = 10 # control steps (0.5 s) +ROCK_ON, ROCK_OFF = np.radians(1.5), np.radians(0.8) # table tilt thresholds of the rock detector +FELL_WINDOW = 40 # control steps after a rock in which lost stages are attributed to it (2 s) +TABLE_MOVE_TOL = 0.03 # success: the table centre within 3 cm of where it stood +TABLE_YAW_TOL = np.radians(10.0) +TABLE_TILT_MAX = np.radians(8.0) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.40 # grasp point above the main table while carrying (bottle bottom ~27 cm up: clears standing bottles) +Z_HANG = 0.42 # ... carrying a bottle that hangs from its stopper (its bottom 27 cm up) +GRASP_NECK = 0.006 # scripted transport grasp point: this far below the neck's top (pads 1.1 cm on the neck, the hand +# 3 mm above the stopper; measured: 4-9 mm below the top hold rigidly, 4 mm above it close on the ball) +NAIVE_GAP = (0.010, 0.040) # Sonnet releases 1-4 cm above the surface +NAIVE_BIAS = (0.008, 0.020) # systematic forward placement error (lh_nudge_row pilot), per instance +NAIVE_RAND = 0.006 +CAREFUL_GAP = 0.004 + + +def bottle_xml(name, rgba): + """square glass bottle: rounded foot (smaller flat contact), body, shoulder, square neck, round stopper. Collision and + visual geoms separate; the inertial (mass, COM) is replaced per instance.""" + h = H_TOT / 2 + zf, zb = -h + HF / 2, -h + HF + (HB - HF) / 2 + zs, zn = -h + HB + HS / 2, -h + HB + HS + HN / 2 + zt = -h + HB + HS + HN + HT / 2 + zk = -h + HB + HS + HN + HT + RK - CAP_SINK + parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("neck", "box", (0, 0, zn), (RN, RN, HN / 2), rgba, f'friction="{BOT_MU} 0.005 0.0001"'), + ("stem", "cylinder", (0, 0, zt), (RT, HT / 2), CAP_RGBA, f'friction="{BOT_MU} 0.005 0.0001"'), + ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')] + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a pale label (visual) so the bottles read as bottles + s.append(f' ') + return _wrap(name, "\n".join(s), h, RB * 1.42) + + +def table_xml(name): + """side table, origin at the centre of the footprint at mid height. Leg k sits under corner CORNERS[k].""" + h = TABLE_H / 2 + zt = h - TOP_T / 2 + zl = -h + LEG_L / 2 + s = [f' ', + f' ', + f' '] + for k, (sx, sy) in enumerate(CORNERS): + p = (sx * LEG_O, sy * LEG_O, zl) + # collision: a capsule inscribed in the square leg -> a rounded, point-like foot (a flat 1.6 cm foot moves the + # rocking axis 1.1 cm towards the loaded corner, and the table's own weight then stops the rock; measured) + s.append(f' ') + s.append(f' ') + for k, (sx, sy) in enumerate(CORNERS): # coloured spots (visual); colours are set per instance + s.append(f' ') + return _wrap(name, "\n".join(s), h, TOP_HW * 1.42) + + +def _fb(d): + return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}" + + +def _lr(d): + return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}" + + +def _ang(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +class WobblySkills(Skills): + """Skills that feed the task's per-step monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class WobblyTable(LFFTask): + name = "lh_wobbly_table" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: 4 bottles x ~7 commands + standing up to three fallen bottles again x ~9 + looking / corrections + agent_max_steps = 120 + instruction = ("Put each of the four bottles on the spot of its own colour on the small wooden table. At the end " + "every bottle must stand upright on its spot, the gripper must be open and clear of the bottles, and " + "the small table must still stand where it is now. (Each bottle has a square neck with a small round " + "white stopper on top. Gripped on the neck, a bottle stays rigid in the fingers; gripped by the " + "stopper alone, it swings freely and hangs straight down.)") + instruction_indirect = ("Set the four coloured bottles out on the little wooden side table, each on the patch that " + "matches its colour. When you finish, all four have to be standing upright on their patches, " + "the gripper open and away from them, and the side table left where it stands. (Gripped " + "on its square neck a bottle stays rigid; gripped by the round white stopper alone it swings " + "freely and hangs straight down.)") + agent_object_names = ["bottles (red, blue, green, yellow; each with a square neck and a small round white stopper)", + "small wooden side table with four coloured spots (red, blue, green, yellow)"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, b) in enumerate(zip(COLOURS, BOTTLES)): + cat = register_generated(f"LffLhwBottle{c.capitalize()}", bottle_xml(f"lff_lhw_bottle_{c}", RGBA[c])) + objs.append((b, cat, f"bottle{i}_region", (-0.30 + 0.13 * i, 0.30, -0.29 + 0.13 * i, 0.31))) + cat = register_generated("LffLhwSideTable", table_xml("lff_lhw_table")) + objs.append((TABLE, cat, "table_region", (-0.05, -0.30, -0.04, -0.29))) + return write_bddl(self.name, "Stand each bottle on the spot of its colour on the small table", objs, []) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.tbid = envs.body_id(self.env, TABLE) + pre = f"{TABLE}_lff_lhw_table" + self.leg_gid = [m.geom_name2id(f"{pre}_leg{k}") for k in range(4)] + self.top_gid = m.geom_name2id(f"{pre}_top") + self.leg_size0 = [m.geom_size[g].copy() for g in self.leg_gid] + self.leg_pos0 = [m.geom_pos[g].copy() for g in self.leg_gid] + self.tbl_ipos0 = m.body_ipos[self.tbid].copy() + self.spot_gid = [m.geom_name2id(f"{pre}_spot{k}") for k in range(4)] + self.bbid = {b: envs.body_id(self.env, b) for b in BOTTLES} + self.cap_gid = {b: m.geom_name2id(f"{b}_lff_lhw_bottle_{c}_cap") for c, b in zip(COLOURS, BOTTLES)} + self.dof = {b: envs.free_joint_addr(self.env, b)[1] for b in BOTTLES} + self.tbl_dof = envs.free_joint_addr(self.env, TABLE)[1] + self.bgeoms = {b: envs.obj_geom_ids(self.env, b) for b in BOTTLES} + self.finger_geoms, self.hand_geoms, self.arm_geoms = [], [], [] + for g in envs.robot_geom_ids(self.env): + n = m.geom_id2name(g) or "" + (self.finger_geoms if "finger" in n else self.hand_geoms if n.startswith("gripper0_") + else self.arm_geoms).append(g) + # per-geom lookup tables for the substep contact check: bottle index (-1 none), robot part (1 finger, 2 hand, + # 3 arm), table geom + self.owner = np.full(m.ngeom, -1, int) + for i, b in enumerate(BOTTLES): + self.owner[self.bgeoms[b]] = i + self.part = np.zeros(m.ngeom, int) + self.part[self.finger_geoms] = 1 + self.part[self.hand_geoms] = 2 + self.part[self.arm_geoms] = 3 + self.is_table = np.zeros(m.ngeom, bool) + self.is_table[envs.obj_geom_ids(self.env, TABLE)] = True + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + # contacts are collected after every MuJoCo substep (same technique as lh_nudge_row; wrappers chain) + sim = self.env.sim + if not getattr(sim, "_lhw_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhw_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhw_wrapped = True + sim._lhw_task = self + self.inst = None + self.mon = None + self.sk = None + self._held_prev = None + + def _substep(self): + d = self.env.sim.data + n = d.ncon + if not n: + return + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + o1, o2 = self.owner[g1], self.owner[g2] + for a, b, pa, pb in zip(g1, g2, o1, o2): + if pa < 0 and pb < 0: + if (self.is_table[a] and self.part[b]) or (self.is_table[b] and self.part[a]): + self._sub_tbl = 1 + continue + if pa >= 0 and pb >= 0: + if pa != pb: + self._sub_obj[int(pa)] = int(pb) + self._sub_obj[int(pb)] = int(pa) + continue + p, o = (pa, b) if pa >= 0 else (pb, a) + part = int(self.part[o]) + if part: + self._sub_rob[int(p)] = min(self._sub_rob.get(int(p), 9), part) + + # ------------------------------------------------------------ instances + @staticmethod + def _supply(side, tx, ty, j): + """slot j (0-3) of the row of bottles on the main table: in front of the side table (robot side) or beside it; + every grasp point stays within 0.70 m (horizontal) of the robot base (the arm stalled 2-3 cm short of low + targets beyond ~0.72 m, measured)""" + if side == "front": + return [tx - 0.215, ty + (j - 1.5) * 0.085] + sg = 1.0 if side == "left" else -1.0 + return [tx - 0.05 + (j - 1.5) * 0.075, ty + sg * 0.22] + + @staticmethod + def _far_first(spot_of, side, tx, ty): + """colours in the order of the scripted naive policy: the spots farthest from the supply first (a careful agent + does not reach over bottles it has already put down), ties broken to the left, then far""" + sup = np.mean([WobblyTable._supply(side, tx, ty, j) for j in range(4)], axis=0) + sc = [] + for c, k in spot_of.items(): + sx, sy = CORNERS[k] + p = np.array([tx + sx * SPOT_O, ty + sy * SPOT_O]) + sc.append((-round(float(np.linalg.norm(p - sup)), 3), -sy, -sx, c)) + return [t[-1] for t in sorted(sc)] + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + tx = float(rng.uniform(-0.13, -0.09)) # side table centre: 53-57 cm in front of the robot base + ty = float(rng.uniform(-0.04, 0.04)) + side = str(rng.choice(["left", "right", "front"])) + perm = [int(v) for v in rng.permutation(4)] # perm[corner] = colour index on that corner's spot + spot_of = {COLOURS[perm[k]]: k for k in range(4)} + # the heavy bottle and the short leg under its spot: balanced over seeds against the scripted naive order (far + # spots first): its spot comes 1st / 2nd / 3rd / 4th in that order for exactly 5 of every 20 consecutive seeds + order = self._far_first(spot_of, side, tx, ty) + pos = int((int(seed) * 7) % 20 // 5) + heavy = order[pos] + short = spot_of[heavy] + slots = [int(v) for v in rng.permutation(4)] + start = {} + for i in range(4): + x, y = self._supply(side, tx, ty, slots[i]) + start[COLOURS[i]] = [x + float(rng.uniform(-0.006, 0.006)), y + float(rng.uniform(-0.006, 0.006))] + mass = {c: float(rng.uniform(*LIGHT_MASS)) for c in COLOURS} + com = {c: float(rng.uniform(*LIGHT_COM)) for c in COLOURS} + mass[heavy] = float(rng.uniform(*HEAVY_MASS)) + com[heavy] = float(rng.uniform(*HEAVY_COM)) + return dict(seed=int(seed), table_xy=[tx, ty], short_leg=int(short), short_corner=CORNER_NAME[CORNERS[short]], + heavy=heavy, heavy_rank_naive=pos + 1, spot_of=spot_of, supply_side=side, start=start, mass=mass, + com=com, short_h=float(rng.uniform(*SHORT_H)), com_bias=COM_BIAS, + yaw0={c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS}, + naive_bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + k = inst["short_leg"] + h = float(inst["short_h"]) + for j, g in enumerate(self.leg_gid): + m.geom_size[g] = self.leg_size0[j] + m.geom_pos[g] = self.leg_pos0[j] + g = self.leg_gid[k] + m.geom_size[g][1] = self.leg_size0[k][1] - h / 2 # capsule half length + m.geom_pos[g][2] = self.leg_pos0[k][2] + h / 2 + opp = CORNERS[(k + 2) % 4] + b = float(inst.get("com_bias", COM_BIAS)) / np.sqrt(2) + m.body_ipos[self.tbid] = [opp[0] * b, opp[1] * b, self.tbl_ipos0[2]] + envs.refit_bounds(m, self.tbid) + for c in COLOURS: + m.geom_rgba[self.spot_gid[inst["spot_of"][c]]] = SPOT_RGBA[c] + for c, bot in zip(COLOURS, BOTTLES): + bid = self.bbid[bot] + M, zc = inst["mass"][c], inst["com"][c] + m.body_mass[bid] = M + m.body_ipos[bid] = [0.0, 0.0, -H_TOT / 2 + zc] + # glass shell + internal weight, roughly: radius of gyration ~ 0.35 x height about horizontal axes + ixx = M * ((2 * RB) ** 2 / 12 + (0.35 * H_TOT) ** 2) + m.body_inertia[bid] = [ixx, ixx, M * (2 * RB) ** 2 / 6] + envs.refit_bounds(m, bid) + m.dof_damping[self.dof[bot]:self.dof[bot] + 6] = BOT_DAMP + self.env.sim.forward() + tx, ty = inst["table_xy"] + # yaw pi: the canonical quaternion LIBERO gives generated objects is a 180 deg yaw (envs.canonical_quat); with + # it the table frame is the world frame + envs.place_upright(self.env, TABLE, [tx, ty], yaw=np.pi, clearance=0.0003) + for c, bot in zip(COLOURS, BOTTLES): + envs.place_upright(self.env, bot, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + self.env.sim.data.qvel[self.tbl_dof:self.tbl_dof + 6] = 0.0 + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = WobblySkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + self._held_prev = None + self.table0 = dict(pos=self.table_pos().tolist(), yaw=self.table_yaw()) + n = len(BOTTLES) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + lost_cause=[None] * n, last_robot=[None] * n, last_obj=[None] * n, last_release=None, + last_table_touch=-10 ** 6, rocked=False, rock_since=0, rocks=[], n_steps=0, + max_table_tilt_deg=0.0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def table_R(self): + return self.env.sim.data.body_xmat[self.tbid].reshape(3, 3).copy() + + def table_pos(self): + return self.env.sim.data.body_xpos[self.tbid].copy() + + def table_yaw(self): + R = self.table_R() + return float(np.arctan2(R[1, 0], R[0, 0])) + + def table_tilt(self): + return float(np.arccos(np.clip(self.table_R()[2, 2], -1, 1))) + + def top_point(self, local_xy): + """world position of a point on the table's top surface (table frame xy)""" + return self.table_pos() + self.table_R() @ np.array([local_xy[0], local_xy[1], TABLE_H / 2]) + + def spot_local(self, colour): + sx, sy = CORNERS[self.inst["spot_of"][colour]] + return np.array([sx * SPOT_O, sy * SPOT_O]) + + def spot_world(self, colour): + return self.top_point(self.spot_local(colour)) + + def top_z_at(self, xy): + """z of the table's top plane above world point xy""" + R, p = self.table_R(), self.table_pos() + n = R[:, 2] + c = p + n * TABLE_H / 2 + return float(c[2] - (n[0] * (xy[0] - c[0]) + n[1] * (xy[1] - c[1])) / max(n[2], 1e-6)) + + def over_table(self, xy): + loc = self.table_R().T @ (np.array([xy[0], xy[1], self.table_pos()[2]]) - self.table_pos()) + return abs(loc[0]) < TOP_HW and abs(loc[1]) < TOP_HW + + def bR(self, b): + return self.env.sim.data.body_xmat[self.bbid[b]].reshape(3, 3).copy() + + def bpos(self, b): + return self.env.sim.data.body_xpos[self.bbid[b]].copy() + + def foot(self, b): + """world position of the centre of the bottle's bottom face""" + return self.bpos(b) - self.bR(b)[:, 2] * H_TOT / 2 + + def tilt(self, b): + return float(np.arccos(np.clip(self.bR(b)[2, 2], -1.0, 1.0))) + + def cap_xyz(self, b): + return self.env.sim.data.geom_xpos[self.cap_gid[b]].copy() + + def held(self, b): + return self.sk is not None and self.sk.holding(b) + + def offset(self, i): + """bottle i's foot centre relative to its spot centre, in the table frame (x forward-back, y left-right), and + the height of its bottom above the table top""" + b, c = BOTTLES[i], COLOURS[i] + loc = self.table_R().T @ (self.foot(b) - self.table_pos()) + return loc[:2] - self.spot_local(c), float(loc[2] - TABLE_H / 2) + + def on_spot(self, i, extra=0.0): + b = BOTTLES[i] + if self.tilt(b) > TILT_OK + (np.radians(2.0) if extra else 0.0): + return False + off, dz = self.offset(i) + if abs(off[0]) > TOL_X + extra or abs(off[1]) > TOL_Y + extra or abs(dz) > ON_TOP: + return False + return not self.held(b) + + def stages(self): + return [self.on_spot(i) for i in range(len(BOTTLES))] + + def table_ok(self): + p0 = np.asarray(self.table0["pos"]) + moved = float(np.linalg.norm(self.table_pos()[:2] - p0[:2])) + dyaw = abs(_ang(self.table_yaw() - self.table0["yaw"])) + return bool(moved <= TABLE_MOVE_TOL and dyaw <= TABLE_YAW_TOL and self.table_tilt() <= TABLE_TILT_MAX), moved, dyaw + + def low_corner(self): + """robot-centric name of the table corner that is lowest (after a rock: the corner over the short leg)""" + zs = {k: self.top_point([sx * TOP_HW, sy * TOP_HW])[2] for k, (sx, sy) in enumerate(CORNERS)} + return CORNER_NAME[CORNERS[min(zs, key=zs.get)]] + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = int(self.sk.n_steps) + rob, obj, tbl = dict(self._sub_rob), dict(self._sub_obj), self._sub_tbl + self._sub_rob, self._sub_obj, self._sub_tbl = {}, {}, 0 + gstate = "open" if self.sk.grip < 0 else "closed" + held_now = None + for c, b in zip(COLOURS, BOTTLES): + if gstate == "closed" and self.held(b): + held_now = c + for i, part in rob.items(): + if COLOURS[i] != held_now: + mon["last_robot"][i] = [{1: "finger", 2: "hand", 3: "arm"}[part], t, gstate] + for i, j in obj.items(): + mon["last_obj"][i] = [COLOURS[j], t] + if tbl: + mon["last_table_touch"] = t + if held_now is None and self._held_prev is not None: # the gripper has just let go of a bottle + mon["last_release"] = [self._held_prev, t] + self._held_prev = held_now + tl = self.table_tilt() + mon["max_table_tilt_deg"] = max(mon["max_table_tilt_deg"], round(float(np.degrees(tl)), 2)) + if mon["n_steps"] % 2: + return + # ---- table rock detector (debounced) + want = tl > ROCK_ON if not mon["rocked"] else tl > ROCK_OFF + if want != mon["rocked"]: + mon["rock_since"] += 2 + if mon["rock_since"] >= 4: + mon["rocked"] = want + mon["rock_since"] = 0 + self._rock_event(want, t - 3) + else: + mon["rock_since"] = 0 + for r in mon["rocks"]: + if not r.get("closed") and t - r["step"] > FELL_WINDOW: + self._close_rock(r) + # ---- stage predicates + for i in range(len(BOTTLES)): + b = BOTTLES[i] + raw = self.on_spot(i, HYST if mon["state"][i] else 0.0) + if raw == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 2 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw + mon["raw_since"][i] = 0 + t0 = int(t - DEBOUNCE + 1) + if raw: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t0) + mon["lost_cause"][i] = cause + off, dz = self.offset(i) + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause, + tilt_deg=round(float(np.degrees(self.tilt(b))), 1), + offset_cm=[round(100 * float(v), 1) for v in off])) + + def _rock_event(self, down, t): + mon = self.mon + rel = mon["last_release"] + e = dict(event="table_rocked" if down else "table_rocked_back", step=int(t), + table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), low_corner=self.low_corner(), + released=rel[0] if rel is not None and t - rel[1] <= 40 else None, + robot_touched_table=bool(t - mon["last_table_touch"] <= 20), + standing=[COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i]]) + # the cheap explanation would be "my hand bumped them": which of the standing bottles did the robot touch in + # the 2 s before the rock (should be none) + e["robot_touched_before"] = [COLOURS[i] for i in range(len(BOTTLES)) if mon["state"][i] and + mon["last_robot"][i] is not None and t - mon["last_robot"][i][1] <= 40] + mon["events"].append(e) + mon["rocks"].append(dict(step=int(t), down=bool(down), standing=list(e["standing"]), event=e)) + + def _close_rock(self, r): + """FELL_WINDOW after a rock: which of the bottles that stood on their spots fell, and did the robot touch any + of them after the rock began (a falling bottle hitting the open fingers)""" + r["closed"] = True + mon = self.mon + fell, touched = [], [] + for c in r["standing"]: + i = COLOURS.index(c) + if self.tilt(BOTTLES[i]) > np.radians(30) or not mon["state"][i]: + fell.append(c) + lr = mon["last_robot"][i] + if lr is not None and lr[1] >= r["step"]: + touched.append(c) + r["event"]["fell"] = fell + r["event"]["robot_touched_while_falling"] = touched + r["fell"] = fell + + def _cause(self, i, t, window=60): + if self.held(BOTTLES[i]): + return "picked_up" + mon = self.mon + for r in reversed(mon["rocks"]): + if 0 <= t - r["step"] <= FELL_WINDOW + 10 and COLOURS[i] in r["standing"]: + return "table_rocked" if r["down"] else "table_rocked_back" + lr, lo = mon["last_robot"][i], mon["last_obj"][i] + cands = [] + if lr is not None and t - lr[1] <= window: + cands.append((lr[1], f"robot_{lr[0]}")) + if lo is not None and t - lo[1] <= window: + cands.append((lo[1] - 30, "bottle:" + lo[0])) + return max(cands)[1] if cands else "other" + + def _finalize_monitor(self, raw): + mon = self.mon + if mon is None: + return + for r in mon["rocks"]: + if not r.get("closed"): + self._close_rock(r) + t = int(self.sk.n_steps) + for i in range(len(BOTTLES)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + else: + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + for j in range(d.ncon): + c = d.contact[j] + if (self.owner[c.geom1] >= 0 and self.part[c.geom2]) or (self.owner[c.geom2] >= 0 and self.part[c.geom1]): + return True + return False + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {b: self.bpos(b) for b in BOTTLES} + t0 = self.table_pos() + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max([float(np.linalg.norm(self.bpos(b) - p0[b])) for b in BOTTLES] + + [float(np.linalg.norm(self.table_pos() - t0))]) + static = moved < 0.003 + raw = self.stages() + self._finalize_monitor(raw) + held = [COLOURS[i] for i, b in enumerate(BOTTLES) if self.held(b)] + tok, tmoved, tyaw = self.table_ok() + mon = self.mon + ev = list(mon["events"]) + rocks = [r for r in mon["rocks"] if r["down"]] + damaging = [r for r in mon["rocks"] if r.get("fell")] + n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev) + n_lost = sum(e.get("event") == "lost" for e in ev) + n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev) + success = bool(all(raw) and static and not held and not touching and tok) + tilted = [i for i in range(len(BOTTLES)) if self.tilt(BOTTLES[i]) > TILT_OK and COLOURS[i] not in held] + ever = mon["ever"] + fell_by_rock = sorted({c for r in damaging for c in r["fell"]}) + if success: + failure = "none" + elif not tok: + failure = "table_moved" + elif held: + failure = "held" + elif tilted: + failure = "toppled_by_rock" if any(COLOURS[i] in fell_by_rock for i in tilted) else "toppled" + elif not all(raw): + failure = "not_on_spot" + elif touching: + failure = "touching" + else: + failure = "not_static" + parts = [] + if success: + parts.append("Every bottle stands upright on the spot of its colour.") + for i in range(len(BOTTLES)): + if raw[i]: + continue + c, b = COLOURS[i], BOTTLES[i] + if c in held: + parts.append(f"The {c} bottle is still held by the gripper.") + continue + off, dz = self.offset(i) + tl = float(np.degrees(self.tilt(b))) + on_small = abs(dz) < 0.05 and max(abs(off + self.spot_local(c))) < TOP_HW + 0.02 + if tl > np.degrees(TILT_OK): + txt = (f"The {c} bottle lies on its side on the {'small' if on_small else 'big'} table" if tl > 45 else + f"The {c} bottle leans {tl:.0f} degrees") + "." + elif abs(dz) > ON_TOP: + txt = f"The {c} bottle is not on the small table." + else: + txt = f"The {c} bottle stands {_fb(off[0])} and {_lr(off[1])} of its spot's centre, not on its spot." + if ever[i] and c in fell_by_rock: + txt += " It had stood on its spot and fell when the small table rocked." + elif ever[i]: + txt += " It had stood on its spot earlier." + parts.append(txt) + if not tok: + parts.append(f"The small table was moved ({100 * tmoved:.1f} cm, {np.degrees(tyaw):.0f} degrees).") + elif not success and all(raw): + if touching: + parts.append("The gripper is still touching a bottle.") + elif not static: + parts.append("Something was still moving.") + if rocks: + r = rocks[0]["event"] + txt = (f"When the {r['released']} bottle was set down, the small table rocked down onto its " + f"{r['low_corner']} leg" if r.get("released") else + f"The small table rocked down onto its {r['low_corner']} leg") + fl = r.get("fell", []) + txt += (" and the " + " and ".join(fl) + f" bottle{'s' if len(fl) > 1 else ''} standing on it fell over." + if fl else ".") + txt += f" That leg is {100 * float(inst['short_h']):.1f} cm shorter than the other three." + parts.append(txt) + trap = bool(damaging) + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(BOTTLES))}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_rocks=len(rocks), + rocked=bool(rocks), trap_fired=trap, recovered_in_attempt=bool(trap and success), + fell_by_rock=fell_by_rock, failure=failure, held=held, touching=bool(touching), + static=bool(static), table_ok=bool(tok), table_moved_cm=round(100 * tmoved, 2), + table_tilt_deg=round(float(np.degrees(self.table_tilt())), 2), + max_table_tilt_deg=mon["max_table_tilt_deg"], + offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)[0]] for i in range(4)}, + tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(BOTTLES[i]))), 1) for i in range(4)}, + heavy=inst["heavy"], short_corner=inst["short_corner"], detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted primitives (move_to + gripper only) + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _lift_to(self, z, speed=0.2): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def _settle(self, b, max_checks=25): + d = self.env.sim.data + da = self.dof[b] + for _ in range(max_checks): + if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2: + return + self.sk.hold(2) + + def upright(self, b): + return self.tilt(b) < np.radians(20) + + def pick_neck(self, b, z_carry=Z_CARRY, yaw=0.0, v=0.2): + """Sonnet-like top-down pick of a standing bottle: open, over it at carry height, straight down to the upper + neck, close, lift to carry height. Returns True if held.""" + sk = self.sk + self._settle(b) + p = self.foot(b) + zg = p[2] + NECK_Z[1] - GRASP_NECK + sk.set_gripper(False, steps=8) + self._lift_to(z_carry) + self._go([p[0], p[1], TZ + z_carry], yaw=yaw, speed=v) + self._go([p[0], p[1], zg + 0.02], speed=0.12) + self._go([p[0], p[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + self._go([p[0], p[1], TZ + z_carry], speed=0.12) + sk.hold(5) + if not self.held(b): + sk.set_gripper(False, steps=8) + return False + return True + + def put_held(self, b, xy, gap, z_carry=Z_CARRY, yaw=None, v=0.2): + """carry the held bottle so that its foot is over world xy, straight down until its bottom is `gap` above the + surface below, let go, lift""" + sk = self.sk + rel = self.foot(b)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + self._go([q[0], q[1], TZ + z_carry], yaw=yaw, speed=v) + sk.hold(10) + rel = self.foot(b)[:2] - sk.eef_pos()[:2] # a bottle hanging from its stopper swings while carried + q = np.asarray(xy, float) - rel + surf = self.top_z_at(xy) if self.over_table(xy) else TZ + dz = sk.eef_pos()[2] - self.foot(b)[2] + zr = surf + dz + gap + self._go([q[0], q[1], zr + 0.02], speed=0.10) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.hold(4) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.10) + self._go([cur[0], cur[1], TZ + z_carry], speed=0.2) + sk.hold(3) + + def surface_z(self, xy): + return self.top_z_at(xy) if self.over_table(xy) else TZ + + def pick_stopper(self, b, v=0.15): + """grasp a lying (or leaning) bottle by its round stopper from above, fingers across the bottle's axis, lift it + until it hangs free. The fingertips stay >= 4 mm above the surface under the stopper: pressing the raised half + of the rocked table rocks it back (measured), and the knock when it comes down again topples standing bottles. + Returns True if held.""" + sk = self.sk + self._settle(b) + for _ in range(2): + k, zg, yaw = self.stopper_grasp(b) # fingers across the bottle's axis + sk.set_gripper(False, steps=8) + self._lift_to(Z_HANG) + self._go([k[0], k[1], TZ + Z_HANG], yaw=yaw, speed=v) + sk.hold(5) + k, zg, _ = self.stopper_grasp(b) + self._go([k[0], k[1], zg + 0.03], speed=0.10) + self._go([k[0], k[1], zg], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([k[0], k[1], zg + 0.08], speed=0.1) + continue + self._go([k[0], k[1], zg + 0.05], speed=0.05) + self._go([k[0], k[1], TZ + Z_HANG], speed=0.10) + sk.hold(20) + return True + return False + + # gripper footprint (measured, t8_hand): the hand's collision hull is a slab 20 cm along the finger axis and ~4 cm + # 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 + # the grasp point to 4.5 cm above it + HAND_U, HAND_V, HAND_Z0 = 0.100, (-0.018, 0.024), 0.03 + FING_U, FING_V, FING_Z = (0.039, 0.066), (-0.009, 0.013), (-0.010, 0.045) + # wrist and forearm (t16_arm, measured at low grasps): lowest point above the grasp point vs the distance from the + # grasp point towards the robot base; they span ~13 cm to either side of that line + ARM_D = (-0.05, 0.05, 0.10, 0.15, 0.20) + ARM_Z = (0.097, 0.100, 0.155, 0.185, 0.31) + ARM_LAT = 0.13 + + def _footprint(self, q, yaw): + """sample points (xy) of the hand slab and of the open fingers for a grasp at q with gripper yaw `yaw`""" + a = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis + c = np.array([np.cos(yaw), np.sin(yaw)]) + hand = [q + u * a + v * c for u in np.linspace(-self.HAND_U, self.HAND_U, 21) + for v in np.linspace(*self.HAND_V, 5)] + fing = [q + sg * u * a + v * c for sg in (-1, 1) for u in np.linspace(*self.FING_U, 4) + for v in np.linspace(*self.FING_V, 3)] + return np.array(hand), np.array(fing) + + def grasp_clearance(self, q, zg, yaw, ignore=()): + """smallest horizontal clearance (m) between the hand / open fingers of a grasp at (q, zg) and any standing + bottle (other than `ignore`) or the small table; negative = collision""" + q = np.asarray(q, float)[:2] + hand, fing = self._footprint(q, yaw) + best = 1.0 + for b in BOTTLES: + if b in ignore or self.held(b) or self.tilt(b) > np.radians(30): + continue + p = self.foot(b)[:2] + top = self.foot(b)[2] + H_TOT + r = RB * 1.42 + if top > zg + self.HAND_Z0: + best = min(best, float(np.min(np.linalg.norm(hand - p, axis=1))) - r) + best = min(best, float(np.min(np.linalg.norm(fing - p, axis=1))) - r) + # the wrist / forearm sloping back towards the robot base over a tall standing bottle + ub = np.array([-0.66, 0.0]) - q + ub /= max(float(np.linalg.norm(ub)), 1e-6) + along, lat = float((p - q) @ ub), float((p - q) @ np.array([-ub[1], ub[0]])) + if self.ARM_D[0] <= along <= self.ARM_D[-1] and abs(lat) < self.ARM_LAT + r: + if top > zg + float(np.interp(along, self.ARM_D, self.ARM_Z)) - 0.01: + best = min(best, -0.01) + # the small table's top plate (and legs) when the grasp is below its top surface + R, P = self.table_R(), self.table_pos() + ztop = P[2] + TABLE_H / 2 + for pts, z0, z1 in ((hand, zg + self.HAND_Z0, zg + 0.13), (fing, zg + self.FING_Z[0], zg + self.FING_Z[1])): + if z0 > ztop + 0.003: + continue + loc = (pts - P[:2]) @ R[:2, :2] + if z1 > ztop - TOP_T: # the plate's height band + d = np.maximum(np.abs(loc) - TOP_HW, 0.0) + inside = np.all(np.abs(loc) < TOP_HW, axis=1) + dist = np.where(inside, -0.01, np.linalg.norm(d, axis=1)) + best = min(best, float(np.min(dist))) + return best + + def stopper_grasp(self, b): + """(xy, z, yaw) of the stopper grasp of a lying bottle: fingers across its axis, fingertips >= 4 mm above the + surface below""" + k = self.cap_xyz(b) + ax = self.bR(b)[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw + zg = max(float(k[2]), self.surface_z(k[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004) + return k[:2], zg, yaw + + def body_grasp(self, b, along=None): + """(xy, z, yaw) of a grasp across a lying bottle's body, `along` m from its bottom (default: the middle)""" + R = self.bR(b) + a = HF + (HB - HF) / 2 if along is None else float(along) + c = self.foot(b) + R[:, 2] * a + ax = R[:2, 2] + yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else self.sk.yaw + zg = max(float(c[2]), self.surface_z(c[:2]) + envs.FINGERTIP_BELOW_SITE + 0.004) + return c[:2], zg, yaw + + def staging_spot(self, b): + """a free place on the main table to lay a fallen bottle down: far from the small table and the other bottles, + within the arm's comfortable reach""" + tx, ty = self.table_pos()[:2] + best, bq = -1.0, None + for x in np.arange(tx - 0.30, tx + 0.06, 0.03): + for y in np.arange(ty - 0.30, ty + 0.31, 0.03): + # within reach, and >= 14 cm inside the main table's edges (it spans x, y = +-0.5, +-0.6): a bottle laid + # down too close to the near edge rolled off onto the floor (measured) + 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: + continue + loc = self.table_R()[:2, :2].T @ (np.array([x, y]) - np.array([tx, ty])) + dt = float(np.linalg.norm(np.maximum(np.abs(loc) - TOP_HW, 0.0))) + if np.all(np.abs(loc) < TOP_HW): + continue + do = min([float(np.linalg.norm(self.foot(o)[:2] - [x, y])) for o in BOTTLES if o != b] + + [float(np.linalg.norm(self.cap_xyz(o)[:2] - [x, y])) for o in BOTTLES if o != b]) + sc = min(dt - 0.10, do - 0.14) # the bottle lies ~16 cm long around the point + if sc > best and min(self.grasp_clearance([x, y], TZ + 0.016, yw, ignore=(b,)) + for yw in (0.0, np.pi / 2)) > 0.01: + best, bq = sc, np.array([x, y]) + return bq + + def stage(self, b, v=0.12): + """the stopper of a fallen bottle cannot be reached: grasp its body at a point where the hand is clear (the + bottle then hangs from the grasp), carry it to free space on the main table, let it down there so that it falls + over away from everything. Returns True if it was moved.""" + sk = self.sk + for along in (0.055, 0.035, 0.075, 0.015, 0.095): + q, zg, yaw = self.body_grasp(b, along) + if self.grasp_clearance(q, zg, yaw, ignore=(b,)) >= 0.004: + break + else: + return False + dst = self.staging_spot(b) + if dst is None: + return False + sk.set_gripper(False, steps=8) + self._lift_to(Z_CARRY) + self._go([q[0], q[1], TZ + Z_CARRY], yaw=yaw, speed=v) + self._go([q[0], q[1], zg + 0.03], speed=0.10) + self._go([q[0], q[1], zg], speed=0.03, tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + if not self.held(b): + sk.set_gripper(False, steps=8) + self._go([q[0], q[1], TZ + Z_CARRY], speed=0.1) + return False + self._go([q[0], q[1], zg + 0.04], speed=0.05) + self._go([q[0], q[1], TZ + Z_HANG], speed=0.10) + sk.hold(15) + self._go([dst[0], dst[1], TZ + Z_HANG], speed=0.10) + sk.hold(15) + drop = envs.obj_min_z(self.env, b) - (TZ + 0.012) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] - drop], speed=0.08) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_HANG], speed=0.15) + self._settle(b, 40) + return True + + def restand(self, i, gap=CAREFUL_GAP, err=None): + """stand bottle i up again on its spot: if the stopper cannot be grasped without the hand touching a standing + bottle or the small table, first lay the bottle down in free space; grasp the stopper, let the bottle hang, + carry it over the spot, lower it until its bottom is `gap` above the table top, let go""" + b, c = BOTTLES[i], COLOURS[i] + q, zg, yaw = self.stopper_grasp(b) + if self.grasp_clearance(q, zg, yaw, ignore=(b,)) < 0.005: + self.stage(b) + if not self.pick_stopper(b): + return False + tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0) + self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10) + self._settle(b) + return self.on_spot(i) + + def place(self, i, gap, err=None, z_carry=Z_CARRY, yaw=0.0, v=0.2): + """one stage: pick bottle i (by the neck if it stands, by the stopper if it lies) and put it on its spot""" + b, c = BOTTLES[i], COLOURS[i] + tgt = self.spot_world(c)[:2] + (np.asarray(err, float) if err is not None else 0.0) + if self.upright(b): + if not self.pick_neck(b, z_carry=z_carry, yaw=yaw, v=v) and not self.pick_neck(b, z_carry=z_carry, + yaw=yaw, v=v): + return False + self.put_held(b, tgt, gap, z_carry=z_carry, yaw=yaw, v=v) + else: + if not self.pick_stopper(b): + return False + self.put_held(b, tgt, gap, z_carry=Z_HANG, v=0.10) + self._settle(b) + return True + + def repair_order(self, idx): + """bottles to fix: one standing upright off its spot first (it may be the heavy one: re-placing it rocks the + table), then lying ones whose stopper is easiest to reach""" + def key(j): + b = BOTTLES[j] + if self.upright(b): + return (0, 0.0) + q, zg, yaw = self.stopper_grasp(b) + return (1, -self.grasp_clearance(q, zg, yaw, ignore=(b,))) + return sorted(idx, key=key) + + def fix(self, i, gap=CAREFUL_GAP): + if self.upright(BOTTLES[i]): + self.place(i, gap) + else: + self.restand(i, gap) + + def check_and_repair(self, rounds=3, gap=CAREFUL_GAP): + """look at every bottle; stand up / re-place every one that is not on its spot""" + for _ in range(rounds): + bad = [i for i in range(4) if not self.on_spot(i)] + if not bad: + return True + for i in self.repair_order(bad): + if not self.on_spot(i): + self.fix(i, gap) + return all(self.stages()) + + def order(self, mode, rng=None, first=None): + o = self._far_first(self.inst["spot_of"], self.inst["supply_side"], *self.inst["table_xy"]) + if mode == "near_first": + o = o[::-1] + elif mode == "random": + o = [o[j] for j in rng.permutation(4)] + if first is not None: + o = [first] + [c for c in o if c != first] + return [COLOURS.index(c) for c in o] + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + order = self.order(params.get("order", "far_first"), rng, params.get("first")) + gap = params.get("gap") # None: random in NAIVE_GAP per placement + bias = np.array([float(params.get("bias_x", 0.0)), 0.0]) + rand = float(params.get("rand", 0.0)) + for i in order: + g = float(rng.uniform(*NAIVE_GAP)) if gap is None else float(gap) + e = bias + (rng.uniform(-rand, rand, 2) if rand else 0.0) + self.place(i, g, err=e, z_carry=params.get("z_carry", Z_CARRY), v=params.get("v", 0.2)) + if params.get("repair") == "each": # looks at all bottles after every step and stands fallen ones up + for _ in range(2): + bad = [j for j in range(4) if self.mon["ever"][j] and not self.on_spot(j)] + for j in self.repair_order(bad): + if not self.on_spot(j): + self.fix(j) + if params.get("check"): + self.check_and_repair() + self._lift_to(Z_CARRY) + self.sk.hold(10) + + # naive = Sonnet-like habits (lh_nudge_row / lh_bystander pilots): careful, far spots first, carries high, vertical + # descent, releases 1-4 cm above the surface, places ~1-2 cm too far forward +- 0.6 cm, no special plan for the + # table, does not look back at the bottles it has already put down + def default_params(self, inst): + return dict(order="far_first", gap=None, bias_x=float(inst["naive_bias_x"]), rand=NAIVE_RAND, + noise_seed=int(inst["seed"]) * 13, repair=None, check=False) + + def oracle_params(self, inst): + """knows the short leg: puts the heavy bottle on its corner first (the table rocks while nothing stands on it), + sets the others down gently, checks at the end""" + return dict(order="far_first", first=inst["heavy"], gap=CAREFUL_GAP, bias_x=0.0, rand=0.0, repair="each", + check=True) + + def adapt_params(self, inst, history): + """attempt >= 2: the bottle whose placement rocked the table (from the event of the failed attempt) first; the + same imprecise habits otherwise; stands fallen bottles up and checks at the end""" + first = None + for h in history: + for e in h["outcome"].get("events", []): + if e.get("event") == "table_rocked" and e.get("released"): + first = e["released"] + break + if first: + break + return dict(self.default_params(inst), first=first, repair="each", check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with a random order and random variation, no history, no look back""" + return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)), + z_carry=float(rng.uniform(0.40, 0.45)), v=float(rng.uniform(0.12, 0.25)), + bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive: one attempt. adaptive: attempt 1 = naive + stands fallen bottles up after every step and checks + at the end; attempts >= 2: the rocking bottle first. blind: naive with a random order. + Extra kinds (controls): naive_heavy_first (naive habits, 1-4 cm drops, but the heavy bottle first), + naive_repair (= adaptive's first attempt), naive_near_first, switch (order change only, no repair), + oracle_noise (+-5 mm).""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + single = ("oracle", "naive", "naive_heavy_first", "naive_repair", "oracle_noise", "naive_near_first") + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "adaptive": + params = (dict(self.default_params(inst), repair="each", check=True) if a == 0 else + self.adapt_params(inst, history)) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + elif kind == "switch": + params = (self.default_params(inst) if a == 0 else + dict(self.adapt_params(inst, history), repair=None, check=False)) + elif kind == "naive_heavy_first": + params = dict(self.default_params(inst), first=inst["heavy"]) + elif kind == "naive_repair": + params = dict(self.default_params(inst), repair="each", check=True) + elif kind == "naive_near_first": + params = dict(self.default_params(inst), order="near_first") + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind in single: + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/agent_cost.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/agent_cost.py new file mode 100644 index 0000000000000000000000000000000000000000..03a49297e0ef82a9c466f2eb36c0de1b3769630f --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/agent_cost.py @@ -0,0 +1,77 @@ +"""Project GPT-6 cost / latency of a protocol from a run directory. + +Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made +with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES: + input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption) + cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) -- + the first call of an attempt is counted as uncached (conservative) + output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500) + latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input + tokens and high/xhigh effort -- treat as an upper-range planning number) +The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls). + + python scripts/agent_cost.py runs/agent/l5_slide_to_target/ --out-tokens 1500 --latency 20 --calls-scale 2 +""" +import argparse +import json +import os +import sys +from collections import defaultdict + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lffbench.agent.cost import PRICES, call_cost # noqa: E402 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("run_dir") + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--out-tokens", type=float, default=1500) + ap.add_argument("--latency", type=float, default=20.0) + ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)") + a = ap.parse_args() + ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))] + calls = [e for e in ev if e["type"] == "llm_call"] + runs = {e["seed"] for e in ev if e["type"] == "run_start"} + real = [c for c in calls if c.get("usage")] + if real and not any("dry_run_request" in c for c in calls): + cost = sum(call_cost(c["usage"], a.model) or 0 for c in real) + lat = [c["latency_s"] for c in real] + u = defaultdict(int) + for c in real: + for kk, v in c["usage"].items(): + u[kk] += v + out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1), + usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1), + latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1)) + else: + prev = {} + tot_in = tot_cached = 0 + cost1 = 0.0 # priced per call (the long-context surcharge applies per request) + for c in calls: + d = c.get("dry_run_request") + if not d: + continue + key = (c["seed"], c["attempt"]) + tin = d["est_input_tokens"] + cached = min(prev.get(key, 0), tin) + prev[key] = tin + tot_in += tin + tot_cached += cached + cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model) + n = len(calls) * a.calls_scale + scale = a.calls_scale + usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens) + cost = cost1 * scale + out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1), + input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1), + usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1), + api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model), + assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency, + calls_scale=a.calls_scale, image_tokens_512px=256)) + print(json.dumps(out, indent=1, default=str)) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/check_breakfast_geometry.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/check_breakfast_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..bb591b652e6beecfdd132163a5405f8253326029 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/check_breakfast_geometry.py @@ -0,0 +1,41 @@ +"""V2 physical height/orientation controls. Initialization interventions are diagnostics only.""" +import json +from pathlib import Path +from PIL import Image +from lffbench import envs +from lffbench.tasks.lh_breakfast_service import BreakfastService + +def main(): + out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/geometry_v2/geometry_controls' + out.mkdir(parents=True,exist_ok=True);rows=[];t=BreakfastService() + for seed in range(1000,1003): + inst=t.sample_instance(seed);t.reset_instance(inst);t.sk.correction=t.sk.bias.copy() + # Move bread clear only at diagnostic initialization, so the obstacle is unambiguous. + envs.set_obj_pose(t.env,'bread_1',[-.09,-.32,.94]);t.env.sim.forward() + def state(stage): + r=dict(seed=seed,stage=stage,lid_deg=t.lid_deg(),butter_height_cm=100*t.butter_height(), + butter_lid_contact=bool(t.butter_lid_contact()),butter_fits=t.butter_in_box(), + applied_torque=float(t.env.sim.data.qfrc_applied[t.dof])) + assert r['applied_torque']==0.,r + rows.append(r);print(json.dumps(r),flush=True) + Image.fromarray(envs.render(t.env,res=512)).save(out/f'{seed}_{stage}.png') + (out/'progress.json').write_text(json.dumps(rows,indent=2)) + return r + # Two empty-box closes prove that the removed closure-count mechanism does not reappear. + for cycle in range(2): + # Let the freely swinging open lid settle before targeting its knob again. + t.open_lid();t.sk.hold(100);t.close_lid(False);t.sk.hold(80) + r=state('empty_close_'+str(cycle+1));assert r['lid_deg']<4 + t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100) + r=state('upright_blocked') + assert r['lid_deg']>10 and r['butter_lid_contact'] and r['butter_height_cm']>7 and not r['butter_fits'],r + # Remove precisely that obstacle, leaving all geometry, forces and joint limits unchanged. + t.open_lid();assert t.pick_place('butter_1',inst['butter_xy'],t.butter_height()/2+.003) + t.close_lid(False);t.sk.hold(80);r=state('obstacle_removed');assert r['lid_deg']<4 + assert t.lay_butter_flat();r=state('laid_flat');assert r['butter_height_cm']<2.9 + t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100) + r=state('flat_inside_closed');assert r['lid_deg']<4 and r['butter_fits'] and not r['butter_lid_contact'],r + (out/'result.json').write_text(json.dumps(dict(passed=True,rows=rows),indent=2)) + t.env.close() + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/gptpolicy_player.sh b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/gptpolicy_player.sh new file mode 100644 index 0000000000000000000000000000000000000000..981bf8317324c0d141066500c27589092be46ddd --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/gptpolicy_player.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Drive one robot_server session with the GPT-Policy harness (frameworks/gpt-policy, simulated +# lffbench_sim adapter + OpenAI Responses provider, GPT-6 Astra, reasoning effort medium). +# +# usage: scripts/gptpolicy_player.sh /session.json [extra gpt-policy-lffbench options] +# e.g. LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10340 direct 3 gptpolicy rgb 1 +# scripts/gptpolicy_player.sh runs/claude/gptpolicy_l1_bias_place_s3000_..._p10340/session.json +# The robot_server interface (v1 / v2) is detected from the first status reply. +# +# Writes into the session's LOG directory: gptpolicy_transcript.jsonl (every model request/response, +# images as file paths + sha256, every robot-server call), final_report.md, gptpolicy_player.log and +# GPT-Policy's own recording gptpolicy_run_*/. The robot server writes events.jsonl and rollout.mp4. +# The server is stopped at the end (it has finished the episode, and rollout.mp4 is closed by then). +set -uo pipefail +[ $# -ge 1 ] || { echo "usage: $0 /session.json [options]"; exit 2; } +SESSION=$(readlink -f "$1"); shift +LOG=$(dirname "$SESSION") +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +[ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh" +# GPT-Policy checkout + venv from integrations/gpt-policy/setup.sh (override: GPTPOLICY_VENV) +VENV=${GPTPOLICY_VENV:-$ROOT/third_party/gpt-policy/.venv} +ENVF=${LFF_ENV_FILE:-$ROOT/.env} +[ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } # OPENAI_API_KEY / OPENAI_BASE_URL / SSL_CERT_FILE (never echoed) +export PYTHONUNBUFFERED=1 +stop_server() { # also on abnormal exit; SIGTERM makes the server close rollout.mp4 first + if [ "${GPTPOLICY_KEEP_SERVER:-0}" != "1" ] && [ -f "$LOG/server.pid" ]; then + kill "$(cat "$LOG/server.pid")" 2>/dev/null || true + fi +} +trap stop_server EXIT +trap 'exit 143' TERM INT HUP +cd /tmp # neutral working directory; the model has no file access anyway +"$VENV/bin/gpt-policy-lffbench" --session "$SESSION" --model "${GPTPOLICY_MODEL:-gpt-6-astra}" \ + --effort "${GPTPOLICY_EFFORT:-medium}" "$@" 2>&1 | tee -a "$LOG/gptpolicy_player.log" +RC=${PIPESTATUS[0]} +echo "gptpolicy_player.sh: gpt-policy-lffbench exit code $RC" >> "$LOG/gptpolicy_player.log" +exit $RC diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/headroom_parts_cart.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/headroom_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..752d1777e6d011bc7723334b8a0e332880ceaae3 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/headroom_parts_cart.py @@ -0,0 +1,19 @@ +"""Incremental physical headroom evaluation of the composite prototype.""" +import argparse,hashlib,json,time +from pathlib import Path +import numpy as np +from lffbench.tasks.lh_parts_cart import PartsCart + +def clean(x): + if isinstance(x,np.ndarray):return x.tolist() + if isinstance(x,np.generic):return x.item() + raise TypeError(type(x).__name__) +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() +out=Path(a.out);out.parent.mkdir(parents=True,exist_ok=True);x=PartsCart();rows=[];start=time.time() +source=Path(__file__).parents[1]/'lffbench/tasks/lh_parts_cart.py';code_hash=hashlib.sha256(source.read_bytes()).hexdigest() +for seed in range(1000,1000+a.n): + i=x.sample_instance(seed);h=x.run_scripted(a.kind,i,k=a.k,seed=seed) + rows.append(dict(seed=seed,history=h));succ=sum(any(z['outcome']['success'] for z in row['history']) for row in rows) + 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)) + print(seed,a.kind,[z['outcome']['success'] for z in h], 'successes',succ,flush=True) +x.env.close() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/lerobot_export.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/lerobot_export.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4fa0a1be92844c9cf410663f77de5e200bda18 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/lerobot_export.py @@ -0,0 +1,431 @@ +"""Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars. + +Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding +can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan): + + python scripts/lerobot_export.py plan --raw [,] --runs-root /runs/api \ + --paper --task-set /sets/main_v2_1inst.txt --work [--batches ...] [--limit N] + python scripts/lerobot_export.py shard --work --shard i --nshards N + python scripts/lerobot_export.py merge --work --nshards N --out + +Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0 +mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped. + +LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t): + observation.images.image agentview RGB 256x256 (upright; LIBERO naming) + observation.images.wrist_image wrist (eye-in-hand) RGB 256x256 + observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout) + observation.joint_pos / joint_vel 7 arm joints (rad, rad/s) + observation.eef_quat 4: xyzw; observation.gripper_width 1 (m) + action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad), + gripper (-1 open, +1 close) + annotation.attempt_index attempt (1-based) the frame belongs to + annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`) + annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action) + annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt + annotation.task_event number of task-monitor events (error / progress events) registered at this step +Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table), +runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state +per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/. +""" +import argparse +import glob +import json +import os +import re +import shutil +import time + +import numpy as np + +FPS = 20 +RES = 256 +BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke", + "cc_smoke", "cc_opus_smoke"] +BATCH_NOTES = { + "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog", + "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267", + "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299", + "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances", + "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)", + "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the " + "with-history continuation of failed runs is incomplete", + "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early", + "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt", + "cc_opus_smoke": "smoke test: single attempt", +} +PHASES = {"move": 0, "gripper": 1, "judge": 2} +CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)", + "L2": "disturbed state to restore (incl. damage the agent causes)", + "L3": "infeasible manipulation strategy (grasp / contact / tool must change)", + "L4": "misjudged geometry (size, shape, fit, hidden structure)", + "L5": "misjudged physics (mass distribution, friction, dynamics)"} + + +def features(): + vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]} + f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names} + i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None} + return { + "observation.images.image": vid(), + "observation.images.wrist_image": vid(), + "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", + "finger_qpos_left", "finger_qpos_right"]), + "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]), + "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]), + "observation.gripper_width": f32(1, ["width_m"]), + "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", + "eef_delta_rot_aa_z", "gripper_close"]), + "annotation.attempt_index": i64(), + "annotation.command_index": i64(), + "annotation.phase": i64(), + "annotation.attempt_success": i64(), + "annotation.task_event": i64(), + } + + +# ------------------------------------------------------------------------------------------------ paper metadata + +def _clean_tex(s): + s = re.sub(r"%.*", "", s) + for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"), + (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"), + (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"), + (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"), + (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]: + s = re.sub(a, b, s) + s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s) + s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s) + for _ in range(3): + s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\$([^$]*)\$", r"\1", s) + s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ") + s = re.sub(r"\{([^{}]*)\}", r"\1", s) + s = re.sub(r"\\[a-zA-Z]+\*?", "", s) + return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip() + + +def paper_tasks(paper_dir): + """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the + paper's task table and task appendix (empty if the paper sources are not there).""" + out = {} + if not paper_dir: + return out + app = os.path.join(paper_dir, "sections", "appendix_tasks.tex") + tab = os.path.join(paper_dir, "sections", "tab_tasks.tex") + if os.path.exists(app): + txt = open(app).read() + parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt) + for i in range(1, len(parts) - 1, 2): + if parts[i] != "\\paragraph{": + continue + body = parts[i + 1] + m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S) + if not m: + continue + name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip() + desc = _clean_tex(body[m.end():]) + out[code] = dict(name=name, cause=_clean_tex(cause), description=desc) + if os.path.exists(tab): + names = {v["name"].lower(): k for k, v in out.items()} + for line in open(tab): + cells = [c.strip() for c in line.split("&")] + if len(cells) != 6 or not cells[-1].endswith("\\\\"): + continue + nm = re.sub(r"\\contscene", "", cells[0]).strip().lower() + code = names.get(nm) + if not code: + continue + out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]), + repair_within_attempt=_clean_tex(cells[3]) == "yes", + oracle_first_attempt_pct=_clean_tex(cells[4]), + naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip())) + return out + + +# ------------------------------------------------------------------------------------------------ collection + +def manifest_status(runs_root, batch, run, cache={}): + if batch not in cache: + p = os.path.join(runs_root, batch, "manifest.json") + cache[batch] = json.load(open(p)) if os.path.exists(p) else {} + m = cache[batch] + for r in m.get("runs", []): + if r.get("run") == run: + return r.get("status", "?"), r + for r in m.get("superseded", []): + if r.get("run") == run: + return "superseded_" + str(r.get("status", "?")), r + return "not_in_manifest", {} + + +def collect(raw_roots, runs_root, batches, task_order): + """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root.""" + eps, rejected, seen = [], [], set() + for root in raw_roots: + for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))): + rep = json.load(open(rj)) + batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"] + if (batches and batch not in batches) or (batch, run) in seen: + continue + seen.add((batch, run)) + ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff") + status, entry = manifest_status(runs_root, batch, run) + if not ok: + never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked") + rejected.append(dict(run=run, batch=batch, run_status=status, + reason="run never started (no contract, no robot command)" if never else + "replay does not reproduce the log (the log has gaps or the replay diverged)", + detail=rep.get("first_mismatches"))) + continue + for ep in rep.get("episodes", []): + d = os.path.join(root, ep["dir"]) + ann = json.load(open(os.path.join(d, "annotation.json"))) + judged = [a for a in ann["attempts"] if a.get("success") is not None] + if not judged or ep["n_frames"] == 0: + rejected.append(dict(run=run, batch=batch, episode=ep["dir"], + reason="no judged attempt" if not judged else "no frames")) + continue + ann["source"]["run_status"] = status + ann["source"]["manifest_id"] = entry.get("id") + ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"], + max_eef_dev_m=rep["max_eef_dev_m"]) + key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99), + {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2), + ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"]) + eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann)) + eps.sort(key=lambda x: x["key"]) + return eps, rejected + + +# ------------------------------------------------------------------------------------------------ writing + +def frames_of(path): + import av + with av.open(path) as c: + for fr in c.decode(video=0): + yield fr.to_ndarray(format="rgb24") + + +def flat_row(i, ann, n, idx0): + s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"] + att = ann["attempts"] + a0 = att[0] + return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n, + batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"], + memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"), + episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att], + harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"), + effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"), + task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"), + category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"], + success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att], + feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att], + auto_ended=[a.get("auto_ended") for a in att], + corrected_later_in_run=[a.get("corrected_later_in_run") for a in att], + error_event_in_attempt=[a.get("error_event_in_attempt") for a in att], + run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"), + n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]), + first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None) + + +def cmd_plan(a): + task_order = {} + if a.task_set and os.path.exists(a.task_set): + for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")): + task_order[line.split(":")[0].strip()] = i + batches = [b for b in a.batches.split(",") if b] if a.batches else None + eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order) + if a.limit: + eps = eps[:a.limit] + paper = paper_tasks(a.paper) + idx0 = 0 + for i, e in enumerate(eps): + ann = e["ann"] + tname = ann["task"]["name"] + if tname in paper: + ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"} + ann["episode_index"] = i + ann["dataset_index_range"] = [idx0, idx0 + e["n"]] + e["index"], e["from"] = i, idx0 + idx0 += e["n"] + del e["key"] + os.makedirs(a.work, exist_ok=True) + with open(os.path.join(a.work, "plan.json"), "w") as f: + json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f, + ensure_ascii=False) + print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True) + + +def shard_range(n_eps, i, k): + return (n_eps * i) // k, (n_eps * (i + 1)) // k + + +def cmd_shard(a): + from lerobot.datasets.lerobot_dataset import LeRobotDataset + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + lo, hi = shard_range(len(eps), a.shard, a.nshards) + out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}") + if os.path.exists(os.path.join(out, "DONE")): + print(f"shard {a.shard}: done already", flush=True) + return + shutil.rmtree(out, ignore_errors=True) + ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out, + robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads, + vcodec=a.vcodec) + nfr = 0 + for e in eps[lo:hi]: + d, ann, n = e["dir"], e["ann"], e["n"] + fr = np.load(os.path.join(d, "frames.npz")) + assert len(fr["action"]) == n, d + succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]} + evc = np.zeros(n, np.int64) + for ev in ann["task_events"]: + if 0 <= ev["frame"] < n: + evc[ev["frame"]] += 1 + state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32) + instr = ann["task"]["instruction"] + k = 0 + for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))): + if k >= n: + break + ds.add_frame({ + "observation.images.image": img, "observation.images.wrist_image": wr, + "observation.state": state[k], + "observation.joint_pos": fr["joint_pos"][k].astype(np.float32), + "observation.joint_vel": fr["joint_vel"][k].astype(np.float32), + "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32), + "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32), + "action": fr["action"][k].astype(np.float32), + "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64), + "annotation.command_index": np.array([fr["command"][k]], np.int64), + "annotation.phase": np.array([fr["phase"][k]], np.int64), + "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64), + "annotation.task_event": np.array([evc[k]], np.int64), + "task": instr, + }) + k += 1 + if k != n: + raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames") + ds.save_episode() + nfr += n + ds.finalize() + shutil.rmtree(os.path.join(out, "images"), ignore_errors=True) + open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n") + print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True) + + +def cmd_merge(a): + from pathlib import Path + from lerobot.datasets.aggregate import aggregate_datasets + t0 = time.time() + plan = json.load(open(os.path.join(a.work, "plan.json"))) + eps = plan["episodes"] + roots, ids = [], [] + for i in range(a.nshards): + lo, hi = shard_range(len(eps), i, a.nshards) + if hi <= lo: + continue + r = os.path.join(a.work, "shards", f"shard_{i:03d}") + if not os.path.exists(os.path.join(r, "DONE")): + raise SystemExit(f"shard {i} is not done") + roots.append(Path(r)) + ids.append(f"{plan['repo_id']}-shard{i:03d}") + if os.path.exists(a.out): + raise SystemExit(f"{a.out} exists; refusing to overwrite") + aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out)) + print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True) + write_sidecars(a, plan) + print(f"merge done in {time.time() - t0:.0f}s", flush=True) + + +def write_sidecars(a, plan): + eps, paper = plan["episodes"], plan["paper"] + lff = os.path.join(a.out, "lff") + for sub in ("annotations", "sim_state", "final", "code"): + os.makedirs(os.path.join(lff, sub), exist_ok=True) + rows, runs, tasks = [], {}, {} + for e in eps: + i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"] + name = f"episode_{i:06d}" + if os.path.exists(os.path.join(d, "sim_state.npy")): + shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy")) + shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz")) + for cam, key in (("agentview", "image"), ("wrist", "wrist_image")): + shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png")) + with open(os.path.join(lff, "annotations", name + ".json"), "w") as f: + json.dump(ann, f, indent=1, ensure_ascii=False) + rows.append(flat_row(i, ann, n, e["from"])) + tname = ann["task"]["name"] + rk = (ann["source"]["batch"], ann["source"]["run"]) + r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"), + run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"], + memory_free_chain_of=ann["source"].get("memory_free_chain_of"), + memory_free_rep=ann["source"].get("memory_free_rep"), task=tname, + seed=ann["task"]["seed"], model=ann["agent"].get("model"), + harness=ann["agent"].get("harness"), + harness_version=ann["agent"].get("harness_version"), + codex_catalog=ann["agent"].get("codex_catalog"), + outcome_class=ann["run_outcome"].get("outcome_class"), + attempt_history=ann["run_outcome"].get("attempt_history"), + agent_final_report=ann["run_outcome"].get("agent_final_report"), + episodes=[])) + for x in ann["attempts"]: + r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success"))) + if tname not in tasks: + tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")} + if tname in paper: + tasks[tname]["paper"] = paper[tname] + tasks[tname]["instances"] = {} + tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"] + # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id) + by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")} + for r in runs.values(): + if r.get("memory_free_chain_of"): + r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"])) + for (b, rn), r in runs.items(): + r["memory_free_retries"] = sorted((x["run"] for x in runs.values() + if x["batch"] == b and x.get("memory_free_chain_of_run") == rn), + key=lambda q: runs[(b, q)].get("memory_free_rep") or 0) + with open(os.path.join(lff, "episodes.jsonl"), "w") as f: + for row in rows: + f.write(json.dumps(row, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "runs.jsonl"), "w") as f: + for r in runs.values(): + f.write(json.dumps(r, ensure_ascii=False) + "\n") + with open(os.path.join(lff, "tasks.json"), "w") as f: + json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False) + with open(os.path.join(lff, "batches.json"), "w") as f: + json.dump(BATCH_NOTES, f, indent=1) + with open(os.path.join(lff, "rejected.json"), "w") as f: + json.dump(plan["rejected"], f, indent=1) + here = os.path.dirname(os.path.abspath(__file__)) + for s in ("lerobot_replay.py", "lerobot_export.py"): + shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("step", choices=["plan", "shard", "merge"]) + ap.add_argument("--work", required=True) + ap.add_argument("--raw", default="") + ap.add_argument("--runs-root", default="") + ap.add_argument("--out", default="") + ap.add_argument("--paper", default="") + ap.add_argument("--task-set", default="") + ap.add_argument("--repo-id", default="lffbench/agent-replays") + ap.add_argument("--batches", default="") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--shard", type=int, default=0) + ap.add_argument("--nshards", type=int, default=1) + ap.add_argument("--threads", type=int, default=2) + ap.add_argument("--vcodec", default="libsvtav1") + a = ap.parse_args() + {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/make_dossier.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/make_dossier.py new file mode 100644 index 0000000000000000000000000000000000000000..b0b97724e0cc03cb852d8fc0ece158512e008827 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/make_dossier.py @@ -0,0 +1,103 @@ +"""Build the record of an earlier failed attempt for the full5 history arms (docs/14 §6). + + python scripts/make_dossier.py [--attempt 1] [--allow-success] + +The record contains only what the agent of that attempt saw: the starting images, every robot command with the +robot's reply (as logged by robot_server), the images those commands produced, the agent's closing remark and the +F1 verdict ("failed"). No outcome codes, measurements or hidden variables. The same builder is used for the own-history +arm (record of a failed independent run on the same instance) and the mismatched arm (record of a failed run on the +twin instance: same layout, different hidden variable), so the two dossiers differ only in content. +""" +import argparse +import json +import os +import shutil + +DROP = ("state_file", "attempt_ended", "camera_file") + + +def shell_args(args): + out = [] + for k, v in args.items(): + v = json.dumps(v) if not isinstance(v, str) else v + out.append(f'{k}="{v}"' if (" " in v or not v) else f"{k}={v}") + return " ".join(out) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("log") + ap.add_argument("out") + ap.add_argument("--attempt", type=int, default=1) + ap.add_argument("--allow-success", action="store_true") + ap.add_argument("--result-extra", default="", + help="layer-3 ladder (docs/20): text appended to the verdict in the Result section (paragraphs " + "separated by blank lines; the first one continues the verdict line). Empty = F1 record, " + "byte-identical to the record built without this option.") + a = ap.parse_args() + evs = [json.loads(line) for line in open(os.path.join(a.log, "events.jsonl")) if line.strip()] + start = next(e for e in evs if e["ev"] == "session_start") + if start.get("style", "la") not in ("la", None) and "style" in start: + raise SystemExit("only la-style runs are supported") + calls = [e for e in evs if e["ev"] == "call" and e.get("attempt") == a.attempt] + done = [e for e in evs if e["ev"] == "done" and e.get("attempt") == a.attempt] + if not done: + raise SystemExit(f"attempt {a.attempt} has no done event (run unfinished?)") + done = done[0] + if done["success"] and not a.allow_success: + raise SystemExit(f"attempt {a.attempt} succeeded; nothing to learn from (use --allow-success to force)") + imgs = os.path.join(a.log, "images") + # commands as that agent issued them: `./robot ` in a CLI workspace, the `robot` tool's argument otherwise + try: + iface = json.load(open(os.path.join(a.log, "agent_iface.json"))).get("agent_iface", "cli") + except OSError: + iface = "cli" + pre = "./robot " if iface == "cli" else "" + os.makedirs(os.path.join(a.out, "obs"), exist_ok=False) + + def copy(rel): + base = os.path.basename(rel) + src = os.path.join(imgs, f"a{a.attempt}_{base}") + if not os.path.exists(src): + return None + shutil.copy(src, os.path.join(a.out, "obs", base)) + return f"obs/{base}" + + # starting images: the first images the agent saw (status at step 0) + first = sorted(f for f in os.listdir(imgs) if f.startswith(f"a{a.attempt}_") and "s000_" in f) + start_imgs = [copy(f.split("_", 1)[1]) for f in first] + lines = ["# Record of the earlier attempt", "", + "Starting scene: " + ", ".join(p for p in start_imgs if p), "", + "## Robot commands and replies", ""] + rec = [] + for i, e in enumerate(calls, 1): + rep = {k: v for k, v in (e.get("report") or {}).items() if k not in DROP} + if "images" in rep: + rep["images"] = [p2 for p2 in (copy(p) for p in rep["images"]) if p2] + cmd = f"{pre}{e['cmd']} {shell_args(e.get('args') or {})}".strip() + lines += [f"{i}. `{cmd}`", " reply: `" + json.dumps(rep) + "`", ""] + rec.append(dict(n=i, command=cmd, reply=rep)) + lines += [f"{len(calls) + 1}. `{pre}finish reason=\"{done.get('reason', '')}\"`", "", + "## Closing remark of that attempt", "", str(done.get("reason", "")), "", + "## Result", ""] + verdict = "The environment judged that attempt: " + ("succeeded." if done["success"] else "failed.") + extra = [x.strip() for x in a.result_extra.split("\n\n") if x.strip()] + if extra: + verdict += " " + extra[0] + lines += [verdict, ""] + for x in extra[1:]: + lines += [x, ""] + with open(os.path.join(a.out, "README.md"), "w") as f: + f.write("\n".join(lines)) + with open(os.path.join(a.out, "record.jsonl"), "w") as f: + for r in rec: + f.write(json.dumps(r) + "\n") + with open(os.path.join(os.path.dirname(os.path.abspath(a.out)), os.path.basename(a.out) + ".source.json"), "w") as f: + json.dump(dict(log=os.path.abspath(a.log), attempt=a.attempt, task=start.get("task"), seed=start.get("seed"), + arm=start.get("arm", "none"), n_commands=len(calls), success=done["success"], + result_extra=a.result_extra), f) + print(json.dumps(dict(out=a.out, n_commands=len(calls), n_images=len(os.listdir(os.path.join(a.out, "obs")))))) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/mismatch_plan.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/mismatch_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..986d7fd5fef959b1b3f8e81170b90acb02fec62e --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/mismatch_plan.py @@ -0,0 +1,149 @@ +"""Mismatched-history control for layer 2 (user 2026-10-27: "错配历史的做一下"; design docs/14 §6 Do / Dm, current protocol). + +Instances: the 9 hidden-variable tasks that have a twin (l7_key_turn has none), every Claude main-table instance +(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. +Arms, all fresh single-attempt agents (= the memory-free retries of the main table) with the same model and CLI: + tw_ twin instance (--arm twin: same layout, the hidden variable takes another value); its failed run is the + mismatched record. If the twin attempt succeeds there is no record: one more twin run (tw2_), then give up. + do_ own record: history/ = attempt 1 of the instance's main-table history run (scripts/make_dossier.py) + dm_ mismatched record: history/ = the failed twin run. README byte-identical to do_; only history/ differs. + + python3 scripts/mismatch_plan.py own build own records + write //own.json and tasks_.txt + python3 scripts/mismatch_plan.py twin build twin records from tw_ (+ tw2_) -> //twin.json; + prints the instances still without a failed twin run + python3 scripts/mismatch_plan.py report per instance: main-table attempt 2 with history (H2) and first + memory-free retry (N2), Do, Dm, twin; totals and paired counts + -> /report.json + markdown on stdout +""" +import json +import os +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +API = os.path.join(ROOT, "runs", "api") +OUT = os.path.join(API, "mismatch_20261027") +TWIN_TASKS = ["l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool", + "l4_fit_container", "l2_turntable_restore", "l3_card_shelf", "l5_loaded_beam"] +MAIN = {"opus": ["cc_opus1", "cc_opus_s2", "cc_opus_s3"], "sonnet": ["cc_main1", "cc_sonnet_s2", "cc_sonnet_s3"]} + + +def runs(batch): + return json.load(open(os.path.join(API, batch, "manifest.json")))["runs"] + + +def attempt1(log): + for line in open(os.path.join(log, "events.jsonl")): + e = json.loads(line) + if e.get("ev") == "done" and e.get("attempt") == 1: + return e + return None + + +def dossier(log, out): + if not os.path.isdir(out): + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, out], check=True, + capture_output=True) + return out + + +def cmd_own(): + for m, batches in MAIN.items(): + own, tasks = {}, [] + for b in batches: + for r in runs(b): + if r["cond"] != "harness" or r["task"] not in TWIN_TASKS or r["status"] != "done": + continue + d = attempt1(r["log"]) + if d is None or d["success"]: + continue + key = f"{r['task']}:{r['seed']}" + own[key] = dossier(r["log"], os.path.join(OUT, m, "own", f"{r['task']}_s{r['seed']}")) + tasks.append(key) + os.makedirs(os.path.join(OUT, m), exist_ok=True) + json.dump(own, open(os.path.join(OUT, m, "own.json"), "w"), indent=1) + open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(tasks) + "\n") + print(m, len(tasks)) + + +def cmd_twin(m): + want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()] + twin = {} + for b in (f"tw_{m}", f"tw2_{m}"): + if not os.path.exists(os.path.join(API, b, "manifest.json")): + continue + for r in runs(b): + key = f"{r['task']}:{r['seed']}" + if key in twin or r["status"] != "done": + continue + d = attempt1(r["log"]) + if d is not None and not d["success"]: + twin[key] = dossier(r["log"], os.path.join(OUT, m, "twin", f"{r['task']}_s{r['seed']}")) + json.dump(twin, open(os.path.join(OUT, m, "twin.json"), "w"), indent=1) + print(json.dumps(dict(model=m, with_record=len(twin), missing=[k for k in want if k not in twin]))) + + +# twin oracle also solves the original instance (docs/14 §6.4, 10-12 validation): mismatch is weak there +WEAK = {"l3_wall_flush", "l3_under_table_tool"} + + +def single(batch): + """task:seed -> True / False (attempt 1 of the batch's done run), None if not run or not finished.""" + out = {} + if not os.path.exists(os.path.join(API, batch, "manifest.json")): + return out + for r in runs(batch): + if r["status"] == "done": + d = attempt1(r["log"]) + out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"]) + return out + + +def main_rows(batches): + rows = {} + for b in batches: + tmp = os.path.join(OUT, f".oc_{b}.json") + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "outcomes.py"), "--batch", b, "--json", tmp], + check=True, capture_output=True) + for r in json.load(open(tmp))["rows"]: + rows[f"{r['task']}:{r['seed']}"] = dict(batch=b, history=r["history"], memfree=r["memfree"]) + os.remove(tmp) + return rows + + +def cmd_report(): + rep, md = {}, [] + for m, batches in MAIN.items(): + want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()] + main = main_rows(batches) + do, dm = single(f"do_{m}"), single(f"dm_{m}") + t1, t2 = single(f"tw_{m}"), single(f"tw2_{m}") # "twin" = F if some twin run failed (a record exists) + tw = {k: (False if False in (t1.get(k), t2.get(k)) else t1.get(k)) for k in set(t1) | set(t2)} + rows = [] + for k in want: + h, mf = main[k]["history"] or "", main[k]["memfree"] or "" + rows.append(dict(inst=k, task=k.split(":")[0], weak=k.split(":")[0] in WEAK, + 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, + Do=do.get(k), Dm=dm.get(k), twin=tw.get(k))) + def rate(key, sub): + v = [r[key] for r in sub if r[key] is not None] + return f"{sum(v)}/{len(v)}" if v else "-" + both = [r for r in rows if r["Do"] is not None and r["Dm"] is not None] + pairs = dict(n=len(both), do_only=sum(r["Do"] and not r["Dm"] for r in both), + dm_only=sum(r["Dm"] and not r["Do"] for r in both), both=sum(r["Do"] and r["Dm"] for r in both)) + rep[m] = dict(rows=rows, pairs=pairs) + md += [f"### {m}", "", "| instance | twin run | H2 (history, main) | N2 (memory-free, main) | Do (own record) | Dm (twin record) |", + "|---|---|---|---|---|---|"] + f = lambda v: "-" if v is None else ("S" if v else "F") + for r in rows: + 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'])} |") + strong = [r for r in rows if not r["weak"]] + md += ["", f"all: H2 {rate('H2', rows)}, N2 {rate('N2', rows)}, Do {rate('Do', rows)}, Dm {rate('Dm', rows)}; " + f"strong mismatch only: Do {rate('Do', strong)}, Dm {rate('Dm', strong)}; " + f"paired Do/Dm n={pairs['n']}: Do only {pairs['do_only']}, Dm only {pairs['dm_only']}, both {pairs['both']}", ""] + json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1) + print("\n".join(md)) + + +if __name__ == "__main__": + {"own": lambda: cmd_own(), "twin": lambda: cmd_twin(sys.argv[2]), "report": lambda: cmd_report()}[sys.argv[1]]() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/vla_eval.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/vla_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..557cc5b3bf7b93550070883290b6d9a7756b3c70 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/vla_eval.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Evaluate a visuomotor policy on LFF-Bench (lffbench/vla.py). + + # one process per shard; the policy server runs elsewhere (openpi serve_policy.py, or StarVLA's) + python scripts/vla_eval.py run --policy ws://127.0.0.1:18000 --set sets/main_v2_3inst.txt --k 3 --out results/vla/ \ + --shard 0/8 --model-name pi05_lff_v1 + python scripts/vla_eval.py report results/vla/ + +Each session writes /_s/summary.json and events.jsonl; a session with a summary.json is skipped, so a +rerun resumes. --tasks takes task:seed[,seed] items, --set a file of them (the sets/ format). +""" +import argparse +import hashlib +import json +import os +import sys +import time +import traceback + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +CAUSES = os.path.join(ROOT, "..", "paper", "fig_scripts", "data", "causes.json") + + +def parse_items(items): + out = [] + for it in items: + name, _, seeds = it.strip().partition(":") + if not seeds: + raise SystemExit(f"{it!r}: expected task:seed[,seed]") + out += [(name, int(s)) for s in seeds.split(",")] + return out + + +def read_set(path): + return [line.strip() for line in open(path) if line.strip() and not line.startswith("#")] + + +def sha256(path): + with open(path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def causes(): + try: + return json.load(open(CAUSES))["cause"] + except OSError: + return {} + + +class Video: + """Frames at the replan rate, agentview next to wrist, written at real time speed.""" + + def __init__(self, path, replan): + import imageio + self.w = imageio.get_writer(path, fps=max(1, round(20 / replan)), quality=7, macro_block_size=8) + + def add(self, t, obs): + self.w.append_data(np.hstack([obs["observation/image"], obs["observation/wrist_image"]])) + + def close(self): + self.w.close() + + +def make_policy(spec): + from lffbench import vla + if spec == "zero": + return vla.ZeroPolicy() + if spec.startswith("ws://"): + return vla.WebsocketPolicy(spec) + raise SystemExit(f"unknown --policy {spec!r}: use ws://host:port or zero") + + +def run_one(task_name, seed, a, policy, tasks): + from lffbench import vla + from lffbench.harnesses.contract import server_code_sha + d = os.path.join(a.out, f"{task_name}_s{seed}") + if os.path.exists(os.path.join(d, "summary.json")): + return "skip" + os.makedirs(d, exist_ok=True) + task = tasks[task_name](cam_res=a.res) + inst = task.sample_instance(seed) + code_sha, code_files = server_code_sha(task_name) + start = dict(ev="session_start", task=task_name, seed=seed, protocol=getattr(task, "protocol", "cross"), + level=task.level, category=task.category, cause=causes().get(task_name), instruction=vla.task_prompt(task, inst), + k=a.k, replan=a.replan, res=a.res, frame=a.frame, idle_s=a.idle_s, probe_every_s=a.probe_every_s, + max_steps=a.max_steps or vla.budget_steps(task), model_name=a.model_name, policy=str(a.policy), + policy_metadata=getattr(policy, "metadata", None), inst={k: v for k, v in inst.items() if not k.startswith("_")}, + server_code_sha256=code_sha, server_code_files=code_files, + vla_sha256=sha256(os.path.join(ROOT, "lffbench", "vla.py")), time=time.time()) + with open(os.path.join(d, "events.jsonl"), "a") as log: + def write(rec): + log.write(json.dumps(rec, default=str) + "\n") + log.flush() + write(start) + video = Video(os.path.join(d, "rollout.mp4"), a.replan) if a.video else None + try: + t0 = time.time() + attempts = vla.run_session(task, inst, policy, k=a.k, max_steps=a.max_steps, replan=a.replan, res=a.res, + frame=a.frame, idle_s=a.idle_s, probe_every_s=a.probe_every_s, + on_frame=video.add if video else None, + on_attempt=lambda r: write(dict(ev="done", **r))) + finally: + if video: + video.close() + succ = [r["success"] for r in attempts] + first = next((r["attempt"] for r in attempts if r["success"]), None) + first_any = next((r["attempt"] for r in attempts if r["success"] or r["first_success_step"] is not None), None) + summary = {key: start[key] for key in ("task", "seed", "protocol", "level", "category", "cause", "k", "replan", "frame", + "max_steps", "model_name", "policy_metadata", "server_code_sha256")} + summary.update(status="ok", n_attempts=len(attempts), success_by_attempt=succ, first_success=first, + attempt1_success=bool(succ[0]), success=first is not None, first_success_any=first_any, + ended_by=[r["end"] for r in attempts], failure=[r["failure"] for r in attempts], + n_steps=[r["n_steps"] for r in attempts], infer_s_mean=[r["infer_s_mean"] for r in attempts], + wall_s=round(time.time() - t0, 2)) + tmp = os.path.join(d, "summary.json.tmp") + json.dump(summary, open(tmp, "w"), indent=1, default=str) + os.replace(tmp, os.path.join(d, "summary.json")) + return "ok" if first is not None else "fail" + + +def cmd_run(a): + from lffbench import tasks as task_pkg # noqa: F401 (registers the task modules) + import importlib + import pkgutil + from lffbench.task_base import TASKS + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + items = list(a.tasks or []) + if a.set: + items += read_set(a.set) + sessions = parse_items(items) + i, n = (int(x) for x in a.shard.split("/")) + sessions = sessions[i::n] + os.makedirs(a.out, exist_ok=True) + policy = make_policy(a.policy) + print(f"[vla_eval] shard {a.shard}: {len(sessions)} sessions, policy {a.policy}, metadata {getattr(policy, 'metadata', None)}", flush=True) + for task_name, seed in sessions: + try: + print(f"[vla_eval] {task_name} s{seed}: {run_one(task_name, seed, a, policy, TASKS)}", flush=True) + except Exception: # one broken session must not end the shard; a missing summary.json makes a rerun retry it + print(f"[vla_eval] {task_name} s{seed}: ERROR\n{traceback.format_exc()}", flush=True) + + +def wilson(s, n, z=1.96): + if not n: + return [None, None] + p = s / n + d = 1 + z * z / n + c = p + z * z / (2 * n) + m = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) + return [round(float((c - m) / d), 4), round(float((c + m) / d), 4)] + + +def cmd_report(a): + rows = [] + for name in sorted(os.listdir(a.dir)): + p = os.path.join(a.dir, name, "summary.json") + if os.path.exists(p): + rows.append(json.load(open(p))) + if not rows: + raise SystemExit(f"no finished sessions in {a.dir}") + k = max(r["k"] for r in rows) + + def stats(group): + n = len(group) + 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)] + anyok = sum(1 for r in group if r["first_success_any"] is not None) + 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, + any_rate=round(anyok / n, 4)) + + by_cause, by_task = {}, {} + for r in rows: + by_cause.setdefault(str(r.get("cause")), []).append(r) + by_task.setdefault(r["task"], []).append(r) + non_l1 = [r for r in rows if r.get("cause") != "L1"] + report = dict(all=stats(rows), excluding_L1=stats(non_l1) if non_l1 else None, + by_cause={c: stats(g) for c, g in sorted(by_cause.items())}, + by_task={t: stats(g) for t, g in sorted(by_task.items())}, + ended_by={e: sum(r["ended_by"].count(e) for r in rows) for e in ("budget", "idle", "policy_ended")}, + 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), + model_names=sorted({str(r.get("model_name")) for r in rows}), + server_code_sha256=sorted({r["server_code_sha256"] for r in rows})) + json.dump(report, open(os.path.join(a.dir, "report.json"), "w"), indent=1) + print(f"{'':24s} {'n':>4s} {'A1':>6s} {f'A{k}':>6s} {'any':>6s}") + 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}") + for c, s in report["by_cause"].items(): + print(f"{c:24s} {s['n']:4d} {s['succ_at'][0]:6.2f} {s['succ_at'][-1]:6.2f} {s['any_rate']:6.2f}") + for t, s in report["by_task"].items(): + print(f"{t:24s} {s['n']:4d} {s['succ_at'][0]:6.2f} {s['succ_at'][-1]:6.2f} {s['any_rate']:6.2f}") + print("L1 tasks do not carry the agents' command-level offset for a direct-action policy; see lffbench/vla.py.") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("run") + r.add_argument("--policy", required=True, help="ws://host:port (openpi protocol) or zero") + r.add_argument("--tasks", nargs="*", help="task:seed[,seed] items") + r.add_argument("--set", help="file of task:seed[,seed] items, e.g. sets/main_v2_3inst.txt") + r.add_argument("--out", required=True) + r.add_argument("--k", type=int, default=3, help="attempts per session") + r.add_argument("--replan", type=int, default=5, help="actions executed from each chunk (openpi's LIBERO eval: 5)") + r.add_argument("--res", type=int, default=256, help="camera resolution (the dataset's: 256)") + r.add_argument("--frame", default="believed", choices=["believed", "true"], help="proprioception frame") + r.add_argument("--max-steps", type=int, default=None, help="control steps per attempt (default: the agents' budget)") + r.add_argument("--idle-s", type=float, default=5.0, help="end the attempt after this long without motion (0: off)") + r.add_argument("--probe-every-s", type=float, default=5.0, help="forked success check every this long (0: off)") + r.add_argument("--shard", default="0/1", help="i/n: run every n-th session starting at i") + r.add_argument("--model-name", default=None) + r.add_argument("--video", action="store_true") + r.set_defaults(fn=cmd_run) + p = sub.add_parser("report") + p.add_argument("dir") + p.set_defaults(fn=cmd_report) + a = ap.parse_args() + a.fn(a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/audit_state.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/audit_state.py new file mode 100644 index 0000000000000000000000000000000000000000..ca750975ae7d008a8d5a7b87dfa1c253f7a75cf4 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/audit_state.py @@ -0,0 +1,79 @@ +"""Host-only, read-only physical evidence for CS/IR review (opt-in). + +Never call outcome(), forward(), step() or a task measurement here: those can +settle physics or consume event cursors. Samples are at control-step boundaries, +not every MuJoCo substep. No sample itself is an error or repair classification. +""" +import json + + +def _json_value(value): + if hasattr(value, "tolist"): + return value.tolist() + raise TypeError(f"Unsupported audit value: {type(value).__name__}") + + +class AuditStateRecorder: + def __init__(self, path): + self.path = path + self.env = None + self.original_step = None + self.wrapped_step = None + self.sequence = 0 + + def write(self, record): + # A separate host-side file, never copied into the agent's sandbox. + with open(self.path, "a", encoding="utf-8") as stream: + stream.write(json.dumps(record, separators=(",", ":"), default=_json_value) + "\n") + + def detach(self): + if self.env is not None and self.env.step is self.wrapped_step: + self.env.step = self.original_step + self.env = None + + def attach(self, env, attempt, command_step): + self.detach() + self.env, self.attempt, self.command_step = env, attempt, command_step + self.original_step = env.step + original_step = self.original_step + model = env.sim.model + self.write(dict(kind="attempt_start", schema="lff-audit-state-1", attempt=attempt, + sampling="after_env_step", bodies=[model.body_id2name(i) for i in range(model.nbody)], + geoms=[model.geom_id2name(i) for i in range(model.ngeom)])) + + def wrapped(action): + result = original_step(action) + if self.env is env and self.wrapped_step is wrapped: + self.sample("control_step") + return result + + self.wrapped_step = wrapped + env.step = wrapped + self.sample("initial") + + def sample(self, phase): + data = self.env.sim.data + self.sequence += 1 + self.write(dict(kind="state", sequence=self.sequence, attempt=self.attempt, + command_step=self.command_step(), phase=phase, sim_time=float(data.time), + qpos=data.qpos.tolist(), qvel=data.qvel.tolist(), + body_xyz=data.body_xpos.tolist(), body_quat_wxyz=data.body_xquat.tolist(), + contacts=[[int(c.geom1), int(c.geom2), float(c.dist)] + for c in data.contact[:data.ncon]])) + + def boundary(self, task, phase): + """Capture after skill callbacks too (some injections happen after env.step). + + Copy existing event lists without calling monitor/outcome methods or + advancing their cursors. These are raw observations, not adjudications. + """ + self.sample(phase) + streams = {} + for name, obj in (("task", task), ("skills", getattr(task, "sk", None)), + ("monitor", getattr(task, "mon", None))): + attrs = obj if isinstance(obj, dict) else getattr(obj, "__dict__", {}) + for key in ("events", "turns", "strikes", "box_moves", "lifts", "grasp_tries"): + if isinstance(attrs.get(key), list): + streams[f"{name}.{key}"] = attrs[key] + self.write(dict(kind="event_snapshot", attempt=self.attempt, + command_step=self.command_step(), phase=phase, streams=streams)) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..a842f619205b88ccc9da3943f48f4f06bfb8e630 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py @@ -0,0 +1,18 @@ +"""Layer-4 intervention texts for lh_tidy_stack (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is +not in the controlled arms of full5. + +Hidden variable: inst["soft_colour"] -- the empty soft carton among the four boxes (None in benign instances). +reveal says which box is soft and how much it carries; not where to put it. +fix the oracle's order (lh_tidy_stack.oracle_params: rigid boxes first, the soft box last, then the cup). +""" +HIDDEN_KEYS = ("soft_colour",) + + +def reveal(inst): + return (f"The {inst['soft_colour']} box is an empty, soft carton. It carries one thing, but gives way as soon as a " + f"second thing rests above it, and everything above it slides off the pile.") + + +def fix(inst, params): + return (f"A way to succeed: stack the other three boxes first, put the {inst['soft_colour']} box on top of them last, " + f"and stand the cup on it. It then carries only the cup.") diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/embodied_evo.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/embodied_evo.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe7bbab6f494d3cfae2f6802e6c266f4561f6dc --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/embodied_evo.py @@ -0,0 +1,135 @@ +"""EmbodiedEvo's Codex launcher and skills/lessons workflow on LFF's MCP. + +Controlled port: same-episode knowledge only, no Playground pretraining, recipes, +native simulator execution or reset. Programs generate/revise action plans in +shell; individual robot commands are executed through MCP. This is explicitly +not EmbodiedEvo's full native code-as-policy evaluation. +""" +import copy +import hashlib +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +from . import contract as C, pins +from .base import HarnessRefused +from .codex import Codex, DISABLE, codex_bin +from .rpent import tree_sha256 + +DEFAULT_SOURCE = "/mnt/cpfs/workspace/env/embodied-evo/src" + + +def load_source(path, module_name): + if sys.version_info < (3, 11): + import tomli + sys.modules.setdefault("tomllib", tomli) + spec = importlib.util.spec_from_file_location(module_name, path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def workflow(source): + text = (Path(source) / "tasks/RoboDojo/Workspace/playground.md").read_text() + loop = text.split("Organize your work as an iterative loop:", 1)[1].split("# Environment and Primitives", 1)[0] + evolution = text.split("# Evolution: skills and lessons", 1)[1].split("# Playground rules", 1)[0] + evolution = evolution.replace("Read `skills/example.md` and `lessons/example.md` first.", + "Start with empty skills/ and lessons/; create them through shell when needed.") + return ("You are an embodied coding agent. Follow the EmbodiedEvo workflow below, adapted to the " + "benchmark's MCP interface. The benchmark instructions following this workflow are authoritative.\n\n" + "Organize your work as an iterative loop:" + loop + "\n# Skills and lessons\n" + evolution + + "\n# MCP adaptation\n" + "Use shell to write and run Python for visual analysis and incremental action-plan generation. " + "Keep reusable helpers and preconditions in skills/, failure evidence and corrections in lessons/, " + "and current plans in submission/. Execute each robot command with the robot MCP tool and inspect " + "its feedback before the next stage; Python in shell cannot contact the robot. Use view_images " + "for obs/ images. Do not assume scripts/env.py, native step(), get_observation(), reset(), or " + "Playground records exist. No preloaded recipes or skills are supplied. Preserve and revise your " + "skills and lessons across attempts of this episode only; the benchmark controls resets and " + "termination. Never replay earlier actions just because you rewrote a plan.\n\n") + + +class EmbodiedEvoCodex(Codex): + name = "embodied_evo_codex" + + def __init__(self, *args, source=None, **kwargs): + self.source = source or os.environ.get("LFF_EMBODIED_EVO_SOURCE", DEFAULT_SOURCE) + self._source_info = None + self.prefix = workflow(self.source) + self.native_launch = load_source(Path(self.source) / "orchestrator/launch_agent.py", "lff_evo_launch") + self.native_recovery = load_source(Path(self.source) / "orchestrator/agent_recovery.py", "lff_evo_recovery") + super().__init__(*args, **kwargs) + if self.catalog != "generic": + raise HarnessRefused("EmbodiedEvo controlled variant requires generic catalog") + + def source_info(self): + if self._source_info is None: + commit = subprocess.check_output(["git", "-C", self.source, "rev-parse", "HEAD"], text=True).strip() + self._source_info = dict(commit=commit, tree_sha256=tree_sha256(self.source), + workflow_sha256=hashlib.sha256(self.prefix.encode()).hexdigest()) + return self._source_info + + def version(self): + return dict(super().version(), framework=self.source_info()) + + def pin_key(self, ep): + v = self.version() + identity = C.sha256_json(v["framework"])[:12] + mode = "" if self.auth == "apikey" else "-chatgpt" + return pins.key(self.name + mode + "-generic-" + identity, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + + def config_info(self): + return dict(super().config_info(), framework=self.source_info(), variant="mcp-skills-lessons", + history="same-thread", cross_episode_memory=False, native_code_execution=False) + + def argv(self, ep, session_path, base_url, first_message, codex_home): + prompt = first_message if first_message.startswith(self.prefix) else self.prefix + first_message + args = self.native_launch.agent_argv("codex", prompt, model=ep.model, effort=ep.effort) + args[0] = codex_bin() + args[args.index("--sandbox") + 1] = "read-only" + # The benchmark fixes the middle layer; native orchestration provides the workflow and launch. + extra = ["--json", "--ignore-user-config", "--ignore-rules"] + for feature in DISABLE: + extra += ["--disable", feature] + for setting in self.config_args(ep, session_path, base_url, codex_home): + extra += ["-c", setting] + return args[:-1] + extra + [prompt] + + def resume_argv(self, handle, message): + thread = self.thread_id(handle.spec.stdout_path) + if not thread: + raise HarnessRefused("EmbodiedEvo resume: missing current thread ID") + args = list(handle.spec.argv) + binary, args[0] = args[0], "codex" + i = args.index("--sandbox") + mode = args[i+1] + del args[i:i+2] + args[-1:-1] = ["-c", "sandbox_mode=" + json.dumps(mode)] + args = self.native_recovery.resume_argv(args, thread) + args[0], args[-1] = binary, message # benchmark-owned continuation; same native resume construction + return args + + def preflight(self, spec, ep, record_dir=None): + proxy = copy.copy(spec) + proxy.first_message = self.prefix + spec.first_message + # super checks all middle-layer fields; this adapter's pin binds the source and workflow hash too. + out = super().preflight(proxy, ep, record_dir) + v = self.version() + anchor_name = "codex-generic" if self.auth == "apikey" else "codex-chatgpt-generic" + anchor_key = pins.key(anchor_name, v["version"], v["binary"]["sha256"], ep.model, ep.effort) + anchor = pins.load(anchor_key, self.pins_dir) + if anchor is None or anchor["fingerprint_sha256"] != out["fingerprint_sha256"]: + raise HarnessRefused("EmbodiedEvo middle layer does not match the pinned Codex baseline") + out.update(anchor_status="match", middle_fingerprint_sha256=out["fingerprint_sha256"], + framework_prefix_sha256=self.source_info()["workflow_sha256"], + framework_prefix_chars=len(self.prefix)) + return out + + def collect(self, handle): + traj = super().collect(handle) + # Preserve provenance alongside native CLI traces. + (Path(handle.ep.log_dir) / "framework.json").write_text(json.dumps(self.config_info(), indent=2)) + return traj diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/api_player.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/api_player.py new file mode 100644 index 0000000000000000000000000000000000000000..696c1e9204de668d41bdd9622931c5c579caea87 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/api_player.py @@ -0,0 +1,446 @@ +"""Drive one robot_server session with a model through its provider's official API (the unified harness). + +Every provider gets exactly the same input: the sandbox README as its instructions and the same tools; only the +wire format differs (lffbench/agent/backends/). After every command the JSON report is returned as the tool output. +Nothing else is sent: no files, no memory, no paths outside the sandbox. + + python scripts/api_player.py --session runs/<...>/session.json --provider anthropic --model claude-opus-5-5 --effort high --style la + +Providers (key / endpoint from the environment, e.g. `set -a; source .env; set +a`): + openai OpenAI Responses API OPENAI_API_KEY [OPENAI_BASE_URL] + anthropic Anthropic Messages API ANTHROPIC_API_KEY + gemini Gemini API (google-genai) GEMINI_API_KEY + chat any OpenAI-compatible Chat Completions endpoint (vLLM / SGLang for open models, xAI, ...) + LFF_CHAT_BASE_URL, LFF_CHAT_API_KEY +`--effort` is the provider's reasoning knob: OpenAI reasoning.effort, Anthropic output_config.effort, Gemini +thinking_level, chat: reasoning_effort (omitted when "none"). + +--style la (LIBERO-Agent-style workspace, the paper's interface): the sandbox is the agent's episode workspace. Besides +`robot` the model gets `shell` (a command run in the workspace inside a jail: no network, robot server unreachable, +host data hidden, see /opt/lffjail/jail_inner.sh) and `view_images` (any image file in the workspace, including ones +it made itself). Tool calls per attempt are capped (agent_iface.json: max_tool_calls); at the cap the attempt is +finished for it. +Logs in the run's log dir: transcript.jsonl (every request / reply / tool call), final_report.md. +""" +import argparse +import base64 +import json +import os +import shlex +import subprocess +import sys +import time +import traceback +import urllib.request + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"): + os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # the venv's own CA bundle lacks the proxy's issuer + +from lffbench.agent.backends import make_backend # noqa: E402 +from lffbench.agent.context import Conversation # noqa: E402 + +PROVIDERS = ("openai", "anthropic", "gemini", "chat") + +TOOL = dict( + name="robot", + description=("Run one robot command. `command` is exactly what you would type after `./robot` in the " + "instructions (e.g. `observe`). Returns the command's JSON report."), + parameters=dict(type="object", properties=dict(command=dict(type="string", description="the robot command")), + required=["command"], additionalProperties=False), +) + +VIEW_TOOL = dict( + name="view_images", + description=("Look at camera images the robot has written. `paths` are image paths exactly as printed by robot " + "commands (e.g. obs/a1_s003_wrist.jpg); any image of this episode can be viewed again. The images " + "are attached right after this call."), + parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"), + description="image paths to view")), + required=["paths"], additionalProperties=False), +) + +TOOL_LA = dict( + name="robot", + description=("Run one robot command. `command` is exactly one of the robot commands in the instructions, e.g. " + "`status` or `move_eef z=1.0 gripper=open`. Returns the command's JSON report, including the paths " + "of the new observation files."), + parameters=TOOL["parameters"], +) + +SHELL_TOOL = dict( + name="shell", + description=("Run a shell command (bash) in your workspace directory, e.g. `ls obs` or `python3 analyse.py`. " + "python3 has numpy, scipy, Pillow and OpenCV. No network; programs cannot control the robot. " + "Time limit 60 s per call. Returns the exit code and the combined stdout/stderr (long output is " + "truncated in the middle)."), + parameters=dict(type="object", properties=dict(command=dict(type="string", description="the bash command")), + required=["command"], additionalProperties=False), +) + +VIEW_TOOL_LA = dict( + name="view_images", + description=("Look at image files in your workspace (.jpg / .jpeg / .png), e.g. obs/a1_s003_wrist.jpg or an image " + "you made yourself; paths are relative to the workspace. At most 8 per call. The images are attached " + "right after this call."), + parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"), + description="image paths to view")), + required=["paths"], additionalProperties=False), +) + +PREAMBLE_LA = ("You control the robot described below and work in the workspace described below. Tools: `robot` runs " + "one robot command per call (the argument is exactly a command from the instructions, e.g. `status`); " + "`shell` runs a shell command in your workspace; `view_images` shows you image files from the " + "workspace. When a robot command tells you to stop or that the episode is over, stop calling tools and " + "reply with a short report: what you did (key commands and parameter values), what you observed, any " + "feedback you got, and how you changed your approach.\n\n") + +PREAMBLE = ("You control the robot described below. You act only through the `robot` tool, one command per call. " + "When a command tells you to stop or that the episode is over, stop calling the tool and reply with a " + "short report: what you did (key commands and parameter values), what you observed, any feedback you " + "got, and how you changed your approach.\n\n") + +JAIL = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "jail", "jail_inner.sh") +SHELL_TIMEOUT = 60 +SHELL_MAX_CHARS = 12000 + + +def run_shell(workspace, command): + """Run `command` in the jailed workspace; returns (exit code, output text, seconds).""" + t0 = time.time() + argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, workspace, + "timeout", "-k", "5", str(SHELL_TIMEOUT), "bash", "-c", command] + try: + r = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + timeout=SHELL_TIMEOUT + 30) + code, out = r.returncode, r.stdout.decode("utf-8", "replace") + except subprocess.TimeoutExpired as e: + code, out = 124, (e.stdout or b"").decode("utf-8", "replace") + if code == 124: + out += f"\n[killed: time limit of {SHELL_TIMEOUT} s]" + if len(out) > SHELL_MAX_CHARS: + h = SHELL_MAX_CHARS // 2 + out = out[:h] + f"\n[... {len(out) - SHELL_MAX_CHARS} characters truncated ...]\n" + out[-h:] + return code, out, time.time() - t0 + + +def workspace_image(workspace, rel): + """Resolve a model-given image path inside the workspace (no escaping via .. or symlinks); None if not allowed.""" + if not isinstance(rel, str) or not rel or rel.startswith("/"): + return None + root = os.path.realpath(workspace) + full = os.path.realpath(os.path.join(root, rel)) + if not full.startswith(root + os.sep) or not os.path.isfile(full): + return None + if os.path.splitext(full)[1].lower() not in (".jpg", ".jpeg", ".png") or os.path.getsize(full) > 8 * 2 ** 20: + return None + return full + + +class FileImage: + """The exact JPEG bytes the server wrote (same bytes a Claude Code player reads).""" + + def __init__(self, path): + self.path = path + base = os.path.basename(path) + self.camera = "wrist" if "wrist" in base else ("agentview" if "agentview" in base else "camera") + self.label = base + + def data_url(self, quality=None): + mime = "image/png" if self.path.lower().endswith(".png") else "image/jpeg" + with open(self.path, "rb") as f: + return f"data:{mime};base64," + base64.b64encode(f.read()).decode() + + +def parse_command(s): + s = s.strip() + s = s.removeprefix("./robot").strip() if s.startswith("./robot") else (s[len("robot "):] if s.startswith("robot ") else s) + toks = shlex.split(s.strip()) + if not toks: + return "help", {} + cmd, args = toks[0], {} + for a in toks[1:]: + if "=" not in a: + return None, f"bad argument {a!r}: use key=value" + k, v = a.split("=", 1) + try: + args[k] = json.loads(v) + except ValueError: + args[k] = v + return cmd, args + + +def call_server(port, token, cmd, args): + req = urllib.request.Request(f"http://127.0.0.1:{port}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(), + headers={"Content-Type": "application/json", "X-Token": token}) + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + with opener.open(req, timeout=900) as r: + return r.read().decode() + + +MAX_NO_TOOL = 3 # nudges in a row for replies without a tool call; the next such reply ends the run + + +def continue_nudge(port, token, stx=None): + """The user message sent when the model replies without a tool call before the episode is over. Native harnesses + send the same text when their CLI exits early (scripts/harness_run.py). stx: a status reply already fetched.""" + try: # tell it where it is: models sometimes believe the episode ended after a failed attempt + if stx is None: + stx = json.loads(call_server(port, token, "status", {})) + where = (f" You are in attempt {stx.get('attempt')} of {stx.get('max_attempts')}; the episode is NOT over." + if stx.get("attempt") else "") + except Exception: + where = "" + return "Continue: issue the next robot command with the `robot` tool." + where + + +def build_backend(a, v2): + """The model backend for --provider; image pruning only where the provider allows editing earlier turns.""" + if a.provider == "openai": + return make_backend("openai", model=a.model, reasoning_effort=a.effort, reasoning_summary="auto", + max_live_images=None if v2 else a.max_live_images, cache_breakpoints="none", max_retries=1) + if a.provider == "anthropic": # append-only history (thinking blocks are bound to it): never prune + return make_backend("anthropic", model=a.model, effort=a.effort, max_live_images=None) + if a.provider == "gemini": + return make_backend("gemini", model=a.model, thinking_level=a.effort, + max_live_images=None if v2 else a.max_live_images) + extra = None if a.effort in ("", "none", None) else dict(reasoning_effort=a.effort) + return make_backend("chat", model=a.model, max_tokens=a.max_output_tokens, temperature=None, extra_body=extra, + max_live_images=None if v2 else a.max_live_images) + + +def context_overflow(err): + """The request no longer fits: token limit (OpenAI / Anthropic / Gemini / Kimi wordings) or too many images.""" + e = err.lower() + return (("context" in e and ("length" in e or "window" in e or "too long" in e)) or "prompt is too long" in e + or ("exceed" in e and "token" in e) or "too many images" in e or "maximum number of images" in e) + + +def live_images(conv): + return sum(1 for it in conv.items if it["kind"] == "user" and it.get("live") for p in it["parts"] + if p["type"] == "image") + + +def main(argv=None, default_provider=None, transcript_name="transcript.jsonl"): + ap = argparse.ArgumentParser() + ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh") + ap.add_argument("--provider", default=default_provider, choices=PROVIDERS, required=default_provider is None) + ap.add_argument("--model", default="gpt-6-astra" if default_provider == "openai" else None, + required=default_provider is None) + ap.add_argument("--effort", default="medium") + ap.add_argument("--max-turns", type=int, default=400) + ap.add_argument("--max-live-images", type=int, default=16) + ap.add_argument("--max-output-tokens", type=int, default=32768, help="chat provider only") + ap.add_argument("--api-retries", type=int, default=8, + help="retries of a failed API call before giving up (back-off 5 s doubling to 120 s: ~9 min)") + ap.add_argument("--max-request-images", type=int, default=500, + help="when the conversation holds more viewed images than this, switch to the context-full " + "policy (Claude through a gateway failed at 601 images, 2026-10-15)") + ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"], + help="v2: images are not attached automatically; the model views them on demand with " + "view_images, and no history is pruned (the agent manages its own context)") + a = ap.parse_args(argv) + + sess = json.load(open(a.session)) + sb, port = sess["sandbox"], sess["port"] + log_dir = os.path.dirname(os.path.abspath(a.session)) + la = a.style == "la" + if la: # no robot CLI in a la workspace: the token is only in the log dir + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + token, max_tool_calls = iface["token"], int(iface["max_tool_calls"]) + else: + token = open(os.path.join(sb, "robot")).read().split('TOKEN = "', 1)[1].split('"', 1)[0] + readme = open(os.path.join(sb, "README.md")).read() + tlog = open(os.path.join(log_dir, transcript_name), "a") + + def log(d): + d["t"] = time.time() + tlog.write(json.dumps(d, ensure_ascii=False) + "\n") + tlog.flush() + + v2 = a.style in ("v2", "la") # la = v2 robot interface + workspace tools + tools = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] if la else ([TOOL, VIEW_TOOL] if v2 else [TOOL]) + backend = build_backend(a, v2) + conv = Conversation((PREAMBLE_LA if la else PREAMBLE) + readme) + log(dict(ev="start", provider=a.provider, model=a.model, effort=a.effort, style=a.style, backend=backend.config(), + instructions=conv.system, tools=tools)) + + def images_part(paths, title): + parts = [dict(type="text", text=title)] + for p in paths: + parts.append(dict(type="image", image=FileImage(os.path.join(sb, p)))) + return parts + + st = json.loads(call_server(port, token, "status", {})) + if v2: # images stay files; the model decides what to look at + first = [dict(type="text", text=("Begin. Current status (robot command `status`):\n" if la else + "Begin. Current status (`./robot status`):\n") + json.dumps(st))] + else: + first = [dict(type="text", text="Begin. Current status (`./robot status`):\n" + + json.dumps({k: v for k, v in st.items() if k != "images"}))] + first += images_part(st.get("images", []), "Current camera images (agentview, wrist):")[1:] + conv.add_user(first, live=True) + log(dict(ev="user", text=first[0]["text"], images=st.get("images", []))) + + finished, no_tool, report = False, 0, None + calls_in_attempt = 0 # la: tool calls (robot + shell + view_images) in the current attempt + usage_tot = dict(input_tokens=0, cached_tokens=0, cache_write_tokens=0, output_tokens=0, reasoning_tokens=0) + for turn in range(a.max_turns): + resp, err = None, None + if v2 and backend.max_live_images is None and live_images(conv) > a.max_request_images: + backend.max_live_images = 32 # same context-full policy as below, before the request limit is hit + log(dict(ev="context_overflow", reason="image count", n_images=live_images(conv), keep_images=32)) + for r in range(a.api_retries + 1): + t0 = time.time() + try: + out = backend.act(conv, tools) + except Exception as e: # flaky endpoint: back off and retry the identical request + err = f"{type(e).__name__}: {str(e)[:300]}" + if v2 and context_overflow(err): + # the context is full (every provider): from now on keep only the newest viewed images + backend.max_live_images = 32 if backend.max_live_images is None else max(backend.max_live_images // 2, 4) + log(dict(ev="context_overflow", reason=err[:120], keep_images=backend.max_live_images)) + log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0)) + time.sleep(min(120, 5 * 2 ** r)) + continue + if out.status == "refusal": # the provider declined: no fallback model (it would change the model under test) + resp, err = out, out.error + break + if out.status == "incomplete": # truncated / malformed turn: not appended, ask again + err = out.error + log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0, usage=out.usage)) + continue + resp = out + break + if resp is None: + log(dict(ev="abort", reason="api failed", error=err)) + print("ABORT api failed:", err, flush=True) + sys.exit(3) + for k in usage_tot: + usage_tot[k] += resp.usage.get(k, 0) + if resp.status == "refusal": + log(dict(ev="refusal", turn=turn, latency_s=resp.latency_s, usage=resp.usage, error=resp.error, + text=resp.text)) + log(dict(ev="abort", reason="refusal", error=resp.error)) + print("ABORT refusal:", resp.error, flush=True) + break + conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name) + log(dict(ev="assistant", turn=turn, latency_s=resp.latency_s, usage=resp.usage, text=resp.text, + reasoning_summary=resp.reasoning_summary, + reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned", + status=resp.status, error=resp.error, + tool_calls=[dict(id=c.id, name=c.name, arguments=c.arguments) for c in resp.tool_calls], + request_stats=resp.request_stats)) + if finished: + report = resp.text + break + if not resp.tool_calls: + no_tool += 1 + nudge = continue_nudge(port, token) + if no_tool > MAX_NO_TOOL: + log(dict(ev="abort", reason="no tool call 4 times")) + break + conv.add_user([dict(type="text", text=nudge)], live=False) + log(dict(ev="user", text=nudge)) + continue + no_tool = 0 + for c in resp.tool_calls: + if la and not finished: + calls_in_attempt += 1 + if la and c.name == "shell": + code, out, dt = run_shell(sb, str(c.arguments.get("command", ""))) + out_text = json.dumps(dict(exit_code=code, output=out)) + conv.add_tool_output(c.id, c.name, out_text) + log(dict(ev="tool", turn=turn, command="shell: " + str(c.arguments.get("command", "")), output=out_text, + shell_s=round(dt, 2))) + continue + if la and c.name == "view_images": + paths = [str(x) for x in (c.arguments.get("paths") or [])][:8] + full = [(x, workspace_image(sb, x)) for x in paths] + ok_paths = [x for x, f in full if f] + out = dict(ok=bool(ok_paths), attached=ok_paths) + if len(ok_paths) < len(paths): + out["not_viewable"] = [x for x, f in full if not f] + conv.add_tool_output(c.id, c.name, json.dumps(out)) + log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths)) + if ok_paths: + parts = [dict(type="text", text="Requested images:")] + for x, f in full: + if f: + parts.append(dict(type="image", image=FileImage(f))) + conv.add_user(parts, live=True) + continue + if c.name == "view_images": + paths = [str(x) for x in (c.arguments.get("paths") or [])][:8] + ok_paths = [x for x in paths if x.startswith("obs/") and "/.." not in x and ".." not in x + and os.path.exists(os.path.join(sb, x))] + bad = [x for x in paths if x not in ok_paths] + out = dict(ok=bool(ok_paths), attached=ok_paths) + if bad: + out["not_found"] = bad + conv.add_tool_output(c.id, c.name, json.dumps(out)) + log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths)) + if ok_paths: + conv.add_user(images_part(ok_paths, "Requested images:"), live=True) + continue + cmdline = str(c.arguments.get("command", "")) + cmd, args = parse_command(cmdline) + if cmd is None: + out_text, paths = json.dumps(dict(ok=False, error=args)), [] + else: + raw = call_server(port, token, cmd, args) + try: + rep = json.loads(raw) + if v2: # keep the image paths in the reply: the model views them itself if it wants + paths = [] + out_text = json.dumps(rep) + else: + paths = rep.pop("images", []) if isinstance(rep, dict) else [] + out_text = json.dumps(rep) + except ValueError: # help text + rep, paths, out_text = {}, [], raw + msg = (rep.get("message", "") + " " + rep.get("error", "")) if isinstance(rep, dict) else "" + if isinstance(rep, dict) and isinstance(rep.get("attempt_ended"), dict): + msg += " " + rep["attempt_ended"].get("message", "") + if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg: + finished = True + if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)): + calls_in_attempt = 0 + conv.add_tool_output(c.id, c.name, out_text) + log(dict(ev="tool", turn=turn, command=cmdline, output=out_text, images=paths)) + if paths and not v2: + conv.add_user(images_part(paths, f"Camera images after `{cmdline}` (agentview, wrist):"), live=True) + if la and not finished and calls_in_attempt >= max_tool_calls: + raw = call_server(port, token, "finish", dict(reason="tool-call budget used up (automatic)")) + try: + rep = json.loads(raw) + except ValueError: + rep = dict(raw=raw) + msg = rep.get("message", "") + " " + rep.get("error", "") + if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg: + finished = True + calls_in_attempt = 0 + note = (f"The budget of {max_tool_calls} tool calls for this attempt was used up, so the attempt was " + f"finished automatically. Result: " + json.dumps(rep)) + conv.add_user([dict(type="text", text=note)], live=False) + log(dict(ev="user", text=note, auto_finish=True)) + if finished: + ask = "Stop now and reply with your short report (no more tool calls)." + conv.add_user([dict(type="text", text=ask)], live=False) + log(dict(ev="user", text=ask)) + if report: + with open(os.path.join(log_dir, "final_report.md"), "w") as f: + f.write(report) + log(dict(ev="end", finished=finished, usage_total=usage_tot)) + print(json.dumps(dict(finished=finished, usage=usage_tot, report=(report or "")[:200])), flush=True) + + +if __name__ == "__main__": + try: + main() + except SystemExit: + raise + except Exception: + traceback.print_exc() + sys.exit(1) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/full_report.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/full_report.py new file mode 100644 index 0000000000000000000000000000000000000000..517955b7426d6e4e08a16504d9451a7c2689d873 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/full_report.py @@ -0,0 +1,89 @@ +"""Summarise a full run (all tasks x harnesses) from the robot-server logs only, so every harness is measured +the same way. + +python scripts/full_report.py --batch full1 [--out ../docs/full1_table.md] + +Per run: outcome of every attempt, attempts used, robot commands, close_gripper calls that ended holding an +object, "empty done" attempts (the agent ended an attempt without a single move / gripper command in it), and +wall time from the first to the last server request. +""" +import argparse +import collections +import json +import os + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +LEVEL = {"l1": "L1", "l2": "L2", "l3": "L3", "l4": "L4", "l5": "L5", "l6": "L6", "l7": "L7"} +HARNESS_NAME = {"gpt_player": "ours", "rpent": "RPent", "gptpolicy": "GPT-Policy", "claude": "ours (Claude CLI)"} + + +def run_info(r): + ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))] + calls = [e for e in ev if e["ev"] == "call"] + dones = [e for e in ev if e["ev"] == "done"] + http = [e for e in ev if e["ev"] == "http"] + # v1: move_to / open_gripper / close_gripper; v2 and la: move_eef [gripper=open|close] (holding is only in `raw`, + # the agent never sees it) + acts_per_attempt = collections.Counter(e["attempt"] for e in calls if e["cmd"] in ("move_to", "open_gripper", "close_gripper") + or (e["cmd"] == "move_eef" and (e.get("report") or {}).get("ok"))) + empty = sum(1 for d in dones if acts_per_attempt.get(d["attempt"], 0) == 0) + closes = [e for e in calls if e["cmd"] == "close_gripper" + or (e["cmd"] == "move_eef" and (e.get("args") or {}).get("gripper") == "close" and (e.get("report") or {}).get("ok"))] + held = sum(1 for e in closes if (e.get("report") or {}).get("holding_object") or (e.get("raw") or {}).get("holding_object")) + first = next((d["attempt"] for d in dones if d["success"]), None) + wall = (http[-1]["t_send"] - http[0]["t_recv"]) / 60 if http else None + return dict(outcomes="".join("S" if d["success"] else "F" for d in dones), attempts=len(dones), first=first, + cmds=len(calls), closes=len(closes), held=held, empty=empty, wall=wall) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", default="full1") + ap.add_argument("--out", default=None) + ap.add_argument("--runs", default="gpt", help="runs///manifest.json (gpt or claude)") + a = ap.parse_args() + m = json.load(open(os.path.join(ROOT, "runs", a.runs, a.batch, "manifest.json"))) + rows = {} + for r in m["runs"]: + try: + h = r.get("harness") or ("claude" if r.get("cond") in ("harness", "noharness") else "gpt_player") + rows[(r["task"], h)] = dict(run_info(r), k=r["k"]) + except FileNotFoundError: + pass + tasks = sorted({t for t, _ in rows}, key=lambda t: (t[:2], t)) + hs = [h for h in ("gpt_player", "rpent", "gptpolicy", "claude") if any(k[1] == h for k in rows)] + L = [f"# {a.batch}: one run per task x harness (see manifest for model / perception / style)", "", + "Cell = outcome of each attempt (S success, F failure); `·` = run missing. Measured from robot-server logs.", "", + "| task | level | " + " | ".join(HARNESS_NAME[h] for h in hs) + " |", "|---|---|" + "---|" * len(hs)] + for t in tasks: + cells = [] + for h in hs: + x = rows.get((t, h)) + cells.append("·" if x is None else (x["outcomes"] or "—")) + L.append(f"| {t} | {LEVEL.get(t[:2], '?')} | " + " | ".join(cells) + " |") + L += ["", "| harness | runs | success @1 | success @3 | grasps held / close_gripper | empty-done attempts | " + "commands / attempt | wall min / run |", "|---|---|---|---|---|---|---|---|"] + for h in hs: + xs = [x for (t, hh), x in rows.items() if hh == h and x["attempts"] > 0] + n = len(xs) + att = sum(x["attempts"] for x in xs) + L.append(f"| {HARNESS_NAME[h]} | {n} | {sum(1 for x in xs if x['first'] == 1)} | " + f"{sum(1 for x in xs if x['first'])} | {sum(x['held'] for x in xs)} / {sum(x['closes'] for x in xs)} | " + f"{sum(x['empty'] for x in xs)} / {att} | {sum(x['cmds'] for x in xs) / max(att, 1):.1f} | " + f"{sum(x['wall'] or 0 for x in xs) / max(n, 1):.0f} |") + by_level = collections.defaultdict(lambda: [0, 0]) + for (t, h), x in rows.items(): + if x["attempts"]: + by_level[LEVEL.get(t[:2], "?")][0] += bool(x["first"]) + by_level[LEVEL.get(t[:2], "?")][1] += 1 + L += ["", "Success @3 by level (all harnesses pooled): " + + ", ".join(f"{lv} {s}/{n}" for lv, (s, n) in sorted(by_level.items()))] + txt = "\n".join(L) + print(txt) + if a.out: + with open(a.out, "w") as f: + f.write(txt + "\n") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/ladder_gpt_plan.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/ladder_gpt_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..46755d64c11bbf84cabe84a9701b431d86b0fb20 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/ladder_gpt_plan.py @@ -0,0 +1,95 @@ +"""Layer-3 feedback ladder for GPT-6 Astra (user 2026-11-02: "跑吧"; same design as scripts/ladder_plan.py, docs/20). +Instances: the main-table attempt 1 failures of GPT-6 Astra on the 8 ladder tasks (turntable left out, as in the +reported Claude totals). Fresh single-attempt agents, Codex 0.163 generic config, jail, high, F1, one round. The F1 rung +is run here (batch lf1_gpt): GPT has no mismatch-control Do arm to reuse. + + python scripts/ladder_gpt_plan.py validate Fix texts for instances Claude's ladder did not cover -> results/_ladder/fix_validate_gpt.json + python scripts/ladder_gpt_plan.py build records -> runs/api/ladder_gpt_20261102/.json + tasks.txt + python scripts/ladder_gpt_plan.py report per instance rungs and totals, next to Opus and Sonnet +""" +import json +import os +import subprocess +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import ladder_plan as L # noqa: E402 + +ROOT, API = L.ROOT, L.API +OUT = os.path.join(API, "ladder_gpt_20261102") +BATCHES = ["cx_main1", "cx_astra_s2", "cx_astra_s3"] +TASKS = {"l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool", + "l4_fit_container", "l3_card_shelf", "l5_loaded_beam"} +FIXV_GPT = os.path.join(ROOT, "results", "_ladder", "fix_validate_gpt.json") +RUNGS = ("F1", "F2", "hplus", "fix") +BATCH = {"F1": "lf1_gpt", "F2": "lf2_gpt", "hplus": "lhp_gpt", "fix": "lfx_gpt"} + + +def instances(): + out = {} + for b in BATCHES: + for r in json.load(open(os.path.join(API, b, "manifest.json")))["runs"]: + if r["cond"] != "harness" or r["status"] != "done" or r["task"] not in TASKS: + continue + d = next((e for e in L.events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None) + if d is not None and not d["success"]: + out[f"{r['task']}:{r['seed']}"] = r["log"] + return out + + +def fixes(): + rows = json.load(open(L.FIXV))["rows"] + if os.path.exists(FIXV_GPT): + rows += json.load(open(FIXV_GPT))["rows"] + return {r["key"]: r for r in rows} + + +def cmd_validate(): + import validate_ladder_fix as V + have = fixes() + want = {k: v for k, v in instances().items() if not have.get(k, {}).get("ok")} + print("to validate:", sorted(want)) + if not want: + return + V.instances = lambda: {k: dict(task=k.split(":")[0], seed=int(k.split(":")[1]), models=["gpt"], + logged=json.loads(open(os.path.join(v, "events.jsonl")).readline())["inst"]) for k, v in want.items()} + sys.argv = ["validate_ladder_fix.py", "--out", FIXV_GPT] + V.main() + + +def cmd_build(): + fx = fixes(); inst = instances(); os.makedirs(OUT, exist_ok=True) + open(os.path.join(OUT, "tasks.txt"), "w").write("\n".join(sorted(inst)) + "\n") + out = {r: {} for r in RUNGS} + for key, log in sorted(inst.items()): + task, seed = key.split(":") + tx = dict(L.texts(dict(log=log, task=task, seed=int(seed)), fx), F1="") + for r in RUNGS: + dst = os.path.join(OUT, r, f"{task}_s{seed}") + if not os.path.isdir(dst): + cmd = [sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst] + (["--result-extra", tx[r]] if tx[r] else []) + subprocess.run(cmd, check=True, capture_output=True) + out[r][key] = dst + for r in RUNGS: + json.dump(out[r], open(os.path.join(OUT, f"{r}.json"), "w"), indent=1) + print(len(inst), "instances x", len(RUNGS), "rungs") + + +def cmd_report(): + keys = [l.strip() for l in open(os.path.join(OUT, "tasks.txt")) if l.strip()] + res = {r: L.single(BATCH[r]) for r in RUNGS} + f = lambda v: "-" if v is None else ("S" if v else "F") + print("| instance | F1 | F2 | H+ | Fix |\n|---|---|---|---|---|") + for k in keys: + print(f"| {k} | " + " | ".join(f(res[r].get(k)) for r in RUNGS) + " |") + rows = [{r: res[r].get(k) for r in RUNGS} for k in keys] + 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} + print("totals:", ", ".join(f"{r} {tot[r][0]}/{tot[r][1]}" for r in RUNGS)) + for lo, hi in zip(RUNGS, RUNGS[1:]): + both = [x for x in rows if x[lo] is not None and x[hi] is not None] + 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)}") + 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) + + +if __name__ == "__main__": + {"validate": cmd_validate, "build": cmd_build, "report": cmd_report}[sys.argv[1]]() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/real_check_driver.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/real_check_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..678bbe888afa8ae295323a74d13cc80d908b22ad --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/real_check_driver.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Conformance check of a robot driver (lffbench/real/protocol.py, spec lffbench/real/DRIVER.md). Run it on the robot PC +(or through the SSH tunnel) before the first real run, and again after any change to the driver. + + python scripts/real_check_driver.py --driver http://127.0.0.1:9900 --token [--yes] [--operator] [--json] + +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 +the current pose. Keep a hand on the e-stop. --yes skips the confirmation; --operator also tests the operator +prompts (you answer them on the driver's terminal). Needs only Python 3 + numpy + Pillow. +Exit code 0 = every check PASS (WARN does not fail). +""" +import argparse +import json +import os +import sys +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path[:0] = [HERE, os.path.join(os.path.dirname(HERE), "lffbench", "real")] # protocol.py next to it, or the repo copy +import numpy as np # noqa: E402 + +from protocol import (CAMERAS, DriverClient, DriverError, info_problems, state_problems) # noqa: E402 + + +class Checks: + def __init__(self): + self.rows = [] + + def add(self, name, status, detail=""): + self.rows.append(dict(name=name, status=status, detail=str(detail))) + print(f"[{status}] {name} {detail}", file=sys.stderr, flush=True) + return status == "PASS" + + def ok(self, name, cond, detail="", warn=False): + return self.add(name, "PASS" if cond else ("WARN" if warn else "FAIL"), detail) + + +def yaw_diff(a, b): + return abs((a - b + 90.0) % 180.0 - 90.0) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900")) + ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", "")) + ap.add_argument("--yes", action="store_true", help="do not ask before moving the arm") + ap.add_argument("--operator", action="store_true", help="also test the operator prompts (reset, judge)") + ap.add_argument("--json", action="store_true", help="print a JSON summary as the last line of stdout") + ap.add_argument("--yaw-tol", type=float, default=2.0, help="degrees (keep 2 for a real arm)") + a = ap.parse_args() + C = Checks() + d = DriverClient(a.driver, a.token, timeout=120) + try: + run(C, d, a) + except DriverError as e: + C.add("driver answered every request", "FAIL", e) + n_fail = sum(r["status"] == "FAIL" for r in C.rows) + print(f"\n{len(C.rows) - n_fail} ok / {n_fail} FAIL", file=sys.stderr) + if a.json: + print(json.dumps(dict(checks=C.rows, n_fail=n_fail))) + sys.exit(1 if n_fail else 0) + + +def run(C, d, a): + # ---- no motion + bad = DriverClient(d.url, d.token + "-wrong") + try: + rep = bad.call("state", allow_not_ok=True) + C.ok("wrong token is refused", rep.get("ok") is False, rep.get("error", "")) + except DriverError as e: + C.add("wrong token is refused", "FAIL", e) + info = d.call("info") + prob = info_problems(info) + if not C.ok("/info has every field", not prob, "; ".join(prob) or {k: info[k] for k in ("robot", "n_joints", "workspace")}): + return + n = int(info["n_joints"]) + st = d.state() + prob = state_problems(st, n) + if not C.ok("/state has every field", not prob, "; ".join(prob) or st): + return + lo, hi = np.array(info["workspace"]["lo"]), np.array(info["workspace"]["hi"]) + p0 = np.array(st["eef_pos"]) + C.ok("current grasp point inside the declared workspace", bool(np.all(p0 >= lo) and np.all(p0 <= hi)), p0.round(4).tolist()) + t0 = time.time() + frames, st2 = d.observe() + dt = time.time() - t0 + for c in CAMERAS: + f = frames[c] + C.ok(f"/observe {c}: RGB image", f.ndim == 3 and f.shape[2] == 3 and min(f.shape[:2]) >= 256, + f"{f.shape[1]}x{f.shape[0]}") + C.ok(f"/observe {c}: not blank", float(f.std()) > 5.0, f"pixel std {f.std():.1f}") + h, w = f.shape[:2] + C.ok(f"/observe {c}: square or close to it (the benchmark centre-crops to a square)", 0.75 <= w / h <= 1.34, + f"{w}x{h}: {abs(w - h) // 2} px cut on each side", warn=True) + C.ok("/observe also returns the state", not state_problems(st2, n)) + C.ok("/observe latency", dt < 2.0, f"{dt:.2f} s", warn=True) + rep = d.call("event", dict(ev="session_start", run="check_driver", task="check", seed=0)) + C.ok("/event answers", rep["ok"]) + rep = d.operator("notice", run="check_driver", attempt=0, text="real_check_driver.py: conformance check running") + C.ok("/operator notice answers", rep["ok"]) + if info["ik"]: + q = d.ik(st["eef_pos"], st["eef_yaw_deg"]) + err = float(np.max(np.abs(np.array(q) - np.array(st["joint_pos_rad"])))) if len(q) == n else None + C.ok("/ik of the current pose = current joint angles (within 0.05 rad)", err is not None and err < 0.05, + f"max |dq| = {err}") + # ---- rejected targets: must not move + for name, tgt in (("far outside the workspace (x + 1 m)", [hi[0] + 1.0, p0[1], p0[2]]), + ("below the workspace floor (z - 5 cm)", [p0[0], p0[1], lo[2] - 0.05])): + rep = d.move(*tgt, st["eef_yaw_deg"], 0.05) + moved = float(np.linalg.norm(np.array(rep["state"]["eef_pos"]) - p0)) + C.ok(f"/move {name} is rejected and the arm does not move", rep["ok"] is False and moved < 0.005, + f"ok={rep['ok']} error={rep.get('error')!r} moved {moved * 100:.1f} cm") + # ---- motion + if not a.yes: + 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" + "Keep a hand on the e-stop and press Enter... ") + up = p0 + [0.0, 0.0, 0.03] + if up[2] > hi[2]: + up = p0 - [0.0, 0.0, 0.03] + y0 = float(st["eef_yaw_deg"]) + rep = d.move(*up, y0, 0.05) + p = np.array(rep["state"]["eef_pos"]) + C.ok("/move 3 cm vertical: ok", rep["ok"], rep.get("error", "")) + 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") + 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']}") + C.ok("/move keeps the yaw (within 2 deg)", yaw_diff(rep["state"]["eef_yaw_deg"], y0) < 2.0, + f"{rep['state']['eef_yaw_deg']:.1f} vs {y0:.1f}") + y1 = y0 + 30.0 if y0 + 30.0 <= info["yaw_range_deg"][1] else y0 - 30.0 + rep = d.move(*up, y1, 0.05) + 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, + f"{rep['state']['eef_yaw_deg']:.1f} vs {y1:.1f}") + C.ok("/move turn 30 deg: position kept (within 5 mm)", np.linalg.norm(np.array(rep["state"]["eef_pos"]) - up) < 0.005) + sign = 1.0 if y1 > y0 else -1.0 + C.add("yaw sign (look at the arm)", "NOTE", + f"it just turned {sign * 30:+.0f} deg: + must be counter-clockwise seen from above (DRIVER.md §3)") + rep = d.move(*up, y0, 0.05) + C.ok("/move turn back", rep["ok"] and yaw_diff(rep["state"]["eef_yaw_deg"], y0) < a.yaw_tol, + f"{rep['state']['eef_yaw_deg']:.1f} vs {y0:.1f}") + rep = d.gripper(True) + w_closed = rep["state"]["gripper_width_m"] + 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']}") + rep = d.gripper(False) + w_open = rep["state"]["gripper_width_m"] + C.ok("/gripper open: width > 3 cm", w_open > 0.03, f"{w_open:.4f} m") + rep = d.move(*p0, y0, 0.05) + C.ok("/move back to the start pose", rep["ok"] and np.linalg.norm(np.array(rep["state"]["eef_pos"]) - p0) < 0.005) + rep = d.home() + C.ok("/home answers with the state", rep["ok"] and not state_problems(rep["state"], n)) + rep = d.call("event", dict(ev="attempt_start", run="check_driver", attempt=1)) # starts the driver's recorder + time.sleep(2.0) + rep2 = d.call("event", dict(ev="attempt_end", run="check_driver", attempt=1)) + C.ok("/event attempt_start / attempt_end answer (recording)", rep["ok"] and rep2["ok"], + "check that the driver wrote a short video (driver_template: /check_driver_a1.mp4)") + if a.operator: + rep = d.operator("reset", run="check_driver", attempt=1, setup="(test) nothing to change, just press Enter") + C.ok("/operator reset returns after Enter", rep["ok"]) + rep = d.operator("judge", run="check_driver", attempt=1, checklist=["(test) answer y"]) + C.ok("/operator judge returns success", rep.get("success") is True, rep) + d.call("event", dict(ev="session_end", run="check_driver")) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/record_breakfast_service.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/record_breakfast_service.py new file mode 100644 index 0000000000000000000000000000000000000000..bc1731b46da0c9383c1513fde541833bfbbd8180 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/record_breakfast_service.py @@ -0,0 +1,89 @@ +"""Continuous simulation recording with a magnified crop; no state edits or model calls.""" +import argparse, hashlib, json +from pathlib import Path +import imageio.v2 as imageio +import numpy as np +from PIL import Image, ImageDraw, ImageFont +from lffbench import envs +from lffbench.tasks.lh_breakfast_service import BreakfastService +import robosuite.utils.transform_utils as T + +FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' + +class Recorder: + def __init__(self,t,out): + self.t=t;self.out=out;self.n=0;self.frames=0;self.timeline=[] + self.phase='Prepare breakfast';self.focus='food';self.raw_n=0 + self.raw=imageio.get_writer(str(out/'breakfast_full_1x.mp4'),fps=5,codec='libx264',quality=8,macro_block_size=1) + self.preview=imageio.get_writer(str(out/'breakfast_recovery_2x.mp4'),fps=10,codec='libx264',quality=8,macro_block_size=1) + self.original=t.env.step;t.env.step=self.step + # Rendering-only side camera makes the reopened lid's gap visible. + m=t.env.sim.model;cid=m.camera_name2id('sideview') + pos=np.array([-.28,-.58,1.16]);target=np.array([-.20,-.10,.96]) + 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) + q=T.mat2quat(np.column_stack([x,y,z])) + m.cam_pos[cid]=pos;m.cam_quat[cid]=q[[3,0,1,2]];m.cam_fovy[cid]=45 + t.env.sim.forward() + def step(self,a): + result=self.original(a);self.n+=1 + if self.n%4==0:self.capture() + return result + def frame(self): + return Image.fromarray(envs.render(self.t.env,res=768)) + def decorate(self,im): + canvas=Image.new('RGB',(1280,928),(19,26,36));canvas.paste(im,(0,48)) + crop={'milk':(440,180,760,500),'lid':(150,230,470,550),'food':(0,220,320,540)}[self.focus] + detail=(Image.fromarray(envs.render(self.t.env,cam='sideview',res=512)) if self.focus=='lid' + else im.crop(crop).resize((512,512),Image.Resampling.LANCZOS)) + canvas.paste(detail,(768,80)) + d=ImageDraw.Draw(canvas);f=ImageFont.truetype(FONT,24);sm=ImageFont.truetype(FONT,20) + d.text((18,10),'BREAKFAST | scripted recovery reference | same attempt | 2x',font=f,fill='white') + d.text((785,52),'Synchronized side view' if self.focus=='lid' else 'Magnified detail from the same frame',font=sm,fill='#b5ccdf') + q=self.t.liquid + for n,line in enumerate([f'Simulation: {self.n*.05:.1f} s',f'Milk in cup: {q["cup"]:.1f} mL', + f'Spilled: {q["spill"]:.1f} mL',f'Pantry lid: {self.t.lid_deg():.1f} deg', + f'Butter height: {100*self.t.butter_height():.1f} cm']): + d.text((790,620+36*n),line,font=f,fill='white') + d.text((18,830),self.phase,font=f,fill='#ffe0a2') + d.text((18,874),'Milk: simplified flow + ballistic parcels; rigid objects: MuJoCo contacts.',font=sm,fill='#b5ccdf') + return np.asarray(canvas) + def capture(self): + im=self.frame();self.raw.append_data(np.asarray(im));self.raw_n+=1 + self.preview.append_data(self.decorate(im));self.frames+=1 + def phase_hook(self,text,state): + if text.startswith(('Tipping handle:','Returning handle:','Bread pickup:','Bread placement:')):return + if 'carton' in text or 'cradle' in text or 'milk' in text.lower():self.focus='milk' + 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' + else:self.focus='food' + self.phase=text + row=dict(state,preview_time_s=self.frames/10,preview_frame=self.frames) + self.timeline.append(row) + im=self.frame();Image.Image.save(im,self.out/f'checkpoint_{len(self.timeline):02d}.png') + # Explicit presentation hold only; no simulation reset or omitted motion. + for _ in range(10):self.preview.append_data(self.decorate(im));self.frames+=1 + print(json.dumps(row,default=lambda v:v.item()),flush=True) + def close(self): + self.t.env.step=self.original;self.raw.close();self.preview.close() + +def main(): + p=argparse.ArgumentParser();p.add_argument('--out',required=True);p.add_argument('--seed',type=int,default=1000) + a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + t=BreakfastService();inst=t.sample_instance(a.seed);t.reset_instance(inst) + r=Recorder(t,out);t.phase_hook=r.phase_hook + try: + t.execute(inst,{'mode':'adaptive'});result=t.outcome(inst) + r.phase_hook('FINAL: breakfast served; all three failures recovered' if result['success'] else 'FINAL: verification failed', + dict(step=t.sk.n_steps,outcome=result)) + finally:r.close() + files=[Path(__file__).resolve().parents[1]/'lffbench/tasks'/n for n in + ('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')] + meta=dict(seed=a.seed,instance=inst,outcome=result,continuous_attempt=True,resets_during_recording=0, + source_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files}, + sim_seconds=r.n*.05,raw_frames=r.raw_n,preview_frames=r.frames,timeline=r.timeline, + presentation='2x with 1 s freeze at labeled checkpoints; full 1x has no presentation freezes', + video_hashes={f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in out.glob('*.mp4')}) + (out/'recording.json').write_text(json.dumps(meta,indent=2,default=lambda v:v.item())) + assert result['success'] and all(result['traps'].values()) and all(result['recovered'].values()),result + t.env.close() + +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/__init__.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..83156cde5c65996496e06fed2b8785dee57aa688 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/__init__.py @@ -0,0 +1,21 @@ +"""Model backends. Import lazily: each API backend needs its provider's SDK (see base.import_sdk).""" +from .base import AttemptInfo, Backend, BackendResponse, RunInfo # noqa: F401 + + +def make_backend(kind, **kw): + if kind == "scripted": + from .scripted import ScriptedBackend + return ScriptedBackend(**kw) + if kind == "openai": + from .openai_responses import OpenAIResponsesBackend + return OpenAIResponsesBackend(**kw) + if kind == "chat": + from .chat_completions import ChatCompletionsBackend + return ChatCompletionsBackend(**kw) + if kind == "anthropic": + from .anthropic_messages import AnthropicMessagesBackend + return AnthropicMessagesBackend(**kw) + if kind == "gemini": + from .gemini import GeminiBackend + return GeminiBackend(**kw) + raise ValueError(kind) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/anthropic_messages.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/anthropic_messages.py new file mode 100644 index 0000000000000000000000000000000000000000..f5072778c98c46c70a5b33190d4621b5af244cd2 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/anthropic_messages.py @@ -0,0 +1,202 @@ +"""Anthropic Messages API backend (Claude Opus 5.5 / Sonnet 5.5 / Fable 5.1 ...), official SDK `anthropic`. + +Same conversation as the OpenAI backends, converted to Messages API blocks: +- system prompt = conv.system; tools = the harness tool specs (strict, one call per turn like the GPT player); +- every assistant turn is stored with its full `content` (thinking blocks with signatures, text, tool_use) and replayed + unchanged, so the model keeps its reasoning across tool calls. Assistant turns are never edited; old images in user + turns may be replaced by a text note (checked 2026-10-15 on Sonnet 5.5 / Opus 5.5 with thinking blocks in the + history: accepted), which the player does only when the context or the per-request image limit is reached; +- tool outputs of one turn become `tool_result` blocks at the start of the next user message; images the harness + attaches after them (observations, view_images) follow in the same user message; +- adaptive thinking with an explicit effort (the per-model default differs: Opus 5.5 medium, Sonnet 5.5 high); +- automatic prompt caching (top-level cache_control): every request caches its whole prefix for the next call; +- streaming, so long thinking turns do not hit the HTTP timeout. +No refusal fallback on purpose: a fallback would silently swap the model under test. A refusal is reported as +status "refusal" and the player ends the run. + +Key from ANTHROPIC_API_KEY (or any credential the SDK resolves). The client is created lazily on the first real +call; tests inject a mock client. +""" +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_sdk + +EFFORTS = ("low", "medium", "high", "xhigh", "max") + + +def _get(obj, key, default=None): + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + +def _to_dict(block): + if isinstance(block, dict): + return dict(block) + if hasattr(block, "to_dict"): + return block.to_dict() + return block.model_dump(mode="json", exclude_none=True) + + +def anthropic_tools(specs, strict=True): + out = [] + for s in specs: + t = dict(name=s["name"], description=s["description"], input_schema=s["parameters"]) + if strict: + t["strict"] = True + out.append(t) + return out + + +def image_block(image, quality=None): + url = image.data_url(quality) + head, data = url.split(",", 1) # data:;base64, + mime = head[len("data:"):].split(";", 1)[0] + return dict(type="image", source=dict(type="base64", media_type=mime, data=data)) + + +class AnthropicMessagesBackend(Backend): + name = "anthropic" + + def __init__(self, model="claude-opus-5-5", effort="high", thinking_display="summarized", max_tokens=64000, + max_live_images=None, jpeg_quality=90, timeout=900.0, max_retries=2, strict_tools=True, + parallel_tool_calls=False, cache=True, client=None): + if effort not in EFFORTS: + raise ValueError(f"effort must be one of {EFFORTS}, got {effort!r}") + self.model = model + self.effort = effort + self.thinking_display = thinking_display # "summarized" (logged as the reasoning summary) | "omitted" + self.max_tokens = max_tokens + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self.max_retries = max_retries + self.strict_tools = strict_tools + self.parallel_tool_calls = parallel_tool_calls + self.cache = cache + self._client = client + + def config(self): + return dict(name=self.name, model=self.model, effort=self.effort, thinking_display=self.thinking_display, + max_tokens=self.max_tokens, max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, + timeout=self.timeout, max_retries=self.max_retries, strict_tools=self.strict_tools, + parallel_tool_calls=self.parallel_tool_calls, cache=self.cache) + + def client(self): + if self._client is None: + anthropic = import_sdk("anthropic") + self._client = anthropic.Anthropic(timeout=self.timeout, max_retries=self.max_retries) + return self._client + + # ------------------------------------------------------------------ request + def convert_items(self, items): + msgs = [] + + def push(role, blocks): + if msgs and msgs[-1]["role"] == role: + msgs[-1]["content"].extend(blocks) + else: + msgs.append(dict(role=role, content=list(blocks))) + + for it in items: + kind = it["kind"] + if kind == "user": + blocks = [] + for p in it["parts"]: + if p["type"] == "text": + blocks.append(dict(type="text", text=p["text"])) + else: + blocks.append(image_block(p["image"], self.jpeg_quality)) + push("user", blocks) + elif kind == "assistant": + if it.get("raw") is not None and it.get("backend") == self.name: + blocks = [dict(b) for b in it["raw"]] + else: # a turn produced by another backend: plain text + tool calls, no thinking + blocks = ([dict(type="text", text=it["text"])] if it.get("text") else []) + blocks += [dict(type="tool_use", id=tc.id, name=tc.name, input=tc.arguments) + for tc in it["tool_calls"]] + if not blocks: + blocks = [dict(type="text", text="(no output)")] + push("assistant", blocks) + elif kind == "tool_output": + push("user", [dict(type="tool_result", tool_use_id=it["call_id"], content=it["text"])]) + else: + raise ValueError(kind) + return msgs + + def build_request(self, conv, tools): + items = prune_live_images(conv.items, self.max_live_images) + req = dict(model=self.model, max_tokens=int(self.max_tokens), system=conv.system, + messages=self.convert_items(items), tools=anthropic_tools(tools, self.strict_tools), + tool_choice=dict(type="auto", disable_parallel_tool_use=not self.parallel_tool_calls), + thinking=dict(type="adaptive", display=self.thinking_display), + output_config=dict(effort=self.effort)) + if self.cache: + req["cache_control"] = dict(type="ephemeral") + return req + + @staticmethod + def request_stats(req): + n_img, img_bytes, txt = 0, 0, len(req.get("system") or "") + for m in req["messages"]: + for b in m["content"]: + t = b.get("type") + if t == "image": + n_img += 1 + img_bytes += len(b["source"]["data"]) + elif t == "text": + txt += len(b["text"]) + elif t == "tool_result": + txt += len(b["content"]) if isinstance(b["content"], str) else 0 + return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_messages=len(req["messages"])) + + # ------------------------------------------------------------------ call + def act(self, conv, tools): + req = self.build_request(conv, tools) + stats = self.request_stats(req) + t0 = time.time() + try: + with self.client().messages.stream(**req) as stream: + msg = stream.get_final_message() + except AssertionError: # the SDK asserts on a stream without message_start (seen through a gateway) + raise RuntimeError("empty response stream (no message_start event)") from None + out = self.parse_response(msg) + out.latency_s = time.time() - t0 + out.request_stats = stats + return out + + def parse_response(self, msg): + calls, texts, summ = [], [], [] + content = _get(msg, "content") or [] + for b in content: + t = _get(b, "type") + if t == "tool_use": + args = _get(b, "input") or {} + calls.append(ToolCall(id=_get(b, "id"), name=_get(b, "name"), arguments=dict(args))) + elif t == "text": + texts.append(_get(b, "text") or "") + elif t == "thinking": + if _get(b, "thinking"): + summ.append(_get(b, "thinking")) + u = _get(msg, "usage") + usage = {} + if u is not None: + fresh = _get(u, "input_tokens", 0) or 0 + read = _get(u, "cache_read_input_tokens", 0) or 0 + write = _get(u, "cache_creation_input_tokens", 0) or 0 + # same meaning as the OpenAI backend: input_tokens = whole prompt, cached_tokens = the part read from cache + usage = dict(input_tokens=fresh + read + write, cached_tokens=read, cache_write_tokens=write, + output_tokens=_get(u, "output_tokens", 0) or 0, reasoning_tokens=0) + stop = _get(msg, "stop_reason") + status, err = "completed", None + if stop == "refusal": + d = _get(msg, "stop_details") + status, err = "refusal", f"refusal: category={_get(d, 'category')} {_get(d, 'explanation') or ''}".strip() + elif stop == "max_tokens": + status, err = "incomplete", "incomplete: max_tokens" + elif not content and u is None: + status, err = "incomplete", "empty response (no content, no usage)" + return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None, + reasoning_summary="\n".join(summ) or None, usage=usage, + raw=[_to_dict(b) for b in content], status=status, error=err) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/base.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/base.py new file mode 100644 index 0000000000000000000000000000000000000000..214f2e2f1a11942180f655914409b7d43b45723d --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/base.py @@ -0,0 +1,82 @@ +"""Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s).""" +import os +import sys +from dataclasses import dataclass, field +from typing import Optional + +# Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh). +# Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name: +# LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence. +API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "") +OPENAI_SDK_DIR = API_SDK_DIR # old name + + +def import_sdk(module): + """Import an API SDK module ("openai", "anthropic", "google.genai").""" + import importlib + try: + return importlib.import_module(module) + except ImportError: + if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path: + sys.path.append(API_SDK_DIR) + return importlib.import_module(module) + + +def import_openai(): + return import_sdk("openai") + + +@dataclass +class BackendResponse: + tool_calls: list = field(default_factory=list) # [ToolCall] + text: Optional[str] = None # visible assistant text (e.g. the diagnosis) + reasoning_summary: Optional[str] = None + usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens + latency_s: float = 0.0 + raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items) + request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ... + status: str = "ok" + error: Optional[str] = None + + +@dataclass +class RunInfo: + task: object # privileged: only the scripted backend may look at task / inst + inst: dict + seed: int + k: int + protocol: str + feedback: str + memory: str + + +@dataclass +class AttemptInfo: + attempt: int + history: list # AttemptRecords visible to the agent under the memory mode (already selected) + continuing: bool = False # within protocol: continuing after a failed done + + +class Backend: + name = "base" + + def begin_run(self, info: RunInfo): + pass + + def begin_attempt(self, info: AttemptInfo): + pass + + def act(self, conv, tools) -> BackendResponse: + raise NotImplementedError + + def on_tool_result(self, call, result): + pass + + def end_attempt(self) -> dict: + return {} + + def end_run(self): + pass + + def config(self) -> dict: + return dict(name=self.name) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/chat_completions.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/chat_completions.py new file mode 100644 index 0000000000000000000000000000000000000000..ec6c2cebb3976390ef7ed172d4b8edbb870a092f --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/chat_completions.py @@ -0,0 +1,150 @@ +"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served +by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format. + +Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard +message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent +back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and +Responses backends do (Kimi's docs ask for this in multi-step tool use).""" +import json +import os +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_openai + + +def chat_tools(specs): + return [dict(type="function", function=dict(name=s["name"], description=s["description"], + parameters=s["parameters"])) for s in specs] + + +class ChatCompletionsBackend(Backend): + name = "chat" + + def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024, + max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None, + replay_reasoning=True): + self.model = model + self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1") + self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY") + self.temperature = temperature + self.max_tokens = max_tokens + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self.extra_body = extra_body + self.replay_reasoning = replay_reasoning + self._client = client + + def config(self): + return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature, + max_tokens=self.max_tokens, max_live_images=self.max_live_images, + replay_reasoning=self.replay_reasoning) + + def client(self): + if self._client is None: + openai = import_openai() + kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1) + if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")): + # local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here) + kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout) + self._client = openai.OpenAI(**kw) + return self._client + + def build_request(self, conv, tools): + msgs = [dict(role="system", content=conv.system)] + for it in prune_live_images(conv.items, self.max_live_images): + if it["kind"] == "user": + content = [] + for p in it["parts"]: + if p["type"] == "text": + content.append(dict(type="text", text=p["text"])) + else: + content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality)))) + msgs.append(dict(role="user", content=content)) + elif it["kind"] == "assistant": + if not it.get("text") and not it["tool_calls"]: + # a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still + # counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content + # nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request + continue + m = dict(role="assistant", content=it.get("text") or None) + rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None + if rc and self.replay_reasoning: + m["reasoning_content"] = rc + if it["tool_calls"]: + m["tool_calls"] = [dict(id=tc.id, type="function", + function=dict(name=tc.name, + arguments=tc.raw_arguments or json.dumps(tc.arguments))) + for tc in it["tool_calls"]] + msgs.append(m) + elif it["kind"] == "tool_output": + msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"])) + req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto", + max_tokens=self.max_tokens) + if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature) + req["temperature"] = self.temperature + if self.extra_body: + req["extra_body"] = dict(self.extra_body) + return req + + def act(self, conv, tools): + req = self.build_request(conv, tools) + n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list) + for c in m["content"] if c.get("type") == "image_url") + t0 = time.time() + resp = self.client().chat.completions.create(**req) + lat = time.time() - t0 + stats = dict(n_images=n_img, n_messages=len(req["messages"])) + if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again + return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete", + error="empty response (no choices)") + msg = resp.choices[0].message + rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content") + calls = [] + for i, tc in enumerate(msg.tool_calls or []): + raw = tc.function.arguments or "" + try: + args = json.loads(raw) if raw else {} + except json.JSONDecodeError: + args = {} + calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw)) + u = resp.usage + ctd = getattr(u, "completion_tokens_details", None) if u else None + usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0, + output_tokens=getattr(u, "completion_tokens", 0) or 0, + reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {} + if not calls and not msg.content and not rc and not u: + return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete", + error="empty response (no output, no usage)") + return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage, + latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats) + + +def tool_results_first(msgs): + """OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly + after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's + output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool + messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after + the last tool message of the turn; nothing else changes order.""" + out, i = [], 0 + while i < len(msgs): + m = msgs[i] + out.append(m) + i += 1 + if m["role"] != "assistant" or not m.get("tool_calls"): + continue + need = {tc["id"] for tc in m["tool_calls"]} + held = [] + while i < len(msgs) and need: + n = msgs[i] + if n["role"] == "tool" and n.get("tool_call_id") in need: + out.append(n) + need.discard(n["tool_call_id"]) + elif n["role"] == "user": + held.append(n) + else: + break + i += 1 + out.extend(held) + return out diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/gemini.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4240f299561c36a664bf40ab8dceaf44715cf8 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/gemini.py @@ -0,0 +1,206 @@ +"""Google Gemini backend (Gemini API, official SDK `google-genai`). + +Same conversation as the other backends, converted to Gemini `contents`: +- system prompt = system_instruction; tools = function declarations with the harness's JSON schemas; +- every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive) + and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call; +- tool outputs of one turn become `function_response` parts at the start of the next user content; images the + harness attaches after them follow in the same user content; +- thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged; +- implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage). + +Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock. +""" +import base64 +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_sdk + + +def _get(obj, key, default=None): + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + +def _strip_additional(schema): + """The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema.""" + if isinstance(schema, dict): + return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"} + if isinstance(schema, list): + return [_strip_additional(v) for v in schema] + return schema + + +def _image_part(image, quality=None): + head, data = image.data_url(quality).split(",", 1) + mime = head[len("data:"):].split(";", 1)[0] + return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data))) + + +class GeminiBackend(Backend): + name = "gemini" + + def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True, + max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90, + timeout=900.0, client=None): + self.model = model + self.thinking_level = thinking_level + self.thinking_budget = thinking_budget + self.include_thoughts = include_thoughts + self.max_output_tokens = max_output_tokens + self.media_resolution = media_resolution + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self._client = client + self._json_schema_field = None + + def config(self): + return dict(name=self.name, model=self.model, thinking_level=self.thinking_level, + thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts, + max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution, + max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout) + + def client(self): + if self._client is None: + genai = import_sdk("google.genai") + self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000))) + return self._client + + def _declarations(self, specs): + if self._json_schema_field is None: + try: + types = import_sdk("google.genai.types") + self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields + except ImportError: # tests without the SDK + self._json_schema_field = True + out = [] + for s in specs: + d = dict(name=s["name"], description=s["description"]) + if self._json_schema_field: + d["parameters_json_schema"] = s["parameters"] + else: + d["parameters"] = _strip_additional(s["parameters"]) + out.append(d) + return [dict(function_declarations=out)] + + # ------------------------------------------------------------------ request + def convert_items(self, items): + contents = [] + + def push(role, parts): + if contents and contents[-1]["role"] == role: + contents[-1]["parts"].extend(parts) + else: + contents.append(dict(role=role, parts=list(parts))) + + for it in items: + kind = it["kind"] + if kind == "user": + parts = [] + for p in it["parts"]: + if p["type"] == "text": + parts.append(dict(text=p["text"])) + else: + parts.append(_image_part(p["image"], self.jpeg_quality)) + push("user", parts) + elif kind == "assistant": + if it.get("raw") is not None and it.get("backend") == self.name: + content = dict(it["raw"][0]) + contents.append(dict(role="model", parts=list(content.get("parts") or []))) + continue + parts = ([dict(text=it["text"])] if it.get("text") else []) + parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]] + push("model", parts or [dict(text="(no output)")]) + elif kind == "tool_output": + fr = dict(name=it["name"], response=dict(output=it["text"])) + if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"): + fr["id"] = it["call_id"] + push("user", [dict(function_response=fr)]) + else: + raise ValueError(kind) + return contents + + def build_request(self, conv, tools): + items = prune_live_images(conv.items, self.max_live_images) + thinking = dict(include_thoughts=self.include_thoughts) + if self.thinking_budget is not None: + thinking["thinking_budget"] = int(self.thinking_budget) + elif self.thinking_level: + thinking["thinking_level"] = self.thinking_level + config = dict(system_instruction=conv.system, tools=self._declarations(tools), + tool_config=dict(function_calling_config=dict(mode="AUTO")), + automatic_function_calling=dict(disable=True), thinking_config=thinking, + max_output_tokens=int(self.max_output_tokens)) + if self.media_resolution: + config["media_resolution"] = self.media_resolution + return dict(model=self.model, contents=self.convert_items(items), config=config) + + @staticmethod + def request_stats(req): + n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "") + for c in req["contents"]: + for p in c["parts"]: + p = p if isinstance(p, dict) else {} + if p.get("inline_data"): + n_img += 1 + img_bytes += len(p["inline_data"]["data"]) + elif p.get("text"): + txt += len(p["text"]) + elif p.get("function_response"): + txt += len(str(p["function_response"].get("response", ""))) + return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"])) + + # ------------------------------------------------------------------ call + def act(self, conv, tools): + req = self.build_request(conv, tools) + stats = self.request_stats(req) + types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys + t0 = time.time() + resp = self.client().models.generate_content( + model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]], + config=types.GenerateContentConfig.model_validate(req["config"])) + out = self.parse_response(resp) + out.latency_s = time.time() - t0 + out.request_stats = stats + return out + + def parse_response(self, resp): + cands = _get(resp, "candidates") or [] + cand = cands[0] if cands else None + content = _get(cand, "content") if cand is not None else None + parts = (_get(content, "parts") or []) if content is not None else [] + calls, texts, summ = [], [], [] + for i, p in enumerate(parts): + fc = _get(p, "function_call") + if fc is not None: + cid = _get(fc, "id") or f"gemini_call_{i}" + calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {}))) + elif _get(p, "text"): + (summ if _get(p, "thought") else texts).append(_get(p, "text")) + u = _get(resp, "usage_metadata") + usage = {} + if u is not None: + usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0, + cached_tokens=_get(u, "cached_content_token_count", 0) or 0, + output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0), + reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0) + finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE" + status, err = "completed", None + if not parts: + status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})" + elif "MAX_TOKENS" in finish or "MALFORMED" in finish: + status, err = "incomplete", f"incomplete: finish_reason={finish}" + elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish: + status, err = "refusal", f"refusal: finish_reason={finish}" + if content is not None and hasattr(content, "model_dump"): + raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes + elif content is not None: + raw = [dict(content)] + else: + raw = None + return BackendResponse(tool_calls=calls, text="\n".join(texts) or None, + reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw, + status=status, error=err) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py new file mode 100644 index 0000000000000000000000000000000000000000..853ba2d0cafd5859a689816ee7541ea3f0d41ca4 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py @@ -0,0 +1,240 @@ +"""OpenAI Responses API backend (default model gpt-6-astra). + +Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with +store=False; reasoning items are replayed with their encrypted content so the model keeps its chain +of thought across tool calls within an attempt. The request prefix (instructions, tools, task text, +packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what +OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs. + +Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time; +the client is created lazily on the first real call (tests inject a mock client). +""" +import json +import os +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_openai + +# GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported. +GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max") + + +def _get(obj, key, default=None): + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + +def _to_dict(item): + if isinstance(item, dict): + return dict(item) + if hasattr(item, "to_dict"): + return item.to_dict(mode="json") + if hasattr(item, "model_dump"): + return item.model_dump(mode="json", exclude_none=True) + return dict(vars(item)) + + +def responses_tools(specs, strict=True): + return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"], + strict=strict) for s in specs] + + +class OpenAIResponsesBackend(Backend): + name = "openai" + + def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto", + max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None, + store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0, + max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last", + prompt_cache_options=None, client=None, http_client=None): + if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS: + raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), " + f"got {reasoning_effort!r}") + self.model = model + self.reasoning_effort = reasoning_effort + self.reasoning_summary = reasoning_summary + self.image_detail = image_detail + self.max_output_tokens = max_output_tokens + self.service_tier = service_tier + self.prompt_cache_key = prompt_cache_key + self.prompt_cache_retention = prompt_cache_retention + self.store = store + self.replay_reasoning = replay_reasoning + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self.max_retries = max_retries + self.extra_body = extra_body + self.strict_tools = strict_tools + # explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last" + assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints + self.cache_breakpoints = cache_breakpoints + self.prompt_cache_options = prompt_cache_options + self._client = client + self._http_client = http_client # optional custom transport (tests, proxies) + self._cache_key = prompt_cache_key + + def config(self): + return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort, + reasoning_summary=self.reasoning_summary, image_detail=self.image_detail, + max_output_tokens=self.max_output_tokens, service_tier=self.service_tier, + prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention, + store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images, + jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries, + extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints, + prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL")) + + # ------------------------------------------------------------------ client + def client(self): + if self._client is None: + key = os.environ.get("OPENAI_API_KEY") + if not key: + raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it") + openai = import_openai() + kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout, + max_retries=self.max_retries) + if self._http_client is not None: + kw["http_client"] = self._http_client + self._client = openai.OpenAI(**kw) + return self._client + + def begin_run(self, info): + if self.prompt_cache_key is None: + # route all calls of one run to the same cache shard + self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}" + + # ------------------------------------------------------------------ request + def convert_items(self, items): + out = [] + last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1) + for i, it in enumerate(items): + kind = it["kind"] + if kind == "user": + content = [] + for p in it["parts"]: + if p["type"] == "text": + content.append(dict(type="input_text", text=p["text"])) + else: + content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality), + detail=self.image_detail)) + # explicit cache breakpoints: end of the stable history item (byte-identical for the whole + # attempt) and end of the newest input (reused by the next call of the attempt) + if content and ((self.cache_breakpoints != "none" and not it.get("live")) + or (self.cache_breakpoints == "history+last" and i == last_user)): + content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit") + out.append(dict(role="user", content=content)) + elif kind == "assistant": + if it.get("raw") and it.get("backend") == self.name: + for r in it["raw"]: + if r.get("type") == "reasoning" and not self.replay_reasoning: + continue + out.append(r) + else: + if it.get("text"): + out.append(dict(role="assistant", content=it["text"])) + for tc in it["tool_calls"]: + out.append(dict(type="function_call", call_id=tc.id, name=tc.name, + arguments=tc.raw_arguments or json.dumps(tc.arguments))) + elif kind == "tool_output": + out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"])) + else: + raise ValueError(kind) + return out + + def build_request(self, conv, tools): + items = prune_live_images(conv.items, self.max_live_images) + req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items), + tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False, + store=self.store) + reasoning = dict(effort=self.reasoning_effort) + if self.reasoning_summary: + reasoning["summary"] = self.reasoning_summary + req["reasoning"] = reasoning + if not self.store and self.replay_reasoning: + req["include"] = ["reasoning.encrypted_content"] + if self.max_output_tokens: + req["max_output_tokens"] = int(self.max_output_tokens) + if self.service_tier: + req["service_tier"] = self.service_tier + if self._cache_key: + req["prompt_cache_key"] = self._cache_key + if self.prompt_cache_retention: + req["prompt_cache_retention"] = self.prompt_cache_retention + if self.prompt_cache_options: + req["prompt_cache_options"] = dict(self.prompt_cache_options) + if self.extra_body: + req["extra_body"] = dict(self.extra_body) + return req + + @staticmethod + def request_stats(req): + n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "") + for it in req["input"]: + for c in (it.get("content") if isinstance(it.get("content"), list) else []): + if c.get("type") == "input_image": + n_img += 1 + img_bytes += len(c["image_url"]) + elif "text" in c: + txt += len(c["text"]) + if isinstance(it.get("content"), str): + txt += len(it["content"]) + if it.get("type") == "function_call_output": + txt += len(it["output"]) if isinstance(it["output"], str) else 0 + if it.get("type") == "function_call": + txt += len(it.get("arguments", "")) + tools_chars = len(json.dumps(req.get("tools", []))) + return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars, + n_input_items=len(req["input"])) + + # ------------------------------------------------------------------ call + def act(self, conv, tools): + req = self.build_request(conv, tools) + stats = self.request_stats(req) + t0 = time.time() + resp = self.client().responses.create(**req) + out = self.parse_response(resp) + out.latency_s = time.time() - t0 + out.request_stats = stats + return out + + def parse_response(self, resp): + calls, texts, summ = [], [], [] + output = _get(resp, "output") or [] + for item in output: + t = _get(item, "type") + if t == "function_call": + raw = _get(item, "arguments") or "" + try: + args = json.loads(raw) if raw else {} + except json.JSONDecodeError: + args = {} + calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args, + raw_arguments=raw)) + elif t == "message": + for c in _get(item, "content") or []: + if _get(c, "type") == "output_text": + texts.append(_get(c, "text") or "") + elif t == "reasoning": + for s in _get(item, "summary") or []: + summ.append(_get(s, "text") or "") + u = _get(resp, "usage") + usage = {} + if u is not None: + itd = _get(u, "input_tokens_details") + otd = _get(u, "output_tokens_details") + usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0, + cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0, + cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0, + output_tokens=_get(u, "output_tokens", 0) or 0, + reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0) + status = _get(resp, "status") or "completed" + err = None + if status == "incomplete": + err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason")) + elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again + status, err = "incomplete", "empty response (no output, no usage)" + return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None, + reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage, + raw=[_to_dict(i) for i in output], status=status, error=err) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/scripted.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/scripted.py new file mode 100644 index 0000000000000000000000000000000000000000..c30b4b503af9c5801b4667276881f16bbbae3e4b --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/agent/backends/scripted.py @@ -0,0 +1,210 @@ +"""Scripted backend: no model. Runs a task's scripted reference policy (adaptive by default) through the +agent tool interface, to test the harness end to end. + +How: the task's own `execute(inst, params)` runs in a worker thread with `task.sk` replaced by a proxy. +Every Skills primitive it calls (move_to / set_gripper / push / grasp_at / place_at) becomes an agent +tool call that is handed to the harness, executed by the ToolExecutor on the main thread, and its +report is returned to the worker. Only one thread runs at a time (queues hand control back and forth), +so MuJoCo is never touched concurrently. Only schema-valid tool calls are emitted, so this also shows +that the tool interface is expressive enough for the task. + +The scripted policy is privileged: it reads the instance (layout) like the task's reference policies +do. It sees earlier attempts only through the memory mode chosen by the harness and only the outcome +fields allowed by the feedback level (F2: structured measurement, F1: success flag, F0: nothing); if +the adaptive rule cannot run on what it sees, it falls back to the task's blind retry rule. +Supported: cross-protocol tasks that implement execute/default_params/adapt_params (+ oracle/blind). +""" +import math +import queue +import threading +import traceback + +import numpy as np + +from ..context import ToolCall +from .base import Backend, BackendResponse + +TIMEOUT_S = 600 + + +class _Abort(Exception): + pass + + +class _Channel: + def __init__(self): + self.req = queue.Queue() + self.res = queue.Queue() + + def call(self, name, args): # worker side + self.req.put(("call", name, args)) + kind, payload = self.res.get(timeout=TIMEOUT_S) + if kind == "abort": + raise _Abort() + return payload + + +class SkillsProxy: + """Stands in for task.sk inside task.execute(); primitives become agent tool calls.""" + + def __init__(self, real, channel): + self._real = real + self._ch = channel + self.untooled_hold_steps = 0 + self.ignored_wrap_yaw_false = 0 + + def move_to(self, target, yaw=None, speed=None, tol=None, max_steps=None, apply_bias=True, wrap_yaw=True): + if not wrap_yaw: # the move_to tool always wraps yaw mod pi (Skills default); counted, not fatal + self.ignored_wrap_yaw_false += 1 + if not apply_bias: + raise NotImplementedError("apply_bias=False cannot be expressed through the agent tools") + yaw_deg = math.degrees(self._real.yaw if yaw is None else float(yaw)) + rep = self._ch.call("move_to", dict(x=float(target[0]), y=float(target[1]), z=float(target[2]), + yaw=round(yaw_deg, 3), speed=None if speed is None else float(speed))) + return dict(prim="move_to", reached=rep.get("reached"), pos=rep.get("eef_pos")) + + def set_gripper(self, close, steps=15): + rep = self._ch.call("close_gripper" if close else "open_gripper", {}) + return dict(prim="close" if close else "open", width=rep.get("gripper_width_m")) + + def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06): + rep = self._ch.call("push", dict(x=float(start_xy[0]), y=float(start_xy[1]), dir_x=float(direction_xy[0]), + dir_y=float(direction_xy[1]), distance=float(distance), speed=float(speed), + z=None if z is None else float(z), runup=float(pre))) + return dict(prim="push", reached=rep.get("sweep_reached"), pos=rep.get("eef_pos")) + + def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15): + self.set_gripper(False, steps=5) + self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw) + self.move_to([xy[0], xy[1], z_grasp]) + self.set_gripper(True) + self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25) + + def place_at(self, xy, z_release, approach=0.10): + self.move_to([xy[0], xy[1], z_release + approach]) + self.move_to([xy[0], xy[1], z_release]) + self.set_gripper(False) + self.move_to([xy[0], xy[1], z_release + approach]) + + def hold(self, steps=10): + # waiting in place has no tool; executed directly (only physics, no new command) and counted + self.untooled_hold_steps += int(steps) + self._real.hold(steps) + + def __getattr__(self, k): # eef_pos, eef_mat, gripper_width, holding, yaw, ... + return getattr(self._real, k) + + +class ScriptedBackend(Backend): + name = "scripted" + + def __init__(self, policy="adaptive", seed=0): + assert policy in ("adaptive", "naive", "oracle", "blind"), policy + self.policy = policy + self.seed = seed + self.info = None + self.rng = None + + def config(self): + return dict(name=self.name, policy=self.policy, seed=self.seed) + + def begin_run(self, info): + if info.protocol != "cross": + raise NotImplementedError("ScriptedBackend supports cross-protocol tasks only (execute/adapt_params)") + self.info = info + self.rng = np.random.default_rng(self.seed + info.seed) + self._oracle = None + if self.policy == "oracle": # privileged scratch rollouts happen before the harness resets the scene + self._oracle = info.task.oracle_params(info.inst) + + # ------------------------------------------------------------------ params from visible history + def _visible(self, rec): + out = rec.outcome + if self.info.feedback == "F2": + vis = dict(out) + elif self.info.feedback == "F1": + vis = dict(success=out.get("success")) + else: + vis = {} + return dict(attempt=rec.attempt, params=rec.backend_meta.get("params"), outcome=vis) + + def _params(self, attempt, history): + task, inst = self.info.task, self.info.inst + if self.policy == "oracle": + return dict(self._oracle), "oracle" + if self.policy == "naive" or not history and self.policy == "adaptive": + return task.default_params(inst), "default" + if self.policy == "blind": + if attempt == 1: + return task.default_params(inst), "default" + return task.blind_params(inst, attempt - 1, self.rng), "blind" + hist = [self._visible(r) for r in history if r.backend_meta.get("params") is not None] + if not hist: + return task.blind_params(inst, attempt - 1, self.rng), "blind(no usable history)" + try: + return task.adapt_params(inst, hist), "adapt" + except (KeyError, TypeError, ValueError): + return task.blind_params(inst, attempt - 1, self.rng), "blind(feedback too coarse)" + + # ------------------------------------------------------------------ attempt + def begin_attempt(self, ainfo): + self.params, self.rule = self._params(ainfo.attempt, ainfo.history) + self.ch = _Channel() + self.thread = None + self.pending = False + self.last_report = None + self.n = 0 + self.proxy = None + + def _worker(self): + try: + self.info.task.execute(self.info.inst, self.params) + self.ch.req.put(("finished", None)) + except _Abort: + pass + except Exception: + self.ch.req.put(("error", traceback.format_exc())) + + def act(self, conv, tools): + if self.thread is None: + task = self.info.task + self.real_sk = task.sk + self.proxy = SkillsProxy(task.sk, self.ch) + task.sk = self.proxy + self.thread = threading.Thread(target=self._worker, daemon=True) + self.thread.start() + elif self.pending: + self.ch.res.put(("result", self.last_report or {})) + self.pending = False + kind, *rest = self.ch.req.get(timeout=TIMEOUT_S) + self.n += 1 + if kind == "call": + name, args = rest[0], rest[1] + self.pending = True + tc = ToolCall(id=f"scripted_{self.n}", name=name, arguments=args) + text = None + if self.n == 1: + text = f"[scripted {self.policy}: rule={self.rule}, params={self.params}]" + return BackendResponse(tool_calls=[tc], text=text) + if kind == "finished": + return BackendResponse(tool_calls=[ToolCall(id=f"scripted_{self.n}", name="done", + arguments=dict(reason=f"scripted {self.policy} policy finished " + f"with params {self.params}"))]) + raise RuntimeError("scripted policy crashed:\n" + str(rest[0])) + + def on_tool_result(self, call, result): + self.last_report = result.report + + def end_attempt(self): + if self.thread is not None: + if self.thread.is_alive(): + if self.pending: + self.ch.res.put(("abort", None)) + self.thread.join(timeout=30) + self.info.task.sk = self.real_sk + meta = dict(policy=self.policy, rule=self.rule, params=self.params) + if self.proxy is not None and self.proxy.untooled_hold_steps: + meta["untooled_hold_steps"] = self.proxy.untooled_hold_steps + if self.proxy is not None and self.proxy.ignored_wrap_yaw_false: + meta["ignored_wrap_yaw_false"] = self.proxy.ignored_wrap_yaw_false + return meta diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l4_fit_container.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l4_fit_container.py new file mode 100644 index 0000000000000000000000000000000000000000..86f8d7075627486afed86a3944b3bc8b95c0ba52 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l4_fit_container.py @@ -0,0 +1,61 @@ +"""Controlled arms for l4_fit_container (2026-10-12). + +Hidden variable: inst["cap"] -- clear (unrendered) bumper caps on both ends of the phone, 0.8-0.9 cm each, so the +phone is 1.6-1.8 cm longer than it looks. The prior picks the box with the most visible room to spare ("snug"), +which is too short for the capped phone; only the "fit" box is long enough. + +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" + and "short_wide"). inst["fit"] is left as is (that box still fits). +twin Same box positions / yaws, same phone, same caps (trap still active), but the inner sizes (and kinds) of the + "fit" and "snug" boxes are swapped. In the twin the prior goes to the place where the ORIGINAL's fitting box + stands (now with snug sizes) and fails on the rim; the twin's fitting box stands where the original's snug box + stands. So the twin's lesson at the action level ("not that box, use that other box") is exactly the reverse + of the original's: following it on the original means choosing the original's failing (snug) box. + Caveat: the abstract lesson ("the phone is longer than it looks, take the box with the most length to spare") + is the same in both -- a negative cap (phone shorter than it looks) is not physically possible here. The box + sizes in the twin images differ from the original's at those two positions (they are visible). +reveal The cap length, in cm, per end and in total. +""" +HIDDEN_KEYS = ("cap",) + + +def h0(inst): + return {"cap": 0.0} + + +def _idx(inst, kind): + return next(j for j, b in enumerate(inst["boxes"]) if b["kind"] == kind) + + +def twin(inst): + f, s = _idx(inst, "fit"), _idx(inst, "snug") + boxes = [dict(b) for b in inst["boxes"]] + for k in ("kind", "inner"): + boxes[f][k], boxes[s][k] = inst["boxes"][s][k], inst["boxes"][f][k] + perc = [list(p) for p in inst["_perc"]] + perc[f], perc[s] = list(inst["_perc"][s]), list(inst["_perc"][f]) + return {"boxes": boxes, "fit": s, "fit_crossed": boxes[s]["crossed"], "_perc": perc} + + +def reveal(inst): + c = 100 * inst["cap"] + return (f"The phone has clear bumper caps on both of its short ends that do not show in the camera images; " + f"each cap adds about {c:.1f} cm, so the phone is about {2 * c:.1f} cm longer than it looks.") + + +def _where(inst, j): + """robot-frame position words of box j in the 2 x 3 grid (rows along x, columns along y)""" + xs = sorted({round(float(b["xy"][0]), 2) for b in inst["boxes"]} | {round(float(inst["phone_xy"][0]), 2)}) + x, y = (float(v) for v in inst["boxes"][j]["xy"]) + 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" + col = "on the robot's left" if y > 0.1 else ("on the robot's right" if y < -0.1 else "in the middle") + return f"{row}, {col}" + + +def fix(inst, params): + """Ladder Fix rung (docs/20): the fitting box (oracle box = inst['fit']), long side along the box's long side.""" + j = int(params["box"]) + return (f"A way to succeed: the phone fits only into the box {_where(inst, j)} (the one with the most length to " + f"spare; it looks tight across, but the phone's width fits). Pick the phone up, turn it so that its long " + f"side lines up with that box's long side, and lower it flat into the middle of that box before you " + f"release it.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py new file mode 100644 index 0000000000000000000000000000000000000000..1d0cee1c01377a6ae8a461a6b31f3c739cd5c6df --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py @@ -0,0 +1,39 @@ +"""Controlled arms for l7_offcenter_push (docs/14 §6). + +Hidden variable: com_offset = e, the shift of the box's centre of mass along its long axis (world +y = robot's left; +|e| in [4.5, 7.5] cm). apply_instance() writes it into body_ipos on every reset; oracle_params() pushes at c = e. + + h0 e = 0: centre of mass in the middle, so the natural push at the middle of the back face goes straight. + twin e -> -e: same distance from the middle, other end heavy. The naive push turns the box just as much but the + other way (clockwise <-> counterclockwise, the other end lags), and the right contact point is on the other + side of the middle, so the original's lesson ("move the contact toward the left/right end") is reversed. + reveal states |e| and its side in the robot-frame words of the F2 feedback (robot's left / right). +""" + +HIDDEN_KEYS = ("com_offset",) + + +def h0(inst): + return {"com_offset": 0.0} + + +def twin(inst): + return {"com_offset": -float(inst["com_offset"])} + + +def reveal(inst): + e = float(inst["com_offset"]) + side = "left" if e > 0 else "right" + 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 " + f"the box's long side, toward the robot's {side}.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): push at the centre of mass (oracle c = e), one slow straight push.""" + c = float(params["c"]) + side = "left" if c > 0 else "right" + return (f"A way to succeed: push at the centre of mass, not at the middle. Close the gripper (yaw 0), put the " + f"fingertips about 1 cm above the table just behind the box's back face (the face towards the robot), " + f"{100 * abs(c):.1f} cm to the robot's {side} of that face's middle, and push slowly (speed about 0.08) " + f"straight forward, away from the robot, until the box is centred in the green rectangle; then lift the " + f"gripper.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..7201f54a4d0ba3fb8e1844420311ced219827fa6 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py @@ -0,0 +1,23 @@ +"""Layer-4 intervention texts for lh_clear_cover (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is +not in the controlled arms of full5. + +Hidden variable: inst["cover"] -- which box carries the nearly invisible clear lid (None in uncovered instances). +reveal says which box is covered and what the lid does to a released cube; not how to deal with it. +fix the oracle's edge push (lh_clear_cover.remove_cover) in move_eef words; params["z_push"] = grasp-point height of + that push in the eef_pos frame, params["push_len"] = length of the sweep (scripts/layer4_plan.py validate). +""" +HIDDEN_KEYS = ("cover",) + + +def reveal(inst): + return (f"The {inst['cover']} box is covered by a loose, nearly invisible clear lid lying on its walls, 8 mm thick. " + f"A cube released over that box stops on the lid at rim height; it is not in the box.") + + +def fix(inst, params): + return (f"A way to succeed: first push the lid off the {inst['cover']} box. Close the gripper, keep yaw 0 and bring " + f"the grasp point to height {params['z_push']:.3f} (the third value of eef_pos), so that the fingertips are " + f"level with the lid's edge, 3 cm outside the edge of the lid that faces the other box. Then in one move_eef " + f"command sweep {params['push_len'] * 100:.0f} cm straight along the line between the two boxes, away from " + f"the other box, at speed 0.06, and lift. The lid is then off. Put each cube into the box of its colour, and " + f"check from the side view that no cube rests at rim height.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json new file mode 100644 index 0000000000000000000000000000000000000000..3b880c73642c7b36c23626a80bd5437eef67bb42 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-1_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-fable-5-1|high", + "fingerprint_sha256": "f44d5ded7b8b847b934c86d8f7b51fa90ae396a1f33bca51e1c946f09da1031b", + "written": "2026-10-21 05:19:35", + "summary": { + "system_chars": 11701, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-fable-5-1" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/harness_run.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/harness_run.py new file mode 100644 index 0000000000000000000000000000000000000000..90c518dbaae11f1096d2f1a97627dbaf3957d9d3 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/harness_run.py @@ -0,0 +1,431 @@ +"""Run one robot_server session (style la) with one agent harness through its adapter (lffbench/harnesses, docs/15). + + python scripts/harness_run.py --harness claude_code --session runs/<...>/session.json --model claude-sonnet-5-5 --effort high + python scripts/harness_run.py --harness codex --session ... --model gpt-6-astra --effort high + python scripts/harness_run.py --harness ours --session ... --provider anthropic --model ... --effort high + +Harnesses: ours (scripts/api_player.py, unchanged), claude_code (arm B, --bare), claude_code_full (arm B', no --bare), +codex (arm F), rpent_codex (RPent, a robot harness framework, on the same Codex; tools through the episode's tool +gateway, lffbench/harnesses/rpent.py). Native harnesses get the reference driver's instructions + first status report as their first user +message (byte-identical README), only our MCP server (scripts/mcp_robot_server.py) as tools, a one-time HOME / config +dir, an opaque work dir /tmp/lffrun/<12 hex> and a process environment that is exactly a whitelist. + +API variables (never inherited from the calling Claude Code / Codex session): + claude_code*: --claude-auth oauth (default for claude_code_full): a Claude subscription, the long-lived token of + `claude setup-token` from LFF_CLAUDE_OAUTH_TOKEN or the KEY=value file LFF_CLAUDE_OAUTH_FILE (key + LFF_CLAUDE_OAUTH_TOKEN or CLAUDE_CODE_OAUTH_TOKEN), passed as CLAUDE_CODE_OAUTH_TOKEN; + --claude-auth apikey (default and only choice for claude_code, which is --bare): key + LFF_ANTHROPIC_API_KEY or ANTHROPIC_API_KEY; + endpoint --api-base-url or LFF_ANTHROPIC_BASE_URL (default: the CLI's own default, the official API) + codex: --codex-provider deepseek: DeepSeek's Responses endpoint (https://api.deepseek.com/), key + LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed to Codex as its provider's OPENAI_API_KEY); + --codex-provider opencode: OpenCode Go's Responses endpoint (OPENCODE_GO_URL), key LFF_OPENCODE_API_KEY + or OPENCODE_API_KEY (the model gateway adds the x-opencode-session header OpenCode Go requires); + --codex-auth chatgpt (default): the ChatGPT subscription login of LFF_CODEX_AUTH_HOME / CODEX_HOME + (a copy of its auth.json, no API key; endpoint the ChatGPT Codex backend unless --api-base-url); + --codex-auth apikey: key LFF_OPENAI_API_KEY or OPENAI_API_KEY; endpoint --api-base-url, + LFF_OPENAI_BASE_URL or OPENAI_BASE_URL (as api_player), else https://api.openai.com/v1 + dsh: DeepSeek's Messages endpoint (DEEPSEEK_ANTHROPIC_URL), or --api-base-url / LFF_DSH_BASE_URL (OpenCode Go: + https://opencode.ai/inference/go), key LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed as DEEPSEEK_API_KEY) + ours: as api_player.py (its own environment) + +Writes into the run's log dir: contract.json, first_message.txt, harness.json (harness name, version, argv with the +first message replaced by its sha256, env key names, contract_sha256, first_message_sha256, config_sha256, preflight +result), harness_preflight.json (full normalised fingerprint), the native event stream, trajectory.jsonl, +harness_audit.json. Exit codes: 0 done, 2 refused at launch (fail-closed), 3 harness error, 143 stopped. +""" +import argparse +import json +import os +import signal +import sys +import time +import traceback + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER, EpisodeSpec, HarnessRefused, get_adapter, render_first_message # noqa: E402 +from lffbench.harnesses import contract as C # noqa: E402 +from lffbench.harnesses import redteam as RT # noqa: E402 + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from api_player import MAX_NO_TOOL, call_server, continue_nudge # noqa: E402 +from tool_gateway import start_gateway, stop_gateway # noqa: E402 +import model_gateway as MG # noqa: E402 + +ANTHROPIC_API = "https://api.anthropic.com" + + +def claude_oauth_token(): + """The subscription token for claude_code_full --claude-auth oauth: LFF_CLAUDE_OAUTH_TOKEN, else the KEY=value + file LFF_CLAUDE_OAUTH_FILE. Never CLAUDE_CODE_OAUTH_TOKEN of the calling environment (that may be the calling + Claude Code session's own login).""" + tok = os.environ.get("LFF_CLAUDE_OAUTH_TOKEN") + if tok: + return tok.strip() + path = os.environ.get("LFF_CLAUDE_OAUTH_FILE") + if path and os.path.isfile(path): + for line in open(path): + k, _, v = line.strip().partition("=") + if k.strip().removeprefix("export ").strip() in ("LFF_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN") and v: + return v.strip().strip("'\"") + raise SystemExit("claude --claude-auth oauth: no token; run `claude setup-token` and put LFF_CLAUDE_OAUTH_TOKEN=... " + "into the file named by LFF_CLAUDE_OAUTH_FILE (or export LFF_CLAUDE_OAUTH_TOKEN)") + + +def default_claude_auth(harness): + return "apikey" if harness == "claude_code" else "oauth" + + +def api_env_for(harness, base_url, codex_auth="apikey", claude_auth="apikey", codex_provider="openai"): + """-> (variables passed to the harness, endpoint or None, endpoint label for harness.json). Endpoints are never + written to the logs, only where they came from.""" + if harness in ROBOT_HARNESSES: + if harness == "rpent_codex": + codex_auth = "apikey" # historical RPent implementation stays unchanged + harness = "codex" + if harness.startswith("claude_code"): + e = {} + if claude_auth == "oauth": + e["CLAUDE_CODE_OAUTH_TOKEN"] = claude_oauth_token() + else: + key = os.environ.get("LFF_ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY") + if key: + e["ANTHROPIC_API_KEY"] = key + url = base_url or os.environ.get("LFF_ANTHROPIC_BASE_URL") + if url: + e["ANTHROPIC_BASE_URL"] = url + dflt = "CLI default (official)" + (", subscription token" if claude_auth == "oauth" else "") + return e, url, ("--api-base-url" if base_url else "LFF_ANTHROPIC_BASE_URL") if url else dflt + if harness == "dsh": + key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY") + from lffbench.harnesses.dsh import DEEPSEEK_ANTHROPIC_URL + url = base_url or os.environ.get("LFF_DSH_BASE_URL") + return ({"DEEPSEEK_API_KEY": key} if key else {}), url or DEEPSEEK_ANTHROPIC_URL, \ + ("--api-base-url" if base_url else "LFF_DSH_BASE_URL") if url else \ + "DeepSeek (DEEPSEEK_ANTHROPIC_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)" + if harness == "codex" and codex_provider == "deepseek": # DeepSeek's own Responses endpoint, an API key + key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY") + from lffbench.harnesses.codex import DEEPSEEK_URL + return ({"OPENAI_API_KEY": key} if key else {}), base_url or DEEPSEEK_URL, \ + "--api-base-url" if base_url else "DeepSeek (DEEPSEEK_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)" + if harness == "codex" and codex_provider == "opencode": # OpenCode Go's Responses endpoint, an API key + key = os.environ.get("LFF_OPENCODE_API_KEY") or os.environ.get("OPENCODE_API_KEY") + from lffbench.harnesses.codex import OPENCODE_GO_URL + return ({"OPENAI_API_KEY": key} if key else {}), base_url or OPENCODE_GO_URL, \ + "--api-base-url" if base_url else "OpenCode Go (OPENCODE_GO_URL, key LFF_OPENCODE_API_KEY / OPENCODE_API_KEY)" + if harness == "codex" and codex_auth == "chatgpt": + return {}, base_url, "--api-base-url" if base_url else "ChatGPT Codex backend (subscription login)" + if harness == "codex": + key = os.environ.get("LFF_OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY") + src = ("--api-base-url" if base_url else "LFF_OPENAI_BASE_URL" if os.environ.get("LFF_OPENAI_BASE_URL") + else "OPENAI_BASE_URL (same as api_player)" if os.environ.get("OPENAI_BASE_URL") else "official default") + url = base_url or os.environ.get("LFF_OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL") + return ({"OPENAI_API_KEY": key} if key else {}), url, src + return {}, None, "api_player's own environment" + + +RESUME_RETRIES = 3 # a resumed CLI that exits before writing any event is started again (nothing reached the model) + + +def mcp_tool_state(log_dir): + """-> (number of MCP tool calls so far, whether our MCP server saw the episode end) from mcp_transcript.jsonl.""" + n, finished = 0, False + try: + for line in open(os.path.join(log_dir, "mcp_transcript.jsonl")): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool": + n, finished = n + 1, bool(d.get("finished")) + except OSError: + pass + return n, finished + + +def continue_episode(ad, h, ep, stop): + """The CLI exited although the episode is not over (it ends when the model replies without a tool call): send + the reference driver's nudge as a user turn, as api_player does after such a reply, and wait again. Same rule: + after MAX_NO_TOOL nudges in a row without a tool call in between, the next such reply ends the run. -> log list.""" + out, no_tool, (n_calls, _) = [], 0, mcp_tool_state(ep.log_dir) + deadline = h.t_start + h.spec.timeout_s + while ad.can_resume and h.exit_reason == "exited" and not stop["flag"]: + n, finished = mcp_tool_state(ep.log_dir) + if finished: # api_player stops here too, without a status call + break + try: # the status call api_player makes for its nudge + stx = json.loads(call_server(ep.port, ep.token, "status", {})) + except Exception as e: + out.append(dict(ev="status_failed", error=f"{type(e).__name__}: {e}"[:300], t=time.time())) + break + if stx.get("finished"): + break + no_tool = 1 if n > n_calls else no_tool + 1 + n_calls = n + if no_tool > MAX_NO_TOOL: + out.append(dict(ev="abort", reason=f"no tool call {no_tool} times", t=time.time())) + break + if time.time() >= deadline: + h.exit_reason = "timeout" + break + msg = continue_nudge(ep.port, ep.token, stx) + out.append(dict(ev="resume", message=msg, attempt=stx.get("attempt"), mcp_tool_calls=n, t=time.time())) + for retry in range(RESUME_RETRIES + 1): + size0 = os.path.getsize(h.spec.stdout_path) if os.path.exists(h.spec.stdout_path) else 0 + ad.resume(h, msg) + ad.wait(h, timeout=max(1.0, deadline - time.time())) + grew = os.path.exists(h.spec.stdout_path) and os.path.getsize(h.spec.stdout_path) > size0 + if h.exit_reason == "exited" or grew or stop["flag"] or retry == RESUME_RETRIES \ + or time.time() + 30 >= deadline: + break + # the resumed CLI exited before writing any event (2026-10-20: the MCP handshake timed out on a loaded + # machine), so nothing reached the model: start the same resume again + out.append(dict(ev="resume_retry", exit_reason=h.exit_reason, t=time.time())) + time.sleep(30) + return out + + +def model_upstream(harness, url, codex_auth): + """-> (gateway kind, the model API the harness would call without the gateway).""" + if harness.startswith("claude_code") or harness == "dsh": + return "anthropic", url or ANTHROPIC_API + from lffbench.harnesses.codex import CHATGPT_BACKEND, OFFICIAL_API + if harness == "rpent_codex": + return "openai", url or OFFICIAL_API + return "openai", url or (CHATGPT_BACKEND if codex_auth == "chatgpt" else OFFICIAL_API) + + +def plain_config_sha256(ad, spec, ep, mg): + """config_sha256 as if the harness called its model API directly: the model gateway is plumbing (like the + proxy variables, base.py PROXY_KEYS), so runs with and without it keep the same configuration hash.""" + if not mg: + return ad.config_sha256(spec, ep) + import copy + s2 = copy.copy(spec) + s2.argv = [a.replace(mg["url"], mg["upstream"]) if isinstance(a, str) else a for a in spec.argv] + s2.env = {k: (v.replace(mg["url"], mg["upstream"]) if isinstance(v, str) else v) for k, v in spec.env.items()} + return ad.config_sha256(s2, ep) + + +def write_json(path, d): + tmp = path + ".tmp" + with open(tmp, "w") as f: + json.dump(d, f, indent=1, ensure_ascii=False, default=str) + os.replace(tmp, path) + + +def run(a, adapter_kw=None): + """Returns (exit code, harness.json dict). adapter_kw overrides adapter construction (self-check).""" + provider = a.provider or PROVIDER.get(a.harness, "") + ep = EpisodeSpec.from_session(a.session, a.model, a.effort, provider) + if getattr(a, "red_team", False): # before the contract: red-team runs get their own contract_sha256 + if a.harness == "ours": + raise SystemExit("--red-team is for native harnesses") + RT.mark(ep.log_dir) + contract, csha = C.write_contract(ep.log_dir) + mg_box = {} # the model gateway process, stopped whatever happens below + try: + return _run(a, adapter_kw, provider, ep, csha, mg_box) + finally: + MG.stop_model_gateway(mg_box.get("proc")) + + +def _run(a, adapter_kw, provider, ep, csha, mg_box): + mg = None + if adapter_kw is None: + a.codex_auth = getattr(a, "codex_auth", None) or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt") + if a.harness == "rpent_codex" and a.codex_auth != "apikey": + raise SystemExit("Historical RPent adapter supports apikey only") + claude_auth = getattr(a, "claude_auth", None) or default_claude_auth(a.harness) + if getattr(a, "codex_provider", "openai") in ("deepseek", "opencode"): + a.codex_auth = "apikey" # no subscription login for DeepSeek / OpenCode Go + api_env, url, endpoint = api_env_for(a.harness, a.api_base_url, getattr(a, "codex_auth", "apikey"), + claude_auth, getattr(a, "codex_provider", "openai")) + if a.harness != "ours" and not getattr(a, "no_model_gateway", False): + # the harness reaches its model API only through the model gateway (scripts/model_gateway.py) + kind, upstream = model_upstream(a.harness, url, a.codex_auth) + mg_box["proc"], mginfo = MG.start_model_gateway(upstream, kind, ep.log_dir, + getattr(a, "token_budget_in", None), + getattr(a, "token_budget_out", None), + allow_files=a.harness == "dsh") + mg = dict(url=mginfo["url"], upstream=upstream, kind=kind, upstream_host=mginfo["upstream_host"], + pid=mginfo["pid"]) + url = mg["url"] + if a.harness.startswith("claude_code"): + api_env["ANTHROPIC_BASE_URL"] = url + adapter_kw = dict(timeout_s=a.timeout) + if a.harness.startswith("claude_code"): + adapter_kw.update(api_env=api_env, max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned, + auth=claude_auth) + elif a.harness == "codex": + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, auth=a.codex_auth, + catalog=a.codex_catalog) + elif a.harness == "dsh": + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned) + elif a.harness in ROBOT_HARNESSES: + adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, + auth=a.codex_auth, catalog=a.codex_catalog) + if a.harness == "rpent_codex": # historical, explicitly exposed RPent experiment settings + adapter_kw.update(sessions=a.rpent_sessions, attempts_per_session=a.rpent_attempts_per_session, + max_turns=a.rpent_max_turns) + if getattr(a, "jail", False): + if a.harness == "ours": + raise SystemExit("--jail is for native harnesses") + adapter_kw["jail"] = True + else: + adapter_kw.update(provider=provider) + else: + endpoint = "set by the caller (self-check)" + ad = get_adapter(a.harness, **adapter_kw) + ver = ad.version() + hj_path = os.path.join(ep.log_dir, "harness.json") + hj = dict(harness=ad.name, version=ver.get("version"), binary=ver.get("binary"), model=a.model, effort=a.effort, + provider=provider, capabilities={k: vars(c) for k, c in ad.capabilities.items()}, + contract_sha256=csha, task=ep.task, seed=ep.seed, api_endpoint_from=endpoint, status="preparing", + t_prepare=time.time(), jail=ad.jail_info(), auth=ad.auth_info() if ad.name != "ours" else None, + config=ad.config_info() if hasattr(ad, "config_info") else None, + model_gateway=({k: mg[k] for k in ("kind", "upstream_host", "pid")} if mg else None)) + if ad.name == "ours": + first = None + spec = ad.prepare(ep) + else: + first, _ = render_first_message(ep) + if getattr(a, "red_team", False): + first = RT.first_message(first) + hj["red_team"] = RT.marker(ep.log_dir) + with open(os.path.join(ep.log_dir, "first_message.txt"), "w") as f: + f.write(first) + spec = ad.prepare(ep, first, **(dict(reuse_state=a.reuse_state) if getattr(a, "reuse_state", None) else {})) + hj["first_message_sha256"] = C.sha256_text(first) + hj.update(argv=ad.logged_argv(spec), cwd=spec.cwd, env_keys=sorted(spec.env), + env_mode="exact whitelist (Popen env=, same as env -i)" if ad.name != "ours" else "inherited (own code)", + state_dirs=spec.state_dirs, config_sha256=plain_config_sha256(ad, spec, ep, mg), status="launching") + write_json(hj_path, hj) + h, code, gw = None, 0, None + stop = dict(flag=False) + + def on_term(*_): + stop["flag"] = True + if h is not None and h.proc is not None: + ad.kill(h) + signal.signal(signal.SIGTERM, on_term) + try: + if (ad.uses_mcp or ad.uses_gateway) and not getattr(a, "no_gateway", False): # the episode's tools, for + # every MCP process of the run / every SDK client of a framework adapter (base.HarnessAdapter.uses_gateway) + gw, ginfo = start_gateway(ep.session_path) + hj["gateway"] = dict(url=ginfo["url"], pid=ginfo["pid"]) + try: + h = ad.launch(spec, ep, skip_preflight=getattr(a, "skip_preflight", False)) + except HarnessRefused as e: + pre = dict(spec.preflight or {}) + hj.update(status="refused", refused=str(e), preflight={k: v for k, v in pre.items() if k != "fingerprint"}) + write_json(hj_path, hj) + print("REFUSED:", e, flush=True) + return 2, hj + pre = dict(spec.preflight or {}) + if "fingerprint" in pre: + write_json(os.path.join(ep.log_dir, "harness_preflight.json"), pre) + hj.update(status="running", pid=h.pid, env_observed_keys=h.env_observed_keys, t_start=h.t_start, + preflight={k: v for k, v in pre.items() if k != "fingerprint"}, init=h.info.get("init")) + write_json(hj_path, hj) + ad.wait(h) + cont = [] if getattr(a, "no_continue", False) else continue_episode(ad, h, ep, stop) + if cont: + hj["continuation"] = cont + write_json(hj_path, hj) + if stop["flag"]: + h.exit_reason, code = "stopped", 143 + tw = ad.collect(h) + au = ad.audit(h) + if ad.name == "ours" and spec.first_message: + hj["first_message_sha256"] = C.sha256_text(spec.first_message) + hj.update(status="done" if code == 0 else "stopped", exit_code=h.exit_code, exit_reason=h.exit_reason, + t_end=h.t_end, wall_s=round(h.t_end - h.t_start, 1), audit_ok=au.get("ok"), + violations=au.get("violations"), final_metrics=(tw.final or {}).get("final_metrics")) + if mg: # refusals do not void the trial; they flag it for a look (EFE running.md "Usage gateway") + tot = MG.read_totals(ep.log_dir) or {} + hj["model_gateway"].update({k: tot.get(k) for k in MG.Totals.KEYS}, tokens=tot.get("tokens"), + models=tot.get("models"), budget_stop=tot.get("budget_stop")) + hj["review_flags"] = ["model_gateway:" + k for k in MG.flagged(tot)] + ( + ["model_gateway:other_model"] if set(tot.get("models") or {}) - {a.model} else []) + if code == 0 and h.exit_code not in (0, None): + code = 3 + write_json(hj_path, hj) + return code, hj + except Exception as e: + hj.update(status="error", error=f"{type(e).__name__}: {e}", traceback=traceback.format_exc()[-3000:]) + write_json(hj_path, hj) + if h is not None and h.proc is not None and h.proc.poll() is None: + ad.kill(h) + return 3, hj + finally: + stop_gateway(gw) + if not getattr(a, "keep_run_dir", False): + ad.cleanup(spec) + + +def parser(): + ap = argparse.ArgumentParser() + ap.add_argument("--harness", required=True, choices=NAMES) + ap.add_argument("--session", required=True) + ap.add_argument("--provider", default=None, help="ours: openai / anthropic / gemini / chat") + ap.add_argument("--model", required=True) + ap.add_argument("--effort", default="high") + ap.add_argument("--api-base-url", default=None) + ap.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"], + help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. " + "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only") + ap.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"], + help="claude_code*: subscription token (default for claude_code_full) or an API key (claude_code, " + "--bare, takes only an API key); see above") + ap.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"], + help="codex: model provider; deepseek = DeepSeek's Responses endpoint with LFF_DEEPSEEK_API_KEY / " + "DEEPSEEK_API_KEY, opencode = OpenCode Go's with LFF_OPENCODE_API_KEY / OPENCODE_API_KEY " + "(both imply --codex-auth apikey)") + ap.add_argument("--codex-catalog", default="generic", choices=["generic", "native"], + help="codex: model catalog, the main table's shared configuration (default) or Codex's native " + "one (control); see lffbench/harnesses/codex.py") + ap.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: --max-budget-usd") + ap.add_argument("--rpent-sessions", type=int, default=5, + help="rpent_codex: planner sessions per episode (RPent --explore-sessions; default 5 = k + 2 spare)") + ap.add_argument("--rpent-attempts-per-session", type=int, default=1, + help="rpent_codex: attempts one session may use (RPent --explore-attempts-per-session): 1 = " + "variant H, a fresh session with a handoff after each failed attempt (default); 0 = no limit") + ap.add_argument("--rpent-max-turns", type=int, default=100, + help="rpent_codex: model responses per session (RPent --max-turns)") + ap.add_argument("--timeout", type=float, default=10800) + ap.add_argument("--allow-unpinned", action="store_true", + help="launch even if no pin exists for this version / model / effort (the preflight still runs)") + ap.add_argument("--keep-run-dir", action="store_true", help="do not delete the one-time dirs (debugging)") + ap.add_argument("--no-gateway", action="store_true", + help="native harnesses: run the tools inside each MCP server process instead of the episode's " + "tool gateway (scripts/tool_gateway.py; same ToolCore, budget carried over via the transcript)") + ap.add_argument("--no-model-gateway", action="store_true", + help="native harnesses: call the model API directly instead of through the run's model gateway " + "(scripts/model_gateway.py: model calls only, provider-side tools refused, tokens counted)") + ap.add_argument("--token-budget-in", type=int, default=None, + help="model gateway: refuse further model calls once this many input tokens were used (cached " + "input counts in full)") + ap.add_argument("--token-budget-out", type=int, default=None, + help="model gateway: ... output tokens (reasoning included)") + ap.add_argument("--red-team", action="store_true", + help="adversarial acceptance run (lffbench/harnesses/redteam.py): the first message starts with the " + "red-team notice; own contract_sha256; read with scripts/redteam_report.py") + ap.add_argument("--no-continue", action="store_true", + help="do not resume a CLI that exited before the episode was over (self-check / debugging)") + ap.add_argument("--jail", action="store_true", + help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4): as uid 65534, no host " + "path visible, MCP server outside behind a socket relay") + return ap + + +def main(): + code, hj = run(parser().parse_args()) + print(json.dumps({k: hj.get(k) for k in ("harness", "status", "exit_reason", "audit_ok", "violations", + "contract_sha256", "final_metrics")}, default=str), flush=True) + sys.exit(code) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/layer4_plan.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/layer4_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..03f7434a8b04de323809f5d8d4879b9933cc3a72 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/layer4_plan.py @@ -0,0 +1,174 @@ +"""Layer-4 minimal intervention (user 2026-10-30: 先用 opus; design reports/layer4_intervention_20261030/PLAN.md). Opus only, on the +two tasks whose every main-table instance failed all three attempts. Same protocol as the layer-3 ladder (a fresh +single-attempt agent, the instance's own failed attempt 1 in history/, F1), only the Result section differs: + + f1 "The environment judged that attempt: failed." + v + a generic reminder to check the goal before ending; no cause + hp + "Cause: " the hidden variable (arm_specs reveal) + fx + cause + how to succeed (arm_specs fix, validated below) + + python scripts/layer4_plan.py validate texts + oracle + LA push, debug and test seeds -> results/_layer4/fix_validate.json + python scripts/layer4_plan.py build debug records -> runs/api/layer4i_20261030/debug/.json + tasks.txt + python scripts/layer4_plan.py build test the same from the failed attempts of batch l4i_first (test seeds) + python scripts/layer4_plan.py report debug|test per instance per condition: outcome, process events, closing claim +""" +import json +import os +import subprocess +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +API = os.path.join(ROOT, "runs", "api") +OUT = os.path.join(API, "layer4i_20261030") +FIXV = os.path.join(ROOT, "results", "_layer4", "fix_validate.json") +CONDS = ("f1", "v", "hp", "fx") +DEBUG = {"lh_clear_cover": {3000: "cc_opus1", 3001: "cc_opus_s2", 3003: "cc_opus_s3"}, + "lh_tidy_stack": {3000: "cc_opus1", 3002: "cc_opus_s2", 3003: "cc_opus_s3"}} +# frozen before any test-seed run: first four seeds from 3100 with the trap active (clear_cover: covered, (seed * 7) % 20 < 10; +# tidy_stack: a soft box that is not on top of a nearest-first pile, (seed * 7) % 20 < 18 and % 4 != 3) +TEST = {"lh_clear_cover": [3100, 3101, 3103, 3104], "lh_tidy_stack": [3100, 3102, 3103, 3104]} +REMINDER = ("Before you end an attempt, use your observations to check whether every part of the goal is actually met; " + "if it is not, keep working.") + + +def events(log): + return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip() and "\0" not in line] + + +def batch_log(batch, task, seed): + runs = json.load(open(os.path.join(API, batch, "manifest.json")))["runs"] + return next(r["log"] for r in runs if r["task"] == task and r["seed"] == seed and r.get("status") == "done" + and r.get("cond") == "harness") + + +def la_push(task, inst): + """the Fix text's lid push as LA commands; returns (z_push, sweep length, lid off?)""" + import numpy as np + from lffbench.agent.tools import ToolExecutor + from lffbench.tasks import lh_clear_cover as cc + from scripts.validate_ladder_fix import la_move + task.reset_instance(inst) + sim = task.env.sim + off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy() + ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",)) + cov = task.covering() + lp = task.lid_pos() + b = np.asarray(inst["boxes"][cov], float) + o = np.asarray(inst["boxes"][[c for c in cc.COLORS if c != cov][0]], float) + d = np.array((0.0, float(np.sign(b[1] - o[1])))) + back = cc.LID_HALF + 0.03 + s = lp[:2] - d * back + z = lp[2] + cc.LID_T / 2 - cc.PUSH_DEPTH + cc.TIP + need = float((b - lp[:2]) @ d) + cc.BOX_OUT + back + 0.03 + e = s + d * need + sb, eb, zb = s - off[:2], e - off[:2], z - off[2] + la_move(task, ex, off, gripper="close") + la_move(task, ex, off, x=sb[0], y=sb[1], z=zb + 0.08, yaw=0) + la_move(task, ex, off, x=sb[0], y=sb[1], z=zb) + la_move(task, ex, off, x=eb[0], y=eb[1], z=zb, speed=cc.PUSH_SPEED) + la_move(task, ex, off, z=zb + 0.10, speed=0.2) + return float(zb), float(need), task.covering() is None + + +def cmd_validate(): + import importlib + import pkgutil + from lffbench import arm_specs + from lffbench import tasks as task_pkg + from lffbench.agent.robot_server import strip_axes + from lffbench.task_base import TASKS + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + rows = [] + for name, seeds in ((t, sorted(DEBUG[t]) + TEST[t]) for t in DEBUG): + task = TASKS[name](cam_res=64) + for seed in seeds: + inst = task.sample_instance(seed) + clean = {k: v for k, v in inst.items() if not k.startswith("_")} + params = dict(task.oracle_params(inst)) + row = dict(key=f"{name}:{seed}", hidden=clean.get("cover") or clean.get("soft_colour")) + row["oracle_success"] = bool(task.run_scripted("oracle", inst, k=1)[0]["outcome"]["success"]) + row["naive_success"] = bool(task.run_scripted("naive", inst, k=1)[0]["outcome"]["success"]) + if name == "lh_clear_cover": + params["z_push"], params["push_len"], row["la_lid_off"] = la_push(task, inst) + task.execute(inst, dict(plan="naive", check="side")) # the placing part, after the LA push + row["la_then_place_success"] = bool(task.outcome(inst)["success"]) + cause, fx = arm_specs.reveal(name, clean), arm_specs.fix(name, clean, params) + row.update(cause=cause, fix=fx, no_axis_labels=strip_axes(cause + fx) == cause + fx) + row["ok"] = bool(row["oracle_success"] and not row["naive_success"] and row["hidden"] and row["no_axis_labels"] + and row.get("la_lid_off", True) and row.get("la_then_place_success", True)) + rows.append(row) + print("OK " if row["ok"] else "BAD", json.dumps({k: v for k, v in row.items() if k not in ("cause", "fix")}), flush=True) + os.makedirs(os.path.dirname(FIXV), exist_ok=True) + json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(FIXV, "w"), indent=1) + print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {FIXV}") + + +def sources(stage): + if stage == "debug": + return [(t, s, batch_log(b, t, s)) for t, d in DEBUG.items() for s, b in sorted(d.items())] + out = [] + for r in json.load(open(os.path.join(API, "l4i_first", "manifest.json")))["runs"]: + if r["status"] == "done": + d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None) + if d is not None and not d["success"]: + out.append((r["task"], r["seed"], r["log"])) + return out + + +def cmd_build(stage): + fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]} + base = os.path.join(OUT, stage) + os.makedirs(base, exist_ok=True) + maps, tasks = {c: {} for c in CONDS}, [] + for task, seed, log in sources(stage): + key = f"{task}:{seed}" + if not fixes[key]["ok"]: + raise SystemExit(f"{key}: fix text not validated") + tasks.append(key) + cause = "Cause: " + fixes[key]["cause"] + extra = dict(f1="", v=REMINDER, hp=cause, fx=cause + "\n\n" + fixes[key]["fix"]) + for c in CONDS: + dst = os.path.join(base, c, f"{task}_s{seed}") + if not os.path.isdir(dst): + subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst, + "--result-extra", extra[c]], check=True, capture_output=True) + maps[c][key] = dst + for c in CONDS: + json.dump(maps[c], open(os.path.join(base, f"{c}.json"), "w"), indent=1) + open(os.path.join(base, "tasks.txt"), "w").write("\n".join(tasks) + "\n") + print(stage, len(tasks), "instances x", len(CONDS), "conditions") + + +def cmd_report(stage): + rows = {} + for c in CONDS: + p = os.path.join(API, f"l4i_{c}_{stage}", "manifest.json") + if not os.path.exists(p): + continue + for r in json.load(open(p))["runs"]: + key = f"{r['task']}:{r['seed']}" + cell = dict(status=r["status"]) + if r["status"] == "done": + ev = events(r["log"]) + d = next((e for e in ev if e["ev"] == "done"), {}) + o = d.get("outcome") or {} + cell.update(success=bool(d.get("success")), calls=d.get("step"), reason=(d.get("reason") or "")[:300], + failure=o.get("failure"), detail=(o.get("detail") or "")[:300], log=r["log"], + events=[e.get("ev") for e in o.get("events", []) if isinstance(e, dict)][:40], + cover_removed=o.get("cover_removed")) + rows.setdefault(key, {})[c] = cell + print("| instance | " + " | ".join(CONDS) + " |") + print("|---|" + "---|" * len(CONDS)) + f = lambda x: "-" if x is None else ("S" if x.get("success") else ("F" if x.get("status") == "done" else x.get("status"))) + for k, v in sorted(rows.items()): + print(f"| {k} | " + " | ".join(f(v.get(c)) for c in CONDS) + " |") + for c in CONDS: + xs = [v[c] for v in rows.values() if c in v and v[c].get("status") == "done"] + print(c, f"{sum(x['success'] for x in xs)}/{len(xs)}") + json.dump(rows, open(os.path.join(OUT, f"report_{stage}.json"), "w"), indent=1) + + +if __name__ == "__main__": + {"validate": cmd_validate, "build": lambda: cmd_build(sys.argv[2]), "report": lambda: cmd_report(sys.argv[2])}[sys.argv[1]]() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/nest_compare.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/nest_compare.py new file mode 100644 index 0000000000000000000000000000000000000000..edd7ffde2150a1b22e90322d4d3fce48fc4ed352 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/nest_compare.py @@ -0,0 +1,71 @@ +"""Render what an agent would see for l4_nest_order: start, the naive (tallest-outermost) attempt's end, the true +order's end. Agentview + a wrist view taken from above the stack (the agent can always move there and look). + +python scripts/nest_compare.py --seeds 1000,1001,1002 --out results/l4_nest_order/compare +""" +import argparse +import os +import sys + +import numpy as np +from PIL import Image, ImageDraw + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from lffbench import envs # noqa: E402 +from lffbench.tasks.l4_nest import NestOrder # noqa: E402 + +RES = 512 + + +def views(task, inst, look_at=None): + """agentview, and the wrist camera ~30 cm above the table over `look_at` (cup index) or at the start pose""" + a = envs.render(task.env, "agentview", RES) + if look_at is not None: + x, y = task._cup_state(inst, look_at)["p"][:2] + task.sk.move_to([x, y, envs.TABLE_Z + 0.30], yaw=0.0, tol=0.003) + envs.settle(task.env, 10) + w = envs.render(task.env, "robot0_eye_in_hand", RES) + return a, w + + +def row(label, a, w): + im = Image.new("RGB", (2 * RES, RES + 22), "white") + im.paste(Image.fromarray(a), (0, 22)) + im.paste(Image.fromarray(w), (RES, 22)) + ImageDraw.Draw(im).text((6, 5), label, fill="black") + return im + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--seeds", default="1000,1001,1002") + ap.add_argument("--out", default=os.path.join(ROOT, "results", "l4_nest_order", "compare")) + args = ap.parse_args() + os.makedirs(args.out, exist_ok=True) + task = NestOrder(cam_res=RES) + for seed in [int(s) for s in args.seeds.split(",")]: + inst = task.sample_instance(seed) + col = [c["color"] for c in inst["cups"]] + name = lambda order: " > ".join(col[j] for j in order) # noqa: E731 + rows = [] + task.reset_instance(inst) + rows.append(row(f"seed {seed} ({inst['case']}) start heights cm {dict(zip(col, inst['height_cm']))} " + f"openings cm {dict(zip(col, inst['opening_cm']))}", *views(task, inst))) + for kind, order in (("naive (tallest outermost)", inst["naive_order"]), ("true order", inst["order"])): + task.reset_instance(inst) + task.execute(inst, dict(order=list(order))) + o = task.outcome(inst) + rows.append(row(f"{kind}: {name(order)} -> {'SUCCESS' if o['success'] else 'FAIL'} | {o['detail']}"[:150], + *views(task, inst, look_at=order[0]))) + sheet = Image.new("RGB", (2 * RES, len(rows) * (RES + 22)), "white") + for k, r in enumerate(rows): + sheet.paste(r, (0, k * (RES + 22))) + p = os.path.join(args.out, f"compare_{seed}.jpg") + sheet.save(p, quality=88) + print(p, flush=True) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/validate_ladder_fix.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/validate_ladder_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..d80168eaa6cf7ce8c79aacac8a0f8d3e25e63e05 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/validate_ladder_fix.py @@ -0,0 +1,168 @@ +"""Check the Fix-rung texts of the layer-3 feedback ladder (docs/20 §4) on every ladder instance. + + python scripts/validate_ladder_fix.py [--out results/_ladder/fix_validate.json] [--only TASK] + +Per instance (task:seed from runs/api/mismatch_20261027//own.json, both models, deduplicated): + 1. the sampled instance equals the one logged in the main-table run (session_start inst); + 2. the scripted oracle succeeds in one attempt; the Fix text is built from the parameters that oracle executed; + 3. the text has no coordinate-axis labels (strip_axes leaves it unchanged) and no internal instance key names; + 4. slide_to_target / tablecloth_pull only: the strike / pull the text describes, issued as LA `move_eef` + commands in the robot-base frame through the same path as robot_server (ToolExecutor move_to with the given + speed), also succeeds -- this checks that "speed" in the text means what move_eef does. The success window is + narrow (~+-0.02) and the LA path does not hit it at exactly the oracle's speed (tablecloth 3001: oracle 0.475 + fails as LA commands, 0.48-0.52 succeed), so for these two the text's speed is the middle of the longest run of + LA successes on a 0.01 grid within +-0.10 of the oracle speed (`la_speed`). +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from lffbench import arm_specs, envs # noqa: E402 +from lffbench import tasks as task_pkg # noqa: E402 +from lffbench.agent.robot_server import strip_axes # noqa: E402 +from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for _m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{_m.name}") + +OUT = os.path.join(ROOT, "runs", "api", "mismatch_20261027") +BANNED = ("com_offset", "com_total", "heavy_edge", "heavy_near", "pane_side", "_oracle", " mu ", "inst[") + + +def instances(): + seen = {} + for m in ("opus", "sonnet"): + for key, d in json.load(open(os.path.join(OUT, m, "own.json"))).items(): + src = json.load(open(d + ".source.json")) + start = json.loads(open(os.path.join(src["log"], "events.jsonl")).readline()) + seen.setdefault(key, dict(task=src["task"], seed=src["seed"], logged=start["inst"], models=[])) + seen[key]["models"].append(m) + return seen + + +def same(a, b): + if isinstance(a, dict): + return isinstance(b, dict) and set(a) == set(b) and all(same(a[k], b[k]) for k in a) + if isinstance(a, (list, tuple)): + return isinstance(b, (list, tuple)) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b)) + if isinstance(a, float) or isinstance(b, float): + return abs(float(a) - float(b)) < 1e-9 + return a == b + + +def la_move(task, ex, off, **args): + """one LA move_eef, as robot_server._handle_v2: absolute base-frame target, move then gripper""" + p = ex.proprio() + cur = np.asarray(p["eef_pos"], float) - off + tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")] + tgt_w = np.asarray(tgt) + off + if any(k in args for k in ("x", "y", "z", "yaw")): + assert np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI), f"target rejected {tgt}" + mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=float(args.get("yaw", p["eef_yaw_deg"]))) + if args.get("speed") is not None: + mv["speed"] = float(args["speed"]) + ex.call("move_to", mv) + if args.get("gripper"): + ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {}) + + +def la_replay(task, inst, params): + """the Fix text of slide / tablecloth as LA commands; returns the outcome""" + task.reset_instance(inst) + sim = task.env.sim + off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy() + ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",)) + zt = envs.TABLE_Z - off[2] # tabletop height in the base frame + v = float(params["speed"]) + if task.name == "l5_slide_to_target": + x0, y0 = (np.asarray(inst["cube_xy"], float) - off[:2]) + la_move(task, ex, off, gripper="close") + la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.12, yaw=0) + la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.02) + la_move(task, ex, off, x=x0 - 0.005, y=y0, z=zt + 0.02, speed=v) + la_move(task, ex, off, z=zt + 0.10, speed=0.3) + else: + from lffbench.tasks.l5_tablecloth_pull import B_HALF, BOARD, H_HALF + b = envs.obj_pos(task.env, BOARD) - off + hx, hy, zg = b[0] - B_HALF[0] + H_HALF[0], b[1], zt + 2 * B_HALF[2] + H_HALF[2] + la_move(task, ex, off, gripper="open") + la_move(task, ex, off, x=hx, y=hy, z=zg + 0.08, yaw=0) + la_move(task, ex, off, x=hx, y=hy, z=zg, gripper="close") + la_move(task, ex, off, x=hx - 0.25, y=hy, z=zg, speed=v, gripper="open") + la_move(task, ex, off, z=zg + 0.10, speed=0.3) + return task.outcome(inst) + + +def la_speed(task, inst, v0): + """middle of the longest run of LA-replay successes on a 0.01 grid around the oracle speed""" + from importlib import import_module + mod = import_module(type(task).__module__) + grid = [round(v, 2) for v in np.arange(round(v0 - 0.10, 2), round(v0 + 0.10, 2) + 1e-9, 0.01) + if mod.V_MIN <= v <= mod.V_MAX] + ok = [bool(la_replay(task, inst, dict(speed=v))["success"]) for v in grid] + best, run = [], [] + for v, s in zip(grid, ok): + run = run + [v] if s else [] + if len(run) > len(best): + best = run + if not best: + return None, dict(zip(map(str, grid), ok)) + return best[len(best) // 2], dict(zip(map(str, grid), ok)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=os.path.join(ROOT, "results", "_ladder", "fix_validate.json")) + ap.add_argument("--only", default="") + a = ap.parse_args() + rows, tasks = [], {} + for key, it in sorted(instances().items()): + if a.only and it["task"] != a.only: + continue + t0 = time.time() + task = tasks.setdefault(it["task"], TASKS[it["task"]](cam_res=64)) + inst = task.sample_instance(it["seed"]) + clean = {k: v for k, v in inst.items() if not k.startswith("_")} + row = dict(key=key, models=it["models"], inst_matches_log=same(json.loads(json.dumps(clean, default=float)), + it["logged"])) + hist = task.run_scripted("oracle", inst, k=1) + params = hist[0]["params"] + row["oracle_success"] = bool(hist[0]["outcome"]["success"]) + row["oracle_failure"] = hist[0]["outcome"].get("failure") + row["params"] = json.loads(json.dumps(params, default=float)) + if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"): + v, sweep = la_speed(task, inst, float(params["speed"])) + row["oracle_speed"], row["la_sweep"] = float(params["speed"]), sweep + params = dict(params, speed=v if v is not None else float(params["speed"])) + row["params"] = json.loads(json.dumps(params, default=float)) + text = arm_specs.fix(it["task"], clean, params) + row["fix"] = text + row["no_axis_labels"] = strip_axes(text) == text + row["no_internal_names"] = not any(b in text for b in BANNED) + if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"): + out = la_replay(task, inst, params) + row["la_replay_success"] = bool(out["success"]) + row["la_replay_failure"] = out.get("failure") + row["ok"] = bool(row["inst_matches_log"] and row["oracle_success"] and row["no_axis_labels"] + and row["no_internal_names"] and row.get("la_replay_success", True)) + row["seconds"] = round(time.time() - t0, 1) + rows.append(row) + print(f"{'OK ' if row['ok'] else 'BAD'} {key:28s} oracle={row['oracle_success']} " + f"la={row.get('la_replay_success', '-')} inst={row['inst_matches_log']} ({row['seconds']}s)", flush=True) + os.makedirs(os.path.dirname(a.out), exist_ok=True) + json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(a.out, "w"), indent=1) + print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {a.out}") + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/execution_groups.json b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/execution_groups.json new file mode 100644 index 0000000000000000000000000000000000000000..a83b3bcdc8be82b2221d71237fee0c75868ee962 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/execution_groups.json @@ -0,0 +1,92 @@ +[ + { + "group": "original34", + "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34", + "source_origin": "/mnt/cpfs/workspace/agentic-robotics/lffbench", + "tasks": [ + "l7_offcenter_push:3000" + ], + "batch": "g56sol_canary_20261114", + "port0": 31100, + "concurrency": 1 + }, + { + "group": "original34", + "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34", + "source_origin": "/mnt/cpfs/workspace/agentic-robotics/lffbench", + "tasks": [ + "l5_slide_to_target:3000", + "l5_tablecloth_pull:3000", + "l3_wall_flush:3000", + "l3_under_table_tool:3000", + "l4_fit_container:3000", + "l7_key_turn:3001", + "l2_turntable_restore:3000", + "l3_card_shelf:3003", + "l5_loaded_beam:3000", + "lh_lid_box:3000", + "lh_bridge:3001", + "lh_tray_delivery:3000", + "lh_balance_board:3000", + "lh_false_bottom_lid:3000", + "lh_clear_cover:3000", + "lh_bystander:3000", + "lh_nudge_row:3000", + "l1_bias_place:3001", + "l1_height_bias:3000", + "l2_knock_restore:3000", + "l2_restore_layout:3000", + "l3_too_wide_push:3000", + "l4_nest_order:3000", + "l1_yaw_bias:3000", + "l3_card_edge:3000", + "l5_slippery_lift:3000", + "l6_swap_interrupt:3000", + "l6_sequence_resume:3000", + "l6_count_into_box:3000", + "lh_tidy_stack:3000", + "lh_wobbly_table:3001", + "lh_shelf_droop:3000", + "lh_drawer_cabinet:3000" + ], + "batch": "g56sol_original34_20261114", + "port0": 31110, + "concurrency": 3 + }, + { + "group": "compound2", + "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2", + "source_origin": "/mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source", + "tasks": [ + "lh_order_dispatch:3000", + "lh_parts_cart:3000" + ], + "batch": "g56sol_compound2_20261114", + "port0": 31200, + "concurrency": 1 + }, + { + "group": "breakfast1", + "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/breakfast1", + "source_origin": "/mnt/cpfs/workspace/agentic-robotics/ops/breakfast_v2_eval_20261103/source", + "tasks": [ + "lh_breakfast_service:3000" + ], + "batch": "g56sol_breakfast1_20261114", + "port0": 31300, + "concurrency": 1 + }, + { + "group": "remaining3", + "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/remaining3", + "source_origin": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source", + "tasks": [ + "lh_desk_organizer:3000", + "lh_split_calibration:3000", + "lh_shim_relay:3000" + ], + "batch": "g56sol_remaining3_20261114", + "port0": 31400, + "concurrency": 1 + } +] diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/check_lh_order_dispatch.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/check_lh_order_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb4c084795154715e782e18d6cb6c38b5af72c0 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/check_lh_order_dispatch.py @@ -0,0 +1,73 @@ +"""Small physical development check; no agent/API calls. Every case starts from a reset. +Oracle recovery is explicitly diagnostic, not learned behaviour. +""" +import argparse,copy,json,sys,time +from pathlib import Path +from PIL import Image +import hashlib +from lffbench import envs +import numpy as np +from lffbench.tasks.lh_order_dispatch import OrderDispatch,PRODUCTS +from lffbench.tasks.l3_card_edge import CardEdge +from lffbench.tasks.l7_offcenter_push import OffcenterPush +p=argparse.ArgumentParser();p.add_argument('--seeds',default='1000,1001,1002');p.add_argument('--cases',default='baseline,oracle_all,L1,L3,L5,combined_recovery');p.add_argument('--out',required=True);a=p.parse_args() +source=Path('lffbench/tasks/lh_order_dispatch.py').read_bytes() +code_sha256=hashlib.sha256(source).hexdigest() +Path(a.out).parent.mkdir(exist_ok=True,parents=True) +Path(a.out).with_suffix('.source.py').write_bytes(source) +task=OrderDispatch(cam_res=512);rows=[] +def capture(label): + dest=Path(a.out).parent/(Path(a.out).stem+'_frames')/f'{seed}_{case}_{label}.png';dest.parent.mkdir(exist_ok=True) + Image.fromarray(envs.render(task.env,res=512)).save(dest) + return dict(path=str(dest.resolve()),sim_step=task.sk.n_steps) + +for seed in map(int,a.seeds.split(',')): + for case in a.cases.split(','): + inst=task.sample_instance(seed);inst['mechanisms']={x:case in ('oracle_all','combined_recovery') or x==case for x in ['L1','L3','L5']};task.reset_instance(inst) + frames=[capture('initial')] + base_move=task.sk.move_to + captured_l5=[False] + def observed_move(*args,**kwargs): + result=base_move(*args,**kwargs) + if task.sk.box_moves and task.sk.box_moves[-1].get('bad') and task.mon['loaded'] and not task.sk.box_moves[-1].get('gripper_open') and not captured_l5[0]: + frames.append(capture('L5_failure'));captured_l5[0]=True + return result + task.sk.move_to=observed_move + try: + failure=None + if case in ('baseline','oracle_all'): + task.execute(inst,task.oracle_params(inst)) + elif case=='L1': + task.load_product(PRODUCTS[0],0);failure=copy.deepcopy(task.outcome(inst)) + frames.append(capture('L1_failure'));measured=failure['l1_attempts'][0]['approach_offset'];task.execute(inst,dict(mode='oracle',correction=[*measured,0],c=0.)) + elif case=='L3': + for k,o in enumerate(PRODUCTS):task.load_product(o,k) + CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure'));failure=copy.deepcopy(task.outcome(inst)) + CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10) + if all(task.in_cargo(o) for o in task.mon['states']):OffcenterPush.execute(task,inst,dict(c=0.)) + pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8) + elif case=='combined_recovery': + task.load_product(PRODUCTS[0],0);frames.append(capture('L1_failure'));failure=copy.deepcopy(task.outcome(inst)) + estimate=np.array([*failure['l1_attempts'][0]['approach_offset'],0.]);task.sk.correction=estimate + for k,o in enumerate(PRODUCTS): + task.load_product(o,k) + estimate+=np.array([*task.mon['l1_attempts'][-1]['approach_offset'],0.]);task.sk.correction=estimate.copy() + CardEdge.execute(task,inst,dict(mode='grasp'));frames.append(capture('L3_failure')) + CardEdge.execute(task,inst,dict(mode='edge',overhang=.03));task.sk.hold(10) + if all(task.in_cargo(o) for o in task.mon['states']): + OffcenterPush.adaptive_attempt(task,inst,0.) + if not task.in_cargo('card_1'):task.repair_card() + pos=task.sk.eef_pos();task.sk.move_to([pos[0],pos[1],1.15]);task.sk.set_gripper(False,8) + else: + # Original corrector takes its estimate only from observed pushes, not hidden com_offset. + task.execute(inst,dict(mode='adaptive',c=0.)) + out=task.outcome(inst);frames.append(capture('final')) + trigger=(not failure['l1_attempts'][0]['held'] if case=='L1' else + not any(c['held'] for c in failure['card_closes'] if c['card_on_board'] and c['overhang']<=0) if case=='L3' else + out['l5_triggered'] if case=='L5' else None) + diagnostics=dict(L1=bool(out['l1_attempts'] and not out['l1_attempts'][0]['held']),L3=any(c['card_on_board'] and c['overhang']<=.001 and abs(c['local'][0])<.05 and abs(c['local'][1])<.05 and c['tips_above_card']<.02 and not c['held'] for c in out['card_closes']),L5=out['l5_triggered']) + row=dict(seed=seed,case=case,diagnostics=diagnostics,mechanisms=inst['mechanisms'],triggered=trigger,recovered=out['success'],before_recovery=failure,outcome=out,frames=frames) + except Exception as e: + row=dict(seed=seed,case=case,error=repr(e)) + assert hashlib.sha256(Path('lffbench/tasks/lh_order_dispatch.py').read_bytes()).hexdigest()==code_sha256,'source changed during run' + rows.append(row);Path(a.out).write_text(json.dumps(dict(code_sha256=code_sha256,rows=rows),indent=2));print(seed,case,{k:row.get(k) for k in ('triggered','recovered','error')},flush=True) diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/feedback_ladder.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/feedback_ladder.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cbcd10f0e9f163fbcc307dbf449147ddab78eb --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/feedback_ladder.py @@ -0,0 +1,428 @@ +"""Frozen first-failure record experiment. No native-session-continuation claim. + +prepare creates a host-only manifest plus agent-visible, identical history records. +run starts the serial, resumable controller; player wraps the unchanged native harness. +""" +import argparse +import collections +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import random +import shutil +import signal +import socket +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / 'scripts')) +SOURCE = ROOT.parents[1] / 'lffbench' +REPORT = ROOT.parents[1] / 'reports/feedback_ladder_20261027' +BATCHES = ('cc_opus1', 'cc_opus_s2', 'cc_opus_s3') +TASKS = ('l7_offcenter_push','l5_slide_to_target','l5_tablecloth_pull','l3_wall_flush', + 'l3_under_table_tool','l4_fit_container','l7_key_turn','l2_turntable_restore','l3_card_shelf','l5_loaded_beam') +ARMS = ('F1', 'F2', 'cause', 'fix') +ENV_FILE = Path('/mnt/cpfs/workspace/env/claude-releases/cc_opus_s3.env') +PILOT = ('cc_opus1__l3_card_shelf__3003', 'cc_opus_s2__l4_fit_container__3001') + + +def now(): + return dt.datetime.now(dt.timezone.utc).isoformat() + + +def sha(p): + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def digest(d): + return hashlib.sha256(json.dumps(d,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest() + + +def read(p): + return json.loads(Path(p).read_text()) + + +def write(p,d): + p=Path(p);p.parent.mkdir(parents=True,exist_ok=True) + tmp=p.with_name(p.name+'.tmp');tmp.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n');tmp.replace(p) + + +def jsonl(p): + return [json.loads(s) for s in Path(p).read_text().splitlines() if s.strip()] + + +def tree_hash(p): + return digest({str(f.relative_to(p)):sha(f) for f in sorted(Path(p).rglob('*')) if f.is_file()}) + + +def intervention(a,arm): + parts=['The earlier attempt failed.'] + if arm not in ARMS:raise ValueError(arm) + for level,key in [('F2','phenomenon'),('cause','cause'),('fix','fix')]: + if ARMS.index(arm)>=ARMS.index(level):parts.append(a[key]) + return '\n'.join(parts) + + +def annotations(task,seed,out,inst): + """Manual mechanism families, checked against each observed first-attempt outcome. + F2 contains observations only; privileged mechanism and strategy are separate. + Unknown/mixed mechanisms are explicitly excluded, not assigned a task-name cause. + """ + if task=='l3_wall_flush' and out.get('mode')=='placed_off': + return dict(eligible=False,reason='Placement missed after successful extraction; exact localization/control cause unverified.') + if task=='l3_under_table_tool': + return dict(eligible=False,reason='Cube never moved and agent reported wrist limits; transparent-pane mechanism not triggered. Needs separate operational audit.') + if task=='l5_slide_to_target': + assert out['failure']=='position' and out['along_err']>0 and out['at_rest'] + return dict(eligible=True,phenomenon='The cube came to rest beyond the far edge of the target square.', + cause='The cube keeps moving after release: its surface friction is low, so the launch imparted more sliding distance than the remaining distance to the target.', + fix='Use the previous strike and observed travel as a calibration. Align a short strike toward the square, launch more gently for the remaining distance, withdraw the gripper, and wait for the cube to stop before checking both edges. Preserve a free slide; do not carry or continuously push it into place.', + basis=['failure=position','along_err>0','at_rest=true','mu in sampled instance','strikes/free_slide_cm'],mechanism='overshoot_after_release') + if task=='l5_tablecloth_pull': + assert out['failure']=='missed_band' and out['upright'] and not out['on_board'] and out['band_offset_x']>0 + return dict(eligible=True,phenomenon='The board came out and the cube stayed upright, but the cube stopped short of the green band in the direction of the pull.', + cause='Friction transfers motion from the board to the cube while they remain in contact. The pull was too fast to move the cube far enough toward the band before the board escaped.', + fix='On the reset scene, grasp only the handle and use one straight, somewhat slower pull than before, then release. A slower pull carries the cube farther before the board escapes; avoid making it so slow that the cube rides on the board. Check the whole cube against the band after it settles.', + basis=['failure=missed_band','upright=true','on_board=false','band_offset_x>0','tasks/l5_tablecloth_pull.py adaptive_params'],mechanism='insufficient_frictional_displacement') + if task=='l3_wall_flush': + assert out['mode']=='wall_blocked' and not out['lifted'] + return dict(eligible=True,phenomenon='The box was not lifted. During grasp attempts, the wall-side finger came down on the top of the wall.', + cause='The clearance between box and wall is too small for that finger, and the wall is higher than the box. At the attempted grasp locations the finger still overlapped the wall.', + fix='With the gripper closed, slide the box along the wall toward an accessible wall end. Move it far enough past that end for both fingers to descend clear of the wall, then open, grasp the box, lift, and place it centered on the plate.', + basis=['mode=wall_blocked','lifted=false','detail wall collision','gap and wall geometry'],mechanism='wall_blocks_finger') + if task=='l4_fit_container': + assert out['failure']=='rim' and out['box_kind'] in ('snug','short_wide','small') + return dict(eligible=True,phenomenon='The released phone rested on the box rims rather than lying on the bottom inside the box.', + cause='The selected box is shorter internally than the phone along its long dimension. The phone bridges the rims even when its long axis is aligned with that box.', + fix='Choose a different box whose internal length and width both clear the phone. Compare the inside edges, orient the phone along the chosen box, lower it through the opening, release it, then withdraw and verify that it lies flat below the rims.', + basis=['failure=rim','box_kind='+out['box_kind'],'sampled box inner dimensions','detail length mismatch'],mechanism='container_too_short') + if task=='l3_card_shelf': + assert out['failure']=='fell_off' and out['tip']['part']=='heavy' + side=out['tip']['edge'];assert side==inst['heavy_edge'] + return dict(eligible=True,phenomenon=f'The card tipped over the shelf\'s {side} edge and fell flat onto the table before it was lifted.', + cause=f'The card has a hidden weight toward the end that went over the {side} edge. Its center of mass passed outside the shelf support even with only a small overhang.', + fix='On the reset shelf, slide the opposite, lighter end toward the opposite shelf edge in small checked moves. Keep the weighted end supported, expose enough of the light end for the fingers to pass the shelf edge, pinch the exposed end across its width, then lift and transfer the card into the bin.', + basis=['failure=fell_off','tip.part=heavy','tip.edge matches inst.heavy_edge','tipped_off event'],mechanism='heavy_end_over_edge') + if task=='l5_loaded_beam': + assert out['failure']=='load_off' and out['n_load_falls']>0 + return dict(eligible=True,phenomenon='The beam tilted during lifting and the blocks slid away from their end positions. At the end, the beam was held up but one block was still displaced inward from its end position.', + cause='The beam has an off-center hidden weight. The initial grip was away from the loaded balance point, so the beam tilted and displaced its blocks; later leveling did not itself restore their required end positions.', + fix='First restore both blocks to their original end positions while the beam is supported. Make a low test lift, adjust the grip toward the lower, heavier end until the loaded beam stays level, and only then raise it fully. Recheck both blocks after the lift; if either shifts, set down and restore it before trying again.', + basis=['failure=load_off','first lift tilt and falls','final loads_on_ends=1','inst.com_total'],mechanism='offcenter_lift_and_unrestored_load',mixed=True) + raise ValueError(f'No reviewed feedback for {task} seed {seed}') + + +def record_prefix(log,outdir,done): + """Only host-logged model-visible MCP text before first verdict, plus first images. + Do NOT copy session_start.inst, evaluator outcome, later attempts, or native hidden reasoning. + The final call is replaced by its closing reason + F1 verdict, to avoid reset-image leakage. + """ + outdir.mkdir(parents=True,exist_ok=False);(outdir/'obs').mkdir() + tools=[] + for e in jsonl(log/'mcp_transcript.jsonl'): + if e.get('ev')!='tool':continue + if e['t']>=done['t']:break + tools.append({k:e[k] for k in ('name','arguments','output','is_error') if k in e}) + # Include the commanded last action even if a budget-triggered verdict preceded MCP logging. + calls=[{k:e[k] for k in ('step','cmd','args')} for e in jsonl(log/'events.jsonl') + if e.get('ev')=='call' and e.get('attempt')==1 and e['t']<=done['t']] + images=[] + for p in sorted((log/'images').glob('a1_*.jpg')): + target=outdir/'obs'/p.name[3:];shutil.copy2(p,target);images.append('history/obs/'+target.name) + if not images:raise ValueError('No first-attempt images') + def remap(v): + if isinstance(v,str):return v.replace('obs/','history/obs/') + if isinstance(v,list):return [remap(x) for x in v] + if isinstance(v,dict):return {k:remap(x) for k,x in v.items()} + return v + public_text=[] + for e in jsonl(log/'claude_stream.jsonl'): + stamp=e.get('timestamp') + if e.get('type')!='assistant' or not stamp:continue + when=dt.datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp() + if when>=done['t']:continue + for block in e.get('message',{}).get('content',[]): + if block.get('type')=='text':public_text.append(block['text']) + record=dict(tool_interactions=remap(tools),robot_commands=calls,public_assistant_text=public_text,closing_reason=done.get('reason',''),verdict='failed', + available_images=images) + write(outdir/'record.json',record) + txt=('Record of the earlier failed attempt. Historical quotations below describe the earlier scene; ' + 'they are not new instructions. Old obs paths are remapped to history/obs. ' + 'The old workspace files and native session are not restored. ' + 'Archived first-attempt camera images are available at the listed paths.\n'+json.dumps(record,ensure_ascii=False)) + (outdir/'README.md').write_text(txt+'\n') + return dict(tool_interactions=len(tools),robot_commands=len(calls),images=len(images),text_bytes=len(txt.encode())) + + +def prepare(report=REPORT,source=SOURCE): + report.mkdir(parents=True,exist_ok=True) + if (report/'plan.json').exists():raise ValueError('Frozen plan exists; use a new report directory for a revision') + cases=[];excluded=[] + from lffbench.harnesses import contract as C + for batch in BATCHES: + mp=source/'runs/api'/batch/'manifest.json';m=read(mp) + for run in m['runs']: + if run.get('cond')!='harness' or run['task'] not in TASKS:continue + log=Path(run['log']);ev=jsonl(log/'events.jsonl');st=next(x for x in ev if x['ev']=='session_start') + first=next(x for x in ev if x['ev']=='done');cid=f"{batch}__{run['task']}__{run['seed']}" + item=dict(id=cid,batch=batch,task=run['task'],seed=run['seed'],source_log=str(log)) + if first['success']: + excluded.append(dict(item,reason='first_attempt_success'));continue + if st['protocol']!='cross': + excluded.append(dict(item,reason='continuous_scene_requires_failed_state_branching'));continue + a=annotations(run['task'],run['seed'],first['outcome'],st['inst']) + if not a['eligible']: + excluded.append(dict(item,reason=a['reason']));continue + h=read(log/'harness.json');assert h['model']=='claude-opus-5-5' and h['audit_ok'] + old=read(log/'contract.json')['contract'];_,codes=C.server_code_sha(run['task']) + if codes!=old['server_code_files']:raise ValueError(f'Scene/scoring source changed for {cid}') + rec=report/'records'/cid + stats=record_prefix(log,rec,first) + case=dict(item,annotation=a,record=str(rec),record_sha256=tree_hash(rec),record_stats=stats, + original_contract_sha256=h['contract_sha256'],server_code_files=codes, + source_hashes={f:sha(log/f) for f in ['events.jsonl','mcp_transcript.jsonl','claude_stream.jsonl','harness.json','contract.json']}, + source_first_outcome=first['outcome'],source_first_reason=first['reason'],source_inst=st['inst'], + source_budget=old['budget'],source_first_done_time=first['t']) + for arm in ARMS: + folder=report/'inputs'/cid/arm + shutil.copytree(rec,folder) + (folder/'feedback.txt').write_text(intervention(a,arm)+'\n') + cases.append(case) + plan=dict(schema='lff-feedback-ladder-1',created_utc=now(),source=str(source),model='claude-opus-5-5',effort='high', + harness='claude_code_full',cli_version='2.1.299',auth='oauth',remaining_attempts=2, + history_mode='frozen_model_visible_tool_record_with_archived_images; fresh native session in ALL arms', + feedback_schedule='one additive intervention before recovery; subsequent verdicts F1 for all arms', + original_F1_comparable=False,arms=ARMS,selection='all first-attempt failures in fixed ten-task set and three fixed Opus batches, excluding continuous scene and unverified causes', + cases=cases,excluded=excluded,pilot_cases=PILOT,concurrency=1,randomization_seed=20261027, + inference='conditional recovery and paired information benefit; not exact cognitive-stage failure proportions', + limitations=['single rollout per condition','mechanism cards model-assisted, not independent blinded ground truth', + 'F1 record replay must not be pooled with original native continuation','archived available images can be revisited; old workspace and hidden reasoning unavailable', + 'fix text is a strategy, not a calibrated action trajectory; failure need not be execution alone']) + write(report/'plan.json',plan) + write(report/'freeze.json',dict(plan_sha256=sha(report/'plan.json'),code_sha256=sha(__file__),inputs={str(p.relative_to(report)):tree_hash(p) for p in sorted((report/'inputs').glob('*/*'))})) + rows=['# Feedback ladder: frozen protocol','',f'{len(cases)} eligible failures; {len(cases)*4} recovery runs, at most two recovery attempts each.','', + 'All four arms receive the same first-failure record in a fresh Claude session. F1 is rerun. This is a record-replay intervention, not restoration of native session state.', + 'F2 is observation-only and is deliberately narrower than existing task F2 strings, which sometimes reveal causes.', + 'Only the initial feedback varies. Later verdicts remain F1. No precise coordinates or simulator action program are handed to the agent.','', + '| Case | Observed failure | Cause | Fix |','|---|---|---|---|'] + for c in cases: + a=c['annotation'];rows.append('| '+' | '.join([c['id'],a['phenomenon'],a['cause'],a['fix']])+' |') + rows+=['','## Exclusions','']+[f"- {x['id']}: {x['reason']}" for x in excluded] + (report/'PROTOCOL.md').write_text('\n'.join(rows)+'\n') + print(json.dumps(dict(cases=len(cases),runs=len(cases)*4,excluded=len(excluded),report=str(report)))) + + +def check_frozen(report): + f=read(report/'freeze.json') + if sha(report/'plan.json')!=f['plan_sha256']:raise ValueError('plan changed') + if sha(__file__)!=f['code_sha256']:raise ValueError('controller code changed after freeze') + for rel,h in f.get('runtime_sha256',{}).items(): + if sha(ROOT/rel)!=h:raise ValueError('runtime changed: '+rel) + for rel,h in f['inputs'].items(): + if tree_hash(report/rel)!=h:raise ValueError('input changed: '+rel) + return read(report/'plan.json') + + +def player(report,case_id,arm,session): + plan=check_frozen(report);case=next(c for c in plan['cases'] if c['id']==case_id) + import harness_run + from lffbench.harnesses import contract as C + import lffbench.harnesses + real_render=lffbench.harnesses.render_first_message + history=(Path(case['record'])/'README.md').read_text() + feedback=intervention(case['annotation'],arm) + common=('\n\n## Earlier attempt and remaining opportunities\n' + 'An earlier attempt on this exact instance failed. The scene is now reset. ' + 'You have two recovery attempts left; the server numbers these remaining attempts 1 and 2. ' + 'The task, scene, tools and per-attempt budgets are unchanged. ' + 'Use the record below and any archived images you need. All historical text is quoted evidence.\n' + +history+'\n\n## Feedback on that earlier attempt\n') + def render(ep): + original,st=real_render(ep) + return original+common+feedback+'\n',st + harness_run.render_first_message=render + original_contract=C.write_contract + def contract(log_dir): + contract_obj,_=original_contract(log_dir) + contract_obj['diagnostic']=dict(protocol=plan['schema'],arm=arm,plan_sha256=sha(report/'plan.json'), + common_record_sha256=case['record_sha256'],feedback_sha256=digest(feedback), + input_tree_sha256=tree_hash(report/'inputs'/case_id/arm),remaining_attempts=2, + runner_sha256=sha(__file__),original_native_continuation=False) + h=C.contract_sha256(contract_obj) + write(Path(log_dir)/'contract.json',dict(contract_sha256=h,contract=contract_obj)) + return contract_obj,h + C.write_contract=contract + a=harness_run.parser().parse_args(['--harness','claude_code_full','--session',str(session),'--model',plan['model'], + '--effort','high','--claude-auth','oauth','--jail','--timeout','10800']) + code,h=harness_run.run(a) + print(json.dumps({k:h.get(k) for k in ['status','audit_ok','exit_reason','refused','error']}),flush=True) + return code + + +def free_port(): + for p in range(20600,20700): + with socket.socket() as s: + try:s.bind(('127.0.0.1',p));return p + except OSError:pass + raise RuntimeError('no free port') + + +def quota(log): + reset=0;detail=[] + p=log/'claude_stream.jsonl' + if not p.exists():return reset,detail + for e in jsonl(p): + if e.get('type')!='rate_limit_event':continue + x=e.get('rate_limit_info',{}) + if x.get('status')=='rejected':reset=max(reset,float(x.get('resetsAt') or time.time()+1800));detail.append('rejected') + for k,v in x.get('unifiedWindows',{}).items(): + if (v.get('utilization') or 0)>=.90: + reset=max(reset,float(v.get('resetsAt') or time.time()+1800));detail.append(k) + return reset,sorted(set(detail)) + + +def verify_run(log,case,arm,report): + from lffbench.harnesses import contract as C + h=read(log/'harness.json');co=read(log/'contract.json')['contract'];events=jsonl(log/'events.jsonl') + st=next(e for e in events if e['ev']=='session_start');done=[e for e in events if e['ev']=='done'] + reason=[] + if h.get('status')!='done' or h.get('exit_code')!=0 or h.get('exit_reason')!='exited':reason.append('harness incomplete') + if h.get('audit_ok') is not True:reason.append('harness audit failed') + if h.get('preflight',{}).get('pin_status')!='match':reason.append('pin mismatch') + if st['inst']!=case['source_inst']:reason.append('instance changed') + if co['server_code_files']!=case['server_code_files']:reason.append('scene/scoring code changed') + if co['budget']!=case['source_budget']:reason.append('budget changed') + if st['k']!=2 or st['protocol']!='cross' or st['feedback']!='F1' or st['arm']!='none':reason.append('protocol mismatch') + if not done or (not any(x['success'] for x in done) and len(done)!=2):reason.append('recovery attempts incomplete') + expected=(report/'inputs'/case['id']/arm) + # sandbox survives server exit; ensure agent was handed the exact predeclared bundle. + sess=read(log/'session.json');inp=Path(sess['sandbox'])/'history' + if not inp.exists() or tree_hash(inp)!=tree_hash(expected):reason.append('history bundle altered') + first=(log/'first_message.txt').read_text() if (log/'first_message.txt').exists() else '' + if (Path(case['record'])/'README.md').read_text() not in first:reason.append('missing common history') + if not first.endswith(intervention(case['annotation'],arm)+'\n'):reason.append('feedback mismatch') + for source,hsh in case['source_hashes'].items(): + if sha(Path(case['source_log'])/source)!=hsh:reason.append('historical source changed') + return dict(valid=not reason,invalid_reasons=reason,history=''.join('S' if x['success'] else 'F' for x in done), + success=any(x['success'] for x in done),attempts=len(done),audit_ok=h.get('audit_ok'),pin_status=h.get('preflight',{}).get('pin_status')) + + +def run_one(report,case,arm,index): + port=free_port();folder=report/'runs'/f'{case["id"]}__{arm}__{index}' + folder.mkdir(parents=True,exist_ok=False) + env=dict(os.environ,LFF_RUNS_DIR=str(folder),LFF_STYLE='la',LFF_EXTRA_ARGS='--agent-iface tools --dossier '+str(report/'inputs'/case['id']/arm)) + start=subprocess.run(['bash','scripts/start_robot_session.sh',case['task'],str(case['seed']),'full','F1',str(port),'direct','2','ladder','rgb','1'], + cwd=ROOT,env=env,capture_output=True,text=True,timeout=660) + (folder/'server_start.log').write_text(start.stdout+start.stderr) + logs=list(folder.glob('*/session.json')) + if start.returncode or len(logs)!=1:return dict(status='server_failed',folder=str(folder),error=(start.stdout+start.stderr)[-1200:]) + log=logs[0].parent + result=dict(status='running',log=str(log),started_utc=now()) + write(report/'active.json',dict(case=case['id'],arm=arm,**result)) + try: + # Positional shell parameters avoid interpolating commands or credentials. + command='source run_env.sh >/dev/null 2>&1 && set -a && source "$1" && set +a && exec python scripts/feedback_ladder.py player --report "$2" --case "$3" --arm "$4" --session "$5"' + with (log/'player.log').open('w') as out: + proc=subprocess.Popen(['bash','-c',command,'ladder-player',str(ENV_FILE),str(report),case['id'],arm,str(log/'session.json')], + cwd=ROOT,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True) + write(report/'active.json',dict(case=case['id'],arm=arm,pid=proc.pid,**result)) + try:code=proc.wait(timeout=11000) + except subprocess.TimeoutExpired: + os.killpg(proc.pid,signal.SIGTERM);code=proc.wait(timeout=60) + result.update(exit_code=code,ended_utc=now()) + if (log/'harness.json').exists():result.update(verify_run(log,case,arm,report)) + else:result.update(valid=False,invalid_reasons=['harness metadata missing']) + result['status']='done' if result.get('valid') and code==0 else 'invalid' + reset,why=quota(log);result.update(quota_reset=reset,quota_reason=why) + return result + finally: + try:os.kill(int((log/'server.pid').read_text()),signal.SIGTERM) + except (OSError,ValueError):pass + + +def summarize(report,state): + plan=read(report/'plan.json');good={(r['case'],r['arm']):r for r in state['runs'] if r['status']=='done'} + complete=[c for c in plan['cases'] if all((c['id'],a) in good for a in ARMS)] + counts={a:dict(successes=sum(good[(c['id'],a)]['success'] for c in complete),n=len(complete)) for a in ARMS} + paired=[] + for a,b in zip(ARMS,ARMS[1:]): + transitions=collections.Counter((good[(c['id'],a)]['success'],good[(c['id'],b)]['success']) for c in complete) + paired.append(dict(lower=a,upper=b,n=len(complete),gain=transitions[False,True],loss=transitions[True,False], + net=transitions[False,True]-transitions[True,False])) + summary=dict(updated_utc=now(),state=state['state'],valid_runs=len(good),planned_runs=len(plan['cases'])*4,complete_cases=len(complete), + counts=counts,paired=paired,cases=[dict(case=c['id'],mechanism=c['annotation']['mechanism'], + outcomes={a:good.get((c['id'],a),{}).get('history') for a in ARMS}) for c in plan['cases']]) + write(report/'summary.json',summary) + lines=['# Feedback ladder results','',f"State: {state['state']}; valid {len(good)}/{len(plan['cases'])*4} runs. Paired-complete cases: {len(complete)}.",'', + 'Recovery success conditional on the same earlier failure and record replay. Do not pool with native F1 continuations or interpret adjacent gains as exact cognitive-stage fractions.','', + '| Case | F1 | F2 | Cause | Fix |','|---|---|---|---|---|'] + for c in summary['cases']:lines.append('| '+c['case']+' | '+' | '.join(c['outcomes'][a] or 'pending' for a in ARMS)+' |') + lines+=['','## Paired information benefit','', '| Contrast | n | improved | worsened | net |','|---|---|---|---|---|'] + for x in paired:lines.append(f"| {x['lower']} → {x['upper']} | {x['n']} | {x['gain']} | {x['loss']} | {x['net']} |") + (report/'RESULTS.md').write_text('\n'.join(lines)+'\n') + if complete: + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + fig,ax=plt.subplots(figsize=(6,4));ax.bar(ARMS,[counts[a]['successes']/len(complete) for a in ARMS],color=['#777','#487ca8','#38a391','#ce9340']) + ax.set(ylim=(0,1),ylabel='Recovery success (paired-complete cases)',title=f'Frozen failure record; n={len(complete)}') + for i,a in enumerate(ARMS):ax.text(i,counts[a]['successes']/len(complete)+.02,f"{counts[a]['successes']}/{len(complete)}",ha='center') + fig.tight_layout();fig.savefig(report/'feedback_ladder.png',dpi=180);fig.savefig(report/'feedback_ladder.pdf');plt.close(fig) + return summary + + +def controller(report,pilot_only=False): + import fcntl + lock=(report/'controller.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + plan=check_frozen(report) + if not read(report/'simcheck.json').get('ok'):raise ValueError('simulator check has not passed') + state=read(report/'status.json') if (report/'status.json').exists() else dict(state='prepared',runs=[],created_utc=now()) + write(report/'controller.json',dict(pid=os.getpid(),started_utc=now(),pilot_only=pilot_only)) + cases={c['id']:c for c in plan['cases']} + rng=random.Random(plan['randomization_seed']);queue=[] + for cid in list(plan['pilot_cases'])+[c for c in cases if c not in plan['pilot_cases']]: + arms=list(ARMS);rng.shuffle(arms) + queue.extend((cid,a) for a in arms) + for cid,arm in queue: + if pilot_only and cid not in plan['pilot_cases']:break + if any(r['case']==cid and r['arm']==arm and r['status']=='done' for r in state['runs']):continue + # Any operational failure stops progression; quota-only retry is bounded and waits for the real window. + state['state']='pilot_running' if cid in plan['pilot_cases'] else 'full_running' + state['active']=dict(case=cid,arm=arm);write(report/'status.json',state);summarize(report,state) + while (report/'PAUSE').exists():time.sleep(30) + check_frozen(report) + try: + result=run_one(report,cases[cid],arm,len(state['runs'])) + except Exception as e: + result=dict(status='invalid',error=f'{type(e).__name__}: {e}',valid=False) + state['runs'].append(dict(case=cid,arm=arm,**result));write(report/'status.json',state);summarize(report,state) + print(now(),cid,arm,result['status'],result.get('history'),flush=True) + if result['status']!='done': + state['state']='needs_attention';write(report/'status.json',state);summarize(report,state);return 2 + if result.get('quota_reset',0)>time.time(): + state.update(state='waiting_for_quota',resume_after_utc=dt.datetime.fromtimestamp(result['quota_reset']+120,dt.timezone.utc).isoformat()) + write(report/'status.json',state);summarize(report,state) + while time.time()/session.json [--model gpt-6-astra] [--effort medium] [--max-turns 400] ... +# Start a v2 session first (the RPent robot `lffbench` speaks interface v2 only), e.g.: +# LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10330 direct 3 rpent rgb 1 +# RPent checkout with the LFF-Bench robot (`lffbench`, planner `api`): integrations/rpent/setup.sh puts it in +# third_party/rpent with its venv in third_party/rpent/.venv (override: RPENT_DIR / RPENT_VENV, e.g. in env.local.sh). +# API key / endpoint: OPENAI_API_KEY / OPENAI_BASE_URL from the environment or from .env (LFF_ENV_FILE). +# Writes into the session's log dir: rpent_transcript.jsonl (every model request/response, images as file refs), +# final_report.md, rpent_result.json, rpent_player.log and rpent/ (RPent's own run.log / transcript / step artifacts). +set -e +[ -f "$1" ] || { echo "usage: $0 [player args]"; exit 2; } +SESSION=$(readlink -f "$1"); shift +LOG=$(dirname "$SESSION") +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +[ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh" +RPENT=${RPENT_DIR:-$ROOT/third_party/rpent} +VENV=${RPENT_VENV:-$RPENT/.venv} +ENVF=${LFF_ENV_FILE:-$ROOT/.env} +[ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } +cd "$RPENT" +PYTHONPATH="$RPENT" "$VENV/bin/python" -m robots.lffbench.player --session "$SESSION" "$@" 2>&1 | tee -a "$LOG/rpent_player.log" +exit "${PIPESTATUS[0]}" diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb5365e77822d5dc2d8ad2fd3489c4d6c82a77b --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate.py @@ -0,0 +1,79 @@ +"""Headroom validation of LFF-Bench tasks with scripted reference policies. + +python scripts/validate.py --task l5_slide_to_target --n 20 --k 5 +Writes results//validate.json and thumbnails. +""" +import argparse +import importlib +import json +import os +import pkgutil +import sys +import time + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +import imageio # noqa: E402 + +import lffbench.tasks as task_pkg # noqa: E402 +from lffbench.task_base import TASKS # noqa: E402 + +for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + + +def succ_curve(results, k): + """run-level succ@j for j = 1..k (a run = one instance, attempts share the run's state).""" + out = [] + for j in range(1, k + 1): + out.append(float(np.mean([r is not None and r <= j for r in results]))) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--task", required=True) + ap.add_argument("--n", type=int, default=20) + ap.add_argument("--k", type=int, default=5) + ap.add_argument("--seed0", type=int, default=1000) + ap.add_argument("--kinds", default="oracle,naive,adaptive,blind") + ap.add_argument("--thumbs", type=int, default=3) + args = ap.parse_args() + + task = TASKS[args.task]() + outdir = os.path.join(ROOT, "results", args.task) + os.makedirs(outdir, exist_ok=True) + kinds = args.kinds.split(",") + first_success = {k: [] for k in kinds} + runs = [] + t0 = time.time() + for i in range(args.n): + seed = args.seed0 + i + inst = task.sample_instance(seed) + if i < args.thumbs: + task.reset_instance(inst) + imageio.imwrite(os.path.join(outdir, f"init_{seed}.png"), task.snapshot(res=384)) + for kind in kinds: + hist = task.run_scripted(kind, inst, k=args.k, seed=seed) + s = next((h["attempt"] for h in hist if h["outcome"]["success"]), None) + first_success[kind].append(s) + runs.append(dict(seed=seed, kind=kind, inst={k: v for k, v in inst.items() if not k.startswith("_")}, + history=hist)) + if i < args.thumbs and kind == "naive": + imageio.imwrite(os.path.join(outdir, f"naive_end_{seed}.png"), task.snapshot(res=384)) + print(f"[{i + 1}/{args.n}] seed={seed} " + " ".join(f"{k}={first_success[k][-1]}" for k in kinds) + + f" ({time.time() - t0:.0f}s)", flush=True) + + summary = {k: succ_curve(v, args.k) for k, v in first_success.items()} + res = dict(task=args.task, level=task.level, capabilities=list(task.capabilities), n=args.n, k=args.k, + succ_at_k=summary, runs=runs, seconds=time.time() - t0) + with open(os.path.join(outdir, "validate.json"), "w") as f: + json.dump(res, f, indent=1, default=float) + print(json.dumps({k: [round(x, 2) for x in v] for k, v in summary.items()})) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate_parts_cart_isolated.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate_parts_cart_isolated.py new file mode 100644 index 0000000000000000000000000000000000000000..2fc7b396510a3b831b746bdb17761fc8c32c5678 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate_parts_cart_isolated.py @@ -0,0 +1,54 @@ +"""Development physical validation; no model API, no pose injection after reset.""" +import argparse,copy,json,time,hashlib +from pathlib import Path +import numpy as np +from PIL import Image +from lffbench.tasks.lh_parts_cart import PartsCart +from lffbench import envs + +def main(): + p=argparse.ArgumentParser();p.add_argument('--seeds',nargs='+',type=int,default=[1000,1001,1002]);p.add_argument('--out',required=True);p.add_argument('--case',choices=['combined','oracle','l4','l2','l5'],default='combined');a=p.parse_args() + out=Path(a.out);out.mkdir(parents=True,exist_ok=True) + x=PartsCart(cam_res=512);rows=[] + def clean(obj): + if isinstance(obj,np.ndarray):return obj.tolist() + if isinstance(obj,np.generic):return obj.item() + raise TypeError(type(obj).__name__) + for seed in a.seeds: + i=x.sample_instance(seed) + if a.case in ['l4','l2','l5']:i['traps']={k:k==a.case.upper() for k in ['L4','L2','L5']} + x.reset_instance(i);r=dict(seed=seed,case=a.case,instance=i,checkpoints=[]);rows.append(r) + def snap(label): + o=copy.deepcopy(x.outcome(i));q=out/f's{seed}_{label}.png';Image.fromarray(x.snapshot(res=512)).save(q) + r['checkpoints'].append(dict(label=label,sim_step=x.sk.n_steps,commands=x.sk.robot_commands,outcome=o,image=str(q.resolve()))) + (out/'results.json').write_text(json.dumps(rows,indent=2,default=clean)) + print(seed,label,o['success'],o['traps'],o['stages'],flush=True) + snap('initial') + if a.case=='oracle': + x.execute(i,x.oracle_params(i));snap('oracle_final');continue + if a.case in ['combined','l4']: + x.tool_push_out();snap('L4_blocked') + x.tool_push_front();snap('L4_retrieved') + x.load(careful=a.case not in ['combined','l2']);snap('loaded') + if a.case in ['l4','l5']: + x.repair_load();snap('loading_prerequisite_repaired') + if a.case in ['combined','l2']: + x.repair_load();snap('L2_restored') + if all(x.cargo_ok(j) for j in range(2)): + if a.case in ['combined','l5']: + # First full naive push, then reuse correction loop without its initial push. + x.transport(0.,False);snap('L5_naive_push') + x._transport_only=True + # Feed a no-op execute only for the corrector's initial call; subsequent _push_at are unchanged. + original=x.execute + x.execute=lambda inst,params:None + try: + from lffbench.tasks.l7_offcenter_push import OffcenterPush + OffcenterPush.adaptive_attempt(x,i,0.) + finally:x.execute=original;x._transport_only=False + snap('L5_corrected') + else:x.transport(i['com_offset'] if i['traps']['L5'] else 0.,False) + x.repair_load();x.sk.set_gripper(False,steps=10);e=x.sk.eef_pos();x.sk.move_to([e[0],e[1],envs.TABLE_Z+.24]);snap('final') + x.env.close() + (out/'manifest.json').write_text(json.dumps(dict(case=a.case,seeds=a.seeds,task_sha256=hashlib.sha256(Path(__file__).parents[1].joinpath('lffbench/tasks/lh_parts_cart.py').read_bytes()).hexdigest(),note='scripted development validation, not model runs'),indent=2)) +if __name__=='__main__':main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/vla_eval.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/vla_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..ce71169d65f8452d4a38f8b45cfb9fc4b92de890 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/vla_eval.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +"""Evaluate a visuomotor policy on LFF-Bench (lffbench/vla.py). + + # one process per shard; the policy server runs elsewhere (openpi serve_policy.py, or StarVLA's) + python scripts/vla_eval.py run --policy ws://127.0.0.1:18000 --set sets/main_v2_3inst.txt --k 3 --out results/vla/ \ + --shard 0/8 --model-name pi05_lff_v1 + python scripts/vla_eval.py report results/vla/ + +Each session writes /_s/summary.json and events.jsonl; a session with a summary.json is skipped, so a +rerun resumes. --tasks takes task:seed[,seed] items, --set a file of them (the sets/ format). +""" +import argparse +import hashlib +import json +import os +import sys +import time +import traceback + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +CAUSES = os.path.join(ROOT, "..", "paper", "fig_scripts", "data", "causes.json") + + +def parse_items(items): + out = [] + for it in items: + name, _, seeds = it.strip().partition(":") + if not seeds: + raise SystemExit(f"{it!r}: expected task:seed[,seed]") + out += [(name, int(s)) for s in seeds.split(",")] + return out + + +def read_set(path): + return [line.strip() for line in open(path) if line.strip() and not line.startswith("#")] + + +def sha256(path): + with open(path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + +def causes(): + try: + return json.load(open(CAUSES))["cause"] + except OSError: + return {} + + +class Video: + """Frames at the replan rate, agentview next to wrist, written at real time speed.""" + + def __init__(self, path, replan): + import imageio + self.w = imageio.get_writer(path, fps=max(1, round(20 / replan)), quality=7, macro_block_size=8) + + def add(self, t, obs): + self.w.append_data(np.hstack([obs["observation/image"], obs["observation/wrist_image"]])) + + def close(self): + self.w.close() + + +def make_policy(spec): + from lffbench import vla + if spec == "zero": + return vla.ZeroPolicy() + if spec.startswith("ws://"): + return vla.WebsocketPolicy(spec) + raise SystemExit(f"unknown --policy {spec!r}: use ws://host:port or zero") + + +def run_one(task_name, seed, a, policy, tasks): + from lffbench import vla + from lffbench.harnesses.contract import server_code_sha + d = os.path.join(a.out, f"{task_name}_s{seed}") + if os.path.exists(os.path.join(d, "summary.json")): + return "skip" + os.makedirs(d, exist_ok=True) + task = tasks[task_name](cam_res=a.res) + inst = task.sample_instance(seed) + code_sha, code_files = server_code_sha(task_name) + start = dict(ev="session_start", task=task_name, seed=seed, protocol=getattr(task, "protocol", "cross"), + level=task.level, category=task.category, cause=causes().get(task_name), instruction=vla.task_prompt(task, inst), + k=a.k, replan=a.replan, res=a.res, frame=a.frame, idle_s=a.idle_s, probe_every_s=a.probe_every_s, + send_step=a.send_step, max_steps=a.max_steps or vla.budget_steps(task), model_name=a.model_name, policy=str(a.policy), + policy_metadata=getattr(policy, "metadata", None), inst={k: v for k, v in inst.items() if not k.startswith("_")}, + server_code_sha256=code_sha, server_code_files=code_files, + vla_sha256=sha256(os.path.join(ROOT, "lffbench", "vla.py")), time=time.time()) + with open(os.path.join(d, "events.jsonl"), "a") as log: + def write(rec): + log.write(json.dumps(rec, default=str) + "\n") + log.flush() + write(start) + video = Video(os.path.join(d, "rollout.mp4"), a.replan) if a.video else None + try: + t0 = time.time() + attempts = vla.run_session(task, inst, policy, k=a.k, max_steps=a.max_steps, replan=a.replan, res=a.res, + frame=a.frame, idle_s=a.idle_s, probe_every_s=a.probe_every_s, + send_step=a.send_step, on_frame=video.add if video else None, + on_attempt=lambda r: write(dict(ev="done", **r))) + finally: + if video: + video.close() + succ = [r["success"] for r in attempts] + first = next((r["attempt"] for r in attempts if r["success"]), None) + first_any = next((r["attempt"] for r in attempts if r["success"] or r["first_success_step"] is not None), None) + summary = {key: start[key] for key in ("task", "seed", "protocol", "level", "category", "cause", "k", "replan", "frame", + "max_steps", "model_name", "policy_metadata", "server_code_sha256")} + summary.update(status="ok", n_attempts=len(attempts), success_by_attempt=succ, first_success=first, + attempt1_success=bool(succ[0]), success=first is not None, first_success_any=first_any, + ended_by=[r["end"] for r in attempts], failure=[r["failure"] for r in attempts], + n_steps=[r["n_steps"] for r in attempts], infer_s_mean=[r["infer_s_mean"] for r in attempts], + wall_s=round(time.time() - t0, 2)) + tmp = os.path.join(d, "summary.json.tmp") + json.dump(summary, open(tmp, "w"), indent=1, default=str) + os.replace(tmp, os.path.join(d, "summary.json")) + return "ok" if first is not None else "fail" + + +def cmd_run(a): + from lffbench import tasks as task_pkg # noqa: F401 (registers the task modules) + import importlib + import pkgutil + from lffbench.task_base import TASKS + for m in pkgutil.iter_modules(task_pkg.__path__): + try: + importlib.import_module(f"lffbench.tasks.{m.name}") + except Exception as e: # a task module still being written elsewhere must not stop the evaluation of the others + print(f"[vla_eval] skipped task module {m.name}: {type(e).__name__}: {e}", flush=True) + items = list(a.tasks or []) + if a.set: + items += read_set(a.set) + sessions = parse_items(items) + i, n = (int(x) for x in a.shard.split("/")) + sessions = sessions[i::n] + os.makedirs(a.out, exist_ok=True) + policy = make_policy(a.policy) + print(f"[vla_eval] shard {a.shard}: {len(sessions)} sessions, policy {a.policy}, metadata {getattr(policy, 'metadata', None)}", flush=True) + for task_name, seed in sessions: + try: + print(f"[vla_eval] {task_name} s{seed}: {run_one(task_name, seed, a, policy, TASKS)}", flush=True) + except Exception: # one broken session must not end the shard; a missing summary.json makes a rerun retry it + print(f"[vla_eval] {task_name} s{seed}: ERROR\n{traceback.format_exc()}", flush=True) + + +def wilson(s, n, z=1.96): + if not n: + return [None, None] + p = s / n + d = 1 + z * z / n + c = p + z * z / (2 * n) + m = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) + return [round(float((c - m) / d), 4), round(float((c + m) / d), 4)] + + +def cmd_report(a): + rows = [] + for name in sorted(os.listdir(a.dir)): + p = os.path.join(a.dir, name, "summary.json") + if os.path.exists(p): + rows.append(json.load(open(p))) + if not rows: + raise SystemExit(f"no finished sessions in {a.dir}") + k = max(r["k"] for r in rows) + + def stats(group): + n = len(group) + 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)] + anyok = sum(1 for r in group if r["first_success_any"] is not None) + 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, + any_rate=round(anyok / n, 4)) + + by_cause, by_task = {}, {} + for r in rows: + by_cause.setdefault(str(r.get("cause")), []).append(r) + by_task.setdefault(r["task"], []).append(r) + non_l1 = [r for r in rows if r.get("cause") != "L1"] + report = dict(all=stats(rows), excluding_L1=stats(non_l1) if non_l1 else None, + by_cause={c: stats(g) for c, g in sorted(by_cause.items())}, + by_task={t: stats(g) for t, g in sorted(by_task.items())}, + ended_by={e: sum(r["ended_by"].count(e) for r in rows) for e in ("budget", "idle", "policy_ended")}, + 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), + model_names=sorted({str(r.get("model_name")) for r in rows}), + server_code_sha256=sorted({r["server_code_sha256"] for r in rows})) + json.dump(report, open(os.path.join(a.dir, "report.json"), "w"), indent=1) + print(f"{'':24s} {'n':>4s} {'A1':>6s} {f'A{k}':>6s} {'any':>6s}") + 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}") + for c, s in report["by_cause"].items(): + print(f"{c:24s} {s['n']:4d} {s['succ_at'][0]:6.2f} {s['succ_at'][-1]:6.2f} {s['any_rate']:6.2f}") + for t, s in report["by_task"].items(): + print(f"{t:24s} {s['n']:4d} {s['succ_at'][0]:6.2f} {s['succ_at'][-1]:6.2f} {s['any_rate']:6.2f}") + print("L1 tasks do not carry the agents' command-level offset for a direct-action policy; see lffbench/vla.py.") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("run") + r.add_argument("--policy", required=True, help="ws://host:port (openpi protocol) or zero") + r.add_argument("--tasks", nargs="*", help="task:seed[,seed] items") + r.add_argument("--set", help="file of task:seed[,seed] items, e.g. sets/main_v2_3inst.txt") + r.add_argument("--out", required=True) + r.add_argument("--k", type=int, default=3, help="attempts per session") + r.add_argument("--replan", type=int, default=5, help="actions executed from each chunk (openpi's LIBERO eval: 5)") + r.add_argument("--res", type=int, default=256, help="camera resolution (the dataset's: 256)") + r.add_argument("--frame", default="believed", choices=["believed", "true"], help="proprioception frame") + r.add_argument("--max-steps", type=int, default=None, help="control steps per attempt (default: the agents' budget)") + r.add_argument("--idle-s", type=float, default=5.0, help="end the attempt after this long without motion (0: off)") + r.add_argument("--probe-every-s", type=float, default=5.0, help="forked success check every this long (0: off)") + r.add_argument("--shard", default="0/1", help="i/n: run every n-th session starting at i") + r.add_argument("--model-name", default=None) + r.add_argument("--video", action="store_true") + r.add_argument("--send-step", action="store_true", + help='add "lff/attempt_step" to every observation (memory policies: history key + attempt boundary)') + r.set_defaults(fn=cmd_run) + p = sub.add_parser("report") + p.add_argument("dir") + p.set_defaults(fn=cmd_report) + a = ap.parse_args() + a.fn(a) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py new file mode 100644 index 0000000000000000000000000000000000000000..af2147531da26ff84843212279ffce9cda5e7916 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py @@ -0,0 +1,63 @@ +"""Controlled-arm spec for l2_turntable_restore (2026-10-12). + +Hidden variable: inst["q0"], the turntable's start angle (rad, + = counter-clockwise seen from above). It is the only +thing the agent has to remember: the main task forces a large turn of the disc (to bring the butter out from under the +shelf), after which nothing in the scene shows the start angle. apply_instance() places the disc at q0 and puts the +butter at disc-frame angle theta (so its world azimuth is theta + q0) on every reset, and reset_instance() records the +start angle from the simulator, so overriding "q0" alone is enough. + +Geometry used below (TurntableRestore.butter_to_basket): with the butter at world azimuth az (about the disc axis) +and box yaw az + tilt, the main task turns the disc by T = wrap(PICK_AZ - tilt - az), PICK_AZ = +90 deg (open side). +Its sign flips at az = flip = -90 deg - tilt (the middle of the covered side); |T| = 180 deg - |az - flip|. + +h0 -> q0 with the butter already at PICK_AZ (open side, long axis along world y): the main task needs no turn + (T ~ 0), so the scripted naive (main task, then stop) leaves the disc at its start angle and succeeds. + NB: the instruction's "under the shelf" is then not literally true (the butter is on the open half). +twin -> q0 with the butter still under the shelf but 35 deg on the OTHER side of flip: the main task turns the disc + the opposite way (|T| = 145 deg, inside the measured 136-179 deg range), so naive still fails visibly, and the + correction (turn back) has the opposite sign; the twin's start angle differs from the original's by + 35 deg + |az - flip| >= 35 deg (tolerance 15 deg), so restoring to the twin's remembered marks fails here. +reveal -> the start angle stated as the direction the yellow stripe points (seen from above), in robot-centric words + (forward = away from the robot, counter-clockwise as in the F2 feedback). +""" +import numpy as np + +HIDDEN_KEYS = ("q0",) + +TARGET = "butter_1" +PICK_AZ = np.pi / 2 # TurntableRestore.PICK_AZ +TWIN_OFF = np.radians(35.0) +STRIPE_ANG = np.pi # disc-frame angle of the yellow stripe (l2_turntable.STRIPE_ANG) + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def _geom(inst): + th, tilt = float(inst["theta"][TARGET]), float(inst["tilt"][TARGET]) + return th, tilt, -np.pi / 2 - tilt + + +def h0(inst): + th, tilt, _ = _geom(inst) + return {"q0": _wrap(PICK_AZ - tilt - th)} + + +def twin(inst): + th, tilt, flip = _geom(inst) + s = 1.0 if _wrap(th + float(inst["q0"]) - flip) >= 0 else -1.0 + return {"q0": _wrap(flip - s * TWIN_OFF - th)} + + +def _compass(deg): + names = ("forward", "forward-left", "left", "backward-left", "backward", "backward-right", "right", "forward-right") + return names[int(np.floor(((deg % 360) + 22.5) / 45.0)) % 8] + + +def reveal(inst): + az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG)) + side = "counter-clockwise" if az >= 0 else "clockwise" + return (f"Note: at the start, seen from above, the yellow stripe on the turntable points out from the turntable's " + f"centre {abs(az):.0f} deg {side} from straight forward (roughly {_compass(az)}); that is the angle the " + f"turntable is at now.") diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py new file mode 100644 index 0000000000000000000000000000000000000000..e4dd94b060df76880ed5f7f8c9a4a96b20e7b77e --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py @@ -0,0 +1,52 @@ +"""Controlled arms for l5_tablecloth_pull (docs/14 §6). + +Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset, +oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled +from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu. + +Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed +up to ~0.8 m/s (0.8 and 1.0 m/s give identical results: the controller saturates). The naive policy yanks at 0.6 m/s. +Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull +slower". + + h0 mu at which the 0.6 m/s yank lands the cube on the band's centre line (calibrated per full5 seed by a + simulated sweep; a linear fit in band_d for other seeds). + twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot + (err +1.5 .. +2.7 cm), so the lesson is "pull faster" (the twin's oracle pulls at 0.64-0.79 m/s; agents can + command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short. + The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the + twin's naive error is only ~1.5-2.7 cm (similar size to the original's short-fall) and the twin's oracle is + within 0.2-0.5 cm of the band tolerance on some seeds. Calibrated per seed; for other seeds 1.2 x the H0 mu. + reveal states the cube's friction coefficient (the only fact that differs between instances). +""" + +HIDDEN_KEYS = ("mu",) + +# Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim). +# seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm]) +_CAL = { + 3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60 + 3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47 + 3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78 + 3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44 + 3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51 +} + + +def _h0_mu(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"]) + + +def h0(inst): + return {"mu": float(_h0_mu(inst))} + + +def twin(inst): + c = _CAL.get(int(inst.get("seed", -1))) + return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))} + + +def reveal(inst): + return (f"The red cube's friction coefficient (against the board and against the table) is about " + f"{float(inst['mu']):.3f}.") diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py new file mode 100644 index 0000000000000000000000000000000000000000..a842f619205b88ccc9da3943f48f4f06bfb8e630 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py @@ -0,0 +1,18 @@ +"""Layer-4 intervention texts for lh_tidy_stack (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is +not in the controlled arms of full5. + +Hidden variable: inst["soft_colour"] -- the empty soft carton among the four boxes (None in benign instances). +reveal says which box is soft and how much it carries; not where to put it. +fix the oracle's order (lh_tidy_stack.oracle_params: rigid boxes first, the soft box last, then the cup). +""" +HIDDEN_KEYS = ("soft_colour",) + + +def reveal(inst): + return (f"The {inst['soft_colour']} box is an empty, soft carton. It carries one thing, but gives way as soon as a " + f"second thing rests above it, and everything above it slides off the pile.") + + +def fix(inst, params): + return (f"A way to succeed: stack the other three boxes first, put the {inst['soft_colour']} box on top of them last, " + f"and stand the cup on it. It then carries only the cup.") diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/gemini.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..1f4240f299561c36a664bf40ab8dceaf44715cf8 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/agent/backends/gemini.py @@ -0,0 +1,206 @@ +"""Google Gemini backend (Gemini API, official SDK `google-genai`). + +Same conversation as the other backends, converted to Gemini `contents`: +- system prompt = system_instruction; tools = function declarations with the harness's JSON schemas; +- every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive) + and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call; +- tool outputs of one turn become `function_response` parts at the start of the next user content; images the + harness attaches after them follow in the same user content; +- thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged; +- implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage). + +Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock. +""" +import base64 +import time + +from ..context import ToolCall, prune_live_images +from .base import Backend, BackendResponse, import_sdk + + +def _get(obj, key, default=None): + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + +def _strip_additional(schema): + """The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema.""" + if isinstance(schema, dict): + return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"} + if isinstance(schema, list): + return [_strip_additional(v) for v in schema] + return schema + + +def _image_part(image, quality=None): + head, data = image.data_url(quality).split(",", 1) + mime = head[len("data:"):].split(";", 1)[0] + return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data))) + + +class GeminiBackend(Backend): + name = "gemini" + + def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True, + max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90, + timeout=900.0, client=None): + self.model = model + self.thinking_level = thinking_level + self.thinking_budget = thinking_budget + self.include_thoughts = include_thoughts + self.max_output_tokens = max_output_tokens + self.media_resolution = media_resolution + self.max_live_images = max_live_images + self.jpeg_quality = jpeg_quality + self.timeout = timeout + self._client = client + self._json_schema_field = None + + def config(self): + return dict(name=self.name, model=self.model, thinking_level=self.thinking_level, + thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts, + max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution, + max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout) + + def client(self): + if self._client is None: + genai = import_sdk("google.genai") + self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000))) + return self._client + + def _declarations(self, specs): + if self._json_schema_field is None: + try: + types = import_sdk("google.genai.types") + self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields + except ImportError: # tests without the SDK + self._json_schema_field = True + out = [] + for s in specs: + d = dict(name=s["name"], description=s["description"]) + if self._json_schema_field: + d["parameters_json_schema"] = s["parameters"] + else: + d["parameters"] = _strip_additional(s["parameters"]) + out.append(d) + return [dict(function_declarations=out)] + + # ------------------------------------------------------------------ request + def convert_items(self, items): + contents = [] + + def push(role, parts): + if contents and contents[-1]["role"] == role: + contents[-1]["parts"].extend(parts) + else: + contents.append(dict(role=role, parts=list(parts))) + + for it in items: + kind = it["kind"] + if kind == "user": + parts = [] + for p in it["parts"]: + if p["type"] == "text": + parts.append(dict(text=p["text"])) + else: + parts.append(_image_part(p["image"], self.jpeg_quality)) + push("user", parts) + elif kind == "assistant": + if it.get("raw") is not None and it.get("backend") == self.name: + content = dict(it["raw"][0]) + contents.append(dict(role="model", parts=list(content.get("parts") or []))) + continue + parts = ([dict(text=it["text"])] if it.get("text") else []) + parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]] + push("model", parts or [dict(text="(no output)")]) + elif kind == "tool_output": + fr = dict(name=it["name"], response=dict(output=it["text"])) + if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"): + fr["id"] = it["call_id"] + push("user", [dict(function_response=fr)]) + else: + raise ValueError(kind) + return contents + + def build_request(self, conv, tools): + items = prune_live_images(conv.items, self.max_live_images) + thinking = dict(include_thoughts=self.include_thoughts) + if self.thinking_budget is not None: + thinking["thinking_budget"] = int(self.thinking_budget) + elif self.thinking_level: + thinking["thinking_level"] = self.thinking_level + config = dict(system_instruction=conv.system, tools=self._declarations(tools), + tool_config=dict(function_calling_config=dict(mode="AUTO")), + automatic_function_calling=dict(disable=True), thinking_config=thinking, + max_output_tokens=int(self.max_output_tokens)) + if self.media_resolution: + config["media_resolution"] = self.media_resolution + return dict(model=self.model, contents=self.convert_items(items), config=config) + + @staticmethod + def request_stats(req): + n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "") + for c in req["contents"]: + for p in c["parts"]: + p = p if isinstance(p, dict) else {} + if p.get("inline_data"): + n_img += 1 + img_bytes += len(p["inline_data"]["data"]) + elif p.get("text"): + txt += len(p["text"]) + elif p.get("function_response"): + txt += len(str(p["function_response"].get("response", ""))) + return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"])) + + # ------------------------------------------------------------------ call + def act(self, conv, tools): + req = self.build_request(conv, tools) + stats = self.request_stats(req) + types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys + t0 = time.time() + resp = self.client().models.generate_content( + model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]], + config=types.GenerateContentConfig.model_validate(req["config"])) + out = self.parse_response(resp) + out.latency_s = time.time() - t0 + out.request_stats = stats + return out + + def parse_response(self, resp): + cands = _get(resp, "candidates") or [] + cand = cands[0] if cands else None + content = _get(cand, "content") if cand is not None else None + parts = (_get(content, "parts") or []) if content is not None else [] + calls, texts, summ = [], [], [] + for i, p in enumerate(parts): + fc = _get(p, "function_call") + if fc is not None: + cid = _get(fc, "id") or f"gemini_call_{i}" + calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {}))) + elif _get(p, "text"): + (summ if _get(p, "thought") else texts).append(_get(p, "text")) + u = _get(resp, "usage_metadata") + usage = {} + if u is not None: + usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0, + cached_tokens=_get(u, "cached_content_token_count", 0) or 0, + output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0), + reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0) + finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE" + status, err = "completed", None + if not parts: + status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})" + elif "MAX_TOKENS" in finish or "MALFORMED" in finish: + status, err = "incomplete", f"incomplete: finish_reason={finish}" + elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish: + status, err = "refusal", f"refusal: finish_reason={finish}" + if content is not None and hasattr(content, "model_dump"): + raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes + elif content is not None: + raw = [dict(content)] + else: + raw = None + return BackendResponse(tool_calls=calls, text="\n".join(texts) or None, + reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw, + status=status, error=err) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_bridge.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..b10b75576304ed46284ba5002c7857fc458d3669 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/tasks/lh_bridge.py @@ -0,0 +1,1101 @@ +"""LH lh_bridge (v2, 2026-10-09): build a small bridge (two pillars, a plank, then the red cube "car" on top); the car is +parked right behind the bridge site, and once the plank is down the agent's natural reach for it knocks the bridge down, +which must be rebuilt before the task can be finished. + +Category: state_restoration, long-horizon self-inflicted regression. The user's example verbatim: "build a bridge; +while working you knock over a foundation you already built and must rebuild it before continuing". + +v1 -> v2 (after the Sonnet 5.5 pilot lh1: only 1 of 3 instances was ever disturbed; Sonnet carried 12-20 cm high and +lifted over built pillars, so the v1 mechanism -- sweeping a pillar with a block carried low -- rarely happened; the one +disturbance was the hand landing on the plank while going for the red cube): the car now starts in the gap between the +two squares, 5.5-9 cm behind the bridge line (right behind where the plank will lie); a spare fifth block; the bridge +4-7 cm further from the robot and the plank nearer, so that knocked parts stay within reach; softer contacts for the +bridge parts (the stiff default made collapsing blocks fly 30-90 cm); the naive reference imitates Sonnet's measured +motion style instead of the v1 low-transit script (kept as naive_v1). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): two coloured square +marks (blue and green, 6 x 6 cm, visual only) 16 cm apart along y, 48-51 cm in front of the robot base; the red cube +(4 cm) in the gap between them, 5.5-9 cm behind the line through the squares (+-3 cm sideways, yaw +-20 deg); five +wooden cubes (edge 5.0-5.6 cm, friction 0.3-0.6, five distinct categories) in a row 9-11 cm behind the squares, two on +one side of the car and three on the other; the plank (24 x 5 x 1.2 cm) lying left-right 19-21 cm behind the squares. + +Stages (order-free predicates, evaluated after every control step by a monitor; events are debounced over 6 steps): + S1 two blocks stacked on the blue square (lower block resting on the table within 2.5 cm of the square's centre, + upper block resting on it within 2.5 cm; any face down, cubes have no "right way up") + S2 the same on the green square + S3 the plank rests on the top blocks of both pillars: in contact with both, not with the table, tilt <= 10 deg + S4 the red cube rests on the plank within 6 cm of the plank's centre along its length +Success = all four hold at the end simultaneously, the scene is static (< 4 mm motion in 1 s) and the robot neither +holds nor touches any object. The monitor's achieved / lost / restored events go to the server log only (F1). + +Why the agent breaks the bridge (measured, see task_cards/lh_bridge.md): with the plank down, the car sits 3-6.5 cm +behind the plank's back edge, between the pillars. The Panda hand is 21 cm long along the finger axis and its underside +is only 2.4 cm above the grasp point; the fingertips hang 1.3 cm below it. Each of the three pilot runs went for the car +differently; scripted here on seeds 1000-1019: hovering ~13 cm above it while turning the wrist from the plank's 90 deg +to the car's yaw, then straight down (5/20 knock the bridge), keeping the 90 deg wrist and going straight down (the hand +lands across the plank: 20/20), or one diagonal move from above the bridge straight down to the grasp (the hand drives +through the bridge: 20/20). The plank and one or both pillar tops fall; in 22 of 24 collapses (seeds 3000-3029) every +part needed stays within reach (a block out of reach is covered by the spare; the plank was thrown out of reach twice). +What prevents it (learnable from one failure, and what Sonnet wrote after its pilot failure): move the car away before +laying the plank. + +Hidden variables: none that matter. Block size and friction are instance variety; the car's distance (5.5-9 cm) and yaw +decide only the "hover" style's outcome. + +Scripted references (perception = simulator state): + naive Sonnet-like (measured on the pilot): instruction order; per pillar the free block nearest its square first; + hover ~12 cm above an object turned to its yaw, vertical descent, grasp 1.1 cm below the top; carry to a bare + square in one diagonal move to 12.5 cm above it, onto a block lift first; lift over a built pillar when the + carried block's straight path would hit it; release, lift to 15 cm; plank lifted to 7 cm, carried at 16 cm, + lift to 21 cm; the car approach style is the pilot's mixture (seed % 3: hover / keep / direct); no final check + naive_v1 the v1 naive (vertical / horizontal legs at 8 cm, carries at max(8 cm, release + 4 cm)), for comparison + oracle careful: first moves the car out of the zone behind the bridge; all transits at 25 cm, vertical approaches + at 0.1 m/s, grasps 1.6 cm below a cube's top, gripper yaw chosen for hand / finger clearance; checks every + stage at the end and repairs what is broken (same repair as adaptive) + adaptive attempt 1 = naive, then checks every stage before finishing and restores what was lost (tips a plank that + stands on edge, puts the plank and car aside, re-stacks the pillars from usable blocks, then plank and car + again); from attempt 2 the careful behaviour + blind naive with random variation (hover / carry / lift heights, diagonal or lift-first carries, car style, + block allocation, 4 mm placement noise), no history + +Protocol: cross (reset to the same instance before every attempt), k = 3. +""" +import os + +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +BLOCKS = ["block_a_1", "block_b_1", "block_c_1", "block_d_1", "block_e_1"] # four are needed, one is a spare +PLANK, CAR = "plank_1", "car_1" +SQUARES = ["square_blue_1", "square_green_1"] # S1 = blue, S2 = green +ITEMS = BLOCKS + [PLANK, CAR] +BLOCK_RGBA = [(0.80, 0.66, 0.46, 1.0), (0.70, 0.55, 0.37, 1.0), (0.84, 0.72, 0.56, 1.0), (0.64, 0.50, 0.36, 1.0), + (0.76, 0.60, 0.42, 1.0)] # wood +PLANK_HALF = (0.12, 0.025, 0.006) # 24 x 5 x 1.2 cm, long axis = body x +CAR_HALF = 0.02 +BLOCK_NOM = 0.026 # nominal half edge in the MJCF (resized per instance) +SQ_HALF = 0.03 +SQ_RGBA = {"square_blue_1": (0.12, 0.30, 0.90, 1.0), "square_green_1": (0.10, 0.70, 0.25, 1.0)} +SQ_NAME = {"square_blue_1": "blue", "square_green_1": "green"} +SPAN = 0.16 # square centre distance (along y) + +TZ = envs.TABLE_Z +BASE_X = -0.66 +HAND_HALF_LONG = 0.106 # Panda hand collision AABB about the grasp site: +-10.6 cm along the finger axis +HAND_HALF_SHORT = 0.036 # +-3.6 cm across it +HAND_BOTTOM = 0.024 # its underside is 2.4 cm above the grasp site (measured) + +SQ_TOL = 0.025 # lower block centre within 2.5 cm of the square centre +STACK_TOL = 0.025 # upper block centre within 2.5 cm of the lower one +FLAT_COS = np.cos(np.radians(12)) +PLANK_TILT = np.radians(10) +CAR_MID = 0.06 +DEBOUNCE = 6 # control steps a predicate must keep its new value before an event is recorded + +# v2 layout (2026-10-09): the red cube ("car") is parked in the gap between the two squares, just behind the bridge +# line, so that once the plank is down a natural top-down grasp of it lands the hand on the plank / pillar tops; the +# four wooden blocks lie in a row behind the bridge, two on each side of the car; the plank lies further back. +LAYOUT = dict(bridge_x=(-0.18, -0.15), row_dx=(0.09, 0.11), y_half=0.30, gap=0.095, car_dx=(0.055, 0.09), car_dy=0.03, + car_clear=0.08, car_yaw=0.35, plank_dx=(0.19, 0.21), block_edge=(0.050, 0.056)) +KEEP_OUT = dict(dx=0.13, dy=0.20) # careful: no parking / no material left within this zone behind the bridge line +# Sonnet-like naive (measured on the lh1 pilot, see task_cards/lh_bridge.md): heights of the grasp site above the table +SN = dict(hover=0.12, carry=0.125, lift=0.15, cross_margin=0.04, plank_lift=0.07, plank_carry=0.16, car_lift=0.17, + end_lift=0.25, top_below=0.011, diag=True, car_style=None, car_hover=0.134, plank_end_lift=0.21, + alloc="greedy") +# how the gripper went for the red cube once the plank was down -- each of the three pilot runs did it differently: +# hover (seed 3002) move to ~13.4 cm above it while turning to its yaw, then straight down +# keep (seed 3000) the same, but still turned 90 deg from laying the plank +# direct (seed 3001) one move from ~21 cm above the bridge straight (diagonally) down to the grasp +# the naive script uses style CAR_STYLES[seed % 3] (car_style=None), i.e. the pilot's mixture +CAR_STYLES = ("hover", "keep", "direct") +Z_NAIVE = 0.08 # naive_v1 transit height of the grasp site above the table +Z_SAFE = 0.25 # careful transit height +NAIVE_LIFT = 0.05 # naive: lift this far straight up after letting go, then head for the next waypoint +NAIVE_STYLE = "legs" # legs: vertical / horizontal legs at the transit height; diag: straight lines between waypoints + + +def _wrap_q(a): + """wrap to [-pi/4, pi/4) (cubes are symmetric under 90 deg)""" + return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (plank / gripper symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +# Contact softness of the bridge parts. LFF-Bench's generated boxes use a very stiff contact (objects._SOLID); when a +# fast hand drives into a stacked bridge, the stiff contacts resolve the overlap with large impulses and blocks fly +# 30-90 cm (measured: up to 1.7 m/s while the hand moved at 0.5-0.8 m/s), often out of reach or off the table. A +# softer contact (MuJoCo-like defaults) keeps collapses local. None = use the stiff default. +CONTACT = os.environ.get("LFF_LHB_CONTACT", 'solimp="0.95 0.99 0.001" solref="0.01 1"') + + +def part_xml(model_name, half, rgba, density): + """box like objects.box_xml, with the task's contact softness""" + if not CONTACT or CONTACT == "stiff": + return box_xml(model_name, half, rgba, density=density) + g = (f' \n' + f' ') + return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def mark_xml(name, rgba): + """flat coloured square, visual only (does not touch the physics)""" + g = (f' ') + return _wrap(name, g, 0.0006, SQ_HALF * 1.42) + + +class BridgeSkills(Skills): + """Skills that feed the task's per-step stage monitor.""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.task.monitor_step() + + +@register_task +class Bridge(LFFTask): + name = "lh_bridge" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 130 + instruction = ("Build a small bridge. First stack two of the wooden blocks on the blue square, then two on the green " + "square, to make two pillars; then lay the long plank across the tops of both pillars; finally put " + "the red cube on the middle of the plank. The finished bridge must stand on its own, with the " + "gripper open and not touching anything.") + instruction_indirect = ("Build a small bridge. First make a tower of two of the wooden cubes on the blue mark on the " + "table, then another tower of two on the green mark; then lay the long flat board across the " + "tops of the two towers; finally set the small red cube on the middle of the board. At the " + "end everything must stand on its own, with the gripper open and not touching anything.") + agent_object_names = ["wooden blocks (5)", "plank", "red cube", "blue square", "green square"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, b in enumerate(BLOCKS): + cat = register_generated(f"LffLhbBlock{'ABCDE'[i]}", part_xml(f"lff_lhb_block_{'abcde'[i]}", (BLOCK_NOM,) * 3, + BLOCK_RGBA[i], 500.0)) + reg = (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31) if i < 4 else (0.10, -0.25, 0.11, -0.24) + objs.append((b, cat, f"blk{i}_region", reg)) + pl = register_generated("LffLhbPlank", part_xml("lff_lhb_plank", PLANK_HALF, (0.50, 0.33, 0.18, 1.0), + density=600.0)) + objs.append((PLANK, pl, "plank_region", (0.05, -0.01, 0.06, 0.01))) + car = register_generated("LffLhbCar", part_xml("lff_lhb_car", (CAR_HALF,) * 3, (0.85, 0.10, 0.08, 1.0), + density=400.0)) + objs.append((CAR, car, "car_region", (-0.30, -0.31, -0.29, -0.30))) + fx = [] + for i, s in enumerate(SQUARES): + cat = register_generated(f"LffLhbSquare{'BG'[i]}", mark_xml(f"lff_lhb_square_{'bg'[i]}", SQ_RGBA[s]), + free=False) + fx.append((s, cat, f"sq{i}_region", (-0.10 + 0.10 * i, -0.31, -0.09 + 0.10 * i, -0.30))) + return write_bddl(self.name, "Build a small bridge from the blocks the plank and the red cube", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.sq_bid = {s: m.body_name2id(self.env.fixtures_dict[s].root_body) for s in SQUARES} + self.geoms = {o: envs.obj_geom_ids(self.env, o) for o in ITEMS} + self.vis_geoms = {} + for o in BLOCKS: + root = envs.body_id(self.env, o) + bodies = {b for b in range(m.nbody) if b == root or m.body_parentid[b] == root} + self.vis_geoms[o] = [g for g in range(m.ngeom) if m.geom_bodyid[g] in bodies and m.geom_contype[g] == 0 + and m.geom_conaffinity[g] == 0 and m.geom_type[g] == 6] + self.block_body = getattr(self, "block_body", {}) + self.block_body[o] = int(m.geom_bodyid[self.geoms[o][0]]) + self.table_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("main_table") + and m.geom_contype[g] != 0] + self.robot_geoms = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + self.sk = None + self.naive_lift = NAIVE_LIFT + self.naive_style = NAIVE_STYLE + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + xb = float(rng.uniform(*LAYOUT["bridge_x"])) + yc = float(rng.uniform(-0.03, 0.03)) + blue_left = bool(rng.random() < 0.5) + sq = {"square_blue_1": [xb, yc + (SPAN / 2 if blue_left else -SPAN / 2)], + "square_green_1": [xb, yc - (SPAN / 2 if blue_left else -SPAN / 2)]} + L = LAYOUT + # the car: in the gap between the two squares, just behind the bridge line + pos = {CAR: [xb + float(rng.uniform(*L["car_dx"])), yc + float(rng.uniform(-L["car_dy"], L["car_dy"]))]} + # five blocks in a row behind the bridge line, two on one side of the car and three on the other + row_x = xb + float(rng.uniform(*L["row_dx"])) + ys = [] + three = 1.0 if rng.random() < 0.5 else -1.0 + for side in (-1.0, 1.0): + n = 3 if side == three else 2 + lo, hi = sorted((pos[CAR][1] + side * L["car_clear"], side * L["y_half"])) + u = np.sort(rng.uniform(0.0, max((hi - lo) - (n - 1) * L["gap"], 0.0), n)) + ys += [lo + k * L["gap"] + u[k] for k in range(n)] + order = rng.permutation(5) + for k, j in enumerate(order): + pos[BLOCKS[j]] = [row_x + float(rng.uniform(-0.01, 0.01)), float(ys[k])] + plank_xy = [xb + float(rng.uniform(*L["plank_dx"])), yc + float(rng.uniform(-0.04, 0.04))] + size = {b: float(rng.uniform(*L["block_edge"])) for b in BLOCKS} + mu = {b: float(rng.uniform(0.3, 0.6)) for b in BLOCKS} + yaw = {o: float(rng.uniform(-0.35, 0.35)) for o in BLOCKS} + yaw[CAR] = float(rng.uniform(-L["car_yaw"], L["car_yaw"])) + yaw[PLANK] = float(np.pi / 2 + rng.uniform(-0.25, 0.25)) # long axis roughly left-right + pos[PLANK] = plank_xy + return dict(seed=int(seed), squares=sq, blue_side="left" if blue_left else "right", pos=pos, yaw=yaw, + size=size, mu=mu, bridge_x=xb, bridge_yc=yc) + + def _resize_block(self, o, edge): + m = self.env.sim.model + h = edge / 2.0 + for g in self.geoms[o] + self.vis_geoms[o]: + m.geom_size[g] = [h, h, h] + m.geom_rbound[g] = float(np.sqrt(3) * h) + m.geom_aabb[g] = [0.0, 0.0, 0.0, h, h, h] + b = self.block_body[o] + mass = 500.0 * edge ** 3 + m.body_mass[b] = mass + m.body_inertia[b] = [mass * edge ** 2 / 6.0] * 3 + envs.refit_bounds(self.env, b) # BVH of the resized block (envs.refit_bounds) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for s in SQUARES: + x, y = inst["squares"][s] + m.body_pos[self.sq_bid[s]] = [x, y, TZ + 0.0007] + m.body_quat[self.sq_bid[s]] = [1.0, 0.0, 0.0, 0.0] + for o in BLOCKS: + self._resize_block(o, inst["size"][o]) + envs.set_friction(self.env, o, inst["mu"][o]) + envs.set_friction(self.env, PLANK, 0.5) + envs.set_friction(self.env, CAR, 0.6) + self.env.sim.forward() + for o in ITEMS: + envs.place_upright(self.env, o, inst["pos"][o], inst["yaw"][o], clearance=0.001) + + def reset_instance(self, inst, recorder=None): + self.mon = None + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 15) + self.sk = BridgeSkills(self.env, self, recorder=recorder) + self.mon = dict(state=[False] * 4, raw_since=[0] * 4, ever=[False] * 4, lost=[False] * 4, events=[]) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def half(self, o): + if o in BLOCKS: + e = self.inst["size"][o] / 2 + return np.array([e, e, e]) + return np.array(PLANK_HALF) if o == PLANK else np.array([CAR_HALF] * 3) + + def R(self, o): + return self.env.sim.data.body_xmat[envs.body_id(self.env, o)].reshape(3, 3).copy() + + def pos(self, o): + return envs.obj_pos(self.env, o) + + def zmin(self, o): + return envs.obj_min_z(self.env, o) + + def zmax(self, o): + return envs.obj_max_z(self.env, o) + + def flat(self, o): + return float(np.max(np.abs(self.R(o)[2]))) > FLAT_COS + + def yaw_of(self, o): + """yaw of the object's body x axis (for the plank: its long axis)""" + R = self.R(o) + return float(np.arctan2(R[1, 0], R[0, 0])) + + def held(self, o): + return self.sk is not None and self.sk.holding(o) + + def contacts(self, a_geoms, b_geoms): + return envs.contacts_between(self.env, a_geoms, b_geoms) + + def pillar(self, s): + """(lower, upper) blocks of a complete pillar on square s, else (lower or None, None)""" + c = np.asarray(self.inst["squares"][s]) + lower = None + for b in BLOCKS: + p = self.pos(b) + if np.linalg.norm(p[:2] - c) <= SQ_TOL and self.zmin(b) < TZ + 0.006 and self.flat(b) and not self.held(b): + lower = b + break + if lower is None: + return None, None + pl = self.pos(lower) + top = self.zmax(lower) + for b in BLOCKS: + if b == lower: + continue + p = self.pos(b) + if (np.linalg.norm(p[:2] - pl[:2]) <= STACK_TOL and abs(self.zmin(b) - top) < 0.006 and self.flat(b) + and not self.held(b)): + return lower, b + return lower, None + + def plank_ok(self, tops): + if any(t is None for t in tops) or self.held(PLANK): + return False + R = self.R(PLANK) + if abs(R[2, 0]) > np.sin(PLANK_TILT) or abs(R[2, 2]) < np.cos(PLANK_TILT): # either broad face up (v2 fix) + return False + if self.zmin(PLANK) < TZ + 0.03 or self.contacts(self.geoms[PLANK], self.table_geoms): + return False + return all(self.contacts(self.geoms[PLANK], self.geoms[t]) for t in tops) + + def car_ok(self): + """the car rests on the plank's upper face (in the plank's own frame, so a slightly tilted plank is fine), + within CAR_MID of the plank's centre along its length""" + if self.held(CAR) or not self.contacts(self.geoms[CAR], self.geoms[PLANK]): + return False + R = self.R(PLANK) + rel = R.T @ (self.pos(CAR) - self.pos(PLANK)) + up = rel[2] * (1.0 if R[2, 2] >= 0 else -1.0) # along the broad face pointing up (a plank may lie upside down) + return bool(abs(rel[0]) <= CAR_MID and abs(rel[1]) <= PLANK_HALF[1] + 0.01 and up > PLANK_HALF[2] + 0.01) + + def stages(self): + """raw predicate values [S1, S2, S3, S4] and the pillars found""" + pa = self.pillar(SQUARES[0]) + pb = self.pillar(SQUARES[1]) + s1, s2 = pa[1] is not None, pb[1] is not None + s3 = bool(s1 and s2 and self.plank_ok([pa[1], pb[1]])) + s4 = bool(self.car_ok()) + return [s1, s2, s3, s4], (pa, pb) + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + raw, _ = self.stages() + t = self.sk.n_steps + for i in range(4): + if raw[i] == mon["state"][i]: + mon["raw_since"][i] = 0 + continue + mon["raw_since"][i] += 1 + if mon["raw_since"][i] < DEBOUNCE: + continue + mon["state"][i] = raw[i] + mon["raw_since"][i] = 0 + t0 = t - DEBOUNCE + 1 + if raw[i]: + ev = "restored" if mon["lost"][i] else "achieved" + mon["ever"][i] = True + else: + ev = "lost" + mon["lost"][i] = True + mon["events"].append(dict(stage=f"S{i + 1}", event=ev, step=int(t0))) + + # ------------------------------------------------------------ outcome + def _dir_words(self, d): + """robot-centric words for a horizontal offset d (world x = forward, away from the robot; y = robot's left)""" + parts = [] + if abs(d[0]) >= 0.01: + parts.append(f"{100 * abs(d[0]):.0f} cm {'forward' if d[0] > 0 else 'back'}") + if abs(d[1]) >= 0.01: + parts.append(f"{100 * abs(d[1]):.0f} cm {'left' if d[1] > 0 else 'right'}") + return (" and ".join(parts) + " of") if parts else "right at" + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {o: self.pos(o) for o in ITEMS} + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or any(self.contacts(list(self.robot_geoms), self.geoms[o]) for o in ITEMS) + moved = max(float(np.linalg.norm(self.pos(o) - p0[o])) for o in ITEMS) + static = moved < 0.004 + raw, (pa, pb) = self.stages() + held = [o for o in ITEMS if sk.holding(o)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + n_reg = sum(e["event"] == "lost" for e in ev) + n_res = sum(e["event"] == "restored" for e in ev) + success = bool(all(raw) and static and not held and not touching) + parts = [] + if success: + failure = "none" + parts.append("The bridge is complete: both pillars stand on their squares, the plank rests across them " + "and the red cube sits on the middle of the plank.") + else: + lost_final = [i for i in range(4) if not raw[i] and mon and mon["ever"][i]] + never = [i for i in range(4) if not raw[i] and not (mon and mon["ever"][i])] + if held: + failure = "held" + elif touching: + failure = "touching" + elif lost_final: + failure = "regressed_" + "".join(f"S{i + 1}" for i in lost_final) + elif never: + failure = "incomplete_" + "".join(f"S{i + 1}" for i in never) + else: + failure = "not_static" + for i, s in enumerate(SQUARES): + if raw[i]: + continue + low, _ = (pa, pb)[i] + c = np.asarray(inst["squares"][s]) + txt = f"The pillar on the {SQ_NAME[s]} square is not standing:" + if low is None: + txt += " no block stands on the square." + else: + txt += " only one block stands on the square." + strays = [b for b in BLOCKS if b not in (pa[0], pa[1], pb[0], pb[1])] + if strays: + near = min(strays, key=lambda b: np.linalg.norm(self.pos(b)[:2] - c)) + txt += f" The nearest loose block lies {self._dir_words(self.pos(near)[:2] - c)} the square." + if mon and mon["ever"][i]: + txt += " It had been built and was knocked down later." + parts.append(txt) + if not raw[2]: + pp = self.pos(PLANK) + if self.contacts(self.geoms[PLANK], self.table_geoms): + where = "touches the table" + elif self.held(PLANK): + where = "is still in the gripper" + else: + where = "does not rest level on the tops of both pillars" + bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0) + parts.append(f"The plank {where}; its centre is {self._dir_words(pp[:2] - bc)} the middle between " + f"the squares." + (" It had been laid and was disturbed later." if mon and mon["ever"][2] + and not raw[2] else "")) + if not raw[3]: + if self.held(CAR): + parts.append("The red cube is still in the gripper.") + elif self.contacts(self.geoms[CAR], self.geoms[PLANK]): + parts.append("The red cube is on the plank but not on its middle part.") + else: + bc = np.mean([inst["squares"][s] for s in SQUARES], axis=0) + parts.append(f"The red cube is not on the plank; it lies {self._dir_words(self.pos(CAR)[:2] - bc)} " + "the middle between the squares.") + if all(raw) and held: + parts.append("The gripper still holds an object.") + elif touching: + parts.append("The gripper is still touching the bridge.") + elif all(raw) and not static: + parts.append("The bridge was still moving.") + if n_reg: + parts.append(f"During the attempt earlier stages were undone {n_reg} time(s) and restored {n_res} time(s).") + if any(w in " ".join(parts) for w in (" forward of", " back of", " back and", " forward and")): + parts.append("(Forward = away from the robot.)") + return dict(success=success, stages={f"S{i + 1}": bool(raw[i]) for i in range(4)}, events=ev, + n_regressions=int(n_reg), n_restored=int(n_res), failure=failure, held=held, + touching=bool(touching), static=bool(static), detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _grip_yaws(self, o): + """candidate gripper yaws for a top-down grasp of o (fingers across a face)""" + if o == PLANK: # fingers (which open along the gripper's y at yaw 0) across the plank's width + return [_wrap_h(self.yaw_of(PLANK))] + a = _wrap_q(self.yaw_of(o)) + return [a, _wrap_h(a + np.pi / 2)] + + def footprint(self, o): + """sample points on the horizontal footprint of o (corners, edge midpoints, centre)""" + R, c, h = self.R(o), self.pos(o), self.half(o) + pts = [] + for sx in (-1, 0, 1): + for sy in (-1, 0, 1): + for sz in ((-1, 1) if o != PLANK else (0,)): + pts.append((c + R @ (h * [sx, sy, sz]))[:2]) + if o == PLANK: + for t_ in np.linspace(-1, 1, 9): + for sy in (-1, 1): + pts.append((c + R @ (h * [t_, sy, 0]))[:2]) + return np.array(pts) + + def _hand_clearance(self, xy, yaw, z_site, ignore=()): + """smallest horizontal clearance (m) between the gripper at a grasp-site height z_site and everything else: + the hand body (+-10.6 x +-3.6 cm, underside 2.4 cm above the site) against items taller than its underside, + the open fingers (two 2 x 2.4 cm boxes 3-5 cm out along the finger axis, tips 1.3 cm below the site) + against items taller than the fingertips. Negative = the gripper would land on something.""" + f = np.array([-np.sin(yaw), np.cos(yaw)]) # finger axis + g = np.array([np.cos(yaw), np.sin(yaw)]) + best = 1.0 + for o in ITEMS: + if o in ignore or self.held(o): + continue + top = self.zmax(o) + if top < z_site - 0.013: + continue + d = self.footprint(o) - np.asarray(xy) + u, v = np.abs(d @ f), np.abs(d @ g) + c = float(np.min(np.maximum(np.abs(u - 0.040) - 0.010, v - 0.012))) # fingers + if top >= z_site + HAND_BOTTOM - 0.002: + c = min(c, float(np.min(np.maximum(u - HAND_HALF_LONG, v - HAND_HALF_SHORT)))) + best = min(best, c) + return best + + @staticmethod + def _pick_yaw(yaws, clearance): + """the gripper yaw closest to straight (0) among those with >= 1 cm clearance, else the clearest one (large + wrist turns near the edge of the workspace make the OSC stop short)""" + c = {a: clearance(a) for a in yaws} + ok = [a for a in yaws if c[a] >= 0.01] + return min(ok, key=abs) if ok else max(yaws, key=c.get) + + def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=250): + return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps) + + def _grasp_z(self, o, careful): + if o in BLOCKS: + return self.zmax(o) - (0.016 if careful else self.inst["size"][o] / 2) + if o == PLANK: + return max(self.zmax(PLANK) + 0.0003 - 0.0125, TZ + 0.011) + return self.zmax(CAR) - (0.016 if careful else CAR_HALF) + + def pick(self, o, careful, noise=None, z_t=None): + """top-down grasp; returns the drop of the object's bottom below the grasp site, or None if not held""" + sk = self.sk + p = self.pos(o) + if noise is not None: + p = p + np.array([noise[0], noise[1], 0.0]) + zg = self._grasp_z(o, careful) + yaws = self._grip_yaws(o) + if careful: + yaw = self._pick_yaw(yaws, lambda a: self._hand_clearance(p[:2], a, zg, ignore=(o,))) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([p[0], p[1], TZ + Z_SAFE], yaw=yaw) + sk.set_gripper(False, steps=8) + self._go([p[0], p[1], zg + 0.03], speed=0.25) + self._go([p[0], p[1], zg], speed=0.1, tol=0.003, max_steps=120) + else: + yaw = min(yaws, key=lambda a: abs(a)) + zt = TZ + (Z_NAIVE if z_t is None else z_t) + sk.set_gripper(False, steps=8) + if self.naive_style == "legs": # rise to the transit height if below it, across, straight down + cur = sk.eef_pos() + if cur[2] < zt - 0.003: + self._go([cur[0], cur[1], zt]) + self._go([p[0], p[1], max(cur[2], zt)], yaw=yaw) + else: # one straight line to the approach point above the object + self._go([p[0], p[1], max(zt, self.zmax(o) + 0.03)], yaw=yaw) + self._go([p[0], p[1], zg], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + drop = float(sk.eef_pos()[2] - self.zmin(o)) + if careful: + self._go([p[0], p[1], TZ + Z_SAFE], speed=0.3) + else: + zt = TZ + (Z_NAIVE if z_t is None else z_t) + self._go([p[0], p[1], max(zt, zg + 0.05)]) + if not sk.holding(o): + sk.set_gripper(False, steps=8) + return None + return drop + + def place(self, o, xy, support_top, drop, yaw, careful, z_t=None, release_gap=0.005, lift=None): + sk = self.sk + zr = support_top + drop + release_gap + if careful and o != PLANK: # cubes are symmetric under 90 deg: release with the fingers where there is room + yaw = self._pick_yaw([yaw, _wrap_h(yaw + np.pi / 2)], lambda a: self._hand_clearance(xy, a, zr, ignore=(o,))) + if careful: + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([xy[0], xy[1], TZ + Z_SAFE], yaw=yaw) + self._go([xy[0], xy[1], zr + 0.03], speed=0.25) + self._go([xy[0], xy[1], zr], speed=0.08, tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + 0.03], speed=0.1) + self._go([xy[0], xy[1], TZ + Z_SAFE], speed=0.3) + else: + if self.naive_style == "legs": + zt = TZ + (Z_NAIVE if z_t is None else z_t) + cur = sk.eef_pos() + h = max(cur[2], zt, zr + 0.04) + if cur[2] < h - 0.003: + self._go([cur[0], cur[1], h]) + self._go([xy[0], xy[1], h], yaw=yaw) + else: + self._go([xy[0], xy[1], zr + 0.04], yaw=yaw) + self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + self._go([xy[0], xy[1], zr + (self.naive_lift if lift is None else lift)]) + sk.hold(5) + + # placing targets --------------------------------------------------------- + def square_xy(self, s): + return np.asarray(self.inst["squares"][s], float) + + def bridge_mid(self): + return np.mean([self.square_xy(s) for s in SQUARES], axis=0) + + def free_blocks(self): + _, (pa, pb) = self.stages() + used = set() + for low, up in (pa, pb): + if up is not None: + used |= {low, up} + return [b for b in BLOCKS if b not in used] + + def _blocker(self, b): + """for a careful top-down grasp of block b: None if the gripper fits at some grasp yaw, else the item in the + way (e.g. the top block of a pillar, or a block, right next to b)""" + zg = self._grasp_z(b, True) + p = self.pos(b)[:2] + if max(self._hand_clearance(p, a, zg, ignore=(b,)) for a in self._grip_yaws(b)) > -0.002: + return None + worst = {} + for o in ITEMS: + if o == b or self.held(o): + continue + worst[o] = max(self._hand_clearance(p, a, zg, ignore=tuple(q for q in ITEMS if q != o)) + for a in self._grip_yaws(b)) + o = min(worst, key=worst.get) + return o if worst[o] <= -0.002 else None + + def build_pillar(self, s, careful, noise_fn, z_t=None, order="target"): + """put blocks on square s until it carries a complete pillar (at most 5 placements)""" + failed = {} + for _ in range(6): + raw, (pa, pb) = self.stages() + low, up = (pa, pb)[SQUARES.index(s)] + if up is not None: + return True + if careful and self.over_budget(): + return False + c = self.square_xy(s) + other = (pa, pb)[1 - SQUARES.index(s)] + cand = [b for b in BLOCKS if b != low and b not in other and (not careful or (self.usable(b) + and failed.get(b, 0) < 2))] + if not cand: + return False + ref = self.sk.eef_pos()[:2] if order == "gripper" else c + cand.sort(key=lambda b: (failed.get(b, 0), np.linalg.norm(self.pos(b)[:2] - ref))) + b = cand[0] + if careful: + free = [q for q in cand if self._blocker(q) is None] + if free: + b = free[0] + else: # every usable block sits right next to something tall: take that thing's top off first + blk = self._blocker(cand[0]) + if blk is not None and blk != PLANK and failed.get(blk, 0) < 2: + if not self.park(blk): + failed[blk] = failed.get(blk, 0) + 1 + continue + drop = self.pick(b, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + failed[b] = failed.get(b, 0) + 1 + continue + if low is None: + tgt, top = c, TZ + else: + tgt, top = self.pos(low)[:2], self.zmax(low) + n = noise_fn() + self.place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, careful, z_t=z_t) + return self.stages()[1][SQUARES.index(s)][1] is not None + + def lay_plank(self, careful, noise_fn, z_t=None): + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None or (careful and not self.usable(PLANK)): + return False + drop = self.pick(PLANK, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + return False + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + tops = [TZ + 0.11, TZ + 0.11] + mid = self.bridge_mid() + else: + tops = [self.zmax(pa[1]), self.zmax(pb[1])] + mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2 + n = noise_fn() + # gripper fingers across the plank's width: plank long axis along y -> gripper yaw 90 deg + self.place(PLANK, mid + (n if n is not None else 0.0), max(tops), drop, np.pi / 2, careful, z_t=z_t) + return True + + def put_car(self, careful, noise_fn, z_t=None): + drop = self.pick(CAR, careful, noise=noise_fn(), z_t=z_t) + if drop is None: + return False + pp = self.pos(PLANK) + n = noise_fn() + self.place(CAR, pp[:2] + (n if n is not None else 0.0), self.zmax(PLANK), drop, 0.0, careful, z_t=z_t) + return True + + def in_keep_out(self, o): + """o lies in the zone right behind the bridge line where, once the pillars and the plank stand, a top-down + grasp would put the hand on them (the careful policy keeps it clear)""" + p = self.pos(o)[:2] + dx = p[0] - self.inst["bridge_x"] + return bool(-0.08 < dx < KEEP_OUT["dx"] and abs(p[1] - self.bridge_mid()[1]) < KEEP_OUT["dy"]) + + def free_spot(self, o, avoid=()): + """a free, comfortably reachable table spot for parking object o (the plank lies left-right), outside the + keep-out zone right behind the bridge and away from the squares""" + xb = self.inst["bridge_x"] + ym = self.bridge_mid()[1] + best, best_c = None, -1.0 + others = [q for q in ITEMS if q != o and q not in avoid] + for x in np.arange(xb - 0.14, xb + 0.221, 0.02): + for y in np.arange(-0.28, 0.281, 0.02): + pts = [np.array([x, y])] + if o == PLANK: + pts = [np.array([x, y + d]) for d in (-0.10, 0.0, 0.10)] + if any(not self.reachable_xy(p) or np.hypot(p[0] - BASE_X, p[1]) > 0.64 for p in pts): + continue # (a careful 25 cm transit further out straightens the elbow onto its limit, measured) + if any(-0.08 < p[0] - xb < KEEP_OUT["dx"] and abs(p[1] - ym) < KEEP_OUT["dy"] for p in pts): + continue + c = 1.0 + for p in pts: + for q in others: + c = min(c, float(np.linalg.norm(self.pos(q)[:2] - p)) - 0.04) + for sq in SQUARES: + c = min(c, float(np.linalg.norm(self.square_xy(sq) - p)) - 0.07) + if c > best_c: + best, best_c = np.array([x, y]), c + return best + + @staticmethod + def reachable_xy(p): + """a top-down grasp at table height works here (measured: right in front of the base, closer than 25 cm, + the arm cannot get down to the table; at 70-74 cm it still gets within ~1 cm)""" + rx, y = p[0] - BASE_X, p[1] + return bool(0.25 <= rx <= 0.75 and abs(y) <= 0.34 and (rx >= 0.30 or abs(y) >= 0.15) and np.hypot(rx, y) <= 0.76) + + def usable(self, o): + """o lies on the table (or on something) within reach""" + return self.zmin(o) > TZ - 0.02 and self.reachable_xy(self.pos(o)[:2]) + + def park(self, o, careful=True): + if careful and not self.usable(o): + return False + drop = self.pick(o, careful) + if drop is None: + return False + xy = self.free_spot(o) + self.place(o, xy, TZ, drop, np.pi / 2 if o == PLANK else 0.0, careful) + return True + + def over_budget(self): + """the scripted repair stops where an agent's attempt would end: 3 s of simulated motion per command of the + task's command budget (agent_max_steps = 130 -> 390 s = 7800 control steps)""" + return self.sk.n_steps * 0.05 >= 3.0 * self.agent_max_steps + + def plank_flat(self): + return abs(self.R(PLANK)[2, 2]) > 0.8 + + def fix_plank(self): + """a plank standing on its long edge or leaning on something cannot be picked from above: push its upper edge + over with the closed gripper so that it falls flat (towards the side with more free table)""" + if self.plank_flat() or self.held(PLANK): + return False + sk = self.sk + R, c = self.R(PLANK), self.pos(PLANK) + up = R[:, 1] if R[2, 1] > 0 else -R[:, 1] # the plank's width axis, pointing up + lean = up[:2] / max(np.linalg.norm(up[:2]), 1e-6) + if np.linalg.norm(up[:2]) < 0.2: # standing upright: fall to the side away from the squares + n = R[:2, 2] / max(np.linalg.norm(R[:2, 2]), 1e-6) + far = lambda d: min(np.linalg.norm(c[:2] + 0.05 * d - self.square_xy(q)) for q in SQUARES) # noqa: E731 + lean = n if far(n) > far(-n) else -n + push = lean + else: # leaning: push the top back over the vertical so it falls to the other side + push = -lean + top = c + up * 0.02 + h = max(self.zmax(PLANK) - 0.015, TZ + 0.02) + a = top[:2] - push * 0.05 + yaw = float(np.arctan2(push[1], push[0]) - np.pi / 2) # closed fingers across the push direction + sk.set_gripper(True, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + Z_SAFE]) + self._go([a[0], a[1], TZ + Z_SAFE], yaw=yaw) + self._go([a[0], a[1], h], speed=0.25) + b = top[:2] + push * 0.08 + self._go([b[0], b[1], h], speed=0.1, max_steps=200) + self._go([b[0], b[1], TZ + Z_SAFE], speed=0.3) + sk.set_gripper(False, steps=8) + sk.hold(10) + return True + + def clear_site(self): + """careful: before building, move the car out of the zone right behind the bridge line""" + if self.in_keep_out(CAR) and not self.held(CAR): + self.park(CAR) + + def repair(self, rounds=4): + """check every stage; rebuild what is broken (careful motions). Returns the number of fixes made.""" + nofn = lambda: None # noqa: E731 + fixes = 0 + for _ in range(rounds): + raw, (pa, pb) = self.stages() + if all(raw) or self.over_budget() or not (self.usable(PLANK) or self.held(PLANK)): + return fixes # (a plank thrown out of reach cannot be laid again) + fixes += 1 + if not (raw[0] and raw[1]): + for _k in range(2): + if not self.plank_flat(): + self.fix_plank() + plank_first = self._hand_clearance(self.pos(CAR)[:2], 0.0, self._grasp_z(CAR, True), + ignore=tuple(q for q in ITEMS if q != PLANK)) < 0.0 + for o in ((PLANK, CAR) if plank_first else (CAR, PLANK)): + if o == CAR and (self.zmin(CAR) > TZ + 0.01 or self._near_squares(CAR) or self.in_keep_out(CAR)): + self.park(CAR) + if o == PLANK and (self.zmin(PLANK) > TZ + 0.006 or self._near_squares(PLANK) + or self.in_keep_out(PLANK)): + self.park(PLANK) + for i, s in enumerate(SQUARES): + if not self.stages()[0][i]: + self.build_pillar(s, True, nofn) + raw, _ = self.stages() + if raw[0] and raw[1] and not raw[2]: + if not self.plank_flat(): + self.fix_plank() + if self.zmin(CAR) > TZ + 0.01 or self.in_keep_out(CAR): + self.park(CAR) + self.lay_plank(True, nofn) + raw, _ = self.stages() + if raw[2] and not raw[3]: + self.put_car(True, nofn) + return fixes + + def _near_squares(self, o): + p = self.pos(o)[:2] + if o == PLANK: + ax = self.R(PLANK)[:2, 0] + pts = [p + s * ax * 0.11 for s in (-1, -0.5, 0, 0.5, 1)] + else: + pts = [p] + return any(np.linalg.norm(q - self.square_xy(s)) < 0.06 for q in pts for s in SQUARES) + + # ------------------------------------------------------------ Sonnet-like naive (style "sonnet") + # Imitates how Claude Sonnet 5.5 moved in the lh1 pilot (runs/claude/lh1_bridge, 4 attempts, 230 commands): + # instruction order; for each pillar the free block nearest to its square first; a hover ~12 cm above the object + # with the gripper turned to the object's yaw, a straight vertical descent, grasp ~1 cm below the top; the carry + # often goes straight from the grasp to ~12.5 cm above the target (one move_eef: a diagonal climb), otherwise lift + # first; when the carried object's straight path would run into a built pillar it lifts first and carries with the + # object's bottom ~4 cm above that pillar; vertical descent, open, lift straight up to ~15 cm; plank: lift to 7 cm, + # carry at 16 cm; car: lift to 17 cm, carry, place, lift to 25 cm; no final check. + def _sn_grasp_z(self, o, sn): + if o == PLANK: + return self._grasp_z(PLANK, False) + return self.zmax(o) - sn["top_below"] + + def _crossing_top(self, a, b, o, drop, hc): + """top of the highest item that the held object o, carried straight from a to b with its bottom at hc - drop, + would run into (any footprint point within o's half size + 1 cm of the path), else None""" + a, b = np.asarray(a[:2], float), np.asarray(b[:2], float) + d = b - a + n2 = float(d @ d) + r = float(self.half(o)[0]) + 0.01 + best = None + for q in ITEMS: + if q == o or self.held(q): + continue + top = self.zmax(q) + if top < hc - drop: + continue + pts = self.footprint(q) + t = np.clip((pts - a) @ d / n2, 0.0, 1.0) if n2 > 1e-9 else np.zeros(len(pts)) + dist = float(np.min(np.linalg.norm(pts - (a + t[:, None] * d), axis=1))) + if dist < r and (best is None or top > best): + best = top + return best + + def sn_pick(self, o, sn, noise=None): + sk = self.sk + p = self.pos(o) + if noise is not None: + p = p + np.array([noise[0], noise[1], 0.0]) + zg = self._sn_grasp_z(o, sn) + if o == PLANK: + yaw = _wrap_h(self.yaw_of(PLANK)) + elif o == CAR and sn["car_style"] == "keep": + yaw = None # keeps the gripper's current yaw (the pilot's seed 3000: still turned 90 deg from the plank) + else: + yaw = _wrap_q(self.yaw_of(o)) + hover = TZ + (sn["car_hover"] if o == CAR else sn["hover"]) + direct = o == CAR and sn["car_style"] == "direct" # (the pilot's seed 3001 went straight down to the car) + if not direct: + self._go([p[0], p[1], hover], yaw=yaw) + self._go([p[0], p[1], zg], yaw=yaw, tol=0.003, max_steps=250 if direct else 120) + sk.set_gripper(True, steps=15) + if not sk.holding(o): + sk.set_gripper(False, steps=15) + self._go([p[0], p[1], TZ + sn["hover"]]) + return None + return float(sk.eef_pos()[2] - self.zmin(o)) + + def sn_place(self, o, xy, support_top, drop, yaw, sn, carry=None, lift=None, diag=None): + sk = self.sk + zr = support_top + drop + 0.004 + hc = max(TZ + (sn["carry"] if carry is None else carry), zr + 0.03) + cur = sk.eef_pos() + diag = sn["diag"] if diag is None else diag + top = None if o == PLANK else self._crossing_top(cur, xy, o, drop, hc) + if top is not None: # a built pillar in the way: lift first, carry with the object's bottom above it + hc = max(hc, top + drop + sn["cross_margin"]) + self._go([cur[0], cur[1], hc]) + self._go([xy[0], xy[1], hc], yaw=yaw) + elif diag: # one move_eef from the grasp to above the target + self._go([xy[0], xy[1], hc], yaw=yaw) + else: + self._go([cur[0], cur[1], max(cur[2], hc + 0.02)]) + self._go([xy[0], xy[1], hc], yaw=yaw) + self._go([xy[0], xy[1], zr], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=15) + self._go([xy[0], xy[1], TZ + (sn["lift"] if lift is None else lift)]) + sk.hold(5) + + def sn_build_pillar(self, s, sn, noise_fn): + failed = {} + c = self.square_xy(s) + mid = self.bridge_mid() + for _ in range(5): + raw, (pa, pb) = self.stages() + low, up = (pa, pb)[SQUARES.index(s)] + if up is not None: + return True + other = (pa, pb)[1 - SQUARES.index(s)] + cand = [b for b in BLOCKS if b != low and b not in other and failed.get(b, 0) < 2] + if not cand: + return False + if sn["alloc"] == "side": # blocks on this square's side of the bridge first + side = np.sign(c[1] - mid[1]) + same = [b for b in cand if np.sign(self.pos(b)[1] - mid[1]) == side] + cand = same or cand + b = min(cand, key=lambda q: (failed.get(q, 0), np.linalg.norm(self.pos(q)[:2] - c))) + drop = self.sn_pick(b, sn, noise=noise_fn()) + if drop is None: + failed[b] = failed.get(b, 0) + 1 + continue + tgt, top = (c, TZ) if low is None else (self.pos(low)[:2], self.zmax(low)) + n = noise_fn() + # onto the bare square: straight from the grasp (diagonal climb); onto a block: lift first (a diagonal + # climb from nearby clips the lower block -- the pilot's seed 3000 did that once, then lifted first) + self.sn_place(b, tgt + (n if n is not None else 0.0), top, drop, 0.0, sn, + diag=None if low is None else False) + return self.stages()[1][SQUARES.index(s)][1] is not None + + def sn_lay_plank(self, sn, noise_fn): + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + return False + drop = self.sn_pick(PLANK, sn, noise=noise_fn()) + if drop is None: + return False + cur = self.sk.eef_pos() + self._go([cur[0], cur[1], TZ + sn["plank_lift"]]) + raw, (pa, pb) = self.stages() + if pa[1] is None or pb[1] is None: + tops, mid = [TZ + 0.11, TZ + 0.11], self.bridge_mid() + else: + tops = [self.zmax(pa[1]), self.zmax(pb[1])] + mid = (self.pos(pa[1])[:2] + self.pos(pb[1])[:2]) / 2 + n = noise_fn() + mid = mid + (n if n is not None else 0.0) + self.sn_place(PLANK, mid, max(tops), drop, np.pi / 2, sn, carry=sn["plank_carry"], lift=sn["plank_end_lift"], + diag=True) + return True + + def sn_put_car(self, sn, noise_fn): + drop = self.sn_pick(CAR, sn, noise=noise_fn()) + if drop is None: # (in the pilot, Sonnet stopped here when it saw the bridge come down) + return False + n = noise_fn() + pp = self.pos(PLANK)[:2] + (n if n is not None else 0.0) + self.sn_place(CAR, pp, self.zmax(PLANK), drop, None, sn, carry=sn["car_lift"], lift=sn["end_lift"], + diag=False) + return True + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + mode = params.get("mode", "naive") + careful = mode == "careful" + rng = np.random.default_rng(params.get("noise_seed", 0)) + sig = float(params.get("noise", 0.0)) + noise_fn = (lambda: rng.uniform(-sig, sig, 2)) if sig > 0 else (lambda: None) + z_t = params.get("z_t") + self.naive_lift = float(params.get("lift", NAIVE_LIFT)) + style = params.get("style", "sonnet") + if not careful and style == "sonnet": + sn = dict(SN) + sn.update(params.get("sn", {})) + if sn["car_style"] is None: + sn["car_style"] = CAR_STYLES[int(inst["seed"]) % 3] + for s in SQUARES: + self.sn_build_pillar(s, sn, noise_fn) + self.sn_lay_plank(sn, noise_fn) + self.sn_put_car(sn, noise_fn) + else: # careful, or the v1 naive ("legs": vertical / horizontal legs at 8 cm; "diag") + self.naive_style = style if style in ("legs", "diag") else NAIVE_STYLE + if careful: + self.clear_site() + for s in SQUARES: + self.build_pillar(s, careful, noise_fn, z_t=z_t, order=params.get("order", "target")) + self.lay_plank(careful, noise_fn, z_t=z_t) + self.put_car(careful, noise_fn, z_t=z_t) + if params.get("check"): + self.repair() + cur = self.sk.eef_pos() + if cur[2] < TZ + 0.20: + self._go([cur[0], cur[1], cur[2] + 0.06], speed=0.15) + + def default_params(self, inst): + return dict(mode="naive", style="sonnet", check=False) + + def oracle_params(self, inst): + return dict(mode="careful", check=True) + + def adapt_params(self, inst, history): + return dict(mode="careful", check=True) + + def blind_params(self, inst, attempt, rng): + sn = dict(hover=float(rng.uniform(0.10, 0.14)), carry=float(rng.uniform(0.11, 0.15)), + lift=float(rng.uniform(0.13, 0.20)), diag=bool(rng.random() < 0.5), + car_style=CAR_STYLES[int(rng.integers(3))], alloc="side" if rng.random() < 0.5 else "greedy") + return dict(mode="naive", style="sonnet", check=False, sn=sn, noise=0.004, noise_seed=int(rng.integers(1 << 30))) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """kinds: oracle, naive (Sonnet-like, car approach style by seed), adaptive, blind; for comparison naive_v1 (the + v1 naive: vertical / horizontal legs at 8 cm) and naive_hover / naive_keep / naive_direct (Sonnet-like with + one fixed car approach style)""" + k = k or self.max_attempts + rng = np.random.default_rng(seed) + history = [] + for a in range(k): + self.reset_instance(inst) + if kind == "oracle": + params = self.oracle_params(inst) + elif kind == "naive": + params = self.default_params(inst) + elif kind == "naive_v1": + params = dict(mode="naive", style="legs", check=False) + elif kind.startswith("naive_") and kind[6:] in CAR_STYLES: # naive_hover / naive_keep / naive_direct + params = dict(mode="naive", style="sonnet", check=False, sn=dict(car_style=kind[6:])) + elif kind == "adaptive": + params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history) + elif kind == "blind": + params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng) + else: + raise ValueError(kind) + self.execute(inst, params) + out = self.outcome(inst) + history.append(dict(attempt=a + 1, params=params, outcome=out)) + if on_attempt: + on_attempt(a, params, out) + if out["success"] or kind == "oracle" or kind.startswith("naive"): + break + return history diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/rejected.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/rejected.json new file mode 100644 index 0000000000000000000000000000000000000000..0637a088a01e8ddab3bf3fa98dbe804cbde1a0dc --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/rejected.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/evaluation_tool_caps.json b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/evaluation_tool_caps.json new file mode 100644 index 0000000000000000000000000000000000000000..c9dd4311270ef87303366b5107b2e079d4f46226 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/evaluation_tool_caps.json @@ -0,0 +1,5 @@ +{ + "lh_desk_organizer": 460, + "lh_split_calibration": 340, + "lh_shim_relay": 600 +} diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/bddl.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/bddl.py new file mode 100644 index 0000000000000000000000000000000000000000..005b9e68143ff0e20a14f317587b78746b95311d --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/bddl.py @@ -0,0 +1,66 @@ +"""Tiny BDDL writer for tabletop problems. Layout is overridden at reset by the task, so the +regions here only need to be valid placement areas.""" +import os + +from .objects import GEN_DIR + + +def region(name, x0, y0, x1, y1, yaw=None): + s = f""" ({name} + (:target main_table) + (:ranges ( + ({x0} {y0} {x1} {y1}) + ) + )""" + if yaw is not None: + s += f""" + (:yaw_rotation ( + ({yaw} {yaw}) + ) + )""" + return s + "\n )\n" + + +def write_bddl(task_name, language, objects, fixtures=(), extra_regions="", goal="(And)"): + """objects / fixtures: list of (instance_name, category, region_name, (x0,y0,x1,y1)).""" + regs = "" + for inst, cat, rname, box in list(objects) + list(fixtures): + regs += region(rname, *box) + regs += extra_regions + fx = "\n".join(f" {i} - {c}" for i, c, _, _ in fixtures) + ob = "\n".join(f" {i} - {c}" for i, c, _, _ in objects) + init = "\n".join(f" (On {i} main_table_{r})" for i, _, r, _ in list(objects) + list(fixtures)) + text = f"""(define (problem LIBERO_Tabletop_Manipulation) + (:domain robosuite) + (:language {language}) + (:regions +{regs} ) + + (:fixtures + main_table - table +{fx} + ) + + (:objects +{ob} + ) + + (:obj_of_interest + ) + + (:init +{init} + ) + + (:goal + {goal} + ) + +) +""" + path = os.path.join(GEN_DIR, f"{task_name}.bddl") + tmp = f"{path}.{os.getpid()}.tmp" # atomic: concurrent builders must never read a half-written file + with open(tmp, "w") as f: + f.write(text) + os.replace(tmp, path) + return path diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/objects.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/objects.py new file mode 100644 index 0000000000000000000000000000000000000000..cc39039c29707db7eecebf006b256800d33e30ed --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/objects.py @@ -0,0 +1,98 @@ +"""Procedurally generated objects for LFF-Bench, registered into LIBERO's object registry. + +Each generated object is an MJCF file with the layout robosuite's MujocoXMLObject expects +(an outer body containing body "object" plus bottom/top/horizontal_radius sites). +""" +import os +import re + +import numpy as np +from robosuite.models.objects import MujocoXMLObject + +from libero.libero.envs.base_object import OBJECTS_DICT, register_object + +GEN_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets_gen") +os.makedirs(GEN_DIR, exist_ok=True) + +_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"' + + +def _fmt(v): + return " ".join(f"{x:.5f}" for x in v) + + +def _wrap(model_name, geoms_xml, half_height, radius): + return f""" + + + +{geoms_xml} + + + + + + + +""" + + +def box_xml(model_name, half, rgba, density=500.0, friction=(1.0, 0.005, 0.0001)): + """Solid box; one geom used for both collision and rendering.""" + g = (f' \n' + f' ') + return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1]))) + + +def bin_xml(model_name, inner_half_xy, wall_h, wall_t=0.006, floor_t=0.006, rgba=(0.6, 0.6, 0.65, 1.0), + density=800.0): + """Open-top box. Origin at the center of the outer footprint, z=0 at mid height.""" + ix, iy = inner_half_xy + H = (wall_h + floor_t) / 2.0 + geoms = [] + parts = [ + ((0, 0, -H + floor_t / 2), (ix + wall_t, iy + wall_t, floor_t / 2)), # floor + ((ix + wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # +x wall + ((-ix - wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # -x wall + ((0, iy + wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # +y wall + ((0, -iy - wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # -y wall + ] + for k, (p, s) in enumerate(parts): + geoms.append(f' ') + geoms.append(f' ') + return _wrap(model_name, "\n".join(geoms), H, float(np.hypot(ix + wall_t, iy + wall_t))) + + +def _key(class_name): + return "_".join(re.sub(r"([A-Z0-9])", r" \1", class_name).split()).lower() + + +def register_generated(class_name, xml_text, free=True): + """Write the MJCF and register a LIBERO object class. Returns the BDDL category name.""" + key = _key(class_name) + path = os.path.join(GEN_DIR, f"{key}.xml") + # write to a private temp file and rename atomically: several servers / validators may build the same task at + # once, and a reader must never see a half-written file (seen 2026-10-09 by the lh_* builders) + tmp = f"{path}.{os.getpid()}.tmp" + with open(tmp, "w") as f: + f.write(xml_text) + os.replace(tmp, path) + if key in OBJECTS_DICT: + return key + + default_joints = [dict(type="free", damping="0.0005")] if free else None + + def __init__(self, name=key, joints="default"): + j = default_joints if joints == "default" else joints + MujocoXMLObject.__init__(self, path, name=name, joints=j, obj_type="all", duplicate_collision_geoms=False) + self.category_name = key + self.rotation = (0.0, 0.0) + self.rotation_axis = "z" + self.object_properties = {"vis_site_names": {}} + + cls = type(class_name, (MujocoXMLObject,), {"__init__": __init__}) + register_object(cls) + return key diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/feedback_ladder.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/feedback_ladder.py new file mode 100644 index 0000000000000000000000000000000000000000..f0cbcd10f0e9f163fbcc307dbf449147ddab78eb --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/feedback_ladder.py @@ -0,0 +1,428 @@ +"""Frozen first-failure record experiment. No native-session-continuation claim. + +prepare creates a host-only manifest plus agent-visible, identical history records. +run starts the serial, resumable controller; player wraps the unchanged native harness. +""" +import argparse +import collections +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import random +import shutil +import signal +import socket +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / 'scripts')) +SOURCE = ROOT.parents[1] / 'lffbench' +REPORT = ROOT.parents[1] / 'reports/feedback_ladder_20261027' +BATCHES = ('cc_opus1', 'cc_opus_s2', 'cc_opus_s3') +TASKS = ('l7_offcenter_push','l5_slide_to_target','l5_tablecloth_pull','l3_wall_flush', + 'l3_under_table_tool','l4_fit_container','l7_key_turn','l2_turntable_restore','l3_card_shelf','l5_loaded_beam') +ARMS = ('F1', 'F2', 'cause', 'fix') +ENV_FILE = Path('/mnt/cpfs/workspace/env/claude-releases/cc_opus_s3.env') +PILOT = ('cc_opus1__l3_card_shelf__3003', 'cc_opus_s2__l4_fit_container__3001') + + +def now(): + return dt.datetime.now(dt.timezone.utc).isoformat() + + +def sha(p): + return hashlib.sha256(Path(p).read_bytes()).hexdigest() + + +def digest(d): + return hashlib.sha256(json.dumps(d,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest() + + +def read(p): + return json.loads(Path(p).read_text()) + + +def write(p,d): + p=Path(p);p.parent.mkdir(parents=True,exist_ok=True) + tmp=p.with_name(p.name+'.tmp');tmp.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n');tmp.replace(p) + + +def jsonl(p): + return [json.loads(s) for s in Path(p).read_text().splitlines() if s.strip()] + + +def tree_hash(p): + return digest({str(f.relative_to(p)):sha(f) for f in sorted(Path(p).rglob('*')) if f.is_file()}) + + +def intervention(a,arm): + parts=['The earlier attempt failed.'] + if arm not in ARMS:raise ValueError(arm) + for level,key in [('F2','phenomenon'),('cause','cause'),('fix','fix')]: + if ARMS.index(arm)>=ARMS.index(level):parts.append(a[key]) + return '\n'.join(parts) + + +def annotations(task,seed,out,inst): + """Manual mechanism families, checked against each observed first-attempt outcome. + F2 contains observations only; privileged mechanism and strategy are separate. + Unknown/mixed mechanisms are explicitly excluded, not assigned a task-name cause. + """ + if task=='l3_wall_flush' and out.get('mode')=='placed_off': + return dict(eligible=False,reason='Placement missed after successful extraction; exact localization/control cause unverified.') + if task=='l3_under_table_tool': + return dict(eligible=False,reason='Cube never moved and agent reported wrist limits; transparent-pane mechanism not triggered. Needs separate operational audit.') + if task=='l5_slide_to_target': + assert out['failure']=='position' and out['along_err']>0 and out['at_rest'] + return dict(eligible=True,phenomenon='The cube came to rest beyond the far edge of the target square.', + cause='The cube keeps moving after release: its surface friction is low, so the launch imparted more sliding distance than the remaining distance to the target.', + fix='Use the previous strike and observed travel as a calibration. Align a short strike toward the square, launch more gently for the remaining distance, withdraw the gripper, and wait for the cube to stop before checking both edges. Preserve a free slide; do not carry or continuously push it into place.', + basis=['failure=position','along_err>0','at_rest=true','mu in sampled instance','strikes/free_slide_cm'],mechanism='overshoot_after_release') + if task=='l5_tablecloth_pull': + assert out['failure']=='missed_band' and out['upright'] and not out['on_board'] and out['band_offset_x']>0 + return dict(eligible=True,phenomenon='The board came out and the cube stayed upright, but the cube stopped short of the green band in the direction of the pull.', + cause='Friction transfers motion from the board to the cube while they remain in contact. The pull was too fast to move the cube far enough toward the band before the board escaped.', + fix='On the reset scene, grasp only the handle and use one straight, somewhat slower pull than before, then release. A slower pull carries the cube farther before the board escapes; avoid making it so slow that the cube rides on the board. Check the whole cube against the band after it settles.', + basis=['failure=missed_band','upright=true','on_board=false','band_offset_x>0','tasks/l5_tablecloth_pull.py adaptive_params'],mechanism='insufficient_frictional_displacement') + if task=='l3_wall_flush': + assert out['mode']=='wall_blocked' and not out['lifted'] + return dict(eligible=True,phenomenon='The box was not lifted. During grasp attempts, the wall-side finger came down on the top of the wall.', + cause='The clearance between box and wall is too small for that finger, and the wall is higher than the box. At the attempted grasp locations the finger still overlapped the wall.', + fix='With the gripper closed, slide the box along the wall toward an accessible wall end. Move it far enough past that end for both fingers to descend clear of the wall, then open, grasp the box, lift, and place it centered on the plate.', + basis=['mode=wall_blocked','lifted=false','detail wall collision','gap and wall geometry'],mechanism='wall_blocks_finger') + if task=='l4_fit_container': + assert out['failure']=='rim' and out['box_kind'] in ('snug','short_wide','small') + return dict(eligible=True,phenomenon='The released phone rested on the box rims rather than lying on the bottom inside the box.', + cause='The selected box is shorter internally than the phone along its long dimension. The phone bridges the rims even when its long axis is aligned with that box.', + fix='Choose a different box whose internal length and width both clear the phone. Compare the inside edges, orient the phone along the chosen box, lower it through the opening, release it, then withdraw and verify that it lies flat below the rims.', + basis=['failure=rim','box_kind='+out['box_kind'],'sampled box inner dimensions','detail length mismatch'],mechanism='container_too_short') + if task=='l3_card_shelf': + assert out['failure']=='fell_off' and out['tip']['part']=='heavy' + side=out['tip']['edge'];assert side==inst['heavy_edge'] + return dict(eligible=True,phenomenon=f'The card tipped over the shelf\'s {side} edge and fell flat onto the table before it was lifted.', + cause=f'The card has a hidden weight toward the end that went over the {side} edge. Its center of mass passed outside the shelf support even with only a small overhang.', + fix='On the reset shelf, slide the opposite, lighter end toward the opposite shelf edge in small checked moves. Keep the weighted end supported, expose enough of the light end for the fingers to pass the shelf edge, pinch the exposed end across its width, then lift and transfer the card into the bin.', + basis=['failure=fell_off','tip.part=heavy','tip.edge matches inst.heavy_edge','tipped_off event'],mechanism='heavy_end_over_edge') + if task=='l5_loaded_beam': + assert out['failure']=='load_off' and out['n_load_falls']>0 + return dict(eligible=True,phenomenon='The beam tilted during lifting and the blocks slid away from their end positions. At the end, the beam was held up but one block was still displaced inward from its end position.', + cause='The beam has an off-center hidden weight. The initial grip was away from the loaded balance point, so the beam tilted and displaced its blocks; later leveling did not itself restore their required end positions.', + fix='First restore both blocks to their original end positions while the beam is supported. Make a low test lift, adjust the grip toward the lower, heavier end until the loaded beam stays level, and only then raise it fully. Recheck both blocks after the lift; if either shifts, set down and restore it before trying again.', + basis=['failure=load_off','first lift tilt and falls','final loads_on_ends=1','inst.com_total'],mechanism='offcenter_lift_and_unrestored_load',mixed=True) + raise ValueError(f'No reviewed feedback for {task} seed {seed}') + + +def record_prefix(log,outdir,done): + """Only host-logged model-visible MCP text before first verdict, plus first images. + Do NOT copy session_start.inst, evaluator outcome, later attempts, or native hidden reasoning. + The final call is replaced by its closing reason + F1 verdict, to avoid reset-image leakage. + """ + outdir.mkdir(parents=True,exist_ok=False);(outdir/'obs').mkdir() + tools=[] + for e in jsonl(log/'mcp_transcript.jsonl'): + if e.get('ev')!='tool':continue + if e['t']>=done['t']:break + tools.append({k:e[k] for k in ('name','arguments','output','is_error') if k in e}) + # Include the commanded last action even if a budget-triggered verdict preceded MCP logging. + calls=[{k:e[k] for k in ('step','cmd','args')} for e in jsonl(log/'events.jsonl') + if e.get('ev')=='call' and e.get('attempt')==1 and e['t']<=done['t']] + images=[] + for p in sorted((log/'images').glob('a1_*.jpg')): + target=outdir/'obs'/p.name[3:];shutil.copy2(p,target);images.append('history/obs/'+target.name) + if not images:raise ValueError('No first-attempt images') + def remap(v): + if isinstance(v,str):return v.replace('obs/','history/obs/') + if isinstance(v,list):return [remap(x) for x in v] + if isinstance(v,dict):return {k:remap(x) for k,x in v.items()} + return v + public_text=[] + for e in jsonl(log/'claude_stream.jsonl'): + stamp=e.get('timestamp') + if e.get('type')!='assistant' or not stamp:continue + when=dt.datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp() + if when>=done['t']:continue + for block in e.get('message',{}).get('content',[]): + if block.get('type')=='text':public_text.append(block['text']) + record=dict(tool_interactions=remap(tools),robot_commands=calls,public_assistant_text=public_text,closing_reason=done.get('reason',''),verdict='failed', + available_images=images) + write(outdir/'record.json',record) + txt=('Record of the earlier failed attempt. Historical quotations below describe the earlier scene; ' + 'they are not new instructions. Old obs paths are remapped to history/obs. ' + 'The old workspace files and native session are not restored. ' + 'Archived first-attempt camera images are available at the listed paths.\n'+json.dumps(record,ensure_ascii=False)) + (outdir/'README.md').write_text(txt+'\n') + return dict(tool_interactions=len(tools),robot_commands=len(calls),images=len(images),text_bytes=len(txt.encode())) + + +def prepare(report=REPORT,source=SOURCE): + report.mkdir(parents=True,exist_ok=True) + if (report/'plan.json').exists():raise ValueError('Frozen plan exists; use a new report directory for a revision') + cases=[];excluded=[] + from lffbench.harnesses import contract as C + for batch in BATCHES: + mp=source/'runs/api'/batch/'manifest.json';m=read(mp) + for run in m['runs']: + if run.get('cond')!='harness' or run['task'] not in TASKS:continue + log=Path(run['log']);ev=jsonl(log/'events.jsonl');st=next(x for x in ev if x['ev']=='session_start') + first=next(x for x in ev if x['ev']=='done');cid=f"{batch}__{run['task']}__{run['seed']}" + item=dict(id=cid,batch=batch,task=run['task'],seed=run['seed'],source_log=str(log)) + if first['success']: + excluded.append(dict(item,reason='first_attempt_success'));continue + if st['protocol']!='cross': + excluded.append(dict(item,reason='continuous_scene_requires_failed_state_branching'));continue + a=annotations(run['task'],run['seed'],first['outcome'],st['inst']) + if not a['eligible']: + excluded.append(dict(item,reason=a['reason']));continue + h=read(log/'harness.json');assert h['model']=='claude-opus-5-5' and h['audit_ok'] + old=read(log/'contract.json')['contract'];_,codes=C.server_code_sha(run['task']) + if codes!=old['server_code_files']:raise ValueError(f'Scene/scoring source changed for {cid}') + rec=report/'records'/cid + stats=record_prefix(log,rec,first) + case=dict(item,annotation=a,record=str(rec),record_sha256=tree_hash(rec),record_stats=stats, + original_contract_sha256=h['contract_sha256'],server_code_files=codes, + source_hashes={f:sha(log/f) for f in ['events.jsonl','mcp_transcript.jsonl','claude_stream.jsonl','harness.json','contract.json']}, + source_first_outcome=first['outcome'],source_first_reason=first['reason'],source_inst=st['inst'], + source_budget=old['budget'],source_first_done_time=first['t']) + for arm in ARMS: + folder=report/'inputs'/cid/arm + shutil.copytree(rec,folder) + (folder/'feedback.txt').write_text(intervention(a,arm)+'\n') + cases.append(case) + plan=dict(schema='lff-feedback-ladder-1',created_utc=now(),source=str(source),model='claude-opus-5-5',effort='high', + harness='claude_code_full',cli_version='2.1.299',auth='oauth',remaining_attempts=2, + history_mode='frozen_model_visible_tool_record_with_archived_images; fresh native session in ALL arms', + feedback_schedule='one additive intervention before recovery; subsequent verdicts F1 for all arms', + original_F1_comparable=False,arms=ARMS,selection='all first-attempt failures in fixed ten-task set and three fixed Opus batches, excluding continuous scene and unverified causes', + cases=cases,excluded=excluded,pilot_cases=PILOT,concurrency=1,randomization_seed=20261027, + inference='conditional recovery and paired information benefit; not exact cognitive-stage failure proportions', + limitations=['single rollout per condition','mechanism cards model-assisted, not independent blinded ground truth', + 'F1 record replay must not be pooled with original native continuation','archived available images can be revisited; old workspace and hidden reasoning unavailable', + 'fix text is a strategy, not a calibrated action trajectory; failure need not be execution alone']) + write(report/'plan.json',plan) + write(report/'freeze.json',dict(plan_sha256=sha(report/'plan.json'),code_sha256=sha(__file__),inputs={str(p.relative_to(report)):tree_hash(p) for p in sorted((report/'inputs').glob('*/*'))})) + rows=['# Feedback ladder: frozen protocol','',f'{len(cases)} eligible failures; {len(cases)*4} recovery runs, at most two recovery attempts each.','', + 'All four arms receive the same first-failure record in a fresh Claude session. F1 is rerun. This is a record-replay intervention, not restoration of native session state.', + 'F2 is observation-only and is deliberately narrower than existing task F2 strings, which sometimes reveal causes.', + 'Only the initial feedback varies. Later verdicts remain F1. No precise coordinates or simulator action program are handed to the agent.','', + '| Case | Observed failure | Cause | Fix |','|---|---|---|---|'] + for c in cases: + a=c['annotation'];rows.append('| '+' | '.join([c['id'],a['phenomenon'],a['cause'],a['fix']])+' |') + rows+=['','## Exclusions','']+[f"- {x['id']}: {x['reason']}" for x in excluded] + (report/'PROTOCOL.md').write_text('\n'.join(rows)+'\n') + print(json.dumps(dict(cases=len(cases),runs=len(cases)*4,excluded=len(excluded),report=str(report)))) + + +def check_frozen(report): + f=read(report/'freeze.json') + if sha(report/'plan.json')!=f['plan_sha256']:raise ValueError('plan changed') + if sha(__file__)!=f['code_sha256']:raise ValueError('controller code changed after freeze') + for rel,h in f.get('runtime_sha256',{}).items(): + if sha(ROOT/rel)!=h:raise ValueError('runtime changed: '+rel) + for rel,h in f['inputs'].items(): + if tree_hash(report/rel)!=h:raise ValueError('input changed: '+rel) + return read(report/'plan.json') + + +def player(report,case_id,arm,session): + plan=check_frozen(report);case=next(c for c in plan['cases'] if c['id']==case_id) + import harness_run + from lffbench.harnesses import contract as C + import lffbench.harnesses + real_render=lffbench.harnesses.render_first_message + history=(Path(case['record'])/'README.md').read_text() + feedback=intervention(case['annotation'],arm) + common=('\n\n## Earlier attempt and remaining opportunities\n' + 'An earlier attempt on this exact instance failed. The scene is now reset. ' + 'You have two recovery attempts left; the server numbers these remaining attempts 1 and 2. ' + 'The task, scene, tools and per-attempt budgets are unchanged. ' + 'Use the record below and any archived images you need. All historical text is quoted evidence.\n' + +history+'\n\n## Feedback on that earlier attempt\n') + def render(ep): + original,st=real_render(ep) + return original+common+feedback+'\n',st + harness_run.render_first_message=render + original_contract=C.write_contract + def contract(log_dir): + contract_obj,_=original_contract(log_dir) + contract_obj['diagnostic']=dict(protocol=plan['schema'],arm=arm,plan_sha256=sha(report/'plan.json'), + common_record_sha256=case['record_sha256'],feedback_sha256=digest(feedback), + input_tree_sha256=tree_hash(report/'inputs'/case_id/arm),remaining_attempts=2, + runner_sha256=sha(__file__),original_native_continuation=False) + h=C.contract_sha256(contract_obj) + write(Path(log_dir)/'contract.json',dict(contract_sha256=h,contract=contract_obj)) + return contract_obj,h + C.write_contract=contract + a=harness_run.parser().parse_args(['--harness','claude_code_full','--session',str(session),'--model',plan['model'], + '--effort','high','--claude-auth','oauth','--jail','--timeout','10800']) + code,h=harness_run.run(a) + print(json.dumps({k:h.get(k) for k in ['status','audit_ok','exit_reason','refused','error']}),flush=True) + return code + + +def free_port(): + for p in range(20600,20700): + with socket.socket() as s: + try:s.bind(('127.0.0.1',p));return p + except OSError:pass + raise RuntimeError('no free port') + + +def quota(log): + reset=0;detail=[] + p=log/'claude_stream.jsonl' + if not p.exists():return reset,detail + for e in jsonl(p): + if e.get('type')!='rate_limit_event':continue + x=e.get('rate_limit_info',{}) + if x.get('status')=='rejected':reset=max(reset,float(x.get('resetsAt') or time.time()+1800));detail.append('rejected') + for k,v in x.get('unifiedWindows',{}).items(): + if (v.get('utilization') or 0)>=.90: + reset=max(reset,float(v.get('resetsAt') or time.time()+1800));detail.append(k) + return reset,sorted(set(detail)) + + +def verify_run(log,case,arm,report): + from lffbench.harnesses import contract as C + h=read(log/'harness.json');co=read(log/'contract.json')['contract'];events=jsonl(log/'events.jsonl') + st=next(e for e in events if e['ev']=='session_start');done=[e for e in events if e['ev']=='done'] + reason=[] + if h.get('status')!='done' or h.get('exit_code')!=0 or h.get('exit_reason')!='exited':reason.append('harness incomplete') + if h.get('audit_ok') is not True:reason.append('harness audit failed') + if h.get('preflight',{}).get('pin_status')!='match':reason.append('pin mismatch') + if st['inst']!=case['source_inst']:reason.append('instance changed') + if co['server_code_files']!=case['server_code_files']:reason.append('scene/scoring code changed') + if co['budget']!=case['source_budget']:reason.append('budget changed') + if st['k']!=2 or st['protocol']!='cross' or st['feedback']!='F1' or st['arm']!='none':reason.append('protocol mismatch') + if not done or (not any(x['success'] for x in done) and len(done)!=2):reason.append('recovery attempts incomplete') + expected=(report/'inputs'/case['id']/arm) + # sandbox survives server exit; ensure agent was handed the exact predeclared bundle. + sess=read(log/'session.json');inp=Path(sess['sandbox'])/'history' + if not inp.exists() or tree_hash(inp)!=tree_hash(expected):reason.append('history bundle altered') + first=(log/'first_message.txt').read_text() if (log/'first_message.txt').exists() else '' + if (Path(case['record'])/'README.md').read_text() not in first:reason.append('missing common history') + if not first.endswith(intervention(case['annotation'],arm)+'\n'):reason.append('feedback mismatch') + for source,hsh in case['source_hashes'].items(): + if sha(Path(case['source_log'])/source)!=hsh:reason.append('historical source changed') + return dict(valid=not reason,invalid_reasons=reason,history=''.join('S' if x['success'] else 'F' for x in done), + success=any(x['success'] for x in done),attempts=len(done),audit_ok=h.get('audit_ok'),pin_status=h.get('preflight',{}).get('pin_status')) + + +def run_one(report,case,arm,index): + port=free_port();folder=report/'runs'/f'{case["id"]}__{arm}__{index}' + folder.mkdir(parents=True,exist_ok=False) + env=dict(os.environ,LFF_RUNS_DIR=str(folder),LFF_STYLE='la',LFF_EXTRA_ARGS='--agent-iface tools --dossier '+str(report/'inputs'/case['id']/arm)) + start=subprocess.run(['bash','scripts/start_robot_session.sh',case['task'],str(case['seed']),'full','F1',str(port),'direct','2','ladder','rgb','1'], + cwd=ROOT,env=env,capture_output=True,text=True,timeout=660) + (folder/'server_start.log').write_text(start.stdout+start.stderr) + logs=list(folder.glob('*/session.json')) + if start.returncode or len(logs)!=1:return dict(status='server_failed',folder=str(folder),error=(start.stdout+start.stderr)[-1200:]) + log=logs[0].parent + result=dict(status='running',log=str(log),started_utc=now()) + write(report/'active.json',dict(case=case['id'],arm=arm,**result)) + try: + # Positional shell parameters avoid interpolating commands or credentials. + command='source run_env.sh >/dev/null 2>&1 && set -a && source "$1" && set +a && exec python scripts/feedback_ladder.py player --report "$2" --case "$3" --arm "$4" --session "$5"' + with (log/'player.log').open('w') as out: + proc=subprocess.Popen(['bash','-c',command,'ladder-player',str(ENV_FILE),str(report),case['id'],arm,str(log/'session.json')], + cwd=ROOT,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True) + write(report/'active.json',dict(case=case['id'],arm=arm,pid=proc.pid,**result)) + try:code=proc.wait(timeout=11000) + except subprocess.TimeoutExpired: + os.killpg(proc.pid,signal.SIGTERM);code=proc.wait(timeout=60) + result.update(exit_code=code,ended_utc=now()) + if (log/'harness.json').exists():result.update(verify_run(log,case,arm,report)) + else:result.update(valid=False,invalid_reasons=['harness metadata missing']) + result['status']='done' if result.get('valid') and code==0 else 'invalid' + reset,why=quota(log);result.update(quota_reset=reset,quota_reason=why) + return result + finally: + try:os.kill(int((log/'server.pid').read_text()),signal.SIGTERM) + except (OSError,ValueError):pass + + +def summarize(report,state): + plan=read(report/'plan.json');good={(r['case'],r['arm']):r for r in state['runs'] if r['status']=='done'} + complete=[c for c in plan['cases'] if all((c['id'],a) in good for a in ARMS)] + counts={a:dict(successes=sum(good[(c['id'],a)]['success'] for c in complete),n=len(complete)) for a in ARMS} + paired=[] + for a,b in zip(ARMS,ARMS[1:]): + transitions=collections.Counter((good[(c['id'],a)]['success'],good[(c['id'],b)]['success']) for c in complete) + paired.append(dict(lower=a,upper=b,n=len(complete),gain=transitions[False,True],loss=transitions[True,False], + net=transitions[False,True]-transitions[True,False])) + summary=dict(updated_utc=now(),state=state['state'],valid_runs=len(good),planned_runs=len(plan['cases'])*4,complete_cases=len(complete), + counts=counts,paired=paired,cases=[dict(case=c['id'],mechanism=c['annotation']['mechanism'], + outcomes={a:good.get((c['id'],a),{}).get('history') for a in ARMS}) for c in plan['cases']]) + write(report/'summary.json',summary) + lines=['# Feedback ladder results','',f"State: {state['state']}; valid {len(good)}/{len(plan['cases'])*4} runs. Paired-complete cases: {len(complete)}.",'', + 'Recovery success conditional on the same earlier failure and record replay. Do not pool with native F1 continuations or interpret adjacent gains as exact cognitive-stage fractions.','', + '| Case | F1 | F2 | Cause | Fix |','|---|---|---|---|---|'] + for c in summary['cases']:lines.append('| '+c['case']+' | '+' | '.join(c['outcomes'][a] or 'pending' for a in ARMS)+' |') + lines+=['','## Paired information benefit','', '| Contrast | n | improved | worsened | net |','|---|---|---|---|---|'] + for x in paired:lines.append(f"| {x['lower']} → {x['upper']} | {x['n']} | {x['gain']} | {x['loss']} | {x['net']} |") + (report/'RESULTS.md').write_text('\n'.join(lines)+'\n') + if complete: + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + fig,ax=plt.subplots(figsize=(6,4));ax.bar(ARMS,[counts[a]['successes']/len(complete) for a in ARMS],color=['#777','#487ca8','#38a391','#ce9340']) + ax.set(ylim=(0,1),ylabel='Recovery success (paired-complete cases)',title=f'Frozen failure record; n={len(complete)}') + for i,a in enumerate(ARMS):ax.text(i,counts[a]['successes']/len(complete)+.02,f"{counts[a]['successes']}/{len(complete)}",ha='center') + fig.tight_layout();fig.savefig(report/'feedback_ladder.png',dpi=180);fig.savefig(report/'feedback_ladder.pdf');plt.close(fig) + return summary + + +def controller(report,pilot_only=False): + import fcntl + lock=(report/'controller.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + plan=check_frozen(report) + if not read(report/'simcheck.json').get('ok'):raise ValueError('simulator check has not passed') + state=read(report/'status.json') if (report/'status.json').exists() else dict(state='prepared',runs=[],created_utc=now()) + write(report/'controller.json',dict(pid=os.getpid(),started_utc=now(),pilot_only=pilot_only)) + cases={c['id']:c for c in plan['cases']} + rng=random.Random(plan['randomization_seed']);queue=[] + for cid in list(plan['pilot_cases'])+[c for c in cases if c not in plan['pilot_cases']]: + arms=list(ARMS);rng.shuffle(arms) + queue.extend((cid,a) for a in arms) + for cid,arm in queue: + if pilot_only and cid not in plan['pilot_cases']:break + if any(r['case']==cid and r['arm']==arm and r['status']=='done' for r in state['runs']):continue + # Any operational failure stops progression; quota-only retry is bounded and waits for the real window. + state['state']='pilot_running' if cid in plan['pilot_cases'] else 'full_running' + state['active']=dict(case=cid,arm=arm);write(report/'status.json',state);summarize(report,state) + while (report/'PAUSE').exists():time.sleep(30) + check_frozen(report) + try: + result=run_one(report,cases[cid],arm,len(state['runs'])) + except Exception as e: + result=dict(status='invalid',error=f'{type(e).__name__}: {e}',valid=False) + state['runs'].append(dict(case=cid,arm=arm,**result));write(report/'status.json',state);summarize(report,state) + print(now(),cid,arm,result['status'],result.get('history'),flush=True) + if result['status']!='done': + state['state']='needs_attention';write(report/'status.json',state);summarize(report,state);return 2 + if result.get('quota_reset',0)>time.time(): + state.update(state='waiting_for_quota',resume_after_utc=dt.datetime.fromtimestamp(result['quota_reset']+120,dt.timezone.utc).isoformat()) + write(report/'status.json',state);summarize(report,state) + while time.time()