diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/layer4_plan.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/layer4_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..03f7434a8b04de323809f5d8d4879b9933cc3a72 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/qwen_vl_server.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/qwen_vl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..33b002cb3516145787158a20c614a4bf1e3e551b --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/qwen_vl_server.py @@ -0,0 +1,535 @@ +#!/usr/bin/env python3 +"""Minimal OpenAI-compatible Chat Completions server (with tool calling) for Qwen3-VL. + +Runs a local HF-format Qwen3-VL checkpoint with transformers (>= 4.57) on one +CUDA-compatible device (here: Alibaba PPU) and exposes: + + POST /v1/chat/completions OpenAI chat.completion (non-streaming; stream=true + is emulated: the full answer is generated first + and then sent as SSE chunks) + GET /v1/models lists the single served model + GET /health liveness + device memory + +Request format accepted (subset of OpenAI): + messages: system / developer / user / assistant (with tool_calls) / tool + user/tool content may be a string or a list of + {"type":"text","text":...} and + {"type":"image_url","image_url":{"url": "data:image/...;base64,..." | http(s) URL | file path}} + tools: [{"type":"function","function":{"name","description","parameters"}}] + tool_choice: "auto" (default) | "none" (tools hidden from the prompt) | + "required" (generation is prefixed with "\n") | + {"type":"function","function":{"name":X}} (prefixed with the call header for X) + parallel_tool_calls: false -> only the first parsed tool call is returned + max_tokens / max_completion_tokens (default --default-max-tokens, 1024) + temperature (absent or 0 -> greedy), top_p, top_k, seed, stop (str or list) +Ignored: n (always 1), response_format, logprobs, presence/frequency penalty, user. + +The model emits Hermes-style {"name":..., "arguments":{...}} +blocks; they are parsed into choices[0].message.tool_calls with arguments as a JSON +string, and the remaining text (if any) becomes message.content (else null). + +Generation is serialised with a lock (one request on the device at a time); the +HTTP layer is a stdlib ThreadingHTTPServer so /health stays responsive. +""" +from __future__ import annotations + +import argparse +import base64 +import io +import json +import logging +import os +import re +import sys +import threading +import time +import traceback +import urllib.request +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +LOG = logging.getLogger("qwen_vl_server") + +TOOL_CALL_RE = re.compile(r"\s*(.*?)\s*", re.DOTALL) +END_MARKERS = ("<|im_end|>", "<|endoftext|>") + + +# ---------------------------------------------------------------------------- +# Request conversion +# ---------------------------------------------------------------------------- +class BadRequest(Exception): + pass + + +def load_image(url: str): + from PIL import Image + + if url.startswith("data:"): + try: + _, b64 = url.split(",", 1) + except ValueError as e: + raise BadRequest("malformed data URL") from e + raw = base64.b64decode(b64) + elif url.startswith("http://") or url.startswith("https://"): + with urllib.request.urlopen(url, timeout=30) as r: + raw = r.read() + else: + path = url[len("file://"):] if url.startswith("file://") else url + with open(path, "rb") as f: + raw = f.read() + img = Image.open(io.BytesIO(raw)) + img.load() + return img.convert("RGB") + + +def convert_content(content, images: list): + """OpenAI content (str | list[part] | None) -> Qwen template content. + + Images are replaced by {"type": "image"} placeholders and the decoded PIL images + are appended to `images` in prompt order (the chat template emits one + <|vision_start|><|image_pad|><|vision_end|> per placeholder, in the same order). + """ + if content is None: + return "" + if isinstance(content, str): + return content + if not isinstance(content, list): + raise BadRequest(f"unsupported content type: {type(content).__name__}") + out = [] + for part in content: + if isinstance(part, str): + out.append({"type": "text", "text": part}) + continue + ptype = part.get("type") + if ptype in ("text", "input_text"): + out.append({"type": "text", "text": part.get("text", "")}) + elif ptype in ("image_url", "input_image", "image"): + iu = part.get("image_url", part.get("image")) + url = iu.get("url") if isinstance(iu, dict) else iu + if not isinstance(url, str): + raise BadRequest("image part without url") + try: + images.append(load_image(url)) + except BadRequest: + raise + except Exception as e: # noqa: BLE001 + raise BadRequest(f"could not load image ({url[:60]}...): {type(e).__name__}: {e}") from e + out.append({"type": "image"}) + else: + raise BadRequest(f"unsupported content part type: {ptype}") + return out + + +def text_only(content) -> str: + if content is None: + return "" + if isinstance(content, str): + return content + return "".join(p.get("text", "") for p in content if isinstance(p, dict)) + + +def convert_messages(messages: list): + if not isinstance(messages, list) or not messages: + raise BadRequest("messages must be a non-empty list") + images: list = [] + system_texts = [] + conv = [] + for m in messages: + role = m.get("role") + if role in ("system", "developer"): + # The Qwen template only renders a leading system message; merge all of them. + system_texts.append(text_only(m.get("content"))) + elif role == "user": + conv.append({"role": "user", "content": convert_content(m.get("content"), images)}) + elif role == "assistant": + c = m.get("content") + msg = {"role": "assistant", "content": text_only(c) if not isinstance(c, str) else c} + tcs = m.get("tool_calls") or [] + if tcs: + norm = [] + for tc in tcs: + fn = tc.get("function", tc) + args = fn.get("arguments", {}) + if not isinstance(args, str): + args = json.dumps(args, ensure_ascii=False) + norm.append({"type": "function", "function": {"name": fn.get("name", ""), "arguments": args}}) + msg["tool_calls"] = norm + conv.append(msg) + elif role in ("tool", "function"): + conv.append({"role": "tool", "content": convert_content(m.get("content"), images)}) + else: + raise BadRequest(f"unsupported role: {role}") + if system_texts: + conv.insert(0, {"role": "system", "content": "\n\n".join(system_texts)}) + return conv, images + + +# ---------------------------------------------------------------------------- +# Output parsing +# ---------------------------------------------------------------------------- +def _loads_lenient(s: str): + s = s.strip() + try: + return json.loads(s) + except json.JSONDecodeError: + pass + # common slips: trailing garbage after the object, missing final brace + start = s.find("{") + if start >= 0: + dec = json.JSONDecoder() + try: + obj, _ = dec.raw_decode(s[start:]) + return obj + except json.JSONDecodeError: + pass + for extra in ("}", "}}", "\"}}"): + try: + return json.loads(s[start:] + extra) + except json.JSONDecodeError: + continue + return None + + +def parse_tool_calls(text: str): + """Return (content_or_None, tool_calls_list).""" + calls = [] + spans = [] + for mt in TOOL_CALL_RE.finditer(text): + spans.append(mt.span()) + calls.append(mt.group(1)) + # an unterminated trailing (e.g. hit max_tokens / model forgot the tag) + last_end = spans[-1][1] if spans else 0 + tail_idx = text.find("", last_end) + if tail_idx >= 0: + spans.append((tail_idx, len(text))) + calls.append(text[tail_idx + len(""):]) + + tool_calls = [] + keep_raw = [] # unparsable blocks stay in content + for (a, b), body in zip(spans, calls): + obj = _loads_lenient(body) + if not isinstance(obj, dict) or "name" not in obj: + keep_raw.append((a, b)) + continue + args = obj.get("arguments", obj.get("parameters", {})) + if isinstance(args, str): + parsed = _loads_lenient(args) + args_str = json.dumps(parsed, ensure_ascii=False) if parsed is not None else args + else: + args_str = json.dumps(args, ensure_ascii=False) + tool_calls.append({ + "id": "call_" + uuid.uuid4().hex[:24], + "type": "function", + "function": {"name": str(obj["name"]), "arguments": args_str}, + }) + + # content = text with successfully parsed blocks removed + parsed_spans = [s for s in spans if s not in keep_raw] + pieces, pos = [], 0 + for a, b in sorted(parsed_spans): + pieces.append(text[pos:a]) + pos = b + pieces.append(text[pos:]) + content = "".join(pieces).strip() + return (content if content else None), tool_calls + + +# ---------------------------------------------------------------------------- +# Model wrapper +# ---------------------------------------------------------------------------- +class Engine: + def __init__(self, args): + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor + + self.torch = torch + self.args = args + self.device = args.device + t0 = time.time() + proc_kwargs = {} + if args.min_pixels: + proc_kwargs["min_pixels"] = args.min_pixels + if args.max_pixels: + proc_kwargs["max_pixels"] = args.max_pixels + if args.attn == "sdpa" and not args.sdpa_native_gqa: + # PPU quirk (measured): torch SDPA with enable_gqa=True fails for decode steps + # (q_len=1, no mask) with "q must have shape (batch_size, seqlen_q, num_heads, + # head_size_og)". Make transformers repeat K/V heads itself instead. + import transformers.integrations.sdpa_attention as _sdpa + + _sdpa.use_gqa_in_sdpa = lambda attention_mask, key: False + self.processor = AutoProcessor.from_pretrained(args.model, **proc_kwargs) + self.tokenizer = self.processor.tokenizer + self.model = AutoModelForImageTextToText.from_pretrained( + args.model, + dtype=torch.bfloat16, + attn_implementation=args.attn, + device_map={"": self.device}, + ).eval() + self.load_time = time.time() - t0 + self.eos_ids = [self.tokenizer.convert_tokens_to_ids(t) for t in END_MARKERS] + self.eos_ids = [i for i in self.eos_ids if isinstance(i, int) and i >= 0] + self.pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.eos_ids[-1] + self.lock = threading.Lock() + LOG.info("model loaded in %.1fs on %s (attn=%s); mem allocated %.2f GiB", + self.load_time, self.device, args.attn, torch.cuda.memory_allocated(self.device) / 2**30) + + def mem(self): + t = self.torch + return { + "allocated_gib": round(t.cuda.memory_allocated(self.device) / 2**30, 2), + "reserved_gib": round(t.cuda.memory_reserved(self.device) / 2**30, 2), + "max_allocated_gib": round(t.cuda.max_memory_allocated(self.device) / 2**30, 2), + } + + def chat(self, req: dict): + torch = self.torch + a = self.args + messages, images = convert_messages(req.get("messages")) + tools = req.get("tools") or None + tool_choice = req.get("tool_choice", "auto") + prefix = "" + if tools: + if tool_choice == "none": + tools = None + elif tool_choice == "required": + prefix = "\n" + elif isinstance(tool_choice, dict): + fname = (tool_choice.get("function") or {}).get("name") or tool_choice.get("name") + if fname: + prefix = '\n{"name": "' + fname + '", "arguments": ' + tmpl_tools = None + if tools: + tmpl_tools = [] + for t in tools: + if isinstance(t, dict) and "function" not in t and "name" in t: + t = {"type": "function", "function": t} + tmpl_tools.append(t) + + prompt = self.processor.apply_chat_template( + messages, tools=tmpl_tools, tokenize=False, add_generation_prompt=True + ) + prefix + inputs = self.processor( + text=[prompt], images=images if images else None, return_tensors="pt" + ).to(self.device) + n_prompt = int(inputs["input_ids"].shape[1]) + if n_prompt > a.max_prompt_tokens: + raise BadRequest(f"prompt has {n_prompt} tokens > --max-prompt-tokens {a.max_prompt_tokens}") + + max_new = req.get("max_completion_tokens") or req.get("max_tokens") or a.default_max_tokens + max_new = int(min(max_new, a.max_tokens_cap)) + temperature = req.get("temperature") + if temperature is None: + temperature = a.default_temperature + gen_kwargs = dict( + max_new_tokens=max_new, + eos_token_id=self.eos_ids, + pad_token_id=self.pad_id, + use_cache=True, + ) + if temperature and float(temperature) > 0: + gen_kwargs.update(do_sample=True, temperature=float(temperature), + top_p=float(req.get("top_p") or 0.8), top_k=int(req.get("top_k") or 20)) + else: + gen_kwargs.update(do_sample=False, temperature=None, top_p=None, top_k=None) + if req.get("seed") is not None: + torch.manual_seed(int(req["seed"])) + + with torch.inference_mode(): + out = self.model.generate(**inputs, **gen_kwargs) + new_ids = out[0, n_prompt:].tolist() + # count tokens up to and including the first EOS + n_completion = len(new_ids) + hit_eos = False + for i, tid in enumerate(new_ids): + if tid in self.eos_ids: + n_completion = i + 1 + hit_eos = True + break + text = self.tokenizer.decode(new_ids[:n_completion], skip_special_tokens=False) + for mk in END_MARKERS: + text = text.replace(mk, "") + text = prefix + text + + stop = req.get("stop") + stopped_by_str = False + if stop: + for s in ([stop] if isinstance(stop, str) else stop): + k = text.find(s, len(prefix)) + if k >= 0: + text = text[:k] + stopped_by_str = True + + if tools: + content, tool_calls = parse_tool_calls(text) + if tool_calls and req.get("parallel_tool_calls") is False: + tool_calls = tool_calls[:1] + else: + content, tool_calls = (text.strip() or None), [] + + if tool_calls: + finish = "tool_calls" + elif hit_eos or stopped_by_str: + finish = "stop" + else: + finish = "length" + message = {"role": "assistant", "content": content} + if tool_calls: + message["tool_calls"] = tool_calls + usage = {"prompt_tokens": n_prompt, "completion_tokens": n_completion, + "total_tokens": n_prompt + n_completion} + return message, finish, usage, len(images), text + + +# ---------------------------------------------------------------------------- +# HTTP +# ---------------------------------------------------------------------------- +ENGINE: Engine | None = None +ARGS = None + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, fmt, *args): # route http.server logs through logging + LOG.debug("%s - %s", self.address_string(), fmt % args) + + def _send_json(self, code: int, obj): + body = json.dumps(obj, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _error(self, code: int, msg: str, etype: str): + self._send_json(code, {"error": {"message": msg, "type": etype, "code": code}}) + + def do_GET(self): + if self.path.rstrip("/") in ("/health", "/v1/health"): + self._send_json(200, {"status": "ok", "model": ARGS.served_name, "memory": ENGINE.mem(), + "load_time_s": round(ENGINE.load_time, 1)}) + elif self.path.rstrip("/") == "/v1/models": + self._send_json(200, {"object": "list", "data": [ + {"id": ARGS.served_name, "object": "model", "created": int(time.time()), "owned_by": "local"}]}) + else: + self._error(404, f"no route {self.path}", "not_found") + + def do_POST(self): + if self.path.rstrip("/") not in ("/v1/chat/completions", "/chat/completions"): + self._error(404, f"no route {self.path}", "not_found") + return + try: + n = int(self.headers.get("Content-Length", "0")) + req = json.loads(self.rfile.read(n).decode("utf-8")) + except Exception as e: # noqa: BLE001 + self._error(400, f"invalid JSON body: {e}", "invalid_request_error") + return + t0 = time.time() + try: + with ENGINE.lock: + t_lock = time.time() + message, finish, usage, n_img, raw = ENGINE.chat(req) + except BadRequest as e: + self._error(400, str(e), "invalid_request_error") + return + except Exception as e: # noqa: BLE001 + LOG.error("generation failed: %s\n%s", e, traceback.format_exc()) + if "out of memory" in str(e).lower(): + try: + ENGINE.torch.cuda.empty_cache() + except Exception: # noqa: BLE001 + pass + self._error(500, f"{type(e).__name__}: {e}", "server_error") + return + dt = time.time() - t0 + LOG.info("req images=%d prompt=%d completion=%d finish=%s tool_calls=%d queue=%.2fs gen=%.2fs mem=%s", + n_img, usage["prompt_tokens"], usage["completion_tokens"], finish, + len(message.get("tool_calls", [])), t_lock - t0, time.time() - t_lock, ENGINE.mem()) + if ARGS.log_outputs: + LOG.info("raw output: %r", raw) + cid = "chatcmpl-" + uuid.uuid4().hex[:24] + created = int(time.time()) + model_name = req.get("model") or ARGS.served_name + if req.get("stream"): + self._send_stream(cid, created, model_name, message, finish, usage, req) + return + self._send_json(200, { + "id": cid, + "object": "chat.completion", + "created": created, + "model": model_name, + "choices": [{"index": 0, "message": message, "finish_reason": finish, "logprobs": None}], + "usage": usage, + "server_timing": {"latency_s": round(dt, 3)}, + }) + + def _send_stream(self, cid, created, model_name, message, finish, usage, req): + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Cache-Control", "no-cache") + self.send_header("Connection", "close") + self.end_headers() + self.close_connection = True + + def chunk(delta, fr=None, with_usage=False): + obj = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name, + "choices": [{"index": 0, "delta": delta, "finish_reason": fr, "logprobs": None}]} + if with_usage: + obj["usage"] = usage + self.wfile.write(b"data: " + json.dumps(obj, ensure_ascii=False).encode() + b"\n\n") + + chunk({"role": "assistant", "content": message.get("content") or ""}) + for i, tc in enumerate(message.get("tool_calls", [])): + chunk({"tool_calls": [dict(tc, index=i)]}) + include_usage = bool((req.get("stream_options") or {}).get("include_usage")) + chunk({}, finish, with_usage=include_usage) + self.wfile.write(b"data: [DONE]\n\n") + self.wfile.flush() + + +def main(): + global ENGINE, ARGS + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--model", default=os.environ.get("QWEN_VL_MODEL", "Qwen/Qwen3-VL-8B-Instruct")) + p.add_argument("--served-name", default="Qwen3-VL-8B-Instruct") + p.add_argument("--host", default="127.0.0.1") + p.add_argument("--port", type=int, default=8765) + p.add_argument("--device", default="cuda:0") + p.add_argument("--attn", default="sdpa", choices=["sdpa", "eager", "flash_attention_2"]) + p.add_argument("--sdpa-native-gqa", action="store_true", + help="let torch SDPA do GQA (enable_gqa=True); broken on PPU for decode, off by default") + p.add_argument("--default-max-tokens", type=int, default=1024) + p.add_argument("--max-tokens-cap", type=int, default=8192) + p.add_argument("--max-prompt-tokens", type=int, default=65536) + p.add_argument("--default-temperature", type=float, default=0.0, + help="used when the request has no temperature; 0 = greedy") + p.add_argument("--min-pixels", type=int, default=0, help="override image processor min_pixels") + p.add_argument("--max-pixels", type=int, default=0, help="override image processor max_pixels") + p.add_argument("--log-outputs", action="store_true", help="log raw model output text per request") + p.add_argument("--warmup", action="store_true", help="run one tiny generation before serving") + ARGS = p.parse_args() + + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout) + import transformers + + LOG.info("transformers %s from %s", transformers.__version__, os.path.dirname(transformers.__file__)) + ENGINE = Engine(ARGS) + if ARGS.warmup: + t = time.time() + with ENGINE.lock: + ENGINE.chat({"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 4}) + LOG.info("warmup done in %.1fs", time.time() - t) + srv = ThreadingHTTPServer((ARGS.host, ARGS.port), Handler) + srv.daemon_threads = True + LOG.info("serving %s on http://%s:%d/v1/chat/completions", ARGS.served_name, ARGS.host, ARGS.port) + try: + srv.serve_forever() + except KeyboardInterrupt: + pass + finally: + srv.server_close() + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/record_breakfast_service.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/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_gpt/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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/summarize.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/summarize.py new file mode 100644 index 0000000000000000000000000000000000000000..5ceda683353fb938c1e8a219552c088181c197c2 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/summarize.py @@ -0,0 +1,33 @@ +"""Aggregate results//validate.json into results/SUMMARY.md (headroom table).""" +import glob +import json +import os + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +def main(): + rows = [] + for p in sorted(glob.glob(os.path.join(ROOT, "results", "*", "validate.json"))): + r = json.load(open(p)) + s = r["succ_at_k"] + + def g(kind, j): + v = s.get(kind) + return "—" if v is None else f"{100 * v[j - 1]:.0f}" + + k = r["k"] + rows.append(f"| {r['task']} | {r['level']} | {', '.join(r['capabilities'])} | {r['n']} | " + f"{g('oracle', 1)} | {g('naive', 1)} | {g('adaptive', 1)} / {g('adaptive', 2)} / {g('adaptive', k)} | " + f"{g('blind', k)} | {r.get('seconds', 0) / 60:.0f} min |") + head = ("| task | level | capabilities | n | oracle@1 | naive@1 | adaptive @1/@2/@k | blind@k | wall |\n" + "|---|---|---|---|---|---|---|---|---|") + text = "# LFF-Bench headroom validation (scripted reference policies)\n\n" + head + "\n" + "\n".join(rows) + "\n" + out = os.path.join(ROOT, "results", "SUMMARY.md") + with open(out, "w") as f: + f.write(text) + print(text) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/images.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/images.py new file mode 100644 index 0000000000000000000000000000000000000000..b1d89bbfa64e5913756c7b7920491d36805b7839 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/images.py @@ -0,0 +1,47 @@ +"""Image references and encoding (JPEG bytes are what the model sees and what is saved to disk).""" +import base64 +import io +from dataclasses import dataclass +from typing import Any, Optional + +import numpy as np + + +@dataclass +class ImageRef: + camera: str # agent-facing camera name ("agentview" / "wrist") + array: Any = None # uint8 HxWx3 + label: str = "" + path: Optional[str] = None # where the encoded image was saved + jpeg: Optional[bytes] = None # encoded bytes actually sent to the model + + def encoded(self, quality=90): + if self.jpeg is None: + if self.array is None and self.path: + with open(self.path, "rb") as f: + self.jpeg = f.read() + else: + self.jpeg = encode_jpeg(self.array, quality) + return self.jpeg + + def data_url(self, quality=90): + return "data:image/jpeg;base64," + base64.b64encode(self.encoded(quality)).decode("ascii") + + @property + def size(self): + return None if self.array is None else tuple(np.asarray(self.array).shape[:2]) + + +def encode_jpeg(arr, quality=90): + from PIL import Image + buf = io.BytesIO() + Image.fromarray(np.asarray(arr, dtype=np.uint8)).save(buf, format="JPEG", quality=int(quality)) + return buf.getvalue() + + +def resize(arr, res): + from PIL import Image + arr = np.asarray(arr, dtype=np.uint8) + if arr.shape[0] == res and arr.shape[1] == res: + return arr + return np.asarray(Image.fromarray(arr).resize((res, res), Image.BILINEAR)) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/tools.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..51e4a2a2feaa238548d752308aca541e6ad416fb --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/tools.py @@ -0,0 +1,392 @@ +"""Agent-facing tool interface on top of `Skills`. + +Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps +acting on every commanded position. Proprioception is reported in the robot's own (possibly +miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the +commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and +the privileged `locate` tool are in the true world frame. + +Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in +`required`, optional ones nullable, no additional properties). +""" +import json +import math +import time +from dataclasses import dataclass, field + +import numpy as np + +from .. import envs +from . import camera as C +from .images import ImageRef + +TABLE_Z = envs.TABLE_Z +# Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are +# clipped and the report says so. +WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005]) +WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50]) +SPEED_RANGE = (0.02, 1.0) +PUSH_DIST_RANGE = (0.0, 0.40) +RUNUP_RANGE = (0.02, 0.30) + +ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push") + + +def _num(desc): + return {"type": "number", "description": desc} + + +def _opt_num(desc): + return {"type": ["number", "null"], "description": desc} + + +def _fn(name, desc, props=None): + props = props or {} + return dict(name=name, description=desc, + parameters={"type": "object", "properties": props, "required": list(props), + "additionalProperties": False}) + + +def tool_specs(privileged_locate=False, object_names=None, image_res=512): + """Backend-neutral tool list: [{name, description, parameters}].""" + specs = [ + _fn("move_to", + "Move the gripper's grasp point (midway between the fingertips) in a straight line to the world " + "position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper " + "opening is not changed. Returns whether the target was reached, the end-effector position, gripper " + "width, whether an object is held and whether the arm touched an object during the motion.", + {"x": _num("target x, metres (world frame; +x away from the robot)"), + "y": _num("target y, metres (world frame; +y to the robot's left)"), + "z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"), + "yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world " + "y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger " + "gripper is symmetric): the controller uses the equivalent angle closest to the current " + "yaw within +-113 deg; the report gives the yaw actually used"), + "speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows " + "(about 0.6 m/s)")}), + _fn("open_gripper", "Open the gripper fully (the arm holds its position)."), + _fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."), + _fn("push", + "Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres " + "behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) " + "through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The " + "gripper is rotated automatically to a fixed orientation relative to the push direction.", + {"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"), + "y": _num("y of that point, m"), + "dir_x": _num("x component of the push direction (normalised internally)"), + "dir_y": _num("y component of the push direction"), + "distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"), + "speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"), + "z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} " + "(2 cm above the table)"), + "runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer " + "run-up lets the gripper reach the commanded speed before contact.")}), + _fn("get_observation", + "Return the current camera images (agentview and wrist) and the robot's proprioceptive state."), + _fn("pixel_to_world", + f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel " + f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the " + f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that " + f"pixel and its height above the table.", + {"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"}, + "u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}), + _fn("done", + "Finish the current attempt. Call this when you believe the task is complete (or you want to stop). " + "Give a short reason: what you did and whether you think it worked.", + {"reason": {"type": "string", "description": "short explanation"}}), + ] + if privileged_locate: + names = list(object_names or []) + prop = {"type": "string", "description": "object name"} + if names: + prop["enum"] = names + specs.insert(-1, _fn("locate", + "PRIVILEGED (ablation): return the true world position of an object's origin and its " + "axis-aligned bounding box.", {"object_name": prop})) + return specs + + +@dataclass +class ToolResult: + name: str + args: dict + ok: bool + report: dict + images: list = field(default_factory=list) + ended: bool = False + wall_s: float = 0.0 + sim_steps: int = 0 + + def text(self): + return json.dumps(self.report, separators=(", ", ": "), default=_json_default) + + +def _json_default(o): + if isinstance(o, (np.floating,)): + return float(o) + if isinstance(o, (np.integer,)): + return int(o) + if isinstance(o, np.ndarray): + return o.tolist() + if isinstance(o, (np.bool_,)): + return bool(o) + raise TypeError(type(o)) + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class ContactTracker: + """Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control + step is 25 substeps; a fast push touches the object for less than one control step, so checking only at + control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the + wrapper only reads contacts and dispatches to the currently active tracker.""" + + def __init__(self, env): + self.env = env + m = env.sim.model + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.names = [] + self.obj_of = np.full(m.ngeom, -1, int) + for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}): + try: + ids = envs.obj_geom_ids(env, name) + except Exception: # fixtures without contact geoms + continue + self.obj_of[ids] = len(self.names) + self.names.append(name) + self.touched = set() + sim = env.sim + if not getattr(sim, "_lff_step_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lff_tracker", None) + if t is not None: + t.check() + sim.step = step + sim._lff_step_wrapped = True + sim._lff_tracker = self + + def reset(self): + self.touched = set() + + def check(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] + hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]]) + for i in set(hit[hit >= 0].tolist()): + self.touched.add(self.names[i]) + + +def parse_args(raw): + if raw is None: + return {} + if isinstance(raw, dict): + return dict(raw) + raw = raw.strip() + return json.loads(raw) if raw else {} + + +class ToolExecutor: + """Executes agent tool calls on a task whose instance has just been reset (task.sk is live).""" + + def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False, + grasp_report="bool", jpeg_quality=90, image_sink=None): + self.task = task + self.inst = inst + self.env = task.env + self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy + self.image_res = int(image_res) + self.cams = tuple(cams) + self.privileged_locate = privileged_locate + self.grasp_report = grasp_report # "bool" | "name" | "none" + self.jpeg_quality = jpeg_quality + self.image_sink = image_sink # callable(ImageRef) -> path (saves the image) + self.objects = list(self.env.objects_dict) + self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched + self._depth_cache = {} + self.n_calls = 0 + + # ------------------------------------------------------------------ state + def eef_yaw_deg(self): + R = self.sk.eef_mat() @ self.sk.R0.T + return math.degrees(math.atan2(R[1, 0], R[0, 0])) + + def held(self): + names = [o for o in self.objects if self.sk.holding(o)] + return names + + def _holding_field(self, names): + if self.grasp_report == "name": + return names[0] if names else None + if self.grasp_report == "none": + return None + return bool(names) + + def proprio(self): + believed = self.sk.eef_pos() - self.sk.bias + p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1), + gripper="closed" if self.sk.grip > 0 else "open", + gripper_width_m=round(self.sk.gripper_width(), 4)) + if self.grasp_report != "none": + p["holding_object"] = self._holding_field(self.held()) + return p + + def render(self, cam, res=None): + res = res or self.image_res + return envs.render(self.env, C.mj_cam(cam), res) + + def observe(self, label=""): + imgs = [] + for cam in self.cams: + ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip()) + if self.image_sink is not None: + self.image_sink(ref) + imgs.append(ref) + self._depth_cache = {} + return imgs + + # ------------------------------------------------------------------ dispatch + def call(self, name, raw_args): + t0 = time.time() + n0 = self.sk.n_steps + self.n_calls += 1 + try: + args = parse_args(raw_args) + except Exception as e: + return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"), + wall_s=time.time() - t0) + fn = getattr(self, f"_t_{name}", None) + if fn is None or (name == "locate" and not self.privileged_locate): + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + try: + res = fn(**args) + except TypeError as e: + res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}")) + except ValueError as e: + res = ToolResult(name, args, False, dict(ok=False, error=str(e))) + res.args = args + res.wall_s = time.time() - t0 + res.sim_steps = self.sk.n_steps - n0 + if res.sim_steps: + self._depth_cache = {} + hook = getattr(self.task, "on_agent_tool", None) + if hook is not None: + hook(self.inst, name, args, res.report) + drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped) + if drain is not None: + ev = drain() + if ev: + res.report["events"] = list(ev) + return res + + # ------------------------------------------------------------------ helpers + def _clip_xyz(self, xyz): + xyz = np.asarray(xyz, float) + if not np.all(np.isfinite(xyz)): + raise ValueError("non-finite coordinates") + c = np.clip(xyz, WS_LO, WS_HI) + return c, (None if np.allclose(c, xyz) else _r(c)) + + @staticmethod + def _clip(v, lo_hi, what): + v = float(v) + if not math.isfinite(v): + raise ValueError(f"{what} must be finite") + return float(np.clip(v, *lo_hi)) + + def _action_report(self, name, extra=None): + names = self.held() + rep = dict(ok=True, tool=name) + if extra: + rep.update(extra) + rep.update(self.proprio()) + if self.grasp_report == "name": + rep["touched_objects"] = sorted(self.tracker.touched) + elif self.grasp_report == "bool": + rep["touched_object"] = bool(self.tracker.touched) + rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2) + return rep + + # ------------------------------------------------------------------ tools + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt, clipped = self._clip_xyz([x, y, z]) + spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed") + self.tracker.reset() + rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi + extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1)) + if clipped: + extra["target_clipped_to"] = clipped + return ToolResult("move_to", {}, True, self._action_report("move_to", extra)) + + def _t_open_gripper(self): + self.tracker.reset() + self.sk.set_gripper(False) + return ToolResult("open_gripper", {}, True, self._action_report("open_gripper")) + + def _t_close_gripper(self): + self.tracker.reset() + self.sk.set_gripper(True) + return ToolResult("close_gripper", {}, True, self._action_report("close_gripper")) + + def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None): + d = np.array([float(dir_x), float(dir_y)]) + if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6: + raise ValueError("push direction must be a non-zero vector") + start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z]) + dist = self._clip(distance, PUSH_DIST_RANGE, "distance") + spd = self._clip(speed, SPEED_RANGE, "speed") + pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup") + self.tracker.reset() + rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre) + extra = dict(sweep_reached=bool(rep["reached"])) + if clipped: + extra["start_clipped_to"] = clipped + return ToolResult("push", {}, True, self._action_report("push", extra)) + + def _t_get_observation(self): + imgs = self.observe(label="requested") + return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()), + images=imgs) + + def _t_pixel_to_world(self, camera, u, v): + cam = str(camera) + if cam not in C.CAMERAS: + raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}") + if cam not in self._depth_cache: + self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res) + r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam]) + rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]), + height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4)) + if not r["valid"]: + rep["warning"] = "pixel shows the far background; the point is unreliable" + return ToolResult("pixel_to_world", {}, True, rep) + + def _t_locate(self, object_name): + if object_name not in self.env.objects_dict: + raise ValueError(f"unknown object {object_name!r}; known: {self.objects}") + lo, hi = self._aabb(object_name) + p = envs.obj_pos(self.env, object_name) + return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo), + bbox_max=_r(hi))) + + 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] + h = np.abs(R) @ m.geom_aabb[g, 3:] + lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h) + return lo, hi + + def _t_done(self, reason=""): + return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True) diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/base.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/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_opus/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_opus/lff/source_closure/lffbench/harnesses/codex.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/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_opus/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_opus/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..2d09a5b6233607bf6538692ac28f560bd8aeba66 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-flash|high", + "fingerprint_sha256": "18044f5deb7b4d0d662d620fce120e85e3f94103fa2699346221fa46d093fc8f", + "written": "2026-10-31 06:05:50", + "summary": { + "system_chars": 109, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..7a1c73ecae20ed503d7144d363aa4747887b4d34 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-chatgpt-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,18 @@ +{ + "key": "sensenova_codex-chatgpt-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9", + "written": "2026-10-26 07:08:06", + "summary": { + "report": "/mnt/cpfs/workspace/agentic-robotics/reports/robot_harness_subscription_resume_20261026/selfcheck_verified/selfcheck.json", + "checks": 10, + "framework": { + "commit": "b513a1c7289ab11eb844856588b64c378705c405", + "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823", + "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350", + "untracked": [ + "lff_integration/__init__.py", + "lff_integration/run.py" + ] + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/redteam.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/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_opus/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_opus/lff/source_closure/lffbench/tasks/l5_slide.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l5_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee239b7ba2793288aeaaa5e5d4f0a5b11c835f5 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l5_slide.py @@ -0,0 +1,577 @@ +"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone. + +Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the +same for every mu. With the default push speed the cube overshoots on slippery instances and stops +short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard +to push next time (cf. MemMimic push_cube, iterative pushing). + +Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt +(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that +carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule +also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The +loophole is now closed by the success rule instead: + +Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there +by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts +checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with +nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push +into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in +front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm. + +Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged +when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside). +`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then +succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the +arm's reach (the attempt is not ended for it). + +Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance +the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre). +SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX), +so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time. + +Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview +camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far +edge by up to ~1 cm covers the far green line but shows < 2 px of red beyond it in the 512 x 512 image, which looks like +"inside / on the line" (self-test: 0.8 cm past the inner edge looked inside). So on the far side the cube may now lie on +the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to +TOL_PAST = 2.0 cm past the square's centre (front face <= 4 mm beyond the line's outer edge). From 2.0 cm on, every one +of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely +inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides +the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +CUBE = "cube_1" +CUBE_HALF = 0.02 +D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long +STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike +TOUCH_MOVE = 0.001 # a contact episode moved the cube if the cube ends >= 1 mm (3-D) from where it was at its start +EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode +V_REST, W_REST = 0.003, 0.05 # cube at rest: linear speed below 3 mm/s and angular speed below 0.05 rad/s ... +REST_SUB = 25 # ... for 25 consecutive substeps (50 ms) +WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest +ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF +OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table +REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable + + +class CubeWatch: + """Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it). + + contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed + EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was + when the episode began, or still moving. + release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide + began (None while the robot has never moved the cube). + strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to + rest (or when the robot touches it again before that: result "interrupted").""" + + def __init__(self, env, target_xy, tol_short, tol_past, tol_across): + m = env.sim.model + self.env = env + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.is_cube = np.zeros(m.ngeom, bool) + self.is_cube[envs.obj_geom_ids(env, CUBE)] = True + self.qa, self.da = envs.free_joint_addr(env, CUBE) + self.target = np.asarray(target_xy, float) + self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside + self.n_sub = 0 + self.ep = None # open contact episode + self.gap = 0 + self.quiet = 0 # consecutive substeps at rest + self.release = None + self.slide = None # free slide in progress: where it started (cube at the episode start) and was released + self.moves = [] # closed contact episodes that moved the cube + self.strikes = [] + + # ------------------------------------------------------------ state + def pos(self): + return self.env.sim.data.qpos[self.qa:self.qa + 3].copy() + + def at_rest(self): + qv = self.env.sim.data.qvel[self.da:self.da + 6] + return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST) + + def judge(self, p): + """Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off). + in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it.""" + along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1]) + if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE: + return along, across, "off" + short, past, beside = self.tol + if -short <= along <= past and abs(across) <= beside: + return along, across, "in" + if along > past: + return along, across, "past" + if along < -short: + return along, across, "short" + return along, across, "beside" + + # ------------------------------------------------------------ per substep + def substep(self): + d = self.env.sim.data + n = d.ncon + touch = False + if n: + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1]))) + self.n_sub += 1 + p = self.pos() + rest = self.at_rest() + self.quiet = self.quiet + 1 if rest else 0 + if touch: + if self.ep is None: + if self.slide is not None: + self._end_slide(p, interrupted=not rest) + self.ep = dict(start=p, sub0=self.n_sub) + self.ep["last"] = p + self.ep["sub1"] = self.n_sub + self.gap = 0 + elif self.ep is not None: + self.gap += 1 + if self.gap >= EP_GAP: + self._close(p, rest) + if self.ep is None and self.slide is not None and self.quiet >= REST_SUB: + self._end_slide(p, interrupted=False) + + def _close(self, p, rest): + ep, self.ep = self.ep, None + if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest: + return # touched a resting cube and left it where it was + self.release = ep["last"][:2].copy() + self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(), + release=ep["last"].round(4).tolist())) + self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"]) + + def _end_slide(self, p, interrupted): + s, self.slide = self.slide, None + free = float(np.linalg.norm(p[:2] - s["release"][:2])) + if free < STRIKE_MIN: + return # a push or a put-down, not a strike + along, across, res = self.judge(p) + self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(), + release=s["release"].round(4).tolist(), rest=p.round(4).tolist(), + pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2), + free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2), + across_err_cm=round(100 * across, 2), + result="interrupted" if interrupted else res, + missed=bool(not interrupted and res != "in"))) + + def flush(self): + """End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact + has moved it (then the cube's current free slide is 0).""" + p = self.pos() + if self.ep is not None: + if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest(): + self.release = p[:2].copy() + self.slide = None + return True + return False + if self.slide is not None and self.at_rest(): + self._end_slide(p, interrupted=False) + return False + + +def _install_watch(sim, watch): + """Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker; + it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one + control step, so contact checks at control steps alone would miss it.""" + if not getattr(sim, "_lff_slide_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + w = getattr(sim, "_lff_slide_watch", None) + if w is not None: + w.substep() + sim.step = step + sim._lff_slide_wrapped = True + sim._lff_slide_watch = watch + + +class SlideSkills(Skills): + """Skills whose motion commands return only once the cube has come to rest (see the module docstring).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self._qa, self._da = envs.free_joint_addr(env, CUBE) + self.waits = [] # (control step, steps waited) for every command that had to wait + + def cube_moving(self): + qv = self.env.sim.data.qvel[self._da:self._da + 6] + return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST) + + def wait_cube_rest(self): + """Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed. + No wait if the cube is already at rest or is held (it then moves with the arm).""" + if not self.cube_moving() or self.holding(CUBE): + return 0 + p, R = self.eef_pos(), self._R() + quiet = 0 + for k in range(WAIT_MAX): + self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + quiet = 0 if self.cube_moving() else quiet + 1 + if quiet >= 2: + break + self.waits.append((self.n_steps, k + 1)) + return k + 1 + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + +INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm +LINE_W = 0.006 +# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of +# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre +# <= 2.0 cm past it, i.e. the front face up to 4 mm beyond the line, which in the 512 x 512 agentview is < 2 px of red +# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19). +TOL_PAST = 0.020 + + +def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W, + line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions).""" + o = inner_half + line_w + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba), + ((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba), + ((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(model_name, g, 0.0012, o) + + +Z_PUSH = envs.TABLE_Z + 0.02 +V_MIN, V_MAX = 0.12, 0.60 +Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table) + + +@register_task +class SlideToTarget(LFFTask): + name = "l5_slide_to_target" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Reason", "Utilize") + # no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there) + instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green " + "square marked on the table. On the side of the square nearest the robot and on its left and " + "right, no part of the cube may lie on or beyond the green border line. On the far side, away from " + "the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. " + "The cube must slide the last part of the way on its own: after it leaves the gripper it has to " + f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the " + "square.") + instruction_indirect = instruction + tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm) + tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST) + runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact + tol_across = INNER_HALF - CUBE_HALF + + def make_bddl(self): + cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1), + density=1000)) + # static fixture (no joint): a free body without collisions would fall through the table + zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False) + objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))] + fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, self.instruction, objs, fixtures=fixtures) + + def apply_instance(self, inst): + m = self.env.sim.model + zone = self.env.fixtures_dict["zone_1"] + # the target zone is a flat marker: no collisions + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("zone_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + x0, y0 = inst["cube_xy"] + envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001]) + bid = m.body_name2id(zone.root_body) + m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + envs.set_friction(self.env, "cube_1", inst["mu"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + x0, y0 = inst["cube_xy"] + self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past, + self.tol_across) + _install_watch(self.env.sim, self.watch) + self.sk = SlideSkills(self.env, recorder=recorder) + return self.sk + + @staticmethod + def max_reach(mu): + """Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m): + mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm.""" + return 0.0103 / mu ** 0.95 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: # reject instances the top speed cannot reach (keeps every instance solvable) + inst = dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))], + target_dist=float(rng.uniform(0.05, 0.12)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10))))) + if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]): + return inst + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 40) + w = self.watch + for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest + if w.at_rest(): + break + envs.settle(self.env, 5) + touching = w.flush() + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, CUBE) + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + _, _, where = w.judge(w.pos()) + inside = where == "in" + at_rest = w.at_rest() + free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0 + slid = bool(w.release is not None and not touching and free >= D_MIN) + success = bool(inside and at_rest and slid) + strikes = w.strikes + n_missed = sum(s["missed"] for s in strikes) + from ..agent.tools import WS_HI, WS_LO + reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN)) + irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach) + + parts = [] + if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN: + parts.append("The cube was not pushed.") + if c[2] < OFF_TABLE_Z: + parts.append("The cube fell off the table.") + else: + state = {"in": "in the square", "past": "it sticks out beyond the far green line", + "short": "it sticks out past the edge of the square nearest the robot"}.get(where, + "not in the square") + if along > 0: + parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).") + else: + parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square " + f"({state}).") + if abs(across) > self.tol_across: + parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} " + f"(robot's view).") + if where == "off" and c[2] > OFF_TABLE_Z: + parts.append("It is not resting on the table.") + if inside and not at_rest: + parts.append("It was still moving when the attempt ended.") + if touching: + parts.append("The gripper was still touching (or holding) the cube when the attempt ended.") + elif inside and w.release is not None and free < D_MIN: + parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide " + f"at least {100 * D_MIN:.0f} cm.") + if success: + failure = None + elif w.release is None and not inside: + failure = "not_touched" + elif not inside: + failure = "position" + elif not at_rest: + failure = "not_at_rest" + else: + failure = "slide_too_short" + out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts), + inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2), + release_xy=None if w.release is None else w.release.round(4).tolist(), + touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes), + n_missed_strikes=int(n_missed), trap_fired=n_missed > 0, + recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable, + strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure) + return out + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the + point of contact, lift (the move returns once the cube has come to rest).""" + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.set_gripper(True, steps=5) + sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), + tol=0.01, max_steps=80) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3) + + def default_params(self, inst): + return dict(speed=0.30) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search + on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt).""" + pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history) + lo = [p for p in pts if p[1] < 0] + hi = [p for p in pts if p[1] > 0] + if lo and hi: + (v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0]) + v = v0 + (v1 - v0) * (-e0) / (e1 - e0) + elif hi: # always overshooting: slow down + v = min(p[0] for p in hi) * 0.7 + else: # always short: speed up + v = max(p[0] for p in lo) * 1.35 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on speed by simulating pushes (uses the true mu).""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(9): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + e = self.outcome(inst)["along_err"] + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + hi = mid + else: + lo = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) + + # ------------------------------------------------------------ scripted within-attempt correction + AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ... + AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command + RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short + + def _strike_here(self, speed): + """Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up + point + close, down, strike (returns at rest), lift.""" + c = envs.obj_pos(self.env, CUBE) + sk = self.sk + sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0) + sk.set_gripper(True, steps=5) + sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3) + return 4 + + def _carry_back(self, inst): + """Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands: + above it + open, down + close, lift, carry, down + open, lift.""" + c = envs.obj_pos(self.env, CUBE) + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0) + sk.set_gripper(False, steps=10) + sk.move_to([c[0], c[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([c[0], c[1], Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([x0, y0, Z_GRASP + 0.10]) + return 6 + + @staticmethod + def _plan_speed(want, pts): + """Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s + prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes + (or extrapolation from the two nearest, exponent clipped to [0.5, 3]).""" + pts = sorted((v, d) for v, d in pts if d > 0.002) + if not pts: + return 0.30 + if len(pts) == 1: + v, d = pts[0] + return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX)) + lo = [p for p in pts if p[1] <= want] + hi = [p for p in pts if p[1] > want] + if lo and hi: + (v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1]) + else: + (v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2] + if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6: + return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX)) + k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0)) + return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX)) + + def _adaptive_attempt(self, inst, pts): + """One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect + perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot, + a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed + planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square + or the next correction would not fit in the agent's command / motion budget.""" + x0, y0 = inst["cube_xy"] + tx = x0 + inst["target_dist"] + sk = self.sk + n0 = sk.n_steps + n_cmd, speeds, path = 0, [], [] + while True: + c = envs.obj_pos(self.env, CUBE) + want = tx - c[0] + near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01 + local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts] + speed = self._plan_speed(want, local) + n_cmd += self._strike_here(speed) + c1 = envs.obj_pos(self.env, CUBE) + pts.append((speed, float(c1[0] - c[0]), near_start)) + speeds.append(round(speed, 4)) + err, across = float(c1[0] - tx), float(c1[1] - y0) + path.append("strike") + if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across: + break + used_s = (sk.n_steps - n0) * DT + if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005: + if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S: + break + continue + if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S: + break + n_cmd += self._carry_back(inst) + path.append("carry_back") + return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd, + sim_s=round((sk.n_steps - n0) * DT, 1)) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects + within the attempt (_adaptive_attempt) and carries what it saw into the next attempt.""" + if kind != "adaptive": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + history, pts = [], [] + for a in range(k): + self.reset_instance(inst) + params = self._adaptive_attempt(inst, pts) + 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 diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_sequence.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..3696302999af83efd1782ea6326db1f794452022 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_sequence.py @@ -0,0 +1,513 @@ +"""L6-C sequence_resume: weigh four items one by one in a given order; an emergency stop resets part of the work. + +Scene: four grocery items (cream cheese, butter, chocolate pudding, popcorn -- small flat boxes), each on its +own round pad (four identical dark pads, flat markers), and a scale (grey square platform, static fixture). +Pad / scale positions and the order are random per instance. + +Instruction: weigh the items one at a time in the given order. Weighing = put the item on the scale and let go; +the scale records a reading after the item has rested on it for 0.5 s and beeps. Then the item goes back on its +own pad before the next item is picked up. Every item must be weighed exactly once; the scale log cannot be +edited, so a second reading of an item or a reading out of turn is a terminal failure. + +Interruption ("emergency stop", once per episode, inside attempt 1): while the robot carries an item, the gripper +opens, a safety routine puts that item back on its own pad and the arm returns to its home pose. Hidden: how +many items had been weighed when it happened, w in {1..4} (uniform), and the phase: the carried item was on its +way to the scale (not yet weighed, phase A) or on its way back (already weighed, phase B); w = 4 is always +phase B. After the stop every item sits on its pad and the arm is at home: the picture looks like the start of +the task. Which item comes next (order[w], or "nothing, call done" for w = 4) is only in the agent's own history +(what it carried, whether the scale had beeped). + +Protocol: within (like l6_swap_interrupt). Events reported immediately (`drain_events`): the scale's beep after +every recorded reading, an error beep for a reading out of turn, and the emergency stop. F2 after `done` gives the +verdict, whether the log is complete, and which items are not on their pads (distance only), never how many +items have been weighed. + +Scripted references (perception = simulator state): + oracle privileged scale log: always weighs order[len(log)] next. + adaptive keeps its own record of readings (an item counts as weighed when the scale beeped while it lay on + it); after the stop it resumes from order[len(record)] (redoes the interrupted item in phase A, goes on + with the next one in phase B, calls done when all four are recorded). + naive memoryless continuation (1 attempt): the picture after the stop shows no progress; it guesses how far + it got (uniform over 0..4 items weighed) and continues from there. + blind memoryless restart (k attempts): starts the sequence over from the first item -> a second reading of + an already weighed item (repeated step). +Extra control (not in the acceptance table): `skip` counts items it *started* to weigh (pick-ups) instead of +readings: correct after a phase-B stop, skips the interrupted item after a phase-A stop. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, register_generated +from ..skills import ROT_SCALE, _rot_err +from ..task_base import LFFTask, register_task +from .l6_swap import _pad_xml as _swap_pad_xml + +ITEMS = ["cream_cheese_1", "butter_1", "chocolate_pudding_1", "popcorn_1"] +CATS = {"cream_cheese_1": "cream_cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate_pudding", + "popcorn_1": "popcorn"} +NAME = {"cream_cheese_1": "cream cheese", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + "popcorn_1": "popcorn"} +DESCR = {"cream_cheese_1": "the pale blue box with the oval logo", "butter_1": "the red box with white lettering", + "chocolate_pudding_1": "the dark brown box", "popcorn_1": "the blue-and-yellow box"} +N_ITEMS = len(ITEMS) +PADS = [f"pad_{i + 1}" for i in range(N_ITEMS)] +PAD_R = 0.055 +PAD_HALF_T = 0.0008 + +SCALE_HALF = 0.06 # platform half size (12 x 12 cm) +SCALE_BASE_HALF = 0.067 +SCALE_TOP = 0.020 # platform top above the table +SCALE_BASE_H = 0.012 +SCALE_RGBA = (0.78, 0.79, 0.80, 1.0) +SCALE_BASE_RGBA = (0.20, 0.20, 0.22, 1.0) + +BASE_X = -0.66 +REGION = (-0.27, 0.05, -0.27, 0.27) +REACH = 0.70 +PAD_MIN = 0.16 +SCALE_MIN = 0.175 +SUCC_R = 0.04 # item centre within 4 cm of its pad centre +GRASP_DZ = 0.012 # gripper-site height above the support surface for a top-down grasp of the flat boxes +Z_CARRY = envs.TABLE_Z + 0.15 +DWELL = 10 # control steps (0.5 s) at rest on the scale before a reading is recorded +LIFTED = 0.04 + + +def scale_xml(model_name): + parts = [((0, 0, SCALE_BASE_H / 2), (SCALE_BASE_HALF, SCALE_BASE_HALF, SCALE_BASE_H / 2), SCALE_BASE_RGBA), + ((0, 0, (SCALE_BASE_H + SCALE_TOP) / 2), (SCALE_HALF, SCALE_HALF, (SCALE_TOP - SCALE_BASE_H) / 2), + SCALE_RGBA)] + g = [] + for k, (pos, half, rgba) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return _wrap(model_name, "\n".join(g), SCALE_TOP / 2, float(np.hypot(SCALE_BASE_HALF, SCALE_BASE_HALF))) + + +def _yaw_of(env, obj): + R = env.sim.data.body_xmat[envs.body_id(env, obj)].reshape(3, 3) + yaw = float(np.arctan2(R[1, 0], R[0, 0])) # long axis of the boxes = body x + return (yaw + np.pi / 2) % np.pi - np.pi / 2 + + +@register_task +class SequenceResume(LFFTask): + name = "l6_sequence_resume" + level = "L6" + category = "procedural_memory" + capabilities = ("Perceive", "Save", "Retrieve", "Utilize") + protocol = "within" + agent_max_steps = 100 # robot commands per attempt for agents (a VLM needs ~60-75) + max_attempts = 5 + _TEMPLATE = ("Weigh the four grocery items one at a time, in this order: {order}. To weigh an item, put it on " + "the grey scale and let go of it; the scale beeps when it has recorded the reading. Then put the " + "item back on its own round pad before you pick up the next item. Weigh every item exactly once: " + "the scale logs every reading, and the log cannot be edited.") + instruction = _TEMPLATE.format(order="(given per instance)") + instruction_indirect = instruction + inject = True + agent_object_names = [NAME[i] for i in ITEMS] + ["scale", "round pads"] + + def agent_instruction(self, inst, variant="direct"): + names = DESCR if variant == "indirect" else NAME + order = [names[o] for o in inst["order"]] + return self._TEMPLATE.format(order=", ".join(order[:-1]) + ", then " + order[-1]) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = False + self._latch = None + orig_step = self.env.step + + def step(action): # per-control-step monitor (also for attempts driven by the agent harness) + if self._latch is not None: + action = self._homing_action() + ret = orig_step(action) + if self._mon: + self._monitor() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + pads = [register_generated(f"LffSeqPad{L}", _swap_pad_xml(f"lff_seq_pad_{L.lower()}")) for L in "ABCD"] + scale = register_generated("LffSeqScale", scale_xml("lff_seq_scale"), free=False) + objs = [(o, CATS[o], f"r{i}", (-0.26 + 0.15 * i - 0.01, -0.31, -0.26 + 0.15 * i + 0.01, -0.29)) + for i, o in enumerate(ITEMS)] + objs += [(PADS[i], pads[i], f"p{i}", (-0.26 + 0.15 * i - 0.01, 0.29, -0.26 + 0.15 * i + 0.01, 0.31)) + for i in range(N_ITEMS)] + fx = [("scale_1", scale, "scale_region", (0.19, -0.01, 0.21, 0.01))] + return write_bddl(self.name, "Weigh the four items one at a time in the given order", objs, fx) # no ; in BDDL + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(5000): + pts = [] + while len(pts) < N_ITEMS + 1: + p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])]) + if np.hypot(p[0] - BASE_X, p[1]) > REACH: + continue + pts.append(p) + scale, pads = pts[0], np.array(pts[1:]) + dp = [np.linalg.norm(pads[i] - pads[j]) for i in range(N_ITEMS) for j in range(i)] + if min(dp) >= PAD_MIN and min(np.linalg.norm(pads - scale, axis=1)) >= SCALE_MIN: + break + else: + raise RuntimeError("could not sample a layout") + order = [ITEMS[i] for i in rng.permutation(N_ITEMS)] + w = int(rng.integers(1, N_ITEMS + 1)) # items weighed when the stop happens + phase = "B" if w == N_ITEMS else str(rng.choice(["A", "B"])) + inst = dict(seed=int(seed), order=order, pads=pads.round(4).tolist(), scale_xy=scale.round(4).tolist(), + item_off=[[float(v) for v in rng.uniform(-0.008, 0.008, 2)] for _ in range(N_ITEMS)], + item_yaw=[float(v) for v in rng.uniform(-0.3, 0.3, N_ITEMS)], + stop_w=w, stop_phase=phase, trigger_dist=float(rng.uniform(0.05, 0.09)), + stop_off=[float(v) for v in rng.uniform(-0.008, 0.008, 2)], + stop_yaw=float(rng.uniform(-0.3, 0.3))) + inst["stop_item"] = order[w] if phase == "A" else order[w - 1] + self.instruction = self.agent_instruction(inst, "direct") # make_video prints task.instruction + self.instruction_indirect = self.agent_instruction(inst, "indirect") + return inst + + def apply_instance(self, inst): + m = self.env.sim.model + for i, p in enumerate(inst["pads"]): + envs.set_obj_pose(self.env, PADS[i], [p[0], p[1], envs.TABLE_Z + PAD_HALF_T + 0.0001]) + bid = m.body_name2id(self.env.fixtures_dict["scale_1"].root_body) + m.body_pos[bid] = [inst["scale_xy"][0], inst["scale_xy"][1], envs.TABLE_Z] + m.body_quat[bid] = [1, 0, 0, 0] + for i, o in enumerate(ITEMS): + p = np.asarray(inst["pads"][i]) + inst["item_off"][i] + envs.place_upright(self.env, o, p, inst["item_yaw"][i]) + self.env.sim.forward() + self._inst = inst + self.pad_of = {o: i for i, o in enumerate(ITEMS)} # item i starts on pad i (pad positions are random) + self.log = [] # scale readings (item names) + self.error = None + self.stop = None + self.events = [] + self._event_cursor = 0 + self._outcome_cursor = 0 + self._dwell = {o: 0 for o in ITEMS} + self._visit = {o: False for o in ITEMS} + self._prev = {} + self._latch = None + self._mon = False + + def reset_instance(self, inst, recorder=None): + self._mon = False + self._latch = None + sk = super().reset_instance(inst, recorder=recorder) + self._home = sk.eef_pos() + self.rest_dz = {o: float(envs.obj_pos(self.env, o)[2] - envs.TABLE_Z) for o in ITEMS} + self._prev = {o: envs.obj_pos(self.env, o) for o in ITEMS} + 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) + + # ------------------------------------------------------------ helpers + def scale_xy(self): + return np.asarray(self._inst["scale_xy"], float) + + def pad_xy(self, o): + return np.asarray(self._inst["pads"][self.pad_of[o]], float) + + def on_scale(self, o, p=None): + p = envs.obj_pos(self.env, o) if p is None else p + d = np.abs(p[:2] - self.scale_xy()) + return bool(d.max() <= SCALE_HALF and abs(p[2] - (envs.TABLE_Z + SCALE_TOP + self.rest_dz[o])) < 0.008) + + def on_own_pad(self, o): + p = envs.obj_pos(self.env, o) + return bool(np.linalg.norm(p[:2] - self.pad_xy(o)) <= SUCC_R + and abs(p[2] - (envs.TABLE_Z + self.rest_dz[o])) < 0.01 and not self.sk.holding(o)) + + # ------------------------------------------------------------ monitor: scale readings + emergency stop + def _monitor(self): + env = self.env + if self._latch is not None: + if len(self.sk.log) > self._latch and np.linalg.norm(self.sk.eef_pos() - self._home) < 0.01: + self._latch = None + for o in ITEMS: + p = envs.obj_pos(env, o) + still = np.linalg.norm(p - self._prev[o]) < 0.0008 + self._prev[o] = p + if self.on_scale(o, p): + if still and not self.sk.holding(o): + self._dwell[o] += 1 + if self._dwell[o] >= DWELL and not self._visit[o]: + self._visit[o] = True + self._record(o) + else: + self._dwell[o] = 0 + else: + self._dwell[o] = 0 + if np.abs(p[:2] - self.scale_xy()).max() > SCALE_HALF or \ + p[2] > envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + 0.02: + self._visit[o] = False + if self.inject and self.stop is None: + self._maybe_stop() + + def _record(self, o): + self.log.append(o) + k = len(self.log) + ok = self.log == self._inst["order"][:k] + if ok: + self.events.append(dict(step=int(self.sk.n_steps), kind="beep", obj=o, + text="The scale beeped: reading recorded.")) + else: + if self.error is None: + self.error = dict(item=o, position=k, step=int(self.sk.n_steps), + kind="repeat" if self.log.count(o) > 1 else "out_of_order") + self.events.append(dict(step=int(self.sk.n_steps), kind="error", obj=o, + text="The scale beeped three times: error, this reading does not follow the " + "requested order. The log cannot be edited.")) + + def _maybe_stop(self): + inst = self._inst + o, w = inst["stop_item"], inst["stop_w"] + if self.log != inst["order"][:w]: + return + p = envs.obj_pos(self.env, o) + if inst["stop_phase"] == "A": + if p[2] < envs.TABLE_Z + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.pad_xy(o)) < inst["trigger_dist"]: + return + else: + if p[2] < envs.TABLE_Z + SCALE_TOP + self.rest_dz[o] + LIFTED: + return + if np.linalg.norm(p[:2] - self.scale_xy()) < inst["trigger_dist"]: + return + if not self.sk.holding(o): + return + self._do_stop(o) + + def _do_stop(self, o): + inst = self._inst + xy = self.pad_xy(o) + np.asarray(inst["stop_off"]) + envs.place_upright(self.env, o, xy, inst["stop_yaw"]) + self.sk.grip = -1.0 + self.sk.yaw = 0.0 + self._latch = len(self.sk.log) # drive the arm home until the current primitive has returned + self._prev[o] = envs.obj_pos(self.env, o) + self.env.sim.forward() + text = ("Emergency stop! The gripper opened, the safety routine put the item the robot was holding back on " + "its pad and moved the arm to its home pose. You may continue the task.") + self.stop = dict(item=o, phase=inst["stop_phase"], weighed=len(self.log), step=int(self.sk.n_steps)) + self.events.append(dict(step=int(self.sk.n_steps), kind="stop", obj=o, text=text)) + + def _homing_action(self): + sk = self.sk + a = np.zeros(self.env.action_dim) + a[:3] = np.clip((self._home - sk.eef_pos()) / sk.pos_scale, -1, 1) + a[3:6] = np.clip(_rot_err(sk.R0, sk.eef_mat()) / ROT_SCALE, -1, 1) + a[6] = -1.0 + return a + + 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) + order = inst["order"] + complete = self.log == order + terminal = self.error is not None + off = [o for o in ITEMS if not self.on_own_pad(o)] + success = bool(complete and not off and not terminal) + if success: + head = "All four items were weighed once, in the requested order, and are back on their pads." + elif terminal: + head = ("The scale log does not follow the requested order (an item was weighed a second time or out " + "of turn). The log cannot be edited, so the task can no longer be completed.") + elif complete: + head = "Every item has been weighed, but not every item is back on its own pad." + else: + head = "Not every item has been weighed yet." + parts = [] + if not success and not terminal: + for o in off: + p = envs.obj_pos(self.env, o) + if self.sk.holding(o): + parts.append(f"the {NAME[o]} is still in the gripper") + elif self.on_scale(o, p): + parts.append(f"the {NAME[o]} is on the scale") + else: + d = np.linalg.norm(p[:2] - self.pad_xy(o)) + parts.append(f"the {NAME[o]} is {100 * d:.0f} cm from the centre of its pad") + detail = head + (" Also: " + "; ".join(parts) + "." if parts else "") + new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "stop"] + self._outcome_cursor = len(self.events) + if new: + detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail + return dict(success=success, terminal=terminal, log=[NAME[o] for o in self.log], n_weighed=len(self.log), + complete=complete, error=self.error, stop=self.stop, + off_pad=[NAME[o] for o in off], detail=detail) + + # ------------------------------------------------------------ motion (scripted policies) + def _support_z(self, o): + p = envs.obj_pos(self.env, o) + return envs.TABLE_Z + (SCALE_TOP if self.on_scale(o, p) or + (np.abs(p[:2] - self.scale_xy()).max() < SCALE_HALF) else 0.0) + + def _n_stops(self): + return sum(e["kind"] == "stop" for e in self.events) + + def _pick(self, o): + sk = self.sk + for _ in range(2): + p = envs.obj_pos(self.env, o) + sk.grasp_at(p[:2], self._support_z(o) + GRASP_DZ, yaw=_yaw_of(self.env, o), lift=0.12) + if sk.holding(o): + return True + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], self._support_z(o) + GRASP_DZ + 0.12]) + return False + + def _carry_to(self, o, xy, z_support): + """Carry the held item to xy and put it down. Returns False if an emergency stop happened.""" + sk = self.sk + n0 = self._n_stops() + sk.move_to([xy[0], xy[1], Z_CARRY]) + if self._n_stops() > n0: + return False + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.004], tol=0.004) + sk.set_gripper(False, steps=12) + sk.move_to([xy[0], xy[1], z_support + GRASP_DZ + 0.10]) + return self._n_stops() == n0 + + def _weigh(self, o): + """Weigh one item (pad -> scale -> pad). Returns (status, beeped): status 'ok' / 'stop_A' / 'stop_B' / + 'no_grasp'; beeped = the scale beeped while the item lay on it (what the agent hears).""" + n_beep = sum(e["kind"] in ("beep", "error") for e in self.events) + if not self._pick(o): + return "no_grasp", False + if not self._carry_to(o, self.scale_xy(), envs.TABLE_Z + SCALE_TOP): + return "stop_A", False + self.sk.hold(6) + beeped = sum(e["kind"] in ("beep", "error") for e in self.events) > n_beep + if not self._pick(o): + return "no_grasp", beeped + if not self._carry_to(o, self.pad_xy(o), envs.TABLE_Z): + return "stop_B", beeped + return "ok", beeped + + def _fix_pads(self, log): + for o in ITEMS: + if not self.on_own_pad(o) and not self.on_scale(o): + if self._pick(o): + self._carry_to(o, self.pad_xy(o), envs.TABLE_Z) + log.append((NAME[o], "back to pad")) + + def _run_from(self, k, record, log, stop_on_stop=False): + """Weigh order[k:] in turn, keeping `record` (the policy's own list of readings it heard).""" + order = self._inst["order"] + i = k + guard = 0 + while i < len(order) and guard < 10 and self.error is None: + guard += 1 + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if beeped: + record.append(o) + if st == "no_grasp": + continue + if st.startswith("stop"): + if stop_on_stop: + return "stopped" + i = len(record) # resume from the own record + continue + i += 1 + return "ok" + + # ------------------------------------------------------------ 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 + 104729) + self.reset_instance(inst) + order = inst["order"] + history = [] + record = [] # adaptive's Save: readings it heard + for a in range(k): + log = [] + plan = dict(kind=kind, steps=log) + if a == 0: + if kind == "oracle": + while len(self.log) < len(order) and self.error is None and len(log) < 12: + o = order[len(self.log)] # privileged scale log + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "oracle: privileged scale log" + elif kind == "adaptive": + self._run_from(0, record, log) + plan["recovery"] = "own record of readings: resume from order[len(record)]" + elif kind == "skip": + started = [] + i = 0 + while i < len(order) and self.error is None and len(log) < 12: + o = order[i] + st, beeped = self._weigh(o) + log.append((NAME[o], st, beeped)) + if st == "no_grasp": + continue + started.append(o) + i = len(started) # counts started items, not readings + plan["recovery"] = "counts items it started to weigh (the interrupted one too)" + else: # memoryless after the stop + r = self._run_from(0, record, log, stop_on_stop=True) + if r == "stopped": + if kind == "naive": + g = int(rng.integers(0, len(order) + 1)) + plan["recovery"] = f"memoryless: guesses {g} items already weighed" + self._run_from(g, [], log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + else: + raise ValueError(kind) + else: + plan["recovery"] = "none (no stop)" + else: + if kind in ("adaptive", "oracle", "skip"): + plan["recovery"] = "memory + F2: put items back on their pads / finish from own record" + if kind == "adaptive" and len(record) < len(order): + self._run_from(len(record), record, log) + if kind == "skip" and not history[-1]["outcome"]["complete"]: + # F2 says the log is incomplete: with memory, the item carried at the stop was not weighed + stopped = [s[0] for h in history for s in h["params"]["steps"] if str(s[1]).startswith("stop")] + if stopped: + o = next(i for i in ITEMS if NAME[i] == stopped[-1]) + st, _ = self._weigh(o) + log.append((NAME[o], st)) + plan["recovery"] = "memory + F2 'not every item weighed': weigh the item carried at the stop" + self._fix_pads(log) + elif kind == "blind": + plan["recovery"] = "memoryless restart from the first item" + self._run_from(0, [], log) + 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 + + 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_opus/lff/source_closure/lffbench/tasks/lh_balance_board.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_balance_board.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4ceaea2c011176291dd2723cc94d344f23d991 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_balance_board.py @@ -0,0 +1,817 @@ +"""LH balance_board: put four look-alike cubes on their marks on a plank that rests loose across a narrow block (a +seesaw); loading it in the wrong order tips the plank, and every cube already on it slides down to the low end. + +Family: long-horizon self-disturbance ("state_restoration"): each stage is a plain pick-and-place of a cube onto its +mark, but a later placement can tip the plank, which sends the cubes placed before it (earlier progress) sliding off +their marks. The agent has to notice it, re-level the plank and re-place them before finishing (within an attempt), and +learn a loading order that keeps the plank level (across attempts; the final-state judge does not enforce an order). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey support (fixture: two 1.5 cm blocks with a 1 cm slot between them, together 4 cm along the plank x 10 cm x + 6 cm high, flat tops) under the middle of + * a dark wooden plank (free body, 46 cm long, pointing away from the robot, 8 cm wide, 1.5 cm thick, 0.5 kg) lying + loose on it, level, with a 2 cm lip across each end. A thin keel under the plank's middle hangs in the slot and keeps + the plank from wandering along the support (+-3 mm); nothing holds it down. It stays level while the combined centre + of mass of plank + cubes is above the support's 4 cm top; otherwise it tips until its low end touches the table + (about 17 degrees); + * four marks (5.8 cm squares, outline + light fill) on the plank, two on each side of the block: an inner one + (8.5-9.5 cm from the middle) and an outer one (15.5-16.5 cm); the colour of each mark is random; + * four 4.5 cm cubes (red, green, blue, yellow) on the table, two left and two right of the plank (random places). + They look alike except for the colour. Cube and plank surfaces are slick (friction 0.2 < tan 17 deg): on a tipped + plank every cube slides down to the lip at the low end. +Why along x with lips (measured, see the task card): with the plank left-right and open ends, the cubes slid off the +ends onto the table 0-11 cm past them, and a default top-down grasp there (fingers left-right, the Panda hand is 21 cm +wide along them) pressed the plank's end down and tipped it again -- restoring became a loop. Along x the default grasp +is across the plank, and the lips keep the cubes on the plank within reach. + +Hidden variable: the cube masses. "Hazard" instances (13 of every 20 consecutive seeds): the two cubes that belong on +the inner marks are heavy (stone, 0.19-0.24 kg), the two for the outer marks are light (48-56 g); the final layout is +balanced. A heavy cube alone on its inner mark tips the plank (1.28-1.43 x the tipping moment); a light one alone on its +outer mark does not (0.72-0.78 x); in the zig-zag order below no step exceeds 0.72-0.81 x. So the only safe loading +orders are "an outer cube, then the inner cube on the OTHER side, then the other inner cube, then the last outer cube" +(zig-zag); end-to-end, alternating outer-first (outer, outer, inner, inner) and inner-first orders all tip it. +"Benign" instances: all four cubes light (26-34 g); no order tips (worst step 0.63-0.75 x). + +Why the natural order fails: nothing in the image shows which cubes are heavy. Any natural order (nearest cube first, +the marks from one end to the other, or the cautious "alternate sides, outer marks first") tips the plank in a hazard +instance; the cubes on it slide to the low end and keep it tipped. A natural plan then keeps going and finishes with +cubes off their marks. What must be learned: check the marks after each placement / before finishing, unload the low +end and re-place (within the attempt), and use the tip to infer which cubes are heavy (an inner cube tipped it; the +layout must balance in the end, so the other inner cube is heavy too) and load in the zig-zag order (across attempts). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube on its +mark, plank level within 3 degrees and still on its support (10-11), nothing held, scene static) plus an event log of every stage predicate (achieved / +lost / restored, with step and cause) and every tip (which end went down, the cube released just before) for the server +log; F1 gives the agent only success / failure. +""" +import itertools + +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 + +TZ = envs.TABLE_Z + +# ---------------------------------------------------------------- geometry / physics +# plank frame: y along the plank (+y = the end toward the robot), x across it, z up. The plank and the block are +# yawed 90 deg, so plank +y = world -x. +PL_HL, PL_HW, PL_HT = 0.23, 0.04, 0.0075 # plank half length, half width, half thickness +LIP_T, LIP_H = 0.008, 0.02 # lip across each end (inside the 46 cm), height above the plank's top +PLANK_MASS = 0.50 +PLANK_ROT_DAMP = 0.01 # N m s / rad on the plank's rotation: after its low end is unloaded it swings over to ~10 deg +# and is calm in ~1.5 s (no damping: ~13 deg and ~2.7 s); the tip itself is not slowed (measured) +PLANK_YAW = np.pi / 2 +RIDGE_HW, RIDGE_HX, RIDGE_H = 0.02, 0.05, 0.06 # support: half width along the plank (s), half depth, height +SLOT_HW = 0.005 # the support is two blocks with a 1 cm slot between them +KEEL_HW, KEEL_H = 0.002, 0.010 # keel under the plank's middle (4 mm x 8 cm x 1 cm) hanging in the slot +CUBE_E = 0.045 +MU = 0.20 # cubes and plank: the cube-plank contact slides above 11 deg; ridge (1.0), table (0.6), finger pads (2.0) win +MU_RIDGE = 1.0 +MARK_HALF, MARK_LINE = 0.029, 0.004 +WOOD = (0.42, 0.27, 0.15, 1.0) # dark walnut: contrasts with the light table, so the tilt reads in the images + +COLORS = ("red", "green", "blue", "yellow") +RGBA = dict(red=(0.85, 0.12, 0.10, 1.0), green=(0.10, 0.62, 0.20, 1.0), blue=(0.15, 0.30, 0.88, 1.0), + yellow=(0.93, 0.78, 0.10, 1.0)) +CUBES = {c: f"{c}_cube_1" for c in COLORS} +PLANK, RIDGE = "plank_1", "ridge_1" +PLANK_MODEL = "lff_lh_bb_plank" +# mark slots in plank-frame order (+y first): the robot's end outer / inner, then the far end inner / outer +SLOTS = ("near_outer", "near_inner", "far_inner", "far_outer") +END_WORD = dict(near="the end nearer the robot", far="the far end") + +# ---------------------------------------------------------------- instances / hidden variable +D_INNER = (0.085, 0.095) # |y| of the inner marks from the plank's middle +D_OUTER = (0.155, 0.165) # the lip stops a cube 19.95 cm out: a cube on a low-side outer mark ends >= 3.5 cm off it +P_HAZARD = 0.65 # fraction of hazard instances, balanced per 20 consecutive seeds (13 / 7) +R_HEAVY = (1.30, 1.40) # hazard: lone heavy cube on its inner mark, moment / tipping moment +R_LIGHT = (0.72, 0.78) # hazard: lone light cube on its outer mark +LIGHT_BENIGN = (0.026, 0.034) # benign: every cube (kg) +H_EST, L_EST = 0.21, 0.04 # nominal masses the adaptive script uses for its hypotheses (it never sees the true ones) + +# ---------------------------------------------------------------- judging +TOL = 0.020 # cube centre within 2 cm of its mark centre (per plank axis) +TOL_LOSE = 0.025 # hysteresis for the monitor +LEVEL_DEG = 3.0 +TIP_DEG = 8.0 # the monitor records a tip when |tilt| exceeds this (a real tip reaches ~17 deg) +LEVEL_DEBOUNCE = 4 # monitor evaluations (0.1 s each) before plank_level changes +FLAT_COS = np.cos(np.radians(15.0)) +SUPPORT_XY = 0.02 # plank on its support: its middle within 2 cm (horizontally) of the support's centre ... +SUPPORT_DZ = 0.02 # ... and not more than 2 cm below its starting height (a tip lowers it ~0.6 cm; off the block ~6 cm) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.17 # careful / adaptive: grasp point above the table while carrying (cube bottom 14.75 cm) +Z_CARRY_NAIVE = 0.15 # naive: just above the cubes already on the plank (their tops at 12 cm) +REL_GAP = 0.004 # release with the cube's bottom this far above the plank + + +def plank_xml(name): + """Board + end lips + keel (collision) and per colour a mark (5 visual-only geoms, moved per instance). + Long axis = body y.""" + g = [] + + def box(nm, pos, size, rgba): + g.append(f'') + g.append(f'') + + dark = (0.25, 0.16, 0.09, 1.0) + box(f"{name}_board", (0, 0, 0), (PL_HW, PL_HL, PL_HT), WOOD) + for k, s in enumerate((1, -1)): + box(f"{name}_lip{k}", (0, s * (PL_HL - LIP_T / 2), PL_HT + LIP_H / 2), (PL_HW, LIP_T / 2, LIP_H / 2), dark) + box(f"{name}_keel", (0, 0, -PL_HT - KEEL_H / 2), (PL_HW, KEEL_HW, KEEL_H / 2), dark) + for c in COLORS: + rgba = RGBA[c] + fill = tuple(0.55 + 0.45 * v for v in rgba[:3]) + (1.0,) + o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE + parts = [((0, 0, PL_HT + 0.0003), (o, o, 0.0003), fill), + ((0, i + w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((0, -i - w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((i + w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba), + ((-i - w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba)] + for k, (p, sz, col) in enumerate(parts): + g.append(f'') + return _wrap(name, "\n ".join(g), PL_HT, float(np.hypot(PL_HL, PL_HW))) + + +def ridge_xml(name): + """Split support: two 1.5 cm blocks with a 1 cm slot between them; the plank rests on both and pivots on their outer + top edges (a 4 cm flat top). The plank's keel hangs in the slot, so the plank cannot wander along its length by + more than +-3 mm (it stays engaged at the full tip angle).""" + rgba = (0.35, 0.35, 0.38, 1.0) + bh = (RIDGE_HW - SLOT_HW) / 2 + g = [] + for k, sy in enumerate((1, -1)): + p, sz = (0, sy * (SLOT_HW + bh), RIDGE_H / 2), (RIDGE_HX, bh, RIDGE_H / 2) + g.append(f'') + g.append(f'') + g = "\n ".join(g) + return f""" + + + + {g} + + + + + + +""" + + +def tip_ratio(items, plank_mass=PLANK_MASS, s=RIDGE_HW): + """Static model of a loose plank on a flat-topped block: |sum m y| / ((M_plank + sum m) s); the plank tips when + this exceeds 1 (the combined centre of mass leaves the block's top). items: [(mass, y from the middle)].""" + if not items: + return 0.0 + mom = sum(m * y for m, y in items) + return abs(mom) / ((plank_mass + sum(m for m, _ in items)) * s) + + +def _side(y): + return "near" if y > 0 else "far" + + +def _along(v): + """plank-frame y offset in robot-centric words (+y = toward the robot)""" + return f"{100 * abs(v):.1f} cm from its mark toward {'the robot' if v > 0 else 'the far end'}" + + +class BoardSkills(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 BalanceBoard(LFFTask): + name = "lh_balance_board" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful zig-zag ~30-36 commands + re-placing four cubes (~30) + looking around + instruction = ("Put each coloured cube on the square mark of the same colour on the long plank. The plank lies loose " + "across a narrow block under its middle. At the end all four cubes must be on their marks and the " + "plank must still rest level on the block.") + instruction_indirect = ("Set the four coloured cubes onto the outlined squares of matching colour on the wooden " + "board that rests across the small grey block. When you are done, every cube must sit on " + "its square and the board must still rest level on the block.") + agent_object_names = ["red cube", "green cube", "blue cube", "yellow cube", "plank", "support block", + "red mark", "green mark", "blue mark", "yellow mark"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + pl = register_generated("LffLhBbPlank", plank_xml(PLANK_MODEL)) + rg = register_generated("LffLhBbRidge", ridge_xml("lff_lh_bb_ridge"), free=False) + objs = [(PLANK, pl, "plank_region", (0.18, -0.01, 0.20, 0.01))] + e = CUBE_E / 2 + for i, c in enumerate(COLORS): + cat = register_generated(f"LffLhBbCube{c.title()}", + box_xml(f"lff_lh_bb_cube_{c}", (e, e, e), RGBA[c], density=500.0, + friction=(MU, 0.005, 0.0001)).replace( + 'solimp="0.998 0.998 0.001" solref="0.001 1"', "")) + objs.append((CUBES[c], cat, f"{c}_cube_region", (-0.32, -0.33 + 0.2 * i, -0.30, -0.31 + 0.2 * i))) + fx = [(RIDGE, rg, "ridge_region", (-0.12, 0.30, -0.10, 0.32))] + return write_bddl(self.name, "put each cube on its mark on the plank and keep the plank level", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.ridge_bid = m.body_name2id(self.env.fixtures_dict[RIDGE].root_body) + self.plank_bid = envs.body_id(self.env, PLANK) + pre = f"{PLANK}_{PLANK_MODEL}" + self.mark_gids = {c: [m.geom_name2id(f"{pre}_mk_{c}_{k}") for k in range(5)] for c in COLORS} + self.mark_pos0 = {c: [m.geom_pos[g].copy() for g in self.mark_gids[c]] for c in COLORS} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, CUBES[c])) for c in COLORS} + self.plank_gids = set(envs.obj_geom_ids(self.env, PLANK)) + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + self.obs = [] # adaptive script: (configuration, tipped) observations, kept across the attempts of one run + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + x0, y0 = float(rng.uniform(-0.18, -0.14)), float(rng.uniform(-0.03, 0.03)) + perm = [str(c) for c in rng.permutation(COLORS)] # colour of the mark in SLOTS order + slot_of = {c: s for c, s in zip(perm, SLOTS)} + dist = dict(near_outer=float(rng.uniform(*D_OUTER)), near_inner=float(rng.uniform(*D_INNER)), + far_inner=-float(rng.uniform(*D_INNER)), far_outer=-float(rng.uniform(*D_OUTER))) + marks = {c: dist[slot_of[c]] for c in COLORS} # plank-frame y of each mark (+ = toward the robot) + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced like l7_key_turn / lh_lid_box + r_h, r_l = float(rng.uniform(*R_HEAVY)), float(rng.uniform(*R_LIGHT)) + light = {c: float(rng.uniform(*LIGHT_BENIGN)) for c in COLORS} + s, pm = RIDGE_HW, PLANK_MASS + if hazard: + # equal moments on both sides -> the finished layout is exactly balanced + dn, do = dist["near_inner"], dist["near_outer"] + y_h = r_h * pm * s / (dn - r_h * s) * dn # heavy on the near inner mark: moment r_h x tipping moment + x_l = r_l * pm * s / (do - r_l * s) * do + mass = {c: (y_h if "inner" in slot_of[c] else x_l) / abs(dist[slot_of[c]]) for c in COLORS} + else: + mass = light + # start: two cubes left and two right of the plank, 17-19 cm from its axis, at two depths (random places) + spots = [(dx, sy) for sy in (1.0, -1.0) for dx in (-0.08, 0.08)] + order = rng.permutation(4) + start = {c: [x0 + spots[j][0] + float(rng.uniform(-0.01, 0.01)), + y0 + spots[j][1] * float(rng.uniform(0.17, 0.19))] for c, j in zip(COLORS, order)} + start_yaw = {c: float(rng.uniform(-0.3, 0.3)) for c in COLORS} + heavy = sorted(c for c in COLORS if mass[c] > 0.1) + return dict(seed=int(seed), plank_xy=[x0, y0], marks=marks, slot_of=slot_of, hazard=hazard, mass=mass, + heavy=heavy, r_heavy=r_h if hazard else None, r_light=r_l if hazard else None, start=start, + start_yaw=start_yaw) + + def apply_instance(self, inst): + self.inst = inst + env = self.env + m = env.sim.model + x0, y0 = inst["plank_xy"] + q = [np.cos(PLANK_YAW / 2), 0.0, 0.0, np.sin(PLANK_YAW / 2)] + m.body_pos[self.ridge_bid] = [x0, y0, TZ] + m.body_quat[self.ridge_bid] = q + envs.scale_mass(env, PLANK, PLANK_MASS) + _, da = envs.free_joint_addr(env, PLANK) + m.dof_damping[da + 3:da + 6] = PLANK_ROT_DAMP + for c in COLORS: + for g, p0 in zip(self.mark_gids[c], self.mark_pos0[c]): + m.geom_pos[g] = p0 + np.array([0.0, inst["marks"][c], 0.0]) + envs.scale_mass(env, CUBES[c], inst["mass"][c]) + envs.set_obj_pose(env, PLANK, [x0, y0, TZ + RIDGE_H + PL_HT + 0.0005], quat_wxyz=np.array(q)) + for c in COLORS: + envs.place_upright(env, CUBES[c], inst["start"][c], yaw=inst["start_yaw"][c]) + + 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, 10) + self.plank_z0 = float(self.plank_pos()[2]) + self.sk = BoardSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def plank_R(self): + return self.env.sim.data.body_xmat[self.plank_bid].reshape(3, 3).copy() + + def plank_pos(self): + return self.env.sim.data.body_xpos[self.plank_bid].copy() + + def tilt_deg(self): + """+ = the plank's end toward the robot is up""" + return float(np.degrees(np.arcsin(np.clip(self.plank_R()[2, 1], -1.0, 1.0)))) + + def is_level(self, deg=LEVEL_DEG): + return abs(self.tilt_deg()) <= deg + + def on_support(self): + """the plank still rests on the support block (10-11: Sonnet lh2 s3001 pushed it off onto the table, where it + lies level, and loaded the cubes there; 'level' alone accepted that)""" + p, r = self.plank_pos(), self.env.sim.data.body_xpos[self.ridge_bid] + return bool(np.linalg.norm(p[:2] - r[:2]) <= SUPPORT_XY and p[2] >= self.plank_z0 - SUPPORT_DZ) + + def in_plank(self, p): + """world point -> plank frame (x across, y along from the middle, z above the plank's mid-plane)""" + return self.plank_R().T @ (np.asarray(p, float) - self.plank_pos()) + + def mark_world(self, c): + return self.plank_pos() + self.plank_R() @ np.array([0.0, self.inst["marks"][c], PL_HT]) + + def cube_pos(self, c): + return envs.obj_pos(self.env, CUBES[c]) + + def held(self, c): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, + object_geoms=self.env.objects_dict[CUBES[c]])) + + def on_plank(self, c): + """resting on the plank's top (plank frame), anywhere along it""" + q = self.in_plank(self.cube_pos(c)) + return bool(abs(q[0]) <= PL_HW + 0.01 and abs(q[1]) <= PL_HL and abs(q[2] - PL_HT - CUBE_E / 2) <= 0.012) + + def mark_offset(self, c): + q = self.in_plank(self.cube_pos(c)) + return np.array([q[0], q[1] - self.inst["marks"][c]]) + + def _flat(self, c): + Rc = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + return bool(np.max(np.abs(self.plank_R()[:, 2] @ Rc)) >= FLAT_COS) + + def on_mark(self, c, tol=TOL): + if not self.on_plank(c): + return False + o = self.mark_offset(c) + return bool(np.max(np.abs(o)) <= tol and self._flat(c) and not self.held(c)) + + def stage_values(self): + v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS} + v["plank_level"] = self.is_level() + v["plank_on_support"] = self.on_support() + return v + + # ------------------------------------------------------------ per-step monitor (server log only) + def _init_monitor(self): + self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"plank_level": True, "plank_on_support": True}, ever=set(), + lost=set(), events=[], step=0, last_touch={c: None for c in COLORS}, + held_prev={c: False for c in COLORS}, last_release=None, tipping=False, tips=[], + level_cnt=0, calm=0, tilt_max=0.0, win_max=0.0) + + def _robot_touches(self): + """cubes touched by the robot or by a cube the robot is carrying, in this control step""" + d = self.env.sim.data + out = set() + carried = [c for c in COLORS if self.mon["held_prev"][c]] + hit = {c: self.robot_gids.union(*[self.cube_gids[h] for h in carried if h != c]) for c in COLORS} + for i in range(d.ncon): + con = d.contact[i] + for c in COLORS: + g = self.cube_gids[c] + if (con.geom1 in g and con.geom2 in hit[c]) or (con.geom2 in g and con.geom1 in hit[c]): + out.add(c) + return out + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + step = self.sk.n_steps + for c in self._robot_touches(): + mon["last_touch"][c] = step + tilt = self.tilt_deg() + mon["tilt_max"] = max(mon["tilt_max"], abs(tilt)) + mon["win_max"] = max(mon["win_max"], abs(tilt)) + if not mon["tipping"] and abs(tilt) > TIP_DEG: + # one tip episode = from |tilt| > 8 deg until the plank has stayed level for 1 s (the swing back and any + # rocking belong to the same episode) + mon["tipping"] = True + mon["calm"] = 0 + rel = mon["last_release"] + tip = dict(step=step, down="near" if tilt < 0 else "far", + after_release=(rel[0] if rel is not None and step - rel[1] <= 60 else None), + on_plank=[c for c in COLORS if self.on_plank(c)], + on_mark=[c for c in COLORS if mon["state"][f"{c}_on_mark"]]) + mon["tips"].append(tip) + mon["events"].append(dict(step=step, pred="plank", ev="tipped", down=tip["down"], + after_release=tip["after_release"], on_mark=tip["on_mark"])) + elif mon["tipping"]: + mon["calm"] = mon["calm"] + 1 if abs(tilt) < LEVEL_DEG else 0 + if mon["calm"] >= 20: + mon["tipping"] = False + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + for c in COLORS: + h = self.held(c) + if mon["held_prev"][c] and not h: + mon["last_release"] = (c, step) + mon["held_prev"][c] = h + key = f"{c}_on_mark" + was = mon["state"][key] + now = self.on_mark(c, TOL if not was else TOL_LOSE) + if now != was: + self._event(key, now, step, c) + lv = self.is_level() + if lv != mon["state"]["plank_level"]: + mon["level_cnt"] += 1 + if mon["level_cnt"] >= LEVEL_DEBOUNCE: + mon["level_cnt"] = 0 + self._event("plank_level", lv, step, None) + else: + mon["level_cnt"] = 0 + sup = self.on_support() + if sup != mon["state"]["plank_on_support"]: + self._event("plank_on_support", sup, step, None) + + def _event(self, key, now, step, color): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + cause = "other" + recent_tip = bool(mon["tips"]) and (mon["tipping"] or step - mon["tips"][-1]["step"] <= 60) + if color is None: + cause = "tip" if recent_tip else "other" + elif self.held(color): + cause = "picked_up" + elif recent_tip: + cause = "tip" + elif mon["last_touch"][color] is not None and step - mon["last_touch"][color] <= 60: + cause = "robot" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, tilt=round(self.tilt_deg(), 1))) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in [CUBES[c] for c in COLORS] + [PLANK]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return False + return True + + def _where(self, c): + """robot-centric description of where a cube that is not on its mark is""" + if self.held(c): + return "is still held by the gripper" + if self.on_plank(c): + o = self.mark_offset(c) + return f"lies on the plank, {_along(o[1])}" + p = self.cube_pos(c) + if np.linalg.norm(p[:2] - np.asarray(self.inst["start"][c])) < 0.02: + return "is still where it started on the table" + q = self.in_plank(p) + if abs(q[1]) > PL_HL: + return f"lies on the table beyond {END_WORD[_side(q[1])]} of the plank" + return "lies on the table beside the plank" + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [c for c in COLORS if self.held(c)] + success = bool(all(vals.values()) and static and not held) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + parts = [] + off = [c for c in COLORS if not vals[f"{c}_on_mark"]] + if success: + failure = None + parts.append("All four cubes are on their marks and the plank is level.") + else: + lost_final = [c for c in off if f"{c}_on_mark" in mon["ever"]] + failure = ("held" if held else "plank_off_support" if not vals["plank_on_support"] else + "regressed" if lost_final else "incomplete" if off else + "not_level" if not vals["plank_level"] else "not_static") + for c in off: + txt = f"The {c} cube is not on its mark: it {self._where(c)}" + if f"{c}_on_mark" in mon["ever"]: + why = [e for e in regress if e["pred"] == f"{c}_on_mark"] + cause = why[-1].get("cause") if why else None + txt += {"tip": " (it had been on its mark; it slid off when the plank tipped).", + "robot": " (it had been on its mark; the robot knocked it off).", + "picked_up": " (it had been on its mark; it was picked up again)."}.get( + cause, " (it had been on its mark earlier).") + else: + txt += " (it was never on its mark)." + parts.append(txt) + if not vals["plank_on_support"]: + parts.append("The plank no longer rests on the support block: it was pushed or knocked off it.") + if not vals["plank_level"]: + t = self.tilt_deg() + parts.append(f"The plank is not level: it is tilted {abs(t):.0f} degrees, " + f"{END_WORD['near' if t < 0 else 'far']} down.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["tips"]: + descr = [] + for tp in mon["tips"]: + d = f"{END_WORD[tp['down']]} down" + if tp["after_release"]: + d += f" right after the {tp['after_release']} cube was set down" + descr.append(d) + parts.append(f"During the attempt the plank tipped {len(mon['tips'])} time(s): " + "; ".join(descr) + ".") + return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + n_tips=len(mon["tips"]), tips=mon["tips"], tilt_max=round(mon["tilt_max"], 1), + tilt_final=round(self.tilt_deg(), 1), hazard=bool(inst["hazard"]), + mark_offsets_cm={c: (100 * self.mark_offset(c)).round(1).tolist() for c in COLORS}, + on_plank={c: self.on_plank(c) for c in COLORS}, detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, c): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _y_on_plank(self): + """cubes resting on the plank now -> their position along it""" + return {c: float(self.in_plank(self.cube_pos(c))[1]) for c in COLORS if self.on_plank(c) and not self.held(c)} + + def plank_calm(self): + _, da = envs.free_joint_addr(self.env, PLANK) + return abs(self.tilt_deg()) < 1.0 and float(np.linalg.norm(self.env.sim.data.qvel[da + 3:da + 6])) < 0.05 + + def wait_calm(self, max_steps=60): + """hold the arm still until the plank has stopped swinging (a careful agent looks before it acts)""" + n = 0 + for _ in range(max_steps): + if self.plank_calm(): + n += 1 + if n >= 5: + return True + else: + n = 0 + self.sk.hold(1) + return False + + def pick(self, c, z_carry): + sk = self.sk + p = self.cube_pos(c) + yaw = self._grasp_yaw(c) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], max(TZ + z_carry, p[2] + 0.06)], yaw=yaw) + 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], TZ + z_carry], speed=0.3) + if not self.held(c): + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], TZ + z_carry]) + return False + return True + + def put(self, c, z_carry=Z_CARRY, noise=None, record=False, careful=False): + """Pick cube c wherever it is and put it on its mark: carry it over the mark, lower it until its bottom is + REL_GAP above the plank, release, lift. Returns whether the plank tipped (|tilt| > TIP_DEG) during the + placement, or None if the cube could not be picked. record=True appends the observation (cubes on the plank + right before the release + this one on its mark, tipped?) for the adaptive script.""" + for _ in range(2): + if self.pick(c, z_carry): + break + else: + return None + sk = self.sk + d = self.mark_world(c) + if noise is not None: + d = d + np.array([noise[0], noise[1], 0.0]) + sk.move_to([d[0], d[1], TZ + z_carry], yaw=0.0) + if careful: + self.wait_calm() + d = self.mark_world(c) + (np.array([noise[0], noise[1], 0.0]) if noise is not None else 0.0) + sk.move_to([d[0], d[1], d[2] + CUBE_E / 2 + REL_GAP], tol=0.003) + was_level = self.plank_calm() + conf = self._y_on_plank() + conf[c] = float(self.inst["marks"][c]) + self.mon["win_max"] = abs(self.tilt_deg()) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], TZ + z_carry]) + sk.hold(12) + tipped = self.mon["win_max"] > TIP_DEG + if tipped: + envs.settle(self.env, 30) # let the cubes slide down + if record and was_level: + self.obs.append(dict(conf=conf, tipped=bool(tipped), after=c)) + return tipped + + def park(self, c): + """take cube c off the plank and set it on a free spot of the table beside the plank""" + x0, y0 = self.inst["plank_xy"] + others = [self.cube_pos(o)[:2] for o in COLORS if o != c] + cands = [np.array([x0 + dx, y0 + sy * dy]) for sy in (1, -1) for dy in (0.18, 0.25) + for dx in (-0.12, -0.04, 0.04, 0.12)] + best = max(cands, key=lambda q: min(np.linalg.norm(q - o) for o in others)) + if not self.pick(c, Z_CARRY): + return False + sk = self.sk + sk.move_to([best[0], best[1], TZ + Z_CARRY], yaw=0.0) + sk.move_to([best[0], best[1], TZ + CUBE_E / 2 + 0.004], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([best[0], best[1], TZ + Z_CARRY]) + return True + + # ---- planning with the static model + def plan(self, todo, hyps): + """Best order to (re)place the cubes in `todo`, given the cubes now on the plank, minimising the worst tip ratio + over the mass hypotheses `hyps` (list of {colour: kg}). A cube that is on the plank off its mark is lifted + (its moment removed) and then set on its mark. Returns (order, worst ratio).""" + cur0 = self._y_on_plank() + best, best_w = list(todo), np.inf + for order in itertools.permutations(todo): + w = 0.0 + for mass in hyps: + cur = dict(cur0) + for c in order: + if c in cur: + del cur[c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + cur[c] = self.inst["marks"][c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + if w < best_w - 1e-9: + best, best_w = list(order), w + return best, best_w + + def hypotheses(self, use_obs=True): + """Heavy / light assignments (nominal masses) that (1) leave the finished layout balanced, (2) admit a loading + order that never tips the plank (the task is solvable) and (3) agree with every observed placement (tipped or + not, with a +-10 % band in which either outcome counts as consistent). Falls back to (1)+(2) if no assignment + agrees with all observations.""" + marks = self.inst["marks"] + prior = [] + for k in range(5): + for heavy in itertools.combinations(COLORS, k): + mass = {c: (H_EST if c in heavy else L_EST) for c in COLORS} + if tip_ratio([(mass[c], marks[c]) for c in COLORS]) > 0.6: + continue + for order in itertools.permutations(COLORS): + cur, w = [], 0.0 + for c in order: + cur.append((mass[c], marks[c])) + w = max(w, tip_ratio(cur)) + if w <= 0.9: + prior.append(mass) + break + if not use_obs: + return prior + post = [] + for mass in prior: + if all(not ((ob["tipped"] and r < 0.9) or (not ob["tipped"] and r > 1.1)) + for ob in self.obs for r in [tip_ratio([(mass[o], y) for o, y in ob["conf"].items()])]): + post.append(mass) + return post or prior + + def unload_until_level(self, max_moves=4): + """while the plank is tipped: take the cube farthest out on its low side off the plank""" + for _ in range(max_moves): + envs.settle(self.env, 20) + self.wait_calm() + if self.is_level(): + return True + t = self.tilt_deg() + yo = self._y_on_plank() + low = [c for c, y in yo.items() if (y > 0) == (t < 0)] + if not low: + return self.is_level() + self.park(min(low, key=lambda o: abs(yo[o]))) # the top of the pile first: the hand clears the others + envs.settle(self.env, 20) + self.wait_calm() + return self.is_level() + + def restore(self, hyps_fn, rounds=3, record=False): + """Check every stage; if something is wrong: unload the low end if the plank is tipped, then (re)place every + cube that is not on its mark in the order the static model rates safest under the current mass hypotheses; + start over after a tip. Up to `rounds` passes.""" + for _ in range(rounds): + envs.settle(self.env, 20) + if all(self.stage_values().values()): + return True + self.unload_until_level() + todo = [c for c in COLORS if not self.on_mark(c)] + if not todo: + continue + hyps = hyps_fn() + order, worst = self.plan(todo, hyps) + if worst > 0.9: # cubes left on the plank make every order risky: clear it and start from empty + for c in [c for c in COLORS if self.on_plank(c)]: + self.park(c) + order, worst = self.plan(list(COLORS), hyps) + for c in order: + if self.on_mark(c): + continue + if self.put(c, Z_CARRY, record=record, careful=True): + break # tipped: look again + envs.settle(self.env, 20) + return all(self.stage_values().values()) + + def naive_order(self, noise_sd=0.0, rng=None): + """nearest cube first, starting from the gripper's position and then from each mark just loaded""" + p = self.sk.eef_pos()[:2] + left, order = list(COLORS), [] + while left: + dist = {c: np.linalg.norm(self.cube_pos(c)[:2] - p) + (rng.normal(0, noise_sd) if rng is not None else 0.0) + for c in left} + c = min(left, key=dist.get) + order.append(c) + left.remove(c) + p = self.mark_world(c)[:2] + return order + + def slot_order(self, kind): + so = {s: c for c, s in self.inst["slot_of"].items()} + seq = dict(end2end=SLOTS, alt_outer=("near_outer", "far_outer", "near_inner", "far_inner"), + alt_inner=("near_inner", "far_inner", "near_outer", "far_outer"))[kind] + return [so[s] for s in seq] + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("seed", 0)) + mode = params["mode"] + if mode == "plan": + hyps = [dict(inst["mass"])] if params.get("true_masses") else self.hypotheses() + order, _ = self.plan(list(COLORS), hyps) + elif mode in ("end2end", "alt_outer", "alt_inner"): + order = self.slot_order(mode) + else: # nearest first (naive / blind) + order = self.naive_order(params.get("order_noise", 0.0), rng) + noise = params.get("noise", 0.0) + z_carry = Z_CARRY if params.get("careful") else Z_CARRY_NAIVE + for c in order: + nz = rng.uniform(-noise, noise, 2) if noise else None + tipped = self.put(c, z_carry, noise=nz, record=params.get("record", False), careful=params.get("careful", False)) + if tipped and params.get("check_each"): + break # look at what happened, then restore below + if params.get("check"): + hyps_fn = (lambda: [dict(inst["mass"])]) if params.get("true_masses") else self.hypotheses + self.restore(hyps_fn, record=params.get("record", False)) + self.sk.hold(10) + return order + + def default_params(self, inst): + return dict(mode="nearest", check=False) + + def oracle_params(self, inst): + return dict(mode="plan", true_masses=True, careful=True, check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load in the order the observations of earlier attempts make safest, check after every + placement and restore at the end""" + return dict(mode="plan", careful=True, check=True, check_each=True, record=True) + + def blind_params(self, inst, attempt, rng): + """nearest-first again with small random variation (order noise, 4 mm placement noise), no history, no check""" + return dict(mode="nearest", check=False, order_noise=0.03, noise=0.004, seed=int(rng.integers(1 << 30))) + + 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 = [] + self.obs = [] + 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": # attempt 1: natural order, but look after every placement and restore + params = (dict(mode="nearest", check=True, check_each=True, record=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 in ("end2end", "alt_outer", "alt_inner"): # extra controls: other natural orders, no check + params = dict(mode=kind, check=False) + elif kind == "oracle_noise": # extra control: the oracle with +-5 mm (uniform) placement noise + params = dict(self.oracle_params(inst), noise=0.005, seed=int(rng.integers(1 << 30))) + elif kind == "switch": # extra control: no in-attempt repair, learn the order across attempts only + params = (dict(mode="nearest", check=False, record=True) if a == 0 else + dict(mode="plan", careful=True, check=False, record=True)) + else: + raise ValueError(kind) + order = self.execute(inst, params) + out = self.outcome(inst) + out["order"] = order + 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", "oracle_noise", "naive", "end2end", "alt_outer", "alt_inner"): + break + return history diff --git a/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_bridge.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..b10b75576304ed46284ba5002c7857fc458d3669 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_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/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_nudge_row.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_nudge_row.py new file mode 100644 index 0000000000000000000000000000000000000000..e681fb7e676fcda50cc393a648311f31083de9f9 --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_nudge_row.py @@ -0,0 +1,821 @@ +"""LH lh_nudge_row v2 (2026-10-14): stand four small cups, one by one, on the four coloured mats of their colours; the +mats lie in two rows of two, and in 7 of 10 instances the two mats of a row touch. Letting go of a cup with the fingers +opening towards the cup already standing on the next mat pushes that cup 1.5-3.4 cm sideways, half off its mat -- it +stays upright, so the damage is small but visible (a near miss that has to be noticed and undone before finishing). + +Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically undo an +earlier one; the agent has to look back at all cups before finishing (within an attempt) or learn to let go without +pushing (across attempts). + +v1 -> v2 (Sonnet 5.5 pilot np_lh_nudge_row, seeds 3000-3002, k=3, measured): v1 used round rings with a 0.8 cm +tolerance. Sonnet put the cups 0.8-2.2 cm too far forward (+x, away from the robot) in almost every attempt and could not +see it (the oblique agentview camera looks along x; a tall cup hides the ring behind it), so 5 of 7 attempts failed +without any nudge (one was a calibration attempt), and the one clear nudge (s3000) left the cup 0.83 cm off -- +invisible. Its left-right errors were <= 0.7 cm, its releases in attempt 1 almost all at wrist yaw ~0 (fingers opening +left-right), and it learned yaw 45 for the last cup after the nudge. v2 therefore (1) replaces the rings by mats 9 cm long (forward-back, tolerance 3 cm: a 2 cm forward bias +passes) and 4.6 cm wide (left-right, tolerance 1.3 cm), (2) puts the two mats of a row edge to edge so that a yaw-0 +release pushes the neighbour sideways, where the camera resolves it, off its mat onto the table, and (3) uses slimmer cups +(2 x 5 cm instead of 4 x 6 cm): the open finger reaches farther past them, so the push is 1.5-3.4 cm instead of 0.3-2.3. +Code and results of v1: lh_nudge_row.py.bak-20261014-v1, results/_old/lh_nudge_row_v1/. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * four coloured mats (dark red, blue, green, ochre; flat, visual only), each 9.0 cm (forward-back) x 4.6 cm, in two rows + (far and near, 1.5 cm apart); block centre 53-59 cm in front of the robot base. Tight block (14 of every 20 + consecutive seeds): the two mats of a row touch. Spaced block (6 of 20): they are 4-5 cm apart and no open finger + reaches the neighbour (the benign instances); + * four slim cups of the bright same colours (2.0 cm wide, 5.0 cm tall, open top, glazed base: friction 0.08-0.12, + 20-32 g), standing in a line 17.5-19 cm from the block on the robot's side, or on its left or right side, in random + order and 9-10 cm apart. + +Risk factor: the block's spacing (visible, instance level); there is no hidden physical variable (v1 measured that a +rubber-footed cup gets tipped over by a re-grasp next to it, and a fallen cup cannot be stood up again). + +Disturbance (physics, no teleport): the gripper opens to 7.9 cm, i.e. each finger moves 3 cm out from a 2 cm cup; the +outer face of an open finger reaches 5.4 cm (tip) to 6.6 cm (upper part) from the grasp point; in a tight block the +neighbour's wall is 3.6 cm away (+- the placement errors). Measured: letting go with the fingers along the row (wrist yaw +0) pushes the neighbour 1.2-3.2 cm sideways, upright (18/18 trials: base friction 0.08 / 0.12 x grasp 0.8-2 cm below the +rim x put down 0.8 cm towards / on target / 0.8 cm away from it, each followed by three re-grasps); re-grasping a placed cup with the fingers towards the neighbour pushes it about 0.3 cm more. With +friction 0.18 or with 2.6 cm cups whose closed finger already presses the neighbour's rim, slim cups tipped over (4/18 +and 6/18) -- hence the low friction and the 2 cm cups. A careful agent avoids the push by letting go with the fingers +opening forward-back (wrist yaw 90: the mats of the other row are 10.5 cm away) or diagonally, and repairs it by +re-centring the pushed cup (lifted 10 cm, carried back, let go the same careful way). + +Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each cup stands upright +(tilt <= 10 deg) on the table, not held, with its whole base on its own mat: centre within 3.0 cm (forward-back) and +1.3 cm (left-right) of the mat's centre. Success = all four at the end, gripper open and not touching any cup, scene +static. The monitor logs achieved / lost / restored per cup, cup_nudged (lost while not held, with displacement and +cause), cup_bumped (pushed by the robot but still on its mat) and cup_restored, 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"] +CUPS = [f"cup_{c}_1" for c in COLOURS] +MATS = [f"mat_{c}_1" for c in COLOURS] +RGBA = {"red": (0.82, 0.16, 0.13, 1.0), "blue": (0.16, 0.36, 0.82, 1.0), "green": (0.16, 0.62, 0.26, 1.0), + "yellow": (0.92, 0.76, 0.12, 1.0)} +MAT_RGBA = {"red": (0.55, 0.13, 0.12, 1.0), "blue": (0.12, 0.22, 0.52, 1.0), "green": (0.10, 0.38, 0.16, 1.0), + "yellow": (0.62, 0.50, 0.08, 1.0)} # dark shades: crisp edges on the light table, bright cups stand out +INSIDE_RGBA = (0.93, 0.92, 0.88, 1.0) # glazed inside of the cups (seen from above) + +# cup geometry (fixed; only mass and base friction change per instance, so no runtime geom edits / BVH refits) +CUP_R, CUP_H = 0.010, 0.050 # slim cups (2 x 5 cm): the open fingers reach far past them (v1: 4 x 6 cm) +COM_Z = -0.006 # centre of mass below the cup's mid-height (heavier base) +WALL_T, BASE_T = 0.0025, 0.003 +NSEG = 12 +CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"' +WALL_MU = 0.8 +BASE_MU = (0.08, 0.12) # glazed base: a pushed cup slides; at 0.18 a slim cup pushed high up tipped (measured) +MASS = (0.020, 0.032) + +# mats (targets) and block +TOL_X = 0.030 # forward-back: the cup centre may be 3 cm from the mat centre (mat 9 cm long) -- Sonnet's measured +# placement bias is 1-2.5 cm forward (v1 pilot), invisible to it in the oblique camera +TOL_Y = 0.013 # left-right: 1.3 cm (mat 4.6 cm wide); a finger-opening push (1.2-3.2 cm, measured) fails it +MAT_L, MAT_W = 2 * (CUP_R + TOL_X), 2 * (CUP_R + TOL_Y) # base completely on the mat <=> centre within the tolerances +ROW_GAP = 0.015 # gap between the far row and the near row of mats (x) +SPACED_GAP = (0.040, 0.050) # spaced block: gap between the two mats of a row (y); an open finger cannot reach +P_TIGHT = 0.70 # 14 of every 20 consecutive seeds: the two mats of a row touch +BLOCK_X = (-0.13, -0.07) # block centre in world x (53-59 cm in front of the robot base) +SUP_D = (0.175, 0.19) # supply line distance from the block centre +SUP_GAP = (0.090, 0.100) + +# predicates / monitor +TILT_OK = np.radians(10.0) +ON_TABLE = 0.004 +HYST = 0.002 +DEBOUNCE = 10 # control steps (0.5 s) +BUMP_MIN = 0.003 + +# scripted motion (heights of the grasp point above the table) +Z_CARRY = 0.20 # Sonnet: lifts to ~20 cm before moving (lh2/lh3 pilots) +Z_LIFT = 0.15 # re-placing a cup that is already down: lift it this high (its base 11 cm up) before moving it +NAIVE_BIAS = (0.008, 0.022) # Sonnet's systematic forward placement error (v1 pilot: +0.8 ... +2.2 cm, per instance) +NAIVE_RAND = 0.006 # +- random placement error per axis (v1 pilot: left-right errors <= 0.7 cm) +NAIVE_FIX_RAND = 0.003 # after re-placing its own cup +FINGER_IN, FINGER_OUT, FINGER_HALF = 0.039, 0.066, 0.013 # open finger footprint (m from the grasp point / half width) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def cup_xml(name, rgba): + """open-top cup: 12 wall boxes (1 mm above the bottom) and an octagonal base of two square boxes (box-box contacts: + a light cylinder on the table creeps by itself in MuJoCo, measured 1.6 cm / 5 s). Visual: a smooth cylinder with the + glazed inside at the top. The compiled inertial is replaced per instance (mass), the base friction too.""" + r, h = CUP_R, CUP_H + g = [f' '] + s = r * np.sin(np.pi / NSEG) + 0.0006 + rc = r * np.cos(np.pi / NSEG) - WALL_T / 2 + for k in range(NSEG): + a = 2 * np.pi * k / NSEG + q = [np.cos(a / 2), 0, 0, np.sin(a / 2)] + g.append(f' ') + a0 = r * 0.70 + for k, ang in enumerate((0.0, np.pi / 4)): + q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)] + g.append(f' ') + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), h / 2, r) + + +def mat_xml(name, rgba): + """flat coloured mat (visual only), long side along body x""" + g = (f' ') + return _wrap(name, g, 0.0004, float(np.hypot(MAT_L, MAT_W) / 2)) + + +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'}" + + +class NudgeSkills(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 NudgeRow(LFFTask): + name = "lh_nudge_row" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + # careful: ~10 commands per cup (40) + re-placing an imprecise cup or two (~15) + re-centring two pushed cups (~20) + # + looking / small corrections (~20), with some margin + agent_max_steps = 110 + instruction = ("Stand each of the four small cups on the mat of the same colour. The four coloured mats lie on the " + "table in two rows of two. At the end every cup must stand upright with its whole base on its own " + "mat (not touching another mat or the table around it), and the gripper must be open and clear of " + "the cups.") + instruction_indirect = ("Set each little cup down on the coloured patch that matches it; the four patches form two " + "rows of two. When you are done every cup has to stand upright with its bottom completely " + "on its own patch, and the gripper must be open and away from the cups.") + agent_object_names = ["small cups (red, blue, green, yellow)", + "coloured mats (red, blue, green, yellow) in two rows of two"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for i, (c, cup) in enumerate(zip(COLOURS, CUPS)): + cat = register_generated(f"LffLhnCup{c.capitalize()}", cup_xml(f"lff_lhn_cup_{c}", RGBA[c])) + objs.append((cup, cat, f"cup{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + for i, (c, mat) in enumerate(zip(COLOURS, MATS)): + cat = register_generated(f"LffLhnMat{c.capitalize()}", mat_xml(f"lff_lhn_mat_{c}", MAT_RGBA[c]), free=False) + fx.append((mat, cat, f"mat{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30))) + return write_bddl(self.name, "Stand each cup on the mat of its colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.mat_bid = {k: m.body_name2id(self.env.fixtures_dict[k].root_body) for k in MATS} + self.cgeoms = {c: envs.obj_geom_ids(self.env, c) for c in CUPS} + self.cbody = {c: int(m.geom_bodyid[self.cgeoms[c][0]]) for c in CUPS} + self.base_geoms = {c: [g for g in self.cgeoms[c] if (m.geom_id2name(g) or "").split("_")[-1] in ("b0", "b1")] + for c in CUPS} + self.finger_geoms, self.hand_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).append(g) + # per-geom lookup tables for the substep contact check: cup index (-1 none), robot part (1 finger, 2 hand) + self.owner = np.full(m.ngeom, -1, int) + for i, c in enumerate(CUPS): + self.owner[self.cgeoms[c]] = i + self.part = np.zeros(m.ngeom, int) + self.part[self.finger_geoms] = 1 + self.part[self.hand_geoms] = 2 + self._sub_rob, self._sub_obj = {}, {} + # contacts are collected after every MuJoCo substep: an opening finger can flick a light cup within one control + # step (same technique as lh_fence; wrappers chain) + sim = self.env.sim + if not getattr(sim, "_lhn_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhn_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhn_wrapped = True + sim._lhn_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) + tight = bool((int(seed) * 7) % 20 < round(20 * P_TIGHT)) # balanced: 14 of every 20 consecutive seeds + gap_y = 0.0 if tight else float(rng.uniform(*SPACED_GAP)) + py = MAT_W + gap_y # mat centre to mat centre within a row (left-right) + px = MAT_L + ROW_GAP # far row to near row (forward-back) + bx = float(rng.uniform(*BLOCK_X)) + side = str(rng.choice(["front", "left", "right"])) + by = float(rng.uniform(-0.04, 0.04)) + if side == "left": + by = float(rng.uniform(-0.08, -0.04)) + elif side == "right": + by = float(rng.uniform(0.04, 0.08)) + # mat positions: block slots (far-left, far-right, near-left, near-right), colours permuted + slots = {"far_left": [bx + px / 2, by + py / 2], "far_right": [bx + px / 2, by - py / 2], + "near_left": [bx - px / 2, by + py / 2], "near_right": [bx - px / 2, by - py / 2]} + names = list(slots) + perm = rng.permutation(4) + mats = {COLOURS[i]: slots[names[perm[i]]] for i in range(4)} + slot_of = {COLOURS[i]: names[perm[i]] for i in range(4)} + # supply line + d = float(rng.uniform(*SUP_D)) + gap = float(rng.uniform(*SUP_GAP)) + offs = (np.arange(4) - 1.5) * gap + float(rng.uniform(-0.02, 0.02)) + if side == "front": + sup = [[bx - d + float(rng.uniform(-0.008, 0.008)), by + o] for o in offs] + else: + sgn = 1.0 if side == "left" else -1.0 + sup = [[bx + o, by + sgn * (d - 0.02) + float(rng.uniform(-0.008, 0.008))] for o in offs] + order = rng.permutation(4) + start = {COLOURS[i]: [float(v) for v in sup[order[i]]] for i in range(4)} + mu = {c: float(rng.uniform(*BASE_MU)) for c in COLOURS} + mass = {c: float(rng.uniform(*MASS)) for c in COLOURS} + yaw0 = {c: float(rng.uniform(-np.pi, np.pi)) for c in COLOURS} + return dict(seed=int(seed), pitch_y=py, pitch_x=px, gap_y=gap_y, block=[bx, by], supply_side=side, + supply_d=d, supply_gap=gap, mats=mats, slot_of=slot_of, start=start, mu=mu, mass=mass, yaw0=yaw0, + tight=tight, block_kind="tight" if tight else "spaced", + naive_bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c, cup in zip(COLOURS, CUPS): + b = self.cbody[cup] + M = inst["mass"][c] + m.body_mass[b] = M + # thin-walled cup (wall + base), approximately + m.body_inertia[b] = [M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), + M * CUP_R ** 2 * 0.8] + for g in self.base_geoms[cup]: + m.geom_friction[g] = [inst["mu"][c], 0.005, 0.0001] + m.geom_priority[g] = 2 + for c, mat in zip(COLOURS, MATS): + x, y = inst["mats"][c] + m.body_pos[self.mat_bid[mat]] = [x, y, TZ + 0.0005] + m.body_quat[self.mat_bid[mat]] = [1.0, 0.0, 0.0, 0.0] + self.env.sim.forward() + for c, cup in zip(COLOURS, CUPS): + envs.place_upright(self.env, cup, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + + 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 = NudgeSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj = {}, {} + n = len(CUPS) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + lost_cause=[None] * n, + anchor=[None] * n, last_robot=[None] * n, last_obj=[None] * n, nudged=[False] * n, + bump_ref=[None] * n, bump_step=[-1000] * n, n_steps=0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def pos(self, cup): + return envs.obj_pos(self.env, cup) + + def tilt(self, cup): + return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, cup), -1.0, 1.0))) + + def held(self, cup): + return self.sk is not None and self.sk.holding(cup) + + def mat_xy(self, i): + return np.asarray(self.inst["mats"][COLOURS[i]], float) + + def offset(self, i): + return self.pos(CUPS[i])[:2] - self.mat_xy(i) + + @staticmethod + def within(off, extra=0.0): + """mat-frame offset (x forward-back, y left-right) inside the tolerances = the cup's whole base on its mat""" + return abs(float(off[0])) <= TOL_X + extra and abs(float(off[1])) <= TOL_Y + extra + + def on_mat(self, i, extra=0.0): + cup = CUPS[i] + if self.tilt(cup) > TILT_OK + (np.radians(2.0) if extra else 0.0): + return False + if not self.within(self.offset(i), extra): + return False + if envs.obj_min_z(self.env, cup) > TZ + ON_TABLE: + return False + return not self.held(cup) + + def stages(self): + return [self.on_mat(i) for i in range(len(CUPS))] + + # ------------------------------------------------------------ monitor + 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 = dict(self._sub_rob) + obj = dict(self._sub_obj) + self._sub_rob, self._sub_obj = {}, {} + gstate = "open" if self.sk.grip < 0 else "closed" + for i, part in rob.items(): + if not self.held(CUPS[i]): + mon["last_robot"][i] = ["finger" if part == 1 else "hand", int(t), gstate] + for i, j in obj.items(): + mon["last_obj"][i] = [COLOURS[j] + (" (held)" if self.held(CUPS[j]) else ""), int(t)] + if mon["n_steps"] % 2: + return + for i in range(len(CUPS)): + cup = CUPS[i] + raw = self.on_mat(i, HYST if mon["state"][i] else 0.0) + # bumps inside the tolerance + if mon["state"][i] and raw and not self.held(cup): + lr = mon["last_robot"][i] + if lr is not None and t - lr[1] <= 2 and mon["bump_ref"][i] is None: + mon["bump_ref"][i] = [self.pos(cup)[:2].tolist(), int(t), 0.0] + ref = mon["bump_ref"][i] + if ref is not None: + ref[2] = max(ref[2], float(np.degrees(self.tilt(cup)))) + if t - ref[1] > 40: + dpos = float(np.linalg.norm(self.pos(cup)[:2] - np.asarray(mon["anchor"][i] or ref[0]))) + if (dpos >= BUMP_MIN or ref[2] >= 2.0) and t - mon["bump_step"][i] > 60: + mon["events"].append(dict(cup=COLOURS[i], event="cup_bumped", step=int(ref[1]), + moved_cm=round(100 * dpos, 2), max_tilt_deg=round(ref[2], 1), + cause=self._cause(i, ref[1] + 1))) + mon["bump_step"][i] = int(t) + mon["bump_ref"][i] = None + 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] # picked_up = the agent re-adjusted a cup it had placed itself + mon["events"].append(e) + if restored and mon["nudged"][i]: + mon["events"].append(dict(cup=COLOURS[i], event="cup_restored", step=t0)) + mon["nudged"][i] = False + mon["ever"][i] = True + mon["anchor"][i] = self.pos(cup)[:2].tolist() + mon["bump_ref"][i] = None + else: + mon["lost"][i] = True + cause = self._cause(i, t) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause)) + if cause != "picked_up": + a = mon["anchor"][i] + d = self.pos(cup)[:2] - np.asarray(a if a is not None else self.mat_xy(i)) + off = self.offset(i) + mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t0, cause=cause, + moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)], + offset_cm=round(100 * float(np.linalg.norm(off)), 2), + tilt_deg=round(float(np.degrees(self.tilt(cup))), 1))) + mon["nudged"][i] = True + + def _cause(self, i, t, window=60): + if self.held(CUPS[i]): + return "picked_up" + lr, lo = self.mon["last_robot"][i], self.mon["last_obj"][i] + cands = [] + if lr is not None and t - lr[1] <= window: + cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else ""))) + if lo is not None and t - lo[1] <= window: + cands.append((lo[1] - 30, "cup:" + lo[0])) # prefer the robot when both touched it recently + return max(cands)[1] if cands else "other" + + def _finalize_monitor(self, raw): + """close the event log at finish: a stage the debounced monitor still holds (it uses a 2 mm hysteresis) but the + final judge does not is logged as lost now (final=True), and vice versa""" + mon = self.mon + if mon is None: + return + t = int(self.sk.n_steps) + for i in range(len(CUPS)): + 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 + continue + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) # the last contact may be long ago (slow creep across the line) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True)) + if cause != "picked_up": + a = mon["anchor"][i] + d = self.pos(CUPS[i])[:2] - np.asarray(a if a is not None else self.mat_xy(i)) + mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t, cause=cause, final=True, + moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)], + offset_cm=round(100 * float(np.linalg.norm(self.offset(i))), 2), + tilt_deg=round(float(np.degrees(self.tilt(CUPS[i]))), 1))) + mon["nudged"][i] = True + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + rob = set(self.finger_geoms) | set(self.hand_geoms) + for j in range(d.ncon): + c = d.contact[j] + if (self.owner[c.geom1] >= 0 and c.geom2 in rob) or (self.owner[c.geom2] >= 0 and c.geom1 in rob): + return True + return False + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {c: self.pos(c) for c in CUPS} + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max(float(np.linalg.norm(self.pos(c) - p0[c])) for c in CUPS) + static = moved < 0.003 + raw = self.stages() + self._finalize_monitor(raw) + held = [COLOURS[i] for i, c in enumerate(CUPS) if self.held(c)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + 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) + nudges = [e for e in ev if e.get("event") == "cup_nudged"] + bumps = [e for e in ev if e.get("event") == "cup_bumped"] + success = bool(all(raw) and static and not held and not touching) + ever = mon["ever"] if mon else [False] * len(CUPS) + tilted = [i for i in range(len(CUPS)) if self.tilt(CUPS[i]) > TILT_OK] + lost_final = [i for i in range(len(CUPS)) if not raw[i] and ever[i]] + never = [i for i in range(len(CUPS)) if not raw[i] and not ever[i]] + if success: + failure = "none" + elif held: + failure = "held" + elif touching: + failure = "touching" + elif tilted: + failure = "tipped" + elif lost_final: + failure = "nudged_out" if any(mon["nudged"][i] for i in lost_final) else "regressed" + elif never: + failure = "not_on_mat" + else: + failure = "not_static" + parts = [] + if success: + parts.append("Every cup stands upright on the mat of its colour.") + for i in range(len(CUPS)): + if raw[i]: + continue + c, cup = COLOURS[i], CUPS[i] + if c in held: + parts.append(f"The {c} cup is still held by the gripper.") + continue + off = self.offset(i) + tl = np.degrees(self.tilt(cup)) + where = f"{_fb(off[0])} and {_lr(off[1])} of the {c} mat's centre" + if tl > np.degrees(TILT_OK): + txt = (f"The {c} cup has fallen over" if tl > 45 else f"The {c} cup leans {tl:.0f} degrees") + f", {where}." + elif float(np.linalg.norm(off)) > 0.08: + txt = f"The {c} cup is not on the {c} mat (its centre is {100 * float(np.linalg.norm(off)):.0f} cm away)." + else: + over = [] + if abs(off[1]) > TOL_Y: + over.append(f"{100 * (abs(off[1]) - TOL_Y):.1f} cm over the mat's {'left' if off[1] > 0 else 'right'} " + f"edge") + if abs(off[0]) > TOL_X: + over.append(f"{100 * (abs(off[0]) - TOL_X):.1f} cm over its {'far' if off[0] > 0 else 'near'} end") + txt = f"The {c} cup stands {where}; its base sticks out " + " and ".join(over) + "." + if ever[i]: + lost = [e for e in ev if e.get("stage") == c and e.get("event") == "lost"] + why = lost[-1].get("cause", "other") if lost else "other" + txt += {"robot_finger_opening": " It had stood on its mat; a finger pushed it when the gripper opened " + "next to it.", + "robot_finger": " It had stood on its mat; a finger pushed it.", + "robot_hand": " It had stood on its mat; the hand pushed it.", + }.get(why, " It had stood on its mat earlier and was pushed by another cup." + if why.startswith("cup:") else " It had stood on its mat earlier.") + parts.append(txt) + if not success and all(raw): + if touching: + parts.append("The gripper is still touching a cup.") + elif not static: + parts.append("Something was still moving.") + if nudges: + parts.append(f"During the attempt cups that stood on their mats were pushed off {len(nudges)} time(s); " + f"{n_res} time(s) a cup was put back.") + trap = bool(nudges) + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(CUPS))}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_nudged=len(nudges), + n_bumped=len(bumps), trap_fired=trap, recovered_in_attempt=bool(trap and success), + nudged_cups=sorted({e["cup"] for e in nudges}), failure=failure, held=held, + touching=bool(touching), static=bool(static), + offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)] for i in range(4)}, + tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(CUPS[i]))), 1) for i in range(4)}, + tight=bool(inst["tight"]), 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 _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def finger_clear(self, q, yaw, ignore=()): + """smallest distance (m) between the open fingers at grasp point q (xy) with gripper yaw `yaw` and the wall of + any standing cup other than `ignore`; finger axis (-sin yaw, cos yaw)""" + a = np.array([-np.sin(yaw), np.cos(yaw)]) + b = np.array([a[1], -a[0]]) + best = 1.0 + for cup in CUPS: + if cup in ignore or self.held(cup): + continue + rel = self.pos(cup)[:2] - np.asarray(q, float) + for s in (1.0, -1.0): + u = s * float(rel @ a) + v = float(rel @ b) + du = max(FINGER_IN - u, 0.0, u - FINGER_OUT) + dv = max(abs(v) - FINGER_HALF, 0.0) + best = min(best, float(np.hypot(du, dv)) - CUP_R) + return best + + def safe_yaw(self, q, ignore=(), prefer=0.0): + """the gripper yaw (0, 90, +-45 deg) whose open fingers stay farthest from the other cups at q""" + cands = [0.0, np.pi / 2, np.pi / 4, -np.pi / 4] + sc = [(round(min(self.finger_clear(q, y, ignore), 0.02), 3), -abs(_wrap_h(y - prefer)), y) for y in cands] + return max(sc)[2] + + def grasp_cup(self, cup, yaw, depth, z_carry=Z_CARRY, v=0.2, err=None, lift=None): + """open, go over the cup at transit height, straight down, close, lift. Returns True if held.""" + sk = self.sk + p = self.pos(cup) + q = p[:2] + (np.asarray(err, float) if err is not None else 0.0) + zg = envs.obj_max_z(self.env, cup) - depth + sk.set_gripper(False, steps=8) + self._lift_to(z_carry) + self._go([q[0], q[1], max(sk.eef_pos()[2], TZ + z_carry)], yaw=yaw, speed=v) + self._go([q[0], q[1], zg + 0.015], speed=0.10) + self._go([q[0], q[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.12) + sk.hold(5) + if not self.held(cup): + sk.set_gripper(False, steps=8) + return False + return True + + def put_cup(self, cup, xy, yaw, z_carry=Z_CARRY, v=0.2, lift=None): + """carry the held cup so that the cup (not the grasp point) is over xy, rotate to `yaw`, straight down until its + base is 3 mm above the table, let go, lift""" + sk = self.sk + rel = self.pos(cup)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + cur = sk.eef_pos() + self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v) + sk.hold(5) + rel = self.pos(cup)[:2] - sk.eef_pos()[:2] # the cup can shift in the fingers while the wrist turns + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, cup) + zr = TZ + dz + 0.003 + self._go([q[0], q[1], zr + 0.015], speed=0.10) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.15) + sk.hold(3) + + def mat_order(self, mode="far_first"): + """colour indices in placement order. far_first (Sonnet): the block row farthest from the supply first, then + the other; within a row from the left (robot's view)""" + sup = np.mean([self.inst["start"][c] for c in COLOURS], axis=0) + blk = np.asarray(self.inst["block"], float) + u = blk - sup + u = u / max(np.linalg.norm(u), 1e-9) + idx = list(range(4)) + far = sorted(idx, key=lambda i: -float((self.mat_xy(i) - blk) @ u)) + rows = [far[:2], far[2:]] + if mode == "near_first": + rows = rows[::-1] + out = [] + for row in rows: + out += sorted(row, key=lambda i: (-self.mat_xy(i)[1], self.mat_xy(i)[0])) # left first + return out + + @staticmethod + def looks_off(off, bias): + """a (biased) observer's verdict: the cup looks off its mat centre by more than 0.8 cm in some direction""" + p = np.asarray(off, float) - np.asarray(bias, float) + return abs(p[0]) > 0.008 or abs(p[1]) > 0.008 + + def place_one(self, i, yaw_rule, depth, rng, bias=(0.0, 0.0), rand=0.0, fix_rand=0.0, check=True, z_carry=Z_CARRY, + v=0.2): + """one stage: pick cup i from wherever it is and put it on its mat; aims at mat + bias (+- rand per axis); then + looks at this cup only (with the same bias) and re-places it if it looks off""" + cup = CUPS[i] + bias = np.asarray(bias, float) + for _ in range(2): + gy = yaw_rule(i, "grasp") + gerr = rng.uniform(-0.003, 0.003, 2) if rand else None + if self.grasp_cup(cup, gy, depth, z_carry=z_carry, v=v, err=gerr): + break + else: + return + e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2) + self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=z_carry, v=v) + if not check: + return + for _ in range(2): + if not self.looks_off(self.offset(i), bias) and self.tilt(cup) < TILT_OK: + return + ry = yaw_rule(i, "grasp") + if not self.grasp_cup(cup, ry, depth, z_carry=Z_LIFT, v=0.1, lift=Z_LIFT): + return + e = rng.uniform(-fix_rand, fix_rand, 2) if fix_rand else np.zeros(2) + self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=Z_LIFT, v=0.1, lift=z_carry) + + def repair(self, rounds=4, depth=0.020, bias=(0.0, 0.0)): + """look at every cup (with the observer's bias); re-centre each one that looks off: grasp and let go with the + fingers opening where no other cup stands. Returns the number of cups moved.""" + bias = np.asarray(bias, float) + moved = 0 + tries = {} + for _ in range(rounds * 4): + bad = [i for i in range(4) if (self.looks_off(self.offset(i), bias) or self.held(CUPS[i])) + and self.tilt(CUPS[i]) < np.radians(30) and tries.get(i, 0) < rounds] + if not bad: + break + i = min(bad, key=lambda j: float(np.linalg.norm(self.pos(CUPS[j])[:2] - self.sk.eef_pos()[:2]))) + tries[i] = tries.get(i, 0) + 1 + cup = CUPS[i] + gy = self.safe_yaw(self.pos(cup)[:2], ignore=(cup,), prefer=self.sk.yaw) + # lift the cup clear of its neighbours before moving it: carried at 10 cm its base clips their rims and + # tips them (v1, measured, 4/20 adaptive runs before this was raised) + if not self.grasp_cup(cup, gy, depth, z_carry=Z_LIFT, v=0.15, lift=Z_LIFT): + continue + moved += 1 + target = self.mat_xy(i) + bias + ry = self.safe_yaw(target, ignore=(cup,), prefer=self.sk.yaw) + self.put_cup(cup, target, ry, z_carry=Z_LIFT, v=0.1, lift=Z_CARRY) + return moved + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + depth = params.get("depth", 0.020) + order = self.mat_order(params.get("order", "far_first")) + mode = params["yaw"] # "fixed" (one wrist yaw for everything) or "safe" (fingers away from placed cups) + y0 = float(params.get("yaw0", 0.0)) + bias = (float(params.get("bias_x", 0.0)), 0.0) + + def yaw_rule(i, what): + if mode == "fixed": + return y0 + q = self.pos(CUPS[i])[:2] if what == "grasp" else self.mat_xy(i) + np.asarray(bias) + return self.safe_yaw(q, ignore=(CUPS[i],), prefer=y0) + + rand = float(params.get("rand", 0.0)) + for i in order: + self.place_one(i, yaw_rule, depth, rng, bias=bias, rand=rand, fix_rand=float(params.get("fix_rand", 0.0)), + check=params.get("self_check", True), z_carry=params.get("z_carry", Z_CARRY), + v=params.get("v", 0.2)) + if params.get("check"): + self.repair(bias=bias) + self._lift_to(0.20) + self.sk.hold(10) + + # naive = Sonnet 5.5's habits measured in the v1 pilot (np_lh_nudge_row): wrist yaw 0 for every grasp and release in + # attempt 1, the row farthest from the supply first, lift to 14-25 cm and carry straight, vertical descents, + # placement 0.8-2.2 cm too far forward (per instance, invisible to it) +- 0.6 cm, looks at the cup it just placed and + # re-places it if it looks off, no look back at the others before finishing + NAIVE = dict(yaw="fixed", yaw0=0.0, order="far_first", self_check=True, check=False, rand=NAIVE_RAND, + fix_rand=NAIVE_FIX_RAND) + CAREFUL = dict(yaw="safe", yaw0=0.0, order="far_first", self_check=True, check=True, rand=0.0, bias_x=0.0) + + def default_params(self, inst): + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, bias_x=float(inst["naive_bias_x"]), + depth=0.008 + 0.012 * ((int(inst["seed"]) * 7) % 11) / 10) # 0.8-2.0 cm below the rim (pilot: ~1 cm) + + def oracle_params(self, inst): + return dict(self.CAREFUL) + + def adapt_params(self, inst, history): + """from attempt 2: let go with the fingers opening away from the placed cups (same imprecision and bias), and + look at every cup before finishing""" + return dict(self.default_params(inst), yaw="safe", check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variation, no history, no final look""" + return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), + yaw0=float(rng.choice([0.0, np.pi / 2])), order=str(rng.choice(["far_first", "near_first"])), + z_carry=float(rng.uniform(0.15, 0.22)), v=float(rng.uniform(0.1, 0.3)), + depth=float(rng.uniform(0.008, 0.025)), bias_x=float(rng.uniform(*NAIVE_BIAS))) + + 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", "naive_yaw90", "naive_check", "careful_bias2", "naive_bias2") + 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": # attempt 1: naive + a final look at every cup (repairs); then careful releases + 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 releases from attempt 2), no final look + params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), yaw="safe") + elif kind == "oracle_noise": # robustness: careful with +-5 mm placement / grasp noise + params = dict(self.CAREFUL, rand=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "naive_yaw90": # control: Sonnet-like but the wrist turned 90 deg for everything + params = dict(self.default_params(inst), yaw0=np.pi / 2) + elif kind == "naive_check": # control: naive + final look (= adaptive's first attempt) + params = dict(self.default_params(inst), check=True) + elif kind == "careful_bias2": # control: careful releases (nothing nudged) but placed 2 cm too far forward + params = dict(self.default_params(inst), yaw="safe", bias_x=0.020) + elif kind == "naive_bias2": # control: naive with a fixed +2 cm forward bias + params = dict(self.default_params(inst), bias_x=0.020) + 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_opus/lff/source_closure/lffbench/tasks/lh_shelf_droop.py b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_shelf_droop.py new file mode 100644 index 0000000000000000000000000000000000000000..d12da555297b5861b08e66421b794b164dd5281e --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_shelf_droop.py @@ -0,0 +1,1009 @@ +"""LH lh_shelf_droop (2026-10-16; v2 the same day): put four jars on a wall shelf. The shelf board hangs on a loose, +spring-loaded fold-down bracket with a weak catch: it stays level as long as the moment of its load about the hinge at +the wall is below the bracket's preload; once the load exceeds it the catch slips and the board folds down to its stop +within about a second, and the jars on it slide off its free edge onto the table, where they lie on their sides. +Jars set down in the middle of the board's depth -- where a careful agent puts them -- push the moment over the preload +with the third jar: a median 0.4 s (90 % within 0.8 s) after that jar is down the board is past 8 deg, and the first +jar slides off a median 1.5 s (1-3 s) after it, while the arm lifts away. The same four jars standing near the wall +(centres up to ~6 cm from it) stay under the preload. Unloaded, the board springs back level. + +Family: long-horizon self-damage ("state_restoration"): a later stage (the third placement) undoes the earlier ones, a +moment after it was done, once the gripper has let go. Within an attempt the agent has to notice the fallen jars, stand +them up again (by their knobs) and put them back -- near the wall, or they slide off again; across attempts it has to +load the shelf near the wall. R4: "I put them down badly / dropped them too hard / my arm knocked them" vs "the shelf +gives way under a load far from the wall". + +v1 -> v2 (measured, scratchpad risk sweeps): v1 had a preloaded spring without a catch (preload 0.45-0.49 N m, 0.6 N m/rad, +damping 2.6-3.4, a slow first-order droop). Jars placed with their centres 6-7 cm from the wall overloaded it only with +the fourth jar, and the board drooped (or the jars slid off) only during the final settle, after `finish` -- 15 of 74 +failing scripted attempts (20 %) showed nothing before finish; 4 jars 6 cm from the wall failed in 9 / 9 seeds. v2 raises +the preload (4 jars up to ~6 cm from the wall hold) and adds the catch + a soft spring + light damping, so every overload +folds the board down within a second, before the agent's next look. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a wall panel (2.5 cm thick, 34 cm + 4 cm long) along x on the robot's right or left (|y| of its face 25-27 cm, centre + x in [-0.17, -0.12]), rising 4.5 cm above the shelf board; + * the shelf board: 34 cm (along the wall) x 20 cm (deep) x 1.2 cm, light wood, top 11 cm above the table, hinged at + the wall face (axis along x at mid-thickness); hard stop at 25 deg of droop. The agentview camera (behind the table, + +x, looking at the robot) sees the board from its end, so the droop is an in-image rotation of the slab; + * four square jars (red, green, blue, yellow; body 5 x 5 x 6 cm, white lid, a 2.2 cm dark ball knob on a 1.2 cm stem; + 10.2 cm tall, 0.24-0.26 kg, centre of mass 2.6 cm up) standing in a row on the table on the other side (|y| 13-17 + cm), 9 cm apart, in random order. + +Hidden variable: the bracket. "loose" (14 of every 20 consecutive seeds): preload 0.62-0.68 N m; "stiff" (6 of 20): +preload 2.5 N m (no placement on the board reaches it). Both look identical. The preload is a spring (0.25 N m/rad +beyond the preload) plus a catch of 0.12 N m that fades out over the first 3 deg of droop; damping 0.45-0.60 N m s/rad. +As the board droops the jars' centres of mass (3.2 cm above the hinge axis) move outwards (+0.08 N m/rad per jar), so +with two or more jars on it nothing stops a board whose catch has slipped before its 25 deg stop. Jar-on-board friction +0.27-0.33 per jar (they slide at ~14.5 deg at 0.30 in MuJoCo's soft contacts). +Moments (jar weight 2.45 N x lever arm of its centre of mass): four jars against the wall (centres 3.5 cm from the +hinge) 0.34 N m; four at 6 cm 0.59 (holds); four at 7 cm 0.69 (over); in the middle of the depth (10.4 cm) one jar 0.25, +two 0.51 (holds), three 0.76 (over). + +Repair: fallen jars lie on the table in front of the board's free edge. Held by the knob (ball, torsional friction +0.0005, condim 4) a lying jar turns between the fingers and hangs straight down (like lh_bystander's bottle cap); the +instruction says so. Put back near the wall, the board stays level. + +Success (final-state judge after a settle of at least 15 s of simulated time with the arm holding still -- longer if +the board is still moving -- so that finishing right after the last placement does not beat the bracket): every jar +stands upright on the board (its bottom on the board's top, within its outline, axis within 10 deg of the board's +normal), not held; the board within 15 deg of level (a board that has folded down holds no standing jar anyway), +touched by nothing but the jars (closes "prop the board" loopholes), the gripper not touching a jar or the board, the +scene static. + +Per-step monitor (server log only; F1 gives the agent success / failure): stage achieved / lost (cause: slid_off, +robot, jar:, picked_up, other) / restored per jar; board sag_start (> 1.5 deg), sag (> 8 deg = trap_fired) and +sag_end, each with the time since the placement that pushed the moment over the preload and the moment itself; +jar_fell (with the time since its own placement and since the sag started). outcome() also reports what the agent's +last images showed at `finish` (board angle, jars already off the board). + +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 +G = 9.81 +DT = 0.05 # control period + +# ---------------------------------------------------------------- jars (square glass jars with a ball knob on the lid) +COLOURS = ["red", "green", "blue", "yellow"] +JARS = [f"jar_{c}_1" for c in COLOURS] +GLASS_RGBA = {"red": (0.78, 0.20, 0.16, 1.0), "green": (0.20, 0.58, 0.28, 1.0), "blue": (0.20, 0.38, 0.80, 1.0), + "yellow": (0.90, 0.72, 0.15, 1.0)} +LID_RGBA = (0.93, 0.93, 0.91, 1.0) +KNOB_RGBA = (0.22, 0.22, 0.24, 1.0) +JB = 0.025 # half width of the square body (5 x 5 cm) +BODY_H = 0.060 +LID_H, LID_B = 0.008, 0.026 # lid height, half width +NECK_R, NECK_H = 0.006, 0.012 +KNOB_R = 0.011 +JAR_H = BODY_H + LID_H + NECK_H + 2 * KNOB_R # 0.102 +KNOB_Z = BODY_H + LID_H + NECK_H + KNOB_R # knob centre above the jar's bottom (0.091) +JAR_COM = 0.026 # centre of mass above the bottom (a filled jar) +JAR_MASS = (0.24, 0.26) +JAR_MU = (0.27, 0.33) # jar body friction (per jar); the board's own is lower, so this one applies on the board +LID_MU = 0.8 +KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): a jar held by its knob swings down and hangs straight +JAR_ROT_DAMP = 0.004 # free-joint angular damping (air drag; damps the swing of a jar hanging from its knob) + +# ---------------------------------------------------------------- shelf (fixture: wall panel + hinged board) +SHELF = "shelf_1" +SHELF_MODEL = "lff_lhs_shelf" +BOARD_L = 0.34 # along the wall (world x) +BOARD_D = 0.20 # depth, from the wall to the free edge +BOARD_T = 0.012 +BOARD_TOP = 0.110 # top surface above the table when level +PANEL_T = 0.025 +LIP = 0.045 # the wall rises this far above the board's top +BOARD_MASS = 0.30 +BOARD_MU = 0.10 # (max rule: the jars' 0.27-0.33 applies) +GAP = 0.004 # board edge to the wall face (the board's lower corner swings towards the wall when it droops) +WOOD = (0.72, 0.55, 0.36, 1.0) +WALL_RGBA = (0.86, 0.86, 0.84, 1.0) +DROOP_MAX = np.radians(25.0) # hard stop of the hinge (at 28 deg the free edge would touch the table) +K_SPRING = 0.25 # N m / rad: the bracket's spring beyond the preload (soft: once the catch slips the board folds down) +LATCH = 0.12 # N m: part of the preload held by the bracket's catch, released over the first LATCH_TH of droop +LATCH_TH = np.radians(3.0) +PRELOAD_LOOSE = (0.62, 0.68) # N m (spring + catch at level) +PRELOAD_STIFF = 2.5 +DAMPING = (0.45, 0.60) # N m s / rad +P_LOOSE = 0.70 # 14 of every 20 consecutive seeds +WALL_Y = (0.25, 0.27) # |y| of the wall face +SHELF_X = (-0.17, -0.12) # centre of the board along the wall +SLOT_U = (-0.12, -0.04, 0.04, 0.12) # slot positions along the board (scripted policies) +SUP_Y = (0.13, 0.17) # |y| of the supply row (other side of the table) +SUP_U = (-0.135, -0.045, 0.045, 0.135) + +# predicates / monitor +TILT_OK = np.radians(10.0) # jar axis vs the board's normal +BOARD_OK = np.radians(15.0) # final judge: the board within 15 deg of level (jars slide off at ~13-16 deg) +SAG0 = np.radians(1.5) # sag_start +SAG_END = np.radians(0.5) +SAG_DEG = np.radians(8.0) # trap fired +DEBOUNCE = 10 # control steps (0.5 s) +SETTLE_MIN, SETTLE_MAX = 300, 600 # final judge: 15-30 s of simulated time with the arm holding still + +# scripted motion +Z_CARRY = 0.25 # grasp point above the table while carrying a jar (its bottom then clears the board by ~5 cm) +R_MID = GAP + BOARD_D / 2 # 0.104: the middle of the board's depth (from the wall face) +R_BACK = JB + 0.010 # 0.035: a jar against the wall (1 cm gap) +NAIVE_BIAS = 0.010 # per instance: Sonnet aims at the middle +- 1 cm (towards the wall or the free edge) +NAIVE_RAND = 0.006 # per jar +NAIVE_V, NAIVE_V_DOWN, NAIVE_WAITS = 0.35, 0.15, 0.5 # pace: ~8 s of simulated time from one placement to the next +# (Sonnet, lh_nudge_row pilot np2: 3.2-8.3 s, median 5.1 s) + + +def jar_xml(name, rgba): + h = JAR_H / 2 + z0 = -h # bottom + m = 0.25 + parts = [("body", "box", (0, 0, z0 + BODY_H / 2), (JB, JB, BODY_H / 2), rgba, 'friction="0.3 0.005 0.0001"'), + ("lid", "box", (0, 0, z0 + BODY_H + LID_H / 2), (LID_B, LID_B, LID_H / 2), LID_RGBA, + f'friction="{LID_MU} 0.005 0.0001"'), + ("neck", "cylinder", (0, 0, z0 + BODY_H + LID_H + NECK_H / 2), (NECK_R, NECK_H / 2), KNOB_RGBA, + f'friction="{LID_MU} 0.005 0.0001"'), + ("knob", "sphere", (0, 0, z0 + KNOB_Z), (KNOB_R,), KNOB_RGBA, + f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')] + ixx = m * ((2 * JB) ** 2 + BODY_H ** 2) / 12 + izz = m * (2 * (2 * JB) ** 2) / 12 + s = [f' '] + for nm, typ, pos, size, c, extra in parts: + s.append(f' ') + s.append(f' ') + # a lighter label band on the body (visual only) + s.append(f' ') + return _wrap(name, "\n".join(s), h, JB * 1.42) + + +def shelf_xml(name): + """fixture frame: origin on the table top below the middle of the hinge line; local +y points from the wall towards + the board's free edge, local x along the wall. Wall panel (static) + board (child body on a hinge about -x at the + wall face, so a positive joint angle lowers the free edge). Wall and board do not collide with each other + (contype 2 / conaffinity 1); both collide with everything else.""" + zc = BOARD_TOP - BOARD_T / 2 # hinge axis height (board mid-thickness) + wall_h = BOARD_TOP + LIP + hw = (BOARD_L + 0.04) / 2 + wall = (f'type="box" pos="0 {-PANEL_T / 2:.5f} {wall_h / 2:.5f}" size="{hw:.5f} {PANEL_T / 2:.5f} {wall_h / 2:.5f}" ' + f'rgba="{_fmt(WALL_RGBA)}"') + g = [f'', + f''] + slab = (f'type="box" pos="0 {BOARD_D / 2 + GAP:.5f} 0" size="{BOARD_L / 2:.5f} {BOARD_D / 2:.5f} {BOARD_T / 2:.5f}" ' + f'rgba="{_fmt(WOOD)}"') + b = [f'', + # stiffness / springref / damping are set per instance (apply_instance) + f'', + f'', + f'', + # darker front edge strip and hinge barrel (visual) + f'', + f''] + nl = "\n " + return f""" + + + + {nl.join(g)} + + {nl.join(b)} + + + + + + + + +""" + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +class DroopSkills(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 ShelfDroop(LFFTask): + name = "lh_shelf_droop" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Restore", "Plan") + protocol = "cross" + max_attempts = 3 + # careful: ~10 commands per jar (40) + standing up and re-placing three fallen jars (~40) + looking / corrections + agent_max_steps = 120 + instruction = ("Put the four jars (red, green, blue, yellow) on the shelf. At the end all four must be standing " + "upright on the shelf board, and the gripper must be open and clear of the jars and the shelf. " + "(Each jar has a round knob on its lid; held by the knob, a jar hangs straight down.)") + instruction_indirect = ("Put the four little square jars with knobbed lids up on the wooden shelf by the wall. " + "When you are done, all of them have to stand upright on the shelf board, and the gripper " + "must be open and away from the jars and the shelf. (Held by its round knob, a jar hangs " + "straight down.)") + agent_object_names = ["jars (red, green, blue, yellow; each with a round knob on its lid -- held by the knob it " + "hangs straight down)", "wooden shelf board on the wall panel"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs = [] + for i, (c, j) in enumerate(zip(COLOURS, JARS)): + cat = register_generated(f"LffLhsJar{c.capitalize()}", jar_xml(f"lff_lhs_jar_{c}", GLASS_RGBA[c])) + objs.append((j, cat, f"jar{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + sh = register_generated("LffLhsShelf", shelf_xml(SHELF_MODEL), free=False) + fx = [(SHELF, sh, "shelf_region", (0.20, -0.31, 0.21, -0.30))] # moved in apply_instance + return write_bddl(self.name, "Put the four jars on the shelf", 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].root_body) + self.jid = m.joint_name2id(f"{SHELF}_hinge") + self.qa, self.da = int(m.jnt_qposadr[self.jid]), int(m.jnt_dofadr[self.jid]) + self.board_bid = int(m.jnt_bodyid[self.jid]) + pre = f"{SHELF}_{SHELF_MODEL}" + self.board_gid = m.geom_name2id(pre + "_board") + self.wall_gid = m.geom_name2id(pre + "_wall") + self.jgeoms = {j: envs.obj_geom_ids(self.env, j) for j in JARS} + self.jbid = {j: int(m.geom_bodyid[self.jgeoms[j][0]]) for j in JARS} # body that carries the inertial + self.body_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_body") for c, j in zip(COLOURS, JARS)} + self.knob_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_knob") for c, j in zip(COLOURS, JARS)} + self.jdof = {j: envs.free_joint_addr(self.env, j)[1] for j in JARS} + # per-geom lookup tables for the substep contact check + self.owner = np.full(m.ngeom, -1, int) # jar index + for i, j in enumerate(JARS): + self.owner[self.jgeoms[j]] = i + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(self.env)] = True + self.is_board = np.zeros(m.ngeom, bool) + self.is_board[self.board_gid] = True + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + sim = self.env.sim + if not getattr(sim, "_lhs_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhs_task", None) + if t is not None: + t._bracket() + if t.mon is not None: + t._substep() + sim.step = step + sim._lhs_wrapped = True + sim._lhs_task = self + self.inst = None + self.mon = None + self.sk = None + + def _bracket(self): + """the bracket's catch (every MuJoCo substep): a torque holding the board up that fades out over the first + LATCH_TH of droop, so a board that starts to droop does not stop part-way but folds down to its stop""" + d = self.env.sim.data + th = float(d.qpos[self.qa]) + d.qfrc_applied[self.da] = -LATCH * float(np.clip(1.0 - th / LATCH_TH, 0.0, 1.0)) + + 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] + for a, b in zip(g1, g2): + pa, pb = self.owner[a], self.owner[b] + if self.is_board[a] or self.is_board[b]: + o = b if self.is_board[a] else a + if self.owner[o] < 0: # the board touched by something that is not a jar (robot, table, ...) + self._sub_board.add("robot" if self.is_robot[o] else (self.env.sim.model.geom_id2name(int(o)) or "?")) + continue + 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) + if self.is_robot[o]: + self._sub_rob[int(p)] = True + + # ------------------------------------------------------------ instances + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + loose = bool((int(seed) * 7) % 20 < round(20 * P_LOOSE)) # balanced: 14 of every 20 consecutive seeds + side = "right" if rng.random() < 0.5 else "left" # where the wall stands (robot's view) + s = -1.0 if side == "right" else 1.0 + x0 = float(rng.uniform(*SHELF_X)) + yw = float(rng.uniform(*WALL_Y)) + preload = float(rng.uniform(*PRELOAD_LOOSE)) if loose else PRELOAD_STIFF + damping = float(rng.uniform(*DAMPING)) + ys = -s * float(rng.uniform(*SUP_Y)) + order = rng.permutation(4) + start = {COLOURS[i]: [float(x0 + SUP_U[order[i]] + rng.uniform(-0.01, 0.01)), float(ys + rng.uniform(-0.008, 0.008))] + for i in range(4)} + yaw0 = {c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS} + mu = {c: float(rng.uniform(*JAR_MU)) for c in COLOURS} + mass = {c: float(rng.uniform(*JAR_MASS)) for c in COLOURS} + return dict(seed=int(seed), loose=loose, bracket="loose" if loose else "stiff", side=side, shelf_x=x0, + wall_y=float(s * yw), preload=preload, damping=damping, stiffness=K_SPRING, start=start, yaw0=yaw0, + mu=mu, mass=mass, naive_bias=float(rng.uniform(-NAIVE_BIAS, NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + s = -1.0 if inst["side"] == "right" else 1.0 + # fixture local +y (towards the free edge) = world -s*y + m.body_pos[self.shelf_bid] = [inst["shelf_x"], inst["wall_y"], TZ] + m.body_quat[self.shelf_bid] = [1.0, 0.0, 0.0, 0.0] if s < 0 else [0.0, 0.0, 0.0, 1.0] + wb = BOARD_MASS * G * (BOARD_D / 2 + GAP) # the board's own weight about the hinge + m.jnt_stiffness[self.jid] = inst["stiffness"] + # spring + catch hold the board level up to a load moment of `preload` (the catch's part fades with the droop) + m.qpos_spring[self.qa] = -(inst["preload"] - LATCH + wb) / inst["stiffness"] + m.dof_damping[self.da] = inst["damping"] + d.qpos[self.qa] = 0.0 + d.qvel[self.da] = 0.0 + d.qfrc_applied[self.da] = -LATCH + for c, j in zip(COLOURS, JARS): + b = self.jbid[j] + M = inst["mass"][c] + m.body_mass[b] = M + m.body_inertia[b] = [M * ((2 * JB) ** 2 + BODY_H ** 2) / 12] * 2 + [M * (2 * JB) ** 2 / 6] + m.geom_friction[self.body_gid[j]] = [inst["mu"][c], 0.005, 0.0001] + m.dof_damping[self.jdof[j] + 3:self.jdof[j] + 6] = JAR_ROT_DAMP + self.env.sim.forward() + for c, j in zip(COLOURS, JARS): + envs.place_upright(self.env, j, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + + 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 = DroopSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + n = len(JARS) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, lost_cause=[None] * n, + events=[], last_robot=[None] * n, last_obj=[None] * n, placed_step=[None] * n, + last_place=None, raw_prev=[False] * n, raw_on=[None] * n, in_sag=False, sag_start=None, sag_fired=False, sag_max=0.0, n_sag=0, + fell_in_sag=[], max_deg=0.0, board_touch=[], n_steps=0, finish_step=None) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def angle(self): + return float(self.env.sim.data.qpos[self.qa]) + + def board_frame(self): + d = self.env.sim.data + return d.xpos[self.board_bid].copy(), d.xmat[self.board_bid].reshape(3, 3).copy() + + def to_board(self, p): + o, R = self.board_frame() + return R.T @ (np.asarray(p, float) - o) + + def board_point(self, u, r, h=BOARD_T / 2): + """world point at (u along the wall, r from the hinge across the board, h above the hinge axis) in the board + frame""" + o, R = self.board_frame() + return o + R @ np.array([u, r, h]) + + def level_point(self, u, r): + """world xy of board coordinates (u, r) with the board level (planning)""" + s = -1.0 if self.inst["side"] == "right" else 1.0 + return np.array([self.inst["shelf_x"] - s * u, self.inst["wall_y"] - s * r]) + + def board_top_z(self): + return TZ + BOARD_TOP + + def jar_axis(self, j): + return self.env.sim.data.xmat[self.jbid[j]].reshape(3, 3)[:, 2].copy() + + def jar_bottom(self, j): + return envs.obj_pos(self.env, j) - self.jar_axis(j) * JAR_H / 2 + + def knob_xyz(self, j): + return self.env.sim.data.geom_xpos[self.knob_gid[j]].copy() + + def tilt(self, j): + return float(np.arccos(np.clip(self.jar_axis(j)[2], -1.0, 1.0))) + + def held(self, j): + return self.sk is not None and self.sk.holding(j) + + def on_board(self, i, extra=0.0): + """jar i stands on the shelf board: its bottom (centre) on the board's top, within the board's outline, its + axis within 10 deg of the board's normal, not held""" + j = JARS[i] + o, R = self.board_frame() + ax = R.T @ self.jar_axis(j) + if ax[2] < np.cos(TILT_OK + extra * 5): + return False + bc = R.T @ (self.jar_bottom(j) - o) + if not (BOARD_T / 2 - 0.004 <= bc[2] <= BOARD_T / 2 + 0.005 + extra): + return False + if abs(bc[0]) > BOARD_L / 2 + extra or not (GAP - extra <= bc[1] <= GAP + BOARD_D + extra): + return False + return not self.held(j) + + def stages(self): + return [self.on_board(i) for i in range(len(JARS))] + + def lever(self, j): + """horizontal distance (m) of the jar's centre of mass from the hinge line, towards the free edge""" + o, R = self.board_frame() + n = R[:, 1].copy() + n[2] = 0.0 + n /= max(np.linalg.norm(n), 1e-9) + return float((self.env.sim.data.xipos[self.jbid[j]] - o) @ n) + + def moment(self, only_state=True): + """load moment (N m) of the jars standing on the board about the hinge""" + mon = self.mon + tot = 0.0 + for i, j in enumerate(JARS): + on = mon["state"][i] if (only_state and mon is not None) else self.on_board(i) + if on: + tot += self.inst["mass"][COLOURS[i]] * G * self.lever(j) + return float(tot) + + def r_cm(self, i): + """distance of jar i's bottom centre from the wall face (cm), in the board frame""" + return 100 * float(self.to_board(self.jar_bottom(JARS[i]))[1]) + + # ------------------------------------------------------------ monitor + def _t(self): + return int(self.sk.n_steps) if self.sk is not None else 0 + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["n_steps"] += 1 + t = self._t() + rob, obj, brd = dict(self._sub_rob), dict(self._sub_obj), set(self._sub_board) + self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set() + for i in rob: + if not self.held(JARS[i]): + mon["last_robot"][i] = int(t) + for i, k in obj.items(): + mon["last_obj"][i] = [COLOURS[k], int(t)] + for b in brd: + if b not in mon["board_touch"]: + mon["board_touch"].append(b) + mon["_board_touch_now"] = sorted(brd) + th = self.angle() + mon["max_deg"] = max(mon["max_deg"], float(np.degrees(th))) + if th > np.radians(5.0): + mon["droop_t"] = int(t) # last step with the board drooped > 5 deg (it springs back once the jars are off) + self._sag(th, t) + if mon["n_steps"] % 2: + return + for i in range(len(JARS)): + raw = self.on_board(i, 0.002 if mon["state"][i] else 0.0) + if raw and not mon["raw_prev"][i]: + mon["raw_on"][i] = int(t) # set down on the board (raw; the stage event below is debounced) + mon["raw_prev"][i] = raw + 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) + c = COLOURS[i] + if raw: + restored = mon["lost"][i] + e = dict(stage=c, event="restored" if restored else "achieved", step=t0, + r_cm=round(self.r_cm(i), 1), moment_Nm=round(self.moment(), 3)) + if restored: + e["after"] = mon["lost_cause"][i] + mon["events"].append(e) + mon["ever"][i] = True + mon["placed_step"][i] = t0 + mon["last_place"] = (c, t0) + else: + mon["lost"][i] = True + cause = self._cause(i, t) + mon["lost_cause"][i] = cause + e = dict(stage=c, event="lost", step=t0, cause=cause, board_deg=round(float(np.degrees(th)), 1)) + mon["events"].append(e) + if cause == "slid_off": + ps = mon["placed_step"][i] + ss = mon["sag_start"]["step"] if mon["sag_start"] else None + sc = mon.get("sag_cause") + mon["events"].append(dict(jar=c, event="jar_fell", step=t0, + dt_since_placed_s=None if ps is None else round((t0 - ps) * DT, 2), + dt_since_sag_start_s=None if ss is None else round((t0 - ss) * DT, 2), + after_placing=None if sc is None else sc[0], + dt_since_cause_s=None if sc is None else round((t0 - sc[1]) * DT, 2), + in_final_settle=mon["finish_step"] is not None, + board_deg=round(float(np.degrees(th)), 1))) + mon["fell_in_sag"].append(c) + + def _sag(self, th, t): + mon = self.mon + if not mon["in_sag"]: + if th > SAG0: + mon["in_sag"] = True + mon["sag_fired"] = False + mon["sag_max"] = th + mon["fell_in_sag"] = [] + lp = self._last_set_down(t) + mon["sag_cause"] = lp + e = dict(event="sag_start", step=int(t), board_deg=round(float(np.degrees(th)), 2), + moment_Nm=round(self.moment(only_state=False), 3), + preload_Nm=round(float(self.inst["preload"]), 3), + after_placing=None if lp is None else lp[0], + dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2), + n_on_board=int(sum(self.on_board(i) for i in range(len(JARS))))) + mon["sag_start"] = e + mon["events"].append(e) + return + mon["sag_max"] = max(mon["sag_max"], th) + if not mon["sag_fired"] and th > SAG_DEG: + mon["sag_fired"] = True + mon["n_sag"] += 1 + ss = mon["sag_start"] + lp = self._last_set_down(t) # the placement that drove the board past 8 deg (sag_start may be earlier: + mon["sag_cause"] = lp # two jars in the middle already make it creep a few degrees) + mon["events"].append(dict(event="sag", step=int(t), board_deg=round(float(np.degrees(th)), 2), + moment_Nm=round(self.moment(only_state=False), 3), + after_placing=None if lp is None else lp[0], + sag_start_after=ss["after_placing"], + dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2), + dt_since_sag_start_s=round((t - ss["step"]) * DT, 2), + in_final_settle=mon["finish_step"] is not None)) + mon["below"] = mon.get("below", 0) + 1 if th < SAG_END else 0 + if mon["below"] >= 2 * DEBOUNCE: # back level for 1 s (the jars that slid off have been registered) + mon["in_sag"] = False + mon["below"] = 0 + mon["events"].append(dict(event="sag_end", step=int(t), max_deg=round(float(np.degrees(mon["sag_max"])), 1), + fell=list(mon["fell_in_sag"]), + duration_s=round((t - mon["sag_start"]["step"]) * DT, 2))) + + def _last_set_down(self, t): + """(colour, step) of the jar most recently set down on the board (raw predicate) that still stands on it""" + mon = self.mon + cands = [(mon["raw_on"][i], COLOURS[i]) for i in range(len(JARS)) + if mon["raw_on"][i] is not None and mon["raw_prev"][i] and mon["raw_on"][i] <= t] + if not cands: + return None + st, c = max(cands) + return (c, st) + + def _cause(self, i, t, window=60): + mon = self.mon + if self.held(JARS[i]): + return "picked_up" + if (mon["in_sag"] and mon["sag_max"] > np.radians(5.0)) or (mon.get("droop_t") is not None + and t - mon["droop_t"] <= window): + return "slid_off" + lr, lo = mon["last_robot"][i], mon["last_obj"][i] + if lr is not None and t - lr <= window: + return "robot" + if lo is not None and t - lo[1] <= window: + return "jar:" + lo[0] + return "other" + + def _finalize_monitor(self, raw): + mon = self.mon + t = self._t() + for i in range(len(JARS)): + if raw[i] == mon["state"][i]: + continue + mon["state"][i] = raw[i] + c = COLOURS[i] + if raw[i]: + restored = mon["lost"][i] + e = dict(stage=c, 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=c, event="lost", step=t, cause=cause, final=True)) + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + jar_touch, board_touch = False, False + for k in range(d.ncon): + c = d.contact[k] + a, b = c.geom1, c.geom2 + if (self.is_robot[a] and self.owner[b] >= 0) or (self.is_robot[b] and self.owner[a] >= 0): + jar_touch = True + if (self.is_robot[a] and self.is_board[b]) or (self.is_robot[b] and self.is_board[a]): + board_touch = True + return jar_touch, board_touch + + def _moving(self): + d = self.env.sim.data + if abs(float(d.qvel[self.da])) > np.radians(0.3): + return True + for j in JARS: + da = self.jdof[j] + if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return True + return False + + def outcome(self, inst): + sk = self.sk + mon = self.mon + mon["finish_step"] = self._t() + # what the agent's last images show (finish returns no image): board angle and the jars already off the board + th_fin = self.angle() + off_fin = [COLOURS[i] for i in range(4) if mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])] + max_fin = float(mon["max_deg"]) + # settle with the arm holding still: >= 15 s of simulated time, up to 30 s while the board or a jar still moves + # (the droop is slow: finishing right after the last placement must not beat it) + n = 0 + while n < SETTLE_MAX: + sk.hold(10) + n += 10 + if n >= SETTLE_MIN and not self._moving() and not mon["in_sag"]: + break + settle_s = n * DT + p0 = {j: envs.obj_pos(self.env, j) for j in JARS} + th0 = self.angle() + jar_touch = board_touch = False + board_other = set() + for _ in range(20): + sk.hold(1) + jt, bt = self._touching() + jar_touch, board_touch = jar_touch or jt, board_touch or bt + board_other |= {b for b in mon.get("_board_touch_now", []) if b != "robot"} + moved = max(float(np.linalg.norm(envs.obj_pos(self.env, j) - p0[j])) for j in JARS) + static = moved < 0.003 and abs(self.angle() - th0) < np.radians(0.3) + raw = self.stages() + self._finalize_monitor(raw) + th = self.angle() + held = [COLOURS[i] for i, j in enumerate(JARS) if self.held(j)] + level = th <= BOARD_OK + propped = sorted(board_other) + success = bool(all(raw) and level and static and not held and not jar_touch and not board_touch and not propped) + ev = list(mon["events"]) + 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) + fell = [e for e in ev if e.get("event") == "jar_fell"] + sags = [e for e in ev if e.get("event") == "sag"] + sag_vis = [e for e in sags if not e.get("in_final_settle")] + starts = [e for e in ev if e.get("event") == "sag_start"] + ever = mon["ever"] + lost_final = [i for i in range(4) if not raw[i] and ever[i]] + never = [i for i in range(4) if not raw[i] and not ever[i]] + if success: + failure = "none" + elif held: + failure = "held" + elif propped or board_touch: + failure = "propped" + elif jar_touch: + failure = "touching" + elif lost_final: + causes = {mon["lost_cause"][i] for i in lost_final} + failure = ("slid_off" if "slid_off" in causes else "knocked_off" if "robot" in causes else "regressed") + elif never: + failure = "not_on_shelf" + elif not level: + failure = "board_drooped" + else: + failure = "not_static" + # ---- F2 text + parts = [] + if success: + parts.append("All four jars stand upright on the shelf board.") + for i in range(4): + if raw[i]: + continue + c, j = COLOURS[i], JARS[i] + if c in held: + parts.append(f"The {c} jar is still held by the gripper.") + continue + pb = self.to_board(self.jar_bottom(j)) + lying = self.tilt(j) > np.radians(45) + if pb[2] < -0.02: # below the board: on the table + where = "lies on its side on the table" if lying else "stands on the table" + dist = 100 * float(pb[1] - (GAP + BOARD_D)) + txt = f"The {c} jar {where}" + (f", {dist:.0f} cm out from the shelf's front edge." if dist > 0 + else ", under the shelf.") + elif lying: + txt = f"The {c} jar lies on its side on the shelf board." + else: + txt = f"The {c} jar is not standing on the shelf board." + if ever[i]: + why = mon["lost_cause"][i] + txt += {"slid_off": " It had stood on the shelf; it slid off when the shelf board drooped under the load.", + "robot": " It had stood on the shelf; the robot knocked it off.", + }.get(why, " It had stood on the shelf earlier.") + parts.append(txt) + if all(raw) and not success: + if not level: + parts.append(f"The shelf board droops by {np.degrees(th):.0f} degrees.") + if held: + pass + elif jar_touch or board_touch: + parts.append("The gripper is still touching " + ("a jar." if jar_touch else "the shelf board.")) + elif propped: + parts.append("The shelf board rests on something below it.") + elif not static: + parts.append("Something was still moving.") + if sags: + parts.append(f"During the attempt the shelf board drooped {len(sags)} time(s) (down to {mon['max_deg']:.0f} " + f"degrees) and {len(fell)} time(s) a jar slid off; {n_res} time(s) a jar was put back.") + trap = bool(sags) + lp = lambda e: e.get("dt_since_placement_s") # noqa: E731 + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(4)}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_fell=len(fell), + n_sag=len(sags), trap_fired=trap, sag_visible=bool(sag_vis), + recovered_in_attempt=bool(trap and success), + first_sag_dt_s=lp(sags[0]) if sags else None, + first_sag_start_dt_s=lp(starts[0]) if starts else None, + first_sag_after=sags[0].get("after_placing") if sags else None, + first_fall_dt_s=fell[0].get("dt_since_cause_s") if fell else None, + fell_before_finish=bool([e for e in fell if not e.get("in_final_settle")]), + board_deg_at_finish=round(float(np.degrees(th_fin)), 1), off_at_finish=off_fin, + max_droop_before_finish_deg=round(max_fin, 1), + visible_before_finish=bool(sag_vis or off_fin or max_fin > np.degrees(SAG_DEG)), + fell_jars=sorted({e["jar"] for e in fell}), failure=failure, held=held, touching=bool(jar_touch), + board_touched=bool(board_touch), propped=propped, static=bool(static), + board_deg=round(float(np.degrees(th)), 2), max_droop_deg=round(mon["max_deg"], 1), + r_cm={COLOURS[i]: round(self.r_cm(i), 1) for i in range(4)}, + moment_Nm=round(self.moment(only_state=False), 3), preload_Nm=round(float(inst["preload"]), 3), + loose=bool(inst["loose"]), settle_s=settle_s, finish_step=mon["finish_step"], + 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.15): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def _settle_jar(self, j, max_checks=30): + d = self.env.sim.data + da = self.jdof[j] + 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 wait_board(self, max_steps=200): + """wait (arm still) until the board stops moving""" + for _ in range(max_steps // 5): + if abs(float(self.env.sim.data.qvel[self.da])) < np.radians(0.3) and not self.mon["in_sag"]: + return + self.sk.hold(5) + + def lying(self, j): + return self.tilt(j) > np.radians(45) + + def pick(self, j, z_carry=Z_CARRY, yaw=0.0, v=0.2, err=None, tries=2, v_down=0.10, waits=1.0): + """grasp the jar by its knob and lift it to carry height. Standing jar: from above, wrist yaw `yaw`. Lying jar: + fingers across its axis; lifted, it turns between the fingers and hangs straight down.""" + sk = self.sk + for _ in range(tries): + self._settle_jar(j) + lying = self.lying(j) + k = self.knob_xyz(j) + if lying: + ax = self.jar_axis(j)[:2] + gy = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw + else: + gy = yaw + q = k[:2] + (np.asarray(err, float) if err is not None else 0.0) + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], max(cur[2], TZ + min(z_carry, 0.22))], speed=0.15) + self._go([q[0], q[1], max(k[2] + 0.06, TZ + min(z_carry, 0.22))], yaw=gy, speed=v) + sk.hold(max(1, int(4 * waits))) + k = self.knob_xyz(j) + q = k[:2] + (np.asarray(err, float) if err is not None else 0.0) + self._go([q[0], q[1], k[2] + 0.015], speed=v_down) + self._go([q[0], q[1], k[2]], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + if lying: # lift slowly until it hangs free, let the swing die down + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + KNOB_Z + 0.04], speed=0.08) + sk.hold(20) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.12, v_down)) + sk.hold(max(1, int(5 * waits))) + if self.held(j): + return True + sk.set_gripper(False, steps=8) + cur = sk.eef_pos() + self._go([cur[0], cur[1], cur[2] + 0.05], speed=0.1) + return False + + def put(self, j, u, r, z_carry=Z_CARRY, h_rel=0.010, v=0.2, yaw=0.0, v_down=0.10, waits=1.0): + """carry the held jar over board point (u, r) (planned with the board level), straight down until its bottom is + h_rel above the board top, let go, lift back to carry height""" + sk = self.sk + xy = self.level_point(u, r) + rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2] + q = xy - rel + cur = sk.eef_pos() + self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v) + sk.hold(max(1, int(12 * waits))) # let the hanging jar stop swinging + rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2] + q = xy - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, j) + zr = self.board_top_z() + dz + h_rel + self._go([q[0], q[1], zr + 0.02], speed=v_down) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.15, v_down)) + sk.hold(3) + + def place(self, i, u, r, p, rng, rand=0.0): + """one stage: pick jar i from wherever it is and put it on the board at (u, r) +- rand""" + j = JARS[i] + e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2) + gerr = rng.uniform(-0.002, 0.002, 2) if rand else None + kw = dict(z_carry=p.get("z_carry", Z_CARRY), v=p.get("v", 0.2), v_down=p.get("v_down", 0.10), + waits=p.get("waits", 1.0)) + if not self.pick(j, err=gerr, **kw): + return False + self.put(j, u + e[0], r + e[1], h_rel=p.get("h_rel", 0.010), **kw) + self._settle_jar(j) + return True + + def supply_order(self): + """jar indices by their supply position: the one whose slot is farthest from the robot first (Sonnet fills a + row from the far end)""" + return sorted(range(4), key=lambda i: -self.inst["start"][COLOURS[i]][0]) + + def slot_u(self, k): + """board u of slot k (k = 0 farthest from the robot)""" + s = -1.0 if self.inst["side"] == "right" else 1.0 + # u runs along local x = -s * world x -> farthest (largest world x) first + return -s * SLOT_U[3 - k] + + def fallen(self): + return [i for i in range(4) if self.mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])] + + def repair(self, r_target, rng, p, rand=0.0, used=None): + """move every jar on the board to depth r_target (same slot), then stand up the fallen ones and put them into the + free slots at r_target""" + sk = self.sk + self.wait_board() + slots = dict(used or {}) + for i in range(4): + if self.on_board(i) and abs(self.r_cm(i) / 100 - r_target) > 0.02: + self.place(i, slots.get(i, self.slot_u(0)), r_target, p, rng, rand) + self.wait_board() + for i in self.fallen(): + free = [k for k in range(4) if self.slot_u(k) not in slots.values()] or [0] + u = slots.get(i, self.slot_u(free[0])) + slots[i] = u + self.place(i, u, r_target, p, rng, rand) + self.wait_board() + sk.hold(5) + return slots + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + r = float(params["r"]) + rand = float(params.get("rand", 0.0)) + order = params.get("order") or self.supply_order() + used = {} + mode_back = False + for k, i in enumerate(order): + u = self.slot_u(k) + used[i] = u + rr = R_BACK + params.get("back_off", 0.0) if mode_back else r + self.place(i, u, rr, params, rng, rand) + # looks at the jar it just placed (Sonnet): re-places it if it is not standing on the board + if not self.on_board(i) and params.get("self_check", True): + self.place(i, u, rr, params, rng, rand) + if params.get("look_back") and (self.fallen() or self.angle() > np.radians(3.0)): + # the shelf sags / jars fell: from now on load it near the wall, and move what is on it there too + mode_back = True + used = self.repair(R_BACK + params.get("back_off", 0.0), rng, params, rand, used) + if params.get("final_check"): + for _ in range(2): + if all(self.stages()): + break + rr = R_BACK + params.get("back_off", 0.0) if (mode_back or params.get("look_back")) else r + used = self.repair(rr, rng, params, rand, used) + if not params.get("fast_finish"): + self._lift_to(Z_CARRY) + self.sk.hold(5) + + # naive = Sonnet-like (DESIGN_INSIGHTS §3; lh_nudge_row / lh_bystander pilots): careful top-down pick and place, jars + # set down in the visual middle of the shelf's depth, released ~1-4 cm above, wrist yaw 0, looks at the jar it just + # placed, no look back at the others before finishing + def default_params(self, inst): + sd = int(inst["seed"]) + return dict(r=R_MID + float(inst["naive_bias"]), rand=NAIVE_RAND, noise_seed=sd * 13, + h_rel=0.010 + 0.030 * ((sd * 7) % 11) / 10, z_carry=Z_CARRY, look_back=False, final_check=False, + v=NAIVE_V, v_down=NAIVE_V_DOWN, waits=NAIVE_WAITS) + + def oracle_params(self, inst): + return dict(r=R_BACK, rand=0.0, h_rel=0.005, z_carry=Z_CARRY, look_back=True, final_check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load the shelf near the wall (same imprecision), look back after every jar and at the end""" + return dict(self.default_params(inst), r=R_BACK + 0.008, look_back=True, final_check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variation (depth on the board, order, heights), no history, no look back""" + order = [int(x) for x in rng.permutation(4)] + return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), r=float(rng.uniform(0.06, 0.15)), + order=order, z_carry=float(rng.uniform(0.24, 0.28)), h_rel=float(rng.uniform(0.005, 0.04)), + v=float(rng.uniform(0.12, 0.3))) + + 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", "naive_front", "naive_back", "naive_check_mid", "naive_fast") + 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": # attempt 1: naive + looks back after every jar; repairs near the wall + params = (dict(self.default_params(inst), look_back=True, final_check=True, back_off=0.008) 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 (near the wall from attempt 2), no repair + params = (self.default_params(inst) if a == 0 else + dict(self.default_params(inst), r=R_BACK + 0.008)) + elif kind == "oracle_noise": + params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "naive_front": # control: naive, but jars set down near the free edge + params = dict(self.default_params(inst), r=GAP + BOARD_D - JB - 0.015) + elif kind == "naive_back": # control: naive pace and imprecision, jars against the wall -> no droop + params = dict(self.default_params(inst), r=R_BACK + 0.008) + elif kind == "naive_check_mid": # control: looks back and repairs, but puts the jars back in the middle + params = dict(self.default_params(inst), final_check=True) + elif kind == "naive_fast": # control: naive at the fastest pace, finishing right after the last jar + params = dict(self.default_params(inst), v=0.6, v_down=0.3, waits=0.1, h_rel=0.03, fast_finish=True) + 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_sonnet/export_status.json b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/export_status.json new file mode 100644 index 0000000000000000000000000000000000000000..3baac021d566528918d868286cfa2b44f3260f7d --- /dev/null +++ b/leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/export_status.json @@ -0,0 +1,25 @@ +{ + "batch": "breakfast_v2_20261103_sonnet", + "status": "complete", + "pid": 1553947, + "started": 1793685798.389435, + "total_runs": 9, + "recorded": 9, + "accepted": 9, + "finished": 1793690058.3777175, + "dataset": "/mnt/cpfs/shared/datasets/lffbench_agent_replays/breakfast-v2-20261103-breakfast_v2_20261103_sonnet", + "validation": { + "codebase_version": "v3.0", + "episodes": 15, + "frames": 43500, + "plan_episodes": 15, + "plan_frames": 43500, + "samples": 60, + "max_state_action_abs_err": 1.156772002630646e-07, + "max_mean_abs_pixel_err": 2.406, + "status": "pass" + }, + "rejected_runs": 0, + "exported_runs": 9, + "complete_coverage": true +} diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/agent/backends/chat_completions.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/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_gpt/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_gpt/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py new file mode 100644 index 0000000000000000000000000000000000000000..7e45931d7094d6260a85d4faa1791ad3e9d072c7 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py @@ -0,0 +1,65 @@ +"""Controlled arms for l3_card_shelf (2026-10-12, docs/14 sec. 6). + +Hidden variable: which end of the (symmetric-looking) card holds the 8 g weight. The centre of mass is compiled into +the card's MJCF along its local +x, so the heavy end is chosen purely by `card_yaw` (heavy end direction = yaw); +`heavy_near` / `heavy_edge` are bookkeeping only (nothing in reset / outcome / policies reads them), kept consistent. +No override changes geometry, mass or inertia, so no bounding-volume refit is involved. + +h0 : the same card turned end for end (yaw + 180 deg): identical pose and footprint, the weight now in the FAR end, + so the common-sense "slide the nearest end out" slides the light end and succeeds. +twin : the trap stays (the heavy end is the nearest end) but it points to the OPPOSITE shelf edge: the card is mirrored + through the shelf centre along its long axis (near gap, side offset, jitter mirrored) and keeps its weight in + the end that is now nearest. The right correction (slide the other, light end) is then over the opposite + edge. For an x-card this makes the near end the BACKWARD one, which the task's own sampler avoids because a + card tipping off the backward edge lands behind the shelf (agentview shows the shelf empty, not the card); + see the arm validation (results/l3_card_shelf/arms/). For an instance whose heavy end is already the far end + (naive succeeds there) the twin keeps the pose and turns the card end for end, so the weight is in the near + end and the heavy edge is again the opposite one. +reveal: which shelf edge the heavy end points to, in the F2 feedback's edge words. +""" +import numpy as np + +HIDDEN_KEYS = ("card_yaw", "heavy_near", "heavy_edge") + +OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"} +GLOSS = {"forward": "away from the robot", "backward": "towards the robot", "left": "on the robot's left", + "right": "on the robot's right"} + + +def _wrap(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +def h0(inst): + if not inst["heavy_near"]: + return {} # already the ordinary case for the naive habit (weight away from the end that gets slid out) + return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=False, heavy_edge=inst["far_edge"]) + + +def twin(inst): + if not inst["heavy_near"]: + return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=True, heavy_edge=inst["near_edge"]) + a = 0 if inst["card_along"] == "x" else 1 # world axis of the card's long side + c = list(inst["card_xy"]) + c[a] = 2.0 * inst["shelf_xy"][a] - c[a] + yaw = inst["card_yaw"] + yaw = np.pi - yaw if a == 0 else -yaw # reflection x -> -x (resp. y -> -y) of the card's heading + return dict(card_xy=[float(c[0]), float(c[1])], card_yaw=_wrap(yaw), near_edge=OPPOSITE[inst["near_edge"]], + far_edge=OPPOSITE[inst["far_edge"]], heavy_edge=OPPOSITE[inst["heavy_edge"]]) + + +def reveal(inst): + e = inst["heavy_edge"] + return (f"The card is not uniform: 8 g of its 10 g are a weight hidden in the end that points towards the shelf's " + f"{e} edge ({GLOSS[e]}), so its centre of mass is 2.8 cm from the card's middle towards that end.") + + +def fix(inst, params): + """Ladder Fix rung (docs/20): slide the light end out (two strokes to 2 and 3 cm), grasp the overhang, bin.""" + light = OPPOSITE[inst["heavy_edge"]] + return (f"A way to succeed: slide the light end out, not the heavy one. The light end is the one pointing towards " + f"the shelf's {light} edge ({GLOSS[light]}). With the gripper closed, press the fingertips lightly on the " + f"middle of the card and drag it slowly (speed about 0.08) along its long side towards that edge, in two " + f"strokes: first until that end sticks out about 2 cm beyond the edge, look, then until it sticks out " + f"about 3 cm. Then open the gripper, grasp the part that sticks out about 2 cm beyond the edge, at the " + f"card's height, lift it and drop the card into the bin.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l7_key_turn.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l7_key_turn.py new file mode 100644 index 0000000000000000000000000000000000000000..907cfe292fd7ae33c3e38f81159e15dd859d9a4f --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/arm_specs/l7_key_turn.py @@ -0,0 +1,34 @@ +"""Controlled-arm spec for l7_key_turn (2026-10-12). + +Hidden variable: inst["direction"], the way the key opens the lock ("CCW" or "CW", seen from above). apply_instance() +derives the joint range and outcome()/check_unlock()/oracle_params() derive the open sign from it on every reset, so +overriding "direction" alone is enough (nothing is cached at sampling time). + +The scripted prior (naive) turns counterclockwise, so the trap exists only on CW locks -- all full5 instances are CW. + +h0 -> direction = "CCW": same lock position / yaw, the key opens the common-sense way, naive succeeds. +twin -> {} (no valid twin). The task has a single binary hidden variable and the trap exists only for one of its two + values: a twin with the trap still active must be CW again, i.e. need exactly the same correction ("turn + clockwise"), and the sign-flipped twin (CCW) is the H0 twin, where naive succeeds. There is no second hidden + constraint (the required angle is the fixed quarter turn named in the instruction). The mismatched-history + arm therefore has to take another instance's history -- note that every trap instance's history teaches the + same correction, so for this task a mismatched history is not misleading about the direction. +reveal -> states which way the key turns and that the other way stops after ~3 deg (the words "clockwise", + "counterclockwise", "seen from above" are those of the task's F2 feedback). +""" + +HIDDEN_KEYS = ("direction",) + + +def h0(inst): + return {"direction": "CCW"} + + +def twin(inst): + return {} + + +def reveal(inst): + ok, other = (("counterclockwise", "clockwise") if inst["direction"] == "CCW" else ("clockwise", "counterclockwise")) + return (f"Note: this lock opens only when the key is turned {ok} (seen from above); turned {other} the key moves " + f"about 3 degrees and then hits a hard stop.") diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/codex.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/codex.py new file mode 100644 index 0000000000000000000000000000000000000000..ed72b09ba59f5d0341540a896f20caa44581b83a --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_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/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9482378574fd6e4fec4b25b958f94103ff4fee --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py @@ -0,0 +1,188 @@ +"""Local fake model APIs for offline harness checks (no real model, no cost). + +Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a +native harness can be driven turn by turn without a model: + FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic + FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider + +A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get +the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps: + ("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read") + ("text", s) a text block / assistant message + ("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript + ("fcall", name, args) Responses: a plain function call + ("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP + tools this way: name "robot", namespace "mcp__lff"; measured with 0.163) + + srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop() +""" +import itertools +import json +import os +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id") + + +class _Base: + final_text = "done" + + def __init__(self, script=None, record_dir=None, port=0): + self.script = list(script or []) + self.record_dir = record_dir + self.port = port + self.lock = threading.Lock() + self.counter = itertools.count(1) + self.requests = [] # (n, path, body) + if record_dir: + os.makedirs(record_dir, exist_ok=True) + + # ------------------------------------------------------------------ plumbing + def start(self): + outer = self + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _record(self, body): + with outer.lock: + n = next(outer.counter) + outer.requests.append((n, self.path, body)) + if outer.record_dir: + with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f: + json.dump(dict(method=self.command, path=self.path, body=body, + headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}), + f, indent=1, ensure_ascii=False) + return n + + def do_GET(self): + self._record(None) + self._send(404, b"{}", "application/json") + + def do_HEAD(self): + self._send(404, b"", "application/json") + + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0)) + try: + body = json.loads(raw) + except ValueError: + body = raw[:4000].decode("utf-8", "replace") + n = self._record(body) + outer.handle(self, n, body) + + def _send(self, code, data, ctype): + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H) + self.httpd.daemon_threads = True + self.port = self.httpd.server_address[1] + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + return self + + def stop(self): + self.httpd.shutdown() + self.httpd.server_close() + + def turn(self, i): + return self.script[i] if i < len(self.script) else [("text", self.final_text)] + + @staticmethod + def send_sse(h, events): + data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events) + h._send(200, data, "text/event-stream") + + +class FakeAnthropic(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}" + + def handle(self, h, n, body): + if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict): + h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json") + return + msgs = body.get("messages", []) + i = sum(1 for m in msgs if m.get("role") == "assistant") + steps = self.turn(i) + blocks = [] + for j, st in enumerate(steps): + if st[0] == "tool": + blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2])) + else: + blocks.append(dict(type="text", text=st[1])) + stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn" + model = body.get("model", "fake") + evs = [("message_start", dict(type="message_start", message=dict( + id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None, + stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))] + for k, b in enumerate(blocks): + if b["type"] == "tool_use": + evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict( + type="tool_use", id=b["id"], name=b["name"], input={})))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict( + type="input_json_delta", partial_json=json.dumps(b["input"]))))) + else: + evs.append(("content_block_start", dict(type="content_block_start", index=k, + content_block=dict(type="text", text="")))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, + delta=dict(type="text_delta", text=b["text"])))) + evs.append(("content_block_stop", dict(type="content_block_stop", index=k))) + evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None), + usage=dict(output_tokens=5)))) + evs.append(("message_stop", dict(type="message_stop"))) + self.send_sse(h, evs) + + def message_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages") + and "count_tokens" not in p] + + +class FakeResponses(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}/v1" + + def handle(self, h, n, body): + if not isinstance(body, dict) or "input" not in body: + h._send(404, b"{}", "application/json") + return + items = body.get("input") or [] + i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in + ("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message" + and it.get("role") == "assistant")) + steps = self.turn(i) + out = [] + for j, st in enumerate(steps): + if st[0] == "exec": + out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name="exec", status="completed", input=st[1])) + elif st[0] == "fcall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name=st[1], arguments=json.dumps(st[2]), status="completed")) + elif st[0] == "nscall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed")) + else: + out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed", + content=[dict(type="output_text", text=st[1], annotations=[])])) + rid = f"resp_fake_{n}" + evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))] + for k, it in enumerate(out): + evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it))) + evs.append(("response.completed", dict(type="response.completed", response=dict( + id=rid, status="completed", output=out, usage=dict( + input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3, + output_tokens_details=dict(reasoning_tokens=0), total_tokens=103))))) + self.send_sse(h, evs) + + def model_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b] diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/framework_codex.py new file mode 100644 index 0000000000000000000000000000000000000000..68a8d7d09835f053760d9d0ca718cd79959b97e4 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_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/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..868ae9088ad36bd56f666750d4d8665ba3fc23ed --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code|2.1.267|0399c793ff571d59|claude-opus-5-5|high", + "fingerprint_sha256": "ba0025718a7a41033ee10a5d00cf9e4fb1c6eff7964f25169f9be4141839cc1f", + "written": "2026-10-20 02:16:03", + "summary": { + "system_chars": 182, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-opus-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..503130cc15af7a2201ecad552e4524cc3816e46d --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full|2.1.267|0399c793ff571d59|claude-opus-5-5|high", + "fingerprint_sha256": "06d6245468d20e3550a7ea4b8b4e7d9eda296ae16915dffa1b5bd7d12066efa6", + "written": "2026-10-13 04:12:41", + "summary": { + "system_chars": 6048, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-opus-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_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/compound-lh-20261102-clh_20261102_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/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_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/compound-lh-20261102-clh_20261102_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/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..c4798ace7f051de8818f09aa5baaed23432f4854 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-v4.1-flash|high", + "fingerprint_sha256": "080d6300858cdfc671e135073ec7f693bcf424eace689ffc480903b40f0e0894", + "written": "2026-10-30 16:02:13", + "summary": { + "system_chars": 114, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-v4.1-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/redteam.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/redteam.py new file mode 100644 index 0000000000000000000000000000000000000000..23c91f0e46b9df03459df1ac50d33a3fcf49dfc5 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_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/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/reference.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/harnesses/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..93a7ecef47a9e0f879e60d8521618b4378658db2 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_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/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/DRIVER.md b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/DRIVER.md new file mode 100644 index 0000000000000000000000000000000000000000..3ac1e4511c50001e98cc06ea902688a42a37ddaa --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/DRIVER.md @@ -0,0 +1,144 @@ +# LFF-Bench 真机驱动说明(给负责机械臂的同学) + +> 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`, +> 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。 + +## 0. 一句话 + +你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。 +模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。 + +``` +评测机(跑模型的人) 机器人电脑(你) +Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改 + └ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……) + └ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist + └ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败) +``` + +模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。 + +## 1. 你要交付的东西 + +1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。 +2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。 +3. 场景道具,见 §6。 +4. `scripts/real_check_driver.py` 全部 PASS(§7)。 +5. 一位操作员,按 §8 的规程操作。可以就是你。 + +需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。 +放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。 + +## 2. 坐标与约定(最重要的一节) + +| 量 | 约定 | +|---|---| +| 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 | +| 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 | +| 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** | +| yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) | +| `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) | +| `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` | +| `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) | + +这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是 +"You control a real `` robot arm (`` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。 + +## 3. 接口 + +所有请求都是 `POST http://127.0.0.1:/`,带 JSON body,请求头 `X-Driver-Token: `。 +所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。 +模板里任何未捕获的异常都会自动变成 fault。 + +| 接口 | 请求 | 回复(`ok` 之外) | 说明 | +|---|---|---|---| +| `info` | `{}` | `protocol` = 1,`robot`,`n_joints`,`cameras` = `["agentview","wrist"]`,`workspace` = `{lo:[x,y,z], hi:[x,y,z]}`,`yaw_range_deg` = `[lo,hi]`,`max_speed`(m/s),`ik`(bool),`driver_version` | 启动时调一次,内容写进每个 run 的契约 | +| `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 | +| `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) | +| `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 | +| `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 | +| `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会中心裁成正方形、缩到 512²,再存成 JPEG q90 | +| `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 | +| `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) | +| `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 | + +驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。 + +## 4. 安全(必须做) + +- **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。 +- **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。 +- **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。 +- **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。 +- `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。 + +## 5. 模型那边看到的和你有关的东西 + +- 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。 + 光照要稳定;模型运行时,画面里不要有人和多余的东西。 +- 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。 +- 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。 + +## 6. 两个任务的场景 + +实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。 + +### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`) + +模型看到的指令(与仿真相同):*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).* + +- **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。 + 可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。 +- **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。 + 合上盖子,两端外观一模一样,贴同样的胶带。 +- **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。 +- **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。 +- **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。 +- **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框); + 对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。 +- **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。 + +### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`) + +模型看到的指令:*Pick up the red cube and put it into the bowl.* + +- 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。 +- 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。 +- **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。 + 但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。 +- **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方块。 + +## 7. 联调步骤 + +1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。 +2. 启动驱动(token 自己定,私下发给跑评测的人): + ```bash + python driver_template.py --port 9900 --token --log driver_logs + ``` +3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上: + ```bash + python real_check_driver.py --driver http://127.0.0.1:9900 --token --operator + ``` + 全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。 +4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一: + - 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 @<机器人电脑>` + - 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 @<评测机>` +5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。 +6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。 + 一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。 + +## 8. 操作员规程 + +- 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。 +- 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。 +- 判 y / n 只看清单本身,不看模型"努力了没有"。 +- `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。 +- 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。 + +## 9. 常见问题 + +- **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。 +- **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。 +- **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。 +- **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。 +- **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。 diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/__init__.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b5513b07c27d6c467f8fd55f228d50d4aef4b482 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/__init__.py @@ -0,0 +1,10 @@ +"""Real-robot backend of LFF-Bench (docs/17): the same agent interface as simulation, with a robot driver underneath. + + protocol.py driver protocol v1 (both sides; stdlib + numpy + Pillow only) + executor.py RealToolExecutor: robot_server's executor on top of a driver (calibration bias injected here) + session.py RealRobotSession: robot_server's LA session without the simulator; python -m lffbench.real.session + tasks.py real-robot tasks (setup sheet, operator checklist, hidden variable from the seed) + fake_driver.py a driver backed by the simulator (no hardware) + driver_template.py skeleton for a hardware driver (copy to the robot PC with protocol.py) + DRIVER.md spec for the driver author and the operator +""" diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/driver_template.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/driver_template.py new file mode 100644 index 0000000000000000000000000000000000000000..e9381480b80fc81dc062c16f1a40b8ebe0475158 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/driver_template.py @@ -0,0 +1,196 @@ +"""Skeleton of a hardware driver for LFF-Bench (spec: DRIVER.md). Copy this file and protocol.py to the robot PC, +fill in the five methods marked TODO, run scripts/real_check_driver.py until every check passes. + + python driver_template.py --port 9900 [--token ] [--log ] + +Only Python 3 + numpy + Pillow are needed here (plus your robot / camera SDKs). Keep the server on 127.0.0.1; the +benchmark machine reaches it through an SSH tunnel (DRIVER.md §7). + +What is already done for you: the HTTP protocol, the token, the operator's terminal prompts, the safety checks that +must run before every motion (hard workspace box, speed limit), the motion timing, and an optional recorder that saves +both cameras to an mp4 per attempt. Everything robot-specific is in the TODO methods. +""" +import argparse +import os +import threading +import time + +import numpy as np + +try: # copied next to protocol.py on the robot PC + from protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize +except ImportError: # inside the repo (python -m lffbench.real.driver_template) + from .protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize + +# ---------------------------------------------------------------------------------------------- your setup (edit) +ROBOT = "AgileX PiPER" # TODO: the arm's name as the agent will read it ("You control a real robot arm") +N_JOINTS = 6 # TODO +# Hard workspace of the GRASP POINT in the robot-base frame (metres). Rejected targets never move the arm. Choose it so +# that every point inside is reachable with the gripper pointing straight down at any yaw in YAW_RANGE_DEG, and the +# lower z bound keeps the fingertips >= 5 mm above the table (the boxes are pushed with the fingertips ~1 cm up). +WORKSPACE_LO = [0.15, -0.25, 0.00] # TODO: measure on your table +WORKSPACE_HI = [0.45, 0.25, 0.30] # TODO +YAW_RANGE_DEG = [-120.0, 120.0] # TODO: gripper yaw your wrist reaches (span >= 180) +MAX_SPEED = 0.25 # m/s, the fastest straight-line speed you allow (the agent may ask for less) +HOME = dict(x=0.25, y=0.0, z=0.20, yaw_deg=0.0) # TODO: above the table centre, out of the agentview's way if possible +REACH_TOL = 0.004 # m: a move counts as finished when within this of the target and stopped +MOVE_TIMEOUT = 30.0 # s +DRIVER_VERSION = "template-0" # TODO: your git commit / date + + +class MyDriver(DriverServer): + image_format = "jpeg" # "png" is lossless but ~5x larger; jpeg q95 is fine over a LAN / SSH tunnel + + def __init__(self, record_dir=""): + self.lock = threading.RLock() # hardware access from the recorder thread and from requests + self.record_dir = record_dir + self.recorder = None + # TODO: connect to the arm, enable it, set the TCP (grasp point = midway between the fingertips, about 1 cm + # above their tips), open the cameras. Example for PiPER (piper_sdk; check the SDK docs, not verified here): + # from piper_sdk import C_PiperInterface_V2 + # self.arm = C_PiperInterface_V2("can0"); self.arm.ConnectPort(); ... enable ... + # Cameras: "agentview" = fixed camera looking at the table from the front/side (sees the whole work area); + # "wrist" = camera on the gripper. E.g. cv2.VideoCapture / pyrealsense2 colour stream. + raise NotImplementedError("connect the arm and the cameras") + + # ------------------------------------------------------------------ TODO 1: low-level hardware + def _send_cartesian(self, x, y, z, yaw_deg, speed): + """Start a straight-line (MoveL) motion of the grasp point to (x, y, z) with the gripper pointing straight down + and rotated by yaw_deg about the base z axis (0 = fingers close along the base y axis, +90 = along the base x + axis, counter-clockwise seen from above). Return False if the controller refuses (no IK).""" + raise NotImplementedError + + def _read_pose(self): + """-> (xyz of the grasp point in the base frame [m], yaw_deg, joint angles [rad], is_moving: bool).""" + raise NotImplementedError + + def _set_gripper(self, close): + """Close (force-limited, stop when blocked) or open fully; return when the fingers have stopped.""" + raise NotImplementedError + + def _gripper_width(self): + """Opening between the fingertips, metres.""" + raise NotImplementedError + + def _grab(self): + """-> {"agentview": HxWx3 uint8 RGB, "wrist": ...}: the newest frames (flush camera buffers first).""" + raise NotImplementedError + + def ik(self, eef_pos, yaw_deg): + """Optional (set info()["ik"] = True), needed only for real_bias_place: joint angles that put the grasp point + at eef_pos / yaw_deg (pointing down), the solution closest to the current joints. Do NOT move the arm.""" + raise NotImplementedError + + # ------------------------------------------------------------------ protocol (normally no need to edit) + def info(self): + return dict(protocol=PROTOCOL_VERSION, robot=ROBOT, n_joints=N_JOINTS, cameras=list(CAMERAS), + workspace=dict(lo=WORKSPACE_LO, hi=WORKSPACE_HI), yaw_range_deg=YAW_RANGE_DEG, max_speed=MAX_SPEED, + ik=False, driver_version=DRIVER_VERSION) + + def state(self): + with self.lock: + xyz, yaw, q, _ = self._read_pose() + return dict(eef_pos=[float(v) for v in xyz], eef_yaw_deg=float(yaw), gripper_width_m=float(self._gripper_width()), + joint_pos_rad=[float(v) for v in q]) + + def _inside(self, x, y, z, yaw_deg): + p = np.array([x, y, z]) + return (bool(np.all(p >= WORKSPACE_LO) and np.all(p <= WORKSPACE_HI)) + and YAW_RANGE_DEG[0] <= yaw_deg <= YAW_RANGE_DEG[1]) + + def move(self, x, y, z, yaw_deg, speed): + if not self._inside(x, y, z, yaw_deg): + return False, "outside the hard workspace", 0.0 + speed = MAX_SPEED if speed is None else float(np.clip(speed, 0.005, MAX_SPEED)) + with self.lock: + t0 = time.time() + if not self._send_cartesian(x, y, z, yaw_deg, speed): + return False, "no IK solution", 0.0 + tgt = np.array([x, y, z]) + while True: # blocking: return only once the arm has stopped + xyz, _, _, moving = self._read_pose() + if not moving and np.linalg.norm(np.asarray(xyz) - tgt) < REACH_TOL: + break + if time.time() - t0 > MOVE_TIMEOUT: + if not moving: + break # stopped short (blocked by an object): a normal outcome, the agent sees the pose + raise RuntimeError("move timed out while still moving") # -> fault: the run stops + time.sleep(0.02) + return True, None, time.time() - t0 + + def gripper(self, close): + with self.lock: + t0 = time.time() + self._set_gripper(close) + return time.time() - t0 + + def home(self): + ok, err, _ = self.move(HOME["x"], HOME["y"], HOME["z"], HOME["yaw_deg"], 0.15) + if not ok: + raise RuntimeError(f"cannot reach the home pose: {err}") + self.gripper(False) + return self.state() + + def images(self): + with self.lock: + return self._grab() + + def event(self, ev, run="", attempt=None, **kw): + if not self.record_dir: + return + if ev == "attempt_start": + self._stop_recording() + try: + self.recorder = Recorder(self, os.path.join(self.record_dir, f"{run}_a{attempt}.mp4")) + except Exception as e: # the video is only for the record: a missing imageio must not end a run as a fault + print(f"WARNING: recorder not started ({type(e).__name__}: {e}); " + "pip install imageio imageio-ffmpeg", flush=True) + elif ev in ("attempt_end", "episode_end", "session_end", "run_invalid"): + self._stop_recording() + + def _stop_recording(self): + if self.recorder is not None: + self.recorder.stop() + self.recorder = None + + +class Recorder(threading.Thread): + """agentview | wrist side by side at ~5 fps while an attempt runs (needs imageio + imageio-ffmpeg).""" + + def __init__(self, drv, path, fps=5, res=360): + super().__init__(daemon=True) + import imageio + self.drv, self.fps, self.res, self.halt = drv, fps, res, threading.Event() + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + self.w = imageio.get_writer(path, fps=fps, macro_block_size=8) + self.start() + + def run(self): + while not self.halt.is_set(): + t0 = time.time() + try: + with self.drv.lock: + f = self.drv._grab() + self.w.append_data(np.concatenate([square_resize(f[c], self.res) for c in CAMERAS], axis=1)) + except Exception as e: # never let the recorder break a run + print("recorder:", e) + self.halt.wait(max(0.0, 1.0 / self.fps - (time.time() - t0))) + + def stop(self): + self.halt.set() + self.join(timeout=5) + self.w.close() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--port", type=int, default=9900) + ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", "")) + ap.add_argument("--log", default="driver_logs", help="operator answers (operator.jsonl) and attempt videos") + a = ap.parse_args() + os.makedirs(a.log, exist_ok=True) + MyDriver(record_dir=a.log).serve(a.port, token=a.token or None, operator_log=os.path.join(a.log, "operator.jsonl")) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/executor.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..edb5a9a3932e891684f2a2c17bb8024c994d46dd --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/real/executor.py @@ -0,0 +1,138 @@ +"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor. + +robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and +call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver +(lffbench/real/protocol.py) instead of the simulator. + +Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and +reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the +ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation. +""" +import math +import time + +import numpy as np + +from ..agent.images import ImageRef +from ..agent.tools import ToolResult, parse_args +from .protocol import CAMERAS, DriverError, square_resize, state_problems + +SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class RealToolExecutor: + def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS): + self.driver, self.info = driver, info + self.bias = np.zeros(3) if bias is None else np.asarray(bias, float) + self.image_res = int(image_res) + self.cams = tuple(cams) + self.n_joints = int(info["n_joints"]) + self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"]) + self.max_speed = float(info["max_speed"]) + self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver + self.n_calls = 0 + self._state = None + self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open) + self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents + self.refresh() + self.yaw_cmd = float(self._state["eef_yaw_deg"]) + + # ------------------------------------------------------------------ state + def _set_state(self, st): + prob = state_problems(st, self.n_joints) + if prob: + raise DriverError("driver state: " + "; ".join(prob)) + self._state = st + + def refresh(self): + self._set_state(self.driver.state()) + + def true_eef(self): + return np.asarray(self._state["eef_pos"], float) + + def believed_eef(self): + return self.true_eef() - self.bias + + def proprio(self): + st = self._state + return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1), + gripper="closed" if self.grip_closed else "open", + gripper_width_m=round(float(st["gripper_width_m"]), 4)) + + def joints(self): + """Joint angles as the robot's encoders would report them under the hidden calibration error.""" + if not np.any(self.bias): + return [float(v) for v in self._state["joint_pos_rad"]] + key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"])) + if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command) + self._ik_key = key + self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])] + return list(self._ik_val) + + def observe(self, label=""): + frames, st = self.driver.observe() + self._set_state(st) + return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip()) + for c in self.cams] + + # ------------------------------------------------------------------ helpers + def wrap_yaw(self, yaw): + """The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to + the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit).""" + cands = [yaw + 180.0 * k for k in range(-3, 4)] + ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw_cmd))) + + # ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call) + def call(self, name, raw_args): + t0 = time.time() + self.n_calls += 1 + args = parse_args(raw_args) + fn = getattr(self, f"_t_{name}", None) + if fn is None: + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + res = fn(**args) + res.args, res.wall_s = args, time.time() - t0 + return res + + def _report(self, name, extra=None): + rep = dict(ok=True, tool=name) + rep.update(extra or {}) + rep.update(self.proprio()) + return rep + + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt = np.array([x, y, z], float) + if not np.all(np.isfinite(tgt)): + return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates")) + spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed)) + yaw_used = self.wrap_yaw(float(yaw)) + cmd = tgt + self.bias # the hidden calibration error acts on every commanded position + rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution) + return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; " + "the arm did not move", driver_error=rep.get("error", ""))) + self.yaw_cmd = yaw_used + reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02) + return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached, + yaw_used_deg=round(yaw_used, 1)))) + + def _gripper(self, close): + rep = self.driver.gripper(close) + self.grip_closed = bool(close) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + name = "close_gripper" if close else "open_gripper" + return ToolResult(name, {}, True, self._report(name)) + + def _t_open_gripper(self): + return self._gripper(False) + + def _t_close_gripper(self): + return self._gripper(True) diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l5_slide.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l5_slide.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee239b7ba2793288aeaaa5e5d4f0a5b11c835f5 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/l5_slide.py @@ -0,0 +1,577 @@ +"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone. + +Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the +same for every mu. With the default push speed the cube overshoots on slippery instances and stops +short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard +to push next time (cf. MemMimic push_cube, iterative pushing). + +Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt +(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that +carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule +also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The +loophole is now closed by the success rule instead: + +Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there +by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts +checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with +nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push +into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in +front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm. + +Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged +when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside). +`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then +succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the +arm's reach (the attempt is not ended for it). + +Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance +the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre). +SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX), +so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time. + +Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview +camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far +edge by up to ~1 cm covers the far green line but shows < 2 px of red beyond it in the 512 x 512 image, which looks like +"inside / on the line" (self-test: 0.8 cm past the inner edge looked inside). So on the far side the cube may now lie on +the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to +TOL_PAST = 2.0 cm past the square's centre (front face <= 4 mm beyond the line's outer edge). From 2.0 cm on, every one +of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely +inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides +the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +CUBE = "cube_1" +CUBE_HALF = 0.02 +D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long +STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike +TOUCH_MOVE = 0.001 # a contact episode moved the cube if the cube ends >= 1 mm (3-D) from where it was at its start +EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode +V_REST, W_REST = 0.003, 0.05 # cube at rest: linear speed below 3 mm/s and angular speed below 0.05 rad/s ... +REST_SUB = 25 # ... for 25 consecutive substeps (50 ms) +WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest +ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF +OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table +REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable + + +class CubeWatch: + """Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it). + + contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed + EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was + when the episode began, or still moving. + release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide + began (None while the robot has never moved the cube). + strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to + rest (or when the robot touches it again before that: result "interrupted").""" + + def __init__(self, env, target_xy, tol_short, tol_past, tol_across): + m = env.sim.model + self.env = env + self.is_robot = np.zeros(m.ngeom, bool) + self.is_robot[envs.robot_geom_ids(env)] = True + self.is_cube = np.zeros(m.ngeom, bool) + self.is_cube[envs.obj_geom_ids(env, CUBE)] = True + self.qa, self.da = envs.free_joint_addr(env, CUBE) + self.target = np.asarray(target_xy, float) + self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside + self.n_sub = 0 + self.ep = None # open contact episode + self.gap = 0 + self.quiet = 0 # consecutive substeps at rest + self.release = None + self.slide = None # free slide in progress: where it started (cube at the episode start) and was released + self.moves = [] # closed contact episodes that moved the cube + self.strikes = [] + + # ------------------------------------------------------------ state + def pos(self): + return self.env.sim.data.qpos[self.qa:self.qa + 3].copy() + + def at_rest(self): + qv = self.env.sim.data.qvel[self.da:self.da + 6] + return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST) + + def judge(self, p): + """Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off). + in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it.""" + along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1]) + if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE: + return along, across, "off" + short, past, beside = self.tol + if -short <= along <= past and abs(across) <= beside: + return along, across, "in" + if along > past: + return along, across, "past" + if along < -short: + return along, across, "short" + return along, across, "beside" + + # ------------------------------------------------------------ per substep + def substep(self): + d = self.env.sim.data + n = d.ncon + touch = False + if n: + g1 = np.asarray(d.contact.geom1)[:n] + g2 = np.asarray(d.contact.geom2)[:n] + touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1]))) + self.n_sub += 1 + p = self.pos() + rest = self.at_rest() + self.quiet = self.quiet + 1 if rest else 0 + if touch: + if self.ep is None: + if self.slide is not None: + self._end_slide(p, interrupted=not rest) + self.ep = dict(start=p, sub0=self.n_sub) + self.ep["last"] = p + self.ep["sub1"] = self.n_sub + self.gap = 0 + elif self.ep is not None: + self.gap += 1 + if self.gap >= EP_GAP: + self._close(p, rest) + if self.ep is None and self.slide is not None and self.quiet >= REST_SUB: + self._end_slide(p, interrupted=False) + + def _close(self, p, rest): + ep, self.ep = self.ep, None + if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest: + return # touched a resting cube and left it where it was + self.release = ep["last"][:2].copy() + self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(), + release=ep["last"].round(4).tolist())) + self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"]) + + def _end_slide(self, p, interrupted): + s, self.slide = self.slide, None + free = float(np.linalg.norm(p[:2] - s["release"][:2])) + if free < STRIKE_MIN: + return # a push or a put-down, not a strike + along, across, res = self.judge(p) + self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(), + release=s["release"].round(4).tolist(), rest=p.round(4).tolist(), + pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2), + free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2), + across_err_cm=round(100 * across, 2), + result="interrupted" if interrupted else res, + missed=bool(not interrupted and res != "in"))) + + def flush(self): + """End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact + has moved it (then the cube's current free slide is 0).""" + p = self.pos() + if self.ep is not None: + if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest(): + self.release = p[:2].copy() + self.slide = None + return True + return False + if self.slide is not None and self.at_rest(): + self._end_slide(p, interrupted=False) + return False + + +def _install_watch(sim, watch): + """Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker; + it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one + control step, so contact checks at control steps alone would miss it.""" + if not getattr(sim, "_lff_slide_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + w = getattr(sim, "_lff_slide_watch", None) + if w is not None: + w.substep() + sim.step = step + sim._lff_slide_wrapped = True + sim._lff_slide_watch = watch + + +class SlideSkills(Skills): + """Skills whose motion commands return only once the cube has come to rest (see the module docstring).""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self._qa, self._da = envs.free_joint_addr(env, CUBE) + self.waits = [] # (control step, steps waited) for every command that had to wait + + def cube_moving(self): + qv = self.env.sim.data.qvel[self._da:self._da + 6] + return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST) + + def wait_cube_rest(self): + """Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed. + No wait if the cube is already at rest or is held (it then moves with the arm).""" + if not self.cube_moving() or self.holding(CUBE): + return 0 + p, R = self.eef_pos(), self._R() + quiet = 0 + for k in range(WAIT_MAX): + self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + quiet = 0 if self.cube_moving() else quiet + 1 + if quiet >= 2: + break + self.waits.append((self.n_steps, k + 1)) + return k + 1 + + def move_to(self, target, *args, **kwargs): + rep = super().move_to(target, *args, **kwargs) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + n = self.wait_cube_rest() + if n: + rep["waited_s"] = round(n * DT, 2) + return rep + + +INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm +LINE_W = 0.006 +# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of +# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre +# <= 2.0 cm past it, i.e. the front face up to 4 mm beyond the line, which in the 512 x 512 agentview is < 2 px of red +# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19). +TOL_PAST = 0.020 + + +def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W, + line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)): + """Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions).""" + o = inner_half + line_w + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba), + ((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba), + ((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba), + ((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(model_name, g, 0.0012, o) + + +Z_PUSH = envs.TABLE_Z + 0.02 +V_MIN, V_MAX = 0.12, 0.60 +Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table) + + +@register_task +class SlideToTarget(LFFTask): + name = "l5_slide_to_target" + level = "L5" + category = "dynamics_adaptation" + capabilities = ("Reason", "Utilize") + # no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there) + instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green " + "square marked on the table. On the side of the square nearest the robot and on its left and " + "right, no part of the cube may lie on or beyond the green border line. On the far side, away from " + "the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. " + "The cube must slide the last part of the way on its own: after it leaves the gripper it has to " + f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the " + "square.") + instruction_indirect = instruction + tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm) + tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST) + runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact + tol_across = INNER_HALF - CUBE_HALF + + def make_bddl(self): + cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1), + density=1000)) + # static fixture (no joint): a free body without collisions would fall through the table + zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False) + objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))] + fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))] + return write_bddl(self.name, self.instruction, objs, fixtures=fixtures) + + def apply_instance(self, inst): + m = self.env.sim.model + zone = self.env.fixtures_dict["zone_1"] + # the target zone is a flat marker: no collisions + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("zone_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + x0, y0 = inst["cube_xy"] + envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001]) + bid = m.body_name2id(zone.root_body) + m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + envs.set_friction(self.env, "cube_1", inst["mu"]) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + x0, y0 = inst["cube_xy"] + self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past, + self.tol_across) + _install_watch(self.env.sim, self.watch) + self.sk = SlideSkills(self.env, recorder=recorder) + return self.sk + + @staticmethod + def max_reach(mu): + """Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m): + mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm.""" + return 0.0103 / mu ** 0.95 + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: # reject instances the top speed cannot reach (keeps every instance solvable) + inst = dict(seed=int(seed), + cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))], + target_dist=float(rng.uniform(0.05, 0.12)), + mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10))))) + if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]): + return inst + + # ------------------------------------------------------------ outcome + def outcome(self, inst): + envs.settle(self.env, 40) + w = self.watch + for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest + if w.at_rest(): + break + envs.settle(self.env, 5) + touching = w.flush() + x0, y0 = inst["cube_xy"] + c = envs.obj_pos(self.env, CUBE) + along = (c[0] - x0) - inst["target_dist"] + across = c[1] - y0 + _, _, where = w.judge(w.pos()) + inside = where == "in" + at_rest = w.at_rest() + free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0 + slid = bool(w.release is not None and not touching and free >= D_MIN) + success = bool(inside and at_rest and slid) + strikes = w.strikes + n_missed = sum(s["missed"] for s in strikes) + from ..agent.tools import WS_HI, WS_LO + reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN)) + irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach) + + parts = [] + if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN: + parts.append("The cube was not pushed.") + if c[2] < OFF_TABLE_Z: + parts.append("The cube fell off the table.") + else: + state = {"in": "in the square", "past": "it sticks out beyond the far green line", + "short": "it sticks out past the edge of the square nearest the robot"}.get(where, + "not in the square") + if along > 0: + parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).") + else: + parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square " + f"({state}).") + if abs(across) > self.tol_across: + parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} " + f"(robot's view).") + if where == "off" and c[2] > OFF_TABLE_Z: + parts.append("It is not resting on the table.") + if inside and not at_rest: + parts.append("It was still moving when the attempt ended.") + if touching: + parts.append("The gripper was still touching (or holding) the cube when the attempt ended.") + elif inside and w.release is not None and free < D_MIN: + parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide " + f"at least {100 * D_MIN:.0f} cm.") + if success: + failure = None + elif w.release is None and not inside: + failure = "not_touched" + elif not inside: + failure = "position" + elif not at_rest: + failure = "not_at_rest" + else: + failure = "slide_too_short" + out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts), + inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2), + release_xy=None if w.release is None else w.release.round(4).tolist(), + touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes), + n_missed_strikes=int(n_missed), trap_fired=n_missed > 0, + recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable, + strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure) + return out + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the + point of contact, lift (the move returns once the cube has come to rest).""" + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.set_gripper(True, steps=5) + sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0) + sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), + tol=0.01, max_steps=80) + sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3) + + def default_params(self, inst): + return dict(speed=0.30) + + def blind_params(self, inst, attempt, rng): + return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))) + + def adapt_params(self, inst, history): + """Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search + on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt).""" + pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history) + lo = [p for p in pts if p[1] < 0] + hi = [p for p in pts if p[1] > 0] + if lo and hi: + (v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0]) + v = v0 + (v1 - v0) * (-e0) / (e1 - e0) + elif hi: # always overshooting: slow down + v = min(p[0] for p in hi) * 0.7 + else: # always short: speed up + v = max(p[0] for p in lo) * 1.35 + return dict(speed=float(np.clip(v, V_MIN, V_MAX))) + + def oracle_params(self, inst): + """Privileged: bisection on speed by simulating pushes (uses the true mu).""" + if "_oracle_speed" in inst: + return dict(speed=inst["_oracle_speed"]) + lo, hi = V_MIN, V_MAX + best = None + for _ in range(9): + mid = 0.5 * (lo + hi) + self.reset_instance(inst) + self.execute(inst, dict(speed=mid)) + e = self.outcome(inst)["along_err"] + if best is None or abs(e) < abs(best[1]): + best = (mid, e) + if e > 0: + hi = mid + else: + lo = mid + inst["_oracle_speed"] = best[0] + self.reset_instance(inst) + return dict(speed=best[0]) + + # ------------------------------------------------------------ scripted within-attempt correction + AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ... + AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command + RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short + + def _strike_here(self, speed): + """Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up + point + close, down, strike (returns at rest), lift.""" + c = envs.obj_pos(self.env, CUBE) + sk = self.sk + sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0) + sk.set_gripper(True, steps=5) + sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01, + max_steps=80) + sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3) + return 4 + + def _carry_back(self, inst): + """Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands: + above it + open, down + close, lift, carry, down + open, lift.""" + c = envs.obj_pos(self.env, CUBE) + x0, y0 = inst["cube_xy"] + sk = self.sk + sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0) + sk.set_gripper(False, steps=10) + sk.move_to([c[0], c[1], Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([c[0], c[1], Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.06]) + sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([x0, y0, Z_GRASP + 0.10]) + return 6 + + @staticmethod + def _plan_speed(want, pts): + """Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s + prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes + (or extrapolation from the two nearest, exponent clipped to [0.5, 3]).""" + pts = sorted((v, d) for v, d in pts if d > 0.002) + if not pts: + return 0.30 + if len(pts) == 1: + v, d = pts[0] + return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX)) + lo = [p for p in pts if p[1] <= want] + hi = [p for p in pts if p[1] > want] + if lo and hi: + (v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1]) + else: + (v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2] + if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6: + return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX)) + k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0)) + return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX)) + + def _adaptive_attempt(self, inst, pts): + """One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect + perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot, + a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed + planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square + or the next correction would not fit in the agent's command / motion budget.""" + x0, y0 = inst["cube_xy"] + tx = x0 + inst["target_dist"] + sk = self.sk + n0 = sk.n_steps + n_cmd, speeds, path = 0, [], [] + while True: + c = envs.obj_pos(self.env, CUBE) + want = tx - c[0] + near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01 + local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts] + speed = self._plan_speed(want, local) + n_cmd += self._strike_here(speed) + c1 = envs.obj_pos(self.env, CUBE) + pts.append((speed, float(c1[0] - c[0]), near_start)) + speeds.append(round(speed, 4)) + err, across = float(c1[0] - tx), float(c1[1] - y0) + path.append("strike") + if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across: + break + used_s = (sk.n_steps - n0) * DT + if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005: + if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S: + break + continue + if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S: + break + n_cmd += self._carry_back(inst) + path.append("carry_back") + return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd, + sim_s=round((sk.n_steps - n0) * DT, 1)) + + def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None): + """oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects + within the attempt (_adaptive_attempt) and carries what it saw into the next attempt.""" + if kind != "adaptive": + return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt) + k = k or self.max_attempts + history, pts = [], [] + for a in range(k): + self.reset_instance(inst) + params = self._adaptive_attempt(inst, pts) + 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 diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_balance_board.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_balance_board.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4ceaea2c011176291dd2723cc94d344f23d991 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_balance_board.py @@ -0,0 +1,817 @@ +"""LH balance_board: put four look-alike cubes on their marks on a plank that rests loose across a narrow block (a +seesaw); loading it in the wrong order tips the plank, and every cube already on it slides down to the low end. + +Family: long-horizon self-disturbance ("state_restoration"): each stage is a plain pick-and-place of a cube onto its +mark, but a later placement can tip the plank, which sends the cubes placed before it (earlier progress) sliding off +their marks. The agent has to notice it, re-level the plank and re-place them before finishing (within an attempt), and +learn a loading order that keeps the plank level (across attempts; the final-state judge does not enforce an order). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a grey support (fixture: two 1.5 cm blocks with a 1 cm slot between them, together 4 cm along the plank x 10 cm x + 6 cm high, flat tops) under the middle of + * a dark wooden plank (free body, 46 cm long, pointing away from the robot, 8 cm wide, 1.5 cm thick, 0.5 kg) lying + loose on it, level, with a 2 cm lip across each end. A thin keel under the plank's middle hangs in the slot and keeps + the plank from wandering along the support (+-3 mm); nothing holds it down. It stays level while the combined centre + of mass of plank + cubes is above the support's 4 cm top; otherwise it tips until its low end touches the table + (about 17 degrees); + * four marks (5.8 cm squares, outline + light fill) on the plank, two on each side of the block: an inner one + (8.5-9.5 cm from the middle) and an outer one (15.5-16.5 cm); the colour of each mark is random; + * four 4.5 cm cubes (red, green, blue, yellow) on the table, two left and two right of the plank (random places). + They look alike except for the colour. Cube and plank surfaces are slick (friction 0.2 < tan 17 deg): on a tipped + plank every cube slides down to the lip at the low end. +Why along x with lips (measured, see the task card): with the plank left-right and open ends, the cubes slid off the +ends onto the table 0-11 cm past them, and a default top-down grasp there (fingers left-right, the Panda hand is 21 cm +wide along them) pressed the plank's end down and tipped it again -- restoring became a loop. Along x the default grasp +is across the plank, and the lips keep the cubes on the plank within reach. + +Hidden variable: the cube masses. "Hazard" instances (13 of every 20 consecutive seeds): the two cubes that belong on +the inner marks are heavy (stone, 0.19-0.24 kg), the two for the outer marks are light (48-56 g); the final layout is +balanced. A heavy cube alone on its inner mark tips the plank (1.28-1.43 x the tipping moment); a light one alone on its +outer mark does not (0.72-0.78 x); in the zig-zag order below no step exceeds 0.72-0.81 x. So the only safe loading +orders are "an outer cube, then the inner cube on the OTHER side, then the other inner cube, then the last outer cube" +(zig-zag); end-to-end, alternating outer-first (outer, outer, inner, inner) and inner-first orders all tip it. +"Benign" instances: all four cubes light (26-34 g); no order tips (worst step 0.63-0.75 x). + +Why the natural order fails: nothing in the image shows which cubes are heavy. Any natural order (nearest cube first, +the marks from one end to the other, or the cautious "alternate sides, outer marks first") tips the plank in a hazard +instance; the cubes on it slide to the low end and keep it tipped. A natural plan then keeps going and finishes with +cubes off their marks. What must be learned: check the marks after each placement / before finishing, unload the low +end and re-place (within the attempt), and use the tip to infer which cubes are heavy (an inner cube tipped it; the +layout must balance in the end, so the other inner cube is heavy too) and load in the zig-zag order (across attempts). + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube on its +mark, plank level within 3 degrees and still on its support (10-11), nothing held, scene static) plus an event log of every stage predicate (achieved / +lost / restored, with step and cause) and every tip (which end went down, the cube released just before) for the server +log; F1 gives the agent only success / failure. +""" +import itertools + +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 + +TZ = envs.TABLE_Z + +# ---------------------------------------------------------------- geometry / physics +# plank frame: y along the plank (+y = the end toward the robot), x across it, z up. The plank and the block are +# yawed 90 deg, so plank +y = world -x. +PL_HL, PL_HW, PL_HT = 0.23, 0.04, 0.0075 # plank half length, half width, half thickness +LIP_T, LIP_H = 0.008, 0.02 # lip across each end (inside the 46 cm), height above the plank's top +PLANK_MASS = 0.50 +PLANK_ROT_DAMP = 0.01 # N m s / rad on the plank's rotation: after its low end is unloaded it swings over to ~10 deg +# and is calm in ~1.5 s (no damping: ~13 deg and ~2.7 s); the tip itself is not slowed (measured) +PLANK_YAW = np.pi / 2 +RIDGE_HW, RIDGE_HX, RIDGE_H = 0.02, 0.05, 0.06 # support: half width along the plank (s), half depth, height +SLOT_HW = 0.005 # the support is two blocks with a 1 cm slot between them +KEEL_HW, KEEL_H = 0.002, 0.010 # keel under the plank's middle (4 mm x 8 cm x 1 cm) hanging in the slot +CUBE_E = 0.045 +MU = 0.20 # cubes and plank: the cube-plank contact slides above 11 deg; ridge (1.0), table (0.6), finger pads (2.0) win +MU_RIDGE = 1.0 +MARK_HALF, MARK_LINE = 0.029, 0.004 +WOOD = (0.42, 0.27, 0.15, 1.0) # dark walnut: contrasts with the light table, so the tilt reads in the images + +COLORS = ("red", "green", "blue", "yellow") +RGBA = dict(red=(0.85, 0.12, 0.10, 1.0), green=(0.10, 0.62, 0.20, 1.0), blue=(0.15, 0.30, 0.88, 1.0), + yellow=(0.93, 0.78, 0.10, 1.0)) +CUBES = {c: f"{c}_cube_1" for c in COLORS} +PLANK, RIDGE = "plank_1", "ridge_1" +PLANK_MODEL = "lff_lh_bb_plank" +# mark slots in plank-frame order (+y first): the robot's end outer / inner, then the far end inner / outer +SLOTS = ("near_outer", "near_inner", "far_inner", "far_outer") +END_WORD = dict(near="the end nearer the robot", far="the far end") + +# ---------------------------------------------------------------- instances / hidden variable +D_INNER = (0.085, 0.095) # |y| of the inner marks from the plank's middle +D_OUTER = (0.155, 0.165) # the lip stops a cube 19.95 cm out: a cube on a low-side outer mark ends >= 3.5 cm off it +P_HAZARD = 0.65 # fraction of hazard instances, balanced per 20 consecutive seeds (13 / 7) +R_HEAVY = (1.30, 1.40) # hazard: lone heavy cube on its inner mark, moment / tipping moment +R_LIGHT = (0.72, 0.78) # hazard: lone light cube on its outer mark +LIGHT_BENIGN = (0.026, 0.034) # benign: every cube (kg) +H_EST, L_EST = 0.21, 0.04 # nominal masses the adaptive script uses for its hypotheses (it never sees the true ones) + +# ---------------------------------------------------------------- judging +TOL = 0.020 # cube centre within 2 cm of its mark centre (per plank axis) +TOL_LOSE = 0.025 # hysteresis for the monitor +LEVEL_DEG = 3.0 +TIP_DEG = 8.0 # the monitor records a tip when |tilt| exceeds this (a real tip reaches ~17 deg) +LEVEL_DEBOUNCE = 4 # monitor evaluations (0.1 s each) before plank_level changes +FLAT_COS = np.cos(np.radians(15.0)) +SUPPORT_XY = 0.02 # plank on its support: its middle within 2 cm (horizontally) of the support's centre ... +SUPPORT_DZ = 0.02 # ... and not more than 2 cm below its starting height (a tip lowers it ~0.6 cm; off the block ~6 cm) + +# ---------------------------------------------------------------- scripted motion +Z_CARRY = 0.17 # careful / adaptive: grasp point above the table while carrying (cube bottom 14.75 cm) +Z_CARRY_NAIVE = 0.15 # naive: just above the cubes already on the plank (their tops at 12 cm) +REL_GAP = 0.004 # release with the cube's bottom this far above the plank + + +def plank_xml(name): + """Board + end lips + keel (collision) and per colour a mark (5 visual-only geoms, moved per instance). + Long axis = body y.""" + g = [] + + def box(nm, pos, size, rgba): + g.append(f'') + g.append(f'') + + dark = (0.25, 0.16, 0.09, 1.0) + box(f"{name}_board", (0, 0, 0), (PL_HW, PL_HL, PL_HT), WOOD) + for k, s in enumerate((1, -1)): + box(f"{name}_lip{k}", (0, s * (PL_HL - LIP_T / 2), PL_HT + LIP_H / 2), (PL_HW, LIP_T / 2, LIP_H / 2), dark) + box(f"{name}_keel", (0, 0, -PL_HT - KEEL_H / 2), (PL_HW, KEEL_HW, KEEL_H / 2), dark) + for c in COLORS: + rgba = RGBA[c] + fill = tuple(0.55 + 0.45 * v for v in rgba[:3]) + (1.0,) + o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE + parts = [((0, 0, PL_HT + 0.0003), (o, o, 0.0003), fill), + ((0, i + w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((0, -i - w / 2, PL_HT + 0.0008), (o, w / 2, 0.0003), rgba), + ((i + w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba), + ((-i - w / 2, 0, PL_HT + 0.0008), (w / 2, o, 0.0003), rgba)] + for k, (p, sz, col) in enumerate(parts): + g.append(f'') + return _wrap(name, "\n ".join(g), PL_HT, float(np.hypot(PL_HL, PL_HW))) + + +def ridge_xml(name): + """Split support: two 1.5 cm blocks with a 1 cm slot between them; the plank rests on both and pivots on their outer + top edges (a 4 cm flat top). The plank's keel hangs in the slot, so the plank cannot wander along its length by + more than +-3 mm (it stays engaged at the full tip angle).""" + rgba = (0.35, 0.35, 0.38, 1.0) + bh = (RIDGE_HW - SLOT_HW) / 2 + g = [] + for k, sy in enumerate((1, -1)): + p, sz = (0, sy * (SLOT_HW + bh), RIDGE_H / 2), (RIDGE_HX, bh, RIDGE_H / 2) + g.append(f'') + g.append(f'') + g = "\n ".join(g) + return f""" + + + + {g} + + + + + + +""" + + +def tip_ratio(items, plank_mass=PLANK_MASS, s=RIDGE_HW): + """Static model of a loose plank on a flat-topped block: |sum m y| / ((M_plank + sum m) s); the plank tips when + this exceeds 1 (the combined centre of mass leaves the block's top). items: [(mass, y from the middle)].""" + if not items: + return 0.0 + mom = sum(m * y for m, y in items) + return abs(mom) / ((plank_mass + sum(m for m, _ in items)) * s) + + +def _side(y): + return "near" if y > 0 else "far" + + +def _along(v): + """plank-frame y offset in robot-centric words (+y = toward the robot)""" + return f"{100 * abs(v):.1f} cm from its mark toward {'the robot' if v > 0 else 'the far end'}" + + +class BoardSkills(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 BalanceBoard(LFFTask): + name = "lh_balance_board" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Restore") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 120 # careful zig-zag ~30-36 commands + re-placing four cubes (~30) + looking around + instruction = ("Put each coloured cube on the square mark of the same colour on the long plank. The plank lies loose " + "across a narrow block under its middle. At the end all four cubes must be on their marks and the " + "plank must still rest level on the block.") + instruction_indirect = ("Set the four coloured cubes onto the outlined squares of matching colour on the wooden " + "board that rests across the small grey block. When you are done, every cube must sit on " + "its square and the board must still rest level on the block.") + agent_object_names = ["red cube", "green cube", "blue cube", "yellow cube", "plank", "support block", + "red mark", "green mark", "blue mark", "yellow mark"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + pl = register_generated("LffLhBbPlank", plank_xml(PLANK_MODEL)) + rg = register_generated("LffLhBbRidge", ridge_xml("lff_lh_bb_ridge"), free=False) + objs = [(PLANK, pl, "plank_region", (0.18, -0.01, 0.20, 0.01))] + e = CUBE_E / 2 + for i, c in enumerate(COLORS): + cat = register_generated(f"LffLhBbCube{c.title()}", + box_xml(f"lff_lh_bb_cube_{c}", (e, e, e), RGBA[c], density=500.0, + friction=(MU, 0.005, 0.0001)).replace( + 'solimp="0.998 0.998 0.001" solref="0.001 1"', "")) + objs.append((CUBES[c], cat, f"{c}_cube_region", (-0.32, -0.33 + 0.2 * i, -0.30, -0.31 + 0.2 * i))) + fx = [(RIDGE, rg, "ridge_region", (-0.12, 0.30, -0.10, 0.32))] + return write_bddl(self.name, "put each cube on its mark on the plank and keep the plank level", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.ridge_bid = m.body_name2id(self.env.fixtures_dict[RIDGE].root_body) + self.plank_bid = envs.body_id(self.env, PLANK) + pre = f"{PLANK}_{PLANK_MODEL}" + self.mark_gids = {c: [m.geom_name2id(f"{pre}_mk_{c}_{k}") for k in range(5)] for c in COLORS} + self.mark_pos0 = {c: [m.geom_pos[g].copy() for g in self.mark_gids[c]] for c in COLORS} + self.cube_gids = {c: set(envs.obj_geom_ids(self.env, CUBES[c])) for c in COLORS} + self.plank_gids = set(envs.obj_geom_ids(self.env, PLANK)) + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.inst = None + self.mon = None + self.obs = [] # adaptive script: (configuration, tipped) observations, kept across the attempts of one run + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + x0, y0 = float(rng.uniform(-0.18, -0.14)), float(rng.uniform(-0.03, 0.03)) + perm = [str(c) for c in rng.permutation(COLORS)] # colour of the mark in SLOTS order + slot_of = {c: s for c, s in zip(perm, SLOTS)} + dist = dict(near_outer=float(rng.uniform(*D_OUTER)), near_inner=float(rng.uniform(*D_INNER)), + far_inner=-float(rng.uniform(*D_INNER)), far_outer=-float(rng.uniform(*D_OUTER))) + marks = {c: dist[slot_of[c]] for c in COLORS} # plank-frame y of each mark (+ = toward the robot) + hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD)) # balanced like l7_key_turn / lh_lid_box + r_h, r_l = float(rng.uniform(*R_HEAVY)), float(rng.uniform(*R_LIGHT)) + light = {c: float(rng.uniform(*LIGHT_BENIGN)) for c in COLORS} + s, pm = RIDGE_HW, PLANK_MASS + if hazard: + # equal moments on both sides -> the finished layout is exactly balanced + dn, do = dist["near_inner"], dist["near_outer"] + y_h = r_h * pm * s / (dn - r_h * s) * dn # heavy on the near inner mark: moment r_h x tipping moment + x_l = r_l * pm * s / (do - r_l * s) * do + mass = {c: (y_h if "inner" in slot_of[c] else x_l) / abs(dist[slot_of[c]]) for c in COLORS} + else: + mass = light + # start: two cubes left and two right of the plank, 17-19 cm from its axis, at two depths (random places) + spots = [(dx, sy) for sy in (1.0, -1.0) for dx in (-0.08, 0.08)] + order = rng.permutation(4) + start = {c: [x0 + spots[j][0] + float(rng.uniform(-0.01, 0.01)), + y0 + spots[j][1] * float(rng.uniform(0.17, 0.19))] for c, j in zip(COLORS, order)} + start_yaw = {c: float(rng.uniform(-0.3, 0.3)) for c in COLORS} + heavy = sorted(c for c in COLORS if mass[c] > 0.1) + return dict(seed=int(seed), plank_xy=[x0, y0], marks=marks, slot_of=slot_of, hazard=hazard, mass=mass, + heavy=heavy, r_heavy=r_h if hazard else None, r_light=r_l if hazard else None, start=start, + start_yaw=start_yaw) + + def apply_instance(self, inst): + self.inst = inst + env = self.env + m = env.sim.model + x0, y0 = inst["plank_xy"] + q = [np.cos(PLANK_YAW / 2), 0.0, 0.0, np.sin(PLANK_YAW / 2)] + m.body_pos[self.ridge_bid] = [x0, y0, TZ] + m.body_quat[self.ridge_bid] = q + envs.scale_mass(env, PLANK, PLANK_MASS) + _, da = envs.free_joint_addr(env, PLANK) + m.dof_damping[da + 3:da + 6] = PLANK_ROT_DAMP + for c in COLORS: + for g, p0 in zip(self.mark_gids[c], self.mark_pos0[c]): + m.geom_pos[g] = p0 + np.array([0.0, inst["marks"][c], 0.0]) + envs.scale_mass(env, CUBES[c], inst["mass"][c]) + envs.set_obj_pose(env, PLANK, [x0, y0, TZ + RIDGE_H + PL_HT + 0.0005], quat_wxyz=np.array(q)) + for c in COLORS: + envs.place_upright(env, CUBES[c], inst["start"][c], yaw=inst["start_yaw"][c]) + + 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, 10) + self.plank_z0 = float(self.plank_pos()[2]) + self.sk = BoardSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def plank_R(self): + return self.env.sim.data.body_xmat[self.plank_bid].reshape(3, 3).copy() + + def plank_pos(self): + return self.env.sim.data.body_xpos[self.plank_bid].copy() + + def tilt_deg(self): + """+ = the plank's end toward the robot is up""" + return float(np.degrees(np.arcsin(np.clip(self.plank_R()[2, 1], -1.0, 1.0)))) + + def is_level(self, deg=LEVEL_DEG): + return abs(self.tilt_deg()) <= deg + + def on_support(self): + """the plank still rests on the support block (10-11: Sonnet lh2 s3001 pushed it off onto the table, where it + lies level, and loaded the cubes there; 'level' alone accepted that)""" + p, r = self.plank_pos(), self.env.sim.data.body_xpos[self.ridge_bid] + return bool(np.linalg.norm(p[:2] - r[:2]) <= SUPPORT_XY and p[2] >= self.plank_z0 - SUPPORT_DZ) + + def in_plank(self, p): + """world point -> plank frame (x across, y along from the middle, z above the plank's mid-plane)""" + return self.plank_R().T @ (np.asarray(p, float) - self.plank_pos()) + + def mark_world(self, c): + return self.plank_pos() + self.plank_R() @ np.array([0.0, self.inst["marks"][c], PL_HT]) + + def cube_pos(self, c): + return envs.obj_pos(self.env, CUBES[c]) + + def held(self, c): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, + object_geoms=self.env.objects_dict[CUBES[c]])) + + def on_plank(self, c): + """resting on the plank's top (plank frame), anywhere along it""" + q = self.in_plank(self.cube_pos(c)) + return bool(abs(q[0]) <= PL_HW + 0.01 and abs(q[1]) <= PL_HL and abs(q[2] - PL_HT - CUBE_E / 2) <= 0.012) + + def mark_offset(self, c): + q = self.in_plank(self.cube_pos(c)) + return np.array([q[0], q[1] - self.inst["marks"][c]]) + + def _flat(self, c): + Rc = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + return bool(np.max(np.abs(self.plank_R()[:, 2] @ Rc)) >= FLAT_COS) + + def on_mark(self, c, tol=TOL): + if not self.on_plank(c): + return False + o = self.mark_offset(c) + return bool(np.max(np.abs(o)) <= tol and self._flat(c) and not self.held(c)) + + def stage_values(self): + v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS} + v["plank_level"] = self.is_level() + v["plank_on_support"] = self.on_support() + return v + + # ------------------------------------------------------------ per-step monitor (server log only) + def _init_monitor(self): + self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"plank_level": True, "plank_on_support": True}, ever=set(), + lost=set(), events=[], step=0, last_touch={c: None for c in COLORS}, + held_prev={c: False for c in COLORS}, last_release=None, tipping=False, tips=[], + level_cnt=0, calm=0, tilt_max=0.0, win_max=0.0) + + def _robot_touches(self): + """cubes touched by the robot or by a cube the robot is carrying, in this control step""" + d = self.env.sim.data + out = set() + carried = [c for c in COLORS if self.mon["held_prev"][c]] + hit = {c: self.robot_gids.union(*[self.cube_gids[h] for h in carried if h != c]) for c in COLORS} + for i in range(d.ncon): + con = d.contact[i] + for c in COLORS: + g = self.cube_gids[c] + if (con.geom1 in g and con.geom2 in hit[c]) or (con.geom2 in g and con.geom1 in hit[c]): + out.add(c) + return out + + def monitor_step(self): + mon = self.mon + if mon is None or self.sk is None: + return + mon["step"] += 1 + step = self.sk.n_steps + for c in self._robot_touches(): + mon["last_touch"][c] = step + tilt = self.tilt_deg() + mon["tilt_max"] = max(mon["tilt_max"], abs(tilt)) + mon["win_max"] = max(mon["win_max"], abs(tilt)) + if not mon["tipping"] and abs(tilt) > TIP_DEG: + # one tip episode = from |tilt| > 8 deg until the plank has stayed level for 1 s (the swing back and any + # rocking belong to the same episode) + mon["tipping"] = True + mon["calm"] = 0 + rel = mon["last_release"] + tip = dict(step=step, down="near" if tilt < 0 else "far", + after_release=(rel[0] if rel is not None and step - rel[1] <= 60 else None), + on_plank=[c for c in COLORS if self.on_plank(c)], + on_mark=[c for c in COLORS if mon["state"][f"{c}_on_mark"]]) + mon["tips"].append(tip) + mon["events"].append(dict(step=step, pred="plank", ev="tipped", down=tip["down"], + after_release=tip["after_release"], on_mark=tip["on_mark"])) + elif mon["tipping"]: + mon["calm"] = mon["calm"] + 1 if abs(tilt) < LEVEL_DEG else 0 + if mon["calm"] >= 20: + mon["tipping"] = False + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + for c in COLORS: + h = self.held(c) + if mon["held_prev"][c] and not h: + mon["last_release"] = (c, step) + mon["held_prev"][c] = h + key = f"{c}_on_mark" + was = mon["state"][key] + now = self.on_mark(c, TOL if not was else TOL_LOSE) + if now != was: + self._event(key, now, step, c) + lv = self.is_level() + if lv != mon["state"]["plank_level"]: + mon["level_cnt"] += 1 + if mon["level_cnt"] >= LEVEL_DEBOUNCE: + mon["level_cnt"] = 0 + self._event("plank_level", lv, step, None) + else: + mon["level_cnt"] = 0 + sup = self.on_support() + if sup != mon["state"]["plank_on_support"]: + self._event("plank_on_support", sup, step, None) + + def _event(self, key, now, step, color): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + cause = "other" + recent_tip = bool(mon["tips"]) and (mon["tipping"] or step - mon["tips"][-1]["step"] <= 60) + if color is None: + cause = "tip" if recent_tip else "other" + elif self.held(color): + cause = "picked_up" + elif recent_tip: + cause = "tip" + elif mon["last_touch"][color] is not None and step - mon["last_touch"][color] <= 60: + cause = "robot" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause, tilt=round(self.tilt_deg(), 1))) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in [CUBES[c] for c in COLORS] + [PLANK]: + _, da = envs.free_joint_addr(self.env, name) + if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3: + return False + return True + + def _where(self, c): + """robot-centric description of where a cube that is not on its mark is""" + if self.held(c): + return "is still held by the gripper" + if self.on_plank(c): + o = self.mark_offset(c) + return f"lies on the plank, {_along(o[1])}" + p = self.cube_pos(c) + if np.linalg.norm(p[:2] - np.asarray(self.inst["start"][c])) < 0.02: + return "is still where it started on the table" + q = self.in_plank(p) + if abs(q[1]) > PL_HL: + return f"lies on the table beyond {END_WORD[_side(q[1])]} of the plank" + return "lies on the table beside the plank" + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [c for c in COLORS if self.held(c)] + success = bool(all(vals.values()) and static and not held) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + parts = [] + off = [c for c in COLORS if not vals[f"{c}_on_mark"]] + if success: + failure = None + parts.append("All four cubes are on their marks and the plank is level.") + else: + lost_final = [c for c in off if f"{c}_on_mark" in mon["ever"]] + failure = ("held" if held else "plank_off_support" if not vals["plank_on_support"] else + "regressed" if lost_final else "incomplete" if off else + "not_level" if not vals["plank_level"] else "not_static") + for c in off: + txt = f"The {c} cube is not on its mark: it {self._where(c)}" + if f"{c}_on_mark" in mon["ever"]: + why = [e for e in regress if e["pred"] == f"{c}_on_mark"] + cause = why[-1].get("cause") if why else None + txt += {"tip": " (it had been on its mark; it slid off when the plank tipped).", + "robot": " (it had been on its mark; the robot knocked it off).", + "picked_up": " (it had been on its mark; it was picked up again)."}.get( + cause, " (it had been on its mark earlier).") + else: + txt += " (it was never on its mark)." + parts.append(txt) + if not vals["plank_on_support"]: + parts.append("The plank no longer rests on the support block: it was pushed or knocked off it.") + if not vals["plank_level"]: + t = self.tilt_deg() + parts.append(f"The plank is not level: it is tilted {abs(t):.0f} degrees, " + f"{END_WORD['near' if t < 0 else 'far']} down.") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["tips"]: + descr = [] + for tp in mon["tips"]: + d = f"{END_WORD[tp['down']]} down" + if tp["after_release"]: + d += f" right after the {tp['after_release']} cube was set down" + descr.append(d) + parts.append(f"During the attempt the plank tipped {len(mon['tips'])} time(s): " + "; ".join(descr) + ".") + return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + n_tips=len(mon["tips"]), tips=mon["tips"], tilt_max=round(mon["tilt_max"], 1), + tilt_final=round(self.tilt_deg(), 1), hazard=bool(inst["hazard"]), + mark_offsets_cm={c: (100 * self.mark_offset(c)).round(1).tolist() for c in COLORS}, + on_plank={c: self.on_plank(c) for c in COLORS}, detail=" ".join(parts)) + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, c): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, CUBES[c])].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _y_on_plank(self): + """cubes resting on the plank now -> their position along it""" + return {c: float(self.in_plank(self.cube_pos(c))[1]) for c in COLORS if self.on_plank(c) and not self.held(c)} + + def plank_calm(self): + _, da = envs.free_joint_addr(self.env, PLANK) + return abs(self.tilt_deg()) < 1.0 and float(np.linalg.norm(self.env.sim.data.qvel[da + 3:da + 6])) < 0.05 + + def wait_calm(self, max_steps=60): + """hold the arm still until the plank has stopped swinging (a careful agent looks before it acts)""" + n = 0 + for _ in range(max_steps): + if self.plank_calm(): + n += 1 + if n >= 5: + return True + else: + n = 0 + self.sk.hold(1) + return False + + def pick(self, c, z_carry): + sk = self.sk + p = self.cube_pos(c) + yaw = self._grasp_yaw(c) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], max(TZ + z_carry, p[2] + 0.06)], yaw=yaw) + 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], TZ + z_carry], speed=0.3) + if not self.held(c): + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], TZ + z_carry]) + return False + return True + + def put(self, c, z_carry=Z_CARRY, noise=None, record=False, careful=False): + """Pick cube c wherever it is and put it on its mark: carry it over the mark, lower it until its bottom is + REL_GAP above the plank, release, lift. Returns whether the plank tipped (|tilt| > TIP_DEG) during the + placement, or None if the cube could not be picked. record=True appends the observation (cubes on the plank + right before the release + this one on its mark, tipped?) for the adaptive script.""" + for _ in range(2): + if self.pick(c, z_carry): + break + else: + return None + sk = self.sk + d = self.mark_world(c) + if noise is not None: + d = d + np.array([noise[0], noise[1], 0.0]) + sk.move_to([d[0], d[1], TZ + z_carry], yaw=0.0) + if careful: + self.wait_calm() + d = self.mark_world(c) + (np.array([noise[0], noise[1], 0.0]) if noise is not None else 0.0) + sk.move_to([d[0], d[1], d[2] + CUBE_E / 2 + REL_GAP], tol=0.003) + was_level = self.plank_calm() + conf = self._y_on_plank() + conf[c] = float(self.inst["marks"][c]) + self.mon["win_max"] = abs(self.tilt_deg()) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], TZ + z_carry]) + sk.hold(12) + tipped = self.mon["win_max"] > TIP_DEG + if tipped: + envs.settle(self.env, 30) # let the cubes slide down + if record and was_level: + self.obs.append(dict(conf=conf, tipped=bool(tipped), after=c)) + return tipped + + def park(self, c): + """take cube c off the plank and set it on a free spot of the table beside the plank""" + x0, y0 = self.inst["plank_xy"] + others = [self.cube_pos(o)[:2] for o in COLORS if o != c] + cands = [np.array([x0 + dx, y0 + sy * dy]) for sy in (1, -1) for dy in (0.18, 0.25) + for dx in (-0.12, -0.04, 0.04, 0.12)] + best = max(cands, key=lambda q: min(np.linalg.norm(q - o) for o in others)) + if not self.pick(c, Z_CARRY): + return False + sk = self.sk + sk.move_to([best[0], best[1], TZ + Z_CARRY], yaw=0.0) + sk.move_to([best[0], best[1], TZ + CUBE_E / 2 + 0.004], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([best[0], best[1], TZ + Z_CARRY]) + return True + + # ---- planning with the static model + def plan(self, todo, hyps): + """Best order to (re)place the cubes in `todo`, given the cubes now on the plank, minimising the worst tip ratio + over the mass hypotheses `hyps` (list of {colour: kg}). A cube that is on the plank off its mark is lifted + (its moment removed) and then set on its mark. Returns (order, worst ratio).""" + cur0 = self._y_on_plank() + best, best_w = list(todo), np.inf + for order in itertools.permutations(todo): + w = 0.0 + for mass in hyps: + cur = dict(cur0) + for c in order: + if c in cur: + del cur[c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + cur[c] = self.inst["marks"][c] + w = max(w, tip_ratio([(mass[o], y) for o, y in cur.items()])) + if w < best_w - 1e-9: + best, best_w = list(order), w + return best, best_w + + def hypotheses(self, use_obs=True): + """Heavy / light assignments (nominal masses) that (1) leave the finished layout balanced, (2) admit a loading + order that never tips the plank (the task is solvable) and (3) agree with every observed placement (tipped or + not, with a +-10 % band in which either outcome counts as consistent). Falls back to (1)+(2) if no assignment + agrees with all observations.""" + marks = self.inst["marks"] + prior = [] + for k in range(5): + for heavy in itertools.combinations(COLORS, k): + mass = {c: (H_EST if c in heavy else L_EST) for c in COLORS} + if tip_ratio([(mass[c], marks[c]) for c in COLORS]) > 0.6: + continue + for order in itertools.permutations(COLORS): + cur, w = [], 0.0 + for c in order: + cur.append((mass[c], marks[c])) + w = max(w, tip_ratio(cur)) + if w <= 0.9: + prior.append(mass) + break + if not use_obs: + return prior + post = [] + for mass in prior: + if all(not ((ob["tipped"] and r < 0.9) or (not ob["tipped"] and r > 1.1)) + for ob in self.obs for r in [tip_ratio([(mass[o], y) for o, y in ob["conf"].items()])]): + post.append(mass) + return post or prior + + def unload_until_level(self, max_moves=4): + """while the plank is tipped: take the cube farthest out on its low side off the plank""" + for _ in range(max_moves): + envs.settle(self.env, 20) + self.wait_calm() + if self.is_level(): + return True + t = self.tilt_deg() + yo = self._y_on_plank() + low = [c for c, y in yo.items() if (y > 0) == (t < 0)] + if not low: + return self.is_level() + self.park(min(low, key=lambda o: abs(yo[o]))) # the top of the pile first: the hand clears the others + envs.settle(self.env, 20) + self.wait_calm() + return self.is_level() + + def restore(self, hyps_fn, rounds=3, record=False): + """Check every stage; if something is wrong: unload the low end if the plank is tipped, then (re)place every + cube that is not on its mark in the order the static model rates safest under the current mass hypotheses; + start over after a tip. Up to `rounds` passes.""" + for _ in range(rounds): + envs.settle(self.env, 20) + if all(self.stage_values().values()): + return True + self.unload_until_level() + todo = [c for c in COLORS if not self.on_mark(c)] + if not todo: + continue + hyps = hyps_fn() + order, worst = self.plan(todo, hyps) + if worst > 0.9: # cubes left on the plank make every order risky: clear it and start from empty + for c in [c for c in COLORS if self.on_plank(c)]: + self.park(c) + order, worst = self.plan(list(COLORS), hyps) + for c in order: + if self.on_mark(c): + continue + if self.put(c, Z_CARRY, record=record, careful=True): + break # tipped: look again + envs.settle(self.env, 20) + return all(self.stage_values().values()) + + def naive_order(self, noise_sd=0.0, rng=None): + """nearest cube first, starting from the gripper's position and then from each mark just loaded""" + p = self.sk.eef_pos()[:2] + left, order = list(COLORS), [] + while left: + dist = {c: np.linalg.norm(self.cube_pos(c)[:2] - p) + (rng.normal(0, noise_sd) if rng is not None else 0.0) + for c in left} + c = min(left, key=dist.get) + order.append(c) + left.remove(c) + p = self.mark_world(c)[:2] + return order + + def slot_order(self, kind): + so = {s: c for c, s in self.inst["slot_of"].items()} + seq = dict(end2end=SLOTS, alt_outer=("near_outer", "far_outer", "near_inner", "far_inner"), + alt_inner=("near_inner", "far_inner", "near_outer", "far_outer"))[kind] + return [so[s] for s in seq] + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("seed", 0)) + mode = params["mode"] + if mode == "plan": + hyps = [dict(inst["mass"])] if params.get("true_masses") else self.hypotheses() + order, _ = self.plan(list(COLORS), hyps) + elif mode in ("end2end", "alt_outer", "alt_inner"): + order = self.slot_order(mode) + else: # nearest first (naive / blind) + order = self.naive_order(params.get("order_noise", 0.0), rng) + noise = params.get("noise", 0.0) + z_carry = Z_CARRY if params.get("careful") else Z_CARRY_NAIVE + for c in order: + nz = rng.uniform(-noise, noise, 2) if noise else None + tipped = self.put(c, z_carry, noise=nz, record=params.get("record", False), careful=params.get("careful", False)) + if tipped and params.get("check_each"): + break # look at what happened, then restore below + if params.get("check"): + hyps_fn = (lambda: [dict(inst["mass"])]) if params.get("true_masses") else self.hypotheses + self.restore(hyps_fn, record=params.get("record", False)) + self.sk.hold(10) + return order + + def default_params(self, inst): + return dict(mode="nearest", check=False) + + def oracle_params(self, inst): + return dict(mode="plan", true_masses=True, careful=True, check=True) + + def adapt_params(self, inst, history): + """from attempt 2: load in the order the observations of earlier attempts make safest, check after every + placement and restore at the end""" + return dict(mode="plan", careful=True, check=True, check_each=True, record=True) + + def blind_params(self, inst, attempt, rng): + """nearest-first again with small random variation (order noise, 4 mm placement noise), no history, no check""" + return dict(mode="nearest", check=False, order_noise=0.03, noise=0.004, seed=int(rng.integers(1 << 30))) + + 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 = [] + self.obs = [] + 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": # attempt 1: natural order, but look after every placement and restore + params = (dict(mode="nearest", check=True, check_each=True, record=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 in ("end2end", "alt_outer", "alt_inner"): # extra controls: other natural orders, no check + params = dict(mode=kind, check=False) + elif kind == "oracle_noise": # extra control: the oracle with +-5 mm (uniform) placement noise + params = dict(self.oracle_params(inst), noise=0.005, seed=int(rng.integers(1 << 30))) + elif kind == "switch": # extra control: no in-attempt repair, learn the order across attempts only + params = (dict(mode="nearest", check=False, record=True) if a == 0 else + dict(mode="plan", careful=True, check=False, record=True)) + else: + raise ValueError(kind) + order = self.execute(inst, params) + out = self.outcome(inst) + out["order"] = order + 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", "oracle_noise", "naive", "end2end", "alt_outer", "alt_inner"): + break + return history diff --git a/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bridge.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..b10b75576304ed46284ba5002c7857fc458d3669 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/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/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_nudge_row.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_nudge_row.py new file mode 100644 index 0000000000000000000000000000000000000000..e681fb7e676fcda50cc393a648311f31083de9f9 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_gpt/lff/source_closure/lffbench/tasks/lh_nudge_row.py @@ -0,0 +1,821 @@ +"""LH lh_nudge_row v2 (2026-10-14): stand four small cups, one by one, on the four coloured mats of their colours; the +mats lie in two rows of two, and in 7 of 10 instances the two mats of a row touch. Letting go of a cup with the fingers +opening towards the cup already standing on the next mat pushes that cup 1.5-3.4 cm sideways, half off its mat -- it +stays upright, so the damage is small but visible (a near miss that has to be noticed and undone before finishing). + +Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically undo an +earlier one; the agent has to look back at all cups before finishing (within an attempt) or learn to let go without +pushing (across attempts). + +v1 -> v2 (Sonnet 5.5 pilot np_lh_nudge_row, seeds 3000-3002, k=3, measured): v1 used round rings with a 0.8 cm +tolerance. Sonnet put the cups 0.8-2.2 cm too far forward (+x, away from the robot) in almost every attempt and could not +see it (the oblique agentview camera looks along x; a tall cup hides the ring behind it), so 5 of 7 attempts failed +without any nudge (one was a calibration attempt), and the one clear nudge (s3000) left the cup 0.83 cm off -- +invisible. Its left-right errors were <= 0.7 cm, its releases in attempt 1 almost all at wrist yaw ~0 (fingers opening +left-right), and it learned yaw 45 for the last cup after the nudge. v2 therefore (1) replaces the rings by mats 9 cm long (forward-back, tolerance 3 cm: a 2 cm forward bias +passes) and 4.6 cm wide (left-right, tolerance 1.3 cm), (2) puts the two mats of a row edge to edge so that a yaw-0 +release pushes the neighbour sideways, where the camera resolves it, off its mat onto the table, and (3) uses slimmer cups +(2 x 5 cm instead of 4 x 6 cm): the open finger reaches farther past them, so the push is 1.5-3.4 cm instead of 0.3-2.3. +Code and results of v1: lh_nudge_row.py.bak-20261014-v1, results/_old/lh_nudge_row_v1/. + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * four coloured mats (dark red, blue, green, ochre; flat, visual only), each 9.0 cm (forward-back) x 4.6 cm, in two rows + (far and near, 1.5 cm apart); block centre 53-59 cm in front of the robot base. Tight block (14 of every 20 + consecutive seeds): the two mats of a row touch. Spaced block (6 of 20): they are 4-5 cm apart and no open finger + reaches the neighbour (the benign instances); + * four slim cups of the bright same colours (2.0 cm wide, 5.0 cm tall, open top, glazed base: friction 0.08-0.12, + 20-32 g), standing in a line 17.5-19 cm from the block on the robot's side, or on its left or right side, in random + order and 9-10 cm apart. + +Risk factor: the block's spacing (visible, instance level); there is no hidden physical variable (v1 measured that a +rubber-footed cup gets tipped over by a re-grasp next to it, and a fallen cup cannot be stood up again). + +Disturbance (physics, no teleport): the gripper opens to 7.9 cm, i.e. each finger moves 3 cm out from a 2 cm cup; the +outer face of an open finger reaches 5.4 cm (tip) to 6.6 cm (upper part) from the grasp point; in a tight block the +neighbour's wall is 3.6 cm away (+- the placement errors). Measured: letting go with the fingers along the row (wrist yaw +0) pushes the neighbour 1.2-3.2 cm sideways, upright (18/18 trials: base friction 0.08 / 0.12 x grasp 0.8-2 cm below the +rim x put down 0.8 cm towards / on target / 0.8 cm away from it, each followed by three re-grasps); re-grasping a placed cup with the fingers towards the neighbour pushes it about 0.3 cm more. With +friction 0.18 or with 2.6 cm cups whose closed finger already presses the neighbour's rim, slim cups tipped over (4/18 +and 6/18) -- hence the low friction and the 2 cm cups. A careful agent avoids the push by letting go with the fingers +opening forward-back (wrist yaw 90: the mats of the other row are 10.5 cm away) or diagonally, and repairs it by +re-centring the pushed cup (lifted 10 cm, carried back, let go the same careful way). + +Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each cup stands upright +(tilt <= 10 deg) on the table, not held, with its whole base on its own mat: centre within 3.0 cm (forward-back) and +1.3 cm (left-right) of the mat's centre. Success = all four at the end, gripper open and not touching any cup, scene +static. The monitor logs achieved / lost / restored per cup, cup_nudged (lost while not held, with displacement and +cause), cup_bumped (pushed by the robot but still on its mat) and cup_restored, 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"] +CUPS = [f"cup_{c}_1" for c in COLOURS] +MATS = [f"mat_{c}_1" for c in COLOURS] +RGBA = {"red": (0.82, 0.16, 0.13, 1.0), "blue": (0.16, 0.36, 0.82, 1.0), "green": (0.16, 0.62, 0.26, 1.0), + "yellow": (0.92, 0.76, 0.12, 1.0)} +MAT_RGBA = {"red": (0.55, 0.13, 0.12, 1.0), "blue": (0.12, 0.22, 0.52, 1.0), "green": (0.10, 0.38, 0.16, 1.0), + "yellow": (0.62, 0.50, 0.08, 1.0)} # dark shades: crisp edges on the light table, bright cups stand out +INSIDE_RGBA = (0.93, 0.92, 0.88, 1.0) # glazed inside of the cups (seen from above) + +# cup geometry (fixed; only mass and base friction change per instance, so no runtime geom edits / BVH refits) +CUP_R, CUP_H = 0.010, 0.050 # slim cups (2 x 5 cm): the open fingers reach far past them (v1: 4 x 6 cm) +COM_Z = -0.006 # centre of mass below the cup's mid-height (heavier base) +WALL_T, BASE_T = 0.0025, 0.003 +NSEG = 12 +CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"' +WALL_MU = 0.8 +BASE_MU = (0.08, 0.12) # glazed base: a pushed cup slides; at 0.18 a slim cup pushed high up tipped (measured) +MASS = (0.020, 0.032) + +# mats (targets) and block +TOL_X = 0.030 # forward-back: the cup centre may be 3 cm from the mat centre (mat 9 cm long) -- Sonnet's measured +# placement bias is 1-2.5 cm forward (v1 pilot), invisible to it in the oblique camera +TOL_Y = 0.013 # left-right: 1.3 cm (mat 4.6 cm wide); a finger-opening push (1.2-3.2 cm, measured) fails it +MAT_L, MAT_W = 2 * (CUP_R + TOL_X), 2 * (CUP_R + TOL_Y) # base completely on the mat <=> centre within the tolerances +ROW_GAP = 0.015 # gap between the far row and the near row of mats (x) +SPACED_GAP = (0.040, 0.050) # spaced block: gap between the two mats of a row (y); an open finger cannot reach +P_TIGHT = 0.70 # 14 of every 20 consecutive seeds: the two mats of a row touch +BLOCK_X = (-0.13, -0.07) # block centre in world x (53-59 cm in front of the robot base) +SUP_D = (0.175, 0.19) # supply line distance from the block centre +SUP_GAP = (0.090, 0.100) + +# predicates / monitor +TILT_OK = np.radians(10.0) +ON_TABLE = 0.004 +HYST = 0.002 +DEBOUNCE = 10 # control steps (0.5 s) +BUMP_MIN = 0.003 + +# scripted motion (heights of the grasp point above the table) +Z_CARRY = 0.20 # Sonnet: lifts to ~20 cm before moving (lh2/lh3 pilots) +Z_LIFT = 0.15 # re-placing a cup that is already down: lift it this high (its base 11 cm up) before moving it +NAIVE_BIAS = (0.008, 0.022) # Sonnet's systematic forward placement error (v1 pilot: +0.8 ... +2.2 cm, per instance) +NAIVE_RAND = 0.006 # +- random placement error per axis (v1 pilot: left-right errors <= 0.7 cm) +NAIVE_FIX_RAND = 0.003 # after re-placing its own cup +FINGER_IN, FINGER_OUT, FINGER_HALF = 0.039, 0.066, 0.013 # open finger footprint (m from the grasp point / half width) + + +def _wrap_h(a): + """wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def cup_xml(name, rgba): + """open-top cup: 12 wall boxes (1 mm above the bottom) and an octagonal base of two square boxes (box-box contacts: + a light cylinder on the table creeps by itself in MuJoCo, measured 1.6 cm / 5 s). Visual: a smooth cylinder with the + glazed inside at the top. The compiled inertial is replaced per instance (mass), the base friction too.""" + r, h = CUP_R, CUP_H + g = [f' '] + s = r * np.sin(np.pi / NSEG) + 0.0006 + rc = r * np.cos(np.pi / NSEG) - WALL_T / 2 + for k in range(NSEG): + a = 2 * np.pi * k / NSEG + q = [np.cos(a / 2), 0, 0, np.sin(a / 2)] + g.append(f' ') + a0 = r * 0.70 + for k, ang in enumerate((0.0, np.pi / 4)): + q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)] + g.append(f' ') + g.append(f' ') + g.append(f' ') + return _wrap(name, "\n".join(g), h / 2, r) + + +def mat_xml(name, rgba): + """flat coloured mat (visual only), long side along body x""" + g = (f' ') + return _wrap(name, g, 0.0004, float(np.hypot(MAT_L, MAT_W) / 2)) + + +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'}" + + +class NudgeSkills(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 NudgeRow(LFFTask): + name = "lh_nudge_row" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Restore") + protocol = "cross" + max_attempts = 3 + # careful: ~10 commands per cup (40) + re-placing an imprecise cup or two (~15) + re-centring two pushed cups (~20) + # + looking / small corrections (~20), with some margin + agent_max_steps = 110 + instruction = ("Stand each of the four small cups on the mat of the same colour. The four coloured mats lie on the " + "table in two rows of two. At the end every cup must stand upright with its whole base on its own " + "mat (not touching another mat or the table around it), and the gripper must be open and clear of " + "the cups.") + instruction_indirect = ("Set each little cup down on the coloured patch that matches it; the four patches form two " + "rows of two. When you are done every cup has to stand upright with its bottom completely " + "on its own patch, and the gripper must be open and away from the cups.") + agent_object_names = ["small cups (red, blue, green, yellow)", + "coloured mats (red, blue, green, yellow) in two rows of two"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for i, (c, cup) in enumerate(zip(COLOURS, CUPS)): + cat = register_generated(f"LffLhnCup{c.capitalize()}", cup_xml(f"lff_lhn_cup_{c}", RGBA[c])) + objs.append((cup, cat, f"cup{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31))) + for i, (c, mat) in enumerate(zip(COLOURS, MATS)): + cat = register_generated(f"LffLhnMat{c.capitalize()}", mat_xml(f"lff_lhn_mat_{c}", MAT_RGBA[c]), free=False) + fx.append((mat, cat, f"mat{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30))) + return write_bddl(self.name, "Stand each cup on the mat of its colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.mat_bid = {k: m.body_name2id(self.env.fixtures_dict[k].root_body) for k in MATS} + self.cgeoms = {c: envs.obj_geom_ids(self.env, c) for c in CUPS} + self.cbody = {c: int(m.geom_bodyid[self.cgeoms[c][0]]) for c in CUPS} + self.base_geoms = {c: [g for g in self.cgeoms[c] if (m.geom_id2name(g) or "").split("_")[-1] in ("b0", "b1")] + for c in CUPS} + self.finger_geoms, self.hand_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).append(g) + # per-geom lookup tables for the substep contact check: cup index (-1 none), robot part (1 finger, 2 hand) + self.owner = np.full(m.ngeom, -1, int) + for i, c in enumerate(CUPS): + self.owner[self.cgeoms[c]] = i + self.part = np.zeros(m.ngeom, int) + self.part[self.finger_geoms] = 1 + self.part[self.hand_geoms] = 2 + self._sub_rob, self._sub_obj = {}, {} + # contacts are collected after every MuJoCo substep: an opening finger can flick a light cup within one control + # step (same technique as lh_fence; wrappers chain) + sim = self.env.sim + if not getattr(sim, "_lhn_wrapped", False): + orig = sim.step + + def step(*a, **k): + orig(*a, **k) + t = getattr(sim, "_lhn_task", None) + if t is not None and t.mon is not None: + t._substep() + sim.step = step + sim._lhn_wrapped = True + sim._lhn_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) + tight = bool((int(seed) * 7) % 20 < round(20 * P_TIGHT)) # balanced: 14 of every 20 consecutive seeds + gap_y = 0.0 if tight else float(rng.uniform(*SPACED_GAP)) + py = MAT_W + gap_y # mat centre to mat centre within a row (left-right) + px = MAT_L + ROW_GAP # far row to near row (forward-back) + bx = float(rng.uniform(*BLOCK_X)) + side = str(rng.choice(["front", "left", "right"])) + by = float(rng.uniform(-0.04, 0.04)) + if side == "left": + by = float(rng.uniform(-0.08, -0.04)) + elif side == "right": + by = float(rng.uniform(0.04, 0.08)) + # mat positions: block slots (far-left, far-right, near-left, near-right), colours permuted + slots = {"far_left": [bx + px / 2, by + py / 2], "far_right": [bx + px / 2, by - py / 2], + "near_left": [bx - px / 2, by + py / 2], "near_right": [bx - px / 2, by - py / 2]} + names = list(slots) + perm = rng.permutation(4) + mats = {COLOURS[i]: slots[names[perm[i]]] for i in range(4)} + slot_of = {COLOURS[i]: names[perm[i]] for i in range(4)} + # supply line + d = float(rng.uniform(*SUP_D)) + gap = float(rng.uniform(*SUP_GAP)) + offs = (np.arange(4) - 1.5) * gap + float(rng.uniform(-0.02, 0.02)) + if side == "front": + sup = [[bx - d + float(rng.uniform(-0.008, 0.008)), by + o] for o in offs] + else: + sgn = 1.0 if side == "left" else -1.0 + sup = [[bx + o, by + sgn * (d - 0.02) + float(rng.uniform(-0.008, 0.008))] for o in offs] + order = rng.permutation(4) + start = {COLOURS[i]: [float(v) for v in sup[order[i]]] for i in range(4)} + mu = {c: float(rng.uniform(*BASE_MU)) for c in COLOURS} + mass = {c: float(rng.uniform(*MASS)) for c in COLOURS} + yaw0 = {c: float(rng.uniform(-np.pi, np.pi)) for c in COLOURS} + return dict(seed=int(seed), pitch_y=py, pitch_x=px, gap_y=gap_y, block=[bx, by], supply_side=side, + supply_d=d, supply_gap=gap, mats=mats, slot_of=slot_of, start=start, mu=mu, mass=mass, yaw0=yaw0, + tight=tight, block_kind="tight" if tight else "spaced", + naive_bias_x=float(rng.uniform(*NAIVE_BIAS))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c, cup in zip(COLOURS, CUPS): + b = self.cbody[cup] + M = inst["mass"][c] + m.body_mass[b] = M + # thin-walled cup (wall + base), approximately + m.body_inertia[b] = [M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), + M * CUP_R ** 2 * 0.8] + for g in self.base_geoms[cup]: + m.geom_friction[g] = [inst["mu"][c], 0.005, 0.0001] + m.geom_priority[g] = 2 + for c, mat in zip(COLOURS, MATS): + x, y = inst["mats"][c] + m.body_pos[self.mat_bid[mat]] = [x, y, TZ + 0.0005] + m.body_quat[self.mat_bid[mat]] = [1.0, 0.0, 0.0, 0.0] + self.env.sim.forward() + for c, cup in zip(COLOURS, CUPS): + envs.place_upright(self.env, cup, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005) + + 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 = NudgeSkills(self.env, self, recorder=recorder) + self._sub_rob, self._sub_obj = {}, {} + n = len(CUPS) + self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[], + lost_cause=[None] * n, + anchor=[None] * n, last_robot=[None] * n, last_obj=[None] * n, nudged=[False] * n, + bump_ref=[None] * n, bump_step=[-1000] * n, n_steps=0) + return self.sk + + # ------------------------------------------------------------ geometry / predicates + def pos(self, cup): + return envs.obj_pos(self.env, cup) + + def tilt(self, cup): + return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, cup), -1.0, 1.0))) + + def held(self, cup): + return self.sk is not None and self.sk.holding(cup) + + def mat_xy(self, i): + return np.asarray(self.inst["mats"][COLOURS[i]], float) + + def offset(self, i): + return self.pos(CUPS[i])[:2] - self.mat_xy(i) + + @staticmethod + def within(off, extra=0.0): + """mat-frame offset (x forward-back, y left-right) inside the tolerances = the cup's whole base on its mat""" + return abs(float(off[0])) <= TOL_X + extra and abs(float(off[1])) <= TOL_Y + extra + + def on_mat(self, i, extra=0.0): + cup = CUPS[i] + if self.tilt(cup) > TILT_OK + (np.radians(2.0) if extra else 0.0): + return False + if not self.within(self.offset(i), extra): + return False + if envs.obj_min_z(self.env, cup) > TZ + ON_TABLE: + return False + return not self.held(cup) + + def stages(self): + return [self.on_mat(i) for i in range(len(CUPS))] + + # ------------------------------------------------------------ monitor + 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 = dict(self._sub_rob) + obj = dict(self._sub_obj) + self._sub_rob, self._sub_obj = {}, {} + gstate = "open" if self.sk.grip < 0 else "closed" + for i, part in rob.items(): + if not self.held(CUPS[i]): + mon["last_robot"][i] = ["finger" if part == 1 else "hand", int(t), gstate] + for i, j in obj.items(): + mon["last_obj"][i] = [COLOURS[j] + (" (held)" if self.held(CUPS[j]) else ""), int(t)] + if mon["n_steps"] % 2: + return + for i in range(len(CUPS)): + cup = CUPS[i] + raw = self.on_mat(i, HYST if mon["state"][i] else 0.0) + # bumps inside the tolerance + if mon["state"][i] and raw and not self.held(cup): + lr = mon["last_robot"][i] + if lr is not None and t - lr[1] <= 2 and mon["bump_ref"][i] is None: + mon["bump_ref"][i] = [self.pos(cup)[:2].tolist(), int(t), 0.0] + ref = mon["bump_ref"][i] + if ref is not None: + ref[2] = max(ref[2], float(np.degrees(self.tilt(cup)))) + if t - ref[1] > 40: + dpos = float(np.linalg.norm(self.pos(cup)[:2] - np.asarray(mon["anchor"][i] or ref[0]))) + if (dpos >= BUMP_MIN or ref[2] >= 2.0) and t - mon["bump_step"][i] > 60: + mon["events"].append(dict(cup=COLOURS[i], event="cup_bumped", step=int(ref[1]), + moved_cm=round(100 * dpos, 2), max_tilt_deg=round(ref[2], 1), + cause=self._cause(i, ref[1] + 1))) + mon["bump_step"][i] = int(t) + mon["bump_ref"][i] = None + 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] # picked_up = the agent re-adjusted a cup it had placed itself + mon["events"].append(e) + if restored and mon["nudged"][i]: + mon["events"].append(dict(cup=COLOURS[i], event="cup_restored", step=t0)) + mon["nudged"][i] = False + mon["ever"][i] = True + mon["anchor"][i] = self.pos(cup)[:2].tolist() + mon["bump_ref"][i] = None + else: + mon["lost"][i] = True + cause = self._cause(i, t) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause)) + if cause != "picked_up": + a = mon["anchor"][i] + d = self.pos(cup)[:2] - np.asarray(a if a is not None else self.mat_xy(i)) + off = self.offset(i) + mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t0, cause=cause, + moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)], + offset_cm=round(100 * float(np.linalg.norm(off)), 2), + tilt_deg=round(float(np.degrees(self.tilt(cup))), 1))) + mon["nudged"][i] = True + + def _cause(self, i, t, window=60): + if self.held(CUPS[i]): + return "picked_up" + lr, lo = self.mon["last_robot"][i], self.mon["last_obj"][i] + cands = [] + if lr is not None and t - lr[1] <= window: + cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else ""))) + if lo is not None and t - lo[1] <= window: + cands.append((lo[1] - 30, "cup:" + lo[0])) # prefer the robot when both touched it recently + return max(cands)[1] if cands else "other" + + def _finalize_monitor(self, raw): + """close the event log at finish: a stage the debounced monitor still holds (it uses a 2 mm hysteresis) but the + final judge does not is logged as lost now (final=True), and vice versa""" + mon = self.mon + if mon is None: + return + t = int(self.sk.n_steps) + for i in range(len(CUPS)): + 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 + continue + mon["lost"][i] = True + cause = self._cause(i, t, window=10 ** 6) # the last contact may be long ago (slow creep across the line) + mon["lost_cause"][i] = cause + mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True)) + if cause != "picked_up": + a = mon["anchor"][i] + d = self.pos(CUPS[i])[:2] - np.asarray(a if a is not None else self.mat_xy(i)) + mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t, cause=cause, final=True, + moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)], + offset_cm=round(100 * float(np.linalg.norm(self.offset(i))), 2), + tilt_deg=round(float(np.degrees(self.tilt(CUPS[i]))), 1))) + mon["nudged"][i] = True + + # ------------------------------------------------------------ outcome + def _touching(self): + d = self.env.sim.data + rob = set(self.finger_geoms) | set(self.hand_geoms) + for j in range(d.ncon): + c = d.contact[j] + if (self.owner[c.geom1] >= 0 and c.geom2 in rob) or (self.owner[c.geom2] >= 0 and c.geom1 in rob): + return True + return False + + def outcome(self, inst): + sk = self.sk + sk.hold(10) + p0 = {c: self.pos(c) for c in CUPS} + touching = False + for _ in range(20): + sk.hold(1) + touching = touching or self._touching() + moved = max(float(np.linalg.norm(self.pos(c) - p0[c])) for c in CUPS) + static = moved < 0.003 + raw = self.stages() + self._finalize_monitor(raw) + held = [COLOURS[i] for i, c in enumerate(CUPS) if self.held(c)] + mon = self.mon + ev = list(mon["events"]) if mon else [] + 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) + nudges = [e for e in ev if e.get("event") == "cup_nudged"] + bumps = [e for e in ev if e.get("event") == "cup_bumped"] + success = bool(all(raw) and static and not held and not touching) + ever = mon["ever"] if mon else [False] * len(CUPS) + tilted = [i for i in range(len(CUPS)) if self.tilt(CUPS[i]) > TILT_OK] + lost_final = [i for i in range(len(CUPS)) if not raw[i] and ever[i]] + never = [i for i in range(len(CUPS)) if not raw[i] and not ever[i]] + if success: + failure = "none" + elif held: + failure = "held" + elif touching: + failure = "touching" + elif tilted: + failure = "tipped" + elif lost_final: + failure = "nudged_out" if any(mon["nudged"][i] for i in lost_final) else "regressed" + elif never: + failure = "not_on_mat" + else: + failure = "not_static" + parts = [] + if success: + parts.append("Every cup stands upright on the mat of its colour.") + for i in range(len(CUPS)): + if raw[i]: + continue + c, cup = COLOURS[i], CUPS[i] + if c in held: + parts.append(f"The {c} cup is still held by the gripper.") + continue + off = self.offset(i) + tl = np.degrees(self.tilt(cup)) + where = f"{_fb(off[0])} and {_lr(off[1])} of the {c} mat's centre" + if tl > np.degrees(TILT_OK): + txt = (f"The {c} cup has fallen over" if tl > 45 else f"The {c} cup leans {tl:.0f} degrees") + f", {where}." + elif float(np.linalg.norm(off)) > 0.08: + txt = f"The {c} cup is not on the {c} mat (its centre is {100 * float(np.linalg.norm(off)):.0f} cm away)." + else: + over = [] + if abs(off[1]) > TOL_Y: + over.append(f"{100 * (abs(off[1]) - TOL_Y):.1f} cm over the mat's {'left' if off[1] > 0 else 'right'} " + f"edge") + if abs(off[0]) > TOL_X: + over.append(f"{100 * (abs(off[0]) - TOL_X):.1f} cm over its {'far' if off[0] > 0 else 'near'} end") + txt = f"The {c} cup stands {where}; its base sticks out " + " and ".join(over) + "." + if ever[i]: + lost = [e for e in ev if e.get("stage") == c and e.get("event") == "lost"] + why = lost[-1].get("cause", "other") if lost else "other" + txt += {"robot_finger_opening": " It had stood on its mat; a finger pushed it when the gripper opened " + "next to it.", + "robot_finger": " It had stood on its mat; a finger pushed it.", + "robot_hand": " It had stood on its mat; the hand pushed it.", + }.get(why, " It had stood on its mat earlier and was pushed by another cup." + if why.startswith("cup:") else " It had stood on its mat earlier.") + parts.append(txt) + if not success and all(raw): + if touching: + parts.append("The gripper is still touching a cup.") + elif not static: + parts.append("Something was still moving.") + if nudges: + parts.append(f"During the attempt cups that stood on their mats were pushed off {len(nudges)} time(s); " + f"{n_res} time(s) a cup was put back.") + trap = bool(nudges) + return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(CUPS))}, events=ev, + n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_nudged=len(nudges), + n_bumped=len(bumps), trap_fired=trap, recovered_in_attempt=bool(trap and success), + nudged_cups=sorted({e["cup"] for e in nudges}), failure=failure, held=held, + touching=bool(touching), static=bool(static), + offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)] for i in range(4)}, + tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(CUPS[i]))), 1) for i in range(4)}, + tight=bool(inst["tight"]), 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 _lift_to(self, z, speed=0.15): + cur = self.sk.eef_pos() + if cur[2] < TZ + z - 0.005: + self._go([cur[0], cur[1], TZ + z], speed=speed) + + def finger_clear(self, q, yaw, ignore=()): + """smallest distance (m) between the open fingers at grasp point q (xy) with gripper yaw `yaw` and the wall of + any standing cup other than `ignore`; finger axis (-sin yaw, cos yaw)""" + a = np.array([-np.sin(yaw), np.cos(yaw)]) + b = np.array([a[1], -a[0]]) + best = 1.0 + for cup in CUPS: + if cup in ignore or self.held(cup): + continue + rel = self.pos(cup)[:2] - np.asarray(q, float) + for s in (1.0, -1.0): + u = s * float(rel @ a) + v = float(rel @ b) + du = max(FINGER_IN - u, 0.0, u - FINGER_OUT) + dv = max(abs(v) - FINGER_HALF, 0.0) + best = min(best, float(np.hypot(du, dv)) - CUP_R) + return best + + def safe_yaw(self, q, ignore=(), prefer=0.0): + """the gripper yaw (0, 90, +-45 deg) whose open fingers stay farthest from the other cups at q""" + cands = [0.0, np.pi / 2, np.pi / 4, -np.pi / 4] + sc = [(round(min(self.finger_clear(q, y, ignore), 0.02), 3), -abs(_wrap_h(y - prefer)), y) for y in cands] + return max(sc)[2] + + def grasp_cup(self, cup, yaw, depth, z_carry=Z_CARRY, v=0.2, err=None, lift=None): + """open, go over the cup at transit height, straight down, close, lift. Returns True if held.""" + sk = self.sk + p = self.pos(cup) + q = p[:2] + (np.asarray(err, float) if err is not None else 0.0) + zg = envs.obj_max_z(self.env, cup) - depth + sk.set_gripper(False, steps=8) + self._lift_to(z_carry) + self._go([q[0], q[1], max(sk.eef_pos()[2], TZ + z_carry)], yaw=yaw, speed=v) + self._go([q[0], q[1], zg + 0.015], speed=0.10) + self._go([q[0], q[1], zg], speed=0.04, tol=0.003, max_steps=150) + sk.set_gripper(True, steps=15) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.12) + sk.hold(5) + if not self.held(cup): + sk.set_gripper(False, steps=8) + return False + return True + + def put_cup(self, cup, xy, yaw, z_carry=Z_CARRY, v=0.2, lift=None): + """carry the held cup so that the cup (not the grasp point) is over xy, rotate to `yaw`, straight down until its + base is 3 mm above the table, let go, lift""" + sk = self.sk + rel = self.pos(cup)[:2] - sk.eef_pos()[:2] + q = np.asarray(xy, float) - rel + cur = sk.eef_pos() + self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v) + sk.hold(5) + rel = self.pos(cup)[:2] - sk.eef_pos()[:2] # the cup can shift in the fingers while the wrist turns + q = np.asarray(xy, float) - rel + dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, cup) + zr = TZ + dz + 0.003 + self._go([q[0], q[1], zr + 0.015], speed=0.10) + self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150) + sk.set_gripper(False, steps=12) + cur = sk.eef_pos() + self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.15) + sk.hold(3) + + def mat_order(self, mode="far_first"): + """colour indices in placement order. far_first (Sonnet): the block row farthest from the supply first, then + the other; within a row from the left (robot's view)""" + sup = np.mean([self.inst["start"][c] for c in COLOURS], axis=0) + blk = np.asarray(self.inst["block"], float) + u = blk - sup + u = u / max(np.linalg.norm(u), 1e-9) + idx = list(range(4)) + far = sorted(idx, key=lambda i: -float((self.mat_xy(i) - blk) @ u)) + rows = [far[:2], far[2:]] + if mode == "near_first": + rows = rows[::-1] + out = [] + for row in rows: + out += sorted(row, key=lambda i: (-self.mat_xy(i)[1], self.mat_xy(i)[0])) # left first + return out + + @staticmethod + def looks_off(off, bias): + """a (biased) observer's verdict: the cup looks off its mat centre by more than 0.8 cm in some direction""" + p = np.asarray(off, float) - np.asarray(bias, float) + return abs(p[0]) > 0.008 or abs(p[1]) > 0.008 + + def place_one(self, i, yaw_rule, depth, rng, bias=(0.0, 0.0), rand=0.0, fix_rand=0.0, check=True, z_carry=Z_CARRY, + v=0.2): + """one stage: pick cup i from wherever it is and put it on its mat; aims at mat + bias (+- rand per axis); then + looks at this cup only (with the same bias) and re-places it if it looks off""" + cup = CUPS[i] + bias = np.asarray(bias, float) + for _ in range(2): + gy = yaw_rule(i, "grasp") + gerr = rng.uniform(-0.003, 0.003, 2) if rand else None + if self.grasp_cup(cup, gy, depth, z_carry=z_carry, v=v, err=gerr): + break + else: + return + e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2) + self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=z_carry, v=v) + if not check: + return + for _ in range(2): + if not self.looks_off(self.offset(i), bias) and self.tilt(cup) < TILT_OK: + return + ry = yaw_rule(i, "grasp") + if not self.grasp_cup(cup, ry, depth, z_carry=Z_LIFT, v=0.1, lift=Z_LIFT): + return + e = rng.uniform(-fix_rand, fix_rand, 2) if fix_rand else np.zeros(2) + self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=Z_LIFT, v=0.1, lift=z_carry) + + def repair(self, rounds=4, depth=0.020, bias=(0.0, 0.0)): + """look at every cup (with the observer's bias); re-centre each one that looks off: grasp and let go with the + fingers opening where no other cup stands. Returns the number of cups moved.""" + bias = np.asarray(bias, float) + moved = 0 + tries = {} + for _ in range(rounds * 4): + bad = [i for i in range(4) if (self.looks_off(self.offset(i), bias) or self.held(CUPS[i])) + and self.tilt(CUPS[i]) < np.radians(30) and tries.get(i, 0) < rounds] + if not bad: + break + i = min(bad, key=lambda j: float(np.linalg.norm(self.pos(CUPS[j])[:2] - self.sk.eef_pos()[:2]))) + tries[i] = tries.get(i, 0) + 1 + cup = CUPS[i] + gy = self.safe_yaw(self.pos(cup)[:2], ignore=(cup,), prefer=self.sk.yaw) + # lift the cup clear of its neighbours before moving it: carried at 10 cm its base clips their rims and + # tips them (v1, measured, 4/20 adaptive runs before this was raised) + if not self.grasp_cup(cup, gy, depth, z_carry=Z_LIFT, v=0.15, lift=Z_LIFT): + continue + moved += 1 + target = self.mat_xy(i) + bias + ry = self.safe_yaw(target, ignore=(cup,), prefer=self.sk.yaw) + self.put_cup(cup, target, ry, z_carry=Z_LIFT, v=0.1, lift=Z_CARRY) + return moved + + def execute(self, inst, params): + rng = np.random.default_rng(params.get("noise_seed", 0)) + depth = params.get("depth", 0.020) + order = self.mat_order(params.get("order", "far_first")) + mode = params["yaw"] # "fixed" (one wrist yaw for everything) or "safe" (fingers away from placed cups) + y0 = float(params.get("yaw0", 0.0)) + bias = (float(params.get("bias_x", 0.0)), 0.0) + + def yaw_rule(i, what): + if mode == "fixed": + return y0 + q = self.pos(CUPS[i])[:2] if what == "grasp" else self.mat_xy(i) + np.asarray(bias) + return self.safe_yaw(q, ignore=(CUPS[i],), prefer=y0) + + rand = float(params.get("rand", 0.0)) + for i in order: + self.place_one(i, yaw_rule, depth, rng, bias=bias, rand=rand, fix_rand=float(params.get("fix_rand", 0.0)), + check=params.get("self_check", True), z_carry=params.get("z_carry", Z_CARRY), + v=params.get("v", 0.2)) + if params.get("check"): + self.repair(bias=bias) + self._lift_to(0.20) + self.sk.hold(10) + + # naive = Sonnet 5.5's habits measured in the v1 pilot (np_lh_nudge_row): wrist yaw 0 for every grasp and release in + # attempt 1, the row farthest from the supply first, lift to 14-25 cm and carry straight, vertical descents, + # placement 0.8-2.2 cm too far forward (per instance, invisible to it) +- 0.6 cm, looks at the cup it just placed and + # re-places it if it looks off, no look back at the others before finishing + NAIVE = dict(yaw="fixed", yaw0=0.0, order="far_first", self_check=True, check=False, rand=NAIVE_RAND, + fix_rand=NAIVE_FIX_RAND) + CAREFUL = dict(yaw="safe", yaw0=0.0, order="far_first", self_check=True, check=True, rand=0.0, bias_x=0.0) + + def default_params(self, inst): + return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, bias_x=float(inst["naive_bias_x"]), + depth=0.008 + 0.012 * ((int(inst["seed"]) * 7) % 11) / 10) # 0.8-2.0 cm below the rim (pilot: ~1 cm) + + def oracle_params(self, inst): + return dict(self.CAREFUL) + + def adapt_params(self, inst, history): + """from attempt 2: let go with the fingers opening away from the placed cups (same imprecision and bias), and + look at every cup before finishing""" + return dict(self.default_params(inst), yaw="safe", check=True) + + def blind_params(self, inst, attempt, rng): + """the naive behaviour with random variation, no history, no final look""" + return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), + yaw0=float(rng.choice([0.0, np.pi / 2])), order=str(rng.choice(["far_first", "near_first"])), + z_carry=float(rng.uniform(0.15, 0.22)), v=float(rng.uniform(0.1, 0.3)), + depth=float(rng.uniform(0.008, 0.025)), bias_x=float(rng.uniform(*NAIVE_BIAS))) + + 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", "naive_yaw90", "naive_check", "careful_bias2", "naive_bias2") + 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": # attempt 1: naive + a final look at every cup (repairs); then careful releases + 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 releases from attempt 2), no final look + params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), yaw="safe") + elif kind == "oracle_noise": # robustness: careful with +-5 mm placement / grasp noise + params = dict(self.CAREFUL, rand=0.005, noise_seed=int(seed) * 7 + a) + elif kind == "naive_yaw90": # control: Sonnet-like but the wrist turned 90 deg for everything + params = dict(self.default_params(inst), yaw0=np.pi / 2) + elif kind == "naive_check": # control: naive + final look (= adaptive's first attempt) + params = dict(self.default_params(inst), check=True) + elif kind == "careful_bias2": # control: careful releases (nothing nudged) but placed 2 cm too far forward + params = dict(self.default_params(inst), yaw="safe", bias_x=0.020) + elif kind == "naive_bias2": # control: naive with a fixed +2 cm forward bias + params = dict(self.default_params(inst), bias_x=0.020) + 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/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/tasks/l6_count.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/tasks/l6_count.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfcc8725cbfb523898ced10b2974c65b5b3b82f --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/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/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/tasks/lh_bystander.py b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/tasks/lh_bystander.py new file mode 100644 index 0000000000000000000000000000000000000000..d29e80c05aadc9cd8aa5e69c81d724f4cd45d971 --- /dev/null +++ b/leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py new file mode 100644 index 0000000000000000000000000000000000000000..ba9482378574fd6e4fec4b25b958f94103ff4fee --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py @@ -0,0 +1,188 @@ +"""Local fake model APIs for offline harness checks (no real model, no cost). + +Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a +native harness can be driven turn by turn without a model: + FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic + FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider + +A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get +the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps: + ("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read") + ("text", s) a text block / assistant message + ("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript + ("fcall", name, args) Responses: a plain function call + ("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP + tools this way: name "robot", namespace "mcp__lff"; measured with 0.163) + + srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop() +""" +import itertools +import json +import os +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id") + + +class _Base: + final_text = "done" + + def __init__(self, script=None, record_dir=None, port=0): + self.script = list(script or []) + self.record_dir = record_dir + self.port = port + self.lock = threading.Lock() + self.counter = itertools.count(1) + self.requests = [] # (n, path, body) + if record_dir: + os.makedirs(record_dir, exist_ok=True) + + # ------------------------------------------------------------------ plumbing + def start(self): + outer = self + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _record(self, body): + with outer.lock: + n = next(outer.counter) + outer.requests.append((n, self.path, body)) + if outer.record_dir: + with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f: + json.dump(dict(method=self.command, path=self.path, body=body, + headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}), + f, indent=1, ensure_ascii=False) + return n + + def do_GET(self): + self._record(None) + self._send(404, b"{}", "application/json") + + def do_HEAD(self): + self._send(404, b"", "application/json") + + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0)) + try: + body = json.loads(raw) + except ValueError: + body = raw[:4000].decode("utf-8", "replace") + n = self._record(body) + outer.handle(self, n, body) + + def _send(self, code, data, ctype): + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H) + self.httpd.daemon_threads = True + self.port = self.httpd.server_address[1] + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + return self + + def stop(self): + self.httpd.shutdown() + self.httpd.server_close() + + def turn(self, i): + return self.script[i] if i < len(self.script) else [("text", self.final_text)] + + @staticmethod + def send_sse(h, events): + data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events) + h._send(200, data, "text/event-stream") + + +class FakeAnthropic(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}" + + def handle(self, h, n, body): + if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict): + h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json") + return + msgs = body.get("messages", []) + i = sum(1 for m in msgs if m.get("role") == "assistant") + steps = self.turn(i) + blocks = [] + for j, st in enumerate(steps): + if st[0] == "tool": + blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2])) + else: + blocks.append(dict(type="text", text=st[1])) + stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn" + model = body.get("model", "fake") + evs = [("message_start", dict(type="message_start", message=dict( + id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None, + stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))] + for k, b in enumerate(blocks): + if b["type"] == "tool_use": + evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict( + type="tool_use", id=b["id"], name=b["name"], input={})))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict( + type="input_json_delta", partial_json=json.dumps(b["input"]))))) + else: + evs.append(("content_block_start", dict(type="content_block_start", index=k, + content_block=dict(type="text", text="")))) + evs.append(("content_block_delta", dict(type="content_block_delta", index=k, + delta=dict(type="text_delta", text=b["text"])))) + evs.append(("content_block_stop", dict(type="content_block_stop", index=k))) + evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None), + usage=dict(output_tokens=5)))) + evs.append(("message_stop", dict(type="message_stop"))) + self.send_sse(h, evs) + + def message_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages") + and "count_tokens" not in p] + + +class FakeResponses(_Base): + @property + def base_url(self): + return f"http://127.0.0.1:{self.port}/v1" + + def handle(self, h, n, body): + if not isinstance(body, dict) or "input" not in body: + h._send(404, b"{}", "application/json") + return + items = body.get("input") or [] + i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in + ("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message" + and it.get("role") == "assistant")) + steps = self.turn(i) + out = [] + for j, st in enumerate(steps): + if st[0] == "exec": + out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name="exec", status="completed", input=st[1])) + elif st[0] == "fcall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + name=st[1], arguments=json.dumps(st[2]), status="completed")) + elif st[0] == "nscall": + out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}", + namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed")) + else: + out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed", + content=[dict(type="output_text", text=st[1], annotations=[])])) + rid = f"resp_fake_{n}" + evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))] + for k, it in enumerate(out): + evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it))) + evs.append(("response.completed", dict(type="response.completed", response=dict( + id=rid, status="completed", output=out, usage=dict( + input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3, + output_tokens_details=dict(reasoning_tokens=0), total_tokens=103))))) + self.send_sse(h, evs) + + def model_requests(self): + return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b] diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json new file mode 100644 index 0000000000000000000000000000000000000000..790b9765d6166fef8ab1d0980097be6659cdf933 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-opus-5-5_high.json @@ -0,0 +1,15 @@ +{ + "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-opus-5-5|high", + "fingerprint_sha256": "1e12511be3f4985ca25bad34cc2db4a0b317d6565b2d12034672aaac2d97bc85", + "written": "2026-10-21 05:19:32", + "summary": { + "system_chars": 5629, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "claude-opus-5-5" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..661033965e55c1f534f4adf686b51ade9ef40886 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,23 @@ +{ + "key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c", + "written": "2026-10-26 07:02:41", + "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": "gpt-6.1-sol", + "sandbox": { + "sandbox": "seccomp", + "sandbox_mode": "read-only" + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json new file mode 100644 index 0000000000000000000000000000000000000000..c4798ace7f051de8818f09aa5baaed23432f4854 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-v4.1-flash_high.json @@ -0,0 +1,15 @@ +{ + "key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-v4.1-flash|high", + "fingerprint_sha256": "080d6300858cdfc671e135073ec7f693bcf424eace689ffc480903b40f0e0894", + "written": "2026-10-30 16:02:13", + "summary": { + "system_chars": 114, + "tools": [ + "mcp__lff__robot", + "mcp__lff__shell", + "mcp__lff__view_images" + ], + "effort_in_request": "high", + "model_in_request": "deepseek-v4.1-flash" + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json new file mode 100644 index 0000000000000000000000000000000000000000..58b346c1dbe6acac0cb98c0e541c8c6e0ae3bdb4 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json @@ -0,0 +1,18 @@ +{ + "key": "sensenova_codex-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high", + "fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9", + "written": "2026-10-25 04:38:49", + "summary": { + "report": "reports/robot_harness_integration_20261025/selfcheck_final/selfcheck.json", + "checks": 10, + "framework": { + "commit": "b513a1c7289ab11eb844856588b64c378705c405", + "patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823", + "tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350", + "untracked": [ + "lff_integration/__init__.py", + "lff_integration/run.py" + ] + } + } +} \ No newline at end of file diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/redteam.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/redteam.py new file mode 100644 index 0000000000000000000000000000000000000000..23c91f0e46b9df03459df1ac50d33a3fcf49dfc5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/executor.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..edb5a9a3932e891684f2a2c17bb8024c994d46dd --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/real/executor.py @@ -0,0 +1,138 @@ +"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor. + +robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and +call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver +(lffbench/real/protocol.py) instead of the simulator. + +Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and +reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the +ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation. +""" +import math +import time + +import numpy as np + +from ..agent.images import ImageRef +from ..agent.tools import ToolResult, parse_args +from .protocol import CAMERAS, DriverError, square_resize, state_problems + +SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful + + +def _r(v, nd=4): + return [round(float(x), nd) for x in v] + + +class RealToolExecutor: + def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS): + self.driver, self.info = driver, info + self.bias = np.zeros(3) if bias is None else np.asarray(bias, float) + self.image_res = int(image_res) + self.cams = tuple(cams) + self.n_joints = int(info["n_joints"]) + self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"]) + self.max_speed = float(info["max_speed"]) + self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver + self.n_calls = 0 + self._state = None + self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open) + self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents + self.refresh() + self.yaw_cmd = float(self._state["eef_yaw_deg"]) + + # ------------------------------------------------------------------ state + def _set_state(self, st): + prob = state_problems(st, self.n_joints) + if prob: + raise DriverError("driver state: " + "; ".join(prob)) + self._state = st + + def refresh(self): + self._set_state(self.driver.state()) + + def true_eef(self): + return np.asarray(self._state["eef_pos"], float) + + def believed_eef(self): + return self.true_eef() - self.bias + + def proprio(self): + st = self._state + return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1), + gripper="closed" if self.grip_closed else "open", + gripper_width_m=round(float(st["gripper_width_m"]), 4)) + + def joints(self): + """Joint angles as the robot's encoders would report them under the hidden calibration error.""" + if not np.any(self.bias): + return [float(v) for v in self._state["joint_pos_rad"]] + key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"])) + if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command) + self._ik_key = key + self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])] + return list(self._ik_val) + + def observe(self, label=""): + frames, st = self.driver.observe() + self._set_state(st) + return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip()) + for c in self.cams] + + # ------------------------------------------------------------------ helpers + def wrap_yaw(self, yaw): + """The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to + the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit).""" + cands = [yaw + 180.0 * k for k in range(-3, 4)] + ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw_cmd))) + + # ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call) + def call(self, name, raw_args): + t0 = time.time() + self.n_calls += 1 + args = parse_args(raw_args) + fn = getattr(self, f"_t_{name}", None) + if fn is None: + return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0) + res = fn(**args) + res.args, res.wall_s = args, time.time() - t0 + return res + + def _report(self, name, extra=None): + rep = dict(ok=True, tool=name) + rep.update(extra or {}) + rep.update(self.proprio()) + return rep + + def _t_move_to(self, x, y, z, yaw, speed=None): + tgt = np.array([x, y, z], float) + if not np.all(np.isfinite(tgt)): + return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates")) + spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed)) + yaw_used = self.wrap_yaw(float(yaw)) + cmd = tgt + self.bias # the hidden calibration error acts on every commanded position + rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution) + return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; " + "the arm did not move", driver_error=rep.get("error", ""))) + self.yaw_cmd = yaw_used + reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02) + return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached, + yaw_used_deg=round(yaw_used, 1)))) + + def _gripper(self, close): + rep = self.driver.gripper(close) + self.grip_closed = bool(close) + self.motion_s += float(rep.get("motion_s") or 0.0) + self._set_state(rep["state"]) + name = "close_gripper" if close else "open_gripper" + return ToolResult(name, {}, True, self._report(name)) + + def _t_open_gripper(self): + return self._gripper(False) + + def _t_close_gripper(self): + return self._gripper(True) diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py new file mode 100644 index 0000000000000000000000000000000000000000..eec94ac61e9f0b98925237971a1da808aded8ef3 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_breakfast_service.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_breakfast_service.py new file mode 100644 index 0000000000000000000000000000000000000000..76f751d6bb88f22613915c975ca99bba920e21ea --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..542d519109d1f085f749fe2db4dd0c20b51281b5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py @@ -0,0 +1,657 @@ +"""LH clear_cover: sort four cubes into two open boxes by colour -- but in half of the instances one box is covered by a +loose clear acrylic lid. A cube carried over that box and released stops on the lid at rim height; it is not in the box. + +Family: long-horizon self-disturbance / common sense ("state_restoration"; design P2-2 in +research_notes/P1P2_加深与常识任务设计.md): four pick-and-place stages that are each easy for a frontier model; the +trap is a commonsense one -- "a box can have a transparent lid" -- and the failure is only visible from the right +viewpoint: from the side (agentview) the cube visibly sits on top of the box, at rim height, with the box floor visible +below it; from straight above (the wrist camera) it lies inside the box's outline and looks almost the same as a cube +that is inside (design rule R5: a top-down view hides height differences). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * two open boxes (fixtures; inside 12 x 12 cm, walls 5 cm high and 8 mm thick, rim 5.6 cm above the table, light + floor) with red and with blue walls, centres at x in [-0.14, -0.08], y = +-(0.12-0.14) (24-28 cm apart); which + colour is on the left is random. The instruction names the boxes by colour, not "left / right" (the design draft's + wording), so that no failure comes from whose left is meant; + * four 4 cm cubes (38 g), two red and two blue, in a row in front of the boxes (x = -0.33, near the robot; 14 cm + apart, shuffled, yaw +-23 deg); + * the clear lid (covered instances only): a loose 13.4 x 13.4 cm, 8 mm clear plate lying on one box's walls, + 1 mm inside their outer faces (no overhang). v2 (2026-10-13, after the Sonnet pilot np_lh_clear_cover): rendered + nearly invisible -- alpha 0.03, matte (no specular glint), no edge highlight (v1: alpha 0.10 + bright edges, and the + pilot agent named "the transparent lid" from the first images); heavy (1 kg; mass is not visible) with friction 1.0 + and priority for all its contacts and medium-stiff contacts, so incidental contact by the hand does not knock it off + (v1, 0.12 kg / mu 0.3 / 6 mm overhang / very stiff contacts: a probe descent between the boxes knocked it off in the + pilot's very first motions). Transparent geoms do not write MuJoCo's depth buffer: in the depth maps + (--perception rgbd) the lid is not there at all. In uncovered instances the lid is parked on the floor far outside + the workspace and the cameras' view. + +Hidden variable: whether a box is covered and which one. Exactly 10 of every 20 consecutive seeds are covered (5 red / +5 blue box): (seed * 7) mod 20 < 10, like lh_lid_box's balanced blocks. + +Why the natural plan fails: carry each cube over its box and release it a few cm above the rim. Over the covered box the +cube lands on the lid and stays there (v2, measured: drops of 1-8 cm, 48/48 stay on the lid, the lid does not move; +pressing a held cube down towards the box floor stops the arm 4.2 cm above the target, the lid moves <= 0.8 mm, 12/12 +still covering). After the release the cube visibly sits on top of the box in agentview (its bottom 0.8 cm above the +rim, the box floor visible below it); checking only from above it looks as if it were in the box (~1.3x bigger). +What must be learned: look from the side / compare heights before finishing, notice the cubes resting at rim height, +remove the lid (push its edge horizontally with the closed gripper, fingertips between the rim and the lid's top face -- +what the pilot agent did when it saw the v1 lid) and put the cubes in (within the attempt), or check for a lid and +remove it before placing anything (across attempts). Pressing the fingertips onto the lid and dragging no longer moves +it (v2: hand friction = rim friction, by design, because a hand landing on the lid while moving sideways is exactly +what knocked the v1 lid off). +Measured, 2 covered instances x 86 Sonnet-like incidental motions (probe descents to 2-5 cm next to / between the +boxes, transits at 11-20 cm over the covered box, low lateral moves next to the boxes): the box got uncovered 1/172 +(v1: 57/172), the lid moved > 2 cm 20/172 (v1: 97/172); a crash sweep through the boxes at 3 cm still knocks it (1/2). +Deliberate edge push, agent-style commands: fingertip target 2-10 mm below the lid's top face 10/10 (+ 8/8 in the +parameter sweep), at the top face 1/2, above it 0/2. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the +cavity of the box of its colour -- centre inside the cavity, lowest point below the rim --, nothing held, the lid not on +a box, scene static) plus a per-step event log (cube stages achieved / lost / restored, rested_on_cover, left_cover, +cover_removed, cover_on_box, in_wrong_box) 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, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z +TIP = envs.FINGERTIP_BELOW_SITE +# ---------------------------------------------------------------- geometry / physics +CUBE_E = 0.04 +CUBE_DENS = 600.0 # -> 38 g +BOX_IN = 0.06 # inner half width (12 x 12 cm cavity) +WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.05 +BOX_OUT = BOX_IN + WALL_T +RIM = FLOOR_T + WALL_H # rim height above the table +WALL_MU = 0.3 # walls (cube contacts; the lid's own friction has priority in its contacts) +LID_T = 0.008 # thick enough that a horizontal push at 'lid height' finds its edge (v1 draft: 4 mm, see the card) +LID_HALF = BOX_OUT - 0.001 # v2: no overhang (1 mm inside the walls' outer faces): a hand landing on its edge cannot tip it +LID_MASS = 1.0 # v2: heavy (a thick glass-like plate; mass is not visible): incidental bumps move it much less +LID_MU = 1.0 # v2: with priority, used for ALL lid contacts (rim, hand, fingers, cubes): pressing on the lid and moving +# sideways cannot drag it (hand friction == rim friction, and the rim also carries the lid's weight) +LID_SOLREF = (0.005, 1.0) # v2: medium-stiff contacts (v1 used _SOLID: a finger that caught the lid's edge while the +LID_SOLIMP = (0.95, 0.99, 0.001) # arm pressed on could squeeze it against the wall and launch it 16-37 cm) +LID_TOP = RIM + LID_T # lid top surface above the table when it lies on a box +LID_RGBA = (0.85, 0.90, 0.95, 0.03) # v2: near-invisible, no edge highlight, no specular (material below) +PARK = (0.0, 1.4) # lid parked on the floor (world z = 0), out of reach and out of view (uncovered instances) + +COLORS = ("red", "blue") +CUBE_RGBA = dict(red=(0.88, 0.10, 0.08, 1.0), blue=(0.10, 0.25, 0.88, 1.0)) +WALL_RGBA = dict(red=(0.72, 0.26, 0.22, 1.0), blue=(0.22, 0.34, 0.72, 1.0)) +FLOOR_RGBA = (0.86, 0.85, 0.82, 1.0) +CUBES = [f"{c}_cube_{i}" for c in COLORS for i in (1, 2)] +BOXES = {c: f"{c}_box_1" for c in COLORS} +LID = "clear_lid_1" + +IN_MARGIN = 0.010 # a cube counts as in a box if its centre is within BOX_IN - IN_MARGIN of the box centre (each axis) +BELOW_RIM = 0.005 # ... and its lowest point is at least this far below the rim +Z_CARRY = 0.15 # scripted transit height of the grasp point above the table (Sonnet: 11-20 cm) +DROP = 0.04 # scripted release: cube bottom this far above the rim (Sonnet-like 3-5 cm) +SLOT = 0.028 # two cubes per box: +-2.8 cm from the centre along y +PUSH_DEPTH = 0.004 # scripted edge push: fingertips this far below the lid's top face (lid 8 mm thick) +PUSH_SPEED = 0.06 + + +def _color(name): + return name.split("_")[0] + + +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'}" + + +def box_xml_cc(name, wall_rgba): + """open-top box, body origin at the centre of its footprint on the table (z = 0 = table top)""" + o = BOX_OUT + parts = [((0, 0, FLOOR_T / 2), (o, o, FLOOR_T / 2), FLOOR_RGBA, 1.0), + ((BOX_IN + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((-BOX_IN - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((0, BOX_IN + WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU), + ((0, -BOX_IN - WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU)] + g = [] + for k, (p, s, c, mu) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return f""" + + + +{chr(10).join(g)} + + + + + + +""" + + +def lid_xml(name): + """clear plate: one collision box + a near-invisible visual twin with a matte material (no specular glint)""" + h, t = LID_HALF, LID_T / 2 + g = [f' ', + f' '] + xml = _wrap(name, "\n".join(g), t, float(np.hypot(h, h))) + mat = (f' \n \n \n') + return xml.replace(" ", mat + " ", 1) + + +class CoverSkills(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 ClearCover(LFFTask): + name = "lh_clear_cover" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Utilize") + protocol = "cross" + max_attempts = 3 + # careful oracle: 4 pick-and-places (~7 commands each = 28) + pushing the lid off (~5) + looking around (~15); + # one recovery: pushing the lid off + re-placing the cubes that were on it (~5 + 2 x 7) -> ~70; Sonnet looks after + # every step and calibrates the wrist camera (cla4: 10+ observe / probe commands) + agent_max_steps = 110 + instruction = "Put the two red cubes into the red box and the two blue cubes into the blue box." + instruction_indirect = "Sort the four small cubes by colour: each cube goes into the box whose walls have its colour." + agent_object_names = ["red cube", "red cube", "blue cube", "blue cube", "red box", "blue box"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for j, c in enumerate(COLORS): + bx = register_generated(f"LffCc{c.title()}Box", box_xml_cc(f"lff_cc_{c}_box", WALL_RGBA[c]), free=False) + fx.append((BOXES[c], bx, f"{c}_box_region", (-0.12, 0.12 - 0.26 * j, -0.10, 0.14 - 0.26 * j))) + k = 0 + for c in COLORS: + for i in (1, 2): + ab = "AB"[i - 1] + cat = register_generated(f"LffCc{c.title()}Cube{ab}", + box_xml(f"lff_cc_{c}_cube_{ab.lower()}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], + density=CUBE_DENS)) + objs.append((f"{c}_cube_{i}", cat, f"{c}_cube_{i}_region", + (-0.34, -0.22 + 0.14 * k, -0.32, -0.20 + 0.14 * k))) + k += 1 + lid = register_generated("LffCc2ClearLid", lid_xml("lff_cc2_clear_lid")) + objs.append((LID, lid, "lid_region", (0.20, -0.01, 0.22, 0.01))) + return write_bddl(self.name, "put the cubes into the boxes of their colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.box_bid = {c: m.body_name2id(self.env.fixtures_dict[BOXES[c]].root_body) for c in COLORS} + self.lid_gids = set(envs.obj_geom_ids(self.env, LID)) + self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES} + self.robot_gids = 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 = float(rng.uniform(-0.13, -0.09)) + left = str(rng.choice(COLORS)) + boxes = {} + for c in COLORS: + s = 1.0 if c == left else -1.0 + boxes[c] = [bx + float(rng.uniform(-0.01, 0.01)), s * float(rng.uniform(0.12, 0.14))] + slots = [-0.21, -0.07, 0.07, 0.21] + perm = rng.permutation(4) + start = {CUBES[i]: [float(-0.33 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + # balanced like lh_lid_box: exactly 10 of every 20 consecutive seeds covered (5 red box, 5 blue box) + r = (int(seed) * 7) % 20 + cover = "red" if r < 5 else ("blue" if r < 10 else None) + return dict(seed=int(seed), boxes=boxes, left_box=left, start=start, + start_yaw={k: float(rng.uniform(-0.4, 0.4)) for k in CUBES}, cover=cover, + cover_side=(None if cover is None else ("left" if cover == left else "right")), + lid_off=[float(v) for v in rng.uniform(-0.004, 0.004, 2)], lid_yaw=float(rng.uniform(-0.05, 0.05))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c in COLORS: + m.body_pos[self.box_bid[c]] = [inst["boxes"][c][0], inst["boxes"][c][1], Z] + m.body_quat[self.box_bid[c]] = [1.0, 0.0, 0.0, 0.0] + for name, xy in inst["start"].items(): + envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name]) + if inst["cover"]: + b = inst["boxes"][inst["cover"]] + envs.set_obj_pose(self.env, LID, [b[0] + inst["lid_off"][0], b[1] + inst["lid_off"][1], + Z + RIM + LID_T / 2 + 0.0005], yaw=inst["lid_yaw"]) + else: + envs.set_obj_pose(self.env, LID, [PARK[0], PARK[1], LID_T / 2 + 0.002]) + envs.set_friction(self.env, LID, LID_MU, priority=2) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = CoverSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def cube_rel(self, name, color): + return envs.obj_pos(self.env, name)[:2] - np.asarray(self.inst["boxes"][color]) + + def in_box(self, name, color, margin=IN_MARGIN): + """centre inside the cavity (per axis), lowest point below the rim, not held""" + rel = self.cube_rel(name, color) + return bool(np.max(np.abs(rel)) <= BOX_IN - margin and envs.obj_min_z(self.env, name) < Z + RIM - BELOW_RIM + and not self.held(name)) + + def where_box(self, name): + for c in COLORS: + if self.in_box(name, c): + return c + return None + + def lid_pos(self): + return envs.obj_pos(self.env, LID) + + def covering(self): + """colour of the box the lid lies on (centre within the box's outer footprint + 1 cm, above the floor), or None""" + p = self.lid_pos() + for c in COLORS: + rel = np.abs(p[:2] - np.asarray(self.inst["boxes"][c])) + if rel[0] <= BOX_OUT + 0.01 and rel[1] <= BOX_OUT + 0.01 and p[2] > Z + 0.02: + return c + return None + + def _touching(self, gids_a, gids_b): + return envs.contacts_between(self.env, gids_a, gids_b) + + def on_cover(self, name, moving_ok=False): + """the cube rests on the lid while the lid lies on a box (contact, not held, slow -- unless `moving_ok`: the + monitor keeps a cube that came to rest on the lid "on" while it rides along with the lid being pushed)""" + if self.covering() is None or self.held(name): + return False + if not self._touching(self.cube_gids[name], self.lid_gids): + return False + if moving_ok: + return True + _, da = envs.free_joint_addr(self.env, name) + return bool(np.linalg.norm(self.env.sim.data.qvel[da:da + 3]) < 0.05) + + def stage_values(self): + v = {f"{n}_in_box": self.in_box(n, _color(n)) for n in CUBES} + v["cover_off_boxes"] = self.covering() is None + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(step=0, state={f"{n}_in_box": False for n in CUBES}, ever=set(), lost=set(), events=[], + on_cover={n: False for n in CUBES}, cover=self.covering(), wrong={n: None for n in CUBES}, + last_touch={n: None for n in CUBES}, rested=[], cover_removed_step=None) + + def _touches(self): + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for n, g in self.cube_gids.items(): + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.robot_gids: + out[n] = "robot" + elif other in self.lid_gids and out.get(n) != "robot": + out[n] = "lid" + return out + + 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"] + for n, who in self._touches().items(): + if who == "robot": + mon["last_touch"][n] = step + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + cov = self.covering() + if cov != mon["cover"]: + if mon["cover"] is not None and cov is None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_removed", box=mon["cover"])) + mon["cover_removed_step"] = step + elif cov is not None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_on_box", box=cov)) + mon["cover"] = cov + for n in CUBES: + oc = self.on_cover(n, moving_ok=mon["on_cover"][n]) + if oc != mon["on_cover"][n]: + mon["on_cover"][n] = oc + if oc: + mon["rested"].append(dict(step=step, cube=n)) + mon["events"].append(dict(step=step, pred=f"{n}_on_cover", ev="rested_on_cover" if oc else "left_cover", + cube=n, box=cov)) + key = f"{n}_in_box" + was = mon["state"][key] + now = self.in_box(n, _color(n), IN_MARGIN if not was else IN_MARGIN - 0.005) + if now != was: + self._event(key, now, step, n) + other = [c for c in COLORS if c != _color(n)][0] + wr = other if self.in_box(n, other) else None + if wr != mon["wrong"][n]: + mon["wrong"][n] = wr + if wr: + mon["events"].append(dict(step=step, pred=key, ev="in_wrong_box", cube=n, box=wr)) + + def _event(self, key, now, step, n): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + if self.held(n): + cause = "picked_up" + else: + lt = mon["last_touch"][n] + cause = "robot" if lt is not None and step - lt <= 60 else "other" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause)) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in CUBES + [LID]: + _, da = envs.free_joint_addr(self.env, name) + 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 outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in CUBES if self.held(n)] + on_cover = [n for n in CUBES if self.on_cover(n)] + wrong = [n for n in CUBES if not vals[f"{n}_in_box"] and self.where_box(n) is not None] + missing = [n for n in CUBES if not vals[f"{n}_in_box"]] + cov = self.covering() + success = bool(all(vals.values()) and static and not held) + failure = None + if not success: + failure = ("held" if held else "cube_on_cover" if on_cover else "wrong_box" if wrong else + "cube_not_in_box" if missing else "cover_on_box" if cov is not None else "not_static") + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + rested_cubes = sorted({r["cube"] for r in mon["rested"]}) + parts = [] + if success: + parts.append("All four cubes are in the boxes of their colour.") + for n in missing: + c = _color(n) + txt = f"A {c} cube is not in the {c} box: " + if n in held: + parts.append(txt + "it is still held by the gripper.") + continue + p = envs.obj_pos(self.env, n) + rel = self.cube_rel(n, c) + if n in on_cover: + txt += (f"it rests on a clear acrylic lid that lies on the {cov} box, " + f"{100 * (envs.obj_min_z(self.env, n) - Z - FLOOR_T):.1f} cm above the box floor") + elif self.where_box(n) is not None: + txt += f"it is in the {self.where_box(n)} box" + else: + h = envs.obj_min_z(self.env, n) - Z + txt += ("it lies on the table" if h < 0.005 else f"it lies {100 * h:.1f} cm above the table") + txt += f", its centre {_fb(rel[0])} and {_lr(rel[1])} of the {c} box's centre" + if n in rested_cubes and n not in on_cover: + txt += " (it had come to rest on the clear lid earlier)" + parts.append(txt + ".") + if cov is not None: + parts.append(f"A clear acrylic lid lies on the {cov} box.") + if not static and all(vals.values()) and not held: + parts.append("Something was still moving at the end.") + if mon["cover_removed_step"] is not None and cov is None: + parts.append("The clear lid was pushed off its box.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + covered=inst["cover"], trap_fired=bool(mon["rested"]), n_rested_on_cover=len(mon["rested"]), + rested_cubes=rested_cubes, cover_removed=mon["cover_removed_step"] is not None, + cover_removed_step=mon["cover_removed_step"], cover_final=cov, on_cover_final=on_cover, + recovered_in_attempt=bool(mon["rested"]) and success, + cube_offsets_cm={n: (100 * self.cube_rel(n, _color(n))).round(1).tolist() for n in CUBES}, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _finger_axis(self, yaw): + """world xy direction along which the fingers close at gripper yaw `yaw` (Skills: yaw 0 = fingers along y)""" + return np.array([-np.sin(yaw), np.cos(yaw)]) + + def _clear_yaw(self, name, room=0.04): + """grasp yaw of the cube: the smallest wrist turn (within +-45 deg) unless one of the open fingertips (4.5 cm + either side) would come down within `room` of another cube's centre (cubes put side by side or pushed off on + the lid stand 1.5-2.5 cm apart); then the 90-deg turned grasp if it has more room""" + p = envs.obj_pos(self.env, name)[:2] + others = [envs.obj_pos(self.env, n)[:2] for n in CUBES if n != name] + + def dmin(yaw): + a = self._finger_axis(yaw) + return min([np.linalg.norm(t - o) for t in (p + a * 0.045, p - a * 0.045) for o in others] or [1.0]) + + y0 = self._grasp_yaw(name) + if dmin(y0) >= room: + return y0 + y1 = float((y0 + np.pi / 2 + np.pi / 2) % np.pi - np.pi / 2) + return y1 if dmin(y1) > dmin(y0) else y0 + + def pick(self, name, z_carry=Z_CARRY): + sk = self.sk + p = envs.obj_pos(self.env, name) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, p[2] - Z + 0.06)], yaw=self._clear_yaw(name)) + sk.move_to([p[0], p[1], p[2]], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + return True + + def place_in(self, name, slot, drop=DROP, z_carry=Z_CARRY, noise=None): + """carry the held cube over its box (slot -1 / +1: 2.8 cm right / left of the centre) and release it with its + bottom `drop` above the rim""" + sk = self.sk + b = np.asarray(self.inst["boxes"][_color(name)], float) + d = b + [0.0, SLOT * slot] + (np.asarray(noise, float) if noise is not None else 0.0) + z_rel = Z + RIM + drop + CUBE_E / 2 + sk.move_to([d[0], d[1], Z + z_carry], yaw=0.0) + sk.move_to([d[0], d[1], z_rel], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], Z + z_carry]) + + def pick_place(self, name, slot, drop=DROP, noise=None): + if self.pick(name): + self.place_in(name, slot, drop=drop, noise=noise) + return True + return False + + def remove_cover(self, direction=None, depth=PUSH_DEPTH, mode="edge"): + """push the lid off its box: closed gripper, fingertips `depth` below the lid's top face, start 3 cm outside + its near edge (mode "edge") or 3 cm inside it, pressing on the lid (mode "press": press and drag -- v2: does not + move the lid any more, see the module docstring), sweep + straight on until the lid has cleared the box (default: sideways, away from the other box), lift""" + cov = self.covering() + if cov is None: + return False + sk = self.sk + lp = self.lid_pos() + b = np.asarray(self.inst["boxes"][cov], float) + if direction is None: + o = np.asarray(self.inst["boxes"][[c for c in COLORS if c != cov][0]], float) + direction = (0.0, float(np.sign(b[1] - o[1]))) + d = np.asarray(direction, float) / np.linalg.norm(direction) + back = LID_HALF + 0.03 if mode == "edge" else LID_HALF - 0.03 + s = lp[:2] - d * back + top = lp[2] + LID_T / 2 + z = top - depth + TIP + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.08], yaw=float(np.arctan2(d[1], d[0]) - np.pi / 2)) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=80) + # sweep until the lid's near edge is 3 cm beyond the box's far wall + need = float((b - lp[:2]) @ d) + BOX_OUT + back + 0.03 + e = s + d * need + sk.move_to([e[0], e[1], z], speed=PUSH_SPEED, tol=0.006, max_steps=int(need / PUSH_SPEED / 0.05) + 80) + sk.move_to([e[0], e[1], z + 0.10], speed=0.2) + sk.set_gripper(False, steps=8) + sk.hold(10) + return self.covering() is None + + def slots(self, order): + """slot of each cube: the first cube of a colour goes right of the centre, the second left""" + seen, out = {c: 0 for c in COLORS}, {} + for n in order: + out[n] = (-1, 1)[seen[_color(n)] % 2] + seen[_color(n)] += 1 + return out + + def wrist_fix(self, rounds=1): + """what a top-down check can see: cubes whose centre is not over the right box's outline (on the table, in + the other box, still held) get placed again; heights are not judged""" + for _ in range(rounds): + bad = [] + for n in CUBES: + rel = self.cube_rel(n, _color(n)) + if self.held(n) or np.max(np.abs(rel)) > BOX_OUT: + bad.append(n) + if not bad: + return + for n in bad: + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + self.pick_place(n, -1 if self.cube_rel(n, _color(n))[1] < 0 else 1) + + def set_aside(self, name): + """pick the cube (e.g. off the lid) and put it down on the table where it started (that spot is free)""" + if not self.pick(name): + return False + sk = self.sk + x, y = self.inst["start"][name] + sk.move_to([x, y, Z + Z_CARRY], yaw=0.0) + sk.move_to([x, y, Z + CUBE_E / 2 + 0.004], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([x, y, Z + Z_CARRY]) + return True + + def side_fix(self, rounds=2): + """the careful check (agentview / heights): every cube must be inside its box, below the rim; if cubes rest on + a lid (or a lid lies on a box): take the cubes off the lid (v2: the heavy lid cannot be pushed off with cubes + standing on it -- the hand runs into them), push the lid off; then place every cube that is not in its box""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + if not v["cover_off_boxes"]: + for n in CUBES: + if self.on_cover(n) or (self.covering() is not None and self._touching(self.cube_gids[n], self.lid_gids)): + self.set_aside(n) + self.remove_cover() + for n in CUBES: + if not self.in_box(n, _color(n)): + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + others = [m for m in CUBES if m != n and _color(m) == _color(n)] + rel_o = self.cube_rel(others[0], _color(n)) if others else np.zeros(2) + self.pick_place(n, 1 if rel_o[1] < 0 else -1) + return all(self.stage_values().values()) + + def execute(self, inst, params): + order = params.get("order") or list(CUBES) + noise = params.get("noise") or {} + drops = params.get("drops") or {} + if params["plan"] == "lid_first": + self.remove_cover(params.get("push_dir"), params.get("push_depth", PUSH_DEPTH), params.get("push_mode", "edge")) + sl = self.slots(order) + for n in order: + self.pick_place(n, sl[n], drop=drops.get(n, DROP), noise=noise.get(n)) + if params.get("check") == "side": + self.side_fix() + elif params.get("check") == "wrist": + self.wrist_fix() + self.sk.hold(10) + + def default_params(self, inst): + return dict(plan="naive", check="wrist") + + def oracle_params(self, inst): + return dict(plan="lid_first", check="side") + + def adapt_params(self, inst, history): + """from attempt 2 on: look for a lid and push it off first, then place, then check from the side""" + return dict(plan="lid_first", check="side") + + def blind_params(self, inst, attempt, rng): + """the natural plan again with small random variations (order, 5 mm placement noise, 3-5 cm drop), no history""" + order = [CUBES[i] for i in rng.permutation(len(CUBES))] + return dict(plan="naive", check="wrist", order=order, + noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES}, + drops={n: float(rng.uniform(0.03, 0.05)) for n in CUBES}) + + 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 = [] + 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(plan="naive", check="side") 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": # extra control (not in validate's table): cross-attempt learning only, no side check + params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check="wrist") + 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"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/mcp_robot_server.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/mcp_robot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18f433abeec51793dbf999e9da2a165b16d9393d --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/mcp_robot_server.py @@ -0,0 +1,140 @@ +"""MCP server (stdio) exposing one robot_server session to a native agent harness (Claude Code, Codex, Gemini CLI, ...). + +The tools are exactly the unified harness's LA tools (scripts/api_player.py): `robot`, `shell` (jailed, in the episode +workspace) and `view_images` (returned as MCP image content), with the same per-attempt tool-call budget: when it is +used up the attempt is finished automatically and the result is appended to that call's output. So a native harness +and the API harness see the same README, tools and limits; only the agent loop around them differs. + + python scripts/mcp_robot_server.py --session runs/<...>/session.json + python scripts/mcp_robot_server.py --schema-only (launch preflight: same tools/list, no session, every call fails) +Every call is logged to /mcp_transcript.jsonl (the first line lists the names of the environment variables the +harness passed to this process, for the harness self-check). Nothing but JSON-RPC goes to stdout. +The tools themselves are scripts/tool_gateway.py's ToolCore: through the episode's tool gateway when the launcher +started one (gateway.json in the log dir; docs/18 §6.1), otherwise in this process. +""" +import argparse +import json +import os +import sys +import time +import traceback + +ENV_AT_START = dict(os.environ) # what the harness passed (before our own imports touch the environment) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "client")) +from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA # noqa: E402 +from lffbench_client import Session as Client # noqa: E402 +from tool_gateway import GATEWAY_FILE, ToolCore # noqa: E402 + +PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05") +TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] + + +class Session: + """One episode's tools. With a tool gateway (scripts/tool_gateway.py, started by harness_run.py; its gateway.json is + in the run's log dir) every call goes to the gateway, which owns the per-attempt budget for the whole episode, also + across the MCP processes of a resumed CLI. Without one, the same ToolCore runs in this process and the budget is + carried over from mcp_transcript.jsonl. Either way the tool outputs are the gateway's ToolCore's, byte for byte.""" + + def __init__(self, session_path): + self.log_dir = os.path.dirname(os.path.abspath(session_path)) + tpath = os.path.join(self.log_dir, "mcp_transcript.jsonl") + gfile = os.path.join(self.log_dir, GATEWAY_FILE) + self.gateway = Client.from_gateway_file(gfile, face="mcp") if os.path.exists(gfile) else None + self.core = None if self.gateway else ToolCore(session_path, carry_from=tpath) + self.calls_in_attempt = self.core.calls_in_attempt if self.core else None + self.finished = self.core.finished if self.core else False + self.tlog = open(tpath, "a") + + def log(self, d): + d["t"] = time.time() + self.tlog.write(json.dumps(d, ensure_ascii=False) + "\n") + self.tlog.flush() + + def call(self, name, args): + """-> (MCP content list, is_error)""" + if self.core is not None: + content, err = self.core.call(name, args) + self.calls_in_attempt, self.finished = self.core.calls_in_attempt, self.core.finished + return content, err + r = self.gateway.call(name, args) + self.calls_in_attempt, self.finished = r.calls_in_attempt, r.finished + return r.content, r.is_error + + +class SchemaOnly: + """No robot session: the harness preflight only needs tools/list (byte-identical to a real session).""" + finished = False + + def log(self, d): + pass + + def call(self, name, args): + return [dict(type="text", text="schema-only preflight server: no robot session")], True + + +def serve(sess): + def send(obj): + sys.stdout.write(json.dumps(obj) + "\n") + sys.stdout.flush() + + for line in sys.stdin: + line = line.strip() + if not line: + continue + try: + msg = json.loads(line) + except ValueError: + send(dict(jsonrpc="2.0", id=None, error=dict(code=-32700, message="parse error"))) + continue + mid, method, params = msg.get("id"), msg.get("method"), msg.get("params") or {} + if mid is None: # notification (notifications/initialized, cancelled, ...) + continue + try: + if method == "initialize": + want = params.get("protocolVersion") + result = dict(protocolVersion=want if want in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0], + capabilities=dict(tools=dict(listChanged=False)), + serverInfo=dict(name="lffbench-robot", version="1.0")) + elif method == "ping": + result = {} + elif method == "tools/list": + result = dict(tools=[dict(name=t["name"], description=t["description"], inputSchema=t["parameters"]) + for t in TOOLS]) + elif method == "tools/call": + name, args = params.get("name"), params.get("arguments") or {} + t0 = time.time() + content, err = sess.call(name, args) + sess.log(dict(ev="tool", name=name, arguments=args, dt=round(time.time() - t0, 2), is_error=err, + output=[c["text"] for c in content if c["type"] == "text"], + images=sum(1 for c in content if c["type"] == "image"), finished=sess.finished, + calls_in_attempt=getattr(sess, "calls_in_attempt", None))) + result = dict(content=content, isError=err) + else: + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32601, message=f"method not found: {method}"))) + continue + send(dict(jsonrpc="2.0", id=mid, result=result)) + except Exception as e: + sess.log(dict(ev="error", method=method, error=traceback.format_exc()[-2000:])) + send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32603, message=f"{type(e).__name__}: {e}"))) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--session", help="session.json written by start_robot_session.sh (la style)") + ap.add_argument("--schema-only", action="store_true", help="serve the tool list only (harness launch preflight)") + a = ap.parse_args() + if a.schema_only: + serve(SchemaOnly()) + return + if not a.session: + ap.error("--session is required (or --schema-only)") + sess = Session(a.session) + import hashlib # names + 8-hex sha256 of each value (enough to tell inherited from fresh values, reveals nothing) + sess.log(dict(ev="start", session=a.session, pid=os.getpid(), env_keys=sorted(ENV_AT_START), + env_value_sha8={k: hashlib.sha256(v.encode()).hexdigest()[:8] for k, v in ENV_AT_START.items()})) + serve(sess) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate_ladder_fix.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate_ladder_fix.py new file mode 100644 index 0000000000000000000000000000000000000000..d80168eaa6cf7ce8c79aacac8a0f8d3e25e63e05 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/source_closure/scripts/validate_parts_cart.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate_parts_cart.py new file mode 100644 index 0000000000000000000000000000000000000000..58349b4c88968dfe22e0ccbb7ce398754fd98f2c --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/validate_parts_cart.py @@ -0,0 +1,52 @@ +"""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 ['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'],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_acceptance.py b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/vla_acceptance.py new file mode 100644 index 0000000000000000000000000000000000000000..2020f59a594069a82ad773c594c798522f733007 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/vla_acceptance.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +"""Acceptance test of the VLA evaluator (lffbench/vla.py) against recorded agent attempts. + +Replays recorded first attempts through the exact path a policy takes (vla.run_session) and checks +- the verdict: outcome() must give the recorded label, for successes AND failures; +- the observation: state and both cameras must equal what the LeRobot dataset holds for that frame, and the prompt + must be what the agent was told (first_message.txt; the proprioception frame is "true" here because the dataset + records the true pose; the evaluator's default applies the L1 calibration errors). + + python3 scripts/vla_acceptance.py plan --out DIR [--per-label 2] # no simulator; any python with pyarrow + python scripts/vla_acceptance.py one DIR/cand/.json # one attempt, in the LFF environment + python3 scripts/vla_acceptance.py summary DIR + +An open-loop replay is only meaningful when the recording is reproduced, so lossless float64 actions are used where the +intermediate recordings exist (published parquet actions are float32 and diverge on chaotic contacts). A candidate +whose replay leaves the recording is reported as `diverged`, not as a verdict error. +""" +import argparse +import collections +import glob +import hashlib +import json +import os +import sys + +import numpy as np + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +AR = os.path.dirname(ROOT) +DATA = "/mnt/cpfs/shared/datasets/lffbench_agent_replays" +CUMULATIVE = {"v1.0", "v1.1", "v1.2", "v1.3"} +DIVERGED_M = 0.005 # the replayed grasp point is this far from the recording + + +def _sha(path, memo={}): + if path not in memo: + memo[path] = hashlib.sha256(open(path, "rb").read()).hexdigest() if os.path.exists(path) else None + return memo[path] + + +def code_matches(run_dir): + p = os.path.join(run_dir, "contract.json") + if not os.path.exists(p): + return False + files = json.load(open(p))["contract"].get("server_code_files") or {} + return bool(files) and all(_sha(os.path.join(ROOT, f)) == h for f, h in files.items()) + + +def raw_roots(): + roots = [f"{AR}/lerobot_replay_raw_local", f"{AR}/lerobot_replay_raw_dlc"] + for pat in ("ops/lerobot_backfill_20261102/exports/*/raw", "ops/lerobot_backfill_20261102/dlc_parallel/exports/*/raw", + "ops/compound_lh_eval_20261102/exports/*/raw", "ops/codex_watch/*/exports/*/raw", + "ops/lerobot_deepseek_20261030/exports/*/raw"): + roots += glob.glob(os.path.join(AR, pat)) + return roots + + +def cmd_plan(a): + import pyarrow.dataset as ds + os.makedirs(os.path.join(a.out, "cand"), exist_ok=True) + roots = raw_roots() + pool = collections.defaultdict(list) + for name in sorted(os.listdir(DATA)): + p = os.path.join(DATA, name, "lff/episodes.jsonl") + if name in CUMULATIVE or not os.path.exists(p): + continue + for line in open(p): + r = json.loads(line) + if not r["attempts"] or r["attempts"][0] != 1 or r["success"][0] is None: + continue + if r.get("auto_ended") and r["auto_ended"][0]: # ended by a budget inside the server, not by `finish` + continue + pool[(r["task"], bool(r["success"][0]))].append((r["length"], name, r)) + n, missing = 0, [] + for (task, label), lst in sorted(pool.items()): + lst.sort(key=lambda x: x[0]) + got, seeds = 0, set() + for need_raw in (True, False): + for length, name, r in lst: + if got >= a.per_label: + break + if r["seed"] in seeds: + continue + run_dir = os.path.join(ROOT, "runs/api", r["batch"], r["run"]) + if not os.path.isdir(run_dir) or not code_matches(run_dir): + continue + raw = next((q for q in (f"{x}/{r['batch']}/{r['run']}/ep00/frames.npz" for x in roots) if os.path.exists(q)), None) + if need_raw and raw is None: + continue + stem = f"{task}__{'ok' if label else 'fail'}{got}" + cand = dict(stem=stem, task=task, seed=r["seed"], label=label, run_dir=run_dir, dataset=name, episode_index=r["episode_index"], + instruction=r["instruction"], protocol=r["protocol"], model=r["model"], raw=raw, length=r["length"]) + if raw is None: + t = ds.dataset(os.path.join(DATA, name, "data"), format="parquet").to_table( + columns=["action", "annotation.phase", "annotation.attempt_index", "observation.state", "frame_index"], + filter=ds.field("episode_index") == r["episode_index"]).sort_by("frame_index") + np.savez(os.path.join(a.out, "cand", stem + ".npz"), + action=np.stack(t["action"].to_numpy(zero_copy_only=False)).astype(np.float64), + phase=t["annotation.phase"].to_numpy().astype(int).reshape(-1), + attempt=t["annotation.attempt_index"].to_numpy().astype(int).reshape(-1), + state=np.stack(t["observation.state"].to_numpy(zero_copy_only=False)).astype(np.float64)) + json.dump(cand, open(os.path.join(a.out, "cand", stem + ".json"), "w"), indent=1) + got += 1 + n += 1 + seeds.add(r["seed"]) + if got < a.per_label: + missing.append((task, label, got)) + print(n, "candidates;", "short of the requested count:", missing) + + +def video_frame(path, t): + import cv2 + cap = cv2.VideoCapture(path) + cap.set(cv2.CAP_PROP_POS_FRAMES, t) + ok, img = cap.read() + cap.release() + return img[:, :, ::-1] if ok else None + + +def cmd_one(a): + sys.path.insert(0, ROOT) + sys.path.insert(0, os.path.join(ROOT, "scripts")) + import lerobot_replay as LR + from lffbench import vla + c = json.load(open(a.cand)) + if c["raw"]: + z = np.load(c["raw"]) + keep = (z["attempt"] == 1) & (z["phase"] != 2) + state = np.concatenate([z["eef_pos"], z["eef_axis_angle"], z["gripper_qpos"]], axis=1) + precision = "float64" + else: + z = np.load(a.cand[:-5] + ".npz") + keep = (z["attempt"] == 1) & (z["phase"] != 2) + state = z["state"] + precision = "float32" + idx = np.flatnonzero(keep) + assert (np.diff(idx) == 1).all() and idx[0] == 0, "attempt 1 must be one contiguous prefix" + actions = z["action"][idx] + s = LR.RunLog(c["run_dir"]).start + task = LR.TASKS[c["task"]](cam_res=256) + inst = task.sample_instance(s["seed"]) + logged = s.get("inst") or {} + if s.get("arm", "none") not in (None, "none") or logged.get("nominal"): + inst.update(logged) + first_message = os.path.join(c["run_dir"], "first_message.txt") + prompt = vla.task_prompt(task, inst) + res = dict(stem=c["stem"], task=c["task"], seed=c["seed"], label=c["label"], precision=precision, n=len(actions), protocol=c["protocol"], + prompt_ok=prompt in open(first_message).read() if os.path.exists(first_message) else prompt == c["instruction"], + first_div=None, parity=[]) + mid = (len(actions) // 2) // 5 * 5 + raw_dir = os.path.dirname(c["raw"]) if c["raw"] else None + + def on_obs(t, obs): + err = float(np.abs(obs["observation/state"] - state[t]).max()) + if res["first_div"] is None and np.linalg.norm(obs["observation/state"][:3] - state[t][:3]) > DIVERGED_M: + res["first_div"] = t + if t in (0, mid) and res["first_div"] is None: + row = dict(t=t, state_err=err) + if raw_dir: + for key, f in (("observation/image", "agentview.mp4"), ("observation/wrist_image", "wrist.mp4")): + img = video_frame(os.path.join(raw_dir, f), t) + if img is not None: + row[f[:-4] + "_mae"] = float(np.abs(obs[key].astype(float) - img.astype(float)).mean()) + res["parity"].append(row) + + policy = vla.ReplayPolicy(actions, chunk=5, on_obs=on_obs) + rec = vla.run_session(task, inst, policy, k=1, max_steps=len(actions), replan=5, frame="true", idle_s=0, probe_every_s=0)[0] + res.update(verdict=rec["success"], end=rec["end"], n_steps=rec["n_steps"], detail=str(rec["detail"])[:240], failure=rec["failure"]) + res["verdict_ok"] = rec["success"] == c["label"] + json.dump(res, open(a.cand.replace("/cand/", "/out/"), "w"), indent=1) + print(c["stem"], "verdict_ok", res["verdict_ok"], "first_div", res["first_div"], "parity", res["parity"][:1], flush=True) + + +def cmd_summary(a): + rows = [json.load(open(f)) for f in sorted(glob.glob(os.path.join(a.dir, "out/*.json")))] + tally = collections.Counter() + bad = [] + for r in rows: + kind = "ok" if r["label"] else "fail" + if r["verdict_ok"]: + tally[kind + "_right"] += 1 + elif r["first_div"] is not None: + tally[kind + "_diverged"] += 1 + bad.append(r) + else: + tally[kind + "_WRONG"] += 1 + bad.append(r) + per_task = collections.defaultdict(lambda: collections.Counter()) + for r in rows: + key = "right" if r["verdict_ok"] else ("diverged" if r["first_div"] is not None else "WRONG") + per_task[r["task"]][("ok_" if r["label"] else "fail_") + key] += 1 + t0 = [p for r in rows for p in r["parity"] if p["t"] == 0] + later = [p for r in rows for p in r["parity"] if p["t"] > 0] + + def worst(ps, key): + vals = [p[key] for p in ps if key in p] + return (round(max(vals), 7), len(vals)) if vals else None + + out = dict(n=len(rows), tally=dict(tally), n_tasks=len(per_task), per_task={t: dict(c) for t, c in sorted(per_task.items())}, + prompt_mismatch=sorted({r["task"] for r in rows if not r["prompt_ok"]}), + parity_t0=dict(state=worst(t0, "state_err"), agentview=worst(t0, "agentview_mae"), wrist=worst(t0, "wrist_mae")), + parity_mid=dict(state=worst(later, "state_err"), agentview=worst(later, "agentview_mae"), wrist=worst(later, "wrist_mae")), + not_right=[{k: r[k] for k in ("stem", "seed", "precision", "first_div", "n", "detail")} for r in bad]) + json.dump(out, open(os.path.join(a.dir, "summary.json"), "w"), indent=1) + print(json.dumps({k: v for k, v in out.items() if k not in ("per_task", "not_right")}, indent=1)) + for r in out["not_right"]: + print(r["stem"], r["seed"], r["precision"], "first_div", r["first_div"], "/", r["n"], "|", r["detail"][:130]) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + sub = ap.add_subparsers(dest="cmd", required=True) + p = sub.add_parser("plan") + p.add_argument("--out", required=True) + p.add_argument("--per-label", type=int, default=2) + p.set_defaults(fn=cmd_plan) + o = sub.add_parser("one") + o.add_argument("cand") + o.set_defaults(fn=cmd_one) + s = sub.add_parser("summary") + s.add_argument("dir") + s.set_defaults(fn=cmd_summary) + 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/tasks/l1_bias.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l1_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..a5743522e389d8640257a0cbab03aa8e7df7dd86 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l1_bias.py @@ -0,0 +1,390 @@ +"""L1-A bias_place: pick up the cream cheese and put it into the bowl, with a miscalibrated arm. + +Level L1 (action fine-tuning): the method (top-down pick across the cheese's short side, carry, release +above the bowl) and the scene understanding are right; only execution precision is off. + +Hidden variable: a fixed calibration offset b = r (cos th, sin th, 0), r ~ U[R_MIN, R_MAX], th ~ U[0, 2 pi), +added to every commanded gripper position (`Skills(bias=b)`). The agent never sees b; positions reported +back to it must be in the commanded frame (`TrackedSkills.reported_eef_pos`), otherwise b leaks. + +Robot: the gripper is a short-stroke parallel gripper (max opening GRIPPER_MAX_OPEN = 5.0 cm, e.g. a +Robotiq Hand-E; implemented by narrowing the Panda finger actuators' ctrlrange). The cream cheese is +4.27 cm wide, so the open fingers clear it by ~3.5 mm per side. + +Why the prior fails. Sent to the true cheese position, the gripper arrives b away. If the component of b +across the cheese (jaw-closing direction) exceeds ~0.7-1.0 cm (measured), a finger comes down on top of the +cheese, the hand stops ~1.5 cm too high and the jaws close above it -> missed grasp, visible in both +cameras. With the stock 8 cm Panda stroke the measured tolerance is ~2.4 cm, so most r in [2, 4] cm would +not fail; that is why the stroke is reduced. The component of b along the cheese does not matter much +(the finger pads can grip anywhere along its 8.1 cm length, and the in-hand offset cancels at the place +because the same b is added there), and the bowl is forgiving. + +What has to be learned: the F2 feedback reports where the gripper closed relative to the cheese's centre +(forward/backward, left/right in the robot frame). That offset is b itself, so after one failure b can be +estimated and subtracted from every commanded position (pick and place alike). +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CHEESE, BOWL = "cream_cheese_1", "akita_black_bowl_1" +JUICE = "orange_juice_1" +DISTRACTORS = ("butter_1", "chocolate_pudding_1", JUICE) +ALL = (CHEESE, BOWL) + DISTRACTORS +NAMES = {CHEESE: "cream cheese", BOWL: "bowl", "butter_1": "butter", "chocolate_pudding_1": "chocolate pudding", + JUICE: "orange juice carton"} +# descriptive names for the indirect variant (same wording as l2_knock_restore where objects overlap) +DESCR = {CHEESE: "blue box", BOWL: "grey bowl", "butter_1": "small orange box", "chocolate_pudding_1": "brown box", + JUICE: "tall juice carton"} +# Cream cheese collision box: 8.12 x 4.27 x 1.79 cm, lying flat, long side along its x axis. +# Realistic masses (LIBERO's are 5-10 g): a 6 g cheese is shoved aside by a finger landing on its edge. +MASS = {CHEESE: 0.227, "butter_1": 0.250, "chocolate_pudding_1": 0.200, BOWL: 0.300} + +# finger tips (0.97 cm below the gripper site) just clear the table; the pads cover 0.6-1.8 cm of the cheese +Z_GRASP = envs.TABLE_Z + 0.0105 +Z_CARRY = envs.TABLE_Z + 0.20 # clears the 13 cm juice carton with the cheese hanging below the fingers +BOWL_RIM = 0.0505 # rim height of the akita bowl above its lowest point +BOWL_R_IN = 0.046 # inner radius of the bowl at the rim +RELEASE_ABOVE_RIM = 0.012 # gripper site above the rim at release (finger pads clear the rim) + +R_MIN, R_MAX = 0.025, 0.040 # bias magnitude range (m) +GRIPPER_MAX_OPEN = 0.050 # short-stroke gripper: max finger gap (m); the cheese is 4.27 cm wide +CHEESE_YAW_MAX = np.deg2rad(10) + + +HOME_XY = np.array([-0.21, 0.0]) # gripper xy at reset + + +def _seg_dist(p, a, b): + """distance from point p to segment ab (2-D)""" + 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 {"y": np.array([np.cos(h), 0, np.sin(h), 0]), "z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis] + + +def _qmul(a, b): + """wxyz quaternion product 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 set_gripper_stroke(env, max_open): + """Limit the jaw opening: each finger's position actuator gets the range [0, max_open/2] (robosuite maps + the open/close command onto the actuator ctrlrange, so "open" now means max_open). The pad faces sit + 0.5 mm inside the joint position, hence the small correction.""" + m = env.sim.model + half = max_open / 2 + 0.0005 + a1, a2 = [m.actuator_name2id(a) for a in env.robots[0].gripper.actuators] + m.actuator_ctrlrange[a1] = [0.0, half] + m.actuator_ctrlrange[a2] = [-half, 0.0] + + +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" + + +class TrackedSkills(Skills): + """Skills that log what the outcome measurement needs, whoever drives them (scripted policy or agent): + where the gripper was and what the fingers touched when the jaws closed, and where the cheese was when + the jaws opened while holding it.""" + + def __init__(self, env, bias=None, recorder=None): + super().__init__(env, bias=bias, recorder=recorder) + self.events = [] + self.cheese_z0 = float(envs.obj_pos(env, CHEESE)[2]) + self.cheese_zmax = self.cheese_z0 + m = env.sim.model + 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 ALL} + # where the cheese was before the gripper last touched it (the reference for the grasp offset, so that + # a finger shoving the cheese aside on the way down does not corrupt the measurement) + self.cheese_ref = envs.obj_pos(env, CHEESE) + + 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 b.""" + 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() # do not leak b through the report + return rep + + def touching(self): + """Objects the gripper is in contact with right now.""" + return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)] + + def _act(self, dpos, drot, grip): + super()._act(dpos, drot, grip) + self.cheese_zmax = max(self.cheese_zmax, float(envs.obj_pos(self.env, CHEESE)[2])) + if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[CHEESE]): + self.cheese_ref = envs.obj_pos(self.env, CHEESE) + + def set_gripper(self, close, steps=15): + if close and self.grip < 0: + self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), + cheese=envs.obj_pos(self.env, CHEESE).tolist(), + cheese_ref=np.asarray(self.cheese_ref).tolist(), touching=self.touching(), + cheese_top=envs.obj_max_z(self.env, CHEESE), step=self.n_steps)) + elif not close and self.grip > 0 and self.holding(CHEESE): + self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), + cheese=envs.obj_pos(self.env, CHEESE).tolist(), + bowl=envs.obj_pos(self.env, BOWL).tolist(), step=self.n_steps)) + return super().set_gripper(close, steps) + + +@register_task +class BiasPlace(LFFTask): + name = "l1_bias_place" + level = "L1" + category = "system_identification" + capabilities = ("Perceive", "Utilize") + protocol = "cross" + # LIBERO calls the bowl "akita black bowl", but under our renderer it looks silver-grey with a gold rim, so + # the colour is not used in the direct instruction (there is only one bowl). + instruction = "Pick up the cream cheese and put it into the bowl." + instruction_indirect = "Pick up the flat blue box with the white oval label and put it into the round grey bowl." + pick_lift_min = 0.03 # cheese counted as picked up if it rose this much + + # ------------------------------------------------------------ scene + def make_bddl(self): + # regions are only used by LIBERO's reset-time sampler (the layout is overridden in apply_instance) + objs = [(CHEESE, "cream_cheese", "cheese_region", (-0.16, -0.22, -0.14, -0.20)), + (BOWL, "akita_black_bowl", "bowl_region", (-0.01, 0.15, 0.01, 0.17)), + ("butter_1", "butter", "butter_region", (-0.16, 0.10, -0.14, 0.12)), + ("chocolate_pudding_1", "chocolate_pudding", "pudding_region", (0.04, -0.17, 0.06, -0.15)), + (JUICE, "orange_juice", "juice_region", (-0.15, -0.03, -0.13, -0.01))] + return write_bddl(self.name, self.instruction, objs) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + # LIBERO's own upright orientation of every object, read off the reset state + self._base_quat = {n: envs.obj_quat(self.env, n) for n in ALL} + + def _place(self, name, xy, yaw): + q = _qmul(_q("z", yaw), self._base_quat[name]) + envs.set_obj_pose(self.env, name, [xy[0], xy[1], envs.TABLE_Z + 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) - (envs.TABLE_Z + 0.0005) + self.env.sim.forward() + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + c = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)]) + bowl = np.array([rng.uniform(-0.15, 0.08), rng.uniform(-0.24, 0.24)]) + if np.linalg.norm(bowl - c) < 0.20: + continue + placed = [c, bowl] + dis = {} + for name in DISTRACTORS: + for _ in range(300): + p = np.array([rng.uniform(-0.22, 0.10), rng.uniform(-0.27, 0.27)]) + if any(np.linalg.norm(p - o) < (0.13 if k < 2 else 0.11) for k, o in enumerate(placed)): + continue + if name == JUICE: + # the 13 cm carton is taller than the hand when it grasps / releases: the Panda hand spans + # +-10.5 cm across the jaws, so keep the carton >= 17 cm from the cheese and the bowl; + # it must also not hide them from the front camera, and must stay >= 10 cm off the + # straight paths home->cheese, home->bowl and cheese->bowl + if np.linalg.norm(p - c) < 0.17 or np.linalg.norm(p - bowl) < 0.17: + continue + if any(p[0] > t[0] - 0.03 and abs(p[1] - t[1]) < 0.14 for t in (c, bowl)): + continue + if any(_seg_dist(p, a, b) < 0.10 for a, b in ((c, bowl), (HOME_XY, c), (HOME_XY, bowl))): + 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 + psi = float(rng.uniform(-CHEESE_YAW_MAX, CHEESE_YAW_MAX)) + n = np.array([-np.sin(psi), np.cos(psi)]) # jaw-closing direction for a grasp across the cheese + l = np.array([np.cos(psi), np.sin(psi)]) + r = rng.uniform(R_MIN, R_MAX) + th = rng.uniform(0, 2 * np.pi) + b = np.array([r * np.cos(th), r * np.sin(th)]) + return dict(seed=int(seed), cheese_xy=c.round(5).tolist(), cheese_yaw=psi, bowl_xy=bowl.round(5).tolist(), + distractors=dis, bias=[float(b[0]), float(b[1]), 0.0], bias_r=float(r), bias_theta=float(th), + bias_across=float(b @ n), bias_along=float(b @ l)) + + def apply_instance(self, inst): + set_gripper_stroke(self.env, GRIPPER_MAX_OPEN) + for name, mass in MASS.items(): + envs.scale_mass(self.env, name, mass) + self._place(CHEESE, inst["cheese_xy"], inst["cheese_yaw"]) + self._place(BOWL, inst["bowl_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 = TrackedSkills(self.env, bias=self.skill_bias(inst), recorder=recorder) + self.start_pos = {n: envs.obj_pos(self.env, n) for n in ALL} + return self.sk + + # ------------------------------------------------------------ outcome + def in_bowl(self): + k = envs.obj_pos(self.env, BOWL) + c = envs.obj_pos(self.env, CHEESE) + base = envs.obj_min_z(self.env, BOWL) + return bool(np.linalg.norm(c[:2] - k[:2]) < BOWL_R_IN and c[2] < base + BOWL_RIM + and envs.obj_upright_cos(self.env, BOWL) > 0.9 and base < envs.TABLE_Z + 0.01) + + def outcome(self, inst): + envs.settle(self.env, 40) + sk = self.sk + k = envs.obj_pos(self.env, BOWL) + c = envs.obj_pos(self.env, CHEESE) + held = sk.holding(CHEESE) + success = bool(self.in_bowl() and not held) + picked = sk.cheese_zmax > sk.cheese_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 = c[:2] - k[:2] + moved = {n: float(np.linalg.norm(envs.obj_pos(self.env, n)[:2] - self.start_pos[n][:2])) + for n in DISTRACTORS} + out = dict(success=success, picked=bool(picked), held_at_end=bool(held), + cheese_end=c.round(4).tolist(), bowl_end=k.round(4).tolist(), end_offset=end_off.round(4).tolist(), + grasp_offset=None, release_offset=None, touched_at_close=None, + distractors_moved_cm={n: round(100 * v, 1) for n, v in moved.items()}) + grasp_txt = "" + if last_close is not None: + go = np.array(last_close["eef"][:2]) - np.array(last_close["cheese_ref"][:2]) + out["grasp_offset"] = go.round(4).tolist() + out["touched_at_close"] = last_close["touching"] + out["cheese_pushed_cm"] = round(100 * float(np.linalg.norm( + np.array(last_close["cheese"][:2]) - np.array(last_close["cheese_ref"][:2]))), 1) + grasp_txt = (f"The gripper closed {dir_words(*go)} of the centre of the cream cheese (measured where " + f"the cheese was before the fingers touched it)") + if releases: + r = releases[-1] + out["release_offset"] = (np.array(r["cheese"][:2]) - np.array(r["bowl"][:2])).round(4).tolist() + if success: + out["failure"] = None + detail = "The cream cheese is in the bowl." + 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 cream cheese was not picked up." + else: + on = [NAMES[n] for n in last_close["touching"] if n != CHEESE] + why = "" + if on: + why = (f" A finger landed on top of the {' and the '.join(on)} instead of going down beside the " + f"cheese, so the jaws closed above the cheese.") + elif CHEESE in last_close["touching"] and not sk.holding(CHEESE): + why = " A finger came down on top of the cream cheese instead of beside it." + elif not last_close["touching"] and last_close.get("cheese_top") is not None: + above = last_close["eef"][2] - envs.FINGERTIP_BELOW_SITE - last_close["cheese_top"] + if above > 0.002: # closed in the air, entirely above the cheese + why = (f" The fingers closed in the air without touching anything: the fingertips were " + f"{100 * above:.1f} cm above the top of the cream cheese.") + detail = f"{grasp_txt} and did not pick it up.{why} The cream cheese is still on the table." + elif held: + out["failure"] = "not_released" + detail = f"{grasp_txt} and picked it up, but the cream cheese is still in the gripper." + elif releases: + out["failure"] = "missed_place" + detail = (f"{grasp_txt} and picked it up. When the gripper opened, the cream cheese was " + f"{dir_words(*out['release_offset'])} of the bowl's centre; it did not end up in the bowl " + f"(it is now {dir_words(*end_off)} of the bowl's centre).") + else: + out["failure"] = "dropped" + detail = (f"{grasp_txt} and picked it up, but it slipped out of the gripper before it was released; " + f"it is now {dir_words(*end_off)} of the bowl's centre.") + out["detail"] = detail + ind = detail + for k in (JUICE, "chocolate_pudding_1", "butter_1", CHEESE, BOWL): # longest names first + ind = ind.replace(NAMES[k], DESCR[k]) + out["detail_indirect"] = ind + return out + + def feedback(self, inst, out, level="F2", indirect=False): + """F0: nothing, F1: success flag, F2: measured offsets. `indirect` uses descriptive object names.""" + 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 across the cheese's short side, carry, release above the bowl. + params['offset'] (xy) is the policy's own correction, added to every commanded position.""" + sk = self.sk + off = np.array(params.get("offset", [0.0, 0.0]), float) + c = envs.obj_pos(self.env, CHEESE) # perfect perception of the current scene + yaw = self.grasp_yaw() + k = envs.obj_pos(self.env, BOWL) + z_rel = envs.obj_min_z(self.env, BOWL) + BOWL_RIM + RELEASE_ABOVE_RIM + g, p = c[:2] + off, k[:2] + off + sk.set_gripper(False, steps=8) + sk.move_to([g[0], g[1], Z_CARRY], yaw=yaw) # approach from above, clear of the 13 cm carton + sk.move_to([g[0], g[1], Z_GRASP + 0.08], tol=0.002) + sk.move_to([g[0], g[1], Z_GRASP], tol=0.003, max_steps=80) + sk.set_gripper(True, steps=15) + sk.move_to([g[0], g[1], Z_CARRY], speed=0.3) + if not sk.holding(CHEESE): # 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 grasp_yaw(self): + """Gripper yaw that closes the jaws across the cheese's short side (yaw 0 closes along world y).""" + xmat = self.env.sim.data.body_xmat[envs.body_id(self.env, CHEESE)].reshape(3, 3) + a = np.arctan2(xmat[1, 0], xmat[0, 0]) # direction of the cheese's long (x) axis + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + def default_params(self, inst): + return dict(offset=[0.0, 0.0]) + + def oracle_params(self, inst): + return dict(offset=(-np.array(inst["bias"][:2])).tolist()) + + def adapt_params(self, inst, history): + """Scripted F2 learner: the reported grasp offset (where the gripper closed relative to the cheese's + centre) measures the calibration offset; accumulate it into the correction subtracted from every + commanded position. If the gripper never closed, fall back to the release offset.""" + last = history[-1] + off = np.array(last["params"]["offset"], float) + o = last["outcome"] + if o.get("grasp_offset") is not None: + off = off - np.array(o["grasp_offset"]) + elif o.get("release_offset") is not None: + off = off - np.array(o["release_offset"]) + return dict(offset=off.round(4).tolist()) + + blind_sigma = 0.005 + + def blind_params(self, inst, attempt, rng): + """Retry the same plan with a small random perturbation of the targets; no use of history.""" + return dict(offset=rng.normal(0.0, self.blind_sigma, 2).round(4).tolist()) diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py new file mode 100644 index 0000000000000000000000000000000000000000..542d519109d1f085f749fe2db4dd0c20b51281b5 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_clear_cover.py @@ -0,0 +1,657 @@ +"""LH clear_cover: sort four cubes into two open boxes by colour -- but in half of the instances one box is covered by a +loose clear acrylic lid. A cube carried over that box and released stops on the lid at rim height; it is not in the box. + +Family: long-horizon self-disturbance / common sense ("state_restoration"; design P2-2 in +research_notes/P1P2_加深与常识任务设计.md): four pick-and-place stages that are each easy for a frontier model; the +trap is a commonsense one -- "a box can have a transparent lid" -- and the failure is only visible from the right +viewpoint: from the side (agentview) the cube visibly sits on top of the box, at rim height, with the box floor visible +below it; from straight above (the wrist camera) it lies inside the box's outline and looks almost the same as a cube +that is inside (design rule R5: a top-down view hides height differences). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * two open boxes (fixtures; inside 12 x 12 cm, walls 5 cm high and 8 mm thick, rim 5.6 cm above the table, light + floor) with red and with blue walls, centres at x in [-0.14, -0.08], y = +-(0.12-0.14) (24-28 cm apart); which + colour is on the left is random. The instruction names the boxes by colour, not "left / right" (the design draft's + wording), so that no failure comes from whose left is meant; + * four 4 cm cubes (38 g), two red and two blue, in a row in front of the boxes (x = -0.33, near the robot; 14 cm + apart, shuffled, yaw +-23 deg); + * the clear lid (covered instances only): a loose 13.4 x 13.4 cm, 8 mm clear plate lying on one box's walls, + 1 mm inside their outer faces (no overhang). v2 (2026-10-13, after the Sonnet pilot np_lh_clear_cover): rendered + nearly invisible -- alpha 0.03, matte (no specular glint), no edge highlight (v1: alpha 0.10 + bright edges, and the + pilot agent named "the transparent lid" from the first images); heavy (1 kg; mass is not visible) with friction 1.0 + and priority for all its contacts and medium-stiff contacts, so incidental contact by the hand does not knock it off + (v1, 0.12 kg / mu 0.3 / 6 mm overhang / very stiff contacts: a probe descent between the boxes knocked it off in the + pilot's very first motions). Transparent geoms do not write MuJoCo's depth buffer: in the depth maps + (--perception rgbd) the lid is not there at all. In uncovered instances the lid is parked on the floor far outside + the workspace and the cameras' view. + +Hidden variable: whether a box is covered and which one. Exactly 10 of every 20 consecutive seeds are covered (5 red / +5 blue box): (seed * 7) mod 20 < 10, like lh_lid_box's balanced blocks. + +Why the natural plan fails: carry each cube over its box and release it a few cm above the rim. Over the covered box the +cube lands on the lid and stays there (v2, measured: drops of 1-8 cm, 48/48 stay on the lid, the lid does not move; +pressing a held cube down towards the box floor stops the arm 4.2 cm above the target, the lid moves <= 0.8 mm, 12/12 +still covering). After the release the cube visibly sits on top of the box in agentview (its bottom 0.8 cm above the +rim, the box floor visible below it); checking only from above it looks as if it were in the box (~1.3x bigger). +What must be learned: look from the side / compare heights before finishing, notice the cubes resting at rim height, +remove the lid (push its edge horizontally with the closed gripper, fingertips between the rim and the lid's top face -- +what the pilot agent did when it saw the v1 lid) and put the cubes in (within the attempt), or check for a lid and +remove it before placing anything (across attempts). Pressing the fingertips onto the lid and dragging no longer moves +it (v2: hand friction = rim friction, by design, because a hand landing on the lid while moving sideways is exactly +what knocked the v1 lid off). +Measured, 2 covered instances x 86 Sonnet-like incidental motions (probe descents to 2-5 cm next to / between the +boxes, transits at 11-20 cm over the covered box, low lateral moves next to the boxes): the box got uncovered 1/172 +(v1: 57/172), the lid moved > 2 cm 20/172 (v1: 97/172); a crash sweep through the boxes at 3 cm still knocks it (1/2). +Deliberate edge push, agent-style commands: fingertip target 2-10 mm below the lid's top face 10/10 (+ 8/8 in the +parameter sweep), at the top face 1/2, above it 0/2. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the +cavity of the box of its colour -- centre inside the cavity, lowest point below the rim --, nothing held, the lid not on +a box, scene static) plus a per-step event log (cube stages achieved / lost / restored, rested_on_cover, left_cover, +cover_removed, cover_on_box, in_wrong_box) 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, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +Z = envs.TABLE_Z +TIP = envs.FINGERTIP_BELOW_SITE +# ---------------------------------------------------------------- geometry / physics +CUBE_E = 0.04 +CUBE_DENS = 600.0 # -> 38 g +BOX_IN = 0.06 # inner half width (12 x 12 cm cavity) +WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.05 +BOX_OUT = BOX_IN + WALL_T +RIM = FLOOR_T + WALL_H # rim height above the table +WALL_MU = 0.3 # walls (cube contacts; the lid's own friction has priority in its contacts) +LID_T = 0.008 # thick enough that a horizontal push at 'lid height' finds its edge (v1 draft: 4 mm, see the card) +LID_HALF = BOX_OUT - 0.001 # v2: no overhang (1 mm inside the walls' outer faces): a hand landing on its edge cannot tip it +LID_MASS = 1.0 # v2: heavy (a thick glass-like plate; mass is not visible): incidental bumps move it much less +LID_MU = 1.0 # v2: with priority, used for ALL lid contacts (rim, hand, fingers, cubes): pressing on the lid and moving +# sideways cannot drag it (hand friction == rim friction, and the rim also carries the lid's weight) +LID_SOLREF = (0.005, 1.0) # v2: medium-stiff contacts (v1 used _SOLID: a finger that caught the lid's edge while the +LID_SOLIMP = (0.95, 0.99, 0.001) # arm pressed on could squeeze it against the wall and launch it 16-37 cm) +LID_TOP = RIM + LID_T # lid top surface above the table when it lies on a box +LID_RGBA = (0.85, 0.90, 0.95, 0.03) # v2: near-invisible, no edge highlight, no specular (material below) +PARK = (0.0, 1.4) # lid parked on the floor (world z = 0), out of reach and out of view (uncovered instances) + +COLORS = ("red", "blue") +CUBE_RGBA = dict(red=(0.88, 0.10, 0.08, 1.0), blue=(0.10, 0.25, 0.88, 1.0)) +WALL_RGBA = dict(red=(0.72, 0.26, 0.22, 1.0), blue=(0.22, 0.34, 0.72, 1.0)) +FLOOR_RGBA = (0.86, 0.85, 0.82, 1.0) +CUBES = [f"{c}_cube_{i}" for c in COLORS for i in (1, 2)] +BOXES = {c: f"{c}_box_1" for c in COLORS} +LID = "clear_lid_1" + +IN_MARGIN = 0.010 # a cube counts as in a box if its centre is within BOX_IN - IN_MARGIN of the box centre (each axis) +BELOW_RIM = 0.005 # ... and its lowest point is at least this far below the rim +Z_CARRY = 0.15 # scripted transit height of the grasp point above the table (Sonnet: 11-20 cm) +DROP = 0.04 # scripted release: cube bottom this far above the rim (Sonnet-like 3-5 cm) +SLOT = 0.028 # two cubes per box: +-2.8 cm from the centre along y +PUSH_DEPTH = 0.004 # scripted edge push: fingertips this far below the lid's top face (lid 8 mm thick) +PUSH_SPEED = 0.06 + + +def _color(name): + return name.split("_")[0] + + +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'}" + + +def box_xml_cc(name, wall_rgba): + """open-top box, body origin at the centre of its footprint on the table (z = 0 = table top)""" + o = BOX_OUT + parts = [((0, 0, FLOOR_T / 2), (o, o, FLOOR_T / 2), FLOOR_RGBA, 1.0), + ((BOX_IN + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((-BOX_IN - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, o, RIM / 2), wall_rgba, WALL_MU), + ((0, BOX_IN + WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU), + ((0, -BOX_IN - WALL_T / 2, RIM / 2), (BOX_IN, WALL_T / 2, RIM / 2), wall_rgba, WALL_MU)] + g = [] + for k, (p, s, c, mu) in enumerate(parts): + g.append(f' ') + g.append(f' ') + return f""" + + + +{chr(10).join(g)} + + + + + + +""" + + +def lid_xml(name): + """clear plate: one collision box + a near-invisible visual twin with a matte material (no specular glint)""" + h, t = LID_HALF, LID_T / 2 + g = [f' ', + f' '] + xml = _wrap(name, "\n".join(g), t, float(np.hypot(h, h))) + mat = (f' \n \n \n') + return xml.replace(" ", mat + " ", 1) + + +class CoverSkills(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 ClearCover(LFFTask): + name = "lh_clear_cover" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Reason", "Plan", "Utilize") + protocol = "cross" + max_attempts = 3 + # careful oracle: 4 pick-and-places (~7 commands each = 28) + pushing the lid off (~5) + looking around (~15); + # one recovery: pushing the lid off + re-placing the cubes that were on it (~5 + 2 x 7) -> ~70; Sonnet looks after + # every step and calibrates the wrist camera (cla4: 10+ observe / probe commands) + agent_max_steps = 110 + instruction = "Put the two red cubes into the red box and the two blue cubes into the blue box." + instruction_indirect = "Sort the four small cubes by colour: each cube goes into the box whose walls have its colour." + agent_object_names = ["red cube", "red cube", "blue cube", "blue cube", "red box", "blue box"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + objs, fx = [], [] + for j, c in enumerate(COLORS): + bx = register_generated(f"LffCc{c.title()}Box", box_xml_cc(f"lff_cc_{c}_box", WALL_RGBA[c]), free=False) + fx.append((BOXES[c], bx, f"{c}_box_region", (-0.12, 0.12 - 0.26 * j, -0.10, 0.14 - 0.26 * j))) + k = 0 + for c in COLORS: + for i in (1, 2): + ab = "AB"[i - 1] + cat = register_generated(f"LffCc{c.title()}Cube{ab}", + box_xml(f"lff_cc_{c}_cube_{ab.lower()}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], + density=CUBE_DENS)) + objs.append((f"{c}_cube_{i}", cat, f"{c}_cube_{i}_region", + (-0.34, -0.22 + 0.14 * k, -0.32, -0.20 + 0.14 * k))) + k += 1 + lid = register_generated("LffCc2ClearLid", lid_xml("lff_cc2_clear_lid")) + objs.append((LID, lid, "lid_region", (0.20, -0.01, 0.22, 0.01))) + return write_bddl(self.name, "put the cubes into the boxes of their colour", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + self.box_bid = {c: m.body_name2id(self.env.fixtures_dict[BOXES[c]].root_body) for c in COLORS} + self.lid_gids = set(envs.obj_geom_ids(self.env, LID)) + self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES} + self.robot_gids = 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 = float(rng.uniform(-0.13, -0.09)) + left = str(rng.choice(COLORS)) + boxes = {} + for c in COLORS: + s = 1.0 if c == left else -1.0 + boxes[c] = [bx + float(rng.uniform(-0.01, 0.01)), s * float(rng.uniform(0.12, 0.14))] + slots = [-0.21, -0.07, 0.07, 0.21] + perm = rng.permutation(4) + start = {CUBES[i]: [float(-0.33 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + # balanced like lh_lid_box: exactly 10 of every 20 consecutive seeds covered (5 red box, 5 blue box) + r = (int(seed) * 7) % 20 + cover = "red" if r < 5 else ("blue" if r < 10 else None) + return dict(seed=int(seed), boxes=boxes, left_box=left, start=start, + start_yaw={k: float(rng.uniform(-0.4, 0.4)) for k in CUBES}, cover=cover, + cover_side=(None if cover is None else ("left" if cover == left else "right")), + lid_off=[float(v) for v in rng.uniform(-0.004, 0.004, 2)], lid_yaw=float(rng.uniform(-0.05, 0.05))) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for c in COLORS: + m.body_pos[self.box_bid[c]] = [inst["boxes"][c][0], inst["boxes"][c][1], Z] + m.body_quat[self.box_bid[c]] = [1.0, 0.0, 0.0, 0.0] + for name, xy in inst["start"].items(): + envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name]) + if inst["cover"]: + b = inst["boxes"][inst["cover"]] + envs.set_obj_pose(self.env, LID, [b[0] + inst["lid_off"][0], b[1] + inst["lid_off"][1], + Z + RIM + LID_T / 2 + 0.0005], yaw=inst["lid_yaw"]) + else: + envs.set_obj_pose(self.env, LID, [PARK[0], PARK[1], LID_T / 2 + 0.002]) + envs.set_friction(self.env, LID, LID_MU, priority=2) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = CoverSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def cube_rel(self, name, color): + return envs.obj_pos(self.env, name)[:2] - np.asarray(self.inst["boxes"][color]) + + def in_box(self, name, color, margin=IN_MARGIN): + """centre inside the cavity (per axis), lowest point below the rim, not held""" + rel = self.cube_rel(name, color) + return bool(np.max(np.abs(rel)) <= BOX_IN - margin and envs.obj_min_z(self.env, name) < Z + RIM - BELOW_RIM + and not self.held(name)) + + def where_box(self, name): + for c in COLORS: + if self.in_box(name, c): + return c + return None + + def lid_pos(self): + return envs.obj_pos(self.env, LID) + + def covering(self): + """colour of the box the lid lies on (centre within the box's outer footprint + 1 cm, above the floor), or None""" + p = self.lid_pos() + for c in COLORS: + rel = np.abs(p[:2] - np.asarray(self.inst["boxes"][c])) + if rel[0] <= BOX_OUT + 0.01 and rel[1] <= BOX_OUT + 0.01 and p[2] > Z + 0.02: + return c + return None + + def _touching(self, gids_a, gids_b): + return envs.contacts_between(self.env, gids_a, gids_b) + + def on_cover(self, name, moving_ok=False): + """the cube rests on the lid while the lid lies on a box (contact, not held, slow -- unless `moving_ok`: the + monitor keeps a cube that came to rest on the lid "on" while it rides along with the lid being pushed)""" + if self.covering() is None or self.held(name): + return False + if not self._touching(self.cube_gids[name], self.lid_gids): + return False + if moving_ok: + return True + _, da = envs.free_joint_addr(self.env, name) + return bool(np.linalg.norm(self.env.sim.data.qvel[da:da + 3]) < 0.05) + + def stage_values(self): + v = {f"{n}_in_box": self.in_box(n, _color(n)) for n in CUBES} + v["cover_off_boxes"] = self.covering() is None + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(step=0, state={f"{n}_in_box": False for n in CUBES}, ever=set(), lost=set(), events=[], + on_cover={n: False for n in CUBES}, cover=self.covering(), wrong={n: None for n in CUBES}, + last_touch={n: None for n in CUBES}, rested=[], cover_removed_step=None) + + def _touches(self): + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for n, g in self.cube_gids.items(): + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.robot_gids: + out[n] = "robot" + elif other in self.lid_gids and out.get(n) != "robot": + out[n] = "lid" + return out + + 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"] + for n, who in self._touches().items(): + if who == "robot": + mon["last_touch"][n] = step + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + cov = self.covering() + if cov != mon["cover"]: + if mon["cover"] is not None and cov is None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_removed", box=mon["cover"])) + mon["cover_removed_step"] = step + elif cov is not None: + mon["events"].append(dict(step=step, pred="cover", ev="cover_on_box", box=cov)) + mon["cover"] = cov + for n in CUBES: + oc = self.on_cover(n, moving_ok=mon["on_cover"][n]) + if oc != mon["on_cover"][n]: + mon["on_cover"][n] = oc + if oc: + mon["rested"].append(dict(step=step, cube=n)) + mon["events"].append(dict(step=step, pred=f"{n}_on_cover", ev="rested_on_cover" if oc else "left_cover", + cube=n, box=cov)) + key = f"{n}_in_box" + was = mon["state"][key] + now = self.in_box(n, _color(n), IN_MARGIN if not was else IN_MARGIN - 0.005) + if now != was: + self._event(key, now, step, n) + other = [c for c in COLORS if c != _color(n)][0] + wr = other if self.in_box(n, other) else None + if wr != mon["wrong"][n]: + mon["wrong"][n] = wr + if wr: + mon["events"].append(dict(step=step, pred=key, ev="in_wrong_box", cube=n, box=wr)) + + def _event(self, key, now, step, n): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + return + if self.held(n): + cause = "picked_up" + else: + lt = mon["last_touch"][n] + cause = "robot" if lt is not None and step - lt <= 60 else "other" + mon["lost"].add(key) + mon["events"].append(dict(step=step, pred=key, ev="lost", cause=cause)) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in CUBES + [LID]: + _, da = envs.free_joint_addr(self.env, name) + 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 outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in CUBES if self.held(n)] + on_cover = [n for n in CUBES if self.on_cover(n)] + wrong = [n for n in CUBES if not vals[f"{n}_in_box"] and self.where_box(n) is not None] + missing = [n for n in CUBES if not vals[f"{n}_in_box"]] + cov = self.covering() + success = bool(all(vals.values()) and static and not held) + failure = None + if not success: + failure = ("held" if held else "cube_on_cover" if on_cover else "wrong_box" if wrong else + "cube_not_in_box" if missing else "cover_on_box" if cov is not None else "not_static") + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + rested_cubes = sorted({r["cube"] for r in mon["rested"]}) + parts = [] + if success: + parts.append("All four cubes are in the boxes of their colour.") + for n in missing: + c = _color(n) + txt = f"A {c} cube is not in the {c} box: " + if n in held: + parts.append(txt + "it is still held by the gripper.") + continue + p = envs.obj_pos(self.env, n) + rel = self.cube_rel(n, c) + if n in on_cover: + txt += (f"it rests on a clear acrylic lid that lies on the {cov} box, " + f"{100 * (envs.obj_min_z(self.env, n) - Z - FLOOR_T):.1f} cm above the box floor") + elif self.where_box(n) is not None: + txt += f"it is in the {self.where_box(n)} box" + else: + h = envs.obj_min_z(self.env, n) - Z + txt += ("it lies on the table" if h < 0.005 else f"it lies {100 * h:.1f} cm above the table") + txt += f", its centre {_fb(rel[0])} and {_lr(rel[1])} of the {c} box's centre" + if n in rested_cubes and n not in on_cover: + txt += " (it had come to rest on the clear lid earlier)" + parts.append(txt + ".") + if cov is not None: + parts.append(f"A clear acrylic lid lies on the {cov} box.") + if not static and all(vals.values()) and not held: + parts.append("Something was still moving at the end.") + if mon["cover_removed_step"] is not None and cov is None: + parts.append("The clear lid was pushed off its box.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + covered=inst["cover"], trap_fired=bool(mon["rested"]), n_rested_on_cover=len(mon["rested"]), + rested_cubes=rested_cubes, cover_removed=mon["cover_removed_step"] is not None, + cover_removed_step=mon["cover_removed_step"], cover_final=cov, on_cover_final=on_cover, + recovered_in_attempt=bool(mon["rested"]) and success, + cube_offsets_cm={n: (100 * self.cube_rel(n, _color(n))).round(1).tolist() for n in CUBES}, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) + + def _finger_axis(self, yaw): + """world xy direction along which the fingers close at gripper yaw `yaw` (Skills: yaw 0 = fingers along y)""" + return np.array([-np.sin(yaw), np.cos(yaw)]) + + def _clear_yaw(self, name, room=0.04): + """grasp yaw of the cube: the smallest wrist turn (within +-45 deg) unless one of the open fingertips (4.5 cm + either side) would come down within `room` of another cube's centre (cubes put side by side or pushed off on + the lid stand 1.5-2.5 cm apart); then the 90-deg turned grasp if it has more room""" + p = envs.obj_pos(self.env, name)[:2] + others = [envs.obj_pos(self.env, n)[:2] for n in CUBES if n != name] + + def dmin(yaw): + a = self._finger_axis(yaw) + return min([np.linalg.norm(t - o) for t in (p + a * 0.045, p - a * 0.045) for o in others] or [1.0]) + + y0 = self._grasp_yaw(name) + if dmin(y0) >= room: + return y0 + y1 = float((y0 + np.pi / 2 + np.pi / 2) % np.pi - np.pi / 2) + return y1 if dmin(y1) > dmin(y0) else y0 + + def pick(self, name, z_carry=Z_CARRY): + sk = self.sk + p = envs.obj_pos(self.env, name) + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, p[2] - Z + 0.06)], yaw=self._clear_yaw(name)) + sk.move_to([p[0], p[1], p[2]], tol=0.003, max_steps=120) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + return True + + def place_in(self, name, slot, drop=DROP, z_carry=Z_CARRY, noise=None): + """carry the held cube over its box (slot -1 / +1: 2.8 cm right / left of the centre) and release it with its + bottom `drop` above the rim""" + sk = self.sk + b = np.asarray(self.inst["boxes"][_color(name)], float) + d = b + [0.0, SLOT * slot] + (np.asarray(noise, float) if noise is not None else 0.0) + z_rel = Z + RIM + drop + CUBE_E / 2 + sk.move_to([d[0], d[1], Z + z_carry], yaw=0.0) + sk.move_to([d[0], d[1], z_rel], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], Z + z_carry]) + + def pick_place(self, name, slot, drop=DROP, noise=None): + if self.pick(name): + self.place_in(name, slot, drop=drop, noise=noise) + return True + return False + + def remove_cover(self, direction=None, depth=PUSH_DEPTH, mode="edge"): + """push the lid off its box: closed gripper, fingertips `depth` below the lid's top face, start 3 cm outside + its near edge (mode "edge") or 3 cm inside it, pressing on the lid (mode "press": press and drag -- v2: does not + move the lid any more, see the module docstring), sweep + straight on until the lid has cleared the box (default: sideways, away from the other box), lift""" + cov = self.covering() + if cov is None: + return False + sk = self.sk + lp = self.lid_pos() + b = np.asarray(self.inst["boxes"][cov], float) + if direction is None: + o = np.asarray(self.inst["boxes"][[c for c in COLORS if c != cov][0]], float) + direction = (0.0, float(np.sign(b[1] - o[1]))) + d = np.asarray(direction, float) / np.linalg.norm(direction) + back = LID_HALF + 0.03 if mode == "edge" else LID_HALF - 0.03 + s = lp[:2] - d * back + top = lp[2] + LID_T / 2 + z = top - depth + TIP + sk.set_gripper(True, steps=8) + sk.move_to([s[0], s[1], z + 0.08], yaw=float(np.arctan2(d[1], d[0]) - np.pi / 2)) + sk.move_to([s[0], s[1], z], tol=0.003, max_steps=80) + # sweep until the lid's near edge is 3 cm beyond the box's far wall + need = float((b - lp[:2]) @ d) + BOX_OUT + back + 0.03 + e = s + d * need + sk.move_to([e[0], e[1], z], speed=PUSH_SPEED, tol=0.006, max_steps=int(need / PUSH_SPEED / 0.05) + 80) + sk.move_to([e[0], e[1], z + 0.10], speed=0.2) + sk.set_gripper(False, steps=8) + sk.hold(10) + return self.covering() is None + + def slots(self, order): + """slot of each cube: the first cube of a colour goes right of the centre, the second left""" + seen, out = {c: 0 for c in COLORS}, {} + for n in order: + out[n] = (-1, 1)[seen[_color(n)] % 2] + seen[_color(n)] += 1 + return out + + def wrist_fix(self, rounds=1): + """what a top-down check can see: cubes whose centre is not over the right box's outline (on the table, in + the other box, still held) get placed again; heights are not judged""" + for _ in range(rounds): + bad = [] + for n in CUBES: + rel = self.cube_rel(n, _color(n)) + if self.held(n) or np.max(np.abs(rel)) > BOX_OUT: + bad.append(n) + if not bad: + return + for n in bad: + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + self.pick_place(n, -1 if self.cube_rel(n, _color(n))[1] < 0 else 1) + + def set_aside(self, name): + """pick the cube (e.g. off the lid) and put it down on the table where it started (that spot is free)""" + if not self.pick(name): + return False + sk = self.sk + x, y = self.inst["start"][name] + sk.move_to([x, y, Z + Z_CARRY], yaw=0.0) + sk.move_to([x, y, Z + CUBE_E / 2 + 0.004], tol=0.003, max_steps=120) + sk.set_gripper(False, steps=12) + sk.move_to([x, y, Z + Z_CARRY]) + return True + + def side_fix(self, rounds=2): + """the careful check (agentview / heights): every cube must be inside its box, below the rim; if cubes rest on + a lid (or a lid lies on a box): take the cubes off the lid (v2: the heavy lid cannot be pushed off with cubes + standing on it -- the hand runs into them), push the lid off; then place every cube that is not in its box""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + if not v["cover_off_boxes"]: + for n in CUBES: + if self.on_cover(n) or (self.covering() is not None and self._touching(self.cube_gids[n], self.lid_gids)): + self.set_aside(n) + self.remove_cover() + for n in CUBES: + if not self.in_box(n, _color(n)): + if self.held(n): + self.sk.set_gripper(False, steps=12) + continue + others = [m for m in CUBES if m != n and _color(m) == _color(n)] + rel_o = self.cube_rel(others[0], _color(n)) if others else np.zeros(2) + self.pick_place(n, 1 if rel_o[1] < 0 else -1) + return all(self.stage_values().values()) + + def execute(self, inst, params): + order = params.get("order") or list(CUBES) + noise = params.get("noise") or {} + drops = params.get("drops") or {} + if params["plan"] == "lid_first": + self.remove_cover(params.get("push_dir"), params.get("push_depth", PUSH_DEPTH), params.get("push_mode", "edge")) + sl = self.slots(order) + for n in order: + self.pick_place(n, sl[n], drop=drops.get(n, DROP), noise=noise.get(n)) + if params.get("check") == "side": + self.side_fix() + elif params.get("check") == "wrist": + self.wrist_fix() + self.sk.hold(10) + + def default_params(self, inst): + return dict(plan="naive", check="wrist") + + def oracle_params(self, inst): + return dict(plan="lid_first", check="side") + + def adapt_params(self, inst, history): + """from attempt 2 on: look for a lid and push it off first, then place, then check from the side""" + return dict(plan="lid_first", check="side") + + def blind_params(self, inst, attempt, rng): + """the natural plan again with small random variations (order, 5 mm placement noise, 3-5 cm drop), no history""" + order = [CUBES[i] for i in rng.permutation(len(CUBES))] + return dict(plan="naive", check="wrist", order=order, + noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES}, + drops={n: float(rng.uniform(0.03, 0.05)) for n in CUBES}) + + 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 = [] + 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(plan="naive", check="side") 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": # extra control (not in validate's table): cross-attempt learning only, no side check + params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check="wrist") + 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"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_lid_box.py b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_lid_box.py new file mode 100644 index 0000000000000000000000000000000000000000..f7c6c649bba53e7fa77a0539b7034c73eb0081f2 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/lh_lid_box.py @@ -0,0 +1,715 @@ +"""LH lid_box: put three blocks on their marks, then open a box, put a red cube in, close it -- the lid falls open onto +the marks behind the box and shoves the blocks standing there off their marks. + +Family: long-horizon self-disturbance ("state_restoration"): the agent's own normal later-stage action (opening the +lid) physically breaks earlier progress (blocks on marks); it has to notice and restore it before finishing (within an +attempt), or learn to open the box first (across attempts; the final-state judge does not enforce an order). + +Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y): + * a flat wooden box (fixture, 12 x 16 cm, walls 3.2 cm, lid 0.6 cm) whose lid is hinged along its far edge; a black + ball knob sticks out of the middle of the lid's front edge. The lid is heavy (0.3 kg) and has no damping: once it + is lifted past vertical it falls backward and comes to rest on a stop (hidden angle) or on whatever is behind the + box; + * three 6 cm cubes ("blocks", blue / green / yellow; light, 54 g, and slippery, mu 0.25) in a row in front of the box + together with a small red cube (2.2 cm); + * three square marks (7.6 cm, outline + light fill) in the blocks' colours: two right behind the box (their near + edge 0.2-1.7 cm from the box's back wall), one beside the box. + +Hidden variable: the lid's opening stop (0 = closed, 90 = upright, 180 = flat behind the box): "far", uniform in FAR +(138-165 deg), in 13 of every 20 consecutive seeds, else "near", uniform in NEAR (100-113 deg). Before the lid is opened +nothing shows it. A far lid lands on the top edge of the blocks standing behind the box and its weight shoves them +away from the robot ("forward") off their marks (measured: 4-10 cm); a near lid comes to rest above them. Stops of +~115-135 deg are left out on purpose: there the lid only grazes the blocks (1-3 cm, right at the tolerance). + +Why the natural order fails: the instruction lists the blocks first (as a user would), so the natural plan places the +blocks, opens the lid (it falls back onto them), puts the cube in, closes the lid and finishes without looking at the +marks again. What must be learned: re-check every stage before finishing and put knocked blocks back after closing the +lid (within the attempt), or open the box first / place the blocks behind it last (across attempts). + +Lid mechanics for agents (`LidSkills`, measured, see the task card): grasping the ball knob from above (fingers on its +left and right, the default yaw) makes a pivot -- the ball turns freely between the fingers about the hinge axis. While +the knob is held, the arm is compliant along the hinge constraint: a commanded straight move is projected onto the +knob's circle around the hinge (at most 1 cm per control step; ~0.07 m/s along the arc in the agent self-test), so +"up 10 cm, then back over the hinge, release" opens the lid and "up, then forward, release" closes it; a move that +makes no more progress ends early (like KeySkills' stalling wrist in l7_key_turn). Without the compliance, all 6 +typical straight-move sequences tried (prototype: this lid with a 2 cm stem, 2026-10-09) pulled the knob out of the +fingers and the lid fell shut; with an earlier, lighter lid only a 3-segment approximation of the arc opened it. + +Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (all blocks on +their marks, red cube in the box, lid closed, nothing held, 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 _SOLID, _fmt, _wrap, box_xml, register_generated +from ..skills import DT, Skills, _rot_err +from ..task_base import LFFTask, register_task + +# ---------------------------------------------------------------- geometry / physics +BOX = "box_1" +BOX_MODEL = "lff_lh_lid_box" +BOX_D, BOX_W = 0.12, 0.16 # outer depth (x) and width (y) +WALL_H, WALL_T, FLOOR_T = 0.032, 0.008, 0.006 +LID_T, LID_MASS = 0.006, 0.30 +KNOB_R, STEM_L = 0.013, 0.032 +HINGE_DAMP, HINGE_FRIC = 0.002, 0.002 +IN_X = BOX_D / 2 - WALL_T # inner half sizes of the cavity +IN_Y = BOX_W / 2 - WALL_T + +BLOCK = 0.06 # cube edge +BLOCK_DENS = 250.0 # -> 54 g +BLOCK_MU = 0.25 +CUBE_E = 0.022 # red cube edge +MARK_HALF = 0.038 +MARK_LINE = 0.004 +TOL = 0.020 # block centre within 2 cm (per axis) of its mark's centre +FLAT_COS = np.cos(np.radians(15.0)) +CUBE_MARGIN = 0.004 +LID_CLOSED = np.radians(4.0) +# hidden stop (deg): in a fraction P_FAR of the instances the lid opens far back, uniform in FAR (it lands on blocks +# standing behind the box and shoves them 4-10 cm), otherwise it stops near upright, uniform in NEAR (it comes to rest +# above them). Far / near is balanced per block of 20 consecutive seeds (13 / 7), see sample_instance. +# Bimodal on purpose: stops between ~115 and ~135 deg make the lid graze the blocks and push them 1-3 cm, i.e. right +# at the tolerance, which is neither a clean disturbance nor a clean no-disturbance (measured, see the task card). +P_FAR = 0.65 +FAR = (138.0, 165.0) +NEAR = (100.0, 113.0) +GAP_LO, GAP_HI = 0.002, 0.017 # near edge of a behind-mark to the box's back wall (block near face +0.8 cm further) + +COLORS = ("blue", "green", "yellow") +RGBA = dict(blue=(0.15, 0.30, 0.85, 1.0), green=(0.10, 0.60, 0.20, 1.0), yellow=(0.92, 0.76, 0.10, 1.0)) +BLOCKS = {c: f"{c}_block_1" for c in COLORS} +MARKS = {c: f"{c}_mark_1" for c in COLORS} +CUBE = "red_cube_1" + +Z_CARRY = 0.13 # scripted transit height of the grasp point above the table when carrying a block +Z_KNOB = WALL_H + LID_T / 2 # knob centre above the table with the lid closed +SMAX = 0.010 # max projected displacement command per control step while the knob is held +STALL = 12 + + +def box_lid_xml(name, body_rgba=(0.55, 0.38, 0.22, 1.0), lid_rgba=(0.70, 0.52, 0.32, 1.0), knob_rgba=(0.10, 0.10, 0.11, 1.0)): + hx, hy = BOX_D / 2, BOX_W / 2 + parts = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)), + ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)), + ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)), + ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))] + g = [] + # box: contype 2 / conaffinity 1 and lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the + # hinge limit holds it closed), but both collide with the robot, the table and the free objects (contype 1) + for k, (pos, s) in enumerate(parts): + g.append(f'') + g.append(f'') + m, L = LID_MASS, BOX_D + lid_c = (-L / 2, 0, LID_T / 2) + lid_s = (L / 2, hy, LID_T / 2) + stem = (-L - STEM_L / 2, 0, LID_T / 2) + ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2) + lid = [f'', + # placeholder range: the opening stop is set per instance (apply_instance) + f'', + f'', + f'', + f'', + f'', + f'', + f''] + shell = "\n ".join(g) + lid_xml = "\n ".join(lid) + return f""" + + + + {shell} + + {lid_xml} + + + + + + + +""" + + +def mark_xml(name, rgba): + """Flat, visual-only square drawn on the table: a light fill plus an outline in the block's colour.""" + fill = tuple(0.55 + 0.45 * c for c in rgba[:3]) + (1.0,) + o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE + parts = [((0, 0, 0.0004), (o, o, 0.0004), fill), + ((0, i + w / 2, 0.0010), (o, w / 2, 0.0002), rgba), + ((0, -i - w / 2, 0.0010), (o, w / 2, 0.0002), rgba), + ((i + w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba), + ((-i - w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba)] + g = "\n".join(f' ' for p, sz, c in parts) + return _wrap(name, g, 0.0012, o) + + +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 LidSkills(Skills): + """Skills for the lid box: a per-step stage monitor, and a hinge-compliant arm while the knob is held (see the + module docstring).""" + + def __init__(self, env, task, recorder=None): + super().__init__(env, recorder=recorder) + self.task = task + self.latched = False + self.rad0 = None + self.y0 = None + self.knob_steps = 0 # control steps driven with the knob held (compliant mode) + self.knob_grasps = 0 + + def holding_knob(self): + """both fingers (pad or finger body) touch the knob ball or its stem""" + 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=self.task.knob_geom_names)) + + def _act(self, dpos, drot, grip): + if self.latched: + e = self.eef_pos() + if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035: + self.latched = False # opened, or the knob slipped out of the fingers + else: + hx, hz = self.task.hinge_xz() + r = np.array([e[0] - hx, e[2] - hz]) + rn = max(float(np.linalg.norm(r)), 1e-6) + tng = np.array([-r[1], r[0]]) / rn + s = float(np.clip(dpos[0] * tng[0] + dpos[2] * tng[1], -SMAX, SMAX)) + corr = (self.rad0 - rn) * r / rn + dpos = np.array([s * tng[0] + corr[0], self.y0 - e[1], s * tng[1] + corr[1]]) + self.knob_steps += 1 + super()._act(dpos, drot, grip) + self.task.monitor_step() + + def set_gripper(self, close, steps=15): + rep = super().set_gripper(close, steps) + if close and self.holding_knob(): + e = self.eef_pos() + hx, hz = self.task.hinge_xz() + self.latched = True + self.rad0 = float(np.hypot(e[0] - hx, e[2] - hz)) + self.y0 = float(e[1]) + self.knob_grasps += 1 + elif not close: + self.latched = False + return rep + + def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True): + """Skills.move_to plus an early stop when the knob is held and the arm has stopped making progress.""" + 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) + R = self._R() + p0 = self.eef_pos() + dist = np.linalg.norm(tgt - p0) + direction = (tgt - p0) / max(dist, 1e-9) + s = 0.0 + hist = [] + stalled = False + 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 + self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + cur = self.eef_pos() + if np.linalg.norm(tgt - cur) < tol and (speed is None or s >= dist): + break + hist.append(cur) + if (self.latched and len(hist) > STALL and (speed is None or s >= dist) + and np.linalg.norm(hist[-1] - hist[-1 - STALL]) < 0.002): + stalled = True + break + 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=stalled) + self.log.append(rep) + return rep + + +@register_task +class LidBox(LFFTask): + name = "lh_lid_box" + level = "L2" + category = "state_restoration" + capabilities = ("Perceive", "Plan", "Reason", "Utilize") + protocol = "cross" + max_attempts = 3 + agent_max_steps = 110 # careful oracle ~45-55 commands + restoring two blocks (~14) + looking around + instruction = ("Put each of the three coloured blocks on the square mark of the same colour on the table. Then open " + "the lid of the wooden box (lift it by the black knob on its front edge), put the red cube inside " + "the box, and close the lid.") + instruction_indirect = ("Set the blue, green and yellow cubes onto the outlined squares of matching colour. Then open " + "the flat wooden case (its lid lifts by the black ball at the front), place the small red " + "cube in it and shut the lid.") + agent_object_names = ["blue block", "green block", "yellow block", "red cube", "wooden box", "lid knob", + "blue mark", "green mark", "yellow mark"] + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffLhLidBox", box_lid_xml(BOX_MODEL), free=False) + b = BLOCK / 2 + objs, fx = [], [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))] + for i, c in enumerate(COLORS): + blk = register_generated(f"LffLhBlock{c.title()}", + box_xml(f"lff_lh_block_{c}", (b, b, b), RGBA[c], density=BLOCK_DENS, + friction=(BLOCK_MU, 0.005, 0.0001)).replace(_SOLID, "")) + mark = register_generated(f"LffLhMark{c.title()}", mark_xml(f"lff_lh_mark_{c}", RGBA[c]), free=False) + objs.append((BLOCKS[c], blk, f"{c}_block_region", (-0.31, -0.22 + 0.15 * i, -0.29, -0.20 + 0.15 * i))) + fx.append((MARKS[c], mark, f"{c}_mark_region", (0.0, -0.22 + 0.15 * i, 0.02, -0.20 + 0.15 * i))) + cube = register_generated("LffLhRedCube", box_xml("lff_lh_red_cube", (CUBE_E / 2,) * 3, (0.85, 0.10, 0.08, 1.0), + density=500)) + objs.append((CUBE, cube, "red_cube_region", (-0.31, 0.24, -0.29, 0.26))) + return write_bddl(self.name, "put the blocks on their marks and the red cube in the box", objs, fx) + + def __init__(self, cam_res=None): + super().__init__(cam_res) + m = self.env.sim.model + pre = f"{BOX}_{BOX_MODEL}" + self.jid = m.joint_name2id(pre + "_hinge") + self.qa = m.jnt_qposadr[self.jid] + self.dof = m.jnt_dofadr[self.jid] + self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body) + self.knob_geom_name = pre + "_knob" + self.knob_geom_names = [pre + "_knob", pre + "_stem"] + self.knob_gid = m.geom_name2id(self.knob_geom_name) + self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")} + self.robot_gids = set(envs.robot_geom_ids(self.env)) + self.mark_bid = {c: m.body_name2id(self.env.fixtures_dict[MARKS[c]].root_body) for c in COLORS} + self.block_gids = {c: set(envs.obj_geom_ids(self.env, BLOCKS[c])) for c in COLORS} + self.inst = None + self.mon = None + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03)) + hinge_x = bx + BOX_D / 2 + order = [str(c) for c in rng.permutation(COLORS)] # [behind-left, behind-right, side] + side = 1.0 if rng.random() < 0.5 else -1.0 + marks = {} + gaps = {} + for c, sy in zip(order[:2], (1.0, -1.0)): + g = float(rng.uniform(GAP_LO, GAP_HI)) + gaps[c] = g + marks[c] = [hinge_x + g + MARK_HALF, by + sy * 0.05 + float(rng.uniform(-0.005, 0.005))] + marks[order[2]] = [bx + float(rng.uniform(-0.03, 0.03)), by + side * (BOX_W / 2 + 0.025 + MARK_HALF)] + # start row in front of the box: four slots outside the knob's lane, shuffled (3 blocks + red cube) + slots = [-0.22, -0.11, 0.11, 0.22] # 11 cm apart: room for the open fingers next to a 6 cm block + items = [BLOCKS[c] for c in COLORS] + [CUBE] + perm = rng.permutation(len(items)) + start = {items[i]: [float(-0.31 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))] + for j, i in enumerate(perm)} + rng.random() # (draw kept so the other parameters stay the same) + # balanced blocks like l7_key_turn: exactly round(20 * P_FAR) of every 20 consecutive seeds open far + far = bool((int(seed) * 7) % 20 < round(20 * P_FAR)) + stop = float(rng.uniform(*(FAR if far else NEAR))) + return dict(seed=int(seed), box_xy=[bx, by], stop_deg=stop, lid_far=far, marks=marks, + behind=order[:2], side_color=order[2], side="left" if side > 0 else "right", gaps=gaps, start=start, + start_yaw={k: float(rng.uniform(-0.3, 0.3)) for k in items}) + + def apply_instance(self, inst): + self.inst = inst + m, d = self.env.sim.model, self.env.sim.data + bx, by = inst["box_xy"] + m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z] + m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0] + m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])] + m.jnt_solref[self.jid] = [0.01, 1.0] + d.qpos[self.qa] = 0.0 + d.qvel[self.dof] = 0.0 + for c in COLORS: + x, y = inst["marks"][c] + m.body_pos[self.mark_bid[c]] = [x, y, envs.TABLE_Z + 0.0002] + m.body_quat[self.mark_bid[c]] = [1.0, 0.0, 0.0, 0.0] + for name, xy in inst["start"].items(): + envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name]) + for c in COLORS: + envs.set_friction(self.env, BLOCKS[c], BLOCK_MU) + + def reset_instance(self, inst, recorder=None): + self.env.reset() + self.apply_instance(inst) + self.env.sim.forward() + envs.settle(self.env, 10) + self.mon = None + self.sk = LidSkills(self.env, self, recorder=recorder) + self._init_monitor() + return self.sk + + # ------------------------------------------------------------ state helpers + def lid_q(self): + return float(self.env.sim.data.qpos[self.qa]) + + def lid_deg(self): + return float(np.degrees(self.lid_q())) + + def knob_xyz(self): + return self.env.sim.data.geom_xpos[self.knob_gid].copy() + + def hinge_xz(self): + return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H + + def held(self, name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name])) + + def _flat(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + return bool(np.max(np.abs(R[2])) >= FLAT_COS) + + def block_offset(self, c): + p = envs.obj_pos(self.env, BLOCKS[c]) + return p[:2] - np.asarray(self.inst["marks"][c]) + + def on_mark(self, c, tol=TOL): + name = BLOCKS[c] + p = envs.obj_pos(self.env, name) + off = p[:2] - np.asarray(self.inst["marks"][c]) + return bool(np.max(np.abs(off)) <= tol and p[2] < envs.TABLE_Z + BLOCK / 2 + 0.01 and self._flat(name) + and not self.held(name)) + + def cube_in_box(self): + p = envs.obj_pos(self.env, CUBE) + rel = p[:2] - np.asarray(self.inst["box_xy"]) + return bool(abs(rel[0]) <= IN_X - CUBE_MARGIN and abs(rel[1]) <= IN_Y - CUBE_MARGIN + and p[2] < envs.TABLE_Z + WALL_H and not self.held(CUBE)) + + def lid_closed(self): + return self.lid_q() <= LID_CLOSED + + def stage_values(self): + v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS} + v["cube_in_box"] = self.cube_in_box() + v["lid_closed"] = self.lid_closed() + return v + + # ------------------------------------------------------------ per-step monitor + def _init_monitor(self): + self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"cube_in_box": False}, ever=set(), + lost=set(), events=[], last_touch={c: None for c in COLORS}, lid_hits=set(), + lid_open_max=0.0, lid_opened=False, lid_open_steps=[], lid_close_steps=[], step=0, + lid_prev=0.0, lid_moving_step=-10 ** 9) + + def _touches(self): + """Per block: was it touched by the lid / the robot in this control step?""" + d = self.env.sim.data + out = {} + for i in range(d.ncon): + c = d.contact[i] + for cc in COLORS: + g = self.block_gids[cc] + other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None) + if other is None: + continue + if other in self.lid_gids: + out[cc] = "lid" + elif other in self.robot_gids and out.get(cc) != "lid": + out[cc] = "robot" + return out + + 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"] + for c, who in self._touches().items(): + mon["last_touch"][c] = (who, step) + if who == "lid": + mon["lid_hits"].add(c) + q = self.lid_deg() + if q > 95.0 and abs(q - mon["lid_prev"]) > 0.5: + mon["lid_moving_step"] = step # the open lid is swinging (its contacts can last less than a control step) + mon["lid_prev"] = q + mon["lid_open_max"] = max(mon["lid_open_max"], q) + if not mon["lid_opened"] and q > 90.0: + mon["lid_opened"] = True + mon["lid_open_steps"].append(step) + mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical")) + elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED): + mon["lid_opened"] = False + mon["lid_close_steps"].append(step) + mon["events"].append(dict(step=step, pred="lid", ev="closed")) + if mon["step"] % 2: + return # predicates every other control step (0.1 s) + for c in COLORS: + key = f"{c}_on_mark" + was = mon["state"][key] + now = self.on_mark(c, TOL if not was else TOL + 0.005) # hysteresis against jitter at the border + if now != was: + self._event(key, now, step, c) + was = mon["state"]["cube_in_box"] + now = self.cube_in_box() + if now != was: + self._event("cube_in_box", now, step, None) + + def _event(self, key, now, step, color): + mon = self.mon + mon["state"][key] = now + if now: + ev = "restored" if key in mon["lost"] else "achieved" + mon["ever"].add(key) + if key in mon["lost"]: + mon["lost"].discard(key) + mon["events"].append(dict(step=step, pred=key, ev=ev)) + else: + cause = "other" + if color is not None: + if self.held(BLOCKS[color]): + cause = "picked_up" + else: + lt = mon["last_touch"][color] + if lt is not None and step - lt[1] <= 60: + cause = lt[0] + if cause == "other" and step - mon["lid_moving_step"] <= 20 and color in self.inst["behind"]: + cause = "lid" # lost while the open lid was swinging down onto the blocks behind the box + elif self.held(CUBE): + cause = "picked_up" + mon["lost"].add(key) + ev = dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1)) + if color is not None: + ev["offset_cm"] = (100 * self.block_offset(color)).round(1).tolist() + mon["events"].append(ev) + + # ------------------------------------------------------------ outcome + def _static(self): + d = self.env.sim.data + for name in [BLOCKS[c] for c in COLORS] + [CUBE]: + _, da = envs.free_joint_addr(self.env, name) + 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 abs(float(d.qvel[self.dof])) < 0.2 + + def outcome(self, inst): + envs.settle(self.env, 30) + mon = self.mon + vals = self.stage_values() + static = self._static() + held = [n for n in [BLOCKS[c] for c in COLORS] + [CUBE] if self.held(n)] + success = bool(all(vals.values()) and static and not held) + regress = [e for e in mon["events"] if e["ev"] == "lost"] + restored = [e for e in mon["events"] if e["ev"] == "restored"] + lid_knocks = [e for e in regress if e.get("cause") == "lid"] + parts = [] + if success: + failure = None + parts.append("All three blocks are on their marks, the red cube is in the box and the lid is closed.") + else: + off = [c for c in COLORS if not vals[f"{c}_on_mark"]] + failure = ("block_off_mark" if off else "cube_not_in_box" if not vals["cube_in_box"] else + "lid_open" if not vals["lid_closed"] else "held" if held else "not_static") + for c in off: + o = self.block_offset(c) + name = BLOCKS[c] + if self.held(name): + parts.append(f"The {c} block is still held by the gripper.") + continue + txt = (f"The {c} block is not on the {c} mark: its centre is {_fb(o[0])} and {_lr(o[1])} of the mark's " + f"centre") + if not self._flat(name): + txt += " and it is tipped over" + why = [e for e in regress if e["pred"] == f"{c}_on_mark"] + if f"{c}_on_mark" not in mon["ever"]: + txt += " (it was never on its mark)." + elif why and why[-1].get("cause") == "lid": + txt += (f" (it had been on its mark; the lid pushed it off when it fell open to " + f"{why[-1]['lid_deg']:.0f} degrees).") + elif why and why[-1].get("cause") == "robot": + txt += " (it had been on its mark; the robot knocked it off)." + else: + txt += " (it had been on its mark earlier)." + parts.append(txt) + if not vals["cube_in_box"]: + if self.held(CUBE): + parts.append("The red cube is still held by the gripper.") + else: + p = envs.obj_pos(self.env, CUBE) + rel = p[:2] - np.asarray(inst["box_xy"]) + parts.append(f"The red cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the " + f"box's centre.") + if not vals["lid_closed"]: + parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees).") + if not static and all(vals.values()): + parts.append("Something was still moving at the end.") + if mon["lid_open_max"] < 90.0: + parts.append("The lid was never opened past upright.") + out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, + events=mon["events"], n_regressions=len(regress), n_restored=len(restored), + n_lid_knocks=len(lid_knocks), lid_hits=sorted(mon["lid_hits"]), + lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1), + knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps, + block_offsets_cm={c: (100 * self.block_offset(c)).round(1).tolist() for c in COLORS}, + detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (perfect perception) + def _grasp_yaw(self, name): + R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3) + i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on) + yaw = float(np.arctan2(R[1, i], R[0, i])) + return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) # a cube: grasp yaw mod 90 deg + + def pick_place(self, name, dest_xy, z_rel, z_carry=Z_CARRY, noise=None, dest_yaw=0.0): + """Top-down pick of `name` at its centre, carry at `z_carry` (grasp point above the table), release with the + grasp point `z_rel` above the table at `dest_xy`, lift.""" + sk = self.sk + Z = envs.TABLE_Z + p = envs.obj_pos(self.env, name) + yaw = self._grasp_yaw(name) + zg = p[2] - Z + sk.set_gripper(False, steps=8) + sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw) + sk.move_to([p[0], p[1], Z + zg], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([p[0], p[1], Z + z_carry], speed=0.3) + if not self.held(name): + sk.set_gripper(False, steps=8) + return False + d = np.asarray(dest_xy, float) + (np.asarray(noise, float) if noise is not None else 0.0) + sk.move_to([d[0], d[1], Z + z_carry], yaw=dest_yaw) + sk.move_to([d[0], d[1], Z + z_rel], tol=0.003) + sk.set_gripper(False, steps=12) + sk.move_to([d[0], d[1], Z + z_carry]) + return True + + def place_block(self, c, noise=None): + return self.pick_place(BLOCKS[c], self.inst["marks"][c], BLOCK / 2 + 0.004, noise=noise) + + def put_cube(self, noise=None): + bx, by = self.inst["box_xy"] + return self.pick_place(CUBE, [bx, by], FLOOR_T + CUBE_E / 2 + 0.008, z_carry=0.12, noise=noise) + + def _grasp_knob(self): + sk = self.sk + k = self.knob_xyz() + sk.set_gripper(False, steps=8) + sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0) + sk.move_to([k[0], k[1], k[2]], tol=0.003) + sk.set_gripper(True, steps=15) + return k + + def open_lid(self, back=0.03, up=0.16): + """grasp the knob; straight up 10 cm; straight to `back` m behind the hinge, `up` m above it; release; lift""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx + back, k[1], hz + up]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06]) + sk.hold(20) + + def close_lid(self): + """grasp the knob where it is; straight up 10 cm; straight forward to 8 cm in front of the hinge; release""" + sk = self.sk + k = self._grasp_knob() + hx, hz = self.hinge_xz() + sk.move_to([k[0], k[1], k[2] + 0.10]) + sk.move_to([hx - 0.08, k[1], k[2] + 0.10]) + sk.set_gripper(False, steps=10) + e = sk.eef_pos() + sk.move_to([e[0], e[1], e[2] + 0.06]) + sk.hold(20) + + def restore(self, rounds=2): + """look at every stage and fix what is wrong (lid open -> close it; cube out -> put it in; block off -> put it + back), up to `rounds` passes""" + for _ in range(rounds): + v = self.stage_values() + if all(v.values()): + return True + if not v["cube_in_box"]: + if self.lid_q() < np.radians(95): + self.open_lid() + self.put_cube() + self.close_lid() + elif not v["lid_closed"]: + self.close_lid() + for c in COLORS: + if not self.on_mark(c): + self.place_block(c) + return all(self.stage_values().values()) + + def execute(self, inst, params): + order = params.get("order") or list(COLORS) + noise = params.get("noise") or {} + if params["plan"] == "blocks_first": + for c in order: + self.place_block(c, noise.get(c)) + self.open_lid(**params.get("open", {})) + self.put_cube(noise.get("cube")) + self.close_lid() + else: # "lid_first": open, cube in, close, then the blocks + self.open_lid(**params.get("open", {})) + self.put_cube(noise.get("cube")) + self.close_lid() + for c in order: + self.place_block(c, noise.get(c)) + if params.get("check"): + self.restore() + self.sk.hold(10) + + def default_params(self, inst): + return dict(plan="blocks_first", check=False) + + def oracle_params(self, inst): + return dict(plan="lid_first", check=True) + + def adapt_params(self, inst, history): + """Used from attempt 2 on, i.e. after a failed attempt (attempt 1 is the natural order plus a final check and + repair, see run_scripted): open the box, put the cube in and close it first, then place the blocks, check.""" + return dict(plan="lid_first", check=True) + + def blind_params(self, inst, attempt, rng): + """the natural order again with small random variations (block order, placement, release point), no check""" + return dict(plan="blocks_first", check=False, order=[str(c) for c in rng.permutation(COLORS)], + noise={c: rng.normal(0.0, 0.004, 2).tolist() for c in COLORS}, + open=dict(back=float(rng.uniform(0.0, 0.05)), up=float(rng.uniform(0.14, 0.18)))) + + 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 = [] + 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(plan="blocks_first", 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": # extra control (not in validate's table): cross-attempt learning only, no re-check + params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check=False) + 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"): + break + return history diff --git a/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/contract.py b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/contract.py new file mode 100644 index 0000000000000000000000000000000000000000..5efe5079fdb7ef9581c6772a9954c3f64b8eda49 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/contract.py @@ -0,0 +1,160 @@ +"""Information contract of one run (docs/15 §1 layer 2) and its hash `contract_sha256`. + +The contract is everything the agent is given that must be identical across harnesses and models for the same +instance and condition: the README text, the three tool schemas, the image spec, the feedback level, --hide-k, the +budgets, the memory condition, the task and seed, and the code that builds the scene and judges it. Two runs whose +`contract_sha256` differ must not share a table cell. + +What is NOT in the contract on purpose: the harness (it is the thing being compared), the model, the port, the +sandbox / log paths, timestamps. + + contract = build_contract(log_dir) # reads session.json, agent_iface.json, events.jsonl, README.md + contract_sha256(contract) # sha256 of the canonical JSON + write_contract(log_dir) # -> /contract.json, returns (contract, sha) +""" +import glob +import hashlib +import json +import os +import re +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # the lffbench repo +CONTRACT_VERSION = 1 +IMAGE_SPEC = dict(cameras=["agentview", "wrist"], width=512, height=512, format="JPEG", jpeg_quality=90, + delivery="files in the workspace, viewed with view_images (bytes unchanged)") +# code that builds the scene, runs the robot and judges the result (task modules are added per task) +SERVER_CODE = ["lffbench/agent/robot_server.py", "lffbench/agent/tools.py", "lffbench/agent/camera.py", + "lffbench/agent/context.py", "lffbench/agent/images.py", "lffbench/envs.py", "lffbench/skills.py", + "lffbench/task_base.py", "lffbench/bddl.py", "lffbench/objects.py"] +# real-robot backend (added for real_* tasks only; the driver itself is recorded as contract["real_driver"]) +REAL_CODE = ["lffbench/real/tasks.py", "lffbench/real/session.py", "lffbench/real/executor.py", "lffbench/real/protocol.py"] + + +def sha256_bytes(b): + return hashlib.sha256(b).hexdigest() + + +def sha256_text(s): + return sha256_bytes(s.encode("utf-8")) + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def canonical(obj): + return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")) + + +def sha256_json(obj): + return sha256_text(canonical(obj)) + + +def tool_schemas(): + """The three LA tools exactly as the reference driver and the MCP server define them.""" + sys.path.insert(0, os.path.join(ROOT, "scripts")) + from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, PREAMBLE_LA # noqa: E402 + return [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA], PREAMBLE_LA + + +def task_module_files(task): + """Source files of the task class `task` (found by its `name = ""` line; .bak files are ignored).""" + pat = re.compile(r"""^\s*name\s*=\s*["']%s["']""" % re.escape(task), re.M) + hits = [] + for p in sorted(glob.glob(os.path.join(ROOT, "lffbench", "tasks", "*.py"))): + try: + if pat.search(open(p, encoding="utf-8").read()): + hits.append(os.path.relpath(p, ROOT)) + except OSError: + pass + arm = os.path.join(ROOT, "lffbench", "arm_specs", f"{task}.py") + if os.path.exists(arm): + hits.append(os.path.relpath(arm, ROOT)) + real = os.path.join(ROOT, "lffbench", "real", "tasks.py") # real-robot tasks (docs/17): add the real backend's code + if not hits and os.path.exists(real) and pat.search(open(real, encoding="utf-8").read()): + hits += REAL_CODE + return hits + + +def server_code_sha(task): + files = SERVER_CODE + task_module_files(task) + per = {f: (sha256_file(os.path.join(ROOT, f)) if os.path.exists(os.path.join(ROOT, f)) else None) for f in files} + return sha256_json(per), per + + +def session_start(log_dir): + with open(os.path.join(log_dir, "events.jsonl")) as f: + for line in f: + d = json.loads(line) + if d.get("ev") == "session_start": + return d + raise RuntimeError(f"no session_start event in {log_dir}/events.jsonl") + + +def readme_budget(readme): + """The per-attempt budgets as the README states them (what the agent is told).""" + out = {} + for key, pat in (("robot_commands", r"at most (\d+) robot commands"), + ("sim_seconds", r"at most ([\d.]+) s of (?:simulated )?robot motion"), # real robot: "s of robot motion" + ("tool_calls", r"at most (\d+) tool calls")): + m = re.search(pat, readme) + out[key] = float(m.group(1)) if m and "." in m.group(1) else (int(m.group(1)) if m else None) + return out + + +def build_contract(log_dir): + log_dir = os.path.abspath(log_dir) + sess = json.load(open(os.path.join(log_dir, "session.json"))) + iface = json.load(open(os.path.join(log_dir, "agent_iface.json"))) + st = session_start(log_dir) + readme = open(os.path.join(sess["sandbox"], "README.md"), encoding="utf-8").read() + tools, preamble = tool_schemas() + code_sha, code_files = server_code_sha(st["task"]) + out = dict( + contract_version=CONTRACT_VERSION, + task=st["task"], seed=st["seed"], + readme_sha256=sha256_text(readme), + preamble_sha256=sha256_text(preamble), + tools=tools, + image_spec=dict(IMAGE_SPEC, perception=st.get("perception", iface.get("perception"))), + feedback=st.get("feedback"), instruction=st.get("instruction"), + memory=st.get("memory"), k=st.get("k"), k_shown=st.get("k_shown"), hide_k=st.get("k_shown") != st.get("k"), + protocol=st.get("protocol"), arm=st.get("arm"), dossier_sha256=sha256_text(st.get("dossier") or ""), + budget=dict(readme_budget(readme), max_tool_calls=iface.get("max_tool_calls"), + tool_call_budget_enforced_by="mcp_robot_server / api_player (per attempt)"), + agent_iface=iface.get("agent_iface"), + server_code_sha256=code_sha, server_code_files=code_files, + ) + if st.get("backend") == "real": # only real-robot runs get this key, so simulated contracts are unchanged + di = st.get("driver_info") or {} + out["real_driver"] = {k: di.get(k) for k in ("protocol", "robot", "n_joints", "workspace", "yaw_range_deg", + "max_speed", "ik", "driver_version")} + out["real_agent_workspace"] = st.get("agent_workspace") + from .redteam import marker # adversarial acceptance runs only (harness_run --red-team): others are unchanged + rt = marker(log_dir) + if rt: + out["red_team"] = rt + return out + + +def contract_sha256(contract): + return sha256_json(contract) + + +def write_contract(log_dir): + c = build_contract(log_dir) + sha = contract_sha256(c) + with open(os.path.join(log_dir, "contract.json"), "w") as f: + json.dump(dict(contract_sha256=sha, contract=c), f, indent=1, ensure_ascii=False) + return c, sha + + +if __name__ == "__main__": + for d in sys.argv[1:]: + c, sha = write_contract(d) + print(sha, d) diff --git a/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/embodied_evo.py b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/embodied_evo.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe7bbab6f494d3cfae2f6802e6c266f4561f6dc --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/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/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/jail.py b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/jail.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa92de82ca61f9ec86cc39756433bb829fe16d9 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/jail.py @@ -0,0 +1,228 @@ +"""Jail for native harness processes (docs/15 §3.4): the harness sees no host path at all, instead of only "having no +tool that reads files". + +Without it, Claude Code / Codex run as root on the host with /mnt visible (task code with the hidden-variable rules, +task cards, earlier runs' logs, .secrets); isolation then rests on every built-in tool being switched off. With it +(adapter option jail=True, `harness_run.py --jail`, `api_batch.py start --jail`): + - the harness runs as the unprivileged host user nobody (uid 65534) in new user + mount namespaces + (jail/harness_jail_inner.sh, installed under /opt/lffjail/hjail by jail/setup_harness_jail.sh): /mnt /home /root + /tmp /run/secrets /etc/dsw are empty tmpfs, system dirs read-only, all capabilities dropped; the network stays + (model API); + - /proc: "static" (Codex) = a read-only tmpfs with static copies of host-wide files (CPU, memory, kernel version) and + the process's own self/ entries, no other pid; "host" (Claude Code, a Bun executable that aborts without a real + procfs; a fresh procfs cannot be mounted in this container because its /proc has locked submounts) = the host + procfs, where as uid 65534 the harness can list processes and read their command lines but not their environ, fd, + cwd or root (checked in tests/harness_selfcheck/jail_probe.py); + - visible again, at their original paths: the one-time work dir, the one-time state dir and the socket dir of the + MCP relay (chowned to uid 65534); the harness binary runs from a verified copy of its release dir under + /opt/lffjail/hjail/bin (the original lives under 0700 dirs in /mnt); + - the MCP server (scripts/mcp_robot_server.py) runs outside the jail; the harness starts the relay + /opt/lffjail/hjail/mcp_fwd.py, which connects to a Unix socket served here: every connection gets its own MCP + server process with stdin / stdout on the socket and the environment {PATH} only. +The harness command line (except argv[0] = the copy), its environment (exact whitelist) and the paths it sees are +unchanged; only the MCP server entry of its config points to the relay. +""" +import hashlib +import os +import secrets +import shutil +import socket +import subprocess +import threading + +JAIL_DIR = "/opt/lffjail/hjail" +INNER = os.path.join(JAIL_DIR, "inner.sh") +RELAY = os.path.join(JAIL_DIR, "mcp_fwd.py") +BIN_DIR = os.path.join(JAIL_DIR, "bin") +RELAY_PYTHON = "/usr/bin/python3" +SOCK_ROOT = "/tmp/lffsock" +JAIL_UID = 65534 +MAX_BINDS = 16 + + +class JailError(RuntimeError): + pass + + +def installed_problems(): + p = [] + for f in (INNER, RELAY): + if not os.path.exists(f): + p.append(f"{f} missing (sudo bash jail/setup_harness_jail.sh)") + if not os.path.isdir(os.path.join(JAIL_DIR, "stage", str(MAX_BINDS - 1))): + p.append(f"{JAIL_DIR}/stage/0..{MAX_BINDS - 1} missing (sudo bash jail/setup_harness_jail.sh)") + if not os.access(RELAY_PYTHON, os.X_OK): + p.append(f"{RELAY_PYTHON} missing") + for t in ("unshare", "setpriv"): + if not shutil.which(t): + p.append(f"{t} not found") + return p + + +def sha256_file(path): + h = hashlib.sha256() + with open(path, "rb") as f: + for b in iter(lambda: f.read(1 << 20), b""): + h.update(b) + return h.hexdigest() + + +def _outermost(dirs): + """Drop directories that lie inside another one of the list (one bind mount covers them).""" + ds = sorted({os.path.realpath(d) for d in dirs if d}, key=len) + out = [] + for d in ds: + if not any(d == o or d.startswith(o.rstrip("/") + "/") for o in out): + out.append(d) + return out + + +def _chown_tree(root, uid): + os.chown(root, uid, uid) + for dp, dn, fn in os.walk(root): + for n in dn + fn: + try: + os.lchown(os.path.join(dp, n), uid, uid) + except FileNotFoundError: + pass + + +def binary_copy(binary): + """A verified copy of the binary's release dir under /opt/lffjail/hjail/bin (readable by uid 65534); returns + (path of the binary in the copy, info). The release dir is the binary's dir, or its parent if that is a bin/.""" + real = os.path.realpath(binary) + if not os.path.isfile(real): + raise JailError(f"harness binary {binary} -> {real} not found") + sha = sha256_file(real) + rel_root = os.path.dirname(real) + if os.path.basename(rel_root) == "bin": + rel_root = os.path.dirname(rel_root) + dst_root = os.path.join(BIN_DIR, f"{os.path.basename(rel_root)}-{sha[:12]}") + dst = os.path.join(dst_root, os.path.relpath(real, rel_root)) + if not (os.path.isfile(dst) and sha256_file(dst) == sha): + os.makedirs(BIN_DIR, mode=0o755, exist_ok=True) + tmp = dst_root + ".tmp-" + secrets.token_hex(3) + shutil.copytree(rel_root, tmp, symlinks=True) + for dp, dn, fn in os.walk(tmp): + os.chmod(dp, 0o755) + if os.path.exists(dst_root): + shutil.rmtree(dst_root) + os.rename(tmp, dst_root) + if sha256_file(dst) != sha: + raise JailError(f"copy of {real} does not match its sha256") + return dst, dict(original=real, copy=dst, sha256=sha) + + +class _Relay: + """Serves one Unix socket; each connection gets a fresh MCP server process attached to it.""" + + def __init__(self, sock_path, argv, env, stderr_path, uid): + self.path, self.argv, self.env, self.stderr_path = sock_path, argv, env, stderr_path + self.procs = [] + self.closed = False + self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.srv.bind(sock_path) + os.chown(sock_path, uid, uid) + os.chmod(sock_path, 0o600) + self.srv.listen(8) + self.t = threading.Thread(target=self._serve, daemon=True) + self.t.start() + + def _serve(self): + while not self.closed: + try: + conn, _ = self.srv.accept() + except OSError: + return + try: + err = open(self.stderr_path, "ab") if self.stderr_path else subprocess.DEVNULL + p = subprocess.Popen(self.argv, stdin=conn.fileno(), stdout=conn.fileno(), stderr=err, env=self.env, + cwd="/", start_new_session=True) + self.procs.append(p) + if err is not subprocess.DEVNULL: + err.close() + finally: + conn.close() + + def close(self): + self.closed = True + try: + self.srv.close() + except OSError: + pass + for p in self.procs: + if p.poll() is None: + p.terminate() + for p in self.procs: + try: + p.wait(timeout=10) + except subprocess.TimeoutExpired: + p.kill() + + +class HarnessJail: + """One per adapter instance. mcp_command() registers a real MCP server command and returns the relay command for + the harness config; wrap() turns the harness argv into the jailed one; close() stops relays and removes sockets.""" + + def __init__(self, binary, proc="static", uid=JAIL_UID, stderr_dir=None): + probs = installed_problems() + if probs: + raise JailError("; ".join(probs)) + if proc not in ("static", "host"): + raise JailError(f"proc must be static or host, not {proc!r}") + self.binary_real = os.path.realpath(binary) + self.binary_jailed, self.binary_info = binary_copy(binary) + self.proc, self.uid = proc, uid + self.sock_dir = None + self.relays = [] + self.stderr_dir = stderr_dir + + def info(self): + return dict(enabled=True, uid=self.uid, proc=self.proc, binary=self.binary_info, inner=INNER, + inner_sha256=sha256_file(INNER), relay=RELAY) + + def _sock_dir(self): + if self.sock_dir is None: + os.makedirs(SOCK_ROOT, mode=0o711, exist_ok=True) + os.chmod(SOCK_ROOT, 0o711) + d = os.path.join(SOCK_ROOT, secrets.token_hex(6)) + os.mkdir(d, 0o700) + os.chown(d, self.uid, self.uid) + self.sock_dir = d + return self.sock_dir + + def mcp_command(self, real_argv, env=None, label="mcp"): + """-> (command, args) for the harness's MCP config: the relay on a new socket served by real_argv.""" + d = self._sock_dir() + path = os.path.join(d, f"{label}-{len(self.relays)}.sock") + err = os.path.join(self.stderr_dir, f"jail_{label}_stderr.log") if self.stderr_dir else None + self.relays.append(_Relay(path, list(real_argv), dict(env or {"PATH": "/usr/bin:/bin"}), err, self.uid)) + return RELAY_PYTHON, [RELAY, path] + + def wrap(self, argv, env, cwd, rw_dirs): + """The jailed argv. Popen it with the same env: the jail forwards exactly those variables. Chowns the + directories that are mounted back (one-time dirs only) to the jail uid.""" + rw = _outermost(list(rw_dirs) + ([self.sock_dir] if self.sock_dir else []) + ([cwd] if cwd else [])) + if len(rw) > MAX_BINDS: + raise JailError(f"too many bind mounts ({len(rw)} > {MAX_BINDS})") + for d in rw: + if not os.path.isdir(d): + raise JailError(f"bind source {d} is not a directory") + if not d.startswith(("/tmp/lffrun/", "/tmp/lffstate/", SOCK_ROOT + "/")): + raise JailError(f"refusing to mount {d} into the jail (only one-time dirs)") + _chown_tree(d, self.uid) + cmd = [self.binary_jailed if os.path.realpath(argv[0]) == self.binary_real else argv[0]] + list(argv[1:]) + out = ["setpriv", f"--reuid={self.uid}", f"--regid={self.uid}", "--clear-groups", "--", + "unshare", "--user", "--map-root-user", "--mount", "--fork", "--kill-child", + INNER, "--keep", ",".join(sorted(env)), "--proc", self.proc] + for d in rw: + out += ["--rw", d] + return out + ["--cwd", cwd or "/", "--exe", self.binary_jailed, "--"] + cmd + + def close(self): + for r in self.relays: + r.close() + self.relays = [] + if self.sock_dir and self.sock_dir.startswith(SOCK_ROOT + "/"): + shutil.rmtree(self.sock_dir, ignore_errors=True) + self.sock_dir = None diff --git a/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/pins.py b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/pins.py new file mode 100644 index 0000000000000000000000000000000000000000..8af8749d43eed7047c1ffa6ed1b3df3bd1a76230 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/pins.py @@ -0,0 +1,40 @@ +"""Pinned launch fingerprints (fail-closed launch, docs/15 §0.4). + +A pin says: "harness at version (binary sha256 ) with model and effort sends exactly this preset +prompt and tool list" (the normalised fingerprint of the first request, see claude_code.request_fingerprint / +codex.request_fingerprint). Pins are written only by tests/harness_selfcheck/selfcheck.py --write-pins after every +offline check passed for that adapter; a launch without a matching pin is refused. + +Only hashes and sizes are stored here (the repo is public); the full fingerprint of each launch is in the run's +harness_preflight.json. +""" +import json +import os +import re +import time + +PINS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pins") + + +def key(adapter, version, binary_sha, model, effort): + return f"{adapter}|{version}|{(binary_sha or 'nobin')[:16]}|{model}|{effort}" + + +def _path(k, pins_dir=None): + return os.path.join(pins_dir or PINS_DIR, re.sub(r"[^A-Za-z0-9.-]+", "_", k) + ".json") + + +def load(k, pins_dir=None): + p = _path(k, pins_dir) + if not os.path.exists(p): + return None + with open(p) as f: + return json.load(f) + + +def write(k, fingerprint_sha256, summary, pins_dir=None): + os.makedirs(pins_dir or PINS_DIR, exist_ok=True) + d = dict(key=k, fingerprint_sha256=fingerprint_sha256, written=time.strftime("%Y-%m-%d %H:%M:%S"), summary=summary) + with open(_path(k, pins_dir), "w") as f: + json.dump(d, f, indent=1) + return d diff --git a/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/sensenova.py b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/sensenova.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab4298a5dee42672e540be1b240c677754b8203 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/sensenova.py @@ -0,0 +1,24 @@ +"""SenseNova-RoboRSI native Codex SDK planner, controlled MCP variant.""" +from .framework_codex import RobotFrameworkCodex + +class SenseNovaCodex(RobotFrameworkCodex): + name = "sensenova_codex" + runtime_home = "/mnt/cpfs/workspace/env/sensenova-roborsi" + + def __init__(self, **kwargs): + kwargs.setdefault("sessions", 1) + kwargs.setdefault("attempts_per_session", 0) + if kwargs["sessions"] != 1 or kwargs["attempts_per_session"] != 0: + raise ValueError("SenseNova controlled variant uses one persistent session for all attempts") + super().__init__(**kwargs) + + def env(self, state, ep, base_url, work): + env = super().env(state, ep, base_url, work) + env["LFF_CONTROLLED_CODEX"] = "1" + return env + + def config_info(self): + info = super().config_info() + info.update(variant="native-codex-planner-mcp", max_sdk_steps=self.max_turns, + history="same-thread", cross_episode_memory=False) + return info diff --git a/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/check_setup.py b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/check_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..c91b70fc618700ec2c265ebd1f9f21fed24e2420 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/check_setup.py @@ -0,0 +1,175 @@ +"""Check that this machine can run LFF-Bench. Run after `source run_env.sh`: + + python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail + python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY / + # OPENAI_BASE_URL from the environment or from .env); costs a few tokens + python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail + +Exit code 0 when every check that ran passed. +""" +import argparse +import os +import subprocess +import sys +import tempfile +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py + +results = [] + + +def report(name, ok, detail=""): + results.append(ok) + print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True) + return ok + + +def check_packages(): + report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0]) + from lffbench.agent.backends.base import import_openai + for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"): + try: + m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"]) + report(f"import {mod}", True, getattr(m, "__version__", "")) + except Exception as e: # noqa: BLE001 + report(f"import {mod}", False, f"{type(e).__name__}: {e}") + cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml") + if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")): + import yaml + assets = yaml.safe_load(open(cfg)).get("assets", "") + report("LIBERO assets", os.path.isdir(assets), assets) + report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}") + + +def check_sim(task_name, seed): + import importlib + import pkgutil + + try: + import lffbench.tasks as task_pkg + from lffbench.task_base import TASKS + except Exception as e: # noqa: BLE001 + report("import lffbench", False, f"{type(e).__name__}: {e}") + return + try: + for m in pkgutil.iter_modules(task_pkg.__path__): + importlib.import_module(f"lffbench.tasks.{m.name}") + except Exception as e: # noqa: BLE001 + report("import tasks", False, f"{type(e).__name__}: {e}") + return + report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks") + t0 = time.time() + try: + task = TASKS[task_name]() + inst = task.sample_instance(seed) + task.reset_instance(inst) + img = task.snapshot() + out = task.outcome(inst) + except Exception as e: # noqa: BLE001 + report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}") + return + ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0 + report(f"simulate + render {task_name}", ok, + f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s") + + +def check_jail(): + if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"), + JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"): + return + probe = r''' +echo "pwd=$(pwd)" +python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1 +echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)" +python3 -c " +import socket +s = socket.socket(); s.settimeout(3) +try: + s.connect(('1.1.1.1', 443)); print('net=open') +except OSError as e: + print('net=blocked') +" +touch made_in_jail && echo "write=ok" +''' + with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws: + argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws, + "timeout", "-k", "5", "60", "bash", "-c", probe] + r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120) + kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l) + if r.returncode != 0 and not kv: + hint = "" + if "Operation not permitted" in r.stdout or "uid_map" in r.stdout: + hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: " + "sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0") + report("jail runs", False, r.stdout.strip()[-400:] + hint) + return + report("jail runs", True, f"workdir {kv.get('pwd')}") + report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:])) + report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0", + f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}") + report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?")) + report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail"))) + + +def load_env_file(): + path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env") + if not os.path.isfile(path): + return None + for line in open(path): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + k, v = line.split("=", 1) + os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\"")) + return path + + +def check_api(model, effort): + src = load_env_file() + 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" # same as scripts/gpt_player.py + if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")), + f"from {src}" if src else "from the environment (no .env)"): + return + base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)" + from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend + t0 = time.time() + try: + client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client() + resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping", + reasoning=dict(effort=effort), store=False, max_output_tokens=256) + text = (resp.output_text or "").strip() + u = resp.usage + report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, " + f"tokens in {u.input_tokens} / out {u.output_tokens}") + except Exception as e: # noqa: BLE001 + report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}") + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint") + ap.add_argument("--model", default="gpt-6-astra") + ap.add_argument("--effort", default="low") + ap.add_argument("--task", default="l5_slide_to_target") + ap.add_argument("--seed", type=int, default=1000) + ap.add_argument("--skip-sim", action="store_true") + ap.add_argument("--skip-jail", action="store_true") + a = ap.parse_args() + os.environ.setdefault("OMP_NUM_THREADS", "1") + check_packages() + if not a.skip_sim: + check_sim(a.task, a.seed) + if not a.skip_jail: + check_jail() + if a.api: + check_api(a.model, a.effort) + n_bad = results.count(False) + print(f"\n{len(results) - n_bad}/{len(results)} checks passed") + sys.exit(1 if n_bad else 0) + + +if __name__ == "__main__": + main() diff --git a/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/full_waves.sh b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/full_waves.sh new file mode 100644 index 0000000000000000000000000000000000000000..d4a98c713907c49980d1dfb6571d022deeb09321 --- /dev/null +++ b/leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/scripts/full_waves.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Run the remaining waves of the full GPT-6 run: wait until at most MAX_LEFT (default 4) runs of the batch are still going, stop the +# robot servers of ended runs (keeps memory bounded), then launch the next wave on all three harnesses. +# usage: scripts/full_waves.sh "" "" ... +cd "$(dirname "$0")/.." +B=$1; shift +reap() { + python3 - "$B" <<'PY' +import json, os, signal, sys, subprocess +b = sys.argv[1] +m = json.load(open(f"runs/gpt/{b}/manifest.json")) +st = subprocess.run(["python3", "scripts/gpt_batch.py", "status", "--batch", b], capture_output=True, text=True).stdout.splitlines() +running = 0 +for r, line in zip(m["runs"], st): + if line.rstrip().endswith("running"): + running += 1 + continue + try: + pid = int(open(os.path.join(r["log"], "server.pid")).read()) + os.kill(pid, signal.SIGTERM) + except Exception: + pass +print(running) +PY +} +wait_below() { while true; do n=$(reap | tail -1); [ "$n" -le "$1" ] && break; sleep 120; done; } +port=${PORT0:-9900} +for W in "$@"; do + wait_below ${MAX_LEFT:-4} + echo "$(date -u +%H:%M) launching wave: $W" + for h in gpt_player rpent gptpolicy; do + python3 scripts/gpt_batch.py start --batch $B --harness $h --model gpt-6-astra --effort medium --perception rgb \ + --style ${STYLE:-v1} --video --k 3 --port0 $port --tasks $W | grep -c '"run"' + port=$((port + 30)) + done +done +wait_below 0 +echo "$(date -u +%H:%M) all waves done" diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/client/pyproject.toml b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/client/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..c2a9951a959c8a5f5e06503737c88014d661c2c4 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/client/pyproject.toml @@ -0,0 +1,13 @@ +[build-system] +requires = ["setuptools>=61"] +build-backend = "setuptools.build_meta" + +[project] +name = "lffbench-client" +version = "0.1.0" +description = "LFF-Bench agent tools (robot / shell / view_images) for robot harness frameworks, via the episode's tool gateway" +requires-python = ">=3.8" +dependencies = [] + +[tool.setuptools] +packages = ["lffbench_client"] diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/envs.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/envs.py new file mode 100644 index 0000000000000000000000000000000000000000..6458cf95f3fe41dae232ea814c6ba7351ac0caa4 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/envs.py @@ -0,0 +1,325 @@ +"""Environment construction and low-level sim helpers on top of LIBERO / robosuite.""" +import os + +os.environ.setdefault("MUJOCO_GL", "osmesa") +os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa") +# LIBERO reads its paths from /config.yaml (written by setup/install.sh into /.libero) +os.environ.setdefault("LIBERO_CONFIG_PATH", os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".libero")) + +import numpy as np + +TABLE_Z = 0.90 # LIBERO main_table top surface (table_offset z) +# Upper limit of the Panda elbow (robot0_joint4; stock -0.0698). The arm is fully stretched at about -0.47 rad; a fast +# move out of a far pose could carry the elbow past that into (-0.47, -0.07], where the OSC's only way to shorten the +# arm runs into the stock limit and every later move stops 4-17 cm short for the rest of the attempt (measured +# 2026-10-19: 50 of 160 targets of the workspace box; 44 of 714 logged LA attempts). Capping the joint keeps the elbow +# on the normal side: reach is unchanged, and no scripted oracle / naive run of the main set goes above -0.73. +ELBOW_Q4_MAX = -0.55 + + +def make_env(bddl_path, cam_res=256, cams=("agentview", "robot0_eye_in_hand"), depth=False, controller=None): + """Build a LIBERO env from a BDDL file without camera rendering on every step. + + Images are rendered on demand with `render(env, cam)`. + """ + import robosuite as suite + import libero.libero.envs.bddl_utils as BDDLUtils + from libero.libero.envs import TASK_MAPPING + + cfg = suite.load_controller_config(default_controller="OSC_POSE") + if controller is None: + from .skills import CONTROLLER + controller = CONTROLLER + if controller: + cfg.update(controller) + info = BDDLUtils.get_problem_info(bddl_path) + env = TASK_MAPPING[info["problem_name"]]( + bddl_path, + robots=["Panda"], + controller_configs=cfg, + gripper_types="default", + initialization_noise=None, + use_camera_obs=False, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + horizon=10 ** 7, + ignore_done=True, + hard_reset=False, + camera_names=list(cams), + camera_heights=cam_res, + camera_widths=cam_res, + camera_depths=depth, + camera_segmentations=None, + renderer="mujoco", + renderer_config=None, + ) + env.lff_language = info["language_instruction"] + m = env.sim.model # hard_reset=False: the model (and this limit) survives env.reset() + m.jnt_range[m.joint_name2id("robot0_joint4"), 1] = ELBOW_Q4_MAX + return env + + +def render(env, cam="agentview", res=256, depth=False): + """Render an RGB image (H, W, 3, uint8), upright.""" + out = env.sim.render(camera_name=cam, width=res, height=res, depth=depth) + if depth: + rgb, d = out + return rgb[::-1].copy(), d[::-1].copy() + return out[::-1].copy() + + +# ---------------------------------------------------------------- object state helpers + +def body_id(env, obj_name): + return env.sim.model.body_name2id(env.objects_dict[obj_name].root_body) + + +def obj_pos(env, obj_name): + return env.sim.data.body_xpos[body_id(env, obj_name)].copy() + + +def obj_quat(env, obj_name): + """wxyz""" + return env.sim.data.body_xquat[body_id(env, obj_name)].copy() + + +def obj_upright_cos(env, obj_name): + """cos of the angle between the object's z axis and world z.""" + xmat = env.sim.data.body_xmat[body_id(env, obj_name)].reshape(3, 3) + return float(xmat[2, 2]) + + +def free_joint_addr(env, obj_name): + jname = env.objects_dict[obj_name].joints[0] + jid = env.sim.model.joint_name2id(jname) + return env.sim.model.jnt_qposadr[jid], env.sim.model.jnt_dofadr[jid] + + +def set_obj_pose(env, obj_name, pos, yaw=0.0, quat_wxyz=None): + """Teleport a free-joint object (used only at reset / by the protocol, never by agents).""" + qa, da = free_joint_addr(env, obj_name) + if quat_wxyz is None: + quat_wxyz = np.array([np.cos(yaw / 2), 0, 0, np.sin(yaw / 2)]) + env.sim.data.qpos[qa:qa + 3] = pos + env.sim.data.qpos[qa + 3:qa + 7] = quat_wxyz + env.sim.data.qvel[da:da + 6] = 0.0 + + +def obj_geom_ids(env, obj_name): + return [env.sim.model.geom_name2id(g) for g in env.objects_dict[obj_name].contact_geoms] + + +def set_friction(env, obj_name, mu, priority=2): + """Set sliding friction of an object's collision geoms and give them priority so their + friction is used in contacts (MuJoCo otherwise takes the max of the two geoms).""" + for g in obj_geom_ids(env, obj_name): + env.sim.model.geom_friction[g, 0] = mu + env.sim.model.geom_priority[g] = priority + + +def scale_mass(env, obj_name, mass): + bid = body_id(env, obj_name) + m0 = env.sim.model.body_mass[bid] + env.sim.model.body_mass[bid] = mass + env.sim.model.body_inertia[bid] *= mass / max(m0, 1e-9) + + +def settle(env, steps=20): + """Let physics settle while holding the arm still.""" + for _ in range(steps): + env.step(np.zeros(env.action_dim)) + + +def contacts_between(env, geoms_a, geoms_b): + a, b = set(geoms_a), set(geoms_b) + d = env.sim.data + for i in range(d.ncon): + c = d.contact[i] + if (c.geom1 in a and c.geom2 in b) or (c.geom1 in b and c.geom2 in a): + return True + return False + + +def robot_geom_ids(env): + m = env.sim.model + ids = [] + for g in range(m.ngeom): + n = m.geom_id2name(g) or "" + if n.startswith("robot0_") or n.startswith("gripper0_"): + ids.append(g) + return ids + + +# ---------------------------------------------------------------- upright placement (added 2026-10-06) + +def _quat_mul(a, b): + """wxyz quaternion product 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 canonical_quat(env, obj_name): + """The orientation LIBERO's own placement gives an object, with any random yaw set to 0 (wxyz). + + Reproduces LIBERO exactly, including its convention bug: TableRegionSampler._sample_quat builds an + xyzw quaternion, multiplies it with obj.init_quat (xyzw), and bddl_base_domain writes that array + straight into the wxyz qpos slot. E.g. scanned objects (plate, bowls, basket; rotation (pi/2, pi/2) + about x) therefore end up yawed by 90 deg, not rolled; HOPE groceries (dict rotation) come out + as (0.5, 0.5, 0.5, 0.5), which is the same under both readings. (Fixed 2026-10-06 after the L3 + developer found plates being stood on edge.)""" + from robosuite.utils.transform_utils import quat_multiply + + o = env.objects_dict[obj_name] + rot = getattr(o, "rotation", None) + ax = getattr(o, "rotation_axis", None) or "z" + + def xyzw(axis, a): + h = a / 2 + return {"x": np.array([np.sin(h), 0.0, 0.0, np.cos(h)]), + "y": np.array([0.0, np.sin(h), 0.0, np.cos(h)]), + "z": np.array([0.0, 0.0, np.sin(h), np.cos(h)])}[axis] + + def fixed(r): # a random range means a free angle -> use 0 (only yaw ranges occur in practice) + return float(r[0]) if float(min(r)) == float(max(r)) else 0.0 + + if isinstance(rot, dict): + q = np.array([0.0, 0.0, 0.0, 1.0]) + for axis, r in rot.items(): + q = quat_multiply(xyzw(axis, fixed(r)), q) + else: + if rot is None: + a = 0.0 + elif isinstance(rot, (tuple, list)): + a = fixed(rot) + else: + a = float(rot) + q = xyzw(ax, a) + init = np.array(getattr(o, "init_quat", [0.0, 0.0, 0.0, 1.0]), dtype=float) + q = quat_multiply(q, init) + return np.array(q, dtype=float) # used directly as wxyz, like LIBERO does + + +def obj_min_z(env, obj_name): + """Lowest world z of the object's collision geoms (exact for boxes, AABB bound for meshes).""" + m, d = env.sim.model, env.sim.data + zmin = np.inf + for g in obj_geom_ids(env, obj_name): + R = d.geom_xmat[g].reshape(3, 3) + c_local = m.geom_aabb[g, :3] + half = m.geom_aabb[g, 3:] + cz = d.geom_xpos[g][2] + R[2] @ c_local + zmin = min(zmin, cz - np.abs(R[2]) @ half) + return float(zmin) + + +def obj_max_z(env, obj_name): + """Highest world z of the object's collision geoms (exact for boxes, AABB bound for meshes).""" + m, d = env.sim.model, env.sim.data + zmax = -np.inf + for g in obj_geom_ids(env, obj_name): + R = d.geom_xmat[g].reshape(3, 3) + cz = d.geom_xpos[g][2] + R[2] @ m.geom_aabb[g, :3] + zmax = max(zmax, cz + np.abs(R[2]) @ m.geom_aabb[g, 3:]) + return float(zmax) + + +FINGERTIP_BELOW_SITE = 0.0095 # lowest point of the Panda finger collision meshes below the grasp site (measured) + + +def place_upright(env, obj_name, xy, yaw=0.0, surface_z=TABLE_Z, clearance=0.002): + """Teleport an object upright (LIBERO canonical orientation, then `yaw` about world z) so that its + lowest collision point sits `clearance` above `surface_z`. Call env.sim.forward() / settle after.""" + q = _quat_mul(np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]), canonical_quat(env, obj_name)) + set_obj_pose(env, obj_name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q) + env.sim.forward() + dz = obj_min_z(env, obj_name) - (surface_z + clearance) + qa, _ = free_joint_addr(env, obj_name) + env.sim.data.qpos[qa + 2] -= dz + env.sim.forward() + + +# ---------------------------------------------------------------- collision bounds after runtime edits (2026-10-12) + +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 _prim_bounds(m, g): + """(half extents in the geom frame, bounding-sphere radius) of a primitive geom from geom_size; None otherwise""" + t, s = int(m.geom_type[g]), m.geom_size[g] + if t == 6: # box + return np.array(s[:3], float), float(np.linalg.norm(s[:3])) + if t == 4: # ellipsoid + return np.array(s[:3], float), float(max(s[:3])) + if t == 2: # sphere + return np.full(3, float(s[0])), float(s[0]) + if t == 5: # cylinder + return np.array([s[0], s[0], s[1]], float), float(np.hypot(s[0], s[1])) + if t == 3: # capsule + return np.array([s[0], s[0], s[0] + s[1]], float), float(s[0] + s[1]) + return None + + +def refit_bounds(model, bodies, margin=0.0, geoms=True): + """Make the collision bounds of `bodies` (body id or ids) consistent again after runtime edits of their geoms + (geom_size / geom_pos / geom_quat) or of their inertial frame (body_ipos / body_iquat). `model`: an env, a + robosuite MjModel wrapper or a raw mujoco.MjModel. + + MuJoCo (3.2.3) computes these bounds at compile time and never updates them: geom_aabb / geom_rbound (geom + frame; broad phase and geom-pair filters) and the per-body bounding-volume hierarchy bvh_aabb, stored in the + body's INERTIAL frame and used by the mid-phase whenever one of the two bodies of a pair has >= 2 collision + geoms. Stale boxes make MuJoCo silently skip contacts (lh_fence v1: a post whose centre of mass was raised sank + 2.2 cm into the table; measured 2026-10-12: a body with a single collision geom whose COM moved 6 cm missed every + contact with a 2-geom body beyond the shifted box). With geoms=True the primitive geoms' geom_aabb / geom_rbound + are recomputed from geom_size (meshes keep theirs); then every BVH node becomes the union of its leaf geoms' + boxes (+ margin) in the runtime inertial frame, following body_sameframe / geom_sameframe like mj_kinematics + (on a pristine model this reproduces the compiled bvh_aabb exactly). + Also note: a runtime body_ipos is ignored by MuJoCo if the compiled inertial pos is the body origin + (body_sameframe = 1); bodies whose centre of mass is moved at runtime need a non-zero compiled inertial pos.""" + if hasattr(model, "sim"): + model = model.sim.model + m = getattr(model, "_model", model) + for b in np.atleast_1d(bodies): + b = int(b) + if geoms: + for g in range(int(m.body_geomadr[b]), int(m.body_geomadr[b] + m.body_geomnum[b])): + pb = _prim_bounds(m, g) + if pb is not None: + m.geom_aabb[g] = [0.0, 0.0, 0.0, *pb[0]] + m.geom_rbound[g] = pb[1] + a, n = int(m.body_bvhadr[b]), int(m.body_bvhnum[b]) + if a < 0 or n < 1: + continue + sf = int(m.body_sameframe[b]) # 1: inertial frame = body frame, 3: same orientation as the body + ip = np.zeros(3) if sf == 1 else np.array(m.body_ipos[b], float) + iR = np.eye(3) if sf in (1, 3) else _quat2mat(m.body_iquat[b]) + + def rec(i): + g = int(m.bvh_nodeid[i]) + if g >= 0: + gsf = int(m.geom_sameframe[g]) # 1: body frame, 2: inertial frame, 3/4: their orientation + gp = np.zeros(3) if gsf == 1 else ip if gsf == 2 else np.array(m.geom_pos[g], float) + gR = np.eye(3) if gsf in (1, 3) else iR if gsf in (2, 4) else _quat2mat(m.geom_quat[g]) + R = iR.T @ gR + c = iR.T @ (gp - ip) + R @ np.asarray(m.geom_aabb[g, :3]) + 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) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/skills.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..dd56a43114d6b80192f28dcafab9a36f2351f005 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_opus/lff/source_closure/lffbench/skills.py @@ -0,0 +1,156 @@ +"""Motion primitives executed with robosuite's OSC_POSE controller. + +All positions are world-frame metres (LIBERO table top is z = TABLE_Z = 0.90). +`bias` is a hidden calibration error added to every commanded position (used by L1 tasks); +agents never see it. +""" +import numpy as np +import robosuite.utils.transform_utils as T + +from .envs import TABLE_Z + +DT = 0.05 # control period (20 Hz) +ROT_SCALE = 0.5 +# Faster OSC than LIBERO's default (default caps the end effector at ~0.25 m/s; this reaches ~0.6 m/s). +CONTROLLER = dict(kp=300, output_max=[0.1, 0.1, 0.1, 0.5, 0.5, 0.5], output_min=[-0.1, -0.1, -0.1, -0.5, -0.5, -0.5]) + + +def _rotz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def _rot_err(R_target, R_cur): + """axis-angle (world frame) rotating R_cur to R_target""" + R = R_target @ R_cur.T + q = T.mat2quat(R) # xyzw + return T.quat2axisangle(q) + + +class Skills: + def __init__(self, env, bias=None, recorder=None): + self.env = env + self.pos_scale = float(env.robots[0].controller.output_max[0]) + self.bias = np.zeros(3) if bias is None else np.asarray(bias, float) + self.grip = -1.0 # -1 open, +1 closed + self.R0 = self.eef_mat().copy() # top-down orientation at reset == yaw 0 + self.yaw = 0.0 + self.recorder = recorder # callable(env) invoked every `record_every` control steps + self.record_every = 4 + self.n_steps = 0 + self.log = [] + + # ------------------------------------------------------------------ state + def eef_pos(self): + return self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id].copy() + + def eef_mat(self): + return self.env.sim.data.site_xmat[self.env.robots[0].eef_site_id].reshape(3, 3).copy() + + def gripper_width(self): + g = self.env.robots[0].gripper + q = [self.env.sim.data.qpos[self.env.sim.model.joint_name2id(j)] for j in g.joints] + return float(abs(q[0] - q[1])) + + def holding(self, obj_name): + return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, + object_geoms=self.env.objects_dict[obj_name])) + + # ------------------------------------------------------------------ low level + def _act(self, dpos, drot, grip): + a = np.zeros(7) + a[:3] = np.clip(dpos / self.pos_scale, -1, 1) + a[3:6] = np.clip(drot / ROT_SCALE, -1, 1) + a[6] = grip + self.env.step(a) + self.n_steps += 1 + if self.recorder is not None and self.n_steps % self.record_every == 0: + self.recorder(self.env) + + def hold(self, steps=10): + p, R = self.eef_pos(), self._R() + for _ in range(steps): + self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip) + + def _R(self, yaw=None): + return _rotz(self.yaw if yaw is None else yaw) @ self.R0 + + # ------------------------------------------------------------------ primitives + YAW_LIMIT = np.pi / 2 + 0.4 + + def wrap_yaw(self, yaw): + """A parallel-jaw gripper is symmetric under a rotation by pi, so pick the equivalent yaw closest + to the current one inside |yaw| <= pi/2 + 0.4. Without this, asking for ~180 deg of wrist rotation + makes the OSC (whose axis-angle error is ambiguous at pi) wind the arm into its joint limits and + it never recovers (found by the L3 developer: push towards -y -> 0/6 success, 2026-10-06).""" + cands = [yaw + k * np.pi for k in range(-3, 4)] + ok = [c for c in cands if abs(c) <= self.YAW_LIMIT] or cands + return float(min(ok, key=lambda c: abs(c - self.yaw))) + + def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True): + """Move the gripper site to `target` (world xyz). If `speed` (m/s) is given the reference + moves along a straight line at that speed; otherwise go as fast as the controller allows. + `yaw` is wrapped to the closest gripper-symmetric equivalent unless wrap_yaw=False. + Returns a report dict.""" + 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) + R = self._R() + p0 = self.eef_pos() + dist = np.linalg.norm(tgt - p0) + direction = (tgt - p0) / max(dist, 1e-9) + s = 0.0 + for k in range(max_steps): + if speed is not None: + s = min(dist, s + speed * DT) + ref = p0 + direction * s + # lead the reference a little so the OSC lag does not throttle the speed + ref = ref + direction * min(dist - s, speed * DT * 1.5) + else: + ref = tgt + cur = self.eef_pos() + self._act(ref - cur, _rot_err(R, self.eef_mat()), self.grip) + err = np.linalg.norm(tgt - self.eef_pos()) + if err < tol and (speed is None or s >= dist): + break + 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) + self.log.append(rep) + return rep + + def set_gripper(self, close, steps=15): + self.grip = 1.0 if close else -1.0 + self.hold(steps) + rep = dict(prim="close" if close else "open", width=round(self.gripper_width(), 4)) + self.log.append(rep) + return rep + + def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15): + """Composite: above -> descend -> close -> lift. For scripted policies.""" + 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], tol=0.003) + self.set_gripper(True, steps=15) + 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], tol=0.004) + self.set_gripper(False, steps=12) + self.move_to([xy[0], xy[1], z_release + approach]) + + def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06): + """Straight-line push: go to `pre` m behind the start point at height z with the gripper closed, + then sweep `pre + distance` along direction at `speed`, stop, and lift away.""" + d = np.asarray(direction_xy, float) + d = d / np.linalg.norm(d) + z = TABLE_Z + 0.02 if z is None else z + s = np.asarray(start_xy, float) - d * pre + self.set_gripper(True, steps=5) + self.move_to([s[0], s[1], z + 0.12], yaw=np.arctan2(d[1], d[0]) - np.pi / 2) + self.move_to([s[0], s[1], z], tol=0.003) + e = s + d * (pre + distance) + rep = self.move_to([e[0], e[1], z], speed=speed, tol=0.01, max_steps=400) + self.hold(2) + self.move_to([e[0], e[1], z + 0.12], speed=0.3) + return rep diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_card_edge.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_card_edge.py new file mode 100644 index 0000000000000000000000000000000000000000..c059c70a35c8232cfb403315761d1f526ee61693 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_card_edge.py @@ -0,0 +1,364 @@ +"""L3 card_edge: a thin card lying flat on a board cannot be pinched; slide it over the board's edge, then grasp it. + +Category: strategy_switching ("this way of doing it cannot work"), the user's taxonomy L3 example verbatim: +"卡片贴着桌面捏不起来 -> 先把卡片滑到桌沿,再夹起来". + +Scene: a wooden board (22 x 26 x 5 cm) on the table with a thin red card (9.0 x 5.6 x 0.2 cm, 10 g) lying flat on it, +long side roughly along x or along y (+-10 deg); a grey bin (16 x 16 cm inside) stands on the table beside the board. +The board stands in for the table edge of the user's example: the real table edge is out of reach (near edge 16 cm +from the robot base, side edges at |y| = 0.6 m) and the harness does not let the grasp point go below the table top. + +Why the prior fails (measured): a top-down grasp across the card's short side. The Panda fingertips land on the +board on either side of the card, but when they close on its 2 mm edge the contact flips to "slide over the top" and +both fingertips ride up over the card and close above it: 0/36 lifts for 1.5 / 2 / 3 mm cards, grasp-point height +-6..+3 mm, xy jitter 5 mm, yaw jitter 0.1 rad (prototype, 2026-10-08). Retrying with small variations fails the same +way. (A 4 mm card could be pinched -- the reason the earlier `l3_flat_card_edge` was dropped.) + +What must be learned from the failure: the card cannot be picked up while it lies flat -> change the strategy: press +the closed fingertips onto the card and slide it (move_to with the fingertips pressing on it) until part of it hangs +over the board's edge, then grasp the overhanging part with the fingertips below the card: then the fingers close on +the card's full edge and it lifts (18/18 for 2.5-3.5 cm of overhang in the prototype). More than half the card's +length over the edge and it tips off the board. + +Protocol: cross (reset to the same instance before every attempt), k = 5. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated +from ..skills import Skills +from ..task_base import LFFTask, register_task + +CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm +CARD_MASS = 0.010 +MU = 0.3 # card and board sliding friction (the fingers' 1.0 / 2.0 win in finger contacts: MuJoCo takes the max) +BOARD_HALF = (0.11, 0.13, 0.025) +BOARD_TOP = envs.TABLE_Z + 2 * BOARD_HALF[2] +BIN_IN = 0.08 # inner half width +BIN_WALL_H = 0.05 +BIN_GAP = 0.06 # board 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 +OVERHANG = 0.03 # scripted target overhang (the grasp works for ~2.5-4.0 cm; the card tips off past ~4.5 cm) +GRASP_OUT = 0.022 # scripted grasp point: this far beyond the board edge (fingers must clear the edge) +DRAG_SPEED = 0.08 + + +def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)): + g = (f' \n' + f' ') + return _wrap(name, g, CARD_HALF[2], float(np.hypot(CARD_HALF[0], CARD_HALF[1]))) + + +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))) + + +EDGES = ("forward", "backward", "left", "right") # board edges in robot-centric words (+x, -x, +y, -y) + + +class CardSkills(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 CardEdge(LFFTask): + name = "l3_card_edge" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Pick up the thin red card lying on the wooden board and put it into the grey bin." + instruction_indirect = "Put the flat red rectangle that lies on the wooden block into the grey container." + + # ------------------------------------------------------------ scene + def make_bddl(self): + card = register_generated("LffThinCard", card_xml("lff_thin_card")) + board = register_generated("LffCardBoard", box_xml("lff_card_board", BOARD_HALF, (0.62, 0.45, 0.27, 1.0), + friction=(MU, 0.005, 0.0001)), free=False) + bin_ = register_generated("LffCardBin", bin_xml("lff_card_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 = [("board_1", board, "board_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.board_bid = m.body_name2id(self.env.fixtures_dict["board_1"].root_body) + self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body) + 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"])) + yaw = (0.0 if along == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10))) + if along == "x": # keep the whole card >= 3 cm (long axis) / 2 cm (short axis) inside the board + off = [rng.uniform(-0.03, 0.03), rng.uniform(-0.07, 0.07)] + else: + off = [rng.uniform(-0.055, 0.055), rng.uniform(-0.05, 0.05)] + side = 1.0 if rng.random() < 0.5 else -1.0 + bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (BOARD_HALF[1] + BIN_GAP + BIN_HALF_OUT)] + return dict(seed=int(seed), board_xy=[bx, by], card_xy=[bx + float(off[0]), by + float(off[1])], + card_yaw=float(yaw), card_along=along, 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["board_xy"] + m.body_pos[self.board_bid] = [bx, by, envs.TABLE_Z + BOARD_HALF[2]] + m.body_quat[self.board_bid] = [1.0, 0.0, 0.0, 0.0] + cx, cy = inst["bin_xy"] + m.body_pos[self.bin_bid] = [cx, cy, envs.TABLE_Z + (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, BOARD_TOP + CARD_HALF[2] + 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 = CardSkills(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) + 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_corners(self): + d = self.env.sim.data + bid = envs.body_id(self.env, "card_1") + R = d.body_xmat[bid].reshape(3, 3) + h = np.array(CARD_HALF) + return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)]) + + def overhang(self): + """(how far the card sticks out beyond the board's edges (m, max over its corners), edge word)""" + c = self.card_corners()[:, :2] - np.asarray(self.inst["board_xy"]) + prot = {"forward": c[:, 0].max() - BOARD_HALF[0], "backward": -c[:, 0].min() - BOARD_HALF[0], + "left": c[:, 1].max() - BOARD_HALF[1], "right": -c[:, 1].min() - BOARD_HALF[1]} + e = max(prot, key=prot.get) + return float(prot[e]), e + + def on_board(self): + p = self.card_pose() + rel = np.abs(p["xy"] - np.asarray(self.inst["board_xy"])) + return bool(rel[0] <= BOARD_HALF[0] and rel[1] <= BOARD_HALF[1] and abs(p["z"] - BOARD_TOP) < 0.012) + + 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"] < envs.TABLE_Z + BIN_T + BIN_WALL_H) + + # ------------------------------------------------------------ monitor + def monitor_step(self): + mon = self.mon + if mon is None: + return + zmin = float(self.card_corners()[:, 2].min()) + mon["max_lift"] = max(mon["max_lift"], zmin - BOARD_TOP) + if self.on_board() or abs(self.card_pose()["z"] - BOARD_TOP) < 0.012: + mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0]) + if self.card_pose()["z"] < BOARD_TOP - 0.02 and not self.sk.holding("card_1"): + mon["fell"] = True + + def close_context(self): + """Where the gripper is relative to the card and the board 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 + b = e[:2] - np.asarray(self.inst["board_xy"]) + beyond = {"forward": b[0] - BOARD_HALF[0], "backward": -b[0] - BOARD_HALF[0], + "left": b[1] - BOARD_HALF[1], "right": -b[1] - BOARD_HALF[1]} + 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_board=self.on_board(), 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) + 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" + if success: + parts.append("The card is in the bin.") + else: + 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") + if held: + mode = "held" + parts.append(f"The card is still held by the gripper, {where}.") + elif lifted: + mode = "dropped" + loc = "on the board" if self.on_board() else ("on the table" if p["z"] < BOARD_TOP - 0.02 else + "partly on the board") + parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the board but is not in the " + f"bin: it lies {loc}, its centre {where}.") + elif mon["fell"]: + mode = "fell_off" + parts.append("The card was never lifted; it fell off the board and lies flat on the table.") + else: + mode = "not_lifted" + parts.append("The card was never lifted; it still lies flat on the board" + + (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to " + f"{100 * mon['max_overhang']:.1f} cm beyond the board's edge)" if mon["max_overhang"] > 0.003 + else ")") if moved > 0.005 else "") + ".") + if not lifted: + if not tries: + parts.append("The gripper never closed with its fingertips down at the card.") + else: + c = tries[-1] + n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else "" + if c["card_on_board"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0: + txt = ("when the gripper closed on the card lying flat on the board, its fingertips were on " + "either side of the card, at board level") + else: + if c["beyond_edge"] >= 0.0: + pos = f"{100 * c['beyond_edge']:.1f} cm beyond the board's {c['beyond_edge_name']} edge" + else: + pos = f"over the board, {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 " + f"beyond the board'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:]) + out = dict(success=success, mode=mode, 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"]), + grasp_tries=tries, closes=sk.closes, detail=" ".join(parts)) + return out + + # ------------------------------------------------------------ scripted policies (move_to + gripper only) + def _edge_plan(self, inst): + """the board edge the card is slid to: along its long side; the near (backward) edge for x-cards, + the closer side edge for y-cards""" + if inst["card_along"] == "x": + return "backward" + return "left" if inst["card_xy"][1] >= inst["board_xy"][1] else "right" + + 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 = envs.TABLE_Z + BIN_WALL_H + 0.12 + sk.move_to([bx, by, hi]) + sk.move_to([bx, by, envs.TABLE_Z + 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): + """closed fingertips pressed on the card's centre, straight move by `delta` (xy), lift""" + sk, p = self.sk, self.card_pose() + z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press + sk.set_gripper(True, steps=8) + sk.move_to([p["xy"][0], p["xy"][1], z + 0.06], yaw=p["yaw"]) + sk.move_to([p["xy"][0], p["xy"][1], z], tol=0.003, max_steps=100) + e = p["xy"] + 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(5) + + def execute(self, inst, params): + p = self.card_pose() + if params["mode"] == "grasp": + xy = p["xy"] + np.asarray(params.get("dxy", (0.0, 0.0))) + self.grasp_and_bin(xy, p["yaw"] + params.get("dyaw", 0.0), BOARD_TOP + params.get("dz", 0.0)) + return + # edge: slide the card along its long side until `overhang` of it sticks out over the chosen edge + edge = params.get("edge") or self._edge_plan(inst) + u = {"forward": (1, 0), "backward": (-1, 0), "left": (0, 1), "right": (0, -1)}[edge] + u = np.asarray(u, float) + c, s = np.cos(p["yaw"]), np.sin(p["yaw"]) + long_ax = np.array([c, s]) if abs(np.array([c, s]) @ u) >= abs(np.array([-s, c]) @ u) else np.array([-s, c]) + long_ax = long_ax * np.sign(long_ax @ u) + b = np.asarray(inst["board_xy"]) + half = BOARD_HALF[0] if edge in ("forward", "backward") else BOARD_HALF[1] + edge_pos = (b @ u) + half # coordinate of the edge along u + ext = CARD_HALF[0] * abs(long_ax @ u) + CARD_HALF[1] * abs(np.array([-long_ax[1], long_ax[0]]) @ u) + for short in (0.01, 0.0): # slide to 1 cm short, look again, slide the rest (one stroke overshoots ~0.7 cm) + p = self.card_pose() + need = edge_pos + float(params["overhang"]) - short - (p["xy"] @ u + ext) # travel still needed along u + if need > 0.003: + self.slide_card(long_ax * need / max(long_ax @ u, 1e-6)) + q = self.card_pose() + cu = float(q["xy"] @ u) + tip_u = cu + CARD_HALF[0] * float(long_ax @ u) # centre of the card's far end, along u + target_u = min(tip_u - 0.008, edge_pos + GRASP_OUT) + g = q["xy"] + long_ax * (target_u - cu) / max(float(long_ax @ u), 1e-6) + self.grasp_and_bin(g, q["yaw"], BOARD_TOP - 0.003) + + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="edge", overhang=OVERHANG) + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dxy=rng.normal(0.0, 0.006, 2).tolist(), dyaw=float(rng.normal(0.0, 0.12)), + dz=float(rng.uniform(-0.006, 0.003))) + + def adapt_params(self, inst, history): + """not lifted while flat on the board (fingers slid over it) -> slide it over the edge first, 3 cm. + Edge tried: card fell off -> 1 cm less; fingers closed without holding and < 4 cm overhang -> 1 cm more.""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] == "grasp": + return dict(mode="edge", overhang=OVERHANG) if out["mode"] in ("not_lifted", "fell_off") else dict(prm) + h = float(prm["overhang"]) + if out["mode"] == "fell_off": + h -= 0.01 + elif out["mode"] == "not_lifted": + h += 0.01 if out["max_overhang"] < 0.04 else -0.005 + return dict(mode="edge", overhang=float(np.clip(h, 0.025, 0.045))) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_wide.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_wide.py new file mode 100644 index 0000000000000000000000000000000000000000..4983d8290676ef823eb1ad9710447698e6bdf2d6 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l3_wide.py @@ -0,0 +1,435 @@ +"""L3-B too_wide_push: a box that is slightly too wide for the gripper must be pushed into a square on the table. + +Why the prior fails: the box looks like an ordinary graspable box (narrow side 8.3-8.9 cm, long side 11-13 cm, +4 cm high), but the Panda's fingers open to only 7.9 cm. A top-down grasp across the narrow side therefore puts +both fingers on top of the box; closing them grips nothing. Across the long side it is worse, and retrying the +same grasp with small variations fails the same way. A difference of 4-10 mm between the box and the maximum +opening is not readable from the camera images, and the agent is not told the gripper's opening. + +What must be learned from the failure: this object cannot be picked up at all -> change the manipulation mode: +close the gripper and push the box (there is no push primitive: the agent closes the gripper, lowers it beside +the box and moves it along the table with move_to), keeping the box from turning, until it lies completely +inside the square. + +Layout (randomised per instance): box size, position and yaw (long side roughly along x or along y, +-10 deg), +target square (18 x 18 cm inner, axis-aligned) 16-22 cm away along one world axis (forward, backward, left or +right) with a lateral offset of up to 3 cm. + +Protocol: cross (reset to the same instance before every attempt), k = 5. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import box_xml, register_generated +from ..skills import DT, _rot_err +from ..task_base import LFFTask, register_task +from .l5_slide import square_frame_xml + +BOX_HALF_MAX = (0.07, 0.05, 0.02) # registered size (x = long, y = narrow, z); shrunk per instance +BOX_HALF_Z = 0.02 # 4 cm high +BOX_MASS = 0.40 +BOX_MU = 0.6 # box sliding friction (priority over the table's 1.0 and the fingers') +GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open +SQ_IN = 0.09 # target square: 18 cm inner side +SQ_LINE = 0.008 +Z_GRASP = envs.TABLE_Z + 0.022 # site height of a normal top-down grasp of a 4 cm box (pads 1.7-3.4 cm above table) +Z_PUSH = envs.TABLE_Z + 0.02 # site height while pushing: finger tips ~1 cm above the table +PUSH_SPEED = 0.08 +FRONT_GAP = 0.03 # where a push stroke starts: this far behind the box face + + +def _wrap_pi(a): + return float((a + np.pi) % (2 * np.pi) - np.pi) + + +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))) + + +DIRS = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)} + + +@register_task +class TooWidePush(LFFTask): + name = "l3_too_wide_push" + level = "L3" + category = "strategy_switching" + capabilities = ("Perceive", "Reason", "Plan") + protocol = "cross" + instruction = "Put the brown box completely inside the green square marked on the table." + instruction_indirect = "Put the cardboard-coloured package completely inside the green outlined area on the table." + + def __init__(self, cam_res=None): + super().__init__(cam_res) + self._mon = None + self.inst = None + orig_step = self.env.step + + def step(action): # per-control-step event monitor (also sees agent-driven attempts) + ret = orig_step(action) + if self._mon is not None: + self._monitor_step() + return ret + + self.env.step = step + + # ------------------------------------------------------------ scene + def make_bddl(self): + box = register_generated("LffWideBox", box_xml("lff_wide_box", BOX_HALF_MAX, (0.62, 0.45, 0.28, 1.0), + density=500)) + sq = register_generated("LffWideSquare", square_frame_xml("lff_wide_square", inner_half=SQ_IN, line_w=SQ_LINE), + free=False) + objs = [("box_1", box, "box_region", (-0.11, -0.21, -0.09, -0.19))] + fx = [("square_1", sq, "square_region", (-0.01, 0.19, 0.01, 0.21))] + return write_bddl(self.name, self.instruction, objs, fx) + + def _box_geoms(self): + if not hasattr(self, "_bg"): + m = self.env.sim.model + bid = envs.body_id(self.env, "box_1") + self._bg = [g for g in range(m.ngeom) if m.geom_bodyid[g] == bid] + return self._bg + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + while True: + narrow = float(rng.uniform(0.083, 0.089)) + long_ = float(rng.uniform(0.11, 0.13)) + long_axis = str(rng.choice(["x", "y"])) + yaw = (0.0 if long_axis == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10))) + dname = str(rng.choice(list(DIRS))) + u = np.array(DIRS[dname]) + # half extent of the box along the push direction (box roughly axis aligned) + ext = 0.5 * (long_ if (long_axis == "x") == (dname in ("forward", "backward")) else narrow) + dist = float(rng.uniform(SQ_IN + ext + 0.01, SQ_IN + ext + 0.07)) + lat = float(rng.uniform(-0.03, 0.03)) + box_xy = np.array([rng.uniform(-0.20, 0.04), rng.uniform(-0.20, 0.20)]) + sq_xy = box_xy + u * dist + np.array([-u[1], u[0]]) * lat + # reach: pushing backward needs the hand ~5 cm beyond the box's far face; the arm's reach at table height + # ends around x = 0.05-0.08 (seed 1015 of the first version: hand stalled at x = 0.09, box never moved) + reach_ok = dname != "backward" or box_xy[0] + ext <= -0.01 + if -0.22 <= sq_xy[0] <= 0.06 and -0.20 <= sq_xy[1] <= 0.20 and reach_ok: + return dict(seed=int(seed), box_half=[long_ / 2, narrow / 2], box_yaw=float(yaw), box_xy=box_xy.tolist(), + square_xy=sq_xy.tolist(), direction=dname, long_axis=long_axis) + + def apply_instance(self, inst): + self.inst = inst + m = self.env.sim.model + for g in self._box_geoms(): + m.geom_size[g, 0], m.geom_size[g, 1] = inst["box_half"] + m.geom_size[g, 2] = BOX_HALF_Z + envs.scale_mass(self.env, "box_1", BOX_MASS) + envs.set_friction(self.env, "box_1", BOX_MU) + sq = self.env.fixtures_dict["square_1"] + for g in range(m.ngeom): + if (m.geom_id2name(g) or "").startswith("square_1_"): + m.geom_contype[g] = 0 + m.geom_conaffinity[g] = 0 + bid = m.body_name2id(sq.root_body) + m.body_pos[bid] = [inst["square_xy"][0], inst["square_xy"][1], envs.TABLE_Z + 0.0002] + m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0] + bx, by = inst["box_xy"] + envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF_Z + 0.0005], yaw=inst["box_yaw"]) + + def reset_instance(self, inst, recorder=None): + self._mon = None + sk = super().reset_instance(inst, recorder=recorder) + self._start_monitor() + return sk + + # ------------------------------------------------------------ geometry / perception stand-in + def observe(self): + """What a perfect perceiver reads off the image: box centre, yaw and footprint, square centre.""" + b = envs.obj_pos(self.env, "box_1") + return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + square_xy=np.array(self.inst["square_xy"], float), half=np.array(self.inst["box_half"], float)) + + def corners3d(self): + """the 8 corners of the box (world)""" + d = self.env.sim.data + bid = envs.body_id(self.env, "box_1") + R = d.body_xmat[bid].reshape(3, 3) + h = np.array([self.inst["box_half"][0], self.inst["box_half"][1], BOX_HALF_Z]) + return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, sz]) for sx in (-1, 1) for sy in (-1, 1) + for sz in (-1, 1)]) + + def corners(self, o=None): + """footprint corners (xy) of the box in its current pose (also when it is tilted or on its side)""" + return self.corners3d()[:, :2] + + def protrusion(self, o=None): + """How far the box footprint sticks out beyond each edge of the square (m, >0 = outside).""" + o = o or self.observe() + rel = self.corners(o) - o["square_xy"] + return {"forward": float(rel[:, 0].max() - SQ_IN), "backward": float(-rel[:, 0].min() - SQ_IN), + "left": float(rel[:, 1].max() - SQ_IN), "right": float(-rel[:, 1].min() - SQ_IN)} + + def extent_along(self, u, o=None): + """half extent of the box footprint along the unit xy vector u""" + o = o or self.observe() + c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"]) + hx, hy = o["half"] + return float(hx * abs(u @ [c, s]) + hy * abs(u @ [-s, c])) + + # ------------------------------------------------------------ contacts / event monitor + def _groups(self): + if not hasattr(self, "_gg"): + m = self.env.sim.model + fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")} + robot = set(envs.robot_geom_ids(self.env)) + self._gg = (fg, robot, set(envs.obj_geom_ids(self.env, "box_1"))) + return self._gg + + def _finger_landings(self): + """{'box' | 'table' | 'other': n_fingers} for fingers resting on a top surface (contact normal vertical).""" + m, d = self.env.sim.model, self.env.sim.data + fg, robot, box = self._groups() + out = {} + for i in range(d.ncon): + c = d.contact[i] + if c.geom1 in fg and c.geom2 not in robot: + f, other = c.geom1, c.geom2 + elif c.geom2 in fg and c.geom1 not in robot: + f, other = c.geom2, c.geom1 + else: + continue + if abs(c.frame[2]) < 0.7: + continue + lab = "box" if other in box else ("table" if (m.geom_id2name(other) or "").startswith("table") else "other") + name = m.geom_id2name(f) or "" + out.setdefault(lab, set()).add("1" if "finger1" in name else "2") + return out + + def _closing_axis(self): + m, d = self.env.sim.model, self.env.sim.data + jid = m.joint_name2id(self.env.robots[0].gripper.joints[0]) + a = d.xaxis[jid][:2] + return a / max(np.linalg.norm(a), 1e-9) + + def _start_monitor(self): + b = envs.obj_pos(self.env, "box_1") + self._mon = dict(rest_z=float(b[2]), start_xy=b[:2].copy(), start_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")), + max_dz=0.0, top_hit=None, prev=set(), was_held=False) + + def _monitor_step(self): + mon = self._mon + zmin = float(self.corners3d()[:, 2].min()) + mon["max_dz"] = max(mon["max_dz"], zmin - envs.TABLE_Z) # whole box above the table + hits = self._finger_landings() + open_ = self.sk is not None and self.sk.gripper_width() > 0.03 + if "box" in hits and "box" not in mon["prev"] and open_: # an open gripper landing on the box top = a grasp + o = self.observe() + ca = self._closing_axis() + e = self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id] + mon["top_hit"] = dict(span=2 * self.extent_along(ca, o), n_fingers=len(hits["box"]), + offset=float(np.linalg.norm(e[:2] - o["box_xy"]))) + if "box" in hits and len(hits["box"]) == 2 and mon["top_hit"] is not None and open_: + mon["top_hit"]["n_fingers"] = 2 + mon["prev"] = set(hits) + + # ------------------------------------------------------------ outcome / F2 + def outcome(self, inst): + """Success = the whole box footprint inside the square, box resting on the table, released.""" + envs.settle(self.env, 30) + env, mon = self.env, self._mon or {} + o = self.observe() + b = envs.obj_pos(env, "box_1") + prot = self.protrusion(o) + inside = max(prot.values()) <= 0.0 + upright = abs(envs.obj_upright_cos(env, "box_1")) > 0.9 + held = bool(self.sk.holding("box_1")) if self.sk is not None else False + zmin = float(self.corners3d()[:, 2].min()) + resting = abs(zmin - envs.TABLE_Z) < 0.01 + success = bool(inside and resting and not held) + rel = o["box_xy"] - o["square_xy"] + moved = float(np.linalg.norm(o["box_xy"] - mon.get("start_xy", o["box_xy"]))) + turned = float(np.degrees(_wrap_pi(o["box_yaw"] - mon.get("start_yaw", o["box_yaw"])))) if upright else 0.0 + lifted = mon.get("max_dz", 0.0) > 0.01 + top = mon.get("top_hit") + parts, mode = [], "success" + + def where(): + return (f"its centre is {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 square's centre") + + def sticking(): + return ", ".join(f"{100 * v:.1f} cm beyond the square's {k} edge" for k, v in + sorted(prot.items(), key=lambda kv: -kv[1]) if v > 0.0) + + if success: + parts.append("The box lies completely inside the square.") + elif b[2] < envs.TABLE_Z - 0.05: + mode = "fell_off" + parts.append("The box fell off the table.") + elif held: + mode = "held" + parts.append(f"The box is still held by the gripper; {where()}.") + elif not resting: + mode = "not_resting" + parts.append(f"The box is not resting on the table (it is propped up or tilted); {where()}.") + else: + mode = "outside" + if top is not None and not lifted: + mode = "too_wide" + if top["n_fingers"] >= 2 or top["span"] > GRIP_OPEN: + parts.append(f"The fingers came down on top of the box instead of on either side of it: along the " + f"gripper's closing direction the box measures {100 * top['span']:.1f} cm, wider than " + f"the gripper's maximum opening ({100 * GRIP_OPEN:.1f} cm). The box was not grasped.") + else: + parts.append(f"A finger came down on top of the box (the gripper was {100 * top['offset']:.1f} cm " + f"from the box centre). The box was not grasped.") + if moved < 0.01: + mode = "not_moved" if mode == "outside" else mode + parts.append(f"The box did not move; it sticks out {sticking()}.") + else: + parts.append(f"The box was moved {100 * moved:.1f} cm but is not completely inside the square: it " + f"sticks out {sticking()}; {where()}.") + if abs(turned) >= 5: + rot = "counter-clockwise" if turned > 0 else "clockwise" + parts.append(f"It turned by {abs(turned):.0f} deg ({rot} seen from above).") + if not success and not upright and mode not in ("fell_off",): + parts.append("The box is no longer lying on its large bottom face.") + out = dict(success=success, mode=mode, inside=bool(inside), protrusion=prot, rel=[float(rel[0]), float(rel[1])], + moved=moved, turned_deg=turned, lifted=bool(lifted), held=held, upright=bool(upright), + top_hit_span=None if top is None else float(top["span"]), + terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts)) + self._start_monitor() + return out + + # ------------------------------------------------------------ primitives for the scripted policies + def _yaw_near(self, yaw): + cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)] + cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands + return float(min(cands, key=lambda c: abs(c - self.sk.yaw))) + + def _align(self, tol=0.03, max_steps=60): + sk = self.sk + for _ in range(max_steps): + R = sk._R() @ sk.eef_mat().T + if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol: + break + sk.hold(1) + + def _guarded_descent(self, xyz, speed=0.12, max_steps=60): + """descent that stops when a finger lands on a top surface above the target (contact sensing)""" + sk = self.sk + p0 = sk.eef_pos() + tgt = np.asarray(xyz, float) + dist = max(np.linalg.norm(tgt - p0), 1e-6) + R = sk._R() + for k in range(max_steps): + ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist) + sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip) + if self._finger_landings() and sk.eef_pos()[2] > tgt[2] + 0.005: + break + if np.linalg.norm(tgt - sk.eef_pos()) < 0.003: + break + sk.hold(4) + + def _finger_front(self, direction): + m, d = self.env.sim.model, self.env.sim.data + e = self.sk.eef_pos() + best = 0.0 + for g in range(m.ngeom): + if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7: + continue + mid = m.geom_dataid[g] + v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]] + w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e + best = max(best, float((w[:, :2] @ direction).max())) + return best + + def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0, across="narrow"): + """Top-down grasp across the box's narrow side at its centre (+ offsets); if it is held, put it in the square.""" + sk, o = self.sk, self.observe() + gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy + # yaw 0 closes along world y; to close across the narrow side (box local y) use the box yaw + yaw = self._yaw_near(o["box_yaw"] + (0.0 if across == "narrow" else np.pi / 2) + dyaw) + sk.set_gripper(False, steps=8) + sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw) + self._align() + self._guarded_descent([gx, gy, Z_GRASP]) + sk.set_gripper(True, steps=15) + z0 = envs.obj_pos(self.env, "box_1")[2] + sk.move_to([gx, gy, Z_GRASP + 0.12], speed=0.25) + if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.06): + sk.set_gripper(False, steps=8) + return + sx, sy = o["square_xy"] + sk.move_to([sx, sy, Z_GRASP + 0.12]) + sk.move_to([sx, sy, Z_GRASP + 0.005]) + sk.set_gripper(False, steps=12) + sk.move_to([sx, sy, Z_GRASP + 0.12]) + + def push_stroke(self, u, dist): + """Closed gripper behind the box face opposite to u (fingers side by side across the push direction), sweep + along u so that the box moves `dist`, then lift away. Built from move_to + close only.""" + sk, o = self.sk, self.observe() + u = np.asarray(u, float) / np.linalg.norm(u) + c = o["box_xy"] + ext = self.extent_along(u, o) + yaw = self._yaw_near(float(np.arctan2(u[1], u[0]))) # yaw a: closing axis along (-sin a, cos a), i.e. across u + sk.set_gripper(True, steps=6) + face = c - u * ext + p_hi = face - u * 0.08 + sk.move_to([p_hi[0], p_hi[1], Z_PUSH + 0.10], yaw=yaw) + self._align() + front = self._finger_front(u) + start = face - u * (front + FRONT_GAP) + stop = face + u * (dist - front) + sk.move_to([start[0], start[1], Z_PUSH + 0.10]) + sk.move_to([start[0], start[1], Z_PUSH], tol=0.003) + sk.move_to([stop[0], stop[1], Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400) + sk.hold(3) + back = stop - u * 0.02 + sk.move_to([back[0], back[1], Z_PUSH], speed=0.1, max_steps=40) + sk.move_to([back[0], back[1], Z_PUSH + 0.10], speed=0.25) + + def push_to(self, goal_xy, max_strokes=4, tol=0.008): + """Closed-loop push along the box's own axes (each stroke perpendicular to a face keeps the box from turning): + re-observe after every stroke, push along the axis with the larger remaining error.""" + for _ in range(max_strokes): + o = self.observe() + d = np.asarray(goal_xy, float) - o["box_xy"] + c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"]) + axes = [np.array([c, s]), np.array([-s, c])] + comps = [float(d @ a) for a in axes] + i = int(np.argmax(np.abs(comps))) + if abs(comps[i]) < tol: + break + u = axes[i] * np.sign(comps[i]) + self.push_stroke(u, abs(comps[i])) + + def execute(self, inst, params): + if params["mode"] == "push": + goal = np.array(inst["square_xy"]) + np.asarray(params.get("goal_offset", (0.0, 0.0))) + self.push_to(goal, max_strokes=params.get("strokes", 4)) + else: + self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0), + params.get("across", "narrow")) + + # ------------------------------------------------------------ scripted references + def default_params(self, inst): + return dict(mode="grasp") + + def oracle_params(self, inst): + return dict(mode="push") + + def blind_params(self, inst, attempt, rng): + return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)), + dyaw=float(rng.normal(0, 0.15))) + + def adapt_params(self, inst, history): + """too_wide (fingers on top of the box, span > opening) -> the box cannot be picked up: push it instead. + A push that leaves the box outside -> push again, aiming past the reported miss (box centre offset).""" + out, prm = history[-1]["outcome"], history[-1]["params"] + if prm["mode"] != "push": + if out["mode"] in ("too_wide", "not_moved"): + return dict(mode="push") + return dict(prm) + if out["mode"] == "outside": + off = np.asarray(prm.get("goal_offset", (0.0, 0.0))) - 0.5 * np.asarray(out["rel"]) + return dict(mode="push", goal_offset=off.tolist()) + return dict(prm) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l4_diagonal.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l4_diagonal.py new file mode 100644 index 0000000000000000000000000000000000000000..684ff8c0dcfa6eb30284e0594ecef678d04a733b --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l4_diagonal.py @@ -0,0 +1,524 @@ +"""L4-B diagonal_fit: put a long bar flat into an open box whose inside is shorter than the bar. + +Scene: one open box (inner a x b, a slightly longer than b, 3 cm walls) and a long, thin wooden bar +(L x 1.2 x 1.4 cm) lying on the table in front of it. The bar is 1.2-2.2 cm longer than the box's inside +length, so it never fits lined up with a side of the box -- it fits only when turned towards the box's +diagonal, at an angle that depends on a, b and L (36-45 deg off the long side; the fitting window at zero +centring error is 12-25 deg wide, see task card). + +Hidden: the exact dimensions (the bar is only 8-17 % longer than the box -- easy to miss at a glance), and +that a diagonal placement exists. Box and bar are resized per instance by editing geom sizes in sim.model, +so one env serves every instance (same technique as l4_fit_container). + +Prior (naive): tidy placement -- line the bar up with the box's long side. It always ends lying across the +box on the rim (visible). F2 after a failure: where the bar lies, the angle between bar and box, and by how +much the bar's footprint at that angle is longer than the inside of the box along the box's long / short +side. A learner can work out the bar length from that and turn the bar towards the diagonal; a second +failure (angle slightly off) gives the over-length along the other side, which tells it which way to correct. + +Only move_to / open / close are needed: grasp the bar in the middle, turn the wrist, release above the box. +""" +import numpy as np + +from .. import envs +from ..bddl import write_bddl +from ..objects import bin_xml, box_xml, register_generated +from ..skills import _rot_err +from ..task_base import LFFTask, register_task + +# bar (local x = long axis); length set per instance +BAR_W, BAR_H = 0.012, 0.014 +BAR_L_MAX = 0.160 +BAR_RGBA = (0.72, 0.36, 0.14, 1.0) +# box (local x = long axis of the opening); inner size set per instance +WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030 +BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height +RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H +BOX_RGBA = (0.55, 0.62, 0.70, 1.0) +# sampling ranges (m) +INNER_A = (0.115, 0.130) # inside length of the box +A_MINUS_B = (0.004, 0.020) # the box is a little longer than wide +OVER_LEN = (0.010, 0.020) # bar length minus inside length of the box +MIN_MARGIN = 0.011 # best-angle clearance (total) the sampler insists on +MIN_WINDOW_DEG = 8.0 # width of the angle window with >= 6 mm total clearance +# execution +Z_GRASP = envs.TABLE_Z + 0.0105 # gripper site; pads span ~0.55-2.25 cm above the table, tips just clear it +Z_CARRY = envs.TABLE_Z + 0.15 +DROP = 0.010 # bar bottom this far above the rim at release +PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) +PERC_SIGMA = 0.003 # perception noise of the scripted adaptive learner (box inner size, bar width) + + +MIDPHASE_OFF = True + + +def disable_midphase(env): + """Box and bar are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding + volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered + size. A box wall moved inwards out of its compiled leaf box is silently skipped by the mid-phase (found on the + nest_order cups, 2026-10-07: the fingers passed through resized walls). Without the mid-phase MuJoCo tests all + geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set when resizing).""" + import mujoco + m = env.sim.model._model + m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE) + + +def wrap_half(a): + """angle modulo pi into [-pi/2, pi/2) (bar and box are 180-deg symmetric)""" + return float((a + np.pi / 2) % np.pi - np.pi / 2) + + +def fold_quarter(a): + """|angle| between two pi-symmetric axes, in [0, pi/2]""" + a = abs(wrap_half(a)) + return float(min(a, np.pi - a)) + + +def footprint(L, W, rel): + """extent of an L x W rectangle turned by rel against the box axes: (along long side, along short side)""" + c, s = abs(np.cos(rel)), abs(np.sin(rel)) + return L * c + W * s, L * s + W * c + + +def margins(L, W, a, b, rel): + e1, e2 = footprint(L, W, rel) + return a - e1, b - e2 + + +def best_angle(L, W, a, b, n=1801): + """angle in [0, pi/2] maximising the smaller of the two clearances; returns (angle, clearance, window)""" + th = np.linspace(0.0, np.pi / 2, n) + m1, m2 = margins(L, W, a, b, th) + m = np.minimum(m1, m2) + i = int(np.argmax(m)) + ok = th[m >= 0.006] + win = float(np.degrees(ok.max() - ok.min())) if len(ok) else 0.0 + return float(th[i]), float(m[i]), win + + +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): + 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 + + +def _rel_dir(dx, dy): + """robot-centric text for an offset in the world frame (forward = +x, left = +y), ending in 'of' / 'from'""" + parts = [] + if abs(dx) >= 0.005: + parts.append(f"{100 * abs(dx):.1f} cm {'forward' if dx > 0 else 'backward'}") + if abs(dy) >= 0.005: + parts.append(f"{100 * abs(dy):.1f} cm to the {'left' if dy > 0 else 'right'}") + return " and ".join(parts) + " of" if parts else "within 0.5 cm of" + + +def _turn_text(signed_deg): + """relative orientation of the bar against the box's long side (no absolute angles)""" + if abs(signed_deg) < 2.0: + return "lies along the box's long side (within 2 degrees)" + side = "counterclockwise (towards the left)" if signed_deg > 0 else "clockwise (towards the right)" + return f"is turned about {abs(signed_deg):.0f} degrees {side}, seen from above, from the box's long side" + + +@register_task +class DiagonalFit(LFFTask): + name = "l4_diagonal_fit" + level = "L4" + category = "geometry_inference" + capabilities = ("Perceive", "Reason") + instruction = "Put the wooden bar into the box so that it lies flat on the bottom of the box." + instruction_indirect = "Put the long brown stick into the grey open tray so that it lies flat on the tray's floor." + + # ------------------------------------------------------------ scene + def make_bddl(self): + bar = register_generated("LffDiagBar", box_xml("lff_diag_bar", (BAR_L_MAX / 2, BAR_W / 2, BAR_H / 2), + BAR_RGBA, density=700)) + box = register_generated("LffDiagBox", bin_xml("lff_diag_box", (0.065, 0.065), WALL_H, wall_t=WALL_T, + floor_t=FLOOR_T, rgba=BOX_RGBA, density=3000)) + objs = [("bar_1", bar, "bar_region", (0.02, -0.01, 0.04, 0.01)), + ("box_1", box, "box_region", (-0.19, -0.01, -0.17, 0.01))] + return write_bddl(self.name, self.instruction, objs) + + def sample_instance(self, seed): + rng = np.random.default_rng(seed) + for _ in range(1000): + a = float(rng.uniform(*INNER_A)) + b = float(a - rng.uniform(*A_MINUS_B)) + L = float(a + rng.uniform(*OVER_LEN)) + th, m, win = best_angle(L, BAR_W, a, b) + if m < MIN_MARGIN or win < MIN_WINDOW_DEG: + continue + box_xy = [float(rng.uniform(-0.22, -0.13)), float(rng.uniform(-0.10, 0.10))] + box_yaw = float(rng.uniform(-np.pi / 4, np.pi / 4)) + bar_xy = [float(rng.uniform(-0.01, 0.05)), float(rng.uniform(-0.13, 0.13))] + bar_yaw = float(rng.uniform(-np.pi / 2, np.pi / 2)) + r_box = (box_xy, box_yaw, (a / 2 + WALL_T + 0.03, b / 2 + WALL_T + 0.03)) + r_bar = (bar_xy, bar_yaw, (L / 2 + 0.01, BAR_W / 2 + 0.03)) + if _rects_overlap(r_box, r_bar): + continue + break + else: + raise RuntimeError("could not sample an instance") + prng = np.random.default_rng(seed + 7919) + perc = [float(a + prng.normal(0, PERC_SIGMA)), float(b + prng.normal(0, PERC_SIGMA)), + float(BAR_W + prng.normal(0, PERC_SIGMA / 2))] + return dict(seed=int(seed), inner=[a, b], bar_len=L, bar_xy=bar_xy, bar_yaw=bar_yaw, box_xy=box_xy, + box_yaw=box_yaw, fit_angle_deg=float(np.degrees(th)), fit_margin_cm=float(100 * m), + fit_window_deg=win, _perc=perc) + + def _reshape_box(self, 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["box_1"] + 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 _resize_bar(self, L): + m = self.env.sim.model + o = self.env.objects_dict["bar_1"] + for n in list(o.contact_geoms) + list(o.visual_geoms): + g = m.geom_name2id(n) + m.geom_size[g] = [L / 2, BAR_W / 2, BAR_H / 2] + m.geom_rbound[g] = float(np.linalg.norm(m.geom_size[g])) + m.geom_aabb[g] = [0, 0, 0, *m.geom_size[g]] + # keep the mass of the resized bar consistent with its volume (density 700); the geoms live in the + # child body "object", not in the root body that carries the free joint + bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])]) + mass = 700.0 * L * BAR_W * BAR_H + m.body_mass[bid] = mass + m.body_inertia[bid] = mass / 12.0 * np.array([BAR_W ** 2 + BAR_H ** 2, L ** 2 + BAR_H ** 2, + L ** 2 + BAR_W ** 2]) + + def apply_instance(self, inst): + if MIDPHASE_OFF: + disable_midphase(self.env) + self._reshape_box(*inst["inner"]) + self._resize_bar(inst["bar_len"]) + envs.set_obj_pose(self.env, "box_1", [*inst["box_xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], + yaw=inst["box_yaw"]) + envs.set_obj_pose(self.env, "bar_1", [*inst["bar_xy"], envs.TABLE_Z + BAR_H / 2 + 0.0005], + yaw=inst["bar_yaw"]) + + # ------------------------------------------------------------ outcome + def _pose(self, name): + bid = envs.body_id(self.env, name) + R = self.env.sim.data.body_xmat[bid].reshape(3, 3) + return self.env.sim.data.body_xpos[bid].copy(), R + + def outcome(self, inst): + envs.settle(self.env, 40) + a, b = inst["inner"] + L = inst["bar_len"] + p, R = self._pose("bar_1") + ax = R[:, 0] + bar_yaw = float(np.arctan2(ax[1], ax[0])) + tilt = float(np.degrees(np.arcsin(min(1.0, abs(ax[2]))))) # long axis vs horizontal + c, Rb = self._pose("box_1") + byaw = float(np.arctan2(Rb[1, 0], Rb[0, 0])) + btilt = float(np.degrees(np.arccos(np.clip(Rb[2, 2], -1, 1)))) + held = bool(self.sk is not None and self.sk.holding("bar_1")) + rel = fold_quarter(bar_yaw - byaw) + # bar footprint corners in the box frame + Rz = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) + corners = _rect_corners(p[:2], bar_yaw, (L / 2 * np.cos(np.radians(tilt)), BAR_W / 2)) + loc = (corners - c[:2]) @ Rz.T + out_x = float(np.max(np.abs(loc[:, 0])) - a / 2) + out_y = float(np.max(np.abs(loc[:, 1])) - b / 2) + centre = Rz @ (p[:2] - c[:2]) + floor_top = c[2] - BOX_HALF_H + FLOOR_T + height = float(envs.obj_min_z(self.env, "bar_1") - floor_top) + in_opening = out_x <= 0.002 and out_y <= 0.002 + on_floor = height < 0.005 and tilt < 6.0 + success = bool(in_opening and on_floor and not held and btilt < 10.0) + m_long, m_short = margins(L, BAR_W, a, b, rel) + fb = dict(rel_deg=round(float(np.degrees(rel)), 1), + over_long_cm=round(-100 * m_long, 1) if m_long < -0.001 else None, + over_short_cm=round(-100 * m_short, 1) if m_short < -0.001 else None, + spare_long_cm=round(100 * max(m_long, 0.0), 1) if m_long >= -0.001 else None, + spare_short_cm=round(100 * max(m_short, 0.0), 1) if m_short >= -0.001 else None, + centre_offset_cm=[round(100 * float(centre[0]), 1), round(100 * float(centre[1]), 1)]) + res = dict(success=success, height_cm=round(100 * height, 2), tilt_deg=round(tilt, 1), held=held, + rel_deg=fb["rel_deg"], bar_xy=[float(p[0]), float(p[1])], feedback=fb) + signed = float(np.degrees(wrap_half(bar_yaw - byaw))) + fb["rel_signed_deg"] = round(signed, 1) + off_w = p[:2] - c[:2] # bar centre relative to the box centre, world axes (only relative values are reported) + if held: + res["detail"] = "The bar is still in the gripper." + res["failure"] = "held" + return res + over_box = abs(centre[0]) < a / 2 + WALL_T and abs(centre[1]) < b / 2 + WALL_T + on_table = envs.obj_min_z(self.env, "bar_1") < envs.TABLE_Z + 0.008 # (floor_top is FLOOR_T above the table) + if not over_box and on_table: + res["detail"] = (f"The bar is not in the box: it is lying on the table, its centre " + f"{_rel_dir(*off_w)} the box's centre.") + res["failure"] = "table" + return res + if success: + res["detail"] = "The bar is lying flat on the bottom of the box." + res["failure"] = None + return res + if not over_box: + res["detail"] = (f"The bar is not in the box: it ended partly on the box's rim, " + f"{100 * (p[2] - envs.TABLE_Z):.1f} cm above the table, its centre " + f"{_rel_dir(*off_w)} the box's centre.") + res["failure"] = "off" + return res + pose_txt = (f"lying across the top of the box on its rim, {100 * height:.1f} cm above the box floor" + if tilt < 6.0 else + f"tilted about {tilt:.0f} degrees, with one end down inside the box and the other end on the rim") + txt = f"The bar did not go in: it is {pose_txt}. The bar {_turn_text(signed)}." + parts = [] + if fb["over_long_cm"]: + parts.append(f"{fb['over_long_cm']:.1f} cm longer than the inside of the box along the box's long side") + if fb["over_short_cm"]: + parts.append(f"{fb['over_short_cm']:.1f} cm longer than the inside of the box along the box's short side") + if parts: + txt += " At that angle the bar's footprint is " + " and ".join(parts) + "." + else: + txt += (f" At that angle the bar's footprint is smaller than the opening (spare {fb['spare_long_cm']:.1f} cm " + f"along the long side, {fb['spare_short_cm']:.1f} cm along the short side), but it caught on the " + f"rim (bar centre {_rel_dir(*off_w)} the box's centre).") + res["detail"] = txt + res["failure"] = "rim" + return res + + # ------------------------------------------------------------ execution + def execute(self, inst, params): + """params: rel_yaw (rad) = angle of the bar's long axis against the box's long side at release. + Optional (tolerance checks): dx / dy release offset of the bar centre from the box centre along the + box's long / short axis (m); drop = bar bottom above the rim at release (m).""" + sk, env = self.sk, self.env + px, py = inst["bar_xy"] + g0 = wrap_half(inst["bar_yaw"]) # yaw 0 closes the fingers along world y = across a bar lying along x + sk.set_gripper(False, steps=5) + sk.move_to([px, py, Z_GRASP + 0.10], yaw=g0) + sk.move_to([px, py, Z_GRASP], tol=0.003) + sk.set_gripper(True, steps=15) + sk.move_to([px, py, Z_CARRY], speed=0.25) + byaw = inst["box_yaw"] + c, s = np.cos(byaw), np.sin(byaw) + dx, dy = params.get("dx", 0.0), params.get("dy", 0.0) + bx, by = inst["box_xy"][0] + c * dx - s * dy, inst["box_xy"][1] + s * dx + c * dy + sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(byaw + params["rel_yaw"])) + off = envs.obj_pos(env, "bar_1") - sk.eef_pos() + drop = params.get("drop", DROP) + sk.move_to([bx - off[0], by - off[1], RIM_Z + drop + BAR_H / 2 + 0.04 - off[2]], tol=0.003) + tgt = self._servo_bar([bx, by], RIM_Z + drop) + sk.grip = -1.0 + 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_bar(self, xy, z_bottom, max_steps=60, tol=0.0015): + """closed loop on the held bar's centre (scripted policies only)""" + sk = self.sk + R = sk._R() + goal = np.array([xy[0], xy[1], z_bottom + BAR_H / 2]) + tgt = e_prev = sk.eef_pos() + for i in range(max_steps): + pb, e = envs.obj_pos(self.env, "bar_1"), sk.eef_pos() + if i >= 8 and np.linalg.norm(pb - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005: + break + tgt = goal - (pb - e) + sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip) + e_prev = e + return tgt + + # ------------------------------------------------------------ scripted policies + def _signed(self, inst, th): + """+th or -th, whichever needs the smaller wrist turn from the bar's current orientation""" + cur = wrap_half(inst["bar_yaw"] - inst["box_yaw"]) + return min((th, -th), key=lambda t: abs(wrap_half(t - cur))) + + def default_params(self, inst): + """tidy prior: bar lined up with the box's long side""" + return dict(rel_yaw=0.0) + + def oracle_params(self, inst): + return dict(rel_yaw=self._signed(inst, np.radians(inst["fit_angle_deg"]))) + + def blind_params(self, inst, attempt, rng): + """no history: the prior again with a little jitter in angle and position""" + return dict(rel_yaw=float(rng.normal(0.0, np.radians(4.0))), dx=float(rng.normal(0, 0.003)), + dy=float(rng.normal(0, 0.003))) + + def adapt_params(self, inst, history): + """Scripted learner on F2 feedback. + + Knows the box's inner size and the bar's width only through noisy perception (inst['_perc'], + sigma = PERC_SIGMA), not the bar's length. Every 'X cm longer than the inside along the long / short side + at angle d' gives an equation for the bar length L (L cos d + W sin d = a + X, or L sin d + W cos d = b + X); + 'spare' values give the same with a negative X. It takes the largest length estimate (conservative) and turns + the bar to the angle with the largest clearance for that length; if the last attempt was already at a + feasible angle and only missed the centre, it keeps the angle.""" + a, b, W = inst["_perc"] + Ls = [] + for h in history: + fb = h["outcome"].get("feedback") or {} + if h["outcome"].get("failure") != "rim": + continue + d = np.radians(fb["rel_deg"]) + c, s = np.cos(d), np.sin(d) + if c > 0.3: + x = fb["over_long_cm"] if fb["over_long_cm"] is not None else -fb["spare_long_cm"] + Ls.append((a + x / 100 - W * s) / c) + if s > 0.3: + x = fb["over_short_cm"] if fb["over_short_cm"] is not None else -fb["spare_short_cm"] + Ls.append((b + x / 100 - W * c) / s) + L_est = max(Ls) if Ls else a + 0.015 + th, m, _ = best_angle(L_est, W, a, b) + return dict(rel_yaw=self._signed(inst, th), L_est=float(L_est)) + + def random_yaw_params(self, inst, history, rng): + """sensitivity variant: a random orientation each retry, no history""" + return dict(rel_yaw=float(rng.uniform(-np.pi / 2, np.pi / 2))) + + EXTRA_KINDS = ("random_yaw",) + + 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) + params = self.default_params(inst) if a == 0 else self.random_yaw_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=10, out=None): + """Release angles 0 / 90 deg (must fail), +-best angle (must succeed) and best +- 6 deg (report).""" + import json + task = DiagonalFit() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + th = np.radians(inst["fit_angle_deg"]) + for name, rel, expect in [("aligned", 0.0, False), ("crossed", np.pi / 2, False), ("best+", th, True), + ("best-", -th, True), ("best-6", th - np.radians(6), None), + ("best+6", th + np.radians(6), None)]: + task.reset_instance(inst) + task.execute(inst, dict(rel_yaw=float(rel))) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, rel_deg=float(np.degrees(rel)), success=o["success"], expect=expect, + failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"], + inner_cm=[round(100 * v, 2) for v in inst["inner"]], bar_cm=round(100 * inst["bar_len"], 2), + fit_margin_cm=round(inst["fit_margin_cm"], 2), fit_window_deg=round(inst["fit_window_deg"], 1))) + flag = "" if expect is None or expect == o["success"] else " <-- MISMATCH" + print(f"seed {seed} {name:8s} rel={np.degrees(rel):+6.1f} succ={o['success']} h={o['height_cm']} " + f"tilt={o['tilt_deg']} margin={inst['fit_margin_cm']:.2f}cm win={inst['fit_window_deg']:.1f}{flag}", + flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + bad = [r for r in rows if r["expect"] is not None and r["expect"] != r["success"]] + print("total", len(rows), "mismatches", len(bad)) + return rows + + +def window_check(seed0=1000, n=6, out=None): + """Release angle swept around the best angle (-16..+16 deg, step 2), bar centred: the physical fitting window + against the geometric clearance.""" + import json + task = DiagonalFit() + rows = [] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + th = inst["fit_angle_deg"] + L, (a, b) = inst["bar_len"], inst["inner"] + for d in range(-16, 17, 2): + rel = np.radians(th + d) + task.reset_instance(inst) + task.execute(inst, dict(rel_yaw=float(rel))) + o = task.outcome(inst) + m1, m2 = margins(L, BAR_W, a, b, rel) + rows.append(dict(seed=seed, d_deg=d, rel_deg=round(th + d, 1), success=o["success"], + clearance_mm=round(1000 * float(min(m1, m2)), 1))) + print(f"seed {seed} best={th:.1f} " + " ".join(f"{r['d_deg']:+d}:{'S' if r['success'] else '.'}" + for r in rows if r["seed"] == seed), flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + return rows + + +def robustness_check(seed0=1000, n=6, out=None): + """Execution errors at the best angle: release off-centre along the box's long / short axis, angle off by + +-4 / +-8 deg, released 3 cm above the rim.""" + import json + task = DiagonalFit() + rows = [] + cases = [("best", {}), ("dx4", dict(dx=0.004)), ("dy4", dict(dy=0.004)), ("dx7", dict(dx=0.007)), + ("dy7", dict(dy=0.007)), ("ang+4", dict(dang=4)), ("ang-4", dict(dang=-4)), ("ang+8", dict(dang=8)), + ("ang-8", dict(dang=-8)), ("drop3cm", dict(drop=0.03)), ("dx4_ang4_drop3", dict(dx=0.004, dang=4, drop=0.03))] + for seed in range(seed0, seed0 + n): + inst = task.sample_instance(seed) + th = inst["fit_angle_deg"] + for name, c in cases: + params = dict(rel_yaw=float(np.radians(th + c.get("dang", 0)))) + params.update({k: v for k, v in c.items() if k != "dang"}) + task.reset_instance(inst) + task.execute(inst, params) + o = task.outcome(inst) + rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], + fit_margin_cm=round(inst["fit_margin_cm"], 2))) + print(f"seed {seed} {name:15s} succ={o['success']} | {o['detail'][:160]}", flush=True) + if out: + with open(out, "w") as f: + json.dump(rows, f, indent=1) + for name, _ in cases: + r = [x["success"] for x in rows if x["case"] == name] + print(f"{name:15s} {sum(r)}/{len(r)}") + return rows + + +if __name__ == "__main__": + # python -m lffbench.tasks.l4_diagonal physics results/l4_diagonal_fit/physics_check.json + import sys + # python -m lffbench.tasks.l4_diagonal window results/l4_diagonal_fit/window_check.json + # python -m lffbench.tasks.l4_diagonal robust results/l4_diagonal_fit/robustness_check.json + if sys.argv[1] == "physics": + physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, + n=int(sys.argv[3]) if len(sys.argv) > 3 else 10) + elif sys.argv[1] == "window": + window_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6) + elif sys.argv[1] == "robust": + robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6) diff --git a/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l6_count.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/l6_count.py new file mode 100644 index 0000000000000000000000000000000000000000..8bfcc8725cbfb523898ced10b2974c65b5b3b82f --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/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/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/lh_bystander.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/lffbench/tasks/lh_bystander.py new file mode 100644 index 0000000000000000000000000000000000000000..d29e80c05aadc9cd8aa5e69c81d724f4cd45d971 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/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/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/la_report.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/la_report.py new file mode 100644 index 0000000000000000000000000000000000000000..d191a51e7bf72871da213d7207d1a85502d6cd76 --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/la_report.py @@ -0,0 +1,93 @@ +"""Per-run table for LA-interface (LIBERO-Agent-style) GPT runs: outcomes from the robot-server log, tool use and +token cost from the player transcript. + +python scripts/la_report.py --batch la1_rgb la1_rgbd [--out ../docs/la1_table.md] +""" +import argparse +import json +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +from full_report import run_info # noqa: E402 + + +def transcript_stats(log): + p = os.path.join(log, "transcript.jsonl") # api_player (unified harness); gpt_player wrote gpt_transcript.jsonl + if not os.path.exists(p): + p = os.path.join(log, "gpt_transcript.jsonl") + st = dict(turns=0, shell=0, view=0, robot=0, auto_finish=0, api_err=0, inp=0, cached=0, out=0, reason=0, ended=None) + if not os.path.exists(p): + au = os.path.join(log, "audit.json") # Claude subagent runs: tool counts from the audit of its transcript + if os.path.exists(au): + d = json.load(open(au)) + bt = d.get("by_tool", {}) + st.update(turns=d.get("n_calls", 0), view=bt.get("Read", 0), shell=bt.get("Bash", 0), + ended=f"audited ({d.get('n_violations')} violations, memory_injected={d.get('memory_injected')})") + return st + for l in open(p): + d = json.loads(l) + ev = d["ev"] + if ev == "assistant": + st["turns"] += 1 + u = d.get("usage") or {} + st["inp"] += u.get("input_tokens", 0) + st["cached"] += u.get("cached_tokens", 0) + st["out"] += u.get("output_tokens", 0) + st["reason"] += u.get("reasoning_tokens", 0) + elif ev == "tool": + c = d.get("command", "") + if c.startswith("shell:"): + st["shell"] += 1 + elif c.startswith("view_images"): + st["view"] += 1 + else: + st["robot"] += 1 + elif ev == "user" and d.get("auto_finish"): + st["auto_finish"] += 1 + elif ev == "api_error": + st["api_err"] += 1 + elif ev in ("end", "abort"): + st["ended"] = ev if ev == "end" else "abort: " + d.get("reason", "") + return st + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--batch", nargs="+", required=True) + ap.add_argument("--out", default=None) + ap.add_argument("--runs", default="gpt", help="runs// (gpt or claude); for claude, 'shell' = all Bash " + "calls (robot + shell) and 'view' = Read calls, from audit.json") + a = ap.parse_args() + L = ["| batch | task | perception | outcomes | robot cmds | grasps held/closed | shell | view | turns | " + "auto-finish | input Mtok (cached) | output ktok (reasoning) | wall min | state |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|"] + tot = dict(inp=0, cached=0, out=0, reason=0) + for b in a.batch: + m = json.load(open(os.path.join(ROOT, "runs", a.runs, b, "manifest.json"))) + for r in m["runs"]: + try: + x = run_info(r) + except FileNotFoundError: + continue + t = transcript_stats(r["log"]) + for k in tot: + tot[k] += t[k] + task = r["task"] + (" (nominal)" if r.get("nominal") else "") + L.append(f"| {b} | {task} | {r.get('perception')} | {x['outcomes'] or '—'} | {x['cmds']} | " + f"{x['held']}/{x['closes']} | {t['shell']} | {t['view']} | {t['turns']} | {t['auto_finish']} | " + f"{t['inp'] / 1e6:.2f} ({t['cached'] / 1e6:.2f}) | {t['out'] / 1e3:.0f} ({t['reason'] / 1e3:.0f}) | " + f"{(x['wall'] or 0):.0f} | {t['ended'] or 'running'} |") + L.append("") + L.append(f"Total tokens: input {tot['inp'] / 1e6:.2f} M (cached {tot['cached'] / 1e6:.2f} M), " + f"output {tot['out'] / 1e3:.0f} k (reasoning {tot['reason'] / 1e3:.0f} k).") + 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/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/tool_gateway.py b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/tool_gateway.py new file mode 100644 index 0000000000000000000000000000000000000000..feafd5cd52edf151c062ca04ac2e856ded80618c --- /dev/null +++ b/leaf/release/source_packages/remaining-lh-20261103-remaining_lh_quota_20261104_opus/lff/source_closure/scripts/tool_gateway.py @@ -0,0 +1,331 @@ +"""Per-episode tool gateway (docs/18 §6.1): the one implementation of the three LA tools for every access path. + +`robot` (forwarded to robot_server), `shell` (jailed, in the episode workspace) and `view_images` (workspace image files), +with the per-attempt tool-call budget counted here once for the whole episode: when it is used up the attempt is +finished automatically and the result is appended to that call's output. The MCP server (scripts/mcp_robot_server.py) +and the Python SDK (client/lffbench_client) are thin clients of this process, so a native harness (Codex, Claude Code) +and a robot harness framework (RPent, ...) get the same tools, outputs and limits. The gateway runs outside the harness +jail next to robot_server; harness processes only see its HTTP port and token, never robot_server's token, the +workspace files or a shell of their own. + + python scripts/tool_gateway.py --session runs/<...>/session.json +writes /gateway.json {url, port, pid, token} (mode 600) once it listens and logs every call to +/gateway_transcript.jsonl. HTTP on 127.0.0.1, header "Authorization: Bearer ": + POST /tool {"name": ..., "arguments": {...}} -> {"content": [...], "is_error", "finished", "calls_in_attempt"} + content items: {"type": "text", "text"} / {"type": "image", "mimeType", "data" (base64)} + GET /tool_specs?style=raw|mcp|anthropic|openai_responses|openai_chat the three tool schemas, descriptions verbatim + GET /readme README.md of the episode workspace + GET /first_message preamble + README + first status report, byte-identical to the native harnesses' first + message (taken from /first_message.txt when the launcher already rendered it) + GET /health + GET /status robot_server's `status`, for a framework's own loop (e.g. the reference driver's "Continue ..." + nudge, which needs the attempt number): not a tool call, not counted in the per-attempt budget, + logged as ev=status; the native harnesses' launcher makes the same call directly + (scripts/harness_run.py continue_episode) +Header "X-LFF-Face" labels the access path in the transcript (mcp, sdk, ...). Contract: like mcp_robot_server.py and +api_player.py the gateway is an access path, not part of contract_sha256 (docs/15 §8.4); the "oracle through every +access path" self-check keeps the paths equal. +""" +import argparse +import base64 +import hmac +import json +import os +import secrets +import subprocess +import sys +import threading +import time +import traceback +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from api_player import (SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, call_server, parse_command, run_shell, # noqa: E402 + workspace_image) + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] +GATEWAY_FILE = "gateway.json" +TRANSCRIPT = "gateway_transcript.jsonl" + + +def tool_specs(style="raw"): + """The three tool schemas in the format a framework registers them in; names, descriptions and parameter schemas + are the reference driver's, verbatim.""" + if style == "raw": + return [dict(t) for t in TOOLS] + if style == "mcp": + return [dict(name=t["name"], description=t["description"], inputSchema=t["parameters"]) for t in TOOLS] + if style == "anthropic": + return [dict(name=t["name"], description=t["description"], input_schema=t["parameters"]) for t in TOOLS] + if style == "openai_responses": + return [dict(type="function", name=t["name"], description=t["description"], parameters=t["parameters"]) + for t in TOOLS] + if style == "openai_chat": + return [dict(type="function", function=dict(name=t["name"], description=t["description"], + parameters=t["parameters"])) for t in TOOLS] + raise ValueError(f"unknown style {style!r}: raw, mcp, anthropic, openai_responses or openai_chat") + + +class ToolCore: + """The three tools on one robot_server session, with the per-attempt tool-call budget. Same semantics and output + text as the reference driver's LA tools (and, before the gateway, mcp_robot_server.Session).""" + + def __init__(self, session_path, carry_from=None): + """carry_from: a transcript (jsonl with ev=tool, calls_in_attempt, finished) to continue the budget from, for an + in-process host that is restarted within one episode (mcp_robot_server without a gateway).""" + sess = json.load(open(session_path)) + self.session_path = os.path.abspath(session_path) + self.sb, self.port = sess["sandbox"], sess["port"] + self.log_dir = os.path.dirname(self.session_path) + iface = json.load(open(os.path.join(self.log_dir, "agent_iface.json"))) + self.token, self.max_tool_calls = iface["token"], int(iface["max_tool_calls"]) + self.calls_in_attempt, self.finished = 0, False + if carry_from and os.path.exists(carry_from): + for line in open(carry_from): + try: + d = json.loads(line) + except ValueError: + continue + if d.get("ev") == "tool" and d.get("calls_in_attempt") is not None: + self.calls_in_attempt, self.finished = int(d["calls_in_attempt"]), bool(d.get("finished")) + + def robot(self, cmdline): + cmd, args = parse_command(cmdline) + if cmd is None: + return json.dumps(dict(ok=False, error=args)) + raw = call_server(self.port, self.token, cmd, args) + try: + rep = json.loads(raw) + except ValueError: # help text + return 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: + self.finished = True + if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)): + self.calls_in_attempt = 0 + return json.dumps(rep) + + def call(self, name, args): + """-> (content list, is_error); content items as in MCP (text / image with base64 data).""" + args = args if isinstance(args, dict) else {} + if not self.finished: + self.calls_in_attempt += 1 + if name == "robot": + content, err = [dict(type="text", text=self.robot(str(args.get("command", ""))))], False + elif name == "shell": + code, out, dt = run_shell(self.sb, str(args.get("command", ""))) + content, err = [dict(type="text", text=json.dumps(dict(exit_code=code, output=out)))], False + elif name == "view_images": + paths = [str(x) for x in (args.get("paths") or [])][:8] + full = [(x, workspace_image(self.sb, x)) for x in paths] + ok = [x for x, f in full if f] + out = dict(ok=bool(ok), attached=ok) + if len(ok) < len(paths): + out["not_viewable"] = [x for x, f in full if not f] + content, err = [dict(type="text", text=json.dumps(out))], False + for x, f in full: + if f: + mime = "image/png" if f.lower().endswith(".png") else "image/jpeg" + content.append(dict(type="image", mimeType=mime, data=base64.b64encode(open(f, "rb").read()).decode())) + else: + return [dict(type="text", text=f"unknown tool {name!r}")], True + if not self.finished and self.calls_in_attempt >= self.max_tool_calls: + raw = call_server(self.port, self.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: + self.finished = True + self.calls_in_attempt = 0 + content.append(dict(type="text", text=(f"The budget of {self.max_tool_calls} tool calls for this attempt was " + f"used up, so the attempt was finished automatically. Result: " + + json.dumps(rep)))) + return content, err + + def readme(self): + return open(os.path.join(self.sb, "README.md"), encoding="utf-8").read() + + def first_message(self): + """The native harnesses' first user message. Rendered by the launcher (harness_run.py) into first_message.txt; + otherwise rendered here once, with the same single `status` call, and saved there.""" + path = os.path.join(self.log_dir, "first_message.txt") + if os.path.exists(path): + return open(path, encoding="utf-8").read() + sys.path.insert(0, ROOT) + from lffbench.harnesses.base import first_message_text + status_json = json.dumps(json.loads(call_server(self.port, self.token, "status", {}))) + text = first_message_text(self.readme(), status_json) + with open(path, "w", encoding="utf-8") as f: + f.write(text) + return text + + +def log_line(f, d): + d["t"] = time.time() + f.write(json.dumps(d, ensure_ascii=False) + "\n") + f.flush() + + +def serve(core, port=0, gateway_file=None, watch_parent=True): + token = secrets.token_hex(16) + lock = threading.Lock() + tlog = open(os.path.join(core.log_dir, TRANSCRIPT), "a") + fm_cache = {} + + class H(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def _send(self, code, body, ctype="application/json"): + data = body if isinstance(body, bytes) else (body if isinstance(body, str) else json.dumps(body)).encode() + self.send_response(code) + self.send_header("Content-Type", ctype + ("; charset=utf-8" if ctype.startswith("text") or + ctype == "application/json" else "")) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _authorized(self): + got = self.headers.get("Authorization", "") + return hmac.compare_digest(got.encode(), f"Bearer {token}".encode()) + + def do_GET(self): + u = urllib.parse.urlparse(self.path) + if u.path == "/health": + return self._send(200, dict(ok=True)) + if not self._authorized(): + return self._send(401, dict(error="unauthorized")) + try: + if u.path == "/tool_specs": + style = (urllib.parse.parse_qs(u.query).get("style") or ["raw"])[0] + return self._send(200, dict(style=style, tools=tool_specs(style))) + if u.path == "/readme": + return self._send(200, core.readme(), "text/markdown") + if u.path == "/first_message": + with lock: + if "text" not in fm_cache: + fm_cache["text"] = core.first_message() + return self._send(200, fm_cache["text"], "text/plain") + if u.path == "/status": # a framework's own status call (not the model's): not counted + face = (self.headers.get("X-LFF-Face") or "http")[:32] + with lock: + raw = call_server(core.port, core.token, "status", {}) + log_line(tlog, dict(ev="status", face=face)) + status = json.loads(raw) + return self._send(200, {k: status.get(k) for k in ("attempt", "max_attempts", "finished")}) + except ValueError as e: + return self._send(400, dict(error=str(e))) + except Exception as e: + log_line(tlog, dict(ev="error", path=u.path, error=traceback.format_exc()[-2000:])) + return self._send(500, dict(error=f"{type(e).__name__}: {e}")) + return self._send(404, dict(error=f"no such path {u.path}")) + + def do_POST(self): + u = urllib.parse.urlparse(self.path) + if not self._authorized(): + return self._send(401, dict(error="unauthorized")) + if u.path != "/tool": + return self._send(404, dict(error=f"no such path {u.path}")) + try: + req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0) or 0)) or b"{}") + name, args = req.get("name"), req.get("arguments") or {} + except (ValueError, AttributeError): + return self._send(400, dict(error="body must be JSON {name, arguments}")) + face = (self.headers.get("X-LFF-Face") or "http")[:32] + try: + with lock: # one tool call at a time per episode, as in the MCP server and the reference driver + t0 = time.time() + content, err = core.call(name, args) + out = dict(content=content, is_error=err, finished=core.finished, + calls_in_attempt=core.calls_in_attempt) + log_line(tlog, dict(ev="tool", face=face, name=name, arguments=args, dt=round(time.time() - t0, 2), + is_error=err, output=[c["text"] for c in content if c["type"] == "text"], + images=sum(1 for c in content if c["type"] == "image"), + finished=core.finished, calls_in_attempt=core.calls_in_attempt)) + except Exception as e: + log_line(tlog, dict(ev="error", face=face, name=name, error=traceback.format_exc()[-2000:])) + return self._send(500, dict(error=f"{type(e).__name__}: {e}")) + return self._send(200, out) + + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + srv.daemon_threads = True + port = srv.server_address[1] + info = dict(url=f"http://127.0.0.1:{port}", port=port, pid=os.getpid(), token=token) + gateway_file = gateway_file or os.path.join(core.log_dir, GATEWAY_FILE) + tmp = gateway_file + ".tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + json.dump(info, f) + os.replace(tmp, gateway_file) + log_line(tlog, dict(ev="start", pid=os.getpid(), port=port, session=core.session_path, + max_tool_calls=core.max_tool_calls)) + import signal + signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=srv.shutdown, daemon=True).start()) + if watch_parent: # exit with the launcher, also when it is killed without cleaning up + ppid = os.getppid() + + def watch(): + while os.getppid() == ppid: + time.sleep(2) + srv.shutdown() + threading.Thread(target=watch, daemon=True).start() + try: + srv.serve_forever(poll_interval=0.5) + finally: + log_line(tlog, dict(ev="stop")) + srv.server_close() + + +# ------------------------------------------------------------------------------------------------ launcher helpers +def start_gateway(session_path, python=None, timeout_s=30, env=None): + """Start a gateway for one episode (child of the caller) and wait until it listens. -> (Popen, info dict with url, + port, pid, token). The caller stops it with stop_gateway().""" + log_dir = os.path.dirname(os.path.abspath(session_path)) + gfile = os.path.join(log_dir, GATEWAY_FILE) + if os.path.exists(gfile): + os.remove(gfile) + err = open(os.path.join(log_dir, "gateway_stderr.txt"), "ab") + p = subprocess.Popen([python or sys.executable, os.path.abspath(__file__), "--session", os.path.abspath(session_path)], + stdin=subprocess.DEVNULL, stdout=err, stderr=err, env=env) + deadline = time.time() + timeout_s + while time.time() < deadline: + if p.poll() is not None: + raise RuntimeError(f"tool gateway exited with code {p.returncode}; see {log_dir}/gateway_stderr.txt") + if os.path.exists(gfile): + return p, json.load(open(gfile)) + time.sleep(0.05) + stop_gateway(p) + raise RuntimeError(f"tool gateway did not start within {timeout_s} s") + + +def stop_gateway(p): + if p is None or p.poll() is not None: + return + p.terminate() + try: + p.wait(timeout=10) + except subprocess.TimeoutExpired: + p.kill() + p.wait() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh (la style)") + ap.add_argument("--port", type=int, default=0, help="0 = pick a free port") + ap.add_argument("--gateway-file", default=None, help=f"default /{GATEWAY_FILE}") + ap.add_argument("--no-watch-parent", action="store_true", help="keep running when the launcher exits") + a = ap.parse_args() + serve(ToolCore(a.session), port=a.port, gateway_file=a.gateway_file, watch_parent=not a.no_watch_parent) + + +if __name__ == "__main__": + main()