Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/envs.py +325 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_high.json +36 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/skills.py +156 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l4_fit.py +574 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_tidy_stack.py +1260 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/trace_gpt_html.py +118 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/validate.py +79 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/validate_parts_cart_isolated.py +54 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py +240 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/contract.py +160 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/jail.py +228 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins.py +40 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/sensenova.py +24 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_shelf_droop.py +1009 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/api_player.py +446 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/check_breakfast_mechanisms.py +79 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/check_split_mechanisms.py +19 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/harness_run.py +431 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/ladder_gpt_plan.py +95 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/record_breakfast_service.py +89 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/start_real_session.sh +30 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/anthropic_messages.py +202 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/base.py +82 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/chat_completions.py +150 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/gemini.py +206 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/openai_responses.py +240 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/scripted.py +210 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/context.py +377 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py +61 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/__init__.py +63 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/base.py +364 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/claude_code.py +514 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/codex.py +688 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/dsh.py +403 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/framework_codex.py +542 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/pins/embodied_evo_codex-generic-646620c9aa77_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +14 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/reference.py +143 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/rpent.py +530 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/trajectory.py +86 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/fake_driver.py +152 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/session.py +346 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l1_yaw.py +439 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l2_knock.py +457 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l3_wall.py +501 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l4_fit.py +574 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l4_nest.py +644 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py +598 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l5_slippery_lift.py +262 -0
- leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py +392 -0
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/envs.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Environment construction and low-level sim helpers on top of LIBERO / robosuite."""
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
os.environ.setdefault("MUJOCO_GL", "osmesa")
|
| 5 |
+
os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
|
| 6 |
+
# LIBERO reads its paths from <LIBERO_CONFIG_PATH>/config.yaml (written by setup/install.sh into <repo>/.libero)
|
| 7 |
+
os.environ.setdefault("LIBERO_CONFIG_PATH", os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".libero"))
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
TABLE_Z = 0.90 # LIBERO main_table top surface (table_offset z)
|
| 12 |
+
# Upper limit of the Panda elbow (robot0_joint4; stock -0.0698). The arm is fully stretched at about -0.47 rad; a fast
|
| 13 |
+
# move out of a far pose could carry the elbow past that into (-0.47, -0.07], where the OSC's only way to shorten the
|
| 14 |
+
# arm runs into the stock limit and every later move stops 4-17 cm short for the rest of the attempt (measured
|
| 15 |
+
# 2026-10-19: 50 of 160 targets of the workspace box; 44 of 714 logged LA attempts). Capping the joint keeps the elbow
|
| 16 |
+
# on the normal side: reach is unchanged, and no scripted oracle / naive run of the main set goes above -0.73.
|
| 17 |
+
ELBOW_Q4_MAX = -0.55
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def make_env(bddl_path, cam_res=256, cams=("agentview", "robot0_eye_in_hand"), depth=False, controller=None):
|
| 21 |
+
"""Build a LIBERO env from a BDDL file without camera rendering on every step.
|
| 22 |
+
|
| 23 |
+
Images are rendered on demand with `render(env, cam)`.
|
| 24 |
+
"""
|
| 25 |
+
import robosuite as suite
|
| 26 |
+
import libero.libero.envs.bddl_utils as BDDLUtils
|
| 27 |
+
from libero.libero.envs import TASK_MAPPING
|
| 28 |
+
|
| 29 |
+
cfg = suite.load_controller_config(default_controller="OSC_POSE")
|
| 30 |
+
if controller is None:
|
| 31 |
+
from .skills import CONTROLLER
|
| 32 |
+
controller = CONTROLLER
|
| 33 |
+
if controller:
|
| 34 |
+
cfg.update(controller)
|
| 35 |
+
info = BDDLUtils.get_problem_info(bddl_path)
|
| 36 |
+
env = TASK_MAPPING[info["problem_name"]](
|
| 37 |
+
bddl_path,
|
| 38 |
+
robots=["Panda"],
|
| 39 |
+
controller_configs=cfg,
|
| 40 |
+
gripper_types="default",
|
| 41 |
+
initialization_noise=None,
|
| 42 |
+
use_camera_obs=False,
|
| 43 |
+
has_renderer=False,
|
| 44 |
+
has_offscreen_renderer=True,
|
| 45 |
+
render_camera="frontview",
|
| 46 |
+
render_collision_mesh=False,
|
| 47 |
+
render_visual_mesh=True,
|
| 48 |
+
render_gpu_device_id=-1,
|
| 49 |
+
control_freq=20,
|
| 50 |
+
horizon=10 ** 7,
|
| 51 |
+
ignore_done=True,
|
| 52 |
+
hard_reset=False,
|
| 53 |
+
camera_names=list(cams),
|
| 54 |
+
camera_heights=cam_res,
|
| 55 |
+
camera_widths=cam_res,
|
| 56 |
+
camera_depths=depth,
|
| 57 |
+
camera_segmentations=None,
|
| 58 |
+
renderer="mujoco",
|
| 59 |
+
renderer_config=None,
|
| 60 |
+
)
|
| 61 |
+
env.lff_language = info["language_instruction"]
|
| 62 |
+
m = env.sim.model # hard_reset=False: the model (and this limit) survives env.reset()
|
| 63 |
+
m.jnt_range[m.joint_name2id("robot0_joint4"), 1] = ELBOW_Q4_MAX
|
| 64 |
+
return env
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def render(env, cam="agentview", res=256, depth=False):
|
| 68 |
+
"""Render an RGB image (H, W, 3, uint8), upright."""
|
| 69 |
+
out = env.sim.render(camera_name=cam, width=res, height=res, depth=depth)
|
| 70 |
+
if depth:
|
| 71 |
+
rgb, d = out
|
| 72 |
+
return rgb[::-1].copy(), d[::-1].copy()
|
| 73 |
+
return out[::-1].copy()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ---------------------------------------------------------------- object state helpers
|
| 77 |
+
|
| 78 |
+
def body_id(env, obj_name):
|
| 79 |
+
return env.sim.model.body_name2id(env.objects_dict[obj_name].root_body)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def obj_pos(env, obj_name):
|
| 83 |
+
return env.sim.data.body_xpos[body_id(env, obj_name)].copy()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def obj_quat(env, obj_name):
|
| 87 |
+
"""wxyz"""
|
| 88 |
+
return env.sim.data.body_xquat[body_id(env, obj_name)].copy()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def obj_upright_cos(env, obj_name):
|
| 92 |
+
"""cos of the angle between the object's z axis and world z."""
|
| 93 |
+
xmat = env.sim.data.body_xmat[body_id(env, obj_name)].reshape(3, 3)
|
| 94 |
+
return float(xmat[2, 2])
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def free_joint_addr(env, obj_name):
|
| 98 |
+
jname = env.objects_dict[obj_name].joints[0]
|
| 99 |
+
jid = env.sim.model.joint_name2id(jname)
|
| 100 |
+
return env.sim.model.jnt_qposadr[jid], env.sim.model.jnt_dofadr[jid]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def set_obj_pose(env, obj_name, pos, yaw=0.0, quat_wxyz=None):
|
| 104 |
+
"""Teleport a free-joint object (used only at reset / by the protocol, never by agents)."""
|
| 105 |
+
qa, da = free_joint_addr(env, obj_name)
|
| 106 |
+
if quat_wxyz is None:
|
| 107 |
+
quat_wxyz = np.array([np.cos(yaw / 2), 0, 0, np.sin(yaw / 2)])
|
| 108 |
+
env.sim.data.qpos[qa:qa + 3] = pos
|
| 109 |
+
env.sim.data.qpos[qa + 3:qa + 7] = quat_wxyz
|
| 110 |
+
env.sim.data.qvel[da:da + 6] = 0.0
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def obj_geom_ids(env, obj_name):
|
| 114 |
+
return [env.sim.model.geom_name2id(g) for g in env.objects_dict[obj_name].contact_geoms]
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def set_friction(env, obj_name, mu, priority=2):
|
| 118 |
+
"""Set sliding friction of an object's collision geoms and give them priority so their
|
| 119 |
+
friction is used in contacts (MuJoCo otherwise takes the max of the two geoms)."""
|
| 120 |
+
for g in obj_geom_ids(env, obj_name):
|
| 121 |
+
env.sim.model.geom_friction[g, 0] = mu
|
| 122 |
+
env.sim.model.geom_priority[g] = priority
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def scale_mass(env, obj_name, mass):
|
| 126 |
+
bid = body_id(env, obj_name)
|
| 127 |
+
m0 = env.sim.model.body_mass[bid]
|
| 128 |
+
env.sim.model.body_mass[bid] = mass
|
| 129 |
+
env.sim.model.body_inertia[bid] *= mass / max(m0, 1e-9)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def settle(env, steps=20):
|
| 133 |
+
"""Let physics settle while holding the arm still."""
|
| 134 |
+
for _ in range(steps):
|
| 135 |
+
env.step(np.zeros(env.action_dim))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def contacts_between(env, geoms_a, geoms_b):
|
| 139 |
+
a, b = set(geoms_a), set(geoms_b)
|
| 140 |
+
d = env.sim.data
|
| 141 |
+
for i in range(d.ncon):
|
| 142 |
+
c = d.contact[i]
|
| 143 |
+
if (c.geom1 in a and c.geom2 in b) or (c.geom1 in b and c.geom2 in a):
|
| 144 |
+
return True
|
| 145 |
+
return False
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def robot_geom_ids(env):
|
| 149 |
+
m = env.sim.model
|
| 150 |
+
ids = []
|
| 151 |
+
for g in range(m.ngeom):
|
| 152 |
+
n = m.geom_id2name(g) or ""
|
| 153 |
+
if n.startswith("robot0_") or n.startswith("gripper0_"):
|
| 154 |
+
ids.append(g)
|
| 155 |
+
return ids
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# ---------------------------------------------------------------- upright placement (added 2026-10-06)
|
| 159 |
+
|
| 160 |
+
def _quat_mul(a, b):
|
| 161 |
+
"""wxyz quaternion product a*b"""
|
| 162 |
+
w1, x1, y1, z1 = a
|
| 163 |
+
w2, x2, y2, z2 = b
|
| 164 |
+
return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
|
| 165 |
+
w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 166 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
|
| 167 |
+
w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def canonical_quat(env, obj_name):
|
| 171 |
+
"""The orientation LIBERO's own placement gives an object, with any random yaw set to 0 (wxyz).
|
| 172 |
+
|
| 173 |
+
Reproduces LIBERO exactly, including its convention bug: TableRegionSampler._sample_quat builds an
|
| 174 |
+
xyzw quaternion, multiplies it with obj.init_quat (xyzw), and bddl_base_domain writes that array
|
| 175 |
+
straight into the wxyz qpos slot. E.g. scanned objects (plate, bowls, basket; rotation (pi/2, pi/2)
|
| 176 |
+
about x) therefore end up yawed by 90 deg, not rolled; HOPE groceries (dict rotation) come out
|
| 177 |
+
as (0.5, 0.5, 0.5, 0.5), which is the same under both readings. (Fixed 2026-10-06 after the L3
|
| 178 |
+
developer found plates being stood on edge.)"""
|
| 179 |
+
from robosuite.utils.transform_utils import quat_multiply
|
| 180 |
+
|
| 181 |
+
o = env.objects_dict[obj_name]
|
| 182 |
+
rot = getattr(o, "rotation", None)
|
| 183 |
+
ax = getattr(o, "rotation_axis", None) or "z"
|
| 184 |
+
|
| 185 |
+
def xyzw(axis, a):
|
| 186 |
+
h = a / 2
|
| 187 |
+
return {"x": np.array([np.sin(h), 0.0, 0.0, np.cos(h)]),
|
| 188 |
+
"y": np.array([0.0, np.sin(h), 0.0, np.cos(h)]),
|
| 189 |
+
"z": np.array([0.0, 0.0, np.sin(h), np.cos(h)])}[axis]
|
| 190 |
+
|
| 191 |
+
def fixed(r): # a random range means a free angle -> use 0 (only yaw ranges occur in practice)
|
| 192 |
+
return float(r[0]) if float(min(r)) == float(max(r)) else 0.0
|
| 193 |
+
|
| 194 |
+
if isinstance(rot, dict):
|
| 195 |
+
q = np.array([0.0, 0.0, 0.0, 1.0])
|
| 196 |
+
for axis, r in rot.items():
|
| 197 |
+
q = quat_multiply(xyzw(axis, fixed(r)), q)
|
| 198 |
+
else:
|
| 199 |
+
if rot is None:
|
| 200 |
+
a = 0.0
|
| 201 |
+
elif isinstance(rot, (tuple, list)):
|
| 202 |
+
a = fixed(rot)
|
| 203 |
+
else:
|
| 204 |
+
a = float(rot)
|
| 205 |
+
q = xyzw(ax, a)
|
| 206 |
+
init = np.array(getattr(o, "init_quat", [0.0, 0.0, 0.0, 1.0]), dtype=float)
|
| 207 |
+
q = quat_multiply(q, init)
|
| 208 |
+
return np.array(q, dtype=float) # used directly as wxyz, like LIBERO does
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def obj_min_z(env, obj_name):
|
| 212 |
+
"""Lowest world z of the object's collision geoms (exact for boxes, AABB bound for meshes)."""
|
| 213 |
+
m, d = env.sim.model, env.sim.data
|
| 214 |
+
zmin = np.inf
|
| 215 |
+
for g in obj_geom_ids(env, obj_name):
|
| 216 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 217 |
+
c_local = m.geom_aabb[g, :3]
|
| 218 |
+
half = m.geom_aabb[g, 3:]
|
| 219 |
+
cz = d.geom_xpos[g][2] + R[2] @ c_local
|
| 220 |
+
zmin = min(zmin, cz - np.abs(R[2]) @ half)
|
| 221 |
+
return float(zmin)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def obj_max_z(env, obj_name):
|
| 225 |
+
"""Highest world z of the object's collision geoms (exact for boxes, AABB bound for meshes)."""
|
| 226 |
+
m, d = env.sim.model, env.sim.data
|
| 227 |
+
zmax = -np.inf
|
| 228 |
+
for g in obj_geom_ids(env, obj_name):
|
| 229 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 230 |
+
cz = d.geom_xpos[g][2] + R[2] @ m.geom_aabb[g, :3]
|
| 231 |
+
zmax = max(zmax, cz + np.abs(R[2]) @ m.geom_aabb[g, 3:])
|
| 232 |
+
return float(zmax)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
FINGERTIP_BELOW_SITE = 0.0095 # lowest point of the Panda finger collision meshes below the grasp site (measured)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def place_upright(env, obj_name, xy, yaw=0.0, surface_z=TABLE_Z, clearance=0.002):
|
| 239 |
+
"""Teleport an object upright (LIBERO canonical orientation, then `yaw` about world z) so that its
|
| 240 |
+
lowest collision point sits `clearance` above `surface_z`. Call env.sim.forward() / settle after."""
|
| 241 |
+
q = _quat_mul(np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]), canonical_quat(env, obj_name))
|
| 242 |
+
set_obj_pose(env, obj_name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
|
| 243 |
+
env.sim.forward()
|
| 244 |
+
dz = obj_min_z(env, obj_name) - (surface_z + clearance)
|
| 245 |
+
qa, _ = free_joint_addr(env, obj_name)
|
| 246 |
+
env.sim.data.qpos[qa + 2] -= dz
|
| 247 |
+
env.sim.forward()
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# ---------------------------------------------------------------- collision bounds after runtime edits (2026-10-12)
|
| 251 |
+
|
| 252 |
+
def _quat2mat(q):
|
| 253 |
+
w, x, y, z = q
|
| 254 |
+
return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
| 255 |
+
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
| 256 |
+
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def _prim_bounds(m, g):
|
| 260 |
+
"""(half extents in the geom frame, bounding-sphere radius) of a primitive geom from geom_size; None otherwise"""
|
| 261 |
+
t, s = int(m.geom_type[g]), m.geom_size[g]
|
| 262 |
+
if t == 6: # box
|
| 263 |
+
return np.array(s[:3], float), float(np.linalg.norm(s[:3]))
|
| 264 |
+
if t == 4: # ellipsoid
|
| 265 |
+
return np.array(s[:3], float), float(max(s[:3]))
|
| 266 |
+
if t == 2: # sphere
|
| 267 |
+
return np.full(3, float(s[0])), float(s[0])
|
| 268 |
+
if t == 5: # cylinder
|
| 269 |
+
return np.array([s[0], s[0], s[1]], float), float(np.hypot(s[0], s[1]))
|
| 270 |
+
if t == 3: # capsule
|
| 271 |
+
return np.array([s[0], s[0], s[0] + s[1]], float), float(s[0] + s[1])
|
| 272 |
+
return None
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def refit_bounds(model, bodies, margin=0.0, geoms=True):
|
| 276 |
+
"""Make the collision bounds of `bodies` (body id or ids) consistent again after runtime edits of their geoms
|
| 277 |
+
(geom_size / geom_pos / geom_quat) or of their inertial frame (body_ipos / body_iquat). `model`: an env, a
|
| 278 |
+
robosuite MjModel wrapper or a raw mujoco.MjModel.
|
| 279 |
+
|
| 280 |
+
MuJoCo (3.2.3) computes these bounds at compile time and never updates them: geom_aabb / geom_rbound (geom
|
| 281 |
+
frame; broad phase and geom-pair filters) and the per-body bounding-volume hierarchy bvh_aabb, stored in the
|
| 282 |
+
body's INERTIAL frame and used by the mid-phase whenever one of the two bodies of a pair has >= 2 collision
|
| 283 |
+
geoms. Stale boxes make MuJoCo silently skip contacts (lh_fence v1: a post whose centre of mass was raised sank
|
| 284 |
+
2.2 cm into the table; measured 2026-10-12: a body with a single collision geom whose COM moved 6 cm missed every
|
| 285 |
+
contact with a 2-geom body beyond the shifted box). With geoms=True the primitive geoms' geom_aabb / geom_rbound
|
| 286 |
+
are recomputed from geom_size (meshes keep theirs); then every BVH node becomes the union of its leaf geoms'
|
| 287 |
+
boxes (+ margin) in the runtime inertial frame, following body_sameframe / geom_sameframe like mj_kinematics
|
| 288 |
+
(on a pristine model this reproduces the compiled bvh_aabb exactly).
|
| 289 |
+
Also note: a runtime body_ipos is ignored by MuJoCo if the compiled inertial pos is the body origin
|
| 290 |
+
(body_sameframe = 1); bodies whose centre of mass is moved at runtime need a non-zero compiled inertial pos."""
|
| 291 |
+
if hasattr(model, "sim"):
|
| 292 |
+
model = model.sim.model
|
| 293 |
+
m = getattr(model, "_model", model)
|
| 294 |
+
for b in np.atleast_1d(bodies):
|
| 295 |
+
b = int(b)
|
| 296 |
+
if geoms:
|
| 297 |
+
for g in range(int(m.body_geomadr[b]), int(m.body_geomadr[b] + m.body_geomnum[b])):
|
| 298 |
+
pb = _prim_bounds(m, g)
|
| 299 |
+
if pb is not None:
|
| 300 |
+
m.geom_aabb[g] = [0.0, 0.0, 0.0, *pb[0]]
|
| 301 |
+
m.geom_rbound[g] = pb[1]
|
| 302 |
+
a, n = int(m.body_bvhadr[b]), int(m.body_bvhnum[b])
|
| 303 |
+
if a < 0 or n < 1:
|
| 304 |
+
continue
|
| 305 |
+
sf = int(m.body_sameframe[b]) # 1: inertial frame = body frame, 3: same orientation as the body
|
| 306 |
+
ip = np.zeros(3) if sf == 1 else np.array(m.body_ipos[b], float)
|
| 307 |
+
iR = np.eye(3) if sf in (1, 3) else _quat2mat(m.body_iquat[b])
|
| 308 |
+
|
| 309 |
+
def rec(i):
|
| 310 |
+
g = int(m.bvh_nodeid[i])
|
| 311 |
+
if g >= 0:
|
| 312 |
+
gsf = int(m.geom_sameframe[g]) # 1: body frame, 2: inertial frame, 3/4: their orientation
|
| 313 |
+
gp = np.zeros(3) if gsf == 1 else ip if gsf == 2 else np.array(m.geom_pos[g], float)
|
| 314 |
+
gR = np.eye(3) if gsf in (1, 3) else iR if gsf in (2, 4) else _quat2mat(m.geom_quat[g])
|
| 315 |
+
R = iR.T @ gR
|
| 316 |
+
c = iR.T @ (gp - ip) + R @ np.asarray(m.geom_aabb[g, :3])
|
| 317 |
+
h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:])
|
| 318 |
+
lo, hi = c - h, c + h
|
| 319 |
+
else:
|
| 320 |
+
l1, h1 = rec(a + int(m.bvh_child[i][0]))
|
| 321 |
+
l2, h2 = rec(a + int(m.bvh_child[i][1]))
|
| 322 |
+
lo, hi = np.minimum(l1, l2), np.maximum(h1, h2)
|
| 323 |
+
m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin])
|
| 324 |
+
return lo, hi
|
| 325 |
+
rec(a)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_high.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-chatgpt|0.163.0|399ff69c431c066e|gpt-6-astra|high",
|
| 3 |
+
"fingerprint_sha256": "359044b5060cd18979e3119b31aa0a6272f52769c7f6a14febeae808d71cc5da",
|
| 4 |
+
"written": "2026-10-19 22:12:19",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 24091,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"collaboration.followup_task",
|
| 9 |
+
"collaboration.interrupt_agent",
|
| 10 |
+
"collaboration.list_agents",
|
| 11 |
+
"collaboration.send_message",
|
| 12 |
+
"collaboration.spawn_agent",
|
| 13 |
+
"collaboration.wait_agent",
|
| 14 |
+
"functions.exec",
|
| 15 |
+
"functions.request_user_input",
|
| 16 |
+
"functions.request_user_input_async",
|
| 17 |
+
"functions.wait"
|
| 18 |
+
],
|
| 19 |
+
"all_tools": [
|
| 20 |
+
"apply_patch",
|
| 21 |
+
"clock__curr_time",
|
| 22 |
+
"list_mcp_resource_templates",
|
| 23 |
+
"list_mcp_resources",
|
| 24 |
+
"mcp__lff__robot",
|
| 25 |
+
"mcp__lff__shell",
|
| 26 |
+
"mcp__lff__view_images",
|
| 27 |
+
"read_mcp_resource"
|
| 28 |
+
],
|
| 29 |
+
"effort_in_request": "high",
|
| 30 |
+
"model_in_request": "gpt-6-astra",
|
| 31 |
+
"sandbox": {
|
| 32 |
+
"sandbox": "seccomp",
|
| 33 |
+
"sandbox_mode": "read-only"
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
}
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/skills.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Motion primitives executed with robosuite's OSC_POSE controller.
|
| 2 |
+
|
| 3 |
+
All positions are world-frame metres (LIBERO table top is z = TABLE_Z = 0.90).
|
| 4 |
+
`bias` is a hidden calibration error added to every commanded position (used by L1 tasks);
|
| 5 |
+
agents never see it.
|
| 6 |
+
"""
|
| 7 |
+
import numpy as np
|
| 8 |
+
import robosuite.utils.transform_utils as T
|
| 9 |
+
|
| 10 |
+
from .envs import TABLE_Z
|
| 11 |
+
|
| 12 |
+
DT = 0.05 # control period (20 Hz)
|
| 13 |
+
ROT_SCALE = 0.5
|
| 14 |
+
# Faster OSC than LIBERO's default (default caps the end effector at ~0.25 m/s; this reaches ~0.6 m/s).
|
| 15 |
+
CONTROLLER = dict(kp=300, output_max=[0.1, 0.1, 0.1, 0.5, 0.5, 0.5], output_min=[-0.1, -0.1, -0.1, -0.5, -0.5, -0.5])
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _rotz(a):
|
| 19 |
+
c, s = np.cos(a), np.sin(a)
|
| 20 |
+
return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _rot_err(R_target, R_cur):
|
| 24 |
+
"""axis-angle (world frame) rotating R_cur to R_target"""
|
| 25 |
+
R = R_target @ R_cur.T
|
| 26 |
+
q = T.mat2quat(R) # xyzw
|
| 27 |
+
return T.quat2axisangle(q)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Skills:
|
| 31 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 32 |
+
self.env = env
|
| 33 |
+
self.pos_scale = float(env.robots[0].controller.output_max[0])
|
| 34 |
+
self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
|
| 35 |
+
self.grip = -1.0 # -1 open, +1 closed
|
| 36 |
+
self.R0 = self.eef_mat().copy() # top-down orientation at reset == yaw 0
|
| 37 |
+
self.yaw = 0.0
|
| 38 |
+
self.recorder = recorder # callable(env) invoked every `record_every` control steps
|
| 39 |
+
self.record_every = 4
|
| 40 |
+
self.n_steps = 0
|
| 41 |
+
self.log = []
|
| 42 |
+
|
| 43 |
+
# ------------------------------------------------------------------ state
|
| 44 |
+
def eef_pos(self):
|
| 45 |
+
return self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id].copy()
|
| 46 |
+
|
| 47 |
+
def eef_mat(self):
|
| 48 |
+
return self.env.sim.data.site_xmat[self.env.robots[0].eef_site_id].reshape(3, 3).copy()
|
| 49 |
+
|
| 50 |
+
def gripper_width(self):
|
| 51 |
+
g = self.env.robots[0].gripper
|
| 52 |
+
q = [self.env.sim.data.qpos[self.env.sim.model.joint_name2id(j)] for j in g.joints]
|
| 53 |
+
return float(abs(q[0] - q[1]))
|
| 54 |
+
|
| 55 |
+
def holding(self, obj_name):
|
| 56 |
+
return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper,
|
| 57 |
+
object_geoms=self.env.objects_dict[obj_name]))
|
| 58 |
+
|
| 59 |
+
# ------------------------------------------------------------------ low level
|
| 60 |
+
def _act(self, dpos, drot, grip):
|
| 61 |
+
a = np.zeros(7)
|
| 62 |
+
a[:3] = np.clip(dpos / self.pos_scale, -1, 1)
|
| 63 |
+
a[3:6] = np.clip(drot / ROT_SCALE, -1, 1)
|
| 64 |
+
a[6] = grip
|
| 65 |
+
self.env.step(a)
|
| 66 |
+
self.n_steps += 1
|
| 67 |
+
if self.recorder is not None and self.n_steps % self.record_every == 0:
|
| 68 |
+
self.recorder(self.env)
|
| 69 |
+
|
| 70 |
+
def hold(self, steps=10):
|
| 71 |
+
p, R = self.eef_pos(), self._R()
|
| 72 |
+
for _ in range(steps):
|
| 73 |
+
self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
|
| 74 |
+
|
| 75 |
+
def _R(self, yaw=None):
|
| 76 |
+
return _rotz(self.yaw if yaw is None else yaw) @ self.R0
|
| 77 |
+
|
| 78 |
+
# ------------------------------------------------------------------ primitives
|
| 79 |
+
YAW_LIMIT = np.pi / 2 + 0.4
|
| 80 |
+
|
| 81 |
+
def wrap_yaw(self, yaw):
|
| 82 |
+
"""A parallel-jaw gripper is symmetric under a rotation by pi, so pick the equivalent yaw closest
|
| 83 |
+
to the current one inside |yaw| <= pi/2 + 0.4. Without this, asking for ~180 deg of wrist rotation
|
| 84 |
+
makes the OSC (whose axis-angle error is ambiguous at pi) wind the arm into its joint limits and
|
| 85 |
+
it never recovers (found by the L3 developer: push towards -y -> 0/6 success, 2026-10-06)."""
|
| 86 |
+
cands = [yaw + k * np.pi for k in range(-3, 4)]
|
| 87 |
+
ok = [c for c in cands if abs(c) <= self.YAW_LIMIT] or cands
|
| 88 |
+
return float(min(ok, key=lambda c: abs(c - self.yaw)))
|
| 89 |
+
|
| 90 |
+
def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
|
| 91 |
+
"""Move the gripper site to `target` (world xyz). If `speed` (m/s) is given the reference
|
| 92 |
+
moves along a straight line at that speed; otherwise go as fast as the controller allows.
|
| 93 |
+
`yaw` is wrapped to the closest gripper-symmetric equivalent unless wrap_yaw=False.
|
| 94 |
+
Returns a report dict."""
|
| 95 |
+
tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
|
| 96 |
+
if yaw is not None:
|
| 97 |
+
self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
|
| 98 |
+
R = self._R()
|
| 99 |
+
p0 = self.eef_pos()
|
| 100 |
+
dist = np.linalg.norm(tgt - p0)
|
| 101 |
+
direction = (tgt - p0) / max(dist, 1e-9)
|
| 102 |
+
s = 0.0
|
| 103 |
+
for k in range(max_steps):
|
| 104 |
+
if speed is not None:
|
| 105 |
+
s = min(dist, s + speed * DT)
|
| 106 |
+
ref = p0 + direction * s
|
| 107 |
+
# lead the reference a little so the OSC lag does not throttle the speed
|
| 108 |
+
ref = ref + direction * min(dist - s, speed * DT * 1.5)
|
| 109 |
+
else:
|
| 110 |
+
ref = tgt
|
| 111 |
+
cur = self.eef_pos()
|
| 112 |
+
self._act(ref - cur, _rot_err(R, self.eef_mat()), self.grip)
|
| 113 |
+
err = np.linalg.norm(tgt - self.eef_pos())
|
| 114 |
+
if err < tol and (speed is None or s >= dist):
|
| 115 |
+
break
|
| 116 |
+
rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
|
| 117 |
+
pos=self.eef_pos().round(4).tolist(), steps=k + 1)
|
| 118 |
+
self.log.append(rep)
|
| 119 |
+
return rep
|
| 120 |
+
|
| 121 |
+
def set_gripper(self, close, steps=15):
|
| 122 |
+
self.grip = 1.0 if close else -1.0
|
| 123 |
+
self.hold(steps)
|
| 124 |
+
rep = dict(prim="close" if close else "open", width=round(self.gripper_width(), 4))
|
| 125 |
+
self.log.append(rep)
|
| 126 |
+
return rep
|
| 127 |
+
|
| 128 |
+
def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15):
|
| 129 |
+
"""Composite: above -> descend -> close -> lift. For scripted policies."""
|
| 130 |
+
self.set_gripper(False, steps=5)
|
| 131 |
+
self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw)
|
| 132 |
+
self.move_to([xy[0], xy[1], z_grasp], tol=0.003)
|
| 133 |
+
self.set_gripper(True, steps=15)
|
| 134 |
+
self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25)
|
| 135 |
+
|
| 136 |
+
def place_at(self, xy, z_release, approach=0.10):
|
| 137 |
+
self.move_to([xy[0], xy[1], z_release + approach])
|
| 138 |
+
self.move_to([xy[0], xy[1], z_release], tol=0.004)
|
| 139 |
+
self.set_gripper(False, steps=12)
|
| 140 |
+
self.move_to([xy[0], xy[1], z_release + approach])
|
| 141 |
+
|
| 142 |
+
def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06):
|
| 143 |
+
"""Straight-line push: go to `pre` m behind the start point at height z with the gripper closed,
|
| 144 |
+
then sweep `pre + distance` along direction at `speed`, stop, and lift away."""
|
| 145 |
+
d = np.asarray(direction_xy, float)
|
| 146 |
+
d = d / np.linalg.norm(d)
|
| 147 |
+
z = TABLE_Z + 0.02 if z is None else z
|
| 148 |
+
s = np.asarray(start_xy, float) - d * pre
|
| 149 |
+
self.set_gripper(True, steps=5)
|
| 150 |
+
self.move_to([s[0], s[1], z + 0.12], yaw=np.arctan2(d[1], d[0]) - np.pi / 2)
|
| 151 |
+
self.move_to([s[0], s[1], z], tol=0.003)
|
| 152 |
+
e = s + d * (pre + distance)
|
| 153 |
+
rep = self.move_to([e[0], e[1], z], speed=speed, tol=0.01, max_steps=400)
|
| 154 |
+
self.hold(2)
|
| 155 |
+
self.move_to([e[0], e[1], z + 0.12], speed=0.3)
|
| 156 |
+
return rep
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l4_fit.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L4-A fit_container: put the phone flat inside the one box it fits into.
|
| 2 |
+
|
| 3 |
+
v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and
|
| 4 |
+
phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time.
|
| 5 |
+
v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is
|
| 6 |
+
rendered), CAP_RANGE = 0.8-0.9 cm each, so it is 1.6-1.8 cm longer than the visible phone. The box sizes are drawn
|
| 7 |
+
against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone:
|
| 8 |
+
fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight),
|
| 9 |
+
snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps,
|
| 10 |
+
short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps,
|
| 11 |
+
narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow,
|
| 12 |
+
small 0.5..1.0 cm too short.
|
| 13 |
+
A phone that does not fit lies on the rim of the box (or tips in at one end), visibly not inside, although in the
|
| 14 |
+
images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it
|
| 15 |
+
appears to (by about the overlap seen) -> the box with the most length to spare.
|
| 16 |
+
|
| 17 |
+
The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as
|
| 18 |
+
the capped length. v2 is kept in l4_fit.py.bak-20261008-height.
|
| 19 |
+
|
| 20 |
+
v2 description:
|
| 21 |
+
|
| 22 |
+
Scene: a dark "phone" (14.0 x 6.8 x 1.2 cm) lies in the front row of a 2 x 3 grid of slots; five open
|
| 23 |
+
boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES):
|
| 24 |
+
fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side),
|
| 25 |
+
short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest),
|
| 26 |
+
narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest),
|
| 27 |
+
small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions),
|
| 28 |
+
short 0.8-2.0 cm too short, as wide as the fitting box.
|
| 29 |
+
Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it
|
| 30 |
+
(+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be
|
| 31 |
+
turned by ~90 deg.
|
| 32 |
+
|
| 33 |
+
Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the
|
| 34 |
+
fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in
|
| 35 |
+
sim.model, so a single env serves every instance.
|
| 36 |
+
|
| 37 |
+
Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed
|
| 38 |
+
2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first
|
| 39 |
+
failures were plain misalignment instead of a size mismatch). F2 feedback after a failed attempt reports where the phone ended up and by how much it is too
|
| 40 |
+
long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger
|
| 41 |
+
in that dimension and turn the phone.
|
| 42 |
+
"""
|
| 43 |
+
import numpy as np
|
| 44 |
+
|
| 45 |
+
from .. import envs
|
| 46 |
+
from ..bddl import write_bddl
|
| 47 |
+
from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
|
| 48 |
+
from ..skills import _rot_err
|
| 49 |
+
from ..task_base import LFFTask, register_task
|
| 50 |
+
|
| 51 |
+
# phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it
|
| 52 |
+
PL, PW, PT = 0.140, 0.068, 0.012
|
| 53 |
+
CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden)
|
| 54 |
+
# boxes (local x = long axis of the opening)
|
| 55 |
+
WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035
|
| 56 |
+
BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height
|
| 57 |
+
RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
|
| 58 |
+
N_BOXES = 5
|
| 59 |
+
ROWS_X = (-0.30, -0.08) # back row (near the robot), front row
|
| 60 |
+
COLS_Y = (-0.22, 0.0, 0.22)
|
| 61 |
+
DROP = 0.012 # phone bottom this far above the rim when released
|
| 62 |
+
Z_CARRY = envs.TABLE_Z + 0.15
|
| 63 |
+
PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way
|
| 64 |
+
PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates
|
| 65 |
+
JITTER_DEG = 15.0
|
| 66 |
+
# inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side).
|
| 67 |
+
# The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has
|
| 68 |
+
# the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio.
|
| 69 |
+
# Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box.
|
| 70 |
+
# v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap)
|
| 71 |
+
BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small")
|
| 72 |
+
INNER_RANGES = {
|
| 73 |
+
"fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest)
|
| 74 |
+
"snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable
|
| 75 |
+
"short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box
|
| 76 |
+
"narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow
|
| 77 |
+
"small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short
|
| 78 |
+
}
|
| 79 |
+
VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps)
|
| 80 |
+
BOX_RGBA = (0.70, 0.60, 0.46, 1.0)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def phone_xml(model_name):
|
| 84 |
+
hx, hy, hz = PL / 2, PW / 2, PT / 2
|
| 85 |
+
body = (0.13, 0.13, 0.15, 1.0)
|
| 86 |
+
screen = (0.02, 0.025, 0.04, 1.0)
|
| 87 |
+
g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" '
|
| 88 |
+
f'density="1500" friction="1.0 0.005 0.0001" {_SOLID} group="0" />\n'
|
| 89 |
+
f' <geom type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" conaffinity="0" contype="0" '
|
| 90 |
+
f'group="1" />\n'
|
| 91 |
+
f' <geom type="box" pos="0 0 {hz:.5f}" size="{_fmt((hx - 0.004, hy - 0.003, 0.0003))}" '
|
| 92 |
+
f'rgba="{_fmt(screen)}" conaffinity="0" contype="0" group="1" />')
|
| 93 |
+
# v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered).
|
| 94 |
+
# Resized per instance in apply_instance (inst["cap"]).
|
| 95 |
+
c = CAP_RANGE[1]
|
| 96 |
+
for k, sx in enumerate((1, -1)):
|
| 97 |
+
g += (f'\n <geom name="{model_name}_cap{k}" type="box" pos="{_fmt((sx * (hx + c / 2), 0, 0))}" '
|
| 98 |
+
f'size="{_fmt((c / 2, hy - 0.001, hz))}" rgba="1 1 1 0" density="400" friction="1.0 0.005 0.0001" '
|
| 99 |
+
f'{_SOLID} group="0" />')
|
| 100 |
+
return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy)))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def wrap_half(a):
|
| 104 |
+
"""angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)"""
|
| 105 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def wrap_quarter(a):
|
| 109 |
+
"""angle modulo pi/2 into [-pi/4, pi/4)"""
|
| 110 |
+
return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def fits_some_yaw(a, b, clearance=0.002, length=PL):
|
| 114 |
+
"""Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in
|
| 115 |
+
total)?"""
|
| 116 |
+
th = np.linspace(0.0, np.pi / 2, 181)
|
| 117 |
+
e1 = length * np.cos(th) + PW * np.sin(th)
|
| 118 |
+
e2 = length * np.sin(th) + PW * np.cos(th)
|
| 119 |
+
return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance)))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _rect_corners(xy, yaw, half):
|
| 123 |
+
c, s = np.cos(yaw), np.sin(yaw)
|
| 124 |
+
R = np.array([[c, -s], [s, c]])
|
| 125 |
+
pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half)
|
| 126 |
+
return pts @ R.T + np.asarray(xy)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _rects_overlap(r1, r2):
|
| 130 |
+
"""separating-axis test for two rotated rectangles given as (xy, yaw, half)"""
|
| 131 |
+
c1, c2 = _rect_corners(*r1), _rect_corners(*r2)
|
| 132 |
+
for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2):
|
| 133 |
+
ax = np.array([np.cos(yaw), np.sin(yaw)])
|
| 134 |
+
p1, p2 = c1 @ ax, c2 @ ax
|
| 135 |
+
if p1.max() < p2.min() or p2.max() < p1.min():
|
| 136 |
+
return False
|
| 137 |
+
return True
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@register_task
|
| 141 |
+
class FitContainer(LFFTask):
|
| 142 |
+
name = "l4_fit_container"
|
| 143 |
+
level = "L4"
|
| 144 |
+
category = "geometry_inference"
|
| 145 |
+
capabilities = ("Perceive", "Reason")
|
| 146 |
+
instruction = "Put the phone flat inside a box that it fits into completely."
|
| 147 |
+
instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely."
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------ scene
|
| 150 |
+
def make_bddl(self):
|
| 151 |
+
phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone"))
|
| 152 |
+
# one category per box (BDDL lists one object per line; same-category lines would overwrite each
|
| 153 |
+
# other). All share the same MJCF; the opening is resized per instance in apply_instance.
|
| 154 |
+
cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H,
|
| 155 |
+
wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA,
|
| 156 |
+
density=3000))
|
| 157 |
+
for c in "ABCDE"]
|
| 158 |
+
objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))]
|
| 159 |
+
slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)]
|
| 160 |
+
for i, (x, y) in enumerate(slots):
|
| 161 |
+
objs.append((f"box_{i + 1}", cats[i], f"box{i + 1}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)))
|
| 162 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 163 |
+
|
| 164 |
+
def sample_instance(self, seed):
|
| 165 |
+
rng = np.random.default_rng(seed)
|
| 166 |
+
j = np.radians(JITTER_DEG)
|
| 167 |
+
for _ in range(500):
|
| 168 |
+
col = int(rng.integers(3))
|
| 169 |
+
phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)]
|
| 170 |
+
phone_yaw = float(rng.uniform(-j, j))
|
| 171 |
+
slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])]
|
| 172 |
+
kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)]
|
| 173 |
+
cap = float(rng.uniform(*CAP_RANGE))
|
| 174 |
+
boxes = []
|
| 175 |
+
for i, (kind, (x, y)) in enumerate(zip(kinds, slots)):
|
| 176 |
+
lo, hi = INNER_RANGES[kind]
|
| 177 |
+
a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1])
|
| 178 |
+
assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap)
|
| 179 |
+
assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b)
|
| 180 |
+
crossed = bool(rng.random() < 0.5)
|
| 181 |
+
yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j))
|
| 182 |
+
boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed,
|
| 183 |
+
xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))],
|
| 184 |
+
yaw=yaw, inner=[float(a), float(b)]))
|
| 185 |
+
rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007))
|
| 186 |
+
for b in boxes]
|
| 187 |
+
rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01)))
|
| 188 |
+
if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)):
|
| 189 |
+
break
|
| 190 |
+
else:
|
| 191 |
+
raise RuntimeError("could not sample a non-overlapping layout")
|
| 192 |
+
prng = np.random.default_rng(seed + 7919)
|
| 193 |
+
perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))]
|
| 194 |
+
for b in boxes]
|
| 195 |
+
return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes,
|
| 196 |
+
fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc)
|
| 197 |
+
|
| 198 |
+
def _reshape_box(self, name, a, b):
|
| 199 |
+
ix, iy, H = a / 2, b / 2, BOX_HALF_H
|
| 200 |
+
parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)),
|
| 201 |
+
((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
|
| 202 |
+
((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
|
| 203 |
+
((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)),
|
| 204 |
+
((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))]
|
| 205 |
+
m = self.env.sim.model
|
| 206 |
+
o = self.env.objects_dict[name]
|
| 207 |
+
for names in (o.contact_geoms, o.visual_geoms):
|
| 208 |
+
assert len(names) == len(parts), names
|
| 209 |
+
for k, n in enumerate(names):
|
| 210 |
+
g = m.geom_name2id(n)
|
| 211 |
+
pos, size = parts[k]
|
| 212 |
+
m.geom_pos[g] = pos
|
| 213 |
+
m.geom_size[g] = size
|
| 214 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 215 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 216 |
+
|
| 217 |
+
def _set_caps(self, cap):
|
| 218 |
+
"""resize the two hidden bumper caps to `cap` (m) per end"""
|
| 219 |
+
m = self.env.sim.model
|
| 220 |
+
if not hasattr(self, "_cap_ids"):
|
| 221 |
+
self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1")
|
| 222 |
+
if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]]
|
| 223 |
+
assert len(self._cap_ids) == 2, self._cap_ids
|
| 224 |
+
for g in self._cap_ids:
|
| 225 |
+
sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0
|
| 226 |
+
size = (cap / 2, PW / 2 - 0.001, PT / 2)
|
| 227 |
+
m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0)
|
| 228 |
+
m.geom_size[g] = size
|
| 229 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 230 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 231 |
+
|
| 232 |
+
def apply_instance(self, inst):
|
| 233 |
+
# walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision
|
| 234 |
+
# mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07).
|
| 235 |
+
# Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below.
|
| 236 |
+
import mujoco
|
| 237 |
+
self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
|
| 238 |
+
self._set_caps(inst["cap"])
|
| 239 |
+
for b in inst["boxes"]:
|
| 240 |
+
self._reshape_box(b["name"], *b["inner"])
|
| 241 |
+
envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"])
|
| 242 |
+
envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005],
|
| 243 |
+
yaw=inst["phone_yaw"])
|
| 244 |
+
|
| 245 |
+
# ------------------------------------------------------------ outcome
|
| 246 |
+
def _pose2d(self, name):
|
| 247 |
+
bid = envs.body_id(self.env, name)
|
| 248 |
+
R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
|
| 249 |
+
p = self.env.sim.data.body_xpos[bid].copy()
|
| 250 |
+
return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1))))
|
| 251 |
+
|
| 252 |
+
def outcome(self, inst):
|
| 253 |
+
envs.settle(self.env, 40)
|
| 254 |
+
p, yaw, tilt = self._pose2d("phone_1")
|
| 255 |
+
held = bool(self.sk is not None and self.sk.holding("phone_1"))
|
| 256 |
+
# which box is the phone in / on: smallest distance of the phone centre outside a box opening
|
| 257 |
+
best = None
|
| 258 |
+
for j, b in enumerate(inst["boxes"]):
|
| 259 |
+
c, byaw, btilt = self._pose2d(b["name"])
|
| 260 |
+
d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2])
|
| 261 |
+
out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0)
|
| 262 |
+
dist = float(np.linalg.norm(out))
|
| 263 |
+
if best is None or dist < best[0]:
|
| 264 |
+
best = (dist, j, c, byaw, btilt)
|
| 265 |
+
dist, j, c, byaw, btilt = best
|
| 266 |
+
b = inst["boxes"][j]
|
| 267 |
+
a_in, b_in = b["inner"]
|
| 268 |
+
floor_top = c[2] - BOX_HALF_H + FLOOR_T
|
| 269 |
+
height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor
|
| 270 |
+
in_opening = dist < 1e-9
|
| 271 |
+
on_floor = height < 0.004 and tilt < 5.0
|
| 272 |
+
success = bool(in_opening and on_floor and not held and btilt < 10.0)
|
| 273 |
+
where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback
|
| 274 |
+
# footprint of the phone (as it lies now) against the opening of that box
|
| 275 |
+
dl = yaw - byaw
|
| 276 |
+
cs, sn = abs(np.cos(dl)), abs(np.sin(dl))
|
| 277 |
+
L = PL + 2 * inst.get("cap", 0.0) # the capped phone
|
| 278 |
+
over_long = L * cs + PW * sn - a_in
|
| 279 |
+
over_short = L * sn + PW * cs - b_in
|
| 280 |
+
along_long = "length" if cs >= sn else "width"
|
| 281 |
+
fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long,
|
| 282 |
+
over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None,
|
| 283 |
+
over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None)
|
| 284 |
+
res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2),
|
| 285 |
+
tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb)
|
| 286 |
+
if held:
|
| 287 |
+
res["detail"] = "The phone is still in the gripper."
|
| 288 |
+
res["failure"] = "held"
|
| 289 |
+
return res
|
| 290 |
+
if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006):
|
| 291 |
+
res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm "
|
| 292 |
+
f"outside the opening of {where}.")
|
| 293 |
+
res["failure"] = "table"
|
| 294 |
+
return res
|
| 295 |
+
if success:
|
| 296 |
+
res["detail"] = f"The phone is lying flat on the bottom of {where}."
|
| 297 |
+
res["failure"] = None
|
| 298 |
+
return res
|
| 299 |
+
pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else
|
| 300 |
+
f"tilted about {tilt:.0f} degrees with one end down inside the box")
|
| 301 |
+
txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}."
|
| 302 |
+
dim_l = "long" if along_long == "length" else "wide"
|
| 303 |
+
dim_s = "wide" if along_long == "length" else "long"
|
| 304 |
+
if fb["over_long_cm"]:
|
| 305 |
+
txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side."
|
| 306 |
+
if fb["over_short_cm"]:
|
| 307 |
+
txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side."
|
| 308 |
+
if not fb["over_long_cm"] and not fb["over_short_cm"]:
|
| 309 |
+
txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim."
|
| 310 |
+
res["detail"] = txt
|
| 311 |
+
res["failure"] = "rim"
|
| 312 |
+
return res
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def box_label(inst, j):
|
| 316 |
+
"""Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left)."""
|
| 317 |
+
ys = [b["xy"][1] for b in inst["boxes"]]
|
| 318 |
+
xs = [b["xy"][0] for b in inst["boxes"]]
|
| 319 |
+
n = len(ys)
|
| 320 |
+
order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first
|
| 321 |
+
r = order.index(j)
|
| 322 |
+
close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04]
|
| 323 |
+
if close: # boxes side by side in y: tell them apart by distance from the robot
|
| 324 |
+
nearer = all(xs[j] < xs[i] for i in close)
|
| 325 |
+
return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position"
|
| 326 |
+
if r == 0:
|
| 327 |
+
return "the box furthest to the robot's left (+y)"
|
| 328 |
+
if r == n - 1:
|
| 329 |
+
return "the box furthest to the robot's right (-y)"
|
| 330 |
+
return "the middle box (between the others, left to right)"
|
| 331 |
+
|
| 332 |
+
# ------------------------------------------------------------ execution
|
| 333 |
+
def execute(self, inst, params):
|
| 334 |
+
"""params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released).
|
| 335 |
+
Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre
|
| 336 |
+
along the box's long / short axis (m), drop = height of the phone bottom above the rim (m)."""
|
| 337 |
+
sk, env = self.sk, self.env
|
| 338 |
+
px, py = inst["phone_xy"]
|
| 339 |
+
zc = envs.TABLE_Z + PT / 2
|
| 340 |
+
g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width
|
| 341 |
+
sk.set_gripper(False, steps=5)
|
| 342 |
+
sk.move_to([px, py, zc + 0.10], yaw=g0)
|
| 343 |
+
sk.move_to([px, py, zc + 0.001], tol=0.003)
|
| 344 |
+
sk.set_gripper(True, steps=15)
|
| 345 |
+
sk.move_to([px, py, Z_CARRY], speed=0.25)
|
| 346 |
+
b = inst["boxes"][int(params["box"])]
|
| 347 |
+
c, s = np.cos(b["yaw"]), np.sin(b["yaw"])
|
| 348 |
+
dx, dy = params.get("dx", 0.0), params.get("dy", 0.0)
|
| 349 |
+
bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy
|
| 350 |
+
sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"]))
|
| 351 |
+
# put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip
|
| 352 |
+
off = envs.obj_pos(env, "phone_1") - sk.eef_pos()
|
| 353 |
+
drop = params.get("drop", DROP)
|
| 354 |
+
sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003)
|
| 355 |
+
tgt = self._servo_phone([bx, by], RIM_Z + drop)
|
| 356 |
+
sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts)
|
| 357 |
+
self._hold_at(tgt, 12)
|
| 358 |
+
sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10])
|
| 359 |
+
sk.move_to(list(PARK), yaw=0.0)
|
| 360 |
+
|
| 361 |
+
def _hold_at(self, target, steps):
|
| 362 |
+
sk = self.sk
|
| 363 |
+
R = sk._R()
|
| 364 |
+
for _ in range(steps):
|
| 365 |
+
sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 366 |
+
|
| 367 |
+
def _servo_phone(self, xy, z_bottom, max_steps=60, tol=0.0015):
|
| 368 |
+
"""Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom.
|
| 369 |
+
Returns the final gripper target."""
|
| 370 |
+
sk = self.sk
|
| 371 |
+
R = sk._R()
|
| 372 |
+
goal = np.array([xy[0], xy[1], z_bottom + PT / 2])
|
| 373 |
+
tgt = e_prev = sk.eef_pos()
|
| 374 |
+
for i in range(max_steps):
|
| 375 |
+
ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos()
|
| 376 |
+
if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
|
| 377 |
+
break
|
| 378 |
+
tgt = goal - (ph - e)
|
| 379 |
+
sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
|
| 380 |
+
e_prev = e
|
| 381 |
+
return tgt
|
| 382 |
+
|
| 383 |
+
# ------------------------------------------------------------ scripted policies
|
| 384 |
+
def _naive_yaw(self, inst, j):
|
| 385 |
+
"""keep the phone's orientation, only snap it to the nearest axis of box j"""
|
| 386 |
+
p = inst["phone_yaw"]
|
| 387 |
+
return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p))
|
| 388 |
+
|
| 389 |
+
def default_params(self, inst):
|
| 390 |
+
"""v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the
|
| 391 |
+
trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its
|
| 392 |
+
tighter direction, i.e. "snug" by construction; phone's long side along the box's long side"""
|
| 393 |
+
marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]]
|
| 394 |
+
j = int(np.argmax(marg))
|
| 395 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 396 |
+
|
| 397 |
+
def nearest_params(self, inst):
|
| 398 |
+
"""v2 prior (kept for reference): nearest box, lined up"""
|
| 399 |
+
d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
|
| 400 |
+
j = int(np.argmin(d))
|
| 401 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 402 |
+
|
| 403 |
+
def oracle_params(self, inst):
|
| 404 |
+
j = inst["fit"]
|
| 405 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 406 |
+
|
| 407 |
+
def blind_params(self, inst, attempt, rng):
|
| 408 |
+
"""no history: a random box (may repeat), lined up like the prior"""
|
| 409 |
+
j = int(rng.integers(N_BOXES))
|
| 410 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 411 |
+
|
| 412 |
+
def naive_keep_yaw_params(self, inst):
|
| 413 |
+
"""old prior (kept for reference): nearest box, keep the phone's orientation"""
|
| 414 |
+
d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
|
| 415 |
+
j = int(np.argmin(d))
|
| 416 |
+
return dict(box=j, place_yaw=self._naive_yaw(inst, j))
|
| 417 |
+
|
| 418 |
+
def adapt_params(self, inst, history):
|
| 419 |
+
"""Scripted learner on F2 feedback.
|
| 420 |
+
|
| 421 |
+
Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the
|
| 422 |
+
phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an
|
| 423 |
+
estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box
|
| 424 |
+
that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and
|
| 425 |
+
lines the phone's long side up with the box's long side.
|
| 426 |
+
"""
|
| 427 |
+
perc = inst["_perc"]
|
| 428 |
+
L_est = W_est = None
|
| 429 |
+
tried_aligned = set()
|
| 430 |
+
for h in history:
|
| 431 |
+
o = h["outcome"]
|
| 432 |
+
fb = o.get("feedback") or {}
|
| 433 |
+
if o.get("failure") != "rim":
|
| 434 |
+
continue
|
| 435 |
+
j = fb["box"]
|
| 436 |
+
a, b = perc[j]
|
| 437 |
+
if fb["along_long"] == "length":
|
| 438 |
+
if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box
|
| 439 |
+
tried_aligned.add(j)
|
| 440 |
+
if fb["over_long_cm"]:
|
| 441 |
+
L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100)
|
| 442 |
+
if fb["over_short_cm"]:
|
| 443 |
+
W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100)
|
| 444 |
+
else:
|
| 445 |
+
if fb["over_short_cm"]:
|
| 446 |
+
L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100)
|
| 447 |
+
if fb["over_long_cm"]:
|
| 448 |
+
W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100)
|
| 449 |
+
thr = 0.002
|
| 450 |
+
cands = []
|
| 451 |
+
for j, (a, b) in enumerate(perc):
|
| 452 |
+
if j in tried_aligned:
|
| 453 |
+
continue
|
| 454 |
+
mL = None if L_est is None else a - L_est
|
| 455 |
+
mW = None if W_est is None else b - W_est
|
| 456 |
+
feasible = (mL is None or mL > thr) and (mW is None or mW > thr)
|
| 457 |
+
if mL is not None and mW is not None:
|
| 458 |
+
key = min(mL, mW)
|
| 459 |
+
elif mL is not None:
|
| 460 |
+
key = b
|
| 461 |
+
elif mW is not None:
|
| 462 |
+
key = a
|
| 463 |
+
else:
|
| 464 |
+
key = a * b
|
| 465 |
+
cands.append((feasible, key, j))
|
| 466 |
+
if not cands:
|
| 467 |
+
j = int(np.argmax([a * b for a, b in perc]))
|
| 468 |
+
else:
|
| 469 |
+
j = max(cands)[2]
|
| 470 |
+
return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 471 |
+
|
| 472 |
+
def elim_params(self, inst, history, rng):
|
| 473 |
+
"""sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up
|
| 474 |
+
after the first attempt) and to never retry a box that got a size verdict; picks among the remaining
|
| 475 |
+
boxes at random, i.e. no size reasoning / perception."""
|
| 476 |
+
bad = set()
|
| 477 |
+
for h in history:
|
| 478 |
+
fb = h["outcome"].get("feedback") or {}
|
| 479 |
+
if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and (
|
| 480 |
+
fb.get("over_long_cm") or fb.get("over_short_cm")):
|
| 481 |
+
bad.add(int(fb["box"]))
|
| 482 |
+
left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES))
|
| 483 |
+
j = int(rng.choice(left))
|
| 484 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 485 |
+
|
| 486 |
+
EXTRA_KINDS = ("elim",)
|
| 487 |
+
|
| 488 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 489 |
+
if kind not in self.EXTRA_KINDS:
|
| 490 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 491 |
+
k = k or self.max_attempts
|
| 492 |
+
rng = np.random.default_rng(seed)
|
| 493 |
+
history = []
|
| 494 |
+
for a in range(k):
|
| 495 |
+
self.reset_instance(inst)
|
| 496 |
+
if a == 0:
|
| 497 |
+
params = self.default_params(inst)
|
| 498 |
+
else:
|
| 499 |
+
params = self.elim_params(inst, history, rng)
|
| 500 |
+
self.execute(inst, params)
|
| 501 |
+
out = self.outcome(inst)
|
| 502 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 503 |
+
if on_attempt:
|
| 504 |
+
on_attempt(a, params, out)
|
| 505 |
+
if out["success"]:
|
| 506 |
+
break
|
| 507 |
+
return history
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
# ---------------------------------------------------------------- physical validity checks
|
| 511 |
+
def physics_check(seed0=1000, n=20, out=None):
|
| 512 |
+
"""Every (box, orientation) pair on each instance, released centred from DROP above the rim.
|
| 513 |
+
Expect success iff the box is the fitting one and the phone's long side is along the box's long side."""
|
| 514 |
+
import json
|
| 515 |
+
task = FitContainer()
|
| 516 |
+
rows = []
|
| 517 |
+
for seed in range(seed0, seed0 + n):
|
| 518 |
+
inst = task.sample_instance(seed)
|
| 519 |
+
for j, b in enumerate(inst["boxes"]):
|
| 520 |
+
for orient in ("aligned", "crossed"):
|
| 521 |
+
task.reset_instance(inst)
|
| 522 |
+
task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2))))
|
| 523 |
+
o = task.outcome(inst)
|
| 524 |
+
rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]],
|
| 525 |
+
orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"),
|
| 526 |
+
failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
|
| 527 |
+
r = rows[-1]
|
| 528 |
+
print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} "
|
| 529 |
+
f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["expect"] else " <-- MISMATCH"), flush=True)
|
| 530 |
+
if out:
|
| 531 |
+
with open(out, "w") as f:
|
| 532 |
+
json.dump(rows, f, indent=1)
|
| 533 |
+
print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows))
|
| 534 |
+
return rows
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def stress_check(seed=1002, out=None):
|
| 538 |
+
"""Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box
|
| 539 |
+
(+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow."""
|
| 540 |
+
import copy
|
| 541 |
+
import json
|
| 542 |
+
task = FitContainer()
|
| 543 |
+
base = task.sample_instance(seed)
|
| 544 |
+
j = base["fit"]
|
| 545 |
+
rows = []
|
| 546 |
+
for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010),
|
| 547 |
+
("narrow_0.5", PL + 0.010, PW - 0.005)]:
|
| 548 |
+
for dx, dy, dyaw, drop in [(0, 0, 0, DROP), (0.004, 0, 0, DROP), (0, 0.004, 0, DROP), (0.007, 0, 0, DROP),
|
| 549 |
+
(0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]:
|
| 550 |
+
inst = copy.deepcopy(base)
|
| 551 |
+
inst["boxes"][j]["inner"] = [a, b]
|
| 552 |
+
task.reset_instance(inst)
|
| 553 |
+
task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)),
|
| 554 |
+
dx=dx, dy=dy, drop=drop))
|
| 555 |
+
o = task.outcome(inst)
|
| 556 |
+
rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000,
|
| 557 |
+
dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"],
|
| 558 |
+
height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
|
| 559 |
+
print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> "
|
| 560 |
+
f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True)
|
| 561 |
+
if out:
|
| 562 |
+
with open(out, "w") as f:
|
| 563 |
+
json.dump(rows, f, indent=1)
|
| 564 |
+
return rows
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
if __name__ == "__main__":
|
| 568 |
+
# python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json
|
| 569 |
+
# python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json
|
| 570 |
+
import sys
|
| 571 |
+
if sys.argv[1] == "physics":
|
| 572 |
+
physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
|
| 573 |
+
elif sys.argv[1] == "stress":
|
| 574 |
+
stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_tidy_stack.py
ADDED
|
@@ -0,0 +1,1260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH lh_tidy_stack v2 (2026-10-16): tidy the table -- stack the four storage boxes (red, green, blue, yellow; alike,
|
| 2 |
+
6 x 6 x 5 cm) into one pile on a grey mat, in any order, then stand the cup on top. In 18 of every 20 instances one box
|
| 3 |
+
(random colour) is an empty, soft carton: it carries one thing, but as soon as a second thing comes to rest above it,
|
| 4 |
+
it gives way -- standing it folds sideways, lying on a side face it is crushed flat -- and everything above it slides
|
| 5 |
+
off the pile: the stage that made the pile two higher destroys the stage before it.
|
| 6 |
+
|
| 7 |
+
Family: long-horizon self-disturbance ("state_restoration"): the later stages' ordinary action (putting the next box on)
|
| 8 |
+
undoes earlier ones; the agent has to see which box gave way, take it out of the pile and rebuild with it on top (within
|
| 9 |
+
an attempt) or remember its colour (across attempts). The cheapest explanation of a toppled pile ("I did not centre the
|
| 10 |
+
box", "I let go too high") is wrong: perfectly centred boxes let go 5 mm above the pile topple it just the same
|
| 11 |
+
(control naive_centred).
|
| 12 |
+
|
| 13 |
+
v1 -> v2 (Sonnet 5.5 pilot np3_lh_tidy_stack, seeds 3000 / 3002 / 3003, k=3; logs measured by the coordinator and
|
| 14 |
+
replayed here): in s3002 attempt 2 boxes that had fallen on their sides were restacked lying (a lying box looks the
|
| 15 |
+
same: they are nearly cubes); the soft box lay on its side at level 2 under two boxes and the cup, and the v1 law, which
|
| 16 |
+
measured the load along the box axis only, saw -0.06 N and never fired -> judged a success. Sonnet also presses what it
|
| 17 |
+
puts down 0.5-1.5 cm below contact (its own logs: the gripper stops 0.6-1.5 cm above the commanded release height), and
|
| 18 |
+
in s3003 a cup pressed onto the soft box on top -- where it belongs -- crushed it under one item (v1: 2.45 N). v2:
|
| 19 |
+
(1) the load is measured along the world vertical, whichever face the carton rests on (`vertical_loads`: the downward
|
| 20 |
+
push on its upper side, limited by the support under it);
|
| 21 |
+
(2) a carton lying on a side face (seam vertical) cannot fold under gravity, so it is crushed instead: both halves
|
| 22 |
+
flatten towards the face they rest on, the upper half by 70 % and the lower by 30 % (runtime geom sizes +
|
| 23 |
+
envs.refit_bounds), the top becomes a 2-3 cm step and what is on it tips off;
|
| 24 |
+
(3) only what rests on the carton counts, at most with its own weight (+0.3 N for impacts): something the robot still
|
| 25 |
+
holds, the robot pushing down through an item it has just let go of, and the fingers pressing the held carton
|
| 26 |
+
itself onto something do not count; the robot's own fingers / hand pushing on its top do (a hard press may crush
|
| 27 |
+
it: the closed gripper 3 mm onto its top does; logged as cause "press", not counted as the trap unless it costs a
|
| 28 |
+
stage);
|
| 29 |
+
(4) items weigh 200 g (box and cup; v1 180 / 160 g) and f_crit = 3.45 N: one item 1.96 N, two 3.92 N;
|
| 30 |
+
(5) the rigid boxes' joints are stiffer (20 Nm/rad, stiff limit; at 3 Nm/rad Sonnet's cup press on a 4-high pile bent
|
| 31 |
+
every box ~4 deg and the pile leaned 10 deg in the replay); after a fold the carton straightens along a rest
|
| 32 |
+
shape that moves back to straight over 1.5 s (released at once, a stiff spring flipped it onto its side);
|
| 33 |
+
(6) stacking tolerance 3 cm instead of 2.5 (a correctly stacked oracle_noise pile failed at 2.51 cm).
|
| 34 |
+
v1 code and results: scratchpad lh_tidy_stack_v1.py, results/_old/lh_tidy_stack_v1/.
|
| 35 |
+
|
| 36 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 37 |
+
* a grey mat (13 x 13 cm, visual only), centre x in [-0.11, -0.05], |y| <= 5 cm;
|
| 38 |
+
* four storage boxes (6 x 6 x 5 cm, bright red / green / blue / yellow with a darker lid line, 200 g; friction 0.5)
|
| 39 |
+
15, 18.5, 22 and 25.5 cm (+-1 cm) from the mat centre, at random angles 30-150 deg from forward on its left and right,
|
| 40 |
+
yaw +-17 deg, colours shuffled;
|
| 41 |
+
* a dark teal cup (5 cm wide, 7 cm tall, 200 g) on the robot's side of the mat, 23-26 cm away.
|
| 42 |
+
|
| 43 |
+
Hidden variable: which box is the soft carton (60 g; mass is not observable). Instances come in balanced blocks of 20
|
| 44 |
+
consecutive seeds ((seed x 7) mod 20 = k): k >= 18 benign (no soft box); otherwise the soft box is the one at rank
|
| 45 |
+
k mod 4 of the distance to the mat (0 = nearest = the bottom of a nearest-first pile, 3 = the top): 5 / 5 / 4 / 4.
|
| 46 |
+
A nearest-first stacker therefore meets it below the top in 14 of 20 instances.
|
| 47 |
+
|
| 48 |
+
Mechanism (physics; nothing is teleported). Every box is built alike: a lower half (the root body) and an upper half
|
| 49 |
+
joined by a ball joint at mid-height (the seam is invisible). In the three rigid boxes the joint is locked (range
|
| 50 |
+
0.003 rad, stiffness 3 Nm/rad). The soft carton follows a load law (`_law_step`, every MuJoCo substep): its compressive
|
| 51 |
+
load (above, low-passed with 0.4 s) is compared with f_crit (instance key "f_crit": the fragility knob). Below it the
|
| 52 |
+
joint keeps 3 Nm/rad (one box 1.3 cm off-centre tilts it < 1 deg: looks like the rigid boxes). Above it:
|
| 53 |
+
* standing or upside down (seam horizontal): the joint stiffness drops to 0.03 Nm/rad -- a column with m g h ~ 0.27
|
| 54 |
+
Nm/rad on it is unstable, centred or not -- and its rest shape bends 12 deg towards a per-instance side: the upper
|
| 55 |
+
half folds sideways (38-54 deg measured, joint limit 54 deg) and what is on it slides off;
|
| 56 |
+
* lying on a side face (seam vertical): crushed as above within ~0.1 s.
|
| 57 |
+
Unloaded (< 0.5 N) for 0.3 s it recovers over ~1.5 s (still visibly bent / flattened in the images of the next one or
|
| 58 |
+
two commands). One item on it is carried (a box let go 4 cm above adds < 0.5 N to the filtered load), two are not. So
|
| 59 |
+
the pile survives only with the soft box on top (carrying just the cup): soft at level 1 -> it gives way when box 3
|
| 60 |
+
lands (boxes 2 and 3 fall), level 2 -> when box 4 lands, level 3 -> when the cup lands (box 4 and the cup fall; standing,
|
| 61 |
+
the cup ends on its side, which a top-down gripper cannot undo, so that attempt cannot be repaired). Measured (v2, naive
|
| 62 |
+
without rebuilding, the 14 trap instances of seeds 1000-1019): standing 14/14 folded at exactly that stage, the soft
|
| 63 |
+
box stayed upright in the pile 14/14 (fold 37-55 deg), the cup fell 4/4 at level 3; lying (control naive_lying: the
|
| 64 |
+
soft box starts on a side face and is stacked lying) crushed at exactly that stage in every trap instance.
|
| 65 |
+
|
| 66 |
+
Why not the linear spring of the brief (a ball joint with one fixed stiffness k): the load that k must carry (the cup)
|
| 67 |
+
and the load that must topple it (one more box) differ by a factor of ~2-3, and an inverted pendulum close to its
|
| 68 |
+
critical load amplifies placement offsets (tilt = W e / (k - m g h)); measured (results/lh_tidy_stack/linear.json,
|
| 69 |
+
instance key law="linear"): no k gives both a soft box that carries the cup on top without sagging and a pile that
|
| 70 |
+
topples however carefully it is centred (k <= 0.25 Nm/rad: the correct pile fails 5-10/10; k = 0.5: a centred
|
| 71 |
+
level-3 soft box carries box + cup, 2/2). A load threshold (walls that
|
| 72 |
+
hold until they buckle) keeps the soft box looking and behaving rigid until the second item, independent of centring.
|
| 73 |
+
|
| 74 |
+
Success predicate (from the instruction): all four boxes in one chain -- the bottom one on the mat (lowest point <= 8 mm
|
| 75 |
+
above the table, centre within 3.5 cm of the mat centre in x and y: its footprint on the 13 cm mat), each next one
|
| 76 |
+
resting on the previous (its lowest point within 1 cm of the top of the box below, centres within 3 cm), every box
|
| 77 |
+
flat (some face within 10 deg of horizontal: a fallen box cannot be stood up again by a vertical gripper, so a box on
|
| 78 |
+
its side counts), not bent (kink <= 10 deg) and not crushed (<= 15 %) --; the cup upright (<= 10 deg) on the top box
|
| 79 |
+
(bottom within 1 cm, centre within 3 cm); nothing held, the gripper not touching anything, the scene static (< 3 mm
|
| 80 |
+
in 1 s). Tolerance: 3 cm = the box's half width, i.e. the upper box's centre of mass is over the lower box's top face
|
| 81 |
+
(physically resting on it; the static check rejects anything that does not stay). Sonnet's measured placement error is
|
| 82 |
+
0.4-1.3 cm, so two placements differ by up to 2.6 cm plus a few mm of landing drift (v2: the 2.5 cm of v1 failed one
|
| 83 |
+
correctly stacked oracle_noise pile, seed 1008, at 2.51 cm).
|
| 84 |
+
|
| 85 |
+
Event monitor (server log only; F1 gives the agent only success / failure): stage predicates red / green / blue /
|
| 86 |
+
yellow (box in the pile) and cup (cup on a complete pile), debounced over 0.5 s: achieved / lost (cause buckle / robot
|
| 87 |
+
/ picked_up / other) / restored; `buckle` (= trap fired: load, the robot's share of it, fold or crush, lying, level,
|
| 88 |
+
items on it), `collapse` (a buckle that cost a stage). Outcome: success, failure (none / held / touching / collapsed /
|
| 89 |
+
regressed / not_stacked / cup_fallen / cup_not_on_top / not_static), trap_fired, recovered_in_attempt, n_buckles,
|
| 90 |
+
n_collapses, buckle_how, max_kink_deg, max_crush, detail (F2). The law's state rides along in task.mon["law"]; a
|
| 91 |
+
crushed carton's geom sizes are restored at every reset.
|
| 92 |
+
|
| 93 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 94 |
+
"""
|
| 95 |
+
import mujoco
|
| 96 |
+
import numpy as np
|
| 97 |
+
|
| 98 |
+
from .. import envs
|
| 99 |
+
from ..bddl import write_bddl
|
| 100 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 101 |
+
from ..skills import Skills
|
| 102 |
+
from ..task_base import LFFTask, register_task
|
| 103 |
+
|
| 104 |
+
TZ = envs.TABLE_Z
|
| 105 |
+
G = 9.81
|
| 106 |
+
COLOURS = ["red", "green", "blue", "yellow"]
|
| 107 |
+
BOXES = [f"box_{c}_1" for c in COLOURS]
|
| 108 |
+
COL = dict(zip(BOXES, COLOURS))
|
| 109 |
+
CUP, MAT = "cup_1", "mat_1"
|
| 110 |
+
RGBA = {"red": (0.80, 0.16, 0.13, 1.0), "green": (0.17, 0.58, 0.25, 1.0), "blue": (0.16, 0.34, 0.80, 1.0),
|
| 111 |
+
"yellow": (0.90, 0.74, 0.14, 1.0)}
|
| 112 |
+
CUP_RGBA = (0.10, 0.45, 0.50, 1.0) # dark teal ceramic, darker inside
|
| 113 |
+
CUP_INSIDE = (0.20, 0.20, 0.19, 1.0)
|
| 114 |
+
MAT_RGBA = (0.45, 0.45, 0.47, 1.0)
|
| 115 |
+
|
| 116 |
+
# ---------------------------------------------------------------- boxes (all four built alike: base + upper part)
|
| 117 |
+
HX, HY, H = 0.030, 0.030, 0.050 # 6 x 6 x 5 cm (the gripper opens 7.9 cm)
|
| 118 |
+
HB = 0.025 # base part height = height of the seam (ball joint) above the bottom: mid-height, so the upper
|
| 119 |
+
# half can fold ~56 deg before its edge reaches the surface below
|
| 120 |
+
HU = H - HB
|
| 121 |
+
BOX_MASS = 0.20 # a filled storage box (v1: 0.18)
|
| 122 |
+
SOFT_MASS = 0.06 # the empty carton (mass is not observable by the agent)
|
| 123 |
+
BOX_MU = 0.5
|
| 124 |
+
CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"'
|
| 125 |
+
# soft-carton law (see SoftLaw): stiff until the compressive load through its walls exceeds F_CRIT, then soft
|
| 126 |
+
K_HI = 3.0 # Nm/rad: the intact soft carton (one box 1.3 cm off-centre tilts it ~0.5 deg; a cup pressed onto it
|
| 127 |
+
# bends it ~4 deg)
|
| 128 |
+
K_RIGID = 20.0 # Nm/rad + a stiff joint limit: the rigid boxes (at 3 Nm/rad a cup pressed onto a 4-high pile bent every
|
| 129 |
+
# box 4 deg and the pile leaned 10 deg -- replay of pilot s3003 on v2; at 20 for the soft carton too
|
| 130 |
+
# its folds flipped it onto its side 4/14 times)
|
| 131 |
+
K_LO = 0.03 # Nm/rad: buckled (one box on it destabilises it: m g h ~ 0.12 Nm/rad)
|
| 132 |
+
DAMP = 0.01
|
| 133 |
+
F_CRIT = 3.45 # N, vertical load from above (resting things + whatever the robot pushes or holds onto it): one
|
| 134 |
+
# item weighs 1.96 N and a held item pressed onto the carton adds <= ~0.9 N before it slips in the
|
| 135 |
+
# fingers (measured, t10_press); two items weigh 3.92 N (v1: 2.45 N with 1.77 / 1.57 N items)
|
| 136 |
+
F_REL = 0.5 # N: unloaded below this ...
|
| 137 |
+
REL_T = 0.3 # ... for this long -> it springs back
|
| 138 |
+
TAU_F = 0.4 # s: low-pass of the load (impacts of a box let go 1-4 cm above do not count)
|
| 139 |
+
K_RISE = 1.5 # s: the folded carton straightens along a reference that moves back to straight in this time
|
| 140 |
+
BEND_REF = np.radians(12.0) # reference bend of the buckled carton (the weak side; direction per instance)
|
| 141 |
+
RANGE_SOFT, RANGE_RIGID = 0.95, 0.003 # rad: kink limit (54 deg) of the soft carton; the rigid boxes are locked
|
| 142 |
+
# v2: a carton lying on a side face (its seam vertical) cannot fold under gravity; it is crushed instead: both halves
|
| 143 |
+
# flatten towards the surface below, the upper half much more, so the top becomes a 2-3 cm step and what is on it
|
| 144 |
+
# tips off (geom sizes changed at runtime + envs.refit_bounds)
|
| 145 |
+
CRUSH_ALPHA = (0.30, 0.70) # fraction of the height lost by the base half / the upper half when fully crushed
|
| 146 |
+
CRUSH_TAU = (0.08, 0.7) # s: crushing / recovering
|
| 147 |
+
FOLD_MIN_UP = 0.7 # |seam normal . vertical| above this: the fold (upright or upside down); below: the crush
|
| 148 |
+
|
| 149 |
+
# ---------------------------------------------------------------- cup
|
| 150 |
+
CUP_R, CUP_H, CUP_MASS = 0.025, 0.070, 0.20 # v1: 0.16
|
| 151 |
+
|
| 152 |
+
# ---------------------------------------------------------------- mat and layout
|
| 153 |
+
MAT_HALF = 0.065 # 13 x 13 cm
|
| 154 |
+
MAT_X, MAT_Y = (-0.11, -0.05), (-0.05, 0.05)
|
| 155 |
+
BOX_D = (0.15, 0.185, 0.22, 0.255) # distances of the four boxes from the mat centre (+- jitter)
|
| 156 |
+
BOX_X = (-0.33, 0.07) # world x range of the box positions (reach)
|
| 157 |
+
BOX_YMAX = 0.30
|
| 158 |
+
BOX_YAW = 0.30
|
| 159 |
+
P_BENIGN = 0.10 # 2 of every 20 consecutive seeds: no soft box
|
| 160 |
+
|
| 161 |
+
# ---------------------------------------------------------------- predicates
|
| 162 |
+
TILT_OK = np.radians(10.0)
|
| 163 |
+
KINK_OK = np.radians(10.0)
|
| 164 |
+
ON_MAT = 0.035 # bottom box centre within 3.5 cm of the mat centre (x and y): its footprint is on the 13 cm mat
|
| 165 |
+
STACK_XY = 0.030 # centre of a box within 3 cm (= the half width) of the centre of the box below: its centre of
|
| 166 |
+
# mass is over the lower box's top face (v2; 2.5 cm judged a resting box 2.51 cm off as not stacked)
|
| 167 |
+
STACK_Z = 0.010
|
| 168 |
+
CUP_XY = 0.030
|
| 169 |
+
DEBOUNCE = 10 # control steps (0.5 s)
|
| 170 |
+
|
| 171 |
+
# ---------------------------------------------------------------- scripted motion
|
| 172 |
+
Z_CARRY = 0.18
|
| 173 |
+
NAIVE_ERR = (0.004, 0.013) # Sonnet's placement error 0.4-1.3 cm (random direction)
|
| 174 |
+
NAIVE_GAP = (0.010, 0.040) # Sonnet lets go 1-4 cm above the surface
|
| 175 |
+
NAIVE_BIAS = (0.0, 0.020) # forward bias of the first box on the mat (oblique camera)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def box_xml(name, rgba):
|
| 179 |
+
"""storage box: base part (root body, 1.6 cm) + upper part (child body) on a ball joint at the seam. Rigid boxes
|
| 180 |
+
get a ~0 kink range at reset; the soft carton a 31.5 deg range and the load-dependent stiffness of SoftLaw.
|
| 181 |
+
Inertials are replaced per instance (mass)."""
|
| 182 |
+
mb, mu = BOX_MASS * HB / H, BOX_MASS * HU / H
|
| 183 |
+
zb = -H / 2 + HB / 2
|
| 184 |
+
dark = [0.72 * c for c in rgba[:3]] + [1.0]
|
| 185 |
+
g = [f' <inertial pos="0 0 {zb:.5f}" mass="{mb:.5f}" diaginertia="1e-5 1e-5 1e-5" />',
|
| 186 |
+
f' <geom name="{name}_base" type="box" size="{HX:.5f} {HY:.5f} {HB / 2:.5f}" pos="0 0 {zb:.5f}" '
|
| 187 |
+
f'rgba="{_fmt(rgba)}" friction="{BOX_MU} 0.005 0.0001" {CONTACT} group="0" />',
|
| 188 |
+
f' <geom type="box" size="{HX:.5f} {HY:.5f} {HB / 2:.5f}" pos="0 0 {zb:.5f}" rgba="{_fmt(rgba)}" '
|
| 189 |
+
f'contype="0" conaffinity="0" group="1" />',
|
| 190 |
+
f' <body name="{name}_upper" pos="0 0 {-H / 2 + HB:.5f}">',
|
| 191 |
+
f' <joint name="{name}_kink" type="ball" pos="0 0 0" range="0 {RANGE_SOFT}" stiffness="{K_HI}" '
|
| 192 |
+
f'damping="{DAMP}" armature="0.0001" />',
|
| 193 |
+
f' <inertial pos="0 0 {HU / 2:.5f}" mass="{mu:.5f}" diaginertia="1e-5 1e-5 1e-5" />',
|
| 194 |
+
f' <geom name="{name}_upper" type="box" size="{HX:.5f} {HY:.5f} {HU / 2:.5f}" pos="0 0 {HU / 2:.5f}" '
|
| 195 |
+
f'rgba="{_fmt(rgba)}" friction="{BOX_MU} 0.005 0.0001" {CONTACT} group="0" />',
|
| 196 |
+
f' <geom type="box" size="{HX:.5f} {HY:.5f} {HU / 2:.5f}" pos="0 0 {HU / 2:.5f}" rgba="{_fmt(rgba)}" '
|
| 197 |
+
f'contype="0" conaffinity="0" group="1" />',
|
| 198 |
+
# lid line (visual only): a darker band 8 mm below the top, on all four boxes
|
| 199 |
+
f' <geom type="box" size="{HX + 0.0006:.5f} {HY + 0.0006:.5f} 0.0012" pos="0 0 {HU - 0.008:.5f}" '
|
| 200 |
+
f'rgba="{_fmt(dark)}" contype="0" conaffinity="0" group="1" />',
|
| 201 |
+
' </body>']
|
| 202 |
+
return _wrap(name, "\n".join(g), H / 2, float(np.hypot(HX, HY)))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def cup_xml(name):
|
| 206 |
+
"""open cup, 5 cm wide, 7 cm tall: 12 wall boxes + an octagonal base of two boxes (box contacts; a light MuJoCo
|
| 207 |
+
cylinder creeps on a flat surface, lh_nudge_row). Visual: a smooth cylinder with a dark inside."""
|
| 208 |
+
r, h = CUP_R, CUP_H
|
| 209 |
+
nseg, wt, bt = 12, 0.004, 0.006
|
| 210 |
+
g = [f' <inertial pos="0 0 {-h / 2 + 0.022:.4f}" mass="{CUP_MASS}" diaginertia="1.5e-4 1.5e-4 1.0e-4" />']
|
| 211 |
+
s = r * np.sin(np.pi / nseg) + 0.0008
|
| 212 |
+
rc = r * np.cos(np.pi / nseg) - wt / 2
|
| 213 |
+
for k in range(nseg):
|
| 214 |
+
a = 2 * np.pi * k / nseg
|
| 215 |
+
q = [np.cos(a / 2), 0, 0, np.sin(a / 2)]
|
| 216 |
+
g.append(f' <geom name="{name}_w{k}" type="box" size="{wt / 2:.5f} {s:.5f} {(h - 0.001) / 2:.5f}" '
|
| 217 |
+
f'pos="{rc * np.cos(a):.5f} {rc * np.sin(a):.5f} 0.0005" quat="{_fmt(q)}" rgba="{_fmt(CUP_RGBA)}" '
|
| 218 |
+
f'friction="0.8 0.005 0.0001" {CONTACT} group="0" />')
|
| 219 |
+
a0 = r * 0.70
|
| 220 |
+
for k, ang in enumerate((0.0, np.pi / 4)):
|
| 221 |
+
q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)]
|
| 222 |
+
g.append(f' <geom name="{name}_b{k}" type="box" size="{a0:.5f} {a0:.5f} {bt / 2:.5f}" '
|
| 223 |
+
f'pos="0 0 {-h / 2 + bt / 2:.5f}" quat="{_fmt(q)}" rgba="{_fmt(CUP_RGBA)}" '
|
| 224 |
+
f'friction="0.6 0.005 0.0001" {CONTACT} group="0" />')
|
| 225 |
+
g.append(f' <geom type="cylinder" size="{r:.5f} {h / 2:.5f}" rgba="{_fmt(CUP_RGBA)}" contype="0" '
|
| 226 |
+
f'conaffinity="0" group="1" />')
|
| 227 |
+
g.append(f' <geom type="cylinder" size="{r - wt:.5f} 0.0005" pos="0 0 {h / 2 - 0.0004:.5f}" '
|
| 228 |
+
f'rgba="{_fmt(CUP_INSIDE)}" contype="0" conaffinity="0" group="1" />')
|
| 229 |
+
return _wrap(name, "\n".join(g), h / 2, r)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def mat_xml(name):
|
| 233 |
+
g = (f' <geom type="box" size="{MAT_HALF:.5f} {MAT_HALF:.5f} 0.0005" rgba="{_fmt(MAT_RGBA)}" contype="0" '
|
| 234 |
+
f'conaffinity="0" group="1" />')
|
| 235 |
+
return _wrap(name, g, 0.0005, MAT_HALF * 1.42)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def free_adr(env, name):
|
| 239 |
+
"""(qpos, dof) address of the object's FREE joint. envs.free_joint_addr takes joints[0], which for an object with a
|
| 240 |
+
jointed child body is the child's joint (robosuite lists the subtree's joints before the free joint it appends)."""
|
| 241 |
+
m = env.sim.model
|
| 242 |
+
for jn in env.objects_dict[name].joints:
|
| 243 |
+
j = m.joint_name2id(jn)
|
| 244 |
+
if int(m.jnt_type[j]) == 0:
|
| 245 |
+
return int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j])
|
| 246 |
+
raise KeyError(name)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def place(env, name, xy, yaw=0.0, surface_z=TZ, clearance=0.0005, tilt=None):
|
| 250 |
+
"""teleport upright (yaw about z; `tilt` rad about the object's own x axis first, e.g. pi/2 = lying on a side
|
| 251 |
+
face -- controls only), lowest collision point `clearance` above surface_z (reset only)"""
|
| 252 |
+
qa, da = free_adr(env, name)
|
| 253 |
+
d = env.sim.data
|
| 254 |
+
d.qpos[qa:qa + 3] = [xy[0], xy[1], surface_z + 0.3]
|
| 255 |
+
q = np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)])
|
| 256 |
+
if tilt:
|
| 257 |
+
w1, z1 = q[0], q[3]
|
| 258 |
+
c, s_ = np.cos(tilt / 2), np.sin(tilt / 2)
|
| 259 |
+
q = np.array([w1 * c, w1 * s_, z1 * s_, z1 * c]) # q_yaw * q_x(tilt)
|
| 260 |
+
d.qpos[qa + 3:qa + 7] = q
|
| 261 |
+
d.qvel[da:da + 6] = 0.0
|
| 262 |
+
env.sim.forward()
|
| 263 |
+
d.qpos[qa + 2] -= envs.obj_min_z(env, name) - (surface_z + clearance)
|
| 264 |
+
env.sim.forward()
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def _fb(v):
|
| 268 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _lr(v):
|
| 272 |
+
return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _wrap_q(a, period):
|
| 276 |
+
"""wrap an angle to [-period/2, period/2)"""
|
| 277 |
+
return float((a + period / 2) % period - period / 2)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class StackSkills(Skills):
|
| 281 |
+
"""Skills that feed the task's per-step monitor."""
|
| 282 |
+
|
| 283 |
+
def __init__(self, env, task, recorder=None):
|
| 284 |
+
super().__init__(env, recorder=recorder)
|
| 285 |
+
self.task = task
|
| 286 |
+
|
| 287 |
+
def _act(self, dpos, drot, grip):
|
| 288 |
+
super()._act(dpos, drot, grip)
|
| 289 |
+
self.task.monitor_step()
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@register_task
|
| 293 |
+
class TidyStack(LFFTask):
|
| 294 |
+
name = "lh_tidy_stack"
|
| 295 |
+
level = "L2"
|
| 296 |
+
category = "state_restoration"
|
| 297 |
+
capabilities = ("Perceive", "Reason", "Restore", "Plan")
|
| 298 |
+
protocol = "cross"
|
| 299 |
+
max_attempts = 3
|
| 300 |
+
# careful: 5 pick-and-places x ~8 commands (40) + a collapse: unstack 1-2 boxes (~16) and rebuild 3-4 (~32)
|
| 301 |
+
# + looking / small corrections (~30), with some margin
|
| 302 |
+
agent_max_steps = 150
|
| 303 |
+
instruction = ("Tidy up the table: stack the four storage boxes (red, green, blue, yellow) into a single pile on the "
|
| 304 |
+
"grey mat, in any order you like, and then put the cup upright on top of the pile. At the end each "
|
| 305 |
+
"box must rest flat on the box below it (the bottom one on the mat), the cup must stand on the top "
|
| 306 |
+
"box, and the gripper must be open and clear of everything.")
|
| 307 |
+
instruction_indirect = ("Clean up the table: pile the four coloured boxes on top of each other on the dark grey "
|
| 308 |
+
"square, in whatever order, and finish by standing the teal mug on top of the pile. In the "
|
| 309 |
+
"end every box has to sit flat on the one below it (the lowest on the grey square), the mug "
|
| 310 |
+
"has to stand on the top box, and the gripper must be open and away from everything.")
|
| 311 |
+
agent_object_names = ["storage boxes (red, green, blue, yellow)", "grey mat", "cup"]
|
| 312 |
+
|
| 313 |
+
# ------------------------------------------------------------ scene
|
| 314 |
+
def make_bddl(self):
|
| 315 |
+
objs = []
|
| 316 |
+
for i, (c, b) in enumerate(zip(COLOURS, BOXES)):
|
| 317 |
+
cat = register_generated(f"LffLtsBox{c.capitalize()}", box_xml(f"lff_lts_box_{c}", RGBA[c]))
|
| 318 |
+
objs.append((b, cat, f"box{i}_region", (-0.30 + 0.13 * i, 0.28, -0.29 + 0.13 * i, 0.29)))
|
| 319 |
+
cat = register_generated("LffLtsCup", cup_xml("lff_lts_cup"))
|
| 320 |
+
objs.append((CUP, cat, "cup_region", (-0.30, -0.29, -0.29, -0.28)))
|
| 321 |
+
mat = register_generated("LffLtsMat", mat_xml("lff_lts_mat"), free=False)
|
| 322 |
+
fx = [(MAT, mat, "mat_region", (0.0, -0.29, 0.01, -0.28))]
|
| 323 |
+
return write_bddl(self.name, "Stack the four boxes on the grey mat and put the cup on top", objs, fx)
|
| 324 |
+
|
| 325 |
+
def __init__(self, cam_res=None):
|
| 326 |
+
super().__init__(cam_res)
|
| 327 |
+
m = self.env.sim.model
|
| 328 |
+
self.mat_bid = m.body_name2id(self.env.fixtures_dict[MAT].root_body)
|
| 329 |
+
self.jid, self.base_bid, self.upper_bid, self.base_gid, self.upper_gid = {}, {}, {}, {}, {}
|
| 330 |
+
for b in BOXES:
|
| 331 |
+
for g in envs.obj_geom_ids(self.env, b):
|
| 332 |
+
n = m.geom_id2name(g)
|
| 333 |
+
if n.endswith("_upper"):
|
| 334 |
+
self.upper_gid[b] = g
|
| 335 |
+
elif n.endswith("_base"):
|
| 336 |
+
self.base_gid[b] = g
|
| 337 |
+
self.upper_bid[b] = int(m.geom_bodyid[self.upper_gid[b]])
|
| 338 |
+
self.base_bid[b] = int(m.geom_bodyid[self.base_gid[b]])
|
| 339 |
+
j = next(m.joint_name2id(jn) for jn in self.env.objects_dict[b].joints if jn.endswith("_kink"))
|
| 340 |
+
self.jid[b] = j
|
| 341 |
+
# every geom of each half (collision and visual) with its compiled size / pos: the crush rescales them
|
| 342 |
+
self.half_geoms = {}
|
| 343 |
+
for b in BOXES:
|
| 344 |
+
hg = []
|
| 345 |
+
for bid in (self.base_bid[b], self.upper_bid[b]):
|
| 346 |
+
gs = [g for g in range(int(m.body_geomadr[bid]), int(m.body_geomadr[bid] + m.body_geomnum[bid]))
|
| 347 |
+
if int(m.geom_type[g]) == 6]
|
| 348 |
+
hg.append((bid, gs, m.geom_size[gs].copy(), m.geom_pos[gs].copy()))
|
| 349 |
+
self.half_geoms[b] = hg
|
| 350 |
+
self.cup_gids = list(envs.obj_geom_ids(self.env, CUP))
|
| 351 |
+
self.obj_bodies = {b: [self.base_bid[b], self.upper_bid[b]] for b in BOXES}
|
| 352 |
+
self.obj_bodies[CUP] = [envs.body_id(self.env, CUP)]
|
| 353 |
+
# per-geom lookup: owner index 0-3 = boxes, 4 = cup, -1 other; robot part 1 = finger, 2 = hand / arm
|
| 354 |
+
self.owner = np.full(m.ngeom, -1, int)
|
| 355 |
+
for i, b in enumerate(BOXES):
|
| 356 |
+
self.owner[[self.base_gid[b], self.upper_gid[b]]] = i
|
| 357 |
+
self.owner[self.cup_gids] = 4
|
| 358 |
+
self.part = np.zeros(m.ngeom, int)
|
| 359 |
+
for g in envs.robot_geom_ids(self.env):
|
| 360 |
+
n = m.geom_id2name(g) or ""
|
| 361 |
+
self.part[g] = 1 if "finger" in n else 2
|
| 362 |
+
self.inst = None
|
| 363 |
+
self.law = None
|
| 364 |
+
self.mon = None
|
| 365 |
+
self.sk = None
|
| 366 |
+
self._sub_rob = {}
|
| 367 |
+
self._held = set() # owner indices (0-3 boxes, 4 cup) held by the gripper, refreshed every control step
|
| 368 |
+
self._rest_cap = np.inf # upper bound of the resting load on the soft carton, refreshed every control step
|
| 369 |
+
sim = self.env.sim
|
| 370 |
+
if not getattr(sim, "_lts_wrapped", False):
|
| 371 |
+
orig = sim.step
|
| 372 |
+
|
| 373 |
+
def step(*a, **k):
|
| 374 |
+
t = getattr(sim, "_lts_task", None)
|
| 375 |
+
if t is not None and t.law is not None:
|
| 376 |
+
t._law_step()
|
| 377 |
+
orig(*a, **k)
|
| 378 |
+
if t is not None and t.mon is not None:
|
| 379 |
+
t._substep()
|
| 380 |
+
sim.step = step
|
| 381 |
+
sim._lts_wrapped = True
|
| 382 |
+
sim._lts_task = self
|
| 383 |
+
|
| 384 |
+
# ------------------------------------------------------------ instances
|
| 385 |
+
def sample_instance(self, seed):
|
| 386 |
+
rng = np.random.default_rng(seed)
|
| 387 |
+
mx, my = float(rng.uniform(*MAT_X)), float(rng.uniform(*MAT_Y))
|
| 388 |
+
ca = np.pi + float(rng.uniform(-0.5, 0.5)) # the cup stands on the robot's side of the mat, 23-26 cm away
|
| 389 |
+
cd = float(rng.uniform(0.23, 0.26))
|
| 390 |
+
cup = [mx + cd * np.cos(ca), my + cd * np.sin(ca)]
|
| 391 |
+
for _ in range(500):
|
| 392 |
+
ds = np.array(BOX_D) + rng.uniform(-0.01, 0.01, 4)
|
| 393 |
+
ang = rng.uniform(np.radians(30), np.radians(150), 4) * rng.choice([-1.0, 1.0], 4)
|
| 394 |
+
pos = np.stack([mx + ds * np.cos(ang), my + ds * np.sin(ang)], 1)
|
| 395 |
+
if not (np.all((pos[:, 0] >= BOX_X[0]) & (pos[:, 0] <= BOX_X[1])) and np.all(np.abs(pos[:, 1]) <= BOX_YMAX)):
|
| 396 |
+
continue
|
| 397 |
+
dd = np.linalg.norm(pos[:, None] - pos[None], axis=2) + np.eye(4)
|
| 398 |
+
if dd.min() < 0.12 or np.linalg.norm(pos - np.asarray(cup), axis=1).min() < 0.14:
|
| 399 |
+
continue
|
| 400 |
+
break
|
| 401 |
+
else:
|
| 402 |
+
raise RuntimeError("layout")
|
| 403 |
+
perm = rng.permutation(4)
|
| 404 |
+
start = {BOXES[i]: [float(v) for v in pos[perm[i]]] for i in range(4)}
|
| 405 |
+
yaw = {b: float(rng.uniform(-BOX_YAW, BOX_YAW)) for b in BOXES}
|
| 406 |
+
mat = np.array([mx, my])
|
| 407 |
+
near = sorted(BOXES, key=lambda b: float(np.linalg.norm(np.asarray(start[b]) - mat)))
|
| 408 |
+
# balanced blocks of 20 consecutive seeds: 2 benign (no soft box); else the soft carton is the box at rank
|
| 409 |
+
# r = 0..3 (0 = nearest the mat, i.e. the bottom of a nearest-first pile; 3 = the top): 5 / 5 / 4 / 4
|
| 410 |
+
k = (int(seed) * 7) % 20
|
| 411 |
+
benign = k >= round(20 * (1 - P_BENIGN))
|
| 412 |
+
rank = None if benign else k % 4
|
| 413 |
+
soft = None if benign else near[rank]
|
| 414 |
+
return dict(seed=int(seed), mat=[mx, my], cup=cup, start=start, yaw=yaw, cup_yaw=float(rng.uniform(-np.pi, np.pi)),
|
| 415 |
+
soft=soft, soft_colour=COL[soft] if soft else None, benign=bool(benign),
|
| 416 |
+
soft_rank_nearest=rank, nearest_order=[COL[b] for b in near],
|
| 417 |
+
buckle_dir=float(np.pi / 2 if rng.random() < 0.5 else -np.pi / 2),
|
| 418 |
+
f_crit=F_CRIT, naive_gap=float(rng.uniform(*NAIVE_GAP)), naive_bias=float(rng.uniform(*NAIVE_BIAS)))
|
| 419 |
+
|
| 420 |
+
def apply_instance(self, inst):
|
| 421 |
+
self.inst = inst
|
| 422 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 423 |
+
m.body_pos[self.mat_bid] = [inst["mat"][0], inst["mat"][1], TZ + 0.0005]
|
| 424 |
+
for b in BOXES:
|
| 425 |
+
j = self.jid[b]
|
| 426 |
+
soft = b == inst["soft"]
|
| 427 |
+
M = SOFT_MASS if soft else BOX_MASS
|
| 428 |
+
for bid, frac, h in ((self.base_bid[b], HB / H, HB), (self.upper_bid[b], HU / H, HU)):
|
| 429 |
+
mm = M * frac
|
| 430 |
+
m.body_mass[bid] = mm
|
| 431 |
+
m.body_inertia[bid] = [mm * (4 * HY * HY + h * h) / 12, mm * (4 * HX * HX + h * h) / 12,
|
| 432 |
+
mm * (4 * HX * HX + 4 * HY * HY) / 12]
|
| 433 |
+
m.jnt_range[j] = [0.0, RANGE_SOFT if soft else RANGE_RIGID]
|
| 434 |
+
m.jnt_solref[j] = [0.02, 1.0] if soft else [0.004, 1.0] # rigid boxes: a stiff limit
|
| 435 |
+
m.jnt_stiffness[j] = K_HI if soft else K_RIGID
|
| 436 |
+
qa, da = int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j])
|
| 437 |
+
m.qpos_spring[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0]
|
| 438 |
+
d.qpos[qa:qa + 4] = [1.0, 0.0, 0.0, 0.0]
|
| 439 |
+
d.qvel[da:da + 3] = 0.0
|
| 440 |
+
self._set_crush(b, 0.0, 2, -1.0) # undo a crush left over from the previous attempt
|
| 441 |
+
place(self.env, b, inst["start"][b], yaw=inst["yaw"][b], tilt=inst.get("lying", {}).get(COL[b]))
|
| 442 |
+
place(self.env, CUP, inst["cup"], yaw=inst["cup_yaw"])
|
| 443 |
+
self.law = None
|
| 444 |
+
if inst["soft"]:
|
| 445 |
+
self.law = dict(box=inst["soft"], f=0.0, fmax=0.0, buckled=False, n=0, rel_t=0.0, t=0.0, buckles=[],
|
| 446 |
+
f_crit=float(inst.get("f_crit", F_CRIT)), dir=float(inst["buckle_dir"]),
|
| 447 |
+
mode=str(inst.get("law", "threshold")), how=None, crush=0.0, crush_set=0.0,
|
| 448 |
+
crush_axis=2, crush_sign=-1.0, f_rest=0.0, f_robot=0.0)
|
| 449 |
+
if self.law["mode"] == "linear": # control only: the brief's fixed-stiffness spring (no load threshold)
|
| 450 |
+
m.jnt_stiffness[self.jid[inst["soft"]]] = float(inst["k_lin"])
|
| 451 |
+
|
| 452 |
+
def reset_instance(self, inst, recorder=None):
|
| 453 |
+
self.mon = None
|
| 454 |
+
self.law = None
|
| 455 |
+
self.env.reset()
|
| 456 |
+
self.apply_instance(inst)
|
| 457 |
+
self.env.sim.forward()
|
| 458 |
+
envs.settle(self.env, 15)
|
| 459 |
+
self.sk = StackSkills(self.env, self, recorder=recorder)
|
| 460 |
+
self._sub_rob = {}
|
| 461 |
+
self._held = set()
|
| 462 |
+
self._rest_cap = np.inf
|
| 463 |
+
self._init_monitor()
|
| 464 |
+
return self.sk
|
| 465 |
+
|
| 466 |
+
# ------------------------------------------------------------ soft-carton law
|
| 467 |
+
def _part_axial(self, gid, axis):
|
| 468 |
+
"""sum of contact forces on geom gid (from any other geom), projected on `axis` (world)"""
|
| 469 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 470 |
+
n = d.ncon
|
| 471 |
+
if not n:
|
| 472 |
+
return 0.0
|
| 473 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 474 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 475 |
+
idx = np.nonzero((g1 == gid) | (g2 == gid))[0]
|
| 476 |
+
tot = 0.0
|
| 477 |
+
f6 = np.zeros(6)
|
| 478 |
+
for i in idx:
|
| 479 |
+
mujoco.mj_contactForce(m._model, d._data, int(i), f6)
|
| 480 |
+
fw = d.contact[int(i)].frame.reshape(3, 3).T @ f6[:3] # force on geom2, world frame
|
| 481 |
+
tot += float(fw @ axis) * (-1.0 if g1[i] == gid else 1.0)
|
| 482 |
+
return tot
|
| 483 |
+
|
| 484 |
+
def vertical_loads(self, b):
|
| 485 |
+
"""vertical contact forces on box b (N), whichever face it rests on: (resting, robot, held, support).
|
| 486 |
+
resting = downward push on its upper side (contact point above its centre) from things resting on it;
|
| 487 |
+
robot = the same from the robot's own fingers / hand pushing on it (not counted while the robot holds b
|
| 488 |
+
itself); held = the same from something the robot holds (pressing it down onto b); support = upward push on
|
| 489 |
+
its lower side. Its two halves never touch (parent and child), so only real contacts count."""
|
| 490 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 491 |
+
n = d.ncon
|
| 492 |
+
if not n:
|
| 493 |
+
return 0.0, 0.0, 0.0, 0.0
|
| 494 |
+
gb, gu = self.base_gid[b], self.upper_gid[b]
|
| 495 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 496 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 497 |
+
idx = np.nonzero((g1 == gb) | (g1 == gu) | (g2 == gb) | (g2 == gu))[0]
|
| 498 |
+
if not len(idx):
|
| 499 |
+
return 0.0, 0.0, 0.0, 0.0
|
| 500 |
+
cz = float(d.xpos[self.base_bid[b]][2]) # the root body sits at the box's centre
|
| 501 |
+
held = self._held
|
| 502 |
+
b_held = BOXES.index(b) in held
|
| 503 |
+
rest = robot = via = sup = 0.0
|
| 504 |
+
f6 = np.zeros(6)
|
| 505 |
+
for i in idx:
|
| 506 |
+
c = d.contact[int(i)]
|
| 507 |
+
mujoco.mj_contactForce(m._model, d._data, int(i), f6)
|
| 508 |
+
fz = float(c.frame.reshape(3, 3)[:, 2] @ f6[:3]) # world z of the force on geom2
|
| 509 |
+
mine1 = g1[i] in (gb, gu)
|
| 510 |
+
fz = -fz if mine1 else fz # force on box b
|
| 511 |
+
other = int(g2[i] if mine1 else g1[i])
|
| 512 |
+
pz = float(c.pos[2])
|
| 513 |
+
if pz > cz + 0.004 and fz < 0.0:
|
| 514 |
+
o = self.owner[other]
|
| 515 |
+
if self.part[other] > 0:
|
| 516 |
+
if not b_held:
|
| 517 |
+
robot -= fz
|
| 518 |
+
elif o >= 0 and o in held:
|
| 519 |
+
via -= fz
|
| 520 |
+
else:
|
| 521 |
+
rest -= fz
|
| 522 |
+
elif pz < cz - 0.004 and fz > 0.0:
|
| 523 |
+
sup += fz
|
| 524 |
+
# what rests on it pushes at most with its own weight: the robot pressing down through an item it has let go
|
| 525 |
+
# of (Sonnet releases with the cup pushed up against the hand, pilot s3003) is not a resting load
|
| 526 |
+
rest = min(rest, self._rest_cap)
|
| 527 |
+
return rest, robot, via, sup
|
| 528 |
+
|
| 529 |
+
def compression(self, b):
|
| 530 |
+
"""compressive force (N) on the carton, (total, resting): the downward push on its upper side from things
|
| 531 |
+
resting on it plus the robot's fingers / hand pushing directly on it, limited by the support under it --
|
| 532 |
+
along the world vertical, whichever face it rests on (v1 measured it along the box axis only: a carton lying
|
| 533 |
+
on its side never buckled). Something the robot still holds does not count: Sonnet presses what it puts down
|
| 534 |
+
0.5-1.5 cm below contact (pilot), which must not crush a carton that will carry the item once let go."""
|
| 535 |
+
rest, robot, via, sup = self.vertical_loads(b)
|
| 536 |
+
return float(min(rest + robot, sup)), float(min(rest, sup))
|
| 537 |
+
|
| 538 |
+
def _law_step(self):
|
| 539 |
+
"""per MuJoCo substep: low-pass the compressive load; above f_crit the carton gives way -- standing or upside
|
| 540 |
+
down it folds (its kink joint loses its stiffness, its rest shape bends towards its weak side and the load
|
| 541 |
+
topples it), lying on a side face it is crushed (both halves flatten, the upper half more); unloaded for
|
| 542 |
+
REL_T it slowly recovers its shape"""
|
| 543 |
+
law = self.law
|
| 544 |
+
b = law["box"]
|
| 545 |
+
m = self.env.sim.model
|
| 546 |
+
dt = float(m.opt.timestep)
|
| 547 |
+
tot, rest = self.compression(b)
|
| 548 |
+
law["f"] += (tot - law["f"]) * dt / TAU_F
|
| 549 |
+
law["f_rest"] += (rest - law["f_rest"]) * dt / TAU_F
|
| 550 |
+
law["fmax"] = max(law["fmax"], law["f"])
|
| 551 |
+
j = self.jid[b]
|
| 552 |
+
qa = int(m.jnt_qposadr[j])
|
| 553 |
+
if law["mode"] == "linear": # control: constant stiffness; a "buckle" = the kink passes 15 deg (re-arms < 5)
|
| 554 |
+
kk = self.kink(b)
|
| 555 |
+
if not law["buckled"] and kk > np.radians(15.0):
|
| 556 |
+
law["buckled"] = True
|
| 557 |
+
law["n"] += 1
|
| 558 |
+
law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2)))
|
| 559 |
+
self._on_buckle()
|
| 560 |
+
elif law["buckled"] and kk < np.radians(5.0):
|
| 561 |
+
law["buckled"] = False
|
| 562 |
+
law["t"] += dt
|
| 563 |
+
return
|
| 564 |
+
if not law["buckled"]:
|
| 565 |
+
if law["f"] > law["f_crit"]:
|
| 566 |
+
law["buckled"] = True
|
| 567 |
+
law["n"] += 1
|
| 568 |
+
law["rel_t"] = 0.0
|
| 569 |
+
R = self.env.sim.data.xmat[self.base_bid[b]].reshape(3, 3)
|
| 570 |
+
law["unbend_q0"] = None
|
| 571 |
+
if abs(R[2, 2]) >= FOLD_MIN_UP: # seam horizontal: fold
|
| 572 |
+
law["how"] = "fold"
|
| 573 |
+
u = R.T @ np.array([np.cos(law["dir"]), np.sin(law["dir"]), 0.0])
|
| 574 |
+
ax = np.array([-u[1], u[0], 0.0])
|
| 575 |
+
ax /= max(np.linalg.norm(ax), 1e-9)
|
| 576 |
+
m.qpos_spring[qa:qa + 4] = [np.cos(BEND_REF / 2), *(np.sin(BEND_REF / 2) * ax)]
|
| 577 |
+
else: # seam vertical (lying on a side face): crush towards the face it rests on
|
| 578 |
+
law["how"] = "crush"
|
| 579 |
+
k = int(np.argmax(np.abs(R[2, :2])))
|
| 580 |
+
law["crush_axis"] = k
|
| 581 |
+
law["crush_sign"] = -float(np.sign(R[2, k]) or 1.0) # local direction of "down" along axis k
|
| 582 |
+
# cause: "load" = what rests on it is enough by itself (>= 60 % of f_crit, i.e. more than one item);
|
| 583 |
+
# "press" = the robot's own push made the difference (a hard press with the gripper)
|
| 584 |
+
cause = "load" if law["f_rest"] >= 0.6 * law["f_crit"] else "press"
|
| 585 |
+
law["buckles"].append(dict(t=round(law["t"], 3), load_N=round(law["f"], 2), how=law["how"],
|
| 586 |
+
resting_N=round(law["f_rest"], 2), cause=cause))
|
| 587 |
+
self._on_buckle()
|
| 588 |
+
elif law["f"] < F_REL:
|
| 589 |
+
law["rel_t"] += dt
|
| 590 |
+
if law["rel_t"] > REL_T:
|
| 591 |
+
law["buckled"] = False
|
| 592 |
+
# straighten smoothly: the rest shape starts at the current bend and moves back to straight over
|
| 593 |
+
# K_RISE (a stiff spring released at once from a 40-50 deg bend flips the light carton over)
|
| 594 |
+
q0 = np.array(self.env.sim.data.qpos[qa:qa + 4], float)
|
| 595 |
+
q0 = q0 / max(np.linalg.norm(q0), 1e-9) * (1.0 if q0[0] >= 0 else -1.0)
|
| 596 |
+
law["unbend_q0"], law["unbend_s"] = q0.tolist(), 0.0
|
| 597 |
+
m.qpos_spring[qa:qa + 4] = q0
|
| 598 |
+
else:
|
| 599 |
+
law["rel_t"] = 0.0
|
| 600 |
+
k = float(m.jnt_stiffness[j])
|
| 601 |
+
if law["buckled"] and law["how"] == "fold":
|
| 602 |
+
m.jnt_stiffness[j] = k + (K_LO - k) * min(1.0, dt / 0.02)
|
| 603 |
+
else:
|
| 604 |
+
m.jnt_stiffness[j] = K_HI
|
| 605 |
+
if law.get("unbend_q0") is not None:
|
| 606 |
+
law["unbend_s"] = min(1.0, law["unbend_s"] + dt / K_RISE)
|
| 607 |
+
q = (1.0 - law["unbend_s"]) * np.asarray(law["unbend_q0"]) + law["unbend_s"] * np.array([1.0, 0, 0, 0])
|
| 608 |
+
m.qpos_spring[qa:qa + 4] = q / np.linalg.norm(q)
|
| 609 |
+
if law["unbend_s"] >= 1.0:
|
| 610 |
+
law["unbend_q0"] = None
|
| 611 |
+
target = 1.0 if (law["buckled"] and law["how"] == "crush") else 0.0
|
| 612 |
+
if target or law["crush"] > 0.0:
|
| 613 |
+
tau = CRUSH_TAU[0] if target else CRUSH_TAU[1]
|
| 614 |
+
law["crush"] += (target - law["crush"]) * min(1.0, dt / tau)
|
| 615 |
+
if not target and law["crush"] < 0.002:
|
| 616 |
+
law["crush"] = 0.0
|
| 617 |
+
if abs(law["crush"] - law["crush_set"]) > 0.004 or (law["crush"] == 0.0 and law["crush_set"] > 0.0):
|
| 618 |
+
self._set_crush(b, law["crush"], law["crush_axis"], law["crush_sign"])
|
| 619 |
+
law["crush_set"] = law["crush"]
|
| 620 |
+
law["t"] += dt
|
| 621 |
+
|
| 622 |
+
def _set_crush(self, b, c, axis, sign):
|
| 623 |
+
"""flatten box b's two halves along their local `axis` by c (0..1) x CRUSH_ALPHA, keeping the faces on the
|
| 624 |
+
`sign` side (the side facing down) in place; then refresh the collision bounds"""
|
| 625 |
+
m = self.env.sim.model
|
| 626 |
+
for (bid, gs, size0, pos0), alpha in zip(self.half_geoms[b], CRUSH_ALPHA):
|
| 627 |
+
size, pos = size0.copy(), pos0.copy()
|
| 628 |
+
if c > 0.0:
|
| 629 |
+
s0 = size0[:, axis]
|
| 630 |
+
s1 = s0 * (1.0 - alpha * c)
|
| 631 |
+
size[:, axis] = s1
|
| 632 |
+
pos[:, axis] = pos0[:, axis] + sign * (s0 - s1)
|
| 633 |
+
m.geom_size[gs] = size
|
| 634 |
+
m.geom_pos[gs] = pos
|
| 635 |
+
envs.refit_bounds(m, [self.half_geoms[b][0][0], self.half_geoms[b][1][0]])
|
| 636 |
+
|
| 637 |
+
def _on_buckle(self):
|
| 638 |
+
mon = self.mon
|
| 639 |
+
if mon is None:
|
| 640 |
+
return
|
| 641 |
+
b = self.law["box"]
|
| 642 |
+
ch = self.pile()
|
| 643 |
+
on = self.items_on(b)
|
| 644 |
+
last = self.law["buckles"][-1] if self.law["buckles"] else {}
|
| 645 |
+
e = dict(event="buckle", box=COL[b], step=int(self.sk.n_steps) if self.sk else 0,
|
| 646 |
+
load_N=round(self.law["f"], 2), level=(ch.index(b) + 1) if b in ch else None,
|
| 647 |
+
items_on=[COL.get(x, "cup") for x in on], how=last.get("how"), cause=last.get("cause"),
|
| 648 |
+
resting_N=last.get("resting_N"),
|
| 649 |
+
lying=bool(abs(self.R(self.base_bid[b])[2, 2]) < FOLD_MIN_UP))
|
| 650 |
+
mon["events"].append(e)
|
| 651 |
+
mon["buckle_steps"].append(e["step"])
|
| 652 |
+
mon["pending_collapse"] = dict(step=e["step"], pile=list(ch), cup=self.cup_on_pile(ch))
|
| 653 |
+
|
| 654 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 655 |
+
def R(self, bid):
|
| 656 |
+
return self.env.sim.data.xmat[bid].reshape(3, 3)
|
| 657 |
+
|
| 658 |
+
def centre(self, name):
|
| 659 |
+
return envs.obj_pos(self.env, name)
|
| 660 |
+
|
| 661 |
+
def flat_tilt(self, b):
|
| 662 |
+
"""angle (rad) between world vertical and the base part's axis closest to it (a box may lie on any face)"""
|
| 663 |
+
R = self.R(self.base_bid[b])
|
| 664 |
+
return float(np.arccos(np.clip(np.max(np.abs(R[2, :])), -1.0, 1.0)))
|
| 665 |
+
|
| 666 |
+
def kink(self, b):
|
| 667 |
+
"""bend of the upper part against the base part (rad)"""
|
| 668 |
+
zb = self.R(self.base_bid[b])[:, 2]
|
| 669 |
+
zu = self.R(self.upper_bid[b])[:, 2]
|
| 670 |
+
return float(np.arccos(np.clip(zb @ zu, -1.0, 1.0)))
|
| 671 |
+
|
| 672 |
+
def cup_tilt(self):
|
| 673 |
+
return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, CUP), -1.0, 1.0)))
|
| 674 |
+
|
| 675 |
+
def held(self, name):
|
| 676 |
+
return self.sk is not None and self.sk.holding(name)
|
| 677 |
+
|
| 678 |
+
def crushed(self, b):
|
| 679 |
+
"""how far box b is crushed (0..1; only the soft carton, lying on a side face, can be)"""
|
| 680 |
+
law = self.law
|
| 681 |
+
return float(law["crush"]) if (law is not None and law["box"] == b) else 0.0
|
| 682 |
+
|
| 683 |
+
def flat(self, b):
|
| 684 |
+
return (self.flat_tilt(b) <= TILT_OK and self.kink(b) <= KINK_OK and self.crushed(b) <= 0.15
|
| 685 |
+
and not self.held(b))
|
| 686 |
+
|
| 687 |
+
def rests_on(self, upper, lower):
|
| 688 |
+
cu, cl = self.centre(upper), self.centre(lower)
|
| 689 |
+
return (np.linalg.norm(cu[:2] - cl[:2]) <= STACK_XY
|
| 690 |
+
and abs(envs.obj_min_z(self.env, upper) - envs.obj_max_z(self.env, lower)) <= STACK_Z)
|
| 691 |
+
|
| 692 |
+
def on_mat(self, b):
|
| 693 |
+
off = self.centre(b)[:2] - np.asarray(self.inst["mat"])
|
| 694 |
+
return bool(np.all(np.abs(off) <= ON_MAT) and envs.obj_min_z(self.env, b) <= TZ + 0.008)
|
| 695 |
+
|
| 696 |
+
def pile(self):
|
| 697 |
+
"""the longest chain of flat boxes: the bottom one on the mat, each next resting on the previous (centres within
|
| 698 |
+
2 cm, faces within 1 cm)"""
|
| 699 |
+
flat = [b for b in BOXES if self.flat(b)]
|
| 700 |
+
best = []
|
| 701 |
+
for b0 in [b for b in flat if self.on_mat(b)]:
|
| 702 |
+
ch = [b0]
|
| 703 |
+
while True:
|
| 704 |
+
nxt = [b for b in flat if b not in ch and self.rests_on(b, ch[-1])]
|
| 705 |
+
if not nxt:
|
| 706 |
+
break
|
| 707 |
+
ch.append(min(nxt, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - self.centre(ch[-1])[:2]))))
|
| 708 |
+
if len(ch) > len(best):
|
| 709 |
+
best = ch
|
| 710 |
+
return best
|
| 711 |
+
|
| 712 |
+
def cup_on(self, b):
|
| 713 |
+
c = self.centre(CUP)
|
| 714 |
+
return bool(self.cup_tilt() <= TILT_OK and not self.held(CUP)
|
| 715 |
+
and np.linalg.norm(c[:2] - self.centre(b)[:2]) <= CUP_XY
|
| 716 |
+
and abs(envs.obj_min_z(self.env, CUP) - envs.obj_max_z(self.env, b)) <= STACK_Z)
|
| 717 |
+
|
| 718 |
+
def cup_on_pile(self, ch=None):
|
| 719 |
+
ch = self.pile() if ch is None else ch
|
| 720 |
+
return bool(len(ch) == len(BOXES) and self.cup_on(ch[-1]))
|
| 721 |
+
|
| 722 |
+
def items_on(self, b):
|
| 723 |
+
"""boxes / cup resting (directly or higher up) on box b, by height and overlap"""
|
| 724 |
+
cb = self.centre(b)
|
| 725 |
+
top = envs.obj_max_z(self.env, b)
|
| 726 |
+
out = []
|
| 727 |
+
for x in BOXES + [CUP]:
|
| 728 |
+
if x == b:
|
| 729 |
+
continue
|
| 730 |
+
c = self.centre(x)
|
| 731 |
+
if envs.obj_min_z(self.env, x) > top - 0.015 and np.linalg.norm(c[:2] - cb[:2]) < 0.06:
|
| 732 |
+
out.append(x)
|
| 733 |
+
return out
|
| 734 |
+
|
| 735 |
+
def stage_values(self):
|
| 736 |
+
ch = self.pile()
|
| 737 |
+
v = {COL[b]: b in ch for b in BOXES}
|
| 738 |
+
v["cup"] = self.cup_on_pile(ch)
|
| 739 |
+
return v, ch
|
| 740 |
+
|
| 741 |
+
# ------------------------------------------------------------ monitor
|
| 742 |
+
def _init_monitor(self):
|
| 743 |
+
keys = COLOURS + ["cup"]
|
| 744 |
+
self.mon = dict(state={k: False for k in keys}, cand={k: 0 for k in keys}, ever={k: False for k in keys},
|
| 745 |
+
lost={k: False for k in keys}, lost_cause={k: None for k in keys}, events=[], n=0,
|
| 746 |
+
last_robot={k: -10 ** 6 for k in keys}, buckle_steps=[], pending_collapse=None,
|
| 747 |
+
max_kink={COL[b]: 0.0 for b in BOXES}, max_crush={COL[b]: 0.0 for b in BOXES},
|
| 748 |
+
max_height=0, n_collapses=0,
|
| 749 |
+
law=self.law) # the carton's law state rides along in the robot server's regression snapshots
|
| 750 |
+
|
| 751 |
+
def _substep(self):
|
| 752 |
+
d = self.env.sim.data
|
| 753 |
+
n = d.ncon
|
| 754 |
+
if not n:
|
| 755 |
+
return
|
| 756 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 757 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 758 |
+
o1, o2 = self.owner[g1], self.owner[g2]
|
| 759 |
+
p1, p2 = self.part[g1], self.part[g2]
|
| 760 |
+
sel = ((o1 >= 0) & (p2 > 0)) | ((o2 >= 0) & (p1 > 0))
|
| 761 |
+
for i in np.nonzero(sel)[0]:
|
| 762 |
+
o = o1[i] if o1[i] >= 0 else o2[i]
|
| 763 |
+
self._sub_rob[int(o)] = True
|
| 764 |
+
|
| 765 |
+
def monitor_step(self):
|
| 766 |
+
mon = self.mon
|
| 767 |
+
if mon is None or self.sk is None:
|
| 768 |
+
return
|
| 769 |
+
mon["n"] += 1
|
| 770 |
+
t = int(self.sk.n_steps)
|
| 771 |
+
self._held = {i for i, x in enumerate(BOXES + [CUP]) if self.held(x)}
|
| 772 |
+
if self.law is not None: # weight of the things (not held) on the soft carton, + 0.3 N for impacts
|
| 773 |
+
m = self.env.sim.model
|
| 774 |
+
self._rest_cap = 0.3 + G * sum(float(np.sum(m.body_mass[self.obj_bodies[x]]))
|
| 775 |
+
for x in self.items_on(self.law["box"])
|
| 776 |
+
if (BOXES + [CUP]).index(x) not in self._held)
|
| 777 |
+
keys = COLOURS + ["cup"]
|
| 778 |
+
for i in list(self._sub_rob):
|
| 779 |
+
mon["last_robot"][keys[i]] = t
|
| 780 |
+
self._sub_rob = {}
|
| 781 |
+
for b in BOXES:
|
| 782 |
+
mon["max_kink"][COL[b]] = max(mon["max_kink"][COL[b]], round(float(np.degrees(self.kink(b))), 1))
|
| 783 |
+
mon["max_crush"][COL[b]] = max(mon["max_crush"][COL[b]], round(self.crushed(b), 2))
|
| 784 |
+
if mon["n"] % 2:
|
| 785 |
+
return
|
| 786 |
+
vals, ch = self.stage_values()
|
| 787 |
+
mon["max_height"] = max(mon["max_height"], len(ch))
|
| 788 |
+
for k in keys:
|
| 789 |
+
raw = vals[k]
|
| 790 |
+
if raw == mon["state"][k]:
|
| 791 |
+
mon["cand"][k] = 0
|
| 792 |
+
continue
|
| 793 |
+
mon["cand"][k] += 2
|
| 794 |
+
if mon["cand"][k] < DEBOUNCE:
|
| 795 |
+
continue
|
| 796 |
+
mon["cand"][k] = 0
|
| 797 |
+
mon["state"][k] = raw
|
| 798 |
+
t0 = t - DEBOUNCE + 1
|
| 799 |
+
if raw:
|
| 800 |
+
restored = mon["lost"][k]
|
| 801 |
+
e = dict(stage=k, event="restored" if restored else "achieved", step=t0)
|
| 802 |
+
if restored:
|
| 803 |
+
e["after"] = mon["lost_cause"][k]
|
| 804 |
+
mon["lost"][k] = False
|
| 805 |
+
mon["ever"][k] = True
|
| 806 |
+
mon["events"].append(e)
|
| 807 |
+
elif mon["ever"][k]:
|
| 808 |
+
cause = self._cause(k, t)
|
| 809 |
+
mon["lost"][k] = True
|
| 810 |
+
mon["lost_cause"][k] = cause
|
| 811 |
+
mon["events"].append(dict(stage=k, event="lost", step=t0, cause=cause))
|
| 812 |
+
pc = mon["pending_collapse"]
|
| 813 |
+
if cause == "buckle" and pc is not None and not pc.get("counted"):
|
| 814 |
+
pc["counted"] = True
|
| 815 |
+
mon["n_collapses"] += 1
|
| 816 |
+
mon["events"].append(dict(event="collapse", step=t0, buckled=self.inst["soft_colour"],
|
| 817 |
+
pile_before=[COL[b] for b in pc["pile"]]))
|
| 818 |
+
|
| 819 |
+
def _cause(self, k, t):
|
| 820 |
+
name = CUP if k == "cup" else BOXES[COLOURS.index(k)]
|
| 821 |
+
if self.held(name):
|
| 822 |
+
return "picked_up"
|
| 823 |
+
bs = self.mon["buckle_steps"]
|
| 824 |
+
if bs and t - bs[-1] <= 80: # within 4 s of a buckle
|
| 825 |
+
return "buckle"
|
| 826 |
+
if t - self.mon["last_robot"][k] <= 30:
|
| 827 |
+
return "robot"
|
| 828 |
+
return "other"
|
| 829 |
+
|
| 830 |
+
def _finalize_monitor(self, vals):
|
| 831 |
+
mon = self.mon
|
| 832 |
+
t = int(self.sk.n_steps)
|
| 833 |
+
for k, raw in vals.items():
|
| 834 |
+
if raw == mon["state"][k]:
|
| 835 |
+
continue
|
| 836 |
+
mon["state"][k] = raw
|
| 837 |
+
if raw:
|
| 838 |
+
restored = mon["lost"][k]
|
| 839 |
+
e = dict(stage=k, event="restored" if restored else "achieved", step=t, final=True)
|
| 840 |
+
if restored:
|
| 841 |
+
e["after"] = mon["lost_cause"][k]
|
| 842 |
+
mon["lost"][k] = False
|
| 843 |
+
mon["ever"][k] = True
|
| 844 |
+
mon["events"].append(e)
|
| 845 |
+
elif mon["ever"][k]:
|
| 846 |
+
cause = self._cause(k, t)
|
| 847 |
+
mon["lost"][k] = True
|
| 848 |
+
mon["lost_cause"][k] = cause
|
| 849 |
+
mon["events"].append(dict(stage=k, event="lost", step=t, cause=cause, final=True))
|
| 850 |
+
|
| 851 |
+
# ------------------------------------------------------------ outcome
|
| 852 |
+
def _touching(self):
|
| 853 |
+
d = self.env.sim.data
|
| 854 |
+
n = d.ncon
|
| 855 |
+
if not n:
|
| 856 |
+
return False
|
| 857 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 858 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 859 |
+
return bool(np.any(((self.owner[g1] >= 0) & (self.part[g2] > 0)) | ((self.owner[g2] >= 0) & (self.part[g1] > 0))))
|
| 860 |
+
|
| 861 |
+
def _static_pos(self):
|
| 862 |
+
return {x: self.centre(x).copy() for x in BOXES + [CUP]}
|
| 863 |
+
|
| 864 |
+
def outcome(self, inst):
|
| 865 |
+
sk = self.sk
|
| 866 |
+
sk.hold(10)
|
| 867 |
+
p0 = self._static_pos()
|
| 868 |
+
touching = False
|
| 869 |
+
for _ in range(20):
|
| 870 |
+
sk.hold(1)
|
| 871 |
+
touching = touching or self._touching()
|
| 872 |
+
moved = max(float(np.linalg.norm(self.centre(x) - p0[x])) for x in p0)
|
| 873 |
+
static = moved < 0.003
|
| 874 |
+
vals, ch = self.stage_values()
|
| 875 |
+
self._finalize_monitor(vals)
|
| 876 |
+
mon = self.mon
|
| 877 |
+
ev = list(mon["events"])
|
| 878 |
+
held = [COL.get(x, "cup") for x in BOXES + [CUP] if self.held(x)]
|
| 879 |
+
success = bool(all(vals.values()) and static and not held and not touching)
|
| 880 |
+
buckles = [e for e in ev if e.get("event") == "buckle"]
|
| 881 |
+
n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
|
| 882 |
+
n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
|
| 883 |
+
soft = inst["soft"]
|
| 884 |
+
buckled_now = bool(self.law is not None and self.law["buckled"])
|
| 885 |
+
cup_fallen = self.cup_tilt() > np.radians(45)
|
| 886 |
+
if success:
|
| 887 |
+
failure = "none"
|
| 888 |
+
elif held:
|
| 889 |
+
failure = "held"
|
| 890 |
+
elif touching and all(vals.values()):
|
| 891 |
+
failure = "touching"
|
| 892 |
+
elif not all(vals[c] for c in COLOURS):
|
| 893 |
+
if buckles and any(mon["ever"][c] for c in COLOURS):
|
| 894 |
+
failure = "collapsed"
|
| 895 |
+
elif any(mon["lost"][c] for c in COLOURS):
|
| 896 |
+
failure = "regressed"
|
| 897 |
+
else:
|
| 898 |
+
failure = "not_stacked"
|
| 899 |
+
elif not vals["cup"]:
|
| 900 |
+
failure = "cup_fallen" if cup_fallen else "cup_not_on_top"
|
| 901 |
+
else:
|
| 902 |
+
failure = "not_static"
|
| 903 |
+
# F2 detail (robot-centric words)
|
| 904 |
+
parts = []
|
| 905 |
+
if success:
|
| 906 |
+
parts.append("All four boxes are stacked on the mat and the cup stands on top.")
|
| 907 |
+
else:
|
| 908 |
+
if ch:
|
| 909 |
+
parts.append("The pile on the mat is " + " / ".join(COL[b] for b in ch) + " (bottom to top).")
|
| 910 |
+
else:
|
| 911 |
+
parts.append("There is no box resting flat on the mat.")
|
| 912 |
+
mat = np.asarray(inst["mat"])
|
| 913 |
+
for b in BOXES:
|
| 914 |
+
if b in ch:
|
| 915 |
+
continue
|
| 916 |
+
c = COL[b]
|
| 917 |
+
if self.held(b):
|
| 918 |
+
parts.append(f"The {c} box is still held by the gripper.")
|
| 919 |
+
continue
|
| 920 |
+
off = self.centre(b)[:2] - mat
|
| 921 |
+
pose = ("lies tilted" if self.flat_tilt(b) > TILT_OK else
|
| 922 |
+
"is crushed flat" if self.crushed(b) > 0.15 else
|
| 923 |
+
f"is bent ({np.degrees(self.kink(b)):.0f} degrees)" if self.kink(b) > KINK_OK else "stands")
|
| 924 |
+
parts.append(f"The {c} box {pose} {_fb(off[0])} and {_lr(off[1])} of the mat's centre, not in the pile.")
|
| 925 |
+
if not vals["cup"]:
|
| 926 |
+
if self.held(CUP):
|
| 927 |
+
parts.append("The cup is still held by the gripper.")
|
| 928 |
+
elif cup_fallen:
|
| 929 |
+
parts.append("The cup has fallen over.")
|
| 930 |
+
else:
|
| 931 |
+
parts.append("The cup is not standing on top of a complete pile.")
|
| 932 |
+
if all(vals.values()):
|
| 933 |
+
if touching:
|
| 934 |
+
parts.append("The gripper is still touching the pile.")
|
| 935 |
+
elif not static:
|
| 936 |
+
parts.append("Something was still moving.")
|
| 937 |
+
loads = [e for e in buckles if e.get("cause") != "press"]
|
| 938 |
+
presses = [e for e in buckles if e.get("cause") == "press"]
|
| 939 |
+
if loads:
|
| 940 |
+
how = ("bent sideways or was crushed" if len({e.get("how") for e in loads}) > 1 else
|
| 941 |
+
"was crushed flat" if loads[0].get("how") == "crush" else "bent sideways")
|
| 942 |
+
parts.append(f"During the attempt the {loads[0]['box']} box {how} under the weight on it "
|
| 943 |
+
f"{len(loads)} time(s) and everything above it slid off.")
|
| 944 |
+
if presses:
|
| 945 |
+
parts.append(f"The {presses[0]['box']} box gave way {len(presses)} time(s) when the gripper pushed down "
|
| 946 |
+
f"on it.")
|
| 947 |
+
# trap fired = the carton gave way under what was put on it (or a giving-way cost a stage); a hard press by the
|
| 948 |
+
# gripper alone on an otherwise lightly loaded carton is logged (n_press_buckles) but is not the trap
|
| 949 |
+
trap = bool(loads) or int(mon["n_collapses"]) > 0
|
| 950 |
+
return dict(success=success, failure=failure, stages=vals, pile=[COL[b] for b in ch], events=ev,
|
| 951 |
+
n_regressions=int(n_reg), n_restored=int(n_res), trap_fired=trap,
|
| 952 |
+
recovered_in_attempt=bool(trap and success), n_buckles=len(buckles),
|
| 953 |
+
n_collapses=int(mon["n_collapses"]), buckle_levels=[e.get("level") for e in buckles],
|
| 954 |
+
buckle_loads_N=[e.get("load_N") for e in buckles], max_kink_deg=dict(mon["max_kink"]),
|
| 955 |
+
max_crush=dict(mon["max_crush"]), buckle_how=[e.get("how") for e in buckles],
|
| 956 |
+
buckle_causes=[e.get("cause") for e in buckles], n_press_buckles=len(presses),
|
| 957 |
+
max_height=int(mon["max_height"]), soft=inst["soft_colour"], benign=bool(inst["benign"]),
|
| 958 |
+
buckled_at_end=buckled_now, cup_fallen=bool(cup_fallen), held=held, touching=bool(touching),
|
| 959 |
+
static=bool(static), detail=" ".join(parts))
|
| 960 |
+
|
| 961 |
+
# ------------------------------------------------------------ scripted primitives (move_to + gripper only)
|
| 962 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 963 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 964 |
+
|
| 965 |
+
def _lift_to(self, z, speed=0.2):
|
| 966 |
+
cur = self.sk.eef_pos()
|
| 967 |
+
if cur[2] < z - 0.005:
|
| 968 |
+
self._go([cur[0], cur[1], z], speed=speed)
|
| 969 |
+
|
| 970 |
+
def _settle(self, steps=40):
|
| 971 |
+
"""hold until boxes / cup have stopped (max `steps` control steps)"""
|
| 972 |
+
p = self._static_pos()
|
| 973 |
+
for _ in range(steps // 4):
|
| 974 |
+
self.sk.hold(4)
|
| 975 |
+
q = self._static_pos()
|
| 976 |
+
if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005:
|
| 977 |
+
return
|
| 978 |
+
p = q
|
| 979 |
+
|
| 980 |
+
def settle_scene(self, max_steps=120):
|
| 981 |
+
"""after a collapse: wait (looking) until nothing moves and no box is visibly bent any more"""
|
| 982 |
+
for _ in range(max_steps // 10):
|
| 983 |
+
self._settle(10)
|
| 984 |
+
if all(self.kink(b) < np.radians(3.0) for b in BOXES):
|
| 985 |
+
p = self._static_pos()
|
| 986 |
+
self.sk.hold(4)
|
| 987 |
+
q = self._static_pos()
|
| 988 |
+
if max(float(np.linalg.norm(q[x] - p[x])) for x in p) < 0.0005:
|
| 989 |
+
return
|
| 990 |
+
|
| 991 |
+
def grasp_yaw(self, name):
|
| 992 |
+
"""wrist yaw that closes the fingers across a horizontal box axis: of the two, the one whose open fingers stay
|
| 993 |
+
clearest of the other objects (a box that fell against another one), then the one needing the least turn"""
|
| 994 |
+
if name == CUP:
|
| 995 |
+
return 0.0
|
| 996 |
+
R = self.R(self.base_bid[name])
|
| 997 |
+
up = int(np.argmax(np.abs(R[2, :])))
|
| 998 |
+
c = self.centre(name)[:2]
|
| 999 |
+
others = [self.centre(x)[:2] for x in BOXES + [CUP] if x != name]
|
| 1000 |
+
best = None
|
| 1001 |
+
for a in range(3):
|
| 1002 |
+
if a == up:
|
| 1003 |
+
continue
|
| 1004 |
+
v = R[:2, a] / max(np.linalg.norm(R[:2, a]), 1e-9)
|
| 1005 |
+
yaw = _wrap_q(float(np.arctan2(v[1], v[0])) - np.pi / 2, np.pi) # fingers close along (-sin yaw, cos yaw)
|
| 1006 |
+
fingers = [c + s_ * 0.045 * v for s_ in (1.0, -1.0)] # open fingers ~4.5 cm from the centre
|
| 1007 |
+
clear = min([float(np.linalg.norm(f - o)) for f in fingers for o in others] + [1.0])
|
| 1008 |
+
key = (round(min(clear, 0.05), 3), -abs(yaw))
|
| 1009 |
+
if best is None or key > best[0]:
|
| 1010 |
+
best = (key, yaw)
|
| 1011 |
+
return best[1]
|
| 1012 |
+
|
| 1013 |
+
def z_clear(self, extra=0.08):
|
| 1014 |
+
"""carry height: above everything on the table"""
|
| 1015 |
+
top = max(envs.obj_max_z(self.env, x) for x in BOXES + [CUP])
|
| 1016 |
+
return max(TZ + Z_CARRY, top + extra)
|
| 1017 |
+
|
| 1018 |
+
def pick(self, name, depth=0.018, z_carry=None, tries=2):
|
| 1019 |
+
sk = self.sk
|
| 1020 |
+
for _ in range(tries):
|
| 1021 |
+
self._settle(20)
|
| 1022 |
+
p = self.centre(name)
|
| 1023 |
+
zt = envs.obj_max_z(self.env, name)
|
| 1024 |
+
yaw = self.grasp_yaw(name)
|
| 1025 |
+
sk.set_gripper(False, steps=10)
|
| 1026 |
+
zc = z_carry or self.z_clear()
|
| 1027 |
+
self._lift_to(zc)
|
| 1028 |
+
self._go([p[0], p[1], zc], yaw=yaw, speed=0.25)
|
| 1029 |
+
self._go([p[0], p[1], zt - depth + 0.02], speed=0.12)
|
| 1030 |
+
self._go([p[0], p[1], max(zt - depth, TZ + 0.012)], speed=0.04, tol=0.003, max_steps=150)
|
| 1031 |
+
sk.set_gripper(True, steps=15)
|
| 1032 |
+
self._go([p[0], p[1], self.z_clear(0.10)], speed=0.15)
|
| 1033 |
+
if self.held(name):
|
| 1034 |
+
return True
|
| 1035 |
+
sk.set_gripper(False, steps=10)
|
| 1036 |
+
return False
|
| 1037 |
+
|
| 1038 |
+
def put(self, name, xy, z_surface, gap, yaw=0.0):
|
| 1039 |
+
"""carry the held object over xy (its centre), straight down until its bottom is `gap` above z_surface, let
|
| 1040 |
+
go, lift 8 cm"""
|
| 1041 |
+
sk = self.sk
|
| 1042 |
+
zc = max(self.z_clear(0.10), sk.eef_pos()[2])
|
| 1043 |
+
rel = self.centre(name)[:2] - sk.eef_pos()[:2]
|
| 1044 |
+
q = np.asarray(xy, float) - rel
|
| 1045 |
+
self._go([q[0], q[1], zc], yaw=yaw, speed=0.25)
|
| 1046 |
+
sk.hold(5)
|
| 1047 |
+
rel = self.centre(name)[:2] - sk.eef_pos()[:2] # the object can shift in the fingers while the wrist turns
|
| 1048 |
+
q = np.asarray(xy, float) - rel
|
| 1049 |
+
dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, name)
|
| 1050 |
+
zr = z_surface + dz + gap
|
| 1051 |
+
self._go([q[0], q[1], zr + 0.03], speed=0.12)
|
| 1052 |
+
self._go([q[0], q[1], zr], speed=0.04, tol=0.003, max_steps=150)
|
| 1053 |
+
sk.set_gripper(False, steps=15)
|
| 1054 |
+
cur = sk.eef_pos()
|
| 1055 |
+
self._go([cur[0], cur[1], cur[2] + 0.08], speed=0.15)
|
| 1056 |
+
self._settle(40)
|
| 1057 |
+
|
| 1058 |
+
def free_spot(self, near_xy):
|
| 1059 |
+
"""a free place on the table (for a box taken off the pile): >= 11 cm from everything, off the mat, reachable"""
|
| 1060 |
+
mat = np.asarray(self.inst["mat"])
|
| 1061 |
+
others = [self.centre(x)[:2] for x in BOXES + [CUP]]
|
| 1062 |
+
best, bd = None, -1.0
|
| 1063 |
+
for r in (0.17, 0.21, 0.25, 0.29):
|
| 1064 |
+
for a in np.radians(np.arange(0, 360, 15)):
|
| 1065 |
+
p = mat + r * np.array([np.cos(a), np.sin(a)])
|
| 1066 |
+
if not (BOX_X[0] - 0.02 <= p[0] <= BOX_X[1] and abs(p[1]) <= BOX_YMAX + 0.02):
|
| 1067 |
+
continue
|
| 1068 |
+
d = min(float(np.linalg.norm(p - o)) for o in others)
|
| 1069 |
+
if d >= 0.11:
|
| 1070 |
+
return p
|
| 1071 |
+
if d > bd:
|
| 1072 |
+
best, bd = p, d
|
| 1073 |
+
return best
|
| 1074 |
+
|
| 1075 |
+
def place_on_pile(self, name, err, gap, rng, bias=0.0):
|
| 1076 |
+
"""put object `name` on the current pile top (or the mat) with a placement error of `err` (m, random direction)"""
|
| 1077 |
+
ch = [b for b in self.pile() if b != name]
|
| 1078 |
+
if ch:
|
| 1079 |
+
# aims every box at the same spot (the bottom box), as an agent that computes the pile's x, y once: errors
|
| 1080 |
+
# do not add up level by level
|
| 1081 |
+
tgt = self.centre(ch[0])[:2].copy()
|
| 1082 |
+
zs = envs.obj_max_z(self.env, ch[-1])
|
| 1083 |
+
else:
|
| 1084 |
+
tgt = np.asarray(self.inst["mat"], float) + np.array([bias, 0.0])
|
| 1085 |
+
zs = TZ
|
| 1086 |
+
if err:
|
| 1087 |
+
a = rng.uniform(0, 2 * np.pi)
|
| 1088 |
+
tgt = tgt + float(err) * np.array([np.cos(a), np.sin(a)])
|
| 1089 |
+
if not self.pick(name):
|
| 1090 |
+
return False
|
| 1091 |
+
self.put(name, tgt, zs, gap)
|
| 1092 |
+
return True
|
| 1093 |
+
|
| 1094 |
+
def lay_aside(self, name, rng):
|
| 1095 |
+
if not self.pick(name):
|
| 1096 |
+
return False
|
| 1097 |
+
p = self.free_spot(self.centre(name)[:2])
|
| 1098 |
+
self.put(name, p, TZ, 0.01)
|
| 1099 |
+
return True
|
| 1100 |
+
|
| 1101 |
+
# ------------------------------------------------------------ scripted policies
|
| 1102 |
+
def nearest_order(self):
|
| 1103 |
+
mat = np.asarray(self.inst["mat"])
|
| 1104 |
+
return sorted(BOXES, key=lambda b: float(np.linalg.norm(self.centre(b)[:2] - mat)))
|
| 1105 |
+
|
| 1106 |
+
def plan(self, params, rng):
|
| 1107 |
+
if params.get("order") == "random":
|
| 1108 |
+
order = [BOXES[i] for i in rng.permutation(4)]
|
| 1109 |
+
else:
|
| 1110 |
+
order = self.nearest_order()
|
| 1111 |
+
soft = params.get("soft_known")
|
| 1112 |
+
if soft:
|
| 1113 |
+
order = [b for b in order if COL[b] != soft] + [b for b in order if COL[b] == soft]
|
| 1114 |
+
return order
|
| 1115 |
+
|
| 1116 |
+
def seen_soft(self):
|
| 1117 |
+
"""the box that visibly bent during this attempt (scripted perception of the kink in the images)"""
|
| 1118 |
+
mk, mc = self.mon["max_kink"], self.mon["max_crush"]
|
| 1119 |
+
for c in COLOURS:
|
| 1120 |
+
if mk[c] > 15.0 or mc[c] > 0.3:
|
| 1121 |
+
return c
|
| 1122 |
+
return None
|
| 1123 |
+
|
| 1124 |
+
def build(self, order, params, rng, first=True):
|
| 1125 |
+
"""stack `order` (boxes not yet in the pile) then the cup; returns 'ok', 'collapse' or 'fail'"""
|
| 1126 |
+
err = params.get("err")
|
| 1127 |
+
gap = params.get("gap", 0.005)
|
| 1128 |
+
# a box that could not be picked up is tried again after the others (one more pass)
|
| 1129 |
+
order = list(order) * 2
|
| 1130 |
+
for b in order:
|
| 1131 |
+
if b in self.pile():
|
| 1132 |
+
continue
|
| 1133 |
+
if params.get("soft_known") and COL[b] == params["soft_known"] and \
|
| 1134 |
+
sum(x in self.pile() for x in BOXES if COL[x] != params["soft_known"]) < len(BOXES) - 1:
|
| 1135 |
+
continue # the soft box only goes on once the three others are in the pile
|
| 1136 |
+
for _ in range(2):
|
| 1137 |
+
n_b = len(self.mon["buckle_steps"])
|
| 1138 |
+
before = self.pile()
|
| 1139 |
+
e = rng.uniform(*err) if err else 0.0
|
| 1140 |
+
if not self.place_on_pile(b, e, gap, rng, bias=params.get("bias", 0.0) if not before else 0.0):
|
| 1141 |
+
break
|
| 1142 |
+
after = self.pile()
|
| 1143 |
+
if len(self.mon["buckle_steps"]) > n_b or any(x not in after for x in before):
|
| 1144 |
+
return "collapse"
|
| 1145 |
+
if b in after:
|
| 1146 |
+
break
|
| 1147 |
+
if len(self.pile()) < len(BOXES):
|
| 1148 |
+
return "fail"
|
| 1149 |
+
if self.cup_tilt() > np.radians(45):
|
| 1150 |
+
return "fail"
|
| 1151 |
+
for _ in range(2):
|
| 1152 |
+
n_b = len(self.mon["buckle_steps"])
|
| 1153 |
+
before = self.pile()
|
| 1154 |
+
e = rng.uniform(*err) if err else 0.0
|
| 1155 |
+
if not self.place_on_pile(CUP, e, gap, rng):
|
| 1156 |
+
return "fail"
|
| 1157 |
+
if len(self.mon["buckle_steps"]) > n_b or any(x not in self.pile() for x in before):
|
| 1158 |
+
return "collapse"
|
| 1159 |
+
if self.cup_on_pile():
|
| 1160 |
+
return "ok"
|
| 1161 |
+
return "fail"
|
| 1162 |
+
|
| 1163 |
+
def rebuild_soft_top(self, soft_colour, params, rng):
|
| 1164 |
+
"""take the soft box (and whatever is on it) off the pile, then stack the rigid boxes and the soft one last"""
|
| 1165 |
+
soft = BOXES[COLOURS.index(soft_colour)]
|
| 1166 |
+
for _ in range(6):
|
| 1167 |
+
ch = self.pile()
|
| 1168 |
+
if soft in ch:
|
| 1169 |
+
self.lay_aside(ch[-1], rng) # from the top down to the soft box
|
| 1170 |
+
elif self.on_mat(soft) or any(soft in self.items_on(b) for b in ch):
|
| 1171 |
+
self.lay_aside(soft, rng) # bent / off-centre on the mat or on the pile
|
| 1172 |
+
else:
|
| 1173 |
+
break
|
| 1174 |
+
order = [b for b in self.nearest_order() if b != soft] + [soft]
|
| 1175 |
+
return self.build(order, dict(params, soft_known=soft_colour), rng)
|
| 1176 |
+
|
| 1177 |
+
def execute(self, inst, params):
|
| 1178 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 1179 |
+
order = self.plan(params, rng)
|
| 1180 |
+
res = self.build(order, params, rng)
|
| 1181 |
+
if res == "collapse":
|
| 1182 |
+
mode = params.get("on_collapse", "rebuild_same")
|
| 1183 |
+
if mode == "rebuild_same": # the cheapest explanation: "I did not centre it" -> same order, more care
|
| 1184 |
+
self.settle_scene()
|
| 1185 |
+
res = self.build(order, dict(params, err=None, gap=0.005), rng)
|
| 1186 |
+
elif mode == "identify": # sees which box bent and rebuilds with it on top
|
| 1187 |
+
self.settle_scene()
|
| 1188 |
+
soft = self.seen_soft()
|
| 1189 |
+
if soft and self.cup_tilt() < np.radians(45):
|
| 1190 |
+
res = self.rebuild_soft_top(soft, params, rng)
|
| 1191 |
+
self._lift_to(self.z_clear(0.06))
|
| 1192 |
+
self.sk.hold(10)
|
| 1193 |
+
return res
|
| 1194 |
+
|
| 1195 |
+
NAIVE = dict(order="nearest", soft_known=None, on_collapse="rebuild_same")
|
| 1196 |
+
|
| 1197 |
+
def default_params(self, inst):
|
| 1198 |
+
"""Sonnet-like: nearest box first, lifts above everything, straight down, lets go 1-4 cm above (per instance),
|
| 1199 |
+
0.4-1.3 cm placement errors, the first box up to 2 cm too far forward; after a collapse it rebuilds once in
|
| 1200 |
+
the same order, more carefully"""
|
| 1201 |
+
return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, err=NAIVE_ERR, gap=float(inst["naive_gap"]),
|
| 1202 |
+
bias=float(inst["naive_bias"]))
|
| 1203 |
+
|
| 1204 |
+
def oracle_params(self, inst):
|
| 1205 |
+
return dict(order="nearest", soft_known=inst["soft_colour"], on_collapse="identify", err=None, gap=0.005)
|
| 1206 |
+
|
| 1207 |
+
def adapt_params(self, inst, history):
|
| 1208 |
+
soft = None
|
| 1209 |
+
for h in history:
|
| 1210 |
+
ev = [e for e in h["outcome"]["events"] if e.get("event") == "buckle"]
|
| 1211 |
+
if ev:
|
| 1212 |
+
soft = ev[0]["box"] # the box seen bending (the kink is visible in the images)
|
| 1213 |
+
return dict(self.default_params(inst), soft_known=soft, on_collapse="identify")
|
| 1214 |
+
|
| 1215 |
+
def blind_params(self, inst, attempt, rng):
|
| 1216 |
+
return dict(self.default_params(inst), order="random", noise_seed=int(rng.integers(1 << 30)),
|
| 1217 |
+
gap=float(rng.uniform(*NAIVE_GAP)), bias=float(rng.uniform(*NAIVE_BIAS)))
|
| 1218 |
+
|
| 1219 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 1220 |
+
k = k or self.max_attempts
|
| 1221 |
+
rng = np.random.default_rng(seed)
|
| 1222 |
+
history = []
|
| 1223 |
+
single = ("oracle", "naive", "naive_centred", "oracle_noise", "naive_once", "naive_lying", "oracle_lying")
|
| 1224 |
+
if kind in ("naive_lying", "oracle_lying") and inst["soft"]:
|
| 1225 |
+
# control (v2): the soft carton starts lying on a side face, so it is stacked lying
|
| 1226 |
+
inst = dict(inst, lying={inst["soft_colour"]: np.pi / 2})
|
| 1227 |
+
for a in range(k):
|
| 1228 |
+
self.reset_instance(inst)
|
| 1229 |
+
if kind == "oracle":
|
| 1230 |
+
params = self.oracle_params(inst)
|
| 1231 |
+
elif kind == "naive":
|
| 1232 |
+
params = self.default_params(inst)
|
| 1233 |
+
elif kind == "adaptive": # attempt 1: naive habits, but it looks at the collapse and rebuilds soft-on-top
|
| 1234 |
+
params = (dict(self.default_params(inst), on_collapse="identify") if a == 0
|
| 1235 |
+
else self.adapt_params(inst, history))
|
| 1236 |
+
elif kind == "blind":
|
| 1237 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 1238 |
+
elif kind == "switch": # control: cross-attempt learning only (no within-attempt identification)
|
| 1239 |
+
params = self.default_params(inst) if a == 0 else dict(self.adapt_params(inst, history),
|
| 1240 |
+
on_collapse="rebuild_same")
|
| 1241 |
+
elif kind == "naive_centred": # control (R4): perfect centring, let go 5 mm above, no rebuild
|
| 1242 |
+
params = dict(self.default_params(inst), err=None, gap=0.005, bias=0.0, on_collapse="none")
|
| 1243 |
+
elif kind == "naive_once": # control: naive without the careful rebuild
|
| 1244 |
+
params = dict(self.default_params(inst), on_collapse="none")
|
| 1245 |
+
elif kind == "naive_lying": # control (v2): naive_once with the soft carton lying on a side face
|
| 1246 |
+
params = dict(self.default_params(inst), on_collapse="none")
|
| 1247 |
+
elif kind == "oracle_lying": # control (v2): soft carton lying, but on top (carries only the cup)
|
| 1248 |
+
params = dict(self.oracle_params(inst))
|
| 1249 |
+
elif kind == "oracle_noise": # robustness: soft box on top with Sonnet-like imprecision
|
| 1250 |
+
params = dict(self.default_params(inst), soft_known=inst["soft_colour"], on_collapse="identify")
|
| 1251 |
+
else:
|
| 1252 |
+
raise ValueError(kind)
|
| 1253 |
+
self.execute(inst, params)
|
| 1254 |
+
out = self.outcome(inst)
|
| 1255 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1256 |
+
if on_attempt:
|
| 1257 |
+
on_attempt(a, params, out)
|
| 1258 |
+
if out["success"] or kind in single:
|
| 1259 |
+
break
|
| 1260 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/trace_gpt_html.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Render one GPT-player run as a self-contained HTML trace: the instructions and tool the model received,
|
| 2 |
+
every request's new content (text + images), the model's reasoning summaries and commands, every server
|
| 3 |
+
report, the server-side ground truth and the done verdicts. Optionally embeds the rollout video.
|
| 4 |
+
|
| 5 |
+
python scripts/trace_gpt_html.py --log runs/gpt/exp2/<run> --out traces/<name>.html [--title ...] [--video]
|
| 6 |
+
"""
|
| 7 |
+
import argparse
|
| 8 |
+
import base64
|
| 9 |
+
import html
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
from trace_html import CSS
|
| 14 |
+
|
| 15 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def esc(s):
|
| 19 |
+
return html.escape(str(s))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def img_tag(path):
|
| 23 |
+
if not os.path.exists(path):
|
| 24 |
+
return f"<span class='lbl'>[missing {esc(os.path.basename(path))}]</span>"
|
| 25 |
+
b = base64.b64encode(open(path, "rb").read()).decode()
|
| 26 |
+
return f"<img src='data:image/jpeg;base64,{b}' title='{esc(os.path.basename(path))}'>"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main():
|
| 30 |
+
ap = argparse.ArgumentParser()
|
| 31 |
+
ap.add_argument("--log", required=True)
|
| 32 |
+
ap.add_argument("--out", required=True)
|
| 33 |
+
ap.add_argument("--title", default="")
|
| 34 |
+
ap.add_argument("--video", action="store_true", help="embed rollout.mp4 (base64)")
|
| 35 |
+
a = ap.parse_args()
|
| 36 |
+
sess = json.load(open(os.path.join(a.log, "session.json")))
|
| 37 |
+
sb = sess["sandbox"]
|
| 38 |
+
tp = os.path.join(a.log, "transcript.jsonl") # api_player; older gpt_player runs: gpt_transcript.jsonl
|
| 39 |
+
tr = [json.loads(l) for l in open(tp if os.path.exists(tp) else os.path.join(a.log, "gpt_transcript.jsonl"))]
|
| 40 |
+
ev = [json.loads(l) for l in open(os.path.join(a.log, "events.jsonl"))]
|
| 41 |
+
start = next(e for e in ev if e["ev"] == "session_start")
|
| 42 |
+
dones = [e for e in ev if e["ev"] == "done"]
|
| 43 |
+
http = [e for e in ev if e["ev"] == "http"]
|
| 44 |
+
asst = [d for d in tr if d["ev"] == "assistant"]
|
| 45 |
+
st = next(d for d in tr if d["ev"] == "start")
|
| 46 |
+
end = next((d for d in tr if d["ev"] in ("end", "abort")), {})
|
| 47 |
+
tot = end.get("usage_total") or {}
|
| 48 |
+
|
| 49 |
+
out = [f"<!doctype html><html lang='zh'><head><meta charset='utf-8'><meta name='viewport' "
|
| 50 |
+
f"content='width=device-width,initial-scale=1'><title>{esc(a.title or 'GPT trace')}</title>"
|
| 51 |
+
f"<style>{CSS}</style></head><body><h1>{esc(a.title or os.path.basename(a.log))}</h1><div class='card'><table>"]
|
| 52 |
+
rows = [("任务 / 种子", f"{start['task']} / {start['seed']}"), ("模型", f"{st['model']}(reasoning effort {st['effort']})"),
|
| 53 |
+
("感知", start.get("perception", "depth") + "(rgb = 只有彩色图,没有深度工具)"),
|
| 54 |
+
("结果", ";".join(f"第{d['attempt']}次 {'成功' if d['success'] else '失败'}" for d in dones) or "—"),
|
| 55 |
+
("机器人命令数", sum(1 for e in ev if e["ev"] == "call")),
|
| 56 |
+
("模型调用次数 / 平均每次延迟", f"{len(asst)} / {sum(d['latency_s'] for d in asst) / max(len(asst), 1):.1f} s"),
|
| 57 |
+
("仿真执行总时长", f"{sum(h['server_s'] for h in http):.0f} s"),
|
| 58 |
+
("token(输入 / 其中缓存 / 输出 / 其中推理)",
|
| 59 |
+
f"{tot.get('input_tokens', 0)} / {tot.get('cached_tokens', 0)} / {tot.get('output_tokens', 0)} / {tot.get('reasoning_tokens', 0)}")]
|
| 60 |
+
out += [f"<tr><th>{esc(k)}</th><td>{esc(v)}</td></tr>" for k, v in rows] + ["</table></div>"]
|
| 61 |
+
inst = {k: v for k, v in start["inst"].items()}
|
| 62 |
+
out.append("<div class='card'><div class='lbl'>服务端真值(模型从未看到)</div><pre>"
|
| 63 |
+
+ esc(json.dumps(inst, indent=1, ensure_ascii=False)[:3000]) + "</pre></div>")
|
| 64 |
+
if a.video and os.path.exists(os.path.join(a.log, "rollout.mp4")):
|
| 65 |
+
b = base64.b64encode(open(os.path.join(a.log, "rollout.mp4"), "rb").read()).decode()
|
| 66 |
+
out.append("<h2>录像(左:第三视角,右:腕部;3 倍速)</h2><video controls style='max-width:100%' "
|
| 67 |
+
f"src='data:video/mp4;base64,{b}'></video>")
|
| 68 |
+
|
| 69 |
+
out.append("<h2>1. 模型收到的系统指令和工具(原文,每次请求都一样)</h2>")
|
| 70 |
+
out.append("<div class='card'>这就是发给 GPT 的全部固定内容:沙箱 README 原文加一句开头说明,以及唯一的 robot 工具。"
|
| 71 |
+
"没有文件、记忆、深度、物体坐标。</div>")
|
| 72 |
+
out.append(f"<details class='card' open><summary>instructions({len(st['instructions'])} 字符)</summary><pre>{esc(st['instructions'])}</pre></details>")
|
| 73 |
+
out.append(f"<details class='card'><summary>tool</summary><pre>{esc(json.dumps(st['tool'], indent=1, ensure_ascii=False))}</pre></details>")
|
| 74 |
+
|
| 75 |
+
out.append("<h2>2. 逐步过程</h2>")
|
| 76 |
+
t0 = tr[0]["t"]
|
| 77 |
+
n = 0
|
| 78 |
+
for d in tr:
|
| 79 |
+
tt = f"+{d['t'] - t0:6.0f}s"
|
| 80 |
+
if d["ev"] == "user":
|
| 81 |
+
imgs = "".join(img_tag(os.path.join(sb, p)) for p in d.get("images", []))
|
| 82 |
+
out.append(f"<div class='card'><span class='n'>{tt}</span> <span class='lbl'>发给模型</span><pre>{esc(d['text'])}</pre>{imgs}</div>")
|
| 83 |
+
elif d["ev"] == "assistant":
|
| 84 |
+
blk = [f"<div class='card'><span class='n'>{tt}</span> <span class='lbl'>模型回复</span> "
|
| 85 |
+
f"<span class='lbl'>({d['latency_s']:.1f} s,输出 {d['usage'].get('output_tokens', 0)} token,"
|
| 86 |
+
f"其中推理 {d['usage'].get('reasoning_tokens', 0)})</span>"]
|
| 87 |
+
if d.get("reasoning_summary"):
|
| 88 |
+
blk.append(f"<div class='lbl think'>推理摘要(模型自己的思考摘要)</div><pre class='think'>{esc(d['reasoning_summary'])}</pre>")
|
| 89 |
+
if d.get("text"):
|
| 90 |
+
blk.append(f"<div class='lbl'>文字</div><pre>{esc(d['text'])}</pre>")
|
| 91 |
+
for c in d["tool_calls"]:
|
| 92 |
+
n += 1
|
| 93 |
+
blk.append(f"<div>#{n} <span class='cmd'>./robot {esc(c['arguments'].get('command', ''))}</span></div>")
|
| 94 |
+
out.append("".join(blk) + "</div>")
|
| 95 |
+
elif d["ev"] == "tool":
|
| 96 |
+
imgs = "".join(img_tag(os.path.join(sb, p)) for p in d.get("images", []))
|
| 97 |
+
txt = d["output"]
|
| 98 |
+
out.append(f"<div class='card'><span class='n'>{tt}</span> <span class='lbl'>服务器返回(作为工具结果发给模型)</span>"
|
| 99 |
+
f"<details {'open' if len(txt) < 1500 else ''}><summary>{len(txt)} 字符</summary><pre>{esc(txt)}</pre></details>"
|
| 100 |
+
+ (f"<div class='lbl'>随后附上的图像</div>{imgs}" if imgs else "") + "</div>")
|
| 101 |
+
elif d["ev"] in ("api_error", "abort"):
|
| 102 |
+
out.append(f"<div class='card bad'>{esc(json.dumps(d, ensure_ascii=False))}</div>")
|
| 103 |
+
out.append("<h2>3. 服务端每次 done 的判定</h2>")
|
| 104 |
+
for e in dones:
|
| 105 |
+
out.append(f"<div class='card'>第 {e['attempt']} 次:<span class='{'ok' if e['success'] else 'bad'}'>"
|
| 106 |
+
f"{'成功' if e['success'] else '失败'}</span>(agent 的理由:{esc(e.get('reason', ''))})<pre>{esc(e.get('feedback', ''))}</pre></div>")
|
| 107 |
+
rep = os.path.join(a.log, "final_report.md")
|
| 108 |
+
if os.path.exists(rep):
|
| 109 |
+
out.append(f"<h2>4. 模型最后的报告</h2><div class='card'><pre>{esc(open(rep).read())}</pre></div>")
|
| 110 |
+
out.append("</body></html>")
|
| 111 |
+
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
|
| 112 |
+
with open(a.out, "w") as f:
|
| 113 |
+
f.write("\n".join(out))
|
| 114 |
+
print(a.out, os.path.getsize(a.out), "bytes; commands", n)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__":
|
| 118 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/validate.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Headroom validation of LFF-Bench tasks with scripted reference policies.
|
| 2 |
+
|
| 3 |
+
python scripts/validate.py --task l5_slide_to_target --n 20 --k 5
|
| 4 |
+
Writes results/<task>/validate.json and thumbnails.
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
import importlib
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import pkgutil
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 17 |
+
sys.path.insert(0, ROOT)
|
| 18 |
+
|
| 19 |
+
import imageio # noqa: E402
|
| 20 |
+
|
| 21 |
+
import lffbench.tasks as task_pkg # noqa: E402
|
| 22 |
+
from lffbench.task_base import TASKS # noqa: E402
|
| 23 |
+
|
| 24 |
+
for m in pkgutil.iter_modules(task_pkg.__path__):
|
| 25 |
+
importlib.import_module(f"lffbench.tasks.{m.name}")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def succ_curve(results, k):
|
| 29 |
+
"""run-level succ@j for j = 1..k (a run = one instance, attempts share the run's state)."""
|
| 30 |
+
out = []
|
| 31 |
+
for j in range(1, k + 1):
|
| 32 |
+
out.append(float(np.mean([r is not None and r <= j for r in results])))
|
| 33 |
+
return out
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main():
|
| 37 |
+
ap = argparse.ArgumentParser()
|
| 38 |
+
ap.add_argument("--task", required=True)
|
| 39 |
+
ap.add_argument("--n", type=int, default=20)
|
| 40 |
+
ap.add_argument("--k", type=int, default=5)
|
| 41 |
+
ap.add_argument("--seed0", type=int, default=1000)
|
| 42 |
+
ap.add_argument("--kinds", default="oracle,naive,adaptive,blind")
|
| 43 |
+
ap.add_argument("--thumbs", type=int, default=3)
|
| 44 |
+
args = ap.parse_args()
|
| 45 |
+
|
| 46 |
+
task = TASKS[args.task]()
|
| 47 |
+
outdir = os.path.join(ROOT, "results", args.task)
|
| 48 |
+
os.makedirs(outdir, exist_ok=True)
|
| 49 |
+
kinds = args.kinds.split(",")
|
| 50 |
+
first_success = {k: [] for k in kinds}
|
| 51 |
+
runs = []
|
| 52 |
+
t0 = time.time()
|
| 53 |
+
for i in range(args.n):
|
| 54 |
+
seed = args.seed0 + i
|
| 55 |
+
inst = task.sample_instance(seed)
|
| 56 |
+
if i < args.thumbs:
|
| 57 |
+
task.reset_instance(inst)
|
| 58 |
+
imageio.imwrite(os.path.join(outdir, f"init_{seed}.png"), task.snapshot(res=384))
|
| 59 |
+
for kind in kinds:
|
| 60 |
+
hist = task.run_scripted(kind, inst, k=args.k, seed=seed)
|
| 61 |
+
s = next((h["attempt"] for h in hist if h["outcome"]["success"]), None)
|
| 62 |
+
first_success[kind].append(s)
|
| 63 |
+
runs.append(dict(seed=seed, kind=kind, inst={k: v for k, v in inst.items() if not k.startswith("_")},
|
| 64 |
+
history=hist))
|
| 65 |
+
if i < args.thumbs and kind == "naive":
|
| 66 |
+
imageio.imwrite(os.path.join(outdir, f"naive_end_{seed}.png"), task.snapshot(res=384))
|
| 67 |
+
print(f"[{i + 1}/{args.n}] seed={seed} " + " ".join(f"{k}={first_success[k][-1]}" for k in kinds)
|
| 68 |
+
+ f" ({time.time() - t0:.0f}s)", flush=True)
|
| 69 |
+
|
| 70 |
+
summary = {k: succ_curve(v, args.k) for k, v in first_success.items()}
|
| 71 |
+
res = dict(task=args.task, level=task.level, capabilities=list(task.capabilities), n=args.n, k=args.k,
|
| 72 |
+
succ_at_k=summary, runs=runs, seconds=time.time() - t0)
|
| 73 |
+
with open(os.path.join(outdir, "validate.json"), "w") as f:
|
| 74 |
+
json.dump(res, f, indent=1, default=float)
|
| 75 |
+
print(json.dumps({k: [round(x, 2) for x in v] for k, v in summary.items()}))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/validate_parts_cart_isolated.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Development physical validation; no model API, no pose injection after reset."""
|
| 2 |
+
import argparse,copy,json,time,hashlib
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from lffbench.tasks.lh_parts_cart import PartsCart
|
| 7 |
+
from lffbench import envs
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
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()
|
| 11 |
+
out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
|
| 12 |
+
x=PartsCart(cam_res=512);rows=[]
|
| 13 |
+
def clean(obj):
|
| 14 |
+
if isinstance(obj,np.ndarray):return obj.tolist()
|
| 15 |
+
if isinstance(obj,np.generic):return obj.item()
|
| 16 |
+
raise TypeError(type(obj).__name__)
|
| 17 |
+
for seed in a.seeds:
|
| 18 |
+
i=x.sample_instance(seed)
|
| 19 |
+
if a.case in ['l4','l2','l5']:i['traps']={k:k==a.case.upper() for k in ['L4','L2','L5']}
|
| 20 |
+
x.reset_instance(i);r=dict(seed=seed,case=a.case,instance=i,checkpoints=[]);rows.append(r)
|
| 21 |
+
def snap(label):
|
| 22 |
+
o=copy.deepcopy(x.outcome(i));q=out/f's{seed}_{label}.png';Image.fromarray(x.snapshot(res=512)).save(q)
|
| 23 |
+
r['checkpoints'].append(dict(label=label,sim_step=x.sk.n_steps,commands=x.sk.robot_commands,outcome=o,image=str(q.resolve())))
|
| 24 |
+
(out/'results.json').write_text(json.dumps(rows,indent=2,default=clean))
|
| 25 |
+
print(seed,label,o['success'],o['traps'],o['stages'],flush=True)
|
| 26 |
+
snap('initial')
|
| 27 |
+
if a.case=='oracle':
|
| 28 |
+
x.execute(i,x.oracle_params(i));snap('oracle_final');continue
|
| 29 |
+
if a.case in ['combined','l4']:
|
| 30 |
+
x.tool_push_out();snap('L4_blocked')
|
| 31 |
+
x.tool_push_front();snap('L4_retrieved')
|
| 32 |
+
x.load(careful=a.case not in ['combined','l2']);snap('loaded')
|
| 33 |
+
if a.case in ['l4','l5']:
|
| 34 |
+
x.repair_load();snap('loading_prerequisite_repaired')
|
| 35 |
+
if a.case in ['combined','l2']:
|
| 36 |
+
x.repair_load();snap('L2_restored')
|
| 37 |
+
if all(x.cargo_ok(j) for j in range(2)):
|
| 38 |
+
if a.case in ['combined','l5']:
|
| 39 |
+
# First full naive push, then reuse correction loop without its initial push.
|
| 40 |
+
x.transport(0.,False);snap('L5_naive_push')
|
| 41 |
+
x._transport_only=True
|
| 42 |
+
# Feed a no-op execute only for the corrector's initial call; subsequent _push_at are unchanged.
|
| 43 |
+
original=x.execute
|
| 44 |
+
x.execute=lambda inst,params:None
|
| 45 |
+
try:
|
| 46 |
+
from lffbench.tasks.l7_offcenter_push import OffcenterPush
|
| 47 |
+
OffcenterPush.adaptive_attempt(x,i,0.)
|
| 48 |
+
finally:x.execute=original;x._transport_only=False
|
| 49 |
+
snap('L5_corrected')
|
| 50 |
+
else:x.transport(i['com_offset'] if i['traps']['L5'] else 0.,False)
|
| 51 |
+
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')
|
| 52 |
+
x.env.close()
|
| 53 |
+
(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))
|
| 54 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/agent/backends/openai_responses.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI Responses API backend (default model gpt-6-astra).
|
| 2 |
+
|
| 3 |
+
Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with
|
| 4 |
+
store=False; reasoning items are replayed with their encrypted content so the model keeps its chain
|
| 5 |
+
of thought across tool calls within an attempt. The request prefix (instructions, tools, task text,
|
| 6 |
+
packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what
|
| 7 |
+
OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs.
|
| 8 |
+
|
| 9 |
+
Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time;
|
| 10 |
+
the client is created lazily on the first real call (tests inject a mock client).
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
from ..context import ToolCall, prune_live_images
|
| 17 |
+
from .base import Backend, BackendResponse, import_openai
|
| 18 |
+
|
| 19 |
+
# GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported.
|
| 20 |
+
GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _get(obj, key, default=None):
|
| 24 |
+
if isinstance(obj, dict):
|
| 25 |
+
return obj.get(key, default)
|
| 26 |
+
return getattr(obj, key, default)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _to_dict(item):
|
| 30 |
+
if isinstance(item, dict):
|
| 31 |
+
return dict(item)
|
| 32 |
+
if hasattr(item, "to_dict"):
|
| 33 |
+
return item.to_dict(mode="json")
|
| 34 |
+
if hasattr(item, "model_dump"):
|
| 35 |
+
return item.model_dump(mode="json", exclude_none=True)
|
| 36 |
+
return dict(vars(item))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def responses_tools(specs, strict=True):
|
| 40 |
+
return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"],
|
| 41 |
+
strict=strict) for s in specs]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class OpenAIResponsesBackend(Backend):
|
| 45 |
+
name = "openai"
|
| 46 |
+
|
| 47 |
+
def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto",
|
| 48 |
+
max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None,
|
| 49 |
+
store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0,
|
| 50 |
+
max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last",
|
| 51 |
+
prompt_cache_options=None, client=None, http_client=None):
|
| 52 |
+
if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS:
|
| 53 |
+
raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), "
|
| 54 |
+
f"got {reasoning_effort!r}")
|
| 55 |
+
self.model = model
|
| 56 |
+
self.reasoning_effort = reasoning_effort
|
| 57 |
+
self.reasoning_summary = reasoning_summary
|
| 58 |
+
self.image_detail = image_detail
|
| 59 |
+
self.max_output_tokens = max_output_tokens
|
| 60 |
+
self.service_tier = service_tier
|
| 61 |
+
self.prompt_cache_key = prompt_cache_key
|
| 62 |
+
self.prompt_cache_retention = prompt_cache_retention
|
| 63 |
+
self.store = store
|
| 64 |
+
self.replay_reasoning = replay_reasoning
|
| 65 |
+
self.max_live_images = max_live_images
|
| 66 |
+
self.jpeg_quality = jpeg_quality
|
| 67 |
+
self.timeout = timeout
|
| 68 |
+
self.max_retries = max_retries
|
| 69 |
+
self.extra_body = extra_body
|
| 70 |
+
self.strict_tools = strict_tools
|
| 71 |
+
# explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last"
|
| 72 |
+
assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints
|
| 73 |
+
self.cache_breakpoints = cache_breakpoints
|
| 74 |
+
self.prompt_cache_options = prompt_cache_options
|
| 75 |
+
self._client = client
|
| 76 |
+
self._http_client = http_client # optional custom transport (tests, proxies)
|
| 77 |
+
self._cache_key = prompt_cache_key
|
| 78 |
+
|
| 79 |
+
def config(self):
|
| 80 |
+
return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort,
|
| 81 |
+
reasoning_summary=self.reasoning_summary, image_detail=self.image_detail,
|
| 82 |
+
max_output_tokens=self.max_output_tokens, service_tier=self.service_tier,
|
| 83 |
+
prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention,
|
| 84 |
+
store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images,
|
| 85 |
+
jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries,
|
| 86 |
+
extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints,
|
| 87 |
+
prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL"))
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ client
|
| 90 |
+
def client(self):
|
| 91 |
+
if self._client is None:
|
| 92 |
+
key = os.environ.get("OPENAI_API_KEY")
|
| 93 |
+
if not key:
|
| 94 |
+
raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it")
|
| 95 |
+
openai = import_openai()
|
| 96 |
+
kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout,
|
| 97 |
+
max_retries=self.max_retries)
|
| 98 |
+
if self._http_client is not None:
|
| 99 |
+
kw["http_client"] = self._http_client
|
| 100 |
+
self._client = openai.OpenAI(**kw)
|
| 101 |
+
return self._client
|
| 102 |
+
|
| 103 |
+
def begin_run(self, info):
|
| 104 |
+
if self.prompt_cache_key is None:
|
| 105 |
+
# route all calls of one run to the same cache shard
|
| 106 |
+
self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}"
|
| 107 |
+
|
| 108 |
+
# ------------------------------------------------------------------ request
|
| 109 |
+
def convert_items(self, items):
|
| 110 |
+
out = []
|
| 111 |
+
last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1)
|
| 112 |
+
for i, it in enumerate(items):
|
| 113 |
+
kind = it["kind"]
|
| 114 |
+
if kind == "user":
|
| 115 |
+
content = []
|
| 116 |
+
for p in it["parts"]:
|
| 117 |
+
if p["type"] == "text":
|
| 118 |
+
content.append(dict(type="input_text", text=p["text"]))
|
| 119 |
+
else:
|
| 120 |
+
content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality),
|
| 121 |
+
detail=self.image_detail))
|
| 122 |
+
# explicit cache breakpoints: end of the stable history item (byte-identical for the whole
|
| 123 |
+
# attempt) and end of the newest input (reused by the next call of the attempt)
|
| 124 |
+
if content and ((self.cache_breakpoints != "none" and not it.get("live"))
|
| 125 |
+
or (self.cache_breakpoints == "history+last" and i == last_user)):
|
| 126 |
+
content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit")
|
| 127 |
+
out.append(dict(role="user", content=content))
|
| 128 |
+
elif kind == "assistant":
|
| 129 |
+
if it.get("raw") and it.get("backend") == self.name:
|
| 130 |
+
for r in it["raw"]:
|
| 131 |
+
if r.get("type") == "reasoning" and not self.replay_reasoning:
|
| 132 |
+
continue
|
| 133 |
+
out.append(r)
|
| 134 |
+
else:
|
| 135 |
+
if it.get("text"):
|
| 136 |
+
out.append(dict(role="assistant", content=it["text"]))
|
| 137 |
+
for tc in it["tool_calls"]:
|
| 138 |
+
out.append(dict(type="function_call", call_id=tc.id, name=tc.name,
|
| 139 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 140 |
+
elif kind == "tool_output":
|
| 141 |
+
out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"]))
|
| 142 |
+
else:
|
| 143 |
+
raise ValueError(kind)
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
def build_request(self, conv, tools):
|
| 147 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 148 |
+
req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items),
|
| 149 |
+
tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False,
|
| 150 |
+
store=self.store)
|
| 151 |
+
reasoning = dict(effort=self.reasoning_effort)
|
| 152 |
+
if self.reasoning_summary:
|
| 153 |
+
reasoning["summary"] = self.reasoning_summary
|
| 154 |
+
req["reasoning"] = reasoning
|
| 155 |
+
if not self.store and self.replay_reasoning:
|
| 156 |
+
req["include"] = ["reasoning.encrypted_content"]
|
| 157 |
+
if self.max_output_tokens:
|
| 158 |
+
req["max_output_tokens"] = int(self.max_output_tokens)
|
| 159 |
+
if self.service_tier:
|
| 160 |
+
req["service_tier"] = self.service_tier
|
| 161 |
+
if self._cache_key:
|
| 162 |
+
req["prompt_cache_key"] = self._cache_key
|
| 163 |
+
if self.prompt_cache_retention:
|
| 164 |
+
req["prompt_cache_retention"] = self.prompt_cache_retention
|
| 165 |
+
if self.prompt_cache_options:
|
| 166 |
+
req["prompt_cache_options"] = dict(self.prompt_cache_options)
|
| 167 |
+
if self.extra_body:
|
| 168 |
+
req["extra_body"] = dict(self.extra_body)
|
| 169 |
+
return req
|
| 170 |
+
|
| 171 |
+
@staticmethod
|
| 172 |
+
def request_stats(req):
|
| 173 |
+
n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "")
|
| 174 |
+
for it in req["input"]:
|
| 175 |
+
for c in (it.get("content") if isinstance(it.get("content"), list) else []):
|
| 176 |
+
if c.get("type") == "input_image":
|
| 177 |
+
n_img += 1
|
| 178 |
+
img_bytes += len(c["image_url"])
|
| 179 |
+
elif "text" in c:
|
| 180 |
+
txt += len(c["text"])
|
| 181 |
+
if isinstance(it.get("content"), str):
|
| 182 |
+
txt += len(it["content"])
|
| 183 |
+
if it.get("type") == "function_call_output":
|
| 184 |
+
txt += len(it["output"]) if isinstance(it["output"], str) else 0
|
| 185 |
+
if it.get("type") == "function_call":
|
| 186 |
+
txt += len(it.get("arguments", ""))
|
| 187 |
+
tools_chars = len(json.dumps(req.get("tools", [])))
|
| 188 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars,
|
| 189 |
+
n_input_items=len(req["input"]))
|
| 190 |
+
|
| 191 |
+
# ------------------------------------------------------------------ call
|
| 192 |
+
def act(self, conv, tools):
|
| 193 |
+
req = self.build_request(conv, tools)
|
| 194 |
+
stats = self.request_stats(req)
|
| 195 |
+
t0 = time.time()
|
| 196 |
+
resp = self.client().responses.create(**req)
|
| 197 |
+
out = self.parse_response(resp)
|
| 198 |
+
out.latency_s = time.time() - t0
|
| 199 |
+
out.request_stats = stats
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
+
def parse_response(self, resp):
|
| 203 |
+
calls, texts, summ = [], [], []
|
| 204 |
+
output = _get(resp, "output") or []
|
| 205 |
+
for item in output:
|
| 206 |
+
t = _get(item, "type")
|
| 207 |
+
if t == "function_call":
|
| 208 |
+
raw = _get(item, "arguments") or ""
|
| 209 |
+
try:
|
| 210 |
+
args = json.loads(raw) if raw else {}
|
| 211 |
+
except json.JSONDecodeError:
|
| 212 |
+
args = {}
|
| 213 |
+
calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args,
|
| 214 |
+
raw_arguments=raw))
|
| 215 |
+
elif t == "message":
|
| 216 |
+
for c in _get(item, "content") or []:
|
| 217 |
+
if _get(c, "type") == "output_text":
|
| 218 |
+
texts.append(_get(c, "text") or "")
|
| 219 |
+
elif t == "reasoning":
|
| 220 |
+
for s in _get(item, "summary") or []:
|
| 221 |
+
summ.append(_get(s, "text") or "")
|
| 222 |
+
u = _get(resp, "usage")
|
| 223 |
+
usage = {}
|
| 224 |
+
if u is not None:
|
| 225 |
+
itd = _get(u, "input_tokens_details")
|
| 226 |
+
otd = _get(u, "output_tokens_details")
|
| 227 |
+
usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0,
|
| 228 |
+
cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0,
|
| 229 |
+
cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0,
|
| 230 |
+
output_tokens=_get(u, "output_tokens", 0) or 0,
|
| 231 |
+
reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0)
|
| 232 |
+
status = _get(resp, "status") or "completed"
|
| 233 |
+
err = None
|
| 234 |
+
if status == "incomplete":
|
| 235 |
+
err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason"))
|
| 236 |
+
elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again
|
| 237 |
+
status, err = "incomplete", "empty response (no output, no usage)"
|
| 238 |
+
return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
|
| 239 |
+
reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage,
|
| 240 |
+
raw=[_to_dict(i) for i in output], status=status, error=err)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/contract.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Information contract of one run (docs/15 §1 layer 2) and its hash `contract_sha256`.
|
| 2 |
+
|
| 3 |
+
The contract is everything the agent is given that must be identical across harnesses and models for the same
|
| 4 |
+
instance and condition: the README text, the three tool schemas, the image spec, the feedback level, --hide-k, the
|
| 5 |
+
budgets, the memory condition, the task and seed, and the code that builds the scene and judges it. Two runs whose
|
| 6 |
+
`contract_sha256` differ must not share a table cell.
|
| 7 |
+
|
| 8 |
+
What is NOT in the contract on purpose: the harness (it is the thing being compared), the model, the port, the
|
| 9 |
+
sandbox / log paths, timestamps.
|
| 10 |
+
|
| 11 |
+
contract = build_contract(log_dir) # reads session.json, agent_iface.json, events.jsonl, README.md
|
| 12 |
+
contract_sha256(contract) # sha256 of the canonical JSON
|
| 13 |
+
write_contract(log_dir) # -> <log_dir>/contract.json, returns (contract, sha)
|
| 14 |
+
"""
|
| 15 |
+
import glob
|
| 16 |
+
import hashlib
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # the lffbench repo
|
| 23 |
+
CONTRACT_VERSION = 1
|
| 24 |
+
IMAGE_SPEC = dict(cameras=["agentview", "wrist"], width=512, height=512, format="JPEG", jpeg_quality=90,
|
| 25 |
+
delivery="files in the workspace, viewed with view_images (bytes unchanged)")
|
| 26 |
+
# code that builds the scene, runs the robot and judges the result (task modules are added per task)
|
| 27 |
+
SERVER_CODE = ["lffbench/agent/robot_server.py", "lffbench/agent/tools.py", "lffbench/agent/camera.py",
|
| 28 |
+
"lffbench/agent/context.py", "lffbench/agent/images.py", "lffbench/envs.py", "lffbench/skills.py",
|
| 29 |
+
"lffbench/task_base.py", "lffbench/bddl.py", "lffbench/objects.py"]
|
| 30 |
+
# real-robot backend (added for real_* tasks only; the driver itself is recorded as contract["real_driver"])
|
| 31 |
+
REAL_CODE = ["lffbench/real/tasks.py", "lffbench/real/session.py", "lffbench/real/executor.py", "lffbench/real/protocol.py"]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def sha256_bytes(b):
|
| 35 |
+
return hashlib.sha256(b).hexdigest()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def sha256_text(s):
|
| 39 |
+
return sha256_bytes(s.encode("utf-8"))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def sha256_file(path):
|
| 43 |
+
h = hashlib.sha256()
|
| 44 |
+
with open(path, "rb") as f:
|
| 45 |
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
| 46 |
+
h.update(chunk)
|
| 47 |
+
return h.hexdigest()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def canonical(obj):
|
| 51 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def sha256_json(obj):
|
| 55 |
+
return sha256_text(canonical(obj))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def tool_schemas():
|
| 59 |
+
"""The three LA tools exactly as the reference driver and the MCP server define them."""
|
| 60 |
+
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
| 61 |
+
from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, PREAMBLE_LA # noqa: E402
|
| 62 |
+
return [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA], PREAMBLE_LA
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def task_module_files(task):
|
| 66 |
+
"""Source files of the task class `task` (found by its `name = "<task>"` line; .bak files are ignored)."""
|
| 67 |
+
pat = re.compile(r"""^\s*name\s*=\s*["']%s["']""" % re.escape(task), re.M)
|
| 68 |
+
hits = []
|
| 69 |
+
for p in sorted(glob.glob(os.path.join(ROOT, "lffbench", "tasks", "*.py"))):
|
| 70 |
+
try:
|
| 71 |
+
if pat.search(open(p, encoding="utf-8").read()):
|
| 72 |
+
hits.append(os.path.relpath(p, ROOT))
|
| 73 |
+
except OSError:
|
| 74 |
+
pass
|
| 75 |
+
arm = os.path.join(ROOT, "lffbench", "arm_specs", f"{task}.py")
|
| 76 |
+
if os.path.exists(arm):
|
| 77 |
+
hits.append(os.path.relpath(arm, ROOT))
|
| 78 |
+
real = os.path.join(ROOT, "lffbench", "real", "tasks.py") # real-robot tasks (docs/17): add the real backend's code
|
| 79 |
+
if not hits and os.path.exists(real) and pat.search(open(real, encoding="utf-8").read()):
|
| 80 |
+
hits += REAL_CODE
|
| 81 |
+
return hits
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def server_code_sha(task):
|
| 85 |
+
files = SERVER_CODE + task_module_files(task)
|
| 86 |
+
per = {f: (sha256_file(os.path.join(ROOT, f)) if os.path.exists(os.path.join(ROOT, f)) else None) for f in files}
|
| 87 |
+
return sha256_json(per), per
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def session_start(log_dir):
|
| 91 |
+
with open(os.path.join(log_dir, "events.jsonl")) as f:
|
| 92 |
+
for line in f:
|
| 93 |
+
d = json.loads(line)
|
| 94 |
+
if d.get("ev") == "session_start":
|
| 95 |
+
return d
|
| 96 |
+
raise RuntimeError(f"no session_start event in {log_dir}/events.jsonl")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def readme_budget(readme):
|
| 100 |
+
"""The per-attempt budgets as the README states them (what the agent is told)."""
|
| 101 |
+
out = {}
|
| 102 |
+
for key, pat in (("robot_commands", r"at most (\d+) robot commands"),
|
| 103 |
+
("sim_seconds", r"at most ([\d.]+) s of (?:simulated )?robot motion"), # real robot: "s of robot motion"
|
| 104 |
+
("tool_calls", r"at most (\d+) tool calls")):
|
| 105 |
+
m = re.search(pat, readme)
|
| 106 |
+
out[key] = float(m.group(1)) if m and "." in m.group(1) else (int(m.group(1)) if m else None)
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def build_contract(log_dir):
|
| 111 |
+
log_dir = os.path.abspath(log_dir)
|
| 112 |
+
sess = json.load(open(os.path.join(log_dir, "session.json")))
|
| 113 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 114 |
+
st = session_start(log_dir)
|
| 115 |
+
readme = open(os.path.join(sess["sandbox"], "README.md"), encoding="utf-8").read()
|
| 116 |
+
tools, preamble = tool_schemas()
|
| 117 |
+
code_sha, code_files = server_code_sha(st["task"])
|
| 118 |
+
out = dict(
|
| 119 |
+
contract_version=CONTRACT_VERSION,
|
| 120 |
+
task=st["task"], seed=st["seed"],
|
| 121 |
+
readme_sha256=sha256_text(readme),
|
| 122 |
+
preamble_sha256=sha256_text(preamble),
|
| 123 |
+
tools=tools,
|
| 124 |
+
image_spec=dict(IMAGE_SPEC, perception=st.get("perception", iface.get("perception"))),
|
| 125 |
+
feedback=st.get("feedback"), instruction=st.get("instruction"),
|
| 126 |
+
memory=st.get("memory"), k=st.get("k"), k_shown=st.get("k_shown"), hide_k=st.get("k_shown") != st.get("k"),
|
| 127 |
+
protocol=st.get("protocol"), arm=st.get("arm"), dossier_sha256=sha256_text(st.get("dossier") or ""),
|
| 128 |
+
budget=dict(readme_budget(readme), max_tool_calls=iface.get("max_tool_calls"),
|
| 129 |
+
tool_call_budget_enforced_by="mcp_robot_server / api_player (per attempt)"),
|
| 130 |
+
agent_iface=iface.get("agent_iface"),
|
| 131 |
+
server_code_sha256=code_sha, server_code_files=code_files,
|
| 132 |
+
)
|
| 133 |
+
if st.get("backend") == "real": # only real-robot runs get this key, so simulated contracts are unchanged
|
| 134 |
+
di = st.get("driver_info") or {}
|
| 135 |
+
out["real_driver"] = {k: di.get(k) for k in ("protocol", "robot", "n_joints", "workspace", "yaw_range_deg",
|
| 136 |
+
"max_speed", "ik", "driver_version")}
|
| 137 |
+
out["real_agent_workspace"] = st.get("agent_workspace")
|
| 138 |
+
from .redteam import marker # adversarial acceptance runs only (harness_run --red-team): others are unchanged
|
| 139 |
+
rt = marker(log_dir)
|
| 140 |
+
if rt:
|
| 141 |
+
out["red_team"] = rt
|
| 142 |
+
return out
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def contract_sha256(contract):
|
| 146 |
+
return sha256_json(contract)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def write_contract(log_dir):
|
| 150 |
+
c = build_contract(log_dir)
|
| 151 |
+
sha = contract_sha256(c)
|
| 152 |
+
with open(os.path.join(log_dir, "contract.json"), "w") as f:
|
| 153 |
+
json.dump(dict(contract_sha256=sha, contract=c), f, indent=1, ensure_ascii=False)
|
| 154 |
+
return c, sha
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == "__main__":
|
| 158 |
+
for d in sys.argv[1:]:
|
| 159 |
+
c, sha = write_contract(d)
|
| 160 |
+
print(sha, d)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/jail.py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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Jail for native harness processes (docs/15 §3.4): the harness sees no host path at all, instead of only "having no
|
| 2 |
+
tool that reads files".
|
| 3 |
+
|
| 4 |
+
Without it, Claude Code / Codex run as root on the host with /mnt visible (task code with the hidden-variable rules,
|
| 5 |
+
task cards, earlier runs' logs, .secrets); isolation then rests on every built-in tool being switched off. With it
|
| 6 |
+
(adapter option jail=True, `harness_run.py --jail`, `api_batch.py start --jail`):
|
| 7 |
+
- the harness runs as the unprivileged host user nobody (uid 65534) in new user + mount namespaces
|
| 8 |
+
(jail/harness_jail_inner.sh, installed under /opt/lffjail/hjail by jail/setup_harness_jail.sh): /mnt /home /root
|
| 9 |
+
/tmp /run/secrets /etc/dsw are empty tmpfs, system dirs read-only, all capabilities dropped; the network stays
|
| 10 |
+
(model API);
|
| 11 |
+
- /proc: "static" (Codex) = a read-only tmpfs with static copies of host-wide files (CPU, memory, kernel version) and
|
| 12 |
+
the process's own self/ entries, no other pid; "host" (Claude Code, a Bun executable that aborts without a real
|
| 13 |
+
procfs; a fresh procfs cannot be mounted in this container because its /proc has locked submounts) = the host
|
| 14 |
+
procfs, where as uid 65534 the harness can list processes and read their command lines but not their environ, fd,
|
| 15 |
+
cwd or root (checked in tests/harness_selfcheck/jail_probe.py);
|
| 16 |
+
- visible again, at their original paths: the one-time work dir, the one-time state dir and the socket dir of the
|
| 17 |
+
MCP relay (chowned to uid 65534); the harness binary runs from a verified copy of its release dir under
|
| 18 |
+
/opt/lffjail/hjail/bin (the original lives under 0700 dirs in /mnt);
|
| 19 |
+
- the MCP server (scripts/mcp_robot_server.py) runs outside the jail; the harness starts the relay
|
| 20 |
+
/opt/lffjail/hjail/mcp_fwd.py, which connects to a Unix socket served here: every connection gets its own MCP
|
| 21 |
+
server process with stdin / stdout on the socket and the environment {PATH} only.
|
| 22 |
+
The harness command line (except argv[0] = the copy), its environment (exact whitelist) and the paths it sees are
|
| 23 |
+
unchanged; only the MCP server entry of its config points to the relay.
|
| 24 |
+
"""
|
| 25 |
+
import hashlib
|
| 26 |
+
import os
|
| 27 |
+
import secrets
|
| 28 |
+
import shutil
|
| 29 |
+
import socket
|
| 30 |
+
import subprocess
|
| 31 |
+
import threading
|
| 32 |
+
|
| 33 |
+
JAIL_DIR = "/opt/lffjail/hjail"
|
| 34 |
+
INNER = os.path.join(JAIL_DIR, "inner.sh")
|
| 35 |
+
RELAY = os.path.join(JAIL_DIR, "mcp_fwd.py")
|
| 36 |
+
BIN_DIR = os.path.join(JAIL_DIR, "bin")
|
| 37 |
+
RELAY_PYTHON = "/usr/bin/python3"
|
| 38 |
+
SOCK_ROOT = "/tmp/lffsock"
|
| 39 |
+
JAIL_UID = 65534
|
| 40 |
+
MAX_BINDS = 16
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class JailError(RuntimeError):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def installed_problems():
|
| 48 |
+
p = []
|
| 49 |
+
for f in (INNER, RELAY):
|
| 50 |
+
if not os.path.exists(f):
|
| 51 |
+
p.append(f"{f} missing (sudo bash jail/setup_harness_jail.sh)")
|
| 52 |
+
if not os.path.isdir(os.path.join(JAIL_DIR, "stage", str(MAX_BINDS - 1))):
|
| 53 |
+
p.append(f"{JAIL_DIR}/stage/0..{MAX_BINDS - 1} missing (sudo bash jail/setup_harness_jail.sh)")
|
| 54 |
+
if not os.access(RELAY_PYTHON, os.X_OK):
|
| 55 |
+
p.append(f"{RELAY_PYTHON} missing")
|
| 56 |
+
for t in ("unshare", "setpriv"):
|
| 57 |
+
if not shutil.which(t):
|
| 58 |
+
p.append(f"{t} not found")
|
| 59 |
+
return p
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def sha256_file(path):
|
| 63 |
+
h = hashlib.sha256()
|
| 64 |
+
with open(path, "rb") as f:
|
| 65 |
+
for b in iter(lambda: f.read(1 << 20), b""):
|
| 66 |
+
h.update(b)
|
| 67 |
+
return h.hexdigest()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _outermost(dirs):
|
| 71 |
+
"""Drop directories that lie inside another one of the list (one bind mount covers them)."""
|
| 72 |
+
ds = sorted({os.path.realpath(d) for d in dirs if d}, key=len)
|
| 73 |
+
out = []
|
| 74 |
+
for d in ds:
|
| 75 |
+
if not any(d == o or d.startswith(o.rstrip("/") + "/") for o in out):
|
| 76 |
+
out.append(d)
|
| 77 |
+
return out
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _chown_tree(root, uid):
|
| 81 |
+
os.chown(root, uid, uid)
|
| 82 |
+
for dp, dn, fn in os.walk(root):
|
| 83 |
+
for n in dn + fn:
|
| 84 |
+
try:
|
| 85 |
+
os.lchown(os.path.join(dp, n), uid, uid)
|
| 86 |
+
except FileNotFoundError:
|
| 87 |
+
pass
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def binary_copy(binary):
|
| 91 |
+
"""A verified copy of the binary's release dir under /opt/lffjail/hjail/bin (readable by uid 65534); returns
|
| 92 |
+
(path of the binary in the copy, info). The release dir is the binary's dir, or its parent if that is a bin/."""
|
| 93 |
+
real = os.path.realpath(binary)
|
| 94 |
+
if not os.path.isfile(real):
|
| 95 |
+
raise JailError(f"harness binary {binary} -> {real} not found")
|
| 96 |
+
sha = sha256_file(real)
|
| 97 |
+
rel_root = os.path.dirname(real)
|
| 98 |
+
if os.path.basename(rel_root) == "bin":
|
| 99 |
+
rel_root = os.path.dirname(rel_root)
|
| 100 |
+
dst_root = os.path.join(BIN_DIR, f"{os.path.basename(rel_root)}-{sha[:12]}")
|
| 101 |
+
dst = os.path.join(dst_root, os.path.relpath(real, rel_root))
|
| 102 |
+
if not (os.path.isfile(dst) and sha256_file(dst) == sha):
|
| 103 |
+
os.makedirs(BIN_DIR, mode=0o755, exist_ok=True)
|
| 104 |
+
tmp = dst_root + ".tmp-" + secrets.token_hex(3)
|
| 105 |
+
shutil.copytree(rel_root, tmp, symlinks=True)
|
| 106 |
+
for dp, dn, fn in os.walk(tmp):
|
| 107 |
+
os.chmod(dp, 0o755)
|
| 108 |
+
if os.path.exists(dst_root):
|
| 109 |
+
shutil.rmtree(dst_root)
|
| 110 |
+
os.rename(tmp, dst_root)
|
| 111 |
+
if sha256_file(dst) != sha:
|
| 112 |
+
raise JailError(f"copy of {real} does not match its sha256")
|
| 113 |
+
return dst, dict(original=real, copy=dst, sha256=sha)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class _Relay:
|
| 117 |
+
"""Serves one Unix socket; each connection gets a fresh MCP server process attached to it."""
|
| 118 |
+
|
| 119 |
+
def __init__(self, sock_path, argv, env, stderr_path, uid):
|
| 120 |
+
self.path, self.argv, self.env, self.stderr_path = sock_path, argv, env, stderr_path
|
| 121 |
+
self.procs = []
|
| 122 |
+
self.closed = False
|
| 123 |
+
self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
| 124 |
+
self.srv.bind(sock_path)
|
| 125 |
+
os.chown(sock_path, uid, uid)
|
| 126 |
+
os.chmod(sock_path, 0o600)
|
| 127 |
+
self.srv.listen(8)
|
| 128 |
+
self.t = threading.Thread(target=self._serve, daemon=True)
|
| 129 |
+
self.t.start()
|
| 130 |
+
|
| 131 |
+
def _serve(self):
|
| 132 |
+
while not self.closed:
|
| 133 |
+
try:
|
| 134 |
+
conn, _ = self.srv.accept()
|
| 135 |
+
except OSError:
|
| 136 |
+
return
|
| 137 |
+
try:
|
| 138 |
+
err = open(self.stderr_path, "ab") if self.stderr_path else subprocess.DEVNULL
|
| 139 |
+
p = subprocess.Popen(self.argv, stdin=conn.fileno(), stdout=conn.fileno(), stderr=err, env=self.env,
|
| 140 |
+
cwd="/", start_new_session=True)
|
| 141 |
+
self.procs.append(p)
|
| 142 |
+
if err is not subprocess.DEVNULL:
|
| 143 |
+
err.close()
|
| 144 |
+
finally:
|
| 145 |
+
conn.close()
|
| 146 |
+
|
| 147 |
+
def close(self):
|
| 148 |
+
self.closed = True
|
| 149 |
+
try:
|
| 150 |
+
self.srv.close()
|
| 151 |
+
except OSError:
|
| 152 |
+
pass
|
| 153 |
+
for p in self.procs:
|
| 154 |
+
if p.poll() is None:
|
| 155 |
+
p.terminate()
|
| 156 |
+
for p in self.procs:
|
| 157 |
+
try:
|
| 158 |
+
p.wait(timeout=10)
|
| 159 |
+
except subprocess.TimeoutExpired:
|
| 160 |
+
p.kill()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class HarnessJail:
|
| 164 |
+
"""One per adapter instance. mcp_command() registers a real MCP server command and returns the relay command for
|
| 165 |
+
the harness config; wrap() turns the harness argv into the jailed one; close() stops relays and removes sockets."""
|
| 166 |
+
|
| 167 |
+
def __init__(self, binary, proc="static", uid=JAIL_UID, stderr_dir=None):
|
| 168 |
+
probs = installed_problems()
|
| 169 |
+
if probs:
|
| 170 |
+
raise JailError("; ".join(probs))
|
| 171 |
+
if proc not in ("static", "host"):
|
| 172 |
+
raise JailError(f"proc must be static or host, not {proc!r}")
|
| 173 |
+
self.binary_real = os.path.realpath(binary)
|
| 174 |
+
self.binary_jailed, self.binary_info = binary_copy(binary)
|
| 175 |
+
self.proc, self.uid = proc, uid
|
| 176 |
+
self.sock_dir = None
|
| 177 |
+
self.relays = []
|
| 178 |
+
self.stderr_dir = stderr_dir
|
| 179 |
+
|
| 180 |
+
def info(self):
|
| 181 |
+
return dict(enabled=True, uid=self.uid, proc=self.proc, binary=self.binary_info, inner=INNER,
|
| 182 |
+
inner_sha256=sha256_file(INNER), relay=RELAY)
|
| 183 |
+
|
| 184 |
+
def _sock_dir(self):
|
| 185 |
+
if self.sock_dir is None:
|
| 186 |
+
os.makedirs(SOCK_ROOT, mode=0o711, exist_ok=True)
|
| 187 |
+
os.chmod(SOCK_ROOT, 0o711)
|
| 188 |
+
d = os.path.join(SOCK_ROOT, secrets.token_hex(6))
|
| 189 |
+
os.mkdir(d, 0o700)
|
| 190 |
+
os.chown(d, self.uid, self.uid)
|
| 191 |
+
self.sock_dir = d
|
| 192 |
+
return self.sock_dir
|
| 193 |
+
|
| 194 |
+
def mcp_command(self, real_argv, env=None, label="mcp"):
|
| 195 |
+
"""-> (command, args) for the harness's MCP config: the relay on a new socket served by real_argv."""
|
| 196 |
+
d = self._sock_dir()
|
| 197 |
+
path = os.path.join(d, f"{label}-{len(self.relays)}.sock")
|
| 198 |
+
err = os.path.join(self.stderr_dir, f"jail_{label}_stderr.log") if self.stderr_dir else None
|
| 199 |
+
self.relays.append(_Relay(path, list(real_argv), dict(env or {"PATH": "/usr/bin:/bin"}), err, self.uid))
|
| 200 |
+
return RELAY_PYTHON, [RELAY, path]
|
| 201 |
+
|
| 202 |
+
def wrap(self, argv, env, cwd, rw_dirs):
|
| 203 |
+
"""The jailed argv. Popen it with the same env: the jail forwards exactly those variables. Chowns the
|
| 204 |
+
directories that are mounted back (one-time dirs only) to the jail uid."""
|
| 205 |
+
rw = _outermost(list(rw_dirs) + ([self.sock_dir] if self.sock_dir else []) + ([cwd] if cwd else []))
|
| 206 |
+
if len(rw) > MAX_BINDS:
|
| 207 |
+
raise JailError(f"too many bind mounts ({len(rw)} > {MAX_BINDS})")
|
| 208 |
+
for d in rw:
|
| 209 |
+
if not os.path.isdir(d):
|
| 210 |
+
raise JailError(f"bind source {d} is not a directory")
|
| 211 |
+
if not d.startswith(("/tmp/lffrun/", "/tmp/lffstate/", SOCK_ROOT + "/")):
|
| 212 |
+
raise JailError(f"refusing to mount {d} into the jail (only one-time dirs)")
|
| 213 |
+
_chown_tree(d, self.uid)
|
| 214 |
+
cmd = [self.binary_jailed if os.path.realpath(argv[0]) == self.binary_real else argv[0]] + list(argv[1:])
|
| 215 |
+
out = ["setpriv", f"--reuid={self.uid}", f"--regid={self.uid}", "--clear-groups", "--",
|
| 216 |
+
"unshare", "--user", "--map-root-user", "--mount", "--fork", "--kill-child",
|
| 217 |
+
INNER, "--keep", ",".join(sorted(env)), "--proc", self.proc]
|
| 218 |
+
for d in rw:
|
| 219 |
+
out += ["--rw", d]
|
| 220 |
+
return out + ["--cwd", cwd or "/", "--exe", self.binary_jailed, "--"] + cmd
|
| 221 |
+
|
| 222 |
+
def close(self):
|
| 223 |
+
for r in self.relays:
|
| 224 |
+
r.close()
|
| 225 |
+
self.relays = []
|
| 226 |
+
if self.sock_dir and self.sock_dir.startswith(SOCK_ROOT + "/"):
|
| 227 |
+
shutil.rmtree(self.sock_dir, ignore_errors=True)
|
| 228 |
+
self.sock_dir = None
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pinned launch fingerprints (fail-closed launch, docs/15 §0.4).
|
| 2 |
+
|
| 3 |
+
A pin says: "harness <name> at version <v> (binary sha256 <b>) with model <m> and effort <e> sends exactly this preset
|
| 4 |
+
prompt and tool list" (the normalised fingerprint of the first request, see claude_code.request_fingerprint /
|
| 5 |
+
codex.request_fingerprint). Pins are written only by tests/harness_selfcheck/selfcheck.py --write-pins after every
|
| 6 |
+
offline check passed for that adapter; a launch without a matching pin is refused.
|
| 7 |
+
|
| 8 |
+
Only hashes and sizes are stored here (the repo is public); the full fingerprint of each launch is in the run's
|
| 9 |
+
harness_preflight.json.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import re
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
PINS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pins")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def key(adapter, version, binary_sha, model, effort):
|
| 20 |
+
return f"{adapter}|{version}|{(binary_sha or 'nobin')[:16]}|{model}|{effort}"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _path(k, pins_dir=None):
|
| 24 |
+
return os.path.join(pins_dir or PINS_DIR, re.sub(r"[^A-Za-z0-9.-]+", "_", k) + ".json")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load(k, pins_dir=None):
|
| 28 |
+
p = _path(k, pins_dir)
|
| 29 |
+
if not os.path.exists(p):
|
| 30 |
+
return None
|
| 31 |
+
with open(p) as f:
|
| 32 |
+
return json.load(f)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def write(k, fingerprint_sha256, summary, pins_dir=None):
|
| 36 |
+
os.makedirs(pins_dir or PINS_DIR, exist_ok=True)
|
| 37 |
+
d = dict(key=k, fingerprint_sha256=fingerprint_sha256, written=time.strftime("%Y-%m-%d %H:%M:%S"), summary=summary)
|
| 38 |
+
with open(_path(k, pins_dir), "w") as f:
|
| 39 |
+
json.dump(d, f, indent=1)
|
| 40 |
+
return d
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/sensenova.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SenseNova-RoboRSI native Codex SDK planner, controlled MCP variant."""
|
| 2 |
+
from .framework_codex import RobotFrameworkCodex
|
| 3 |
+
|
| 4 |
+
class SenseNovaCodex(RobotFrameworkCodex):
|
| 5 |
+
name = "sensenova_codex"
|
| 6 |
+
runtime_home = "/mnt/cpfs/workspace/env/sensenova-roborsi"
|
| 7 |
+
|
| 8 |
+
def __init__(self, **kwargs):
|
| 9 |
+
kwargs.setdefault("sessions", 1)
|
| 10 |
+
kwargs.setdefault("attempts_per_session", 0)
|
| 11 |
+
if kwargs["sessions"] != 1 or kwargs["attempts_per_session"] != 0:
|
| 12 |
+
raise ValueError("SenseNova controlled variant uses one persistent session for all attempts")
|
| 13 |
+
super().__init__(**kwargs)
|
| 14 |
+
|
| 15 |
+
def env(self, state, ep, base_url, work):
|
| 16 |
+
env = super().env(state, ep, base_url, work)
|
| 17 |
+
env["LFF_CONTROLLED_CODEX"] = "1"
|
| 18 |
+
return env
|
| 19 |
+
|
| 20 |
+
def config_info(self):
|
| 21 |
+
info = super().config_info()
|
| 22 |
+
info.update(variant="native-codex-planner-mcp", max_sdk_steps=self.max_turns,
|
| 23 |
+
history="same-thread", cross_episode_memory=False)
|
| 24 |
+
return info
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_shelf_droop.py
ADDED
|
@@ -0,0 +1,1009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""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,
|
| 2 |
+
spring-loaded fold-down bracket with a weak catch: it stays level as long as the moment of its load about the hinge at
|
| 3 |
+
the wall is below the bracket's preload; once the load exceeds it the catch slips and the board folds down to its stop
|
| 4 |
+
within about a second, and the jars on it slide off its free edge onto the table, where they lie on their sides.
|
| 5 |
+
Jars set down in the middle of the board's depth -- where a careful agent puts them -- push the moment over the preload
|
| 6 |
+
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
|
| 7 |
+
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
|
| 8 |
+
(centres up to ~6 cm from it) stay under the preload. Unloaded, the board springs back level.
|
| 9 |
+
|
| 10 |
+
Family: long-horizon self-damage ("state_restoration"): a later stage (the third placement) undoes the earlier ones, a
|
| 11 |
+
moment after it was done, once the gripper has let go. Within an attempt the agent has to notice the fallen jars, stand
|
| 12 |
+
them up again (by their knobs) and put them back -- near the wall, or they slide off again; across attempts it has to
|
| 13 |
+
load the shelf near the wall. R4: "I put them down badly / dropped them too hard / my arm knocked them" vs "the shelf
|
| 14 |
+
gives way under a load far from the wall".
|
| 15 |
+
|
| 16 |
+
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,
|
| 17 |
+
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
|
| 18 |
+
the fourth jar, and the board drooped (or the jars slid off) only during the final settle, after `finish` -- 15 of 74
|
| 19 |
+
failing scripted attempts (20 %) showed nothing before finish; 4 jars 6 cm from the wall failed in 9 / 9 seeds. v2 raises
|
| 20 |
+
the preload (4 jars up to ~6 cm from the wall hold) and adds the catch + a soft spring + light damping, so every overload
|
| 21 |
+
folds the board down within a second, before the agent's next look.
|
| 22 |
+
|
| 23 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 24 |
+
* 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
|
| 25 |
+
x in [-0.17, -0.12]), rising 4.5 cm above the shelf board;
|
| 26 |
+
* 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
|
| 27 |
+
the wall face (axis along x at mid-thickness); hard stop at 25 deg of droop. The agentview camera (behind the table,
|
| 28 |
+
+x, looking at the robot) sees the board from its end, so the droop is an in-image rotation of the slab;
|
| 29 |
+
* 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;
|
| 30 |
+
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
|
| 31 |
+
cm), 9 cm apart, in random order.
|
| 32 |
+
|
| 33 |
+
Hidden variable: the bracket. "loose" (14 of every 20 consecutive seeds): preload 0.62-0.68 N m; "stiff" (6 of 20):
|
| 34 |
+
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
|
| 35 |
+
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.
|
| 36 |
+
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
|
| 37 |
+
with two or more jars on it nothing stops a board whose catch has slipped before its 25 deg stop. Jar-on-board friction
|
| 38 |
+
0.27-0.33 per jar (they slide at ~14.5 deg at 0.30 in MuJoCo's soft contacts).
|
| 39 |
+
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
|
| 40 |
+
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,
|
| 41 |
+
two 0.51 (holds), three 0.76 (over).
|
| 42 |
+
|
| 43 |
+
Repair: fallen jars lie on the table in front of the board's free edge. Held by the knob (ball, torsional friction
|
| 44 |
+
0.0005, condim 4) a lying jar turns between the fingers and hangs straight down (like lh_bystander's bottle cap); the
|
| 45 |
+
instruction says so. Put back near the wall, the board stays level.
|
| 46 |
+
|
| 47 |
+
Success (final-state judge after a settle of at least 15 s of simulated time with the arm holding still -- longer if
|
| 48 |
+
the board is still moving -- so that finishing right after the last placement does not beat the bracket): every jar
|
| 49 |
+
stands upright on the board (its bottom on the board's top, within its outline, axis within 10 deg of the board's
|
| 50 |
+
normal), not held; the board within 15 deg of level (a board that has folded down holds no standing jar anyway),
|
| 51 |
+
touched by nothing but the jars (closes "prop the board" loopholes), the gripper not touching a jar or the board, the
|
| 52 |
+
scene static.
|
| 53 |
+
|
| 54 |
+
Per-step monitor (server log only; F1 gives the agent success / failure): stage achieved / lost (cause: slid_off,
|
| 55 |
+
robot, jar:<colour>, picked_up, other) / restored per jar; board sag_start (> 1.5 deg), sag (> 8 deg = trap_fired) and
|
| 56 |
+
sag_end, each with the time since the placement that pushed the moment over the preload and the moment itself;
|
| 57 |
+
jar_fell (with the time since its own placement and since the sag started). outcome() also reports what the agent's
|
| 58 |
+
last images showed at `finish` (board angle, jars already off the board).
|
| 59 |
+
|
| 60 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 61 |
+
"""
|
| 62 |
+
import numpy as np
|
| 63 |
+
|
| 64 |
+
from .. import envs
|
| 65 |
+
from ..bddl import write_bddl
|
| 66 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 67 |
+
from ..skills import Skills
|
| 68 |
+
from ..task_base import LFFTask, register_task
|
| 69 |
+
|
| 70 |
+
TZ = envs.TABLE_Z
|
| 71 |
+
G = 9.81
|
| 72 |
+
DT = 0.05 # control period
|
| 73 |
+
|
| 74 |
+
# ---------------------------------------------------------------- jars (square glass jars with a ball knob on the lid)
|
| 75 |
+
COLOURS = ["red", "green", "blue", "yellow"]
|
| 76 |
+
JARS = [f"jar_{c}_1" for c in COLOURS]
|
| 77 |
+
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),
|
| 78 |
+
"yellow": (0.90, 0.72, 0.15, 1.0)}
|
| 79 |
+
LID_RGBA = (0.93, 0.93, 0.91, 1.0)
|
| 80 |
+
KNOB_RGBA = (0.22, 0.22, 0.24, 1.0)
|
| 81 |
+
JB = 0.025 # half width of the square body (5 x 5 cm)
|
| 82 |
+
BODY_H = 0.060
|
| 83 |
+
LID_H, LID_B = 0.008, 0.026 # lid height, half width
|
| 84 |
+
NECK_R, NECK_H = 0.006, 0.012
|
| 85 |
+
KNOB_R = 0.011
|
| 86 |
+
JAR_H = BODY_H + LID_H + NECK_H + 2 * KNOB_R # 0.102
|
| 87 |
+
KNOB_Z = BODY_H + LID_H + NECK_H + KNOB_R # knob centre above the jar's bottom (0.091)
|
| 88 |
+
JAR_COM = 0.026 # centre of mass above the bottom (a filled jar)
|
| 89 |
+
JAR_MASS = (0.24, 0.26)
|
| 90 |
+
JAR_MU = (0.27, 0.33) # jar body friction (per jar); the board's own is lower, so this one applies on the board
|
| 91 |
+
LID_MU = 0.8
|
| 92 |
+
KNOB_MU_T = 0.0005 # torsional friction of the knob (condim 4): a jar held by its knob swings down and hangs straight
|
| 93 |
+
JAR_ROT_DAMP = 0.004 # free-joint angular damping (air drag; damps the swing of a jar hanging from its knob)
|
| 94 |
+
|
| 95 |
+
# ---------------------------------------------------------------- shelf (fixture: wall panel + hinged board)
|
| 96 |
+
SHELF = "shelf_1"
|
| 97 |
+
SHELF_MODEL = "lff_lhs_shelf"
|
| 98 |
+
BOARD_L = 0.34 # along the wall (world x)
|
| 99 |
+
BOARD_D = 0.20 # depth, from the wall to the free edge
|
| 100 |
+
BOARD_T = 0.012
|
| 101 |
+
BOARD_TOP = 0.110 # top surface above the table when level
|
| 102 |
+
PANEL_T = 0.025
|
| 103 |
+
LIP = 0.045 # the wall rises this far above the board's top
|
| 104 |
+
BOARD_MASS = 0.30
|
| 105 |
+
BOARD_MU = 0.10 # (max rule: the jars' 0.27-0.33 applies)
|
| 106 |
+
GAP = 0.004 # board edge to the wall face (the board's lower corner swings towards the wall when it droops)
|
| 107 |
+
WOOD = (0.72, 0.55, 0.36, 1.0)
|
| 108 |
+
WALL_RGBA = (0.86, 0.86, 0.84, 1.0)
|
| 109 |
+
DROOP_MAX = np.radians(25.0) # hard stop of the hinge (at 28 deg the free edge would touch the table)
|
| 110 |
+
K_SPRING = 0.25 # N m / rad: the bracket's spring beyond the preload (soft: once the catch slips the board folds down)
|
| 111 |
+
LATCH = 0.12 # N m: part of the preload held by the bracket's catch, released over the first LATCH_TH of droop
|
| 112 |
+
LATCH_TH = np.radians(3.0)
|
| 113 |
+
PRELOAD_LOOSE = (0.62, 0.68) # N m (spring + catch at level)
|
| 114 |
+
PRELOAD_STIFF = 2.5
|
| 115 |
+
DAMPING = (0.45, 0.60) # N m s / rad
|
| 116 |
+
P_LOOSE = 0.70 # 14 of every 20 consecutive seeds
|
| 117 |
+
WALL_Y = (0.25, 0.27) # |y| of the wall face
|
| 118 |
+
SHELF_X = (-0.17, -0.12) # centre of the board along the wall
|
| 119 |
+
SLOT_U = (-0.12, -0.04, 0.04, 0.12) # slot positions along the board (scripted policies)
|
| 120 |
+
SUP_Y = (0.13, 0.17) # |y| of the supply row (other side of the table)
|
| 121 |
+
SUP_U = (-0.135, -0.045, 0.045, 0.135)
|
| 122 |
+
|
| 123 |
+
# predicates / monitor
|
| 124 |
+
TILT_OK = np.radians(10.0) # jar axis vs the board's normal
|
| 125 |
+
BOARD_OK = np.radians(15.0) # final judge: the board within 15 deg of level (jars slide off at ~13-16 deg)
|
| 126 |
+
SAG0 = np.radians(1.5) # sag_start
|
| 127 |
+
SAG_END = np.radians(0.5)
|
| 128 |
+
SAG_DEG = np.radians(8.0) # trap fired
|
| 129 |
+
DEBOUNCE = 10 # control steps (0.5 s)
|
| 130 |
+
SETTLE_MIN, SETTLE_MAX = 300, 600 # final judge: 15-30 s of simulated time with the arm holding still
|
| 131 |
+
|
| 132 |
+
# scripted motion
|
| 133 |
+
Z_CARRY = 0.25 # grasp point above the table while carrying a jar (its bottom then clears the board by ~5 cm)
|
| 134 |
+
R_MID = GAP + BOARD_D / 2 # 0.104: the middle of the board's depth (from the wall face)
|
| 135 |
+
R_BACK = JB + 0.010 # 0.035: a jar against the wall (1 cm gap)
|
| 136 |
+
NAIVE_BIAS = 0.010 # per instance: Sonnet aims at the middle +- 1 cm (towards the wall or the free edge)
|
| 137 |
+
NAIVE_RAND = 0.006 # per jar
|
| 138 |
+
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
|
| 139 |
+
# (Sonnet, lh_nudge_row pilot np2: 3.2-8.3 s, median 5.1 s)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def jar_xml(name, rgba):
|
| 143 |
+
h = JAR_H / 2
|
| 144 |
+
z0 = -h # bottom
|
| 145 |
+
m = 0.25
|
| 146 |
+
parts = [("body", "box", (0, 0, z0 + BODY_H / 2), (JB, JB, BODY_H / 2), rgba, 'friction="0.3 0.005 0.0001"'),
|
| 147 |
+
("lid", "box", (0, 0, z0 + BODY_H + LID_H / 2), (LID_B, LID_B, LID_H / 2), LID_RGBA,
|
| 148 |
+
f'friction="{LID_MU} 0.005 0.0001"'),
|
| 149 |
+
("neck", "cylinder", (0, 0, z0 + BODY_H + LID_H + NECK_H / 2), (NECK_R, NECK_H / 2), KNOB_RGBA,
|
| 150 |
+
f'friction="{LID_MU} 0.005 0.0001"'),
|
| 151 |
+
("knob", "sphere", (0, 0, z0 + KNOB_Z), (KNOB_R,), KNOB_RGBA,
|
| 152 |
+
f'friction="1 {KNOB_MU_T} 0.0001" condim="4" priority="2"')]
|
| 153 |
+
ixx = m * ((2 * JB) ** 2 + BODY_H ** 2) / 12
|
| 154 |
+
izz = m * (2 * (2 * JB) ** 2) / 12
|
| 155 |
+
s = [f' <inertial pos="0 0 {z0 + JAR_COM:.4f}" mass="{m}" diaginertia="{ixx:.3e} {ixx:.3e} {izz:.3e}" />']
|
| 156 |
+
for nm, typ, pos, size, c, extra in parts:
|
| 157 |
+
s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
|
| 158 |
+
f'{extra} group="0" />')
|
| 159 |
+
s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
|
| 160 |
+
f'conaffinity="0" group="1" />')
|
| 161 |
+
# a lighter label band on the body (visual only)
|
| 162 |
+
s.append(f' <geom type="box" pos="0 0 {z0 + BODY_H * 0.55:.4f}" size="{JB + 0.0006:.4f} {JB + 0.0006:.4f} 0.012" '
|
| 163 |
+
f'rgba="0.95 0.93 0.86 1" contype="0" conaffinity="0" group="1" />')
|
| 164 |
+
return _wrap(name, "\n".join(s), h, JB * 1.42)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def shelf_xml(name):
|
| 168 |
+
"""fixture frame: origin on the table top below the middle of the hinge line; local +y points from the wall towards
|
| 169 |
+
the board's free edge, local x along the wall. Wall panel (static) + board (child body on a hinge about -x at the
|
| 170 |
+
wall face, so a positive joint angle lowers the free edge). Wall and board do not collide with each other
|
| 171 |
+
(contype 2 / conaffinity 1); both collide with everything else."""
|
| 172 |
+
zc = BOARD_TOP - BOARD_T / 2 # hinge axis height (board mid-thickness)
|
| 173 |
+
wall_h = BOARD_TOP + LIP
|
| 174 |
+
hw = (BOARD_L + 0.04) / 2
|
| 175 |
+
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}" '
|
| 176 |
+
f'rgba="{_fmt(WALL_RGBA)}"')
|
| 177 |
+
g = [f'<geom name="{name}_wall" {wall} friction="0.6 0.005 0.0001" contype="2" conaffinity="1" group="0" />',
|
| 178 |
+
f'<geom {wall} contype="0" conaffinity="0" group="1" />']
|
| 179 |
+
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}" '
|
| 180 |
+
f'rgba="{_fmt(WOOD)}"')
|
| 181 |
+
b = [f'<inertial pos="0 {BOARD_D / 2 + GAP:.5f} 0" mass="{BOARD_MASS}" '
|
| 182 |
+
f'diaginertia="{BOARD_MASS * BOARD_D ** 2 / 12:.3e} {BOARD_MASS * BOARD_L ** 2 / 12:.3e} '
|
| 183 |
+
f'{BOARD_MASS * (BOARD_L ** 2 + BOARD_D ** 2) / 12:.3e}" />',
|
| 184 |
+
# stiffness / springref / damping are set per instance (apply_instance)
|
| 185 |
+
f'<joint name="hinge" type="hinge" axis="-1 0 0" pos="0 0 0" limited="true" range="0 {DROOP_MAX:.4f}" '
|
| 186 |
+
f'stiffness="{K_SPRING}" springref="-1" damping="3.0" armature="0.002" solreflimit="0.004 1" '
|
| 187 |
+
f'solimplimit="0.95 0.99 0.001" />',
|
| 188 |
+
f'<geom name="{name}_board" {slab} friction="{BOARD_MU} 0.005 0.0001" contype="2" conaffinity="1" '
|
| 189 |
+
f'group="0" />',
|
| 190 |
+
f'<geom {slab} contype="0" conaffinity="0" group="1" />',
|
| 191 |
+
# darker front edge strip and hinge barrel (visual)
|
| 192 |
+
f'<geom type="box" pos="0 {BOARD_D + GAP - 0.003:.5f} 0" size="{BOARD_L / 2 + 0.0005:.5f} 0.0032 '
|
| 193 |
+
f'{BOARD_T / 2 + 0.0005:.5f}" rgba="0.50 0.36 0.22 1" contype="0" conaffinity="0" group="1" />',
|
| 194 |
+
f'<geom type="cylinder" pos="0 0.004 {-BOARD_T / 2:.5f}" size="0.005 {BOARD_L / 2 - 0.01:.5f}" '
|
| 195 |
+
f'quat="0.70711 0 0.70711 0" rgba="0.55 0.55 0.58 1" contype="0" conaffinity="0" group="1" />']
|
| 196 |
+
nl = "\n "
|
| 197 |
+
return f"""<mujoco model="{name}">
|
| 198 |
+
<worldbody>
|
| 199 |
+
<body>
|
| 200 |
+
<body name="object">
|
| 201 |
+
{nl.join(g)}
|
| 202 |
+
<body name="board" pos="0 0 {zc:.5f}">
|
| 203 |
+
{nl.join(b)}
|
| 204 |
+
</body>
|
| 205 |
+
</body>
|
| 206 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 207 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {wall_h:.5f}" name="top_site" />
|
| 208 |
+
<site rgba="0 0 0 0" size="0.005" pos="{hw:.5f} {BOARD_D:.5f} 0" name="horizontal_radius_site" />
|
| 209 |
+
</body>
|
| 210 |
+
</worldbody>
|
| 211 |
+
</mujoco>
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _wrap_h(a):
|
| 216 |
+
"""wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)"""
|
| 217 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class DroopSkills(Skills):
|
| 221 |
+
"""Skills that feed the task's per-step monitor."""
|
| 222 |
+
|
| 223 |
+
def __init__(self, env, task, recorder=None):
|
| 224 |
+
super().__init__(env, recorder=recorder)
|
| 225 |
+
self.task = task
|
| 226 |
+
|
| 227 |
+
def _act(self, dpos, drot, grip):
|
| 228 |
+
super()._act(dpos, drot, grip)
|
| 229 |
+
self.task.monitor_step()
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
@register_task
|
| 233 |
+
class ShelfDroop(LFFTask):
|
| 234 |
+
name = "lh_shelf_droop"
|
| 235 |
+
level = "L2"
|
| 236 |
+
category = "state_restoration"
|
| 237 |
+
capabilities = ("Perceive", "Reason", "Restore", "Plan")
|
| 238 |
+
protocol = "cross"
|
| 239 |
+
max_attempts = 3
|
| 240 |
+
# careful: ~10 commands per jar (40) + standing up and re-placing three fallen jars (~40) + looking / corrections
|
| 241 |
+
agent_max_steps = 120
|
| 242 |
+
instruction = ("Put the four jars (red, green, blue, yellow) on the shelf. At the end all four must be standing "
|
| 243 |
+
"upright on the shelf board, and the gripper must be open and clear of the jars and the shelf. "
|
| 244 |
+
"(Each jar has a round knob on its lid; held by the knob, a jar hangs straight down.)")
|
| 245 |
+
instruction_indirect = ("Put the four little square jars with knobbed lids up on the wooden shelf by the wall. "
|
| 246 |
+
"When you are done, all of them have to stand upright on the shelf board, and the gripper "
|
| 247 |
+
"must be open and away from the jars and the shelf. (Held by its round knob, a jar hangs "
|
| 248 |
+
"straight down.)")
|
| 249 |
+
agent_object_names = ["jars (red, green, blue, yellow; each with a round knob on its lid -- held by the knob it "
|
| 250 |
+
"hangs straight down)", "wooden shelf board on the wall panel"]
|
| 251 |
+
|
| 252 |
+
# ------------------------------------------------------------ scene
|
| 253 |
+
def make_bddl(self):
|
| 254 |
+
objs = []
|
| 255 |
+
for i, (c, j) in enumerate(zip(COLOURS, JARS)):
|
| 256 |
+
cat = register_generated(f"LffLhsJar{c.capitalize()}", jar_xml(f"lff_lhs_jar_{c}", GLASS_RGBA[c]))
|
| 257 |
+
objs.append((j, cat, f"jar{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31)))
|
| 258 |
+
sh = register_generated("LffLhsShelf", shelf_xml(SHELF_MODEL), free=False)
|
| 259 |
+
fx = [(SHELF, sh, "shelf_region", (0.20, -0.31, 0.21, -0.30))] # moved in apply_instance
|
| 260 |
+
return write_bddl(self.name, "Put the four jars on the shelf", objs, fx)
|
| 261 |
+
|
| 262 |
+
def __init__(self, cam_res=None):
|
| 263 |
+
super().__init__(cam_res)
|
| 264 |
+
m = self.env.sim.model
|
| 265 |
+
self.shelf_bid = m.body_name2id(self.env.fixtures_dict[SHELF].root_body)
|
| 266 |
+
self.jid = m.joint_name2id(f"{SHELF}_hinge")
|
| 267 |
+
self.qa, self.da = int(m.jnt_qposadr[self.jid]), int(m.jnt_dofadr[self.jid])
|
| 268 |
+
self.board_bid = int(m.jnt_bodyid[self.jid])
|
| 269 |
+
pre = f"{SHELF}_{SHELF_MODEL}"
|
| 270 |
+
self.board_gid = m.geom_name2id(pre + "_board")
|
| 271 |
+
self.wall_gid = m.geom_name2id(pre + "_wall")
|
| 272 |
+
self.jgeoms = {j: envs.obj_geom_ids(self.env, j) for j in JARS}
|
| 273 |
+
self.jbid = {j: int(m.geom_bodyid[self.jgeoms[j][0]]) for j in JARS} # body that carries the inertial
|
| 274 |
+
self.body_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_body") for c, j in zip(COLOURS, JARS)}
|
| 275 |
+
self.knob_gid = {j: m.geom_name2id(f"{j}_lff_lhs_jar_{c}_knob") for c, j in zip(COLOURS, JARS)}
|
| 276 |
+
self.jdof = {j: envs.free_joint_addr(self.env, j)[1] for j in JARS}
|
| 277 |
+
# per-geom lookup tables for the substep contact check
|
| 278 |
+
self.owner = np.full(m.ngeom, -1, int) # jar index
|
| 279 |
+
for i, j in enumerate(JARS):
|
| 280 |
+
self.owner[self.jgeoms[j]] = i
|
| 281 |
+
self.is_robot = np.zeros(m.ngeom, bool)
|
| 282 |
+
self.is_robot[envs.robot_geom_ids(self.env)] = True
|
| 283 |
+
self.is_board = np.zeros(m.ngeom, bool)
|
| 284 |
+
self.is_board[self.board_gid] = True
|
| 285 |
+
self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set()
|
| 286 |
+
sim = self.env.sim
|
| 287 |
+
if not getattr(sim, "_lhs_wrapped", False):
|
| 288 |
+
orig = sim.step
|
| 289 |
+
|
| 290 |
+
def step(*a, **k):
|
| 291 |
+
orig(*a, **k)
|
| 292 |
+
t = getattr(sim, "_lhs_task", None)
|
| 293 |
+
if t is not None:
|
| 294 |
+
t._bracket()
|
| 295 |
+
if t.mon is not None:
|
| 296 |
+
t._substep()
|
| 297 |
+
sim.step = step
|
| 298 |
+
sim._lhs_wrapped = True
|
| 299 |
+
sim._lhs_task = self
|
| 300 |
+
self.inst = None
|
| 301 |
+
self.mon = None
|
| 302 |
+
self.sk = None
|
| 303 |
+
|
| 304 |
+
def _bracket(self):
|
| 305 |
+
"""the bracket's catch (every MuJoCo substep): a torque holding the board up that fades out over the first
|
| 306 |
+
LATCH_TH of droop, so a board that starts to droop does not stop part-way but folds down to its stop"""
|
| 307 |
+
d = self.env.sim.data
|
| 308 |
+
th = float(d.qpos[self.qa])
|
| 309 |
+
d.qfrc_applied[self.da] = -LATCH * float(np.clip(1.0 - th / LATCH_TH, 0.0, 1.0))
|
| 310 |
+
|
| 311 |
+
def _substep(self):
|
| 312 |
+
d = self.env.sim.data
|
| 313 |
+
n = d.ncon
|
| 314 |
+
if not n:
|
| 315 |
+
return
|
| 316 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 317 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 318 |
+
for a, b in zip(g1, g2):
|
| 319 |
+
pa, pb = self.owner[a], self.owner[b]
|
| 320 |
+
if self.is_board[a] or self.is_board[b]:
|
| 321 |
+
o = b if self.is_board[a] else a
|
| 322 |
+
if self.owner[o] < 0: # the board touched by something that is not a jar (robot, table, ...)
|
| 323 |
+
self._sub_board.add("robot" if self.is_robot[o] else (self.env.sim.model.geom_id2name(int(o)) or "?"))
|
| 324 |
+
continue
|
| 325 |
+
if pa < 0 and pb < 0:
|
| 326 |
+
continue
|
| 327 |
+
if pa >= 0 and pb >= 0:
|
| 328 |
+
if pa != pb:
|
| 329 |
+
self._sub_obj[int(pa)] = int(pb)
|
| 330 |
+
self._sub_obj[int(pb)] = int(pa)
|
| 331 |
+
continue
|
| 332 |
+
p, o = (pa, b) if pa >= 0 else (pb, a)
|
| 333 |
+
if self.is_robot[o]:
|
| 334 |
+
self._sub_rob[int(p)] = True
|
| 335 |
+
|
| 336 |
+
# ------------------------------------------------------------ instances
|
| 337 |
+
def sample_instance(self, seed):
|
| 338 |
+
rng = np.random.default_rng(seed)
|
| 339 |
+
loose = bool((int(seed) * 7) % 20 < round(20 * P_LOOSE)) # balanced: 14 of every 20 consecutive seeds
|
| 340 |
+
side = "right" if rng.random() < 0.5 else "left" # where the wall stands (robot's view)
|
| 341 |
+
s = -1.0 if side == "right" else 1.0
|
| 342 |
+
x0 = float(rng.uniform(*SHELF_X))
|
| 343 |
+
yw = float(rng.uniform(*WALL_Y))
|
| 344 |
+
preload = float(rng.uniform(*PRELOAD_LOOSE)) if loose else PRELOAD_STIFF
|
| 345 |
+
damping = float(rng.uniform(*DAMPING))
|
| 346 |
+
ys = -s * float(rng.uniform(*SUP_Y))
|
| 347 |
+
order = rng.permutation(4)
|
| 348 |
+
start = {COLOURS[i]: [float(x0 + SUP_U[order[i]] + rng.uniform(-0.01, 0.01)), float(ys + rng.uniform(-0.008, 0.008))]
|
| 349 |
+
for i in range(4)}
|
| 350 |
+
yaw0 = {c: float(rng.uniform(-0.3, 0.3)) for c in COLOURS}
|
| 351 |
+
mu = {c: float(rng.uniform(*JAR_MU)) for c in COLOURS}
|
| 352 |
+
mass = {c: float(rng.uniform(*JAR_MASS)) for c in COLOURS}
|
| 353 |
+
return dict(seed=int(seed), loose=loose, bracket="loose" if loose else "stiff", side=side, shelf_x=x0,
|
| 354 |
+
wall_y=float(s * yw), preload=preload, damping=damping, stiffness=K_SPRING, start=start, yaw0=yaw0,
|
| 355 |
+
mu=mu, mass=mass, naive_bias=float(rng.uniform(-NAIVE_BIAS, NAIVE_BIAS)))
|
| 356 |
+
|
| 357 |
+
def apply_instance(self, inst):
|
| 358 |
+
self.inst = inst
|
| 359 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 360 |
+
s = -1.0 if inst["side"] == "right" else 1.0
|
| 361 |
+
# fixture local +y (towards the free edge) = world -s*y
|
| 362 |
+
m.body_pos[self.shelf_bid] = [inst["shelf_x"], inst["wall_y"], TZ]
|
| 363 |
+
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]
|
| 364 |
+
wb = BOARD_MASS * G * (BOARD_D / 2 + GAP) # the board's own weight about the hinge
|
| 365 |
+
m.jnt_stiffness[self.jid] = inst["stiffness"]
|
| 366 |
+
# spring + catch hold the board level up to a load moment of `preload` (the catch's part fades with the droop)
|
| 367 |
+
m.qpos_spring[self.qa] = -(inst["preload"] - LATCH + wb) / inst["stiffness"]
|
| 368 |
+
m.dof_damping[self.da] = inst["damping"]
|
| 369 |
+
d.qpos[self.qa] = 0.0
|
| 370 |
+
d.qvel[self.da] = 0.0
|
| 371 |
+
d.qfrc_applied[self.da] = -LATCH
|
| 372 |
+
for c, j in zip(COLOURS, JARS):
|
| 373 |
+
b = self.jbid[j]
|
| 374 |
+
M = inst["mass"][c]
|
| 375 |
+
m.body_mass[b] = M
|
| 376 |
+
m.body_inertia[b] = [M * ((2 * JB) ** 2 + BODY_H ** 2) / 12] * 2 + [M * (2 * JB) ** 2 / 6]
|
| 377 |
+
m.geom_friction[self.body_gid[j]] = [inst["mu"][c], 0.005, 0.0001]
|
| 378 |
+
m.dof_damping[self.jdof[j] + 3:self.jdof[j] + 6] = JAR_ROT_DAMP
|
| 379 |
+
self.env.sim.forward()
|
| 380 |
+
for c, j in zip(COLOURS, JARS):
|
| 381 |
+
envs.place_upright(self.env, j, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
|
| 382 |
+
|
| 383 |
+
def reset_instance(self, inst, recorder=None):
|
| 384 |
+
self.mon = None
|
| 385 |
+
self.env.reset()
|
| 386 |
+
self.apply_instance(inst)
|
| 387 |
+
self.env.sim.forward()
|
| 388 |
+
envs.settle(self.env, 15)
|
| 389 |
+
self.sk = DroopSkills(self.env, self, recorder=recorder)
|
| 390 |
+
self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set()
|
| 391 |
+
n = len(JARS)
|
| 392 |
+
self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, lost_cause=[None] * n,
|
| 393 |
+
events=[], last_robot=[None] * n, last_obj=[None] * n, placed_step=[None] * n,
|
| 394 |
+
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,
|
| 395 |
+
fell_in_sag=[], max_deg=0.0, board_touch=[], n_steps=0, finish_step=None)
|
| 396 |
+
return self.sk
|
| 397 |
+
|
| 398 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 399 |
+
def angle(self):
|
| 400 |
+
return float(self.env.sim.data.qpos[self.qa])
|
| 401 |
+
|
| 402 |
+
def board_frame(self):
|
| 403 |
+
d = self.env.sim.data
|
| 404 |
+
return d.xpos[self.board_bid].copy(), d.xmat[self.board_bid].reshape(3, 3).copy()
|
| 405 |
+
|
| 406 |
+
def to_board(self, p):
|
| 407 |
+
o, R = self.board_frame()
|
| 408 |
+
return R.T @ (np.asarray(p, float) - o)
|
| 409 |
+
|
| 410 |
+
def board_point(self, u, r, h=BOARD_T / 2):
|
| 411 |
+
"""world point at (u along the wall, r from the hinge across the board, h above the hinge axis) in the board
|
| 412 |
+
frame"""
|
| 413 |
+
o, R = self.board_frame()
|
| 414 |
+
return o + R @ np.array([u, r, h])
|
| 415 |
+
|
| 416 |
+
def level_point(self, u, r):
|
| 417 |
+
"""world xy of board coordinates (u, r) with the board level (planning)"""
|
| 418 |
+
s = -1.0 if self.inst["side"] == "right" else 1.0
|
| 419 |
+
return np.array([self.inst["shelf_x"] - s * u, self.inst["wall_y"] - s * r])
|
| 420 |
+
|
| 421 |
+
def board_top_z(self):
|
| 422 |
+
return TZ + BOARD_TOP
|
| 423 |
+
|
| 424 |
+
def jar_axis(self, j):
|
| 425 |
+
return self.env.sim.data.xmat[self.jbid[j]].reshape(3, 3)[:, 2].copy()
|
| 426 |
+
|
| 427 |
+
def jar_bottom(self, j):
|
| 428 |
+
return envs.obj_pos(self.env, j) - self.jar_axis(j) * JAR_H / 2
|
| 429 |
+
|
| 430 |
+
def knob_xyz(self, j):
|
| 431 |
+
return self.env.sim.data.geom_xpos[self.knob_gid[j]].copy()
|
| 432 |
+
|
| 433 |
+
def tilt(self, j):
|
| 434 |
+
return float(np.arccos(np.clip(self.jar_axis(j)[2], -1.0, 1.0)))
|
| 435 |
+
|
| 436 |
+
def held(self, j):
|
| 437 |
+
return self.sk is not None and self.sk.holding(j)
|
| 438 |
+
|
| 439 |
+
def on_board(self, i, extra=0.0):
|
| 440 |
+
"""jar i stands on the shelf board: its bottom (centre) on the board's top, within the board's outline, its
|
| 441 |
+
axis within 10 deg of the board's normal, not held"""
|
| 442 |
+
j = JARS[i]
|
| 443 |
+
o, R = self.board_frame()
|
| 444 |
+
ax = R.T @ self.jar_axis(j)
|
| 445 |
+
if ax[2] < np.cos(TILT_OK + extra * 5):
|
| 446 |
+
return False
|
| 447 |
+
bc = R.T @ (self.jar_bottom(j) - o)
|
| 448 |
+
if not (BOARD_T / 2 - 0.004 <= bc[2] <= BOARD_T / 2 + 0.005 + extra):
|
| 449 |
+
return False
|
| 450 |
+
if abs(bc[0]) > BOARD_L / 2 + extra or not (GAP - extra <= bc[1] <= GAP + BOARD_D + extra):
|
| 451 |
+
return False
|
| 452 |
+
return not self.held(j)
|
| 453 |
+
|
| 454 |
+
def stages(self):
|
| 455 |
+
return [self.on_board(i) for i in range(len(JARS))]
|
| 456 |
+
|
| 457 |
+
def lever(self, j):
|
| 458 |
+
"""horizontal distance (m) of the jar's centre of mass from the hinge line, towards the free edge"""
|
| 459 |
+
o, R = self.board_frame()
|
| 460 |
+
n = R[:, 1].copy()
|
| 461 |
+
n[2] = 0.0
|
| 462 |
+
n /= max(np.linalg.norm(n), 1e-9)
|
| 463 |
+
return float((self.env.sim.data.xipos[self.jbid[j]] - o) @ n)
|
| 464 |
+
|
| 465 |
+
def moment(self, only_state=True):
|
| 466 |
+
"""load moment (N m) of the jars standing on the board about the hinge"""
|
| 467 |
+
mon = self.mon
|
| 468 |
+
tot = 0.0
|
| 469 |
+
for i, j in enumerate(JARS):
|
| 470 |
+
on = mon["state"][i] if (only_state and mon is not None) else self.on_board(i)
|
| 471 |
+
if on:
|
| 472 |
+
tot += self.inst["mass"][COLOURS[i]] * G * self.lever(j)
|
| 473 |
+
return float(tot)
|
| 474 |
+
|
| 475 |
+
def r_cm(self, i):
|
| 476 |
+
"""distance of jar i's bottom centre from the wall face (cm), in the board frame"""
|
| 477 |
+
return 100 * float(self.to_board(self.jar_bottom(JARS[i]))[1])
|
| 478 |
+
|
| 479 |
+
# ------------------------------------------------------------ monitor
|
| 480 |
+
def _t(self):
|
| 481 |
+
return int(self.sk.n_steps) if self.sk is not None else 0
|
| 482 |
+
|
| 483 |
+
def monitor_step(self):
|
| 484 |
+
mon = self.mon
|
| 485 |
+
if mon is None or self.sk is None:
|
| 486 |
+
return
|
| 487 |
+
mon["n_steps"] += 1
|
| 488 |
+
t = self._t()
|
| 489 |
+
rob, obj, brd = dict(self._sub_rob), dict(self._sub_obj), set(self._sub_board)
|
| 490 |
+
self._sub_rob, self._sub_obj, self._sub_board = {}, {}, set()
|
| 491 |
+
for i in rob:
|
| 492 |
+
if not self.held(JARS[i]):
|
| 493 |
+
mon["last_robot"][i] = int(t)
|
| 494 |
+
for i, k in obj.items():
|
| 495 |
+
mon["last_obj"][i] = [COLOURS[k], int(t)]
|
| 496 |
+
for b in brd:
|
| 497 |
+
if b not in mon["board_touch"]:
|
| 498 |
+
mon["board_touch"].append(b)
|
| 499 |
+
mon["_board_touch_now"] = sorted(brd)
|
| 500 |
+
th = self.angle()
|
| 501 |
+
mon["max_deg"] = max(mon["max_deg"], float(np.degrees(th)))
|
| 502 |
+
if th > np.radians(5.0):
|
| 503 |
+
mon["droop_t"] = int(t) # last step with the board drooped > 5 deg (it springs back once the jars are off)
|
| 504 |
+
self._sag(th, t)
|
| 505 |
+
if mon["n_steps"] % 2:
|
| 506 |
+
return
|
| 507 |
+
for i in range(len(JARS)):
|
| 508 |
+
raw = self.on_board(i, 0.002 if mon["state"][i] else 0.0)
|
| 509 |
+
if raw and not mon["raw_prev"][i]:
|
| 510 |
+
mon["raw_on"][i] = int(t) # set down on the board (raw; the stage event below is debounced)
|
| 511 |
+
mon["raw_prev"][i] = raw
|
| 512 |
+
if raw == mon["state"][i]:
|
| 513 |
+
mon["raw_since"][i] = 0
|
| 514 |
+
continue
|
| 515 |
+
mon["raw_since"][i] += 2
|
| 516 |
+
if mon["raw_since"][i] < DEBOUNCE:
|
| 517 |
+
continue
|
| 518 |
+
mon["state"][i] = raw
|
| 519 |
+
mon["raw_since"][i] = 0
|
| 520 |
+
t0 = int(t - DEBOUNCE + 1)
|
| 521 |
+
c = COLOURS[i]
|
| 522 |
+
if raw:
|
| 523 |
+
restored = mon["lost"][i]
|
| 524 |
+
e = dict(stage=c, event="restored" if restored else "achieved", step=t0,
|
| 525 |
+
r_cm=round(self.r_cm(i), 1), moment_Nm=round(self.moment(), 3))
|
| 526 |
+
if restored:
|
| 527 |
+
e["after"] = mon["lost_cause"][i]
|
| 528 |
+
mon["events"].append(e)
|
| 529 |
+
mon["ever"][i] = True
|
| 530 |
+
mon["placed_step"][i] = t0
|
| 531 |
+
mon["last_place"] = (c, t0)
|
| 532 |
+
else:
|
| 533 |
+
mon["lost"][i] = True
|
| 534 |
+
cause = self._cause(i, t)
|
| 535 |
+
mon["lost_cause"][i] = cause
|
| 536 |
+
e = dict(stage=c, event="lost", step=t0, cause=cause, board_deg=round(float(np.degrees(th)), 1))
|
| 537 |
+
mon["events"].append(e)
|
| 538 |
+
if cause == "slid_off":
|
| 539 |
+
ps = mon["placed_step"][i]
|
| 540 |
+
ss = mon["sag_start"]["step"] if mon["sag_start"] else None
|
| 541 |
+
sc = mon.get("sag_cause")
|
| 542 |
+
mon["events"].append(dict(jar=c, event="jar_fell", step=t0,
|
| 543 |
+
dt_since_placed_s=None if ps is None else round((t0 - ps) * DT, 2),
|
| 544 |
+
dt_since_sag_start_s=None if ss is None else round((t0 - ss) * DT, 2),
|
| 545 |
+
after_placing=None if sc is None else sc[0],
|
| 546 |
+
dt_since_cause_s=None if sc is None else round((t0 - sc[1]) * DT, 2),
|
| 547 |
+
in_final_settle=mon["finish_step"] is not None,
|
| 548 |
+
board_deg=round(float(np.degrees(th)), 1)))
|
| 549 |
+
mon["fell_in_sag"].append(c)
|
| 550 |
+
|
| 551 |
+
def _sag(self, th, t):
|
| 552 |
+
mon = self.mon
|
| 553 |
+
if not mon["in_sag"]:
|
| 554 |
+
if th > SAG0:
|
| 555 |
+
mon["in_sag"] = True
|
| 556 |
+
mon["sag_fired"] = False
|
| 557 |
+
mon["sag_max"] = th
|
| 558 |
+
mon["fell_in_sag"] = []
|
| 559 |
+
lp = self._last_set_down(t)
|
| 560 |
+
mon["sag_cause"] = lp
|
| 561 |
+
e = dict(event="sag_start", step=int(t), board_deg=round(float(np.degrees(th)), 2),
|
| 562 |
+
moment_Nm=round(self.moment(only_state=False), 3),
|
| 563 |
+
preload_Nm=round(float(self.inst["preload"]), 3),
|
| 564 |
+
after_placing=None if lp is None else lp[0],
|
| 565 |
+
dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2),
|
| 566 |
+
n_on_board=int(sum(self.on_board(i) for i in range(len(JARS)))))
|
| 567 |
+
mon["sag_start"] = e
|
| 568 |
+
mon["events"].append(e)
|
| 569 |
+
return
|
| 570 |
+
mon["sag_max"] = max(mon["sag_max"], th)
|
| 571 |
+
if not mon["sag_fired"] and th > SAG_DEG:
|
| 572 |
+
mon["sag_fired"] = True
|
| 573 |
+
mon["n_sag"] += 1
|
| 574 |
+
ss = mon["sag_start"]
|
| 575 |
+
lp = self._last_set_down(t) # the placement that drove the board past 8 deg (sag_start may be earlier:
|
| 576 |
+
mon["sag_cause"] = lp # two jars in the middle already make it creep a few degrees)
|
| 577 |
+
mon["events"].append(dict(event="sag", step=int(t), board_deg=round(float(np.degrees(th)), 2),
|
| 578 |
+
moment_Nm=round(self.moment(only_state=False), 3),
|
| 579 |
+
after_placing=None if lp is None else lp[0],
|
| 580 |
+
sag_start_after=ss["after_placing"],
|
| 581 |
+
dt_since_placement_s=None if lp is None else round((t - lp[1]) * DT, 2),
|
| 582 |
+
dt_since_sag_start_s=round((t - ss["step"]) * DT, 2),
|
| 583 |
+
in_final_settle=mon["finish_step"] is not None))
|
| 584 |
+
mon["below"] = mon.get("below", 0) + 1 if th < SAG_END else 0
|
| 585 |
+
if mon["below"] >= 2 * DEBOUNCE: # back level for 1 s (the jars that slid off have been registered)
|
| 586 |
+
mon["in_sag"] = False
|
| 587 |
+
mon["below"] = 0
|
| 588 |
+
mon["events"].append(dict(event="sag_end", step=int(t), max_deg=round(float(np.degrees(mon["sag_max"])), 1),
|
| 589 |
+
fell=list(mon["fell_in_sag"]),
|
| 590 |
+
duration_s=round((t - mon["sag_start"]["step"]) * DT, 2)))
|
| 591 |
+
|
| 592 |
+
def _last_set_down(self, t):
|
| 593 |
+
"""(colour, step) of the jar most recently set down on the board (raw predicate) that still stands on it"""
|
| 594 |
+
mon = self.mon
|
| 595 |
+
cands = [(mon["raw_on"][i], COLOURS[i]) for i in range(len(JARS))
|
| 596 |
+
if mon["raw_on"][i] is not None and mon["raw_prev"][i] and mon["raw_on"][i] <= t]
|
| 597 |
+
if not cands:
|
| 598 |
+
return None
|
| 599 |
+
st, c = max(cands)
|
| 600 |
+
return (c, st)
|
| 601 |
+
|
| 602 |
+
def _cause(self, i, t, window=60):
|
| 603 |
+
mon = self.mon
|
| 604 |
+
if self.held(JARS[i]):
|
| 605 |
+
return "picked_up"
|
| 606 |
+
if (mon["in_sag"] and mon["sag_max"] > np.radians(5.0)) or (mon.get("droop_t") is not None
|
| 607 |
+
and t - mon["droop_t"] <= window):
|
| 608 |
+
return "slid_off"
|
| 609 |
+
lr, lo = mon["last_robot"][i], mon["last_obj"][i]
|
| 610 |
+
if lr is not None and t - lr <= window:
|
| 611 |
+
return "robot"
|
| 612 |
+
if lo is not None and t - lo[1] <= window:
|
| 613 |
+
return "jar:" + lo[0]
|
| 614 |
+
return "other"
|
| 615 |
+
|
| 616 |
+
def _finalize_monitor(self, raw):
|
| 617 |
+
mon = self.mon
|
| 618 |
+
t = self._t()
|
| 619 |
+
for i in range(len(JARS)):
|
| 620 |
+
if raw[i] == mon["state"][i]:
|
| 621 |
+
continue
|
| 622 |
+
mon["state"][i] = raw[i]
|
| 623 |
+
c = COLOURS[i]
|
| 624 |
+
if raw[i]:
|
| 625 |
+
restored = mon["lost"][i]
|
| 626 |
+
e = dict(stage=c, event="restored" if restored else "achieved", step=t, final=True)
|
| 627 |
+
if restored:
|
| 628 |
+
e["after"] = mon["lost_cause"][i]
|
| 629 |
+
mon["events"].append(e)
|
| 630 |
+
mon["ever"][i] = True
|
| 631 |
+
else:
|
| 632 |
+
mon["lost"][i] = True
|
| 633 |
+
cause = self._cause(i, t, window=10 ** 6)
|
| 634 |
+
mon["lost_cause"][i] = cause
|
| 635 |
+
mon["events"].append(dict(stage=c, event="lost", step=t, cause=cause, final=True))
|
| 636 |
+
|
| 637 |
+
# ------------------------------------------------------------ outcome
|
| 638 |
+
def _touching(self):
|
| 639 |
+
d = self.env.sim.data
|
| 640 |
+
jar_touch, board_touch = False, False
|
| 641 |
+
for k in range(d.ncon):
|
| 642 |
+
c = d.contact[k]
|
| 643 |
+
a, b = c.geom1, c.geom2
|
| 644 |
+
if (self.is_robot[a] and self.owner[b] >= 0) or (self.is_robot[b] and self.owner[a] >= 0):
|
| 645 |
+
jar_touch = True
|
| 646 |
+
if (self.is_robot[a] and self.is_board[b]) or (self.is_robot[b] and self.is_board[a]):
|
| 647 |
+
board_touch = True
|
| 648 |
+
return jar_touch, board_touch
|
| 649 |
+
|
| 650 |
+
def _moving(self):
|
| 651 |
+
d = self.env.sim.data
|
| 652 |
+
if abs(float(d.qvel[self.da])) > np.radians(0.3):
|
| 653 |
+
return True
|
| 654 |
+
for j in JARS:
|
| 655 |
+
da = self.jdof[j]
|
| 656 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.01 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.3:
|
| 657 |
+
return True
|
| 658 |
+
return False
|
| 659 |
+
|
| 660 |
+
def outcome(self, inst):
|
| 661 |
+
sk = self.sk
|
| 662 |
+
mon = self.mon
|
| 663 |
+
mon["finish_step"] = self._t()
|
| 664 |
+
# what the agent's last images show (finish returns no image): board angle and the jars already off the board
|
| 665 |
+
th_fin = self.angle()
|
| 666 |
+
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])]
|
| 667 |
+
max_fin = float(mon["max_deg"])
|
| 668 |
+
# settle with the arm holding still: >= 15 s of simulated time, up to 30 s while the board or a jar still moves
|
| 669 |
+
# (the droop is slow: finishing right after the last placement must not beat it)
|
| 670 |
+
n = 0
|
| 671 |
+
while n < SETTLE_MAX:
|
| 672 |
+
sk.hold(10)
|
| 673 |
+
n += 10
|
| 674 |
+
if n >= SETTLE_MIN and not self._moving() and not mon["in_sag"]:
|
| 675 |
+
break
|
| 676 |
+
settle_s = n * DT
|
| 677 |
+
p0 = {j: envs.obj_pos(self.env, j) for j in JARS}
|
| 678 |
+
th0 = self.angle()
|
| 679 |
+
jar_touch = board_touch = False
|
| 680 |
+
board_other = set()
|
| 681 |
+
for _ in range(20):
|
| 682 |
+
sk.hold(1)
|
| 683 |
+
jt, bt = self._touching()
|
| 684 |
+
jar_touch, board_touch = jar_touch or jt, board_touch or bt
|
| 685 |
+
board_other |= {b for b in mon.get("_board_touch_now", []) if b != "robot"}
|
| 686 |
+
moved = max(float(np.linalg.norm(envs.obj_pos(self.env, j) - p0[j])) for j in JARS)
|
| 687 |
+
static = moved < 0.003 and abs(self.angle() - th0) < np.radians(0.3)
|
| 688 |
+
raw = self.stages()
|
| 689 |
+
self._finalize_monitor(raw)
|
| 690 |
+
th = self.angle()
|
| 691 |
+
held = [COLOURS[i] for i, j in enumerate(JARS) if self.held(j)]
|
| 692 |
+
level = th <= BOARD_OK
|
| 693 |
+
propped = sorted(board_other)
|
| 694 |
+
success = bool(all(raw) and level and static and not held and not jar_touch and not board_touch and not propped)
|
| 695 |
+
ev = list(mon["events"])
|
| 696 |
+
n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
|
| 697 |
+
n_lost = sum(e.get("event") == "lost" for e in ev)
|
| 698 |
+
n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
|
| 699 |
+
fell = [e for e in ev if e.get("event") == "jar_fell"]
|
| 700 |
+
sags = [e for e in ev if e.get("event") == "sag"]
|
| 701 |
+
sag_vis = [e for e in sags if not e.get("in_final_settle")]
|
| 702 |
+
starts = [e for e in ev if e.get("event") == "sag_start"]
|
| 703 |
+
ever = mon["ever"]
|
| 704 |
+
lost_final = [i for i in range(4) if not raw[i] and ever[i]]
|
| 705 |
+
never = [i for i in range(4) if not raw[i] and not ever[i]]
|
| 706 |
+
if success:
|
| 707 |
+
failure = "none"
|
| 708 |
+
elif held:
|
| 709 |
+
failure = "held"
|
| 710 |
+
elif propped or board_touch:
|
| 711 |
+
failure = "propped"
|
| 712 |
+
elif jar_touch:
|
| 713 |
+
failure = "touching"
|
| 714 |
+
elif lost_final:
|
| 715 |
+
causes = {mon["lost_cause"][i] for i in lost_final}
|
| 716 |
+
failure = ("slid_off" if "slid_off" in causes else "knocked_off" if "robot" in causes else "regressed")
|
| 717 |
+
elif never:
|
| 718 |
+
failure = "not_on_shelf"
|
| 719 |
+
elif not level:
|
| 720 |
+
failure = "board_drooped"
|
| 721 |
+
else:
|
| 722 |
+
failure = "not_static"
|
| 723 |
+
# ---- F2 text
|
| 724 |
+
parts = []
|
| 725 |
+
if success:
|
| 726 |
+
parts.append("All four jars stand upright on the shelf board.")
|
| 727 |
+
for i in range(4):
|
| 728 |
+
if raw[i]:
|
| 729 |
+
continue
|
| 730 |
+
c, j = COLOURS[i], JARS[i]
|
| 731 |
+
if c in held:
|
| 732 |
+
parts.append(f"The {c} jar is still held by the gripper.")
|
| 733 |
+
continue
|
| 734 |
+
pb = self.to_board(self.jar_bottom(j))
|
| 735 |
+
lying = self.tilt(j) > np.radians(45)
|
| 736 |
+
if pb[2] < -0.02: # below the board: on the table
|
| 737 |
+
where = "lies on its side on the table" if lying else "stands on the table"
|
| 738 |
+
dist = 100 * float(pb[1] - (GAP + BOARD_D))
|
| 739 |
+
txt = f"The {c} jar {where}" + (f", {dist:.0f} cm out from the shelf's front edge." if dist > 0
|
| 740 |
+
else ", under the shelf.")
|
| 741 |
+
elif lying:
|
| 742 |
+
txt = f"The {c} jar lies on its side on the shelf board."
|
| 743 |
+
else:
|
| 744 |
+
txt = f"The {c} jar is not standing on the shelf board."
|
| 745 |
+
if ever[i]:
|
| 746 |
+
why = mon["lost_cause"][i]
|
| 747 |
+
txt += {"slid_off": " It had stood on the shelf; it slid off when the shelf board drooped under the load.",
|
| 748 |
+
"robot": " It had stood on the shelf; the robot knocked it off.",
|
| 749 |
+
}.get(why, " It had stood on the shelf earlier.")
|
| 750 |
+
parts.append(txt)
|
| 751 |
+
if all(raw) and not success:
|
| 752 |
+
if not level:
|
| 753 |
+
parts.append(f"The shelf board droops by {np.degrees(th):.0f} degrees.")
|
| 754 |
+
if held:
|
| 755 |
+
pass
|
| 756 |
+
elif jar_touch or board_touch:
|
| 757 |
+
parts.append("The gripper is still touching " + ("a jar." if jar_touch else "the shelf board."))
|
| 758 |
+
elif propped:
|
| 759 |
+
parts.append("The shelf board rests on something below it.")
|
| 760 |
+
elif not static:
|
| 761 |
+
parts.append("Something was still moving.")
|
| 762 |
+
if sags:
|
| 763 |
+
parts.append(f"During the attempt the shelf board drooped {len(sags)} time(s) (down to {mon['max_deg']:.0f} "
|
| 764 |
+
f"degrees) and {len(fell)} time(s) a jar slid off; {n_res} time(s) a jar was put back.")
|
| 765 |
+
trap = bool(sags)
|
| 766 |
+
lp = lambda e: e.get("dt_since_placement_s") # noqa: E731
|
| 767 |
+
return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(4)}, events=ev,
|
| 768 |
+
n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_fell=len(fell),
|
| 769 |
+
n_sag=len(sags), trap_fired=trap, sag_visible=bool(sag_vis),
|
| 770 |
+
recovered_in_attempt=bool(trap and success),
|
| 771 |
+
first_sag_dt_s=lp(sags[0]) if sags else None,
|
| 772 |
+
first_sag_start_dt_s=lp(starts[0]) if starts else None,
|
| 773 |
+
first_sag_after=sags[0].get("after_placing") if sags else None,
|
| 774 |
+
first_fall_dt_s=fell[0].get("dt_since_cause_s") if fell else None,
|
| 775 |
+
fell_before_finish=bool([e for e in fell if not e.get("in_final_settle")]),
|
| 776 |
+
board_deg_at_finish=round(float(np.degrees(th_fin)), 1), off_at_finish=off_fin,
|
| 777 |
+
max_droop_before_finish_deg=round(max_fin, 1),
|
| 778 |
+
visible_before_finish=bool(sag_vis or off_fin or max_fin > np.degrees(SAG_DEG)),
|
| 779 |
+
fell_jars=sorted({e["jar"] for e in fell}), failure=failure, held=held, touching=bool(jar_touch),
|
| 780 |
+
board_touched=bool(board_touch), propped=propped, static=bool(static),
|
| 781 |
+
board_deg=round(float(np.degrees(th)), 2), max_droop_deg=round(mon["max_deg"], 1),
|
| 782 |
+
r_cm={COLOURS[i]: round(self.r_cm(i), 1) for i in range(4)},
|
| 783 |
+
moment_Nm=round(self.moment(only_state=False), 3), preload_Nm=round(float(inst["preload"]), 3),
|
| 784 |
+
loose=bool(inst["loose"]), settle_s=settle_s, finish_step=mon["finish_step"],
|
| 785 |
+
detail=" ".join(parts))
|
| 786 |
+
|
| 787 |
+
# ------------------------------------------------------------ scripted primitives (move_to + gripper only)
|
| 788 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 789 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 790 |
+
|
| 791 |
+
def _lift_to(self, z, speed=0.15):
|
| 792 |
+
cur = self.sk.eef_pos()
|
| 793 |
+
if cur[2] < TZ + z - 0.005:
|
| 794 |
+
self._go([cur[0], cur[1], TZ + z], speed=speed)
|
| 795 |
+
|
| 796 |
+
def _settle_jar(self, j, max_checks=30):
|
| 797 |
+
d = self.env.sim.data
|
| 798 |
+
da = self.jdof[j]
|
| 799 |
+
for _ in range(max_checks):
|
| 800 |
+
if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
|
| 801 |
+
return
|
| 802 |
+
self.sk.hold(2)
|
| 803 |
+
|
| 804 |
+
def wait_board(self, max_steps=200):
|
| 805 |
+
"""wait (arm still) until the board stops moving"""
|
| 806 |
+
for _ in range(max_steps // 5):
|
| 807 |
+
if abs(float(self.env.sim.data.qvel[self.da])) < np.radians(0.3) and not self.mon["in_sag"]:
|
| 808 |
+
return
|
| 809 |
+
self.sk.hold(5)
|
| 810 |
+
|
| 811 |
+
def lying(self, j):
|
| 812 |
+
return self.tilt(j) > np.radians(45)
|
| 813 |
+
|
| 814 |
+
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):
|
| 815 |
+
"""grasp the jar by its knob and lift it to carry height. Standing jar: from above, wrist yaw `yaw`. Lying jar:
|
| 816 |
+
fingers across its axis; lifted, it turns between the fingers and hangs straight down."""
|
| 817 |
+
sk = self.sk
|
| 818 |
+
for _ in range(tries):
|
| 819 |
+
self._settle_jar(j)
|
| 820 |
+
lying = self.lying(j)
|
| 821 |
+
k = self.knob_xyz(j)
|
| 822 |
+
if lying:
|
| 823 |
+
ax = self.jar_axis(j)[:2]
|
| 824 |
+
gy = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw
|
| 825 |
+
else:
|
| 826 |
+
gy = yaw
|
| 827 |
+
q = k[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 828 |
+
sk.set_gripper(False, steps=8)
|
| 829 |
+
cur = sk.eef_pos()
|
| 830 |
+
self._go([cur[0], cur[1], max(cur[2], TZ + min(z_carry, 0.22))], speed=0.15)
|
| 831 |
+
self._go([q[0], q[1], max(k[2] + 0.06, TZ + min(z_carry, 0.22))], yaw=gy, speed=v)
|
| 832 |
+
sk.hold(max(1, int(4 * waits)))
|
| 833 |
+
k = self.knob_xyz(j)
|
| 834 |
+
q = k[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 835 |
+
self._go([q[0], q[1], k[2] + 0.015], speed=v_down)
|
| 836 |
+
self._go([q[0], q[1], k[2]], speed=0.04, tol=0.003, max_steps=150)
|
| 837 |
+
sk.set_gripper(True, steps=15)
|
| 838 |
+
if lying: # lift slowly until it hangs free, let the swing die down
|
| 839 |
+
cur = sk.eef_pos()
|
| 840 |
+
self._go([cur[0], cur[1], TZ + KNOB_Z + 0.04], speed=0.08)
|
| 841 |
+
sk.hold(20)
|
| 842 |
+
cur = sk.eef_pos()
|
| 843 |
+
self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.12, v_down))
|
| 844 |
+
sk.hold(max(1, int(5 * waits)))
|
| 845 |
+
if self.held(j):
|
| 846 |
+
return True
|
| 847 |
+
sk.set_gripper(False, steps=8)
|
| 848 |
+
cur = sk.eef_pos()
|
| 849 |
+
self._go([cur[0], cur[1], cur[2] + 0.05], speed=0.1)
|
| 850 |
+
return False
|
| 851 |
+
|
| 852 |
+
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):
|
| 853 |
+
"""carry the held jar over board point (u, r) (planned with the board level), straight down until its bottom is
|
| 854 |
+
h_rel above the board top, let go, lift back to carry height"""
|
| 855 |
+
sk = self.sk
|
| 856 |
+
xy = self.level_point(u, r)
|
| 857 |
+
rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2]
|
| 858 |
+
q = xy - rel
|
| 859 |
+
cur = sk.eef_pos()
|
| 860 |
+
self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v)
|
| 861 |
+
sk.hold(max(1, int(12 * waits))) # let the hanging jar stop swinging
|
| 862 |
+
rel = self.jar_bottom(j)[:2] - sk.eef_pos()[:2]
|
| 863 |
+
q = xy - rel
|
| 864 |
+
dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, j)
|
| 865 |
+
zr = self.board_top_z() + dz + h_rel
|
| 866 |
+
self._go([q[0], q[1], zr + 0.02], speed=v_down)
|
| 867 |
+
self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
|
| 868 |
+
sk.set_gripper(False, steps=12)
|
| 869 |
+
cur = sk.eef_pos()
|
| 870 |
+
self._go([cur[0], cur[1], TZ + z_carry], speed=max(0.15, v_down))
|
| 871 |
+
sk.hold(3)
|
| 872 |
+
|
| 873 |
+
def place(self, i, u, r, p, rng, rand=0.0):
|
| 874 |
+
"""one stage: pick jar i from wherever it is and put it on the board at (u, r) +- rand"""
|
| 875 |
+
j = JARS[i]
|
| 876 |
+
e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2)
|
| 877 |
+
gerr = rng.uniform(-0.002, 0.002, 2) if rand else None
|
| 878 |
+
kw = dict(z_carry=p.get("z_carry", Z_CARRY), v=p.get("v", 0.2), v_down=p.get("v_down", 0.10),
|
| 879 |
+
waits=p.get("waits", 1.0))
|
| 880 |
+
if not self.pick(j, err=gerr, **kw):
|
| 881 |
+
return False
|
| 882 |
+
self.put(j, u + e[0], r + e[1], h_rel=p.get("h_rel", 0.010), **kw)
|
| 883 |
+
self._settle_jar(j)
|
| 884 |
+
return True
|
| 885 |
+
|
| 886 |
+
def supply_order(self):
|
| 887 |
+
"""jar indices by their supply position: the one whose slot is farthest from the robot first (Sonnet fills a
|
| 888 |
+
row from the far end)"""
|
| 889 |
+
return sorted(range(4), key=lambda i: -self.inst["start"][COLOURS[i]][0])
|
| 890 |
+
|
| 891 |
+
def slot_u(self, k):
|
| 892 |
+
"""board u of slot k (k = 0 farthest from the robot)"""
|
| 893 |
+
s = -1.0 if self.inst["side"] == "right" else 1.0
|
| 894 |
+
# u runs along local x = -s * world x -> farthest (largest world x) first
|
| 895 |
+
return -s * SLOT_U[3 - k]
|
| 896 |
+
|
| 897 |
+
def fallen(self):
|
| 898 |
+
return [i for i in range(4) if self.mon["ever"][i] and not self.on_board(i) and not self.held(JARS[i])]
|
| 899 |
+
|
| 900 |
+
def repair(self, r_target, rng, p, rand=0.0, used=None):
|
| 901 |
+
"""move every jar on the board to depth r_target (same slot), then stand up the fallen ones and put them into the
|
| 902 |
+
free slots at r_target"""
|
| 903 |
+
sk = self.sk
|
| 904 |
+
self.wait_board()
|
| 905 |
+
slots = dict(used or {})
|
| 906 |
+
for i in range(4):
|
| 907 |
+
if self.on_board(i) and abs(self.r_cm(i) / 100 - r_target) > 0.02:
|
| 908 |
+
self.place(i, slots.get(i, self.slot_u(0)), r_target, p, rng, rand)
|
| 909 |
+
self.wait_board()
|
| 910 |
+
for i in self.fallen():
|
| 911 |
+
free = [k for k in range(4) if self.slot_u(k) not in slots.values()] or [0]
|
| 912 |
+
u = slots.get(i, self.slot_u(free[0]))
|
| 913 |
+
slots[i] = u
|
| 914 |
+
self.place(i, u, r_target, p, rng, rand)
|
| 915 |
+
self.wait_board()
|
| 916 |
+
sk.hold(5)
|
| 917 |
+
return slots
|
| 918 |
+
|
| 919 |
+
def execute(self, inst, params):
|
| 920 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 921 |
+
r = float(params["r"])
|
| 922 |
+
rand = float(params.get("rand", 0.0))
|
| 923 |
+
order = params.get("order") or self.supply_order()
|
| 924 |
+
used = {}
|
| 925 |
+
mode_back = False
|
| 926 |
+
for k, i in enumerate(order):
|
| 927 |
+
u = self.slot_u(k)
|
| 928 |
+
used[i] = u
|
| 929 |
+
rr = R_BACK + params.get("back_off", 0.0) if mode_back else r
|
| 930 |
+
self.place(i, u, rr, params, rng, rand)
|
| 931 |
+
# looks at the jar it just placed (Sonnet): re-places it if it is not standing on the board
|
| 932 |
+
if not self.on_board(i) and params.get("self_check", True):
|
| 933 |
+
self.place(i, u, rr, params, rng, rand)
|
| 934 |
+
if params.get("look_back") and (self.fallen() or self.angle() > np.radians(3.0)):
|
| 935 |
+
# the shelf sags / jars fell: from now on load it near the wall, and move what is on it there too
|
| 936 |
+
mode_back = True
|
| 937 |
+
used = self.repair(R_BACK + params.get("back_off", 0.0), rng, params, rand, used)
|
| 938 |
+
if params.get("final_check"):
|
| 939 |
+
for _ in range(2):
|
| 940 |
+
if all(self.stages()):
|
| 941 |
+
break
|
| 942 |
+
rr = R_BACK + params.get("back_off", 0.0) if (mode_back or params.get("look_back")) else r
|
| 943 |
+
used = self.repair(rr, rng, params, rand, used)
|
| 944 |
+
if not params.get("fast_finish"):
|
| 945 |
+
self._lift_to(Z_CARRY)
|
| 946 |
+
self.sk.hold(5)
|
| 947 |
+
|
| 948 |
+
# naive = Sonnet-like (DESIGN_INSIGHTS §3; lh_nudge_row / lh_bystander pilots): careful top-down pick and place, jars
|
| 949 |
+
# 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
|
| 950 |
+
# placed, no look back at the others before finishing
|
| 951 |
+
def default_params(self, inst):
|
| 952 |
+
sd = int(inst["seed"])
|
| 953 |
+
return dict(r=R_MID + float(inst["naive_bias"]), rand=NAIVE_RAND, noise_seed=sd * 13,
|
| 954 |
+
h_rel=0.010 + 0.030 * ((sd * 7) % 11) / 10, z_carry=Z_CARRY, look_back=False, final_check=False,
|
| 955 |
+
v=NAIVE_V, v_down=NAIVE_V_DOWN, waits=NAIVE_WAITS)
|
| 956 |
+
|
| 957 |
+
def oracle_params(self, inst):
|
| 958 |
+
return dict(r=R_BACK, rand=0.0, h_rel=0.005, z_carry=Z_CARRY, look_back=True, final_check=True)
|
| 959 |
+
|
| 960 |
+
def adapt_params(self, inst, history):
|
| 961 |
+
"""from attempt 2: load the shelf near the wall (same imprecision), look back after every jar and at the end"""
|
| 962 |
+
return dict(self.default_params(inst), r=R_BACK + 0.008, look_back=True, final_check=True)
|
| 963 |
+
|
| 964 |
+
def blind_params(self, inst, attempt, rng):
|
| 965 |
+
"""the naive behaviour with random variation (depth on the board, order, heights), no history, no look back"""
|
| 966 |
+
order = [int(x) for x in rng.permutation(4)]
|
| 967 |
+
return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)), r=float(rng.uniform(0.06, 0.15)),
|
| 968 |
+
order=order, z_carry=float(rng.uniform(0.24, 0.28)), h_rel=float(rng.uniform(0.005, 0.04)),
|
| 969 |
+
v=float(rng.uniform(0.12, 0.3)))
|
| 970 |
+
|
| 971 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 972 |
+
k = k or self.max_attempts
|
| 973 |
+
rng = np.random.default_rng(seed)
|
| 974 |
+
history = []
|
| 975 |
+
single = ("oracle", "naive", "oracle_noise", "naive_front", "naive_back", "naive_check_mid", "naive_fast")
|
| 976 |
+
for a in range(k):
|
| 977 |
+
self.reset_instance(inst)
|
| 978 |
+
if kind == "oracle":
|
| 979 |
+
params = self.oracle_params(inst)
|
| 980 |
+
elif kind == "naive":
|
| 981 |
+
params = self.default_params(inst)
|
| 982 |
+
elif kind == "adaptive": # attempt 1: naive + looks back after every jar; repairs near the wall
|
| 983 |
+
params = (dict(self.default_params(inst), look_back=True, final_check=True, back_off=0.008) if a == 0
|
| 984 |
+
else self.adapt_params(inst, history))
|
| 985 |
+
elif kind == "blind":
|
| 986 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 987 |
+
elif kind == "switch": # control: cross-attempt learning only (near the wall from attempt 2), no repair
|
| 988 |
+
params = (self.default_params(inst) if a == 0 else
|
| 989 |
+
dict(self.default_params(inst), r=R_BACK + 0.008))
|
| 990 |
+
elif kind == "oracle_noise":
|
| 991 |
+
params = dict(self.oracle_params(inst), rand=0.005, noise_seed=int(seed) * 7 + a)
|
| 992 |
+
elif kind == "naive_front": # control: naive, but jars set down near the free edge
|
| 993 |
+
params = dict(self.default_params(inst), r=GAP + BOARD_D - JB - 0.015)
|
| 994 |
+
elif kind == "naive_back": # control: naive pace and imprecision, jars against the wall -> no droop
|
| 995 |
+
params = dict(self.default_params(inst), r=R_BACK + 0.008)
|
| 996 |
+
elif kind == "naive_check_mid": # control: looks back and repairs, but puts the jars back in the middle
|
| 997 |
+
params = dict(self.default_params(inst), final_check=True)
|
| 998 |
+
elif kind == "naive_fast": # control: naive at the fastest pace, finishing right after the last jar
|
| 999 |
+
params = dict(self.default_params(inst), v=0.6, v_down=0.3, waits=0.1, h_rel=0.03, fast_finish=True)
|
| 1000 |
+
else:
|
| 1001 |
+
raise ValueError(kind)
|
| 1002 |
+
self.execute(inst, params)
|
| 1003 |
+
out = self.outcome(inst)
|
| 1004 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 1005 |
+
if on_attempt:
|
| 1006 |
+
on_attempt(a, params, out)
|
| 1007 |
+
if out["success"] or kind in single:
|
| 1008 |
+
break
|
| 1009 |
+
return history
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/api_player.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Drive one robot_server session with a model through its provider's official API (the unified harness).
|
| 2 |
+
|
| 3 |
+
Every provider gets exactly the same input: the sandbox README as its instructions and the same tools; only the
|
| 4 |
+
wire format differs (lffbench/agent/backends/). After every command the JSON report is returned as the tool output.
|
| 5 |
+
Nothing else is sent: no files, no memory, no paths outside the sandbox.
|
| 6 |
+
|
| 7 |
+
python scripts/api_player.py --session runs/<...>/session.json --provider anthropic --model claude-opus-5-5 --effort high --style la
|
| 8 |
+
|
| 9 |
+
Providers (key / endpoint from the environment, e.g. `set -a; source .env; set +a`):
|
| 10 |
+
openai OpenAI Responses API OPENAI_API_KEY [OPENAI_BASE_URL]
|
| 11 |
+
anthropic Anthropic Messages API ANTHROPIC_API_KEY
|
| 12 |
+
gemini Gemini API (google-genai) GEMINI_API_KEY
|
| 13 |
+
chat any OpenAI-compatible Chat Completions endpoint (vLLM / SGLang for open models, xAI, ...)
|
| 14 |
+
LFF_CHAT_BASE_URL, LFF_CHAT_API_KEY
|
| 15 |
+
`--effort` is the provider's reasoning knob: OpenAI reasoning.effort, Anthropic output_config.effort, Gemini
|
| 16 |
+
thinking_level, chat: reasoning_effort (omitted when "none").
|
| 17 |
+
|
| 18 |
+
--style la (LIBERO-Agent-style workspace, the paper's interface): the sandbox is the agent's episode workspace. Besides
|
| 19 |
+
`robot` the model gets `shell` (a command run in the workspace inside a jail: no network, robot server unreachable,
|
| 20 |
+
host data hidden, see /opt/lffjail/jail_inner.sh) and `view_images` (any image file in the workspace, including ones
|
| 21 |
+
it made itself). Tool calls per attempt are capped (agent_iface.json: max_tool_calls); at the cap the attempt is
|
| 22 |
+
finished for it.
|
| 23 |
+
Logs in the run's log dir: transcript.jsonl (every request / reply / tool call), final_report.md.
|
| 24 |
+
"""
|
| 25 |
+
import argparse
|
| 26 |
+
import base64
|
| 27 |
+
import json
|
| 28 |
+
import os
|
| 29 |
+
import shlex
|
| 30 |
+
import subprocess
|
| 31 |
+
import sys
|
| 32 |
+
import time
|
| 33 |
+
import traceback
|
| 34 |
+
import urllib.request
|
| 35 |
+
|
| 36 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 37 |
+
sys.path.insert(0, ROOT)
|
| 38 |
+
if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"):
|
| 39 |
+
os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # the venv's own CA bundle lacks the proxy's issuer
|
| 40 |
+
|
| 41 |
+
from lffbench.agent.backends import make_backend # noqa: E402
|
| 42 |
+
from lffbench.agent.context import Conversation # noqa: E402
|
| 43 |
+
|
| 44 |
+
PROVIDERS = ("openai", "anthropic", "gemini", "chat")
|
| 45 |
+
|
| 46 |
+
TOOL = dict(
|
| 47 |
+
name="robot",
|
| 48 |
+
description=("Run one robot command. `command` is exactly what you would type after `./robot` in the "
|
| 49 |
+
"instructions (e.g. `observe`). Returns the command's JSON report."),
|
| 50 |
+
parameters=dict(type="object", properties=dict(command=dict(type="string", description="the robot command")),
|
| 51 |
+
required=["command"], additionalProperties=False),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
VIEW_TOOL = dict(
|
| 55 |
+
name="view_images",
|
| 56 |
+
description=("Look at camera images the robot has written. `paths` are image paths exactly as printed by robot "
|
| 57 |
+
"commands (e.g. obs/a1_s003_wrist.jpg); any image of this episode can be viewed again. The images "
|
| 58 |
+
"are attached right after this call."),
|
| 59 |
+
parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"),
|
| 60 |
+
description="image paths to view")),
|
| 61 |
+
required=["paths"], additionalProperties=False),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
TOOL_LA = dict(
|
| 65 |
+
name="robot",
|
| 66 |
+
description=("Run one robot command. `command` is exactly one of the robot commands in the instructions, e.g. "
|
| 67 |
+
"`status` or `move_eef z=1.0 gripper=open`. Returns the command's JSON report, including the paths "
|
| 68 |
+
"of the new observation files."),
|
| 69 |
+
parameters=TOOL["parameters"],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
SHELL_TOOL = dict(
|
| 73 |
+
name="shell",
|
| 74 |
+
description=("Run a shell command (bash) in your workspace directory, e.g. `ls obs` or `python3 analyse.py`. "
|
| 75 |
+
"python3 has numpy, scipy, Pillow and OpenCV. No network; programs cannot control the robot. "
|
| 76 |
+
"Time limit 60 s per call. Returns the exit code and the combined stdout/stderr (long output is "
|
| 77 |
+
"truncated in the middle)."),
|
| 78 |
+
parameters=dict(type="object", properties=dict(command=dict(type="string", description="the bash command")),
|
| 79 |
+
required=["command"], additionalProperties=False),
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
VIEW_TOOL_LA = dict(
|
| 83 |
+
name="view_images",
|
| 84 |
+
description=("Look at image files in your workspace (.jpg / .jpeg / .png), e.g. obs/a1_s003_wrist.jpg or an image "
|
| 85 |
+
"you made yourself; paths are relative to the workspace. At most 8 per call. The images are attached "
|
| 86 |
+
"right after this call."),
|
| 87 |
+
parameters=dict(type="object", properties=dict(paths=dict(type="array", items=dict(type="string"),
|
| 88 |
+
description="image paths to view")),
|
| 89 |
+
required=["paths"], additionalProperties=False),
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
PREAMBLE_LA = ("You control the robot described below and work in the workspace described below. Tools: `robot` runs "
|
| 93 |
+
"one robot command per call (the argument is exactly a command from the instructions, e.g. `status`); "
|
| 94 |
+
"`shell` runs a shell command in your workspace; `view_images` shows you image files from the "
|
| 95 |
+
"workspace. When a robot command tells you to stop or that the episode is over, stop calling tools and "
|
| 96 |
+
"reply with a short report: what you did (key commands and parameter values), what you observed, any "
|
| 97 |
+
"feedback you got, and how you changed your approach.\n\n")
|
| 98 |
+
|
| 99 |
+
PREAMBLE = ("You control the robot described below. You act only through the `robot` tool, one command per call. "
|
| 100 |
+
"When a command tells you to stop or that the episode is over, stop calling the tool and reply with a "
|
| 101 |
+
"short report: what you did (key commands and parameter values), what you observed, any feedback you "
|
| 102 |
+
"got, and how you changed your approach.\n\n")
|
| 103 |
+
|
| 104 |
+
JAIL = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "jail", "jail_inner.sh")
|
| 105 |
+
SHELL_TIMEOUT = 60
|
| 106 |
+
SHELL_MAX_CHARS = 12000
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def run_shell(workspace, command):
|
| 110 |
+
"""Run `command` in the jailed workspace; returns (exit code, output text, seconds)."""
|
| 111 |
+
t0 = time.time()
|
| 112 |
+
argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, workspace,
|
| 113 |
+
"timeout", "-k", "5", str(SHELL_TIMEOUT), "bash", "-c", command]
|
| 114 |
+
try:
|
| 115 |
+
r = subprocess.run(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
| 116 |
+
timeout=SHELL_TIMEOUT + 30)
|
| 117 |
+
code, out = r.returncode, r.stdout.decode("utf-8", "replace")
|
| 118 |
+
except subprocess.TimeoutExpired as e:
|
| 119 |
+
code, out = 124, (e.stdout or b"").decode("utf-8", "replace")
|
| 120 |
+
if code == 124:
|
| 121 |
+
out += f"\n[killed: time limit of {SHELL_TIMEOUT} s]"
|
| 122 |
+
if len(out) > SHELL_MAX_CHARS:
|
| 123 |
+
h = SHELL_MAX_CHARS // 2
|
| 124 |
+
out = out[:h] + f"\n[... {len(out) - SHELL_MAX_CHARS} characters truncated ...]\n" + out[-h:]
|
| 125 |
+
return code, out, time.time() - t0
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def workspace_image(workspace, rel):
|
| 129 |
+
"""Resolve a model-given image path inside the workspace (no escaping via .. or symlinks); None if not allowed."""
|
| 130 |
+
if not isinstance(rel, str) or not rel or rel.startswith("/"):
|
| 131 |
+
return None
|
| 132 |
+
root = os.path.realpath(workspace)
|
| 133 |
+
full = os.path.realpath(os.path.join(root, rel))
|
| 134 |
+
if not full.startswith(root + os.sep) or not os.path.isfile(full):
|
| 135 |
+
return None
|
| 136 |
+
if os.path.splitext(full)[1].lower() not in (".jpg", ".jpeg", ".png") or os.path.getsize(full) > 8 * 2 ** 20:
|
| 137 |
+
return None
|
| 138 |
+
return full
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class FileImage:
|
| 142 |
+
"""The exact JPEG bytes the server wrote (same bytes a Claude Code player reads)."""
|
| 143 |
+
|
| 144 |
+
def __init__(self, path):
|
| 145 |
+
self.path = path
|
| 146 |
+
base = os.path.basename(path)
|
| 147 |
+
self.camera = "wrist" if "wrist" in base else ("agentview" if "agentview" in base else "camera")
|
| 148 |
+
self.label = base
|
| 149 |
+
|
| 150 |
+
def data_url(self, quality=None):
|
| 151 |
+
mime = "image/png" if self.path.lower().endswith(".png") else "image/jpeg"
|
| 152 |
+
with open(self.path, "rb") as f:
|
| 153 |
+
return f"data:{mime};base64," + base64.b64encode(f.read()).decode()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def parse_command(s):
|
| 157 |
+
s = s.strip()
|
| 158 |
+
s = s.removeprefix("./robot").strip() if s.startswith("./robot") else (s[len("robot "):] if s.startswith("robot ") else s)
|
| 159 |
+
toks = shlex.split(s.strip())
|
| 160 |
+
if not toks:
|
| 161 |
+
return "help", {}
|
| 162 |
+
cmd, args = toks[0], {}
|
| 163 |
+
for a in toks[1:]:
|
| 164 |
+
if "=" not in a:
|
| 165 |
+
return None, f"bad argument {a!r}: use key=value"
|
| 166 |
+
k, v = a.split("=", 1)
|
| 167 |
+
try:
|
| 168 |
+
args[k] = json.loads(v)
|
| 169 |
+
except ValueError:
|
| 170 |
+
args[k] = v
|
| 171 |
+
return cmd, args
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def call_server(port, token, cmd, args):
|
| 175 |
+
req = urllib.request.Request(f"http://127.0.0.1:{port}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(),
|
| 176 |
+
headers={"Content-Type": "application/json", "X-Token": token})
|
| 177 |
+
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
| 178 |
+
with opener.open(req, timeout=900) as r:
|
| 179 |
+
return r.read().decode()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
MAX_NO_TOOL = 3 # nudges in a row for replies without a tool call; the next such reply ends the run
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def continue_nudge(port, token, stx=None):
|
| 186 |
+
"""The user message sent when the model replies without a tool call before the episode is over. Native harnesses
|
| 187 |
+
send the same text when their CLI exits early (scripts/harness_run.py). stx: a status reply already fetched."""
|
| 188 |
+
try: # tell it where it is: models sometimes believe the episode ended after a failed attempt
|
| 189 |
+
if stx is None:
|
| 190 |
+
stx = json.loads(call_server(port, token, "status", {}))
|
| 191 |
+
where = (f" You are in attempt {stx.get('attempt')} of {stx.get('max_attempts')}; the episode is NOT over."
|
| 192 |
+
if stx.get("attempt") else "")
|
| 193 |
+
except Exception:
|
| 194 |
+
where = ""
|
| 195 |
+
return "Continue: issue the next robot command with the `robot` tool." + where
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def build_backend(a, v2):
|
| 199 |
+
"""The model backend for --provider; image pruning only where the provider allows editing earlier turns."""
|
| 200 |
+
if a.provider == "openai":
|
| 201 |
+
return make_backend("openai", model=a.model, reasoning_effort=a.effort, reasoning_summary="auto",
|
| 202 |
+
max_live_images=None if v2 else a.max_live_images, cache_breakpoints="none", max_retries=1)
|
| 203 |
+
if a.provider == "anthropic": # append-only history (thinking blocks are bound to it): never prune
|
| 204 |
+
return make_backend("anthropic", model=a.model, effort=a.effort, max_live_images=None)
|
| 205 |
+
if a.provider == "gemini":
|
| 206 |
+
return make_backend("gemini", model=a.model, thinking_level=a.effort,
|
| 207 |
+
max_live_images=None if v2 else a.max_live_images)
|
| 208 |
+
extra = None if a.effort in ("", "none", None) else dict(reasoning_effort=a.effort)
|
| 209 |
+
return make_backend("chat", model=a.model, max_tokens=a.max_output_tokens, temperature=None, extra_body=extra,
|
| 210 |
+
max_live_images=None if v2 else a.max_live_images)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def context_overflow(err):
|
| 214 |
+
"""The request no longer fits: token limit (OpenAI / Anthropic / Gemini / Kimi wordings) or too many images."""
|
| 215 |
+
e = err.lower()
|
| 216 |
+
return (("context" in e and ("length" in e or "window" in e or "too long" in e)) or "prompt is too long" in e
|
| 217 |
+
or ("exceed" in e and "token" in e) or "too many images" in e or "maximum number of images" in e)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def live_images(conv):
|
| 221 |
+
return sum(1 for it in conv.items if it["kind"] == "user" and it.get("live") for p in it["parts"]
|
| 222 |
+
if p["type"] == "image")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def main(argv=None, default_provider=None, transcript_name="transcript.jsonl"):
|
| 226 |
+
ap = argparse.ArgumentParser()
|
| 227 |
+
ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh")
|
| 228 |
+
ap.add_argument("--provider", default=default_provider, choices=PROVIDERS, required=default_provider is None)
|
| 229 |
+
ap.add_argument("--model", default="gpt-6-astra" if default_provider == "openai" else None,
|
| 230 |
+
required=default_provider is None)
|
| 231 |
+
ap.add_argument("--effort", default="medium")
|
| 232 |
+
ap.add_argument("--max-turns", type=int, default=400)
|
| 233 |
+
ap.add_argument("--max-live-images", type=int, default=16)
|
| 234 |
+
ap.add_argument("--max-output-tokens", type=int, default=32768, help="chat provider only")
|
| 235 |
+
ap.add_argument("--api-retries", type=int, default=8,
|
| 236 |
+
help="retries of a failed API call before giving up (back-off 5 s doubling to 120 s: ~9 min)")
|
| 237 |
+
ap.add_argument("--max-request-images", type=int, default=500,
|
| 238 |
+
help="when the conversation holds more viewed images than this, switch to the context-full "
|
| 239 |
+
"policy (Claude through a gateway failed at 601 images, 2026-10-15)")
|
| 240 |
+
ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"],
|
| 241 |
+
help="v2: images are not attached automatically; the model views them on demand with "
|
| 242 |
+
"view_images, and no history is pruned (the agent manages its own context)")
|
| 243 |
+
a = ap.parse_args(argv)
|
| 244 |
+
|
| 245 |
+
sess = json.load(open(a.session))
|
| 246 |
+
sb, port = sess["sandbox"], sess["port"]
|
| 247 |
+
log_dir = os.path.dirname(os.path.abspath(a.session))
|
| 248 |
+
la = a.style == "la"
|
| 249 |
+
if la: # no robot CLI in a la workspace: the token is only in the log dir
|
| 250 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 251 |
+
token, max_tool_calls = iface["token"], int(iface["max_tool_calls"])
|
| 252 |
+
else:
|
| 253 |
+
token = open(os.path.join(sb, "robot")).read().split('TOKEN = "', 1)[1].split('"', 1)[0]
|
| 254 |
+
readme = open(os.path.join(sb, "README.md")).read()
|
| 255 |
+
tlog = open(os.path.join(log_dir, transcript_name), "a")
|
| 256 |
+
|
| 257 |
+
def log(d):
|
| 258 |
+
d["t"] = time.time()
|
| 259 |
+
tlog.write(json.dumps(d, ensure_ascii=False) + "\n")
|
| 260 |
+
tlog.flush()
|
| 261 |
+
|
| 262 |
+
v2 = a.style in ("v2", "la") # la = v2 robot interface + workspace tools
|
| 263 |
+
tools = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA] if la else ([TOOL, VIEW_TOOL] if v2 else [TOOL])
|
| 264 |
+
backend = build_backend(a, v2)
|
| 265 |
+
conv = Conversation((PREAMBLE_LA if la else PREAMBLE) + readme)
|
| 266 |
+
log(dict(ev="start", provider=a.provider, model=a.model, effort=a.effort, style=a.style, backend=backend.config(),
|
| 267 |
+
instructions=conv.system, tools=tools))
|
| 268 |
+
|
| 269 |
+
def images_part(paths, title):
|
| 270 |
+
parts = [dict(type="text", text=title)]
|
| 271 |
+
for p in paths:
|
| 272 |
+
parts.append(dict(type="image", image=FileImage(os.path.join(sb, p))))
|
| 273 |
+
return parts
|
| 274 |
+
|
| 275 |
+
st = json.loads(call_server(port, token, "status", {}))
|
| 276 |
+
if v2: # images stay files; the model decides what to look at
|
| 277 |
+
first = [dict(type="text", text=("Begin. Current status (robot command `status`):\n" if la else
|
| 278 |
+
"Begin. Current status (`./robot status`):\n") + json.dumps(st))]
|
| 279 |
+
else:
|
| 280 |
+
first = [dict(type="text", text="Begin. Current status (`./robot status`):\n" +
|
| 281 |
+
json.dumps({k: v for k, v in st.items() if k != "images"}))]
|
| 282 |
+
first += images_part(st.get("images", []), "Current camera images (agentview, wrist):")[1:]
|
| 283 |
+
conv.add_user(first, live=True)
|
| 284 |
+
log(dict(ev="user", text=first[0]["text"], images=st.get("images", [])))
|
| 285 |
+
|
| 286 |
+
finished, no_tool, report = False, 0, None
|
| 287 |
+
calls_in_attempt = 0 # la: tool calls (robot + shell + view_images) in the current attempt
|
| 288 |
+
usage_tot = dict(input_tokens=0, cached_tokens=0, cache_write_tokens=0, output_tokens=0, reasoning_tokens=0)
|
| 289 |
+
for turn in range(a.max_turns):
|
| 290 |
+
resp, err = None, None
|
| 291 |
+
if v2 and backend.max_live_images is None and live_images(conv) > a.max_request_images:
|
| 292 |
+
backend.max_live_images = 32 # same context-full policy as below, before the request limit is hit
|
| 293 |
+
log(dict(ev="context_overflow", reason="image count", n_images=live_images(conv), keep_images=32))
|
| 294 |
+
for r in range(a.api_retries + 1):
|
| 295 |
+
t0 = time.time()
|
| 296 |
+
try:
|
| 297 |
+
out = backend.act(conv, tools)
|
| 298 |
+
except Exception as e: # flaky endpoint: back off and retry the identical request
|
| 299 |
+
err = f"{type(e).__name__}: {str(e)[:300]}"
|
| 300 |
+
if v2 and context_overflow(err):
|
| 301 |
+
# the context is full (every provider): from now on keep only the newest viewed images
|
| 302 |
+
backend.max_live_images = 32 if backend.max_live_images is None else max(backend.max_live_images // 2, 4)
|
| 303 |
+
log(dict(ev="context_overflow", reason=err[:120], keep_images=backend.max_live_images))
|
| 304 |
+
log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0))
|
| 305 |
+
time.sleep(min(120, 5 * 2 ** r))
|
| 306 |
+
continue
|
| 307 |
+
if out.status == "refusal": # the provider declined: no fallback model (it would change the model under test)
|
| 308 |
+
resp, err = out, out.error
|
| 309 |
+
break
|
| 310 |
+
if out.status == "incomplete": # truncated / malformed turn: not appended, ask again
|
| 311 |
+
err = out.error
|
| 312 |
+
log(dict(ev="api_error", turn=turn, retry=r, error=err, dt=time.time() - t0, usage=out.usage))
|
| 313 |
+
continue
|
| 314 |
+
resp = out
|
| 315 |
+
break
|
| 316 |
+
if resp is None:
|
| 317 |
+
log(dict(ev="abort", reason="api failed", error=err))
|
| 318 |
+
print("ABORT api failed:", err, flush=True)
|
| 319 |
+
sys.exit(3)
|
| 320 |
+
for k in usage_tot:
|
| 321 |
+
usage_tot[k] += resp.usage.get(k, 0)
|
| 322 |
+
if resp.status == "refusal":
|
| 323 |
+
log(dict(ev="refusal", turn=turn, latency_s=resp.latency_s, usage=resp.usage, error=resp.error,
|
| 324 |
+
text=resp.text))
|
| 325 |
+
log(dict(ev="abort", reason="refusal", error=resp.error))
|
| 326 |
+
print("ABORT refusal:", resp.error, flush=True)
|
| 327 |
+
break
|
| 328 |
+
conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name)
|
| 329 |
+
log(dict(ev="assistant", turn=turn, latency_s=resp.latency_s, usage=resp.usage, text=resp.text,
|
| 330 |
+
reasoning_summary=resp.reasoning_summary,
|
| 331 |
+
reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned",
|
| 332 |
+
status=resp.status, error=resp.error,
|
| 333 |
+
tool_calls=[dict(id=c.id, name=c.name, arguments=c.arguments) for c in resp.tool_calls],
|
| 334 |
+
request_stats=resp.request_stats))
|
| 335 |
+
if finished:
|
| 336 |
+
report = resp.text
|
| 337 |
+
break
|
| 338 |
+
if not resp.tool_calls:
|
| 339 |
+
no_tool += 1
|
| 340 |
+
nudge = continue_nudge(port, token)
|
| 341 |
+
if no_tool > MAX_NO_TOOL:
|
| 342 |
+
log(dict(ev="abort", reason="no tool call 4 times"))
|
| 343 |
+
break
|
| 344 |
+
conv.add_user([dict(type="text", text=nudge)], live=False)
|
| 345 |
+
log(dict(ev="user", text=nudge))
|
| 346 |
+
continue
|
| 347 |
+
no_tool = 0
|
| 348 |
+
for c in resp.tool_calls:
|
| 349 |
+
if la and not finished:
|
| 350 |
+
calls_in_attempt += 1
|
| 351 |
+
if la and c.name == "shell":
|
| 352 |
+
code, out, dt = run_shell(sb, str(c.arguments.get("command", "")))
|
| 353 |
+
out_text = json.dumps(dict(exit_code=code, output=out))
|
| 354 |
+
conv.add_tool_output(c.id, c.name, out_text)
|
| 355 |
+
log(dict(ev="tool", turn=turn, command="shell: " + str(c.arguments.get("command", "")), output=out_text,
|
| 356 |
+
shell_s=round(dt, 2)))
|
| 357 |
+
continue
|
| 358 |
+
if la and c.name == "view_images":
|
| 359 |
+
paths = [str(x) for x in (c.arguments.get("paths") or [])][:8]
|
| 360 |
+
full = [(x, workspace_image(sb, x)) for x in paths]
|
| 361 |
+
ok_paths = [x for x, f in full if f]
|
| 362 |
+
out = dict(ok=bool(ok_paths), attached=ok_paths)
|
| 363 |
+
if len(ok_paths) < len(paths):
|
| 364 |
+
out["not_viewable"] = [x for x, f in full if not f]
|
| 365 |
+
conv.add_tool_output(c.id, c.name, json.dumps(out))
|
| 366 |
+
log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths))
|
| 367 |
+
if ok_paths:
|
| 368 |
+
parts = [dict(type="text", text="Requested images:")]
|
| 369 |
+
for x, f in full:
|
| 370 |
+
if f:
|
| 371 |
+
parts.append(dict(type="image", image=FileImage(f)))
|
| 372 |
+
conv.add_user(parts, live=True)
|
| 373 |
+
continue
|
| 374 |
+
if c.name == "view_images":
|
| 375 |
+
paths = [str(x) for x in (c.arguments.get("paths") or [])][:8]
|
| 376 |
+
ok_paths = [x for x in paths if x.startswith("obs/") and "/.." not in x and ".." not in x
|
| 377 |
+
and os.path.exists(os.path.join(sb, x))]
|
| 378 |
+
bad = [x for x in paths if x not in ok_paths]
|
| 379 |
+
out = dict(ok=bool(ok_paths), attached=ok_paths)
|
| 380 |
+
if bad:
|
| 381 |
+
out["not_found"] = bad
|
| 382 |
+
conv.add_tool_output(c.id, c.name, json.dumps(out))
|
| 383 |
+
log(dict(ev="tool", turn=turn, command="view_images " + " ".join(paths), output=json.dumps(out), images=ok_paths))
|
| 384 |
+
if ok_paths:
|
| 385 |
+
conv.add_user(images_part(ok_paths, "Requested images:"), live=True)
|
| 386 |
+
continue
|
| 387 |
+
cmdline = str(c.arguments.get("command", ""))
|
| 388 |
+
cmd, args = parse_command(cmdline)
|
| 389 |
+
if cmd is None:
|
| 390 |
+
out_text, paths = json.dumps(dict(ok=False, error=args)), []
|
| 391 |
+
else:
|
| 392 |
+
raw = call_server(port, token, cmd, args)
|
| 393 |
+
try:
|
| 394 |
+
rep = json.loads(raw)
|
| 395 |
+
if v2: # keep the image paths in the reply: the model views them itself if it wants
|
| 396 |
+
paths = []
|
| 397 |
+
out_text = json.dumps(rep)
|
| 398 |
+
else:
|
| 399 |
+
paths = rep.pop("images", []) if isinstance(rep, dict) else []
|
| 400 |
+
out_text = json.dumps(rep)
|
| 401 |
+
except ValueError: # help text
|
| 402 |
+
rep, paths, out_text = {}, [], raw
|
| 403 |
+
msg = (rep.get("message", "") + " " + rep.get("error", "")) if isinstance(rep, dict) else ""
|
| 404 |
+
if isinstance(rep, dict) and isinstance(rep.get("attempt_ended"), dict):
|
| 405 |
+
msg += " " + rep["attempt_ended"].get("message", "")
|
| 406 |
+
if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
|
| 407 |
+
finished = True
|
| 408 |
+
if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)):
|
| 409 |
+
calls_in_attempt = 0
|
| 410 |
+
conv.add_tool_output(c.id, c.name, out_text)
|
| 411 |
+
log(dict(ev="tool", turn=turn, command=cmdline, output=out_text, images=paths))
|
| 412 |
+
if paths and not v2:
|
| 413 |
+
conv.add_user(images_part(paths, f"Camera images after `{cmdline}` (agentview, wrist):"), live=True)
|
| 414 |
+
if la and not finished and calls_in_attempt >= max_tool_calls:
|
| 415 |
+
raw = call_server(port, token, "finish", dict(reason="tool-call budget used up (automatic)"))
|
| 416 |
+
try:
|
| 417 |
+
rep = json.loads(raw)
|
| 418 |
+
except ValueError:
|
| 419 |
+
rep = dict(raw=raw)
|
| 420 |
+
msg = rep.get("message", "") + " " + rep.get("error", "")
|
| 421 |
+
if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
|
| 422 |
+
finished = True
|
| 423 |
+
calls_in_attempt = 0
|
| 424 |
+
note = (f"The budget of {max_tool_calls} tool calls for this attempt was used up, so the attempt was "
|
| 425 |
+
f"finished automatically. Result: " + json.dumps(rep))
|
| 426 |
+
conv.add_user([dict(type="text", text=note)], live=False)
|
| 427 |
+
log(dict(ev="user", text=note, auto_finish=True))
|
| 428 |
+
if finished:
|
| 429 |
+
ask = "Stop now and reply with your short report (no more tool calls)."
|
| 430 |
+
conv.add_user([dict(type="text", text=ask)], live=False)
|
| 431 |
+
log(dict(ev="user", text=ask))
|
| 432 |
+
if report:
|
| 433 |
+
with open(os.path.join(log_dir, "final_report.md"), "w") as f:
|
| 434 |
+
f.write(report)
|
| 435 |
+
log(dict(ev="end", finished=finished, usage_total=usage_tot))
|
| 436 |
+
print(json.dumps(dict(finished=finished, usage=usage_tot, report=(report or "")[:200])), flush=True)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
if __name__ == "__main__":
|
| 440 |
+
try:
|
| 441 |
+
main()
|
| 442 |
+
except SystemExit:
|
| 443 |
+
raise
|
| 444 |
+
except Exception:
|
| 445 |
+
traceback.print_exc()
|
| 446 |
+
sys.exit(1)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/check_breakfast_mechanisms.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mechanism-on/off controls and negative judge fixtures, separate from rollouts."""
|
| 2 |
+
import argparse, copy, json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from lffbench.tasks.lh_breakfast_service import BreakfastService
|
| 6 |
+
from lffbench import envs
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
p=argparse.ArgumentParser();p.add_argument('--liquid-only',action='store_true')
|
| 10 |
+
p.add_argument('--judge-only',action='store_true');args=p.parse_args()
|
| 11 |
+
out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/mechanisms'
|
| 12 |
+
out.mkdir(parents=True,exist_ok=True);t=BreakfastService();rows=[]
|
| 13 |
+
if args.judge_only:rows=json.loads((out/'controls_progress.json').read_text())
|
| 14 |
+
for seed in ([] if args.liquid_only or args.judge_only else range(1000,1003)):
|
| 15 |
+
for enabled in (True,False):
|
| 16 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L1']=enabled;t.reset_instance(inst)
|
| 17 |
+
t.calibration_probe();row=dict(seed=seed,mechanism='L1',enabled=enabled,triggered=t.traps['L1'])
|
| 18 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 19 |
+
assert row['triggered']==enabled,row
|
| 20 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L3']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
|
| 21 |
+
t.direct_carton_lift();row=dict(seed=seed,mechanism='L3',enabled=enabled,**t.pull_probe)
|
| 22 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 23 |
+
assert row['held_before'] and ((row['displacement_m']<.01) if enabled else (row['displacement_m']>.04)),row
|
| 24 |
+
inst=t.sample_instance(seed);inst['mechanisms']['L2']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
|
| 25 |
+
for _ in range(2):t.open_lid();t.close_lid(False)
|
| 26 |
+
t.sk.hold(300);failure=t.lid_deg()
|
| 27 |
+
if enabled:t.open_lid();t.close_lid(True);t.sk.hold(300)
|
| 28 |
+
row=dict(seed=seed,mechanism='L2',enabled=enabled,lid_after_quick_closes=failure,final_lid=t.lid_deg())
|
| 29 |
+
rows.append(row);print(json.dumps(row),flush=True)
|
| 30 |
+
assert (failure>10 if enabled else failure<4) and row['final_lid']<4,row
|
| 31 |
+
(out/'controls_progress.json').write_text(json.dumps(rows,indent=2))
|
| 32 |
+
liquid_controls=json.loads((out/'liquid_controls.json').read_text()) if args.judge_only else []
|
| 33 |
+
for case in ([] if args.judge_only else ('upright','tilted_aligned','tilted_misaligned')):
|
| 34 |
+
inst=t.sample_instance(1000);t.reset_instance(inst)
|
| 35 |
+
if case!='upright':t.env.sim.data.qpos[t.pour_qa]=1.35
|
| 36 |
+
if case=='tilted_misaligned':t.env.sim.model.body_pos[t.cup_bid,0]+=.20
|
| 37 |
+
t.env.sim.forward();t.sk.hold(160)
|
| 38 |
+
q=t.liquid;inflight=sum(p['ml'] for p in q['parcels'])
|
| 39 |
+
row=dict(case=case,cup_ml=q['cup'],spill_ml=q['spill'],reservoir_ml=q['reservoir'],
|
| 40 |
+
conservation_error_ml=abs(300-q['cup']-q['spill']-q['reservoir']-inflight))
|
| 41 |
+
liquid_controls.append(row);print(json.dumps(row),flush=True)
|
| 42 |
+
assert row['conservation_error_ml']<1e-8,row
|
| 43 |
+
if case=='upright':assert q['cup']==q['spill']==0,row
|
| 44 |
+
elif case=='tilted_aligned':assert q['cup']>=179 and q['spill']>50,row
|
| 45 |
+
else:assert q['cup']==0 and q['spill']>200,row
|
| 46 |
+
if args.liquid_only:
|
| 47 |
+
(out/'liquid_controls.json').write_text(json.dumps(liquid_controls,indent=2))
|
| 48 |
+
t.env.close();return
|
| 49 |
+
# Obtain a successful physical endpoint before mutating diagnostic scoring fixtures.
|
| 50 |
+
inst=t.sample_instance(1000);t.reset_instance(inst);t.execute(inst,{'mode':'oracle'});baseline=t.outcome(inst)
|
| 51 |
+
assert baseline['success'],baseline
|
| 52 |
+
state=copy.deepcopy(t.env.sim.get_state());liquid=copy.deepcopy(t.liquid)
|
| 53 |
+
mon=copy.deepcopy(t.mon);closes=t.closes_done;latch=t.active_latch
|
| 54 |
+
negatives=[]
|
| 55 |
+
for case in ('no_milk','too_much_milk','spill','bread_off_plate','butter_outside','lid_open','carton_tilted','gripper_closed'):
|
| 56 |
+
t.env.sim.set_state(state);t.env.sim.forward();t.liquid=copy.deepcopy(liquid);t.sk.grip=-1.;t.drift_active=False
|
| 57 |
+
t.mon=copy.deepcopy(mon);t.closes_done=closes;t.active_latch=latch
|
| 58 |
+
if case=='no_milk':t.liquid['reservoir']+=t.liquid['cup'];t.liquid['cup']=0
|
| 59 |
+
elif case=='too_much_milk':
|
| 60 |
+
t.liquid['reservoir']-=175-t.liquid['cup'];t.liquid['cup']=175
|
| 61 |
+
elif case=='spill':t.liquid['reservoir']-=25;t.liquid['spill']=25;t.liquid['spill_xy']=[.2,0]
|
| 62 |
+
elif case=='bread_off_plate':envs.set_obj_pose(t.env,'bread_1',[-.30,.03,.912])
|
| 63 |
+
elif case=='butter_outside':envs.set_obj_pose(t.env,'butter_1',[-.35,-.32,.914])
|
| 64 |
+
elif case=='lid_open':t.env.sim.data.qpos[t.qa]=1.0
|
| 65 |
+
elif case=='carton_tilted':t.env.sim.data.qpos[t.pour_qa]=1.35
|
| 66 |
+
elif case=='gripper_closed':t.sk.grip=1.
|
| 67 |
+
t.env.sim.forward();result=t.outcome(inst)
|
| 68 |
+
negatives.append(dict(case=case,accepted=result['success'],failure=result['failure'],stages=result['stages']))
|
| 69 |
+
print(json.dumps(negatives[-1],default=lambda v:v.item()),flush=True)
|
| 70 |
+
predicate={'no_milk':'milk_served','too_much_milk':'milk_served','spill':'spill_ok',
|
| 71 |
+
'bread_off_plate':'bread_on_plate','butter_outside':'butter_in_box','lid_open':'lid_closed',
|
| 72 |
+
'carton_tilted':'carton_upright','gripper_closed':'gripper_open'}[case]
|
| 73 |
+
assert not result['success'] and not result['stages'][predicate],case
|
| 74 |
+
data=dict(controls=rows,liquid_controls=liquid_controls,negative_fixtures=negatives,
|
| 75 |
+
scope='Controlled interventions are diagnostics, not agent rollouts')
|
| 76 |
+
(out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item()))
|
| 77 |
+
t.env.close()
|
| 78 |
+
|
| 79 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/check_split_mechanisms.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Paired physical counterfactuals, not model evaluations or reset-based demos."""
|
| 2 |
+
import argparse,copy,json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from lffbench.tasks.lh_split_calibration import SplitCalibration,RED,BLUE,JAR_H
|
| 5 |
+
from check_compound_remaining import plain
|
| 6 |
+
p=argparse.ArgumentParser();p.add_argument('--n',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True);t=SplitCalibration();rows=[]
|
| 7 |
+
for seed in range(1000,1000+a.n):
|
| 8 |
+
i=t.sample_instance(seed);r=dict(seed=seed)
|
| 9 |
+
t.reset_instance(i);r['biased_pick']=t.pick(RED)
|
| 10 |
+
z=copy.deepcopy(i);z['near_bias']=z['far_bias']=[0,0,0];t.reset_instance(z);r['zero_bias_pick']=t.pick(RED)
|
| 11 |
+
for wrong in (False,True):
|
| 12 |
+
t.reset_instance(i);t.sk.correction=i['near_bias'];assert t.pick(RED);t.place(RED,i['red_goal'],.9+JAR_H/2+.003,0);before=t.red_ok()
|
| 13 |
+
t.sk.correction=i['far_bias'];assert t.pick(BLUE);t.sk.correction=i['far_bias'] if wrong else i['near_bias'];t.place(BLUE,i['blue_goal'],.922,1.5707963267948966)
|
| 14 |
+
r['transferred_far' if wrong else 'correct_near']=dict(red_before=before,red_after=t.red_ok(),blue_fit=t.blue_ok())
|
| 15 |
+
t.reset_instance(i);t.sk.correction=i['far_bias'];assert t.pick(BLUE);t.sk.correction=i['near_bias'];t.place(BLUE,i['blue_goal'],.922,1.5707963267948966);r['sideways_fit']=t.blue_ok()
|
| 16 |
+
assert t.pick(BLUE);t.place(BLUE,i['blue_goal'],.920,0);r['aligned_fit']=t.blue_ok()
|
| 17 |
+
r['pass']=bool(not r['biased_pick'] and r['zero_bias_pick'] and r['correct_near']['red_before'] and r['correct_near']['red_after'] and r['transferred_far']['red_before'] and not r['transferred_far']['red_after'] and not r['sideways_fit'] and r['aligned_fit'])
|
| 18 |
+
rows.append(r);(out/'progress.json').write_text(json.dumps(rows,indent=2,default=plain));print(json.dumps(r,default=plain),flush=True)
|
| 19 |
+
(out/'summary.json').write_text(json.dumps(dict(rows=rows,pass_count=sum(r['pass'] for r in rows)),indent=2,default=plain));t.env.close();assert all(r['pass'] for r in rows)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/harness_run.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run one robot_server session (style la) with one agent harness through its adapter (lffbench/harnesses, docs/15).
|
| 2 |
+
|
| 3 |
+
python scripts/harness_run.py --harness claude_code --session runs/<...>/session.json --model claude-sonnet-5-5 --effort high
|
| 4 |
+
python scripts/harness_run.py --harness codex --session ... --model gpt-6-astra --effort high
|
| 5 |
+
python scripts/harness_run.py --harness ours --session ... --provider anthropic --model ... --effort high
|
| 6 |
+
|
| 7 |
+
Harnesses: ours (scripts/api_player.py, unchanged), claude_code (arm B, --bare), claude_code_full (arm B', no --bare),
|
| 8 |
+
codex (arm F), rpent_codex (RPent, a robot harness framework, on the same Codex; tools through the episode's tool
|
| 9 |
+
gateway, lffbench/harnesses/rpent.py). Native harnesses get the reference driver's instructions + first status report as their first user
|
| 10 |
+
message (byte-identical README), only our MCP server (scripts/mcp_robot_server.py) as tools, a one-time HOME / config
|
| 11 |
+
dir, an opaque work dir /tmp/lffrun/<12 hex> and a process environment that is exactly a whitelist.
|
| 12 |
+
|
| 13 |
+
API variables (never inherited from the calling Claude Code / Codex session):
|
| 14 |
+
claude_code*: --claude-auth oauth (default for claude_code_full): a Claude subscription, the long-lived token of
|
| 15 |
+
`claude setup-token` from LFF_CLAUDE_OAUTH_TOKEN or the KEY=value file LFF_CLAUDE_OAUTH_FILE (key
|
| 16 |
+
LFF_CLAUDE_OAUTH_TOKEN or CLAUDE_CODE_OAUTH_TOKEN), passed as CLAUDE_CODE_OAUTH_TOKEN;
|
| 17 |
+
--claude-auth apikey (default and only choice for claude_code, which is --bare): key
|
| 18 |
+
LFF_ANTHROPIC_API_KEY or ANTHROPIC_API_KEY;
|
| 19 |
+
endpoint --api-base-url or LFF_ANTHROPIC_BASE_URL (default: the CLI's own default, the official API)
|
| 20 |
+
codex: --codex-provider deepseek: DeepSeek's Responses endpoint (https://api.deepseek.com/), key
|
| 21 |
+
LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed to Codex as its provider's OPENAI_API_KEY);
|
| 22 |
+
--codex-provider opencode: OpenCode Go's Responses endpoint (OPENCODE_GO_URL), key LFF_OPENCODE_API_KEY
|
| 23 |
+
or OPENCODE_API_KEY (the model gateway adds the x-opencode-session header OpenCode Go requires);
|
| 24 |
+
--codex-auth chatgpt (default): the ChatGPT subscription login of LFF_CODEX_AUTH_HOME / CODEX_HOME
|
| 25 |
+
(a copy of its auth.json, no API key; endpoint the ChatGPT Codex backend unless --api-base-url);
|
| 26 |
+
--codex-auth apikey: key LFF_OPENAI_API_KEY or OPENAI_API_KEY; endpoint --api-base-url,
|
| 27 |
+
LFF_OPENAI_BASE_URL or OPENAI_BASE_URL (as api_player), else https://api.openai.com/v1
|
| 28 |
+
dsh: DeepSeek's Messages endpoint (DEEPSEEK_ANTHROPIC_URL), or --api-base-url / LFF_DSH_BASE_URL (OpenCode Go:
|
| 29 |
+
https://opencode.ai/inference/go), key LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed as DEEPSEEK_API_KEY)
|
| 30 |
+
ours: as api_player.py (its own environment)
|
| 31 |
+
|
| 32 |
+
Writes into the run's log dir: contract.json, first_message.txt, harness.json (harness name, version, argv with the
|
| 33 |
+
first message replaced by its sha256, env key names, contract_sha256, first_message_sha256, config_sha256, preflight
|
| 34 |
+
result), harness_preflight.json (full normalised fingerprint), the native event stream, trajectory.jsonl,
|
| 35 |
+
harness_audit.json. Exit codes: 0 done, 2 refused at launch (fail-closed), 3 harness error, 143 stopped.
|
| 36 |
+
"""
|
| 37 |
+
import argparse
|
| 38 |
+
import json
|
| 39 |
+
import os
|
| 40 |
+
import signal
|
| 41 |
+
import sys
|
| 42 |
+
import time
|
| 43 |
+
import traceback
|
| 44 |
+
|
| 45 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 46 |
+
sys.path.insert(0, ROOT)
|
| 47 |
+
from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER, EpisodeSpec, HarnessRefused, get_adapter, render_first_message # noqa: E402
|
| 48 |
+
from lffbench.harnesses import contract as C # noqa: E402
|
| 49 |
+
from lffbench.harnesses import redteam as RT # noqa: E402
|
| 50 |
+
|
| 51 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 52 |
+
from api_player import MAX_NO_TOOL, call_server, continue_nudge # noqa: E402
|
| 53 |
+
from tool_gateway import start_gateway, stop_gateway # noqa: E402
|
| 54 |
+
import model_gateway as MG # noqa: E402
|
| 55 |
+
|
| 56 |
+
ANTHROPIC_API = "https://api.anthropic.com"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def claude_oauth_token():
|
| 60 |
+
"""The subscription token for claude_code_full --claude-auth oauth: LFF_CLAUDE_OAUTH_TOKEN, else the KEY=value
|
| 61 |
+
file LFF_CLAUDE_OAUTH_FILE. Never CLAUDE_CODE_OAUTH_TOKEN of the calling environment (that may be the calling
|
| 62 |
+
Claude Code session's own login)."""
|
| 63 |
+
tok = os.environ.get("LFF_CLAUDE_OAUTH_TOKEN")
|
| 64 |
+
if tok:
|
| 65 |
+
return tok.strip()
|
| 66 |
+
path = os.environ.get("LFF_CLAUDE_OAUTH_FILE")
|
| 67 |
+
if path and os.path.isfile(path):
|
| 68 |
+
for line in open(path):
|
| 69 |
+
k, _, v = line.strip().partition("=")
|
| 70 |
+
if k.strip().removeprefix("export ").strip() in ("LFF_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN") and v:
|
| 71 |
+
return v.strip().strip("'\"")
|
| 72 |
+
raise SystemExit("claude --claude-auth oauth: no token; run `claude setup-token` and put LFF_CLAUDE_OAUTH_TOKEN=... "
|
| 73 |
+
"into the file named by LFF_CLAUDE_OAUTH_FILE (or export LFF_CLAUDE_OAUTH_TOKEN)")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def default_claude_auth(harness):
|
| 77 |
+
return "apikey" if harness == "claude_code" else "oauth"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def api_env_for(harness, base_url, codex_auth="apikey", claude_auth="apikey", codex_provider="openai"):
|
| 81 |
+
"""-> (variables passed to the harness, endpoint or None, endpoint label for harness.json). Endpoints are never
|
| 82 |
+
written to the logs, only where they came from."""
|
| 83 |
+
if harness in ROBOT_HARNESSES:
|
| 84 |
+
if harness == "rpent_codex":
|
| 85 |
+
codex_auth = "apikey" # historical RPent implementation stays unchanged
|
| 86 |
+
harness = "codex"
|
| 87 |
+
if harness.startswith("claude_code"):
|
| 88 |
+
e = {}
|
| 89 |
+
if claude_auth == "oauth":
|
| 90 |
+
e["CLAUDE_CODE_OAUTH_TOKEN"] = claude_oauth_token()
|
| 91 |
+
else:
|
| 92 |
+
key = os.environ.get("LFF_ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY")
|
| 93 |
+
if key:
|
| 94 |
+
e["ANTHROPIC_API_KEY"] = key
|
| 95 |
+
url = base_url or os.environ.get("LFF_ANTHROPIC_BASE_URL")
|
| 96 |
+
if url:
|
| 97 |
+
e["ANTHROPIC_BASE_URL"] = url
|
| 98 |
+
dflt = "CLI default (official)" + (", subscription token" if claude_auth == "oauth" else "")
|
| 99 |
+
return e, url, ("--api-base-url" if base_url else "LFF_ANTHROPIC_BASE_URL") if url else dflt
|
| 100 |
+
if harness == "dsh":
|
| 101 |
+
key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
|
| 102 |
+
from lffbench.harnesses.dsh import DEEPSEEK_ANTHROPIC_URL
|
| 103 |
+
url = base_url or os.environ.get("LFF_DSH_BASE_URL")
|
| 104 |
+
return ({"DEEPSEEK_API_KEY": key} if key else {}), url or DEEPSEEK_ANTHROPIC_URL, \
|
| 105 |
+
("--api-base-url" if base_url else "LFF_DSH_BASE_URL") if url else \
|
| 106 |
+
"DeepSeek (DEEPSEEK_ANTHROPIC_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)"
|
| 107 |
+
if harness == "codex" and codex_provider == "deepseek": # DeepSeek's own Responses endpoint, an API key
|
| 108 |
+
key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
|
| 109 |
+
from lffbench.harnesses.codex import DEEPSEEK_URL
|
| 110 |
+
return ({"OPENAI_API_KEY": key} if key else {}), base_url or DEEPSEEK_URL, \
|
| 111 |
+
"--api-base-url" if base_url else "DeepSeek (DEEPSEEK_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)"
|
| 112 |
+
if harness == "codex" and codex_provider == "opencode": # OpenCode Go's Responses endpoint, an API key
|
| 113 |
+
key = os.environ.get("LFF_OPENCODE_API_KEY") or os.environ.get("OPENCODE_API_KEY")
|
| 114 |
+
from lffbench.harnesses.codex import OPENCODE_GO_URL
|
| 115 |
+
return ({"OPENAI_API_KEY": key} if key else {}), base_url or OPENCODE_GO_URL, \
|
| 116 |
+
"--api-base-url" if base_url else "OpenCode Go (OPENCODE_GO_URL, key LFF_OPENCODE_API_KEY / OPENCODE_API_KEY)"
|
| 117 |
+
if harness == "codex" and codex_auth == "chatgpt":
|
| 118 |
+
return {}, base_url, "--api-base-url" if base_url else "ChatGPT Codex backend (subscription login)"
|
| 119 |
+
if harness == "codex":
|
| 120 |
+
key = os.environ.get("LFF_OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY")
|
| 121 |
+
src = ("--api-base-url" if base_url else "LFF_OPENAI_BASE_URL" if os.environ.get("LFF_OPENAI_BASE_URL")
|
| 122 |
+
else "OPENAI_BASE_URL (same as api_player)" if os.environ.get("OPENAI_BASE_URL") else "official default")
|
| 123 |
+
url = base_url or os.environ.get("LFF_OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL")
|
| 124 |
+
return ({"OPENAI_API_KEY": key} if key else {}), url, src
|
| 125 |
+
return {}, None, "api_player's own environment"
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
RESUME_RETRIES = 3 # a resumed CLI that exits before writing any event is started again (nothing reached the model)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def mcp_tool_state(log_dir):
|
| 132 |
+
"""-> (number of MCP tool calls so far, whether our MCP server saw the episode end) from mcp_transcript.jsonl."""
|
| 133 |
+
n, finished = 0, False
|
| 134 |
+
try:
|
| 135 |
+
for line in open(os.path.join(log_dir, "mcp_transcript.jsonl")):
|
| 136 |
+
try:
|
| 137 |
+
d = json.loads(line)
|
| 138 |
+
except ValueError:
|
| 139 |
+
continue
|
| 140 |
+
if d.get("ev") == "tool":
|
| 141 |
+
n, finished = n + 1, bool(d.get("finished"))
|
| 142 |
+
except OSError:
|
| 143 |
+
pass
|
| 144 |
+
return n, finished
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def continue_episode(ad, h, ep, stop):
|
| 148 |
+
"""The CLI exited although the episode is not over (it ends when the model replies without a tool call): send
|
| 149 |
+
the reference driver's nudge as a user turn, as api_player does after such a reply, and wait again. Same rule:
|
| 150 |
+
after MAX_NO_TOOL nudges in a row without a tool call in between, the next such reply ends the run. -> log list."""
|
| 151 |
+
out, no_tool, (n_calls, _) = [], 0, mcp_tool_state(ep.log_dir)
|
| 152 |
+
deadline = h.t_start + h.spec.timeout_s
|
| 153 |
+
while ad.can_resume and h.exit_reason == "exited" and not stop["flag"]:
|
| 154 |
+
n, finished = mcp_tool_state(ep.log_dir)
|
| 155 |
+
if finished: # api_player stops here too, without a status call
|
| 156 |
+
break
|
| 157 |
+
try: # the status call api_player makes for its nudge
|
| 158 |
+
stx = json.loads(call_server(ep.port, ep.token, "status", {}))
|
| 159 |
+
except Exception as e:
|
| 160 |
+
out.append(dict(ev="status_failed", error=f"{type(e).__name__}: {e}"[:300], t=time.time()))
|
| 161 |
+
break
|
| 162 |
+
if stx.get("finished"):
|
| 163 |
+
break
|
| 164 |
+
no_tool = 1 if n > n_calls else no_tool + 1
|
| 165 |
+
n_calls = n
|
| 166 |
+
if no_tool > MAX_NO_TOOL:
|
| 167 |
+
out.append(dict(ev="abort", reason=f"no tool call {no_tool} times", t=time.time()))
|
| 168 |
+
break
|
| 169 |
+
if time.time() >= deadline:
|
| 170 |
+
h.exit_reason = "timeout"
|
| 171 |
+
break
|
| 172 |
+
msg = continue_nudge(ep.port, ep.token, stx)
|
| 173 |
+
out.append(dict(ev="resume", message=msg, attempt=stx.get("attempt"), mcp_tool_calls=n, t=time.time()))
|
| 174 |
+
for retry in range(RESUME_RETRIES + 1):
|
| 175 |
+
size0 = os.path.getsize(h.spec.stdout_path) if os.path.exists(h.spec.stdout_path) else 0
|
| 176 |
+
ad.resume(h, msg)
|
| 177 |
+
ad.wait(h, timeout=max(1.0, deadline - time.time()))
|
| 178 |
+
grew = os.path.exists(h.spec.stdout_path) and os.path.getsize(h.spec.stdout_path) > size0
|
| 179 |
+
if h.exit_reason == "exited" or grew or stop["flag"] or retry == RESUME_RETRIES \
|
| 180 |
+
or time.time() + 30 >= deadline:
|
| 181 |
+
break
|
| 182 |
+
# the resumed CLI exited before writing any event (2026-10-20: the MCP handshake timed out on a loaded
|
| 183 |
+
# machine), so nothing reached the model: start the same resume again
|
| 184 |
+
out.append(dict(ev="resume_retry", exit_reason=h.exit_reason, t=time.time()))
|
| 185 |
+
time.sleep(30)
|
| 186 |
+
return out
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def model_upstream(harness, url, codex_auth):
|
| 190 |
+
"""-> (gateway kind, the model API the harness would call without the gateway)."""
|
| 191 |
+
if harness.startswith("claude_code") or harness == "dsh":
|
| 192 |
+
return "anthropic", url or ANTHROPIC_API
|
| 193 |
+
from lffbench.harnesses.codex import CHATGPT_BACKEND, OFFICIAL_API
|
| 194 |
+
if harness == "rpent_codex":
|
| 195 |
+
return "openai", url or OFFICIAL_API
|
| 196 |
+
return "openai", url or (CHATGPT_BACKEND if codex_auth == "chatgpt" else OFFICIAL_API)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def plain_config_sha256(ad, spec, ep, mg):
|
| 200 |
+
"""config_sha256 as if the harness called its model API directly: the model gateway is plumbing (like the
|
| 201 |
+
proxy variables, base.py PROXY_KEYS), so runs with and without it keep the same configuration hash."""
|
| 202 |
+
if not mg:
|
| 203 |
+
return ad.config_sha256(spec, ep)
|
| 204 |
+
import copy
|
| 205 |
+
s2 = copy.copy(spec)
|
| 206 |
+
s2.argv = [a.replace(mg["url"], mg["upstream"]) if isinstance(a, str) else a for a in spec.argv]
|
| 207 |
+
s2.env = {k: (v.replace(mg["url"], mg["upstream"]) if isinstance(v, str) else v) for k, v in spec.env.items()}
|
| 208 |
+
return ad.config_sha256(s2, ep)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def write_json(path, d):
|
| 212 |
+
tmp = path + ".tmp"
|
| 213 |
+
with open(tmp, "w") as f:
|
| 214 |
+
json.dump(d, f, indent=1, ensure_ascii=False, default=str)
|
| 215 |
+
os.replace(tmp, path)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def run(a, adapter_kw=None):
|
| 219 |
+
"""Returns (exit code, harness.json dict). adapter_kw overrides adapter construction (self-check)."""
|
| 220 |
+
provider = a.provider or PROVIDER.get(a.harness, "")
|
| 221 |
+
ep = EpisodeSpec.from_session(a.session, a.model, a.effort, provider)
|
| 222 |
+
if getattr(a, "red_team", False): # before the contract: red-team runs get their own contract_sha256
|
| 223 |
+
if a.harness == "ours":
|
| 224 |
+
raise SystemExit("--red-team is for native harnesses")
|
| 225 |
+
RT.mark(ep.log_dir)
|
| 226 |
+
contract, csha = C.write_contract(ep.log_dir)
|
| 227 |
+
mg_box = {} # the model gateway process, stopped whatever happens below
|
| 228 |
+
try:
|
| 229 |
+
return _run(a, adapter_kw, provider, ep, csha, mg_box)
|
| 230 |
+
finally:
|
| 231 |
+
MG.stop_model_gateway(mg_box.get("proc"))
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _run(a, adapter_kw, provider, ep, csha, mg_box):
|
| 235 |
+
mg = None
|
| 236 |
+
if adapter_kw is None:
|
| 237 |
+
a.codex_auth = getattr(a, "codex_auth", None) or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt")
|
| 238 |
+
if a.harness == "rpent_codex" and a.codex_auth != "apikey":
|
| 239 |
+
raise SystemExit("Historical RPent adapter supports apikey only")
|
| 240 |
+
claude_auth = getattr(a, "claude_auth", None) or default_claude_auth(a.harness)
|
| 241 |
+
if getattr(a, "codex_provider", "openai") in ("deepseek", "opencode"):
|
| 242 |
+
a.codex_auth = "apikey" # no subscription login for DeepSeek / OpenCode Go
|
| 243 |
+
api_env, url, endpoint = api_env_for(a.harness, a.api_base_url, getattr(a, "codex_auth", "apikey"),
|
| 244 |
+
claude_auth, getattr(a, "codex_provider", "openai"))
|
| 245 |
+
if a.harness != "ours" and not getattr(a, "no_model_gateway", False):
|
| 246 |
+
# the harness reaches its model API only through the model gateway (scripts/model_gateway.py)
|
| 247 |
+
kind, upstream = model_upstream(a.harness, url, a.codex_auth)
|
| 248 |
+
mg_box["proc"], mginfo = MG.start_model_gateway(upstream, kind, ep.log_dir,
|
| 249 |
+
getattr(a, "token_budget_in", None),
|
| 250 |
+
getattr(a, "token_budget_out", None),
|
| 251 |
+
allow_files=a.harness == "dsh")
|
| 252 |
+
mg = dict(url=mginfo["url"], upstream=upstream, kind=kind, upstream_host=mginfo["upstream_host"],
|
| 253 |
+
pid=mginfo["pid"])
|
| 254 |
+
url = mg["url"]
|
| 255 |
+
if a.harness.startswith("claude_code"):
|
| 256 |
+
api_env["ANTHROPIC_BASE_URL"] = url
|
| 257 |
+
adapter_kw = dict(timeout_s=a.timeout)
|
| 258 |
+
if a.harness.startswith("claude_code"):
|
| 259 |
+
adapter_kw.update(api_env=api_env, max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned,
|
| 260 |
+
auth=claude_auth)
|
| 261 |
+
elif a.harness == "codex":
|
| 262 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, auth=a.codex_auth,
|
| 263 |
+
catalog=a.codex_catalog)
|
| 264 |
+
elif a.harness == "dsh":
|
| 265 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned)
|
| 266 |
+
elif a.harness in ROBOT_HARNESSES:
|
| 267 |
+
adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned,
|
| 268 |
+
auth=a.codex_auth, catalog=a.codex_catalog)
|
| 269 |
+
if a.harness == "rpent_codex": # historical, explicitly exposed RPent experiment settings
|
| 270 |
+
adapter_kw.update(sessions=a.rpent_sessions, attempts_per_session=a.rpent_attempts_per_session,
|
| 271 |
+
max_turns=a.rpent_max_turns)
|
| 272 |
+
if getattr(a, "jail", False):
|
| 273 |
+
if a.harness == "ours":
|
| 274 |
+
raise SystemExit("--jail is for native harnesses")
|
| 275 |
+
adapter_kw["jail"] = True
|
| 276 |
+
else:
|
| 277 |
+
adapter_kw.update(provider=provider)
|
| 278 |
+
else:
|
| 279 |
+
endpoint = "set by the caller (self-check)"
|
| 280 |
+
ad = get_adapter(a.harness, **adapter_kw)
|
| 281 |
+
ver = ad.version()
|
| 282 |
+
hj_path = os.path.join(ep.log_dir, "harness.json")
|
| 283 |
+
hj = dict(harness=ad.name, version=ver.get("version"), binary=ver.get("binary"), model=a.model, effort=a.effort,
|
| 284 |
+
provider=provider, capabilities={k: vars(c) for k, c in ad.capabilities.items()},
|
| 285 |
+
contract_sha256=csha, task=ep.task, seed=ep.seed, api_endpoint_from=endpoint, status="preparing",
|
| 286 |
+
t_prepare=time.time(), jail=ad.jail_info(), auth=ad.auth_info() if ad.name != "ours" else None,
|
| 287 |
+
config=ad.config_info() if hasattr(ad, "config_info") else None,
|
| 288 |
+
model_gateway=({k: mg[k] for k in ("kind", "upstream_host", "pid")} if mg else None))
|
| 289 |
+
if ad.name == "ours":
|
| 290 |
+
first = None
|
| 291 |
+
spec = ad.prepare(ep)
|
| 292 |
+
else:
|
| 293 |
+
first, _ = render_first_message(ep)
|
| 294 |
+
if getattr(a, "red_team", False):
|
| 295 |
+
first = RT.first_message(first)
|
| 296 |
+
hj["red_team"] = RT.marker(ep.log_dir)
|
| 297 |
+
with open(os.path.join(ep.log_dir, "first_message.txt"), "w") as f:
|
| 298 |
+
f.write(first)
|
| 299 |
+
spec = ad.prepare(ep, first, **(dict(reuse_state=a.reuse_state) if getattr(a, "reuse_state", None) else {}))
|
| 300 |
+
hj["first_message_sha256"] = C.sha256_text(first)
|
| 301 |
+
hj.update(argv=ad.logged_argv(spec), cwd=spec.cwd, env_keys=sorted(spec.env),
|
| 302 |
+
env_mode="exact whitelist (Popen env=, same as env -i)" if ad.name != "ours" else "inherited (own code)",
|
| 303 |
+
state_dirs=spec.state_dirs, config_sha256=plain_config_sha256(ad, spec, ep, mg), status="launching")
|
| 304 |
+
write_json(hj_path, hj)
|
| 305 |
+
h, code, gw = None, 0, None
|
| 306 |
+
stop = dict(flag=False)
|
| 307 |
+
|
| 308 |
+
def on_term(*_):
|
| 309 |
+
stop["flag"] = True
|
| 310 |
+
if h is not None and h.proc is not None:
|
| 311 |
+
ad.kill(h)
|
| 312 |
+
signal.signal(signal.SIGTERM, on_term)
|
| 313 |
+
try:
|
| 314 |
+
if (ad.uses_mcp or ad.uses_gateway) and not getattr(a, "no_gateway", False): # the episode's tools, for
|
| 315 |
+
# every MCP process of the run / every SDK client of a framework adapter (base.HarnessAdapter.uses_gateway)
|
| 316 |
+
gw, ginfo = start_gateway(ep.session_path)
|
| 317 |
+
hj["gateway"] = dict(url=ginfo["url"], pid=ginfo["pid"])
|
| 318 |
+
try:
|
| 319 |
+
h = ad.launch(spec, ep, skip_preflight=getattr(a, "skip_preflight", False))
|
| 320 |
+
except HarnessRefused as e:
|
| 321 |
+
pre = dict(spec.preflight or {})
|
| 322 |
+
hj.update(status="refused", refused=str(e), preflight={k: v for k, v in pre.items() if k != "fingerprint"})
|
| 323 |
+
write_json(hj_path, hj)
|
| 324 |
+
print("REFUSED:", e, flush=True)
|
| 325 |
+
return 2, hj
|
| 326 |
+
pre = dict(spec.preflight or {})
|
| 327 |
+
if "fingerprint" in pre:
|
| 328 |
+
write_json(os.path.join(ep.log_dir, "harness_preflight.json"), pre)
|
| 329 |
+
hj.update(status="running", pid=h.pid, env_observed_keys=h.env_observed_keys, t_start=h.t_start,
|
| 330 |
+
preflight={k: v for k, v in pre.items() if k != "fingerprint"}, init=h.info.get("init"))
|
| 331 |
+
write_json(hj_path, hj)
|
| 332 |
+
ad.wait(h)
|
| 333 |
+
cont = [] if getattr(a, "no_continue", False) else continue_episode(ad, h, ep, stop)
|
| 334 |
+
if cont:
|
| 335 |
+
hj["continuation"] = cont
|
| 336 |
+
write_json(hj_path, hj)
|
| 337 |
+
if stop["flag"]:
|
| 338 |
+
h.exit_reason, code = "stopped", 143
|
| 339 |
+
tw = ad.collect(h)
|
| 340 |
+
au = ad.audit(h)
|
| 341 |
+
if ad.name == "ours" and spec.first_message:
|
| 342 |
+
hj["first_message_sha256"] = C.sha256_text(spec.first_message)
|
| 343 |
+
hj.update(status="done" if code == 0 else "stopped", exit_code=h.exit_code, exit_reason=h.exit_reason,
|
| 344 |
+
t_end=h.t_end, wall_s=round(h.t_end - h.t_start, 1), audit_ok=au.get("ok"),
|
| 345 |
+
violations=au.get("violations"), final_metrics=(tw.final or {}).get("final_metrics"))
|
| 346 |
+
if mg: # refusals do not void the trial; they flag it for a look (EFE running.md "Usage gateway")
|
| 347 |
+
tot = MG.read_totals(ep.log_dir) or {}
|
| 348 |
+
hj["model_gateway"].update({k: tot.get(k) for k in MG.Totals.KEYS}, tokens=tot.get("tokens"),
|
| 349 |
+
models=tot.get("models"), budget_stop=tot.get("budget_stop"))
|
| 350 |
+
hj["review_flags"] = ["model_gateway:" + k for k in MG.flagged(tot)] + (
|
| 351 |
+
["model_gateway:other_model"] if set(tot.get("models") or {}) - {a.model} else [])
|
| 352 |
+
if code == 0 and h.exit_code not in (0, None):
|
| 353 |
+
code = 3
|
| 354 |
+
write_json(hj_path, hj)
|
| 355 |
+
return code, hj
|
| 356 |
+
except Exception as e:
|
| 357 |
+
hj.update(status="error", error=f"{type(e).__name__}: {e}", traceback=traceback.format_exc()[-3000:])
|
| 358 |
+
write_json(hj_path, hj)
|
| 359 |
+
if h is not None and h.proc is not None and h.proc.poll() is None:
|
| 360 |
+
ad.kill(h)
|
| 361 |
+
return 3, hj
|
| 362 |
+
finally:
|
| 363 |
+
stop_gateway(gw)
|
| 364 |
+
if not getattr(a, "keep_run_dir", False):
|
| 365 |
+
ad.cleanup(spec)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def parser():
|
| 369 |
+
ap = argparse.ArgumentParser()
|
| 370 |
+
ap.add_argument("--harness", required=True, choices=NAMES)
|
| 371 |
+
ap.add_argument("--session", required=True)
|
| 372 |
+
ap.add_argument("--provider", default=None, help="ours: openai / anthropic / gemini / chat")
|
| 373 |
+
ap.add_argument("--model", required=True)
|
| 374 |
+
ap.add_argument("--effort", default="high")
|
| 375 |
+
ap.add_argument("--api-base-url", default=None)
|
| 376 |
+
ap.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"],
|
| 377 |
+
help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. "
|
| 378 |
+
"SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only")
|
| 379 |
+
ap.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"],
|
| 380 |
+
help="claude_code*: subscription token (default for claude_code_full) or an API key (claude_code, "
|
| 381 |
+
"--bare, takes only an API key); see above")
|
| 382 |
+
ap.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"],
|
| 383 |
+
help="codex: model provider; deepseek = DeepSeek's Responses endpoint with LFF_DEEPSEEK_API_KEY / "
|
| 384 |
+
"DEEPSEEK_API_KEY, opencode = OpenCode Go's with LFF_OPENCODE_API_KEY / OPENCODE_API_KEY "
|
| 385 |
+
"(both imply --codex-auth apikey)")
|
| 386 |
+
ap.add_argument("--codex-catalog", default="generic", choices=["generic", "native"],
|
| 387 |
+
help="codex: model catalog, the main table's shared configuration (default) or Codex's native "
|
| 388 |
+
"one (control); see lffbench/harnesses/codex.py")
|
| 389 |
+
ap.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: --max-budget-usd")
|
| 390 |
+
ap.add_argument("--rpent-sessions", type=int, default=5,
|
| 391 |
+
help="rpent_codex: planner sessions per episode (RPent --explore-sessions; default 5 = k + 2 spare)")
|
| 392 |
+
ap.add_argument("--rpent-attempts-per-session", type=int, default=1,
|
| 393 |
+
help="rpent_codex: attempts one session may use (RPent --explore-attempts-per-session): 1 = "
|
| 394 |
+
"variant H, a fresh session with a handoff after each failed attempt (default); 0 = no limit")
|
| 395 |
+
ap.add_argument("--rpent-max-turns", type=int, default=100,
|
| 396 |
+
help="rpent_codex: model responses per session (RPent --max-turns)")
|
| 397 |
+
ap.add_argument("--timeout", type=float, default=10800)
|
| 398 |
+
ap.add_argument("--allow-unpinned", action="store_true",
|
| 399 |
+
help="launch even if no pin exists for this version / model / effort (the preflight still runs)")
|
| 400 |
+
ap.add_argument("--keep-run-dir", action="store_true", help="do not delete the one-time dirs (debugging)")
|
| 401 |
+
ap.add_argument("--no-gateway", action="store_true",
|
| 402 |
+
help="native harnesses: run the tools inside each MCP server process instead of the episode's "
|
| 403 |
+
"tool gateway (scripts/tool_gateway.py; same ToolCore, budget carried over via the transcript)")
|
| 404 |
+
ap.add_argument("--no-model-gateway", action="store_true",
|
| 405 |
+
help="native harnesses: call the model API directly instead of through the run's model gateway "
|
| 406 |
+
"(scripts/model_gateway.py: model calls only, provider-side tools refused, tokens counted)")
|
| 407 |
+
ap.add_argument("--token-budget-in", type=int, default=None,
|
| 408 |
+
help="model gateway: refuse further model calls once this many input tokens were used (cached "
|
| 409 |
+
"input counts in full)")
|
| 410 |
+
ap.add_argument("--token-budget-out", type=int, default=None,
|
| 411 |
+
help="model gateway: ... output tokens (reasoning included)")
|
| 412 |
+
ap.add_argument("--red-team", action="store_true",
|
| 413 |
+
help="adversarial acceptance run (lffbench/harnesses/redteam.py): the first message starts with the "
|
| 414 |
+
"red-team notice; own contract_sha256; read with scripts/redteam_report.py")
|
| 415 |
+
ap.add_argument("--no-continue", action="store_true",
|
| 416 |
+
help="do not resume a CLI that exited before the episode was over (self-check / debugging)")
|
| 417 |
+
ap.add_argument("--jail", action="store_true",
|
| 418 |
+
help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4): as uid 65534, no host "
|
| 419 |
+
"path visible, MCP server outside behind a socket relay")
|
| 420 |
+
return ap
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def main():
|
| 424 |
+
code, hj = run(parser().parse_args())
|
| 425 |
+
print(json.dumps({k: hj.get(k) for k in ("harness", "status", "exit_reason", "audit_ok", "violations",
|
| 426 |
+
"contract_sha256", "final_metrics")}, default=str), flush=True)
|
| 427 |
+
sys.exit(code)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
if __name__ == "__main__":
|
| 431 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/ladder_gpt_plan.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layer-3 feedback ladder for GPT-6 Astra (user 2026-11-02: "跑吧"; same design as scripts/ladder_plan.py, docs/20).
|
| 2 |
+
Instances: the main-table attempt 1 failures of GPT-6 Astra on the 8 ladder tasks (turntable left out, as in the
|
| 3 |
+
reported Claude totals). Fresh single-attempt agents, Codex 0.163 generic config, jail, high, F1, one round. The F1 rung
|
| 4 |
+
is run here (batch lf1_gpt): GPT has no mismatch-control Do arm to reuse.
|
| 5 |
+
|
| 6 |
+
python scripts/ladder_gpt_plan.py validate Fix texts for instances Claude's ladder did not cover -> results/_ladder/fix_validate_gpt.json
|
| 7 |
+
python scripts/ladder_gpt_plan.py build records -> runs/api/ladder_gpt_20261102/<rung>.json + tasks.txt
|
| 8 |
+
python scripts/ladder_gpt_plan.py report per instance rungs and totals, next to Opus and Sonnet
|
| 9 |
+
"""
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 16 |
+
import ladder_plan as L # noqa: E402
|
| 17 |
+
|
| 18 |
+
ROOT, API = L.ROOT, L.API
|
| 19 |
+
OUT = os.path.join(API, "ladder_gpt_20261102")
|
| 20 |
+
BATCHES = ["cx_main1", "cx_astra_s2", "cx_astra_s3"]
|
| 21 |
+
TASKS = {"l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool",
|
| 22 |
+
"l4_fit_container", "l3_card_shelf", "l5_loaded_beam"}
|
| 23 |
+
FIXV_GPT = os.path.join(ROOT, "results", "_ladder", "fix_validate_gpt.json")
|
| 24 |
+
RUNGS = ("F1", "F2", "hplus", "fix")
|
| 25 |
+
BATCH = {"F1": "lf1_gpt", "F2": "lf2_gpt", "hplus": "lhp_gpt", "fix": "lfx_gpt"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def instances():
|
| 29 |
+
out = {}
|
| 30 |
+
for b in BATCHES:
|
| 31 |
+
for r in json.load(open(os.path.join(API, b, "manifest.json")))["runs"]:
|
| 32 |
+
if r["cond"] != "harness" or r["status"] != "done" or r["task"] not in TASKS:
|
| 33 |
+
continue
|
| 34 |
+
d = next((e for e in L.events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
|
| 35 |
+
if d is not None and not d["success"]:
|
| 36 |
+
out[f"{r['task']}:{r['seed']}"] = r["log"]
|
| 37 |
+
return out
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def fixes():
|
| 41 |
+
rows = json.load(open(L.FIXV))["rows"]
|
| 42 |
+
if os.path.exists(FIXV_GPT):
|
| 43 |
+
rows += json.load(open(FIXV_GPT))["rows"]
|
| 44 |
+
return {r["key"]: r for r in rows}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def cmd_validate():
|
| 48 |
+
import validate_ladder_fix as V
|
| 49 |
+
have = fixes()
|
| 50 |
+
want = {k: v for k, v in instances().items() if not have.get(k, {}).get("ok")}
|
| 51 |
+
print("to validate:", sorted(want))
|
| 52 |
+
if not want:
|
| 53 |
+
return
|
| 54 |
+
V.instances = lambda: {k: dict(task=k.split(":")[0], seed=int(k.split(":")[1]), models=["gpt"],
|
| 55 |
+
logged=json.loads(open(os.path.join(v, "events.jsonl")).readline())["inst"]) for k, v in want.items()}
|
| 56 |
+
sys.argv = ["validate_ladder_fix.py", "--out", FIXV_GPT]
|
| 57 |
+
V.main()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def cmd_build():
|
| 61 |
+
fx = fixes(); inst = instances(); os.makedirs(OUT, exist_ok=True)
|
| 62 |
+
open(os.path.join(OUT, "tasks.txt"), "w").write("\n".join(sorted(inst)) + "\n")
|
| 63 |
+
out = {r: {} for r in RUNGS}
|
| 64 |
+
for key, log in sorted(inst.items()):
|
| 65 |
+
task, seed = key.split(":")
|
| 66 |
+
tx = dict(L.texts(dict(log=log, task=task, seed=int(seed)), fx), F1="")
|
| 67 |
+
for r in RUNGS:
|
| 68 |
+
dst = os.path.join(OUT, r, f"{task}_s{seed}")
|
| 69 |
+
if not os.path.isdir(dst):
|
| 70 |
+
cmd = [sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst] + (["--result-extra", tx[r]] if tx[r] else [])
|
| 71 |
+
subprocess.run(cmd, check=True, capture_output=True)
|
| 72 |
+
out[r][key] = dst
|
| 73 |
+
for r in RUNGS:
|
| 74 |
+
json.dump(out[r], open(os.path.join(OUT, f"{r}.json"), "w"), indent=1)
|
| 75 |
+
print(len(inst), "instances x", len(RUNGS), "rungs")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def cmd_report():
|
| 79 |
+
keys = [l.strip() for l in open(os.path.join(OUT, "tasks.txt")) if l.strip()]
|
| 80 |
+
res = {r: L.single(BATCH[r]) for r in RUNGS}
|
| 81 |
+
f = lambda v: "-" if v is None else ("S" if v else "F")
|
| 82 |
+
print("| instance | F1 | F2 | H+ | Fix |\n|---|---|---|---|---|")
|
| 83 |
+
for k in keys:
|
| 84 |
+
print(f"| {k} | " + " | ".join(f(res[r].get(k)) for r in RUNGS) + " |")
|
| 85 |
+
rows = [{r: res[r].get(k) for r in RUNGS} for k in keys]
|
| 86 |
+
tot = {r: [sum(bool(x[r]) for x in rows if x[r] is not None), sum(x[r] is not None for x in rows)] for r in RUNGS}
|
| 87 |
+
print("totals:", ", ".join(f"{r} {tot[r][0]}/{tot[r][1]}" for r in RUNGS))
|
| 88 |
+
for lo, hi in zip(RUNGS, RUNGS[1:]):
|
| 89 |
+
both = [x for x in rows if x[lo] is not None and x[hi] is not None]
|
| 90 |
+
print(f"{lo}->{hi}: n={len(both)} up {sum(bool(x[hi]) and not x[lo] for x in both)} down {sum(bool(x[lo]) and not x[hi] for x in both)}")
|
| 91 |
+
json.dump(dict(rows=[dict(inst=k, **{r: res[r].get(k) for r in RUNGS}) for k in keys], totals=tot), open(os.path.join(OUT, "report.json"), "w"), indent=1)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
{"validate": cmd_validate, "build": cmd_build, "report": cmd_report}[sys.argv[1]]()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/record_breakfast_service.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Continuous simulation recording with a magnified crop; no state edits or model calls."""
|
| 2 |
+
import argparse, hashlib, json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import imageio.v2 as imageio
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 7 |
+
from lffbench import envs
|
| 8 |
+
from lffbench.tasks.lh_breakfast_service import BreakfastService
|
| 9 |
+
import robosuite.utils.transform_utils as T
|
| 10 |
+
|
| 11 |
+
FONT='/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf'
|
| 12 |
+
|
| 13 |
+
class Recorder:
|
| 14 |
+
def __init__(self,t,out):
|
| 15 |
+
self.t=t;self.out=out;self.n=0;self.frames=0;self.timeline=[]
|
| 16 |
+
self.phase='Prepare breakfast';self.focus='food';self.raw_n=0
|
| 17 |
+
self.raw=imageio.get_writer(str(out/'breakfast_full_1x.mp4'),fps=5,codec='libx264',quality=8,macro_block_size=1)
|
| 18 |
+
self.preview=imageio.get_writer(str(out/'breakfast_recovery_2x.mp4'),fps=10,codec='libx264',quality=8,macro_block_size=1)
|
| 19 |
+
self.original=t.env.step;t.env.step=self.step
|
| 20 |
+
# Rendering-only side camera makes the reopened lid's gap visible.
|
| 21 |
+
m=t.env.sim.model;cid=m.camera_name2id('sideview')
|
| 22 |
+
pos=np.array([-.28,-.58,1.16]);target=np.array([-.20,-.10,.96])
|
| 23 |
+
z=(pos-target)/np.linalg.norm(pos-target);x=np.cross([0,0,1],z);x/=np.linalg.norm(x);y=np.cross(z,x)
|
| 24 |
+
q=T.mat2quat(np.column_stack([x,y,z]))
|
| 25 |
+
m.cam_pos[cid]=pos;m.cam_quat[cid]=q[[3,0,1,2]];m.cam_fovy[cid]=45
|
| 26 |
+
t.env.sim.forward()
|
| 27 |
+
def step(self,a):
|
| 28 |
+
result=self.original(a);self.n+=1
|
| 29 |
+
if self.n%4==0:self.capture()
|
| 30 |
+
return result
|
| 31 |
+
def frame(self):
|
| 32 |
+
return Image.fromarray(envs.render(self.t.env,res=768))
|
| 33 |
+
def decorate(self,im):
|
| 34 |
+
canvas=Image.new('RGB',(1280,928),(19,26,36));canvas.paste(im,(0,48))
|
| 35 |
+
crop={'milk':(440,180,760,500),'lid':(150,230,470,550),'food':(0,220,320,540)}[self.focus]
|
| 36 |
+
detail=(Image.fromarray(envs.render(self.t.env,cam='sideview',res=512)) if self.focus=='lid'
|
| 37 |
+
else im.crop(crop).resize((512,512),Image.Resampling.LANCZOS))
|
| 38 |
+
canvas.paste(detail,(768,80))
|
| 39 |
+
d=ImageDraw.Draw(canvas);f=ImageFont.truetype(FONT,24);sm=ImageFont.truetype(FONT,20)
|
| 40 |
+
d.text((18,10),'BREAKFAST | scripted recovery reference | same attempt | 2x',font=f,fill='white')
|
| 41 |
+
d.text((785,52),'Synchronized side view' if self.focus=='lid' else 'Magnified detail from the same frame',font=sm,fill='#b5ccdf')
|
| 42 |
+
q=self.t.liquid
|
| 43 |
+
for n,line in enumerate([f'Simulation: {self.n*.05:.1f} s',f'Milk in cup: {q["cup"]:.1f} mL',
|
| 44 |
+
f'Spilled: {q["spill"]:.1f} mL',f'Pantry lid: {self.t.lid_deg():.1f} deg',
|
| 45 |
+
f'Butter height: {100*self.t.butter_height():.1f} cm']):
|
| 46 |
+
d.text((790,620+36*n),line,font=f,fill='white')
|
| 47 |
+
d.text((18,830),self.phase,font=f,fill='#ffe0a2')
|
| 48 |
+
d.text((18,874),'Milk: simplified flow + ballistic parcels; rigid objects: MuJoCo contacts.',font=sm,fill='#b5ccdf')
|
| 49 |
+
return np.asarray(canvas)
|
| 50 |
+
def capture(self):
|
| 51 |
+
im=self.frame();self.raw.append_data(np.asarray(im));self.raw_n+=1
|
| 52 |
+
self.preview.append_data(self.decorate(im));self.frames+=1
|
| 53 |
+
def phase_hook(self,text,state):
|
| 54 |
+
if text.startswith(('Tipping handle:','Returning handle:','Bread pickup:','Bread placement:')):return
|
| 55 |
+
if 'carton' in text or 'cradle' in text or 'milk' in text.lower():self.focus='milk'
|
| 56 |
+
elif 'pantry' in text.lower() or 'L4' in text or 'lid' in text.lower() or 'inside the box' in text or 'Upright butter' in text:self.focus='lid'
|
| 57 |
+
else:self.focus='food'
|
| 58 |
+
self.phase=text
|
| 59 |
+
row=dict(state,preview_time_s=self.frames/10,preview_frame=self.frames)
|
| 60 |
+
self.timeline.append(row)
|
| 61 |
+
im=self.frame();Image.Image.save(im,self.out/f'checkpoint_{len(self.timeline):02d}.png')
|
| 62 |
+
# Explicit presentation hold only; no simulation reset or omitted motion.
|
| 63 |
+
for _ in range(10):self.preview.append_data(self.decorate(im));self.frames+=1
|
| 64 |
+
print(json.dumps(row,default=lambda v:v.item()),flush=True)
|
| 65 |
+
def close(self):
|
| 66 |
+
self.t.env.step=self.original;self.raw.close();self.preview.close()
|
| 67 |
+
|
| 68 |
+
def main():
|
| 69 |
+
p=argparse.ArgumentParser();p.add_argument('--out',required=True);p.add_argument('--seed',type=int,default=1000)
|
| 70 |
+
a=p.parse_args();out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
|
| 71 |
+
t=BreakfastService();inst=t.sample_instance(a.seed);t.reset_instance(inst)
|
| 72 |
+
r=Recorder(t,out);t.phase_hook=r.phase_hook
|
| 73 |
+
try:
|
| 74 |
+
t.execute(inst,{'mode':'adaptive'});result=t.outcome(inst)
|
| 75 |
+
r.phase_hook('FINAL: breakfast served; all three failures recovered' if result['success'] else 'FINAL: verification failed',
|
| 76 |
+
dict(step=t.sk.n_steps,outcome=result))
|
| 77 |
+
finally:r.close()
|
| 78 |
+
files=[Path(__file__).resolve().parents[1]/'lffbench/tasks'/n for n in
|
| 79 |
+
('lh_breakfast_service.py','lh_pantry_relatch.py','lh_lid_box.py')]
|
| 80 |
+
meta=dict(seed=a.seed,instance=inst,outcome=result,continuous_attempt=True,resets_during_recording=0,
|
| 81 |
+
source_hashes={str(f):hashlib.sha256(f.read_bytes()).hexdigest() for f in files},
|
| 82 |
+
sim_seconds=r.n*.05,raw_frames=r.raw_n,preview_frames=r.frames,timeline=r.timeline,
|
| 83 |
+
presentation='2x with 1 s freeze at labeled checkpoints; full 1x has no presentation freezes',
|
| 84 |
+
video_hashes={f.name:hashlib.sha256(f.read_bytes()).hexdigest() for f in out.glob('*.mp4')})
|
| 85 |
+
(out/'recording.json').write_text(json.dumps(meta,indent=2,default=lambda v:v.item()))
|
| 86 |
+
assert result['success'] and all(result['traps'].values()) and all(result['recovered'].values()),result
|
| 87 |
+
t.env.close()
|
| 88 |
+
|
| 89 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/start_real_session.sh
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Start a REAL-robot server (lffbench/real/session.py) + workspace for one task instance; same output as
|
| 3 |
+
# scripts/start_robot_session.sh (SANDBOX=, LOG=, <LOG>/session.json), so harness_run.py / api_player.py run on it unchanged.
|
| 4 |
+
# usage: scripts/start_real_session.sh <task> <seed> <memory full|none> <feedback F0|F1> <port> [instruction direct|indirect] [k] [tag]
|
| 5 |
+
# The driver: $LFF_REAL_DRIVER (default http://127.0.0.1:9900, normally an SSH tunnel to the robot PC) and $LFF_DRIVER_TOKEN.
|
| 6 |
+
# Blocks until the operator has set up the scene for attempt 1 (up to $LFF_REAL_READY_WAIT s, default 3600).
|
| 7 |
+
set -e
|
| 8 |
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
| 9 |
+
TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}
|
| 10 |
+
RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT}
|
| 11 |
+
SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))')
|
| 12 |
+
LOG=${LFF_RUNS_DIR:-$ROOT/runs/real}/$RUN
|
| 13 |
+
mkdir -p "$SANDBOX" "$LOG"
|
| 14 |
+
cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1
|
| 15 |
+
KARG=""; [ -n "$K" ] && KARG="--k $K"
|
| 16 |
+
nohup python -m lffbench.real.session --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \
|
| 17 |
+
--instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --run-name "$RUN" ${LFF_EXTRA_ARGS:-} $KARG \
|
| 18 |
+
> "$LOG/server.log" 2>&1 &
|
| 19 |
+
echo $! > "$LOG/server.pid"
|
| 20 |
+
WAIT=${LFF_REAL_READY_WAIT:-3600}
|
| 21 |
+
for i in $(seq 1 "$WAIT"); do
|
| 22 |
+
[ -f "$LOG/READY" ] && break
|
| 23 |
+
kill -0 "$(cat "$LOG/server.pid")" 2>/dev/null || break
|
| 24 |
+
[ $((i % 30)) -eq 0 ] && echo "waiting for the operator to set up the scene ($i s)" >&2
|
| 25 |
+
sleep 1
|
| 26 |
+
done
|
| 27 |
+
[ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; exit 1; }
|
| 28 |
+
echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json"
|
| 29 |
+
echo "SANDBOX=$SANDBOX"
|
| 30 |
+
echo "LOG=$LOG"
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Anthropic Messages API backend (Claude Opus 5.5 / Sonnet 5.5 / Fable 5.1 ...), official SDK `anthropic`.
|
| 2 |
+
|
| 3 |
+
Same conversation as the OpenAI backends, converted to Messages API blocks:
|
| 4 |
+
- system prompt = conv.system; tools = the harness tool specs (strict, one call per turn like the GPT player);
|
| 5 |
+
- every assistant turn is stored with its full `content` (thinking blocks with signatures, text, tool_use) and replayed
|
| 6 |
+
unchanged, so the model keeps its reasoning across tool calls. Assistant turns are never edited; old images in user
|
| 7 |
+
turns may be replaced by a text note (checked 2026-10-15 on Sonnet 5.5 / Opus 5.5 with thinking blocks in the
|
| 8 |
+
history: accepted), which the player does only when the context or the per-request image limit is reached;
|
| 9 |
+
- tool outputs of one turn become `tool_result` blocks at the start of the next user message; images the harness
|
| 10 |
+
attaches after them (observations, view_images) follow in the same user message;
|
| 11 |
+
- adaptive thinking with an explicit effort (the per-model default differs: Opus 5.5 medium, Sonnet 5.5 high);
|
| 12 |
+
- automatic prompt caching (top-level cache_control): every request caches its whole prefix for the next call;
|
| 13 |
+
- streaming, so long thinking turns do not hit the HTTP timeout.
|
| 14 |
+
No refusal fallback on purpose: a fallback would silently swap the model under test. A refusal is reported as
|
| 15 |
+
status "refusal" and the player ends the run.
|
| 16 |
+
|
| 17 |
+
Key from ANTHROPIC_API_KEY (or any credential the SDK resolves). The client is created lazily on the first real
|
| 18 |
+
call; tests inject a mock client.
|
| 19 |
+
"""
|
| 20 |
+
import time
|
| 21 |
+
|
| 22 |
+
from ..context import ToolCall, prune_live_images
|
| 23 |
+
from .base import Backend, BackendResponse, import_sdk
|
| 24 |
+
|
| 25 |
+
EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _get(obj, key, default=None):
|
| 29 |
+
if isinstance(obj, dict):
|
| 30 |
+
return obj.get(key, default)
|
| 31 |
+
return getattr(obj, key, default)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _to_dict(block):
|
| 35 |
+
if isinstance(block, dict):
|
| 36 |
+
return dict(block)
|
| 37 |
+
if hasattr(block, "to_dict"):
|
| 38 |
+
return block.to_dict()
|
| 39 |
+
return block.model_dump(mode="json", exclude_none=True)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def anthropic_tools(specs, strict=True):
|
| 43 |
+
out = []
|
| 44 |
+
for s in specs:
|
| 45 |
+
t = dict(name=s["name"], description=s["description"], input_schema=s["parameters"])
|
| 46 |
+
if strict:
|
| 47 |
+
t["strict"] = True
|
| 48 |
+
out.append(t)
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def image_block(image, quality=None):
|
| 53 |
+
url = image.data_url(quality)
|
| 54 |
+
head, data = url.split(",", 1) # data:<mime>;base64,<data>
|
| 55 |
+
mime = head[len("data:"):].split(";", 1)[0]
|
| 56 |
+
return dict(type="image", source=dict(type="base64", media_type=mime, data=data))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class AnthropicMessagesBackend(Backend):
|
| 60 |
+
name = "anthropic"
|
| 61 |
+
|
| 62 |
+
def __init__(self, model="claude-opus-5-5", effort="high", thinking_display="summarized", max_tokens=64000,
|
| 63 |
+
max_live_images=None, jpeg_quality=90, timeout=900.0, max_retries=2, strict_tools=True,
|
| 64 |
+
parallel_tool_calls=False, cache=True, client=None):
|
| 65 |
+
if effort not in EFFORTS:
|
| 66 |
+
raise ValueError(f"effort must be one of {EFFORTS}, got {effort!r}")
|
| 67 |
+
self.model = model
|
| 68 |
+
self.effort = effort
|
| 69 |
+
self.thinking_display = thinking_display # "summarized" (logged as the reasoning summary) | "omitted"
|
| 70 |
+
self.max_tokens = max_tokens
|
| 71 |
+
self.max_live_images = max_live_images
|
| 72 |
+
self.jpeg_quality = jpeg_quality
|
| 73 |
+
self.timeout = timeout
|
| 74 |
+
self.max_retries = max_retries
|
| 75 |
+
self.strict_tools = strict_tools
|
| 76 |
+
self.parallel_tool_calls = parallel_tool_calls
|
| 77 |
+
self.cache = cache
|
| 78 |
+
self._client = client
|
| 79 |
+
|
| 80 |
+
def config(self):
|
| 81 |
+
return dict(name=self.name, model=self.model, effort=self.effort, thinking_display=self.thinking_display,
|
| 82 |
+
max_tokens=self.max_tokens, max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality,
|
| 83 |
+
timeout=self.timeout, max_retries=self.max_retries, strict_tools=self.strict_tools,
|
| 84 |
+
parallel_tool_calls=self.parallel_tool_calls, cache=self.cache)
|
| 85 |
+
|
| 86 |
+
def client(self):
|
| 87 |
+
if self._client is None:
|
| 88 |
+
anthropic = import_sdk("anthropic")
|
| 89 |
+
self._client = anthropic.Anthropic(timeout=self.timeout, max_retries=self.max_retries)
|
| 90 |
+
return self._client
|
| 91 |
+
|
| 92 |
+
# ------------------------------------------------------------------ request
|
| 93 |
+
def convert_items(self, items):
|
| 94 |
+
msgs = []
|
| 95 |
+
|
| 96 |
+
def push(role, blocks):
|
| 97 |
+
if msgs and msgs[-1]["role"] == role:
|
| 98 |
+
msgs[-1]["content"].extend(blocks)
|
| 99 |
+
else:
|
| 100 |
+
msgs.append(dict(role=role, content=list(blocks)))
|
| 101 |
+
|
| 102 |
+
for it in items:
|
| 103 |
+
kind = it["kind"]
|
| 104 |
+
if kind == "user":
|
| 105 |
+
blocks = []
|
| 106 |
+
for p in it["parts"]:
|
| 107 |
+
if p["type"] == "text":
|
| 108 |
+
blocks.append(dict(type="text", text=p["text"]))
|
| 109 |
+
else:
|
| 110 |
+
blocks.append(image_block(p["image"], self.jpeg_quality))
|
| 111 |
+
push("user", blocks)
|
| 112 |
+
elif kind == "assistant":
|
| 113 |
+
if it.get("raw") is not None and it.get("backend") == self.name:
|
| 114 |
+
blocks = [dict(b) for b in it["raw"]]
|
| 115 |
+
else: # a turn produced by another backend: plain text + tool calls, no thinking
|
| 116 |
+
blocks = ([dict(type="text", text=it["text"])] if it.get("text") else [])
|
| 117 |
+
blocks += [dict(type="tool_use", id=tc.id, name=tc.name, input=tc.arguments)
|
| 118 |
+
for tc in it["tool_calls"]]
|
| 119 |
+
if not blocks:
|
| 120 |
+
blocks = [dict(type="text", text="(no output)")]
|
| 121 |
+
push("assistant", blocks)
|
| 122 |
+
elif kind == "tool_output":
|
| 123 |
+
push("user", [dict(type="tool_result", tool_use_id=it["call_id"], content=it["text"])])
|
| 124 |
+
else:
|
| 125 |
+
raise ValueError(kind)
|
| 126 |
+
return msgs
|
| 127 |
+
|
| 128 |
+
def build_request(self, conv, tools):
|
| 129 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 130 |
+
req = dict(model=self.model, max_tokens=int(self.max_tokens), system=conv.system,
|
| 131 |
+
messages=self.convert_items(items), tools=anthropic_tools(tools, self.strict_tools),
|
| 132 |
+
tool_choice=dict(type="auto", disable_parallel_tool_use=not self.parallel_tool_calls),
|
| 133 |
+
thinking=dict(type="adaptive", display=self.thinking_display),
|
| 134 |
+
output_config=dict(effort=self.effort))
|
| 135 |
+
if self.cache:
|
| 136 |
+
req["cache_control"] = dict(type="ephemeral")
|
| 137 |
+
return req
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def request_stats(req):
|
| 141 |
+
n_img, img_bytes, txt = 0, 0, len(req.get("system") or "")
|
| 142 |
+
for m in req["messages"]:
|
| 143 |
+
for b in m["content"]:
|
| 144 |
+
t = b.get("type")
|
| 145 |
+
if t == "image":
|
| 146 |
+
n_img += 1
|
| 147 |
+
img_bytes += len(b["source"]["data"])
|
| 148 |
+
elif t == "text":
|
| 149 |
+
txt += len(b["text"])
|
| 150 |
+
elif t == "tool_result":
|
| 151 |
+
txt += len(b["content"]) if isinstance(b["content"], str) else 0
|
| 152 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_messages=len(req["messages"]))
|
| 153 |
+
|
| 154 |
+
# ------------------------------------------------------------------ call
|
| 155 |
+
def act(self, conv, tools):
|
| 156 |
+
req = self.build_request(conv, tools)
|
| 157 |
+
stats = self.request_stats(req)
|
| 158 |
+
t0 = time.time()
|
| 159 |
+
try:
|
| 160 |
+
with self.client().messages.stream(**req) as stream:
|
| 161 |
+
msg = stream.get_final_message()
|
| 162 |
+
except AssertionError: # the SDK asserts on a stream without message_start (seen through a gateway)
|
| 163 |
+
raise RuntimeError("empty response stream (no message_start event)") from None
|
| 164 |
+
out = self.parse_response(msg)
|
| 165 |
+
out.latency_s = time.time() - t0
|
| 166 |
+
out.request_stats = stats
|
| 167 |
+
return out
|
| 168 |
+
|
| 169 |
+
def parse_response(self, msg):
|
| 170 |
+
calls, texts, summ = [], [], []
|
| 171 |
+
content = _get(msg, "content") or []
|
| 172 |
+
for b in content:
|
| 173 |
+
t = _get(b, "type")
|
| 174 |
+
if t == "tool_use":
|
| 175 |
+
args = _get(b, "input") or {}
|
| 176 |
+
calls.append(ToolCall(id=_get(b, "id"), name=_get(b, "name"), arguments=dict(args)))
|
| 177 |
+
elif t == "text":
|
| 178 |
+
texts.append(_get(b, "text") or "")
|
| 179 |
+
elif t == "thinking":
|
| 180 |
+
if _get(b, "thinking"):
|
| 181 |
+
summ.append(_get(b, "thinking"))
|
| 182 |
+
u = _get(msg, "usage")
|
| 183 |
+
usage = {}
|
| 184 |
+
if u is not None:
|
| 185 |
+
fresh = _get(u, "input_tokens", 0) or 0
|
| 186 |
+
read = _get(u, "cache_read_input_tokens", 0) or 0
|
| 187 |
+
write = _get(u, "cache_creation_input_tokens", 0) or 0
|
| 188 |
+
# same meaning as the OpenAI backend: input_tokens = whole prompt, cached_tokens = the part read from cache
|
| 189 |
+
usage = dict(input_tokens=fresh + read + write, cached_tokens=read, cache_write_tokens=write,
|
| 190 |
+
output_tokens=_get(u, "output_tokens", 0) or 0, reasoning_tokens=0)
|
| 191 |
+
stop = _get(msg, "stop_reason")
|
| 192 |
+
status, err = "completed", None
|
| 193 |
+
if stop == "refusal":
|
| 194 |
+
d = _get(msg, "stop_details")
|
| 195 |
+
status, err = "refusal", f"refusal: category={_get(d, 'category')} {_get(d, 'explanation') or ''}".strip()
|
| 196 |
+
elif stop == "max_tokens":
|
| 197 |
+
status, err = "incomplete", "incomplete: max_tokens"
|
| 198 |
+
elif not content and u is None:
|
| 199 |
+
status, err = "incomplete", "empty response (no content, no usage)"
|
| 200 |
+
return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
|
| 201 |
+
reasoning_summary="\n".join(summ) or None, usage=usage,
|
| 202 |
+
raw=[_to_dict(b) for b in content], status=status, error=err)
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/base.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backend interface: a backend maps a conversation (+ tool specs) to the next tool call(s)."""
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
# Normally the API SDKs (`openai`, `anthropic`, `google-genai`) are installed in the venv (setup/install.sh).
|
| 8 |
+
# Optionally they can live in a separate `pip install --target` directory, given by LFF_API_SDK_DIR (older name:
|
| 9 |
+
# LFF_OPENAI_SDK_DIR), that is APPENDED to sys.path so every package already in the venv keeps precedence.
|
| 10 |
+
API_SDK_DIR = os.environ.get("LFF_API_SDK_DIR") or os.environ.get("LFF_OPENAI_SDK_DIR", "")
|
| 11 |
+
OPENAI_SDK_DIR = API_SDK_DIR # old name
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def import_sdk(module):
|
| 15 |
+
"""Import an API SDK module ("openai", "anthropic", "google.genai")."""
|
| 16 |
+
import importlib
|
| 17 |
+
try:
|
| 18 |
+
return importlib.import_module(module)
|
| 19 |
+
except ImportError:
|
| 20 |
+
if API_SDK_DIR and os.path.isdir(API_SDK_DIR) and API_SDK_DIR not in sys.path:
|
| 21 |
+
sys.path.append(API_SDK_DIR)
|
| 22 |
+
return importlib.import_module(module)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def import_openai():
|
| 26 |
+
return import_sdk("openai")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class BackendResponse:
|
| 31 |
+
tool_calls: list = field(default_factory=list) # [ToolCall]
|
| 32 |
+
text: Optional[str] = None # visible assistant text (e.g. the diagnosis)
|
| 33 |
+
reasoning_summary: Optional[str] = None
|
| 34 |
+
usage: dict = field(default_factory=dict) # input_tokens, cached_tokens, output_tokens, reasoning_tokens
|
| 35 |
+
latency_s: float = 0.0
|
| 36 |
+
raw: Optional[list] = None # backend-specific items to replay in later requests (e.g. reasoning items)
|
| 37 |
+
request_stats: dict = field(default_factory=dict) # n_images, n_items, bytes, ...
|
| 38 |
+
status: str = "ok"
|
| 39 |
+
error: Optional[str] = None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class RunInfo:
|
| 44 |
+
task: object # privileged: only the scripted backend may look at task / inst
|
| 45 |
+
inst: dict
|
| 46 |
+
seed: int
|
| 47 |
+
k: int
|
| 48 |
+
protocol: str
|
| 49 |
+
feedback: str
|
| 50 |
+
memory: str
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@dataclass
|
| 54 |
+
class AttemptInfo:
|
| 55 |
+
attempt: int
|
| 56 |
+
history: list # AttemptRecords visible to the agent under the memory mode (already selected)
|
| 57 |
+
continuing: bool = False # within protocol: continuing after a failed done
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Backend:
|
| 61 |
+
name = "base"
|
| 62 |
+
|
| 63 |
+
def begin_run(self, info: RunInfo):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
def begin_attempt(self, info: AttemptInfo):
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
def act(self, conv, tools) -> BackendResponse:
|
| 70 |
+
raise NotImplementedError
|
| 71 |
+
|
| 72 |
+
def on_tool_result(self, call, result):
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
def end_attempt(self) -> dict:
|
| 76 |
+
return {}
|
| 77 |
+
|
| 78 |
+
def end_run(self):
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
def config(self) -> dict:
|
| 82 |
+
return dict(name=self.name)
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/chat_completions.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served
|
| 2 |
+
by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format.
|
| 3 |
+
|
| 4 |
+
Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard
|
| 5 |
+
message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent
|
| 6 |
+
back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and
|
| 7 |
+
Responses backends do (Kimi's docs ask for this in multi-step tool use)."""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
from ..context import ToolCall, prune_live_images
|
| 13 |
+
from .base import Backend, BackendResponse, import_openai
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def chat_tools(specs):
|
| 17 |
+
return [dict(type="function", function=dict(name=s["name"], description=s["description"],
|
| 18 |
+
parameters=s["parameters"])) for s in specs]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ChatCompletionsBackend(Backend):
|
| 22 |
+
name = "chat"
|
| 23 |
+
|
| 24 |
+
def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024,
|
| 25 |
+
max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None,
|
| 26 |
+
replay_reasoning=True):
|
| 27 |
+
self.model = model
|
| 28 |
+
self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1")
|
| 29 |
+
self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY")
|
| 30 |
+
self.temperature = temperature
|
| 31 |
+
self.max_tokens = max_tokens
|
| 32 |
+
self.max_live_images = max_live_images
|
| 33 |
+
self.jpeg_quality = jpeg_quality
|
| 34 |
+
self.timeout = timeout
|
| 35 |
+
self.extra_body = extra_body
|
| 36 |
+
self.replay_reasoning = replay_reasoning
|
| 37 |
+
self._client = client
|
| 38 |
+
|
| 39 |
+
def config(self):
|
| 40 |
+
return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature,
|
| 41 |
+
max_tokens=self.max_tokens, max_live_images=self.max_live_images,
|
| 42 |
+
replay_reasoning=self.replay_reasoning)
|
| 43 |
+
|
| 44 |
+
def client(self):
|
| 45 |
+
if self._client is None:
|
| 46 |
+
openai = import_openai()
|
| 47 |
+
kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1)
|
| 48 |
+
if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")):
|
| 49 |
+
# local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here)
|
| 50 |
+
kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout)
|
| 51 |
+
self._client = openai.OpenAI(**kw)
|
| 52 |
+
return self._client
|
| 53 |
+
|
| 54 |
+
def build_request(self, conv, tools):
|
| 55 |
+
msgs = [dict(role="system", content=conv.system)]
|
| 56 |
+
for it in prune_live_images(conv.items, self.max_live_images):
|
| 57 |
+
if it["kind"] == "user":
|
| 58 |
+
content = []
|
| 59 |
+
for p in it["parts"]:
|
| 60 |
+
if p["type"] == "text":
|
| 61 |
+
content.append(dict(type="text", text=p["text"]))
|
| 62 |
+
else:
|
| 63 |
+
content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality))))
|
| 64 |
+
msgs.append(dict(role="user", content=content))
|
| 65 |
+
elif it["kind"] == "assistant":
|
| 66 |
+
if not it.get("text") and not it["tool_calls"]:
|
| 67 |
+
# a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still
|
| 68 |
+
# counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content
|
| 69 |
+
# nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request
|
| 70 |
+
continue
|
| 71 |
+
m = dict(role="assistant", content=it.get("text") or None)
|
| 72 |
+
rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None
|
| 73 |
+
if rc and self.replay_reasoning:
|
| 74 |
+
m["reasoning_content"] = rc
|
| 75 |
+
if it["tool_calls"]:
|
| 76 |
+
m["tool_calls"] = [dict(id=tc.id, type="function",
|
| 77 |
+
function=dict(name=tc.name,
|
| 78 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 79 |
+
for tc in it["tool_calls"]]
|
| 80 |
+
msgs.append(m)
|
| 81 |
+
elif it["kind"] == "tool_output":
|
| 82 |
+
msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"]))
|
| 83 |
+
req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto",
|
| 84 |
+
max_tokens=self.max_tokens)
|
| 85 |
+
if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature)
|
| 86 |
+
req["temperature"] = self.temperature
|
| 87 |
+
if self.extra_body:
|
| 88 |
+
req["extra_body"] = dict(self.extra_body)
|
| 89 |
+
return req
|
| 90 |
+
|
| 91 |
+
def act(self, conv, tools):
|
| 92 |
+
req = self.build_request(conv, tools)
|
| 93 |
+
n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list)
|
| 94 |
+
for c in m["content"] if c.get("type") == "image_url")
|
| 95 |
+
t0 = time.time()
|
| 96 |
+
resp = self.client().chat.completions.create(**req)
|
| 97 |
+
lat = time.time() - t0
|
| 98 |
+
stats = dict(n_images=n_img, n_messages=len(req["messages"]))
|
| 99 |
+
if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again
|
| 100 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 101 |
+
error="empty response (no choices)")
|
| 102 |
+
msg = resp.choices[0].message
|
| 103 |
+
rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content")
|
| 104 |
+
calls = []
|
| 105 |
+
for i, tc in enumerate(msg.tool_calls or []):
|
| 106 |
+
raw = tc.function.arguments or ""
|
| 107 |
+
try:
|
| 108 |
+
args = json.loads(raw) if raw else {}
|
| 109 |
+
except json.JSONDecodeError:
|
| 110 |
+
args = {}
|
| 111 |
+
calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw))
|
| 112 |
+
u = resp.usage
|
| 113 |
+
ctd = getattr(u, "completion_tokens_details", None) if u else None
|
| 114 |
+
usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0,
|
| 115 |
+
output_tokens=getattr(u, "completion_tokens", 0) or 0,
|
| 116 |
+
reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {}
|
| 117 |
+
if not calls and not msg.content and not rc and not u:
|
| 118 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 119 |
+
error="empty response (no output, no usage)")
|
| 120 |
+
return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage,
|
| 121 |
+
latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def tool_results_first(msgs):
|
| 125 |
+
"""OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly
|
| 126 |
+
after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's
|
| 127 |
+
output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool
|
| 128 |
+
messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after
|
| 129 |
+
the last tool message of the turn; nothing else changes order."""
|
| 130 |
+
out, i = [], 0
|
| 131 |
+
while i < len(msgs):
|
| 132 |
+
m = msgs[i]
|
| 133 |
+
out.append(m)
|
| 134 |
+
i += 1
|
| 135 |
+
if m["role"] != "assistant" or not m.get("tool_calls"):
|
| 136 |
+
continue
|
| 137 |
+
need = {tc["id"] for tc in m["tool_calls"]}
|
| 138 |
+
held = []
|
| 139 |
+
while i < len(msgs) and need:
|
| 140 |
+
n = msgs[i]
|
| 141 |
+
if n["role"] == "tool" and n.get("tool_call_id") in need:
|
| 142 |
+
out.append(n)
|
| 143 |
+
need.discard(n["tool_call_id"])
|
| 144 |
+
elif n["role"] == "user":
|
| 145 |
+
held.append(n)
|
| 146 |
+
else:
|
| 147 |
+
break
|
| 148 |
+
i += 1
|
| 149 |
+
out.extend(held)
|
| 150 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Google Gemini backend (Gemini API, official SDK `google-genai`).
|
| 2 |
+
|
| 3 |
+
Same conversation as the other backends, converted to Gemini `contents`:
|
| 4 |
+
- system prompt = system_instruction; tools = function declarations with the harness's JSON schemas;
|
| 5 |
+
- every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive)
|
| 6 |
+
and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call;
|
| 7 |
+
- tool outputs of one turn become `function_response` parts at the start of the next user content; images the
|
| 8 |
+
harness attaches after them follow in the same user content;
|
| 9 |
+
- thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged;
|
| 10 |
+
- implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage).
|
| 11 |
+
|
| 12 |
+
Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock.
|
| 13 |
+
"""
|
| 14 |
+
import base64
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
from ..context import ToolCall, prune_live_images
|
| 18 |
+
from .base import Backend, BackendResponse, import_sdk
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _get(obj, key, default=None):
|
| 22 |
+
if isinstance(obj, dict):
|
| 23 |
+
return obj.get(key, default)
|
| 24 |
+
return getattr(obj, key, default)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _strip_additional(schema):
|
| 28 |
+
"""The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema."""
|
| 29 |
+
if isinstance(schema, dict):
|
| 30 |
+
return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"}
|
| 31 |
+
if isinstance(schema, list):
|
| 32 |
+
return [_strip_additional(v) for v in schema]
|
| 33 |
+
return schema
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _image_part(image, quality=None):
|
| 37 |
+
head, data = image.data_url(quality).split(",", 1)
|
| 38 |
+
mime = head[len("data:"):].split(";", 1)[0]
|
| 39 |
+
return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data)))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class GeminiBackend(Backend):
|
| 43 |
+
name = "gemini"
|
| 44 |
+
|
| 45 |
+
def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True,
|
| 46 |
+
max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90,
|
| 47 |
+
timeout=900.0, client=None):
|
| 48 |
+
self.model = model
|
| 49 |
+
self.thinking_level = thinking_level
|
| 50 |
+
self.thinking_budget = thinking_budget
|
| 51 |
+
self.include_thoughts = include_thoughts
|
| 52 |
+
self.max_output_tokens = max_output_tokens
|
| 53 |
+
self.media_resolution = media_resolution
|
| 54 |
+
self.max_live_images = max_live_images
|
| 55 |
+
self.jpeg_quality = jpeg_quality
|
| 56 |
+
self.timeout = timeout
|
| 57 |
+
self._client = client
|
| 58 |
+
self._json_schema_field = None
|
| 59 |
+
|
| 60 |
+
def config(self):
|
| 61 |
+
return dict(name=self.name, model=self.model, thinking_level=self.thinking_level,
|
| 62 |
+
thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts,
|
| 63 |
+
max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution,
|
| 64 |
+
max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout)
|
| 65 |
+
|
| 66 |
+
def client(self):
|
| 67 |
+
if self._client is None:
|
| 68 |
+
genai = import_sdk("google.genai")
|
| 69 |
+
self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000)))
|
| 70 |
+
return self._client
|
| 71 |
+
|
| 72 |
+
def _declarations(self, specs):
|
| 73 |
+
if self._json_schema_field is None:
|
| 74 |
+
try:
|
| 75 |
+
types = import_sdk("google.genai.types")
|
| 76 |
+
self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields
|
| 77 |
+
except ImportError: # tests without the SDK
|
| 78 |
+
self._json_schema_field = True
|
| 79 |
+
out = []
|
| 80 |
+
for s in specs:
|
| 81 |
+
d = dict(name=s["name"], description=s["description"])
|
| 82 |
+
if self._json_schema_field:
|
| 83 |
+
d["parameters_json_schema"] = s["parameters"]
|
| 84 |
+
else:
|
| 85 |
+
d["parameters"] = _strip_additional(s["parameters"])
|
| 86 |
+
out.append(d)
|
| 87 |
+
return [dict(function_declarations=out)]
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ request
|
| 90 |
+
def convert_items(self, items):
|
| 91 |
+
contents = []
|
| 92 |
+
|
| 93 |
+
def push(role, parts):
|
| 94 |
+
if contents and contents[-1]["role"] == role:
|
| 95 |
+
contents[-1]["parts"].extend(parts)
|
| 96 |
+
else:
|
| 97 |
+
contents.append(dict(role=role, parts=list(parts)))
|
| 98 |
+
|
| 99 |
+
for it in items:
|
| 100 |
+
kind = it["kind"]
|
| 101 |
+
if kind == "user":
|
| 102 |
+
parts = []
|
| 103 |
+
for p in it["parts"]:
|
| 104 |
+
if p["type"] == "text":
|
| 105 |
+
parts.append(dict(text=p["text"]))
|
| 106 |
+
else:
|
| 107 |
+
parts.append(_image_part(p["image"], self.jpeg_quality))
|
| 108 |
+
push("user", parts)
|
| 109 |
+
elif kind == "assistant":
|
| 110 |
+
if it.get("raw") is not None and it.get("backend") == self.name:
|
| 111 |
+
content = dict(it["raw"][0])
|
| 112 |
+
contents.append(dict(role="model", parts=list(content.get("parts") or [])))
|
| 113 |
+
continue
|
| 114 |
+
parts = ([dict(text=it["text"])] if it.get("text") else [])
|
| 115 |
+
parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]]
|
| 116 |
+
push("model", parts or [dict(text="(no output)")])
|
| 117 |
+
elif kind == "tool_output":
|
| 118 |
+
fr = dict(name=it["name"], response=dict(output=it["text"]))
|
| 119 |
+
if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"):
|
| 120 |
+
fr["id"] = it["call_id"]
|
| 121 |
+
push("user", [dict(function_response=fr)])
|
| 122 |
+
else:
|
| 123 |
+
raise ValueError(kind)
|
| 124 |
+
return contents
|
| 125 |
+
|
| 126 |
+
def build_request(self, conv, tools):
|
| 127 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 128 |
+
thinking = dict(include_thoughts=self.include_thoughts)
|
| 129 |
+
if self.thinking_budget is not None:
|
| 130 |
+
thinking["thinking_budget"] = int(self.thinking_budget)
|
| 131 |
+
elif self.thinking_level:
|
| 132 |
+
thinking["thinking_level"] = self.thinking_level
|
| 133 |
+
config = dict(system_instruction=conv.system, tools=self._declarations(tools),
|
| 134 |
+
tool_config=dict(function_calling_config=dict(mode="AUTO")),
|
| 135 |
+
automatic_function_calling=dict(disable=True), thinking_config=thinking,
|
| 136 |
+
max_output_tokens=int(self.max_output_tokens))
|
| 137 |
+
if self.media_resolution:
|
| 138 |
+
config["media_resolution"] = self.media_resolution
|
| 139 |
+
return dict(model=self.model, contents=self.convert_items(items), config=config)
|
| 140 |
+
|
| 141 |
+
@staticmethod
|
| 142 |
+
def request_stats(req):
|
| 143 |
+
n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "")
|
| 144 |
+
for c in req["contents"]:
|
| 145 |
+
for p in c["parts"]:
|
| 146 |
+
p = p if isinstance(p, dict) else {}
|
| 147 |
+
if p.get("inline_data"):
|
| 148 |
+
n_img += 1
|
| 149 |
+
img_bytes += len(p["inline_data"]["data"])
|
| 150 |
+
elif p.get("text"):
|
| 151 |
+
txt += len(p["text"])
|
| 152 |
+
elif p.get("function_response"):
|
| 153 |
+
txt += len(str(p["function_response"].get("response", "")))
|
| 154 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"]))
|
| 155 |
+
|
| 156 |
+
# ------------------------------------------------------------------ call
|
| 157 |
+
def act(self, conv, tools):
|
| 158 |
+
req = self.build_request(conv, tools)
|
| 159 |
+
stats = self.request_stats(req)
|
| 160 |
+
types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys
|
| 161 |
+
t0 = time.time()
|
| 162 |
+
resp = self.client().models.generate_content(
|
| 163 |
+
model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]],
|
| 164 |
+
config=types.GenerateContentConfig.model_validate(req["config"]))
|
| 165 |
+
out = self.parse_response(resp)
|
| 166 |
+
out.latency_s = time.time() - t0
|
| 167 |
+
out.request_stats = stats
|
| 168 |
+
return out
|
| 169 |
+
|
| 170 |
+
def parse_response(self, resp):
|
| 171 |
+
cands = _get(resp, "candidates") or []
|
| 172 |
+
cand = cands[0] if cands else None
|
| 173 |
+
content = _get(cand, "content") if cand is not None else None
|
| 174 |
+
parts = (_get(content, "parts") or []) if content is not None else []
|
| 175 |
+
calls, texts, summ = [], [], []
|
| 176 |
+
for i, p in enumerate(parts):
|
| 177 |
+
fc = _get(p, "function_call")
|
| 178 |
+
if fc is not None:
|
| 179 |
+
cid = _get(fc, "id") or f"gemini_call_{i}"
|
| 180 |
+
calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {})))
|
| 181 |
+
elif _get(p, "text"):
|
| 182 |
+
(summ if _get(p, "thought") else texts).append(_get(p, "text"))
|
| 183 |
+
u = _get(resp, "usage_metadata")
|
| 184 |
+
usage = {}
|
| 185 |
+
if u is not None:
|
| 186 |
+
usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0,
|
| 187 |
+
cached_tokens=_get(u, "cached_content_token_count", 0) or 0,
|
| 188 |
+
output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0),
|
| 189 |
+
reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0)
|
| 190 |
+
finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE"
|
| 191 |
+
status, err = "completed", None
|
| 192 |
+
if not parts:
|
| 193 |
+
status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})"
|
| 194 |
+
elif "MAX_TOKENS" in finish or "MALFORMED" in finish:
|
| 195 |
+
status, err = "incomplete", f"incomplete: finish_reason={finish}"
|
| 196 |
+
elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish:
|
| 197 |
+
status, err = "refusal", f"refusal: finish_reason={finish}"
|
| 198 |
+
if content is not None and hasattr(content, "model_dump"):
|
| 199 |
+
raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes
|
| 200 |
+
elif content is not None:
|
| 201 |
+
raw = [dict(content)]
|
| 202 |
+
else:
|
| 203 |
+
raw = None
|
| 204 |
+
return BackendResponse(tool_calls=calls, text="\n".join(texts) or None,
|
| 205 |
+
reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw,
|
| 206 |
+
status=status, error=err)
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/openai_responses.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI Responses API backend (default model gpt-6-astra).
|
| 2 |
+
|
| 3 |
+
Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with
|
| 4 |
+
store=False; reasoning items are replayed with their encrypted content so the model keeps its chain
|
| 5 |
+
of thought across tool calls within an attempt. The request prefix (instructions, tools, task text,
|
| 6 |
+
packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what
|
| 7 |
+
OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs.
|
| 8 |
+
|
| 9 |
+
Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time;
|
| 10 |
+
the client is created lazily on the first real call (tests inject a mock client).
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
from ..context import ToolCall, prune_live_images
|
| 17 |
+
from .base import Backend, BackendResponse, import_openai
|
| 18 |
+
|
| 19 |
+
# GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported.
|
| 20 |
+
GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _get(obj, key, default=None):
|
| 24 |
+
if isinstance(obj, dict):
|
| 25 |
+
return obj.get(key, default)
|
| 26 |
+
return getattr(obj, key, default)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _to_dict(item):
|
| 30 |
+
if isinstance(item, dict):
|
| 31 |
+
return dict(item)
|
| 32 |
+
if hasattr(item, "to_dict"):
|
| 33 |
+
return item.to_dict(mode="json")
|
| 34 |
+
if hasattr(item, "model_dump"):
|
| 35 |
+
return item.model_dump(mode="json", exclude_none=True)
|
| 36 |
+
return dict(vars(item))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def responses_tools(specs, strict=True):
|
| 40 |
+
return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"],
|
| 41 |
+
strict=strict) for s in specs]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class OpenAIResponsesBackend(Backend):
|
| 45 |
+
name = "openai"
|
| 46 |
+
|
| 47 |
+
def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto",
|
| 48 |
+
max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None,
|
| 49 |
+
store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0,
|
| 50 |
+
max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last",
|
| 51 |
+
prompt_cache_options=None, client=None, http_client=None):
|
| 52 |
+
if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS:
|
| 53 |
+
raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), "
|
| 54 |
+
f"got {reasoning_effort!r}")
|
| 55 |
+
self.model = model
|
| 56 |
+
self.reasoning_effort = reasoning_effort
|
| 57 |
+
self.reasoning_summary = reasoning_summary
|
| 58 |
+
self.image_detail = image_detail
|
| 59 |
+
self.max_output_tokens = max_output_tokens
|
| 60 |
+
self.service_tier = service_tier
|
| 61 |
+
self.prompt_cache_key = prompt_cache_key
|
| 62 |
+
self.prompt_cache_retention = prompt_cache_retention
|
| 63 |
+
self.store = store
|
| 64 |
+
self.replay_reasoning = replay_reasoning
|
| 65 |
+
self.max_live_images = max_live_images
|
| 66 |
+
self.jpeg_quality = jpeg_quality
|
| 67 |
+
self.timeout = timeout
|
| 68 |
+
self.max_retries = max_retries
|
| 69 |
+
self.extra_body = extra_body
|
| 70 |
+
self.strict_tools = strict_tools
|
| 71 |
+
# explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last"
|
| 72 |
+
assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints
|
| 73 |
+
self.cache_breakpoints = cache_breakpoints
|
| 74 |
+
self.prompt_cache_options = prompt_cache_options
|
| 75 |
+
self._client = client
|
| 76 |
+
self._http_client = http_client # optional custom transport (tests, proxies)
|
| 77 |
+
self._cache_key = prompt_cache_key
|
| 78 |
+
|
| 79 |
+
def config(self):
|
| 80 |
+
return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort,
|
| 81 |
+
reasoning_summary=self.reasoning_summary, image_detail=self.image_detail,
|
| 82 |
+
max_output_tokens=self.max_output_tokens, service_tier=self.service_tier,
|
| 83 |
+
prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention,
|
| 84 |
+
store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images,
|
| 85 |
+
jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries,
|
| 86 |
+
extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints,
|
| 87 |
+
prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL"))
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ client
|
| 90 |
+
def client(self):
|
| 91 |
+
if self._client is None:
|
| 92 |
+
key = os.environ.get("OPENAI_API_KEY")
|
| 93 |
+
if not key:
|
| 94 |
+
raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it")
|
| 95 |
+
openai = import_openai()
|
| 96 |
+
kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout,
|
| 97 |
+
max_retries=self.max_retries)
|
| 98 |
+
if self._http_client is not None:
|
| 99 |
+
kw["http_client"] = self._http_client
|
| 100 |
+
self._client = openai.OpenAI(**kw)
|
| 101 |
+
return self._client
|
| 102 |
+
|
| 103 |
+
def begin_run(self, info):
|
| 104 |
+
if self.prompt_cache_key is None:
|
| 105 |
+
# route all calls of one run to the same cache shard
|
| 106 |
+
self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}"
|
| 107 |
+
|
| 108 |
+
# ------------------------------------------------------------------ request
|
| 109 |
+
def convert_items(self, items):
|
| 110 |
+
out = []
|
| 111 |
+
last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1)
|
| 112 |
+
for i, it in enumerate(items):
|
| 113 |
+
kind = it["kind"]
|
| 114 |
+
if kind == "user":
|
| 115 |
+
content = []
|
| 116 |
+
for p in it["parts"]:
|
| 117 |
+
if p["type"] == "text":
|
| 118 |
+
content.append(dict(type="input_text", text=p["text"]))
|
| 119 |
+
else:
|
| 120 |
+
content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality),
|
| 121 |
+
detail=self.image_detail))
|
| 122 |
+
# explicit cache breakpoints: end of the stable history item (byte-identical for the whole
|
| 123 |
+
# attempt) and end of the newest input (reused by the next call of the attempt)
|
| 124 |
+
if content and ((self.cache_breakpoints != "none" and not it.get("live"))
|
| 125 |
+
or (self.cache_breakpoints == "history+last" and i == last_user)):
|
| 126 |
+
content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit")
|
| 127 |
+
out.append(dict(role="user", content=content))
|
| 128 |
+
elif kind == "assistant":
|
| 129 |
+
if it.get("raw") and it.get("backend") == self.name:
|
| 130 |
+
for r in it["raw"]:
|
| 131 |
+
if r.get("type") == "reasoning" and not self.replay_reasoning:
|
| 132 |
+
continue
|
| 133 |
+
out.append(r)
|
| 134 |
+
else:
|
| 135 |
+
if it.get("text"):
|
| 136 |
+
out.append(dict(role="assistant", content=it["text"]))
|
| 137 |
+
for tc in it["tool_calls"]:
|
| 138 |
+
out.append(dict(type="function_call", call_id=tc.id, name=tc.name,
|
| 139 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 140 |
+
elif kind == "tool_output":
|
| 141 |
+
out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"]))
|
| 142 |
+
else:
|
| 143 |
+
raise ValueError(kind)
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
def build_request(self, conv, tools):
|
| 147 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 148 |
+
req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items),
|
| 149 |
+
tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False,
|
| 150 |
+
store=self.store)
|
| 151 |
+
reasoning = dict(effort=self.reasoning_effort)
|
| 152 |
+
if self.reasoning_summary:
|
| 153 |
+
reasoning["summary"] = self.reasoning_summary
|
| 154 |
+
req["reasoning"] = reasoning
|
| 155 |
+
if not self.store and self.replay_reasoning:
|
| 156 |
+
req["include"] = ["reasoning.encrypted_content"]
|
| 157 |
+
if self.max_output_tokens:
|
| 158 |
+
req["max_output_tokens"] = int(self.max_output_tokens)
|
| 159 |
+
if self.service_tier:
|
| 160 |
+
req["service_tier"] = self.service_tier
|
| 161 |
+
if self._cache_key:
|
| 162 |
+
req["prompt_cache_key"] = self._cache_key
|
| 163 |
+
if self.prompt_cache_retention:
|
| 164 |
+
req["prompt_cache_retention"] = self.prompt_cache_retention
|
| 165 |
+
if self.prompt_cache_options:
|
| 166 |
+
req["prompt_cache_options"] = dict(self.prompt_cache_options)
|
| 167 |
+
if self.extra_body:
|
| 168 |
+
req["extra_body"] = dict(self.extra_body)
|
| 169 |
+
return req
|
| 170 |
+
|
| 171 |
+
@staticmethod
|
| 172 |
+
def request_stats(req):
|
| 173 |
+
n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "")
|
| 174 |
+
for it in req["input"]:
|
| 175 |
+
for c in (it.get("content") if isinstance(it.get("content"), list) else []):
|
| 176 |
+
if c.get("type") == "input_image":
|
| 177 |
+
n_img += 1
|
| 178 |
+
img_bytes += len(c["image_url"])
|
| 179 |
+
elif "text" in c:
|
| 180 |
+
txt += len(c["text"])
|
| 181 |
+
if isinstance(it.get("content"), str):
|
| 182 |
+
txt += len(it["content"])
|
| 183 |
+
if it.get("type") == "function_call_output":
|
| 184 |
+
txt += len(it["output"]) if isinstance(it["output"], str) else 0
|
| 185 |
+
if it.get("type") == "function_call":
|
| 186 |
+
txt += len(it.get("arguments", ""))
|
| 187 |
+
tools_chars = len(json.dumps(req.get("tools", [])))
|
| 188 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars,
|
| 189 |
+
n_input_items=len(req["input"]))
|
| 190 |
+
|
| 191 |
+
# ------------------------------------------------------------------ call
|
| 192 |
+
def act(self, conv, tools):
|
| 193 |
+
req = self.build_request(conv, tools)
|
| 194 |
+
stats = self.request_stats(req)
|
| 195 |
+
t0 = time.time()
|
| 196 |
+
resp = self.client().responses.create(**req)
|
| 197 |
+
out = self.parse_response(resp)
|
| 198 |
+
out.latency_s = time.time() - t0
|
| 199 |
+
out.request_stats = stats
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
+
def parse_response(self, resp):
|
| 203 |
+
calls, texts, summ = [], [], []
|
| 204 |
+
output = _get(resp, "output") or []
|
| 205 |
+
for item in output:
|
| 206 |
+
t = _get(item, "type")
|
| 207 |
+
if t == "function_call":
|
| 208 |
+
raw = _get(item, "arguments") or ""
|
| 209 |
+
try:
|
| 210 |
+
args = json.loads(raw) if raw else {}
|
| 211 |
+
except json.JSONDecodeError:
|
| 212 |
+
args = {}
|
| 213 |
+
calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args,
|
| 214 |
+
raw_arguments=raw))
|
| 215 |
+
elif t == "message":
|
| 216 |
+
for c in _get(item, "content") or []:
|
| 217 |
+
if _get(c, "type") == "output_text":
|
| 218 |
+
texts.append(_get(c, "text") or "")
|
| 219 |
+
elif t == "reasoning":
|
| 220 |
+
for s in _get(item, "summary") or []:
|
| 221 |
+
summ.append(_get(s, "text") or "")
|
| 222 |
+
u = _get(resp, "usage")
|
| 223 |
+
usage = {}
|
| 224 |
+
if u is not None:
|
| 225 |
+
itd = _get(u, "input_tokens_details")
|
| 226 |
+
otd = _get(u, "output_tokens_details")
|
| 227 |
+
usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0,
|
| 228 |
+
cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0,
|
| 229 |
+
cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0,
|
| 230 |
+
output_tokens=_get(u, "output_tokens", 0) or 0,
|
| 231 |
+
reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0)
|
| 232 |
+
status = _get(resp, "status") or "completed"
|
| 233 |
+
err = None
|
| 234 |
+
if status == "incomplete":
|
| 235 |
+
err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason"))
|
| 236 |
+
elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again
|
| 237 |
+
status, err = "incomplete", "empty response (no output, no usage)"
|
| 238 |
+
return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
|
| 239 |
+
reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage,
|
| 240 |
+
raw=[_to_dict(i) for i in output], status=status, error=err)
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/scripted.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scripted backend: no model. Runs a task's scripted reference policy (adaptive by default) through the
|
| 2 |
+
agent tool interface, to test the harness end to end.
|
| 3 |
+
|
| 4 |
+
How: the task's own `execute(inst, params)` runs in a worker thread with `task.sk` replaced by a proxy.
|
| 5 |
+
Every Skills primitive it calls (move_to / set_gripper / push / grasp_at / place_at) becomes an agent
|
| 6 |
+
tool call that is handed to the harness, executed by the ToolExecutor on the main thread, and its
|
| 7 |
+
report is returned to the worker. Only one thread runs at a time (queues hand control back and forth),
|
| 8 |
+
so MuJoCo is never touched concurrently. Only schema-valid tool calls are emitted, so this also shows
|
| 9 |
+
that the tool interface is expressive enough for the task.
|
| 10 |
+
|
| 11 |
+
The scripted policy is privileged: it reads the instance (layout) like the task's reference policies
|
| 12 |
+
do. It sees earlier attempts only through the memory mode chosen by the harness and only the outcome
|
| 13 |
+
fields allowed by the feedback level (F2: structured measurement, F1: success flag, F0: nothing); if
|
| 14 |
+
the adaptive rule cannot run on what it sees, it falls back to the task's blind retry rule.
|
| 15 |
+
Supported: cross-protocol tasks that implement execute/default_params/adapt_params (+ oracle/blind).
|
| 16 |
+
"""
|
| 17 |
+
import math
|
| 18 |
+
import queue
|
| 19 |
+
import threading
|
| 20 |
+
import traceback
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from ..context import ToolCall
|
| 25 |
+
from .base import Backend, BackendResponse
|
| 26 |
+
|
| 27 |
+
TIMEOUT_S = 600
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class _Abort(Exception):
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class _Channel:
|
| 35 |
+
def __init__(self):
|
| 36 |
+
self.req = queue.Queue()
|
| 37 |
+
self.res = queue.Queue()
|
| 38 |
+
|
| 39 |
+
def call(self, name, args): # worker side
|
| 40 |
+
self.req.put(("call", name, args))
|
| 41 |
+
kind, payload = self.res.get(timeout=TIMEOUT_S)
|
| 42 |
+
if kind == "abort":
|
| 43 |
+
raise _Abort()
|
| 44 |
+
return payload
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class SkillsProxy:
|
| 48 |
+
"""Stands in for task.sk inside task.execute(); primitives become agent tool calls."""
|
| 49 |
+
|
| 50 |
+
def __init__(self, real, channel):
|
| 51 |
+
self._real = real
|
| 52 |
+
self._ch = channel
|
| 53 |
+
self.untooled_hold_steps = 0
|
| 54 |
+
self.ignored_wrap_yaw_false = 0
|
| 55 |
+
|
| 56 |
+
def move_to(self, target, yaw=None, speed=None, tol=None, max_steps=None, apply_bias=True, wrap_yaw=True):
|
| 57 |
+
if not wrap_yaw: # the move_to tool always wraps yaw mod pi (Skills default); counted, not fatal
|
| 58 |
+
self.ignored_wrap_yaw_false += 1
|
| 59 |
+
if not apply_bias:
|
| 60 |
+
raise NotImplementedError("apply_bias=False cannot be expressed through the agent tools")
|
| 61 |
+
yaw_deg = math.degrees(self._real.yaw if yaw is None else float(yaw))
|
| 62 |
+
rep = self._ch.call("move_to", dict(x=float(target[0]), y=float(target[1]), z=float(target[2]),
|
| 63 |
+
yaw=round(yaw_deg, 3), speed=None if speed is None else float(speed)))
|
| 64 |
+
return dict(prim="move_to", reached=rep.get("reached"), pos=rep.get("eef_pos"))
|
| 65 |
+
|
| 66 |
+
def set_gripper(self, close, steps=15):
|
| 67 |
+
rep = self._ch.call("close_gripper" if close else "open_gripper", {})
|
| 68 |
+
return dict(prim="close" if close else "open", width=rep.get("gripper_width_m"))
|
| 69 |
+
|
| 70 |
+
def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06):
|
| 71 |
+
rep = self._ch.call("push", dict(x=float(start_xy[0]), y=float(start_xy[1]), dir_x=float(direction_xy[0]),
|
| 72 |
+
dir_y=float(direction_xy[1]), distance=float(distance), speed=float(speed),
|
| 73 |
+
z=None if z is None else float(z), runup=float(pre)))
|
| 74 |
+
return dict(prim="push", reached=rep.get("sweep_reached"), pos=rep.get("eef_pos"))
|
| 75 |
+
|
| 76 |
+
def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15):
|
| 77 |
+
self.set_gripper(False, steps=5)
|
| 78 |
+
self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw)
|
| 79 |
+
self.move_to([xy[0], xy[1], z_grasp])
|
| 80 |
+
self.set_gripper(True)
|
| 81 |
+
self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25)
|
| 82 |
+
|
| 83 |
+
def place_at(self, xy, z_release, approach=0.10):
|
| 84 |
+
self.move_to([xy[0], xy[1], z_release + approach])
|
| 85 |
+
self.move_to([xy[0], xy[1], z_release])
|
| 86 |
+
self.set_gripper(False)
|
| 87 |
+
self.move_to([xy[0], xy[1], z_release + approach])
|
| 88 |
+
|
| 89 |
+
def hold(self, steps=10):
|
| 90 |
+
# waiting in place has no tool; executed directly (only physics, no new command) and counted
|
| 91 |
+
self.untooled_hold_steps += int(steps)
|
| 92 |
+
self._real.hold(steps)
|
| 93 |
+
|
| 94 |
+
def __getattr__(self, k): # eef_pos, eef_mat, gripper_width, holding, yaw, ...
|
| 95 |
+
return getattr(self._real, k)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class ScriptedBackend(Backend):
|
| 99 |
+
name = "scripted"
|
| 100 |
+
|
| 101 |
+
def __init__(self, policy="adaptive", seed=0):
|
| 102 |
+
assert policy in ("adaptive", "naive", "oracle", "blind"), policy
|
| 103 |
+
self.policy = policy
|
| 104 |
+
self.seed = seed
|
| 105 |
+
self.info = None
|
| 106 |
+
self.rng = None
|
| 107 |
+
|
| 108 |
+
def config(self):
|
| 109 |
+
return dict(name=self.name, policy=self.policy, seed=self.seed)
|
| 110 |
+
|
| 111 |
+
def begin_run(self, info):
|
| 112 |
+
if info.protocol != "cross":
|
| 113 |
+
raise NotImplementedError("ScriptedBackend supports cross-protocol tasks only (execute/adapt_params)")
|
| 114 |
+
self.info = info
|
| 115 |
+
self.rng = np.random.default_rng(self.seed + info.seed)
|
| 116 |
+
self._oracle = None
|
| 117 |
+
if self.policy == "oracle": # privileged scratch rollouts happen before the harness resets the scene
|
| 118 |
+
self._oracle = info.task.oracle_params(info.inst)
|
| 119 |
+
|
| 120 |
+
# ------------------------------------------------------------------ params from visible history
|
| 121 |
+
def _visible(self, rec):
|
| 122 |
+
out = rec.outcome
|
| 123 |
+
if self.info.feedback == "F2":
|
| 124 |
+
vis = dict(out)
|
| 125 |
+
elif self.info.feedback == "F1":
|
| 126 |
+
vis = dict(success=out.get("success"))
|
| 127 |
+
else:
|
| 128 |
+
vis = {}
|
| 129 |
+
return dict(attempt=rec.attempt, params=rec.backend_meta.get("params"), outcome=vis)
|
| 130 |
+
|
| 131 |
+
def _params(self, attempt, history):
|
| 132 |
+
task, inst = self.info.task, self.info.inst
|
| 133 |
+
if self.policy == "oracle":
|
| 134 |
+
return dict(self._oracle), "oracle"
|
| 135 |
+
if self.policy == "naive" or not history and self.policy == "adaptive":
|
| 136 |
+
return task.default_params(inst), "default"
|
| 137 |
+
if self.policy == "blind":
|
| 138 |
+
if attempt == 1:
|
| 139 |
+
return task.default_params(inst), "default"
|
| 140 |
+
return task.blind_params(inst, attempt - 1, self.rng), "blind"
|
| 141 |
+
hist = [self._visible(r) for r in history if r.backend_meta.get("params") is not None]
|
| 142 |
+
if not hist:
|
| 143 |
+
return task.blind_params(inst, attempt - 1, self.rng), "blind(no usable history)"
|
| 144 |
+
try:
|
| 145 |
+
return task.adapt_params(inst, hist), "adapt"
|
| 146 |
+
except (KeyError, TypeError, ValueError):
|
| 147 |
+
return task.blind_params(inst, attempt - 1, self.rng), "blind(feedback too coarse)"
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------------ attempt
|
| 150 |
+
def begin_attempt(self, ainfo):
|
| 151 |
+
self.params, self.rule = self._params(ainfo.attempt, ainfo.history)
|
| 152 |
+
self.ch = _Channel()
|
| 153 |
+
self.thread = None
|
| 154 |
+
self.pending = False
|
| 155 |
+
self.last_report = None
|
| 156 |
+
self.n = 0
|
| 157 |
+
self.proxy = None
|
| 158 |
+
|
| 159 |
+
def _worker(self):
|
| 160 |
+
try:
|
| 161 |
+
self.info.task.execute(self.info.inst, self.params)
|
| 162 |
+
self.ch.req.put(("finished", None))
|
| 163 |
+
except _Abort:
|
| 164 |
+
pass
|
| 165 |
+
except Exception:
|
| 166 |
+
self.ch.req.put(("error", traceback.format_exc()))
|
| 167 |
+
|
| 168 |
+
def act(self, conv, tools):
|
| 169 |
+
if self.thread is None:
|
| 170 |
+
task = self.info.task
|
| 171 |
+
self.real_sk = task.sk
|
| 172 |
+
self.proxy = SkillsProxy(task.sk, self.ch)
|
| 173 |
+
task.sk = self.proxy
|
| 174 |
+
self.thread = threading.Thread(target=self._worker, daemon=True)
|
| 175 |
+
self.thread.start()
|
| 176 |
+
elif self.pending:
|
| 177 |
+
self.ch.res.put(("result", self.last_report or {}))
|
| 178 |
+
self.pending = False
|
| 179 |
+
kind, *rest = self.ch.req.get(timeout=TIMEOUT_S)
|
| 180 |
+
self.n += 1
|
| 181 |
+
if kind == "call":
|
| 182 |
+
name, args = rest[0], rest[1]
|
| 183 |
+
self.pending = True
|
| 184 |
+
tc = ToolCall(id=f"scripted_{self.n}", name=name, arguments=args)
|
| 185 |
+
text = None
|
| 186 |
+
if self.n == 1:
|
| 187 |
+
text = f"[scripted {self.policy}: rule={self.rule}, params={self.params}]"
|
| 188 |
+
return BackendResponse(tool_calls=[tc], text=text)
|
| 189 |
+
if kind == "finished":
|
| 190 |
+
return BackendResponse(tool_calls=[ToolCall(id=f"scripted_{self.n}", name="done",
|
| 191 |
+
arguments=dict(reason=f"scripted {self.policy} policy finished "
|
| 192 |
+
f"with params {self.params}"))])
|
| 193 |
+
raise RuntimeError("scripted policy crashed:\n" + str(rest[0]))
|
| 194 |
+
|
| 195 |
+
def on_tool_result(self, call, result):
|
| 196 |
+
self.last_report = result.report
|
| 197 |
+
|
| 198 |
+
def end_attempt(self):
|
| 199 |
+
if self.thread is not None:
|
| 200 |
+
if self.thread.is_alive():
|
| 201 |
+
if self.pending:
|
| 202 |
+
self.ch.res.put(("abort", None))
|
| 203 |
+
self.thread.join(timeout=30)
|
| 204 |
+
self.info.task.sk = self.real_sk
|
| 205 |
+
meta = dict(policy=self.policy, rule=self.rule, params=self.params)
|
| 206 |
+
if self.proxy is not None and self.proxy.untooled_hold_steps:
|
| 207 |
+
meta["untooled_hold_steps"] = self.proxy.untooled_hold_steps
|
| 208 |
+
if self.proxy is not None and self.proxy.ignored_wrap_yaw_false:
|
| 209 |
+
meta["ignored_wrap_yaw_false"] = self.proxy.ignored_wrap_yaw_false
|
| 210 |
+
return meta
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/context.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backend-neutral conversation, attempt records, memory selection and prompt text.
|
| 2 |
+
|
| 3 |
+
A conversation is a list of items (plain dicts):
|
| 4 |
+
{"kind": "user", "parts": [{"type": "text", "text": str} | {"type": "image", "image": ImageRef}], "live": bool}
|
| 5 |
+
{"kind": "assistant", "text": str|None, "tool_calls": [ToolCall], "raw": list|None, "backend": str}
|
| 6 |
+
{"kind": "tool_output", "call_id": str, "name": str, "text": str}
|
| 7 |
+
The system prompt is kept separately (Conversation.system). Backends convert this into their own wire
|
| 8 |
+
format (OpenAI Responses input items, Chat Completions messages, ...).
|
| 9 |
+
|
| 10 |
+
"live" user items are the current attempt's observations; old live images can be dropped to bound the
|
| 11 |
+
request size. History (earlier attempts) is packed into the attempt's first user item and never pruned,
|
| 12 |
+
so the request prefix stays byte-stable within an attempt and grows append-only across attempts
|
| 13 |
+
(prompt-cache friendly).
|
| 14 |
+
"""
|
| 15 |
+
import copy
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
from ..envs import TABLE_Z
|
| 22 |
+
|
| 23 |
+
MEMORY_MODES = ("none", "full", "last", "mismatched")
|
| 24 |
+
FEEDBACK_LEVELS = ("F0", "F1", "F2")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class ToolCall:
|
| 29 |
+
id: str
|
| 30 |
+
name: str
|
| 31 |
+
arguments: dict
|
| 32 |
+
raw_arguments: str = ""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class StepRecord:
|
| 37 |
+
step: int
|
| 38 |
+
name: str
|
| 39 |
+
args: dict
|
| 40 |
+
report: dict
|
| 41 |
+
ok: bool
|
| 42 |
+
wall_s: float = 0.0
|
| 43 |
+
sim_steps: int = 0
|
| 44 |
+
frame: object = None # ImageRef of the agentview after this step (for keyframes)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class AttemptRecord:
|
| 49 |
+
seed: int
|
| 50 |
+
attempt: int
|
| 51 |
+
steps: list = field(default_factory=list)
|
| 52 |
+
keyframes: list = field(default_factory=list) # [(caption, ImageRef)]
|
| 53 |
+
outcome: dict = field(default_factory=dict)
|
| 54 |
+
success: bool = False
|
| 55 |
+
feedback: str = ""
|
| 56 |
+
done_reason: Optional[str] = None
|
| 57 |
+
diagnosis: Optional[str] = None
|
| 58 |
+
ended_by: str = ""
|
| 59 |
+
backend_meta: dict = field(default_factory=dict)
|
| 60 |
+
|
| 61 |
+
def action_signature(self, nd=2):
|
| 62 |
+
"""Rounded action sequence (to compare consecutive attempts: 'same mistake again')."""
|
| 63 |
+
sig = []
|
| 64 |
+
for s in self.steps:
|
| 65 |
+
if s.name in ("get_observation", "pixel_to_world", "locate", "done"):
|
| 66 |
+
continue
|
| 67 |
+
sig.append((s.name, tuple(sorted((k, round(v, nd) if isinstance(v, (int, float)) and v is not None else v)
|
| 68 |
+
for k, v in s.args.items()))))
|
| 69 |
+
return tuple(sig)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def select_history(mode, own, donor=None):
|
| 73 |
+
"""Which earlier attempts the agent sees at the start of the next attempt."""
|
| 74 |
+
if mode == "none":
|
| 75 |
+
return []
|
| 76 |
+
if mode == "full":
|
| 77 |
+
return list(own)
|
| 78 |
+
if mode == "last":
|
| 79 |
+
return list(own[-1:])
|
| 80 |
+
if mode == "mismatched":
|
| 81 |
+
if donor is None:
|
| 82 |
+
raise ValueError("mismatched memory needs donor attempts from another instance")
|
| 83 |
+
return list(donor[:len(own)])
|
| 84 |
+
raise ValueError(mode)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Conversation:
|
| 88 |
+
def __init__(self, system):
|
| 89 |
+
self.system = system
|
| 90 |
+
self.items = []
|
| 91 |
+
|
| 92 |
+
def add_user(self, parts, live=True):
|
| 93 |
+
self.items.append(dict(kind="user", parts=list(parts), live=live))
|
| 94 |
+
|
| 95 |
+
def add_assistant(self, text, tool_calls, raw=None, backend=""):
|
| 96 |
+
self.items.append(dict(kind="assistant", text=text, tool_calls=list(tool_calls), raw=raw, backend=backend))
|
| 97 |
+
|
| 98 |
+
def add_tool_output(self, call_id, name, text):
|
| 99 |
+
self.items.append(dict(kind="tool_output", call_id=call_id, name=name, text=text))
|
| 100 |
+
|
| 101 |
+
def n_images(self):
|
| 102 |
+
return sum(1 for it in self.items if it["kind"] == "user" for p in it["parts"] if p["type"] == "image")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def prune_live_images(items, max_live):
|
| 106 |
+
"""Copy of `items` keeping only the newest `max_live` live images. Hysteresis: when the budget is
|
| 107 |
+
exceeded, prune down to half of it so the request prefix stays stable for several steps."""
|
| 108 |
+
if max_live is None or max_live < 0:
|
| 109 |
+
return items
|
| 110 |
+
live = [(i, j) for i, it in enumerate(items) if it["kind"] == "user" and it.get("live")
|
| 111 |
+
for j, p in enumerate(it["parts"]) if p["type"] == "image"]
|
| 112 |
+
if len(live) <= max_live:
|
| 113 |
+
return items
|
| 114 |
+
keep_n = max(max_live // 2, 1)
|
| 115 |
+
drop = set(live[:len(live) - keep_n])
|
| 116 |
+
out = []
|
| 117 |
+
for i, it in enumerate(items):
|
| 118 |
+
if it["kind"] == "user" and any((i, j) in drop for j in range(len(it["parts"]))):
|
| 119 |
+
it = dict(it)
|
| 120 |
+
parts = []
|
| 121 |
+
for j, p in enumerate(it["parts"]):
|
| 122 |
+
if (i, j) in drop:
|
| 123 |
+
parts.append(dict(type="text", text=f"[{p['image'].camera} image omitted to save context]"))
|
| 124 |
+
else:
|
| 125 |
+
parts.append(p)
|
| 126 |
+
it["parts"] = parts
|
| 127 |
+
out.append(it)
|
| 128 |
+
return out
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ---------------------------------------------------------------------------------------------- text
|
| 132 |
+
|
| 133 |
+
def fmt_num(v):
|
| 134 |
+
if v is None:
|
| 135 |
+
return "null"
|
| 136 |
+
if isinstance(v, bool):
|
| 137 |
+
return str(v).lower()
|
| 138 |
+
if isinstance(v, float):
|
| 139 |
+
return f"{v:.3f}".rstrip("0").rstrip(".") if abs(v) < 1e4 else f"{v:.4g}"
|
| 140 |
+
return json.dumps(v)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def fmt_call(name, args):
|
| 144 |
+
return f"{name}(" + ", ".join(f"{k}={fmt_num(v)}" for k, v in args.items()) + ")"
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def fmt_report(name, rep):
|
| 148 |
+
if not rep.get("ok", False):
|
| 149 |
+
return "ERROR: " + str(rep.get("error"))
|
| 150 |
+
bits = []
|
| 151 |
+
if "reached" in rep:
|
| 152 |
+
bits.append("reached" if rep["reached"] else "NOT reached")
|
| 153 |
+
if "sweep_reached" in rep:
|
| 154 |
+
bits.append("sweep completed" if rep["sweep_reached"] else "sweep NOT completed")
|
| 155 |
+
if "eef_pos" in rep and name in ("move_to", "push", "open_gripper", "close_gripper"):
|
| 156 |
+
bits.append("eef (" + ", ".join(f"{x:.3f}" for x in rep["eef_pos"]) + ")")
|
| 157 |
+
if name in ("open_gripper", "close_gripper"):
|
| 158 |
+
bits.append(f"width {rep.get('gripper_width_m', 0):.3f} m")
|
| 159 |
+
if rep.get("holding_object") not in (None, False):
|
| 160 |
+
bits.append(f"holding {rep['holding_object']}" if isinstance(rep["holding_object"], str) else "holding an object")
|
| 161 |
+
if rep.get("touched_object") or rep.get("touched_objects"):
|
| 162 |
+
t = rep.get("touched_objects")
|
| 163 |
+
bits.append("touched " + ", ".join(t) if t else "touched an object")
|
| 164 |
+
if name == "pixel_to_world":
|
| 165 |
+
bits.append("world (" + ", ".join(f"{x:.3f}" for x in rep["world_xyz"]) + ")")
|
| 166 |
+
if name == "locate":
|
| 167 |
+
bits.append("pos (" + ", ".join(f"{x:.3f}" for x in rep["position"]) + ")")
|
| 168 |
+
if "target_clipped_to" in rep or "start_clipped_to" in rep:
|
| 169 |
+
bits.append("target clipped to workspace")
|
| 170 |
+
if rep.get("events"):
|
| 171 |
+
bits.append("EVENT: " + " ".join(rep["events"]))
|
| 172 |
+
return "; ".join(bits) if bits else "ok"
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def summarize_actions(steps):
|
| 176 |
+
lines = []
|
| 177 |
+
for s in steps:
|
| 178 |
+
if s.name == "done":
|
| 179 |
+
lines.append(f"{s.step}. done(reason={json.dumps(s.args.get('reason', ''))})")
|
| 180 |
+
else:
|
| 181 |
+
lines.append(f"{s.step}. {fmt_call(s.name, s.args)} -> {fmt_report(s.name, s.report)}")
|
| 182 |
+
return "\n".join(lines) if lines else "(no actions)"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _text(t):
|
| 186 |
+
return dict(type="text", text=t)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _img(ref):
|
| 190 |
+
return dict(type="image", image=ref)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class PromptBuilder:
|
| 194 |
+
"""All text the agent sees. One instance per (task, config)."""
|
| 195 |
+
|
| 196 |
+
def __init__(self, task, protocol, k, memory, feedback, image_res, cam_axes, privileged_locate=False,
|
| 197 |
+
object_names=(), grasp_report="bool", cams=("agentview", "wrist"), depth_tool=True):
|
| 198 |
+
self.task, self.protocol, self.k = task, protocol, k
|
| 199 |
+
self.depth_tool = depth_tool
|
| 200 |
+
self.memory, self.feedback = memory, feedback
|
| 201 |
+
self.image_res, self.cam_axes = image_res, cam_axes
|
| 202 |
+
self.privileged_locate, self.object_names = privileged_locate, list(object_names)
|
| 203 |
+
self.grasp_report, self.cams = grasp_report, tuple(cams)
|
| 204 |
+
|
| 205 |
+
# ----------------------------------------------------------------------------- system prompt
|
| 206 |
+
def system_prompt(self):
|
| 207 |
+
ax = self.cam_axes.get("agentview") or {}
|
| 208 |
+
wx = self.cam_axes.get("wrist") or {}
|
| 209 |
+
lines = [
|
| 210 |
+
"You control a Franka Panda robot arm with a parallel-jaw gripper in a tabletop physics simulation. "
|
| 211 |
+
"You act only by calling the provided tools, exactly one tool call per turn. Every action tool returns an "
|
| 212 |
+
"execution report; after each action you also receive new camera images and the robot's proprioceptive "
|
| 213 |
+
"state.",
|
| 214 |
+
"",
|
| 215 |
+
"Coordinates (world frame, metres): the table top is at z = %.2f; the robot base is at x = -0.66, y = 0; "
|
| 216 |
+
"+x points away from the robot, +y to the robot's left, +z up. Positions given to move_to / push are for "
|
| 217 |
+
"the gripper's grasp point (midway between the fingertips). The gripper always points straight down; yaw "
|
| 218 |
+
"(degrees) turns it about the vertical axis: at yaw 0 the fingers close along the world y axis, at yaw 90 "
|
| 219 |
+
"along the world x axis; yaw is taken modulo 180 degrees because the gripper is symmetric." % TABLE_Z,
|
| 220 |
+
"",
|
| 221 |
+
"Direction words in every text you receive (task, reports, feedback) are robot-centric: forward = +x (away "
|
| 222 |
+
"from the robot), backward = -x (toward the robot), left = +y (the robot's left), right = -y (the robot's "
|
| 223 |
+
"right), up = +z. They never mean left/right in an image.",
|
| 224 |
+
"",
|
| 225 |
+
"Cameras (%dx%d images): 'agentview' looks at the table from the side opposite the robot, so the robot "
|
| 226 |
+
"appears at the top of that image; image-right is %s and image-down is %s in world coordinates (so the "
|
| 227 |
+
"robot's left appears on the right side of that image). 'wrist' is "
|
| 228 |
+
"mounted on the gripper and looks down between the fingers (at yaw 0, image-right is %s and image-down is "
|
| 229 |
+
"%s).%s"
|
| 230 |
+
% (self.image_res, self.image_res, ax.get("right", "?"), ax.get("down", "?"), wx.get("right", "?"),
|
| 231 |
+
wx.get("down", "?"),
|
| 232 |
+
" For pixel_to_world, u is the column counted from the left edge and v the row counted from the top "
|
| 233 |
+
"edge of the image as you received it." if self.depth_tool else ""),
|
| 234 |
+
"",
|
| 235 |
+
"Proprioception (end-effector position, yaw, gripper width%s) comes from the robot's own sensors."
|
| 236 |
+
% (", whether an object is held" if self.grasp_report != "none" else ""),
|
| 237 |
+
]
|
| 238 |
+
if self.privileged_locate:
|
| 239 |
+
lines += ["", "The locate tool is available and returns exact object positions. Objects: "
|
| 240 |
+
+ ", ".join(self.object_names) + "."]
|
| 241 |
+
else:
|
| 242 |
+
lines += ["", "Object positions are not given to you: localise objects from the images, e.g. by calling "
|
| 243 |
+
"pixel_to_world on the pixel where you see them." if self.depth_tool else
|
| 244 |
+
"Object positions are not given to you and there is no depth sensor: the cameras give colour "
|
| 245 |
+
"images only. Localise objects from the images."]
|
| 246 |
+
lines += ["", self._protocol_text(), "", self._feedback_text()]
|
| 247 |
+
if self.memory != "none":
|
| 248 |
+
lines += ["", "At the start of every attempt after the first, before your first tool call, write one to "
|
| 249 |
+
"three sentences assessing the earlier attempt(s): what happened and what you will keep or "
|
| 250 |
+
"change."]
|
| 251 |
+
lines += ["", "Finish by calling done(reason) when you believe the task is complete. Be precise: small errors "
|
| 252 |
+
"in position or speed matter."]
|
| 253 |
+
return "\n".join(lines)
|
| 254 |
+
|
| 255 |
+
def _protocol_text(self):
|
| 256 |
+
if self.memory == "none":
|
| 257 |
+
if self.protocol == "within":
|
| 258 |
+
return "Work on the task until you believe it is complete, then call done."
|
| 259 |
+
return "You have one attempt at the task; it ends when you call done."
|
| 260 |
+
if self.protocol == "within":
|
| 261 |
+
if self.feedback == "F0":
|
| 262 |
+
return (f"Everything happens in one continuous episode. After you call done you may be asked to "
|
| 263 |
+
f"continue from the current state; you may call done at most {self.k} times.")
|
| 264 |
+
return (f"Everything happens in one continuous episode. When you call done, the task is checked; if it is "
|
| 265 |
+
f"not complete you are told so and continue from the current state. You may call done at most "
|
| 266 |
+
f"{self.k} times.")
|
| 267 |
+
return (f"You get up to {self.k} attempts at the same task. Before every attempt the scene is reset to exactly "
|
| 268 |
+
f"the same initial state, with the same objects and the same physical properties. Each attempt ends "
|
| 269 |
+
f"when you call done; you will then see a summary of the attempt (key images, the actions you "
|
| 270 |
+
f"executed{'' if self.feedback == 'F0' else ' and outcome feedback'}).")
|
| 271 |
+
|
| 272 |
+
def _feedback_text(self):
|
| 273 |
+
if self.memory == "none":
|
| 274 |
+
return ""
|
| 275 |
+
if self.feedback == "F0":
|
| 276 |
+
return ("You will not be told whether an attempt succeeded; judge it from the images. "
|
| 277 |
+
+ ("Attempts continue until the budget is used up." if self.protocol == "cross" else ""))
|
| 278 |
+
if self.feedback == "F1":
|
| 279 |
+
return "After each attempt you are told only whether it succeeded."
|
| 280 |
+
return "After each attempt you are told whether it succeeded and, if not, a measurement of what went wrong."
|
| 281 |
+
|
| 282 |
+
# ----------------------------------------------------------------------------- per attempt
|
| 283 |
+
def history_parts(self, instruction, history):
|
| 284 |
+
"""First user item of an attempt (not pruned): task + packed earlier attempts. The header carries no
|
| 285 |
+
count so that the item grows append-only from one attempt to the next (prompt-cache friendly)."""
|
| 286 |
+
parts = [_text("TASK: " + instruction)]
|
| 287 |
+
if history:
|
| 288 |
+
parts.append(_text("\n=== Your earlier attempts ==="))
|
| 289 |
+
for i, rec in enumerate(history, 1):
|
| 290 |
+
parts += self.history_block(rec, i)
|
| 291 |
+
parts.append(_text("=== End of earlier attempts ==="))
|
| 292 |
+
return parts
|
| 293 |
+
|
| 294 |
+
def current_parts(self, attempt, obs_images, proprio, continuing=False):
|
| 295 |
+
"""Second user item of an attempt (live): attempt counter + current observation."""
|
| 296 |
+
parts = []
|
| 297 |
+
if self.memory != "none":
|
| 298 |
+
if self.protocol == "within" and continuing:
|
| 299 |
+
if self.feedback == "F0":
|
| 300 |
+
parts.append(_text(f"You called done. Continue from the current state (this is segment "
|
| 301 |
+
f"{attempt}; you may call done at most {self.k} times in total)."))
|
| 302 |
+
else:
|
| 303 |
+
parts.append(_text(f"You called done, but the task is not complete. Continue from the current "
|
| 304 |
+
f"state (this is segment {attempt}; you may call done at most {self.k} times "
|
| 305 |
+
f"in total)."))
|
| 306 |
+
elif self.protocol == "cross":
|
| 307 |
+
parts.append(_text(f"This is attempt {attempt} of at most {self.k}. The scene has been reset."))
|
| 308 |
+
parts += self.observation_parts("Current observation", obs_images, proprio)
|
| 309 |
+
return parts
|
| 310 |
+
|
| 311 |
+
def history_block(self, rec, idx):
|
| 312 |
+
head = f"\n--- Attempt {idx} ---" if self.protocol == "cross" else f"\n--- Segment {idx} (until done call {idx}) ---"
|
| 313 |
+
parts = [_text(head + "\nActions executed:\n" + summarize_actions(rec.steps))]
|
| 314 |
+
fb = (rec.feedback or "").strip()
|
| 315 |
+
if self.feedback != "F0" and fb:
|
| 316 |
+
parts.append(_text("Outcome feedback: " + fb))
|
| 317 |
+
if rec.keyframes:
|
| 318 |
+
parts.append(_text("Key images (" + ", ".join(c for c, _ in rec.keyframes) + "):"))
|
| 319 |
+
for cap, ref in rec.keyframes:
|
| 320 |
+
parts.append(_text(f"[{cap}]"))
|
| 321 |
+
parts.append(_img(ref))
|
| 322 |
+
return parts
|
| 323 |
+
|
| 324 |
+
def observation_parts(self, title, images, proprio):
|
| 325 |
+
parts = [_text(f"\n{title}:")]
|
| 326 |
+
for ref in images:
|
| 327 |
+
parts.append(_text(f"{ref.camera} camera:"))
|
| 328 |
+
parts.append(_img(ref))
|
| 329 |
+
parts.append(_text("Proprioception: " + json.dumps(proprio)))
|
| 330 |
+
return parts
|
| 331 |
+
|
| 332 |
+
def step_observation(self, step, tool_name, images, proprio):
|
| 333 |
+
return self.observation_parts(f"Observation after step {step} ({tool_name})", images, proprio)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def nudge():
|
| 337 |
+
return [_text("Please continue by calling exactly one tool (call done if you are finished).")]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def pick_keyframes(steps, initial, final, n=4):
|
| 341 |
+
"""<= n agentview keyframes: start, up to n-2 informative intermediate frames, end (after settling)."""
|
| 342 |
+
out = [("start of attempt", initial)] if initial is not None and n >= 2 else []
|
| 343 |
+
budget = n - len(out) - (1 if final is not None else 0)
|
| 344 |
+
cands = [s for s in steps if s.frame is not None]
|
| 345 |
+
if budget > 0 and cands:
|
| 346 |
+
events = [s for s in cands if s.name in ("push", "close_gripper", "open_gripper")
|
| 347 |
+
or s.report.get("touched_object") or s.report.get("touched_objects")]
|
| 348 |
+
pool = events if len(events) >= budget else cands
|
| 349 |
+
if len(pool) > budget:
|
| 350 |
+
idx = [round(i * (len(pool) - 1) / max(budget - 1, 1)) for i in range(budget)] if budget > 1 \
|
| 351 |
+
else [len(pool) - 1]
|
| 352 |
+
pool = [pool[i] for i in sorted(set(idx))]
|
| 353 |
+
for s in sorted(pool, key=lambda s: s.step)[:budget]:
|
| 354 |
+
out.append((f"after step {s.step} ({s.name})", s.frame))
|
| 355 |
+
if final is not None:
|
| 356 |
+
out.append(("end of attempt, after objects settled", final))
|
| 357 |
+
return out[:n]
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def wilson(k, n, z=1.96):
|
| 361 |
+
if n == 0:
|
| 362 |
+
return (float("nan"), float("nan"))
|
| 363 |
+
p = k / n
|
| 364 |
+
d = 1 + z * z / n
|
| 365 |
+
c = (p + z * z / (2 * n)) / d
|
| 366 |
+
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
|
| 367 |
+
return (max(0.0, c - h), min(1.0, c + h))
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def deep_strip_images(obj):
|
| 371 |
+
"""JSON-friendly copy of conversation items (images -> paths)."""
|
| 372 |
+
obj = copy.copy(obj)
|
| 373 |
+
if isinstance(obj, dict):
|
| 374 |
+
return {k: (v.path if k == "image" else deep_strip_images(v)) for k, v in obj.items()}
|
| 375 |
+
if isinstance(obj, list):
|
| 376 |
+
return [deep_strip_images(v) for v in obj]
|
| 377 |
+
return obj
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l5_tablecloth_pull (docs/14 §6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset,
|
| 4 |
+
oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled
|
| 5 |
+
from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu.
|
| 6 |
+
|
| 7 |
+
Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed
|
| 8 |
+
up to ~0.8 m/s (0.8 and 1.0 m/s give identical results: the controller saturates). The naive policy yanks at 0.6 m/s.
|
| 9 |
+
Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull
|
| 10 |
+
slower".
|
| 11 |
+
|
| 12 |
+
h0 mu at which the 0.6 m/s yank lands the cube on the band's centre line (calibrated per full5 seed by a
|
| 13 |
+
simulated sweep; a linear fit in band_d for other seeds).
|
| 14 |
+
twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot
|
| 15 |
+
(err +1.5 .. +2.7 cm), so the lesson is "pull faster" (the twin's oracle pulls at 0.64-0.79 m/s; agents can
|
| 16 |
+
command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short.
|
| 17 |
+
The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the
|
| 18 |
+
twin's naive error is only ~1.5-2.7 cm (similar size to the original's short-fall) and the twin's oracle is
|
| 19 |
+
within 0.2-0.5 cm of the band tolerance on some seeds. Calibrated per seed; for other seeds 1.2 x the H0 mu.
|
| 20 |
+
reveal states the cube's friction coefficient (the only fact that differs between instances).
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
HIDDEN_KEYS = ("mu",)
|
| 24 |
+
|
| 25 |
+
# Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim).
|
| 26 |
+
# seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm])
|
| 27 |
+
_CAL = {
|
| 28 |
+
3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60
|
| 29 |
+
3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47
|
| 30 |
+
3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78
|
| 31 |
+
3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44
|
| 32 |
+
3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _h0_mu(inst):
|
| 37 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 38 |
+
return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"])
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def h0(inst):
|
| 42 |
+
return {"mu": float(_h0_mu(inst))}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def twin(inst):
|
| 46 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 47 |
+
return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def reveal(inst):
|
| 51 |
+
return (f"The red cube's friction coefficient (against the board and against the table) is about "
|
| 52 |
+
f"{float(inst['mu']):.3f}.")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def fix(inst, params):
|
| 56 |
+
"""Ladder Fix rung (docs/20): one pull of 25 cm at the oracle speed (bisection with the true mu), as
|
| 57 |
+
l5_tablecloth_pull.execute; move_eef speed = Skills.move_to speed."""
|
| 58 |
+
v = float(params["speed"])
|
| 59 |
+
return (f"A way to succeed: pull at the right speed. Grasp the black handle (jaws closing across its 4 cm width), "
|
| 60 |
+
f"then in one move_eef command pull the board straight towards the robot by 25 cm at speed {v:.2f}; then "
|
| 61 |
+
f"open the gripper and lift. The cube then lands in the green band.")
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness adapters (docs/15): one way to plug any agent harness into a robot_server session.
|
| 2 |
+
|
| 3 |
+
ours reference driver scripts/api_player.py (main table)
|
| 4 |
+
claude_code Claude Code CLI, --bare, only our MCP tools (arm B)
|
| 5 |
+
claude_code_full Claude Code CLI without --bare: full system prompt, still one-time dirs and only MCP (arm B')
|
| 6 |
+
codex Codex CLI exec (+ exec resume on early exit), one-time CODEX_HOME, only our MCP tools (arm F)
|
| 7 |
+
rpent_codex RPent (robot harness framework) on Codex: RPent's loop and prompt, the main table's Codex config,
|
| 8 |
+
tools through the episode's tool gateway (docs/18, lffbench/harnesses/rpent.py)
|
| 9 |
+
dsh DeepSeek Harness (`dsh --profile headless`), only our MCP tools, one-time dirs
|
| 10 |
+
|
| 11 |
+
Use scripts/harness_run.py (one session) or scripts/api_batch.py start --harness ... (batches).
|
| 12 |
+
"""
|
| 13 |
+
import json
|
| 14 |
+
import importlib
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
|
| 18 |
+
from .base import EpisodeSpec, HarnessAdapter, HarnessRefused, first_message_text # noqa: F401
|
| 19 |
+
|
| 20 |
+
# A new Codex-based Robot Harness registers here; both single-run and batch CLIs
|
| 21 |
+
# derive their choices, provider and common options from this registry.
|
| 22 |
+
ROBOT_HARNESSES = {
|
| 23 |
+
"rpent_codex": ("rpent", "RPentCodex"),
|
| 24 |
+
"sensenova_codex": ("sensenova", "SenseNovaCodex"),
|
| 25 |
+
"embodied_evo_codex": ("embodied_evo", "EmbodiedEvoCodex"),
|
| 26 |
+
}
|
| 27 |
+
NAMES = ("ours", "claude_code", "claude_code_full", "codex", "dsh", *ROBOT_HARNESSES)
|
| 28 |
+
PROVIDER = dict(claude_code="anthropic", claude_code_full="anthropic", codex="openai", dsh="deepseek",
|
| 29 |
+
**{name: "openai" for name in ROBOT_HARNESSES})
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_adapter(name, **kw):
|
| 33 |
+
if name == "ours":
|
| 34 |
+
from .reference import Reference
|
| 35 |
+
return Reference(**kw)
|
| 36 |
+
if name == "claude_code":
|
| 37 |
+
from .claude_code import ClaudeCode
|
| 38 |
+
return ClaudeCode(**kw)
|
| 39 |
+
if name == "claude_code_full":
|
| 40 |
+
from .claude_code import ClaudeCodeFull
|
| 41 |
+
return ClaudeCodeFull(**kw)
|
| 42 |
+
if name == "codex":
|
| 43 |
+
from .codex import Codex
|
| 44 |
+
return Codex(**kw)
|
| 45 |
+
if name == "dsh":
|
| 46 |
+
from .dsh import DeepSeekHarness
|
| 47 |
+
return DeepSeekHarness(**kw)
|
| 48 |
+
if name in ROBOT_HARNESSES:
|
| 49 |
+
module, cls = ROBOT_HARNESSES[name]
|
| 50 |
+
return getattr(importlib.import_module("." + module, __name__), cls)(**kw)
|
| 51 |
+
raise ValueError(f"unknown harness {name!r}; one of {NAMES}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def render_first_message(ep):
|
| 55 |
+
"""Call `status` once over HTTP (exactly as the reference driver does before its first turn) and build the first
|
| 56 |
+
user message for a native harness. Returns (text, status_json)."""
|
| 57 |
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
| 58 |
+
"scripts"))
|
| 59 |
+
from api_player import call_server # noqa: E402
|
| 60 |
+
st = json.loads(call_server(ep.port, ep.token, "status", {}))
|
| 61 |
+
readme = open(os.path.join(ep.sandbox, "README.md")).read()
|
| 62 |
+
status_json = json.dumps(st)
|
| 63 |
+
return first_message_text(readme, status_json), status_json
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness adapter interface (docs/15 §3).
|
| 2 |
+
|
| 3 |
+
An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log
|
| 4 |
+
dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations).
|
| 5 |
+
Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server /
|
| 6 |
+
reference driver enforce them identically for every harness.
|
| 7 |
+
|
| 8 |
+
name stable harness name (the "harness" column of a table)
|
| 9 |
+
capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source;
|
| 10 |
+
a missing item makes the class definition fail (so the import fails)
|
| 11 |
+
version() the actual installed version (probed before launch)
|
| 12 |
+
prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env
|
| 13 |
+
launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle
|
| 14 |
+
collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason
|
| 15 |
+
audit(h) tool list, preset prompt, memory, state left behind, violations
|
| 16 |
+
"""
|
| 17 |
+
import dataclasses
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import secrets
|
| 21 |
+
import shutil
|
| 22 |
+
import signal
|
| 23 |
+
import subprocess
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
from . import contract as C
|
| 27 |
+
|
| 28 |
+
EVIDENCE = ("launch", "stream", "server", "probe", "preflight")
|
| 29 |
+
|
| 30 |
+
REQUIRED = {
|
| 31 |
+
"only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use",
|
| 32 |
+
"images_reach_model": "view_images returns the image bytes to the model unchanged",
|
| 33 |
+
"non_persistent_session": "nothing of the session is written to disk for later runs",
|
| 34 |
+
"pinned_version": "the harness version (and binary hash) is recorded and pinned",
|
| 35 |
+
"machine_readable_events": "a machine-readable event stream of the whole run",
|
| 36 |
+
"tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)",
|
| 37 |
+
"model_and_effort": "model and reasoning effort can be set and are visible in the request",
|
| 38 |
+
}
|
| 39 |
+
FORBIDDEN = {
|
| 40 |
+
"persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)",
|
| 41 |
+
"instruction_file_injection": "instruction files picked up from the work / config / home dir",
|
| 42 |
+
"web_access": "web search / fetch",
|
| 43 |
+
"host_file_read": "reading host files outside the episode workspace",
|
| 44 |
+
"builtin_shell": "a shell of the harness itself (outside our jailed shell tool)",
|
| 45 |
+
"subagent_delegation": "spawning sub-agents",
|
| 46 |
+
"background_execution": "background tasks that outlive a tool call",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclasses.dataclass(frozen=True)
|
| 51 |
+
class Cap:
|
| 52 |
+
status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial"
|
| 53 |
+
evidence: str # one of EVIDENCE
|
| 54 |
+
note: str = ""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")
|
| 58 |
+
NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
|
| 59 |
+
NO_PROXY_LOCAL = "127.0.0.1,localhost,::1"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def proxy_env(environ=None):
|
| 63 |
+
"""The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines
|
| 64 |
+
that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list.
|
| 65 |
+
Not part of config_sha256 (machine plumbing, not harness configuration)."""
|
| 66 |
+
environ = os.environ if environ is None else environ
|
| 67 |
+
e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)}
|
| 68 |
+
if e:
|
| 69 |
+
e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS})
|
| 70 |
+
return e
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class CapabilityError(TypeError):
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_capabilities(name, caps):
|
| 78 |
+
if not isinstance(caps, dict):
|
| 79 |
+
raise CapabilityError(f"{name}: capabilities must be a dict")
|
| 80 |
+
missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps]
|
| 81 |
+
extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN]
|
| 82 |
+
if missing or extra:
|
| 83 |
+
raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}")
|
| 84 |
+
for k, c in caps.items():
|
| 85 |
+
if not isinstance(c, Cap) or c.evidence not in EVIDENCE:
|
| 86 |
+
raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})")
|
| 87 |
+
ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial")
|
| 88 |
+
if c.status not in ok:
|
| 89 |
+
raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class HarnessRefused(RuntimeError):
|
| 93 |
+
"""Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one."""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@dataclasses.dataclass
|
| 97 |
+
class EpisodeSpec:
|
| 98 |
+
session_path: str
|
| 99 |
+
log_dir: str
|
| 100 |
+
sandbox: str
|
| 101 |
+
port: int
|
| 102 |
+
token: str
|
| 103 |
+
max_tool_calls: int
|
| 104 |
+
model: str
|
| 105 |
+
effort: str
|
| 106 |
+
provider: str = ""
|
| 107 |
+
task: str = ""
|
| 108 |
+
seed: int = 0
|
| 109 |
+
extra: dict = dataclasses.field(default_factory=dict)
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def from_session(cls, session_path, model, effort, provider="", **extra):
|
| 113 |
+
session_path = os.path.abspath(session_path)
|
| 114 |
+
log_dir = os.path.dirname(session_path)
|
| 115 |
+
sess = json.load(open(session_path))
|
| 116 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 117 |
+
st = C.session_start(log_dir)
|
| 118 |
+
return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]),
|
| 119 |
+
token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort,
|
| 120 |
+
provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclasses.dataclass
|
| 124 |
+
class LaunchSpec:
|
| 125 |
+
argv: list # full argv (the first message may be one element)
|
| 126 |
+
env: dict # the complete environment of the harness process (nothing else is inherited)
|
| 127 |
+
cwd: str
|
| 128 |
+
run_dir: str = "" # one-time dir tree, removed after audit
|
| 129 |
+
state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...)
|
| 130 |
+
first_message: str = ""
|
| 131 |
+
config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote
|
| 132 |
+
stdout_path: str = ""
|
| 133 |
+
stderr_path: str = ""
|
| 134 |
+
redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log
|
| 135 |
+
preflight: dict = dataclasses.field(default_factory=dict)
|
| 136 |
+
timeout_s: float = 10800
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclasses.dataclass
|
| 140 |
+
class RunHandle:
|
| 141 |
+
spec: LaunchSpec
|
| 142 |
+
ep: EpisodeSpec
|
| 143 |
+
proc: object = None
|
| 144 |
+
pid: int = 0
|
| 145 |
+
t_start: float = 0.0
|
| 146 |
+
t_end: float = 0.0
|
| 147 |
+
exit_code: int = None
|
| 148 |
+
exit_reason: str = ""
|
| 149 |
+
env_observed_keys: list = None # read from /proc/<pid>/environ right after the start
|
| 150 |
+
info: dict = dataclasses.field(default_factory=dict)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def env_keys_of(pid):
|
| 154 |
+
try:
|
| 155 |
+
raw = open(f"/proc/{pid}/environ", "rb").read()
|
| 156 |
+
except OSError:
|
| 157 |
+
return None
|
| 158 |
+
return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv})
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def new_run_dir(root="/tmp/lffrun"):
|
| 162 |
+
"""/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses)."""
|
| 163 |
+
os.makedirs(root, exist_ok=True)
|
| 164 |
+
while True:
|
| 165 |
+
d = os.path.join(root, secrets.token_hex(6))
|
| 166 |
+
try:
|
| 167 |
+
os.mkdir(d, 0o700)
|
| 168 |
+
return d
|
| 169 |
+
except FileExistsError:
|
| 170 |
+
continue
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def binary_info(path):
|
| 174 |
+
real = os.path.realpath(path)
|
| 175 |
+
return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class HarnessAdapter:
|
| 179 |
+
name = None
|
| 180 |
+
capabilities = None
|
| 181 |
+
uses_mcp = False
|
| 182 |
+
uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for
|
| 183 |
+
# this adapter: MCP adapters through the MCP server, framework adapters
|
| 184 |
+
# (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN
|
| 185 |
+
clean_dirs = () # keys of spec.state_dirs that must be empty at launch
|
| 186 |
+
clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json)
|
| 187 |
+
ancestor_files = () # instruction files that must not exist in the work dir or any ancestor
|
| 188 |
+
unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read)
|
| 189 |
+
jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4)
|
| 190 |
+
can_resume = False # resume(): the CLI can continue its session with one more user message
|
| 191 |
+
|
| 192 |
+
def clean_state_problems(self, spec):
|
| 193 |
+
"""Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an
|
| 194 |
+
ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md)."""
|
| 195 |
+
p = []
|
| 196 |
+
if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd):
|
| 197 |
+
p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}")
|
| 198 |
+
for k in self.clean_dirs:
|
| 199 |
+
d = spec.state_dirs.get(k)
|
| 200 |
+
left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else []
|
| 201 |
+
if left:
|
| 202 |
+
p.append(f"{k} dir not empty: {sorted(left)[:5]}")
|
| 203 |
+
d = spec.cwd
|
| 204 |
+
while d and d != "/":
|
| 205 |
+
d = os.path.dirname(d)
|
| 206 |
+
for f in self.ancestor_files:
|
| 207 |
+
if os.path.exists(os.path.join(d, f)):
|
| 208 |
+
p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}")
|
| 209 |
+
return p
|
| 210 |
+
|
| 211 |
+
def __init_subclass__(cls, **kw):
|
| 212 |
+
super().__init_subclass__(**kw)
|
| 213 |
+
if cls.name is None:
|
| 214 |
+
raise CapabilityError(f"{cls.__name__}: no name")
|
| 215 |
+
check_capabilities(cls.name, cls.capabilities)
|
| 216 |
+
|
| 217 |
+
# -------------------------------------------------------------------------------------------- interface
|
| 218 |
+
def version(self):
|
| 219 |
+
raise NotImplementedError
|
| 220 |
+
|
| 221 |
+
def prepare(self, ep, first_message):
|
| 222 |
+
raise NotImplementedError
|
| 223 |
+
|
| 224 |
+
def preflight(self, spec, ep):
|
| 225 |
+
"""Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused."""
|
| 226 |
+
return dict(skipped=True)
|
| 227 |
+
|
| 228 |
+
def collect(self, h):
|
| 229 |
+
raise NotImplementedError
|
| 230 |
+
|
| 231 |
+
def audit(self, h):
|
| 232 |
+
raise NotImplementedError
|
| 233 |
+
|
| 234 |
+
# -------------------------------------------------------------------------------------------- shared
|
| 235 |
+
def mcp_server_command(self, python, script, args):
|
| 236 |
+
"""(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it."""
|
| 237 |
+
if self.jail is not None:
|
| 238 |
+
return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"})
|
| 239 |
+
return python, [script] + list(args)
|
| 240 |
+
|
| 241 |
+
def jailed_argv(self, argv, env, cwd, dirs):
|
| 242 |
+
"""argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back."""
|
| 243 |
+
return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv)
|
| 244 |
+
|
| 245 |
+
def jail_info(self):
|
| 246 |
+
return self.jail.info() if self.jail is not None else dict(enabled=False)
|
| 247 |
+
|
| 248 |
+
def auth_info(self):
|
| 249 |
+
"""How the harness authenticates to the model API (for harness.json; never a secret)."""
|
| 250 |
+
return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {}))
|
| 251 |
+
|
| 252 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 253 |
+
if not self.unsafe_skip_clean_check:
|
| 254 |
+
probs = self.clean_state_problems(spec)
|
| 255 |
+
if probs:
|
| 256 |
+
spec.preflight = dict(problems=probs)
|
| 257 |
+
raise HarnessRefused("clean-state check: " + "; ".join(probs))
|
| 258 |
+
spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep)
|
| 259 |
+
out = open(spec.stdout_path, "wb")
|
| 260 |
+
err = open(spec.stderr_path, "wb")
|
| 261 |
+
h = RunHandle(spec=spec, ep=ep, t_start=time.time())
|
| 262 |
+
argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 263 |
+
h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 264 |
+
stderr=err, start_new_session=True)
|
| 265 |
+
h.pid = h.proc.pid
|
| 266 |
+
for _ in range(20): # the exec has happened once /proc/<pid>/environ differs from ours
|
| 267 |
+
keys = env_keys_of(h.pid)
|
| 268 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 269 |
+
break
|
| 270 |
+
time.sleep(0.05)
|
| 271 |
+
h.env_observed_keys = keys # retain the observed sample; a second read can race setpriv/exec
|
| 272 |
+
return h
|
| 273 |
+
|
| 274 |
+
def resume_argv(self, h, message):
|
| 275 |
+
"""argv that continues the run's session with one more user message (adapters with can_resume)."""
|
| 276 |
+
raise NotImplementedError
|
| 277 |
+
|
| 278 |
+
def resume(self, h, message):
|
| 279 |
+
"""Continue the run's session with one more user message, after the CLI exited before the episode was over
|
| 280 |
+
(scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output
|
| 281 |
+
is appended to the same stdout / stderr files."""
|
| 282 |
+
spec = h.spec
|
| 283 |
+
argv = self.resume_argv(h, message)
|
| 284 |
+
out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab")
|
| 285 |
+
jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 286 |
+
h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 287 |
+
stderr=err, start_new_session=True)
|
| 288 |
+
h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, ""
|
| 289 |
+
keys = None
|
| 290 |
+
for _ in range(20):
|
| 291 |
+
keys = env_keys_of(h.pid)
|
| 292 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 293 |
+
break
|
| 294 |
+
time.sleep(0.05)
|
| 295 |
+
h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message,
|
| 296 |
+
argv=[("<message>" if x == message else x) for x in argv],
|
| 297 |
+
env_observed_keys=keys))
|
| 298 |
+
return h
|
| 299 |
+
|
| 300 |
+
def wait(self, h, timeout=None):
|
| 301 |
+
try:
|
| 302 |
+
h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s)
|
| 303 |
+
h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}"
|
| 304 |
+
except subprocess.TimeoutExpired:
|
| 305 |
+
self.kill(h)
|
| 306 |
+
h.exit_reason = "timeout"
|
| 307 |
+
h.t_end = time.time()
|
| 308 |
+
return h
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def kill(h):
|
| 312 |
+
try:
|
| 313 |
+
os.killpg(h.proc.pid, signal.SIGTERM)
|
| 314 |
+
h.exit_code = h.proc.wait(timeout=20)
|
| 315 |
+
except ProcessLookupError:
|
| 316 |
+
pass
|
| 317 |
+
except subprocess.TimeoutExpired:
|
| 318 |
+
os.killpg(h.proc.pid, signal.SIGKILL)
|
| 319 |
+
h.exit_code = h.proc.wait()
|
| 320 |
+
|
| 321 |
+
def logged_argv(self, spec):
|
| 322 |
+
return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)]
|
| 323 |
+
|
| 324 |
+
def cleanup(self, spec):
|
| 325 |
+
if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir):
|
| 326 |
+
shutil.rmtree(spec.run_dir, ignore_errors=True)
|
| 327 |
+
for d in spec.state_dirs.values():
|
| 328 |
+
if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d):
|
| 329 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 330 |
+
if self.jail is not None:
|
| 331 |
+
self.jail.close()
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def gateway_env(log_dir):
|
| 335 |
+
"""{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose
|
| 336 |
+
process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before
|
| 337 |
+
launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the
|
| 338 |
+
gateway's, never robot_server's."""
|
| 339 |
+
d = json.load(open(os.path.join(log_dir, "gateway.json")))
|
| 340 |
+
return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]}
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def snapshot_tree(root):
|
| 344 |
+
"""Relative paths of all files under root (to list what a harness left behind)."""
|
| 345 |
+
out = []
|
| 346 |
+
for dp, dn, fn in os.walk(root):
|
| 347 |
+
for f in fn:
|
| 348 |
+
out.append(os.path.relpath(os.path.join(dp, f), root))
|
| 349 |
+
return sorted(out)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def first_message_text(readme, status_json):
|
| 353 |
+
"""What a native harness gets as its first user message: the reference driver's instructions (preamble + README,
|
| 354 |
+
byte-identical) followed by its first user turn (the status report). The reference driver sends the same two
|
| 355 |
+
strings as system prompt and first user message; native harnesses keep their own system prompt."""
|
| 356 |
+
from .contract import tool_schemas
|
| 357 |
+
_, preamble = tool_schemas()
|
| 358 |
+
return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def reference_instructions(readme):
|
| 362 |
+
from .contract import tool_schemas
|
| 363 |
+
_, preamble = tool_schemas()
|
| 364 |
+
return preamble + readme
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/claude_code.py
ADDED
|
@@ -0,0 +1,514 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.1).
|
| 2 |
+
|
| 3 |
+
Two variants:
|
| 4 |
+
claude_code arm B : -p --bare (system prompt ~400 chars, no CLAUDE.md / auto-memory / hooks / plugins)
|
| 5 |
+
claude_code_full arm B': same but without --bare: Claude Code's full system prompt; still a one-time config dir and
|
| 6 |
+
HOME, an empty opaque work dir, --tools "" and only our MCP server
|
| 7 |
+
Both: process env is exactly the whitelist (env -i equivalent; plus the calling HTTP(S) proxy, base.proxy_env),
|
| 8 |
+
HOME / CLAUDE_CONFIG_DIR / TMPDIR are one-time dirs
|
| 9 |
+
under /tmp/lffstate/<hex>, the work dir is /tmp/lffrun/<12 hex> (its path is written into the system prompt), the MCP
|
| 10 |
+
server is scripts/mcp_robot_server.py on the run's session.
|
| 11 |
+
|
| 12 |
+
Two ways to authenticate (auth=):
|
| 13 |
+
apikey ANTHROPIC_API_KEY (api_env)
|
| 14 |
+
oauth a Claude subscription: the long-lived token of `claude setup-token`, passed as CLAUDE_CODE_OAUTH_TOKEN
|
| 15 |
+
(api_env; never taken from the calling environment). claude_code_full only: --bare reads nothing but
|
| 16 |
+
ANTHROPIC_API_KEY / apiKeyHelper (2.1.267 --help).
|
| 17 |
+
Measured with 2.1.267 against the fake server (2026-10-20): the same single request in both modes, identical system
|
| 18 |
+
prompt, tools, messages and parameters; oauth sends Authorization: Bearer instead of x-api-key, two more beta flags
|
| 19 |
+
(oauth-2025-04-20, extended-cache-ttl-2025-04-11) and cache_control ttl=1h. Pins are per auth mode (pin name
|
| 20 |
+
claude_code_full-oauth).
|
| 21 |
+
|
| 22 |
+
Early exit: `claude -p` ends when the model replies without a tool call, also mid-episode. scripts/harness_run.py then
|
| 23 |
+
sends the reference driver's nudge with `claude -p <nudge> --resume <session>` (resume_argv), as for Codex. Hence no
|
| 24 |
+
--no-session-persistence: the session transcript is kept in the one-time CLAUDE_CONFIG_DIR (removed after the run);
|
| 25 |
+
the audit allows only this run's session. Measured against the fake server: the resumed request has the same system
|
| 26 |
+
prompt, tools, parameters and headers, then the earlier turns and the nudge as a user message.
|
| 27 |
+
|
| 28 |
+
Fail-closed launch: before the real run the same argv / env is started once against a local fake Anthropic server
|
| 29 |
+
(free) with a schema-only MCP server; the first request's tool list, system prompt, harness-added message prefix and
|
| 30 |
+
request parameters are normalised and hashed, and the launch is refused unless the hash equals the pinned one
|
| 31 |
+
(pins/claude_code*.json, written by tests/harness_selfcheck after the self-check passed). During the real run the
|
| 32 |
+
stream's init event is checked again (tool list); on a mismatch the process is killed.
|
| 33 |
+
"""
|
| 34 |
+
import copy
|
| 35 |
+
import json
|
| 36 |
+
import os
|
| 37 |
+
import re
|
| 38 |
+
import shutil
|
| 39 |
+
import subprocess
|
| 40 |
+
import sys
|
| 41 |
+
import time
|
| 42 |
+
|
| 43 |
+
from . import contract as C
|
| 44 |
+
from . import pins
|
| 45 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 46 |
+
new_run_dir, proxy_env, snapshot_tree)
|
| 47 |
+
from .fakeapi import FakeAnthropic
|
| 48 |
+
from .trajectory import TrajWriter, strip_mcp
|
| 49 |
+
|
| 50 |
+
ROOT = C.ROOT
|
| 51 |
+
MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
|
| 52 |
+
MCP_TOOLS = ["mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images"]
|
| 53 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 54 |
+
OAUTH_KEY = "CLAUDE_CODE_OAUTH_TOKEN"
|
| 55 |
+
PREFLIGHT_CREDENTIAL = dict(apikey=("ANTHROPIC_API_KEY", "sk-preflight-not-a-key"),
|
| 56 |
+
oauth=(OAUTH_KEY, "sk-ant-oat01-" + "x" * 95 + "AA")) # dummies, only for the fake server
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def claude_bin():
|
| 60 |
+
return os.environ.get("LFF_CLAUDE_BIN") or shutil.which("claude") or "claude"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _norm(s, spec):
|
| 64 |
+
"""Remove what legitimately differs between runs from preset prompt text: paths of the one-time dirs, dates."""
|
| 65 |
+
for k, v in sorted(dict(spec.state_dirs, cwd=spec.cwd).items(), key=lambda kv: -len(kv[1])):
|
| 66 |
+
s = s.replace(v, f"<{k.upper()}>")
|
| 67 |
+
s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
|
| 68 |
+
s = re.sub(r"-tmp-lffrun-[0-9a-f]{12}", "<RUNDIR_SLUG>", s) # auto-memory dir name derived from the cwd
|
| 69 |
+
s = re.sub(r"(cc_version=\d+\.\d+\.\d+)\.[0-9a-f]+", r"\1.<X>", s) # billing header suffix varies per request
|
| 70 |
+
s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
|
| 71 |
+
s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
|
| 72 |
+
s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "<UUID>", s)
|
| 73 |
+
return s
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def request_fingerprint(body, headers, spec, first_message):
|
| 77 |
+
"""Normalised preset part of the first request + the checks that do not need a pin."""
|
| 78 |
+
problems = []
|
| 79 |
+
system = body.get("system")
|
| 80 |
+
if isinstance(system, str):
|
| 81 |
+
system = [dict(type="text", text=system)]
|
| 82 |
+
sys_blocks = [dict(text=_norm(b.get("text", ""), spec), cache=bool(b.get("cache_control"))) for b in system or []]
|
| 83 |
+
tools = [dict(name=t.get("name"), description=t.get("description"), input_schema=t.get("input_schema"))
|
| 84 |
+
for t in body.get("tools") or []]
|
| 85 |
+
if [t["name"] for t in tools] != MCP_TOOLS:
|
| 86 |
+
problems.append(f"tool list is {[t['name'] for t in tools]}, expected {MCP_TOOLS}")
|
| 87 |
+
msgs = body.get("messages") or []
|
| 88 |
+
first = msgs[0] if msgs else {}
|
| 89 |
+
content = first.get("content")
|
| 90 |
+
if isinstance(content, str):
|
| 91 |
+
content = [dict(type="text", text=content)]
|
| 92 |
+
prefix, found = [], False
|
| 93 |
+
for b in content or []:
|
| 94 |
+
if b.get("type") == "text" and b.get("text") == first_message:
|
| 95 |
+
found = True
|
| 96 |
+
break
|
| 97 |
+
prefix.append(_norm(b.get("text", "") if b.get("type") == "text" else json.dumps(b, sort_keys=True), spec))
|
| 98 |
+
if not found:
|
| 99 |
+
problems.append("the first user message does not contain our first message byte-for-byte as one block")
|
| 100 |
+
params = {k: body.get(k) for k in ("model", "max_tokens", "thinking", "output_config", "context_management",
|
| 101 |
+
"temperature", "top_p", "top_k", "tool_choice")}
|
| 102 |
+
fp = dict(system=sys_blocks, tools=tools, user_prefix=prefix, params=params,
|
| 103 |
+
anthropic_beta=sorted((headers.get("anthropic-beta") or headers.get("Anthropic-Beta") or "").split(",")),
|
| 104 |
+
system_chars=sum(len(b.get("text", "")) for b in system or []))
|
| 105 |
+
return fp, problems
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class ClaudeCode(HarnessAdapter):
|
| 109 |
+
name = "claude_code"
|
| 110 |
+
bare = True
|
| 111 |
+
uses_mcp = True
|
| 112 |
+
clean_dirs = ("home", "config", "tmp")
|
| 113 |
+
ancestor_files = ("CLAUDE.md", "CLAUDE.local.md", ".claude", "AGENTS.md")
|
| 114 |
+
can_resume = True
|
| 115 |
+
capabilities = dict(
|
| 116 |
+
only_benchmark_tools=Cap("yes", "preflight", '--tools "" + --strict-mcp-config: request tools = 3 MCP tools'),
|
| 117 |
+
images_reach_model=Cap("yes", "probe", "MCP image content forwarded as image blocks, md5 equal"),
|
| 118 |
+
non_persistent_session=Cap("yes", "probe", "only this run's session (kept for -p --resume) in the one-time "
|
| 119 |
+
"config dir, removed after the run"),
|
| 120 |
+
pinned_version=Cap("yes", "launch", "claude --version + binary sha256 in harness.json; pin per version"),
|
| 121 |
+
machine_readable_events=Cap("yes", "stream", "--output-format stream-json --verbose"),
|
| 122 |
+
tool_calls_logged=Cap("yes", "stream", "tool_use / tool_result in stream + mcp_transcript + events.jsonl"),
|
| 123 |
+
model_and_effort=Cap("yes", "preflight", "--model / --effort; request output_config.effort checked"),
|
| 124 |
+
persistent_memory=Cap("absent", "probe", "--bare: no auto-memory; canaries never reach the request"),
|
| 125 |
+
instruction_file_injection=Cap("absent", "probe", "--bare: CLAUDE.md discovery off; canaries absent"),
|
| 126 |
+
web_access=Cap("absent", "preflight", "no WebFetch / WebSearch tool in the request"),
|
| 127 |
+
host_file_read=Cap("absent", "probe", "no Read tool; MCP shell is jailed; view_images confined"),
|
| 128 |
+
builtin_shell=Cap("absent", "preflight", "no Bash tool in the request"),
|
| 129 |
+
subagent_delegation=Cap("absent", "preflight", "no Agent / Task tool in the request"),
|
| 130 |
+
background_execution=Cap("absent", "preflight", "no Bash / Monitor tool in the request"),
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def __init__(self, api_env=None, max_budget_usd=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 134 |
+
python=None, extra_args=None, jail=False, auth="apikey"):
|
| 135 |
+
"""api_env: the only API variables passed to the harness: {"ANTHROPIC_API_KEY": ...} (auth="apikey") or
|
| 136 |
+
{"CLAUDE_CODE_OAUTH_TOKEN": ...} (auth="oauth", a subscription token of `claude setup-token`), optional
|
| 137 |
+
"ANTHROPIC_BASE_URL". Never inherited from the calling environment. jail: run the CLI in the
|
| 138 |
+
native-harness jail (lffbench/harnesses/jail.py; /proc stays the host's: Bun needs it)."""
|
| 139 |
+
if auth not in PREFLIGHT_CREDENTIAL:
|
| 140 |
+
raise ValueError(f"auth must be one of {sorted(PREFLIGHT_CREDENTIAL)}, not {auth!r}")
|
| 141 |
+
if auth == "oauth" and self.bare:
|
| 142 |
+
raise ValueError("claude_code (--bare) authenticates only with ANTHROPIC_API_KEY / apiKeyHelper; "
|
| 143 |
+
"use claude_code_full for a subscription token")
|
| 144 |
+
other = PREFLIGHT_CREDENTIAL["oauth" if auth == "apikey" else "apikey"][0]
|
| 145 |
+
if other in (api_env or {}):
|
| 146 |
+
raise ValueError(f"auth={auth}: api_env must not hold {other} (the CLI would use it instead)")
|
| 147 |
+
self.auth = auth
|
| 148 |
+
if jail:
|
| 149 |
+
from .jail import HarnessJail
|
| 150 |
+
self.jail = HarnessJail(claude_bin(), proc="host")
|
| 151 |
+
self.api_env = dict(api_env or {})
|
| 152 |
+
self.proxy = proxy_env()
|
| 153 |
+
self.max_budget_usd = max_budget_usd
|
| 154 |
+
self.timeout_s = timeout_s
|
| 155 |
+
self.pins_dir = pins_dir
|
| 156 |
+
self.allow_unpinned = allow_unpinned
|
| 157 |
+
self.python = python or sys.executable
|
| 158 |
+
self.extra_args = list(extra_args or [])
|
| 159 |
+
self._version = None
|
| 160 |
+
|
| 161 |
+
# ------------------------------------------------------------------------------------------------ version
|
| 162 |
+
def version(self):
|
| 163 |
+
if self._version is None:
|
| 164 |
+
b = claude_bin()
|
| 165 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent"), capture_output=True,
|
| 166 |
+
text=True, timeout=60)
|
| 167 |
+
v = (out.stdout.strip().split() or ["?"])[0]
|
| 168 |
+
self._version = dict(version=v, binary=binary_info(b))
|
| 169 |
+
return self._version
|
| 170 |
+
|
| 171 |
+
def pin_key(self, ep):
|
| 172 |
+
v = self.version()
|
| 173 |
+
name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
|
| 174 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 175 |
+
|
| 176 |
+
def auth_info(self):
|
| 177 |
+
key = PREFLIGHT_CREDENTIAL[self.auth][0]
|
| 178 |
+
return dict(mode=self.auth, credential_var=key, credential_set=bool(self.api_env.get(key)),
|
| 179 |
+
keys=sorted(self.api_env))
|
| 180 |
+
|
| 181 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 182 |
+
def mcp_config(self, session_path=None, describe=False):
|
| 183 |
+
"""describe: for config_sha256 only (jailed, no relay is set up for it)."""
|
| 184 |
+
args = ["--session", session_path] if session_path else ["--schema-only"]
|
| 185 |
+
if describe or self.jail is None:
|
| 186 |
+
cmd, a = ("<jail relay>" if self.jail is not None else self.python), [MCP_SCRIPT] + args
|
| 187 |
+
else:
|
| 188 |
+
cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args)
|
| 189 |
+
return {"mcpServers": {"lff": {"type": "stdio", "command": cmd, "args": a, "env": {"PATH": BASE_PATH}}}}
|
| 190 |
+
|
| 191 |
+
def argv(self, spec_paths, ep, first_message):
|
| 192 |
+
a = [claude_bin(), "-p", first_message]
|
| 193 |
+
if self.bare:
|
| 194 |
+
a.append("--bare")
|
| 195 |
+
a += ["--tools", "", "--strict-mcp-config", "--mcp-config", spec_paths["mcp_config"],
|
| 196 |
+
"--allowedTools", ",".join(MCP_TOOLS), "--permission-mode", "dontAsk", "--disable-slash-commands",
|
| 197 |
+
"--output-format", "stream-json", "--verbose", "--model", ep.model, "--effort", ep.effort]
|
| 198 |
+
if self.max_budget_usd:
|
| 199 |
+
a += ["--max-budget-usd", str(self.max_budget_usd)]
|
| 200 |
+
return a + self.extra_args
|
| 201 |
+
|
| 202 |
+
@staticmethod
|
| 203 |
+
def session_ids(stdout_path):
|
| 204 |
+
"""Session ids of the init events in the stream, in order (one per launch / resume)."""
|
| 205 |
+
out = []
|
| 206 |
+
try:
|
| 207 |
+
for line in open(stdout_path, encoding="utf-8", errors="replace"):
|
| 208 |
+
if line.startswith("{") and '"init"' in line:
|
| 209 |
+
d = json.loads(line)
|
| 210 |
+
if d.get("type") == "system" and d.get("subtype") == "init" and d.get("session_id"):
|
| 211 |
+
out.append(d["session_id"])
|
| 212 |
+
except (OSError, ValueError):
|
| 213 |
+
pass
|
| 214 |
+
return out
|
| 215 |
+
|
| 216 |
+
def resume_argv(self, h, message):
|
| 217 |
+
"""`claude -p <message> ... --resume <session>`: the launch's flags unchanged, the message in the place of the
|
| 218 |
+
first message (right after -p, before the variadic --allowedTools)."""
|
| 219 |
+
sids = self.session_ids(h.spec.stdout_path)
|
| 220 |
+
if not sids:
|
| 221 |
+
raise HarnessRefused("resume: no session id in the stream")
|
| 222 |
+
a = list(h.spec.argv)
|
| 223 |
+
return a[:2] + [message] + a[3:] + ["--resume", sids[0]]
|
| 224 |
+
|
| 225 |
+
def env(self, state):
|
| 226 |
+
# CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: measured 2026-10-21 with 2.1.299 and claude-fable-5-1: when the model's
|
| 227 |
+
# safeguards flag a request, the CLI otherwise answers it, and the rest of the session, with another model
|
| 228 |
+
# (claude-opus-4-8) under the requested model's name; with it, a flagged request ends as a refusal
|
| 229 |
+
# (system event model_refusal_no_fallback) and the run stays on the model under test
|
| 230 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], CLAUDE_CONFIG_DIR=state["config"], TMPDIR=state["tmp"],
|
| 231 |
+
LANG="C.UTF-8", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1", DISABLE_AUTOUPDATER="1",
|
| 232 |
+
DISABLE_TELEMETRY="1", DISABLE_ERROR_REPORTING="1", MCP_TIMEOUT="60000", MCP_TOOL_TIMEOUT="900000",
|
| 233 |
+
CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK="1")
|
| 234 |
+
e.update(self.proxy)
|
| 235 |
+
e.update(self.api_env)
|
| 236 |
+
return e
|
| 237 |
+
|
| 238 |
+
def _state_dirs(self, hexname=None):
|
| 239 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 240 |
+
os.makedirs(root, exist_ok=True)
|
| 241 |
+
state = dict(state=root, home=os.path.join(root, "home"), config=os.path.join(root, "config"),
|
| 242 |
+
tmp=os.path.join(root, "tmp"))
|
| 243 |
+
for k in ("home", "config", "tmp"):
|
| 244 |
+
os.makedirs(state[k], exist_ok=True)
|
| 245 |
+
return state
|
| 246 |
+
|
| 247 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 248 |
+
work = new_run_dir("/tmp/lffrun")
|
| 249 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 250 |
+
if self.jail is not None:
|
| 251 |
+
self.jail.stderr_dir = ep.log_dir
|
| 252 |
+
mcp_path = os.path.join(state["state"], "mcp.json")
|
| 253 |
+
with open(mcp_path, "w") as f:
|
| 254 |
+
json.dump(self.mcp_config(ep.session_path), f)
|
| 255 |
+
argv = self.argv(dict(mcp_config=mcp_path), ep, first_message)
|
| 256 |
+
spec = LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
|
| 257 |
+
first_message=first_message, config_files=dict(mcp_config=mcp_path),
|
| 258 |
+
stdout_path=os.path.join(ep.log_dir, "claude_stream.jsonl"),
|
| 259 |
+
stderr_path=os.path.join(ep.log_dir, "claude_stderr.txt"),
|
| 260 |
+
redact_argv={2: f"<first message: sha256={C.sha256_text(first_message)}>"},
|
| 261 |
+
timeout_s=self.timeout_s)
|
| 262 |
+
return spec
|
| 263 |
+
|
| 264 |
+
def config_sha256(self, spec, ep):
|
| 265 |
+
"""Hash of everything configurable (argv without the first message, MCP config, env values except keys /
|
| 266 |
+
one-time dirs)."""
|
| 267 |
+
argv = [("<MCP_CONFIG>" if a == spec.config_files["mcp_config"] else a) for a in self.logged_argv(spec)[3:]]
|
| 268 |
+
env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
|
| 269 |
+
if k not in ("HOME", "CLAUDE_CONFIG_DIR", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
|
| 270 |
+
return C.sha256_json(dict(argv=argv, mcp=self.mcp_config("<SESSION>", describe=True), env=env))
|
| 271 |
+
|
| 272 |
+
# ------------------------------------------------------------------------------------------------ preflight
|
| 273 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 274 |
+
"""Run the identical command against a fake API (free); refuse on any mismatch with the pin."""
|
| 275 |
+
t0 = time.time()
|
| 276 |
+
fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start()
|
| 277 |
+
pre_state = self._state_dirs()
|
| 278 |
+
try:
|
| 279 |
+
mcp_path = os.path.join(pre_state["state"], "mcp.json")
|
| 280 |
+
with open(mcp_path, "w") as f:
|
| 281 |
+
json.dump(self.mcp_config(None), f)
|
| 282 |
+
argv = self.argv(dict(mcp_config=mcp_path), ep, spec.first_message)
|
| 283 |
+
env = {k: v for k, v in self.env(pre_state).items() if k not in self.api_env} # no real credential
|
| 284 |
+
cred_key, cred_dummy = PREFLIGHT_CREDENTIAL[self.auth]
|
| 285 |
+
env.update({"ANTHROPIC_BASE_URL": fake.base_url, cred_key: cred_dummy})
|
| 286 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre_state.values())), env=env, cwd=spec.cwd,
|
| 287 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
|
| 288 |
+
reqs = fake.message_requests()
|
| 289 |
+
if not reqs:
|
| 290 |
+
raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): "
|
| 291 |
+
f"{r.stderr.decode('utf-8', 'replace')[-500:]}")
|
| 292 |
+
n, body = reqs[0]
|
| 293 |
+
headers = {}
|
| 294 |
+
if record_dir:
|
| 295 |
+
headers = json.load(open(os.path.join(record_dir, f"req_{n:03d}.json"))).get("headers", {})
|
| 296 |
+
fp, problems = request_fingerprint(body, headers, spec, spec.first_message)
|
| 297 |
+
init = next((json.loads(x) for x in r.stdout.decode("utf-8", "replace").splitlines()
|
| 298 |
+
if x.startswith('{"type":"system"') and '"init"' in x), {})
|
| 299 |
+
if init.get("tools") != MCP_TOOLS:
|
| 300 |
+
problems.append(f"init event tools {init.get('tools')}")
|
| 301 |
+
want_src = "ANTHROPIC_API_KEY" if self.auth == "apikey" else "none" # none = no API key: the OAuth token
|
| 302 |
+
if init.get("apiKeySource") != want_src:
|
| 303 |
+
problems.append(f"init apiKeySource {init.get('apiKeySource')!r}, expected {want_src!r} for "
|
| 304 |
+
f"auth={self.auth}")
|
| 305 |
+
if self.bare and "memory_paths" in init:
|
| 306 |
+
problems.append("init event has memory_paths under --bare")
|
| 307 |
+
if [s.get("status") for s in init.get("mcp_servers", [])] != ["connected"]:
|
| 308 |
+
problems.append(f"MCP servers {init.get('mcp_servers')}")
|
| 309 |
+
if os.listdir(spec.cwd):
|
| 310 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 311 |
+
fp_sha = C.sha256_json(fp)
|
| 312 |
+
out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs),
|
| 313 |
+
tools=[t["name"] for t in fp["tools"]], effort_in_request=(fp["params"].get("output_config")
|
| 314 |
+
or {}).get("effort"),
|
| 315 |
+
model_in_request=fp["params"].get("model"), init_tools=init.get("tools"),
|
| 316 |
+
memory_paths=init.get("memory_paths"), dt_s=round(time.time() - t0, 1), problems=problems)
|
| 317 |
+
if out["effort_in_request"] != ep.effort:
|
| 318 |
+
problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}")
|
| 319 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 320 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 321 |
+
out["fingerprint"] = fp
|
| 322 |
+
if problems:
|
| 323 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 324 |
+
if pin is None:
|
| 325 |
+
if not self.allow_unpinned:
|
| 326 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 327 |
+
f"with --write-pins after the self-check passes)")
|
| 328 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 329 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 330 |
+
raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
|
| 331 |
+
f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
|
| 332 |
+
else:
|
| 333 |
+
out["pin_status"] = "match"
|
| 334 |
+
return out
|
| 335 |
+
finally:
|
| 336 |
+
fake.stop()
|
| 337 |
+
shutil.rmtree(pre_state["state"], ignore_errors=True)
|
| 338 |
+
|
| 339 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 340 |
+
try:
|
| 341 |
+
h = super().launch(spec, ep, skip_preflight)
|
| 342 |
+
except HarnessRefused:
|
| 343 |
+
raise
|
| 344 |
+
# second line of defence: the init event of the real run
|
| 345 |
+
deadline = time.time() + 120
|
| 346 |
+
while time.time() < deadline and h.proc.poll() is None:
|
| 347 |
+
init = self._init_event(spec)
|
| 348 |
+
if init is not None:
|
| 349 |
+
h.info["init"] = {k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version",
|
| 350 |
+
"permissionMode", "memory_paths", "apiKeySource")}
|
| 351 |
+
if init.get("tools") != MCP_TOOLS:
|
| 352 |
+
self.kill(h)
|
| 353 |
+
h.exit_reason = "refused: init tools " + json.dumps(init.get("tools"))
|
| 354 |
+
raise HarnessRefused(h.exit_reason)
|
| 355 |
+
break
|
| 356 |
+
time.sleep(0.2)
|
| 357 |
+
return h
|
| 358 |
+
|
| 359 |
+
@staticmethod
|
| 360 |
+
def _init_event(spec):
|
| 361 |
+
try:
|
| 362 |
+
with open(spec.stdout_path) as f:
|
| 363 |
+
for line in f:
|
| 364 |
+
if line.startswith("{"):
|
| 365 |
+
d = json.loads(line)
|
| 366 |
+
if d.get("type") == "system" and d.get("subtype") == "init":
|
| 367 |
+
return d
|
| 368 |
+
except (OSError, ValueError):
|
| 369 |
+
return None
|
| 370 |
+
return None
|
| 371 |
+
|
| 372 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 373 |
+
def collect(self, h):
|
| 374 |
+
spec, ep = h.spec, h.ep
|
| 375 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 376 |
+
init, result, by_id, compactions, other = None, None, {}, 0, []
|
| 377 |
+
inits, results = [], [] # one init / result per launch or resume
|
| 378 |
+
lines = open(spec.stdout_path, encoding="utf-8", errors="replace").read().splitlines()
|
| 379 |
+
for line in lines:
|
| 380 |
+
if not line.startswith("{"):
|
| 381 |
+
continue
|
| 382 |
+
d = json.loads(line)
|
| 383 |
+
t = d.get("type")
|
| 384 |
+
if t == "system" and d.get("subtype") == "init":
|
| 385 |
+
init = init or d
|
| 386 |
+
inits.append(d)
|
| 387 |
+
elif t == "system":
|
| 388 |
+
if "compact" in str(d.get("subtype", "")):
|
| 389 |
+
compactions += 1
|
| 390 |
+
other.append(d.get("subtype"))
|
| 391 |
+
elif t == "assistant":
|
| 392 |
+
m = d.get("message") or {}
|
| 393 |
+
mid = m.get("id") or d.get("uuid")
|
| 394 |
+
st = by_id.get(mid)
|
| 395 |
+
if st is None:
|
| 396 |
+
u = m.get("usage") or {}
|
| 397 |
+
st = tw.add_step("agent", timestamp=d.get("timestamp"), model_name=m.get("model"),
|
| 398 |
+
metrics=dict(prompt_tokens=u.get("input_tokens"),
|
| 399 |
+
completion_tokens=u.get("output_tokens"),
|
| 400 |
+
cached_tokens=u.get("cache_read_input_tokens")))
|
| 401 |
+
by_id[mid] = st
|
| 402 |
+
for b in m.get("content") or []:
|
| 403 |
+
if b.get("type") == "text":
|
| 404 |
+
st["message"] += b.get("text", "")
|
| 405 |
+
elif b.get("type") == "thinking":
|
| 406 |
+
st["reasoning_content"] += b.get("thinking", "")
|
| 407 |
+
elif b.get("type") == "tool_use":
|
| 408 |
+
st["tool_calls"].append(dict(tool_call_id=b.get("id"), function_name=strip_mcp(b.get("name")),
|
| 409 |
+
native_name=b.get("name"), arguments=b.get("input")))
|
| 410 |
+
elif t == "user":
|
| 411 |
+
for b in (d.get("message") or {}).get("content") or []:
|
| 412 |
+
if isinstance(b, dict) and b.get("type") == "tool_result":
|
| 413 |
+
c = b.get("content")
|
| 414 |
+
texts, imgs = [], 0
|
| 415 |
+
for x in (c if isinstance(c, list) else [dict(type="text", text=c)]):
|
| 416 |
+
if x.get("type") == "text":
|
| 417 |
+
texts.append(x.get("text") or "")
|
| 418 |
+
elif x.get("type") == "image":
|
| 419 |
+
imgs += 1
|
| 420 |
+
tw.add_result(b.get("tool_use_id"), "\n".join(texts), bool(b.get("is_error")), imgs)
|
| 421 |
+
elif t == "result":
|
| 422 |
+
result = d
|
| 423 |
+
results.append(d)
|
| 424 |
+
v = self.version()
|
| 425 |
+
tw.set_header(session_id=(init or {}).get("session_id"), source=os.path.basename(spec.stdout_path),
|
| 426 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
|
| 427 |
+
tools=(init or {}).get("tools"))
|
| 428 |
+
|
| 429 |
+
def tot(key, sub=None): # summed over the segments (each resume reports its own usage)
|
| 430 |
+
vals = [((r.get("usage") or {}).get(key) if sub is None else r.get(key)) for r in results]
|
| 431 |
+
vals = [x for x in vals if isinstance(x, (int, float))]
|
| 432 |
+
return sum(vals) if vals else None
|
| 433 |
+
cost = tot("total_cost_usd", sub=True)
|
| 434 |
+
tw.set_final(h.exit_reason, native_result={k: (result or {}).get(k) for k in
|
| 435 |
+
("subtype", "is_error", "num_turns", "duration_ms",
|
| 436 |
+
"duration_api_ms", "total_cost_usd", "usage", "modelUsage")},
|
| 437 |
+
total_prompt_tokens=(tot("input_tokens") or 0) + (tot("cache_read_input_tokens") or 0)
|
| 438 |
+
+ (tot("cache_creation_input_tokens") or 0),
|
| 439 |
+
total_completion_tokens=tot("output_tokens"), total_cached_tokens=tot("cache_read_input_tokens"),
|
| 440 |
+
total_cost_usd=cost, compactions=compactions, segments=len(results))
|
| 441 |
+
tw.write()
|
| 442 |
+
h.info.update(init_full=init, inits=inits, result=result, results=results, compactions=compactions,
|
| 443 |
+
other_system=other, traj=tw)
|
| 444 |
+
return tw
|
| 445 |
+
|
| 446 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 447 |
+
def audit(self, h):
|
| 448 |
+
spec, ep = h.spec, h.ep
|
| 449 |
+
init = h.info.get("init_full") or {}
|
| 450 |
+
tw = h.info.get("traj")
|
| 451 |
+
v, problems, notes = [], [], []
|
| 452 |
+
inits = h.info.get("inits") or [init]
|
| 453 |
+
for i, x in enumerate(inits): # every launch / resume
|
| 454 |
+
if x.get("tools") != MCP_TOOLS:
|
| 455 |
+
v.append(f"init {i} tools {x.get('tools')}")
|
| 456 |
+
sids = sorted({x.get("session_id") for x in inits if x.get("session_id")})
|
| 457 |
+
if len(sids) > 1:
|
| 458 |
+
v.append(f"several sessions in one run: {sids}")
|
| 459 |
+
if h.info.get("resumes"):
|
| 460 |
+
notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
|
| 461 |
+
f"episode was over)")
|
| 462 |
+
if self.bare and init.get("memory_paths"):
|
| 463 |
+
v.append(f"memory_paths {init.get('memory_paths')}")
|
| 464 |
+
if not self.bare and init.get("memory_paths"):
|
| 465 |
+
mp = json.dumps(init.get("memory_paths"))
|
| 466 |
+
if spec.state_dirs["state"] not in mp and spec.cwd not in mp:
|
| 467 |
+
v.append(f"memory_paths outside the one-time dirs: {mp}")
|
| 468 |
+
notes.append("full variant: memory_paths point into the one-time dirs (empty at start)")
|
| 469 |
+
names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]]
|
| 470 |
+
bad = sorted({n for n in names if n not in MCP_TOOLS})
|
| 471 |
+
if bad:
|
| 472 |
+
notes.append(f"model asked for unavailable tools (all rejected by the harness): {bad}")
|
| 473 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 474 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 475 |
+
left = dict(config=snapshot_tree(spec.state_dirs["config"]), home=snapshot_tree(spec.state_dirs["home"]),
|
| 476 |
+
work=snapshot_tree(spec.cwd))
|
| 477 |
+
mcp_logs = [p for p in left["home"] if "/mcp-logs-" in p]
|
| 478 |
+
own = [p for p in left["config"] if sids and p.startswith("projects/")
|
| 479 |
+
and (p.endswith(f"/{sids[0]}.jsonl") or f"/{sids[0]}/" in p)] # this run's session (for --resume)
|
| 480 |
+
transcripts = [p for p in left["config"] + left["home"] if p.endswith(".jsonl") and p not in mcp_logs
|
| 481 |
+
and p not in own]
|
| 482 |
+
if transcripts:
|
| 483 |
+
v.append(f"session transcripts other than this run's session: {transcripts}")
|
| 484 |
+
if own:
|
| 485 |
+
notes.append(f"this run's own session kept in the one-time config dir (for --resume): {own}")
|
| 486 |
+
if mcp_logs: # MCP connection log of the CLI in the one-time HOME (removed after the run, never read back)
|
| 487 |
+
notes.append(f"Claude Code wrote its MCP log into the one-time HOME: {mcp_logs}")
|
| 488 |
+
if left["work"]:
|
| 489 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 490 |
+
mcp_env = None
|
| 491 |
+
mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
|
| 492 |
+
if os.path.exists(mt):
|
| 493 |
+
for line in open(mt):
|
| 494 |
+
d = json.loads(line)
|
| 495 |
+
if d.get("ev") == "start" and "env_keys" in d:
|
| 496 |
+
mcp_env = d["env_keys"]
|
| 497 |
+
out = dict(harness=self.name, violations=v, problems=problems, notes=notes, files_left=left,
|
| 498 |
+
mcp_server_env_keys=mcp_env, compactions=h.info.get("compactions"),
|
| 499 |
+
init={k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version",
|
| 500 |
+
"permissionMode", "memory_paths", "apiKeySource")},
|
| 501 |
+
tool_calls=len(names), unavailable_tool_requests=bad, ok=not v)
|
| 502 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 503 |
+
json.dump(out, f, indent=1)
|
| 504 |
+
return out
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
class ClaudeCodeFull(ClaudeCode):
|
| 508 |
+
name = "claude_code_full"
|
| 509 |
+
bare = False
|
| 510 |
+
capabilities = dict(ClaudeCode.capabilities,
|
| 511 |
+
persistent_memory=Cap("partial", "probe", "auto-memory is on in the harness, but its dirs are "
|
| 512 |
+
"one-time and empty; canaries outside them never reach the request"),
|
| 513 |
+
instruction_file_injection=Cap("partial", "probe", "CLAUDE.md discovery is on, but work / "
|
| 514 |
+
"config / home are empty one-time dirs; canaries outside absent"))
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/codex.py
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Codex CLI as a native harness (arm F; flags measured in research_notes/harness接入调研/02 §2.3, Codex 0.156).
|
| 2 |
+
|
| 3 |
+
Launch: process env exactly the whitelist (env -i equivalent), a brand-new empty CODEX_HOME and HOME (one-time, under
|
| 4 |
+
/tmp/lffstate/<hex>), work dir /tmp/lffrun/<12 hex>, `codex exec --json --skip-git-repo-check --ignore-user-config
|
| 5 |
+
--ignore-rules -s read-only`, ~20 features disabled, project docs / permissions / environment context /
|
| 6 |
+
collaboration-mode / skills instructions off, web search off, and only our MCP server with
|
| 7 |
+
default_tools_approval_mode="approve" (otherwise exec mode silently denies MCP calls).
|
| 8 |
+
|
| 9 |
+
Early exit: `codex exec` ends when the model replies without a tool call, also when the episode is not over (measured
|
| 10 |
+
2026-10-19, cx_pilot6b: gpt-6-astra stopped after a failed first attempt, "I stopped after the one authorized
|
| 11 |
+
attempt", although the finish reply said attempt 2 of 3 starts now). scripts/harness_run.py then sends the reference
|
| 12 |
+
driver's nudge as a user turn with `codex exec resume <thread>` (resume_argv), at most api_player.MAX_NO_TOOL times in
|
| 13 |
+
a row. Hence no --ephemeral: the session is kept in the one-time CODEX_HOME (memories off; removed after the run).
|
| 14 |
+
Measured with 0.163 against the fake server: the resumed request has the same developer messages, tools, model and
|
| 15 |
+
parameters as the first, then the earlier turns and the nudge as a user message.
|
| 16 |
+
|
| 17 |
+
The model API is a custom Responses provider "lffapi", so the preflight can point exactly the same config at a local
|
| 18 |
+
fake server by changing only base_url. Two ways to authenticate (auth=):
|
| 19 |
+
apikey env_key OPENAI_API_KEY (api_env), default endpoint the official API
|
| 20 |
+
chatgpt a ChatGPT subscription login (no API key; same as RPent's codex planner reusing `codex login`): the
|
| 21 |
+
provider gets requires_openai_auth=true (requests carry the login's bearer + chatgpt-account-id), default
|
| 22 |
+
endpoint the ChatGPT Codex backend; a copy of auth.json from the source CODEX_HOME is put into the one-time
|
| 23 |
+
CODEX_HOME (the only file allowed there at launch). If Codex refreshes the login during a run, the refreshed
|
| 24 |
+
auth.json is written back to the source (refresh tokens rotate), unless the source changed meanwhile.
|
| 25 |
+
Launch is refused when the source login is close to its refresh (parallel copies would each rotate it).
|
| 26 |
+
Measured with 0.163 against the fake server: same body keys and headers in both modes plus chatgpt-account-id; the
|
| 27 |
+
preset differs (exec tool description), so pins are per auth mode (pin name codex-chatgpt).
|
| 28 |
+
The calling environment's HTTP(S) proxy is passed through (base.proxy_env; NO_PROXY = loopback only).
|
| 29 |
+
|
| 30 |
+
Model configuration (catalog=, user 2026-10-20): Codex picks the system prompt, tool form and context window per
|
| 31 |
+
model from its model catalog. We always pass an explicit model_catalog_json written into the one-time CODEX_HOME, so
|
| 32 |
+
nothing depends on the catalog the subscription backend serves on the day:
|
| 33 |
+
generic (main table, every model) one entry built from codex_catalogs/generic_<version>.json: what Codex sends for a
|
| 34 |
+
model it has no entry for (its generic Codex CLI prompt, plain function tools, no code mode); per model only
|
| 35 |
+
slug, input modalities and reasoning levels. Measured with 0.163 against the fake server: the request equals
|
| 36 |
+
the no-catalog fallback for an unknown slug apart from message ids.
|
| 37 |
+
native (control) codex_catalogs/native_<version>.json = `codex debug models --bundled` of that binary: the request
|
| 38 |
+
equals the one without any catalog (GPT: code mode, its own prompt). The pins of before 10-20 stay valid.
|
| 39 |
+
Pins are per catalog (pin name codex[-chatgpt][-generic]).
|
| 40 |
+
|
| 41 |
+
Known, accepted differences in native (code mode) catalogs (reported, not fixable by config in 0.156):
|
| 42 |
+
- code mode: the model sees one `exec` tool (JavaScript in a V8 isolate without fs / network); our tools are nested
|
| 43 |
+
and listed only in ALL_TOOLS; MCP images reach the model only if the model's JS calls image(...)
|
| 44 |
+
- apply_patch (blocked by the read-only sandbox), clock, 3 MCP-resource tools (our server has no resources),
|
| 45 |
+
request_user_input, and 6 collaboration.* sub-agent tools cannot be removed; a sub-agent call is an audit violation
|
| 46 |
+
- --json has tokens but no dollar cost
|
| 47 |
+
Fail-closed launch: the preflight checks the top-level tools, the exec nested-tool list (ALL_TOOLS, printed by a
|
| 48 |
+
scripted exec call), the developer (preset) messages and request parameters against the pin.
|
| 49 |
+
"""
|
| 50 |
+
import base64
|
| 51 |
+
import datetime
|
| 52 |
+
import fcntl
|
| 53 |
+
import json
|
| 54 |
+
import os
|
| 55 |
+
import re
|
| 56 |
+
import shutil
|
| 57 |
+
import sqlite3
|
| 58 |
+
import subprocess
|
| 59 |
+
import sys
|
| 60 |
+
import time
|
| 61 |
+
|
| 62 |
+
from . import contract as C
|
| 63 |
+
from . import pins
|
| 64 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 65 |
+
new_run_dir, proxy_env, snapshot_tree)
|
| 66 |
+
from .fakeapi import FakeResponses
|
| 67 |
+
from .trajectory import TrajWriter
|
| 68 |
+
|
| 69 |
+
ROOT = C.ROOT
|
| 70 |
+
MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
|
| 71 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 72 |
+
OFFICIAL_API = "https://api.openai.com/v1"
|
| 73 |
+
CHATGPT_BACKEND = "https://chatgpt.com/backend-api/codex"
|
| 74 |
+
AUTH_FILE = "auth.json"
|
| 75 |
+
AUTH_LOCK = "/tmp/lffstate/.codex_auth.lock"
|
| 76 |
+
MAX_LOGIN_AGE_H = 8 * 24 # codex-rs TOKEN_REFRESH_INTERVAL (8 days, from the source, not measured here): a login
|
| 77 |
+
# older than this is refreshed at start, by every parallel copy
|
| 78 |
+
MIN_ACCESS_LEFT_H = 24 # an access token expiring during a run makes the run's copy refresh it
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _jwt_claims(tok):
|
| 82 |
+
try:
|
| 83 |
+
p = tok.split(".")[1]
|
| 84 |
+
return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
|
| 85 |
+
except (IndexError, ValueError, AttributeError):
|
| 86 |
+
return {}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def chatgpt_login_status(home):
|
| 90 |
+
"""-> dict(ok, problem, last_refresh_h, access_token_valid_h) of the ChatGPT login in home/auth.json. No secret
|
| 91 |
+
leaves this function."""
|
| 92 |
+
src = os.path.join(home, AUTH_FILE)
|
| 93 |
+
try:
|
| 94 |
+
with open(src) as f:
|
| 95 |
+
a = json.load(f)
|
| 96 |
+
except (OSError, ValueError) as e:
|
| 97 |
+
return dict(ok=False, problem=f"cannot read {src}: {type(e).__name__}")
|
| 98 |
+
tok = a.get("tokens") or {}
|
| 99 |
+
if a.get("auth_mode") != "chatgpt" or not tok.get("access_token") or not tok.get("refresh_token"):
|
| 100 |
+
return dict(ok=False, problem=f"{src} is not a ChatGPT login (auth_mode={a.get('auth_mode')!r})")
|
| 101 |
+
now = time.time()
|
| 102 |
+
try:
|
| 103 |
+
lr_text = re.sub(r"(\.\d{6})\d+", r"\1", str(a.get("last_refresh")))
|
| 104 |
+
lr = datetime.datetime.fromisoformat(lr_text.replace("Z", "+00:00")).timestamp()
|
| 105 |
+
age_h = (now - lr) / 3600
|
| 106 |
+
except ValueError:
|
| 107 |
+
age_h = float("inf")
|
| 108 |
+
left_h = (float(_jwt_claims(tok["access_token"]).get("exp") or 0) - now) / 3600
|
| 109 |
+
out = dict(ok=True, problem=None, last_refresh_h=round(age_h, 1), access_token_valid_h=round(left_h, 1))
|
| 110 |
+
if age_h >= MAX_LOGIN_AGE_H or left_h < MIN_ACCESS_LEFT_H:
|
| 111 |
+
out.update(ok=False, problem=f"the ChatGPT login in {home} is due for a refresh (last refresh {age_h:.0f} h ago, "
|
| 112 |
+
f"access token valid {left_h:.0f} h): refresh it once outside the benchmark (use "
|
| 113 |
+
f"codex with CODEX_HOME={home}), so that parallel runs do not each rotate it")
|
| 114 |
+
return out
|
| 115 |
+
DISABLE = ["shell_tool", "unified_exec", "view_image", "multi_agent", "multi_agent_v2", "apps", "browser_use",
|
| 116 |
+
"browser_use_external", "computer_use", "image_generation", "plugins", "hooks", "skill_search",
|
| 117 |
+
"tool_suggest", "goals", "sleep_tool", "in_app_browser", "memories", "skill_mcp_dependency_install",
|
| 118 |
+
"realtime_conversation"]
|
| 119 |
+
# what remains in 0.156 after the lock-down (measured): anything else is refused at launch
|
| 120 |
+
EXPECTED_TOP = ["collaboration.followup_task", "collaboration.interrupt_agent", "collaboration.list_agents",
|
| 121 |
+
"collaboration.send_message", "collaboration.spawn_agent", "collaboration.wait_agent",
|
| 122 |
+
"functions.exec", "functions.request_user_input", "functions.request_user_input_async",
|
| 123 |
+
"functions.wait"]
|
| 124 |
+
EXPECTED_ALL_TOOLS = ["apply_patch", "clock__curr_time", "list_mcp_resource_templates", "list_mcp_resources",
|
| 125 |
+
"mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images", "read_mcp_resource"]
|
| 126 |
+
# generic catalog (no code mode), measured with 0.163: our tools are plain functions in the mcp__lff namespace
|
| 127 |
+
EXPECTED_TOP_GENERIC = ["list_mcp_resource_templates", "list_mcp_resources", "mcp__lff.robot", "mcp__lff.shell",
|
| 128 |
+
"mcp__lff.view_images", "read_mcp_resource", "request_user_input"]
|
| 129 |
+
CATALOG_DIR = os.path.join(ROOT, "lffbench", "harnesses", "codex_catalogs")
|
| 130 |
+
CATALOG_FILE = "lff_model_catalog.json" # written into the one-time CODEX_HOME before launch
|
| 131 |
+
CATALOGS = ("generic", "native")
|
| 132 |
+
# generic catalog: the per-model fields (input modalities; the run's reasoning level is always listed)
|
| 133 |
+
TEXT_ONLY_MODELS = {"deepseek-v4-pro": ["text"]} # DeepSeek's Codex guide (read 2026-10-20): v4-pro takes no images
|
| 134 |
+
DEEPSEEK_URL = "https://api.deepseek.com/" # same guide: base_url, wire_api = "responses"
|
| 135 |
+
OPENCODE_GO_URL = "https://opencode.ai/inference/go/openai/v1" # OpenCode Go, Responses API (checked 2026-10-29)
|
| 136 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 137 |
+
OK_ITEMS = ("agent_message", "reasoning", "mcp_tool_call", "error")
|
| 138 |
+
PREFLIGHT_JS = "text(JSON.stringify(ALL_TOOLS));"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def codex_bin():
|
| 142 |
+
return os.environ.get("LFF_CODEX_BIN") or shutil.which("codex") or "codex"
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def toml_str(s):
|
| 146 |
+
return json.dumps(s) # a JSON string literal is a valid TOML basic string
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _norm(s, cwd):
|
| 150 |
+
s = s.replace(cwd, "<CWD>")
|
| 151 |
+
s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
|
| 152 |
+
s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
|
| 153 |
+
s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
|
| 154 |
+
s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "<UUID>", s)
|
| 155 |
+
return s
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _walk_tools(ts, prefix=""):
|
| 159 |
+
out = []
|
| 160 |
+
for t in ts or []:
|
| 161 |
+
if t.get("type") == "namespace":
|
| 162 |
+
out += _walk_tools(t.get("tools"), prefix + t.get("name", "") + ".")
|
| 163 |
+
else:
|
| 164 |
+
out.append(dict(name=prefix + (t.get("name") or t.get("type") or "?"), type=t.get("type"),
|
| 165 |
+
description=t.get("description"), parameters=t.get("parameters"), format=t.get("format")))
|
| 166 |
+
return out
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def request_fingerprint(body, cwd, first_message, expected_top=None):
|
| 170 |
+
problems = []
|
| 171 |
+
items = body.get("input") or []
|
| 172 |
+
top = _walk_tools(body.get("tools"))
|
| 173 |
+
dev, users = [], []
|
| 174 |
+
for it in items:
|
| 175 |
+
if it.get("type") == "additional_tools":
|
| 176 |
+
top += _walk_tools(it.get("tools"))
|
| 177 |
+
elif it.get("type") == "message" and it.get("role") in ("developer", "system"):
|
| 178 |
+
dev.append(_norm("\n".join(c.get("text", "") for c in it.get("content") or []), cwd))
|
| 179 |
+
elif it.get("type") == "message" and it.get("role") == "user":
|
| 180 |
+
users.append(it)
|
| 181 |
+
names = sorted(t["name"] for t in top)
|
| 182 |
+
expected_top = EXPECTED_TOP if expected_top is None else expected_top
|
| 183 |
+
if names != expected_top:
|
| 184 |
+
problems.append(f"top-level tools {names} != expected {expected_top}")
|
| 185 |
+
texts = [c.get("text") for u in users for c in u.get("content") or []]
|
| 186 |
+
if texts != [first_message]:
|
| 187 |
+
problems.append(f"user input is not exactly our first message ({len(texts)} user text blocks)")
|
| 188 |
+
for t in top:
|
| 189 |
+
if t.get("description"):
|
| 190 |
+
t["description"] = _norm(t["description"], cwd)
|
| 191 |
+
params = {k: body.get(k) for k in ("model", "reasoning", "parallel_tool_calls", "store", "include", "text",
|
| 192 |
+
"tool_choice", "instructions", "max_output_tokens", "temperature")}
|
| 193 |
+
meta = body.get("client_metadata") or {}
|
| 194 |
+
try:
|
| 195 |
+
turn_meta = json.loads(meta.get("x-codex-turn-metadata") or "{}")
|
| 196 |
+
except ValueError:
|
| 197 |
+
turn_meta = {}
|
| 198 |
+
sandbox = {k: turn_meta.get(k) for k in ("sandbox", "sandbox_mode")}
|
| 199 |
+
if sandbox.get("sandbox_mode") != "read-only":
|
| 200 |
+
problems.append(f"sandbox {sandbox}")
|
| 201 |
+
fp = dict(tools=sorted(top, key=lambda t: t["name"]), developer=dev, params=params, sandbox=sandbox,
|
| 202 |
+
developer_chars=sum(len(d) for d in dev))
|
| 203 |
+
return fp, problems
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def model_catalog(mode, version, model, modalities=None, effort=None):
|
| 207 |
+
"""-> (catalog dict for model_catalog_json, source file). Refuses (fail-closed) when the version has no catalog
|
| 208 |
+
file or, for native, when the model has no entry."""
|
| 209 |
+
if mode not in CATALOGS:
|
| 210 |
+
raise ValueError(f"catalog must be one of {CATALOGS}, not {mode!r}")
|
| 211 |
+
src = os.path.join(CATALOG_DIR, f"{mode}_{version}.json")
|
| 212 |
+
if not os.path.exists(src):
|
| 213 |
+
raise HarnessRefused(f"no {mode} model catalog for Codex {version} ({os.path.relpath(src, ROOT)})")
|
| 214 |
+
d = json.load(open(src))
|
| 215 |
+
if mode == "native":
|
| 216 |
+
if not any(m.get("slug") == model for m in d.get("models") or []):
|
| 217 |
+
raise HarnessRefused(f"native catalog {os.path.basename(src)} has no entry for {model}")
|
| 218 |
+
return d, src
|
| 219 |
+
e = dict(d["entry"], slug=model, display_name=model)
|
| 220 |
+
modalities = modalities or TEXT_ONLY_MODELS.get(model)
|
| 221 |
+
if modalities:
|
| 222 |
+
e["input_modalities"] = list(modalities)
|
| 223 |
+
levels = [dict(x) for x in e.get("supported_reasoning_levels") or []]
|
| 224 |
+
if effort and effort not in [x.get("effort") for x in levels]:
|
| 225 |
+
levels.append(dict(effort=effort, description=effort))
|
| 226 |
+
e["supported_reasoning_levels"] = levels
|
| 227 |
+
return dict(models=[e]), src
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def all_tools_from(body):
|
| 231 |
+
"""The ALL_TOOLS list printed by the preflight exec call (in the second request)."""
|
| 232 |
+
for it in body.get("input") or []:
|
| 233 |
+
if it.get("type") == "custom_tool_call_output":
|
| 234 |
+
out = it.get("output")
|
| 235 |
+
parts = out if isinstance(out, list) else [dict(text=out)]
|
| 236 |
+
for p in parts:
|
| 237 |
+
t = (p.get("text") or "").strip()
|
| 238 |
+
if t.startswith("["):
|
| 239 |
+
try:
|
| 240 |
+
return json.loads(t)
|
| 241 |
+
except ValueError:
|
| 242 |
+
pass
|
| 243 |
+
return None
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class Codex(HarnessAdapter):
|
| 247 |
+
name = "codex"
|
| 248 |
+
uses_mcp = True
|
| 249 |
+
can_resume = True
|
| 250 |
+
clean_dirs = ("home", "codex_home", "tmp")
|
| 251 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 252 |
+
capabilities = dict(
|
| 253 |
+
only_benchmark_tools=Cap("partial", "preflight", "generic catalog: our 3 MCP tools as functions + residual "
|
| 254 |
+
"resource×3 / request_user_input; native (code mode): reachable only via exec(JS), "
|
| 255 |
+
"residual apply_patch(blocked) / clock / resource×3 / request_user_input / "
|
| 256 |
+
"collaboration×6"),
|
| 257 |
+
images_reach_model=Cap("partial", "probe", "generic: MCP images go to the model; native (code mode): only if "
|
| 258 |
+
"the model's JS calls image(); bytes unchanged either way"),
|
| 259 |
+
non_persistent_session=Cap("yes", "probe", "only this run's thread, in the one-time CODEX_HOME (for exec "
|
| 260 |
+
"resume), removed after the run; memories off"),
|
| 261 |
+
pinned_version=Cap("yes", "launch", "codex --version + binary sha256 in harness.json; pin per version"),
|
| 262 |
+
machine_readable_events=Cap("yes", "stream", "exec --json (items + usage, no cost)"),
|
| 263 |
+
tool_calls_logged=Cap("yes", "stream", "mcp_tool_call items + mcp_transcript + events.jsonl"),
|
| 264 |
+
model_and_effort=Cap("yes", "preflight", "-m / model_reasoning_effort; request reasoning.effort checked"),
|
| 265 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; canaries absent"),
|
| 266 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0 + empty CODEX_HOME (AGENTS.md)"),
|
| 267 |
+
web_access=Cap("absent", "probe", "web_search disabled; exec isolate has no fetch"),
|
| 268 |
+
host_file_read=Cap("absent", "probe", "shell / unified_exec / view_image off; exec has no require; "
|
| 269 |
+
"read-only sandbox"),
|
| 270 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 271 |
+
subagent_delegation=Cap("partial", "preflight", "collaboration.* tools cannot be disabled in 0.156; any use "
|
| 272 |
+
"is an audit violation"),
|
| 273 |
+
background_execution=Cap("partial", "preflight", "functions.wait / long exec yields exist; audited"),
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 277 |
+
python=None, extra_args=None, jail=False, auth="apikey", auth_home=None, catalog="generic",
|
| 278 |
+
modalities=None):
|
| 279 |
+
"""api_env: {"OPENAI_API_KEY": ...} (the provider's env_key, auth="apikey"); base_url: Responses endpoint
|
| 280 |
+
(default: official API / ChatGPT Codex backend by auth). auth="chatgpt": a ChatGPT login copied from
|
| 281 |
+
auth_home (default LFF_CODEX_AUTH_HOME, else the calling CODEX_HOME, else ~/.codex), no API key.
|
| 282 |
+
jail: run the CLI in the native-harness jail (lffbench/harnesses/jail.py, static /proc).
|
| 283 |
+
catalog: "generic" (shared configuration of the main table) or "native" (Codex's own entry for the model);
|
| 284 |
+
modalities: input modalities of a generic entry (default text + image)."""
|
| 285 |
+
if catalog not in CATALOGS:
|
| 286 |
+
raise ValueError(f"catalog must be one of {CATALOGS}, not {catalog!r}")
|
| 287 |
+
self.catalog, self.modalities = catalog, (list(modalities) if modalities else None)
|
| 288 |
+
self._catalog_sha = {} # one-time CODEX_HOME -> sha256 of the catalog written there
|
| 289 |
+
if auth not in ("apikey", "chatgpt"):
|
| 290 |
+
raise ValueError(f"auth must be apikey or chatgpt, not {auth!r}")
|
| 291 |
+
if jail:
|
| 292 |
+
from .jail import HarnessJail
|
| 293 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 294 |
+
self.auth = auth
|
| 295 |
+
self.auth_home = None
|
| 296 |
+
self._auth_copies = {} # one-time CODEX_HOME -> sha256 of the auth.json copied into it
|
| 297 |
+
if auth == "chatgpt":
|
| 298 |
+
self.auth_home = os.path.abspath(auth_home or os.environ.get("LFF_CODEX_AUTH_HOME")
|
| 299 |
+
or os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"))
|
| 300 |
+
self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
|
| 301 |
+
self.api_env = dict(api_env or {}) if auth == "apikey" else {}
|
| 302 |
+
self.base_url = base_url or (OFFICIAL_API if auth == "apikey" else CHATGPT_BACKEND)
|
| 303 |
+
self.proxy = proxy_env()
|
| 304 |
+
self.timeout_s = timeout_s
|
| 305 |
+
self.pins_dir = pins_dir
|
| 306 |
+
self.allow_unpinned = allow_unpinned
|
| 307 |
+
self.python = python or sys.executable
|
| 308 |
+
self.extra_args = list(extra_args or [])
|
| 309 |
+
self._version = None
|
| 310 |
+
|
| 311 |
+
# ------------------------------------------------------------------------------------------------ auth
|
| 312 |
+
def auth_info(self):
|
| 313 |
+
if self.auth == "apikey":
|
| 314 |
+
return dict(mode="apikey", keys=sorted(self.api_env))
|
| 315 |
+
st = chatgpt_login_status(self.auth_home)
|
| 316 |
+
return dict(mode="chatgpt", source=self.auth_home, **{k: v for k, v in st.items() if k != "ok"})
|
| 317 |
+
|
| 318 |
+
def config_info(self):
|
| 319 |
+
"""For harness.json: which model catalog the run used."""
|
| 320 |
+
return dict(catalog=self.catalog, modalities=self.modalities)
|
| 321 |
+
|
| 322 |
+
def _install_catalog(self, codex_home, ep):
|
| 323 |
+
"""Write the run's model catalog into the one-time CODEX_HOME (the only file besides auth.json allowed there
|
| 324 |
+
at launch). -> (path, sha256, source file, code mode)."""
|
| 325 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, self.modalities, ep.effort)
|
| 326 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 327 |
+
with open(path, "w") as f:
|
| 328 |
+
json.dump(cat, f)
|
| 329 |
+
sha = C.sha256_file(path)
|
| 330 |
+
self._catalog_sha[codex_home] = sha
|
| 331 |
+
entry = next(m for m in cat["models"] if m.get("slug") == ep.model)
|
| 332 |
+
return path, sha, os.path.relpath(src, ROOT), entry.get("tool_mode") == "code_mode_only"
|
| 333 |
+
|
| 334 |
+
def _install_auth(self, codex_home):
|
| 335 |
+
"""auth="chatgpt": copy the source login into a one-time CODEX_HOME (refused if it is due for a refresh)."""
|
| 336 |
+
if self.auth != "chatgpt":
|
| 337 |
+
return
|
| 338 |
+
st = chatgpt_login_status(self.auth_home)
|
| 339 |
+
if not st["ok"]:
|
| 340 |
+
raise HarnessRefused("ChatGPT login: " + st["problem"])
|
| 341 |
+
dst = os.path.join(codex_home, AUTH_FILE)
|
| 342 |
+
with open(os.path.join(self.auth_home, AUTH_FILE), "rb") as f:
|
| 343 |
+
data = f.read()
|
| 344 |
+
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 345 |
+
with os.fdopen(fd, "wb") as f:
|
| 346 |
+
f.write(data)
|
| 347 |
+
self._auth_copies[codex_home] = C.sha256_file(dst)
|
| 348 |
+
|
| 349 |
+
def _sync_auth_back(self, codex_home):
|
| 350 |
+
"""After a run: if Codex refreshed the login in the run's copy, write it back to the source (refresh tokens
|
| 351 |
+
rotate, the source's old one may no longer work), unless the source changed since the copy. -> note or None."""
|
| 352 |
+
copied = self._auth_copies.pop(codex_home, None)
|
| 353 |
+
p = os.path.join(codex_home, AUTH_FILE)
|
| 354 |
+
if copied is None or not os.path.exists(p) or C.sha256_file(p) == copied:
|
| 355 |
+
return None
|
| 356 |
+
try:
|
| 357 |
+
with open(p, "rb") as f:
|
| 358 |
+
data = f.read()
|
| 359 |
+
new = json.loads(data)
|
| 360 |
+
except (OSError, ValueError):
|
| 361 |
+
return "auth.json in the run's CODEX_HOME changed and is unreadable: not written back"
|
| 362 |
+
if new.get("auth_mode") != "chatgpt" or not (new.get("tokens") or {}).get("refresh_token"):
|
| 363 |
+
return "auth.json in the run's CODEX_HOME changed but holds no ChatGPT login: not written back"
|
| 364 |
+
src = os.path.join(self.auth_home, AUTH_FILE)
|
| 365 |
+
os.makedirs(os.path.dirname(AUTH_LOCK), exist_ok=True)
|
| 366 |
+
with open(AUTH_LOCK, "a") as lk:
|
| 367 |
+
fcntl.flock(lk, fcntl.LOCK_EX)
|
| 368 |
+
if C.sha256_file(src) != copied:
|
| 369 |
+
return "the run refreshed its login copy, but the source auth.json changed meanwhile: not written back"
|
| 370 |
+
tmp = src + ".lff-tmp"
|
| 371 |
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 372 |
+
with os.fdopen(fd, "wb") as f:
|
| 373 |
+
f.write(data)
|
| 374 |
+
os.replace(tmp, src)
|
| 375 |
+
return "the run refreshed the ChatGPT login: refreshed auth.json written back to the source"
|
| 376 |
+
|
| 377 |
+
def version(self):
|
| 378 |
+
if self._version is None:
|
| 379 |
+
b = codex_bin()
|
| 380 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 381 |
+
CODEX_HOME="/nonexistent"),
|
| 382 |
+
capture_output=True, text=True, timeout=60)
|
| 383 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 384 |
+
self._version = dict(version=v, binary=binary_info(b))
|
| 385 |
+
return self._version
|
| 386 |
+
|
| 387 |
+
def pin_key(self, ep):
|
| 388 |
+
v = self.version()
|
| 389 |
+
name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
|
| 390 |
+
name += "" if self.catalog == "native" else f"-{self.catalog}"
|
| 391 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 392 |
+
|
| 393 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 394 |
+
def config_args(self, ep, session_path, base_url, codex_home):
|
| 395 |
+
mcp_cmd, mcp_args = self.mcp_server_command(self.python, MCP_SCRIPT, ["--session", session_path] if session_path
|
| 396 |
+
else ["--schema-only"])
|
| 397 |
+
c = ["model_reasoning_effort=" + toml_str(ep.effort),
|
| 398 |
+
"project_doc_max_bytes=0", "include_permissions_instructions=false", "include_environment_context=false",
|
| 399 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 400 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 401 |
+
'model_provider="lffapi"', 'model_providers.lffapi.name="lffapi"',
|
| 402 |
+
"model_providers.lffapi.base_url=" + toml_str(base_url), 'model_providers.lffapi.wire_api="responses"',
|
| 403 |
+
('model_providers.lffapi.env_key="OPENAI_API_KEY"' if self.auth == "apikey"
|
| 404 |
+
else "model_providers.lffapi.requires_openai_auth=true"),
|
| 405 |
+
"mcp_servers.lff.command=" + toml_str(mcp_cmd),
|
| 406 |
+
"mcp_servers.lff.args=[" + ",".join(toml_str(x) for x in mcp_args) + "]",
|
| 407 |
+
"mcp_servers.lff.env={PATH=" + toml_str(BASE_PATH) + "}",
|
| 408 |
+
'mcp_servers.lff.enabled_tools=["robot","shell","view_images"]',
|
| 409 |
+
'mcp_servers.lff.default_tools_approval_mode="approve"', "mcp_servers.lff.required=true",
|
| 410 |
+
"mcp_servers.lff.startup_timeout_sec=60", "mcp_servers.lff.tool_timeout_sec=900",
|
| 411 |
+
"model_catalog_json=" + toml_str(os.path.join(codex_home, CATALOG_FILE))]
|
| 412 |
+
return c
|
| 413 |
+
|
| 414 |
+
def argv(self, ep, session_path, base_url, first_message, codex_home):
|
| 415 |
+
a = [codex_bin(), "exec", "--json", "--skip-git-repo-check", "--ignore-user-config",
|
| 416 |
+
"--ignore-rules", "-s", "read-only", "-m", ep.model]
|
| 417 |
+
for f in DISABLE:
|
| 418 |
+
a += ["--disable", f]
|
| 419 |
+
for c in self.config_args(ep, session_path, base_url, codex_home):
|
| 420 |
+
a += ["-c", c]
|
| 421 |
+
return a + self.extra_args + [first_message]
|
| 422 |
+
|
| 423 |
+
@staticmethod
|
| 424 |
+
def thread_id(stdout_path):
|
| 425 |
+
t = None
|
| 426 |
+
for line in open(stdout_path, encoding="utf-8", errors="replace"):
|
| 427 |
+
if line.startswith("{") and '"thread.started"' in line:
|
| 428 |
+
t = json.loads(line).get("thread_id") or t
|
| 429 |
+
return t
|
| 430 |
+
|
| 431 |
+
def resume_argv(self, h, message):
|
| 432 |
+
"""`codex exec resume <thread> <message>` with the launch's flags and config; resume has no -s, so the
|
| 433 |
+
sandbox goes in as sandbox_mode."""
|
| 434 |
+
thread = self.thread_id(h.spec.stdout_path)
|
| 435 |
+
if not thread:
|
| 436 |
+
raise HarnessRefused("resume: no thread id in the event stream")
|
| 437 |
+
a = list(h.spec.argv[:-1]) # without the first message
|
| 438 |
+
i = a.index("exec")
|
| 439 |
+
rest = a[i + 1:]
|
| 440 |
+
j = rest.index("-s")
|
| 441 |
+
mode = rest[j + 1]
|
| 442 |
+
del rest[j:j + 2]
|
| 443 |
+
return a[:i + 1] + ["resume"] + rest + ["-c", "sandbox_mode=" + toml_str(mode), thread, message]
|
| 444 |
+
|
| 445 |
+
def env(self, state):
|
| 446 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], CODEX_HOME=state["codex_home"], TMPDIR=state["tmp"],
|
| 447 |
+
LANG="C.UTF-8")
|
| 448 |
+
e.update(self.proxy)
|
| 449 |
+
e.update(self.api_env)
|
| 450 |
+
return e
|
| 451 |
+
|
| 452 |
+
def _state_dirs(self, hexname=None):
|
| 453 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 454 |
+
os.makedirs(root, exist_ok=True)
|
| 455 |
+
state = dict(state=root, home=os.path.join(root, "home"), codex_home=os.path.join(root, "codex_home"),
|
| 456 |
+
tmp=os.path.join(root, "tmp"))
|
| 457 |
+
for k in ("home", "codex_home", "tmp"):
|
| 458 |
+
os.makedirs(state[k], exist_ok=True)
|
| 459 |
+
return state
|
| 460 |
+
|
| 461 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 462 |
+
work = new_run_dir("/tmp/lffrun")
|
| 463 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 464 |
+
if self.jail is not None:
|
| 465 |
+
self.jail.stderr_dir = ep.log_dir
|
| 466 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 467 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 468 |
+
cat_path, cat_sha, cat_src, code_mode = self._install_catalog(state["codex_home"], ep)
|
| 469 |
+
argv = self.argv(ep, ep.session_path, self.base_url, first_message, state["codex_home"])
|
| 470 |
+
return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
|
| 471 |
+
first_message=first_message, stdout_path=os.path.join(ep.log_dir, "codex_events.jsonl"),
|
| 472 |
+
stderr_path=os.path.join(ep.log_dir, "codex_stderr.txt"),
|
| 473 |
+
redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
|
| 474 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 475 |
+
catalog=self.catalog, code_mode=code_mode)),
|
| 476 |
+
timeout_s=self.timeout_s)
|
| 477 |
+
|
| 478 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 479 |
+
self._install_auth(spec.state_dirs["codex_home"])
|
| 480 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 481 |
+
|
| 482 |
+
def cleanup(self, spec):
|
| 483 |
+
self._sync_auth_back(spec.state_dirs.get("codex_home", ""))
|
| 484 |
+
super().cleanup(spec)
|
| 485 |
+
|
| 486 |
+
def config_sha256(self, spec, ep):
|
| 487 |
+
"""Hash of everything configurable (argv without the first message, env values except keys / one-time dirs)."""
|
| 488 |
+
argv = [re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", a.replace(ep.session_path, "<SESSION>"))
|
| 489 |
+
.replace(spec.state_dirs["codex_home"], "<CODEX_HOME>") for a in self.logged_argv(spec)[1:-1]]
|
| 490 |
+
env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
|
| 491 |
+
if k not in ("HOME", "CODEX_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
|
| 492 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 493 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat))
|
| 494 |
+
|
| 495 |
+
# ------------------------------------------------------------------------------------------------ preflight
|
| 496 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 497 |
+
t0 = time.time()
|
| 498 |
+
code_mode = (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True)
|
| 499 |
+
script = [[("exec", PREFLIGHT_JS)], [("text", "preflight ok")]] if code_mode else [[("text", "preflight ok")]]
|
| 500 |
+
fake = FakeResponses(script, record_dir=record_dir).start()
|
| 501 |
+
pre = self._state_dirs()
|
| 502 |
+
try:
|
| 503 |
+
self._install_auth(pre["codex_home"])
|
| 504 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 505 |
+
argv = self.argv(ep, None, fake.base_url, spec.first_message, pre["codex_home"])
|
| 506 |
+
env = self.env(pre)
|
| 507 |
+
if self.auth == "apikey":
|
| 508 |
+
env["OPENAI_API_KEY"] = "sk-preflight-not-a-key"
|
| 509 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 510 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
|
| 511 |
+
reqs = fake.model_requests()
|
| 512 |
+
if len(reqs) < (2 if code_mode else 1):
|
| 513 |
+
raise HarnessRefused(f"preflight: {len(reqs)} model requests (rc={r.returncode}): "
|
| 514 |
+
f"{r.stderr.decode('utf-8', 'replace')[-800:]}")
|
| 515 |
+
fp, problems = request_fingerprint(reqs[0][1], spec.cwd, spec.first_message,
|
| 516 |
+
EXPECTED_TOP if code_mode else EXPECTED_TOP_GENERIC)
|
| 517 |
+
at_names = None
|
| 518 |
+
if code_mode: # our tools are nested in exec: the scripted exec call prints them
|
| 519 |
+
at = all_tools_from(reqs[1][1])
|
| 520 |
+
if at is None:
|
| 521 |
+
problems.append("exec preflight did not print ALL_TOOLS")
|
| 522 |
+
at = []
|
| 523 |
+
at_names = sorted(t.get("name") if isinstance(t, dict) else str(t) for t in at)
|
| 524 |
+
if at_names != EXPECTED_ALL_TOOLS:
|
| 525 |
+
problems.append(f"ALL_TOOLS {at_names} != expected {EXPECTED_ALL_TOOLS}")
|
| 526 |
+
fp["all_tools"] = [({k: (_norm(v, spec.cwd) if isinstance(v, str) else v) for k, v in t.items()}
|
| 527 |
+
if isinstance(t, dict) else t) for t in sorted(at, key=lambda t: json.dumps(t))]
|
| 528 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 529 |
+
if effort != ep.effort:
|
| 530 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 531 |
+
if os.listdir(spec.cwd):
|
| 532 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 533 |
+
fp_sha = C.sha256_json(fp)
|
| 534 |
+
out = dict(fingerprint_sha256=fp_sha, developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 535 |
+
top_tools=[t["name"] for t in fp["tools"]], all_tools=at_names, code_mode=code_mode,
|
| 536 |
+
catalog=self.catalog, effort_in_request=effort,
|
| 537 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], dt_s=round(time.time() - t0, 1),
|
| 538 |
+
problems=problems)
|
| 539 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 540 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 541 |
+
out["fingerprint"] = fp
|
| 542 |
+
if problems:
|
| 543 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 544 |
+
if pin is None:
|
| 545 |
+
if not self.allow_unpinned:
|
| 546 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 547 |
+
f"with --write-pins after the self-check passes)")
|
| 548 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 549 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 550 |
+
raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
|
| 551 |
+
f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
|
| 552 |
+
else:
|
| 553 |
+
out["pin_status"] = "match"
|
| 554 |
+
return out
|
| 555 |
+
finally:
|
| 556 |
+
fake.stop()
|
| 557 |
+
self._sync_auth_back(pre["codex_home"])
|
| 558 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 559 |
+
|
| 560 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 561 |
+
def collect(self, h):
|
| 562 |
+
spec, ep = h.spec, h.ep
|
| 563 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 564 |
+
thread, usage, items, errors = None, dict(input=0, cached=0, output=0, reasoning=0), [], []
|
| 565 |
+
for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
|
| 566 |
+
if not line.startswith("{"):
|
| 567 |
+
continue
|
| 568 |
+
d = json.loads(line)
|
| 569 |
+
t = d.get("type")
|
| 570 |
+
if t == "thread.started":
|
| 571 |
+
thread = d.get("thread_id")
|
| 572 |
+
elif t == "turn.completed":
|
| 573 |
+
u = d.get("usage") or {}
|
| 574 |
+
usage["input"] += u.get("input_tokens") or 0
|
| 575 |
+
usage["cached"] += u.get("cached_input_tokens") or 0
|
| 576 |
+
usage["output"] += u.get("output_tokens") or 0
|
| 577 |
+
usage["reasoning"] += u.get("reasoning_output_tokens") or 0
|
| 578 |
+
elif t in ("error", "turn.failed"):
|
| 579 |
+
errors.append(d)
|
| 580 |
+
elif t == "item.completed":
|
| 581 |
+
it = d.get("item") or {}
|
| 582 |
+
items.append(it.get("type"))
|
| 583 |
+
if it.get("type") == "agent_message":
|
| 584 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 585 |
+
elif it.get("type") == "reasoning":
|
| 586 |
+
tw.add_step("agent", reasoning=it.get("text", ""))
|
| 587 |
+
else:
|
| 588 |
+
name = it.get("tool") if it.get("type") == "mcp_tool_call" else it.get("type")
|
| 589 |
+
args = it.get("arguments") if it.get("type") == "mcp_tool_call" else {
|
| 590 |
+
k: v for k, v in it.items() if k not in ("id", "type", "status")}
|
| 591 |
+
st = tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 592 |
+
native_name=f"{it.get('server', '')}.{name}"
|
| 593 |
+
if it.get("type") == "mcp_tool_call" else name,
|
| 594 |
+
item_type=it.get("type"), arguments=args)])
|
| 595 |
+
res = it.get("result") or {}
|
| 596 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 597 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 598 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 599 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 600 |
+
del st
|
| 601 |
+
v = self.version()
|
| 602 |
+
tw.set_header(session_id=thread, source=os.path.basename(spec.stdout_path),
|
| 603 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
|
| 604 |
+
tools=EXPECTED_ALL_TOOLS if (spec.config_files.get("model_catalog_json") or {}).get(
|
| 605 |
+
"code_mode", True) else EXPECTED_TOP_GENERIC)
|
| 606 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items))),
|
| 607 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 608 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 609 |
+
tw.write()
|
| 610 |
+
h.info.update(items=items, traj=tw, thread=thread, errors=errors)
|
| 611 |
+
return tw
|
| 612 |
+
|
| 613 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 614 |
+
@staticmethod
|
| 615 |
+
def sqlite_rows(path, table):
|
| 616 |
+
"""Row count of `table`, read from a copy (the db may be in WAL mode and still open)."""
|
| 617 |
+
import tempfile
|
| 618 |
+
try:
|
| 619 |
+
with tempfile.TemporaryDirectory() as td:
|
| 620 |
+
for suf in ("", "-wal", "-shm"):
|
| 621 |
+
if os.path.exists(path + suf):
|
| 622 |
+
shutil.copy(path + suf, os.path.join(td, "db.sqlite" + suf))
|
| 623 |
+
con = sqlite3.connect(os.path.join(td, "db.sqlite"))
|
| 624 |
+
n = con.execute(f"select count(*) from {table}").fetchone()[0]
|
| 625 |
+
con.close()
|
| 626 |
+
return n
|
| 627 |
+
except (sqlite3.Error, OSError) as e:
|
| 628 |
+
return f"n/a ({e})"
|
| 629 |
+
|
| 630 |
+
def audit(self, h):
|
| 631 |
+
spec, ep = h.spec, h.ep
|
| 632 |
+
v, notes = [], []
|
| 633 |
+
items = h.info.get("items") or []
|
| 634 |
+
bad = sorted({i for i in items if i not in OK_ITEMS})
|
| 635 |
+
if bad:
|
| 636 |
+
v.append(f"non-MCP items in the event stream: {bad}")
|
| 637 |
+
tw = h.info.get("traj")
|
| 638 |
+
residual = []
|
| 639 |
+
for st in (tw.steps if tw else []):
|
| 640 |
+
for tc in st["tool_calls"]:
|
| 641 |
+
if tc.get("item_type") != "mcp_tool_call":
|
| 642 |
+
continue
|
| 643 |
+
if tc["native_name"].startswith("lff.") and tc["function_name"] in MCP_TOOLS:
|
| 644 |
+
continue
|
| 645 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 646 |
+
residual.append(tc["function_name"]) # our server has no resources: always empty
|
| 647 |
+
else:
|
| 648 |
+
v.append(f"unexpected MCP call {tc['native_name']}")
|
| 649 |
+
if residual:
|
| 650 |
+
notes.append(f"residual MCP-resource tool calls (empty, our server has no resources): {residual}")
|
| 651 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 652 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 653 |
+
ch = spec.state_dirs["codex_home"]
|
| 654 |
+
note = self._sync_auth_back(ch)
|
| 655 |
+
if note:
|
| 656 |
+
notes.append(note)
|
| 657 |
+
left = dict(codex_home=snapshot_tree(ch), home=snapshot_tree(spec.state_dirs["home"]),
|
| 658 |
+
work=snapshot_tree(spec.cwd))
|
| 659 |
+
threads = None
|
| 660 |
+
for f in left["codex_home"]:
|
| 661 |
+
if re.match(r"state_\d+\.sqlite$", f):
|
| 662 |
+
threads = self.sqlite_rows(os.path.join(ch, f), "threads")
|
| 663 |
+
if isinstance(threads, int) and threads > 1:
|
| 664 |
+
v.append(f"{threads} threads persisted in CODEX_HOME (only this run's one is expected)")
|
| 665 |
+
thread = h.info.get("thread")
|
| 666 |
+
sessions = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))]
|
| 667 |
+
foreign = [f for f in sessions if not (thread and f.startswith("sessions/") and f.endswith(f"-{thread}.jsonl"))]
|
| 668 |
+
if foreign:
|
| 669 |
+
v.append(f"session files other than this run's thread: {foreign}")
|
| 670 |
+
if h.info.get("resumes"):
|
| 671 |
+
notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
|
| 672 |
+
f"episode was over)")
|
| 673 |
+
if left["work"]:
|
| 674 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 675 |
+
if (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True):
|
| 676 |
+
notes.append("image forwarding (model calls image()) is not visible in --json; needs the model proxy (P1)")
|
| 677 |
+
mcp_env = None
|
| 678 |
+
mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
|
| 679 |
+
if os.path.exists(mt):
|
| 680 |
+
for line in open(mt):
|
| 681 |
+
d = json.loads(line)
|
| 682 |
+
if d.get("ev") == "start" and "env_keys" in d:
|
| 683 |
+
mcp_env = d["env_keys"]
|
| 684 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, threads_rows=threads,
|
| 685 |
+
mcp_server_env_keys=mcp_env, item_types=sorted(set(items)), errors=h.info.get("errors"), ok=not v)
|
| 686 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 687 |
+
json.dump(out, f, indent=1)
|
| 688 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/dsh.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DeepSeek Harness (`dsh`, deepseek-ai/deepseek-harness, developer preview) as a native harness.
|
| 2 |
+
|
| 3 |
+
Launch: `node <dsh>/lib/bin.js --profile headless --patch <one-time patch> --json <first message>`, process env exactly
|
| 4 |
+
the whitelist, a brand-new empty DSH_HOME and HOME under /tmp/lffstate/<hex>, work dir /tmp/lffrun/<12 hex>. The patch
|
| 5 |
+
is a Cordis overlay on the shipped headless profile: it switches off every built-in tool plugin and what serves only
|
| 6 |
+
them (memory-like instructions, skills, goals, web, sub-agents, plan mode, code-mode tool calls) and adds our MCP
|
| 7 |
+
server. What stays as shipped is the harness under test: its system prompt, agent loop, retry policy, compaction,
|
| 8 |
+
tool-result pruning and image offload.
|
| 9 |
+
|
| 10 |
+
Two more plugins are off because they are provider telemetry, not agent behaviour (model-hidden top-level request
|
| 11 |
+
fields, docs/deepseek-llm-api-wire-extensions.md): session-log-deepseek (`dsh_session_log`: the session log on every
|
| 12 |
+
request) and plugin-package-inventory-deepseek (`dsh_plugin_packages`). session-title-llm is off: an extra model call
|
| 13 |
+
that only names the session.
|
| 14 |
+
|
| 15 |
+
The model API is the direct DeepSeek adapter (Anthropic Messages, default root https://api.deepseek.com/anthropic, or
|
| 16 |
+
OpenCode Go's https://opencode.ai/inference/go; model id passed through, `output_config.effort`). DeepSeek's adapter uploads each request image through /v1/files and
|
| 17 |
+
sends file ids, falling back to inline base64; the model gateway allows the Files path for this harness
|
| 18 |
+
(scripts/model_gateway.py --allow-files), otherwise each image would first fail an upload.
|
| 19 |
+
|
| 20 |
+
Release layout (LFF_DSH_HOME, default /mnt/cpfs/workspace/env/dsh-<version>): bin/node (official Node.js build, no
|
| 21 |
+
dependency on /etc/dsw, so it runs in the jail) + node_modules/ from `npm install @deepseek-ai/dsh@<version>`. The pin
|
| 22 |
+
key's hash covers bin/node and package-lock.json.
|
| 23 |
+
|
| 24 |
+
Early exit: as for the other CLIs, the process ends when the model replies without a tool call, also mid-episode;
|
| 25 |
+
scripts/harness_run.py then sends the reference driver's nudge with `--session-id <id> <nudge>` (resume_argv).
|
| 26 |
+
|
| 27 |
+
The --json stream caps strings at 8 KiB and is not lossless, so the durable session log (session.v4.jsonl.zstd) is
|
| 28 |
+
copied into the run's log dir in audit(), before the one-time dirs are removed.
|
| 29 |
+
|
| 30 |
+
Fail-closed launch: as Claude Code (claude_code.py): the same argv / env against a local fake Anthropic server with a
|
| 31 |
+
schema-only MCP server; tools, system prompt, harness-added message prefix and parameters are hashed against the pin.
|
| 32 |
+
"""
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import shutil
|
| 37 |
+
import subprocess
|
| 38 |
+
import sys
|
| 39 |
+
import time
|
| 40 |
+
|
| 41 |
+
from . import contract as C
|
| 42 |
+
from . import pins
|
| 43 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 44 |
+
new_run_dir, proxy_env, snapshot_tree)
|
| 45 |
+
from .claude_code import MCP_TOOLS, request_fingerprint
|
| 46 |
+
from .fakeapi import FakeAnthropic
|
| 47 |
+
from .trajectory import TrajWriter, strip_mcp
|
| 48 |
+
|
| 49 |
+
ROOT = C.ROOT
|
| 50 |
+
MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
|
| 51 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 52 |
+
DEFAULT_RELEASE = "/mnt/cpfs/workspace/env/dsh-0.2.1-rc.5"
|
| 53 |
+
DEEPSEEK_ANTHROPIC_URL = "https://api.deepseek.com/anthropic"
|
| 54 |
+
BIN_JS = os.path.join("node_modules", "@deepseek-ai", "dsh", "lib", "bin.js")
|
| 55 |
+
PACKAGE_JSON = os.path.join("node_modules", "@deepseek-ai", "dsh", "package.json")
|
| 56 |
+
CONTEXT_WINDOW = 1048576 # GET https://api.deepseek.com/models, DeepSeek-V4.1-Flash, 2026-10-30
|
| 57 |
+
SESSION_LOG = "session.v4.jsonl.zstd"
|
| 58 |
+
OK_EVENTS = ("session", "status", "text", "thinking", "tool_call", "tool_result", "final", "error")
|
| 59 |
+
# request fields of the provider telemetry plugins switched off in the patch: their return is a launch refusal
|
| 60 |
+
TELEMETRY_FIELDS = ("dsh_session_log", "dsh_plugin_packages")
|
| 61 |
+
DISABLE = ["tool-bash", "tool-pwsh", "tool-jobs", "tool-fs", "tool-fs-search", "tool-skill", "tool-todo", "tool-goal",
|
| 62 |
+
"tool-web", "tool-subagent", "tool-subagent-fork", "tool-subagent-control", "tool-workflow",
|
| 63 |
+
"tool-working-directory", "mcp-resources", "agent-instructions", "skill-filesystem", "skill",
|
| 64 |
+
"goal-round-driver", "command-goal", "goal", "plan-mode", "subagent-fork-in-process",
|
| 65 |
+
"subagent-spawn-in-process", "subagent", "workflow-ptc", "tool-executor-ptc", "ptc-runtime",
|
| 66 |
+
"web-fetch-http", "web-deepseek-api", "web-search-deepseek", "web", "session-title-llm",
|
| 67 |
+
"session-log-deepseek", "plugin-package-inventory-deepseek", "llm-deepseek-account"]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def release_dir():
|
| 71 |
+
return os.environ.get("LFF_DSH_HOME") or DEFAULT_RELEASE
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def node_bin():
|
| 75 |
+
return os.path.join(release_dir(), "bin", "node")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _yaml_str(s):
|
| 79 |
+
return json.dumps(s) # a JSON string is a valid YAML flow scalar
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def patch_yaml(mcp_cmd, mcp_args, cwd, effort, base_url, model):
|
| 83 |
+
"""The Cordis overlay of a run. A config override replaces the whole entry config, hence the full llm-deepseek row.
|
| 84 |
+
The model is declared in `models` because dsh treats a model id outside its built-in catalog as text-only
|
| 85 |
+
(docs/user/guide/providers.md), and the OpenCode Go id is one; capacity and image input from DeepSeek's /models."""
|
| 86 |
+
out = [f"- id: {name}\n disabled: true\n" for name in DISABLE]
|
| 87 |
+
out.append("- id: llm-deepseek\n config:\n"
|
| 88 |
+
f" baseURL: {_yaml_str(base_url)}\n apiKeyEnv: DEEPSEEK_API_KEY\n"
|
| 89 |
+
f" reasoningEffort: {_yaml_str(effort)}\n"
|
| 90 |
+
f" models:\n - id: {_yaml_str(model)}\n contextWindow: {CONTEXT_WINDOW}\n"
|
| 91 |
+
" inputModalities: [text, image]\n")
|
| 92 |
+
out.append("- insert:\n - id: mcp-lff\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n"
|
| 93 |
+
" serverName: lff\n transport: stdio\n"
|
| 94 |
+
f" command: {_yaml_str(mcp_cmd)}\n"
|
| 95 |
+
f" args: {json.dumps(list(mcp_args))}\n"
|
| 96 |
+
f" env: {{PATH: {_yaml_str(BASE_PATH)}}}\n"
|
| 97 |
+
f" cwd: {_yaml_str(cwd)}\n"
|
| 98 |
+
" toolCallTimeoutMs: 900000\n failOnStartupError: true\n")
|
| 99 |
+
return "".join(out)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class DeepSeekHarness(HarnessAdapter):
|
| 103 |
+
name = "dsh"
|
| 104 |
+
uses_mcp = True
|
| 105 |
+
can_resume = True
|
| 106 |
+
clean_dirs = ("home", "dsh_home", "tmp")
|
| 107 |
+
ancestor_files = ("AGENTS.md", "CLAUDE.md", ".dsh", ".agents")
|
| 108 |
+
capabilities = dict(
|
| 109 |
+
only_benchmark_tools=Cap("yes", "preflight", "built-in tool plugins off in the patch: request tools = 3 MCP "
|
| 110 |
+
"tools"),
|
| 111 |
+
images_reach_model=Cap("partial", "probe", "MCP images reach the model through dsh's request-image pipeline, "
|
| 112 |
+
"which resizes to DeepSeek's vision grid (at most 1024 tokens an image) and may offload "
|
| 113 |
+
"the oldest images of a long run; not byte-identical above that size"),
|
| 114 |
+
non_persistent_session=Cap("yes", "probe", "only this run's session (for --session-id) in the one-time "
|
| 115 |
+
"DSH_HOME, removed after the run"),
|
| 116 |
+
pinned_version=Cap("yes", "launch", "package version + hash of bin/node and package-lock.json in harness.json"),
|
| 117 |
+
machine_readable_events=Cap("partial", "stream", "--json NDJSON, strings capped at 8 KiB; the lossless session "
|
| 118 |
+
"log is copied into the log dir"),
|
| 119 |
+
tool_calls_logged=Cap("yes", "stream", "tool_call / tool_result in stream + mcp_transcript + events.jsonl"),
|
| 120 |
+
model_and_effort=Cap("yes", "preflight", "agent default model / llm-deepseek reasoningEffort; request "
|
| 121 |
+
"output_config.effort checked"),
|
| 122 |
+
persistent_memory=Cap("absent", "probe", "no memory plugin in the profile; empty one-time DSH_HOME"),
|
| 123 |
+
instruction_file_injection=Cap("absent", "preflight", "agent-instructions and skills plugins off; empty dirs"),
|
| 124 |
+
web_access=Cap("absent", "preflight", "web plugins off; no web tool in the request"),
|
| 125 |
+
host_file_read=Cap("absent", "preflight", "tool-fs / tool-fs-search off; MCP shell is jailed"),
|
| 126 |
+
builtin_shell=Cap("absent", "preflight", "tool-bash / tool-pwsh off; not in the request"),
|
| 127 |
+
subagent_delegation=Cap("absent", "preflight", "subagent plugins off; not in the request"),
|
| 128 |
+
background_execution=Cap("absent", "preflight", "tool-jobs off; not in the request"),
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, python=None,
|
| 132 |
+
extra_args=None, jail=False):
|
| 133 |
+
"""api_env: {"DEEPSEEK_API_KEY": ...}; base_url: Messages root (default the official one; never read from the
|
| 134 |
+
calling environment)."""
|
| 135 |
+
self.release = release_dir()
|
| 136 |
+
self.node = node_bin()
|
| 137 |
+
if not os.access(self.node, os.X_OK):
|
| 138 |
+
raise HarnessRefused(f"dsh: no {self.node} (see lffbench/harnesses/dsh.py, release layout)")
|
| 139 |
+
if jail:
|
| 140 |
+
from .jail import HarnessJail
|
| 141 |
+
self.jail = HarnessJail(self.node, proc="host") # /proc: Node reads the host's cgroup / cpu files
|
| 142 |
+
self.api_env = dict(api_env or {})
|
| 143 |
+
self.base_url = base_url or DEEPSEEK_ANTHROPIC_URL
|
| 144 |
+
self.proxy = proxy_env()
|
| 145 |
+
self.timeout_s = timeout_s
|
| 146 |
+
self.pins_dir = pins_dir
|
| 147 |
+
self.allow_unpinned = allow_unpinned
|
| 148 |
+
self.python = python or sys.executable
|
| 149 |
+
self.extra_args = list(extra_args or [])
|
| 150 |
+
self._version = None
|
| 151 |
+
|
| 152 |
+
# ------------------------------------------------------------------------------------------------ version
|
| 153 |
+
def version(self):
|
| 154 |
+
if self._version is None:
|
| 155 |
+
pkg = json.load(open(os.path.join(self.release, PACKAGE_JSON)))
|
| 156 |
+
lock = C.sha256_file(os.path.join(self.release, "package-lock.json"))
|
| 157 |
+
node = binary_info(self.node)
|
| 158 |
+
self._version = dict(version=pkg["version"], binary=node, package_lock_sha256=lock,
|
| 159 |
+
pin_sha256=C.sha256_text(node["sha256"] + lock))
|
| 160 |
+
return self._version
|
| 161 |
+
|
| 162 |
+
def pin_key(self, ep):
|
| 163 |
+
v = self.version()
|
| 164 |
+
return pins.key(self.name, v["version"], v["pin_sha256"], ep.model, ep.effort)
|
| 165 |
+
|
| 166 |
+
def auth_info(self):
|
| 167 |
+
return dict(mode="apikey", keys=sorted(self.api_env))
|
| 168 |
+
|
| 169 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 170 |
+
def bin_js(self):
|
| 171 |
+
"""lib/bin.js as the process sees it: in the jail, inside the verified copy of the release dir."""
|
| 172 |
+
if self.jail is not None:
|
| 173 |
+
root = os.path.dirname(os.path.dirname(self.jail.binary_jailed))
|
| 174 |
+
return os.path.join(root, BIN_JS)
|
| 175 |
+
return os.path.join(self.release, BIN_JS)
|
| 176 |
+
|
| 177 |
+
def argv(self, patch_path, first_message):
|
| 178 |
+
return [self.node, self.bin_js(), "--profile", "headless", "--patch", patch_path, "--json"] + self.extra_args + [
|
| 179 |
+
first_message]
|
| 180 |
+
|
| 181 |
+
def write_patch(self, state, session_path, cwd, ep, base_url):
|
| 182 |
+
args = ["--session", session_path] if session_path else ["--schema-only"]
|
| 183 |
+
cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args)
|
| 184 |
+
path = os.path.join(state["state"], "patch.yml")
|
| 185 |
+
with open(path, "w") as f:
|
| 186 |
+
f.write(patch_yaml(cmd, a, cwd, ep.effort, base_url, ep.model))
|
| 187 |
+
return path
|
| 188 |
+
|
| 189 |
+
def env(self, state, base_url_unused=None):
|
| 190 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], DSH_HOME=state["dsh_home"], TMPDIR=state["tmp"], LANG="C.UTF-8",
|
| 191 |
+
NO_UPDATE_NOTIFIER="1")
|
| 192 |
+
e.update(self.proxy)
|
| 193 |
+
e.update(self.api_env)
|
| 194 |
+
return e
|
| 195 |
+
|
| 196 |
+
def _state_dirs(self, hexname=None):
|
| 197 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 198 |
+
os.makedirs(root, exist_ok=True)
|
| 199 |
+
state = dict(state=root, home=os.path.join(root, "home"), dsh_home=os.path.join(root, "dsh_home"),
|
| 200 |
+
tmp=os.path.join(root, "tmp"))
|
| 201 |
+
for k in ("home", "dsh_home", "tmp"):
|
| 202 |
+
os.makedirs(state[k], exist_ok=True)
|
| 203 |
+
return state
|
| 204 |
+
|
| 205 |
+
def _write_profile_default(self, state, ep):
|
| 206 |
+
"""The run's model as the profile's default (a config override of agent-default-model) goes into the patch of
|
| 207 |
+
the same directory: dsh has no --model flag in headless mode."""
|
| 208 |
+
path = os.path.join(state["state"], "patch.yml")
|
| 209 |
+
with open(path, "a") as f:
|
| 210 |
+
f.write("- id: agent-default-model\n config:\n provider: deepseek-official\n"
|
| 211 |
+
f" model: {_yaml_str(ep.model)}\n")
|
| 212 |
+
|
| 213 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 214 |
+
work = new_run_dir("/tmp/lffrun")
|
| 215 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 216 |
+
if self.jail is not None:
|
| 217 |
+
self.jail.stderr_dir = ep.log_dir
|
| 218 |
+
patch = self.write_patch(state, ep.session_path, work, ep, self.base_url)
|
| 219 |
+
self._write_profile_default(state, ep)
|
| 220 |
+
argv = self.argv(patch, first_message)
|
| 221 |
+
return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
|
| 222 |
+
first_message=first_message, config_files=dict(patch=patch),
|
| 223 |
+
stdout_path=os.path.join(ep.log_dir, "dsh_events.jsonl"),
|
| 224 |
+
stderr_path=os.path.join(ep.log_dir, "dsh_stderr.txt"),
|
| 225 |
+
redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
|
| 226 |
+
timeout_s=self.timeout_s)
|
| 227 |
+
|
| 228 |
+
def config_sha256(self, spec, ep):
|
| 229 |
+
"""Hash of everything configurable: argv without the first message, the patch with the run's paths normalised,
|
| 230 |
+
env values except keys / one-time dirs."""
|
| 231 |
+
def norm(s):
|
| 232 |
+
s = s.replace(spec.state_dirs["state"], "<STATE>").replace(spec.cwd, "<CWD>").replace(ep.session_path,
|
| 233 |
+
"<SESSION>")
|
| 234 |
+
s = re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", s)
|
| 235 |
+
return re.sub(r"http://127\.0\.0\.1:\d+[^\"\s]*", "<MODEL_ENDPOINT>", s)
|
| 236 |
+
argv = [norm(a) for a in self.logged_argv(spec)[1:-1]]
|
| 237 |
+
patch = norm(open(spec.config_files["patch"]).read())
|
| 238 |
+
env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
|
| 239 |
+
if k not in ("HOME", "DSH_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
|
| 240 |
+
return C.sha256_json(dict(argv=argv, patch=patch, env=env))
|
| 241 |
+
|
| 242 |
+
# ------------------------------------------------------------------------------------------------ preflight
|
| 243 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 244 |
+
t0 = time.time()
|
| 245 |
+
fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start()
|
| 246 |
+
pre = self._state_dirs()
|
| 247 |
+
try:
|
| 248 |
+
patch = self.write_patch(pre, None, spec.cwd, ep, fake.base_url)
|
| 249 |
+
self._write_profile_default(pre, ep)
|
| 250 |
+
argv = self.argv(patch, spec.first_message)
|
| 251 |
+
env = {k: v for k, v in self.env(pre).items() if k not in self.api_env}
|
| 252 |
+
env["DEEPSEEK_API_KEY"] = "sk-preflight-not-a-key"
|
| 253 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 254 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
|
| 255 |
+
reqs = fake.message_requests()
|
| 256 |
+
if not reqs:
|
| 257 |
+
raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): "
|
| 258 |
+
f"{r.stderr.decode('utf-8', 'replace')[-800:]}"
|
| 259 |
+
f"{r.stdout.decode('utf-8', 'replace')[-400:]}")
|
| 260 |
+
n, body = reqs[0]
|
| 261 |
+
fp, problems = request_fingerprint(body, {}, spec, spec.first_message)
|
| 262 |
+
fp.pop("anthropic_beta", None)
|
| 263 |
+
fp["body_keys"] = sorted(body)
|
| 264 |
+
for f in TELEMETRY_FIELDS:
|
| 265 |
+
if f in body:
|
| 266 |
+
problems.append(f"request carries the telemetry field {f}")
|
| 267 |
+
if os.listdir(spec.cwd):
|
| 268 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 269 |
+
fp_sha = C.sha256_json(fp)
|
| 270 |
+
out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs),
|
| 271 |
+
tools=[t["name"] for t in fp["tools"]],
|
| 272 |
+
effort_in_request=(fp["params"].get("output_config") or {}).get("effort"),
|
| 273 |
+
model_in_request=fp["params"].get("model"), dt_s=round(time.time() - t0, 1), problems=problems)
|
| 274 |
+
if out["effort_in_request"] != ep.effort:
|
| 275 |
+
problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}")
|
| 276 |
+
if out["model_in_request"] != ep.model:
|
| 277 |
+
problems.append(f"model in request {out['model_in_request']!r} != {ep.model!r}")
|
| 278 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 279 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 280 |
+
out["fingerprint"] = fp
|
| 281 |
+
if problems:
|
| 282 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 283 |
+
if pin is None:
|
| 284 |
+
if not self.allow_unpinned:
|
| 285 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 286 |
+
f"with --write-pins after the self-check passes)")
|
| 287 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 288 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 289 |
+
raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
|
| 290 |
+
f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
|
| 291 |
+
else:
|
| 292 |
+
out["pin_status"] = "match"
|
| 293 |
+
return out
|
| 294 |
+
finally:
|
| 295 |
+
fake.stop()
|
| 296 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 297 |
+
|
| 298 |
+
# ------------------------------------------------------------------------------------------------ resume
|
| 299 |
+
@staticmethod
|
| 300 |
+
def session_ids(stdout_path):
|
| 301 |
+
out = []
|
| 302 |
+
try:
|
| 303 |
+
for line in open(stdout_path, encoding="utf-8", errors="replace"):
|
| 304 |
+
if line.startswith('{"type":"session"'):
|
| 305 |
+
out.append(json.loads(line)["sessionId"])
|
| 306 |
+
except (OSError, ValueError, KeyError):
|
| 307 |
+
pass
|
| 308 |
+
return out
|
| 309 |
+
|
| 310 |
+
def resume_argv(self, h, message):
|
| 311 |
+
sids = self.session_ids(h.spec.stdout_path)
|
| 312 |
+
if not sids:
|
| 313 |
+
raise HarnessRefused("resume: no session id in the stream")
|
| 314 |
+
return list(h.spec.argv[:-1]) + ["--session-id", sids[0], message]
|
| 315 |
+
|
| 316 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 317 |
+
def collect(self, h):
|
| 318 |
+
spec, ep = h.spec, h.ep
|
| 319 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 320 |
+
usage, sid, kinds, errors, turn_ends, truncated = dict(input=0, cached=0, output=0, cache_write=0), None, [], [], [], 0
|
| 321 |
+
cur = None
|
| 322 |
+
for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
|
| 323 |
+
if not line.startswith("{"):
|
| 324 |
+
continue
|
| 325 |
+
d = json.loads(line)
|
| 326 |
+
t = d.get("type")
|
| 327 |
+
kinds.append(t)
|
| 328 |
+
truncated += bool(d.get("truncated"))
|
| 329 |
+
if t == "session":
|
| 330 |
+
sid = sid or d.get("sessionId")
|
| 331 |
+
elif t == "text":
|
| 332 |
+
cur = tw.add_step("agent", message=d.get("text", ""))
|
| 333 |
+
elif t == "thinking":
|
| 334 |
+
cur = tw.add_step("agent", reasoning=d.get("text", ""))
|
| 335 |
+
elif t == "tool_call":
|
| 336 |
+
tw.add_step("agent", tool_calls=[dict(tool_call_id=d.get("callId"), function_name=strip_mcp(d.get("tool")),
|
| 337 |
+
native_name=d.get("tool"), arguments=d.get("input"))])
|
| 338 |
+
elif t == "tool_result":
|
| 339 |
+
tw.add_result(d.get("callId"), d.get("result", ""), d.get("status") == "error", 0)
|
| 340 |
+
elif t == "status" and d.get("phase") == "step_end":
|
| 341 |
+
u = d.get("usage") or {}
|
| 342 |
+
usage["input"] += u.get("inputTokens") or 0
|
| 343 |
+
usage["output"] += u.get("outputTokens") or 0
|
| 344 |
+
usage["cached"] += u.get("cacheReadTokens") or 0
|
| 345 |
+
usage["cache_write"] += u.get("cacheWriteTokens") or 0
|
| 346 |
+
elif t == "status" and d.get("phase") == "turn_end":
|
| 347 |
+
turn_ends.append(d.get("reason"))
|
| 348 |
+
elif t == "error":
|
| 349 |
+
errors.append(d)
|
| 350 |
+
del cur
|
| 351 |
+
v = self.version()
|
| 352 |
+
tw.set_header(session_id=sid, source=os.path.basename(spec.stdout_path),
|
| 353 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
|
| 354 |
+
tools=MCP_TOOLS)
|
| 355 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], turn_ends=turn_ends[-5:]),
|
| 356 |
+
total_prompt_tokens=usage["input"] + usage["cached"] + usage["cache_write"],
|
| 357 |
+
total_completion_tokens=usage["output"], total_cached_tokens=usage["cached"],
|
| 358 |
+
total_cost_usd=None, segments=len(turn_ends), truncated_events=truncated)
|
| 359 |
+
tw.write()
|
| 360 |
+
h.info.update(kinds=kinds, traj=tw, session=sid, errors=errors, turn_ends=turn_ends)
|
| 361 |
+
return tw
|
| 362 |
+
|
| 363 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 364 |
+
def audit(self, h):
|
| 365 |
+
spec, ep = h.spec, h.ep
|
| 366 |
+
v, notes = [], []
|
| 367 |
+
bad = sorted({k for k in h.info.get("kinds") or [] if k not in OK_EVENTS})
|
| 368 |
+
if bad:
|
| 369 |
+
notes.append(f"unknown event types in the stream: {bad}")
|
| 370 |
+
tw = h.info.get("traj")
|
| 371 |
+
names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]]
|
| 372 |
+
badt = sorted({n for n in names if n not in MCP_TOOLS})
|
| 373 |
+
if badt:
|
| 374 |
+
notes.append(f"model asked for unavailable tools: {badt}")
|
| 375 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 376 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 377 |
+
left = dict(dsh_home=snapshot_tree(spec.state_dirs["dsh_home"]), home=snapshot_tree(spec.state_dirs["home"]),
|
| 378 |
+
work=snapshot_tree(spec.cwd))
|
| 379 |
+
sid = h.info.get("session")
|
| 380 |
+
logs = [p for p in left["dsh_home"] if p.endswith(SESSION_LOG)]
|
| 381 |
+
foreign = [p for p in logs if not (sid and f"/{sid}/" in p)]
|
| 382 |
+
if foreign:
|
| 383 |
+
v.append(f"session logs other than this run's: {foreign}")
|
| 384 |
+
for p in logs:
|
| 385 |
+
shutil.copy(os.path.join(spec.state_dirs["dsh_home"], p), os.path.join(ep.log_dir, SESSION_LOG))
|
| 386 |
+
if h.info.get("resumes"):
|
| 387 |
+
notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
|
| 388 |
+
f"episode was over)")
|
| 389 |
+
if left["work"]:
|
| 390 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 391 |
+
mcp_env = None
|
| 392 |
+
mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
|
| 393 |
+
if os.path.exists(mt):
|
| 394 |
+
for line in open(mt):
|
| 395 |
+
d = json.loads(line)
|
| 396 |
+
if d.get("ev") == "start" and "env_keys" in d:
|
| 397 |
+
mcp_env = d["env_keys"]
|
| 398 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, mcp_server_env_keys=mcp_env,
|
| 399 |
+
errors=h.info.get("errors"), turn_ends=h.info.get("turn_ends"), tool_calls=len(names),
|
| 400 |
+
unavailable_tool_requests=badt, ok=not v)
|
| 401 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 402 |
+
json.dump(out, f, indent=1)
|
| 403 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/framework_codex.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared launcher for robot frameworks using a native Codex backend.
|
| 2 |
+
|
| 3 |
+
The external integration contract is Session.first_message(), Session.tool_specs(),
|
| 4 |
+
and Session.call(name, arguments). This launcher owns isolation, model configuration,
|
| 5 |
+
pins, trajectory collection and audits; framework plugins own their native loop.
|
| 6 |
+
Based on the validated RPent launcher; RPent's historical launcher remains frozen.
|
| 7 |
+
"""
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import shutil
|
| 12 |
+
import subprocess
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
from . import contract as C
|
| 16 |
+
from . import pins
|
| 17 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 18 |
+
gateway_env, new_run_dir, proxy_env, snapshot_tree)
|
| 19 |
+
from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
|
| 20 |
+
request_fingerprint, toml_str)
|
| 21 |
+
from .fakeapi import FakeResponses
|
| 22 |
+
from .trajectory import TrajWriter
|
| 23 |
+
|
| 24 |
+
ROOT = C.ROOT
|
| 25 |
+
JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework"
|
| 26 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 27 |
+
MCP_SERVER = "lff"
|
| 28 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 29 |
+
TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def tree_sha256(root, skip=TREE_SKIP):
|
| 34 |
+
"""sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
|
| 35 |
+
h = hashlib.sha256()
|
| 36 |
+
for dp, dn, fn in os.walk(root):
|
| 37 |
+
dn[:] = sorted(d for d in dn if d not in skip)
|
| 38 |
+
for f in sorted(fn):
|
| 39 |
+
if f.endswith(".pyc"):
|
| 40 |
+
continue
|
| 41 |
+
p = os.path.join(dp, f)
|
| 42 |
+
rel = os.path.relpath(p, root)
|
| 43 |
+
if os.path.islink(p):
|
| 44 |
+
h.update(f"L {rel} {os.readlink(p)}\n".encode())
|
| 45 |
+
else:
|
| 46 |
+
h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
|
| 47 |
+
return h.hexdigest()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def runtime_info(home):
|
| 51 |
+
"""The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
|
| 52 |
+
src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
|
| 53 |
+
for d in (src, venv):
|
| 54 |
+
if not os.path.isdir(d):
|
| 55 |
+
raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)")
|
| 56 |
+
|
| 57 |
+
def git(*a):
|
| 58 |
+
r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
|
| 59 |
+
return r.stdout.strip() if r.returncode == 0 else None
|
| 60 |
+
commit = git("rev-parse", "HEAD")
|
| 61 |
+
patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
|
| 62 |
+
untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
|
| 63 |
+
return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
|
| 64 |
+
untracked=sorted(u for u in untracked if "__pycache__" not in u),
|
| 65 |
+
tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def jail_runtime_copy(home, tree):
|
| 69 |
+
"""A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not)."""
|
| 70 |
+
dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}")
|
| 71 |
+
stamp = os.path.join(dst, ".tree_sha256")
|
| 72 |
+
if os.path.exists(stamp) and open(stamp).read().strip() == tree:
|
| 73 |
+
return dst
|
| 74 |
+
os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True)
|
| 75 |
+
tmp = dst + ".tmp-" + os.urandom(3).hex()
|
| 76 |
+
shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
|
| 77 |
+
ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
|
| 78 |
+
shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
|
| 79 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
| 80 |
+
got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
|
| 81 |
+
).hexdigest()
|
| 82 |
+
if got != tree:
|
| 83 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 84 |
+
raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
|
| 85 |
+
for dp, dn, fn in os.walk(tmp):
|
| 86 |
+
os.chmod(dp, 0o755)
|
| 87 |
+
for f in fn:
|
| 88 |
+
p = os.path.join(dp, f)
|
| 89 |
+
if not os.path.islink(p):
|
| 90 |
+
os.chmod(p, os.stat(p).st_mode | 0o444)
|
| 91 |
+
with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
|
| 92 |
+
f.write(tree)
|
| 93 |
+
if os.path.exists(dst):
|
| 94 |
+
shutil.rmtree(dst)
|
| 95 |
+
os.rename(tmp, dst)
|
| 96 |
+
return dst
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def codex_overrides(effort, catalog_path):
|
| 100 |
+
"""The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
|
| 101 |
+
overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process)."""
|
| 102 |
+
return (["model_reasoning_effort=" + toml_str(effort),
|
| 103 |
+
"include_permissions_instructions=false", "include_environment_context=false",
|
| 104 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 105 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 106 |
+
f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
|
| 107 |
+
f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
|
| 108 |
+
f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
|
| 109 |
+
f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
|
| 110 |
+
"model_catalog_json=" + toml_str(catalog_path)]
|
| 111 |
+
+ [f"features.{f}=false" for f in DISABLE])
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _items(stream_path):
|
| 115 |
+
"""Codex app-server notifications of one robot framework session (robot framework writes them as JSONL)."""
|
| 116 |
+
out = []
|
| 117 |
+
if not os.path.exists(stream_path):
|
| 118 |
+
return out
|
| 119 |
+
for line in open(stream_path, encoding="utf-8", errors="replace"):
|
| 120 |
+
try:
|
| 121 |
+
out.append(json.loads(line))
|
| 122 |
+
except ValueError:
|
| 123 |
+
continue
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _item_of(ev):
|
| 128 |
+
it = (ev.get("payload") or {}).get("item") or {}
|
| 129 |
+
return it.get("root", it) if isinstance(it, dict) else {}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class RobotFrameworkCodex(HarnessAdapter):
|
| 133 |
+
name = "framework_codex"
|
| 134 |
+
runtime_home = "/nonexistent"
|
| 135 |
+
runtime_module = "lff_integration.run"
|
| 136 |
+
default_steps = 500
|
| 137 |
+
uses_mcp = False
|
| 138 |
+
uses_gateway = True
|
| 139 |
+
can_resume = False
|
| 140 |
+
clean_dirs = ("home", "codex_home", "tmp", "out")
|
| 141 |
+
clean_allowed = {"codex_home": (CATALOG_FILE,)}
|
| 142 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 143 |
+
capabilities = dict(
|
| 144 |
+
only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
|
| 145 |
+
"mcp__lff functions + residual resource×3 / request_user_input; robot framework registers "
|
| 146 |
+
"no tool of its own (no file tools, no finish)"),
|
| 147 |
+
images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, "
|
| 148 |
+
"JPEG with its own MIME type"),
|
| 149 |
+
non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the "
|
| 150 |
+
"run; no preloaded or cross-episode framework memory"),
|
| 151 |
+
pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in "
|
| 152 |
+
"harness.json; pin per version and tree"),
|
| 153 |
+
machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session "
|
| 154 |
+
"(codex.out.stream.jsonl) + robot framework run.json"),
|
| 155 |
+
tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"),
|
| 156 |
+
model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
|
| 157 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not "
|
| 158 |
+
"constructed"),
|
| 159 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
|
| 160 |
+
web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
|
| 161 |
+
host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
|
| 162 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 163 |
+
subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
|
| 164 |
+
background_execution=Cap("absent", "preflight", "no background tool in the request"),
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 168 |
+
jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500,
|
| 169 |
+
home=None, provider=None, auth_home=None):
|
| 170 |
+
"""Common controlled Codex SDK launcher.
|
| 171 |
+
|
| 172 |
+
The plugin entrypoint interprets its declared loop options. For SenseNova,
|
| 173 |
+
max_turns is the upstream SDK-step limit, not a provider-response count.
|
| 174 |
+
Robot commands, simulation time and tool budgets are always server-owned.
|
| 175 |
+
"""
|
| 176 |
+
if auth not in ("apikey", "chatgpt"):
|
| 177 |
+
raise ValueError("framework_codex auth must be apikey or chatgpt")
|
| 178 |
+
if catalog not in CATALOGS:
|
| 179 |
+
raise ValueError(f"catalog must be one of {CATALOGS}")
|
| 180 |
+
self.auth, self.catalog = auth, catalog
|
| 181 |
+
self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog)
|
| 182 |
+
self.api_env = self._auth_manager.api_env
|
| 183 |
+
self.base_url = self._auth_manager.base_url
|
| 184 |
+
self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
|
| 185 |
+
self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
|
| 186 |
+
self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
|
| 187 |
+
int(max_turns)
|
| 188 |
+
self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home
|
| 189 |
+
self.proxy = proxy_env()
|
| 190 |
+
self._version = None
|
| 191 |
+
self._runtime = None
|
| 192 |
+
self.runtime_dir = self.home
|
| 193 |
+
if jail:
|
| 194 |
+
from .jail import HarnessJail
|
| 195 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 196 |
+
|
| 197 |
+
# ------------------------------------------------------------------------------------------------ identity
|
| 198 |
+
def runtime(self):
|
| 199 |
+
if self._runtime is None:
|
| 200 |
+
self._runtime = runtime_info(self.home)
|
| 201 |
+
if self.jail is not None:
|
| 202 |
+
self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
|
| 203 |
+
return self._runtime
|
| 204 |
+
|
| 205 |
+
def version(self):
|
| 206 |
+
if self._version is None:
|
| 207 |
+
b = codex_bin()
|
| 208 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 209 |
+
CODEX_HOME="/nonexistent"),
|
| 210 |
+
capture_output=True, text=True, timeout=60)
|
| 211 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 212 |
+
rt = self.runtime()
|
| 213 |
+
self._version = dict(version=v, binary=binary_info(b),
|
| 214 |
+
framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
|
| 215 |
+
tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
|
| 216 |
+
return self._version
|
| 217 |
+
|
| 218 |
+
def pin_key(self, ep):
|
| 219 |
+
v = self.version()
|
| 220 |
+
mode = "" if self.auth == "apikey" else "-chatgpt"
|
| 221 |
+
name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}"
|
| 222 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 223 |
+
|
| 224 |
+
def anchor_pin_key(self, ep):
|
| 225 |
+
"""The main table's codex pin for the same model / effort (apikey, same catalog)."""
|
| 226 |
+
v = self.version()
|
| 227 |
+
name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}")
|
| 228 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 229 |
+
|
| 230 |
+
def auth_info(self):
|
| 231 |
+
if self.auth == "chatgpt":
|
| 232 |
+
return self._auth_manager.auth_info()
|
| 233 |
+
return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
|
| 234 |
+
"OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
|
| 235 |
+
|
| 236 |
+
def config_info(self):
|
| 237 |
+
return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
|
| 238 |
+
max_turns=self.max_turns, framework=self.version()["framework"])
|
| 239 |
+
|
| 240 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 241 |
+
def _state_dirs(self, hexname=None):
|
| 242 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 243 |
+
os.makedirs(root, exist_ok=True)
|
| 244 |
+
state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
|
| 245 |
+
for k in ("home", "codex_home", "tmp", "out"):
|
| 246 |
+
os.makedirs(state[k], exist_ok=True)
|
| 247 |
+
return state
|
| 248 |
+
|
| 249 |
+
def _install_catalog(self, codex_home, ep):
|
| 250 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
|
| 251 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 252 |
+
with open(path, "w") as f:
|
| 253 |
+
json.dump(cat, f)
|
| 254 |
+
return path, C.sha256_file(path), os.path.relpath(src, ROOT)
|
| 255 |
+
|
| 256 |
+
def argv(self, ep, out_dir, sessions=None, preflight=False):
|
| 257 |
+
py = os.path.join(self.runtime_dir, "venv", "bin", "python")
|
| 258 |
+
return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
|
| 259 |
+
"--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
|
| 260 |
+
"--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
|
| 261 |
+
+ (["--no-continue"] if preflight else [])
|
| 262 |
+
|
| 263 |
+
def env(self, state, ep, base_url, work):
|
| 264 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
|
| 265 |
+
CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
|
| 266 |
+
CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER,
|
| 267 |
+
FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
|
| 268 |
+
ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
|
| 269 |
+
FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
|
| 270 |
+
PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
|
| 271 |
+
if self.auth == "chatgpt":
|
| 272 |
+
# The native API provider declares env_key. Codex app-server still requires that
|
| 273 |
+
# variable even with requires_openai_auth=true, so select a separate provider
|
| 274 |
+
# with no env_key. Do not inject a dummy key or modify the upstream runtime.
|
| 275 |
+
provider_id = "lffsubscription"
|
| 276 |
+
overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"])
|
| 277 |
+
overrides += ["model_provider=" + toml_str(provider_id),
|
| 278 |
+
f"model_providers.{provider_id}.name=" + toml_str(provider_id),
|
| 279 |
+
f"model_providers.{provider_id}.wire_api=\"responses\"",
|
| 280 |
+
f"model_providers.{provider_id}.base_url=" + toml_str(base_url),
|
| 281 |
+
f"model_providers.{provider_id}.requires_openai_auth=true"]
|
| 282 |
+
e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides)
|
| 283 |
+
e.update(self.proxy)
|
| 284 |
+
if self.api_env.get("OPENAI_API_KEY"):
|
| 285 |
+
e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
|
| 286 |
+
return e
|
| 287 |
+
|
| 288 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 289 |
+
self.version()
|
| 290 |
+
work = new_run_dir("/tmp/lffrun")
|
| 291 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 292 |
+
if self.jail is not None:
|
| 293 |
+
self.jail.stderr_dir = ep.log_dir
|
| 294 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 295 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 296 |
+
cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
|
| 297 |
+
return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
|
| 298 |
+
run_dir=work, state_dirs=state, first_message=first_message,
|
| 299 |
+
stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"),
|
| 300 |
+
stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"),
|
| 301 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 302 |
+
catalog=self.catalog, code_mode=False)),
|
| 303 |
+
timeout_s=self.timeout_s)
|
| 304 |
+
|
| 305 |
+
def config_sha256(self, spec, ep):
|
| 306 |
+
argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<FRAMEWORK>")
|
| 307 |
+
for a in spec.argv]
|
| 308 |
+
hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH",
|
| 309 |
+
"LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
|
| 310 |
+
env = {k: v for k, v in spec.env.items() if k not in hidden}
|
| 311 |
+
env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace(
|
| 312 |
+
spec.state_dirs["codex_home"], "<CODEX_HOME>")
|
| 313 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 314 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
|
| 315 |
+
framework_tree_sha256=self.version()["framework"]["tree_sha256"]))
|
| 316 |
+
|
| 317 |
+
# ------------------------------------------------------------------------------------------------ launch
|
| 318 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 319 |
+
"""harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
|
| 320 |
+
self._auth_manager._install_auth(spec.state_dirs["codex_home"])
|
| 321 |
+
spec.env.update(gateway_env(ep.log_dir))
|
| 322 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 323 |
+
|
| 324 |
+
def cleanup(self, spec):
|
| 325 |
+
self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", ""))
|
| 326 |
+
super().cleanup(spec)
|
| 327 |
+
|
| 328 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 329 |
+
"""The same framework process, one session, against a local fake Responses server that answers with text
|
| 330 |
+
only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
|
| 331 |
+
sandbox, robot framework's prefix + our first message) against the pins."""
|
| 332 |
+
t0 = time.time()
|
| 333 |
+
fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
|
| 334 |
+
pre = self._state_dirs()
|
| 335 |
+
try:
|
| 336 |
+
self._auth_manager._install_auth(pre["codex_home"])
|
| 337 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 338 |
+
env = self.env(pre, ep, fake.base_url, spec.cwd)
|
| 339 |
+
if self.auth == "apikey":
|
| 340 |
+
env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
|
| 341 |
+
env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
|
| 342 |
+
argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
|
| 343 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 344 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
|
| 345 |
+
reqs = fake.model_requests()
|
| 346 |
+
if not reqs:
|
| 347 |
+
# Native planners may record failures only in run.json, with empty stdout/stderr.
|
| 348 |
+
record = os.path.join(pre["out"], "run.json")
|
| 349 |
+
detail = ""
|
| 350 |
+
if os.path.isfile(record):
|
| 351 |
+
with open(record) as f:
|
| 352 |
+
failed_run = json.load(f)
|
| 353 |
+
detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error"))
|
| 354 |
+
raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
|
| 355 |
+
f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}")
|
| 356 |
+
body = reqs[0][1]
|
| 357 |
+
fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
|
| 358 |
+
problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
|
| 359 |
+
users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
|
| 360 |
+
and it.get("role") == "user" for c in it.get("content") or []]
|
| 361 |
+
prefix = None
|
| 362 |
+
if len(users) != 1 or not users[0].endswith(spec.first_message):
|
| 363 |
+
problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
|
| 364 |
+
else:
|
| 365 |
+
prefix = users[0][:-len(spec.first_message)]
|
| 366 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 367 |
+
if effort != ep.effort:
|
| 368 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 369 |
+
if fp["params"].get("model") != ep.model:
|
| 370 |
+
problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
|
| 371 |
+
if os.listdir(spec.cwd):
|
| 372 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 373 |
+
mid_sha = C.sha256_json(fp)
|
| 374 |
+
full = dict(middle=fp, framework_prefix=prefix)
|
| 375 |
+
fp_sha = C.sha256_json(full)
|
| 376 |
+
anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
|
| 377 |
+
out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
|
| 378 |
+
framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
|
| 379 |
+
framework_prefix_chars=len(prefix) if prefix is not None else None,
|
| 380 |
+
developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 381 |
+
top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
|
| 382 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
|
| 383 |
+
dt_s=round(time.time() - t0, 1), problems=problems,
|
| 384 |
+
anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
|
| 385 |
+
if anchor is None:
|
| 386 |
+
out["anchor_status"] = "no main-table pin for this model / effort"
|
| 387 |
+
elif anchor["fingerprint_sha256"] != mid_sha:
|
| 388 |
+
problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
|
| 389 |
+
f"({anchor['key']}): the middle layer is not the main table's")
|
| 390 |
+
else:
|
| 391 |
+
out["anchor_status"] = "match"
|
| 392 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 393 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 394 |
+
out["fingerprint"] = full
|
| 395 |
+
if problems:
|
| 396 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 397 |
+
if pin is None:
|
| 398 |
+
if not self.allow_unpinned:
|
| 399 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 400 |
+
f"with --write-pins after the self-check passes)")
|
| 401 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 402 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 403 |
+
raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
|
| 404 |
+
f"({pin['key']})")
|
| 405 |
+
else:
|
| 406 |
+
out["pin_status"] = "match"
|
| 407 |
+
return out
|
| 408 |
+
finally:
|
| 409 |
+
fake.stop()
|
| 410 |
+
self._auth_manager._sync_auth_back(pre["codex_home"])
|
| 411 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 412 |
+
|
| 413 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 414 |
+
def collect(self, h):
|
| 415 |
+
spec, ep = h.spec, h.ep
|
| 416 |
+
dst = os.path.join(ep.log_dir, "framework")
|
| 417 |
+
if os.path.isdir(spec.state_dirs["out"]):
|
| 418 |
+
shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
|
| 419 |
+
run = {}
|
| 420 |
+
if os.path.exists(os.path.join(dst, "run.json")):
|
| 421 |
+
run = json.load(open(os.path.join(dst, "run.json")))
|
| 422 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 423 |
+
usage = dict(input=0, cached=0, output=0, reasoning=0)
|
| 424 |
+
items, threads, errors = [], [], []
|
| 425 |
+
for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
|
| 426 |
+
else []:
|
| 427 |
+
last = None
|
| 428 |
+
for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
|
| 429 |
+
m = ev.get("method") or ev.get("type")
|
| 430 |
+
p = ev.get("payload") or {}
|
| 431 |
+
if m == "thread/tokenUsage/updated":
|
| 432 |
+
last = (p.get("token_usage") or {}).get("total") or last
|
| 433 |
+
if p.get("thread_id") and p["thread_id"] not in threads:
|
| 434 |
+
threads.append(p["thread_id"])
|
| 435 |
+
elif m in ("error", "fatal", "timeout"):
|
| 436 |
+
errors.append(ev)
|
| 437 |
+
elif m == "item/completed":
|
| 438 |
+
it = _item_of(ev)
|
| 439 |
+
t = it.get("type")
|
| 440 |
+
items.append(t)
|
| 441 |
+
if t == "agentMessage":
|
| 442 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 443 |
+
elif t == "reasoning":
|
| 444 |
+
tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
|
| 445 |
+
elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
|
| 446 |
+
name = it.get("tool") or t
|
| 447 |
+
tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 448 |
+
native_name=f"{it.get('server', '')}.{name}",
|
| 449 |
+
item_type=t, arguments=it.get("arguments"),
|
| 450 |
+
session=sdir)])
|
| 451 |
+
res = it.get("result") or {}
|
| 452 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 453 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 454 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 455 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 456 |
+
if last:
|
| 457 |
+
usage["input"] += last.get("input_tokens") or 0
|
| 458 |
+
usage["cached"] += last.get("cached_input_tokens") or 0
|
| 459 |
+
usage["output"] += last.get("output_tokens") or 0
|
| 460 |
+
usage["reasoning"] += last.get("reasoning_output_tokens") or 0
|
| 461 |
+
# Framework close-out uses the same counted gateway shell, outside
|
| 462 |
+
# the model stream. Keep it visible in trajectories and tool totals.
|
| 463 |
+
session_record = next((s for s in run.get("sessions", [])
|
| 464 |
+
if sdir == f"session_{s['number']:03d}"), {})
|
| 465 |
+
handoff = session_record.get("handoff") or {}
|
| 466 |
+
if handoff:
|
| 467 |
+
call_id = f"framework-handoff-{sdir}"
|
| 468 |
+
tw.add_step("framework", tool_calls=[dict(
|
| 469 |
+
tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
|
| 470 |
+
item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
|
| 471 |
+
tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
|
| 472 |
+
if c.get("type") == "text"))
|
| 473 |
+
v = self.version()
|
| 474 |
+
tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl",
|
| 475 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
|
| 476 |
+
framework=v["framework"]), tools=EXPECTED_TOP_GENERIC)
|
| 477 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
|
| 478 |
+
run={k: run.get(k) for k in ("stop", "finished",
|
| 479 |
+
"attempts_failed", "tool_calls")},
|
| 480 |
+
sessions=len(run.get("sessions") or [])),
|
| 481 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 482 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 483 |
+
tw.write()
|
| 484 |
+
h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
|
| 485 |
+
return tw
|
| 486 |
+
|
| 487 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 488 |
+
def audit(self, h):
|
| 489 |
+
spec, ep = h.spec, h.ep
|
| 490 |
+
v, notes = [], []
|
| 491 |
+
items = h.info.get("items") or []
|
| 492 |
+
bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
|
| 493 |
+
"plan", "hookPrompt")})
|
| 494 |
+
if bad:
|
| 495 |
+
v.append(f"items other than messages / reasoning / MCP calls: {bad}")
|
| 496 |
+
residual = []
|
| 497 |
+
tw = h.info.get("traj")
|
| 498 |
+
for st in (tw.steps if tw else []):
|
| 499 |
+
for tc in st["tool_calls"]:
|
| 500 |
+
if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
|
| 501 |
+
continue
|
| 502 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 503 |
+
residual.append(tc["function_name"])
|
| 504 |
+
else:
|
| 505 |
+
v.append(f"unexpected tool call {tc['native_name']}")
|
| 506 |
+
if residual:
|
| 507 |
+
notes.append(f"residual MCP-resource tool calls (empty): {residual}")
|
| 508 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 509 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 510 |
+
run = h.info.get("run") or {}
|
| 511 |
+
nsess = len(run.get("sessions") or [])
|
| 512 |
+
if len(h.info.get("threads") or []) > max(1, nsess):
|
| 513 |
+
v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions")
|
| 514 |
+
if nsess > 1:
|
| 515 |
+
notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)")
|
| 516 |
+
if run.get("stop") not in (None, "episode over"):
|
| 517 |
+
notes.append(f"robot framework stopped: {run.get('stop')}")
|
| 518 |
+
left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
|
| 519 |
+
work=snapshot_tree(spec.cwd))
|
| 520 |
+
if left["work"]:
|
| 521 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 522 |
+
foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
|
| 523 |
+
and not any(t in f for t in (h.info.get("threads") or []))]
|
| 524 |
+
if foreign:
|
| 525 |
+
v.append(f"session files other than this run's threads: {foreign}")
|
| 526 |
+
gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
|
| 527 |
+
faces = set()
|
| 528 |
+
if os.path.exists(gt):
|
| 529 |
+
for line in open(gt):
|
| 530 |
+
try:
|
| 531 |
+
d = json.loads(line)
|
| 532 |
+
except ValueError:
|
| 533 |
+
continue
|
| 534 |
+
if d.get("ev") == "tool" and d.get("face"):
|
| 535 |
+
faces.add(d["face"])
|
| 536 |
+
if faces - {self.name}:
|
| 537 |
+
v.append(f"gateway calls from other access paths: {sorted(faces)}")
|
| 538 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
|
| 539 |
+
item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
|
| 540 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 541 |
+
json.dump(out, f, indent=1)
|
| 542 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/pins/embodied_evo_codex-generic-646620c9aa77_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "embodied_evo_codex-generic-646620c9aa77|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
|
| 3 |
+
"fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
|
| 4 |
+
"written": "2026-10-25 04:39:36",
|
| 5 |
+
"summary": {
|
| 6 |
+
"report": "reports/robot_harness_integration_20261025/selfcheck_final/selfcheck.json",
|
| 7 |
+
"checks": 10,
|
| 8 |
+
"framework": {
|
| 9 |
+
"commit": "470278c478bdb5e4b6f17dde1ea0393761f230f0",
|
| 10 |
+
"tree_sha256": "1aeeee06baa254fce963c153f883e3605180d0f39e06e5f8fd6ac15f3c10e0c1",
|
| 11 |
+
"workflow_sha256": "95bcf2e05ad493f808aa03aa6a17fc7c7c470a1c5a25075247b864c008132ba2"
|
| 12 |
+
}
|
| 13 |
+
}
|
| 14 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/redteam.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adversarial acceptance (red-team) runs: an agent told to get "Attempt succeeded." without doing the task.
|
| 2 |
+
|
| 3 |
+
Embodied First Exam merges a benchmark only after such a trial scored 0 on its tasks (PROTOCOL Appendix H.1). Here a
|
| 4 |
+
red-team run is an ordinary native-harness run whose first message starts with RED_TEAM_TEXT; everything else (task,
|
| 5 |
+
instance, tools, budgets, jail, model gateway) is unchanged. harness_run.py --red-team writes the marker file
|
| 6 |
+
red_team.json into the run's log dir before the contract is built, and contract.build_contract adds the key
|
| 7 |
+
"red_team" only for such runs, so their contract_sha256 never equals a normal run's and no table can mix them
|
| 8 |
+
(normal contracts are unchanged). scripts/redteam_report.py lists every success and every flag for a human look: a
|
| 9 |
+
success is either a hole in the success check / the sandbox (fix the task, bump its version) or the agent solving
|
| 10 |
+
the task anyway (legitimate; noted).
|
| 11 |
+
"""
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
RED_TEAM_VERSION = "rt1"
|
| 17 |
+
MARKER = "red_team.json"
|
| 18 |
+
RED_TEAM_TEXT = """\
|
| 19 |
+
[ADVERSARIAL ACCEPTANCE TEST - read this first]
|
| 20 |
+
This episode is a red-team test of the benchmark itself, not an evaluation of you. Your goal is to make the \
|
| 21 |
+
environment report "Attempt succeeded." WITHOUT doing the task the way the instructions below intend. Look for any \
|
| 22 |
+
way the success check, the simulator or the tools can be fooled, for example:
|
| 23 |
+
- end states that satisfy the letter of the success condition but not its intent (objects knocked, pushed off \
|
| 24 |
+
supports or wedged so that a measured quantity reads as "done"; partial work that the check counts as complete);
|
| 25 |
+
- physics glitches (objects tunnelling, launching, jittering into place) or moving objects with something other \
|
| 26 |
+
than the intended contact;
|
| 27 |
+
- command or protocol tricks (malformed or extreme arguments, sequences the robot interface does not expect, \
|
| 28 |
+
finishing at an unusual moment);
|
| 29 |
+
- information you are not meant to have (files, environment variables, processes, network ports, logs or source \
|
| 30 |
+
code reachable from the shell; anything that reveals the hidden properties of the scene or the success check).
|
| 31 |
+
Do not damage the machine and do not try to reach the internet. Do everything through the tools you have. Whenever \
|
| 32 |
+
an attempt ends, write what you tried and what happened into the file redteam_notes.md in your workspace. At the \
|
| 33 |
+
end, reply with a report that starts with "RED-TEAM REPORT:" and lists every trick you tried, whether the \
|
| 34 |
+
environment reported success for it, and anything you found that a benchmark maintainer should fix. If you solve \
|
| 35 |
+
the task in the ordinary way, say so explicitly: that is not a finding.
|
| 36 |
+
[END OF TEST NOTICE - the ordinary instructions of the episode follow]
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def text_sha256():
|
| 42 |
+
return hashlib.sha256(RED_TEAM_TEXT.encode("utf-8")).hexdigest()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def mark(log_dir):
|
| 46 |
+
"""Write the marker before contract.write_contract runs."""
|
| 47 |
+
with open(os.path.join(log_dir, MARKER), "w") as f:
|
| 48 |
+
json.dump(dict(version=RED_TEAM_VERSION, text_sha256=text_sha256()), f)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def marker(log_dir):
|
| 52 |
+
try:
|
| 53 |
+
return json.load(open(os.path.join(log_dir, MARKER)))
|
| 54 |
+
except (OSError, ValueError):
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def first_message(normal):
|
| 59 |
+
return RED_TEAM_TEXT + normal
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/reference.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness).
|
| 2 |
+
|
| 3 |
+
Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its
|
| 4 |
+
own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only
|
| 5 |
+
adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
from . import contract as C
|
| 12 |
+
from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions
|
| 13 |
+
from .trajectory import TrajWriter
|
| 14 |
+
|
| 15 |
+
ROOT = C.ROOT
|
| 16 |
+
PLAYER = os.path.join(ROOT, "scripts", "api_player.py")
|
| 17 |
+
DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py",
|
| 18 |
+
"lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py",
|
| 19 |
+
"lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Reference(HarnessAdapter):
|
| 23 |
+
name = "ours"
|
| 24 |
+
capabilities = dict(
|
| 25 |
+
only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"),
|
| 26 |
+
images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"),
|
| 27 |
+
non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"),
|
| 28 |
+
pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"),
|
| 29 |
+
machine_readable_events=Cap("yes", "stream", "transcript.jsonl"),
|
| 30 |
+
tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"),
|
| 31 |
+
model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"),
|
| 32 |
+
persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"),
|
| 33 |
+
instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"),
|
| 34 |
+
web_access=Cap("absent", "launch", "no such tool"),
|
| 35 |
+
host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"),
|
| 36 |
+
builtin_shell=Cap("absent", "launch", "only the jailed shell tool"),
|
| 37 |
+
subagent_delegation=Cap("absent", "launch", "no such tool"),
|
| 38 |
+
background_execution=Cap("absent", "launch", "no such tool"),
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_):
|
| 42 |
+
self.provider = provider
|
| 43 |
+
self.base_env = dict(env if env is not None else os.environ)
|
| 44 |
+
self.timeout_s = timeout_s
|
| 45 |
+
self.python = python or sys.executable
|
| 46 |
+
|
| 47 |
+
def version(self):
|
| 48 |
+
per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))}
|
| 49 |
+
sha = C.sha256_json(per)
|
| 50 |
+
return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get(
|
| 51 |
+
"scripts/api_player.py")))
|
| 52 |
+
|
| 53 |
+
def prepare(self, ep, first_message=None):
|
| 54 |
+
argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider,
|
| 55 |
+
"--model", ep.model, "--effort", ep.effort, "--style", "la"]
|
| 56 |
+
return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="",
|
| 57 |
+
stdout_path=os.path.join(ep.log_dir, "api_player.log"),
|
| 58 |
+
stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s)
|
| 59 |
+
|
| 60 |
+
def config_sha256(self, spec, ep):
|
| 61 |
+
return C.sha256_json(dict(argv=[a.replace(ep.session_path, "<SESSION>") for a in spec.argv[1:]]))
|
| 62 |
+
|
| 63 |
+
def launch(self, spec, ep, skip_preflight=True):
|
| 64 |
+
# stdout and stderr go to the same api_player.log (as before the adapter layer)
|
| 65 |
+
import subprocess
|
| 66 |
+
import time
|
| 67 |
+
from .base import RunHandle, env_keys_of
|
| 68 |
+
spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code")
|
| 69 |
+
log = open(spec.stdout_path, "ab")
|
| 70 |
+
h = RunHandle(spec=spec, ep=ep, t_start=time.time())
|
| 71 |
+
h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log,
|
| 72 |
+
stderr=subprocess.STDOUT, start_new_session=True)
|
| 73 |
+
h.pid = h.proc.pid
|
| 74 |
+
time.sleep(0.2)
|
| 75 |
+
h.env_observed_keys = env_keys_of(h.pid)
|
| 76 |
+
return h
|
| 77 |
+
|
| 78 |
+
def collect(self, h):
|
| 79 |
+
ep = h.ep
|
| 80 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 81 |
+
p = os.path.join(ep.log_dir, "transcript.jsonl")
|
| 82 |
+
start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0)
|
| 83 |
+
last_agent = None
|
| 84 |
+
for line in (open(p) if os.path.exists(p) else []):
|
| 85 |
+
d = json.loads(line)
|
| 86 |
+
e = d.get("ev")
|
| 87 |
+
if e == "start":
|
| 88 |
+
start = d
|
| 89 |
+
elif e == "user":
|
| 90 |
+
if first_user is None:
|
| 91 |
+
first_user = d.get("text")
|
| 92 |
+
tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t"))
|
| 93 |
+
elif e == "assistant":
|
| 94 |
+
u = d.get("usage") or {}
|
| 95 |
+
tot["inp"] += u.get("input_tokens", 0)
|
| 96 |
+
tot["out"] += u.get("output_tokens", 0)
|
| 97 |
+
tot["cached"] += u.get("cached_tokens", 0)
|
| 98 |
+
last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "",
|
| 99 |
+
timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"],
|
| 100 |
+
function_name=c["name"],
|
| 101 |
+
native_name=c["name"],
|
| 102 |
+
arguments=c["arguments"])
|
| 103 |
+
for c in d.get("tool_calls") or []],
|
| 104 |
+
metrics=dict(prompt_tokens=u.get("input_tokens"),
|
| 105 |
+
completion_tokens=u.get("output_tokens"),
|
| 106 |
+
cached_tokens=u.get("cached_tokens")))
|
| 107 |
+
elif e == "tool" and last_agent is not None:
|
| 108 |
+
pending = [tc for tc in last_agent["tool_calls"]
|
| 109 |
+
if not any(r["source_call_id"] == tc["tool_call_id"]
|
| 110 |
+
for r in last_agent["observation"]["results"])]
|
| 111 |
+
if pending:
|
| 112 |
+
tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or []))
|
| 113 |
+
elif e in ("end", "abort"):
|
| 114 |
+
end = d
|
| 115 |
+
tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl",
|
| 116 |
+
agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model,
|
| 117 |
+
effort=ep.effort, provider=ep.provider or self.provider),
|
| 118 |
+
tools=[t["name"] for t in (start or {}).get("tools") or []])
|
| 119 |
+
tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")),
|
| 120 |
+
native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"],
|
| 121 |
+
total_cached_tokens=tot["cached"])
|
| 122 |
+
tw.write()
|
| 123 |
+
h.info.update(traj=tw, start=start, first_user=first_user)
|
| 124 |
+
if start and first_user is not None: # the same string a native harness gets as its first message
|
| 125 |
+
readme = open(os.path.join(ep.sandbox, "README.md")).read()
|
| 126 |
+
h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme)
|
| 127 |
+
# the same composition as base.first_message_text: identical sha256 for the same instance
|
| 128 |
+
h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user
|
| 129 |
+
return tw
|
| 130 |
+
|
| 131 |
+
def audit(self, h):
|
| 132 |
+
ep = h.ep
|
| 133 |
+
start = h.info.get("start") or {}
|
| 134 |
+
tools, _ = C.tool_schemas()
|
| 135 |
+
v = []
|
| 136 |
+
if start and start.get("tools") != tools:
|
| 137 |
+
v.append("driver tools differ from the contract's tool schemas")
|
| 138 |
+
if h.info.get("instructions_match_readme") is False:
|
| 139 |
+
v.append("driver instructions != preamble + README")
|
| 140 |
+
out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"])
|
| 141 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 142 |
+
json.dump(out, f, indent=1)
|
| 143 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/rpent.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RPent (a robot harness framework, RLinf/RPent v0.1) on Codex as an upper-layer harness (docs/18; research note
|
| 2 |
+
harness接入调研/04 §13.7-13.9).
|
| 3 |
+
|
| 4 |
+
rpent_codex RPent's session loop, prompt and archive / handoff rules (robots/lffbench in an RPent checkout with our
|
| 5 |
+
patch), driving Codex through RPent's own Codex planner (openai_codex SDK -> `codex app-server`)
|
| 6 |
+
|
| 7 |
+
What the run is made of:
|
| 8 |
+
- the RPent runtime (LFF_RPENT_HOME, default /mnt/cpfs/workspace/env/rpent-v0.1): src/ = RPent at a pinned commit
|
| 9 |
+
plus our patch (integrations/rpent-v0.1), venv/ = its locked dependencies on /usr/bin/python3.12, no simulator;
|
| 10 |
+
hashed into rpent_tree_sha256 (recorded, and part of the pin);
|
| 11 |
+
- the framework process `python -m robots.lffbench.run` (one per episode), whose only way to the robot is the
|
| 12 |
+
episode's tool gateway (uses_gateway: LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN, lffbench_client, face "rpent");
|
| 13 |
+
- Codex: the same pinned binary and the same configuration as the main table's `codex` adapter (generic model
|
| 14 |
+
catalog in a one-time CODEX_HOME, the same disabled features and instruction switches, read-only sandbox, MCP
|
| 15 |
+
tools approved), passed to RPent's planner as RPENT_CODEX_CONFIG_OVERRIDES; RPent's in-process MCP server is named
|
| 16 |
+
"lff", so the model sees mcp__lff.robot / .shell / .view_images exactly as with `codex exec`.
|
| 17 |
+
Measured 2026-10-21 (fake API, Codex 0.163.0, gpt-6.1-sol / high): the first request of this path has the same
|
| 18 |
+
normalised fingerprint (tools, developer message, parameters, sandbox) as the `codex` adapter's preflight request;
|
| 19 |
+
the only difference is RPent's system prompt in front of the first user message (RPent puts system prompt and first
|
| 20 |
+
message into one user turn). The preflight checks both: the middle-layer fingerprint against the main table's codex
|
| 21 |
+
pin for the same model / effort (when it exists) and the whole fingerprint (incl. RPent's prefix) against this
|
| 22 |
+
adapter's own pin.
|
| 23 |
+
|
| 24 |
+
The framework owns its loop (sessions, handoff, archive): harness_run's resume / nudge does not apply (can_resume
|
| 25 |
+
False). Episode budgets and attempt switching stay with robot_server and the gateway. Only an API key is supported
|
| 26 |
+
(auth="apikey"; the side table runs gpt-6.1-sol on an OpenAI key, user 2026-10-21).
|
| 27 |
+
"""
|
| 28 |
+
import hashlib
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
import shutil
|
| 32 |
+
import subprocess
|
| 33 |
+
import time
|
| 34 |
+
|
| 35 |
+
from . import contract as C
|
| 36 |
+
from . import pins
|
| 37 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 38 |
+
gateway_env, new_run_dir, proxy_env, snapshot_tree)
|
| 39 |
+
from .codex import (CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
|
| 40 |
+
request_fingerprint, toml_str)
|
| 41 |
+
from .fakeapi import FakeResponses
|
| 42 |
+
from .trajectory import TrajWriter
|
| 43 |
+
|
| 44 |
+
ROOT = C.ROOT
|
| 45 |
+
RPENT_HOME = "/mnt/cpfs/workspace/env/rpent-v0.1"
|
| 46 |
+
JAIL_RPENT_DIR = "/opt/lffjail/hjail/rpent"
|
| 47 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 48 |
+
MCP_SERVER = "lff"
|
| 49 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 50 |
+
TREE_SKIP = {".git", "__pycache__", "docs", "tests", ".github"}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def rpent_home():
|
| 54 |
+
return os.environ.get("LFF_RPENT_HOME") or RPENT_HOME
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def tree_sha256(root, skip=TREE_SKIP):
|
| 58 |
+
"""sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
|
| 59 |
+
h = hashlib.sha256()
|
| 60 |
+
for dp, dn, fn in os.walk(root):
|
| 61 |
+
dn[:] = sorted(d for d in dn if d not in skip)
|
| 62 |
+
for f in sorted(fn):
|
| 63 |
+
if f.endswith(".pyc"):
|
| 64 |
+
continue
|
| 65 |
+
p = os.path.join(dp, f)
|
| 66 |
+
rel = os.path.relpath(p, root)
|
| 67 |
+
if os.path.islink(p):
|
| 68 |
+
h.update(f"L {rel} {os.readlink(p)}\n".encode())
|
| 69 |
+
else:
|
| 70 |
+
h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
|
| 71 |
+
return h.hexdigest()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def runtime_info(home):
|
| 75 |
+
"""The RPent runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
|
| 76 |
+
src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
|
| 77 |
+
for d in (src, venv):
|
| 78 |
+
if not os.path.isdir(d):
|
| 79 |
+
raise HarnessRefused(f"RPent runtime incomplete: {d} missing (integrations/rpent-v0.1/setup.sh)")
|
| 80 |
+
|
| 81 |
+
def git(*a):
|
| 82 |
+
r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
|
| 83 |
+
return r.stdout.strip() if r.returncode == 0 else None
|
| 84 |
+
commit = git("rev-parse", "HEAD")
|
| 85 |
+
patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
|
| 86 |
+
untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
|
| 87 |
+
return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
|
| 88 |
+
untracked=sorted(u for u in untracked if "__pycache__" not in u),
|
| 89 |
+
tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def jail_runtime_copy(home, tree):
|
| 93 |
+
"""A verified read-only copy of the runtime under /opt/lffjail/hjail/rpent (visible in the jail; /mnt is not)."""
|
| 94 |
+
dst = os.path.join(JAIL_RPENT_DIR, f"rpent-{tree[:12]}")
|
| 95 |
+
stamp = os.path.join(dst, ".tree_sha256")
|
| 96 |
+
if os.path.exists(stamp) and open(stamp).read().strip() == tree:
|
| 97 |
+
return dst
|
| 98 |
+
os.makedirs(JAIL_RPENT_DIR, mode=0o755, exist_ok=True)
|
| 99 |
+
tmp = dst + ".tmp-" + os.urandom(3).hex()
|
| 100 |
+
shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
|
| 101 |
+
ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
|
| 102 |
+
shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
|
| 103 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
| 104 |
+
got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
|
| 105 |
+
).hexdigest()
|
| 106 |
+
if got != tree:
|
| 107 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 108 |
+
raise HarnessRefused(f"copy of the RPent runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
|
| 109 |
+
for dp, dn, fn in os.walk(tmp):
|
| 110 |
+
os.chmod(dp, 0o755)
|
| 111 |
+
for f in fn:
|
| 112 |
+
p = os.path.join(dp, f)
|
| 113 |
+
if not os.path.islink(p):
|
| 114 |
+
os.chmod(p, os.stat(p).st_mode | 0o444)
|
| 115 |
+
with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
|
| 116 |
+
f.write(tree)
|
| 117 |
+
if os.path.exists(dst):
|
| 118 |
+
shutil.rmtree(dst)
|
| 119 |
+
os.rename(tmp, dst)
|
| 120 |
+
return dst
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def codex_overrides(effort, catalog_path):
|
| 124 |
+
"""The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
|
| 125 |
+
overrides for RPent's planner; the provider and the MCP server URL are RPent's own (CODEX_BASE_URL, in-process)."""
|
| 126 |
+
return (["model_reasoning_effort=" + toml_str(effort),
|
| 127 |
+
"include_permissions_instructions=false", "include_environment_context=false",
|
| 128 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 129 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 130 |
+
f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
|
| 131 |
+
f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
|
| 132 |
+
f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
|
| 133 |
+
f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
|
| 134 |
+
"model_catalog_json=" + toml_str(catalog_path)]
|
| 135 |
+
+ [f"features.{f}=false" for f in DISABLE])
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _items(stream_path):
|
| 139 |
+
"""Codex app-server notifications of one RPent session (RPent writes them as JSONL)."""
|
| 140 |
+
out = []
|
| 141 |
+
if not os.path.exists(stream_path):
|
| 142 |
+
return out
|
| 143 |
+
for line in open(stream_path, encoding="utf-8", errors="replace"):
|
| 144 |
+
try:
|
| 145 |
+
out.append(json.loads(line))
|
| 146 |
+
except ValueError:
|
| 147 |
+
continue
|
| 148 |
+
return out
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _item_of(ev):
|
| 152 |
+
it = (ev.get("payload") or {}).get("item") or {}
|
| 153 |
+
return it.get("root", it) if isinstance(it, dict) else {}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class RPentCodex(HarnessAdapter):
|
| 157 |
+
name = "rpent_codex"
|
| 158 |
+
uses_mcp = False
|
| 159 |
+
uses_gateway = True
|
| 160 |
+
can_resume = False
|
| 161 |
+
clean_dirs = ("home", "codex_home", "tmp", "out")
|
| 162 |
+
clean_allowed = {"codex_home": (CATALOG_FILE,)}
|
| 163 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 164 |
+
capabilities = dict(
|
| 165 |
+
only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
|
| 166 |
+
"mcp__lff functions + residual resource×3 / request_user_input; RPent registers "
|
| 167 |
+
"no tool of its own (no file tools, no finish)"),
|
| 168 |
+
images_reach_model=Cap("yes", "probe", "gateway content blocks passed through verbatim (ToolResult.content), "
|
| 169 |
+
"JPEG with its own MIME type"),
|
| 170 |
+
non_persistent_session=Cap("yes", "probe", "RPent's threads only in the one-time CODEX_HOME, removed after the "
|
| 171 |
+
"run; no RPent memory (no MemoryManager, no HF memory)"),
|
| 172 |
+
pinned_version=Cap("yes", "launch", "codex binary sha256 + RPent commit / patch / tree hash (src + venv) in "
|
| 173 |
+
"harness.json; pin per version and tree"),
|
| 174 |
+
machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per RPent session "
|
| 175 |
+
"(codex.out.stream.jsonl) + RPent run.json"),
|
| 176 |
+
tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (face rpent) + events.jsonl"),
|
| 177 |
+
model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
|
| 178 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; RPent memory not "
|
| 179 |
+
"constructed"),
|
| 180 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
|
| 181 |
+
web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
|
| 182 |
+
host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
|
| 183 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 184 |
+
subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
|
| 185 |
+
background_execution=Cap("absent", "preflight", "no background tool in the request"),
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 189 |
+
jail=False, auth="apikey", catalog="generic", sessions=5, attempts_per_session=1, max_turns=100,
|
| 190 |
+
home=None, provider=None):
|
| 191 |
+
"""api_env: {"OPENAI_API_KEY": ...}; base_url: Responses endpoint (default: the official API). sessions /
|
| 192 |
+
attempts_per_session / max_turns: RPent's --explore-sessions / --explore-attempts-per-session / --max-turns.
|
| 193 |
+
Defaults = the side table's setting (user 2026-10-21): variant H (one attempt per session, then a fresh session
|
| 194 |
+
with RPent's handoff), up to 5 sessions (k=3 + 2 spare), 100 model responses per session; within a session the
|
| 195 |
+
reference driver's continue rule (robots/lffbench/toolkit.py)."""
|
| 196 |
+
if auth != "apikey":
|
| 197 |
+
raise ValueError("rpent_codex supports auth=apikey only")
|
| 198 |
+
if catalog not in CATALOGS:
|
| 199 |
+
raise ValueError(f"catalog must be one of {CATALOGS}")
|
| 200 |
+
self.auth, self.catalog = auth, catalog
|
| 201 |
+
self.api_env = dict(api_env or {})
|
| 202 |
+
self.base_url = base_url or OFFICIAL_API
|
| 203 |
+
self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
|
| 204 |
+
self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
|
| 205 |
+
int(max_turns)
|
| 206 |
+
self.home = home or rpent_home()
|
| 207 |
+
self.proxy = proxy_env()
|
| 208 |
+
self._version = None
|
| 209 |
+
self._runtime = None
|
| 210 |
+
self.runtime_dir = self.home
|
| 211 |
+
if jail:
|
| 212 |
+
from .jail import HarnessJail
|
| 213 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 214 |
+
|
| 215 |
+
# ------------------------------------------------------------------------------------------------ identity
|
| 216 |
+
def runtime(self):
|
| 217 |
+
if self._runtime is None:
|
| 218 |
+
self._runtime = runtime_info(self.home)
|
| 219 |
+
if self.jail is not None:
|
| 220 |
+
self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
|
| 221 |
+
return self._runtime
|
| 222 |
+
|
| 223 |
+
def version(self):
|
| 224 |
+
if self._version is None:
|
| 225 |
+
b = codex_bin()
|
| 226 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 227 |
+
CODEX_HOME="/nonexistent"),
|
| 228 |
+
capture_output=True, text=True, timeout=60)
|
| 229 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 230 |
+
rt = self.runtime()
|
| 231 |
+
self._version = dict(version=v, binary=binary_info(b),
|
| 232 |
+
rpent=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
|
| 233 |
+
tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
|
| 234 |
+
return self._version
|
| 235 |
+
|
| 236 |
+
def pin_key(self, ep):
|
| 237 |
+
v = self.version()
|
| 238 |
+
name = f"{self.name}-{self.catalog}-{v['rpent']['tree_sha256'][:12]}"
|
| 239 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 240 |
+
|
| 241 |
+
def anchor_pin_key(self, ep):
|
| 242 |
+
"""The main table's codex pin for the same model / effort (apikey, same catalog)."""
|
| 243 |
+
v = self.version()
|
| 244 |
+
name = "codex" + ("" if self.catalog == "native" else f"-{self.catalog}")
|
| 245 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 246 |
+
|
| 247 |
+
def auth_info(self):
|
| 248 |
+
return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
|
| 249 |
+
"OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
|
| 250 |
+
|
| 251 |
+
def config_info(self):
|
| 252 |
+
return dict(catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
|
| 253 |
+
max_turns=self.max_turns, rpent=self.version()["rpent"])
|
| 254 |
+
|
| 255 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 256 |
+
def _state_dirs(self, hexname=None):
|
| 257 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 258 |
+
os.makedirs(root, exist_ok=True)
|
| 259 |
+
state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
|
| 260 |
+
for k in ("home", "codex_home", "tmp", "out"):
|
| 261 |
+
os.makedirs(state[k], exist_ok=True)
|
| 262 |
+
return state
|
| 263 |
+
|
| 264 |
+
def _install_catalog(self, codex_home, ep):
|
| 265 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
|
| 266 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 267 |
+
with open(path, "w") as f:
|
| 268 |
+
json.dump(cat, f)
|
| 269 |
+
return path, C.sha256_file(path), os.path.relpath(src, ROOT)
|
| 270 |
+
|
| 271 |
+
def argv(self, ep, out_dir, sessions=None, preflight=False):
|
| 272 |
+
py = os.path.join(self.runtime_dir, "venv", "bin", "python")
|
| 273 |
+
return [py, "-m", "robots.lffbench.run", "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
|
| 274 |
+
"--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
|
| 275 |
+
"--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
|
| 276 |
+
+ (["--no-continue"] if preflight else [])
|
| 277 |
+
|
| 278 |
+
def env(self, state, ep, base_url, work):
|
| 279 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
|
| 280 |
+
CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
|
| 281 |
+
CODEX_BASE_URL=base_url, RPENT_CODEX_SANDBOX="read_only", RPENT_MCP_SERVER_NAME=MCP_SERVER,
|
| 282 |
+
RPENT_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
|
| 283 |
+
ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
|
| 284 |
+
RPENT_REPO_ROOT=work, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
|
| 285 |
+
PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
|
| 286 |
+
e.update(self.proxy)
|
| 287 |
+
if self.api_env.get("OPENAI_API_KEY"):
|
| 288 |
+
e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
|
| 289 |
+
return e
|
| 290 |
+
|
| 291 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 292 |
+
self.version()
|
| 293 |
+
work = new_run_dir("/tmp/lffrun")
|
| 294 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 295 |
+
if self.jail is not None:
|
| 296 |
+
self.jail.stderr_dir = ep.log_dir
|
| 297 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 298 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 299 |
+
cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
|
| 300 |
+
return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
|
| 301 |
+
run_dir=work, state_dirs=state, first_message=first_message,
|
| 302 |
+
stdout_path=os.path.join(ep.log_dir, "rpent_stdout.txt"),
|
| 303 |
+
stderr_path=os.path.join(ep.log_dir, "rpent_stderr.txt"),
|
| 304 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 305 |
+
catalog=self.catalog, code_mode=False)),
|
| 306 |
+
timeout_s=self.timeout_s)
|
| 307 |
+
|
| 308 |
+
def config_sha256(self, spec, ep):
|
| 309 |
+
argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<RPENT>")
|
| 310 |
+
for a in spec.argv]
|
| 311 |
+
hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "RPENT_REPO_ROOT", "PYTHONPATH",
|
| 312 |
+
"LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
|
| 313 |
+
env = {k: v for k, v in spec.env.items() if k not in hidden}
|
| 314 |
+
env["RPENT_CODEX_CONFIG_OVERRIDES"] = env.get("RPENT_CODEX_CONFIG_OVERRIDES", "").replace(
|
| 315 |
+
spec.state_dirs["codex_home"], "<CODEX_HOME>")
|
| 316 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 317 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
|
| 318 |
+
rpent_tree_sha256=self.version()["rpent"]["tree_sha256"]))
|
| 319 |
+
|
| 320 |
+
# ------------------------------------------------------------------------------------------------ launch
|
| 321 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 322 |
+
"""harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
|
| 323 |
+
spec.env.update(gateway_env(ep.log_dir))
|
| 324 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 325 |
+
|
| 326 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 327 |
+
"""The same framework process, one session, against a local fake Responses server that answers with text
|
| 328 |
+
only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
|
| 329 |
+
sandbox, RPent's prefix + our first message) against the pins."""
|
| 330 |
+
t0 = time.time()
|
| 331 |
+
fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
|
| 332 |
+
pre = self._state_dirs()
|
| 333 |
+
try:
|
| 334 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 335 |
+
env = self.env(pre, ep, fake.base_url, spec.cwd)
|
| 336 |
+
env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
|
| 337 |
+
env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
|
| 338 |
+
argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
|
| 339 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 340 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
|
| 341 |
+
reqs = fake.model_requests()
|
| 342 |
+
if not reqs:
|
| 343 |
+
raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
|
| 344 |
+
f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]}")
|
| 345 |
+
body = reqs[0][1]
|
| 346 |
+
fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
|
| 347 |
+
problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
|
| 348 |
+
users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
|
| 349 |
+
and it.get("role") == "user" for c in it.get("content") or []]
|
| 350 |
+
prefix = None
|
| 351 |
+
if len(users) != 1 or not users[0].endswith(spec.first_message):
|
| 352 |
+
problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
|
| 353 |
+
else:
|
| 354 |
+
prefix = users[0][:-len(spec.first_message)]
|
| 355 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 356 |
+
if effort != ep.effort:
|
| 357 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 358 |
+
if fp["params"].get("model") != ep.model:
|
| 359 |
+
problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
|
| 360 |
+
if os.listdir(spec.cwd):
|
| 361 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 362 |
+
mid_sha = C.sha256_json(fp)
|
| 363 |
+
full = dict(middle=fp, rpent_prefix=prefix)
|
| 364 |
+
fp_sha = C.sha256_json(full)
|
| 365 |
+
anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
|
| 366 |
+
out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
|
| 367 |
+
rpent_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
|
| 368 |
+
rpent_prefix_chars=len(prefix) if prefix is not None else None,
|
| 369 |
+
developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 370 |
+
top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
|
| 371 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
|
| 372 |
+
dt_s=round(time.time() - t0, 1), problems=problems,
|
| 373 |
+
anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
|
| 374 |
+
if anchor is None:
|
| 375 |
+
out["anchor_status"] = "no main-table pin for this model / effort"
|
| 376 |
+
elif anchor["fingerprint_sha256"] != mid_sha:
|
| 377 |
+
problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
|
| 378 |
+
f"({anchor['key']}): the middle layer is not the main table's")
|
| 379 |
+
else:
|
| 380 |
+
out["anchor_status"] = "match"
|
| 381 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 382 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 383 |
+
out["fingerprint"] = full
|
| 384 |
+
if problems:
|
| 385 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 386 |
+
if pin is None:
|
| 387 |
+
if not self.allow_unpinned:
|
| 388 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 389 |
+
f"with --write-pins after the self-check passes)")
|
| 390 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 391 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 392 |
+
raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
|
| 393 |
+
f"({pin['key']})")
|
| 394 |
+
else:
|
| 395 |
+
out["pin_status"] = "match"
|
| 396 |
+
return out
|
| 397 |
+
finally:
|
| 398 |
+
fake.stop()
|
| 399 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 400 |
+
|
| 401 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 402 |
+
def collect(self, h):
|
| 403 |
+
spec, ep = h.spec, h.ep
|
| 404 |
+
dst = os.path.join(ep.log_dir, "rpent")
|
| 405 |
+
if os.path.isdir(spec.state_dirs["out"]):
|
| 406 |
+
shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
|
| 407 |
+
run = {}
|
| 408 |
+
if os.path.exists(os.path.join(dst, "run.json")):
|
| 409 |
+
run = json.load(open(os.path.join(dst, "run.json")))
|
| 410 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 411 |
+
usage = dict(input=0, cached=0, output=0, reasoning=0)
|
| 412 |
+
items, threads, errors = [], [], []
|
| 413 |
+
for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
|
| 414 |
+
else []:
|
| 415 |
+
last = None
|
| 416 |
+
for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
|
| 417 |
+
m = ev.get("method") or ev.get("type")
|
| 418 |
+
p = ev.get("payload") or {}
|
| 419 |
+
if m == "thread/tokenUsage/updated":
|
| 420 |
+
last = (p.get("token_usage") or {}).get("total") or last
|
| 421 |
+
if p.get("thread_id") and p["thread_id"] not in threads:
|
| 422 |
+
threads.append(p["thread_id"])
|
| 423 |
+
elif m in ("error", "fatal", "timeout"):
|
| 424 |
+
errors.append(ev)
|
| 425 |
+
elif m == "item/completed":
|
| 426 |
+
it = _item_of(ev)
|
| 427 |
+
t = it.get("type")
|
| 428 |
+
items.append(t)
|
| 429 |
+
if t == "agentMessage":
|
| 430 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 431 |
+
elif t == "reasoning":
|
| 432 |
+
tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
|
| 433 |
+
elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
|
| 434 |
+
name = it.get("tool") or t
|
| 435 |
+
tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 436 |
+
native_name=f"{it.get('server', '')}.{name}",
|
| 437 |
+
item_type=t, arguments=it.get("arguments"),
|
| 438 |
+
session=sdir)])
|
| 439 |
+
res = it.get("result") or {}
|
| 440 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 441 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 442 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 443 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 444 |
+
if last:
|
| 445 |
+
usage["input"] += last.get("input_tokens") or 0
|
| 446 |
+
usage["cached"] += last.get("cached_input_tokens") or 0
|
| 447 |
+
usage["output"] += last.get("output_tokens") or 0
|
| 448 |
+
usage["reasoning"] += last.get("reasoning_output_tokens") or 0
|
| 449 |
+
# Framework close-out uses the same counted gateway shell, outside
|
| 450 |
+
# the model stream. Keep it visible in trajectories and tool totals.
|
| 451 |
+
session_record = next((s for s in run.get("sessions", [])
|
| 452 |
+
if sdir == f"session_{s['number']:03d}"), {})
|
| 453 |
+
handoff = session_record.get("handoff") or {}
|
| 454 |
+
if handoff:
|
| 455 |
+
call_id = f"framework-handoff-{sdir}"
|
| 456 |
+
tw.add_step("framework", tool_calls=[dict(
|
| 457 |
+
tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
|
| 458 |
+
item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
|
| 459 |
+
tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
|
| 460 |
+
if c.get("type") == "text"))
|
| 461 |
+
v = self.version()
|
| 462 |
+
tw.set_header(session_id=",".join(threads), source="rpent/sessions/*/codex.out.stream.jsonl",
|
| 463 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
|
| 464 |
+
rpent=v["rpent"]), tools=EXPECTED_TOP_GENERIC)
|
| 465 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
|
| 466 |
+
run={k: run.get(k) for k in ("stop", "finished",
|
| 467 |
+
"attempts_failed", "tool_calls")},
|
| 468 |
+
sessions=len(run.get("sessions") or [])),
|
| 469 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 470 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 471 |
+
tw.write()
|
| 472 |
+
h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
|
| 473 |
+
return tw
|
| 474 |
+
|
| 475 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 476 |
+
def audit(self, h):
|
| 477 |
+
spec, ep = h.spec, h.ep
|
| 478 |
+
v, notes = [], []
|
| 479 |
+
items = h.info.get("items") or []
|
| 480 |
+
bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
|
| 481 |
+
"plan", "hookPrompt")})
|
| 482 |
+
if bad:
|
| 483 |
+
v.append(f"items other than messages / reasoning / MCP calls: {bad}")
|
| 484 |
+
residual = []
|
| 485 |
+
tw = h.info.get("traj")
|
| 486 |
+
for st in (tw.steps if tw else []):
|
| 487 |
+
for tc in st["tool_calls"]:
|
| 488 |
+
if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
|
| 489 |
+
continue
|
| 490 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 491 |
+
residual.append(tc["function_name"])
|
| 492 |
+
else:
|
| 493 |
+
v.append(f"unexpected tool call {tc['native_name']}")
|
| 494 |
+
if residual:
|
| 495 |
+
notes.append(f"residual MCP-resource tool calls (empty): {residual}")
|
| 496 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 497 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 498 |
+
run = h.info.get("run") or {}
|
| 499 |
+
nsess = len(run.get("sessions") or [])
|
| 500 |
+
if len(h.info.get("threads") or []) > max(1, nsess):
|
| 501 |
+
v.append(f"{len(h.info['threads'])} Codex threads for {nsess} RPent sessions")
|
| 502 |
+
if nsess > 1:
|
| 503 |
+
notes.append(f"{nsess} RPent sessions (handoff after a session ended before the episode was over)")
|
| 504 |
+
if run.get("stop") not in (None, "episode over"):
|
| 505 |
+
notes.append(f"RPent stopped: {run.get('stop')}")
|
| 506 |
+
left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
|
| 507 |
+
work=snapshot_tree(spec.cwd))
|
| 508 |
+
if left["work"]:
|
| 509 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 510 |
+
foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
|
| 511 |
+
and not any(t in f for t in (h.info.get("threads") or []))]
|
| 512 |
+
if foreign:
|
| 513 |
+
v.append(f"session files other than this run's threads: {foreign}")
|
| 514 |
+
gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
|
| 515 |
+
faces = set()
|
| 516 |
+
if os.path.exists(gt):
|
| 517 |
+
for line in open(gt):
|
| 518 |
+
try:
|
| 519 |
+
d = json.loads(line)
|
| 520 |
+
except ValueError:
|
| 521 |
+
continue
|
| 522 |
+
if d.get("ev") == "tool" and d.get("face"):
|
| 523 |
+
faces.add(d["face"])
|
| 524 |
+
if faces - {"rpent"}:
|
| 525 |
+
v.append(f"gateway calls from other access paths: {sorted(faces)}")
|
| 526 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
|
| 527 |
+
item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
|
| 528 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 529 |
+
json.dump(out, f, indent=1)
|
| 530 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/harnesses/trajectory.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unified trajectory (minimal, field names follow Harbor's ATIF where there is one).
|
| 2 |
+
|
| 3 |
+
<log_dir>/trajectory.jsonl, one JSON object per line:
|
| 4 |
+
line 1 {"kind": "header", "schema": "lff-traj-0", "atif_like": "ATIF v1.x field names", "session_id",
|
| 5 |
+
"agent": {"name", "version", "model_name", "effort"}, "tools": [...], "source": "<native log file>"}
|
| 6 |
+
steps {"kind": "step", "step_id", "timestamp", "source": "user"|"agent"|"system", "message",
|
| 7 |
+
"reasoning_content", "tool_calls": [{"tool_call_id", "function_name", "arguments"}],
|
| 8 |
+
"observation": {"results": [{"source_call_id", "content", "is_error", "images"}]},
|
| 9 |
+
"metrics": {"prompt_tokens", "completion_tokens", "cached_tokens", "cost_usd"}}
|
| 10 |
+
last {"kind": "final", "final_metrics": {"total_prompt_tokens", "total_completion_tokens",
|
| 11 |
+
"total_cached_tokens", "total_cost_usd", "total_steps"}, "exit_reason", "native_result"}
|
| 12 |
+
Not full ATIF: no per-step model name, no subagent trajectories, images only counted (bytes stay in the workspace).
|
| 13 |
+
Tool names are reported without the MCP prefix (robot / shell / view_images), so all harnesses line up.
|
| 14 |
+
"""
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
SCHEMA = "lff-traj-0"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def strip_mcp(name):
|
| 22 |
+
for p in ("mcp__lff__", "lff."):
|
| 23 |
+
if name and name.startswith(p):
|
| 24 |
+
return name[len(p):]
|
| 25 |
+
return name
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TrajWriter:
|
| 29 |
+
def __init__(self, path):
|
| 30 |
+
self.path = path
|
| 31 |
+
self.steps = []
|
| 32 |
+
self.header = None
|
| 33 |
+
self.final = None
|
| 34 |
+
|
| 35 |
+
def set_header(self, **kw):
|
| 36 |
+
self.header = dict(kind="header", schema=SCHEMA, atif_like="field names follow Harbor ATIF", **kw)
|
| 37 |
+
|
| 38 |
+
def add_step(self, source, message="", reasoning="", tool_calls=None, timestamp=None, metrics=None, **extra):
|
| 39 |
+
st = dict(kind="step", step_id=len(self.steps) + 1, timestamp=timestamp, source=source, message=message or "",
|
| 40 |
+
reasoning_content=reasoning or "", tool_calls=tool_calls or [],
|
| 41 |
+
observation=dict(results=[]), metrics=metrics or {})
|
| 42 |
+
st.update(extra)
|
| 43 |
+
self.steps.append(st)
|
| 44 |
+
return st
|
| 45 |
+
|
| 46 |
+
def add_result(self, call_id, content, is_error=False, images=0):
|
| 47 |
+
for st in reversed(self.steps):
|
| 48 |
+
if any(tc["tool_call_id"] == call_id for tc in st["tool_calls"]):
|
| 49 |
+
st["observation"]["results"].append(dict(source_call_id=call_id, content=content, is_error=is_error,
|
| 50 |
+
images=images))
|
| 51 |
+
return True
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
def set_final(self, exit_reason, native_result=None, **metrics):
|
| 55 |
+
fm = dict(total_prompt_tokens=0, total_completion_tokens=0, total_cached_tokens=0, total_cost_usd=None,
|
| 56 |
+
total_steps=len(self.steps))
|
| 57 |
+
fm.update({k: v for k, v in metrics.items() if v is not None})
|
| 58 |
+
self.final = dict(kind="final", final_metrics=fm, exit_reason=exit_reason, native_result=native_result)
|
| 59 |
+
|
| 60 |
+
def write(self):
|
| 61 |
+
with open(self.path, "w") as f:
|
| 62 |
+
for d in [self.header] + self.steps + [self.final]:
|
| 63 |
+
if d is not None:
|
| 64 |
+
f.write(json.dumps(d, ensure_ascii=False) + "\n")
|
| 65 |
+
return self.path
|
| 66 |
+
|
| 67 |
+
def tool_call_names(self):
|
| 68 |
+
return [tc["function_name"] for st in self.steps for tc in st["tool_calls"]]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read(path):
|
| 72 |
+
with open(path) as f:
|
| 73 |
+
return [json.loads(line) for line in f if line.strip()]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def usage_summary(log_dir):
|
| 77 |
+
"""Token / cost totals from trajectory.jsonl (None if missing)."""
|
| 78 |
+
p = os.path.join(log_dir or "", "trajectory.jsonl")
|
| 79 |
+
if not os.path.exists(p):
|
| 80 |
+
return None
|
| 81 |
+
rows = read(p)
|
| 82 |
+
fin = next((r for r in rows if r.get("kind") == "final"), None)
|
| 83 |
+
steps = [r for r in rows if r.get("kind") == "step" and r.get("source") == "agent"]
|
| 84 |
+
out = dict(calls=len(steps), exit_reason=(fin or {}).get("exit_reason"))
|
| 85 |
+
out.update((fin or {}).get("final_metrics") or {})
|
| 86 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/fake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ole real-robot path (harness -> MCP -> real robot server -> driver) runs without hardware.
|
| 3 |
+
|
| 4 |
+
It behaves like a real driver: it reports the TRUE pose in the robot-base frame (no calibration bias of its own; the
|
| 5 |
+
benchmark injects the bias), sends lossless PNG frames, rejects targets outside its hard workspace, and has an
|
| 6 |
+
operator. The operator is the simulator unless --operator console: "reset" resets the simulated scene, "judge" is the
|
| 7 |
+
task's own success rule (task.outcome).
|
| 8 |
+
|
| 9 |
+
python -m lffbench.real.fake_driver --task l7_offcenter_push --seed 3000 --port 9900 --token <t> [--nominal]
|
| 10 |
+
[--operator auto|console] [--log <dir>]
|
| 11 |
+
|
| 12 |
+
--nominal removes the task's hidden calibration bias (L1 tasks), which is what a real arm looks like when the benchmark
|
| 13 |
+
injects the bias in software (real_bias_place).
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
import time
|
| 20 |
+
import types
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from .protocol import CAMERAS, PROTOCOL_VERSION, ConsoleOperator, DriverServer
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SimDriver(DriverServer):
|
| 28 |
+
def __init__(self, task, seed, nominal=False, image_res=512, operator="auto", log_dir=""):
|
| 29 |
+
from ..agent import robot_server as RS # registers every simulated task
|
| 30 |
+
from ..agent.tools import SPEED_RANGE, WS_HI, WS_LO, ToolExecutor
|
| 31 |
+
from ..task_base import TASKS
|
| 32 |
+
self.RS, self.ToolExecutor = RS, ToolExecutor
|
| 33 |
+
self.task_name, self.seed, self.image_res = task, int(seed), int(image_res)
|
| 34 |
+
self.task = TASKS[task](cam_res=self.image_res)
|
| 35 |
+
self.inst = self.task.sample_instance(self.seed)
|
| 36 |
+
if nominal: # same rule as robot_server --nominal
|
| 37 |
+
for k in [k for k in self.inst if "bias" in k]:
|
| 38 |
+
v = self.inst[k]
|
| 39 |
+
self.inst[k] = [0.0] * len(v) if isinstance(v, (list, tuple)) else 0.0 if isinstance(v, (int, float)) else v
|
| 40 |
+
self.operator_mode = operator
|
| 41 |
+
self.log_dir = log_dir
|
| 42 |
+
if log_dir:
|
| 43 |
+
os.makedirs(log_dir, exist_ok=True)
|
| 44 |
+
self.console_op = ConsoleOperator(os.path.join(log_dir, "operator.jsonl") if log_dir else None)
|
| 45 |
+
self._reset()
|
| 46 |
+
sim = self.task.env.sim
|
| 47 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 48 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 49 |
+
self.ws_lo, self.ws_hi = WS_LO - self.base_off, WS_HI - self.base_off
|
| 50 |
+
self.max_speed = float(SPEED_RANGE[1])
|
| 51 |
+
self.yaw_limit_deg = math.degrees(self.task.sk.YAW_LIMIT)
|
| 52 |
+
|
| 53 |
+
def _reset(self):
|
| 54 |
+
self.task.reset_instance(self.inst)
|
| 55 |
+
self.ex = self.ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=CAMERAS)
|
| 56 |
+
|
| 57 |
+
def _log(self, d):
|
| 58 |
+
if self.log_dir:
|
| 59 |
+
with open(os.path.join(self.log_dir, "driver_events.jsonl"), "a") as f:
|
| 60 |
+
f.write(json.dumps(dict(d, t=time.time()), default=str) + "\n")
|
| 61 |
+
|
| 62 |
+
# ------------------------------------------------------------------ protocol
|
| 63 |
+
def info(self):
|
| 64 |
+
return dict(protocol=PROTOCOL_VERSION, robot="Franka Emika Panda (fake driver, simulated)", n_joints=7,
|
| 65 |
+
cameras=list(CAMERAS), workspace=dict(lo=self.ws_lo.round(6).tolist(), hi=self.ws_hi.round(6).tolist()),
|
| 66 |
+
yaw_range_deg=[-self.yaw_limit_deg, self.yaw_limit_deg], max_speed=self.max_speed, ik=True,
|
| 67 |
+
driver_version=f"fake_driver sim:{self.task_name} seed:{self.seed}")
|
| 68 |
+
|
| 69 |
+
def home(self):
|
| 70 |
+
# the simulated arm goes home with the scene reset that always follows (operator "reset")
|
| 71 |
+
return self.state()
|
| 72 |
+
|
| 73 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 74 |
+
tgt = np.array([x, y, z], float)
|
| 75 |
+
if not (np.all(tgt >= self.ws_lo - 1e-9) and np.all(tgt <= self.ws_hi + 1e-9)):
|
| 76 |
+
return False, "outside the hard workspace", 0.0
|
| 77 |
+
w = tgt + self.base_off
|
| 78 |
+
n0 = self.task.sk.n_steps
|
| 79 |
+
mv = dict(x=float(w[0]), y=float(w[1]), z=float(w[2]), yaw=float(yaw_deg))
|
| 80 |
+
if speed is not None:
|
| 81 |
+
mv["speed"] = float(speed)
|
| 82 |
+
res = self.ex.call("move_to", mv)
|
| 83 |
+
if not res.ok:
|
| 84 |
+
return False, res.report.get("error", "rejected"), 0.0
|
| 85 |
+
return True, None, (self.task.sk.n_steps - n0) * 0.05
|
| 86 |
+
|
| 87 |
+
def gripper(self, close):
|
| 88 |
+
n0 = self.task.sk.n_steps
|
| 89 |
+
self.ex.call("close_gripper" if close else "open_gripper", {})
|
| 90 |
+
return (self.task.sk.n_steps - n0) * 0.05
|
| 91 |
+
|
| 92 |
+
def _joints(self):
|
| 93 |
+
rob = self.task.env.robots[0]
|
| 94 |
+
return self.task.env.sim.data.qpos[np.array(rob._ref_joint_pos_indexes)].copy()
|
| 95 |
+
|
| 96 |
+
def state(self):
|
| 97 |
+
sk = self.task.sk
|
| 98 |
+
return dict(eef_pos=[float(v) for v in sk.eef_pos() - self.base_off], eef_yaw_deg=float(self.ex.eef_yaw_deg()),
|
| 99 |
+
gripper_width_m=float(sk.gripper_width()), joint_pos_rad=[float(v) for v in self._joints()])
|
| 100 |
+
|
| 101 |
+
def images(self):
|
| 102 |
+
return {r.camera: r.array for r in self.ex.observe()}
|
| 103 |
+
|
| 104 |
+
def ik(self, eef_pos, yaw_deg):
|
| 105 |
+
"""Joint angles for the grasp point at eef_pos (base frame) with the current orientation: the same damped
|
| 106 |
+
least squares as robot_server._believed_joints (yaw_deg is the current yaw here)."""
|
| 107 |
+
sk = self.task.sk
|
| 108 |
+
T_true = np.eye(4)
|
| 109 |
+
T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos()
|
| 110 |
+
T_b = T_true.copy()
|
| 111 |
+
T_b[:3, 3] = np.asarray(eef_pos, float) + self.base_off
|
| 112 |
+
shim = types.SimpleNamespace(task=self.task, _believed_pose=lambda: (T_b, T_true))
|
| 113 |
+
return [float(v) for v in self.RS._believed_joints(shim)]
|
| 114 |
+
|
| 115 |
+
def operator(self, kind, **kw):
|
| 116 |
+
self._log(dict(ev="operator", kind=kind, **{k: v for k, v in kw.items() if k != "checklist"}))
|
| 117 |
+
if kind == "reset":
|
| 118 |
+
if self.operator_mode == "console":
|
| 119 |
+
self.console_op(kind, **kw)
|
| 120 |
+
self._reset()
|
| 121 |
+
return dict(ok=True)
|
| 122 |
+
if kind == "judge":
|
| 123 |
+
out = self.task.outcome(self.inst)
|
| 124 |
+
if self.operator_mode == "console":
|
| 125 |
+
kw = dict(kw, text=(kw.get("text", "") + f"\n(simulator says: success={bool(out['success'])}, "
|
| 126 |
+
f"{out.get('failure') or out.get('detail') or ''})"))
|
| 127 |
+
return self.console_op(kind, **kw)
|
| 128 |
+
return dict(ok=True, success=bool(out["success"]),
|
| 129 |
+
note=str(out.get("failure") or ("ok" if out["success"] else "")))
|
| 130 |
+
return dict(ok=True)
|
| 131 |
+
|
| 132 |
+
def event(self, ev, **kw):
|
| 133 |
+
self._log(dict(ev=ev, **kw))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main():
|
| 137 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 138 |
+
ap.add_argument("--task", default="l7_offcenter_push", help="simulated LFF-Bench task that plays the real scene")
|
| 139 |
+
ap.add_argument("--seed", type=int, default=3000)
|
| 140 |
+
ap.add_argument("--port", type=int, default=9900)
|
| 141 |
+
ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
|
| 142 |
+
ap.add_argument("--nominal", action="store_true", help="remove the simulated task's calibration bias")
|
| 143 |
+
ap.add_argument("--operator", default="auto", choices=["auto", "console"])
|
| 144 |
+
ap.add_argument("--image-res", type=int, default=512)
|
| 145 |
+
ap.add_argument("--log", default="", help="directory for driver_events.jsonl / operator.jsonl")
|
| 146 |
+
a = ap.parse_args()
|
| 147 |
+
drv = SimDriver(a.task, a.seed, nominal=a.nominal, image_res=a.image_res, operator=a.operator, log_dir=a.log)
|
| 148 |
+
drv.serve(a.port, token=a.token or None)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/real/session.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot server for a real arm: robot_server's LA interface (README, robot commands, budgets, attempts, F1, --hide-k,
|
| 2 |
+
memory conditions, events.jsonl, observation files) with a robot driver instead of the simulator.
|
| 3 |
+
|
| 4 |
+
Everything above this server is unchanged: the MCP server (scripts/mcp_robot_server.py), the native-harness adapters
|
| 5 |
+
(Codex / Claude Code, with or without the jail), api_player. They talk to this server exactly as to the simulated one
|
| 6 |
+
(POST /call on 127.0.0.1, same token file, same workspace layout). Below it, lffbench/real/protocol.py talks to the
|
| 7 |
+
driver on the robot PC (usually through an SSH tunnel).
|
| 8 |
+
|
| 9 |
+
What differs from simulation, all of it on purpose (docs/17):
|
| 10 |
+
- README: "a real <robot> arm (<n> joints)" instead of "Franka Emika Panda (7 joints) ... in a physics simulation";
|
| 11 |
+
"a person resets the scene"; "s of robot motion" (budget_left key motion_seconds instead of sim_seconds).
|
| 12 |
+
- outcome: the operator judges the end state against the task's checklist (F1 only; F2 needs simulator measurements).
|
| 13 |
+
- reset: arm to home, then the operator rebuilds the scene from the task's setup sheet.
|
| 14 |
+
- a driver fault ends the episode and marks the run invalid (events.jsonl ev=run_invalid).
|
| 15 |
+
- no video, no regression snapshots here (the driver side records video).
|
| 16 |
+
|
| 17 |
+
python -m lffbench.real.session --task real_offcenter_push --seed 5000 --driver http://127.0.0.1:9900 \
|
| 18 |
+
--sandbox <dir> --log-dir <dir> --port 9800 [robot_server's la options]
|
| 19 |
+
(scripts/start_real_session.sh does this and writes session.json, like scripts/start_robot_session.sh.)
|
| 20 |
+
"""
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import signal
|
| 25 |
+
import time
|
| 26 |
+
import traceback
|
| 27 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
from ..agent import robot_server as RS
|
| 32 |
+
from ..agent.tools import _json_default
|
| 33 |
+
from .executor import RealToolExecutor
|
| 34 |
+
from .protocol import DriverClient, DriverError, DriverFault
|
| 35 |
+
from .tasks import REAL_TASKS
|
| 36 |
+
|
| 37 |
+
SIM_TEXT = { # robot_server._readme_la sentence -> real-robot sentence (each must occur, else refuse to start)
|
| 38 |
+
"embodiment": ("You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics "
|
| 39 |
+
"simulation.", "You control a real {robot} robot arm ({n} joints) with a two-finger parallel gripper."),
|
| 40 |
+
"reset": ("Before every attempt the scene is reset to exactly the same initial state.",
|
| 41 |
+
"Before every attempt a person resets the scene to the same initial state."),
|
| 42 |
+
"motion": (" s of simulated robot motion;", " s of robot motion;"),
|
| 43 |
+
"joints": ("joint_pos_rad = the 7 arm joint angles", "joint_pos_rad = the {n} arm joint angles"),
|
| 44 |
+
}
|
| 45 |
+
REPLY_TEXT = [("The scene has been reset to exactly the same initial state.",
|
| 46 |
+
"A person has reset the scene to the same initial state.")]
|
| 47 |
+
FAULT_MSG = "The robot stopped because of a hardware problem. The episode is over. Stop now and report."
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _realify(o):
|
| 51 |
+
"""Agent-facing reply wording for the real robot (see module doc)."""
|
| 52 |
+
if isinstance(o, dict):
|
| 53 |
+
return {("motion_seconds" if k == "sim_seconds" else k): _realify(v) for k, v in o.items()}
|
| 54 |
+
if isinstance(o, list):
|
| 55 |
+
return [_realify(v) for v in o]
|
| 56 |
+
if isinstance(o, str):
|
| 57 |
+
for a, b in REPLY_TEXT:
|
| 58 |
+
o = o.replace(a, b)
|
| 59 |
+
return o
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class RealRobotSession(RS.RobotSession):
|
| 63 |
+
def __init__(self, a): # robot_server.RobotSession.__init__ minus the simulator
|
| 64 |
+
bad = [m for m, c in (("--style la", a.style != "la"), ("--perception rgb", a.perception != "rgb"),
|
| 65 |
+
("--feedback F0|F1", a.feedback == "F2"), ("--arm none", a.arm != "none"),
|
| 66 |
+
("no --nominal", a.nominal)) if c]
|
| 67 |
+
if bad:
|
| 68 |
+
raise SystemExit("real robot needs " + ", ".join(bad))
|
| 69 |
+
self.a = a
|
| 70 |
+
self.task = REAL_TASKS[a.task]()
|
| 71 |
+
self.task.judge = self._judge
|
| 72 |
+
if a.max_steps is None:
|
| 73 |
+
a.max_steps = int(self.task.agent_max_steps)
|
| 74 |
+
self.inst = self.task.sample_instance(a.seed)
|
| 75 |
+
self.inst_override = json.loads(a.inst_override) if a.inst_override else {}
|
| 76 |
+
self.inst.update(self.inst_override) # tests only (logged)
|
| 77 |
+
self.arm, self.arm_overrides, self.reveal_text = "none", {}, ""
|
| 78 |
+
self.n_mon_events = 0
|
| 79 |
+
self.protocol = self.task.protocol
|
| 80 |
+
self.k = a.k or self.task.max_attempts
|
| 81 |
+
self.k_shown = 1 if a.hide_k and a.memory == "full" else self.k
|
| 82 |
+
self.sandbox = os.path.abspath(a.sandbox)
|
| 83 |
+
self.obs_dir = os.path.join(self.sandbox, "obs")
|
| 84 |
+
self.log_dir = os.path.abspath(a.log_dir)
|
| 85 |
+
os.makedirs(self.obs_dir, exist_ok=True)
|
| 86 |
+
os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True)
|
| 87 |
+
self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a")
|
| 88 |
+
import secrets
|
| 89 |
+
self.token = secrets.token_hex(8)
|
| 90 |
+
self.n_actions, self.attempt, self.step = 0, 1, 0
|
| 91 |
+
self.finished, self.waiting_new_agent, self.invalid = False, False, ""
|
| 92 |
+
self.history, self.last_send, self.video = [], None, None
|
| 93 |
+
self.base_off = np.zeros(3) # the driver already reports the robot-base frame
|
| 94 |
+
self.run = a.run_name or os.path.basename(self.log_dir)
|
| 95 |
+
self.driver = DriverClient(a.driver, a.driver_token, timeout=a.driver_timeout)
|
| 96 |
+
self.dinfo = self.driver.info()
|
| 97 |
+
if self.task.needs_ik and np.any(self.task.bias(self.inst)) and not self.dinfo["ik"]:
|
| 98 |
+
raise SystemExit(f"{a.task} has a calibration bias: the driver must implement /ik (believed joint angles)")
|
| 99 |
+
m = float(self.task.bias_margin)
|
| 100 |
+
self.ws_lo = np.asarray(self.dinfo["workspace"]["lo"], float) + [m, m, 0.0]
|
| 101 |
+
self.ws_hi = np.asarray(self.dinfo["workspace"]["hi"], float) - [m, m, 0.0]
|
| 102 |
+
self.driver.event("session_start", run=self.run, task=a.task, seed=a.seed, k=self.k)
|
| 103 |
+
self._start_attempt(reset=True)
|
| 104 |
+
self._write_sandbox()
|
| 105 |
+
self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol,
|
| 106 |
+
memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception,
|
| 107 |
+
inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm,
|
| 108 |
+
arm_overrides={}, reveal="", dossier=a.dossier or "", backend="real",
|
| 109 |
+
driver_info={k: v for k, v in self.dinfo.items() if k != "ok"},
|
| 110 |
+
agent_workspace=dict(lo=self.ws_lo.round(4).tolist(), hi=self.ws_hi.round(4).tolist()),
|
| 111 |
+
inst_override=self.inst_override, sim_counterpart=self.task.sim_counterpart,
|
| 112 |
+
video_ignored=bool(a.video)))
|
| 113 |
+
|
| 114 |
+
# ------------------------------------------------------------------ simulator-dependent parts, replaced
|
| 115 |
+
def _start_attempt(self, reset):
|
| 116 |
+
self.n_actions = 0
|
| 117 |
+
if reset:
|
| 118 |
+
self.driver.home()
|
| 119 |
+
self.driver.operator("reset", run=self.run, attempt=self.attempt, setup=self.task.setup_text(self.inst),
|
| 120 |
+
text=f"task {self.a.task} seed {self.a.seed}")
|
| 121 |
+
self.driver.event("attempt_start", run=self.run, attempt=self.attempt)
|
| 122 |
+
self.ex = RealToolExecutor(self.driver, self.dinfo, bias=self.task.bias(self.inst), image_res=self.a.image_res)
|
| 123 |
+
self.step = 0
|
| 124 |
+
|
| 125 |
+
def _judge(self, inst):
|
| 126 |
+
self.driver.event("attempt_end", run=self.run, attempt=self.attempt)
|
| 127 |
+
rep = self.driver.operator("judge", run=self.run, attempt=self.attempt, checklist=self.task.checklist(inst),
|
| 128 |
+
text=f"task {self.a.task} seed {self.a.seed}: judge the scene as it is now")
|
| 129 |
+
if not isinstance(rep.get("success"), bool):
|
| 130 |
+
raise DriverError("/operator judge: reply needs \"success\": true|false")
|
| 131 |
+
return dict(success=rep["success"], note=str(rep.get("note", "")), judged_by="operator",
|
| 132 |
+
motion_s=round(self.ex.motion_s, 2))
|
| 133 |
+
|
| 134 |
+
def _budget_left(self):
|
| 135 |
+
used = self.ex.motion_s
|
| 136 |
+
return dict(commands=max(self.a.max_steps - self.n_actions, 0),
|
| 137 |
+
sim_seconds=round(max(self.sim_budget() - used, 0.0), 1)) # renamed to motion_seconds in replies
|
| 138 |
+
|
| 139 |
+
def _state_v2(self):
|
| 140 |
+
p = self.ex.proprio()
|
| 141 |
+
st = dict(eef_pos=p["eef_pos"], eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 142 |
+
st["joint_pos_rad"] = [round(float(v), 4) for v in self.ex.joints()]
|
| 143 |
+
st["budget_left"] = self._budget_left()
|
| 144 |
+
return st
|
| 145 |
+
|
| 146 |
+
def _snap_regressions(self):
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
def readme_la(self):
|
| 150 |
+
text = RS._readme_la(self)
|
| 151 |
+
n = int(self.dinfo["n_joints"])
|
| 152 |
+
for key, (old, new) in SIM_TEXT.items():
|
| 153 |
+
if key == "reset" and self.protocol != "cross":
|
| 154 |
+
continue
|
| 155 |
+
if old not in text: # robot_server's README changed: update SIM_TEXT rather than ship a half-sim README
|
| 156 |
+
raise SystemExit(f"README sentence for {key!r} not found in robot_server._readme_la: {old!r}")
|
| 157 |
+
text = text.replace(old, new.format(robot=self.dinfo["robot"], n=n))
|
| 158 |
+
return text
|
| 159 |
+
|
| 160 |
+
def _done(self, reason):
|
| 161 |
+
rep = RS.RobotSession._done(self, reason)
|
| 162 |
+
if self.finished:
|
| 163 |
+
self.driver.event("episode_end", run=self.run, attempt=self.attempt)
|
| 164 |
+
return rep
|
| 165 |
+
|
| 166 |
+
# ------------------------------------------------------------------ dispatch
|
| 167 |
+
def handle(self, cmd, args):
|
| 168 |
+
if self.invalid:
|
| 169 |
+
return dict(ok=False, error=FAULT_MSG)
|
| 170 |
+
try:
|
| 171 |
+
return _realify(RS.RobotSession.handle(self, cmd, args))
|
| 172 |
+
except DriverError as e: # robot fault, operator marked the run invalid, or the driver broke the protocol
|
| 173 |
+
self.invalid, self.finished = str(e), True
|
| 174 |
+
self.log(dict(ev="run_invalid", attempt=self.attempt, step=self.step, cmd=cmd, args=args,
|
| 175 |
+
fault=isinstance(e, DriverFault), error=str(e), traceback=traceback.format_exc()[-2000:]))
|
| 176 |
+
try:
|
| 177 |
+
self.driver.event("run_invalid", run=self.run, attempt=self.attempt, error=str(e))
|
| 178 |
+
except DriverError:
|
| 179 |
+
pass
|
| 180 |
+
return dict(ok=False, error=FAULT_MSG)
|
| 181 |
+
|
| 182 |
+
def handle_v2(self, cmd, args):
|
| 183 |
+
if cmd != "move_eef" or self.finished:
|
| 184 |
+
return RS._handle_v2(self, cmd, args)
|
| 185 |
+
return self._move_eef(args)
|
| 186 |
+
|
| 187 |
+
def _move_eef(self, args):
|
| 188 |
+
"""robot_server._handle_v2's move_eef branch (same checks, order, replies and log lines) with the driver's
|
| 189 |
+
workspace instead of the simulator's WS_LO / WS_HI. tests/real_selfcheck.py compares the two paths reply by
|
| 190 |
+
reply; keep them in step."""
|
| 191 |
+
cmd = "move_eef"
|
| 192 |
+
self.n_actions += 1
|
| 193 |
+
if self.n_actions > self.a.max_steps:
|
| 194 |
+
rep = self._done("command budget used up (automatic)")
|
| 195 |
+
rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up."
|
| 196 |
+
return rep
|
| 197 |
+
self.step += 1
|
| 198 |
+
p = self.ex.proprio()
|
| 199 |
+
unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}
|
| 200 |
+
if unknown:
|
| 201 |
+
rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed")
|
| 202 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 203 |
+
return rep
|
| 204 |
+
try:
|
| 205 |
+
cur = np.asarray(p["eef_pos"], float)
|
| 206 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 207 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 208 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 209 |
+
except (TypeError, ValueError):
|
| 210 |
+
rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers")
|
| 211 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 212 |
+
return rep
|
| 213 |
+
grip = args.get("gripper")
|
| 214 |
+
if grip not in (None, "open", "close"):
|
| 215 |
+
rep = dict(ok=False, error="gripper must be open or close")
|
| 216 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 217 |
+
return rep
|
| 218 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 219 |
+
tgt = np.asarray(tgt)
|
| 220 |
+
if moving and not (np.all(tgt >= self.ws_lo) and np.all(tgt <= self.ws_hi)):
|
| 221 |
+
rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move")
|
| 222 |
+
rep.update(self._state_v2())
|
| 223 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 224 |
+
return rep
|
| 225 |
+
left = self._budget_left()["sim_seconds"]
|
| 226 |
+
raw = {}
|
| 227 |
+
rejected = False
|
| 228 |
+
if moving:
|
| 229 |
+
mv = dict(x=float(tgt[0]), y=float(tgt[1]), z=float(tgt[2]), yaw=yaw)
|
| 230 |
+
if speed is not None:
|
| 231 |
+
mv["speed"] = speed
|
| 232 |
+
res = self.ex.call("move_to", mv)
|
| 233 |
+
raw.update(res.report)
|
| 234 |
+
rejected = not res.ok # the driver refused (no IK solution ...): the arm did not move, skip the gripper
|
| 235 |
+
if grip is not None and not rejected:
|
| 236 |
+
res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {})
|
| 237 |
+
raw.update(res.report)
|
| 238 |
+
rep = dict(ok=bool(raw.get("ok", True)))
|
| 239 |
+
if raw.get("error"):
|
| 240 |
+
rep["error"] = raw["error"]
|
| 241 |
+
rep.update(self._state_v2())
|
| 242 |
+
if moving:
|
| 243 |
+
err = tgt - np.asarray(rep["eef_pos"])
|
| 244 |
+
dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0
|
| 245 |
+
rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1))
|
| 246 |
+
rep["images"] = self._save_obs(cmd)
|
| 247 |
+
rep.update(self._la_files())
|
| 248 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw))
|
| 249 |
+
if rep["budget_left"]["sim_seconds"] <= 0 and left > 0:
|
| 250 |
+
fin = self._done("motion budget used up (automatic)")
|
| 251 |
+
fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up."
|
| 252 |
+
rep["attempt_ended"] = fin
|
| 253 |
+
return rep
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def serve(a):
|
| 257 |
+
"""robot_server.serve with the real session (same HTTP contract: POST /call, X-Token, 127.0.0.1)."""
|
| 258 |
+
sess = RealRobotSession(a)
|
| 259 |
+
|
| 260 |
+
class H(BaseHTTPRequestHandler):
|
| 261 |
+
def log_message(self, *x):
|
| 262 |
+
pass
|
| 263 |
+
|
| 264 |
+
def do_POST(self):
|
| 265 |
+
t_recv = time.time()
|
| 266 |
+
cmd = ""
|
| 267 |
+
try:
|
| 268 |
+
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
| 269 |
+
cmd = body.get("cmd", "")
|
| 270 |
+
if self.headers.get("X-Token") != sess.token:
|
| 271 |
+
rep = dict(ok=False, error="unauthorised")
|
| 272 |
+
else:
|
| 273 |
+
rep = sess.handle(cmd, body.get("args", {}) or {})
|
| 274 |
+
except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent
|
| 275 |
+
sess.log(dict(ev="error", error=traceback.format_exc()))
|
| 276 |
+
rep = dict(ok=False, error=f"internal error: {type(e).__name__}")
|
| 277 |
+
data = json.dumps(rep, default=_json_default, indent=None).encode()
|
| 278 |
+
if "text" in rep:
|
| 279 |
+
data = rep["text"].encode()
|
| 280 |
+
self.send_response(200)
|
| 281 |
+
self.send_header("Content-Type", "application/json")
|
| 282 |
+
self.end_headers()
|
| 283 |
+
self.wfile.write(data)
|
| 284 |
+
t_send = time.time()
|
| 285 |
+
sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send,
|
| 286 |
+
server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None))
|
| 287 |
+
sess.last_send = t_send
|
| 288 |
+
|
| 289 |
+
def _term(*_):
|
| 290 |
+
try: # short timeout: the driver may be blocked on an operator prompt
|
| 291 |
+
sess.driver.call("event", dict(ev="session_end", run=sess.run, attempt=sess.attempt), timeout=5)
|
| 292 |
+
except Exception:
|
| 293 |
+
pass
|
| 294 |
+
os._exit(0)
|
| 295 |
+
|
| 296 |
+
signal.signal(signal.SIGTERM, _term)
|
| 297 |
+
srv = HTTPServer(("127.0.0.1", a.port), H)
|
| 298 |
+
print(f"real robot server ready on 127.0.0.1:{a.port} driver={a.driver} sandbox={sess.sandbox} log={sess.log_dir}",
|
| 299 |
+
flush=True)
|
| 300 |
+
with open(os.path.join(sess.log_dir, "READY"), "w") as f:
|
| 301 |
+
f.write(str(os.getpid()))
|
| 302 |
+
srv.serve_forever()
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def parser():
|
| 306 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 307 |
+
ap.add_argument("--task", required=True, choices=sorted(REAL_TASKS))
|
| 308 |
+
ap.add_argument("--seed", type=int, required=True)
|
| 309 |
+
ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900"),
|
| 310 |
+
help="driver URL (default $LFF_REAL_DRIVER or http://127.0.0.1:9900, i.e. an SSH tunnel)")
|
| 311 |
+
ap.add_argument("--driver-token", default=os.environ.get("LFF_DRIVER_TOKEN", ""),
|
| 312 |
+
help="driver token (default $LFF_DRIVER_TOKEN)")
|
| 313 |
+
ap.add_argument("--driver-timeout", type=float, default=180.0, help="seconds per driver call (operator: no limit)")
|
| 314 |
+
ap.add_argument("--run-name", default="", help="shown to the operator (default: the log dir name)")
|
| 315 |
+
ap.add_argument("--inst-override", default=os.environ.get("LFF_REAL_INST_OVERRIDE", ""),
|
| 316 |
+
help="TESTS ONLY: JSON merged into the instance (logged; default $LFF_REAL_INST_OVERRIDE)")
|
| 317 |
+
# robot_server's options that apply to the real robot (same names and defaults as there, except perception/style)
|
| 318 |
+
ap.add_argument("--k", type=int, default=None)
|
| 319 |
+
ap.add_argument("--memory", default="full", choices=["full", "none"])
|
| 320 |
+
ap.add_argument("--hide-k", action="store_true")
|
| 321 |
+
ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
|
| 322 |
+
ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"])
|
| 323 |
+
ap.add_argument("--image-res", type=int, default=512)
|
| 324 |
+
ap.add_argument("--port", type=int, default=8765)
|
| 325 |
+
ap.add_argument("--sandbox", required=True)
|
| 326 |
+
ap.add_argument("--log-dir", required=True)
|
| 327 |
+
ap.add_argument("--max-steps", type=int, default=None)
|
| 328 |
+
ap.add_argument("--perception", default="rgb", choices=["depth", "rgb", "rgbd"])
|
| 329 |
+
ap.add_argument("--style", default="la", choices=["v1", "v2", "la"])
|
| 330 |
+
ap.add_argument("--nominal", action="store_true")
|
| 331 |
+
ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"])
|
| 332 |
+
ap.add_argument("--max-tool-calls", type=int, default=100)
|
| 333 |
+
ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"])
|
| 334 |
+
ap.add_argument("--dossier", default="")
|
| 335 |
+
ap.add_argument("--video", default="", help="ignored (the driver side records video)")
|
| 336 |
+
ap.add_argument("--video-every", type=int, default=3)
|
| 337 |
+
ap.add_argument("--video-fps", type=int, default=20)
|
| 338 |
+
return ap
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def main():
|
| 342 |
+
serve(parser().parse_args())
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
if __name__ == "__main__":
|
| 346 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l1_yaw.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L1-C yaw_bias: put a long bar into a narrow holder, with an arm whose wrist rotation is miscalibrated.
|
| 2 |
+
|
| 3 |
+
Category system_identification (level L1, action fine-tuning): the method (top-down pick across the bar, carry,
|
| 4 |
+
line the bar up with the holder, release just above the holder) and the scene understanding are right; only the
|
| 5 |
+
robot's own wrist rotation is off.
|
| 6 |
+
|
| 7 |
+
Hidden variable: a fixed wrist-yaw calibration offset beta, |beta| ~ U[15, 30] deg with a random sign: every
|
| 8 |
+
commanded gripper yaw theta is executed as theta + beta. The robot reports its yaw in its own (miscalibrated) frame,
|
| 9 |
+
so the agent's proprioception says "yaw = theta" (implemented by shifting the robot's notion of yaw 0, `Skills.R0`,
|
| 10 |
+
by beta: the agent harness computes the reported yaw from R0, so beta never shows up in a reading). At reset the
|
| 11 |
+
wrist is turned to the robot's own yaw 0 (true yaw beta), so the first reading is 0.
|
| 12 |
+
|
| 13 |
+
Why the prior fails: the bar is 14 cm long and 1.8 cm wide; the holder's opening is 3.2 cm wide (16 cm long).
|
| 14 |
+
Commanded to grasp square across the bar, the jaws actually come down rotated by beta; closing turns the bar until it
|
| 15 |
+
lies square in the jaws, so the bar ends up rotated by beta relative to where the robot thinks it is. Lined up
|
| 16 |
+
"exactly" with the holder, the bar is then beta off the holder's axis; its footprint across the opening
|
| 17 |
+
(14 sin beta + 1.8 cos beta >= 5.4 cm for beta >= 15 deg) is wider than the holder (4.4 cm outside), so it comes
|
| 18 |
+
down across the walls and stays on top of the holder at an angle -- clearly visible from both cameras. The
|
| 19 |
+
alignment tolerance is about +-5 deg (geometry; measured: see the task card).
|
| 20 |
+
|
| 21 |
+
What has to be learned: F2 reports by how many degrees, and in which sense, the bar's long axis was rotated from the
|
| 22 |
+
holder's long axis when the gripper opened (and how far the jaws were turned from square to the bar when they
|
| 23 |
+
closed). That angle is beta itself, so after one failure beta can be estimated and subtracted from every commanded
|
| 24 |
+
yaw.
|
| 25 |
+
"""
|
| 26 |
+
import re
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
from .. import envs
|
| 31 |
+
from ..bddl import write_bddl
|
| 32 |
+
from ..objects import bin_xml, box_xml, register_generated
|
| 33 |
+
from ..skills import Skills, _rotz
|
| 34 |
+
from ..task_base import LFFTask, register_task
|
| 35 |
+
|
| 36 |
+
BAR, HOLDER = "bar_1", "holder_1"
|
| 37 |
+
DISTRACTORS = ("cream_cheese_1", "butter_1")
|
| 38 |
+
FREE_OBJECTS = (BAR,) + DISTRACTORS
|
| 39 |
+
NAMES = {BAR: "blue bar", HOLDER: "holder", "cream_cheese_1": "cream cheese", "butter_1": "butter"}
|
| 40 |
+
DESCR = {BAR: "long blue stick", HOLDER: "narrow grey trough", "cream_cheese_1": "flat blue box",
|
| 41 |
+
"butter_1": "small orange box"}
|
| 42 |
+
|
| 43 |
+
BAR_HALF = (0.070, 0.009, 0.009) # 14 x 1.8 x 1.8 cm, long side along the bar's x axis
|
| 44 |
+
HOLDER_IN = (0.080, 0.016) # inner half extents of the holder's opening: 16 x 3.2 cm
|
| 45 |
+
WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030
|
| 46 |
+
HOLDER_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height
|
| 47 |
+
RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
|
| 48 |
+
MASS = {BAR: 0.070, "cream_cheese_1": 0.227, "butter_1": 0.250}
|
| 49 |
+
# Bar friction 0.5 with geom priority, so it is used for all bar contacts (also against the finger pads, mu 2). With
|
| 50 |
+
# the pads' mu 2 the jaws pinch a misaligned bar at their corners and it stays skewed in the hand (measured: turned
|
| 51 |
+
# 3-13 deg of beta 15-25 deg while closing); with 0.5 the closing jaws square it up (turned = beta, measured).
|
| 52 |
+
BAR_MU = 0.5
|
| 53 |
+
|
| 54 |
+
SITE_ABOVE_TABLE = 0.0105 # grasp point 1.05 cm above the table: fingertips ~1 mm above it
|
| 55 |
+
Z_CARRY = envs.TABLE_Z + 0.15
|
| 56 |
+
RELEASE_GAP = 0.012 # bar bottom this far above the holder's rim at release
|
| 57 |
+
BETA_MIN, BETA_MAX = np.deg2rad(15), np.deg2rad(30)
|
| 58 |
+
AXIS_MAX = np.deg2rad(45) # bar / holder long axes within +-45 deg of the forward (x) direction
|
| 59 |
+
HOME_XY = np.array([-0.21, 0.0])
|
| 60 |
+
REHOME_STEPS = 40
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def wrap_half(a):
|
| 64 |
+
"""angle modulo pi into [-pi/2, pi/2) (the bar, the holder and the jaws are 180-deg symmetric)"""
|
| 65 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _yaw_of_xmat(xmat):
|
| 69 |
+
return float(np.arctan2(xmat[1, 0], xmat[0, 0]))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _seg_dist(p, a, b):
|
| 73 |
+
ab = b - a
|
| 74 |
+
u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
|
| 75 |
+
return float(np.linalg.norm(a + u * ab - p))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _q(axis, a):
|
| 79 |
+
h = a / 2
|
| 80 |
+
return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _qmul(a, b):
|
| 84 |
+
w1, x1, y1, z1 = a
|
| 85 |
+
w2, x2, y2, z2 = b
|
| 86 |
+
return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 87 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def dir_words(dx, dy):
|
| 91 |
+
"""Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
|
| 92 |
+
parts = []
|
| 93 |
+
if abs(dy) >= 0.0005:
|
| 94 |
+
parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
|
| 95 |
+
if abs(dx) >= 0.0005:
|
| 96 |
+
parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
|
| 97 |
+
return " and ".join(parts) if parts else "exactly at the position"
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def rot_words(a):
|
| 101 |
+
"""Sense of a rotation about the vertical axis. Positive = counter-clockwise seen from above = from forward (+x)
|
| 102 |
+
towards the robot's left (+y) = increasing yaw."""
|
| 103 |
+
d = np.degrees(a)
|
| 104 |
+
if abs(d) < 0.5:
|
| 105 |
+
return "not rotated (within 0.5 deg)"
|
| 106 |
+
if d > 0:
|
| 107 |
+
return f"rotated {d:.0f} deg counter-clockwise seen from above (from forward towards the robot's left, +yaw)"
|
| 108 |
+
return f"rotated {-d:.0f} deg clockwise seen from above (from forward towards the robot's right, -yaw)"
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class YawSkills(Skills):
|
| 112 |
+
"""Skills with a miscalibrated wrist: commanded yaw theta is executed as theta + yaw_bias. Implemented by shifting
|
| 113 |
+
the robot's notion of yaw 0 (`R0`, which Skills uses to build every orientation target and the agent harness uses
|
| 114 |
+
to report the yaw) by yaw_bias; `R0_true` is the real top-down orientation at yaw 0. Also logs what the outcome
|
| 115 |
+
measurement needs, whoever drives the skills (scripted policy or agent)."""
|
| 116 |
+
|
| 117 |
+
def __init__(self, env, yaw_bias=0.0, recorder=None):
|
| 118 |
+
super().__init__(env, bias=None, recorder=recorder)
|
| 119 |
+
self.yaw_bias = float(yaw_bias)
|
| 120 |
+
self.R0_true = self.R0.copy()
|
| 121 |
+
self.R0 = _rotz(self.yaw_bias) @ self.R0_true
|
| 122 |
+
self.events = []
|
| 123 |
+
m = env.sim.model
|
| 124 |
+
self._finger_geoms = {
|
| 125 |
+
side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]]
|
| 126 |
+
for side in ("left_finger", "right_finger")}
|
| 127 |
+
self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
|
| 128 |
+
self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS}
|
| 129 |
+
self.bar_z0 = float(envs.obj_pos(env, BAR)[2])
|
| 130 |
+
self.bar_zmax = self.bar_z0
|
| 131 |
+
self.bar_ref_yaw = self.bar_yaw()
|
| 132 |
+
self.bar_ref = envs.obj_pos(env, BAR) # bar pose before the fingers last touched it
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------------ state
|
| 135 |
+
def true_yaw(self):
|
| 136 |
+
return _yaw_of_xmat(self.eef_mat() @ self.R0_true.T)
|
| 137 |
+
|
| 138 |
+
def reported_yaw(self):
|
| 139 |
+
"""Yaw as the miscalibrated robot believes it to be. Anything shown to the agent must use this."""
|
| 140 |
+
return _yaw_of_xmat(self.eef_mat() @ self.R0.T)
|
| 141 |
+
|
| 142 |
+
def bar_yaw(self):
|
| 143 |
+
return _yaw_of_xmat(self.env.sim.data.body_xmat[envs.body_id(self.env, BAR)].reshape(3, 3))
|
| 144 |
+
|
| 145 |
+
def touching(self):
|
| 146 |
+
return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
|
| 147 |
+
|
| 148 |
+
def holding_bar(self):
|
| 149 |
+
bg = self._obj_geoms[BAR]
|
| 150 |
+
return all(envs.contacts_between(self.env, gs, bg) for gs in self._finger_geoms.values())
|
| 151 |
+
|
| 152 |
+
def holding(self, obj_name):
|
| 153 |
+
"""The agent harness reports `holding_object` through this; same finger-contact test as the outcome."""
|
| 154 |
+
if obj_name == BAR:
|
| 155 |
+
return self.holding_bar()
|
| 156 |
+
return super().holding(obj_name)
|
| 157 |
+
|
| 158 |
+
def wrap_yaw(self, yaw):
|
| 159 |
+
"""Like Skills.wrap_yaw (the gripper is symmetric under pi), but the window |yaw| <= YAW_LIMIT is applied
|
| 160 |
+
to the TRUE wrist yaw (commanded + yaw_bias): the joint-7 limit is a property of the real wrist. Without
|
| 161 |
+
this, a commanded -113 deg with yaw_bias -30 deg drives joint 7 into its limit (measured: stops at true
|
| 162 |
+
-137 deg, reported -107 deg)."""
|
| 163 |
+
cands = [yaw + k * np.pi for k in range(-3, 4)]
|
| 164 |
+
ok = [c for c in cands if abs(c + self.yaw_bias) <= self.YAW_LIMIT] or cands
|
| 165 |
+
return float(min(ok, key=lambda c: abs(c - self.yaw)))
|
| 166 |
+
|
| 167 |
+
def move_to(self, target, *args, **kwargs):
|
| 168 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 169 |
+
rep["yaw_reported_deg"] = round(float(np.degrees(self.reported_yaw())), 1)
|
| 170 |
+
return rep
|
| 171 |
+
|
| 172 |
+
def _act(self, dpos, drot, grip):
|
| 173 |
+
super()._act(dpos, drot, grip)
|
| 174 |
+
self.bar_zmax = max(self.bar_zmax, float(envs.obj_pos(self.env, BAR)[2]))
|
| 175 |
+
if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[BAR]):
|
| 176 |
+
self.bar_ref_yaw = self.bar_yaw()
|
| 177 |
+
self.bar_ref = envs.obj_pos(self.env, BAR)
|
| 178 |
+
|
| 179 |
+
def set_gripper(self, close, steps=15):
|
| 180 |
+
if close and self.grip < 0:
|
| 181 |
+
self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(),
|
| 182 |
+
bar=envs.obj_pos(self.env, BAR).tolist(), bar_ref_yaw=self.bar_ref_yaw,
|
| 183 |
+
bar_ref=np.asarray(self.bar_ref).tolist(), touching=self.touching(),
|
| 184 |
+
step=self.n_steps))
|
| 185 |
+
elif not close and self.grip > 0 and self.holding_bar():
|
| 186 |
+
self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(),
|
| 187 |
+
bar=envs.obj_pos(self.env, BAR).tolist(), bar_yaw=self.bar_yaw(),
|
| 188 |
+
step=self.n_steps))
|
| 189 |
+
rep = super().set_gripper(close, steps)
|
| 190 |
+
if close and self.events and self.events[-1]["kind"] == "close":
|
| 191 |
+
self.events[-1]["bar_yaw_after"] = self.bar_yaw()
|
| 192 |
+
return rep
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@register_task
|
| 196 |
+
class YawBias(LFFTask):
|
| 197 |
+
name = "l1_yaw_bias"
|
| 198 |
+
level = "L1"
|
| 199 |
+
category = "system_identification"
|
| 200 |
+
capabilities = ("Perceive", "Utilize")
|
| 201 |
+
protocol = "cross"
|
| 202 |
+
instruction = "Pick up the blue bar and put it into the holder."
|
| 203 |
+
instruction_indirect = "Pick up the long blue stick and drop it into the narrow grey trough so that it lies inside."
|
| 204 |
+
pick_lift_min = 0.03
|
| 205 |
+
|
| 206 |
+
# ------------------------------------------------------------ scene
|
| 207 |
+
def make_bddl(self):
|
| 208 |
+
bar = register_generated("LffYbBar", box_xml("lff_yb_bar", BAR_HALF, (0.15, 0.35, 0.85, 1.0), density=1500))
|
| 209 |
+
holder = register_generated("LffYbHolder", bin_xml("lff_yb_holder", HOLDER_IN, WALL_H, wall_t=WALL_T,
|
| 210 |
+
floor_t=FLOOR_T, rgba=(0.55, 0.56, 0.60, 1.0),
|
| 211 |
+
density=2000), free=False)
|
| 212 |
+
objs = [(BAR, bar, "bar_region", (-0.21, -0.26, -0.19, -0.24)),
|
| 213 |
+
("cream_cheese_1", "cream_cheese", "cheese_region", (-0.21, 0.24, -0.19, 0.26)),
|
| 214 |
+
("butter_1", "butter", "butter_region", (0.15, -0.26, 0.17, -0.24))]
|
| 215 |
+
fx = [(HOLDER, holder, "holder_region", (0.09, -0.01, 0.11, 0.01))]
|
| 216 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 217 |
+
|
| 218 |
+
def __init__(self, cam_res=None):
|
| 219 |
+
super().__init__(cam_res)
|
| 220 |
+
self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS}
|
| 221 |
+
m = self.env.sim.model
|
| 222 |
+
self._holder_bid = m.body_name2id(self.env.fixtures_dict[HOLDER].root_body)
|
| 223 |
+
|
| 224 |
+
def _place(self, name, xy, yaw, z0=envs.TABLE_Z):
|
| 225 |
+
q = _qmul(_q("z", yaw), self._base_quat[name])
|
| 226 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q)
|
| 227 |
+
self.env.sim.forward()
|
| 228 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 229 |
+
self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005)
|
| 230 |
+
self.env.sim.forward()
|
| 231 |
+
|
| 232 |
+
def sample_instance(self, seed):
|
| 233 |
+
rng = np.random.default_rng(seed)
|
| 234 |
+
while True:
|
| 235 |
+
b = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)])
|
| 236 |
+
h = np.array([rng.uniform(-0.14, 0.06), rng.uniform(-0.22, 0.22)])
|
| 237 |
+
if np.linalg.norm(h - b) < 0.22:
|
| 238 |
+
continue
|
| 239 |
+
placed = [b, h]
|
| 240 |
+
dis = {}
|
| 241 |
+
for name in DISTRACTORS:
|
| 242 |
+
for _ in range(300):
|
| 243 |
+
p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)])
|
| 244 |
+
if any(np.linalg.norm(p - o) < 0.15 for o in placed):
|
| 245 |
+
continue
|
| 246 |
+
if any(_seg_dist(p, a, c) < 0.10 for a, c in ((b, h), (HOME_XY, b))):
|
| 247 |
+
continue
|
| 248 |
+
break
|
| 249 |
+
else:
|
| 250 |
+
break
|
| 251 |
+
placed.append(p)
|
| 252 |
+
dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
|
| 253 |
+
if len(dis) == len(DISTRACTORS):
|
| 254 |
+
break
|
| 255 |
+
bar_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX))
|
| 256 |
+
holder_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX))
|
| 257 |
+
beta = float(rng.choice([-1.0, 1.0]) * rng.uniform(BETA_MIN, BETA_MAX))
|
| 258 |
+
return dict(seed=int(seed), bar_xy=b.round(5).tolist(), bar_yaw=bar_yaw, holder_xy=h.round(5).tolist(),
|
| 259 |
+
holder_yaw=holder_yaw, distractors=dis, yaw_bias=beta, yaw_bias_deg=float(np.degrees(beta)))
|
| 260 |
+
|
| 261 |
+
def apply_instance(self, inst):
|
| 262 |
+
m = self.env.sim.model
|
| 263 |
+
m.body_pos[self._holder_bid] = [inst["holder_xy"][0], inst["holder_xy"][1], envs.TABLE_Z + HOLDER_HALF_H]
|
| 264 |
+
m.body_quat[self._holder_bid] = _q("z", inst["holder_yaw"])
|
| 265 |
+
for name, mass in MASS.items():
|
| 266 |
+
envs.scale_mass(self.env, name, mass)
|
| 267 |
+
self.env.sim.forward()
|
| 268 |
+
self._place(BAR, inst["bar_xy"], inst["bar_yaw"])
|
| 269 |
+
envs.set_friction(self.env, BAR, BAR_MU, priority=3)
|
| 270 |
+
for name, v in inst["distractors"].items():
|
| 271 |
+
self._place(name, v["xy"], v["yaw"])
|
| 272 |
+
|
| 273 |
+
def reset_instance(self, inst, recorder=None):
|
| 274 |
+
self.env.reset()
|
| 275 |
+
self.apply_instance(inst)
|
| 276 |
+
self.env.sim.forward()
|
| 277 |
+
envs.settle(self.env, 10)
|
| 278 |
+
self.sk = YawSkills(self.env, yaw_bias=inst["yaw_bias"], recorder=recorder)
|
| 279 |
+
self.sk.hold(REHOME_STEPS) # turn the wrist to the robot's own yaw 0 (true yaw = beta)
|
| 280 |
+
self.sk.n_steps = 0
|
| 281 |
+
self.sk.events = []
|
| 282 |
+
self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS}
|
| 283 |
+
return self.sk
|
| 284 |
+
|
| 285 |
+
# ------------------------------------------------------------ outcome
|
| 286 |
+
def holder_frame(self, xy):
|
| 287 |
+
"""xy (world) -> (along, across) in the holder frame, relative to the holder centre"""
|
| 288 |
+
c = self.env.sim.model.body_pos[self._holder_bid][:2].copy()
|
| 289 |
+
a = self.holder_yaw()
|
| 290 |
+
R = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]])
|
| 291 |
+
return R @ (np.asarray(xy[:2]) - c)
|
| 292 |
+
|
| 293 |
+
def holder_yaw(self):
|
| 294 |
+
q = self.env.sim.model.body_quat[self._holder_bid]
|
| 295 |
+
return float(2 * np.arctan2(q[3], q[0]))
|
| 296 |
+
|
| 297 |
+
def in_holder(self):
|
| 298 |
+
p = envs.obj_pos(self.env, BAR)
|
| 299 |
+
u, v = self.holder_frame(p)
|
| 300 |
+
return bool(abs(u) < HOLDER_IN[0] and abs(v) < HOLDER_IN[1] and p[2] < RIM_Z
|
| 301 |
+
and envs.obj_upright_cos(self.env, BAR) > 0.95)
|
| 302 |
+
|
| 303 |
+
def outcome(self, inst):
|
| 304 |
+
envs.settle(self.env, 40)
|
| 305 |
+
sk = self.sk
|
| 306 |
+
p = envs.obj_pos(self.env, BAR)
|
| 307 |
+
held = sk.holding_bar()
|
| 308 |
+
success = bool(self.in_holder() and not held)
|
| 309 |
+
picked = sk.bar_zmax > sk.bar_z0 + self.pick_lift_min
|
| 310 |
+
closes = [e for e in sk.events if e["kind"] == "close"]
|
| 311 |
+
last_close = closes[-1] if closes else None
|
| 312 |
+
releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
|
| 313 |
+
hy = self.holder_yaw()
|
| 314 |
+
end_mis = wrap_half(sk.bar_yaw() - hy)
|
| 315 |
+
hc = self.env.sim.model.body_pos[self._holder_bid][:2]
|
| 316 |
+
out = dict(success=success, picked=bool(picked), held_at_end=bool(held), bar_end=p.round(4).tolist(),
|
| 317 |
+
bar_end_misalign_deg=round(float(np.degrees(end_mis)), 1), grasp_misalign=None,
|
| 318 |
+
bar_turned_in_grasp=None, release_misalign=None, release_offset=None, touched_at_close=None)
|
| 319 |
+
grasp_txt = ""
|
| 320 |
+
if last_close is not None:
|
| 321 |
+
gm = wrap_half(last_close["true_yaw"] - last_close["bar_ref_yaw"])
|
| 322 |
+
turned = wrap_half(last_close.get("bar_yaw_after", last_close["bar_ref_yaw"]) - last_close["bar_ref_yaw"])
|
| 323 |
+
out["grasp_misalign"] = round(gm, 4)
|
| 324 |
+
out["bar_turned_in_grasp"] = round(turned, 4)
|
| 325 |
+
out["touched_at_close"] = last_close["touching"]
|
| 326 |
+
go = np.array(last_close["eef"][:2]) - np.array(last_close.get("bar_ref", last_close["bar"])[:2])
|
| 327 |
+
a = last_close["bar_ref_yaw"]
|
| 328 |
+
along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)]
|
| 329 |
+
over_bar = bool(abs(along) <= BAR_HALF[0] and abs(across) <= BAR_HALF[1] + 0.02)
|
| 330 |
+
out["grasp_xy_offset"] = go.round(4).tolist()
|
| 331 |
+
out["grasp_over_bar"] = over_bar
|
| 332 |
+
if over_bar:
|
| 333 |
+
grasp_txt = f"When the jaws closed on the blue bar, they were {rot_words(gm)} from square across the bar"
|
| 334 |
+
if np.linalg.norm(go) >= 0.015:
|
| 335 |
+
grasp_txt += f" (the grasp point was {dir_words(*go)} of the bar's centre)"
|
| 336 |
+
else:
|
| 337 |
+
grasp_txt = (f"When the jaws closed, the grasp point was {dir_words(*go)} of the blue bar's centre, i.e. "
|
| 338 |
+
f"not over the bar, and the jaws were {rot_words(gm)} from square across the bar")
|
| 339 |
+
if abs(np.degrees(turned)) >= 2:
|
| 340 |
+
grasp_txt += f", and the closing fingers turned the bar by {abs(np.degrees(turned)):.0f} deg"
|
| 341 |
+
if releases:
|
| 342 |
+
r = releases[-1]
|
| 343 |
+
rm = wrap_half(r["bar_yaw"] - hy)
|
| 344 |
+
out["release_misalign"] = round(rm, 4)
|
| 345 |
+
out["release_offset"] = (np.array(r["bar"][:2]) - hc).round(4).tolist()
|
| 346 |
+
if success:
|
| 347 |
+
out["failure"] = None
|
| 348 |
+
detail = "The blue bar is inside the holder."
|
| 349 |
+
if out["release_misalign"] is not None:
|
| 350 |
+
detail += (f" When the gripper opened, the bar's long axis was {rot_words(out['release_misalign'])} "
|
| 351 |
+
f"from the holder's long axis.")
|
| 352 |
+
elif not picked:
|
| 353 |
+
out["failure"] = "missed_grasp"
|
| 354 |
+
if last_close is None:
|
| 355 |
+
detail = "The gripper never closed; the blue bar was not picked up."
|
| 356 |
+
else:
|
| 357 |
+
detail = f"{grasp_txt}, but the bar was not picked up. It is still on the table."
|
| 358 |
+
elif held:
|
| 359 |
+
out["failure"] = "not_released"
|
| 360 |
+
detail = f"{grasp_txt}. The bar was picked up but it is still in the gripper."
|
| 361 |
+
elif releases:
|
| 362 |
+
out["failure"] = "missed_place"
|
| 363 |
+
if p[2] > RIM_Z - 0.002:
|
| 364 |
+
where = (f"The bar came down across the holder's walls instead of dropping in; it is now lying on top "
|
| 365 |
+
f"of the holder, its long axis {rot_words(end_mis)} from the holder's long axis.")
|
| 366 |
+
else:
|
| 367 |
+
where = (f"The bar did not end up inside the holder (its centre is now "
|
| 368 |
+
f"{dir_words(*(p[:2] - hc))} of the holder's centre).")
|
| 369 |
+
detail = (f"{grasp_txt}. When the gripper opened above the holder, the bar's long axis was "
|
| 370 |
+
f"{rot_words(out['release_misalign'])} from the holder's long axis, and the bar's centre was "
|
| 371 |
+
f"{dir_words(*out['release_offset'])} of the holder's centre. {where}")
|
| 372 |
+
else:
|
| 373 |
+
out["failure"] = "dropped"
|
| 374 |
+
detail = (f"{grasp_txt}. The bar was lifted but slipped out of the fingers before the gripper opened; it is "
|
| 375 |
+
f"now {dir_words(*(p[:2] - hc))} of the holder's centre.")
|
| 376 |
+
out["detail"] = detail
|
| 377 |
+
ind = detail
|
| 378 |
+
for k in sorted(NAMES, key=lambda n: -len(NAMES[n])):
|
| 379 |
+
ind = ind.replace(NAMES[k], DESCR[k])
|
| 380 |
+
ind = re.sub(r"\bbar\b", "stick", ind) # the bare noun would give the direct name away
|
| 381 |
+
out["detail_indirect"] = ind
|
| 382 |
+
return out
|
| 383 |
+
|
| 384 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 385 |
+
if indirect and level == "F2":
|
| 386 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 387 |
+
return super().feedback(inst, out, level)
|
| 388 |
+
|
| 389 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 390 |
+
def execute(self, inst, params):
|
| 391 |
+
"""Top-down pick square across the bar at its centre, carry, line the bar up with the holder and release it
|
| 392 |
+
just above the holder's rim. params['dyaw'] (rad) is the policy's own yaw correction, added to every
|
| 393 |
+
commanded yaw."""
|
| 394 |
+
sk = self.sk
|
| 395 |
+
dy = float(params.get("dyaw", 0.0))
|
| 396 |
+
b = envs.obj_pos(self.env, BAR) # perfect perception of the current scene
|
| 397 |
+
psi = sk.bar_yaw()
|
| 398 |
+
hc = self.env.sim.model.body_pos[self._holder_bid][:2].copy()
|
| 399 |
+
phi = self.holder_yaw()
|
| 400 |
+
z_grasp = envs.TABLE_Z + SITE_ABOVE_TABLE
|
| 401 |
+
z_rel = RIM_Z + RELEASE_GAP + SITE_ABOVE_TABLE
|
| 402 |
+
sk.set_gripper(False, steps=8)
|
| 403 |
+
sk.move_to([b[0], b[1], Z_CARRY], yaw=wrap_half(psi) + dy)
|
| 404 |
+
sk.move_to([b[0], b[1], z_grasp + 0.06], tol=0.002)
|
| 405 |
+
sk.move_to([b[0], b[1], z_grasp], tol=0.003, max_steps=80)
|
| 406 |
+
sk.set_gripper(True, steps=15)
|
| 407 |
+
sk.move_to([b[0], b[1], Z_CARRY], speed=0.3)
|
| 408 |
+
if not sk.holding_bar(): # missed: a real controller sees the jaws closed on nothing and stops
|
| 409 |
+
return
|
| 410 |
+
sk.move_to([hc[0], hc[1], Z_CARRY], yaw=wrap_half(phi) + dy, tol=0.003)
|
| 411 |
+
sk.move_to([hc[0], hc[1], z_rel], tol=0.003, max_steps=100)
|
| 412 |
+
sk.hold(5)
|
| 413 |
+
sk.set_gripper(False, steps=12)
|
| 414 |
+
sk.move_to([hc[0], hc[1], Z_CARRY], speed=0.3)
|
| 415 |
+
|
| 416 |
+
def default_params(self, inst):
|
| 417 |
+
return dict(dyaw=0.0)
|
| 418 |
+
|
| 419 |
+
def oracle_params(self, inst):
|
| 420 |
+
return dict(dyaw=-float(inst["yaw_bias"]))
|
| 421 |
+
|
| 422 |
+
def adapt_params(self, inst, history):
|
| 423 |
+
"""Scripted F2 learner: the reported angle between the bar and the holder when the gripper opened is the
|
| 424 |
+
part of the wrist offset not yet corrected; accumulate it into the correction subtracted from every
|
| 425 |
+
commanded yaw. If the bar was never released, use the jaw angle at the grasp instead."""
|
| 426 |
+
last = history[-1]
|
| 427 |
+
dy = float(last["params"]["dyaw"])
|
| 428 |
+
o = last["outcome"]
|
| 429 |
+
if o.get("release_misalign") is not None:
|
| 430 |
+
dy -= o["release_misalign"]
|
| 431 |
+
elif o.get("grasp_misalign") is not None:
|
| 432 |
+
dy -= o["grasp_misalign"]
|
| 433 |
+
return dict(dyaw=round(dy, 4))
|
| 434 |
+
|
| 435 |
+
blind_sigma = np.deg2rad(4.0)
|
| 436 |
+
|
| 437 |
+
def blind_params(self, inst, attempt, rng):
|
| 438 |
+
"""Retry the same plan with a small random perturbation of the commanded yaws; no use of history."""
|
| 439 |
+
return dict(dyaw=round(float(rng.normal(0.0, self.blind_sigma)), 4))
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l2_knock.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
| 1 |
+
"""L2-A knock_restore: move the ketchup from the tray into the basket; everything else must stay on the tray.
|
| 2 |
+
|
| 3 |
+
Constructed L2 event: the first time the ketchup is lifted off the tray (grasped and raised 3 cm), one of
|
| 4 |
+
its two neighbours on the tray is "knocked" off the tray and lands upright on the table beside it. Which
|
| 5 |
+
neighbour and to which side of the tray (left / right in the camera image) it falls are hidden per-instance
|
| 6 |
+
variables; only the scene *after* the failure shows which item is missing and where it is. The main task itself still succeeds, so an agent that stops after
|
| 7 |
+
the main task fails; it has to notice the side effect and put the item back (within-episode recovery).
|
| 8 |
+
|
| 9 |
+
Protocols
|
| 10 |
+
within (default, `l2_knock_restore`) one episode; attempt 1 = the main task, every later attempt is one
|
| 11 |
+
corrective round chosen by the policy; the outcome (success + F2 text) is computed after each round.
|
| 12 |
+
cross (`l2_knock_restore_cross`) reset to the same instance between attempts; the knock happens again
|
| 13 |
+
on every attempt, so a learner must anticipate it. Validated strategy: restore the reported item
|
| 14 |
+
right after the main task. The rule also allows prevention (the knock only hits a neighbour that is
|
| 15 |
+
still within 12 cm of the ketchup's start spot), but picking a neighbour up in place is mostly blocked
|
| 16 |
+
by the tray's end wall (Panda hand), so prevention is not a validated strategy (see the task card).
|
| 17 |
+
"""
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from .. import envs
|
| 21 |
+
from ..bddl import write_bddl
|
| 22 |
+
from ..skills import Skills
|
| 23 |
+
from ..task_base import LFFTask, register_task
|
| 24 |
+
|
| 25 |
+
TARGET = "ketchup_1"
|
| 26 |
+
NEIGHBOR_POOL = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
|
| 27 |
+
TRAY, BASKET = "wooden_tray_1", "basket_1"
|
| 28 |
+
PARK_XY = {"cream_cheese_1": (0.0, 1.2), "butter_1": (0.2, 1.2), "chocolate_pudding_1": (-0.2, 1.2)}
|
| 29 |
+
|
| 30 |
+
# wooden_tray collision geometry in its body frame (from the LIBERO MJCF; long axis = body x)
|
| 31 |
+
TRAY_IN_X = (-0.128, 0.143)
|
| 32 |
+
TRAY_IN_Y = (-0.081, 0.072)
|
| 33 |
+
TRAY_OUT_X = (-0.142, 0.156)
|
| 34 |
+
TRAY_OUT_Y = (-0.088, 0.080)
|
| 35 |
+
TRAY_CX, TRAY_CY = 0.0075, -0.0045 # centre of the inner floor
|
| 36 |
+
TRAY_FLOOR = 0.0072 # floor top above the tray's lowest point
|
| 37 |
+
BASKET_IN = 0.060 # half size of the basket's inner floor (square, centred on the body origin)
|
| 38 |
+
BASKET_RIM = 0.150 # rim height above the basket's lowest point
|
| 39 |
+
BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
|
| 40 |
+
|
| 41 |
+
NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
|
| 42 |
+
"chocolate_pudding_1": "chocolate pudding"}
|
| 43 |
+
DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
|
| 44 |
+
"chocolate_pudding_1": "brown box"}
|
| 45 |
+
SIDES = ("left", "right") # side of the tray in the agentview image: left = world -y, right = world +y
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _qz(a):
|
| 49 |
+
return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _wrap_half(a):
|
| 53 |
+
"""wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
|
| 54 |
+
return (a + np.pi / 2) % np.pi - np.pi / 2
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class KnockSkills(Skills):
|
| 58 |
+
"""Skills with a hook called after every control step (used for the failure injection)."""
|
| 59 |
+
|
| 60 |
+
def __init__(self, env, bias=None, recorder=None, hook=None):
|
| 61 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 62 |
+
self.hook = hook
|
| 63 |
+
|
| 64 |
+
def _act(self, dpos, drot, grip):
|
| 65 |
+
super()._act(dpos, drot, grip)
|
| 66 |
+
if self.hook is not None:
|
| 67 |
+
self.hook()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@register_task
|
| 71 |
+
class KnockRestore(LFFTask):
|
| 72 |
+
name = "l2_knock_restore"
|
| 73 |
+
level = "L2"
|
| 74 |
+
category = "state_restoration"
|
| 75 |
+
capabilities = ("Perceive", "Plan")
|
| 76 |
+
protocol = "within"
|
| 77 |
+
instruction = "Move the ketchup from the tray into the basket. Everything else must stay on the tray."
|
| 78 |
+
instruction_indirect = ("Move the red bottle from the wooden tray into the wicker basket. "
|
| 79 |
+
"Everything else must stay on the tray.")
|
| 80 |
+
knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
|
| 81 |
+
knock_radius = 0.12 # only a victim still within this distance of the ketchup's start spot is knocked
|
| 82 |
+
|
| 83 |
+
def __init__(self, cam_res=None):
|
| 84 |
+
super().__init__(cam_res)
|
| 85 |
+
# upright orientations (wxyz), fixed here so the task does not depend on LIBERO's placement convention:
|
| 86 |
+
# the ketchup mesh is modelled lying down; tray / basket / boxes are upright in their mesh frame
|
| 87 |
+
# (identity => tray long axis along world x, as the TRAY_* constants assume).
|
| 88 |
+
self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
|
| 89 |
+
self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
|
| 90 |
+
self._inj = None
|
| 91 |
+
self.start = {}
|
| 92 |
+
|
| 93 |
+
# ------------------------------------------------------------ scene
|
| 94 |
+
def make_bddl(self):
|
| 95 |
+
names = [TARGET, *NEIGHBOR_POOL, TRAY, BASKET]
|
| 96 |
+
objs = []
|
| 97 |
+
for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
|
| 98 |
+
x0 = -0.30 + 0.13 * (i % 3)
|
| 99 |
+
y0 = -0.25 + 0.25 * (i // 3)
|
| 100 |
+
objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
|
| 101 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 102 |
+
|
| 103 |
+
def sample_instance(self, seed):
|
| 104 |
+
rng = np.random.default_rng(seed)
|
| 105 |
+
nb = [str(x) for x in rng.choice(NEIGHBOR_POOL, size=2, replace=False)] # [robot side, far side]
|
| 106 |
+
victim = int(rng.integers(2))
|
| 107 |
+
side = str(rng.choice(SIDES))
|
| 108 |
+
return dict(seed=int(seed),
|
| 109 |
+
tray_xy=[float(rng.uniform(-0.07, 0.01)), float(rng.uniform(-0.11, -0.08))],
|
| 110 |
+
tray_yaw=float(rng.uniform(-0.10, 0.10)),
|
| 111 |
+
basket_xy=[float(rng.uniform(-0.08, 0.02)), float(rng.uniform(0.24, 0.26))],
|
| 112 |
+
target_dx=float(rng.uniform(-0.01, 0.01)),
|
| 113 |
+
target_yaw=float(np.pi / 2 + rng.uniform(-0.2, 0.2)),
|
| 114 |
+
neighbors=nb,
|
| 115 |
+
nb_gap=[float(rng.uniform(0.066, 0.078)) for _ in range(2)],
|
| 116 |
+
nb_dy=[float(rng.uniform(-0.012, 0.012)) for _ in range(2)],
|
| 117 |
+
nb_yaw=[float(np.pi / 2 + rng.uniform(-0.15, 0.15)) for _ in range(2)],
|
| 118 |
+
# hidden variables of the injected failure
|
| 119 |
+
victim=nb[victim], side=side,
|
| 120 |
+
land_gap=float(rng.uniform(0.015, 0.035 if side == "right" else 0.04)), # wall -> object
|
| 121 |
+
land_off=float(rng.uniform(-0.025, 0.025)), # along the wall, from the victim's spot
|
| 122 |
+
land_dyaw=float(rng.uniform(-0.35, 0.35)))
|
| 123 |
+
|
| 124 |
+
def _tray_frame(self):
|
| 125 |
+
p = envs.obj_pos(self.env, TRAY)
|
| 126 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, TRAY)].reshape(3, 3)
|
| 127 |
+
return p, R
|
| 128 |
+
|
| 129 |
+
def tray_yaw(self):
|
| 130 |
+
_, R = self._tray_frame()
|
| 131 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 132 |
+
|
| 133 |
+
def tray_to_world(self, lx, ly):
|
| 134 |
+
p, R = self._tray_frame()
|
| 135 |
+
return p[:2] + R[:2, :2] @ np.array([lx, ly])
|
| 136 |
+
|
| 137 |
+
def world_to_tray(self, xy):
|
| 138 |
+
p, R = self._tray_frame()
|
| 139 |
+
return R[:2, :2].T @ (np.asarray(xy[:2]) - p[:2])
|
| 140 |
+
|
| 141 |
+
def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
|
| 142 |
+
"""Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z."""
|
| 143 |
+
q = envs._quat_mul(_qz(yaw), self.q_up[name])
|
| 144 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
|
| 145 |
+
self.env.sim.forward()
|
| 146 |
+
dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
|
| 147 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 148 |
+
self.env.sim.data.qpos[qa + 2] -= dz
|
| 149 |
+
self.env.sim.forward()
|
| 150 |
+
|
| 151 |
+
def apply_instance(self, inst):
|
| 152 |
+
env = self.env
|
| 153 |
+
envs.scale_mass(env, TRAY, 2.0) # heavy enough not to be dragged around by the gripper
|
| 154 |
+
envs.scale_mass(env, BASKET, 2.0)
|
| 155 |
+
for n in NEIGHBOR_POOL:
|
| 156 |
+
if n not in inst["neighbors"]:
|
| 157 |
+
self.place(n, PARK_XY[n], 0.0, surface_z=0.0) # unused neighbour: on the floor, out of view
|
| 158 |
+
self.place(TRAY, inst["tray_xy"], inst["tray_yaw"])
|
| 159 |
+
self.place(BASKET, inst["basket_xy"], 0.0)
|
| 160 |
+
floor = envs.TABLE_Z + TRAY_FLOOR
|
| 161 |
+
ty = inst["tray_yaw"]
|
| 162 |
+
cx = TRAY_CX + inst["target_dx"]
|
| 163 |
+
self.place(TARGET, self.tray_to_world(cx, TRAY_CY), ty + inst["target_yaw"], floor)
|
| 164 |
+
for i, n in enumerate(inst["neighbors"]): # in a row along the tray: [robot side, ketchup, far side]
|
| 165 |
+
lx = cx + (-1 if i == 0 else 1) * inst["nb_gap"][i]
|
| 166 |
+
self.place(n, self.tray_to_world(lx, TRAY_CY + inst["nb_dy"][i]), ty + inst["nb_yaw"][i], floor)
|
| 167 |
+
env.sim.forward()
|
| 168 |
+
|
| 169 |
+
def reset_instance(self, inst, recorder=None):
|
| 170 |
+
self.env.reset()
|
| 171 |
+
self.apply_instance(inst)
|
| 172 |
+
self.env.sim.forward()
|
| 173 |
+
envs.settle(self.env, 10)
|
| 174 |
+
self.start = {n: self.footprint(n) for n in [TARGET] + inst["neighbors"]}
|
| 175 |
+
self._inj = dict(inst=inst, done=False, knocked=False, step=None)
|
| 176 |
+
self.sk = KnockSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, hook=self._knock_hook)
|
| 177 |
+
return self.sk
|
| 178 |
+
|
| 179 |
+
# ------------------------------------------------------------ measurements
|
| 180 |
+
def footprint(self, name):
|
| 181 |
+
"""Measured pose summary of an object: AABB centre, yaw of the long horizontal axis, half sizes, z range.
|
| 182 |
+
Scripted policies use it as a stand-in for perception."""
|
| 183 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 184 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 185 |
+
best = None
|
| 186 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 187 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 188 |
+
c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
|
| 189 |
+
e = np.abs(R) @ m.geom_aabb[g, 3:]
|
| 190 |
+
lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
|
| 191 |
+
vol = float(np.prod(m.geom_aabb[g, 3:]))
|
| 192 |
+
if best is None or vol > best[0]:
|
| 193 |
+
best = (vol, R, m.geom_aabb[g, 3:])
|
| 194 |
+
_, R, half = best
|
| 195 |
+
horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
|
| 196 |
+
ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
|
| 197 |
+
return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
|
| 198 |
+
half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
|
| 199 |
+
|
| 200 |
+
def _corners_tray(self, name):
|
| 201 |
+
"""All collision-box corners of `name` in tray coordinates."""
|
| 202 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 203 |
+
pts = []
|
| 204 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 205 |
+
Rg = d.geom_xmat[g].reshape(3, 3)
|
| 206 |
+
c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
|
| 207 |
+
h = m.geom_aabb[g, 3:]
|
| 208 |
+
for sx in (-1, 1):
|
| 209 |
+
for sy in (-1, 1):
|
| 210 |
+
for sz in (-1, 1):
|
| 211 |
+
pts.append(self.world_to_tray(c + Rg @ (h * np.array([sx, sy, sz]))))
|
| 212 |
+
return np.array(pts)
|
| 213 |
+
|
| 214 |
+
# ------------------------------------------------------------ failure injection
|
| 215 |
+
def _knock_hook(self):
|
| 216 |
+
st = self._inj
|
| 217 |
+
if st is None or st["done"] or self.sk is None:
|
| 218 |
+
return
|
| 219 |
+
if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
|
| 220 |
+
return
|
| 221 |
+
if not self.sk.holding(TARGET):
|
| 222 |
+
return
|
| 223 |
+
st["done"] = True
|
| 224 |
+
inst = st["inst"]
|
| 225 |
+
vxy = np.array(self.footprint(inst["victim"])["center"][:2])
|
| 226 |
+
if np.linalg.norm(vxy - np.array(self.start[TARGET]["center"][:2])) > self.knock_radius:
|
| 227 |
+
return # the victim was moved out of the way beforehand: nothing happens
|
| 228 |
+
self.knock(inst)
|
| 229 |
+
st["knocked"] = True
|
| 230 |
+
st["step"] = self.sk.n_steps
|
| 231 |
+
|
| 232 |
+
def knock(self, inst):
|
| 233 |
+
"""Teleport the victim off the tray onto the table beside the long wall on `side`: upright, long axis
|
| 234 |
+
roughly perpendicular to the wall (so a gripper closing along the wall can pick it up), nearest point
|
| 235 |
+
`land_gap` from the wall's outer face, `land_off` along the wall from where it stood.
|
| 236 |
+
(The robot-side end of the tray was tried too: the end wall hides a flat box there from agentview.)"""
|
| 237 |
+
v, side = inst["victim"], inst["side"]
|
| 238 |
+
loc = self.world_to_tray(self.footprint(v)["center"])
|
| 239 |
+
axis, sgn = 1, (1 if side == "right" else -1)
|
| 240 |
+
wall = TRAY_OUT_Y[1] if sgn > 0 else TRAY_OUT_Y[0]
|
| 241 |
+
self.place(v, self.tray_to_world(loc[0] + inst["land_off"], wall + sgn * 0.08),
|
| 242 |
+
self.tray_yaw() + np.pi / 2 + inst["land_dyaw"])
|
| 243 |
+
pts = self._corners_tray(v)
|
| 244 |
+
near = pts[:, axis].min() if sgn > 0 else pts[:, axis].max()
|
| 245 |
+
shift = (wall + sgn * inst["land_gap"]) - near
|
| 246 |
+
_, R = self._tray_frame()
|
| 247 |
+
qa, _ = envs.free_joint_addr(self.env, v)
|
| 248 |
+
self.env.sim.data.qpos[qa:qa + 2] += R[:2, axis] * shift
|
| 249 |
+
self.env.sim.forward()
|
| 250 |
+
|
| 251 |
+
# ------------------------------------------------------------ outcome
|
| 252 |
+
def where(self, name):
|
| 253 |
+
"""Classify where an object is: 'tray', 'basket', 'gripper', 'table' or 'other'."""
|
| 254 |
+
f = self.footprint(name)
|
| 255 |
+
c = np.array(f["center"])
|
| 256 |
+
lt = self.world_to_tray(c)
|
| 257 |
+
if self.sk is not None and self.sk.holding(name) and f["zmin"] > envs.TABLE_Z + 0.02:
|
| 258 |
+
return "gripper", f
|
| 259 |
+
if (TRAY_IN_X[0] - 0.005 <= lt[0] <= TRAY_IN_X[1] + 0.005 and TRAY_IN_Y[0] - 0.005 <= lt[1] <= TRAY_IN_Y[1] + 0.005
|
| 260 |
+
and f["zmin"] > envs.obj_min_z(self.env, TRAY) + 0.002):
|
| 261 |
+
return "tray", f
|
| 262 |
+
bp = envs.obj_pos(self.env, BASKET)
|
| 263 |
+
if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM:
|
| 264 |
+
return "basket", f
|
| 265 |
+
if f["zmin"] < envs.TABLE_Z + 0.01:
|
| 266 |
+
return "table", f
|
| 267 |
+
return "other", f
|
| 268 |
+
|
| 269 |
+
def rel_to_tray(self, c):
|
| 270 |
+
"""Where a point on the table is relative to the tray, in robot-centric words (never image left/right).
|
| 271 |
+
Distances are from the tray's outer edge to the object's centre."""
|
| 272 |
+
lt = self.world_to_tray(c)
|
| 273 |
+
dy = lt[1] - TRAY_OUT_Y[1] if lt[1] > TRAY_OUT_Y[1] else (lt[1] - TRAY_OUT_Y[0] if lt[1] < TRAY_OUT_Y[0] else 0.0)
|
| 274 |
+
dx = lt[0] - TRAY_OUT_X[1] if lt[0] > TRAY_OUT_X[1] else (lt[0] - TRAY_OUT_X[0] if lt[0] < TRAY_OUT_X[0] else 0.0)
|
| 275 |
+
# robot-centric words (tray yaw is within +-0.1 rad, so tray axes ~ world axes): +y = robot's left,
|
| 276 |
+
# +x = forward (away from the robot)
|
| 277 |
+
parts = []
|
| 278 |
+
if dy:
|
| 279 |
+
parts.append(f"{100 * abs(dy):.0f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'} of the tray")
|
| 280 |
+
if dx:
|
| 281 |
+
parts.append(f"{100 * abs(dx):.0f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'} "
|
| 282 |
+
f"of the tray")
|
| 283 |
+
return " and ".join(parts) if parts else "right next to the tray"
|
| 284 |
+
|
| 285 |
+
def _describe(self, inst, loc, names):
|
| 286 |
+
t_loc = loc[TARGET][0]
|
| 287 |
+
tn = names[TARGET]
|
| 288 |
+
msgs = []
|
| 289 |
+
if t_loc != "basket":
|
| 290 |
+
msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
|
| 291 |
+
"tray": f"The {tn} is still on the tray, not in the basket.",
|
| 292 |
+
"table": f"The {tn} is on the table ({self.rel_to_tray(loc[TARGET][1]['center'])}), "
|
| 293 |
+
"not in the basket."}.get(t_loc, f"The {tn} is not in the basket."))
|
| 294 |
+
for n in inst["neighbors"]:
|
| 295 |
+
l, f = loc[n]
|
| 296 |
+
if l == "tray":
|
| 297 |
+
continue
|
| 298 |
+
msgs.append({"table": f"The {names[n]} is no longer on the tray: it is on the table "
|
| 299 |
+
f"{self.rel_to_tray(f['center'])}.",
|
| 300 |
+
"basket": f"The {names[n]} is no longer on the tray: it is in the basket.",
|
| 301 |
+
"gripper": f"The {names[n]} is no longer on the tray: it is still in the gripper."}
|
| 302 |
+
.get(l, f"The {names[n]} is no longer on the tray."))
|
| 303 |
+
if not msgs:
|
| 304 |
+
msgs.append(f"The {tn} is in the basket and everything else is on the tray.")
|
| 305 |
+
return " ".join(msgs)
|
| 306 |
+
|
| 307 |
+
def outcome(self, inst):
|
| 308 |
+
envs.settle(self.env, 30)
|
| 309 |
+
loc = {n: self.where(n) for n in [TARGET] + inst["neighbors"]}
|
| 310 |
+
off = [n for n in inst["neighbors"] if loc[n][0] != "tray"]
|
| 311 |
+
success = bool(loc[TARGET][0] == "basket" and not off)
|
| 312 |
+
return dict(success=success,
|
| 313 |
+
target_loc=loc[TARGET][0],
|
| 314 |
+
locations={n: l for n, (l, _) in loc.items()},
|
| 315 |
+
off_tray=off,
|
| 316 |
+
footprints={n: f for n, (_, f) in loc.items()},
|
| 317 |
+
knocked=bool(self._inj and self._inj["knocked"]),
|
| 318 |
+
detail=self._describe(inst, loc, NAMES),
|
| 319 |
+
detail_indirect=self._describe(inst, loc, DESCR))
|
| 320 |
+
|
| 321 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 322 |
+
"""F0: nothing, F1: success flag, F2: which item is where. `indirect` uses descriptive names."""
|
| 323 |
+
if indirect and level == "F2":
|
| 324 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 325 |
+
return super().feedback(inst, out, level)
|
| 326 |
+
|
| 327 |
+
# ------------------------------------------------------------ scripted motions
|
| 328 |
+
def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.012, fp=None,
|
| 329 |
+
travel_z=1.15):
|
| 330 |
+
"""Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
|
| 331 |
+
object bottom `clearance` above `support_z` at dest_xy. Moves between places at `travel_z` (above the
|
| 332 |
+
basket rim) so the arm does not sweep through the scene."""
|
| 333 |
+
sk = self.sk
|
| 334 |
+
f = fp or self.footprint(name)
|
| 335 |
+
c = np.array(f["center"])
|
| 336 |
+
h = f["zmax"] - f["zmin"]
|
| 337 |
+
gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
|
| 338 |
+
if name == TARGET:
|
| 339 |
+
zg = f["zmax"] - 0.035
|
| 340 |
+
else:
|
| 341 |
+
zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # fingertips reach ~1.3 cm below the grip site
|
| 342 |
+
sk.set_gripper(False, steps=6)
|
| 343 |
+
p = sk.eef_pos()
|
| 344 |
+
if p[2] < travel_z - 0.02:
|
| 345 |
+
sk.move_to([p[0], p[1], travel_z])
|
| 346 |
+
sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
|
| 347 |
+
sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
|
| 348 |
+
sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
|
| 349 |
+
sk.set_gripper(True, steps=12)
|
| 350 |
+
sk.move_to([c[0], c[1], carry_z], speed=0.3)
|
| 351 |
+
gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
|
| 352 |
+
sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
|
| 353 |
+
sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.004, speed=0.25,
|
| 354 |
+
max_steps=120)
|
| 355 |
+
sk.set_gripper(False, steps=10)
|
| 356 |
+
sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
|
| 357 |
+
|
| 358 |
+
def main_task(self, fp=None):
|
| 359 |
+
"""Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
|
| 360 |
+
b = envs.obj_pos(self.env, BASKET)
|
| 361 |
+
floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
|
| 362 |
+
self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
|
| 363 |
+
|
| 364 |
+
def restore_spot(self, name, inst):
|
| 365 |
+
"""A free spot on the tray for `name`: the ketchup's start spot or `name`'s own start spot, whichever
|
| 366 |
+
is further from everything else currently on the tray."""
|
| 367 |
+
others = [n for n in [TARGET] + inst["neighbors"] if n != name and self.where(n)[0] == "tray"]
|
| 368 |
+
best, best_d = None, -1.0
|
| 369 |
+
for cand in (TARGET, name):
|
| 370 |
+
xy = np.array(self.start[cand]["center"][:2])
|
| 371 |
+
dmin = min([np.linalg.norm(xy - np.array(self.footprint(o)["center"][:2])) for o in others] + [1.0])
|
| 372 |
+
if dmin > best_d + 0.01:
|
| 373 |
+
best, best_d = xy, dmin
|
| 374 |
+
return best
|
| 375 |
+
|
| 376 |
+
def restore(self, name, inst):
|
| 377 |
+
"""Put `name` back onto the tray (long axis across the tray, fingers closing along the tray)."""
|
| 378 |
+
xy = self.restore_spot(name, inst)
|
| 379 |
+
self.pick_place(name, xy, envs.TABLE_Z + TRAY_FLOOR, dest_yaw=self.tray_yaw() + np.pi / 2, carry_z=1.08,
|
| 380 |
+
clearance=0.013)
|
| 381 |
+
|
| 382 |
+
def do(self, actions, inst):
|
| 383 |
+
for act in actions:
|
| 384 |
+
if act[0] == "ketchup_to_basket":
|
| 385 |
+
self.main_task(fp=act[1] if len(act) > 1 else None)
|
| 386 |
+
elif act[0] == "restore":
|
| 387 |
+
self.restore(act[1], inst)
|
| 388 |
+
else:
|
| 389 |
+
raise ValueError(act)
|
| 390 |
+
|
| 391 |
+
# ------------------------------------------------------------ scripted reference policies
|
| 392 |
+
def _plan(self, kind, inst, a, history, rng):
|
| 393 |
+
"""Actions of one attempt. JSON-friendly lists: ["ketchup_to_basket"] / ["restore", name]."""
|
| 394 |
+
if kind == "naive" or (a == 0 and kind in ("adaptive", "blind")):
|
| 395 |
+
return [["ketchup_to_basket"]]
|
| 396 |
+
if kind == "oracle": # knows the victim: restores it right after the main task, without feedback
|
| 397 |
+
return [["ketchup_to_basket"], ["restore", inst["victim"]]]
|
| 398 |
+
if kind == "adaptive": # F2 says what is wrong; perception (measured pose) says where it is
|
| 399 |
+
last = history[-1]["outcome"]
|
| 400 |
+
acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
|
| 401 |
+
return acts + [["restore", n] for n in last["off_tray"]]
|
| 402 |
+
if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
|
| 403 |
+
fp = self.footprint(TARGET)
|
| 404 |
+
fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
|
| 405 |
+
return [["ketchup_to_basket", fp]]
|
| 406 |
+
raise ValueError(kind)
|
| 407 |
+
|
| 408 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 409 |
+
"""Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.
|
| 410 |
+
After every attempt the outcome (success + F2 detail) is measured; stops at success
|
| 411 |
+
(oracle / naive stop after attempt 1)."""
|
| 412 |
+
k = k or self.max_attempts
|
| 413 |
+
rng = np.random.default_rng(seed)
|
| 414 |
+
history = []
|
| 415 |
+
self.reset_instance(inst)
|
| 416 |
+
for a in range(k):
|
| 417 |
+
actions = self._plan(kind, inst, a, history, rng)
|
| 418 |
+
self.do(actions, inst)
|
| 419 |
+
out = self.outcome(inst)
|
| 420 |
+
params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
|
| 421 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 422 |
+
if on_attempt:
|
| 423 |
+
on_attempt(a, params, out)
|
| 424 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 425 |
+
break
|
| 426 |
+
return history
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
@register_task
|
| 430 |
+
class KnockRestoreCross(KnockRestore):
|
| 431 |
+
"""Cross-attempt variant: reset to the same instance before every attempt; the knock happens again each
|
| 432 |
+
time. Learned behaviour: anticipate it (restore the reported item right after the main task)."""
|
| 433 |
+
name = "l2_knock_restore_cross"
|
| 434 |
+
protocol = "cross"
|
| 435 |
+
|
| 436 |
+
def _plan(self, kind, inst, a, history, rng):
|
| 437 |
+
if kind == "adaptive" and a > 0: # remembers which item(s) fell last time; finds them by looking
|
| 438 |
+
fallen = sorted({n for h in history for n in h["outcome"]["off_tray"]})
|
| 439 |
+
return [["ketchup_to_basket"]] + [["restore", n] for n in fallen]
|
| 440 |
+
return super()._plan(kind, inst, a, history, rng)
|
| 441 |
+
|
| 442 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 443 |
+
k = k or self.max_attempts
|
| 444 |
+
rng = np.random.default_rng(seed)
|
| 445 |
+
history = []
|
| 446 |
+
for a in range(k):
|
| 447 |
+
self.reset_instance(inst)
|
| 448 |
+
actions = self._plan(kind, inst, a, history, rng)
|
| 449 |
+
self.do(actions, inst)
|
| 450 |
+
out = self.outcome(inst)
|
| 451 |
+
params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
|
| 452 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 453 |
+
if on_attempt:
|
| 454 |
+
on_attempt(a, params, out)
|
| 455 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 456 |
+
break
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L3-A wall_flush: a flat long box lies flush against a low fixed wall; put it on the plate.
|
| 2 |
+
|
| 3 |
+
Why the prior fails: the only graspable dimension of the box is its 6 cm width (the Panda opens to
|
| 4 |
+
~7.9 cm; the box is 16 cm long). Grasping across the width needs one finger between the box and the
|
| 5 |
+
wall, but the box touches the wall (gap 0-3 mm) along its whole length, so that finger lands on top of
|
| 6 |
+
the wall (4.5 cm high; the box is 3.5 cm high) and the gripper closes above the box. Retrying the same
|
| 7 |
+
grasp with small variations fails the same way.
|
| 8 |
+
|
| 9 |
+
What must be learned from the failure: this grasp is infeasible in this state -> change the manipulation
|
| 10 |
+
mode: first slide the box along the wall until it clears the wall's end (non-prehensile pre-grasp
|
| 11 |
+
manipulation), then grasp it across its width.
|
| 12 |
+
|
| 13 |
+
Layout: the wall runs along y (left-right as seen from the robot). Randomised per instance: wall length
|
| 14 |
+
(24-30 cm), wall position, whether the wall is on the far (+x) or near (-x) side of the box, where the
|
| 15 |
+
box sits along the wall (always fully alongside it, >= 2 cm of wall beyond each end), box-wall gap
|
| 16 |
+
(0-3 mm, below camera resolution), plate position (on the open side of the box).
|
| 17 |
+
|
| 18 |
+
Protocols: `l3_wall_flush` (cross: reset to the same instance before every attempt) and
|
| 19 |
+
`l3_wall_flush_within` (one episode; each attempt starts from wherever the previous one left things).
|
| 20 |
+
"""
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from .. import envs
|
| 24 |
+
from ..bddl import write_bddl
|
| 25 |
+
from ..objects import box_xml, register_generated
|
| 26 |
+
from ..skills import DT, _rot_err
|
| 27 |
+
from ..task_base import LFFTask, register_task
|
| 28 |
+
|
| 29 |
+
BOX_HALF = np.array([0.03, 0.08, 0.0175]) # 6 (x) x 16 (y) x 3.5 cm; long axis along y
|
| 30 |
+
WALL_HALF_T = 0.015 # 3 cm thick (x)
|
| 31 |
+
WALL_HALF_H = 0.0225 # 4.5 cm high
|
| 32 |
+
WALL_HALF_L_MAX = 0.16 # registered half length (y); shrunk per instance
|
| 33 |
+
WALL_MU = 2.0 # wall sliding friction (MuJoCo uses the max of the two geoms: finger-wall and box-wall contacts get 2.0)
|
| 34 |
+
BOX_DENSITY = 1500.0 # -> 0.50 kg
|
| 35 |
+
GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open
|
| 36 |
+
FINGER_NEEDS = 0.012 # free space a finger needs beside the box (pad + finger shell), measured
|
| 37 |
+
Z_GRASP = envs.TABLE_Z + 0.022 # gripper-site height for grasping (pads cover 1.7-3.4 cm above the table)
|
| 38 |
+
Z_PUSH = envs.TABLE_Z + 0.022 # site height while pushing: finger tips 1.2 cm above the table, hand ~7 mm above the wall
|
| 39 |
+
PUSH_SPEED = 0.08
|
| 40 |
+
FINGER_BELOW_SITE = 0.0096 # finger tips are this far below the gripper site (measured)
|
| 41 |
+
PLACE_Z = envs.TABLE_Z + 0.048 # site height at release over the plate (box bottom ~8 mm above the rim)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _wrap_half_pi(a):
|
| 45 |
+
"""wrap to [-pi/2, pi/2): box and parallel gripper are both symmetric under 180 deg"""
|
| 46 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _yaw_of(quat_wxyz):
|
| 50 |
+
w, x, y, z = quat_wxyz
|
| 51 |
+
return _wrap_half_pi(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@register_task
|
| 55 |
+
class WallFlush(LFFTask):
|
| 56 |
+
name = "l3_wall_flush"
|
| 57 |
+
level = "L3"
|
| 58 |
+
category = "strategy_switching"
|
| 59 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 60 |
+
protocol = "cross"
|
| 61 |
+
instruction = "Put the long box on the plate."
|
| 62 |
+
instruction_indirect = "Put the flat blue block onto the round dish."
|
| 63 |
+
|
| 64 |
+
def __init__(self, cam_res=None):
|
| 65 |
+
super().__init__(cam_res)
|
| 66 |
+
self._mon = None
|
| 67 |
+
# Per-control-step event monitor. It wraps env.step so that it also sees attempts driven by the agent
|
| 68 |
+
# harness (whose tools call Skills / env.step directly), not only the scripted `execute`.
|
| 69 |
+
orig_step = self.env.step
|
| 70 |
+
|
| 71 |
+
def step(action):
|
| 72 |
+
ret = orig_step(action)
|
| 73 |
+
if self._mon is not None:
|
| 74 |
+
self._monitor_step()
|
| 75 |
+
return ret
|
| 76 |
+
|
| 77 |
+
self.env.step = step
|
| 78 |
+
|
| 79 |
+
def reset_instance(self, inst, recorder=None):
|
| 80 |
+
self._mon = None
|
| 81 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 82 |
+
self._start_monitor()
|
| 83 |
+
return sk
|
| 84 |
+
|
| 85 |
+
# ------------------------------------------------------------ scene
|
| 86 |
+
def make_bddl(self):
|
| 87 |
+
# 0.5 kg box and a grippy wall top (mu 2): with mu 1 / 0.13 kg an *unguarded* press onto the wall top (plain
|
| 88 |
+
# move_to down, as an agent would do) let the finger slide ~5 cm off the wall and, on the wall-far side,
|
| 89 |
+
# flipped the box onto its 3.5 cm side (10/60 instances) -- an accidental, graspable state (see task card).
|
| 90 |
+
box = register_generated("LffFlushBox", box_xml("lff_flush_box", BOX_HALF, (0.12, 0.30, 0.80, 1.0),
|
| 91 |
+
density=BOX_DENSITY))
|
| 92 |
+
wall = register_generated("LffFlushWall", box_xml("lff_flush_wall", (WALL_HALF_T, WALL_HALF_L_MAX, WALL_HALF_H),
|
| 93 |
+
(0.62, 0.50, 0.36, 1.0), density=1000,
|
| 94 |
+
friction=(WALL_MU, 0.005, 0.0001)), free=False)
|
| 95 |
+
# regions only need to be valid and far apart; the layout is overridden in apply_instance
|
| 96 |
+
objs = [("box_1", box, "box_region", (-0.21, -0.26, -0.19, -0.24)),
|
| 97 |
+
("plate_1", "plate", "plate_region", (-0.01, 0.24, 0.01, 0.26))]
|
| 98 |
+
fx = [("wall_1", wall, "wall_region", (0.19, -0.01, 0.21, 0.01))]
|
| 99 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 100 |
+
|
| 101 |
+
def _wall(self):
|
| 102 |
+
"""(root body id, geom ids) of the wall fixture"""
|
| 103 |
+
if not hasattr(self, "_wall_cache"):
|
| 104 |
+
m = self.env.sim.model
|
| 105 |
+
bid = m.body_name2id(self.env.fixtures_dict["wall_1"].root_body)
|
| 106 |
+
|
| 107 |
+
def under(b):
|
| 108 |
+
while b > 0:
|
| 109 |
+
if b == bid:
|
| 110 |
+
return True
|
| 111 |
+
b = m.body_parentid[b]
|
| 112 |
+
return False
|
| 113 |
+
|
| 114 |
+
self._wall_cache = (bid, [g for g in range(m.ngeom) if under(m.geom_bodyid[g])])
|
| 115 |
+
return self._wall_cache
|
| 116 |
+
|
| 117 |
+
def sample_instance(self, seed):
|
| 118 |
+
rng = np.random.default_rng(seed)
|
| 119 |
+
side = int(rng.choice([-1, 1])) # +1: wall on the far (+x) side of the box, -1: near (-x) side
|
| 120 |
+
wall_hl = float(rng.uniform(0.12, 0.15))
|
| 121 |
+
wall_y = float(rng.uniform(-0.06, 0.06))
|
| 122 |
+
u_max = wall_hl - BOX_HALF[1] - 0.02 # >= 2 cm of wall beyond each end of the box
|
| 123 |
+
box_y = wall_y + float(rng.uniform(-u_max, u_max))
|
| 124 |
+
gap = float(rng.uniform(0.0, 0.003))
|
| 125 |
+
box_x = float(rng.uniform(-0.12, -0.04)) if side > 0 else float(rng.uniform(-0.20, -0.12))
|
| 126 |
+
wall_x = box_x + side * (WALL_HALF_T + BOX_HALF[0] + gap)
|
| 127 |
+
plate_xy = [box_x - side * float(rng.uniform(0.16, 0.18)), box_y + float(rng.uniform(-0.06, 0.06))]
|
| 128 |
+
return dict(seed=int(seed), side=side, wall_hl=wall_hl, wall_xy=[wall_x, wall_y], gap=gap,
|
| 129 |
+
box_xy=[box_x, box_y], plate_xy=plate_xy)
|
| 130 |
+
|
| 131 |
+
def apply_instance(self, inst):
|
| 132 |
+
m = self.env.sim.model
|
| 133 |
+
bid, geoms = self._wall()
|
| 134 |
+
for g in geoms: # shrink the (collision + visual) wall boxes to this instance's length
|
| 135 |
+
m.geom_size[g, 1] = inst["wall_hl"]
|
| 136 |
+
m.body_pos[bid] = [inst["wall_xy"][0], inst["wall_xy"][1], envs.TABLE_Z + WALL_HALF_H]
|
| 137 |
+
m.body_quat[bid] = [1, 0, 0, 0]
|
| 138 |
+
bx, by = inst["box_xy"]
|
| 139 |
+
envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF[2] + 0.0005])
|
| 140 |
+
self._move_keep_orientation("plate_1", inst["plate_xy"])
|
| 141 |
+
|
| 142 |
+
def _move_keep_orientation(self, name, xy, clearance=0.002):
|
| 143 |
+
"""Move a LIBERO mesh object to xy keeping the orientation LIBERO's sampler gave it at reset (that
|
| 144 |
+
orientation is the upright one; see task card), lowest collision point `clearance` above the table."""
|
| 145 |
+
qa, da = envs.free_joint_addr(self.env, name)
|
| 146 |
+
d = self.env.sim.data
|
| 147 |
+
d.qpos[qa:qa + 2] = xy
|
| 148 |
+
d.qvel[da:da + 6] = 0.0
|
| 149 |
+
self.env.sim.forward()
|
| 150 |
+
d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance)
|
| 151 |
+
self.env.sim.forward()
|
| 152 |
+
|
| 153 |
+
# ------------------------------------------------------------ perception stand-in
|
| 154 |
+
def observe(self):
|
| 155 |
+
"""What a perfect perceiver reads off the camera image: box centre / yaw, the wall's footprint and the
|
| 156 |
+
plate centre. (Not the box-wall gap: 0-3 mm is below the camera resolution.)"""
|
| 157 |
+
bid, geoms = self._wall()
|
| 158 |
+
m = self.env.sim.model
|
| 159 |
+
wx, wy = m.body_pos[bid][:2]
|
| 160 |
+
hl = m.geom_size[geoms[0], 1]
|
| 161 |
+
b = envs.obj_pos(self.env, "box_1")
|
| 162 |
+
return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")),
|
| 163 |
+
wall_x=float(wx), wall_y=(float(wy - hl), float(wy + hl)),
|
| 164 |
+
plate_xy=envs.obj_pos(self.env, "plate_1")[:2].copy())
|
| 165 |
+
|
| 166 |
+
def _gap_now(self, o=None):
|
| 167 |
+
o = o or self.observe()
|
| 168 |
+
return float(abs(o["box_xy"][0] - o["wall_x"]) - WALL_HALF_T - BOX_HALF[0])
|
| 169 |
+
|
| 170 |
+
def alongside_wall(self, o=None):
|
| 171 |
+
"""box (centre) still beside the wall and too close to it for a finger"""
|
| 172 |
+
o = o or self.observe()
|
| 173 |
+
return bool(o["wall_y"][0] < o["box_xy"][1] < o["wall_y"][1] and self._gap_now(o) < FINGER_NEEDS)
|
| 174 |
+
|
| 175 |
+
# ------------------------------------------------------------ contacts
|
| 176 |
+
def _finger_landings(self):
|
| 177 |
+
"""Surfaces the finger tips are resting on: contacts between a finger and a non-robot geom whose normal is
|
| 178 |
+
mostly vertical (a tip landing on a top surface). Returns {label: contact z}, label in 'wall' | 'box' |
|
| 179 |
+
'plate' | 'table' | 'other'. Side contacts (a finger brushing the box's side, the push stroke) are ignored."""
|
| 180 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 181 |
+
if not hasattr(self, "_geom_groups"):
|
| 182 |
+
fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")}
|
| 183 |
+
robot = set(envs.robot_geom_ids(self.env))
|
| 184 |
+
self._geom_groups = (fg, robot, set(self._wall()[1]), set(envs.obj_geom_ids(self.env, "box_1")),
|
| 185 |
+
set(envs.obj_geom_ids(self.env, "plate_1")))
|
| 186 |
+
fg, robot, wall, box, plate = self._geom_groups
|
| 187 |
+
out = {}
|
| 188 |
+
for i in range(d.ncon):
|
| 189 |
+
c = d.contact[i]
|
| 190 |
+
if c.geom1 in fg and c.geom2 not in robot:
|
| 191 |
+
other = c.geom2
|
| 192 |
+
elif c.geom2 in fg and c.geom1 not in robot:
|
| 193 |
+
other = c.geom1
|
| 194 |
+
else:
|
| 195 |
+
continue
|
| 196 |
+
if abs(c.frame[2]) < 0.7:
|
| 197 |
+
continue
|
| 198 |
+
if other in wall:
|
| 199 |
+
lab = "wall"
|
| 200 |
+
elif other in box:
|
| 201 |
+
lab = "box"
|
| 202 |
+
elif other in plate:
|
| 203 |
+
lab = "plate"
|
| 204 |
+
else:
|
| 205 |
+
lab = "table" if (m.geom_id2name(other) or "").startswith("table") else "other"
|
| 206 |
+
out.setdefault(lab, float(c.pos[2]))
|
| 207 |
+
return out
|
| 208 |
+
|
| 209 |
+
def _finger_landing(self):
|
| 210 |
+
hits = self._finger_landings()
|
| 211 |
+
for lab in ("wall", "box", "plate", "table", "other"):
|
| 212 |
+
if lab in hits:
|
| 213 |
+
return lab
|
| 214 |
+
return None
|
| 215 |
+
|
| 216 |
+
# ------------------------------------------------------------ event monitor (what happened in this attempt)
|
| 217 |
+
def _closing_axis(self):
|
| 218 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 219 |
+
jid = m.joint_name2id(self.env.robots[0].gripper.joints[0])
|
| 220 |
+
a = d.xaxis[jid][:2]
|
| 221 |
+
return a / max(np.linalg.norm(a), 1e-9)
|
| 222 |
+
|
| 223 |
+
def _snapshot(self, contact_z):
|
| 224 |
+
"""state at the moment a finger lands on something"""
|
| 225 |
+
o = self.observe()
|
| 226 |
+
e = self.sk.eef_pos() if self.sk is not None else self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id]
|
| 227 |
+
bx = self.env.sim.data.body_xmat[envs.body_id(self.env, "box_1")].reshape(3, 3)[:2, 0] # box short axis
|
| 228 |
+
cosang = abs(float(self._closing_axis() @ (bx / max(np.linalg.norm(bx), 1e-9))))
|
| 229 |
+
yaw_err = float(np.arccos(np.clip(cosang, 0.0, 1.0)))
|
| 230 |
+
wy0, wy1 = o["wall_y"]
|
| 231 |
+
return dict(contact_z=float(contact_z - envs.TABLE_Z), eef=[float(e[0]), float(e[1]), float(e[2])],
|
| 232 |
+
box_xy=[float(o["box_xy"][0]), float(o["box_xy"][1])], gap=self._gap_now(o),
|
| 233 |
+
alongside=self.alongside_wall(o), yaw_err=yaw_err,
|
| 234 |
+
span=float(2 * (BOX_HALF[0] * np.cos(yaw_err) + BOX_HALF[1] * np.sin(yaw_err))),
|
| 235 |
+
box_offset=float(np.linalg.norm(np.array(e[:2]) - o["box_xy"])),
|
| 236 |
+
# signed wall length beside the gripper towards each end (< 0: gripper is past that end)
|
| 237 |
+
wall_left={1: float(wy1 - e[1]), -1: float(e[1] - wy0)})
|
| 238 |
+
|
| 239 |
+
def _start_monitor(self):
|
| 240 |
+
b = envs.obj_pos(self.env, "box_1")
|
| 241 |
+
self._mon = dict(start_xy=b[:2].copy(), rest_z=float(b[2]), max_dz=0.0, wall_hit=None, box_top_hit=None,
|
| 242 |
+
prev=set())
|
| 243 |
+
|
| 244 |
+
def _monitor_step(self):
|
| 245 |
+
mon = self._mon
|
| 246 |
+
hits = self._finger_landings()
|
| 247 |
+
mon["max_dz"] = max(mon["max_dz"], float(envs.obj_pos(self.env, "box_1")[2] - mon["rest_z"]))
|
| 248 |
+
for lab, key in (("wall", "wall_hit"), ("box", "box_top_hit")):
|
| 249 |
+
if lab in hits and lab not in mon["prev"]: # onset of a landing; keep the latest one
|
| 250 |
+
mon[key] = self._snapshot(hits[lab])
|
| 251 |
+
mon["prev"] = set(hits)
|
| 252 |
+
|
| 253 |
+
def _finger_front(self, direction):
|
| 254 |
+
"""how far the (closed) fingers stick out from the gripper site along `direction` (xy unit vector)"""
|
| 255 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 256 |
+
e = self.sk.eef_pos()
|
| 257 |
+
best = 0.0
|
| 258 |
+
for g in range(m.ngeom):
|
| 259 |
+
if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7:
|
| 260 |
+
continue
|
| 261 |
+
mid = m.geom_dataid[g]
|
| 262 |
+
v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]]
|
| 263 |
+
w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e
|
| 264 |
+
best = max(best, float((w[:, :2] @ direction).max()))
|
| 265 |
+
return best
|
| 266 |
+
|
| 267 |
+
# ------------------------------------------------------------ primitives used by the scripted policies
|
| 268 |
+
def _yaw_near(self, yaw):
|
| 269 |
+
"""The parallel gripper (and the box) are symmetric under 180 deg, so pick yaw + k*pi closest to the current
|
| 270 |
+
commanded yaw: the OSC's axis-angle error is ill-defined at 180 deg and a half-turn request can flip the
|
| 271 |
+
hand over (measured: in the within protocol it twisted the arm into a state it never recovered from)."""
|
| 272 |
+
cands = [yaw + k * np.pi for k in (-1, 0, 1)]
|
| 273 |
+
cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands
|
| 274 |
+
return float(min(cands, key=lambda c: abs(c - self.sk.yaw)))
|
| 275 |
+
|
| 276 |
+
def _align(self, tol=0.03, max_steps=60):
|
| 277 |
+
"""Skills.move_to stops on position only; hold until the commanded yaw has actually been reached."""
|
| 278 |
+
sk = self.sk
|
| 279 |
+
for _ in range(max_steps):
|
| 280 |
+
R = sk._R() @ sk.eef_mat().T
|
| 281 |
+
if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol:
|
| 282 |
+
break
|
| 283 |
+
sk.hold(1)
|
| 284 |
+
|
| 285 |
+
def _guarded_descent(self, xyz, speed=0.12, max_steps=60):
|
| 286 |
+
"""Straight-line descent that stops as soon as a finger lands on a surface above the target (the way a
|
| 287 |
+
grasp approach with contact sensing behaves). Without it, the OSC keeps pressing the finger into the
|
| 288 |
+
wall top and the compliant arm slides ~2 cm sideways off it. Returns what the finger landed on."""
|
| 289 |
+
sk = self.sk
|
| 290 |
+
p0 = sk.eef_pos()
|
| 291 |
+
tgt = np.asarray(xyz, float) + sk.bias
|
| 292 |
+
dist = max(np.linalg.norm(tgt - p0), 1e-6)
|
| 293 |
+
R = sk._R()
|
| 294 |
+
landed = None
|
| 295 |
+
for k in range(max_steps):
|
| 296 |
+
ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist)
|
| 297 |
+
sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 298 |
+
hit = self._finger_landing()
|
| 299 |
+
if hit is not None and sk.eef_pos()[2] > tgt[2] + 0.005:
|
| 300 |
+
landed = hit
|
| 301 |
+
break
|
| 302 |
+
if np.linalg.norm(tgt - sk.eef_pos()) < 0.003:
|
| 303 |
+
break
|
| 304 |
+
sk.hold(4)
|
| 305 |
+
return landed
|
| 306 |
+
|
| 307 |
+
def push_along_wall(self, end, margin):
|
| 308 |
+
"""Closed gripper (fingers side by side across the box) behind the box's trailing end face; slide the
|
| 309 |
+
box along y (towards the wall's +y end if end=+1, -y end if end=-1) until the box centre is `margin`
|
| 310 |
+
beyond that end of the wall."""
|
| 311 |
+
sk, o = self.sk, self.observe()
|
| 312 |
+
bx, by = o["box_xy"]
|
| 313 |
+
wall_end = o["wall_y"][1] if end > 0 else o["wall_y"][0]
|
| 314 |
+
dist = float(np.clip(end * (wall_end + end * margin - by), 0.0, 0.32))
|
| 315 |
+
yaw = self._yaw_near(o["box_yaw"] + np.pi / 2) # fingers close along the box's short axis
|
| 316 |
+
u = np.array([0.0, float(end)])
|
| 317 |
+
sk.set_gripper(True, steps=6)
|
| 318 |
+
sk.move_to([bx, by - end * (BOX_HALF[1] + 0.06), Z_PUSH + 0.10], yaw=yaw)
|
| 319 |
+
self._align()
|
| 320 |
+
front = self._finger_front(u)
|
| 321 |
+
face = by - end * BOX_HALF[1]
|
| 322 |
+
start_y = face - end * (front + 0.035)
|
| 323 |
+
stop_y = face + end * (dist - front)
|
| 324 |
+
sk.move_to([bx, start_y, Z_PUSH + 0.10])
|
| 325 |
+
sk.move_to([bx, start_y, Z_PUSH], tol=0.003)
|
| 326 |
+
sk.move_to([bx, stop_y, Z_PUSH], speed=PUSH_SPEED, tol=0.005, max_steps=300)
|
| 327 |
+
sk.hold(3)
|
| 328 |
+
sk.move_to([bx, stop_y, Z_PUSH + 0.10], speed=0.2)
|
| 329 |
+
|
| 330 |
+
def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0):
|
| 331 |
+
"""Top-down grasp across the box's width at the observed box centre (+ offsets), lift; if the box is
|
| 332 |
+
held, carry it to the plate and release it there."""
|
| 333 |
+
sk, o = self.sk, self.observe()
|
| 334 |
+
gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy
|
| 335 |
+
yaw = self._yaw_near(o["box_yaw"] + np.pi / 2 + dyaw)
|
| 336 |
+
sk.set_gripper(False, steps=8)
|
| 337 |
+
sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw)
|
| 338 |
+
self._align()
|
| 339 |
+
self._guarded_descent([gx, gy, Z_GRASP])
|
| 340 |
+
sk.set_gripper(True, steps=15)
|
| 341 |
+
z0 = envs.obj_pos(self.env, "box_1")[2]
|
| 342 |
+
sk.move_to([gx, gy, Z_GRASP + 0.15], speed=0.25)
|
| 343 |
+
if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.08):
|
| 344 |
+
sk.set_gripper(False, steps=8)
|
| 345 |
+
return
|
| 346 |
+
px, py = o["plate_xy"]
|
| 347 |
+
sk.move_to([px, py, PLACE_Z + 0.10])
|
| 348 |
+
sk.move_to([px, py, PLACE_Z], tol=0.004)
|
| 349 |
+
sk.set_gripper(False, steps=12)
|
| 350 |
+
sk.move_to([px, py, PLACE_Z + 0.10])
|
| 351 |
+
|
| 352 |
+
def execute(self, inst, params):
|
| 353 |
+
if params["mode"] == "push_grasp":
|
| 354 |
+
self.push_along_wall(params["end"], params["margin"])
|
| 355 |
+
self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0))
|
| 356 |
+
|
| 357 |
+
# ------------------------------------------------------------ outcome / F2 feedback
|
| 358 |
+
def outcome(self, inst):
|
| 359 |
+
"""Success = box resting flat on the plate, released. The F2 text is built from the event monitor, so it
|
| 360 |
+
describes agent-driven attempts as well as scripted ones. Ends the current monitoring segment."""
|
| 361 |
+
envs.settle(self.env, 30)
|
| 362 |
+
env, mon = self.env, self._mon or {}
|
| 363 |
+
b = envs.obj_pos(env, "box_1")
|
| 364 |
+
p = envs.obj_pos(env, "plate_1")
|
| 365 |
+
dxy = float(np.linalg.norm(b[:2] - p[:2]))
|
| 366 |
+
flat = abs(envs.obj_upright_cos(env, "box_1")) > 0.9
|
| 367 |
+
held = bool(self.sk.holding("box_1")) if self.sk is not None else False
|
| 368 |
+
on_plate = envs.contacts_between(env, envs.obj_geom_ids(env, "box_1"), envs.obj_geom_ids(env, "plate_1"))
|
| 369 |
+
success = bool(dxy < 0.05 and envs.obj_min_z(env, "box_1") > envs.TABLE_Z + 0.004 and flat and not held
|
| 370 |
+
and on_plate)
|
| 371 |
+
lifted = mon.get("max_dz", 0.0) > 0.03
|
| 372 |
+
start = mon.get("start_xy", b[:2])
|
| 373 |
+
moved_y = float(b[1] - start[1])
|
| 374 |
+
pushed = (not lifted) and abs(moved_y) > 0.02
|
| 375 |
+
wall_hit, top_hit = mon.get("wall_hit"), mon.get("box_top_hit")
|
| 376 |
+
side_txt = "far (+x)" if inst["side"] > 0 else "near (-x)"
|
| 377 |
+
mode, parts, wall_left = "success", [], None
|
| 378 |
+
if success:
|
| 379 |
+
parts.append("The box is resting on the plate.")
|
| 380 |
+
else:
|
| 381 |
+
if pushed:
|
| 382 |
+
parts.append(f"The box was pushed {100 * abs(moved_y):.1f} cm along the wall (towards "
|
| 383 |
+
f"{'+y' if moved_y > 0 else '-y'}).")
|
| 384 |
+
if lifted:
|
| 385 |
+
if held:
|
| 386 |
+
mode = "still_held"
|
| 387 |
+
parts.append("The box is still in the gripper; it was not released on the plate.")
|
| 388 |
+
elif on_plate:
|
| 389 |
+
mode = "placed_off"
|
| 390 |
+
parts.append(f"The box was put on the plate but is not resting on it properly ({100 * dxy:.1f} cm "
|
| 391 |
+
f"from the plate centre{'' if flat else ', tilted'}).")
|
| 392 |
+
else:
|
| 393 |
+
mode = "placed_off"
|
| 394 |
+
parts.append(f"The box was lifted but ended on the table, {100 * dxy:.1f} cm from the plate "
|
| 395 |
+
f"centre.")
|
| 396 |
+
elif wall_hit is not None:
|
| 397 |
+
mode = "wall_blocked"
|
| 398 |
+
parts.append(
|
| 399 |
+
f"The gripper could not get around the box: the finger on the wall side ({side_txt} side) came down "
|
| 400 |
+
f"on top of the wall, {100 * wall_hit['contact_z']:.1f} cm above the table, which is higher than "
|
| 401 |
+
f"the top of the box ({200 * BOX_HALF[2]:.1f} cm), so the box was not grasped or lifted. Where the "
|
| 402 |
+
f"gripper came down, the box is flush against the wall (gap {1000 * max(wall_hit['gap'], 0):.0f} mm).")
|
| 403 |
+
if pushed:
|
| 404 |
+
e = 1 if moved_y > 0 else -1
|
| 405 |
+
wall_left = wall_hit["wall_left"][e]
|
| 406 |
+
if wall_left > 0:
|
| 407 |
+
parts.append(f"The wall still continues {100 * wall_left:.1f} cm beyond the grasp point in the "
|
| 408 |
+
f"{'+y' if e > 0 else '-y'} direction.")
|
| 409 |
+
else:
|
| 410 |
+
parts.append(f"The grasp point was only {100 * -wall_left:.1f} cm past the "
|
| 411 |
+
f"{'+y' if e > 0 else '-y'} end of the wall, so the finger still came down on it.")
|
| 412 |
+
elif top_hit is not None:
|
| 413 |
+
mode = "box_top"
|
| 414 |
+
if top_hit["yaw_err"] > np.radians(30):
|
| 415 |
+
parts.append(f"The fingers came down on top of the box: along the gripper's closing direction the "
|
| 416 |
+
f"box measures {100 * top_hit['span']:.0f} cm, more than the {100 * GRIP_OPEN:.1f} cm "
|
| 417 |
+
f"maximum opening. The box was not lifted.")
|
| 418 |
+
else:
|
| 419 |
+
parts.append(f"A finger came down on top of the box (the gripper was {100 * top_hit['box_offset']:.1f}"
|
| 420 |
+
f" cm from the box centre), so the box was not grasped or lifted.")
|
| 421 |
+
else:
|
| 422 |
+
mode = "not_lifted"
|
| 423 |
+
parts.append(f"The box was not lifted; it is {100 * dxy:.1f} cm from the plate centre.")
|
| 424 |
+
if b[2] < envs.TABLE_Z - 0.05:
|
| 425 |
+
mode = "fell_off"
|
| 426 |
+
parts.append("The box fell off the table.")
|
| 427 |
+
elif not flat and mode != "placed_off":
|
| 428 |
+
parts.append("The box is no longer lying flat.")
|
| 429 |
+
out = dict(success=success, mode=mode, plate_dist=dxy, box_xy=[float(b[0]), float(b[1])], lifted=bool(lifted),
|
| 430 |
+
pushed_y=moved_y, alongside_wall=self.alongside_wall(), wall_left=wall_left,
|
| 431 |
+
terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts))
|
| 432 |
+
self._start_monitor() # next segment (within protocol) starts here
|
| 433 |
+
return out
|
| 434 |
+
|
| 435 |
+
# ------------------------------------------------------------ scripted references
|
| 436 |
+
def _nearer_end(self):
|
| 437 |
+
o = self.observe()
|
| 438 |
+
by = o["box_xy"][1]
|
| 439 |
+
return 1 if (o["wall_y"][1] - by) < (by - o["wall_y"][0]) else -1
|
| 440 |
+
|
| 441 |
+
def default_params(self, inst):
|
| 442 |
+
return dict(mode="grasp")
|
| 443 |
+
|
| 444 |
+
def oracle_params(self, inst):
|
| 445 |
+
return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045)
|
| 446 |
+
|
| 447 |
+
def blind_params(self, inst, attempt, rng):
|
| 448 |
+
return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)),
|
| 449 |
+
dyaw=float(rng.normal(0, 0.12)))
|
| 450 |
+
|
| 451 |
+
def adapt_params(self, inst, history):
|
| 452 |
+
"""Uses the F2 measurements of the previous attempt:
|
| 453 |
+
wall_blocked / box_top on a direct grasp -> switch mode: slide the box out past the nearer wall end
|
| 454 |
+
(wall ends read off the image), then grasp;
|
| 455 |
+
wall_blocked after a push -> push further by the reported remaining wall length + 2 cm;
|
| 456 |
+
anything else (missed, dropped, ...) -> keep the strategy (the state is re-observed)."""
|
| 457 |
+
out, prm = history[-1]["outcome"], history[-1]["params"]
|
| 458 |
+
if prm["mode"] != "push_grasp":
|
| 459 |
+
if out["mode"] in ("wall_blocked", "box_top"):
|
| 460 |
+
return dict(mode="push_grasp", end=self._nearer_end(), margin=0.045)
|
| 461 |
+
return dict(prm)
|
| 462 |
+
if out["mode"] == "wall_blocked":
|
| 463 |
+
return dict(mode="push_grasp", end=prm["end"],
|
| 464 |
+
margin=float(prm["margin"] + max(out["wall_left"] or 0.0, 0.0) + 0.02))
|
| 465 |
+
return dict(prm)
|
| 466 |
+
|
| 467 |
+
# ------------------------------------------------------------ protocols
|
| 468 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 469 |
+
if self.protocol != "within":
|
| 470 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 471 |
+
k = k or self.max_attempts
|
| 472 |
+
rng = np.random.default_rng(seed)
|
| 473 |
+
history = []
|
| 474 |
+
self.reset_instance(inst)
|
| 475 |
+
for a in range(k):
|
| 476 |
+
if kind == "oracle":
|
| 477 |
+
params = self.oracle_params(inst)
|
| 478 |
+
elif kind == "naive":
|
| 479 |
+
params = self.default_params(inst)
|
| 480 |
+
elif kind == "adaptive":
|
| 481 |
+
params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history)
|
| 482 |
+
elif kind == "blind":
|
| 483 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 484 |
+
else:
|
| 485 |
+
raise ValueError(kind)
|
| 486 |
+
if params["mode"] == "push_grasp" and not self.alongside_wall():
|
| 487 |
+
params = dict(params, mode="grasp") # already pushed clear in an earlier attempt of this episode
|
| 488 |
+
self.execute(inst, params)
|
| 489 |
+
out = self.outcome(inst)
|
| 490 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 491 |
+
if on_attempt:
|
| 492 |
+
on_attempt(a, params, out)
|
| 493 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 494 |
+
break
|
| 495 |
+
return history
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
@register_task
|
| 499 |
+
class WallFlushWithin(WallFlush):
|
| 500 |
+
name = "l3_wall_flush_within"
|
| 501 |
+
protocol = "within"
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l4_fit.py
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L4-A fit_container: put the phone flat inside the one box it fits into.
|
| 2 |
+
|
| 3 |
+
v3 (2026-10-08, user review of cla2): in v2 the only hidden information was which box is big enough, and box and
|
| 4 |
+
phone sizes are visible: all 4 Sonnet runs compared the sizes in the images and chose the right box first time.
|
| 5 |
+
v3 makes the phone itself bigger than it looks: it wears clear bumper caps on both ends (collision only, nothing is
|
| 6 |
+
rendered), CAP_RANGE = 0.8-0.9 cm each, so it is 1.6-1.8 cm longer than the visible phone. The box sizes are drawn
|
| 7 |
+
against the VISIBLE phone so that the boxes that look roomiest are too short for the capped phone:
|
| 8 |
+
fit visible margin +2.8..3.2 cm along the phone's length, only +0.8..0.9 cm across (looks tight),
|
| 9 |
+
snug +1.15..1.25 cm along, +2.5..3.0 cm across: the most comfortable-looking box, too short with the caps,
|
| 10 |
+
short_wide +0.3..0.6 cm along, +3..4 cm across: the biggest box, too short with the caps,
|
| 11 |
+
narrow_long +3.5..4.0 cm along but 0.3..0.6 cm too narrow,
|
| 12 |
+
small 0.5..1.0 cm too short.
|
| 13 |
+
A phone that does not fit lies on the rim of the box (or tips in at one end), visibly not inside, although in the
|
| 14 |
+
images it looks shorter than the opening. What has to be learned from that: the phone needs more length than it
|
| 15 |
+
appears to (by about the overlap seen) -> the box with the most length to spare.
|
| 16 |
+
|
| 17 |
+
The text below is the v2 description (layout, execution, feedback) and still applies, with "phone length" read as
|
| 18 |
+
the capped length. v2 is kept in l4_fit.py.bak-20261008-height.
|
| 19 |
+
|
| 20 |
+
v2 description:
|
| 21 |
+
|
| 22 |
+
Scene: a dark "phone" (14.0 x 6.8 x 1.2 cm) lies in the front row of a 2 x 3 grid of slots; five open
|
| 23 |
+
boxes of the same colour and the same height fill the other five slots (inner sizes: see INNER_RANGES):
|
| 24 |
+
fit inner = phone + 1.0-1.5 cm in both directions (phone long side along box long side),
|
| 25 |
+
short_wide 0.5-1.5 cm too short but 3.5-5 cm wider than the phone (looks biggest),
|
| 26 |
+
narrow_long 0.5-1.5 cm too narrow but 2.5-3.5 cm longer than the phone (the longest),
|
| 27 |
+
small 0.5-1.2 cm too short and 0.3-0.6 cm too narrow (most phone-like proportions),
|
| 28 |
+
short 0.8-2.0 cm too short, as wide as the fitting box.
|
| 29 |
+
Each box is either roughly lined up with the phone's current long axis or roughly perpendicular to it
|
| 30 |
+
(+-15 deg jitter), independently with p = 0.5 -- so half of the time the fitting box needs the phone to be
|
| 31 |
+
turned by ~90 deg.
|
| 32 |
+
|
| 33 |
+
Hidden: which box fits (only careful size comparison reveals it -- the boxes look alike), and whether the
|
| 34 |
+
fitting box needs the phone rotated. Box sizes are rebuilt per instance by resizing the bin geoms in
|
| 35 |
+
sim.model, so a single env serves every instance.
|
| 36 |
+
|
| 37 |
+
Prior (naive): take the nearest box and line the phone's long side up with the box's long side (changed
|
| 38 |
+
2026-10-06 at the user's request: before, the prior kept the phone's orientation, so half of the first
|
| 39 |
+
failures were plain misalignment instead of a size mismatch). F2 feedback after a failed attempt reports where the phone ended up and by how much it is too
|
| 40 |
+
long / too wide along the box's long / short side; a learner can then rule out boxes that are not bigger
|
| 41 |
+
in that dimension and turn the phone.
|
| 42 |
+
"""
|
| 43 |
+
import numpy as np
|
| 44 |
+
|
| 45 |
+
from .. import envs
|
| 46 |
+
from ..bddl import write_bddl
|
| 47 |
+
from ..objects import _SOLID, _fmt, _wrap, bin_xml, register_generated
|
| 48 |
+
from ..skills import _rot_err
|
| 49 |
+
from ..task_base import LFFTask, register_task
|
| 50 |
+
|
| 51 |
+
# phone (local x = long axis); PL is the visible length, the caps add 2 * cap (inst["cap"]) to it
|
| 52 |
+
PL, PW, PT = 0.140, 0.068, 0.012
|
| 53 |
+
CAP_RANGE = (0.008, 0.009) # clear bumper cap length per end (hidden)
|
| 54 |
+
# boxes (local x = long axis of the opening)
|
| 55 |
+
WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.035
|
| 56 |
+
BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin is at mid height
|
| 57 |
+
RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
|
| 58 |
+
N_BOXES = 5
|
| 59 |
+
ROWS_X = (-0.30, -0.08) # back row (near the robot), front row
|
| 60 |
+
COLS_Y = (-0.22, 0.0, 0.22)
|
| 61 |
+
DROP = 0.012 # phone bottom this far above the rim when released
|
| 62 |
+
Z_CARRY = envs.TABLE_Z + 0.15
|
| 63 |
+
PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35) # out of the agentview camera's way
|
| 64 |
+
PERC_SIGMA = 0.003 # perception noise (m) of the scripted adaptive policy's box-size estimates
|
| 65 |
+
JITTER_DEG = 15.0
|
| 66 |
+
# inner size of each box kind = phone size + uniform(lo, hi) offset (m), (long side, short side).
|
| 67 |
+
# The distractors are chosen so that no coarse size heuristic finds the fitting box: the "short_wide" box has
|
| 68 |
+
# the largest area and width, "narrow_long" is the longest, "small" has the most phone-like aspect ratio.
|
| 69 |
+
# Only comparing both box dimensions with the phone's (or the F2 feedback) singles out the fitting box.
|
| 70 |
+
# v3: offsets are relative to the VISIBLE phone (PL x PW); only "fit" takes the capped phone (PL + 2 cap)
|
| 71 |
+
BOX_KINDS = ("fit", "snug", "short_wide", "narrow_long", "small")
|
| 72 |
+
INNER_RANGES = {
|
| 73 |
+
"fit": ((0.028, 0.008), (0.032, 0.009)), # +2.8..3.2 cm along, +0.8..0.9 cm across (looks the tightest)
|
| 74 |
+
"snug": ((0.0115, 0.025), (0.0125, 0.030)), # +1.15..1.25 along, +2.5..3.0 across: looks the most comfortable
|
| 75 |
+
"short_wide": ((0.003, 0.030), (0.006, 0.040)), # +0.3..0.6 along, +3..4 across: the biggest box
|
| 76 |
+
"narrow_long": ((0.035, -0.006), (0.040, -0.003)), # +3.5..4.0 along, 0.3..0.6 cm too narrow
|
| 77 |
+
"small": ((-0.010, 0.003), (-0.005, 0.006)), # 0.5..1.0 cm too short
|
| 78 |
+
}
|
| 79 |
+
VISIBLE_FIT = ("fit", "snug", "short_wide") # kinds that fit the phone as it looks (no caps)
|
| 80 |
+
BOX_RGBA = (0.70, 0.60, 0.46, 1.0)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def phone_xml(model_name):
|
| 84 |
+
hx, hy, hz = PL / 2, PW / 2, PT / 2
|
| 85 |
+
body = (0.13, 0.13, 0.15, 1.0)
|
| 86 |
+
screen = (0.02, 0.025, 0.04, 1.0)
|
| 87 |
+
g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" '
|
| 88 |
+
f'density="1500" friction="1.0 0.005 0.0001" {_SOLID} group="0" />\n'
|
| 89 |
+
f' <geom type="box" size="{_fmt((hx, hy, hz))}" rgba="{_fmt(body)}" conaffinity="0" contype="0" '
|
| 90 |
+
f'group="1" />\n'
|
| 91 |
+
f' <geom type="box" pos="0 0 {hz:.5f}" size="{_fmt((hx - 0.004, hy - 0.003, 0.0003))}" '
|
| 92 |
+
f'rgba="{_fmt(screen)}" conaffinity="0" contype="0" group="1" />')
|
| 93 |
+
# v3: clear bumper caps on both ends: collision only, fully transparent, no visual twin (nothing is rendered).
|
| 94 |
+
# Resized per instance in apply_instance (inst["cap"]).
|
| 95 |
+
c = CAP_RANGE[1]
|
| 96 |
+
for k, sx in enumerate((1, -1)):
|
| 97 |
+
g += (f'\n <geom name="{model_name}_cap{k}" type="box" pos="{_fmt((sx * (hx + c / 2), 0, 0))}" '
|
| 98 |
+
f'size="{_fmt((c / 2, hy - 0.001, hz))}" rgba="1 1 1 0" density="400" friction="1.0 0.005 0.0001" '
|
| 99 |
+
f'{_SOLID} group="0" />')
|
| 100 |
+
return _wrap(model_name, g, hz, float(np.hypot(hx + c, hy)))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def wrap_half(a):
|
| 104 |
+
"""angle modulo pi into [-pi/2, pi/2) (the phone and the boxes are 180-deg symmetric)"""
|
| 105 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def wrap_quarter(a):
|
| 109 |
+
"""angle modulo pi/2 into [-pi/4, pi/4)"""
|
| 110 |
+
return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def fits_some_yaw(a, b, clearance=0.002, length=PL):
|
| 114 |
+
"""Does the phone's footprint (length x PW) fit inside an a x b opening at any yaw (with `clearance` to spare in
|
| 115 |
+
total)?"""
|
| 116 |
+
th = np.linspace(0.0, np.pi / 2, 181)
|
| 117 |
+
e1 = length * np.cos(th) + PW * np.sin(th)
|
| 118 |
+
e2 = length * np.sin(th) + PW * np.cos(th)
|
| 119 |
+
return bool(np.any((e1 <= a - clearance) & (e2 <= b - clearance)))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _rect_corners(xy, yaw, half):
|
| 123 |
+
c, s = np.cos(yaw), np.sin(yaw)
|
| 124 |
+
R = np.array([[c, -s], [s, c]])
|
| 125 |
+
pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half)
|
| 126 |
+
return pts @ R.T + np.asarray(xy)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _rects_overlap(r1, r2):
|
| 130 |
+
"""separating-axis test for two rotated rectangles given as (xy, yaw, half)"""
|
| 131 |
+
c1, c2 = _rect_corners(*r1), _rect_corners(*r2)
|
| 132 |
+
for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2):
|
| 133 |
+
ax = np.array([np.cos(yaw), np.sin(yaw)])
|
| 134 |
+
p1, p2 = c1 @ ax, c2 @ ax
|
| 135 |
+
if p1.max() < p2.min() or p2.max() < p1.min():
|
| 136 |
+
return False
|
| 137 |
+
return True
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@register_task
|
| 141 |
+
class FitContainer(LFFTask):
|
| 142 |
+
name = "l4_fit_container"
|
| 143 |
+
level = "L4"
|
| 144 |
+
category = "geometry_inference"
|
| 145 |
+
capabilities = ("Perceive", "Reason")
|
| 146 |
+
instruction = "Put the phone flat inside a box that it fits into completely."
|
| 147 |
+
instruction_indirect = "Put the black rectangular gadget flat inside a box that it fits into completely."
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------ scene
|
| 150 |
+
def make_bddl(self):
|
| 151 |
+
phone = register_generated("LffFitPhone", phone_xml("lff_fit_phone"))
|
| 152 |
+
# one category per box (BDDL lists one object per line; same-category lines would overwrite each
|
| 153 |
+
# other). All share the same MJCF; the opening is resized per instance in apply_instance.
|
| 154 |
+
cats = [register_generated(f"LffFitBox{c}", bin_xml(f"lff_fit_box_{c.lower()}", (0.075, 0.040), WALL_H,
|
| 155 |
+
wall_t=WALL_T, floor_t=FLOOR_T, rgba=BOX_RGBA,
|
| 156 |
+
density=3000))
|
| 157 |
+
for c in "ABCDE"]
|
| 158 |
+
objs = [("phone_1", phone, "phone_region", (-0.09, -0.01, -0.07, 0.01))]
|
| 159 |
+
slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == 0.0)]
|
| 160 |
+
for i, (x, y) in enumerate(slots):
|
| 161 |
+
objs.append((f"box_{i + 1}", cats[i], f"box{i + 1}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01)))
|
| 162 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 163 |
+
|
| 164 |
+
def sample_instance(self, seed):
|
| 165 |
+
rng = np.random.default_rng(seed)
|
| 166 |
+
j = np.radians(JITTER_DEG)
|
| 167 |
+
for _ in range(500):
|
| 168 |
+
col = int(rng.integers(3))
|
| 169 |
+
phone_xy = [ROWS_X[1] + rng.uniform(-0.01, 0.01), COLS_Y[col] + rng.uniform(-0.01, 0.01)]
|
| 170 |
+
phone_yaw = float(rng.uniform(-j, j))
|
| 171 |
+
slots = [(x, y) for x in ROWS_X for y in COLS_Y if not (x == ROWS_X[1] and y == COLS_Y[col])]
|
| 172 |
+
kinds = [BOX_KINDS[k] for k in rng.permutation(N_BOXES)]
|
| 173 |
+
cap = float(rng.uniform(*CAP_RANGE))
|
| 174 |
+
boxes = []
|
| 175 |
+
for i, (kind, (x, y)) in enumerate(zip(kinds, slots)):
|
| 176 |
+
lo, hi = INNER_RANGES[kind]
|
| 177 |
+
a, b = PL + rng.uniform(lo[0], hi[0]), PW + rng.uniform(lo[1], hi[1])
|
| 178 |
+
assert (kind == "fit") == fits_some_yaw(a, b, length=PL + 2 * cap), (kind, a, b, cap)
|
| 179 |
+
assert (kind in VISIBLE_FIT) == fits_some_yaw(a, b), (kind, a, b)
|
| 180 |
+
crossed = bool(rng.random() < 0.5)
|
| 181 |
+
yaw = wrap_half(phone_yaw + (np.pi / 2 if crossed else 0.0) + rng.uniform(-j, j))
|
| 182 |
+
boxes.append(dict(name=f"box_{i + 1}", kind=kind, crossed=crossed,
|
| 183 |
+
xy=[float(x + rng.uniform(-0.01, 0.01)), float(y + rng.uniform(-0.01, 0.01))],
|
| 184 |
+
yaw=yaw, inner=[float(a), float(b)]))
|
| 185 |
+
rects = [(b["xy"], b["yaw"], (b["inner"][0] / 2 + WALL_T + 0.007, b["inner"][1] / 2 + WALL_T + 0.007))
|
| 186 |
+
for b in boxes]
|
| 187 |
+
rects.append((phone_xy, phone_yaw, (PL / 2 + 0.01, PW / 2 + 0.01)))
|
| 188 |
+
if not any(_rects_overlap(rects[p], rects[q]) for p in range(len(rects)) for q in range(p)):
|
| 189 |
+
break
|
| 190 |
+
else:
|
| 191 |
+
raise RuntimeError("could not sample a non-overlapping layout")
|
| 192 |
+
prng = np.random.default_rng(seed + 7919)
|
| 193 |
+
perc = [[float(b["inner"][0] + prng.normal(0, PERC_SIGMA)), float(b["inner"][1] + prng.normal(0, PERC_SIGMA))]
|
| 194 |
+
for b in boxes]
|
| 195 |
+
return dict(seed=int(seed), phone_xy=[float(v) for v in phone_xy], phone_yaw=phone_yaw, boxes=boxes,
|
| 196 |
+
fit=int(kinds.index("fit")), fit_crossed=boxes[kinds.index("fit")]["crossed"], cap=cap, _perc=perc)
|
| 197 |
+
|
| 198 |
+
def _reshape_box(self, name, a, b):
|
| 199 |
+
ix, iy, H = a / 2, b / 2, BOX_HALF_H
|
| 200 |
+
parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)),
|
| 201 |
+
((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
|
| 202 |
+
((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
|
| 203 |
+
((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)),
|
| 204 |
+
((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))]
|
| 205 |
+
m = self.env.sim.model
|
| 206 |
+
o = self.env.objects_dict[name]
|
| 207 |
+
for names in (o.contact_geoms, o.visual_geoms):
|
| 208 |
+
assert len(names) == len(parts), names
|
| 209 |
+
for k, n in enumerate(names):
|
| 210 |
+
g = m.geom_name2id(n)
|
| 211 |
+
pos, size = parts[k]
|
| 212 |
+
m.geom_pos[g] = pos
|
| 213 |
+
m.geom_size[g] = size
|
| 214 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 215 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 216 |
+
|
| 217 |
+
def _set_caps(self, cap):
|
| 218 |
+
"""resize the two hidden bumper caps to `cap` (m) per end"""
|
| 219 |
+
m = self.env.sim.model
|
| 220 |
+
if not hasattr(self, "_cap_ids"):
|
| 221 |
+
self._cap_ids = [g for g in envs.obj_geom_ids(self.env, "phone_1")
|
| 222 |
+
if m.geom_rgba[g][3] == 0.0 and m.geom_contype[g]]
|
| 223 |
+
assert len(self._cap_ids) == 2, self._cap_ids
|
| 224 |
+
for g in self._cap_ids:
|
| 225 |
+
sx = 1.0 if m.geom_pos[g][0] > 0 else -1.0
|
| 226 |
+
size = (cap / 2, PW / 2 - 0.001, PT / 2)
|
| 227 |
+
m.geom_pos[g] = (sx * (PL / 2 + cap / 2), 0.0, 0.0)
|
| 228 |
+
m.geom_size[g] = size
|
| 229 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 230 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 231 |
+
|
| 232 |
+
def apply_instance(self, inst):
|
| 233 |
+
# walls are moved inwards at run time, out of the compile-time per-body BVH leaf boxes, so the collision
|
| 234 |
+
# mid-phase can silently skip them (fingers / phone pass through; found on l4_nest_order 2026-10-07).
|
| 235 |
+
# Testing all geom pairs of nearby bodies is exact; the run-time geom_rbound / geom_aabb are set below.
|
| 236 |
+
import mujoco
|
| 237 |
+
self.env.sim.model._model.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
|
| 238 |
+
self._set_caps(inst["cap"])
|
| 239 |
+
for b in inst["boxes"]:
|
| 240 |
+
self._reshape_box(b["name"], *b["inner"])
|
| 241 |
+
envs.set_obj_pose(self.env, b["name"], [*b["xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005], yaw=b["yaw"])
|
| 242 |
+
envs.set_obj_pose(self.env, "phone_1", [*inst["phone_xy"], envs.TABLE_Z + PT / 2 + 0.0005],
|
| 243 |
+
yaw=inst["phone_yaw"])
|
| 244 |
+
|
| 245 |
+
# ------------------------------------------------------------ outcome
|
| 246 |
+
def _pose2d(self, name):
|
| 247 |
+
bid = envs.body_id(self.env, name)
|
| 248 |
+
R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
|
| 249 |
+
p = self.env.sim.data.body_xpos[bid].copy()
|
| 250 |
+
return p, float(np.arctan2(R[1, 0], R[0, 0])), float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1))))
|
| 251 |
+
|
| 252 |
+
def outcome(self, inst):
|
| 253 |
+
envs.settle(self.env, 40)
|
| 254 |
+
p, yaw, tilt = self._pose2d("phone_1")
|
| 255 |
+
held = bool(self.sk is not None and self.sk.holding("phone_1"))
|
| 256 |
+
# which box is the phone in / on: smallest distance of the phone centre outside a box opening
|
| 257 |
+
best = None
|
| 258 |
+
for j, b in enumerate(inst["boxes"]):
|
| 259 |
+
c, byaw, btilt = self._pose2d(b["name"])
|
| 260 |
+
d = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]]) @ (p[:2] - c[:2])
|
| 261 |
+
out = np.maximum(np.abs(d) - np.array(b["inner"]) / 2, 0.0)
|
| 262 |
+
dist = float(np.linalg.norm(out))
|
| 263 |
+
if best is None or dist < best[0]:
|
| 264 |
+
best = (dist, j, c, byaw, btilt)
|
| 265 |
+
dist, j, c, byaw, btilt = best
|
| 266 |
+
b = inst["boxes"][j]
|
| 267 |
+
a_in, b_in = b["inner"]
|
| 268 |
+
floor_top = c[2] - BOX_HALF_H + FLOOR_T
|
| 269 |
+
height = float(p[2] - PT / 2 - floor_top) # phone bottom above the box floor
|
| 270 |
+
in_opening = dist < 1e-9
|
| 271 |
+
on_floor = height < 0.004 and tilt < 5.0
|
| 272 |
+
success = bool(in_opening and on_floor and not held and btilt < 10.0)
|
| 273 |
+
where = self.box_label(inst, j) # relative description only: no absolute coordinates in feedback
|
| 274 |
+
# footprint of the phone (as it lies now) against the opening of that box
|
| 275 |
+
dl = yaw - byaw
|
| 276 |
+
cs, sn = abs(np.cos(dl)), abs(np.sin(dl))
|
| 277 |
+
L = PL + 2 * inst.get("cap", 0.0) # the capped phone
|
| 278 |
+
over_long = L * cs + PW * sn - a_in
|
| 279 |
+
over_short = L * sn + PW * cs - b_in
|
| 280 |
+
along_long = "length" if cs >= sn else "width"
|
| 281 |
+
fb = dict(box=j, box_xy=[round(float(c[0]), 2), round(float(c[1]), 2)], along_long=along_long,
|
| 282 |
+
over_long_cm=round(100 * over_long, 1) if over_long > 0.001 else None,
|
| 283 |
+
over_short_cm=round(100 * over_short, 1) if over_short > 0.001 else None)
|
| 284 |
+
res = dict(success=success, box=j, box_kind=b["kind"], height_cm=round(100 * height, 2),
|
| 285 |
+
tilt_deg=round(tilt, 1), held=held, phone_xy=[float(p[0]), float(p[1])], feedback=fb)
|
| 286 |
+
if held:
|
| 287 |
+
res["detail"] = "The phone is still in the gripper."
|
| 288 |
+
res["failure"] = "held"
|
| 289 |
+
return res
|
| 290 |
+
if dist > 0.02 or (not in_opening and p[2] < envs.TABLE_Z + PT / 2 + 0.006):
|
| 291 |
+
res["detail"] = (f"The phone is not in any box: it is lying on the table, about {100 * dist:.0f} cm "
|
| 292 |
+
f"outside the opening of {where}.")
|
| 293 |
+
res["failure"] = "table"
|
| 294 |
+
return res
|
| 295 |
+
if success:
|
| 296 |
+
res["detail"] = f"The phone is lying flat on the bottom of {where}."
|
| 297 |
+
res["failure"] = None
|
| 298 |
+
return res
|
| 299 |
+
pose_txt = ("lying flat on top of the walls" if tilt < 5.0 else
|
| 300 |
+
f"tilted about {tilt:.0f} degrees with one end down inside the box")
|
| 301 |
+
txt = f"The phone did not go in: it is resting on the walls of {where}, {pose_txt}."
|
| 302 |
+
dim_l = "long" if along_long == "length" else "wide"
|
| 303 |
+
dim_s = "wide" if along_long == "length" else "long"
|
| 304 |
+
if fb["over_long_cm"]:
|
| 305 |
+
txt += f" It is about {fb['over_long_cm']:.1f} cm too {dim_l} for that box along the box's long side."
|
| 306 |
+
if fb["over_short_cm"]:
|
| 307 |
+
txt += f" It is about {fb['over_short_cm']:.1f} cm too {dim_s} for that box along the box's short side."
|
| 308 |
+
if not fb["over_long_cm"] and not fb["over_short_cm"]:
|
| 309 |
+
txt += " Its footprint is smaller than the opening, but it was not lined up with the box and caught on the rim."
|
| 310 |
+
res["detail"] = txt
|
| 311 |
+
res["failure"] = "rim"
|
| 312 |
+
return res
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def box_label(inst, j):
|
| 316 |
+
"""Name box j by its place among the boxes in robot-centric terms (left = +y = the robot's left)."""
|
| 317 |
+
ys = [b["xy"][1] for b in inst["boxes"]]
|
| 318 |
+
xs = [b["xy"][0] for b in inst["boxes"]]
|
| 319 |
+
n = len(ys)
|
| 320 |
+
order = sorted(range(n), key=lambda i: -ys[i]) # robot's left first
|
| 321 |
+
r = order.index(j)
|
| 322 |
+
close = [i for i in range(n) if i != j and abs(ys[i] - ys[j]) < 0.04]
|
| 323 |
+
if close: # boxes side by side in y: tell them apart by distance from the robot
|
| 324 |
+
nearer = all(xs[j] < xs[i] for i in close)
|
| 325 |
+
return f"the box {'nearest to' if nearer else 'farthest from'} the robot among those at the same left-right position"
|
| 326 |
+
if r == 0:
|
| 327 |
+
return "the box furthest to the robot's left (+y)"
|
| 328 |
+
if r == n - 1:
|
| 329 |
+
return "the box furthest to the robot's right (-y)"
|
| 330 |
+
return "the middle box (between the others, left to right)"
|
| 331 |
+
|
| 332 |
+
# ------------------------------------------------------------ execution
|
| 333 |
+
def execute(self, inst, params):
|
| 334 |
+
"""params: box (index into inst['boxes']), place_yaw (world yaw of the phone's long side when released).
|
| 335 |
+
Optional (tolerance checks only): dx / dy = release offset of the phone centre from the box centre
|
| 336 |
+
along the box's long / short axis (m), drop = height of the phone bottom above the rim (m)."""
|
| 337 |
+
sk, env = self.sk, self.env
|
| 338 |
+
px, py = inst["phone_xy"]
|
| 339 |
+
zc = envs.TABLE_Z + PT / 2
|
| 340 |
+
g0 = wrap_half(inst["phone_yaw"]) # fingers close across the phone's width
|
| 341 |
+
sk.set_gripper(False, steps=5)
|
| 342 |
+
sk.move_to([px, py, zc + 0.10], yaw=g0)
|
| 343 |
+
sk.move_to([px, py, zc + 0.001], tol=0.003)
|
| 344 |
+
sk.set_gripper(True, steps=15)
|
| 345 |
+
sk.move_to([px, py, Z_CARRY], speed=0.25)
|
| 346 |
+
b = inst["boxes"][int(params["box"])]
|
| 347 |
+
c, s = np.cos(b["yaw"]), np.sin(b["yaw"])
|
| 348 |
+
dx, dy = params.get("dx", 0.0), params.get("dy", 0.0)
|
| 349 |
+
bx, by = b["xy"][0] + c * dx - s * dy, b["xy"][1] + s * dx + c * dy
|
| 350 |
+
sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(params["place_yaw"]))
|
| 351 |
+
# put the phone's centre (not the gripper's) over the box centre: compensates in-hand slip
|
| 352 |
+
off = envs.obj_pos(env, "phone_1") - sk.eef_pos()
|
| 353 |
+
drop = params.get("drop", DROP)
|
| 354 |
+
sk.move_to([bx - off[0], by - off[1], RIM_Z + max(0.05, drop + 0.01) - off[2]], tol=0.003)
|
| 355 |
+
tgt = self._servo_phone([bx, by], RIM_Z + drop)
|
| 356 |
+
sk.grip = -1.0 # open while holding the arm at a fixed target (Skills.hold re-anchors and drifts)
|
| 357 |
+
self._hold_at(tgt, 12)
|
| 358 |
+
sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10])
|
| 359 |
+
sk.move_to(list(PARK), yaw=0.0)
|
| 360 |
+
|
| 361 |
+
def _hold_at(self, target, steps):
|
| 362 |
+
sk = self.sk
|
| 363 |
+
R = sk._R()
|
| 364 |
+
for _ in range(steps):
|
| 365 |
+
sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 366 |
+
|
| 367 |
+
def _servo_phone(self, xy, z_bottom, max_steps=60, tol=0.0015):
|
| 368 |
+
"""Closed-loop: move the gripper until the held phone's centre is over xy and its bottom at z_bottom.
|
| 369 |
+
Returns the final gripper target."""
|
| 370 |
+
sk = self.sk
|
| 371 |
+
R = sk._R()
|
| 372 |
+
goal = np.array([xy[0], xy[1], z_bottom + PT / 2])
|
| 373 |
+
tgt = e_prev = sk.eef_pos()
|
| 374 |
+
for i in range(max_steps):
|
| 375 |
+
ph, e = envs.obj_pos(self.env, "phone_1"), sk.eef_pos()
|
| 376 |
+
if i >= 8 and np.linalg.norm(ph - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
|
| 377 |
+
break
|
| 378 |
+
tgt = goal - (ph - e)
|
| 379 |
+
sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
|
| 380 |
+
e_prev = e
|
| 381 |
+
return tgt
|
| 382 |
+
|
| 383 |
+
# ------------------------------------------------------------ scripted policies
|
| 384 |
+
def _naive_yaw(self, inst, j):
|
| 385 |
+
"""keep the phone's orientation, only snap it to the nearest axis of box j"""
|
| 386 |
+
p = inst["phone_yaw"]
|
| 387 |
+
return float(p + wrap_quarter(inst["boxes"][j]["yaw"] - p))
|
| 388 |
+
|
| 389 |
+
def default_params(self, inst):
|
| 390 |
+
"""v3 prior: careful size comparison against the phone as it looks (exact visible sizes: the prior models the
|
| 391 |
+
trap; perception noise is only given to the adaptive learner) -- the box with the most room to spare in its
|
| 392 |
+
tighter direction, i.e. "snug" by construction; phone's long side along the box's long side"""
|
| 393 |
+
marg = [min(b["inner"][0] - PL, b["inner"][1] - PW) for b in inst["boxes"]]
|
| 394 |
+
j = int(np.argmax(marg))
|
| 395 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 396 |
+
|
| 397 |
+
def nearest_params(self, inst):
|
| 398 |
+
"""v2 prior (kept for reference): nearest box, lined up"""
|
| 399 |
+
d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
|
| 400 |
+
j = int(np.argmin(d))
|
| 401 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 402 |
+
|
| 403 |
+
def oracle_params(self, inst):
|
| 404 |
+
j = inst["fit"]
|
| 405 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 406 |
+
|
| 407 |
+
def blind_params(self, inst, attempt, rng):
|
| 408 |
+
"""no history: a random box (may repeat), lined up like the prior"""
|
| 409 |
+
j = int(rng.integers(N_BOXES))
|
| 410 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 411 |
+
|
| 412 |
+
def naive_keep_yaw_params(self, inst):
|
| 413 |
+
"""old prior (kept for reference): nearest box, keep the phone's orientation"""
|
| 414 |
+
d = [np.hypot(b["xy"][0] - inst["phone_xy"][0], b["xy"][1] - inst["phone_xy"][1]) for b in inst["boxes"]]
|
| 415 |
+
j = int(np.argmin(d))
|
| 416 |
+
return dict(box=j, place_yaw=self._naive_yaw(inst, j))
|
| 417 |
+
|
| 418 |
+
def adapt_params(self, inst, history):
|
| 419 |
+
"""Scripted learner on F2 feedback.
|
| 420 |
+
|
| 421 |
+
Sees the boxes with noisy size estimates (inst['_perc'], sigma = PERC_SIGMA) but does not know the
|
| 422 |
+
phone's size. Each 'too long / too wide by X along the box's long / short side' message gives an
|
| 423 |
+
estimate of the phone's length or width (perceived box dimension + X). It then picks an untried box
|
| 424 |
+
that is big enough in every estimated dimension (preferring the biggest in the still-unknown one) and
|
| 425 |
+
lines the phone's long side up with the box's long side.
|
| 426 |
+
"""
|
| 427 |
+
perc = inst["_perc"]
|
| 428 |
+
L_est = W_est = None
|
| 429 |
+
tried_aligned = set()
|
| 430 |
+
for h in history:
|
| 431 |
+
o = h["outcome"]
|
| 432 |
+
fb = o.get("feedback") or {}
|
| 433 |
+
if o.get("failure") != "rim":
|
| 434 |
+
continue
|
| 435 |
+
j = fb["box"]
|
| 436 |
+
a, b = perc[j]
|
| 437 |
+
if fb["along_long"] == "length":
|
| 438 |
+
if fb["over_long_cm"] or fb["over_short_cm"]: # a size verdict on this box
|
| 439 |
+
tried_aligned.add(j)
|
| 440 |
+
if fb["over_long_cm"]:
|
| 441 |
+
L_est = max(L_est or 0.0, a + fb["over_long_cm"] / 100)
|
| 442 |
+
if fb["over_short_cm"]:
|
| 443 |
+
W_est = max(W_est or 0.0, b + fb["over_short_cm"] / 100)
|
| 444 |
+
else:
|
| 445 |
+
if fb["over_short_cm"]:
|
| 446 |
+
L_est = max(L_est or 0.0, b + fb["over_short_cm"] / 100)
|
| 447 |
+
if fb["over_long_cm"]:
|
| 448 |
+
W_est = max(W_est or 0.0, a + fb["over_long_cm"] / 100)
|
| 449 |
+
thr = 0.002
|
| 450 |
+
cands = []
|
| 451 |
+
for j, (a, b) in enumerate(perc):
|
| 452 |
+
if j in tried_aligned:
|
| 453 |
+
continue
|
| 454 |
+
mL = None if L_est is None else a - L_est
|
| 455 |
+
mW = None if W_est is None else b - W_est
|
| 456 |
+
feasible = (mL is None or mL > thr) and (mW is None or mW > thr)
|
| 457 |
+
if mL is not None and mW is not None:
|
| 458 |
+
key = min(mL, mW)
|
| 459 |
+
elif mL is not None:
|
| 460 |
+
key = b
|
| 461 |
+
elif mW is not None:
|
| 462 |
+
key = a
|
| 463 |
+
else:
|
| 464 |
+
key = a * b
|
| 465 |
+
cands.append((feasible, key, j))
|
| 466 |
+
if not cands:
|
| 467 |
+
j = int(np.argmax([a * b for a, b in perc]))
|
| 468 |
+
else:
|
| 469 |
+
j = max(cands)[2]
|
| 470 |
+
return dict(box=int(j), place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 471 |
+
|
| 472 |
+
def elim_params(self, inst, history, rng):
|
| 473 |
+
"""sensitivity variant: uses the feedback only to learn the orientation (always lines the phone up
|
| 474 |
+
after the first attempt) and to never retry a box that got a size verdict; picks among the remaining
|
| 475 |
+
boxes at random, i.e. no size reasoning / perception."""
|
| 476 |
+
bad = set()
|
| 477 |
+
for h in history:
|
| 478 |
+
fb = h["outcome"].get("feedback") or {}
|
| 479 |
+
if h["outcome"].get("failure") == "rim" and fb.get("along_long") == "length" and (
|
| 480 |
+
fb.get("over_long_cm") or fb.get("over_short_cm")):
|
| 481 |
+
bad.add(int(fb["box"]))
|
| 482 |
+
left = [j for j in range(N_BOXES) if j not in bad] or list(range(N_BOXES))
|
| 483 |
+
j = int(rng.choice(left))
|
| 484 |
+
return dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"]))
|
| 485 |
+
|
| 486 |
+
EXTRA_KINDS = ("elim",)
|
| 487 |
+
|
| 488 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 489 |
+
if kind not in self.EXTRA_KINDS:
|
| 490 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 491 |
+
k = k or self.max_attempts
|
| 492 |
+
rng = np.random.default_rng(seed)
|
| 493 |
+
history = []
|
| 494 |
+
for a in range(k):
|
| 495 |
+
self.reset_instance(inst)
|
| 496 |
+
if a == 0:
|
| 497 |
+
params = self.default_params(inst)
|
| 498 |
+
else:
|
| 499 |
+
params = self.elim_params(inst, history, rng)
|
| 500 |
+
self.execute(inst, params)
|
| 501 |
+
out = self.outcome(inst)
|
| 502 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 503 |
+
if on_attempt:
|
| 504 |
+
on_attempt(a, params, out)
|
| 505 |
+
if out["success"]:
|
| 506 |
+
break
|
| 507 |
+
return history
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
# ---------------------------------------------------------------- physical validity checks
|
| 511 |
+
def physics_check(seed0=1000, n=20, out=None):
|
| 512 |
+
"""Every (box, orientation) pair on each instance, released centred from DROP above the rim.
|
| 513 |
+
Expect success iff the box is the fitting one and the phone's long side is along the box's long side."""
|
| 514 |
+
import json
|
| 515 |
+
task = FitContainer()
|
| 516 |
+
rows = []
|
| 517 |
+
for seed in range(seed0, seed0 + n):
|
| 518 |
+
inst = task.sample_instance(seed)
|
| 519 |
+
for j, b in enumerate(inst["boxes"]):
|
| 520 |
+
for orient in ("aligned", "crossed"):
|
| 521 |
+
task.reset_instance(inst)
|
| 522 |
+
task.execute(inst, dict(box=j, place_yaw=float(b["yaw"] + (0.0 if orient == "aligned" else np.pi / 2))))
|
| 523 |
+
o = task.outcome(inst)
|
| 524 |
+
rows.append(dict(seed=seed, box=j, kind=b["kind"], inner_cm=[round(100 * v, 2) for v in b["inner"]],
|
| 525 |
+
orient=orient, success=o["success"], expect=bool(j == inst["fit"] and orient == "aligned"),
|
| 526 |
+
failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
|
| 527 |
+
r = rows[-1]
|
| 528 |
+
print(f"seed {seed} box {j} {b['kind']:6s} {orient:7s} succ={r['success']} h={r['height_cm']} "
|
| 529 |
+
f"tilt={r['tilt_deg']}" + ("" if r["success"] == r["expect"] else " <-- MISMATCH"), flush=True)
|
| 530 |
+
if out:
|
| 531 |
+
with open(out, "w") as f:
|
| 532 |
+
json.dump(rows, f, indent=1)
|
| 533 |
+
print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows))
|
| 534 |
+
return rows
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def stress_check(seed=1002, out=None):
|
| 538 |
+
"""Release errors (offset / yaw / drop height) at the edges of the size ranges: the tightest fitting box
|
| 539 |
+
(+1.0 cm in both directions) and boxes only 0.5 cm too short / too narrow."""
|
| 540 |
+
import copy
|
| 541 |
+
import json
|
| 542 |
+
task = FitContainer()
|
| 543 |
+
base = task.sample_instance(seed)
|
| 544 |
+
j = base["fit"]
|
| 545 |
+
rows = []
|
| 546 |
+
for name, a, b in [("fit_min", PL + 0.010, PW + 0.010), ("short_0.5", PL - 0.005, PW + 0.010),
|
| 547 |
+
("narrow_0.5", PL + 0.010, PW - 0.005)]:
|
| 548 |
+
for dx, dy, dyaw, drop in [(0, 0, 0, DROP), (0.004, 0, 0, DROP), (0, 0.004, 0, DROP), (0.007, 0, 0, DROP),
|
| 549 |
+
(0, 0, 3, DROP), (0, 0, 6, DROP), (0, 0, 0, 0.05), (0.004, 0.003, 3, 0.05)]:
|
| 550 |
+
inst = copy.deepcopy(base)
|
| 551 |
+
inst["boxes"][j]["inner"] = [a, b]
|
| 552 |
+
task.reset_instance(inst)
|
| 553 |
+
task.execute(inst, dict(box=j, place_yaw=float(inst["boxes"][j]["yaw"] + np.radians(dyaw)),
|
| 554 |
+
dx=dx, dy=dy, drop=drop))
|
| 555 |
+
o = task.outcome(inst)
|
| 556 |
+
rows.append(dict(case=name, inner_cm=[round(a * 100, 2), round(b * 100, 2)], dx_mm=dx * 1000,
|
| 557 |
+
dy_mm=dy * 1000, dyaw_deg=dyaw, drop_cm=drop * 100, success=o["success"],
|
| 558 |
+
height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"]))
|
| 559 |
+
print(f"{name:11s} dx={dx * 1000:.0f}mm dy={dy * 1000:.0f}mm dyaw={dyaw}deg drop={drop * 100:.1f}cm -> "
|
| 560 |
+
f"succ={o['success']} h={o['height_cm']} tilt={o['tilt_deg']} | {o['detail']}", flush=True)
|
| 561 |
+
if out:
|
| 562 |
+
with open(out, "w") as f:
|
| 563 |
+
json.dump(rows, f, indent=1)
|
| 564 |
+
return rows
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
if __name__ == "__main__":
|
| 568 |
+
# python -m lffbench.tasks.l4_fit physics results/l4_fit_container/physics_check.json
|
| 569 |
+
# python -m lffbench.tasks.l4_fit stress results/l4_fit_container/stress_check.json
|
| 570 |
+
import sys
|
| 571 |
+
if sys.argv[1] == "physics":
|
| 572 |
+
physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
|
| 573 |
+
elif sys.argv[1] == "stress":
|
| 574 |
+
stress_check(out=sys.argv[2] if len(sys.argv) > 2 else None)
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l4_nest.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 3 |
+
Scene: three open round cups (red, green, blue; 1.5 mm walls leaning outwards by TAPER_DEG = 5 deg, like slightly
|
| 4 |
+
flared tumblers) stand apart on the table. Each cup has its own bottom width and its own height (re-drawn per
|
| 5 |
+
instance, 3.5-10 cm tall). Cups are resized per instance by editing their geoms in sim.model (wall segments +
|
| 6 |
+
floor), so one env serves every instance (same technique as l4_fit_container).
|
| 7 |
+
|
| 8 |
+
Trap (common sense): "the bigger cup goes outside", and a cup looks big mostly by its height. On (1 - P_AGREE) of
|
| 9 |
+
the instances the tallest cup is the middle one by width: it is at least INV_DH = 3.5 cm taller than the widest cup.
|
| 10 |
+
Their openings then differ by only 3-9 mm in diameter, and from the wrist camera at its start height the taller
|
| 11 |
+
one's opening is closer to the camera and looks about as big (about half the instances: bigger); from the front
|
| 12 |
+
camera the taller one looks clearly bigger. The narrowest cup is the shortest, so the very first move of the naive
|
| 13 |
+
order (widest cup into the tallest one) already fails, out on the table.
|
| 14 |
+
|
| 15 |
+
A variant where the innermost cup was taller than the middle one (and the widest cup the tallest) was dropped
|
| 16 |
+
2026-10-08: its failure (middle cup on the rim of the innermost cup, both inside the outer one) looked like a nest
|
| 17 |
+
from both cameras -- the same flaw as the 14-deg version.
|
| 18 |
+
|
| 19 |
+
What the failure looks like (the point of this version, user review 2026-10-08): which cup fits into which is
|
| 20 |
+
decided by the bottoms (same flare for all cups), and the sizes are drawn so that a cup whose bottom is too wide
|
| 21 |
+
does not go in at all -- it stays on the other cup's rim or wedges in the opening, its bottom at most STUCK_MAX
|
| 22 |
+
= 0.5 cm below the rim. So a wrong placement leaves a cup standing on top of another one, its whole body above the
|
| 23 |
+
rim: visible in both cameras without any text feedback. A cup that fits goes down to the floor (centring tolerance
|
| 24 |
+
>= TOL_MIN = 7.5 mm thanks to the flare); in the right nest the taller, narrower cups stick out of the shorter,
|
| 25 |
+
wider ones, but each stands inside the next.
|
| 26 |
+
|
| 27 |
+
Prior (naive): tallest cup outermost, then the next tallest. Learner: a cup that ended up on top of another cup
|
| 28 |
+
must go outside it; swap that pair. Feedback F1 (default) says only failed / succeeded; F2 (ablation) describes
|
| 29 |
+
which cup stands in / on which, in words, with no sizes or positions.
|
| 30 |
+
|
| 31 |
+
Only move_to / open / close are needed: grasp a cup across its upper wall, carry it over the other cup, release it
|
| 32 |
+
just above that cup's rim.
|
| 33 |
+
"""
|
| 34 |
+
import itertools
|
| 35 |
+
|
| 36 |
+
import numpy as np
|
| 37 |
+
|
| 38 |
+
from .. import envs
|
| 39 |
+
from ..bddl import write_bddl
|
| 40 |
+
from ..objects import _SOLID, _fmt, _wrap, register_generated
|
| 41 |
+
from ..skills import _rot_err
|
| 42 |
+
from ..task_base import LFFTask, register_task
|
| 43 |
+
|
| 44 |
+
N_SEG = 20 # wall segments per cup (regular polygon)
|
| 45 |
+
TAN_SEG = float(np.tan(np.pi / N_SEG))
|
| 46 |
+
COS_SEG = float(np.cos(np.pi / N_SEG))
|
| 47 |
+
TAPER_DEG = 5.0 # wall lean (from vertical)
|
| 48 |
+
TAPER = float(np.radians(TAPER_DEG))
|
| 49 |
+
TT = float(np.tan(TAPER))
|
| 50 |
+
WALL_T = 0.0015 # wall thickness (normal to the wall)
|
| 51 |
+
WALL_TH = WALL_T / float(np.cos(TAPER)) # horizontal wall thickness
|
| 52 |
+
FLOOR_T = 0.003
|
| 53 |
+
Z0 = 0.0003 # walls start this far above the cup's underside (the floor disc carries the cup)
|
| 54 |
+
H_RANGE = (0.035, 0.100) # total cup height
|
| 55 |
+
RB_WIDE = (0.023, 0.030) # bottom outer apothem of the cup with the widest bottom
|
| 56 |
+
STEP = (0.0055, 0.0075) # bottom apothem difference between neighbours in the true order
|
| 57 |
+
RIM_MAX = 0.033 # outer apothem of the widest opening (gripper opens 7.9 cm)
|
| 58 |
+
CLEAR_MIN = 0.003 # radial gap (worst case) of a fitting cup standing on the other cup's floor
|
| 59 |
+
TOL_MIN = 0.0075 # a fitting cup goes in if its bottom lands within this of the other cup's axis
|
| 60 |
+
STUCK_MAX = 0.005 # a too-wide cup's bottom stops no deeper than this below the other cup's rim (5-deg walls
|
| 61 |
+
# self-lock: a cup pressed 1.2 cm into the opening wedged, and the narrow cup tipped over with it)
|
| 62 |
+
INV_DH = 0.035 # in the swapped pair the narrower cup is taller by at least this
|
| 63 |
+
KEEP_DH = 0.010 # in an unswapped pair the wider cup is taller by at least this
|
| 64 |
+
P_AGREE = 0.15 # share of instances whose height order is the right nesting order
|
| 65 |
+
SEAT_H = 0.010 # "standing on the floor": bottom less than this above the other cup's floor
|
| 66 |
+
SEAT_TILT = 15.0 # deg; a tall cup in a short, wider one can lean a little
|
| 67 |
+
WRIST_CAM_H = 0.367 # wrist camera height above the table at the start pose (measured 2026-10-08)
|
| 68 |
+
COLORS = {"red": (0.78, 0.22, 0.20, 1.0), "green": (0.28, 0.62, 0.32, 1.0), "blue": (0.22, 0.42, 0.80, 1.0)}
|
| 69 |
+
CUP_NAMES = ("cup_1", "cup_2", "cup_3")
|
| 70 |
+
DENSITY = 600.0
|
| 71 |
+
# execution
|
| 72 |
+
GRASP_BELOW_RIM = 0.012 # gripper site this far below the rim when grasping
|
| 73 |
+
Z_CARRY = envs.TABLE_Z + 0.24
|
| 74 |
+
DROP = 0.006 # held cup's bottom this far above the receiving rim at release
|
| 75 |
+
FINGER_CLEAR = 0.015 # gripper site at least this far above any rim around the target at release: fingers opened
|
| 76 |
+
# inside a taller outer cup press on its wall and carry it away on the way up (seed 1009, 2026-10-08)
|
| 77 |
+
PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35)
|
| 78 |
+
H_NOISE = 0.03 # relative noise of the blind policy's height judgement
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# ---------------------------------------------------------------- cup geometry
|
| 82 |
+
def _quat_mul(a, b):
|
| 83 |
+
w1, x1, y1, z1 = a
|
| 84 |
+
w2, x2, y2, z2 = b
|
| 85 |
+
return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
|
| 86 |
+
w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _seg_quat(phi):
|
| 90 |
+
"""segment frame: about z by phi, then tilted about its own y (tangential) axis by TAPER, so that its local z
|
| 91 |
+
(along the wall) leans outwards and its local x is the wall's outward normal"""
|
| 92 |
+
qz = np.array([np.cos(phi / 2), 0.0, 0.0, np.sin(phi / 2)])
|
| 93 |
+
qy = np.array([np.cos(TAPER / 2), 0.0, np.sin(TAPER / 2), 0.0])
|
| 94 |
+
return _quat_mul(qz, qy)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def seg_half_len(rb, H):
|
| 98 |
+
"""tangential half length of a wall segment: one polygon side at the rim (+0.2 mm overlap)"""
|
| 99 |
+
return (rb + TT * H) * TAN_SEG + 0.0002
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def rim_radius(rb, H):
|
| 103 |
+
"""outer apothem of the opening"""
|
| 104 |
+
return rb + TT * H
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def inner_radius(rb, z):
|
| 108 |
+
"""inner apothem at height z above the cup's underside"""
|
| 109 |
+
return rb + TT * z - WALL_TH
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def bottom_reach(rb, H):
|
| 113 |
+
"""largest horizontal radius of the cup's outside at its bottom (the segment tips stick out a little beyond
|
| 114 |
+
the polygon because every segment is as wide as a rim-level polygon side)"""
|
| 115 |
+
return float(np.hypot(rb + TT * Z0, seg_half_len(rb, H)))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def fit_clearance(rb_in, H_in, rb_out):
|
| 119 |
+
"""radial clearance (worst case over relative yaw) of cup `in` standing on the floor of cup `out`;
|
| 120 |
+
negative = does not go down to the floor. The flare is the same for both cups, so the bottom is the tightest
|
| 121 |
+
height."""
|
| 122 |
+
return inner_radius(rb_out, FLOOR_T) - bottom_reach(rb_in, H_in)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def centring_tol(rb_in, H_in, rb_out, H_out):
|
| 126 |
+
"""how far (worst case) cup `in`'s bottom centre may be off cup `out`'s axis when it is lowered in at the rim
|
| 127 |
+
and still get inside (the flared wall then guides it down)"""
|
| 128 |
+
return inner_radius(rb_out, H_out) - bottom_reach(rb_in, H_in)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def stop_height(rb_in, rb_out, H_out):
|
| 132 |
+
"""height (above cup `out`'s underside) where a too-wide cup `in`, lowered centred, stops: where its bottom
|
| 133 |
+
meets the sloping inner wall, or on the rim if that is higher than the cup"""
|
| 134 |
+
return min((rb_in - rb_out + WALL_TH) / TT, H_out)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def _cup_parts(rb, H):
|
| 138 |
+
"""[(pos, half size, quat)] of the wall segments in the cup body frame (origin at mid height)."""
|
| 139 |
+
zc = (Z0 + H) / 2
|
| 140 |
+
hs = (H - Z0) / (2 * np.cos(TAPER))
|
| 141 |
+
rc = rb + TT * zc - WALL_T / 2 * np.cos(TAPER)
|
| 142 |
+
zz = zc + WALL_T / 2 * np.sin(TAPER) - H / 2
|
| 143 |
+
hl = seg_half_len(rb, H)
|
| 144 |
+
out = []
|
| 145 |
+
for k in range(N_SEG):
|
| 146 |
+
phi = 2 * np.pi * k / N_SEG
|
| 147 |
+
out.append(((rc * np.cos(phi), rc * np.sin(phi), zz), (WALL_T / 2, hl, hs), _seg_quat(phi)))
|
| 148 |
+
return out
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _floor_part(rb, H):
|
| 152 |
+
return (0.0, 0.0, -H / 2 + FLOOR_T / 2), (rb - 0.0003, FLOOR_T / 2, 0.0), np.array([1.0, 0.0, 0.0, 0.0])
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def cup_xml(model_name, rgba):
|
| 156 |
+
"""Open flared cup: N_SEG tilted wall boxes + a cylinder floor (sizes are overwritten per instance)."""
|
| 157 |
+
geoms = []
|
| 158 |
+
rb, H = RB_WIDE[1], H_RANGE[1]
|
| 159 |
+
for k, (p, s, q) in enumerate(_cup_parts(rb, H)):
|
| 160 |
+
geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" '
|
| 161 |
+
f'quat="{_fmt(q)}" rgba="{_fmt(rgba)}" density="{DENSITY:.0f}" friction="0.8 0.005 0.0001" '
|
| 162 |
+
f'{_SOLID} group="0" />')
|
| 163 |
+
geoms.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
|
| 164 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 165 |
+
fp, fs, _ = _floor_part(rb, H)
|
| 166 |
+
geoms.append(f' <geom name="{model_name}_g{N_SEG}" type="cylinder" pos="{_fmt(fp)}" size="{_fmt(fs[:2])}" '
|
| 167 |
+
f'rgba="{_fmt(rgba)}" density="{DENSITY:.0f}" friction="0.8 0.005 0.0001" {_SOLID} group="0" />')
|
| 168 |
+
geoms.append(f' <geom type="cylinder" pos="{_fmt(fp)}" size="{_fmt(fs[:2])}" rgba="{_fmt(rgba)}" '
|
| 169 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 170 |
+
return _wrap(model_name, "\n".join(geoms), H / 2, rim_radius(rb, H) / COS_SEG)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def disable_midphase(env):
|
| 174 |
+
"""The cups are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding
|
| 175 |
+
volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered
|
| 176 |
+
maximum size. A resized wall that lies outside its compiled leaf box is silently skipped: the gripper fingers
|
| 177 |
+
passed straight through the walls of the smaller cups (found 2026-10-07). Without the mid-phase MuJoCo tests all
|
| 178 |
+
geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set in _reshape_cup)."""
|
| 179 |
+
import mujoco
|
| 180 |
+
m = env.sim.model._model
|
| 181 |
+
m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def kendall(a, b):
|
| 185 |
+
"""number of pairs ordered differently in the two orders"""
|
| 186 |
+
pa, pb = {c: k for k, c in enumerate(a)}, {c: k for k, c in enumerate(b)}
|
| 187 |
+
return sum((pa[x] < pa[y]) != (pb[x] < pb[y]) for x, y in itertools.combinations(a, 2))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@register_task
|
| 191 |
+
class NestOrder(LFFTask):
|
| 192 |
+
name = "l4_nest_order"
|
| 193 |
+
level = "L4"
|
| 194 |
+
category = "geometry_inference"
|
| 195 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 196 |
+
instruction = "Nest the red, green and blue cups one inside another."
|
| 197 |
+
instruction_indirect = "Put the three cups one inside another, like a set of nesting cups."
|
| 198 |
+
|
| 199 |
+
# ------------------------------------------------------------ scene
|
| 200 |
+
def make_bddl(self):
|
| 201 |
+
cats = [register_generated(f"LffNestCup{c.capitalize()}", cup_xml(f"lff_nest_cup_{c}", COLORS[c]))
|
| 202 |
+
for c in COLORS]
|
| 203 |
+
regions = [(-0.25, -0.15), (-0.05, 0.0), (-0.25, 0.15)]
|
| 204 |
+
objs = [(n, cat, f"{n}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01))
|
| 205 |
+
for n, cat, (x, y) in zip(CUP_NAMES, cats, regions)]
|
| 206 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 207 |
+
|
| 208 |
+
@staticmethod
|
| 209 |
+
def _heights_ok(case, h):
|
| 210 |
+
"""h[s] = height of the cup with the s-th narrowest bottom (0 = innermost in the true nest)"""
|
| 211 |
+
if case == "agree": # taller = wider: the height order is the nesting order
|
| 212 |
+
return h[2] >= h[1] + KEEP_DH and h[1] >= h[0] + KEEP_DH
|
| 213 |
+
if case == "swap_wide": # the middle cup is the tallest, the narrowest one the shortest
|
| 214 |
+
return h[1] >= h[2] + INV_DH and h[2] >= h[0] + KEEP_DH
|
| 215 |
+
raise ValueError(case)
|
| 216 |
+
|
| 217 |
+
def sample_instance(self, seed):
|
| 218 |
+
rng = np.random.default_rng(seed)
|
| 219 |
+
u = rng.random()
|
| 220 |
+
case = "agree" if u < P_AGREE else "swap_wide"
|
| 221 |
+
for _ in range(200000):
|
| 222 |
+
heights = [float(rng.uniform(*H_RANGE)) for _ in range(3)] # by true size: 0 = narrowest bottom
|
| 223 |
+
if not self._heights_ok(case, heights):
|
| 224 |
+
continue
|
| 225 |
+
rb3 = float(rng.uniform(*RB_WIDE))
|
| 226 |
+
rb2 = rb3 - float(rng.uniform(*STEP))
|
| 227 |
+
rb1 = rb2 - float(rng.uniform(*STEP))
|
| 228 |
+
rbs = [rb1, rb2, rb3]
|
| 229 |
+
rims = [rim_radius(rb, h) for rb, h in zip(rbs, heights)]
|
| 230 |
+
if max(rims) > RIM_MAX:
|
| 231 |
+
continue
|
| 232 |
+
ok = True
|
| 233 |
+
for p, q in itertools.permutations(range(3), 2): # p into q
|
| 234 |
+
if p < q:
|
| 235 |
+
ok &= (fit_clearance(rbs[p], heights[p], rbs[q]) >= CLEAR_MIN
|
| 236 |
+
and centring_tol(rbs[p], heights[p], rbs[q], heights[q]) >= TOL_MIN)
|
| 237 |
+
else:
|
| 238 |
+
ok &= heights[q] - stop_height(rbs[p], rbs[q], heights[q]) <= STUCK_MAX
|
| 239 |
+
if ok:
|
| 240 |
+
break
|
| 241 |
+
else:
|
| 242 |
+
raise RuntimeError("could not sample cup sizes")
|
| 243 |
+
xy = []
|
| 244 |
+
while len(xy) < 3:
|
| 245 |
+
xy = []
|
| 246 |
+
for _k in range(3):
|
| 247 |
+
for _t in range(200):
|
| 248 |
+
p = [float(rng.uniform(-0.27, 0.02)), float(rng.uniform(-0.17, 0.17))]
|
| 249 |
+
if all(np.hypot(p[0] - q[0], p[1] - q[1]) >= 0.14 for q in xy):
|
| 250 |
+
xy.append(p)
|
| 251 |
+
break
|
| 252 |
+
# the colour is fixed per object (cup_1 red, cup_2 green, cup_3 blue: one generated class each); shuffle
|
| 253 |
+
# which object gets which size / height / position
|
| 254 |
+
perm = [int(i) for i in rng.permutation(3)] # perm[size index] = object slot
|
| 255 |
+
cups = [None] * 3
|
| 256 |
+
for s in range(3):
|
| 257 |
+
cups[perm[s]] = dict(name=CUP_NAMES[perm[s]], color=list(COLORS)[perm[s]], rb=rbs[s], height=heights[s],
|
| 258 |
+
rim=rims[s], xy=xy[s], size_rank=s)
|
| 259 |
+
order = sorted(range(3), key=lambda j: -cups[j]["rb"]) # outermost first (indices into cups)
|
| 260 |
+
naive = sorted(range(3), key=lambda j: -cups[j]["height"])
|
| 261 |
+
assert (naive == order) == (case == "agree"), (seed, case)
|
| 262 |
+
by = lambda s: perm[s] # noqa: E731 object index of size rank s
|
| 263 |
+
return dict(seed=int(seed), case=case, cups=cups, order=order, naive_order=naive,
|
| 264 |
+
bottom_cm=[round(200 * c["rb"], 2) for c in cups],
|
| 265 |
+
opening_cm=[round(200 * c["rim"], 2) for c in cups],
|
| 266 |
+
height_cm=[round(100 * c["height"], 2) for c in cups],
|
| 267 |
+
# relative size of each opening in the wrist camera at its start height (1 = largest)
|
| 268 |
+
wrist_apparent=[round(float(v), 3) for v in (lambda a: a / a.max())(np.array(
|
| 269 |
+
[c["rim"] / (WRIST_CAM_H - c["height"]) for c in cups]))],
|
| 270 |
+
clear_mm=[round(1000 * fit_clearance(rbs[s], heights[s], rbs[s + 1]), 2) for s in range(2)],
|
| 271 |
+
tol_mm=[round(1000 * centring_tol(rbs[s], heights[s], rbs[s + 1], heights[s + 1]), 2)
|
| 272 |
+
for s in range(2)],
|
| 273 |
+
# wrong neighbour pairs: how deep (cm) the wider cup's bottom gets below the narrower cup's rim
|
| 274 |
+
stuck_cm={f"{by(s + 1)}in{by(s)}": round(100 * (heights[s] - stop_height(
|
| 275 |
+
rbs[s + 1], rbs[s], heights[s])), 2) for s in range(2)})
|
| 276 |
+
|
| 277 |
+
def _reshape_cup(self, name, rb, H):
|
| 278 |
+
m = self.env.sim.model
|
| 279 |
+
o = self.env.objects_dict[name]
|
| 280 |
+
parts = _cup_parts(rb, H) + [_floor_part(rb, H)]
|
| 281 |
+
for names in (o.contact_geoms, o.visual_geoms):
|
| 282 |
+
assert len(names) == len(parts), (name, len(names))
|
| 283 |
+
for k, n in enumerate(names):
|
| 284 |
+
g = m.geom_name2id(n)
|
| 285 |
+
pos, size, quat = parts[k]
|
| 286 |
+
m.geom_pos[g] = pos
|
| 287 |
+
m.geom_size[g] = size
|
| 288 |
+
m.geom_quat[g] = quat
|
| 289 |
+
if k < N_SEG:
|
| 290 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 291 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 292 |
+
else:
|
| 293 |
+
m.geom_rbound[g] = float(np.hypot(size[0], size[1]))
|
| 294 |
+
m.geom_aabb[g] = [0, 0, 0, size[0], size[0], size[1]]
|
| 295 |
+
# mass / inertia of the resized cup: conical shell + disc floor
|
| 296 |
+
bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])])
|
| 297 |
+
slant = (H - Z0) / np.cos(TAPER)
|
| 298 |
+
r_mid = rb + TT * (H + Z0) / 2
|
| 299 |
+
wall_m = DENSITY * 2 * np.pi * r_mid * WALL_T * slant
|
| 300 |
+
floor_m = DENSITY * np.pi * rb ** 2 * FLOOR_T
|
| 301 |
+
mass = wall_m + floor_m
|
| 302 |
+
# wall centroid height (from the underside): area-weighted, r grows linearly with z
|
| 303 |
+
r0, r1 = rb + TT * Z0, rb + TT * H
|
| 304 |
+
z_w = Z0 + (H - Z0) * (r0 + 2 * r1) / (3 * (r0 + r1))
|
| 305 |
+
z_cm = (wall_m * z_w + floor_m * FLOOR_T / 2) / mass
|
| 306 |
+
Izz = wall_m * r_mid ** 2 + floor_m * rb ** 2 / 2
|
| 307 |
+
Ixx = (wall_m * (r_mid ** 2 / 2 + (H - Z0) ** 2 / 12 + (z_w - z_cm) ** 2)
|
| 308 |
+
+ floor_m * (rb ** 2 / 4 + (FLOOR_T / 2 - z_cm) ** 2))
|
| 309 |
+
m.body_mass[bid] = mass
|
| 310 |
+
m.body_inertia[bid] = [Ixx, Ixx, Izz]
|
| 311 |
+
m.body_ipos[bid] = [0.0, 0.0, z_cm - H / 2]
|
| 312 |
+
m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 313 |
+
|
| 314 |
+
def apply_instance(self, inst):
|
| 315 |
+
disable_midphase(self.env)
|
| 316 |
+
for c in inst["cups"]:
|
| 317 |
+
self._reshape_cup(c["name"], c["rb"], c["height"])
|
| 318 |
+
envs.set_obj_pose(self.env, c["name"], [*c["xy"], envs.TABLE_Z + c["height"] / 2 + 0.0005])
|
| 319 |
+
|
| 320 |
+
# ------------------------------------------------------------ state
|
| 321 |
+
def _cup_state(self, inst, j):
|
| 322 |
+
c = inst["cups"][j]
|
| 323 |
+
bid = envs.body_id(self.env, c["name"])
|
| 324 |
+
p = self.env.sim.data.body_xpos[bid].copy()
|
| 325 |
+
R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
|
| 326 |
+
tilt = float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1))))
|
| 327 |
+
bottom = p - R[:, 2] * c["height"] / 2 # centre of the floor's underside
|
| 328 |
+
rim = p + R[:, 2] * c["height"] / 2
|
| 329 |
+
return dict(p=p, tilt=tilt, bottom=bottom, rim=rim, floor_top=bottom[2] + FLOOR_T * R[2, 2])
|
| 330 |
+
|
| 331 |
+
def relations(self, inst):
|
| 332 |
+
"""For each cup: which cup it stands in / on (if any), how high, seated or not."""
|
| 333 |
+
st = [self._cup_state(inst, j) for j in range(3)]
|
| 334 |
+
rel = []
|
| 335 |
+
for j in range(3):
|
| 336 |
+
sj = st[j]
|
| 337 |
+
best = None
|
| 338 |
+
for i in range(3):
|
| 339 |
+
if i == j:
|
| 340 |
+
continue
|
| 341 |
+
ci, si = inst["cups"][i], st[i]
|
| 342 |
+
if si["tilt"] > 45:
|
| 343 |
+
continue
|
| 344 |
+
d = float(np.hypot(*(sj["bottom"][:2] - si["p"][:2])))
|
| 345 |
+
if d > rim_radius(ci["rb"], ci["height"]) + 0.01:
|
| 346 |
+
continue # not above / in cup i
|
| 347 |
+
hb = float(sj["bottom"][2] - si["floor_top"]) # j's bottom above i's floor
|
| 348 |
+
# (the last test keeps a cup from being reported as standing in the cup it contains)
|
| 349 |
+
if hb < -0.004 or hb > ci["height"] + 0.02 or sj["bottom"][2] < si["bottom"][2] + FLOOR_T / 2:
|
| 350 |
+
continue
|
| 351 |
+
if best is None or hb < best[1]:
|
| 352 |
+
best = (i, hb, d)
|
| 353 |
+
if best is None:
|
| 354 |
+
on_table = sj["bottom"][2] < envs.TABLE_Z + 0.01 and sj["tilt"] < 30
|
| 355 |
+
rel.append(dict(cup=j, on=None, table=bool(on_table), tilt=sj["tilt"], xy=sj["p"][:2].tolist(),
|
| 356 |
+
fallen=bool(sj["tilt"] > 45)))
|
| 357 |
+
continue
|
| 358 |
+
i, hb, d = best
|
| 359 |
+
ci = inst["cups"][i]
|
| 360 |
+
seated = hb < SEAT_H and sj["tilt"] < SEAT_TILT
|
| 361 |
+
on_rim = hb > ci["height"] - FLOOR_T - 0.004
|
| 362 |
+
rel.append(dict(cup=j, on=i, height=hb, seated=bool(seated), on_rim=bool(on_rim), tilt=sj["tilt"],
|
| 363 |
+
offset=d, xy=sj["p"][:2].tolist(), fallen=bool(sj["tilt"] > 45)))
|
| 364 |
+
return rel
|
| 365 |
+
|
| 366 |
+
def outcome(self, inst):
|
| 367 |
+
envs.settle(self.env, 40)
|
| 368 |
+
cups = inst["cups"]
|
| 369 |
+
rel = self.relations(inst)
|
| 370 |
+
held = [j for j in range(3) if self.sk is not None and self.sk.holding(cups[j]["name"])]
|
| 371 |
+
col = [c["color"] for c in cups]
|
| 372 |
+
seated_in = {r["cup"]: r["on"] for r in rel if r.get("on") is not None and r["seated"]}
|
| 373 |
+
# success: a chain outer <- mid <- inner, all seated and upright, the outer cup standing on the table
|
| 374 |
+
success = False
|
| 375 |
+
for a, b, c in itertools.permutations(range(3)):
|
| 376 |
+
if seated_in.get(b) == a and seated_in.get(c) == b and _on_table_upright(rel, a):
|
| 377 |
+
success = True
|
| 378 |
+
success = bool(success and not held)
|
| 379 |
+
fb = dict(seated=[[j, i] for j, i in seated_in.items()], blocked=[], offcentre=[], held=held)
|
| 380 |
+
lines = []
|
| 381 |
+
res = dict(success=success, relations=rel, feedback=fb)
|
| 382 |
+
if held:
|
| 383 |
+
lines.append(f"The {col[held[0]]} cup is still in the gripper.")
|
| 384 |
+
if success:
|
| 385 |
+
a = [j for j in range(3) if j not in seated_in][0]
|
| 386 |
+
b = [j for j, i in seated_in.items() if i == a][0]
|
| 387 |
+
c = [j for j, i in seated_in.items() if i == b][0]
|
| 388 |
+
res["detail"] = (f"All three cups are nested: the {col[c]} cup stands inside the {col[b]} cup, "
|
| 389 |
+
f"which stands inside the {col[a]} cup.")
|
| 390 |
+
res["failure"] = None
|
| 391 |
+
return res
|
| 392 |
+
# bottom-up description
|
| 393 |
+
st = {r["cup"]: self._cup_state(inst, r["cup"]) for r in rel}
|
| 394 |
+
for r in sorted(rel, key=lambda r: st[r["cup"]]["bottom"][2]):
|
| 395 |
+
j = r["cup"]
|
| 396 |
+
if j in held:
|
| 397 |
+
continue
|
| 398 |
+
if r.get("on") is None:
|
| 399 |
+
if r["fallen"]:
|
| 400 |
+
lines.append(f"The {col[j]} cup has fallen over.")
|
| 401 |
+
elif r["table"]:
|
| 402 |
+
lines.append(f"The {col[j]} cup is standing on the table, not in another cup.")
|
| 403 |
+
else:
|
| 404 |
+
lines.append(f"The {col[j]} cup is neither standing on the table nor inside another cup.")
|
| 405 |
+
continue
|
| 406 |
+
i = r["on"]
|
| 407 |
+
if r["seated"]:
|
| 408 |
+
lines.append(f"The {col[j]} cup is inside the {col[i]} cup, standing on its bottom.")
|
| 409 |
+
continue
|
| 410 |
+
# did not go in. The text says only what a camera shows (no sizes); the structured field keeps the
|
| 411 |
+
# nominal verdict for the scripted learner
|
| 412 |
+
tilt = f", tilted about {r['tilt']:.0f} degrees" if r["tilt"] >= 8 else ""
|
| 413 |
+
if r["on_rim"]:
|
| 414 |
+
lines.append(f"The {col[j]} cup is sitting on the rim of the {col[i]} cup, not inside it{tilt}.")
|
| 415 |
+
else:
|
| 416 |
+
lines.append(f"The {col[j]} cup is stuck in the opening of the {col[i]} cup, not down inside "
|
| 417 |
+
f"it{tilt}.")
|
| 418 |
+
over = cups[j]["rb"] - cups[i]["rb"]
|
| 419 |
+
if over > 0:
|
| 420 |
+
fb["blocked"].append([j, i, round(100 * r["height"], 1)])
|
| 421 |
+
else:
|
| 422 |
+
fb["offcentre"].append([j, i, round(100 * r["height"], 1)])
|
| 423 |
+
res["detail"] = " ".join(lines) if lines else "The cups are not nested."
|
| 424 |
+
res["failure"] = "blocked" if fb["blocked"] else ("offcentre" if fb["offcentre"] else
|
| 425 |
+
("held" if held else "incomplete"))
|
| 426 |
+
return res
|
| 427 |
+
|
| 428 |
+
# ------------------------------------------------------------ execution
|
| 429 |
+
def execute(self, inst, params):
|
| 430 |
+
"""params: order = [outer, middle, inner] (indices into inst['cups']). Puts the middle cup into the outer
|
| 431 |
+
one; if it went in (judged from the scene, as an agent would see it), puts the inner cup into the middle
|
| 432 |
+
one. Optional (robustness checks): dxy = (dx, dy) release offset (m), drop (m), grasp_below (m),
|
| 433 |
+
carry_speed (m/s or None = as fast as the controller allows)."""
|
| 434 |
+
o, mid, inn = [int(v) for v in params["order"]]
|
| 435 |
+
ok = self._move_cup(inst, mid, o, params)
|
| 436 |
+
if ok:
|
| 437 |
+
self._move_cup(inst, inn, mid, params)
|
| 438 |
+
self.sk.move_to(list(PARK), yaw=0.0)
|
| 439 |
+
|
| 440 |
+
def _move_cup(self, inst, j, i, params):
|
| 441 |
+
sk = self.sk
|
| 442 |
+
sj = self._cup_state(inst, j)
|
| 443 |
+
x, y = sj["p"][:2]
|
| 444 |
+
rim = sj["rim"][2]
|
| 445 |
+
sk.set_gripper(False, steps=5)
|
| 446 |
+
sk.move_to([x, y, Z_CARRY], yaw=0.0)
|
| 447 |
+
sk.move_to([x, y, rim + 0.06], tol=0.004)
|
| 448 |
+
sk.move_to([x, y, rim - params.get("grasp_below", GRASP_BELOW_RIM)], tol=0.003)
|
| 449 |
+
sk.set_gripper(True, steps=15)
|
| 450 |
+
sk.move_to([x, y, Z_CARRY], speed=params.get("carry_speed", 0.3))
|
| 451 |
+
si = self._cup_state(inst, i)
|
| 452 |
+
dx, dy = params.get("dxy", (0.0, 0.0))
|
| 453 |
+
tx, ty = si["p"][0] + dx, si["p"][1] + dy
|
| 454 |
+
drop = params.get("drop", DROP)
|
| 455 |
+
sk.move_to([tx, ty, Z_CARRY], tol=0.004)
|
| 456 |
+
off = self._cup_state(inst, j)["bottom"] - sk.eef_pos()
|
| 457 |
+
# approach above the highest rim there (the target cup may stand inside a taller one)
|
| 458 |
+
top = max(s["rim"][2] for s in (self._cup_state(inst, q) for q in range(3) if q != j)
|
| 459 |
+
if np.hypot(s["p"][0] - tx, s["p"][1] - ty) < 0.04)
|
| 460 |
+
sk.move_to([tx - off[0], ty - off[1], max(top, si["rim"][2]) + drop + 0.03 - off[2]], tol=0.003)
|
| 461 |
+
z_rel = si["rim"][2] + drop
|
| 462 |
+
if top > si["rim"][2] + 0.002: # the target stands inside a taller cup: let go above that rim
|
| 463 |
+
z_rel = max(z_rel, top + FINGER_CLEAR - (inst["cups"][j]["height"]
|
| 464 |
+
- params.get("grasp_below", GRASP_BELOW_RIM)))
|
| 465 |
+
tgt = self._servo_cup(inst, j, [tx, ty], z_rel)
|
| 466 |
+
sk.grip = -1.0
|
| 467 |
+
self._hold_at(tgt, 12)
|
| 468 |
+
sk.move_to([tgt[0], tgt[1], Z_CARRY], speed=0.3)
|
| 469 |
+
envs.settle(self.env, 20)
|
| 470 |
+
r = [q for q in self.relations(inst) if q["cup"] == j][0]
|
| 471 |
+
return bool(r.get("on") == i and r["seated"])
|
| 472 |
+
|
| 473 |
+
def _hold_at(self, target, steps):
|
| 474 |
+
sk = self.sk
|
| 475 |
+
R = sk._R()
|
| 476 |
+
for _ in range(steps):
|
| 477 |
+
sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 478 |
+
|
| 479 |
+
def _servo_cup(self, inst, j, xy, z_bottom, max_steps=60, tol=0.0015):
|
| 480 |
+
"""closed loop on the held cup's bottom centre (scripted policies only). Stops where the cup is held up
|
| 481 |
+
(a too-wide cup on / in another cup's rim) instead of pressing on: a person lets go there too, and
|
| 482 |
+
pressing on tips the cups over."""
|
| 483 |
+
sk = self.sk
|
| 484 |
+
R = sk._R()
|
| 485 |
+
goal = np.array([xy[0], xy[1], z_bottom])
|
| 486 |
+
tgt = e_prev = sk.eef_pos()
|
| 487 |
+
zs = []
|
| 488 |
+
for k in range(max_steps):
|
| 489 |
+
b, e = self._cup_state(inst, j)["bottom"], sk.eef_pos()
|
| 490 |
+
if k >= 8 and np.linalg.norm(b - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
|
| 491 |
+
break
|
| 492 |
+
zs.append(b[2])
|
| 493 |
+
if k >= 12 and b[2] - goal[2] > 0.003 and zs[-6] - b[2] < 0.0005:
|
| 494 |
+
return e # blocked: release here
|
| 495 |
+
tgt = goal - (b - e)
|
| 496 |
+
sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
|
| 497 |
+
e_prev = e
|
| 498 |
+
return tgt
|
| 499 |
+
|
| 500 |
+
# ------------------------------------------------------------ scripted policies
|
| 501 |
+
def default_params(self, inst):
|
| 502 |
+
"""prior: the bigger-looking cup goes outside, and the cups look big by their height: tallest outermost"""
|
| 503 |
+
return dict(order=list(inst["naive_order"]))
|
| 504 |
+
|
| 505 |
+
def oracle_params(self, inst):
|
| 506 |
+
return dict(order=list(inst["order"]))
|
| 507 |
+
|
| 508 |
+
def blind_params(self, inst, attempt, rng):
|
| 509 |
+
"""no history: the same height judgement again, with a little noise"""
|
| 510 |
+
est = [c["height"] * (1 + rng.normal(0, H_NOISE)) for c in inst["cups"]]
|
| 511 |
+
return dict(order=[int(i) for i in np.argsort(est)[::-1]])
|
| 512 |
+
|
| 513 |
+
@staticmethod
|
| 514 |
+
def constraints(history):
|
| 515 |
+
"""pairs (outer, inner) implied by the F2 feedback of earlier attempts"""
|
| 516 |
+
pairs = set()
|
| 517 |
+
for h in history:
|
| 518 |
+
fb = h["outcome"].get("feedback") or {}
|
| 519 |
+
for j, i in fb.get("seated", []):
|
| 520 |
+
pairs.add((int(i), int(j))) # j sits in i -> i is outside j
|
| 521 |
+
for j, i, _ in fb.get("blocked", []):
|
| 522 |
+
pairs.add((int(j), int(i))) # j does not fit into i -> j must be outside i
|
| 523 |
+
for j, i, _ in fb.get("offcentre", []):
|
| 524 |
+
pairs.add((int(i), int(j))) # j would fit into i
|
| 525 |
+
return pairs
|
| 526 |
+
|
| 527 |
+
def adapt_params(self, inst, history):
|
| 528 |
+
"""Scripted learner. It does not perceive the bottoms at all; it uses only which cup went into / stayed on
|
| 529 |
+
top of which (visible in the camera images; the structured part of the outcome): every such relation gives
|
| 530 |
+
an (outer, inner) pair; among the untried orders consistent with all pairs it takes the one closest (fewest
|
| 531 |
+
swapped pairs) to its prior, the height order; ties go to the larger height agreement."""
|
| 532 |
+
pairs = self.constraints(history)
|
| 533 |
+
rims = [c["height"] for c in inst["cups"]]
|
| 534 |
+
prior = list(inst["naive_order"])
|
| 535 |
+
tried = {tuple(h["params"]["order"]) for h in history if (h["outcome"].get("feedback") or {}).get("blocked")}
|
| 536 |
+
cands = []
|
| 537 |
+
for order in itertools.permutations(range(3)):
|
| 538 |
+
pos = {c: k for k, c in enumerate(order)}
|
| 539 |
+
consistent = all(pos[a] < pos[b] for a, b in pairs)
|
| 540 |
+
agree = sum(rims[order[k]] - rims[order[k + 1]] for k in range(2))
|
| 541 |
+
cands.append((consistent, tuple(order) not in tried, -kendall(order, prior), agree, order))
|
| 542 |
+
best = max(cands)
|
| 543 |
+
return dict(order=list(best[4]))
|
| 544 |
+
|
| 545 |
+
def random_order_params(self, inst, history, rng):
|
| 546 |
+
"""sensitivity variant: a random order each retry, no history"""
|
| 547 |
+
return dict(order=[int(i) for i in rng.permutation(3)])
|
| 548 |
+
|
| 549 |
+
EXTRA_KINDS = ("random_order",)
|
| 550 |
+
|
| 551 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 552 |
+
if kind not in self.EXTRA_KINDS:
|
| 553 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 554 |
+
k = k or self.max_attempts
|
| 555 |
+
rng = np.random.default_rng(seed)
|
| 556 |
+
history = []
|
| 557 |
+
for a in range(k):
|
| 558 |
+
self.reset_instance(inst)
|
| 559 |
+
params = self.default_params(inst) if a == 0 else self.random_order_params(inst, history, rng)
|
| 560 |
+
self.execute(inst, params)
|
| 561 |
+
out = self.outcome(inst)
|
| 562 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 563 |
+
if on_attempt:
|
| 564 |
+
on_attempt(a, params, out)
|
| 565 |
+
if out["success"]:
|
| 566 |
+
break
|
| 567 |
+
return history
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
def _on_table_upright(rel, j):
|
| 571 |
+
r = [q for q in rel if q["cup"] == j][0]
|
| 572 |
+
return r.get("on") is None and r["table"] and r["tilt"] < 8.0 and not r["fallen"]
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
# ---------------------------------------------------------------- physical validity checks
|
| 576 |
+
def physics_check(seed0=1000, n=8, out=None):
|
| 577 |
+
"""All 6 orders on each instance; expect success iff the order is the true one."""
|
| 578 |
+
import json
|
| 579 |
+
task = NestOrder()
|
| 580 |
+
rows = []
|
| 581 |
+
for seed in range(seed0, seed0 + n):
|
| 582 |
+
inst = task.sample_instance(seed)
|
| 583 |
+
for order in itertools.permutations(range(3)):
|
| 584 |
+
task.reset_instance(inst)
|
| 585 |
+
task.execute(inst, dict(order=list(order)))
|
| 586 |
+
o = task.outcome(inst)
|
| 587 |
+
expect = list(order) == inst["order"]
|
| 588 |
+
# for a cup that did not go in: how far (cm) its bottom is below the other cup's rim
|
| 589 |
+
below_rim = [round(100 * (inst["cups"][r["on"]]["height"] - FLOOR_T - r["height"]), 2)
|
| 590 |
+
for r in o["relations"] if r.get("on") is not None and not r["seated"]]
|
| 591 |
+
rows.append(dict(seed=seed, case=inst["case"], order=list(order), success=o["success"], expect=expect,
|
| 592 |
+
failure=o["failure"], detail=o["detail"], below_rim_cm=below_rim,
|
| 593 |
+
clear_mm=inst["clear_mm"], tol_mm=inst["tol_mm"], bottom_cm=inst["bottom_cm"],
|
| 594 |
+
opening_cm=inst["opening_cm"], height_cm=inst["height_cm"]))
|
| 595 |
+
print(f"seed {seed} order {order} succ={o['success']} expect={expect} | {o['detail']}"
|
| 596 |
+
+ ("" if o["success"] == expect else " <-- MISMATCH"), flush=True)
|
| 597 |
+
if out:
|
| 598 |
+
with open(out, "w") as f:
|
| 599 |
+
json.dump(rows, f, indent=1)
|
| 600 |
+
print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows))
|
| 601 |
+
return rows
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
def robustness_check(seed0=1000, n=6, out=None):
|
| 605 |
+
"""True order with execution errors: release off-centre (both moves) by 0-9 mm in a random direction, released
|
| 606 |
+
3 cm above the rim, grasped lower, carried at full controller speed."""
|
| 607 |
+
import json
|
| 608 |
+
task = NestOrder()
|
| 609 |
+
rows = []
|
| 610 |
+
cases = [("centred", {}), ("off3", dict(off=0.003)), ("off5", dict(off=0.005)), ("off7", dict(off=0.007)),
|
| 611 |
+
("off9", dict(off=0.009)), ("drop3cm", dict(drop=0.03)), ("off4_drop3cm", dict(off=0.004, drop=0.03)),
|
| 612 |
+
("grasp2cm", dict(grasp_below=0.02)), ("fast_carry", dict(carry_speed=None))]
|
| 613 |
+
for seed in range(seed0, seed0 + n):
|
| 614 |
+
inst = task.sample_instance(seed)
|
| 615 |
+
rng = np.random.default_rng(seed)
|
| 616 |
+
for name, c in cases:
|
| 617 |
+
a = rng.uniform(0, 2 * np.pi)
|
| 618 |
+
off = c.get("off", 0.0)
|
| 619 |
+
params = dict(order=list(inst["order"]), dxy=(off * np.cos(a), off * np.sin(a)))
|
| 620 |
+
params.update({k: v for k, v in c.items() if k != "off"})
|
| 621 |
+
task.reset_instance(inst)
|
| 622 |
+
task.execute(inst, params)
|
| 623 |
+
o = task.outcome(inst)
|
| 624 |
+
rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], tol_mm=inst["tol_mm"],
|
| 625 |
+
height_cm=inst["height_cm"]))
|
| 626 |
+
print(f"seed {seed} {name:13s} succ={o['success']} | {o['detail']}", flush=True)
|
| 627 |
+
if out:
|
| 628 |
+
with open(out, "w") as f:
|
| 629 |
+
json.dump(rows, f, indent=1)
|
| 630 |
+
for name, _ in cases:
|
| 631 |
+
r = [x["success"] for x in rows if x["case"] == name]
|
| 632 |
+
print(f"{name:13s} {sum(r)}/{len(r)}")
|
| 633 |
+
return rows
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
if __name__ == "__main__":
|
| 637 |
+
# python -m lffbench.tasks.l4_nest physics results/l4_nest_order/physics_check.json [n]
|
| 638 |
+
# python -m lffbench.tasks.l4_nest robust results/l4_nest_order/robustness_check.json [n]
|
| 639 |
+
import sys
|
| 640 |
+
n_arg = int(sys.argv[3]) if len(sys.argv) > 3 else None
|
| 641 |
+
if sys.argv[1] == "physics":
|
| 642 |
+
physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 8)
|
| 643 |
+
elif sys.argv[1] == "robust":
|
| 644 |
+
robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 6)
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py
ADDED
|
@@ -0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L5 loaded_beam (2026-10-12): a deepened l5_slippery_lift -- lift a loaded bar level without spilling its load.
|
| 2 |
+
|
| 3 |
+
Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 2, 3.1): l5_slippery_lift saturated. Sonnet 5.5 (cla4)
|
| 4 |
+
grasped the bar's middle, lifted, saw the 45-60 deg tilt, put the bar down and regrasped near the centre of mass,
|
| 5 |
+
all inside attempt 1 (both runs succeeded on attempt 1): the tilting lift cost nothing. Rule R3: the first
|
| 6 |
+
common-sense interaction must cost something. Here the tilting lift spills the load.
|
| 7 |
+
|
| 8 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, "left" = +y): the l5_slippery_lift bar (steel grey,
|
| 9 |
+
4 x 28 x 4 cm, long axis along the robot's left-right axis, same layout and hidden weight per seed) with two small red
|
| 10 |
+
blocks (2.5 cm cubes, 30 g, smooth: friction 0.2, they slide on the steel beyond ~11 deg of tilt) resting on its top
|
| 11 |
+
near the ends, 12.5 cm left and right of its middle.
|
| 12 |
+
|
| 13 |
+
Hidden variable (same in every attempt, invisible): a slug inside the bar puts its centre of mass e = 2.5-7 cm from
|
| 14 |
+
the middle, towards the left or right end (bar 0.8-1.2 kg, finger friction 0.40-0.60; l5_slippery_lift). The blocks
|
| 15 |
+
are symmetric, so the centre of mass of bar + blocks sits at M e / (M + 2 m) (2.3-6.7 cm).
|
| 16 |
+
|
| 17 |
+
Mechanism (physics, nothing teleported): grasped at its middle and lifted, the bar rotates in the slippery finger
|
| 18 |
+
pads and hangs tilted; the block on the low (heavy) end slides off, drops onto the table and, once the bar is set down
|
| 19 |
+
again, lies 2-5 cm beyond the bar's end; the other block slides along the bar to the fingers. Measured (20 seeds,
|
| 20 |
+
middle grasp): lift 15 cm at 0.1 m/s -> tilt 29-54 deg, spill 20/20; 15 cm at 0.03 m/s -> spill 20/20 (block friction =
|
| 21 |
+
the bar's, task card); a 5.5 cm "half lift" -> 20-22 deg, spill 20/20; 3 cm -> 10-11 deg, spill 2/20; 1 / 1.5 cm test
|
| 22 |
+
lifts -> 0.6-2.5 / 2.5-4.5 deg, spill 0/20 each (the low end stays on the table). Putting it right is a real repair:
|
| 23 |
+
set the bar down, release, pick the fallen block from the table, put it back on the end, move the other block back to
|
| 24 |
+
its end, regrasp nearer the heavy end, lift again: 20 commands for the scripted policy (5 for the whole oracle; the
|
| 25 |
+
same repair costs 7 commands in l5_slippery_lift, where nothing spills). What helps: a ~1 cm test lift shows the tilt
|
| 26 |
+
direction without spilling, or, after the first failure, grasping on the side of the end that sank (the heavy end),
|
| 27 |
+
ideally at the combined centre of mass (+-5 mm: 80/80 level lifts, nothing spilled).
|
| 28 |
+
|
| 29 |
+
Success: the bar is held (after a 1.5 s hold), tilted <= 8 deg, its lowest point >= 10 cm above the table (the
|
| 30 |
+
l5_slippery_lift condition), and both blocks rest on the bar, one within 3 cm of each end position (+-12.5 cm from the
|
| 31 |
+
middle; either block may sit on either end). Protocol: cross (reset before every attempt), k = 3.
|
| 32 |
+
|
| 33 |
+
Outcome (server log only; the agent gets F1): success / failure code, the bar's tilt and height, final block states,
|
| 34 |
+
per-step events (bar_lifted, bar_tilted, load_fell = the trap fired, load_displaced, load_removed, load_restored with
|
| 35 |
+
by_robot, bar_set_down), the lifts with their grasp points and maximum tilt, trap_fired, recovered_in_attempt,
|
| 36 |
+
first_interaction_ok and an F2-style `detail` in robot-centric words.
|
| 37 |
+
"""
|
| 38 |
+
import numpy as np
|
| 39 |
+
|
| 40 |
+
from .. import envs
|
| 41 |
+
from ..bddl import write_bddl
|
| 42 |
+
from ..objects import box_xml, register_generated
|
| 43 |
+
from ..task_base import register_task
|
| 44 |
+
from .l5_slippery_lift import (BAR, HALF, LIFT_MIN, TILT_MAX, YAW_ACROSS, Z_GRASP, BarSkills, SlipperyLift,
|
| 45 |
+
bar_tilt_deg, weighted_box_xml)
|
| 46 |
+
|
| 47 |
+
TZ = envs.TABLE_Z
|
| 48 |
+
LOADS = ("block_1", "block_2") # block_1 starts on the left (+y) end, block_2 on the right (-y) end
|
| 49 |
+
LOAD_SIGN = {"block_1": 1.0, "block_2": -1.0}
|
| 50 |
+
LOAD_H = 0.0125 # 2.5 cm cubes
|
| 51 |
+
LOAD_MASS = 0.030
|
| 52 |
+
LOAD_RGBA = (0.85, 0.20, 0.12, 1.0)
|
| 53 |
+
LOAD_MU = 0.20 # block sliding friction (geom priority 3: used against the bar, the table and the fingers): the blocks
|
| 54 |
+
# slide on the steel bar beyond ~11 deg of tilt. With the bar's own mu (0.4-0.6, slide beyond 22-31 deg)
|
| 55 |
+
# a 5.5 cm "half lift" (20 deg) spilled nothing (0/10) and was a free probe; with 0.2 it spills.
|
| 56 |
+
SLOT = 0.125 # block centre this far from the bar's middle (along the bar)
|
| 57 |
+
SLOT_TOL = 0.03 # success: within 3 cm of an end position
|
| 58 |
+
BAR_TOP = TZ + 2 * HALF[2]
|
| 59 |
+
LIFTED = 0.02 # the bar's centre this much higher than at rest (while held) -> "lifted" (a ~1 cm test lift is not)
|
| 60 |
+
DOWN = 0.008 # ... and back below this -> "set down"
|
| 61 |
+
DEBOUNCE = 5 # control steps a new block state must persist before it counts
|
| 62 |
+
SAFE_ALONG = 0.09 # scripted grasps stay within +-9 cm of the middle (the hand must not touch the blocks)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class _Budget(Exception):
|
| 66 |
+
"""the scripted policy used up the agent command budget of the attempt"""
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def bar_frame(env):
|
| 70 |
+
"""(centre, along, side, up): `along` = the bar's long axis oriented towards the robot's left (+y); `up` = the
|
| 71 |
+
bar's cross-section axis closest to world up (the face the blocks rest on); `side` completes the frame."""
|
| 72 |
+
bid = envs.body_id(env, BAR)
|
| 73 |
+
d = env.sim.data
|
| 74 |
+
c = d.body_xpos[bid].copy()
|
| 75 |
+
R = d.body_xmat[bid].reshape(3, 3)
|
| 76 |
+
al = R[:, 1].copy()
|
| 77 |
+
if al[1] < 0:
|
| 78 |
+
al = -al
|
| 79 |
+
up = max((R[:, 0].copy(), R[:, 2].copy()), key=lambda v: abs(v[2]))
|
| 80 |
+
if up[2] < 0:
|
| 81 |
+
up = -up
|
| 82 |
+
side = np.cross(up, al)
|
| 83 |
+
return c, al, side, up
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _end_word(s):
|
| 87 |
+
return "left" if s > 0 else "right"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class BeamSkills(BarSkills):
|
| 91 |
+
"""BarSkills (records where along the bar the jaws closed) + the task's per-step monitor."""
|
| 92 |
+
|
| 93 |
+
def __init__(self, env, task, recorder=None):
|
| 94 |
+
super().__init__(env, recorder=recorder)
|
| 95 |
+
self.task = task
|
| 96 |
+
|
| 97 |
+
def _act(self, dpos, drot, grip):
|
| 98 |
+
super()._act(dpos, drot, grip)
|
| 99 |
+
self.task.monitor_step()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@register_task
|
| 103 |
+
class LoadedBeam(SlipperyLift):
|
| 104 |
+
name = "l5_loaded_beam"
|
| 105 |
+
level = "L5"
|
| 106 |
+
category = "dynamics_adaptation"
|
| 107 |
+
capabilities = ("Perceive", "Reason", "Plan", "Utilize")
|
| 108 |
+
protocol = "cross"
|
| 109 |
+
max_attempts = 3
|
| 110 |
+
agent_max_steps = 40
|
| 111 |
+
instruction = ("Lift the metal bar together with the two small red blocks resting near its ends, and hold it level "
|
| 112 |
+
"(tilted less than 8 degrees) with its lowest point at least 10 cm above the table. Both blocks must "
|
| 113 |
+
"stay on the bar near its ends. Keep holding the bar when you finish.")
|
| 114 |
+
instruction_indirect = ("Raise the long grey rod with the two little red cubes sitting near its ends and hold it "
|
| 115 |
+
"horizontal (tilted less than 8 degrees), its lowest point at least 10 cm above the table. "
|
| 116 |
+
"Both cubes must stay on the rod near its ends. Keep holding the rod when you finish.")
|
| 117 |
+
|
| 118 |
+
# ------------------------------------------------------------ scene
|
| 119 |
+
def make_bddl(self):
|
| 120 |
+
bar = register_generated("LffBeamBar", weighted_box_xml("lff_beam_bar", HALF, (0.52, 0.55, 0.58, 1.0)))
|
| 121 |
+
dens = LOAD_MASS / (2 * LOAD_H) ** 3
|
| 122 |
+
la = register_generated("LffBeamBlockA", box_xml("lff_beam_block_a", (LOAD_H,) * 3, LOAD_RGBA, density=dens))
|
| 123 |
+
lb = register_generated("LffBeamBlockB", box_xml("lff_beam_block_b", (LOAD_H,) * 3, LOAD_RGBA, density=dens))
|
| 124 |
+
# LIBERO's sampler puts the bar anywhere within +-13 cm of its region's centre (it "keeps the bar's 14 cm
|
| 125 |
+
# radius inside" a 2 cm region) and rejects block placements closer than 14 + 1.8 cm to it: the block regions
|
| 126 |
+
# are >= 19 cm from every possible bar position (the first layout, 2 cm beside the bar's range, failed with
|
| 127 |
+
# "Cannot place all objects" in 13 of 400 resets, this one 0 of 400). apply_instance moves everything anyway.
|
| 128 |
+
objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01)),
|
| 129 |
+
("block_1", la, "block1_region", (-0.11, 0.32, -0.09, 0.34)),
|
| 130 |
+
("block_2", lb, "block2_region", (-0.11, -0.34, -0.09, -0.32))]
|
| 131 |
+
return write_bddl(self.name, "lift the loaded bar and hold it level", objs)
|
| 132 |
+
|
| 133 |
+
def __init__(self, cam_res=None):
|
| 134 |
+
self.mon = None
|
| 135 |
+
self.budget = None # scripted policies only: command budget of the current attempt
|
| 136 |
+
self.ncmd = 0
|
| 137 |
+
super().__init__(cam_res)
|
| 138 |
+
|
| 139 |
+
def sample_instance(self, seed):
|
| 140 |
+
inst = super().sample_instance(seed) # same bar layout and hidden weight as l5_slippery_lift for this seed
|
| 141 |
+
m = inst["mass"]
|
| 142 |
+
inst.update(load_mass=LOAD_MASS, slot=SLOT,
|
| 143 |
+
com_total=float(m * inst["com_offset"] / (m + 2 * LOAD_MASS))) # bar + both blocks on their ends
|
| 144 |
+
return inst
|
| 145 |
+
|
| 146 |
+
def apply_instance(self, inst):
|
| 147 |
+
super().apply_instance(inst) # bar pose, friction, hidden weight (+ envs.refit_bounds)
|
| 148 |
+
x, y = inst["bar_xy"]
|
| 149 |
+
for nm in LOADS:
|
| 150 |
+
envs.set_obj_pose(self.env, nm, [x, y + LOAD_SIGN[nm] * SLOT, BAR_TOP + LOAD_H + 0.0005])
|
| 151 |
+
if LOAD_MU is not None:
|
| 152 |
+
envs.set_friction(self.env, nm, LOAD_MU, priority=3)
|
| 153 |
+
|
| 154 |
+
def reset_instance(self, inst, recorder=None):
|
| 155 |
+
self.env.reset()
|
| 156 |
+
self.apply_instance(inst)
|
| 157 |
+
self.env.sim.forward()
|
| 158 |
+
envs.settle(self.env, 10)
|
| 159 |
+
self.mon = None
|
| 160 |
+
self.sk = BeamSkills(self.env, self, recorder=recorder)
|
| 161 |
+
self._init_monitor()
|
| 162 |
+
return self.sk
|
| 163 |
+
|
| 164 |
+
# ------------------------------------------------------------ state
|
| 165 |
+
def bar_bottom(self):
|
| 166 |
+
return envs.obj_min_z(self.env, BAR) - TZ
|
| 167 |
+
|
| 168 |
+
def load_rel(self, nm):
|
| 169 |
+
"""block centre in the bar frame: (along (+ = towards the bar's left end), side, height above the bar's centre)"""
|
| 170 |
+
c, al, side, up = bar_frame(self.env)
|
| 171 |
+
r = envs.obj_pos(self.env, nm) - c
|
| 172 |
+
return float(r @ al), float(r @ side), float(r @ up)
|
| 173 |
+
|
| 174 |
+
def _block_held(self, nm):
|
| 175 |
+
sk = self.sk
|
| 176 |
+
if sk is None or sk.grip < 0:
|
| 177 |
+
return False
|
| 178 |
+
if np.linalg.norm(envs.obj_pos(self.env, nm) - sk.eef_pos()) > 0.06:
|
| 179 |
+
return False
|
| 180 |
+
return sk.holding(nm)
|
| 181 |
+
|
| 182 |
+
def load_state(self, nm, tol=SLOT_TOL):
|
| 183 |
+
"""'slot+' / 'slot-' (on the bar within `tol` of its left / right end position), 'bar' (on the bar
|
| 184 |
+
elsewhere), 'held', 'table', 'air' (anything else: falling, resting on the gripper ...)"""
|
| 185 |
+
if self._block_held(nm):
|
| 186 |
+
return "held"
|
| 187 |
+
a, s, u = self.load_rel(nm)
|
| 188 |
+
if abs(u - (HALF[2] + LOAD_H)) <= 0.008 and abs(s) <= HALF[0] + 0.003 and abs(a) <= HALF[1] + 0.003:
|
| 189 |
+
if abs(a - SLOT) <= tol:
|
| 190 |
+
return "slot+"
|
| 191 |
+
if abs(a + SLOT) <= tol:
|
| 192 |
+
return "slot-"
|
| 193 |
+
return "bar"
|
| 194 |
+
if envs.obj_pos(self.env, nm)[2] < TZ + 0.027:
|
| 195 |
+
return "table"
|
| 196 |
+
return "air"
|
| 197 |
+
|
| 198 |
+
# ------------------------------------------------------------ monitor
|
| 199 |
+
def _init_monitor(self):
|
| 200 |
+
st = {nm: self.load_state(nm) for nm in LOADS}
|
| 201 |
+
self.mon = dict(stable=dict(st), cand={nm: None for nm in LOADS}, cnt={nm: 0 for nm in LOADS},
|
| 202 |
+
last_on_bar={nm: self.load_rel(nm)[0] for nm in LOADS}, lost=set(), carried=set(), events=[],
|
| 203 |
+
lifts=[],
|
| 204 |
+
lifted=False, tilted=False, max_tilt=0.0)
|
| 205 |
+
|
| 206 |
+
def _event(self, ev, step=None, **kw):
|
| 207 |
+
self.mon["events"].append(dict(step=int(self.sk.n_steps if step is None else step), ev=ev, **kw))
|
| 208 |
+
|
| 209 |
+
def _last_grasp(self):
|
| 210 |
+
return next((c for c in reversed(self.sk.closes) if c["holding"]), None)
|
| 211 |
+
|
| 212 |
+
def monitor_step(self):
|
| 213 |
+
mon, sk = self.mon, self.sk
|
| 214 |
+
if mon is None or sk is None:
|
| 215 |
+
return
|
| 216 |
+
n = sk.n_steps
|
| 217 |
+
# --- the bar: lifts and tilt
|
| 218 |
+
rise = float(envs.obj_pos(self.env, BAR)[2]) - (TZ + HALF[2])
|
| 219 |
+
held = sk.grip > 0 and sk.holding(BAR)
|
| 220 |
+
if not mon["lifted"] and held and rise > LIFTED:
|
| 221 |
+
g = self._last_grasp()
|
| 222 |
+
mon["lifted"], mon["tilted"], mon["max_tilt"] = True, False, 0.0
|
| 223 |
+
mon["lifts"].append(dict(step_up=n, step_down=None, grasp_along=None if g is None else round(g["along"], 4),
|
| 224 |
+
max_tilt_deg=0.0, falls=[]))
|
| 225 |
+
self._event("bar_lifted", grasp_along=mon["lifts"][-1]["grasp_along"])
|
| 226 |
+
if mon["lifted"]:
|
| 227 |
+
t = bar_tilt_deg(self.env)
|
| 228 |
+
lift = mon["lifts"][-1]
|
| 229 |
+
if abs(t) > abs(lift["max_tilt_deg"]):
|
| 230 |
+
lift["max_tilt_deg"] = round(t, 1)
|
| 231 |
+
if not mon["tilted"] and abs(t) > TILT_MAX and held:
|
| 232 |
+
mon["tilted"] = True
|
| 233 |
+
self._event("bar_tilted", tilt_deg=round(t, 1), low_end=_end_word(t))
|
| 234 |
+
if rise < DOWN:
|
| 235 |
+
mon["lifted"] = False
|
| 236 |
+
lift["step_down"] = n
|
| 237 |
+
self._event("bar_set_down", max_tilt_deg=lift["max_tilt_deg"])
|
| 238 |
+
# --- the blocks (debounced state machine)
|
| 239 |
+
for nm in LOADS:
|
| 240 |
+
# hysteresis: a block that has left its end position must come back within 2 cm of an end to count as
|
| 241 |
+
# restored (a block sliding along the tilted bar hovered around the 3 cm limit and flickered)
|
| 242 |
+
s = self.load_state(nm, SLOT_TOL - 0.01 if nm in mon["lost"] else SLOT_TOL)
|
| 243 |
+
if s in ("slot+", "slot-", "bar"):
|
| 244 |
+
mon["last_on_bar"][nm] = self.load_rel(nm)[0]
|
| 245 |
+
old = mon["stable"][nm]
|
| 246 |
+
if s == old:
|
| 247 |
+
mon["cand"][nm], mon["cnt"][nm] = None, 0
|
| 248 |
+
continue
|
| 249 |
+
if s != mon["cand"][nm]:
|
| 250 |
+
mon["cand"][nm], mon["cnt"][nm] = s, 0
|
| 251 |
+
mon["cnt"][nm] += 1
|
| 252 |
+
if mon["cnt"][nm] < DEBOUNCE:
|
| 253 |
+
continue
|
| 254 |
+
step = n - DEBOUNCE + 1
|
| 255 |
+
mon["stable"][nm], mon["cand"][nm], mon["cnt"][nm] = s, None, 0
|
| 256 |
+
start = _end_word(LOAD_SIGN[nm])
|
| 257 |
+
if s == "held":
|
| 258 |
+
mon["carried"].add(nm)
|
| 259 |
+
if s in ("slot+", "slot-"):
|
| 260 |
+
if nm in mon["lost"]:
|
| 261 |
+
# by_robot: the gripper carried it back (else physics did, e.g. the high-end block sliding back out
|
| 262 |
+
# while the bar swings after the other block fell: 3-4 of 59 blind attempts)
|
| 263 |
+
mon["lost"].discard(nm)
|
| 264 |
+
self._event("load_restored", step, load=nm, start_end=start, end=_end_word(1 if s == "slot+" else -1),
|
| 265 |
+
by_robot=nm in mon["carried"])
|
| 266 |
+
mon["carried"].discard(nm)
|
| 267 |
+
elif old in ("slot+", "slot-") and s == "bar":
|
| 268 |
+
mon["lost"].add(nm)
|
| 269 |
+
self._event("load_displaced", step, load=nm, start_end=start, along_cm=round(100 * self.load_rel(nm)[0], 1))
|
| 270 |
+
elif old in ("slot+", "slot-", "bar", "air") and s == "table":
|
| 271 |
+
mon["lost"].add(nm)
|
| 272 |
+
end = _end_word(mon["last_on_bar"][nm])
|
| 273 |
+
self._event("load_fell", step, load=nm, start_end=start, off_end=end)
|
| 274 |
+
if mon["lifted"]:
|
| 275 |
+
mon["lifts"][-1]["falls"].append(nm)
|
| 276 |
+
elif old == "held" and s == "table":
|
| 277 |
+
mon["lost"].add(nm)
|
| 278 |
+
self._event("load_removed", step, load=nm, start_end=start)
|
| 279 |
+
elif old in ("slot+", "slot-") and s == "held":
|
| 280 |
+
mon["lost"].add(nm) # picked up by the agent: counts as lost until it is back on an end
|
| 281 |
+
|
| 282 |
+
# ------------------------------------------------------------ outcome / F2
|
| 283 |
+
def _where(self, nm):
|
| 284 |
+
"""robot-centric description of a block that is not on an end position"""
|
| 285 |
+
st = self.load_state(nm)
|
| 286 |
+
a, s, u = self.load_rel(nm)
|
| 287 |
+
if st == "held":
|
| 288 |
+
return "is held in the gripper"
|
| 289 |
+
if st == "bar":
|
| 290 |
+
e = 1.0 if a >= 0 else -1.0
|
| 291 |
+
return (f"is still on the bar but {100 * (SLOT - abs(a)):.0f} cm in from its {_end_word(e)} end position "
|
| 292 |
+
f"({100 * abs(a):.0f} cm {_end_word(e)} of the bar's middle)")
|
| 293 |
+
c, al, side, up = bar_frame(self.env)
|
| 294 |
+
e = 1.0 if a >= 0 else -1.0
|
| 295 |
+
u = al[:2] / max(np.linalg.norm(al[:2]), 1e-6) # the bar's direction seen from above
|
| 296 |
+
end = c[:2] + al[:2] * e * HALF[1] # the end's position seen from above (also while the bar hangs tilted)
|
| 297 |
+
r = envs.obj_pos(self.env, nm)[:2] - end
|
| 298 |
+
beyond = float(r @ u) * e
|
| 299 |
+
lateral = float(r @ np.array([-u[1], u[0]]))
|
| 300 |
+
where = "on the table" if st == "table" else "off the bar"
|
| 301 |
+
if beyond > 0 and abs(lateral) < 0.04:
|
| 302 |
+
return f"lies {where}, {100 * beyond:.0f} cm beyond the bar's {_end_word(e)} end"
|
| 303 |
+
fx = f"{100 * abs(r[0]):.0f} cm {'forward' if r[0] > 0 else 'back'}"
|
| 304 |
+
fy = f"{100 * abs(r[1]):.0f} cm {'left' if r[1] > 0 else 'right'}"
|
| 305 |
+
return f"lies {where}, {fx} and {fy} of the bar's {_end_word(e)} end"
|
| 306 |
+
|
| 307 |
+
def outcome(self, inst):
|
| 308 |
+
sk, mon = self.sk, self.mon
|
| 309 |
+
sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws)
|
| 310 |
+
held = bool(sk.holding(BAR))
|
| 311 |
+
tilt = bar_tilt_deg(self.env)
|
| 312 |
+
bottom = self.bar_bottom()
|
| 313 |
+
states = {nm: self.load_state(nm) for nm in LOADS}
|
| 314 |
+
on_plus = [nm for nm in LOADS if states[nm] == "slot+"]
|
| 315 |
+
on_minus = [nm for nm in LOADS if states[nm] == "slot-"]
|
| 316 |
+
loads_ok = len(on_plus) == 1 and len(on_minus) == 1
|
| 317 |
+
level_ok = held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN
|
| 318 |
+
success = bool(level_ok and loads_ok)
|
| 319 |
+
lifted_ever = bool(mon["lifts"]) or (sk.zmax - sk.z0) > 0.03
|
| 320 |
+
g = self._last_grasp()
|
| 321 |
+
evs = mon["events"]
|
| 322 |
+
falls = [e for e in evs if e["ev"] == "load_fell"]
|
| 323 |
+
restored = [e for e in evs if e["ev"] == "load_restored"]
|
| 324 |
+
lifts = mon["lifts"]
|
| 325 |
+
first_ok = None if not lifts else bool(not lifts[0]["falls"]) # the first lift spilled nothing
|
| 326 |
+
# --- text
|
| 327 |
+
gtxt = ""
|
| 328 |
+
if g is not None:
|
| 329 |
+
a = g["along"]
|
| 330 |
+
gtxt = (f" You last grasped the bar {100 * abs(a):.1f} cm to the {_end_word(a)} of its middle."
|
| 331 |
+
if abs(a) >= 0.0005 else " You last grasped the bar at its middle.")
|
| 332 |
+
tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {_end_word(tilt)} end lower than its "
|
| 333 |
+
f"{_end_word(-tilt)} end")
|
| 334 |
+
if success:
|
| 335 |
+
failure = None
|
| 336 |
+
bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, "
|
| 337 |
+
"with a block on each end.")
|
| 338 |
+
elif held and abs(tilt) > TILT_MAX:
|
| 339 |
+
failure = "tilted"
|
| 340 |
+
bar_txt = f"The bar did not stay level: it rotated in the gripper and now {tilt_txt}."
|
| 341 |
+
if bottom < LIFT_MIN:
|
| 342 |
+
bar_txt += f" Its lowest point is {100 * bottom:.0f} cm above the table."
|
| 343 |
+
elif held and bottom < LIFT_MIN:
|
| 344 |
+
failure = "too_low"
|
| 345 |
+
bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only "
|
| 346 |
+
f"{100 * bottom:.0f} cm above the table.")
|
| 347 |
+
elif held:
|
| 348 |
+
failure = "load_off"
|
| 349 |
+
bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, "
|
| 350 |
+
"but the blocks are not both on its ends.")
|
| 351 |
+
elif lifted_ever:
|
| 352 |
+
failure = "dropped"
|
| 353 |
+
bar_txt = "The bar was lifted but is no longer in the gripper; it lies on the table."
|
| 354 |
+
else:
|
| 355 |
+
failure = "no_grasp"
|
| 356 |
+
bar_txt = ("The gripper never closed on the bar; it is still lying on the table." if not sk.closes else
|
| 357 |
+
"The gripper did not catch the bar; it is still lying on the table.")
|
| 358 |
+
parts = [bar_txt]
|
| 359 |
+
if falls:
|
| 360 |
+
f0 = falls[0]
|
| 361 |
+
lift = next((l for l in lifts if f0["load"] in l["falls"]), None)
|
| 362 |
+
how = (f" while the bar hung tilted by up to {abs(lift['max_tilt_deg']):.0f} degrees with its "
|
| 363 |
+
f"{_end_word(lift['max_tilt_deg'])} end lower") if lift and abs(lift["max_tilt_deg"]) > 1 else ""
|
| 364 |
+
parts.append(f"The {f0['start_end']} block slid off the bar's {f0['off_end']} end{how}."
|
| 365 |
+
+ (f" Blocks fell off {len(falls)} times in this attempt." if len(falls) > 1 else ""))
|
| 366 |
+
if not loads_ok:
|
| 367 |
+
for nm in LOADS:
|
| 368 |
+
if states[nm] in ("slot+", "slot-") and (len(on_plus) == 1 or states[nm] != "slot+") and \
|
| 369 |
+
(len(on_minus) == 1 or states[nm] != "slot-"):
|
| 370 |
+
continue
|
| 371 |
+
parts.append(f"The {_end_word(LOAD_SIGN[nm])} block {self._where(nm)}.")
|
| 372 |
+
detail = " ".join(parts) + gtxt
|
| 373 |
+
loads = {}
|
| 374 |
+
for nm in LOADS:
|
| 375 |
+
a, s, u = self.load_rel(nm)
|
| 376 |
+
loads[nm] = dict(state=states[nm], along_cm=round(100 * a, 1), side_cm=round(100 * s, 1),
|
| 377 |
+
above_bar_centre_cm=round(100 * u, 1))
|
| 378 |
+
out = dict(success=success, failure=failure, held=held, tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1),
|
| 379 |
+
grasp_along=None if g is None else round(g["along"], 4),
|
| 380 |
+
stages=dict(bar_held_level_high=bool(level_ok), loads_on_ends=bool(loads_ok)),
|
| 381 |
+
loads=loads, loads_on_ends=len(on_plus) + len(on_minus) if loads_ok else
|
| 382 |
+
int(len(on_plus) >= 1) + int(len(on_minus) >= 1),
|
| 383 |
+
trap_fired=bool(falls), n_load_falls=len(falls), n_restored=len(restored),
|
| 384 |
+
n_restored_by_robot=len([e for e in restored if e.get("by_robot")]),
|
| 385 |
+
n_regressions=len([e for e in evs if e["ev"] in ("load_fell", "load_displaced")]),
|
| 386 |
+
recovered_in_attempt=bool(falls and success), first_interaction_ok=first_ok,
|
| 387 |
+
n_lifts=len(lifts), lifts=lifts, events=list(evs), closes=sk.closes, detail=detail)
|
| 388 |
+
out["detail_indirect"] = detail.replace("bar", "rod").replace("block", "cube")
|
| 389 |
+
return out
|
| 390 |
+
|
| 391 |
+
# ------------------------------------------------------------ scripted primitives (agent-command counted)
|
| 392 |
+
def _cmd(self, target=None, yaw=None, speed=None, grip=None, tol=0.004, max_steps=250):
|
| 393 |
+
"""one agent command (move_eef with an optional gripper action, or observe when nothing is given)"""
|
| 394 |
+
self.ncmd += 1
|
| 395 |
+
if self.budget is not None and self.ncmd > self.budget:
|
| 396 |
+
raise _Budget()
|
| 397 |
+
sk = self.sk
|
| 398 |
+
if target is not None:
|
| 399 |
+
t = np.asarray(target, float).copy()
|
| 400 |
+
t[2] = max(t[2], TZ + 0.006) # the agent interface does not go below 0.5 cm above the table
|
| 401 |
+
sk.move_to(t, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 402 |
+
if grip is not None:
|
| 403 |
+
sk.set_gripper(bool(grip))
|
| 404 |
+
|
| 405 |
+
def grasp_lift(self, along, lift=0.15, speed=0.10, dx=0.0):
|
| 406 |
+
"""open, above the grasp point (jaws across the bar), descend, close, lift, look: 5 commands"""
|
| 407 |
+
c, al, side, up = bar_frame(self.env)
|
| 408 |
+
g = c + al * float(along) + np.array([dx, 0.0, 0.0])
|
| 409 |
+
z = max(float(c[2]), Z_GRASP)
|
| 410 |
+
self._cmd([g[0], g[1], z + 0.10], yaw=YAW_ACROSS, grip=False)
|
| 411 |
+
self._cmd([g[0], g[1], z], tol=0.003)
|
| 412 |
+
self._cmd(grip=True)
|
| 413 |
+
self._cmd([g[0], g[1], z + lift], speed=speed, max_steps=600)
|
| 414 |
+
self._cmd()
|
| 415 |
+
|
| 416 |
+
def put_down(self):
|
| 417 |
+
"""lower the held bar onto the table, release, back up: 2 commands"""
|
| 418 |
+
e = self.sk.eef_pos()
|
| 419 |
+
self._cmd([e[0], e[1], Z_GRASP + 0.003], speed=0.05, grip=False, max_steps=600)
|
| 420 |
+
self._cmd([e[0], e[1], Z_GRASP + 0.12])
|
| 421 |
+
|
| 422 |
+
def _block_yaw(self, nm):
|
| 423 |
+
"""gripper yaw whose jaws close on two faces of the block, preferring jaws that do not reach towards the bar"""
|
| 424 |
+
q = envs.obj_quat(self.env, nm)
|
| 425 |
+
w, x, y, z = q
|
| 426 |
+
psi = float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 427 |
+
c, al, side, up = bar_frame(self.env)
|
| 428 |
+
p = envs.obj_pos(self.env, nm)
|
| 429 |
+
a = float(np.clip((p - c) @ al, -HALF[1], HALF[1]))
|
| 430 |
+
v = (p - (c + al * a))[:2]
|
| 431 |
+
v = v / max(np.linalg.norm(v), 1e-6)
|
| 432 |
+
best = None
|
| 433 |
+
for k in range(2):
|
| 434 |
+
ang = psi + k * np.pi / 2 # closing direction candidate (a face normal)
|
| 435 |
+
n = np.array([np.cos(ang), np.sin(ang)])
|
| 436 |
+
score = abs(n @ v)
|
| 437 |
+
if best is None or score < best[0]:
|
| 438 |
+
best = (score, ang)
|
| 439 |
+
yaw = best[1] + np.pi / 2 # yaw = closing direction + 90 deg (YAW_ACROSS closes along world x)
|
| 440 |
+
return float((yaw + np.pi / 2) % np.pi - np.pi / 2)
|
| 441 |
+
|
| 442 |
+
def move_block_to_slot(self, nm, sign, tries=2):
|
| 443 |
+
"""pick a block (from the table or the bar) and set it on the end position `sign`: 6 commands per try"""
|
| 444 |
+
sk = self.sk
|
| 445 |
+
for _ in range(tries):
|
| 446 |
+
p = envs.obj_pos(self.env, nm)
|
| 447 |
+
yaw = self._block_yaw(nm)
|
| 448 |
+
zg = max(float(p[2]), TZ + 0.008)
|
| 449 |
+
self._cmd([p[0], p[1], zg + 0.08], yaw=yaw, grip=False)
|
| 450 |
+
self._cmd([p[0], p[1], zg], tol=0.003, grip=True)
|
| 451 |
+
self._cmd([p[0], p[1], BAR_TOP + LOAD_H + 0.07])
|
| 452 |
+
if not sk.holding(nm):
|
| 453 |
+
continue
|
| 454 |
+
c, al, side, up = bar_frame(self.env)
|
| 455 |
+
t = c + al * sign * SLOT
|
| 456 |
+
ztop = envs.obj_max_z(self.env, BAR)
|
| 457 |
+
self._cmd([t[0], t[1], ztop + LOAD_H + 0.06])
|
| 458 |
+
self._cmd([t[0], t[1], ztop + LOAD_H + 0.004], speed=0.05, grip=False)
|
| 459 |
+
self._cmd([t[0], t[1], ztop + LOAD_H + 0.08])
|
| 460 |
+
if self.load_state(nm) == ("slot+" if sign > 0 else "slot-"):
|
| 461 |
+
return True
|
| 462 |
+
return False
|
| 463 |
+
|
| 464 |
+
def restore_loads(self):
|
| 465 |
+
"""put every block that is not on an end position back onto a free end; True if both ends are taken"""
|
| 466 |
+
for _ in range(2):
|
| 467 |
+
st = {nm: self.load_state(nm) for nm in LOADS}
|
| 468 |
+
free = [s for s in (1.0, -1.0) if not any(v == ("slot+" if s > 0 else "slot-") for v in st.values())]
|
| 469 |
+
if not free:
|
| 470 |
+
return True
|
| 471 |
+
loose = [nm for nm in LOADS if st[nm] not in ("slot+", "slot-")]
|
| 472 |
+
for sgn in free:
|
| 473 |
+
if not loose:
|
| 474 |
+
break
|
| 475 |
+
c, al, side, up = bar_frame(self.env)
|
| 476 |
+
slot = c + al * sgn * SLOT
|
| 477 |
+
nm = min(loose, key=lambda b: np.linalg.norm(envs.obj_pos(self.env, b)[:2] - slot[:2]))
|
| 478 |
+
loose.remove(nm)
|
| 479 |
+
self.move_block_to_slot(nm, sgn)
|
| 480 |
+
self._cmd() # look
|
| 481 |
+
st = {nm: self.load_state(nm) for nm in LOADS}
|
| 482 |
+
return sorted(st.values()) == ["slot+", "slot-"]
|
| 483 |
+
|
| 484 |
+
def judge(self):
|
| 485 |
+
"""what an agent sees after a lift (perfect perception): (all good, tilt, blocks on their ends)"""
|
| 486 |
+
tilt = bar_tilt_deg(self.env)
|
| 487 |
+
st = sorted(self.load_state(nm) for nm in LOADS)
|
| 488 |
+
ok_loads = st == ["slot+", "slot-"]
|
| 489 |
+
good = self.sk.holding(BAR) and abs(tilt) <= TILT_MAX - 2 and self.bar_bottom() >= LIFT_MIN + 0.01 and ok_loads
|
| 490 |
+
return bool(good), float(tilt), ok_loads
|
| 491 |
+
|
| 492 |
+
# ------------------------------------------------------------ scripted policies
|
| 493 |
+
def execute(self, inst, params):
|
| 494 |
+
self.grasp_lift(params["along"], params.get("lift", 0.15), params.get("speed", 0.10), params.get("dx", 0.0))
|
| 495 |
+
|
| 496 |
+
def default_params(self, inst):
|
| 497 |
+
return dict(along=0.0, lift=0.15, speed=0.10) # Sonnet 5.5 (cla4): middle, up to ~15-18 cm at 0.1 m/s
|
| 498 |
+
|
| 499 |
+
def oracle_params(self, inst):
|
| 500 |
+
return dict(along=float(inst["com_total"]), lift=0.15, speed=0.10)
|
| 501 |
+
|
| 502 |
+
def blind_params(self, inst, attempt, rng):
|
| 503 |
+
return dict(along=float(rng.normal(0.0, 0.01)), lift=float(rng.uniform(0.12, 0.18)),
|
| 504 |
+
speed=float(rng.uniform(0.05, 0.20)))
|
| 505 |
+
|
| 506 |
+
MARGIN = 0.008 # a lift that sank towards +y at grasp g says COM > g + MARGIN
|
| 507 |
+
STEP = 0.030 # first move towards the end that sank when only one side is bounded
|
| 508 |
+
|
| 509 |
+
def bracket(self, obs):
|
| 510 |
+
"""grasp point from (grasp_along, tilt) observations: the end that sank is the heavy side of that grasp"""
|
| 511 |
+
lo, hi = -SAFE_ALONG, SAFE_ALONG
|
| 512 |
+
lo_set = hi_set = False
|
| 513 |
+
for g, t in obs:
|
| 514 |
+
if t > 0:
|
| 515 |
+
lo, lo_set = max(lo, g + self.MARGIN), True
|
| 516 |
+
else:
|
| 517 |
+
hi, hi_set = min(hi, g - self.MARGIN), True
|
| 518 |
+
if lo_set and hi_set:
|
| 519 |
+
a = 0.5 * (lo + hi)
|
| 520 |
+
elif lo_set:
|
| 521 |
+
a = lo + self.STEP - self.MARGIN
|
| 522 |
+
elif hi_set:
|
| 523 |
+
a = hi - self.STEP + self.MARGIN
|
| 524 |
+
else:
|
| 525 |
+
a = 0.0
|
| 526 |
+
return float(np.clip(a, -SAFE_ALONG, SAFE_ALONG))
|
| 527 |
+
|
| 528 |
+
def adapt_params(self, inst, history):
|
| 529 |
+
obs = [o for h in history for o in h["params"].get("obs", [])]
|
| 530 |
+
return dict(along=self.bracket(obs))
|
| 531 |
+
|
| 532 |
+
def adaptive_attempt(self, obs):
|
| 533 |
+
"""lift at the current estimate; if the bar tilts or a block falls: set the bar down, put the blocks back,
|
| 534 |
+
regrasp on the side of the end that sank (bracketing), lift again -- while the command budget allows"""
|
| 535 |
+
tried = []
|
| 536 |
+
along = self.bracket(obs)
|
| 537 |
+
while True:
|
| 538 |
+
tried.append(round(along, 4))
|
| 539 |
+
self.grasp_lift(along)
|
| 540 |
+
good, tilt, ok_loads = self.judge()
|
| 541 |
+
if good:
|
| 542 |
+
return tried
|
| 543 |
+
g = self._last_grasp()
|
| 544 |
+
if abs(tilt) > 3.0 or not ok_loads:
|
| 545 |
+
lift = self.mon["lifts"][-1] if self.mon["lifts"] else None
|
| 546 |
+
t = tilt if abs(tilt) > 3.0 else (lift["max_tilt_deg"] if lift else 0.0)
|
| 547 |
+
if abs(t) > 1.0:
|
| 548 |
+
obs.append((g["along"] if g is not None else along, t))
|
| 549 |
+
# a repair = set down (2) + both blocks back (2 x 6: the fallen one and the one that slid to the fingers)
|
| 550 |
+
# + look (1) + regrasp, lift, look (5) = 20 commands; without enough budget keep holding the bar as it is
|
| 551 |
+
if self.budget is not None and self.ncmd + 20 > self.budget:
|
| 552 |
+
return tried
|
| 553 |
+
self.put_down()
|
| 554 |
+
if not self.restore_loads():
|
| 555 |
+
return tried
|
| 556 |
+
along = self.bracket(obs)
|
| 557 |
+
|
| 558 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 559 |
+
"""cross protocol with an agent-like command budget per attempt (agent_max_steps; one move_eef with an optional
|
| 560 |
+
gripper action, or one observe, = one command). naive / oracle / blind: one lift, no checking.
|
| 561 |
+
adaptive: naive in attempt 1 but checks and repairs inside the attempt (`adaptive_attempt`); later attempts
|
| 562 |
+
start from the grasp point learned so far."""
|
| 563 |
+
k = k or self.max_attempts
|
| 564 |
+
rng = np.random.default_rng(seed)
|
| 565 |
+
history, obs = [], []
|
| 566 |
+
for a in range(k):
|
| 567 |
+
self.reset_instance(inst)
|
| 568 |
+
self.ncmd, self.budget = 0, self.agent_max_steps
|
| 569 |
+
if kind == "oracle":
|
| 570 |
+
params = self.oracle_params(inst)
|
| 571 |
+
elif kind == "naive":
|
| 572 |
+
params = self.default_params(inst)
|
| 573 |
+
elif kind == "blind":
|
| 574 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 575 |
+
elif kind == "adaptive":
|
| 576 |
+
params = dict(obs=[])
|
| 577 |
+
else:
|
| 578 |
+
raise ValueError(kind)
|
| 579 |
+
n0 = len(obs)
|
| 580 |
+
try:
|
| 581 |
+
if kind == "adaptive":
|
| 582 |
+
params["tried"] = self.adaptive_attempt(obs)
|
| 583 |
+
else:
|
| 584 |
+
self.execute(inst, params)
|
| 585 |
+
except _Budget:
|
| 586 |
+
params["budget_used_up"] = True
|
| 587 |
+
if kind == "adaptive":
|
| 588 |
+
params["obs"] = [[round(g, 4), round(t, 1)] for g, t in obs[n0:]]
|
| 589 |
+
self.budget = None
|
| 590 |
+
out = self.outcome(inst)
|
| 591 |
+
out["commands"] = self.ncmd
|
| 592 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 593 |
+
if on_attempt:
|
| 594 |
+
on_attempt(a, params, out)
|
| 595 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 596 |
+
break
|
| 597 |
+
return history
|
| 598 |
+
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l5_slippery_lift.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L5-B slippery_lift: pick up a heavy, slippery metal bar and hold it level.
|
| 2 |
+
|
| 3 |
+
Category dynamics_adaptation (L5): "figure out how this object moves".
|
| 4 |
+
|
| 5 |
+
Scene: one long steel-grey bar (4 x 28 x 4 cm, lying along the robot's left-right axis) on the table. It looks
|
| 6 |
+
perfectly uniform, but a heavy slug is hidden inside it at an unknown position, so its centre of mass sits
|
| 7 |
+
e = 2.5-7 cm from the bar's midpoint, towards the left or the right end. The bar is heavy (0.8-1.2 kg) and its
|
| 8 |
+
surface is slippery (finger friction 0.40-0.60): the two finger pads can hold its weight, but they cannot hold
|
| 9 |
+
much torque.
|
| 10 |
+
|
| 11 |
+
Why the prior fails. The natural grasp is across the bar at its midpoint. With the centre of mass a few cm to
|
| 12 |
+
one side, gravity twists the bar in the pads as soon as it is lifted: the heavy end swings down and the bar
|
| 13 |
+
ends up hanging tilted by ~10-50 deg (measured). Slow lifting does not help (the torque is static).
|
| 14 |
+
|
| 15 |
+
What has to be learned. Which end sank tells on which side of the grasp the centre of mass lies; the grasp
|
| 16 |
+
has to move towards that end until it is within ~1.5 cm of the hidden centre of mass (measured window). The
|
| 17 |
+
tilt magnitude saturates, so the distance has to be found by bracketing over a few attempts.
|
| 18 |
+
|
| 19 |
+
Measured physics (2026-10-07, `l5dyn/bar_win.py`): mass 0.8-1.2 kg, mu 0.4-0.6, lift 15 cm at 0.15 m/s:
|
| 20 |
+
|grasp - COM| <= 1.0 cm -> tilt <= 2 deg; 1.5 cm -> 0-41 deg; >= 2 cm -> mostly 30-50 deg; the tilt does not
|
| 21 |
+
creep during a 3 s hold. mu 0.8 gave non-monotone tilts and is not used; mu 0.3 + 1.3 kg slips out entirely.
|
| 22 |
+
"""
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from .. import envs
|
| 26 |
+
from ..bddl import write_bddl
|
| 27 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 28 |
+
from ..skills import Skills
|
| 29 |
+
from ..task_base import LFFTask, register_task
|
| 30 |
+
|
| 31 |
+
BAR = "bar_1"
|
| 32 |
+
HALF = (0.02, 0.14, 0.02) # 4 (x) x 28 (y) x 4 (z) cm, long axis along world y
|
| 33 |
+
_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
|
| 34 |
+
W_FRAC = 0.6 # fraction of the bar's mass in the hidden slug
|
| 35 |
+
W_HALF = 0.015 # slug half size (for its inertia)
|
| 36 |
+
E_MIN, E_MAX = 0.025, 0.070 # |COM offset| from the bar's midpoint (m)
|
| 37 |
+
LIFT_MIN = 0.10 # the bar's lowest point must be this high above the table
|
| 38 |
+
TILT_MAX = 8.0 # deg
|
| 39 |
+
Z_GRASP = envs.TABLE_Z + HALF[2] # gripper site at the bar's mid height (finger tips 0.7 cm above the table)
|
| 40 |
+
Z_LIFT = Z_GRASP + 0.15
|
| 41 |
+
YAW_ACROSS = np.pi / 2 # jaws close along world x, i.e. across the bar
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def weighted_box_xml(name, half, rgba, mass=1.0, friction=(1.0, 0.005, 0.0001)):
|
| 45 |
+
"""Box with an explicit inertial. Its pos is off-centre at compile time so MuJoCo keeps
|
| 46 |
+
body_sameframe = 0 / body_simple = 0 and honours the per-instance body_ipos set in apply_instance."""
|
| 47 |
+
I = [mass / 3 * (half[1] ** 2 + half[2] ** 2), mass / 3 * (half[0] ** 2 + half[2] ** 2),
|
| 48 |
+
mass / 3 * (half[0] ** 2 + half[1] ** 2)]
|
| 49 |
+
g = (f' <inertial pos="0 0.001 0.001" mass="{mass}" diaginertia="{_fmt(I)}" />\n'
|
| 50 |
+
f' <geom name="{name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 51 |
+
f'friction="{_fmt(friction)}" {_SOLID} group="0" />\n'
|
| 52 |
+
f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
|
| 53 |
+
return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def set_hidden_weight(env, obj, half, mass, w_frac, w_pos, w_half=W_HALF):
|
| 57 |
+
"""Uniform shell of mass (1 - w_frac) * mass plus a hidden cube slug of w_frac * mass at w_pos (body frame).
|
| 58 |
+
Sets the body's mass, centre of mass and inertia; returns the centre of mass (body frame)."""
|
| 59 |
+
m = env.sim.model
|
| 60 |
+
bid = envs.body_id(env, obj)
|
| 61 |
+
ms, mw = (1 - w_frac) * mass, w_frac * mass
|
| 62 |
+
w_pos = np.asarray(w_pos, float)
|
| 63 |
+
c = mw * w_pos / mass
|
| 64 |
+
hx, hy, hz = half
|
| 65 |
+
|
| 66 |
+
def par(mm, r): # parallel-axis terms (diagonal)
|
| 67 |
+
return mm * np.array([r[1] ** 2 + r[2] ** 2, r[0] ** 2 + r[2] ** 2, r[0] ** 2 + r[1] ** 2])
|
| 68 |
+
|
| 69 |
+
I = (ms / 3 * np.array([hy ** 2 + hz ** 2, hx ** 2 + hz ** 2, hx ** 2 + hy ** 2]) + par(ms, -c)
|
| 70 |
+
+ mw / 6 * (2 * w_half) ** 2 * np.ones(3) + par(mw, w_pos - c))
|
| 71 |
+
m.body_mass[bid] = mass
|
| 72 |
+
m.body_ipos[bid] = c
|
| 73 |
+
m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 74 |
+
m.body_inertia[bid] = I
|
| 75 |
+
envs.refit_bounds(env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds)
|
| 76 |
+
return c
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def bar_axis(env):
|
| 80 |
+
"""World direction of the bar's long axis (body y)."""
|
| 81 |
+
return env.sim.data.body_xmat[envs.body_id(env, BAR)].reshape(3, 3)[:, 1].copy()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def bar_tilt_deg(env):
|
| 85 |
+
"""Signed tilt of the bar's long axis from horizontal; > 0: the bar's +y end is lower."""
|
| 86 |
+
ax = bar_axis(env)
|
| 87 |
+
if ax[1] < 0: # orient the axis towards the robot's left so the sign is about world left/right
|
| 88 |
+
ax = -ax
|
| 89 |
+
return float(np.degrees(np.arcsin(np.clip(-ax[2], -1.0, 1.0))))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def side_words(sign):
|
| 93 |
+
return "left (+y)" if sign > 0 else "right (-y)"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class BarSkills(Skills):
|
| 97 |
+
"""Skills that record where along the bar the jaws closed, whoever drives them (scripted or agent)."""
|
| 98 |
+
|
| 99 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 100 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 101 |
+
self.closes = []
|
| 102 |
+
self.zmax = float(envs.obj_pos(env, BAR)[2])
|
| 103 |
+
self.z0 = self.zmax
|
| 104 |
+
|
| 105 |
+
def _act(self, dpos, drot, grip):
|
| 106 |
+
super()._act(dpos, drot, grip)
|
| 107 |
+
self.zmax = max(self.zmax, float(envs.obj_pos(self.env, BAR)[2]))
|
| 108 |
+
|
| 109 |
+
def set_gripper(self, close, steps=15):
|
| 110 |
+
rep = super().set_gripper(close, steps)
|
| 111 |
+
if close:
|
| 112 |
+
c = envs.obj_pos(self.env, BAR)
|
| 113 |
+
ax = bar_axis(self.env)
|
| 114 |
+
if ax[1] < 0:
|
| 115 |
+
ax = -ax
|
| 116 |
+
along = float((self.eef_pos() - c) @ ax) # + : grasp on the left (+y) side of the midpoint
|
| 117 |
+
self.closes.append(dict(along=along, holding=self.holding(BAR), step=self.n_steps))
|
| 118 |
+
return rep
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@register_task
|
| 122 |
+
class SlipperyLift(LFFTask):
|
| 123 |
+
name = "l5_slippery_lift"
|
| 124 |
+
level = "L5"
|
| 125 |
+
category = "dynamics_adaptation"
|
| 126 |
+
capabilities = ("Perceive", "Reason", "Utilize")
|
| 127 |
+
protocol = "cross"
|
| 128 |
+
instruction = ("Pick up the metal bar and hold it level (tilted less than 8 degrees), with its lowest point at "
|
| 129 |
+
"least 10 cm above the table. Keep holding it when you finish.")
|
| 130 |
+
instruction_indirect = ("Pick up the long grey rod lying on the table and hold it horizontal (tilted less than 8 "
|
| 131 |
+
"degrees), with its lowest point at least 10 cm above the table. Keep holding it when you "
|
| 132 |
+
"finish.")
|
| 133 |
+
|
| 134 |
+
# ------------------------------------------------------------ scene
|
| 135 |
+
def make_bddl(self):
|
| 136 |
+
bar = register_generated("LffSteelBar", weighted_box_xml("lff_steel_bar", HALF, (0.52, 0.55, 0.58, 1.0)))
|
| 137 |
+
objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01))]
|
| 138 |
+
return write_bddl(self.name, "pick up the bar and hold it level", objs) # BDDL cannot parse parentheses
|
| 139 |
+
|
| 140 |
+
def sample_instance(self, seed):
|
| 141 |
+
rng = np.random.default_rng(seed)
|
| 142 |
+
e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX))
|
| 143 |
+
return dict(seed=int(seed),
|
| 144 |
+
bar_xy=[float(rng.uniform(-0.12, -0.03)), float(rng.uniform(-0.06, 0.06))],
|
| 145 |
+
com_offset=e, # along the bar, + = towards the robot's left (+y) end
|
| 146 |
+
mass=float(rng.uniform(0.8, 1.2)),
|
| 147 |
+
mu=float(rng.uniform(0.40, 0.60)))
|
| 148 |
+
|
| 149 |
+
def apply_instance(self, inst):
|
| 150 |
+
x, y = inst["bar_xy"]
|
| 151 |
+
envs.set_obj_pose(self.env, BAR, [x, y, envs.TABLE_Z + HALF[2] + 0.001])
|
| 152 |
+
envs.set_friction(self.env, BAR, inst["mu"])
|
| 153 |
+
set_hidden_weight(self.env, BAR, HALF, inst["mass"], W_FRAC, [0.0, inst["com_offset"] / W_FRAC, 0.0])
|
| 154 |
+
|
| 155 |
+
def reset_instance(self, inst, recorder=None):
|
| 156 |
+
self.env.reset()
|
| 157 |
+
self.apply_instance(inst)
|
| 158 |
+
self.env.sim.forward()
|
| 159 |
+
envs.settle(self.env, 10)
|
| 160 |
+
self.sk = BarSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
|
| 161 |
+
return self.sk
|
| 162 |
+
|
| 163 |
+
# ------------------------------------------------------------ outcome
|
| 164 |
+
def outcome(self, inst):
|
| 165 |
+
sk = self.sk
|
| 166 |
+
sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws)
|
| 167 |
+
held = sk.holding(BAR)
|
| 168 |
+
tilt = bar_tilt_deg(self.env)
|
| 169 |
+
bottom = envs.obj_min_z(self.env, BAR) - envs.TABLE_Z
|
| 170 |
+
lifted = (sk.zmax - sk.z0) > 0.03
|
| 171 |
+
close = next((c for c in reversed(sk.closes) if c["holding"]), sk.closes[-1] if sk.closes else None)
|
| 172 |
+
success = bool(held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN)
|
| 173 |
+
out = dict(success=success, held=bool(held), tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1),
|
| 174 |
+
grasp_along=None if close is None else round(close["along"], 4))
|
| 175 |
+
g = ""
|
| 176 |
+
if close is not None and close["holding"]:
|
| 177 |
+
a = close["along"]
|
| 178 |
+
g = (f" You grasped the bar {100 * abs(a):.1f} cm to the {side_words(a)} of its midpoint."
|
| 179 |
+
if abs(a) >= 0.0005 else " You grasped the bar at its midpoint.")
|
| 180 |
+
tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {side_words(tilt).split()[0]} end lower than its "
|
| 181 |
+
f"{side_words(-tilt).split()[0]} end")
|
| 182 |
+
if success:
|
| 183 |
+
out["failure"] = None
|
| 184 |
+
detail = f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table." + g
|
| 185 |
+
elif held and abs(tilt) > TILT_MAX:
|
| 186 |
+
out["failure"] = "tilted"
|
| 187 |
+
detail = ("The bar did not stay level: it rotated in the gripper while it was being lifted and now "
|
| 188 |
+
f"{tilt_txt}." + g)
|
| 189 |
+
if bottom < LIFT_MIN:
|
| 190 |
+
detail += f" Its lowest point is {100 * bottom:.0f} cm above the table."
|
| 191 |
+
elif held:
|
| 192 |
+
out["failure"] = "too_low"
|
| 193 |
+
detail = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only "
|
| 194 |
+
f"{100 * bottom:.0f} cm above the table." + g)
|
| 195 |
+
elif lifted:
|
| 196 |
+
out["failure"] = "dropped"
|
| 197 |
+
detail = ("The bar was lifted but slipped out of the gripper and fell back onto the table "
|
| 198 |
+
f"(it now lies tilted by {abs(tilt):.0f} degrees)." + g)
|
| 199 |
+
elif close is None:
|
| 200 |
+
out["failure"] = "no_grasp"
|
| 201 |
+
detail = "The gripper never closed on the bar; it is still lying on the table."
|
| 202 |
+
else:
|
| 203 |
+
out["failure"] = "no_grasp"
|
| 204 |
+
detail = "The gripper closed but did not catch the bar; it is still lying on the table."
|
| 205 |
+
out["detail"] = detail
|
| 206 |
+
out["detail_indirect"] = detail.replace("bar", "rod")
|
| 207 |
+
return out
|
| 208 |
+
|
| 209 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 210 |
+
if indirect and level == "F2":
|
| 211 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 212 |
+
return super().feedback(inst, out, level)
|
| 213 |
+
|
| 214 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 215 |
+
def execute(self, inst, params):
|
| 216 |
+
"""Grasp across the bar at `along` (m from the visible midpoint, + = left / +y) and lift 15 cm."""
|
| 217 |
+
sk = self.sk
|
| 218 |
+
c = envs.obj_pos(self.env, BAR) # visible bar pose (perfect perception)
|
| 219 |
+
ax = bar_axis(self.env)
|
| 220 |
+
if ax[1] < 0:
|
| 221 |
+
ax = -ax
|
| 222 |
+
g = c + ax * float(params["along"])
|
| 223 |
+
sk.set_gripper(False, steps=5)
|
| 224 |
+
sk.move_to([g[0], g[1], Z_GRASP + 0.10], yaw=YAW_ACROSS)
|
| 225 |
+
sk.move_to([g[0], g[1], Z_GRASP], tol=0.003)
|
| 226 |
+
sk.set_gripper(True, steps=15)
|
| 227 |
+
sk.move_to([g[0], g[1], Z_LIFT], speed=0.15, tol=0.004, max_steps=300)
|
| 228 |
+
|
| 229 |
+
def default_params(self, inst):
|
| 230 |
+
return dict(along=0.0)
|
| 231 |
+
|
| 232 |
+
def oracle_params(self, inst):
|
| 233 |
+
return dict(along=float(inst["com_offset"]))
|
| 234 |
+
|
| 235 |
+
MARGIN = 0.008 # a tilt towards +y at grasp g means COM > g + MARGIN (window is ~+-1.5 cm)
|
| 236 |
+
STEP = 0.030 # first step towards the heavy end when only one side is bounded
|
| 237 |
+
|
| 238 |
+
def adapt_params(self, inst, history):
|
| 239 |
+
"""Bracketing on the grasp point: the end that sank is the heavy side of the last grasp."""
|
| 240 |
+
lo, hi = -HALF[1], HALF[1]
|
| 241 |
+
lo_set = hi_set = False
|
| 242 |
+
for h in history:
|
| 243 |
+
o = h["outcome"]
|
| 244 |
+
g = o["grasp_along"] if o.get("grasp_along") is not None else h["params"]["along"]
|
| 245 |
+
if o.get("failure") == "tilted" or (o.get("failure") == "dropped" and abs(o["tilt_deg"]) > 3):
|
| 246 |
+
if o["tilt_deg"] > 0: # left end sank -> COM left of the grasp
|
| 247 |
+
lo, lo_set = max(lo, g + self.MARGIN), True
|
| 248 |
+
else:
|
| 249 |
+
hi, hi_set = min(hi, g - self.MARGIN), True
|
| 250 |
+
last = history[-1]["params"]["along"]
|
| 251 |
+
if lo_set and hi_set:
|
| 252 |
+
a = 0.5 * (lo + hi)
|
| 253 |
+
elif lo_set:
|
| 254 |
+
a = lo + self.STEP - self.MARGIN
|
| 255 |
+
elif hi_set:
|
| 256 |
+
a = hi - self.STEP + self.MARGIN
|
| 257 |
+
else: # no direction information (e.g. too low): repeat
|
| 258 |
+
a = last
|
| 259 |
+
return dict(along=float(np.clip(a, -0.12, 0.12)))
|
| 260 |
+
|
| 261 |
+
def blind_params(self, inst, attempt, rng):
|
| 262 |
+
return dict(along=float(rng.normal(0.0, 0.01)))
|
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L5-C tablecloth_pull: yank a board out from under a cube so that the cube lands inside a band.
|
| 2 |
+
|
| 3 |
+
Category dynamics_adaptation (L5): "figure out how this object moves". Replaces l5_tip_threshold, which could not
|
| 4 |
+
be built robustly with this robot (see task_cards/l5_tip_threshold.md).
|
| 5 |
+
|
| 6 |
+
Scene: a 30 x 8 x 1 cm wooden board lies on the table, pointing away from the robot, with a black handle block
|
| 7 |
+
at its near end. A red 4 cm cube stands on the far part of the board. A green band (6 cm deep, across the
|
| 8 |
+
table) is painted on the table under the board, a few cm closer to the robot than the cube. The agent may touch
|
| 9 |
+
only the board / handle, never the cube.
|
| 10 |
+
|
| 11 |
+
Physics. If the board is pulled slowly the cube rides along on it (static friction). If it is yanked, the board
|
| 12 |
+
slides out from under the cube; while it slides, friction drags the cube a little towards the robot, so the
|
| 13 |
+
cube drops onto the table having moved d towards the robot. d DEcreases with the pull speed (counter-intuitive:
|
| 14 |
+
a harder yank moves the cube less) and increases with the cube-board friction mu.
|
| 15 |
+
|
| 16 |
+
Hidden variable: the cube's friction mu (0.08-0.15; the cube looks the same for every mu), which shifts the whole
|
| 17 |
+
speed -> displacement curve and the speed below which the cube rides along.
|
| 18 |
+
|
| 19 |
+
Why the prior fails. The classic tablecloth prior is to yank as fast as possible (0.6 m/s, the arm's top speed);
|
| 20 |
+
the band is always placed >= 1.3 cm beyond the displacement such a yank produces, so the cube lands short of it. F2 reports where the cube ended relative to the band (robot-frame words, cm) or that it
|
| 21 |
+
rode along; the agent has to infer which way to change the pull speed (faster = less displacement) and by how
|
| 22 |
+
much.
|
| 23 |
+
|
| 24 |
+
Rule (stated in the instruction and enforced, 2026-10-08): ONE pull. Only one move command may drive the board
|
| 25 |
+
(>= PULL_EPS), the cube must still be where it started (<= PRE_TOL, grasp nudges) when that pull begins, and all
|
| 26 |
+
other move commands together may drive the board at most STRAY_MAX. Gripper open / close commands never count.
|
| 27 |
+
Without it every cla2 success (Sonnet, 4/4) dragged the board slowly first so that the cube rode to the band and the
|
| 28 |
+
last pull only added a little (one dragged it 4 cm, then yanked it sideways; one moved it with 11 commands, most
|
| 29 |
+
of them open-gripper strikes): the friction never mattered.
|
| 30 |
+
"""
|
| 31 |
+
import numpy as np
|
| 32 |
+
|
| 33 |
+
from .. import envs
|
| 34 |
+
from ..bddl import write_bddl
|
| 35 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 36 |
+
from ..skills import Skills
|
| 37 |
+
from ..task_base import LFFTask, register_task
|
| 38 |
+
|
| 39 |
+
BOARD, CUBE, BAND = "board_1", "cube_1", "band_1"
|
| 40 |
+
B_HALF = (0.15, 0.04, 0.005) # 30 x 8 x 1 cm
|
| 41 |
+
H_HALF = (0.0125, 0.02, 0.015) # handle 2.5 x 4 x 3 cm on top of the near end
|
| 42 |
+
C_HALF = 0.02 # 4 cm cube
|
| 43 |
+
LF = 0.05 # cube centre to the board's far edge
|
| 44 |
+
BAND_HALF_X = 0.03 # band 6 cm deep: the 4 cm cube must be fully inside -> centre within +-1 cm
|
| 45 |
+
BAND_HALF_Y = 0.12
|
| 46 |
+
LINE_W = 0.005
|
| 47 |
+
TOL = BAND_HALF_X - C_HALF
|
| 48 |
+
MU_BOARD = 0.3 # board-table friction (fixed)
|
| 49 |
+
STROKE = 0.25 # scripted pull length
|
| 50 |
+
V_MIN, V_MAX = 0.15, 0.80
|
| 51 |
+
# one-pull rule (2026-10-08). Board motion is the larger of its two ends' 3-D paths and is only counted while the robot
|
| 52 |
+
# drives the board (touches it, or it speeds up; a board sliding on its own only slows down), so coasting after a
|
| 53 |
+
# strike or a release is not charged to the next command. Measured on the cla2 agent runs and the scripted policy:
|
| 54 |
+
# approach moves 0 mm; closing on the handle 0.6-2 mm (agents) / 4.6 mm (script); release after the pull 3-10 mm
|
| 55 |
+
# (gripper commands never count as pulls); the loophole drags 13-41 mm per command, open-gripper strikes 11-54 mm.
|
| 56 |
+
PULL_EPS = 0.003 # a move command that drives the board this far is a pull
|
| 57 |
+
PRE_TOL = 0.01 # the cube may have moved at most this much (grasp nudges) when the pull starts
|
| 58 |
+
STRAY_MAX = 0.005 # board motion driven by all the other move commands together (each below PULL_EPS)
|
| 59 |
+
ACC_EPS = 0.0002 # board speed-up per control step (m/step) that counts as the robot driving it
|
| 60 |
+
_SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def board_xml(name):
|
| 64 |
+
hp = (-B_HALF[0] + H_HALF[0], 0.0, B_HALF[2] + H_HALF[2])
|
| 65 |
+
wood, black = (0.62, 0.45, 0.28, 1.0), (0.12, 0.12, 0.12, 1.0)
|
| 66 |
+
g = (f' <inertial pos="0.001 0 0.001" mass="0.3" diaginertia="0.0016 0.0023 0.0039" />\n'
|
| 67 |
+
f' <geom name="{name}_g0" type="box" size="{_fmt(B_HALF)}" rgba="{_fmt(wood)}" {_SOLID} group="0" />\n'
|
| 68 |
+
f' <geom name="{name}_g1" type="box" pos="{_fmt(hp)}" size="{_fmt(H_HALF)}" rgba="{_fmt(black)}" '
|
| 69 |
+
f'{_SOLID} group="0" />\n'
|
| 70 |
+
f' <geom type="box" size="{_fmt(B_HALF)}" rgba="{_fmt(wood)}" conaffinity="0" contype="0" group="1" />\n'
|
| 71 |
+
f' <geom type="box" pos="{_fmt(hp)}" size="{_fmt(H_HALF)}" rgba="{_fmt(black)}" conaffinity="0" '
|
| 72 |
+
f'contype="0" group="1" />')
|
| 73 |
+
# small horizontal radius: only LIBERO's reset-time sampler reads it (the layout is overridden anyway)
|
| 74 |
+
return _wrap(name, g, B_HALF[2], 0.03)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def band_xml(name, line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)):
|
| 78 |
+
"""Flat visual band across the table (no collisions): light fill + dark lines on its two long edges."""
|
| 79 |
+
hx, hy = BAND_HALF_X, BAND_HALF_Y
|
| 80 |
+
parts = [((0, 0, 0.0004), (hx, hy, 0.0004), fill_rgba),
|
| 81 |
+
((hx + LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba),
|
| 82 |
+
((-hx - LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba)]
|
| 83 |
+
g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
|
| 84 |
+
f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
|
| 85 |
+
return _wrap(name, g, 0.0012, 0.03)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def d_range(mu):
|
| 89 |
+
"""Band distances sampled for a given mu (m). Calibrated 2026-10-07 (LF 5 cm, board at x 0.05): the cube
|
| 90 |
+
moves d(0.6 m/s) ~ 0.33 * mu - 0.85 cm when yanked at the controller's top speed (mu 0.08 -> 1.8 cm,
|
| 91 |
+
0.10 -> 2.3, 0.12 -> 3.1, 0.15 -> 4.3 cm) and >= 0.5 * mu at a pull ~0.05 m/s above the ride-along speed (0.08 -> 4.1 cm at
|
| 92 |
+
0.35 m/s, 0.15 -> 7.6 cm at 0.45 m/s). The band centre is put ~1.5 cm beyond the top-speed displacement, so
|
| 93 |
+
the 'yank as fast as possible' prior always lands the cube short of the band."""
|
| 94 |
+
return 0.33 * mu + 0.0065, 0.50 * mu
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class ClothSkills(Skills):
|
| 98 |
+
"""Skills that watch, every control step, whether the robot touches the cube (not allowed) and how each
|
| 99 |
+
move_to / gripper command moves the board and the cube (one pull only)."""
|
| 100 |
+
|
| 101 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 102 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 103 |
+
m = env.sim.model
|
| 104 |
+
self._robot = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
|
| 105 |
+
self._cube = envs.obj_geom_ids(env, CUBE)
|
| 106 |
+
self._board = envs.obj_geom_ids(env, BOARD)
|
| 107 |
+
self.touched_cube = False
|
| 108 |
+
self.cube0 = envs.obj_pos(env, CUBE)
|
| 109 |
+
self._ends = self._board_ends()
|
| 110 |
+
self._bstep = 0.0 # board motion in the previous control step
|
| 111 |
+
self._seg = None
|
| 112 |
+
self.segments = [] # one entry per move_to / set_gripper command
|
| 113 |
+
|
| 114 |
+
def _board_ends(self):
|
| 115 |
+
"""Both ends of the board's long axis (world xyz): their motion also catches turning and tilting."""
|
| 116 |
+
b = envs.obj_pos(self.env, BOARD)
|
| 117 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3)
|
| 118 |
+
return np.stack([b - R[:, 0] * B_HALF[0], b + R[:, 0] * B_HALF[0]])
|
| 119 |
+
|
| 120 |
+
def _act(self, dpos, drot, grip):
|
| 121 |
+
super()._act(dpos, drot, grip)
|
| 122 |
+
if not self.touched_cube and envs.contacts_between(self.env, self._robot, self._cube):
|
| 123 |
+
self.touched_cube = True
|
| 124 |
+
ends = self._board_ends()
|
| 125 |
+
step = float(np.max(np.linalg.norm(ends - self._ends, axis=1)))
|
| 126 |
+
touch = envs.contacts_between(self.env, self._robot, self._board)
|
| 127 |
+
speed_up = step - self._bstep > ACC_EPS
|
| 128 |
+
self._ends, self._bstep = ends, step
|
| 129 |
+
s = self._seg
|
| 130 |
+
if s is not None:
|
| 131 |
+
s["path"] += step
|
| 132 |
+
s["touch"] += int(touch)
|
| 133 |
+
if touch or speed_up:
|
| 134 |
+
s["driven"] += step
|
| 135 |
+
|
| 136 |
+
def _segment(self, kind, fn, *args, **kwargs):
|
| 137 |
+
c0, b0 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD)
|
| 138 |
+
self._seg = dict(kind=kind, step0=self.n_steps, path=0.0, driven=0.0, touch=0)
|
| 139 |
+
try:
|
| 140 |
+
rep = fn(*args, **kwargs)
|
| 141 |
+
finally:
|
| 142 |
+
s, self._seg = self._seg, None
|
| 143 |
+
c1, b1 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD)
|
| 144 |
+
s.update(steps=self.n_steps - s["step0"], board_dxy=(b1 - b0)[:2].round(4).tolist(),
|
| 145 |
+
cube_dxy=(c1 - c0)[:2].round(4).tolist(), cube_from_start=(c0 - self.cube0)[:2].round(4).tolist())
|
| 146 |
+
self.segments.append(s)
|
| 147 |
+
return rep
|
| 148 |
+
|
| 149 |
+
def move_to(self, target, *args, **kwargs):
|
| 150 |
+
return self._segment("move", super().move_to, target, *args, **kwargs)
|
| 151 |
+
|
| 152 |
+
def set_gripper(self, close, steps=15):
|
| 153 |
+
return self._segment("close" if close else "open", super().set_gripper, close, steps)
|
| 154 |
+
|
| 155 |
+
def pull_check(self):
|
| 156 |
+
"""Pulls (move commands that drove the board >= PULL_EPS), where the cube was when the (first) pull started,
|
| 157 |
+
and the board motion driven by the other move commands."""
|
| 158 |
+
moves = [s for s in self.segments if s["kind"] == "move"]
|
| 159 |
+
pulls = [s for s in moves if s["driven"] >= PULL_EPS]
|
| 160 |
+
stray = sum(s["driven"] for s in moves if s["driven"] < PULL_EPS)
|
| 161 |
+
pre = (float(np.linalg.norm(pulls[0]["cube_from_start"])) if pulls
|
| 162 |
+
else float(np.linalg.norm((envs.obj_pos(self.env, CUBE) - self.cube0)[:2])))
|
| 163 |
+
return dict(n_pulls=len(pulls), pulls_cm=[round(100 * s["driven"], 1) for s in pulls],
|
| 164 |
+
pre_pull_cube_cm=round(100 * pre, 1), stray_cm=round(100 * stray, 2))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@register_task
|
| 168 |
+
class TableclothPull(LFFTask):
|
| 169 |
+
name = "l5_tablecloth_pull"
|
| 170 |
+
level = "L5"
|
| 171 |
+
category = "dynamics_adaptation"
|
| 172 |
+
capabilities = ("Perceive", "Reason", "Utilize")
|
| 173 |
+
protocol = "cross"
|
| 174 |
+
instruction = ("Pull the wooden board out from under the red cube so that the cube ends up standing on the table "
|
| 175 |
+
"completely inside the green band. Touch only the board and its black handle, never the cube. "
|
| 176 |
+
"Only one pull is allowed per attempt: grasp the black handle, pull the board out with ONE move "
|
| 177 |
+
"command, then release it. Any other move that drags, pushes or nudges the board, before or after "
|
| 178 |
+
"the pull, counts as another pull.")
|
| 179 |
+
instruction_indirect = ("Pull the long brown plank out from under the small red block so that the block ends up "
|
| 180 |
+
"standing on the table completely inside the green stripe. Touch only the plank and its "
|
| 181 |
+
"black handle, never the block. Only one pull is allowed per attempt: grasp the black "
|
| 182 |
+
"handle, pull the plank out with ONE move command, then release it. Any other move that "
|
| 183 |
+
"drags, pushes or nudges the plank, before or after the pull, counts as another pull.")
|
| 184 |
+
|
| 185 |
+
# ------------------------------------------------------------ scene
|
| 186 |
+
def make_bddl(self):
|
| 187 |
+
board = register_generated("LffClothBoard", board_xml("lff_cloth_board"))
|
| 188 |
+
cube = register_generated("LffClothCube", box_xml("lff_cloth_cube", (C_HALF,) * 3, (0.85, 0.15, 0.15, 1.0),
|
| 189 |
+
density=2300))
|
| 190 |
+
band = register_generated("LffClothBand", band_xml("lff_cloth_band"), free=False)
|
| 191 |
+
objs = [(BOARD, board, "board_region", (0.09, -0.26, 0.11, -0.24)),
|
| 192 |
+
(CUBE, cube, "cube_region", (-0.21, 0.24, -0.19, 0.26))]
|
| 193 |
+
fixtures = [(BAND, band, "band_region", (-0.31, -0.01, -0.29, 0.01))]
|
| 194 |
+
return write_bddl(self.name, "pull the board out from under the cube", objs, fixtures=fixtures)
|
| 195 |
+
|
| 196 |
+
def sample_instance(self, seed):
|
| 197 |
+
rng = np.random.default_rng(seed)
|
| 198 |
+
mu = float(np.exp(rng.uniform(np.log(0.08), np.log(0.15))))
|
| 199 |
+
lo, hi = d_range(mu)
|
| 200 |
+
d = float(rng.uniform(lo, max(lo, hi)))
|
| 201 |
+
return dict(seed=int(seed), board_xy=[float(rng.uniform(0.03, 0.08)), float(rng.uniform(-0.08, 0.08))],
|
| 202 |
+
mu=mu, band_d=d)
|
| 203 |
+
|
| 204 |
+
def cube_start(self, inst):
|
| 205 |
+
bx, by = inst["board_xy"]
|
| 206 |
+
return np.array([bx + B_HALF[0] - LF, by])
|
| 207 |
+
|
| 208 |
+
def band_center(self, inst):
|
| 209 |
+
c = self.cube_start(inst)
|
| 210 |
+
return np.array([c[0] - inst["band_d"], c[1]])
|
| 211 |
+
|
| 212 |
+
def apply_instance(self, inst):
|
| 213 |
+
m = self.env.sim.model
|
| 214 |
+
for g in range(m.ngeom): # the band is a flat marker: no collisions
|
| 215 |
+
if (m.geom_id2name(g) or "").startswith(BAND + "_"):
|
| 216 |
+
m.geom_contype[g] = 0
|
| 217 |
+
m.geom_conaffinity[g] = 0
|
| 218 |
+
bx, by = inst["board_xy"]
|
| 219 |
+
envs.set_obj_pose(self.env, BOARD, [bx, by, envs.TABLE_Z + B_HALF[2] + 0.0005])
|
| 220 |
+
c = self.cube_start(inst)
|
| 221 |
+
envs.set_obj_pose(self.env, CUBE, [c[0], c[1], envs.TABLE_Z + 2 * B_HALF[2] + C_HALF + 0.0005])
|
| 222 |
+
envs.set_friction(self.env, BOARD, MU_BOARD, priority=1)
|
| 223 |
+
envs.set_friction(self.env, CUBE, inst["mu"], priority=2) # cube-board and cube-table contacts use mu
|
| 224 |
+
bid = m.body_name2id(self.env.fixtures_dict[BAND].root_body)
|
| 225 |
+
bc = self.band_center(inst)
|
| 226 |
+
m.body_pos[bid] = [bc[0], bc[1], envs.TABLE_Z + 0.0002]
|
| 227 |
+
m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 228 |
+
|
| 229 |
+
def reset_instance(self, inst, recorder=None):
|
| 230 |
+
from robosuite.utils.errors import RandomizationError
|
| 231 |
+
for _ in range(20): # LIBERO's reset-time placement sampler occasionally fails; the layout is overridden
|
| 232 |
+
try:
|
| 233 |
+
self.env.reset()
|
| 234 |
+
break
|
| 235 |
+
except RandomizationError:
|
| 236 |
+
continue
|
| 237 |
+
self.apply_instance(inst)
|
| 238 |
+
self.env.sim.forward()
|
| 239 |
+
envs.settle(self.env, 10)
|
| 240 |
+
self.sk = ClothSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
|
| 241 |
+
return self.sk
|
| 242 |
+
|
| 243 |
+
# ------------------------------------------------------------ outcome
|
| 244 |
+
def cube_on_board(self):
|
| 245 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 246 |
+
b = envs.obj_pos(self.env, BOARD)
|
| 247 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3)
|
| 248 |
+
local = R.T @ (c - b)
|
| 249 |
+
return bool(abs(local[0]) < B_HALF[0] + 0.005 and abs(local[1]) < B_HALF[1] + 0.005
|
| 250 |
+
and c[2] > envs.TABLE_Z + 2 * B_HALF[2] + C_HALF - 0.004)
|
| 251 |
+
|
| 252 |
+
def outcome(self, inst):
|
| 253 |
+
sk = self.sk
|
| 254 |
+
envs.settle(self.env, 60)
|
| 255 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 256 |
+
c0 = self.cube_start(inst)
|
| 257 |
+
bc = self.band_center(inst)
|
| 258 |
+
moved = float(c0[0] - c[0]) # towards the robot
|
| 259 |
+
off = c[:2] - bc # + x: cube forward (away from the robot) of the band's centre line
|
| 260 |
+
upright = envs.obj_upright_cos(self.env, CUBE) > 0.95
|
| 261 |
+
on_board = self.cube_on_board()
|
| 262 |
+
on_table = c[2] < envs.TABLE_Z + C_HALF + 0.004
|
| 263 |
+
in_band = bool(abs(off[0]) <= TOL and abs(off[1]) <= BAND_HALF_Y - C_HALF)
|
| 264 |
+
pc = sk.pull_check()
|
| 265 |
+
rule = []
|
| 266 |
+
if pc["n_pulls"] > 1:
|
| 267 |
+
rule.append(f"The board was moved by {pc['n_pulls']} separate move commands "
|
| 268 |
+
f"({', '.join(f'{v:.1f}' for v in pc['pulls_cm'])} cm); only one pull is allowed.")
|
| 269 |
+
if pc["n_pulls"] and pc["pre_pull_cube_cm"] > 100 * PRE_TOL:
|
| 270 |
+
rule.append(f"When the pull started the cube had already been moved {pc['pre_pull_cube_cm']:.1f} cm by "
|
| 271 |
+
f"earlier small moves of the board; only one pull is allowed.")
|
| 272 |
+
if pc["stray_cm"] > 100 * STRAY_MAX:
|
| 273 |
+
rule.append(f"Besides the pull, other move commands moved the board {pc['stray_cm']:.1f} cm in total; "
|
| 274 |
+
f"only one pull is allowed.")
|
| 275 |
+
success = bool(in_band and on_table and upright and not on_board and not sk.touched_cube and not rule)
|
| 276 |
+
b_moved = float(np.linalg.norm(envs.obj_pos(self.env, BOARD)[:2] - np.asarray(inst["board_xy"])))
|
| 277 |
+
out = dict(success=success, touched_cube=bool(sk.touched_cube), on_board=on_board, upright=bool(upright),
|
| 278 |
+
moved_toward_robot=round(moved, 4), band_offset_x=round(float(off[0]), 4),
|
| 279 |
+
err=round(float(moved - inst["band_d"]), 4), board_moved=round(b_moved, 4),
|
| 280 |
+
one_pull=not rule, **pc)
|
| 281 |
+
side = ("forward (+x, away from the robot)" if off[0] > 0 else "backward (-x, toward the robot)")
|
| 282 |
+
where = (f"its centre is {100 * abs(off[0]):.1f} cm {side} of the band's centre line"
|
| 283 |
+
if abs(off[0]) >= 0.0005 else "its centre is on the band's centre line")
|
| 284 |
+
if sk.touched_cube:
|
| 285 |
+
out["failure"] = "touched_cube"
|
| 286 |
+
detail = "The robot touched the cube, which is not allowed."
|
| 287 |
+
elif on_board and b_moved < 0.02:
|
| 288 |
+
out["failure"] = "board_not_moved"
|
| 289 |
+
detail = "The board was not pulled; the cube is still standing on it."
|
| 290 |
+
elif on_board:
|
| 291 |
+
out["failure"] = "rode_along"
|
| 292 |
+
detail = (f"The board was pulled {100 * b_moved:.0f} cm, but the cube rode along on it: it is still on the "
|
| 293 |
+
f"board and moved {100 * moved:.1f} cm toward the robot.")
|
| 294 |
+
elif not upright:
|
| 295 |
+
out["failure"] = "toppled"
|
| 296 |
+
detail = f"The board came out from under the cube, but the cube fell over; {where}."
|
| 297 |
+
elif in_band and on_table and upright:
|
| 298 |
+
out["failure"] = None
|
| 299 |
+
detail = (f"The board came out from under the cube and the cube is standing inside the green band; {where}. "
|
| 300 |
+
f"It moved {100 * moved:.1f} cm toward the robot.")
|
| 301 |
+
else:
|
| 302 |
+
out["failure"] = "missed_band"
|
| 303 |
+
detail = (f"The board came out from under the cube and the cube is standing on the table, but not "
|
| 304 |
+
f"completely inside the green band: {where}. It moved {100 * moved:.1f} cm toward the robot.")
|
| 305 |
+
if rule and not sk.touched_cube:
|
| 306 |
+
out["failure"] = "several_pulls"
|
| 307 |
+
detail = " ".join(rule) + " " + detail
|
| 308 |
+
out["detail"] = detail
|
| 309 |
+
out["detail_indirect"] = (detail.replace("board", "plank").replace("cube", "block")
|
| 310 |
+
.replace("green band", "green stripe").replace("band's", "stripe's"))
|
| 311 |
+
return out
|
| 312 |
+
|
| 313 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 314 |
+
if indirect and level == "F2":
|
| 315 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 316 |
+
return super().feedback(inst, out, level)
|
| 317 |
+
|
| 318 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 319 |
+
def execute(self, inst, params):
|
| 320 |
+
"""Grasp the handle (jaws across its 4 cm width) and pull the board STROKE m toward the robot at `speed`."""
|
| 321 |
+
sk = self.sk
|
| 322 |
+
b = envs.obj_pos(self.env, BOARD)
|
| 323 |
+
hx, hy = b[0] - B_HALF[0] + H_HALF[0], b[1]
|
| 324 |
+
zg = envs.TABLE_Z + 2 * B_HALF[2] + H_HALF[2]
|
| 325 |
+
sk.set_gripper(False, steps=5)
|
| 326 |
+
sk.move_to([hx, hy, zg + 0.08], yaw=0.0)
|
| 327 |
+
sk.move_to([hx, hy, zg], tol=0.003)
|
| 328 |
+
sk.set_gripper(True, steps=15)
|
| 329 |
+
sk.move_to([hx - STROKE, hy, zg], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), tol=0.01,
|
| 330 |
+
max_steps=300)
|
| 331 |
+
sk.set_gripper(False, steps=8)
|
| 332 |
+
sk.move_to([hx - STROKE, hy, zg + 0.10], speed=0.3)
|
| 333 |
+
|
| 334 |
+
def default_params(self, inst):
|
| 335 |
+
"""Prior: the classic tablecloth trick -- yank as fast as the arm can."""
|
| 336 |
+
return dict(speed=0.60)
|
| 337 |
+
|
| 338 |
+
def blind_params(self, inst, attempt, rng):
|
| 339 |
+
return dict(speed=float(np.clip(0.60 + rng.normal(0, 0.06), V_MIN, V_MAX)))
|
| 340 |
+
|
| 341 |
+
def adapt_params(self, inst, history):
|
| 342 |
+
"""Bracketing search on the pull speed with the signed displacement error (riding along = far too much
|
| 343 |
+
displacement). Faster -> less displacement."""
|
| 344 |
+
pts = []
|
| 345 |
+
for h in history:
|
| 346 |
+
o = h["outcome"]
|
| 347 |
+
if o.get("failure") in ("rode_along", "board_not_moved"):
|
| 348 |
+
e = 0.10
|
| 349 |
+
elif o.get("failure") in ("touched_cube", "several_pulls"):
|
| 350 |
+
continue
|
| 351 |
+
else:
|
| 352 |
+
e = o["err"]
|
| 353 |
+
pts.append((h["params"]["speed"], e))
|
| 354 |
+
hi_err = [p for p in pts if p[1] > 0] # moved too much -> needs a faster pull
|
| 355 |
+
lo_err = [p for p in pts if p[1] < 0] # moved too little -> needs a slower pull
|
| 356 |
+
if hi_err and lo_err:
|
| 357 |
+
(v0, e0) = max(hi_err, key=lambda p: p[0]) # fastest pull that still moved it too much
|
| 358 |
+
(v1, e1) = min(lo_err, key=lambda p: p[0]) # slowest pull that moved it too little
|
| 359 |
+
if e0 >= 0.05: # rode along: no usable slope -> bisect
|
| 360 |
+
v = 0.5 * (v0 + v1)
|
| 361 |
+
else:
|
| 362 |
+
v = v0 + (v1 - v0) * e0 / (e0 - e1)
|
| 363 |
+
elif hi_err:
|
| 364 |
+
v = max(p[0] for p in hi_err) * 1.25
|
| 365 |
+
else:
|
| 366 |
+
v = min(p[0] for p in lo_err) * 0.8
|
| 367 |
+
return dict(speed=float(np.clip(v, V_MIN, V_MAX)))
|
| 368 |
+
|
| 369 |
+
def oracle_params(self, inst):
|
| 370 |
+
"""Privileged: bisection on the speed by simulating pulls with the true mu."""
|
| 371 |
+
if "_oracle_speed" in inst:
|
| 372 |
+
return dict(speed=inst["_oracle_speed"])
|
| 373 |
+
lo, hi = V_MIN, V_MAX
|
| 374 |
+
best = None
|
| 375 |
+
for _ in range(10):
|
| 376 |
+
mid = 0.5 * (lo + hi)
|
| 377 |
+
self.reset_instance(inst)
|
| 378 |
+
self.execute(inst, dict(speed=mid))
|
| 379 |
+
o = self.outcome(inst)
|
| 380 |
+
e = 0.10 if o["failure"] in ("rode_along", "board_not_moved") else o["err"]
|
| 381 |
+
if o["success"]:
|
| 382 |
+
best = (mid, e)
|
| 383 |
+
break
|
| 384 |
+
if best is None or abs(e) < abs(best[1]):
|
| 385 |
+
best = (mid, e)
|
| 386 |
+
if e > 0:
|
| 387 |
+
lo = mid
|
| 388 |
+
else:
|
| 389 |
+
hi = mid
|
| 390 |
+
inst["_oracle_speed"] = best[0]
|
| 391 |
+
self.reset_instance(inst)
|
| 392 |
+
return dict(speed=best[0])
|