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_gpt/lff/source_closure/lffbench/agent/backends/__init__.py +21 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/gemini.py +206 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/harness.py +300 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/metrics.py +97 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/__init__.py +53 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py +65 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py +61 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l4_fit_container.py +61 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l7_key_turn.py +34 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py +39 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py +23 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py +18 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_nudge_row.py +821 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_shelf_droop.py +1009 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/scripts/trace_gpt_html.py +118 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/client/lffbench_client/__init__.py +139 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json +23 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/agent_viewer/live.py +406 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/arm_specs/__init__.py +53 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json +36 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json +15 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/cs_ir_report.py +87 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/gpt_player.py +20 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/headroom_parts_cart.py +19 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/l6_controls.py +92 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/mismatch_plan.py +149 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/outcomes.py +141 -0
- leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json +23 -0
- leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/scripts/qwen_vl_server.py +535 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/openai_responses.py +240 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/base.py +364 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py +136 -0
- leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l7_offcenter_push.py +613 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/context.py +377 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/runlog.py +62 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py +73 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json +15 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json +36 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l2_turntable.py +469 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l3_card_edge.py +364 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_cost.py +77 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/audit_subagent.py +130 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/mcp_robot_server.py +140 -0
- leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/trace_gpt_html.py +118 -0
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model backends. Import lazily: each API backend needs its provider's SDK (see base.import_sdk)."""
|
| 2 |
+
from .base import AttemptInfo, Backend, BackendResponse, RunInfo # noqa: F401
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def make_backend(kind, **kw):
|
| 6 |
+
if kind == "scripted":
|
| 7 |
+
from .scripted import ScriptedBackend
|
| 8 |
+
return ScriptedBackend(**kw)
|
| 9 |
+
if kind == "openai":
|
| 10 |
+
from .openai_responses import OpenAIResponsesBackend
|
| 11 |
+
return OpenAIResponsesBackend(**kw)
|
| 12 |
+
if kind == "chat":
|
| 13 |
+
from .chat_completions import ChatCompletionsBackend
|
| 14 |
+
return ChatCompletionsBackend(**kw)
|
| 15 |
+
if kind == "anthropic":
|
| 16 |
+
from .anthropic_messages import AnthropicMessagesBackend
|
| 17 |
+
return AnthropicMessagesBackend(**kw)
|
| 18 |
+
if kind == "gemini":
|
| 19 |
+
from .gemini import GeminiBackend
|
| 20 |
+
return GeminiBackend(**kw)
|
| 21 |
+
raise ValueError(kind)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/backends/gemini.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Google Gemini backend (Gemini API, official SDK `google-genai`).
|
| 2 |
+
|
| 3 |
+
Same conversation as the other backends, converted to Gemini `contents`:
|
| 4 |
+
- system prompt = system_instruction; tools = function declarations with the harness's JSON schemas;
|
| 5 |
+
- every model turn is stored as the full returned `Content` (python-mode dump, so `thought_signature` bytes survive)
|
| 6 |
+
and replayed unchanged: Gemini 3 models need the signatures back to continue their reasoning after a tool call;
|
| 7 |
+
- tool outputs of one turn become `function_response` parts at the start of the next user content; images the
|
| 8 |
+
harness attaches after them follow in the same user content;
|
| 9 |
+
- thinking: `thinking_level` (Gemini 3) or `thinking_budget` (Gemini 2.5), with thought summaries logged;
|
| 10 |
+
- implicit prompt caching is automatic on the Gemini API (cached tokens are reported in usage).
|
| 11 |
+
|
| 12 |
+
Key from GEMINI_API_KEY / GOOGLE_API_KEY (the SDK reads them). The client is created lazily; tests inject a mock.
|
| 13 |
+
"""
|
| 14 |
+
import base64
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
from ..context import ToolCall, prune_live_images
|
| 18 |
+
from .base import Backend, BackendResponse, import_sdk
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _get(obj, key, default=None):
|
| 22 |
+
if isinstance(obj, dict):
|
| 23 |
+
return obj.get(key, default)
|
| 24 |
+
return getattr(obj, key, default)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _strip_additional(schema):
|
| 28 |
+
"""The OpenAPI subset of `parameters` has no additionalProperties; used only if the SDK lacks parameters_json_schema."""
|
| 29 |
+
if isinstance(schema, dict):
|
| 30 |
+
return {k: _strip_additional(v) for k, v in schema.items() if k != "additionalProperties"}
|
| 31 |
+
if isinstance(schema, list):
|
| 32 |
+
return [_strip_additional(v) for v in schema]
|
| 33 |
+
return schema
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _image_part(image, quality=None):
|
| 37 |
+
head, data = image.data_url(quality).split(",", 1)
|
| 38 |
+
mime = head[len("data:"):].split(";", 1)[0]
|
| 39 |
+
return dict(inline_data=dict(mime_type=mime, data=base64.b64decode(data)))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class GeminiBackend(Backend):
|
| 43 |
+
name = "gemini"
|
| 44 |
+
|
| 45 |
+
def __init__(self, model="gemini-3.5-pro", thinking_level="high", thinking_budget=None, include_thoughts=True,
|
| 46 |
+
max_output_tokens=65536, media_resolution=None, max_live_images=None, jpeg_quality=90,
|
| 47 |
+
timeout=900.0, client=None):
|
| 48 |
+
self.model = model
|
| 49 |
+
self.thinking_level = thinking_level
|
| 50 |
+
self.thinking_budget = thinking_budget
|
| 51 |
+
self.include_thoughts = include_thoughts
|
| 52 |
+
self.max_output_tokens = max_output_tokens
|
| 53 |
+
self.media_resolution = media_resolution
|
| 54 |
+
self.max_live_images = max_live_images
|
| 55 |
+
self.jpeg_quality = jpeg_quality
|
| 56 |
+
self.timeout = timeout
|
| 57 |
+
self._client = client
|
| 58 |
+
self._json_schema_field = None
|
| 59 |
+
|
| 60 |
+
def config(self):
|
| 61 |
+
return dict(name=self.name, model=self.model, thinking_level=self.thinking_level,
|
| 62 |
+
thinking_budget=self.thinking_budget, include_thoughts=self.include_thoughts,
|
| 63 |
+
max_output_tokens=self.max_output_tokens, media_resolution=self.media_resolution,
|
| 64 |
+
max_live_images=self.max_live_images, jpeg_quality=self.jpeg_quality, timeout=self.timeout)
|
| 65 |
+
|
| 66 |
+
def client(self):
|
| 67 |
+
if self._client is None:
|
| 68 |
+
genai = import_sdk("google.genai")
|
| 69 |
+
self._client = genai.Client(http_options=dict(timeout=int(self.timeout * 1000)))
|
| 70 |
+
return self._client
|
| 71 |
+
|
| 72 |
+
def _declarations(self, specs):
|
| 73 |
+
if self._json_schema_field is None:
|
| 74 |
+
try:
|
| 75 |
+
types = import_sdk("google.genai.types")
|
| 76 |
+
self._json_schema_field = "parameters_json_schema" in types.FunctionDeclaration.model_fields
|
| 77 |
+
except ImportError: # tests without the SDK
|
| 78 |
+
self._json_schema_field = True
|
| 79 |
+
out = []
|
| 80 |
+
for s in specs:
|
| 81 |
+
d = dict(name=s["name"], description=s["description"])
|
| 82 |
+
if self._json_schema_field:
|
| 83 |
+
d["parameters_json_schema"] = s["parameters"]
|
| 84 |
+
else:
|
| 85 |
+
d["parameters"] = _strip_additional(s["parameters"])
|
| 86 |
+
out.append(d)
|
| 87 |
+
return [dict(function_declarations=out)]
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ request
|
| 90 |
+
def convert_items(self, items):
|
| 91 |
+
contents = []
|
| 92 |
+
|
| 93 |
+
def push(role, parts):
|
| 94 |
+
if contents and contents[-1]["role"] == role:
|
| 95 |
+
contents[-1]["parts"].extend(parts)
|
| 96 |
+
else:
|
| 97 |
+
contents.append(dict(role=role, parts=list(parts)))
|
| 98 |
+
|
| 99 |
+
for it in items:
|
| 100 |
+
kind = it["kind"]
|
| 101 |
+
if kind == "user":
|
| 102 |
+
parts = []
|
| 103 |
+
for p in it["parts"]:
|
| 104 |
+
if p["type"] == "text":
|
| 105 |
+
parts.append(dict(text=p["text"]))
|
| 106 |
+
else:
|
| 107 |
+
parts.append(_image_part(p["image"], self.jpeg_quality))
|
| 108 |
+
push("user", parts)
|
| 109 |
+
elif kind == "assistant":
|
| 110 |
+
if it.get("raw") is not None and it.get("backend") == self.name:
|
| 111 |
+
content = dict(it["raw"][0])
|
| 112 |
+
contents.append(dict(role="model", parts=list(content.get("parts") or [])))
|
| 113 |
+
continue
|
| 114 |
+
parts = ([dict(text=it["text"])] if it.get("text") else [])
|
| 115 |
+
parts += [dict(function_call=dict(name=tc.name, args=tc.arguments)) for tc in it["tool_calls"]]
|
| 116 |
+
push("model", parts or [dict(text="(no output)")])
|
| 117 |
+
elif kind == "tool_output":
|
| 118 |
+
fr = dict(name=it["name"], response=dict(output=it["text"]))
|
| 119 |
+
if it["call_id"] and not str(it["call_id"]).startswith("gemini_call_"):
|
| 120 |
+
fr["id"] = it["call_id"]
|
| 121 |
+
push("user", [dict(function_response=fr)])
|
| 122 |
+
else:
|
| 123 |
+
raise ValueError(kind)
|
| 124 |
+
return contents
|
| 125 |
+
|
| 126 |
+
def build_request(self, conv, tools):
|
| 127 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 128 |
+
thinking = dict(include_thoughts=self.include_thoughts)
|
| 129 |
+
if self.thinking_budget is not None:
|
| 130 |
+
thinking["thinking_budget"] = int(self.thinking_budget)
|
| 131 |
+
elif self.thinking_level:
|
| 132 |
+
thinking["thinking_level"] = self.thinking_level
|
| 133 |
+
config = dict(system_instruction=conv.system, tools=self._declarations(tools),
|
| 134 |
+
tool_config=dict(function_calling_config=dict(mode="AUTO")),
|
| 135 |
+
automatic_function_calling=dict(disable=True), thinking_config=thinking,
|
| 136 |
+
max_output_tokens=int(self.max_output_tokens))
|
| 137 |
+
if self.media_resolution:
|
| 138 |
+
config["media_resolution"] = self.media_resolution
|
| 139 |
+
return dict(model=self.model, contents=self.convert_items(items), config=config)
|
| 140 |
+
|
| 141 |
+
@staticmethod
|
| 142 |
+
def request_stats(req):
|
| 143 |
+
n_img, img_bytes, txt = 0, 0, len(req["config"].get("system_instruction") or "")
|
| 144 |
+
for c in req["contents"]:
|
| 145 |
+
for p in c["parts"]:
|
| 146 |
+
p = p if isinstance(p, dict) else {}
|
| 147 |
+
if p.get("inline_data"):
|
| 148 |
+
n_img += 1
|
| 149 |
+
img_bytes += len(p["inline_data"]["data"])
|
| 150 |
+
elif p.get("text"):
|
| 151 |
+
txt += len(p["text"])
|
| 152 |
+
elif p.get("function_response"):
|
| 153 |
+
txt += len(str(p["function_response"].get("response", "")))
|
| 154 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt, n_contents=len(req["contents"]))
|
| 155 |
+
|
| 156 |
+
# ------------------------------------------------------------------ call
|
| 157 |
+
def act(self, conv, tools):
|
| 158 |
+
req = self.build_request(conv, tools)
|
| 159 |
+
stats = self.request_stats(req)
|
| 160 |
+
types = import_sdk("google.genai.types") # typed objects: plain nested dicts are sent with snake_case keys
|
| 161 |
+
t0 = time.time()
|
| 162 |
+
resp = self.client().models.generate_content(
|
| 163 |
+
model=req["model"], contents=[types.Content.model_validate(c) for c in req["contents"]],
|
| 164 |
+
config=types.GenerateContentConfig.model_validate(req["config"]))
|
| 165 |
+
out = self.parse_response(resp)
|
| 166 |
+
out.latency_s = time.time() - t0
|
| 167 |
+
out.request_stats = stats
|
| 168 |
+
return out
|
| 169 |
+
|
| 170 |
+
def parse_response(self, resp):
|
| 171 |
+
cands = _get(resp, "candidates") or []
|
| 172 |
+
cand = cands[0] if cands else None
|
| 173 |
+
content = _get(cand, "content") if cand is not None else None
|
| 174 |
+
parts = (_get(content, "parts") or []) if content is not None else []
|
| 175 |
+
calls, texts, summ = [], [], []
|
| 176 |
+
for i, p in enumerate(parts):
|
| 177 |
+
fc = _get(p, "function_call")
|
| 178 |
+
if fc is not None:
|
| 179 |
+
cid = _get(fc, "id") or f"gemini_call_{i}"
|
| 180 |
+
calls.append(ToolCall(id=cid, name=_get(fc, "name"), arguments=dict(_get(fc, "args") or {})))
|
| 181 |
+
elif _get(p, "text"):
|
| 182 |
+
(summ if _get(p, "thought") else texts).append(_get(p, "text"))
|
| 183 |
+
u = _get(resp, "usage_metadata")
|
| 184 |
+
usage = {}
|
| 185 |
+
if u is not None:
|
| 186 |
+
usage = dict(input_tokens=_get(u, "prompt_token_count", 0) or 0,
|
| 187 |
+
cached_tokens=_get(u, "cached_content_token_count", 0) or 0,
|
| 188 |
+
output_tokens=(_get(u, "candidates_token_count", 0) or 0) + (_get(u, "thoughts_token_count", 0) or 0),
|
| 189 |
+
reasoning_tokens=_get(u, "thoughts_token_count", 0) or 0)
|
| 190 |
+
finish = str(_get(cand, "finish_reason") or "") if cand is not None else "NO_CANDIDATE"
|
| 191 |
+
status, err = "completed", None
|
| 192 |
+
if not parts:
|
| 193 |
+
status, err = "incomplete", f"incomplete: empty response (finish_reason={finish})"
|
| 194 |
+
elif "MAX_TOKENS" in finish or "MALFORMED" in finish:
|
| 195 |
+
status, err = "incomplete", f"incomplete: finish_reason={finish}"
|
| 196 |
+
elif "SAFETY" in finish or "PROHIBITED" in finish or "BLOCKLIST" in finish:
|
| 197 |
+
status, err = "refusal", f"refusal: finish_reason={finish}"
|
| 198 |
+
if content is not None and hasattr(content, "model_dump"):
|
| 199 |
+
raw = [content.model_dump(exclude_none=True)] # python mode: thought_signature stays bytes
|
| 200 |
+
elif content is not None:
|
| 201 |
+
raw = [dict(content)]
|
| 202 |
+
else:
|
| 203 |
+
raw = None
|
| 204 |
+
return BackendResponse(tool_calls=calls, text="\n".join(texts) or None,
|
| 205 |
+
reasoning_summary="\n".join(summ) or None, usage=usage, raw=raw,
|
| 206 |
+
status=status, error=err)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/harness.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Protocol controller: runs a backend on task instances, attempt by attempt.
|
| 2 |
+
|
| 3 |
+
cross protocol : reset to the same instance (same layout + hidden variables) before every attempt
|
| 4 |
+
within protocol: one continuous episode; each `done` call closes a segment ("attempt") that is checked;
|
| 5 |
+
the agent continues from the current state if it failed and budget remains
|
| 6 |
+
Both protocols pack finished attempts the same way (keyframes <= 4, action summary, feedback F0/F1/F2) and
|
| 7 |
+
show them according to the memory mode (none / full / last / mismatched).
|
| 8 |
+
"""
|
| 9 |
+
import time
|
| 10 |
+
from dataclasses import asdict, dataclass, field
|
| 11 |
+
|
| 12 |
+
from .context import (FEEDBACK_LEVELS, MEMORY_MODES, AttemptRecord, Conversation, PromptBuilder, StepRecord,
|
| 13 |
+
pick_keyframes, select_history, summarize_actions)
|
| 14 |
+
from .cost import call_cost, estimate_request_tokens
|
| 15 |
+
from .metrics import run_summary
|
| 16 |
+
from .backends.base import AttemptInfo, RunInfo
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class HarnessConfig:
|
| 21 |
+
memory: str = "full"
|
| 22 |
+
feedback: str = "F2"
|
| 23 |
+
k: int = None # attempts (cross) / done calls (within); default task.max_attempts
|
| 24 |
+
image_res: int = 512
|
| 25 |
+
keyframe_res: int = None # default = image_res
|
| 26 |
+
n_keyframes: int = 4
|
| 27 |
+
cams: tuple = ("agentview", "wrist")
|
| 28 |
+
auto_obs: bool = True # send new images after every action tool
|
| 29 |
+
max_steps: int = 30 # tool calls per attempt
|
| 30 |
+
max_no_tool: int = 3 # consecutive replies without a tool call before the attempt is ended
|
| 31 |
+
privileged_locate: bool = False
|
| 32 |
+
grasp_report: str = "bool" # "bool" | "name" | "none"
|
| 33 |
+
instruction: str = "direct" # "direct" | "indirect"
|
| 34 |
+
early_stop: str = "auto" # "auto" (stop at first success unless F0), "yes", "no"
|
| 35 |
+
settle_within: int = 20 # control steps held still before checking a within-protocol segment
|
| 36 |
+
jpeg_quality: int = 90
|
| 37 |
+
save_images: bool = True
|
| 38 |
+
model_for_cost: str = "gpt-6-astra"
|
| 39 |
+
extra: dict = field(default_factory=dict)
|
| 40 |
+
|
| 41 |
+
def validate(self):
|
| 42 |
+
assert self.memory in MEMORY_MODES, self.memory
|
| 43 |
+
assert self.feedback in FEEDBACK_LEVELS, self.feedback
|
| 44 |
+
assert self.grasp_report in ("bool", "name", "none")
|
| 45 |
+
assert self.instruction in ("direct", "indirect")
|
| 46 |
+
assert self.early_stop in ("auto", "yes", "no")
|
| 47 |
+
assert 1 <= self.n_keyframes <= 4 or self.n_keyframes == 0
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def clean_inst(inst):
|
| 51 |
+
return {k: v for k, v in inst.items() if not str(k).startswith("_")}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class AgentHarness:
|
| 55 |
+
def __init__(self, task, backend, cfg: HarnessConfig, logger, payload_probe=None, executor_factory=None,
|
| 56 |
+
cam_axes=None):
|
| 57 |
+
cfg.validate()
|
| 58 |
+
self.task, self.backend, self.cfg, self.log = task, backend, cfg, logger
|
| 59 |
+
self.protocol = getattr(task, "protocol", "cross")
|
| 60 |
+
self.k = cfg.k or task.max_attempts
|
| 61 |
+
self.payload_probe = payload_probe # optional OpenAIResponsesBackend used only to size requests (dry run)
|
| 62 |
+
self.executor_factory = executor_factory # tests: build a fake executor instead of ToolExecutor
|
| 63 |
+
self._cam_axes = cam_axes
|
| 64 |
+
|
| 65 |
+
# ------------------------------------------------------------------ helpers
|
| 66 |
+
def instruction(self, inst):
|
| 67 |
+
hook = getattr(self.task, "agent_instruction", None)
|
| 68 |
+
if hook is not None:
|
| 69 |
+
return hook(inst, self.cfg.instruction)
|
| 70 |
+
if self.cfg.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""):
|
| 71 |
+
return self.task.instruction_indirect
|
| 72 |
+
return self.task.instruction
|
| 73 |
+
|
| 74 |
+
def feedback(self, inst, out, level):
|
| 75 |
+
import inspect
|
| 76 |
+
fn = self.task.feedback
|
| 77 |
+
if "indirect" in inspect.signature(fn).parameters: # tasks that phrase feedback per instruction variant
|
| 78 |
+
return fn(inst, out, level, indirect=self.cfg.instruction == "indirect")
|
| 79 |
+
return fn(inst, out, level)
|
| 80 |
+
|
| 81 |
+
def early_stop(self):
|
| 82 |
+
if self.cfg.early_stop == "auto":
|
| 83 |
+
return self.cfg.feedback != "F0"
|
| 84 |
+
return self.cfg.early_stop == "yes"
|
| 85 |
+
|
| 86 |
+
def terminal(self, out):
|
| 87 |
+
hook = getattr(self.task, "is_terminal", None)
|
| 88 |
+
if hook is not None:
|
| 89 |
+
return bool(hook(out))
|
| 90 |
+
return bool(out.get("terminal") or out.get("overshoot"))
|
| 91 |
+
|
| 92 |
+
def _executor(self, inst):
|
| 93 |
+
if self.executor_factory is not None:
|
| 94 |
+
return self.executor_factory(self, inst)
|
| 95 |
+
from .tools import ToolExecutor
|
| 96 |
+
return ToolExecutor(self.task, inst, image_res=self.cfg.image_res, cams=self.cfg.cams,
|
| 97 |
+
privileged_locate=self.cfg.privileged_locate, grasp_report=self.cfg.grasp_report,
|
| 98 |
+
jpeg_quality=self.cfg.jpeg_quality, image_sink=self._sink)
|
| 99 |
+
|
| 100 |
+
def _sink(self, ref):
|
| 101 |
+
self._img_counter += 1
|
| 102 |
+
rel = f"seed{self._seed}/a{self._attempt}_s{self._step:02d}_{self._img_counter:03d}_{ref.camera}.jpg"
|
| 103 |
+
return self.log.save_image(ref, rel)
|
| 104 |
+
|
| 105 |
+
def _keyframe(self, ref):
|
| 106 |
+
"""Separate (possibly smaller) copy of an agentview frame for the history."""
|
| 107 |
+
from .images import ImageRef
|
| 108 |
+
kres = self.cfg.keyframe_res or self.cfg.image_res
|
| 109 |
+
kf = ImageRef(camera=ref.camera, array=ref.array, label=ref.label)
|
| 110 |
+
if kres == self.cfg.image_res:
|
| 111 |
+
kf.jpeg, kf.path = ref.jpeg, ref.path
|
| 112 |
+
return kf
|
| 113 |
+
self._img_counter += 1
|
| 114 |
+
rel = f"seed{self._seed}/a{self._attempt}_key_{self._img_counter:03d}_{ref.camera}.jpg"
|
| 115 |
+
return self.log.save_image(kf, rel, res=kres)
|
| 116 |
+
|
| 117 |
+
def prompts(self, executor):
|
| 118 |
+
if self._cam_axes is None:
|
| 119 |
+
from . import camera as C
|
| 120 |
+
self._cam_axes = {c: C.describe_axes(self.task.env, c, self.cfg.image_res) for c in C.CAMERAS}
|
| 121 |
+
names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
|
| 122 |
+
return PromptBuilder(self.task, self.protocol, self.k, self.cfg.memory, self.cfg.feedback, self.cfg.image_res,
|
| 123 |
+
self._cam_axes, privileged_locate=self.cfg.privileged_locate, object_names=names,
|
| 124 |
+
grasp_report=self.cfg.grasp_report, cams=self.cfg.cams)
|
| 125 |
+
|
| 126 |
+
# ------------------------------------------------------------------ run
|
| 127 |
+
def run_instance(self, seed, donor=None):
|
| 128 |
+
"""donor: AttemptRecords of another instance (memory=mismatched). Returns (summary, records)."""
|
| 129 |
+
task, cfg = self.task, self.cfg
|
| 130 |
+
inst = task.sample_instance(seed)
|
| 131 |
+
self._seed, self._attempt, self._step, self._img_counter = seed, 0, 0, 0
|
| 132 |
+
self._llm_calls = []
|
| 133 |
+
t_run = time.time()
|
| 134 |
+
sim_wall = 0.0
|
| 135 |
+
info = RunInfo(task=task, inst=inst, seed=seed, k=self.k, protocol=self.protocol, feedback=cfg.feedback,
|
| 136 |
+
memory=cfg.memory)
|
| 137 |
+
self.backend.begin_run(info)
|
| 138 |
+
self.log.event("run_start", seed=seed, inst=clean_inst(inst), task=task.name, protocol=self.protocol, k=self.k,
|
| 139 |
+
memory=cfg.memory, feedback=cfg.feedback, donor_seed=donor[0].seed if donor else None)
|
| 140 |
+
records, executor, status = [], None, "ok"
|
| 141 |
+
for a in range(1, self.k + 1):
|
| 142 |
+
self._attempt, self._step = a, 0
|
| 143 |
+
if self.protocol == "cross" or executor is None:
|
| 144 |
+
t0 = time.time()
|
| 145 |
+
task.reset_instance(inst)
|
| 146 |
+
executor = self._executor(inst)
|
| 147 |
+
sim_wall += time.time() - t0
|
| 148 |
+
visible = select_history(cfg.memory, records, donor)
|
| 149 |
+
rec, attempt_sim = self._attempt_loop(inst, seed, a, visible, executor,
|
| 150 |
+
continuing=self.protocol == "within" and a > 1)
|
| 151 |
+
sim_wall += attempt_sim
|
| 152 |
+
records.append(rec)
|
| 153 |
+
if rec.ended_by == "backend_error":
|
| 154 |
+
status = "error"
|
| 155 |
+
break
|
| 156 |
+
if rec.success and self.early_stop():
|
| 157 |
+
break
|
| 158 |
+
if self.protocol == "within" and (rec.success or self.terminal(rec.outcome)):
|
| 159 |
+
break
|
| 160 |
+
self.backend.end_run()
|
| 161 |
+
summ = run_summary(seed, records, self.k, status=status, llm_calls=self._llm_calls,
|
| 162 |
+
extra=dict(sim_wall_s=round(sim_wall, 2), wall_s=round(time.time() - t_run, 2),
|
| 163 |
+
donor_seed=donor[0].seed if donor else None))
|
| 164 |
+
self.log.event("run_end", **summ)
|
| 165 |
+
summ["_llm_calls"] = self._llm_calls
|
| 166 |
+
return summ, records
|
| 167 |
+
|
| 168 |
+
def _attempt_loop(self, inst, seed, a, visible, ex, continuing):
|
| 169 |
+
cfg, task, backend = self.cfg, self.task, self.backend
|
| 170 |
+
P = self.prompts(ex)
|
| 171 |
+
tools = self.tool_specs()
|
| 172 |
+
conv = Conversation(P.system_prompt())
|
| 173 |
+
backend.begin_attempt(AttemptInfo(attempt=a, history=visible, continuing=continuing))
|
| 174 |
+
sim_t = 0.0
|
| 175 |
+
t0 = time.time()
|
| 176 |
+
obs0 = ex.observe(label="start")
|
| 177 |
+
sim_t += time.time() - t0
|
| 178 |
+
conv.add_user(P.history_parts(self.instruction(inst), visible), live=False)
|
| 179 |
+
conv.add_user(P.current_parts(a, obs0, ex.proprio(), continuing), live=True)
|
| 180 |
+
steps, diagnosis, done_reason, ended_by = [], None, None, None
|
| 181 |
+
n_calls, no_tool = 0, 0
|
| 182 |
+
while ended_by is None:
|
| 183 |
+
if len(steps) >= cfg.max_steps:
|
| 184 |
+
ended_by = "step_budget"
|
| 185 |
+
break
|
| 186 |
+
try:
|
| 187 |
+
resp = backend.act(conv, tools)
|
| 188 |
+
except Exception as e: # API failure after retries, crashed scripted policy, ...
|
| 189 |
+
self.log.event("llm_error", seed=seed, attempt=a, call=n_calls + 1, error=repr(e)[:4000])
|
| 190 |
+
ended_by = "backend_error"
|
| 191 |
+
break
|
| 192 |
+
n_calls += 1
|
| 193 |
+
call_rec = self._log_llm_call(seed, a, n_calls, resp, conv, tools)
|
| 194 |
+
self._llm_calls.append(call_rec)
|
| 195 |
+
if n_calls == 1 and resp.text:
|
| 196 |
+
diagnosis = resp.text
|
| 197 |
+
conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name)
|
| 198 |
+
if not resp.tool_calls:
|
| 199 |
+
no_tool += 1
|
| 200 |
+
if no_tool >= cfg.max_no_tool:
|
| 201 |
+
ended_by = "no_tool_call"
|
| 202 |
+
break
|
| 203 |
+
conv.add_user(P.nudge(), live=True)
|
| 204 |
+
continue
|
| 205 |
+
no_tool = 0
|
| 206 |
+
acted = None
|
| 207 |
+
for tc in resp.tool_calls:
|
| 208 |
+
self._step = len(steps) + 1
|
| 209 |
+
res = ex.call(tc.name, tc.raw_arguments or tc.arguments)
|
| 210 |
+
sim_t += res.wall_s
|
| 211 |
+
conv.add_tool_output(tc.id, tc.name, res.text())
|
| 212 |
+
backend.on_tool_result(tc, res)
|
| 213 |
+
st = StepRecord(step=self._step, name=tc.name, args=res.args, report=res.report, ok=res.ok,
|
| 214 |
+
wall_s=round(res.wall_s, 3), sim_steps=res.sim_steps)
|
| 215 |
+
steps.append(st)
|
| 216 |
+
if res.images:
|
| 217 |
+
conv.add_user(P.observation_parts(f"Images returned by get_observation (step {self._step})",
|
| 218 |
+
res.images, ex.proprio()), live=True)
|
| 219 |
+
if tc.name in ("move_to", "open_gripper", "close_gripper", "push") and res.ok:
|
| 220 |
+
acted = st
|
| 221 |
+
self.log.event("tool_call", seed=seed, attempt=a, step=self._step, call_id=tc.id, name=tc.name,
|
| 222 |
+
args=res.args, ok=res.ok, report=res.report, wall_s=round(res.wall_s, 3),
|
| 223 |
+
sim_steps=res.sim_steps, images=[i.path for i in res.images])
|
| 224 |
+
if res.ended:
|
| 225 |
+
done_reason = res.args.get("reason")
|
| 226 |
+
ended_by = "done"
|
| 227 |
+
break
|
| 228 |
+
if len(steps) >= cfg.max_steps:
|
| 229 |
+
break
|
| 230 |
+
if ended_by is None and acted is not None:
|
| 231 |
+
t1 = time.time()
|
| 232 |
+
if cfg.auto_obs:
|
| 233 |
+
obs = ex.observe(label=f"step{acted.step}")
|
| 234 |
+
conv.add_user(P.step_observation(acted.step, acted.name, obs, ex.proprio()), live=True)
|
| 235 |
+
acted.frame = next((o for o in obs if o.camera == "agentview"), obs[0])
|
| 236 |
+
else: # still keep an agentview frame for the history keyframes / logs
|
| 237 |
+
from .images import ImageRef
|
| 238 |
+
acted.frame = self._sink(ImageRef(camera="agentview", array=ex.render("agentview"),
|
| 239 |
+
label=f"step{acted.step}"))
|
| 240 |
+
sim_t += time.time() - t1
|
| 241 |
+
self.log.event("observation", seed=seed, attempt=a, step=acted.step,
|
| 242 |
+
images=[acted.frame.path] if not cfg.auto_obs else [o.path for o in obs],
|
| 243 |
+
proprio=ex.proprio())
|
| 244 |
+
meta = backend.end_attempt() or {}
|
| 245 |
+
# ------------------------------------------------------------ outcome + packing
|
| 246 |
+
t1 = time.time()
|
| 247 |
+
home = getattr(task, "go_home", None) # task-defined end-of-attempt motion (e.g. L6: arm out of view)
|
| 248 |
+
if home is not None and ended_by != "backend_error":
|
| 249 |
+
home()
|
| 250 |
+
if self.protocol == "within" and cfg.settle_within:
|
| 251 |
+
ex.sk.hold(cfg.settle_within)
|
| 252 |
+
out = task.outcome(inst)
|
| 253 |
+
from .images import ImageRef
|
| 254 |
+
self._step = 99
|
| 255 |
+
final = self._sink(ImageRef(camera="agentview", array=ex.render("agentview", cfg.keyframe_res or cfg.image_res),
|
| 256 |
+
label="end"))
|
| 257 |
+
sim_t += time.time() - t1
|
| 258 |
+
fb = self.feedback(inst, out, cfg.feedback)
|
| 259 |
+
fb_full = self.feedback(inst, out, "F2")
|
| 260 |
+
init_frame = next((o for o in obs0 if o.camera == "agentview"), None)
|
| 261 |
+
for s in steps:
|
| 262 |
+
if s.frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res:
|
| 263 |
+
s.frame = self._keyframe(s.frame)
|
| 264 |
+
if init_frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res:
|
| 265 |
+
init_frame = self._keyframe(init_frame)
|
| 266 |
+
kfs = pick_keyframes(steps, init_frame, final, cfg.n_keyframes) if cfg.n_keyframes else []
|
| 267 |
+
rec = AttemptRecord(seed=seed, attempt=a, steps=steps, keyframes=kfs, outcome=dict(out),
|
| 268 |
+
success=bool(out.get("success")), feedback=fb, done_reason=done_reason, diagnosis=diagnosis,
|
| 269 |
+
ended_by=ended_by, backend_meta=meta)
|
| 270 |
+
calls = [c for c in self._llm_calls if c["attempt"] == a]
|
| 271 |
+
self.log.event("attempt_end", seed=seed, attempt=a, success=rec.success, outcome=out, feedback_shown=fb,
|
| 272 |
+
feedback_f2=fb_full, ended_by=ended_by, done_reason=done_reason, diagnosis=diagnosis,
|
| 273 |
+
n_steps=len(steps), n_llm_calls=len(calls), backend_meta=meta,
|
| 274 |
+
history_shown=[(h.seed, h.attempt) for h in visible],
|
| 275 |
+
keyframes=[(c, r.path) for c, r in kfs], action_summary=summarize_actions(steps),
|
| 276 |
+
llm_latency_s=round(sum(c["latency_s"] for c in calls), 3), sim_wall_s=round(sim_t, 3))
|
| 277 |
+
return rec, sim_t
|
| 278 |
+
|
| 279 |
+
def tool_specs(self):
|
| 280 |
+
from .tools import tool_specs
|
| 281 |
+
names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
|
| 282 |
+
return tool_specs(self.cfg.privileged_locate, names, self.cfg.image_res)
|
| 283 |
+
|
| 284 |
+
def _log_llm_call(self, seed, a, n, resp, conv, tools):
|
| 285 |
+
rec = dict(seed=seed, attempt=a, call=n, latency_s=round(resp.latency_s, 3), usage=resp.usage,
|
| 286 |
+
cost_usd=call_cost(resp.usage, self.cfg.model_for_cost) if resp.usage else None,
|
| 287 |
+
status=resp.status, error=resp.error, text=resp.text, reasoning_summary=resp.reasoning_summary,
|
| 288 |
+
reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned",
|
| 289 |
+
tool_calls=[dict(id=t.id, name=t.name, arguments=t.arguments) for t in resp.tool_calls],
|
| 290 |
+
request=resp.request_stats, conv_images=conv.n_images())
|
| 291 |
+
if self.payload_probe is not None: # dry run: size of the request GPT-6 would have received
|
| 292 |
+
stats = self.payload_probe.request_stats(self.payload_probe.build_request(conv, tools))
|
| 293 |
+
stats["est_input_tokens"] = estimate_request_tokens(stats, self.cfg.image_res)
|
| 294 |
+
rec["dry_run_request"] = stats
|
| 295 |
+
self.log.event("llm_call", **rec)
|
| 296 |
+
return rec
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def config_dict(cfg):
|
| 300 |
+
return asdict(cfg)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/agent/metrics.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run-level metrics (design doc 02 §5): succ@k per run, attempt-1 success, first-success attempt,
|
| 2 |
+
fields for ΔICL = succ@k(with history) - pass@k_iid(independent retries), same-mistake (repeated
|
| 3 |
+
action) rate, residuals, tokens / cost / latency."""
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from .context import wilson
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def run_summary(seed, records, k, status="ok", llm_calls=(), extra=None):
|
| 10 |
+
"""records: list[AttemptRecord] of one run (one instance)."""
|
| 11 |
+
succ = [bool(r.success) for r in records]
|
| 12 |
+
first = next((r.attempt for r in records if r.success), None)
|
| 13 |
+
fails = [r for r in records if not r.success]
|
| 14 |
+
pairs = [(a, b) for a, b in zip(records, records[1:]) if not a.success]
|
| 15 |
+
repeats = [a.action_signature() == b.action_signature() for a, b in pairs]
|
| 16 |
+
residuals = [{kk: v for kk, v in r.outcome.items() if kk.endswith("_err") and isinstance(v, (int, float))}
|
| 17 |
+
for r in records]
|
| 18 |
+
lat = [c.get("latency_s", 0.0) for c in llm_calls]
|
| 19 |
+
usage = {key: int(sum((c.get("usage") or {}).get(key, 0) or 0 for c in llm_calls))
|
| 20 |
+
for key in ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens",
|
| 21 |
+
"reasoning_tokens")}
|
| 22 |
+
cost = [c.get("cost_usd") for c in llm_calls if c.get("cost_usd") is not None]
|
| 23 |
+
out = dict(seed=seed, status=status, k=k, n_attempts=len(records), success_by_attempt=succ,
|
| 24 |
+
first_success=first, success=first is not None, attempt1_success=bool(succ[0]) if succ else False,
|
| 25 |
+
ended_by=[r.ended_by for r in records], n_failed_attempts=len(fails),
|
| 26 |
+
repeated_action_pairs=int(sum(repeats)), failed_pairs=len(pairs), residuals=residuals,
|
| 27 |
+
n_llm_calls=len(llm_calls), llm_latency_s=float(sum(lat)), usage=usage,
|
| 28 |
+
cost_usd=float(sum(cost)) if cost else None,
|
| 29 |
+
n_tool_calls=int(sum(len(r.steps) for r in records)))
|
| 30 |
+
if extra:
|
| 31 |
+
out.update(extra)
|
| 32 |
+
return out
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def aggregate(runs, k):
|
| 36 |
+
ok = [r for r in runs if r["status"] == "ok"]
|
| 37 |
+
n = len(ok)
|
| 38 |
+
first = [r["first_success"] for r in ok]
|
| 39 |
+
curve, ci = [], []
|
| 40 |
+
for j in range(1, k + 1):
|
| 41 |
+
s = sum(1 for f in first if f is not None and f <= j)
|
| 42 |
+
curve.append(s / n if n else float("nan"))
|
| 43 |
+
ci.append(wilson(s, n))
|
| 44 |
+
p1 = curve[0] if curve else float("nan")
|
| 45 |
+
succ_first = [f for f in first if f is not None]
|
| 46 |
+
calls = [c for r in ok for c in r.get("_llm_calls", [])]
|
| 47 |
+
lat = np.array([c.get("latency_s", 0.0) for c in calls]) if calls else np.zeros(0)
|
| 48 |
+
pairs = sum(r["failed_pairs"] for r in ok)
|
| 49 |
+
tot = {key: int(sum(r["usage"].get(key, 0) for r in ok))
|
| 50 |
+
for key in ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens", "reasoning_tokens")}
|
| 51 |
+
costs = [r["cost_usd"] for r in ok if r.get("cost_usd") is not None]
|
| 52 |
+
return dict(
|
| 53 |
+
n_runs=n, n_error_runs=len(runs) - n, k=k,
|
| 54 |
+
succ_at=curve, succ_at_ci95=ci, succ_at_k=curve[-1] if curve else float("nan"),
|
| 55 |
+
attempt1_success=p1,
|
| 56 |
+
# ΔICL needs pass@k of independent retries: measure it with --memory none on the same seeds and
|
| 57 |
+
# compare with scripts/agent_compare.py. The analytic value assumes i.i.d. attempts with the
|
| 58 |
+
# attempt-1 success rate of THIS run set (a cheaper but weaker reference).
|
| 59 |
+
pass_at_k_iid_analytic=1 - (1 - p1) ** k if n else float("nan"),
|
| 60 |
+
delta_icl_vs_analytic_iid=(curve[-1] - (1 - (1 - p1) ** k)) if n else float("nan"),
|
| 61 |
+
mean_first_success=float(np.mean(succ_first)) if succ_first else None,
|
| 62 |
+
median_first_success=float(np.median(succ_first)) if succ_first else None,
|
| 63 |
+
repeated_action_rate=(sum(r["repeated_action_pairs"] for r in ok) / pairs) if pairs else None,
|
| 64 |
+
llm_calls_per_run=float(np.mean([r["n_llm_calls"] for r in ok])) if ok else None,
|
| 65 |
+
llm_latency_mean_s=float(lat.mean()) if lat.size else None,
|
| 66 |
+
llm_latency_p50_s=float(np.percentile(lat, 50)) if lat.size else None,
|
| 67 |
+
llm_latency_p95_s=float(np.percentile(lat, 95)) if lat.size else None,
|
| 68 |
+
llm_latency_per_run_s=float(np.mean([r["llm_latency_s"] for r in ok])) if ok else None,
|
| 69 |
+
sim_wall_per_run_s=float(np.mean([r.get("sim_wall_s", 0.0) for r in ok])) if ok else None,
|
| 70 |
+
tool_calls_per_run=float(np.mean([r["n_tool_calls"] for r in ok])) if ok else None,
|
| 71 |
+
usage_total=tot,
|
| 72 |
+
cache_hit_rate=(tot["cached_tokens"] / tot["input_tokens"]) if tot["input_tokens"] else None,
|
| 73 |
+
cost_usd_total=float(sum(costs)) if costs else None,
|
| 74 |
+
cost_usd_per_run=float(np.mean(costs)) if costs else None,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def paired_delta(with_runs, iid_runs, k, n_boot=10000, seed=0):
|
| 79 |
+
"""ΔICL = succ@k(with) - succ@k(iid) on the seeds both run sets share, with a paired bootstrap CI."""
|
| 80 |
+
a = {r["seed"]: r for r in with_runs if r["status"] == "ok"}
|
| 81 |
+
b = {r["seed"]: r for r in iid_runs if r["status"] == "ok"}
|
| 82 |
+
seeds = sorted(set(a) & set(b))
|
| 83 |
+
if not seeds:
|
| 84 |
+
return dict(n=0)
|
| 85 |
+
|
| 86 |
+
def ok(r):
|
| 87 |
+
return r["first_success"] is not None and r["first_success"] <= k
|
| 88 |
+
|
| 89 |
+
x = np.array([ok(a[s]) for s in seeds], float)
|
| 90 |
+
y = np.array([ok(b[s]) for s in seeds], float)
|
| 91 |
+
d = x - y
|
| 92 |
+
rng = np.random.default_rng(seed)
|
| 93 |
+
idx = rng.integers(0, len(d), size=(n_boot, len(d)))
|
| 94 |
+
boot = d[idx].mean(1)
|
| 95 |
+
return dict(n=len(seeds), succ_at_k_with=float(x.mean()), succ_at_k_iid=float(y.mean()), delta_icl=float(d.mean()),
|
| 96 |
+
ci95=[float(np.percentile(boot, 2.5)), float(np.percentile(boot, 97.5))],
|
| 97 |
+
discordant=dict(with_only=int(((x == 1) & (y == 0)).sum()), iid_only=int(((x == 0) & (y == 1)).sum())))
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-task specs for the controlled arms of full5 (2026-10-12, docs/14 §6).
|
| 2 |
+
|
| 3 |
+
One module per task, named exactly like the task (lffbench/arm_specs/<task_name>.py), defining:
|
| 4 |
+
|
| 5 |
+
HIDDEN_KEYS : tuple of instance keys that carry the hidden variable(s)
|
| 6 |
+
h0(inst) -> dict overrides for the H0 twin: same layout, hidden variable at its "ordinary" value, so the
|
| 7 |
+
common-sense first attempt succeeds (scripted naive succeeds)
|
| 8 |
+
twin(inst) -> dict overrides for the mismatched-history source: same layout, the trap is still active (scripted
|
| 9 |
+
naive still fails, visibly) but the right correction is different from the original instance's,
|
| 10 |
+
ideally opposite (e.g. centre of mass on the other side)
|
| 11 |
+
reveal(inst)-> str H+ text appended to the task instruction: the hidden variable stated plainly in robot-frame
|
| 12 |
+
words a careful human could act on, without prescribing the solution
|
| 13 |
+
|
| 14 |
+
All three take the ORIGINAL sampled instance and return only the keys to change (JSON-serialisable). The server
|
| 15 |
+
applies them with dict.update() after sample_instance(); reset_instance() must honour them.
|
| 16 |
+
"""
|
| 17 |
+
import importlib
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load(task_name):
|
| 21 |
+
"""The spec module for task_name, or None if the task has no controlled-arm spec."""
|
| 22 |
+
try:
|
| 23 |
+
return importlib.import_module(f"{__name__}.{task_name}")
|
| 24 |
+
except ModuleNotFoundError as e:
|
| 25 |
+
if e.name == f"{__name__}.{task_name}":
|
| 26 |
+
return None
|
| 27 |
+
raise
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def overrides(task_name, arm, inst):
|
| 31 |
+
"""Instance overrides for arm in (h0, twin); {} for other arms."""
|
| 32 |
+
if arm not in ("h0", "twin"):
|
| 33 |
+
return {}
|
| 34 |
+
spec = load(task_name)
|
| 35 |
+
if spec is None:
|
| 36 |
+
raise SystemExit(f"--arm {arm}: no spec in lffbench/arm_specs/{task_name}.py")
|
| 37 |
+
return getattr(spec, arm)(inst)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def reveal(task_name, inst):
|
| 41 |
+
spec = load(task_name)
|
| 42 |
+
if spec is None:
|
| 43 |
+
raise SystemExit(f"--arm hplus: no spec in lffbench/arm_specs/{task_name}.py")
|
| 44 |
+
return spec.reveal(inst)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def fix(task_name, inst, params):
|
| 48 |
+
"""Fix-rung text of the layer-3 feedback ladder (docs/20): how to succeed on this instance, in robot-frame words,
|
| 49 |
+
built from the task's oracle parameters `params` (task.oracle_params(inst), computed by the caller with the sim)."""
|
| 50 |
+
spec = load(task_name)
|
| 51 |
+
if spec is None or not hasattr(spec, "fix"):
|
| 52 |
+
raise SystemExit(f"ladder fix: no fix() in lffbench/arm_specs/{task_name}.py")
|
| 53 |
+
return spec.fix(inst, params)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l3_card_shelf.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l3_card_shelf (2026-10-12, docs/14 sec. 6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: which end of the (symmetric-looking) card holds the 8 g weight. The centre of mass is compiled into
|
| 4 |
+
the card's MJCF along its local +x, so the heavy end is chosen purely by `card_yaw` (heavy end direction = yaw);
|
| 5 |
+
`heavy_near` / `heavy_edge` are bookkeeping only (nothing in reset / outcome / policies reads them), kept consistent.
|
| 6 |
+
No override changes geometry, mass or inertia, so no bounding-volume refit is involved.
|
| 7 |
+
|
| 8 |
+
h0 : the same card turned end for end (yaw + 180 deg): identical pose and footprint, the weight now in the FAR end,
|
| 9 |
+
so the common-sense "slide the nearest end out" slides the light end and succeeds.
|
| 10 |
+
twin : the trap stays (the heavy end is the nearest end) but it points to the OPPOSITE shelf edge: the card is mirrored
|
| 11 |
+
through the shelf centre along its long axis (near gap, side offset, jitter mirrored) and keeps its weight in
|
| 12 |
+
the end that is now nearest. The right correction (slide the other, light end) is then over the opposite
|
| 13 |
+
edge. For an x-card this makes the near end the BACKWARD one, which the task's own sampler avoids because a
|
| 14 |
+
card tipping off the backward edge lands behind the shelf (agentview shows the shelf empty, not the card);
|
| 15 |
+
see the arm validation (results/l3_card_shelf/arms/). For an instance whose heavy end is already the far end
|
| 16 |
+
(naive succeeds there) the twin keeps the pose and turns the card end for end, so the weight is in the near
|
| 17 |
+
end and the heavy edge is again the opposite one.
|
| 18 |
+
reveal: which shelf edge the heavy end points to, in the F2 feedback's edge words.
|
| 19 |
+
"""
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
HIDDEN_KEYS = ("card_yaw", "heavy_near", "heavy_edge")
|
| 23 |
+
|
| 24 |
+
OPPOSITE = {"forward": "backward", "backward": "forward", "left": "right", "right": "left"}
|
| 25 |
+
GLOSS = {"forward": "away from the robot", "backward": "towards the robot", "left": "on the robot's left",
|
| 26 |
+
"right": "on the robot's right"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _wrap(a):
|
| 30 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def h0(inst):
|
| 34 |
+
if not inst["heavy_near"]:
|
| 35 |
+
return {} # already the ordinary case for the naive habit (weight away from the end that gets slid out)
|
| 36 |
+
return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=False, heavy_edge=inst["far_edge"])
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def twin(inst):
|
| 40 |
+
if not inst["heavy_near"]:
|
| 41 |
+
return dict(card_yaw=_wrap(inst["card_yaw"] + np.pi), heavy_near=True, heavy_edge=inst["near_edge"])
|
| 42 |
+
a = 0 if inst["card_along"] == "x" else 1 # world axis of the card's long side
|
| 43 |
+
c = list(inst["card_xy"])
|
| 44 |
+
c[a] = 2.0 * inst["shelf_xy"][a] - c[a]
|
| 45 |
+
yaw = inst["card_yaw"]
|
| 46 |
+
yaw = np.pi - yaw if a == 0 else -yaw # reflection x -> -x (resp. y -> -y) of the card's heading
|
| 47 |
+
return dict(card_xy=[float(c[0]), float(c[1])], card_yaw=_wrap(yaw), near_edge=OPPOSITE[inst["near_edge"]],
|
| 48 |
+
far_edge=OPPOSITE[inst["far_edge"]], heavy_edge=OPPOSITE[inst["heavy_edge"]])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def reveal(inst):
|
| 52 |
+
e = inst["heavy_edge"]
|
| 53 |
+
return (f"The card is not uniform: 8 g of its 10 g are a weight hidden in the end that points towards the shelf's "
|
| 54 |
+
f"{e} edge ({GLOSS[e]}), so its centre of mass is 2.8 cm from the card's middle towards that end.")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def fix(inst, params):
|
| 58 |
+
"""Ladder Fix rung (docs/20): slide the light end out (two strokes to 2 and 3 cm), grasp the overhang, bin."""
|
| 59 |
+
light = OPPOSITE[inst["heavy_edge"]]
|
| 60 |
+
return (f"A way to succeed: slide the light end out, not the heavy one. The light end is the one pointing towards "
|
| 61 |
+
f"the shelf's {light} edge ({GLOSS[light]}). With the gripper closed, press the fingertips lightly on the "
|
| 62 |
+
f"middle of the card and drag it slowly (speed about 0.08) along its long side towards that edge, in two "
|
| 63 |
+
f"strokes: first until that end sticks out about 2 cm beyond the edge, look, then until it sticks out "
|
| 64 |
+
f"about 3 cm. Then open the gripper, grasp the part that sticks out about 2 cm beyond the edge, at the "
|
| 65 |
+
f"card's height, lift it and drop the card into the bin.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l3_wall_flush (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["gap"] -- the box-wall gap, 0-3 mm (below camera resolution), far less than the ~1.2 cm a
|
| 4 |
+
finger needs, so the wall-side finger lands on the wall top. sample_instance caches the wall position derived from it
|
| 5 |
+
(wall_x = box_x + side * (wall half thickness + box half width + gap)) and apply_instance reads only inst["wall_xy"],
|
| 6 |
+
so every override below sets wall_xy as well.
|
| 7 |
+
|
| 8 |
+
h0 gap = 5 cm: box, plate, wall length and wall y unchanged, the wall moved 4.7-5 cm away from the box (on the
|
| 9 |
+
same side). There is room for the whole finger and the prior (grasp across the width where the box lies) works.
|
| 10 |
+
(2.5 cm was not enough: the open fingers reach 6.6 cm from the grasp centre, so with the wall on the far side
|
| 11 |
+
the outer edge of the finger still caught the wall top and the box slipped out on the way, seeds 3000 / 3003.)
|
| 12 |
+
twin Gap unchanged (box still flush, trap active), box / plate / wall length / wall x unchanged, but the wall slid
|
| 13 |
+
along y so that the box sits near the OTHER end of the wall, 2 cm of wall beyond the box's end (the sampler's
|
| 14 |
+
extreme). The original's nearer wall end is +y (or -y); the twin's is -y (or +y): the push that clears the
|
| 15 |
+
wall goes the opposite way, and is the shortest possible push (about 10 + 4.5 cm).
|
| 16 |
+
Note: pushing the original's box towards its FAR end also clears the wall (just a longer push), so the cross
|
| 17 |
+
check "twin oracle on the original" succeeds (measured 5/5, seeds 3000-3004; results/l3_wall_flush/arms/
|
| 18 |
+
validate.json). The twin changes which way to push, not whether pushing works.
|
| 19 |
+
reveal The gap, and on which side of the box the wall is, in the task's F2 frame words.
|
| 20 |
+
"""
|
| 21 |
+
BOX_HALF_X, BOX_HALF_Y, WALL_HALF_T = 0.03, 0.08, 0.015
|
| 22 |
+
H0_GAP = 0.05
|
| 23 |
+
|
| 24 |
+
HIDDEN_KEYS = ("gap",)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _wall_x(inst, gap):
|
| 28 |
+
return inst["box_xy"][0] + inst["side"] * (WALL_HALF_T + BOX_HALF_X + gap)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def h0(inst):
|
| 32 |
+
return {"gap": H0_GAP, "wall_xy": [_wall_x(inst, H0_GAP), inst["wall_xy"][1]]}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def twin(inst):
|
| 36 |
+
wy, by = inst["wall_xy"][1], inst["box_xy"][1]
|
| 37 |
+
u_max = inst["wall_hl"] - BOX_HALF_Y - 0.02
|
| 38 |
+
nearer = 1 if by - wy > 0 else -1 # same rule as WallFlush._nearer_end
|
| 39 |
+
u_twin = -nearer * u_max # box offset from the wall centre in the twin: near the other end
|
| 40 |
+
return {"wall_xy": [inst["wall_xy"][0], by - u_twin]}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def reveal(inst):
|
| 44 |
+
side = "far side (away from the robot)" if inst["side"] > 0 else "near side (toward the robot)"
|
| 45 |
+
return (f"The long box is pressed against the wall on its {side} along its whole length: the gap between box "
|
| 46 |
+
f"and wall is only about {max(100 * inst['gap'], 0.1):.1f} cm.")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def fix(inst, params):
|
| 50 |
+
"""Ladder Fix rung (docs/20): push the box along the wall past its nearer end (oracle end, margin 4.5 cm), then
|
| 51 |
+
grasp across the width and place."""
|
| 52 |
+
end, margin = int(params["end"]), float(params["margin"])
|
| 53 |
+
wy, hl, by = float(inst["wall_xy"][1]), float(inst["wall_hl"]), float(inst["box_xy"][1])
|
| 54 |
+
wall_end = wy + hl if end > 0 else wy - hl
|
| 55 |
+
dist = max(0.0, end * (wall_end + end * margin - by))
|
| 56 |
+
side, other = ("left", "right") if end > 0 else ("right", "left")
|
| 57 |
+
return (f"A way to succeed: first get the box away from the wall, then grasp it. With the gripper closed and the "
|
| 58 |
+
f"fingertips about 1 cm above the table, push on the box's end face on the robot's {other} side and slide "
|
| 59 |
+
f"the box slowly (speed about 0.08) along the wall towards the robot's {side}, about {100 * dist:.0f} cm, "
|
| 60 |
+
f"until the whole box is past the end of the wall (its centre about {100 * margin:.1f} cm beyond the "
|
| 61 |
+
f"wall's end). Then lift, open the gripper, grasp the box across its 6 cm width and put it on the plate.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l4_fit_container.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l4_fit_container (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["cap"] -- clear (unrendered) bumper caps on both ends of the phone, 0.8-0.9 cm each, so the
|
| 4 |
+
phone is 1.6-1.8 cm longer than it looks. The prior picks the box with the most visible room to spare ("snug"),
|
| 5 |
+
which is too short for the capped phone; only the "fit" box is long enough.
|
| 6 |
+
|
| 7 |
+
h0 cap = 0: no caps. The phone is exactly as big as it looks, the "snug" box the prior picks fits it (as do "fit"
|
| 8 |
+
and "short_wide"). inst["fit"] is left as is (that box still fits).
|
| 9 |
+
twin Same box positions / yaws, same phone, same caps (trap still active), but the inner sizes (and kinds) of the
|
| 10 |
+
"fit" and "snug" boxes are swapped. In the twin the prior goes to the place where the ORIGINAL's fitting box
|
| 11 |
+
stands (now with snug sizes) and fails on the rim; the twin's fitting box stands where the original's snug box
|
| 12 |
+
stands. So the twin's lesson at the action level ("not that box, use that other box") is exactly the reverse
|
| 13 |
+
of the original's: following it on the original means choosing the original's failing (snug) box.
|
| 14 |
+
Caveat: the abstract lesson ("the phone is longer than it looks, take the box with the most length to spare")
|
| 15 |
+
is the same in both -- a negative cap (phone shorter than it looks) is not physically possible here. The box
|
| 16 |
+
sizes in the twin images differ from the original's at those two positions (they are visible).
|
| 17 |
+
reveal The cap length, in cm, per end and in total.
|
| 18 |
+
"""
|
| 19 |
+
HIDDEN_KEYS = ("cap",)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def h0(inst):
|
| 23 |
+
return {"cap": 0.0}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _idx(inst, kind):
|
| 27 |
+
return next(j for j, b in enumerate(inst["boxes"]) if b["kind"] == kind)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def twin(inst):
|
| 31 |
+
f, s = _idx(inst, "fit"), _idx(inst, "snug")
|
| 32 |
+
boxes = [dict(b) for b in inst["boxes"]]
|
| 33 |
+
for k in ("kind", "inner"):
|
| 34 |
+
boxes[f][k], boxes[s][k] = inst["boxes"][s][k], inst["boxes"][f][k]
|
| 35 |
+
perc = [list(p) for p in inst["_perc"]]
|
| 36 |
+
perc[f], perc[s] = list(inst["_perc"][s]), list(inst["_perc"][f])
|
| 37 |
+
return {"boxes": boxes, "fit": s, "fit_crossed": boxes[s]["crossed"], "_perc": perc}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def reveal(inst):
|
| 41 |
+
c = 100 * inst["cap"]
|
| 42 |
+
return (f"The phone has clear bumper caps on both of its short ends that do not show in the camera images; "
|
| 43 |
+
f"each cap adds about {c:.1f} cm, so the phone is about {2 * c:.1f} cm longer than it looks.")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _where(inst, j):
|
| 47 |
+
"""robot-frame position words of box j in the 2 x 3 grid (rows along x, columns along y)"""
|
| 48 |
+
xs = sorted({round(float(b["xy"][0]), 2) for b in inst["boxes"]} | {round(float(inst["phone_xy"][0]), 2)})
|
| 49 |
+
x, y = (float(v) for v in inst["boxes"][j]["xy"])
|
| 50 |
+
row = "in the row nearer to the robot" if abs(x - xs[0]) < abs(x - xs[-1]) else "in the row farther from the robot"
|
| 51 |
+
col = "on the robot's left" if y > 0.1 else ("on the robot's right" if y < -0.1 else "in the middle")
|
| 52 |
+
return f"{row}, {col}"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def fix(inst, params):
|
| 56 |
+
"""Ladder Fix rung (docs/20): the fitting box (oracle box = inst['fit']), long side along the box's long side."""
|
| 57 |
+
j = int(params["box"])
|
| 58 |
+
return (f"A way to succeed: the phone fits only into the box {_where(inst, j)} (the one with the most length to "
|
| 59 |
+
f"spare; it looks tight across, but the phone's width fits). Pick the phone up, turn it so that its long "
|
| 60 |
+
f"side lines up with that box's long side, and lower it flat into the middle of that box before you "
|
| 61 |
+
f"release it.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l7_key_turn.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled-arm spec for l7_key_turn (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["direction"], the way the key opens the lock ("CCW" or "CW", seen from above). apply_instance()
|
| 4 |
+
derives the joint range and outcome()/check_unlock()/oracle_params() derive the open sign from it on every reset, so
|
| 5 |
+
overriding "direction" alone is enough (nothing is cached at sampling time).
|
| 6 |
+
|
| 7 |
+
The scripted prior (naive) turns counterclockwise, so the trap exists only on CW locks -- all full5 instances are CW.
|
| 8 |
+
|
| 9 |
+
h0 -> direction = "CCW": same lock position / yaw, the key opens the common-sense way, naive succeeds.
|
| 10 |
+
twin -> {} (no valid twin). The task has a single binary hidden variable and the trap exists only for one of its two
|
| 11 |
+
values: a twin with the trap still active must be CW again, i.e. need exactly the same correction ("turn
|
| 12 |
+
clockwise"), and the sign-flipped twin (CCW) is the H0 twin, where naive succeeds. There is no second hidden
|
| 13 |
+
constraint (the required angle is the fixed quarter turn named in the instruction). The mismatched-history
|
| 14 |
+
arm therefore has to take another instance's history -- note that every trap instance's history teaches the
|
| 15 |
+
same correction, so for this task a mismatched history is not misleading about the direction.
|
| 16 |
+
reveal -> states which way the key turns and that the other way stops after ~3 deg (the words "clockwise",
|
| 17 |
+
"counterclockwise", "seen from above" are those of the task's F2 feedback).
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
HIDDEN_KEYS = ("direction",)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def h0(inst):
|
| 24 |
+
return {"direction": "CCW"}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def twin(inst):
|
| 28 |
+
return {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def reveal(inst):
|
| 32 |
+
ok, other = (("counterclockwise", "clockwise") if inst["direction"] == "CCW" else ("clockwise", "counterclockwise"))
|
| 33 |
+
return (f"Note: this lock opens only when the key is turned {ok} (seen from above); turned {other} the key moves "
|
| 34 |
+
f"about 3 degrees and then hits a hard stop.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/l7_offcenter_push.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l7_offcenter_push (docs/14 §6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: com_offset = e, the shift of the box's centre of mass along its long axis (world +y = robot's left;
|
| 4 |
+
|e| in [4.5, 7.5] cm). apply_instance() writes it into body_ipos on every reset; oracle_params() pushes at c = e.
|
| 5 |
+
|
| 6 |
+
h0 e = 0: centre of mass in the middle, so the natural push at the middle of the back face goes straight.
|
| 7 |
+
twin e -> -e: same distance from the middle, other end heavy. The naive push turns the box just as much but the
|
| 8 |
+
other way (clockwise <-> counterclockwise, the other end lags), and the right contact point is on the other
|
| 9 |
+
side of the middle, so the original's lesson ("move the contact toward the left/right end") is reversed.
|
| 10 |
+
reveal states |e| and its side in the robot-frame words of the F2 feedback (robot's left / right).
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
HIDDEN_KEYS = ("com_offset",)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def h0(inst):
|
| 17 |
+
return {"com_offset": 0.0}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def twin(inst):
|
| 21 |
+
return {"com_offset": -float(inst["com_offset"])}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def reveal(inst):
|
| 25 |
+
e = float(inst["com_offset"])
|
| 26 |
+
side = "left" if e > 0 else "right"
|
| 27 |
+
return (f"The box's centre of mass is not at its middle: it is about {100 * abs(e):.1f} cm from the middle along "
|
| 28 |
+
f"the box's long side, toward the robot's {side}.")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def fix(inst, params):
|
| 32 |
+
"""Ladder Fix rung (docs/20): push at the centre of mass (oracle c = e), one slow straight push."""
|
| 33 |
+
c = float(params["c"])
|
| 34 |
+
side = "left" if c > 0 else "right"
|
| 35 |
+
return (f"A way to succeed: push at the centre of mass, not at the middle. Close the gripper (yaw 0), put the "
|
| 36 |
+
f"fingertips about 1 cm above the table just behind the box's back face (the face towards the robot), "
|
| 37 |
+
f"{100 * abs(c):.1f} cm to the robot's {side} of that face's middle, and push slowly (speed about 0.08) "
|
| 38 |
+
f"straight forward, away from the robot, until the box is centred in the green rectangle; then lift the "
|
| 39 |
+
f"gripper.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/lh_clear_cover.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layer-4 intervention texts for lh_clear_cover (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is
|
| 2 |
+
not in the controlled arms of full5.
|
| 3 |
+
|
| 4 |
+
Hidden variable: inst["cover"] -- which box carries the nearly invisible clear lid (None in uncovered instances).
|
| 5 |
+
reveal says which box is covered and what the lid does to a released cube; not how to deal with it.
|
| 6 |
+
fix the oracle's edge push (lh_clear_cover.remove_cover) in move_eef words; params["z_push"] = grasp-point height of
|
| 7 |
+
that push in the eef_pos frame, params["push_len"] = length of the sweep (scripts/layer4_plan.py validate).
|
| 8 |
+
"""
|
| 9 |
+
HIDDEN_KEYS = ("cover",)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def reveal(inst):
|
| 13 |
+
return (f"The {inst['cover']} box is covered by a loose, nearly invisible clear lid lying on its walls, 8 mm thick. "
|
| 14 |
+
f"A cube released over that box stops on the lid at rim height; it is not in the box.")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def fix(inst, params):
|
| 18 |
+
return (f"A way to succeed: first push the lid off the {inst['cover']} box. Close the gripper, keep yaw 0 and bring "
|
| 19 |
+
f"the grasp point to height {params['z_push']:.3f} (the third value of eef_pos), so that the fingertips are "
|
| 20 |
+
f"level with the lid's edge, 3 cm outside the edge of the lid that faces the other box. Then in one move_eef "
|
| 21 |
+
f"command sweep {params['push_len'] * 100:.0f} cm straight along the line between the two boxes, away from "
|
| 22 |
+
f"the other box, at speed 0.06, and lift. The lid is then off. Put each cube into the box of its colour, and "
|
| 23 |
+
f"check from the side view that no cube rests at rim height.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Layer-4 intervention texts for lh_tidy_stack (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is
|
| 2 |
+
not in the controlled arms of full5.
|
| 3 |
+
|
| 4 |
+
Hidden variable: inst["soft_colour"] -- the empty soft carton among the four boxes (None in benign instances).
|
| 5 |
+
reveal says which box is soft and how much it carries; not where to put it.
|
| 6 |
+
fix the oracle's order (lh_tidy_stack.oracle_params: rigid boxes first, the soft box last, then the cup).
|
| 7 |
+
"""
|
| 8 |
+
HIDDEN_KEYS = ("soft_colour",)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def reveal(inst):
|
| 12 |
+
return (f"The {inst['soft_colour']} box is an empty, soft carton. It carries one thing, but gives way as soon as a "
|
| 13 |
+
f"second thing rests above it, and everything above it slides off the pile.")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def fix(inst, params):
|
| 17 |
+
return (f"A way to succeed: stack the other three boxes first, put the {inst['soft_colour']} box on top of them last, "
|
| 18 |
+
f"and stand the cup on it. It then carries only the cup.")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "fbf323682711d7010fa8cd2c9036b1082dab2a6cd4cf80983be1adf64e037d7c",
|
| 4 |
+
"written": "2026-10-20 02:16:00",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 182,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-sonnet-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_nudge_row.py
ADDED
|
@@ -0,0 +1,821 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LH lh_nudge_row v2 (2026-10-14): stand four small cups, one by one, on the four coloured mats of their colours; the
|
| 2 |
+
mats lie in two rows of two, and in 7 of 10 instances the two mats of a row touch. Letting go of a cup with the fingers
|
| 3 |
+
opening towards the cup already standing on the next mat pushes that cup 1.5-3.4 cm sideways, half off its mat -- it
|
| 4 |
+
stays upright, so the damage is small but visible (a near miss that has to be noticed and undone before finishing).
|
| 5 |
+
|
| 6 |
+
Family: long-horizon self-disturbance ("state_restoration"): every placement is a later stage that can physically undo an
|
| 7 |
+
earlier one; the agent has to look back at all cups before finishing (within an attempt) or learn to let go without
|
| 8 |
+
pushing (across attempts).
|
| 9 |
+
|
| 10 |
+
v1 -> v2 (Sonnet 5.5 pilot np_lh_nudge_row, seeds 3000-3002, k=3, measured): v1 used round rings with a 0.8 cm
|
| 11 |
+
tolerance. Sonnet put the cups 0.8-2.2 cm too far forward (+x, away from the robot) in almost every attempt and could not
|
| 12 |
+
see it (the oblique agentview camera looks along x; a tall cup hides the ring behind it), so 5 of 7 attempts failed
|
| 13 |
+
without any nudge (one was a calibration attempt), and the one clear nudge (s3000) left the cup 0.83 cm off --
|
| 14 |
+
invisible. Its left-right errors were <= 0.7 cm, its releases in attempt 1 almost all at wrist yaw ~0 (fingers opening
|
| 15 |
+
left-right), and it learned yaw 45 for the last cup after the nudge. v2 therefore (1) replaces the rings by mats 9 cm long (forward-back, tolerance 3 cm: a 2 cm forward bias
|
| 16 |
+
passes) and 4.6 cm wide (left-right, tolerance 1.3 cm), (2) puts the two mats of a row edge to edge so that a yaw-0
|
| 17 |
+
release pushes the neighbour sideways, where the camera resolves it, off its mat onto the table, and (3) uses slimmer cups
|
| 18 |
+
(2 x 5 cm instead of 4 x 6 cm): the open finger reaches farther past them, so the push is 1.5-3.4 cm instead of 0.3-2.3.
|
| 19 |
+
Code and results of v1: lh_nudge_row.py.bak-20261014-v1, results/_old/lh_nudge_row_v1/.
|
| 20 |
+
|
| 21 |
+
Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
|
| 22 |
+
* four coloured mats (dark red, blue, green, ochre; flat, visual only), each 9.0 cm (forward-back) x 4.6 cm, in two rows
|
| 23 |
+
(far and near, 1.5 cm apart); block centre 53-59 cm in front of the robot base. Tight block (14 of every 20
|
| 24 |
+
consecutive seeds): the two mats of a row touch. Spaced block (6 of 20): they are 4-5 cm apart and no open finger
|
| 25 |
+
reaches the neighbour (the benign instances);
|
| 26 |
+
* four slim cups of the bright same colours (2.0 cm wide, 5.0 cm tall, open top, glazed base: friction 0.08-0.12,
|
| 27 |
+
20-32 g), standing in a line 17.5-19 cm from the block on the robot's side, or on its left or right side, in random
|
| 28 |
+
order and 9-10 cm apart.
|
| 29 |
+
|
| 30 |
+
Risk factor: the block's spacing (visible, instance level); there is no hidden physical variable (v1 measured that a
|
| 31 |
+
rubber-footed cup gets tipped over by a re-grasp next to it, and a fallen cup cannot be stood up again).
|
| 32 |
+
|
| 33 |
+
Disturbance (physics, no teleport): the gripper opens to 7.9 cm, i.e. each finger moves 3 cm out from a 2 cm cup; the
|
| 34 |
+
outer face of an open finger reaches 5.4 cm (tip) to 6.6 cm (upper part) from the grasp point; in a tight block the
|
| 35 |
+
neighbour's wall is 3.6 cm away (+- the placement errors). Measured: letting go with the fingers along the row (wrist yaw
|
| 36 |
+
0) pushes the neighbour 1.2-3.2 cm sideways, upright (18/18 trials: base friction 0.08 / 0.12 x grasp 0.8-2 cm below the
|
| 37 |
+
rim x put down 0.8 cm towards / on target / 0.8 cm away from it, each followed by three re-grasps); re-grasping a placed cup with the fingers towards the neighbour pushes it about 0.3 cm more. With
|
| 38 |
+
friction 0.18 or with 2.6 cm cups whose closed finger already presses the neighbour's rim, slim cups tipped over (4/18
|
| 39 |
+
and 6/18) -- hence the low friction and the 2 cm cups. A careful agent avoids the push by letting go with the fingers
|
| 40 |
+
opening forward-back (wrist yaw 90: the mats of the other row are 10.5 cm away) or diagonally, and repairs it by
|
| 41 |
+
re-centring the pushed cup (lifted 10 cm, carried back, let go the same careful way).
|
| 42 |
+
|
| 43 |
+
Success predicates (evaluated every other control step by a monitor, debounced over 0.5 s): each cup stands upright
|
| 44 |
+
(tilt <= 10 deg) on the table, not held, with its whole base on its own mat: centre within 3.0 cm (forward-back) and
|
| 45 |
+
1.3 cm (left-right) of the mat's centre. Success = all four at the end, gripper open and not touching any cup, scene
|
| 46 |
+
static. The monitor logs achieved / lost / restored per cup, cup_nudged (lost while not held, with displacement and
|
| 47 |
+
cause), cup_bumped (pushed by the robot but still on its mat) and cup_restored, for the server log only (F1 gives the
|
| 48 |
+
agent only success / failure).
|
| 49 |
+
|
| 50 |
+
Protocol: cross (reset to the same instance before every attempt), k = 3.
|
| 51 |
+
"""
|
| 52 |
+
import numpy as np
|
| 53 |
+
|
| 54 |
+
from .. import envs
|
| 55 |
+
from ..bddl import write_bddl
|
| 56 |
+
from ..objects import _fmt, _wrap, register_generated
|
| 57 |
+
from ..skills import Skills
|
| 58 |
+
from ..task_base import LFFTask, register_task
|
| 59 |
+
|
| 60 |
+
TZ = envs.TABLE_Z
|
| 61 |
+
COLOURS = ["red", "blue", "green", "yellow"]
|
| 62 |
+
CUPS = [f"cup_{c}_1" for c in COLOURS]
|
| 63 |
+
MATS = [f"mat_{c}_1" for c in COLOURS]
|
| 64 |
+
RGBA = {"red": (0.82, 0.16, 0.13, 1.0), "blue": (0.16, 0.36, 0.82, 1.0), "green": (0.16, 0.62, 0.26, 1.0),
|
| 65 |
+
"yellow": (0.92, 0.76, 0.12, 1.0)}
|
| 66 |
+
MAT_RGBA = {"red": (0.55, 0.13, 0.12, 1.0), "blue": (0.12, 0.22, 0.52, 1.0), "green": (0.10, 0.38, 0.16, 1.0),
|
| 67 |
+
"yellow": (0.62, 0.50, 0.08, 1.0)} # dark shades: crisp edges on the light table, bright cups stand out
|
| 68 |
+
INSIDE_RGBA = (0.93, 0.92, 0.88, 1.0) # glazed inside of the cups (seen from above)
|
| 69 |
+
|
| 70 |
+
# cup geometry (fixed; only mass and base friction change per instance, so no runtime geom edits / BVH refits)
|
| 71 |
+
CUP_R, CUP_H = 0.010, 0.050 # slim cups (2 x 5 cm): the open fingers reach far past them (v1: 4 x 6 cm)
|
| 72 |
+
COM_Z = -0.006 # centre of mass below the cup's mid-height (heavier base)
|
| 73 |
+
WALL_T, BASE_T = 0.0025, 0.003
|
| 74 |
+
NSEG = 12
|
| 75 |
+
CONTACT = 'solimp="0.95 0.99 0.001" solref="0.01 1"'
|
| 76 |
+
WALL_MU = 0.8
|
| 77 |
+
BASE_MU = (0.08, 0.12) # glazed base: a pushed cup slides; at 0.18 a slim cup pushed high up tipped (measured)
|
| 78 |
+
MASS = (0.020, 0.032)
|
| 79 |
+
|
| 80 |
+
# mats (targets) and block
|
| 81 |
+
TOL_X = 0.030 # forward-back: the cup centre may be 3 cm from the mat centre (mat 9 cm long) -- Sonnet's measured
|
| 82 |
+
# placement bias is 1-2.5 cm forward (v1 pilot), invisible to it in the oblique camera
|
| 83 |
+
TOL_Y = 0.013 # left-right: 1.3 cm (mat 4.6 cm wide); a finger-opening push (1.2-3.2 cm, measured) fails it
|
| 84 |
+
MAT_L, MAT_W = 2 * (CUP_R + TOL_X), 2 * (CUP_R + TOL_Y) # base completely on the mat <=> centre within the tolerances
|
| 85 |
+
ROW_GAP = 0.015 # gap between the far row and the near row of mats (x)
|
| 86 |
+
SPACED_GAP = (0.040, 0.050) # spaced block: gap between the two mats of a row (y); an open finger cannot reach
|
| 87 |
+
P_TIGHT = 0.70 # 14 of every 20 consecutive seeds: the two mats of a row touch
|
| 88 |
+
BLOCK_X = (-0.13, -0.07) # block centre in world x (53-59 cm in front of the robot base)
|
| 89 |
+
SUP_D = (0.175, 0.19) # supply line distance from the block centre
|
| 90 |
+
SUP_GAP = (0.090, 0.100)
|
| 91 |
+
|
| 92 |
+
# predicates / monitor
|
| 93 |
+
TILT_OK = np.radians(10.0)
|
| 94 |
+
ON_TABLE = 0.004
|
| 95 |
+
HYST = 0.002
|
| 96 |
+
DEBOUNCE = 10 # control steps (0.5 s)
|
| 97 |
+
BUMP_MIN = 0.003
|
| 98 |
+
|
| 99 |
+
# scripted motion (heights of the grasp point above the table)
|
| 100 |
+
Z_CARRY = 0.20 # Sonnet: lifts to ~20 cm before moving (lh2/lh3 pilots)
|
| 101 |
+
Z_LIFT = 0.15 # re-placing a cup that is already down: lift it this high (its base 11 cm up) before moving it
|
| 102 |
+
NAIVE_BIAS = (0.008, 0.022) # Sonnet's systematic forward placement error (v1 pilot: +0.8 ... +2.2 cm, per instance)
|
| 103 |
+
NAIVE_RAND = 0.006 # +- random placement error per axis (v1 pilot: left-right errors <= 0.7 cm)
|
| 104 |
+
NAIVE_FIX_RAND = 0.003 # after re-placing its own cup
|
| 105 |
+
FINGER_IN, FINGER_OUT, FINGER_HALF = 0.039, 0.066, 0.013 # open finger footprint (m from the grasp point / half width)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _wrap_h(a):
|
| 109 |
+
"""wrap to [-pi/2, pi/2) (the gripper is symmetric under 180 deg)"""
|
| 110 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def cup_xml(name, rgba):
|
| 114 |
+
"""open-top cup: 12 wall boxes (1 mm above the bottom) and an octagonal base of two square boxes (box-box contacts:
|
| 115 |
+
a light cylinder on the table creeps by itself in MuJoCo, measured 1.6 cm / 5 s). Visual: a smooth cylinder with the
|
| 116 |
+
glazed inside at the top. The compiled inertial is replaced per instance (mass), the base friction too."""
|
| 117 |
+
r, h = CUP_R, CUP_H
|
| 118 |
+
g = [f' <inertial pos="0 0 {COM_Z:.4f}" mass="0.055" diaginertia="2.6e-5 2.6e-5 1.6e-5" />']
|
| 119 |
+
s = r * np.sin(np.pi / NSEG) + 0.0006
|
| 120 |
+
rc = r * np.cos(np.pi / NSEG) - WALL_T / 2
|
| 121 |
+
for k in range(NSEG):
|
| 122 |
+
a = 2 * np.pi * k / NSEG
|
| 123 |
+
q = [np.cos(a / 2), 0, 0, np.sin(a / 2)]
|
| 124 |
+
g.append(f' <geom name="{name}_w{k}" type="box" size="{WALL_T / 2:.5f} {s:.5f} {(h - 0.001) / 2:.5f}" '
|
| 125 |
+
f'pos="{rc * np.cos(a):.5f} {rc * np.sin(a):.5f} 0.0005" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
|
| 126 |
+
f'friction="{WALL_MU} 0.005 0.0001" {CONTACT} group="0" />')
|
| 127 |
+
a0 = r * 0.70
|
| 128 |
+
for k, ang in enumerate((0.0, np.pi / 4)):
|
| 129 |
+
q = [np.cos(ang / 2), 0, 0, np.sin(ang / 2)]
|
| 130 |
+
g.append(f' <geom name="{name}_b{k}" type="box" size="{a0:.5f} {a0:.5f} {BASE_T / 2:.5f}" '
|
| 131 |
+
f'pos="0 0 {-h / 2 + BASE_T / 2:.5f}" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
|
| 132 |
+
f'friction="0.5 0.005 0.0001" {CONTACT} group="0" />')
|
| 133 |
+
g.append(f' <geom type="cylinder" size="{r:.5f} {h / 2:.5f}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" '
|
| 134 |
+
f'group="1" />')
|
| 135 |
+
g.append(f' <geom type="cylinder" size="{r - WALL_T:.5f} 0.0004" pos="0 0 {h / 2 - 0.0003:.5f}" '
|
| 136 |
+
f'rgba="{_fmt(INSIDE_RGBA)}" contype="0" conaffinity="0" group="1" />')
|
| 137 |
+
return _wrap(name, "\n".join(g), h / 2, r)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def mat_xml(name, rgba):
|
| 141 |
+
"""flat coloured mat (visual only), long side along body x"""
|
| 142 |
+
g = (f' <geom type="box" size="{MAT_L / 2:.5f} {MAT_W / 2:.5f} 0.0004" rgba="{_fmt(rgba)}" contype="0" '
|
| 143 |
+
f'conaffinity="0" group="1" />')
|
| 144 |
+
return _wrap(name, g, 0.0004, float(np.hypot(MAT_L, MAT_W) / 2))
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _fb(d):
|
| 148 |
+
return f"{100 * abs(d):.1f} cm {'forward' if d > 0 else 'back'}"
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _lr(d):
|
| 152 |
+
return f"{100 * abs(d):.1f} cm to the {'left' if d > 0 else 'right'}"
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class NudgeSkills(Skills):
|
| 156 |
+
"""Skills that feed the task's per-step monitor."""
|
| 157 |
+
|
| 158 |
+
def __init__(self, env, task, recorder=None):
|
| 159 |
+
super().__init__(env, recorder=recorder)
|
| 160 |
+
self.task = task
|
| 161 |
+
|
| 162 |
+
def _act(self, dpos, drot, grip):
|
| 163 |
+
super()._act(dpos, drot, grip)
|
| 164 |
+
self.task.monitor_step()
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@register_task
|
| 168 |
+
class NudgeRow(LFFTask):
|
| 169 |
+
name = "lh_nudge_row"
|
| 170 |
+
level = "L2"
|
| 171 |
+
category = "state_restoration"
|
| 172 |
+
capabilities = ("Perceive", "Plan", "Reason", "Restore")
|
| 173 |
+
protocol = "cross"
|
| 174 |
+
max_attempts = 3
|
| 175 |
+
# careful: ~10 commands per cup (40) + re-placing an imprecise cup or two (~15) + re-centring two pushed cups (~20)
|
| 176 |
+
# + looking / small corrections (~20), with some margin
|
| 177 |
+
agent_max_steps = 110
|
| 178 |
+
instruction = ("Stand each of the four small cups on the mat of the same colour. The four coloured mats lie on the "
|
| 179 |
+
"table in two rows of two. At the end every cup must stand upright with its whole base on its own "
|
| 180 |
+
"mat (not touching another mat or the table around it), and the gripper must be open and clear of "
|
| 181 |
+
"the cups.")
|
| 182 |
+
instruction_indirect = ("Set each little cup down on the coloured patch that matches it; the four patches form two "
|
| 183 |
+
"rows of two. When you are done every cup has to stand upright with its bottom completely "
|
| 184 |
+
"on its own patch, and the gripper must be open and away from the cups.")
|
| 185 |
+
agent_object_names = ["small cups (red, blue, green, yellow)",
|
| 186 |
+
"coloured mats (red, blue, green, yellow) in two rows of two"]
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------ scene
|
| 189 |
+
def make_bddl(self):
|
| 190 |
+
objs, fx = [], []
|
| 191 |
+
for i, (c, cup) in enumerate(zip(COLOURS, CUPS)):
|
| 192 |
+
cat = register_generated(f"LffLhnCup{c.capitalize()}", cup_xml(f"lff_lhn_cup_{c}", RGBA[c]))
|
| 193 |
+
objs.append((cup, cat, f"cup{i}_region", (-0.30 + 0.12 * i, 0.30, -0.29 + 0.12 * i, 0.31)))
|
| 194 |
+
for i, (c, mat) in enumerate(zip(COLOURS, MATS)):
|
| 195 |
+
cat = register_generated(f"LffLhnMat{c.capitalize()}", mat_xml(f"lff_lhn_mat_{c}", MAT_RGBA[c]), free=False)
|
| 196 |
+
fx.append((mat, cat, f"mat{i}_region", (-0.30 + 0.12 * i, -0.31, -0.29 + 0.12 * i, -0.30)))
|
| 197 |
+
return write_bddl(self.name, "Stand each cup on the mat of its colour", objs, fx)
|
| 198 |
+
|
| 199 |
+
def __init__(self, cam_res=None):
|
| 200 |
+
super().__init__(cam_res)
|
| 201 |
+
m = self.env.sim.model
|
| 202 |
+
self.mat_bid = {k: m.body_name2id(self.env.fixtures_dict[k].root_body) for k in MATS}
|
| 203 |
+
self.cgeoms = {c: envs.obj_geom_ids(self.env, c) for c in CUPS}
|
| 204 |
+
self.cbody = {c: int(m.geom_bodyid[self.cgeoms[c][0]]) for c in CUPS}
|
| 205 |
+
self.base_geoms = {c: [g for g in self.cgeoms[c] if (m.geom_id2name(g) or "").split("_")[-1] in ("b0", "b1")]
|
| 206 |
+
for c in CUPS}
|
| 207 |
+
self.finger_geoms, self.hand_geoms = [], []
|
| 208 |
+
for g in envs.robot_geom_ids(self.env):
|
| 209 |
+
n = m.geom_id2name(g) or ""
|
| 210 |
+
(self.finger_geoms if "finger" in n else self.hand_geoms).append(g)
|
| 211 |
+
# per-geom lookup tables for the substep contact check: cup index (-1 none), robot part (1 finger, 2 hand)
|
| 212 |
+
self.owner = np.full(m.ngeom, -1, int)
|
| 213 |
+
for i, c in enumerate(CUPS):
|
| 214 |
+
self.owner[self.cgeoms[c]] = i
|
| 215 |
+
self.part = np.zeros(m.ngeom, int)
|
| 216 |
+
self.part[self.finger_geoms] = 1
|
| 217 |
+
self.part[self.hand_geoms] = 2
|
| 218 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 219 |
+
# contacts are collected after every MuJoCo substep: an opening finger can flick a light cup within one control
|
| 220 |
+
# step (same technique as lh_fence; wrappers chain)
|
| 221 |
+
sim = self.env.sim
|
| 222 |
+
if not getattr(sim, "_lhn_wrapped", False):
|
| 223 |
+
orig = sim.step
|
| 224 |
+
|
| 225 |
+
def step(*a, **k):
|
| 226 |
+
orig(*a, **k)
|
| 227 |
+
t = getattr(sim, "_lhn_task", None)
|
| 228 |
+
if t is not None and t.mon is not None:
|
| 229 |
+
t._substep()
|
| 230 |
+
sim.step = step
|
| 231 |
+
sim._lhn_wrapped = True
|
| 232 |
+
sim._lhn_task = self
|
| 233 |
+
self.inst = None
|
| 234 |
+
self.mon = None
|
| 235 |
+
self.sk = None
|
| 236 |
+
|
| 237 |
+
def _substep(self):
|
| 238 |
+
d = self.env.sim.data
|
| 239 |
+
n = d.ncon
|
| 240 |
+
if not n:
|
| 241 |
+
return
|
| 242 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 243 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 244 |
+
o1, o2 = self.owner[g1], self.owner[g2]
|
| 245 |
+
for a, b, pa, pb in zip(g1, g2, o1, o2):
|
| 246 |
+
if pa < 0 and pb < 0:
|
| 247 |
+
continue
|
| 248 |
+
if pa >= 0 and pb >= 0:
|
| 249 |
+
if pa != pb:
|
| 250 |
+
self._sub_obj[int(pa)] = int(pb)
|
| 251 |
+
self._sub_obj[int(pb)] = int(pa)
|
| 252 |
+
continue
|
| 253 |
+
p, o = (pa, b) if pa >= 0 else (pb, a)
|
| 254 |
+
part = self.part[o]
|
| 255 |
+
if part:
|
| 256 |
+
prev = self._sub_rob.get(int(p), 0)
|
| 257 |
+
self._sub_rob[int(p)] = 1 if (part == 1 or prev == 1) else 2
|
| 258 |
+
|
| 259 |
+
# ------------------------------------------------------------ instances
|
| 260 |
+
def sample_instance(self, seed):
|
| 261 |
+
rng = np.random.default_rng(seed)
|
| 262 |
+
tight = bool((int(seed) * 7) % 20 < round(20 * P_TIGHT)) # balanced: 14 of every 20 consecutive seeds
|
| 263 |
+
gap_y = 0.0 if tight else float(rng.uniform(*SPACED_GAP))
|
| 264 |
+
py = MAT_W + gap_y # mat centre to mat centre within a row (left-right)
|
| 265 |
+
px = MAT_L + ROW_GAP # far row to near row (forward-back)
|
| 266 |
+
bx = float(rng.uniform(*BLOCK_X))
|
| 267 |
+
side = str(rng.choice(["front", "left", "right"]))
|
| 268 |
+
by = float(rng.uniform(-0.04, 0.04))
|
| 269 |
+
if side == "left":
|
| 270 |
+
by = float(rng.uniform(-0.08, -0.04))
|
| 271 |
+
elif side == "right":
|
| 272 |
+
by = float(rng.uniform(0.04, 0.08))
|
| 273 |
+
# mat positions: block slots (far-left, far-right, near-left, near-right), colours permuted
|
| 274 |
+
slots = {"far_left": [bx + px / 2, by + py / 2], "far_right": [bx + px / 2, by - py / 2],
|
| 275 |
+
"near_left": [bx - px / 2, by + py / 2], "near_right": [bx - px / 2, by - py / 2]}
|
| 276 |
+
names = list(slots)
|
| 277 |
+
perm = rng.permutation(4)
|
| 278 |
+
mats = {COLOURS[i]: slots[names[perm[i]]] for i in range(4)}
|
| 279 |
+
slot_of = {COLOURS[i]: names[perm[i]] for i in range(4)}
|
| 280 |
+
# supply line
|
| 281 |
+
d = float(rng.uniform(*SUP_D))
|
| 282 |
+
gap = float(rng.uniform(*SUP_GAP))
|
| 283 |
+
offs = (np.arange(4) - 1.5) * gap + float(rng.uniform(-0.02, 0.02))
|
| 284 |
+
if side == "front":
|
| 285 |
+
sup = [[bx - d + float(rng.uniform(-0.008, 0.008)), by + o] for o in offs]
|
| 286 |
+
else:
|
| 287 |
+
sgn = 1.0 if side == "left" else -1.0
|
| 288 |
+
sup = [[bx + o, by + sgn * (d - 0.02) + float(rng.uniform(-0.008, 0.008))] for o in offs]
|
| 289 |
+
order = rng.permutation(4)
|
| 290 |
+
start = {COLOURS[i]: [float(v) for v in sup[order[i]]] for i in range(4)}
|
| 291 |
+
mu = {c: float(rng.uniform(*BASE_MU)) for c in COLOURS}
|
| 292 |
+
mass = {c: float(rng.uniform(*MASS)) for c in COLOURS}
|
| 293 |
+
yaw0 = {c: float(rng.uniform(-np.pi, np.pi)) for c in COLOURS}
|
| 294 |
+
return dict(seed=int(seed), pitch_y=py, pitch_x=px, gap_y=gap_y, block=[bx, by], supply_side=side,
|
| 295 |
+
supply_d=d, supply_gap=gap, mats=mats, slot_of=slot_of, start=start, mu=mu, mass=mass, yaw0=yaw0,
|
| 296 |
+
tight=tight, block_kind="tight" if tight else "spaced",
|
| 297 |
+
naive_bias_x=float(rng.uniform(*NAIVE_BIAS)))
|
| 298 |
+
|
| 299 |
+
def apply_instance(self, inst):
|
| 300 |
+
self.inst = inst
|
| 301 |
+
m = self.env.sim.model
|
| 302 |
+
for c, cup in zip(COLOURS, CUPS):
|
| 303 |
+
b = self.cbody[cup]
|
| 304 |
+
M = inst["mass"][c]
|
| 305 |
+
m.body_mass[b] = M
|
| 306 |
+
# thin-walled cup (wall + base), approximately
|
| 307 |
+
m.body_inertia[b] = [M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12), M * (CUP_R ** 2 / 2 + CUP_H ** 2 / 12),
|
| 308 |
+
M * CUP_R ** 2 * 0.8]
|
| 309 |
+
for g in self.base_geoms[cup]:
|
| 310 |
+
m.geom_friction[g] = [inst["mu"][c], 0.005, 0.0001]
|
| 311 |
+
m.geom_priority[g] = 2
|
| 312 |
+
for c, mat in zip(COLOURS, MATS):
|
| 313 |
+
x, y = inst["mats"][c]
|
| 314 |
+
m.body_pos[self.mat_bid[mat]] = [x, y, TZ + 0.0005]
|
| 315 |
+
m.body_quat[self.mat_bid[mat]] = [1.0, 0.0, 0.0, 0.0]
|
| 316 |
+
self.env.sim.forward()
|
| 317 |
+
for c, cup in zip(COLOURS, CUPS):
|
| 318 |
+
envs.place_upright(self.env, cup, inst["start"][c], yaw=inst["yaw0"][c], clearance=0.0005)
|
| 319 |
+
|
| 320 |
+
def reset_instance(self, inst, recorder=None):
|
| 321 |
+
self.mon = None
|
| 322 |
+
self.env.reset()
|
| 323 |
+
self.apply_instance(inst)
|
| 324 |
+
self.env.sim.forward()
|
| 325 |
+
envs.settle(self.env, 15)
|
| 326 |
+
self.sk = NudgeSkills(self.env, self, recorder=recorder)
|
| 327 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 328 |
+
n = len(CUPS)
|
| 329 |
+
self.mon = dict(state=[False] * n, raw_since=[0] * n, ever=[False] * n, lost=[False] * n, events=[],
|
| 330 |
+
lost_cause=[None] * n,
|
| 331 |
+
anchor=[None] * n, last_robot=[None] * n, last_obj=[None] * n, nudged=[False] * n,
|
| 332 |
+
bump_ref=[None] * n, bump_step=[-1000] * n, n_steps=0)
|
| 333 |
+
return self.sk
|
| 334 |
+
|
| 335 |
+
# ------------------------------------------------------------ geometry / predicates
|
| 336 |
+
def pos(self, cup):
|
| 337 |
+
return envs.obj_pos(self.env, cup)
|
| 338 |
+
|
| 339 |
+
def tilt(self, cup):
|
| 340 |
+
return float(np.arccos(np.clip(envs.obj_upright_cos(self.env, cup), -1.0, 1.0)))
|
| 341 |
+
|
| 342 |
+
def held(self, cup):
|
| 343 |
+
return self.sk is not None and self.sk.holding(cup)
|
| 344 |
+
|
| 345 |
+
def mat_xy(self, i):
|
| 346 |
+
return np.asarray(self.inst["mats"][COLOURS[i]], float)
|
| 347 |
+
|
| 348 |
+
def offset(self, i):
|
| 349 |
+
return self.pos(CUPS[i])[:2] - self.mat_xy(i)
|
| 350 |
+
|
| 351 |
+
@staticmethod
|
| 352 |
+
def within(off, extra=0.0):
|
| 353 |
+
"""mat-frame offset (x forward-back, y left-right) inside the tolerances = the cup's whole base on its mat"""
|
| 354 |
+
return abs(float(off[0])) <= TOL_X + extra and abs(float(off[1])) <= TOL_Y + extra
|
| 355 |
+
|
| 356 |
+
def on_mat(self, i, extra=0.0):
|
| 357 |
+
cup = CUPS[i]
|
| 358 |
+
if self.tilt(cup) > TILT_OK + (np.radians(2.0) if extra else 0.0):
|
| 359 |
+
return False
|
| 360 |
+
if not self.within(self.offset(i), extra):
|
| 361 |
+
return False
|
| 362 |
+
if envs.obj_min_z(self.env, cup) > TZ + ON_TABLE:
|
| 363 |
+
return False
|
| 364 |
+
return not self.held(cup)
|
| 365 |
+
|
| 366 |
+
def stages(self):
|
| 367 |
+
return [self.on_mat(i) for i in range(len(CUPS))]
|
| 368 |
+
|
| 369 |
+
# ------------------------------------------------------------ monitor
|
| 370 |
+
def monitor_step(self):
|
| 371 |
+
mon = self.mon
|
| 372 |
+
if mon is None or self.sk is None:
|
| 373 |
+
return
|
| 374 |
+
mon["n_steps"] += 1
|
| 375 |
+
t = self.sk.n_steps
|
| 376 |
+
rob = dict(self._sub_rob)
|
| 377 |
+
obj = dict(self._sub_obj)
|
| 378 |
+
self._sub_rob, self._sub_obj = {}, {}
|
| 379 |
+
gstate = "open" if self.sk.grip < 0 else "closed"
|
| 380 |
+
for i, part in rob.items():
|
| 381 |
+
if not self.held(CUPS[i]):
|
| 382 |
+
mon["last_robot"][i] = ["finger" if part == 1 else "hand", int(t), gstate]
|
| 383 |
+
for i, j in obj.items():
|
| 384 |
+
mon["last_obj"][i] = [COLOURS[j] + (" (held)" if self.held(CUPS[j]) else ""), int(t)]
|
| 385 |
+
if mon["n_steps"] % 2:
|
| 386 |
+
return
|
| 387 |
+
for i in range(len(CUPS)):
|
| 388 |
+
cup = CUPS[i]
|
| 389 |
+
raw = self.on_mat(i, HYST if mon["state"][i] else 0.0)
|
| 390 |
+
# bumps inside the tolerance
|
| 391 |
+
if mon["state"][i] and raw and not self.held(cup):
|
| 392 |
+
lr = mon["last_robot"][i]
|
| 393 |
+
if lr is not None and t - lr[1] <= 2 and mon["bump_ref"][i] is None:
|
| 394 |
+
mon["bump_ref"][i] = [self.pos(cup)[:2].tolist(), int(t), 0.0]
|
| 395 |
+
ref = mon["bump_ref"][i]
|
| 396 |
+
if ref is not None:
|
| 397 |
+
ref[2] = max(ref[2], float(np.degrees(self.tilt(cup))))
|
| 398 |
+
if t - ref[1] > 40:
|
| 399 |
+
dpos = float(np.linalg.norm(self.pos(cup)[:2] - np.asarray(mon["anchor"][i] or ref[0])))
|
| 400 |
+
if (dpos >= BUMP_MIN or ref[2] >= 2.0) and t - mon["bump_step"][i] > 60:
|
| 401 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_bumped", step=int(ref[1]),
|
| 402 |
+
moved_cm=round(100 * dpos, 2), max_tilt_deg=round(ref[2], 1),
|
| 403 |
+
cause=self._cause(i, ref[1] + 1)))
|
| 404 |
+
mon["bump_step"][i] = int(t)
|
| 405 |
+
mon["bump_ref"][i] = None
|
| 406 |
+
if raw == mon["state"][i]:
|
| 407 |
+
mon["raw_since"][i] = 0
|
| 408 |
+
continue
|
| 409 |
+
mon["raw_since"][i] += 2
|
| 410 |
+
if mon["raw_since"][i] < DEBOUNCE:
|
| 411 |
+
continue
|
| 412 |
+
mon["state"][i] = raw
|
| 413 |
+
mon["raw_since"][i] = 0
|
| 414 |
+
t0 = int(t - DEBOUNCE + 1)
|
| 415 |
+
if raw:
|
| 416 |
+
restored = mon["lost"][i]
|
| 417 |
+
e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t0)
|
| 418 |
+
if restored:
|
| 419 |
+
e["after"] = mon["lost_cause"][i] # picked_up = the agent re-adjusted a cup it had placed itself
|
| 420 |
+
mon["events"].append(e)
|
| 421 |
+
if restored and mon["nudged"][i]:
|
| 422 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_restored", step=t0))
|
| 423 |
+
mon["nudged"][i] = False
|
| 424 |
+
mon["ever"][i] = True
|
| 425 |
+
mon["anchor"][i] = self.pos(cup)[:2].tolist()
|
| 426 |
+
mon["bump_ref"][i] = None
|
| 427 |
+
else:
|
| 428 |
+
mon["lost"][i] = True
|
| 429 |
+
cause = self._cause(i, t)
|
| 430 |
+
mon["lost_cause"][i] = cause
|
| 431 |
+
mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t0, cause=cause))
|
| 432 |
+
if cause != "picked_up":
|
| 433 |
+
a = mon["anchor"][i]
|
| 434 |
+
d = self.pos(cup)[:2] - np.asarray(a if a is not None else self.mat_xy(i))
|
| 435 |
+
off = self.offset(i)
|
| 436 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t0, cause=cause,
|
| 437 |
+
moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)],
|
| 438 |
+
offset_cm=round(100 * float(np.linalg.norm(off)), 2),
|
| 439 |
+
tilt_deg=round(float(np.degrees(self.tilt(cup))), 1)))
|
| 440 |
+
mon["nudged"][i] = True
|
| 441 |
+
|
| 442 |
+
def _cause(self, i, t, window=60):
|
| 443 |
+
if self.held(CUPS[i]):
|
| 444 |
+
return "picked_up"
|
| 445 |
+
lr, lo = self.mon["last_robot"][i], self.mon["last_obj"][i]
|
| 446 |
+
cands = []
|
| 447 |
+
if lr is not None and t - lr[1] <= window:
|
| 448 |
+
cands.append((lr[1], f"robot_{lr[0]}" + ("_opening" if lr[2] == "open" else "")))
|
| 449 |
+
if lo is not None and t - lo[1] <= window:
|
| 450 |
+
cands.append((lo[1] - 30, "cup:" + lo[0])) # prefer the robot when both touched it recently
|
| 451 |
+
return max(cands)[1] if cands else "other"
|
| 452 |
+
|
| 453 |
+
def _finalize_monitor(self, raw):
|
| 454 |
+
"""close the event log at finish: a stage the debounced monitor still holds (it uses a 2 mm hysteresis) but the
|
| 455 |
+
final judge does not is logged as lost now (final=True), and vice versa"""
|
| 456 |
+
mon = self.mon
|
| 457 |
+
if mon is None:
|
| 458 |
+
return
|
| 459 |
+
t = int(self.sk.n_steps)
|
| 460 |
+
for i in range(len(CUPS)):
|
| 461 |
+
if raw[i] == mon["state"][i]:
|
| 462 |
+
continue
|
| 463 |
+
mon["state"][i] = raw[i]
|
| 464 |
+
if raw[i]:
|
| 465 |
+
restored = mon["lost"][i]
|
| 466 |
+
e = dict(stage=COLOURS[i], event="restored" if restored else "achieved", step=t, final=True)
|
| 467 |
+
if restored:
|
| 468 |
+
e["after"] = mon["lost_cause"][i]
|
| 469 |
+
mon["events"].append(e)
|
| 470 |
+
mon["ever"][i] = True
|
| 471 |
+
continue
|
| 472 |
+
mon["lost"][i] = True
|
| 473 |
+
cause = self._cause(i, t, window=10 ** 6) # the last contact may be long ago (slow creep across the line)
|
| 474 |
+
mon["lost_cause"][i] = cause
|
| 475 |
+
mon["events"].append(dict(stage=COLOURS[i], event="lost", step=t, cause=cause, final=True))
|
| 476 |
+
if cause != "picked_up":
|
| 477 |
+
a = mon["anchor"][i]
|
| 478 |
+
d = self.pos(CUPS[i])[:2] - np.asarray(a if a is not None else self.mat_xy(i))
|
| 479 |
+
mon["events"].append(dict(cup=COLOURS[i], event="cup_nudged", step=t, cause=cause, final=True,
|
| 480 |
+
moved_cm=[round(100 * float(d[0]), 2), round(100 * float(d[1]), 2)],
|
| 481 |
+
offset_cm=round(100 * float(np.linalg.norm(self.offset(i))), 2),
|
| 482 |
+
tilt_deg=round(float(np.degrees(self.tilt(CUPS[i]))), 1)))
|
| 483 |
+
mon["nudged"][i] = True
|
| 484 |
+
|
| 485 |
+
# ------------------------------------------------------------ outcome
|
| 486 |
+
def _touching(self):
|
| 487 |
+
d = self.env.sim.data
|
| 488 |
+
rob = set(self.finger_geoms) | set(self.hand_geoms)
|
| 489 |
+
for j in range(d.ncon):
|
| 490 |
+
c = d.contact[j]
|
| 491 |
+
if (self.owner[c.geom1] >= 0 and c.geom2 in rob) or (self.owner[c.geom2] >= 0 and c.geom1 in rob):
|
| 492 |
+
return True
|
| 493 |
+
return False
|
| 494 |
+
|
| 495 |
+
def outcome(self, inst):
|
| 496 |
+
sk = self.sk
|
| 497 |
+
sk.hold(10)
|
| 498 |
+
p0 = {c: self.pos(c) for c in CUPS}
|
| 499 |
+
touching = False
|
| 500 |
+
for _ in range(20):
|
| 501 |
+
sk.hold(1)
|
| 502 |
+
touching = touching or self._touching()
|
| 503 |
+
moved = max(float(np.linalg.norm(self.pos(c) - p0[c])) for c in CUPS)
|
| 504 |
+
static = moved < 0.003
|
| 505 |
+
raw = self.stages()
|
| 506 |
+
self._finalize_monitor(raw)
|
| 507 |
+
held = [COLOURS[i] for i, c in enumerate(CUPS) if self.held(c)]
|
| 508 |
+
mon = self.mon
|
| 509 |
+
ev = list(mon["events"]) if mon else []
|
| 510 |
+
n_reg = sum(e.get("event") == "lost" and e.get("cause") != "picked_up" for e in ev)
|
| 511 |
+
n_lost = sum(e.get("event") == "lost" for e in ev)
|
| 512 |
+
n_res = sum(e.get("event") == "restored" and e.get("after") != "picked_up" for e in ev)
|
| 513 |
+
nudges = [e for e in ev if e.get("event") == "cup_nudged"]
|
| 514 |
+
bumps = [e for e in ev if e.get("event") == "cup_bumped"]
|
| 515 |
+
success = bool(all(raw) and static and not held and not touching)
|
| 516 |
+
ever = mon["ever"] if mon else [False] * len(CUPS)
|
| 517 |
+
tilted = [i for i in range(len(CUPS)) if self.tilt(CUPS[i]) > TILT_OK]
|
| 518 |
+
lost_final = [i for i in range(len(CUPS)) if not raw[i] and ever[i]]
|
| 519 |
+
never = [i for i in range(len(CUPS)) if not raw[i] and not ever[i]]
|
| 520 |
+
if success:
|
| 521 |
+
failure = "none"
|
| 522 |
+
elif held:
|
| 523 |
+
failure = "held"
|
| 524 |
+
elif touching:
|
| 525 |
+
failure = "touching"
|
| 526 |
+
elif tilted:
|
| 527 |
+
failure = "tipped"
|
| 528 |
+
elif lost_final:
|
| 529 |
+
failure = "nudged_out" if any(mon["nudged"][i] for i in lost_final) else "regressed"
|
| 530 |
+
elif never:
|
| 531 |
+
failure = "not_on_mat"
|
| 532 |
+
else:
|
| 533 |
+
failure = "not_static"
|
| 534 |
+
parts = []
|
| 535 |
+
if success:
|
| 536 |
+
parts.append("Every cup stands upright on the mat of its colour.")
|
| 537 |
+
for i in range(len(CUPS)):
|
| 538 |
+
if raw[i]:
|
| 539 |
+
continue
|
| 540 |
+
c, cup = COLOURS[i], CUPS[i]
|
| 541 |
+
if c in held:
|
| 542 |
+
parts.append(f"The {c} cup is still held by the gripper.")
|
| 543 |
+
continue
|
| 544 |
+
off = self.offset(i)
|
| 545 |
+
tl = np.degrees(self.tilt(cup))
|
| 546 |
+
where = f"{_fb(off[0])} and {_lr(off[1])} of the {c} mat's centre"
|
| 547 |
+
if tl > np.degrees(TILT_OK):
|
| 548 |
+
txt = (f"The {c} cup has fallen over" if tl > 45 else f"The {c} cup leans {tl:.0f} degrees") + f", {where}."
|
| 549 |
+
elif float(np.linalg.norm(off)) > 0.08:
|
| 550 |
+
txt = f"The {c} cup is not on the {c} mat (its centre is {100 * float(np.linalg.norm(off)):.0f} cm away)."
|
| 551 |
+
else:
|
| 552 |
+
over = []
|
| 553 |
+
if abs(off[1]) > TOL_Y:
|
| 554 |
+
over.append(f"{100 * (abs(off[1]) - TOL_Y):.1f} cm over the mat's {'left' if off[1] > 0 else 'right'} "
|
| 555 |
+
f"edge")
|
| 556 |
+
if abs(off[0]) > TOL_X:
|
| 557 |
+
over.append(f"{100 * (abs(off[0]) - TOL_X):.1f} cm over its {'far' if off[0] > 0 else 'near'} end")
|
| 558 |
+
txt = f"The {c} cup stands {where}; its base sticks out " + " and ".join(over) + "."
|
| 559 |
+
if ever[i]:
|
| 560 |
+
lost = [e for e in ev if e.get("stage") == c and e.get("event") == "lost"]
|
| 561 |
+
why = lost[-1].get("cause", "other") if lost else "other"
|
| 562 |
+
txt += {"robot_finger_opening": " It had stood on its mat; a finger pushed it when the gripper opened "
|
| 563 |
+
"next to it.",
|
| 564 |
+
"robot_finger": " It had stood on its mat; a finger pushed it.",
|
| 565 |
+
"robot_hand": " It had stood on its mat; the hand pushed it.",
|
| 566 |
+
}.get(why, " It had stood on its mat earlier and was pushed by another cup."
|
| 567 |
+
if why.startswith("cup:") else " It had stood on its mat earlier.")
|
| 568 |
+
parts.append(txt)
|
| 569 |
+
if not success and all(raw):
|
| 570 |
+
if touching:
|
| 571 |
+
parts.append("The gripper is still touching a cup.")
|
| 572 |
+
elif not static:
|
| 573 |
+
parts.append("Something was still moving.")
|
| 574 |
+
if nudges:
|
| 575 |
+
parts.append(f"During the attempt cups that stood on their mats were pushed off {len(nudges)} time(s); "
|
| 576 |
+
f"{n_res} time(s) a cup was put back.")
|
| 577 |
+
trap = bool(nudges)
|
| 578 |
+
return dict(success=success, stages={COLOURS[i]: bool(raw[i]) for i in range(len(CUPS))}, events=ev,
|
| 579 |
+
n_regressions=int(n_reg), n_lost=int(n_lost), n_restored=int(n_res), n_nudged=len(nudges),
|
| 580 |
+
n_bumped=len(bumps), trap_fired=trap, recovered_in_attempt=bool(trap and success),
|
| 581 |
+
nudged_cups=sorted({e["cup"] for e in nudges}), failure=failure, held=held,
|
| 582 |
+
touching=bool(touching), static=bool(static),
|
| 583 |
+
offsets_cm={COLOURS[i]: [round(100 * float(v), 2) for v in self.offset(i)] for i in range(4)},
|
| 584 |
+
tilts_deg={COLOURS[i]: round(float(np.degrees(self.tilt(CUPS[i]))), 1) for i in range(4)},
|
| 585 |
+
tight=bool(inst["tight"]), detail=" ".join(parts))
|
| 586 |
+
|
| 587 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 588 |
+
def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
|
| 589 |
+
return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 590 |
+
|
| 591 |
+
def _lift_to(self, z, speed=0.15):
|
| 592 |
+
cur = self.sk.eef_pos()
|
| 593 |
+
if cur[2] < TZ + z - 0.005:
|
| 594 |
+
self._go([cur[0], cur[1], TZ + z], speed=speed)
|
| 595 |
+
|
| 596 |
+
def finger_clear(self, q, yaw, ignore=()):
|
| 597 |
+
"""smallest distance (m) between the open fingers at grasp point q (xy) with gripper yaw `yaw` and the wall of
|
| 598 |
+
any standing cup other than `ignore`; finger axis (-sin yaw, cos yaw)"""
|
| 599 |
+
a = np.array([-np.sin(yaw), np.cos(yaw)])
|
| 600 |
+
b = np.array([a[1], -a[0]])
|
| 601 |
+
best = 1.0
|
| 602 |
+
for cup in CUPS:
|
| 603 |
+
if cup in ignore or self.held(cup):
|
| 604 |
+
continue
|
| 605 |
+
rel = self.pos(cup)[:2] - np.asarray(q, float)
|
| 606 |
+
for s in (1.0, -1.0):
|
| 607 |
+
u = s * float(rel @ a)
|
| 608 |
+
v = float(rel @ b)
|
| 609 |
+
du = max(FINGER_IN - u, 0.0, u - FINGER_OUT)
|
| 610 |
+
dv = max(abs(v) - FINGER_HALF, 0.0)
|
| 611 |
+
best = min(best, float(np.hypot(du, dv)) - CUP_R)
|
| 612 |
+
return best
|
| 613 |
+
|
| 614 |
+
def safe_yaw(self, q, ignore=(), prefer=0.0):
|
| 615 |
+
"""the gripper yaw (0, 90, +-45 deg) whose open fingers stay farthest from the other cups at q"""
|
| 616 |
+
cands = [0.0, np.pi / 2, np.pi / 4, -np.pi / 4]
|
| 617 |
+
sc = [(round(min(self.finger_clear(q, y, ignore), 0.02), 3), -abs(_wrap_h(y - prefer)), y) for y in cands]
|
| 618 |
+
return max(sc)[2]
|
| 619 |
+
|
| 620 |
+
def grasp_cup(self, cup, yaw, depth, z_carry=Z_CARRY, v=0.2, err=None, lift=None):
|
| 621 |
+
"""open, go over the cup at transit height, straight down, close, lift. Returns True if held."""
|
| 622 |
+
sk = self.sk
|
| 623 |
+
p = self.pos(cup)
|
| 624 |
+
q = p[:2] + (np.asarray(err, float) if err is not None else 0.0)
|
| 625 |
+
zg = envs.obj_max_z(self.env, cup) - depth
|
| 626 |
+
sk.set_gripper(False, steps=8)
|
| 627 |
+
self._lift_to(z_carry)
|
| 628 |
+
self._go([q[0], q[1], max(sk.eef_pos()[2], TZ + z_carry)], yaw=yaw, speed=v)
|
| 629 |
+
self._go([q[0], q[1], zg + 0.015], speed=0.10)
|
| 630 |
+
self._go([q[0], q[1], zg], speed=0.04, tol=0.003, max_steps=150)
|
| 631 |
+
sk.set_gripper(True, steps=15)
|
| 632 |
+
cur = sk.eef_pos()
|
| 633 |
+
self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.12)
|
| 634 |
+
sk.hold(5)
|
| 635 |
+
if not self.held(cup):
|
| 636 |
+
sk.set_gripper(False, steps=8)
|
| 637 |
+
return False
|
| 638 |
+
return True
|
| 639 |
+
|
| 640 |
+
def put_cup(self, cup, xy, yaw, z_carry=Z_CARRY, v=0.2, lift=None):
|
| 641 |
+
"""carry the held cup so that the cup (not the grasp point) is over xy, rotate to `yaw`, straight down until its
|
| 642 |
+
base is 3 mm above the table, let go, lift"""
|
| 643 |
+
sk = self.sk
|
| 644 |
+
rel = self.pos(cup)[:2] - sk.eef_pos()[:2]
|
| 645 |
+
q = np.asarray(xy, float) - rel
|
| 646 |
+
cur = sk.eef_pos()
|
| 647 |
+
self._go([q[0], q[1], max(cur[2], TZ + z_carry)], yaw=yaw, speed=v)
|
| 648 |
+
sk.hold(5)
|
| 649 |
+
rel = self.pos(cup)[:2] - sk.eef_pos()[:2] # the cup can shift in the fingers while the wrist turns
|
| 650 |
+
q = np.asarray(xy, float) - rel
|
| 651 |
+
dz = sk.eef_pos()[2] - envs.obj_min_z(self.env, cup)
|
| 652 |
+
zr = TZ + dz + 0.003
|
| 653 |
+
self._go([q[0], q[1], zr + 0.015], speed=0.10)
|
| 654 |
+
self._go([q[0], q[1], zr], speed=0.03, tol=0.003, max_steps=150)
|
| 655 |
+
sk.set_gripper(False, steps=12)
|
| 656 |
+
cur = sk.eef_pos()
|
| 657 |
+
self._go([cur[0], cur[1], TZ + (z_carry if lift is None else lift)], speed=0.15)
|
| 658 |
+
sk.hold(3)
|
| 659 |
+
|
| 660 |
+
def mat_order(self, mode="far_first"):
|
| 661 |
+
"""colour indices in placement order. far_first (Sonnet): the block row farthest from the supply first, then
|
| 662 |
+
the other; within a row from the left (robot's view)"""
|
| 663 |
+
sup = np.mean([self.inst["start"][c] for c in COLOURS], axis=0)
|
| 664 |
+
blk = np.asarray(self.inst["block"], float)
|
| 665 |
+
u = blk - sup
|
| 666 |
+
u = u / max(np.linalg.norm(u), 1e-9)
|
| 667 |
+
idx = list(range(4))
|
| 668 |
+
far = sorted(idx, key=lambda i: -float((self.mat_xy(i) - blk) @ u))
|
| 669 |
+
rows = [far[:2], far[2:]]
|
| 670 |
+
if mode == "near_first":
|
| 671 |
+
rows = rows[::-1]
|
| 672 |
+
out = []
|
| 673 |
+
for row in rows:
|
| 674 |
+
out += sorted(row, key=lambda i: (-self.mat_xy(i)[1], self.mat_xy(i)[0])) # left first
|
| 675 |
+
return out
|
| 676 |
+
|
| 677 |
+
@staticmethod
|
| 678 |
+
def looks_off(off, bias):
|
| 679 |
+
"""a (biased) observer's verdict: the cup looks off its mat centre by more than 0.8 cm in some direction"""
|
| 680 |
+
p = np.asarray(off, float) - np.asarray(bias, float)
|
| 681 |
+
return abs(p[0]) > 0.008 or abs(p[1]) > 0.008
|
| 682 |
+
|
| 683 |
+
def place_one(self, i, yaw_rule, depth, rng, bias=(0.0, 0.0), rand=0.0, fix_rand=0.0, check=True, z_carry=Z_CARRY,
|
| 684 |
+
v=0.2):
|
| 685 |
+
"""one stage: pick cup i from wherever it is and put it on its mat; aims at mat + bias (+- rand per axis); then
|
| 686 |
+
looks at this cup only (with the same bias) and re-places it if it looks off"""
|
| 687 |
+
cup = CUPS[i]
|
| 688 |
+
bias = np.asarray(bias, float)
|
| 689 |
+
for _ in range(2):
|
| 690 |
+
gy = yaw_rule(i, "grasp")
|
| 691 |
+
gerr = rng.uniform(-0.003, 0.003, 2) if rand else None
|
| 692 |
+
if self.grasp_cup(cup, gy, depth, z_carry=z_carry, v=v, err=gerr):
|
| 693 |
+
break
|
| 694 |
+
else:
|
| 695 |
+
return
|
| 696 |
+
e = rng.uniform(-rand, rand, 2) if rand else np.zeros(2)
|
| 697 |
+
self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=z_carry, v=v)
|
| 698 |
+
if not check:
|
| 699 |
+
return
|
| 700 |
+
for _ in range(2):
|
| 701 |
+
if not self.looks_off(self.offset(i), bias) and self.tilt(cup) < TILT_OK:
|
| 702 |
+
return
|
| 703 |
+
ry = yaw_rule(i, "grasp")
|
| 704 |
+
if not self.grasp_cup(cup, ry, depth, z_carry=Z_LIFT, v=0.1, lift=Z_LIFT):
|
| 705 |
+
return
|
| 706 |
+
e = rng.uniform(-fix_rand, fix_rand, 2) if fix_rand else np.zeros(2)
|
| 707 |
+
self.put_cup(cup, self.mat_xy(i) + bias + e, yaw_rule(i, "release"), z_carry=Z_LIFT, v=0.1, lift=z_carry)
|
| 708 |
+
|
| 709 |
+
def repair(self, rounds=4, depth=0.020, bias=(0.0, 0.0)):
|
| 710 |
+
"""look at every cup (with the observer's bias); re-centre each one that looks off: grasp and let go with the
|
| 711 |
+
fingers opening where no other cup stands. Returns the number of cups moved."""
|
| 712 |
+
bias = np.asarray(bias, float)
|
| 713 |
+
moved = 0
|
| 714 |
+
tries = {}
|
| 715 |
+
for _ in range(rounds * 4):
|
| 716 |
+
bad = [i for i in range(4) if (self.looks_off(self.offset(i), bias) or self.held(CUPS[i]))
|
| 717 |
+
and self.tilt(CUPS[i]) < np.radians(30) and tries.get(i, 0) < rounds]
|
| 718 |
+
if not bad:
|
| 719 |
+
break
|
| 720 |
+
i = min(bad, key=lambda j: float(np.linalg.norm(self.pos(CUPS[j])[:2] - self.sk.eef_pos()[:2])))
|
| 721 |
+
tries[i] = tries.get(i, 0) + 1
|
| 722 |
+
cup = CUPS[i]
|
| 723 |
+
gy = self.safe_yaw(self.pos(cup)[:2], ignore=(cup,), prefer=self.sk.yaw)
|
| 724 |
+
# lift the cup clear of its neighbours before moving it: carried at 10 cm its base clips their rims and
|
| 725 |
+
# tips them (v1, measured, 4/20 adaptive runs before this was raised)
|
| 726 |
+
if not self.grasp_cup(cup, gy, depth, z_carry=Z_LIFT, v=0.15, lift=Z_LIFT):
|
| 727 |
+
continue
|
| 728 |
+
moved += 1
|
| 729 |
+
target = self.mat_xy(i) + bias
|
| 730 |
+
ry = self.safe_yaw(target, ignore=(cup,), prefer=self.sk.yaw)
|
| 731 |
+
self.put_cup(cup, target, ry, z_carry=Z_LIFT, v=0.1, lift=Z_CARRY)
|
| 732 |
+
return moved
|
| 733 |
+
|
| 734 |
+
def execute(self, inst, params):
|
| 735 |
+
rng = np.random.default_rng(params.get("noise_seed", 0))
|
| 736 |
+
depth = params.get("depth", 0.020)
|
| 737 |
+
order = self.mat_order(params.get("order", "far_first"))
|
| 738 |
+
mode = params["yaw"] # "fixed" (one wrist yaw for everything) or "safe" (fingers away from placed cups)
|
| 739 |
+
y0 = float(params.get("yaw0", 0.0))
|
| 740 |
+
bias = (float(params.get("bias_x", 0.0)), 0.0)
|
| 741 |
+
|
| 742 |
+
def yaw_rule(i, what):
|
| 743 |
+
if mode == "fixed":
|
| 744 |
+
return y0
|
| 745 |
+
q = self.pos(CUPS[i])[:2] if what == "grasp" else self.mat_xy(i) + np.asarray(bias)
|
| 746 |
+
return self.safe_yaw(q, ignore=(CUPS[i],), prefer=y0)
|
| 747 |
+
|
| 748 |
+
rand = float(params.get("rand", 0.0))
|
| 749 |
+
for i in order:
|
| 750 |
+
self.place_one(i, yaw_rule, depth, rng, bias=bias, rand=rand, fix_rand=float(params.get("fix_rand", 0.0)),
|
| 751 |
+
check=params.get("self_check", True), z_carry=params.get("z_carry", Z_CARRY),
|
| 752 |
+
v=params.get("v", 0.2))
|
| 753 |
+
if params.get("check"):
|
| 754 |
+
self.repair(bias=bias)
|
| 755 |
+
self._lift_to(0.20)
|
| 756 |
+
self.sk.hold(10)
|
| 757 |
+
|
| 758 |
+
# naive = Sonnet 5.5's habits measured in the v1 pilot (np_lh_nudge_row): wrist yaw 0 for every grasp and release in
|
| 759 |
+
# attempt 1, the row farthest from the supply first, lift to 14-25 cm and carry straight, vertical descents,
|
| 760 |
+
# placement 0.8-2.2 cm too far forward (per instance, invisible to it) +- 0.6 cm, looks at the cup it just placed and
|
| 761 |
+
# re-places it if it looks off, no look back at the others before finishing
|
| 762 |
+
NAIVE = dict(yaw="fixed", yaw0=0.0, order="far_first", self_check=True, check=False, rand=NAIVE_RAND,
|
| 763 |
+
fix_rand=NAIVE_FIX_RAND)
|
| 764 |
+
CAREFUL = dict(yaw="safe", yaw0=0.0, order="far_first", self_check=True, check=True, rand=0.0, bias_x=0.0)
|
| 765 |
+
|
| 766 |
+
def default_params(self, inst):
|
| 767 |
+
return dict(self.NAIVE, noise_seed=int(inst["seed"]) * 13, bias_x=float(inst["naive_bias_x"]),
|
| 768 |
+
depth=0.008 + 0.012 * ((int(inst["seed"]) * 7) % 11) / 10) # 0.8-2.0 cm below the rim (pilot: ~1 cm)
|
| 769 |
+
|
| 770 |
+
def oracle_params(self, inst):
|
| 771 |
+
return dict(self.CAREFUL)
|
| 772 |
+
|
| 773 |
+
def adapt_params(self, inst, history):
|
| 774 |
+
"""from attempt 2: let go with the fingers opening away from the placed cups (same imprecision and bias), and
|
| 775 |
+
look at every cup before finishing"""
|
| 776 |
+
return dict(self.default_params(inst), yaw="safe", check=True)
|
| 777 |
+
|
| 778 |
+
def blind_params(self, inst, attempt, rng):
|
| 779 |
+
"""the naive behaviour with random variation, no history, no final look"""
|
| 780 |
+
return dict(self.default_params(inst), noise_seed=int(rng.integers(1 << 30)),
|
| 781 |
+
yaw0=float(rng.choice([0.0, np.pi / 2])), order=str(rng.choice(["far_first", "near_first"])),
|
| 782 |
+
z_carry=float(rng.uniform(0.15, 0.22)), v=float(rng.uniform(0.1, 0.3)),
|
| 783 |
+
depth=float(rng.uniform(0.008, 0.025)), bias_x=float(rng.uniform(*NAIVE_BIAS)))
|
| 784 |
+
|
| 785 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 786 |
+
k = k or self.max_attempts
|
| 787 |
+
rng = np.random.default_rng(seed)
|
| 788 |
+
history = []
|
| 789 |
+
single = ("oracle", "naive", "oracle_noise", "naive_yaw90", "naive_check", "careful_bias2", "naive_bias2")
|
| 790 |
+
for a in range(k):
|
| 791 |
+
self.reset_instance(inst)
|
| 792 |
+
if kind == "oracle":
|
| 793 |
+
params = self.oracle_params(inst)
|
| 794 |
+
elif kind == "naive":
|
| 795 |
+
params = self.default_params(inst)
|
| 796 |
+
elif kind == "adaptive": # attempt 1: naive + a final look at every cup (repairs); then careful releases
|
| 797 |
+
params = dict(self.default_params(inst), check=True) if a == 0 else self.adapt_params(inst, history)
|
| 798 |
+
elif kind == "blind":
|
| 799 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 800 |
+
elif kind == "switch": # control: cross-attempt learning only (careful releases from attempt 2), no final look
|
| 801 |
+
params = self.default_params(inst) if a == 0 else dict(self.default_params(inst), yaw="safe")
|
| 802 |
+
elif kind == "oracle_noise": # robustness: careful with +-5 mm placement / grasp noise
|
| 803 |
+
params = dict(self.CAREFUL, rand=0.005, noise_seed=int(seed) * 7 + a)
|
| 804 |
+
elif kind == "naive_yaw90": # control: Sonnet-like but the wrist turned 90 deg for everything
|
| 805 |
+
params = dict(self.default_params(inst), yaw0=np.pi / 2)
|
| 806 |
+
elif kind == "naive_check": # control: naive + final look (= adaptive's first attempt)
|
| 807 |
+
params = dict(self.default_params(inst), check=True)
|
| 808 |
+
elif kind == "careful_bias2": # control: careful releases (nothing nudged) but placed 2 cm too far forward
|
| 809 |
+
params = dict(self.default_params(inst), yaw="safe", bias_x=0.020)
|
| 810 |
+
elif kind == "naive_bias2": # control: naive with a fixed +2 cm forward bias
|
| 811 |
+
params = dict(self.default_params(inst), bias_x=0.020)
|
| 812 |
+
else:
|
| 813 |
+
raise ValueError(kind)
|
| 814 |
+
self.execute(inst, params)
|
| 815 |
+
out = self.outcome(inst)
|
| 816 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 817 |
+
if on_attempt:
|
| 818 |
+
on_attempt(a, params, out)
|
| 819 |
+
if out["success"] or kind in single:
|
| 820 |
+
break
|
| 821 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_gpt/lff/source_closure/lffbench/tasks/lh_shelf_droop.py
ADDED
|
@@ -0,0 +1,1009 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/breakfast-v2-20261103-breakfast_v2_20261103_gpt/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_sonnet/lff/source_closure/client/lffbench_client/__init__.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LFF-Bench Python client: the three agent tools of one episode, for any robot harness framework (docs/18 §6.3).
|
| 2 |
+
|
| 3 |
+
Only the standard library; it never imports the simulator. It talks to the episode's tool gateway
|
| 4 |
+
(scripts/tool_gateway.py), which runs next to the robot server and owns the per-attempt tool-call budget, the jailed
|
| 5 |
+
shell and the workspace images. A framework registers the three tools with the schemas from tool_specs() and calls
|
| 6 |
+
them through a Session:
|
| 7 |
+
|
| 8 |
+
from lffbench_client import Session
|
| 9 |
+
s = Session.from_env() # LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN (set by the launcher)
|
| 10 |
+
first = s.first_message() # README + first status, as every harness gets it
|
| 11 |
+
tools = s.tool_specs("openai_responses") # or raw / mcp / anthropic / openai_chat
|
| 12 |
+
r = s.robot("move_eef x=0.5 y=0.0 z=0.2") # -> ToolResult
|
| 13 |
+
r.json() # the robot server's reply as a dict
|
| 14 |
+
s.view_images(["obs/s001_agentview.jpg"]).images # [(mime, bytes)]
|
| 15 |
+
|
| 16 |
+
A ToolResult's content is the list a model should see, in MCP form (text items and base64 image items); finished
|
| 17 |
+
says that the episode is over (stop calling tools). Nothing here can reset the scene or read the verdict: the only
|
| 18 |
+
feedback is what the robot server writes into the tool results.
|
| 19 |
+
"""
|
| 20 |
+
import base64
|
| 21 |
+
import dataclasses
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import urllib.error
|
| 25 |
+
import urllib.parse
|
| 26 |
+
import urllib.request
|
| 27 |
+
|
| 28 |
+
__all__ = ["Session", "ToolResult", "GatewayError", "STYLES"]
|
| 29 |
+
__version__ = "0.1.0"
|
| 30 |
+
|
| 31 |
+
STYLES = ("raw", "mcp", "anthropic", "openai_responses", "openai_chat")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class GatewayError(RuntimeError):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclasses.dataclass
|
| 39 |
+
class ToolResult:
|
| 40 |
+
content: list # [{"type": "text", "text"} | {"type": "image", "mimeType", "data" (base64)}]
|
| 41 |
+
is_error: bool
|
| 42 |
+
finished: bool # the episode is over: stop calling tools and report
|
| 43 |
+
calls_in_attempt: int # tool calls used in the current attempt (after an automatic finish: 0)
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def text(self):
|
| 47 |
+
"""All text items, joined by newlines."""
|
| 48 |
+
return "\n".join(c["text"] for c in self.content if c.get("type") == "text")
|
| 49 |
+
|
| 50 |
+
def json(self):
|
| 51 |
+
"""The first text item parsed as JSON (robot / shell / view_images replies are JSON objects)."""
|
| 52 |
+
for c in self.content:
|
| 53 |
+
if c.get("type") == "text":
|
| 54 |
+
return json.loads(c["text"])
|
| 55 |
+
raise ValueError("no text item")
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def images(self):
|
| 59 |
+
"""[(mime type, bytes)] of the image items."""
|
| 60 |
+
return [(c["mimeType"], base64.b64decode(c["data"])) for c in self.content if c.get("type") == "image"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class Session:
|
| 64 |
+
"""One episode's tools through its gateway. face labels this access path in the gateway transcript."""
|
| 65 |
+
|
| 66 |
+
def __init__(self, url, token, face="sdk", timeout_s=900.0):
|
| 67 |
+
self.url, self.token, self.face, self.timeout_s = url.rstrip("/"), token, face, timeout_s
|
| 68 |
+
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never via a proxy
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def from_env(cls, face="sdk", **kw):
|
| 72 |
+
url, token = os.environ.get("LFF_GATEWAY_URL"), os.environ.get("LFF_GATEWAY_TOKEN")
|
| 73 |
+
if not url or not token:
|
| 74 |
+
raise GatewayError("LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN are not set")
|
| 75 |
+
return cls(url, token, face=face, **kw)
|
| 76 |
+
|
| 77 |
+
@classmethod
|
| 78 |
+
def from_gateway_file(cls, path, face="sdk", **kw):
|
| 79 |
+
"""gateway.json written by the gateway in the run's log dir (launchers only; harness processes get env vars)."""
|
| 80 |
+
d = json.load(open(path))
|
| 81 |
+
return cls(d["url"], d["token"], face=face, **kw)
|
| 82 |
+
|
| 83 |
+
# ------------------------------------------------------------------------------------------------ http
|
| 84 |
+
def _request(self, method, path, body=None):
|
| 85 |
+
req = urllib.request.Request(self.url + path, method=method,
|
| 86 |
+
data=None if body is None else json.dumps(body).encode(),
|
| 87 |
+
headers={"Authorization": f"Bearer {self.token}", "X-LFF-Face": self.face,
|
| 88 |
+
"Content-Type": "application/json"})
|
| 89 |
+
try:
|
| 90 |
+
with self._opener.open(req, timeout=self.timeout_s) as r:
|
| 91 |
+
return r.read(), r.headers.get("Content-Type", "")
|
| 92 |
+
except urllib.error.HTTPError as e:
|
| 93 |
+
raise GatewayError(f"{method} {path}: HTTP {e.code}: {e.read()[:500].decode('utf-8', 'replace')}") from None
|
| 94 |
+
except urllib.error.URLError as e:
|
| 95 |
+
raise GatewayError(f"{method} {path}: {e.reason}") from None
|
| 96 |
+
|
| 97 |
+
def _get_json(self, path):
|
| 98 |
+
return json.loads(self._request("GET", path)[0])
|
| 99 |
+
|
| 100 |
+
# ------------------------------------------------------------------------------------------------ tools
|
| 101 |
+
def call(self, name, arguments=None):
|
| 102 |
+
raw, _ = self._request("POST", "/tool", dict(name=name, arguments=arguments or {}))
|
| 103 |
+
d = json.loads(raw)
|
| 104 |
+
return ToolResult(content=d["content"], is_error=bool(d["is_error"]), finished=bool(d["finished"]),
|
| 105 |
+
calls_in_attempt=d.get("calls_in_attempt"))
|
| 106 |
+
|
| 107 |
+
def robot(self, command):
|
| 108 |
+
"""One robot command, exactly as in the instructions (e.g. 'status', 'move_eef x=0.5 z=0.2', 'finish ...')."""
|
| 109 |
+
return self.call("robot", dict(command=command))
|
| 110 |
+
|
| 111 |
+
def shell(self, command):
|
| 112 |
+
"""A bash command in the episode workspace (jailed: no network, nothing outside the workspace)."""
|
| 113 |
+
return self.call("shell", dict(command=command))
|
| 114 |
+
|
| 115 |
+
def view_images(self, paths):
|
| 116 |
+
"""Image files of the workspace (e.g. obs/s001_agentview.jpg); the images come back as image items."""
|
| 117 |
+
return self.call("view_images", dict(paths=list(paths)))
|
| 118 |
+
|
| 119 |
+
# ------------------------------------------------------------------------------------------------ instructions
|
| 120 |
+
def tool_specs(self, style="raw"):
|
| 121 |
+
"""The three tool schemas with the reference descriptions, in one of STYLES."""
|
| 122 |
+
if style not in STYLES:
|
| 123 |
+
raise ValueError(f"style must be one of {STYLES}")
|
| 124 |
+
return self._get_json("/tool_specs?style=" + urllib.parse.quote(style))["tools"]
|
| 125 |
+
|
| 126 |
+
def readme(self):
|
| 127 |
+
return self._request("GET", "/readme")[0].decode("utf-8")
|
| 128 |
+
|
| 129 |
+
def first_message(self):
|
| 130 |
+
"""Preamble + README + first status report: the first user message every harness gets."""
|
| 131 |
+
return self._request("GET", "/first_message")[0].decode("utf-8")
|
| 132 |
+
|
| 133 |
+
def health(self):
|
| 134 |
+
return self._get_json("/health")
|
| 135 |
+
|
| 136 |
+
def status(self):
|
| 137 |
+
"""robot_server's `status` for the framework's own loop (e.g. a "continue" nudge that names the attempt): not
|
| 138 |
+
a tool call of the model, not counted in the per-attempt budget. Never show it to the model as a tool result."""
|
| 139 |
+
return self._get_json("/status")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-generic_0.163.0_399ff69c431c066e_deepseek-v4.1-flash_high.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-generic|0.163.0|399ff69c431c066e|deepseek-v4.1-flash|high",
|
| 3 |
+
"fingerprint_sha256": "52d7de20832981196514c20e91635e50a2dc6241fa45a1bbfd863d08dc8cc740",
|
| 4 |
+
"written": "2026-10-29 16:15:13",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 16979,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"list_mcp_resource_templates",
|
| 9 |
+
"list_mcp_resources",
|
| 10 |
+
"mcp__lff.robot",
|
| 11 |
+
"mcp__lff.shell",
|
| 12 |
+
"mcp__lff.view_images",
|
| 13 |
+
"read_mcp_resource",
|
| 14 |
+
"request_user_input"
|
| 15 |
+
],
|
| 16 |
+
"effort_in_request": "high",
|
| 17 |
+
"model_in_request": "deepseek-v4.1-flash",
|
| 18 |
+
"sandbox": {
|
| 19 |
+
"sandbox": "seccomp",
|
| 20 |
+
"sandbox_mode": "read-only"
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
}
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/agent_viewer/live.py
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Read-only terminal viewer for active LFF-Bench runs (ANSI images or ASCII)."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
import argparse
|
| 5 |
+
import base64
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import shutil
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
# Strip terminal controls from untrusted logged text; only this program emits ANSI.
|
| 16 |
+
def clean(value):
|
| 17 |
+
return re.sub(r'[\x00-\x1f\x7f-\x9f]', ' ', str(value))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def read_json(path):
|
| 21 |
+
try:
|
| 22 |
+
return json.loads(Path(path).read_text())
|
| 23 |
+
except (OSError, ValueError):
|
| 24 |
+
return None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Tail:
|
| 28 |
+
"""Only consume complete JSONL records; tolerate concurrent append and rotation."""
|
| 29 |
+
def __init__(self, path):
|
| 30 |
+
self.path, self.offset, self.pending, self.identity = Path(path), 0, b'', None
|
| 31 |
+
self.errors = 0
|
| 32 |
+
self.generation = 0
|
| 33 |
+
|
| 34 |
+
def read(self):
|
| 35 |
+
try:
|
| 36 |
+
with self.path.open('rb') as stream:
|
| 37 |
+
stat = os.fstat(stream.fileno())
|
| 38 |
+
identity = (stat.st_dev, stat.st_ino)
|
| 39 |
+
if self.identity is not None and (identity != self.identity or stat.st_size < self.offset):
|
| 40 |
+
self.offset, self.pending = 0, b''
|
| 41 |
+
self.generation += 1
|
| 42 |
+
self.identity = identity
|
| 43 |
+
stream.seek(self.offset)
|
| 44 |
+
chunk = stream.read()
|
| 45 |
+
self.offset = stream.tell()
|
| 46 |
+
except OSError:
|
| 47 |
+
return []
|
| 48 |
+
lines = (self.pending + chunk).split(b'\n')
|
| 49 |
+
self.pending = lines.pop()
|
| 50 |
+
out = []
|
| 51 |
+
for line in lines:
|
| 52 |
+
if not line.strip():
|
| 53 |
+
continue
|
| 54 |
+
try:
|
| 55 |
+
row = json.loads(line)
|
| 56 |
+
if isinstance(row, dict):
|
| 57 |
+
out.append(row)
|
| 58 |
+
else:
|
| 59 |
+
self.errors += 1
|
| 60 |
+
except (ValueError, UnicodeDecodeError):
|
| 61 |
+
self.errors += 1
|
| 62 |
+
return out
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Run:
|
| 66 |
+
def __init__(self, path):
|
| 67 |
+
self.path = Path(path)
|
| 68 |
+
self.task = self.path.name
|
| 69 |
+
self.calls = 0
|
| 70 |
+
self.attempt = 1
|
| 71 |
+
self.outcomes = []
|
| 72 |
+
self.command = '等待工具调用'
|
| 73 |
+
self.command_at = None
|
| 74 |
+
self.view_paths = []
|
| 75 |
+
self.view_at = None
|
| 76 |
+
self.view_sequence = 0
|
| 77 |
+
self.embedded_sequence = 0
|
| 78 |
+
self.embedded_paths = []
|
| 79 |
+
self.embedded = []
|
| 80 |
+
self.summary = ''
|
| 81 |
+
self.status = '等待日志'
|
| 82 |
+
self.notice = ''
|
| 83 |
+
self.last_activity = None
|
| 84 |
+
names = ['events.jsonl', 'gateway_transcript.jsonl', 'mcp_transcript.jsonl',
|
| 85 |
+
'transcript.jsonl', 'gpt_transcript.jsonl', 'codex_events.jsonl']
|
| 86 |
+
self.tails = {n: Tail(self.path / n) for n in names}
|
| 87 |
+
self.image_cache = {}
|
| 88 |
+
|
| 89 |
+
def update(self):
|
| 90 |
+
gateway = 'gateway_transcript.jsonl' if (self.path/'gateway_transcript.jsonl').exists() else 'mcp_transcript.jsonl'
|
| 91 |
+
api = 'transcript.jsonl' if (self.path/'transcript.jsonl').exists() else 'gpt_transcript.jsonl'
|
| 92 |
+
for name in ['events.jsonl', gateway, api, 'codex_events.jsonl']:
|
| 93 |
+
tail = self.tails[name]
|
| 94 |
+
generation = tail.generation
|
| 95 |
+
rows = tail.read()
|
| 96 |
+
if tail.generation != generation:
|
| 97 |
+
# Avoid mixing observations and counts across replaced/truncated runs.
|
| 98 |
+
self.__init__(self.path)
|
| 99 |
+
self.notice = '日志已轮转,重新读取'
|
| 100 |
+
return self.update()
|
| 101 |
+
for row in rows:
|
| 102 |
+
if row.get('t') is not None:
|
| 103 |
+
self.last_activity = max(self.last_activity or 0, row['t'])
|
| 104 |
+
if name == 'events.jsonl':
|
| 105 |
+
if row.get('ev') == 'session_start':
|
| 106 |
+
self.task = row.get('task', self.task)
|
| 107 |
+
self.status = '运行中'
|
| 108 |
+
elif row.get('ev') == 'call':
|
| 109 |
+
self.calls += 1
|
| 110 |
+
self.attempt = row.get('attempt', self.attempt)
|
| 111 |
+
self.command = row.get('cmd', '') + ' ' + json.dumps(row.get('args', {}), ensure_ascii=False)
|
| 112 |
+
self.command_at = row.get('t')
|
| 113 |
+
elif row.get('ev') == 'done':
|
| 114 |
+
self.outcomes.append((row.get('attempt'), row.get('success')))
|
| 115 |
+
elif name == gateway:
|
| 116 |
+
if row.get('ev') != 'tool':
|
| 117 |
+
continue
|
| 118 |
+
if row.get('finished'):
|
| 119 |
+
self.status = '任务已结束'
|
| 120 |
+
if row.get('name') == 'view_images' and not row.get('is_error') and row.get('images', 0) > 0:
|
| 121 |
+
paths = []
|
| 122 |
+
for output in row.get('output', []):
|
| 123 |
+
try:
|
| 124 |
+
obj = json.loads(output)
|
| 125 |
+
paths.extend(obj.get('attached', []))
|
| 126 |
+
except (ValueError, TypeError, AttributeError):
|
| 127 |
+
pass
|
| 128 |
+
# Only mark confirmed attachments as observed, not requested files.
|
| 129 |
+
if paths:
|
| 130 |
+
self.view_paths, self.view_at = paths, row.get('t')
|
| 131 |
+
self.view_sequence += 1
|
| 132 |
+
if row.get('name') == 'robot':
|
| 133 |
+
self.command = row.get('arguments', {}).get('command', self.command)
|
| 134 |
+
self.command_at = row.get('t')
|
| 135 |
+
elif name == api:
|
| 136 |
+
if row.get('ev') in ('user', 'tool') and row.get('images'):
|
| 137 |
+
self.view_paths, self.view_at = row['images'], row.get('t')
|
| 138 |
+
self.view_sequence += 1
|
| 139 |
+
if row.get('ev') == 'assistant':
|
| 140 |
+
self.summary = row.get('reasoning_summary') or row.get('text') or ''
|
| 141 |
+
if row.get('ev') in ('end', 'abort'):
|
| 142 |
+
self.status = '已结束' if row['ev'] == 'end' else '已中断'
|
| 143 |
+
elif name == 'codex_events.jsonl' and row.get('type') == 'item.completed':
|
| 144 |
+
item = row.get('item', {})
|
| 145 |
+
if item.get('type') in ('reasoning', 'agent_message'):
|
| 146 |
+
self.summary = item.get('text', '')
|
| 147 |
+
if item.get('type') == 'mcp_tool_call' and item.get('tool') == 'view_images' and not item.get('error'):
|
| 148 |
+
content = (item.get('result') or {}).get('content', [])
|
| 149 |
+
paths, raw = [], []
|
| 150 |
+
for c in content:
|
| 151 |
+
if c.get('type') == 'text':
|
| 152 |
+
try:
|
| 153 |
+
paths.extend(json.loads(c.get('text', '')).get('attached', []))
|
| 154 |
+
except (ValueError, AttributeError):
|
| 155 |
+
pass
|
| 156 |
+
elif c.get('type') == 'image':
|
| 157 |
+
try:
|
| 158 |
+
raw.append(base64.b64decode(c['data'], validate=True))
|
| 159 |
+
except (ValueError, KeyError):
|
| 160 |
+
pass
|
| 161 |
+
if raw and len(raw) == len(paths):
|
| 162 |
+
self.embedded_paths, self.embedded = paths, raw
|
| 163 |
+
self.embedded_sequence += 1
|
| 164 |
+
if not (self.path/gateway).exists():
|
| 165 |
+
self.view_paths = paths
|
| 166 |
+
self.view_sequence = self.embedded_sequence
|
| 167 |
+
self.notice = f'跳过 {sum(t.errors for t in self.tails.values())} 条损坏日志' if any(t.errors for t in self.tails.values()) else self.notice
|
| 168 |
+
|
| 169 |
+
def frames(self):
|
| 170 |
+
session = read_json(self.path/'session.json') or {}
|
| 171 |
+
roots = [self.path]
|
| 172 |
+
if session.get('sandbox'):
|
| 173 |
+
roots.append(Path(session['sandbox']))
|
| 174 |
+
result = []
|
| 175 |
+
for index, ref in enumerate(self.view_paths):
|
| 176 |
+
if not isinstance(ref, str):
|
| 177 |
+
continue
|
| 178 |
+
if self.embedded_sequence == self.view_sequence and self.embedded_paths == self.view_paths and index < len(self.embedded):
|
| 179 |
+
result.append((ref, self.embedded[index], '工具响应内嵌图片'))
|
| 180 |
+
continue
|
| 181 |
+
for root in roots:
|
| 182 |
+
target = (root/ref).resolve()
|
| 183 |
+
if not target.is_relative_to(root.resolve()) or not target.is_file():
|
| 184 |
+
continue
|
| 185 |
+
stat = target.stat()
|
| 186 |
+
if self.view_at is not None and stat.st_mtime > self.view_at + 0.1:
|
| 187 |
+
result.append((ref, None, '文件在观察后已修改,不能确认原图'))
|
| 188 |
+
break
|
| 189 |
+
key = (str(target), stat.st_mtime_ns, stat.st_size)
|
| 190 |
+
if key not in self.image_cache:
|
| 191 |
+
self.image_cache = {key: target.read_bytes()}
|
| 192 |
+
result.append((ref, self.image_cache[key], '日志引用文件(未校验原始字节)'))
|
| 193 |
+
break
|
| 194 |
+
else:
|
| 195 |
+
result.append((ref, None, '图片文件不可用'))
|
| 196 |
+
return result
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def choose_run(batch):
|
| 200 |
+
data = read_json(Path(batch)/'manifest.json')
|
| 201 |
+
if not data:
|
| 202 |
+
return None, '批次清单暂不可读'
|
| 203 |
+
rows = data.get('runs', [])
|
| 204 |
+
counts = {key: sum(r.get('status') == key for r in rows) for key in ['done', 'running', 'pending']}
|
| 205 |
+
active = [r for r in rows if r.get('status') == 'running' and r.get('log')]
|
| 206 |
+
completed = [r for r in rows if r.get('log')]
|
| 207 |
+
row = active[0] if active else completed[-1] if completed else None
|
| 208 |
+
summary = ' / '.join(f'{key} {count}' for key, count in counts.items())
|
| 209 |
+
return row, summary
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def image_lines(raw, columns, rows, color):
|
| 213 |
+
from PIL import Image, ImageOps
|
| 214 |
+
image = Image.open(io.BytesIO(raw)).convert('RGB')
|
| 215 |
+
width, height = columns, rows * 2
|
| 216 |
+
image = ImageOps.contain(image, (width, height))
|
| 217 |
+
pixels = image.load()
|
| 218 |
+
lines = []
|
| 219 |
+
ramp = ' .:-=+*#%@'
|
| 220 |
+
for y in range(0, image.height, 2):
|
| 221 |
+
line = ''
|
| 222 |
+
for x in range(image.width):
|
| 223 |
+
upper, lower = pixels[x,y], pixels[x,min(y+1,image.height-1)]
|
| 224 |
+
if color:
|
| 225 |
+
line += '\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm▀' % (*upper, *lower)
|
| 226 |
+
else:
|
| 227 |
+
value = (sum(upper) + sum(lower)) / 6
|
| 228 |
+
line += ramp[min(9, int(value/256*10))]
|
| 229 |
+
lines.append(line + ('\033[0m' if color else ''))
|
| 230 |
+
return lines
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# Native image transports keep source pixels rather than quantizing to text cells.
|
| 234 |
+
KITTY_IMAGE_ID = 1987000000 + os.getpid() % 100000
|
| 235 |
+
|
| 236 |
+
def choose_renderer(requested, environ=None, tty=True):
|
| 237 |
+
env = os.environ if environ is None else environ
|
| 238 |
+
if not tty:
|
| 239 |
+
return 'ansi'
|
| 240 |
+
# This embedded terminal was observed to swallow OSC 1337 images, leaving
|
| 241 |
+
# the reserved rectangle blank. Keep a visible preview even for old commands.
|
| 242 |
+
if env.get('TERM_PROGRAM') == 'claude-desktop' and requested == 'iterm':
|
| 243 |
+
return 'ansi'
|
| 244 |
+
if requested != 'auto':
|
| 245 |
+
return requested
|
| 246 |
+
# Multiplexers need terminal-specific passthrough setup; keep auto conservative.
|
| 247 |
+
if env.get('TMUX') or env.get('STY'):
|
| 248 |
+
return 'ansi'
|
| 249 |
+
if env.get('KITTY_WINDOW_ID') or env.get('TERM') == 'xterm-kitty':
|
| 250 |
+
return 'kitty'
|
| 251 |
+
if env.get('TERM_PROGRAM') in ('iTerm.app', 'WezTerm'):
|
| 252 |
+
return 'iterm'
|
| 253 |
+
return 'ansi'
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def native_image(raw_images, columns, rows, renderer):
|
| 257 |
+
from PIL import Image
|
| 258 |
+
decoded = [Image.open(io.BytesIO(raw)).convert('RGB') for raw in raw_images]
|
| 259 |
+
# Place full-resolution views side by side without resampling source pixels.
|
| 260 |
+
canvas = Image.new('RGB', (sum(im.width for im in decoded), max(im.height for im in decoded)))
|
| 261 |
+
x = 0
|
| 262 |
+
for im in decoded:
|
| 263 |
+
canvas.paste(im, (x, 0))
|
| 264 |
+
x += im.width
|
| 265 |
+
buf = io.BytesIO()
|
| 266 |
+
canvas.save(buf, format='PNG')
|
| 267 |
+
data = base64.b64encode(buf.getvalue()).decode()
|
| 268 |
+
if renderer == 'iterm':
|
| 269 |
+
sequence = f'\033]1337;File=inline=1;width={columns};height={rows};preserveAspectRatio=1:{data}\a'
|
| 270 |
+
else:
|
| 271 |
+
# Preserve aspect in the usual 1:2 text cells; don't stretch square inputs.
|
| 272 |
+
w = max(1, min(columns, int(rows * 2 * canvas.width / canvas.height)))
|
| 273 |
+
h = max(1, min(rows, round(w * canvas.height / canvas.width / 2)))
|
| 274 |
+
chunks = [data[i:i+4096] for i in range(0, len(data), 4096)]
|
| 275 |
+
sequence = ''
|
| 276 |
+
for n, chunk in enumerate(chunks):
|
| 277 |
+
meta = f'a=T,f=100,t=d,i={KITTY_IMAGE_ID},q=2,C=1,c={w},r={h},' if n == 0 else ''
|
| 278 |
+
sequence += f'\033_G{meta}m={int(n < len(chunks)-1)};{chunk}\033\\'
|
| 279 |
+
# Both protocols are given a reserved rectangle; restore before advancing.
|
| 280 |
+
return '\0337' + sequence + '\0338' + '\n' * (rows - 1)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def clear_native(renderer):
|
| 284 |
+
return f'\033_Ga=d,d=I,i={KITTY_IMAGE_ID},q=2\033\\' if renderer == 'kitty' else ''
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def age(timestamp):
|
| 288 |
+
return f'{max(0,int(time.time()-timestamp))} 秒前' if timestamp else '时间未记录'
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def render(run, label, width, rows, color, images, renderer="ansi", camera="all"):
|
| 292 |
+
lines = [clean(label)[:width], f'{clean(run.task)} | {clean(run.status)} | 尝试 {run.attempt} | 机器人动作 {run.calls}',
|
| 293 |
+
f'最近动作 ({age(run.command_at)}): {clean(run.command)[:max(15,width-22)]}',
|
| 294 |
+
f'最近返回给 Agent 的图片 ({age(run.view_at)}):按观察事件更新,不是连续视频']
|
| 295 |
+
frames = run.frames()
|
| 296 |
+
if camera != "all":
|
| 297 |
+
keyword = "agentview" if camera == "main" else "wrist"
|
| 298 |
+
frames = [f for f in frames if keyword in f[0]][-1:]
|
| 299 |
+
if not frames:
|
| 300 |
+
lines.append('尚未发现已返回给 Agent 的图片。')
|
| 301 |
+
if images and frames:
|
| 302 |
+
shown = frames[-2:]
|
| 303 |
+
cell = max(12,(width-3*(len(shown)-1))//len(shown))
|
| 304 |
+
columns = []
|
| 305 |
+
for ref, raw, source in shown:
|
| 306 |
+
display = ('字符缩略图' if renderer == 'ansi' else '原图像素') if raw else '不可用'
|
| 307 |
+
lines.append(f' {clean(ref)} · 来源:{source} · 显示:{display}')
|
| 308 |
+
try:
|
| 309 |
+
columns.append(image_lines(raw, cell, rows, color) if raw else ['[原图不可用]'])
|
| 310 |
+
except Exception as exc:
|
| 311 |
+
columns.append([f'[无法解码图片: {type(exc).__name__}]'])
|
| 312 |
+
if renderer in ('iterm', 'kitty') and any(raw for _, raw, _ in shown):
|
| 313 |
+
try:
|
| 314 |
+
lines.append(native_image([raw for _, raw, _ in shown if raw], width, rows, renderer))
|
| 315 |
+
columns = []
|
| 316 |
+
except Exception as exc:
|
| 317 |
+
lines.append(f'原图显示编码失败,使用字符预览: {type(exc).__name__}')
|
| 318 |
+
for y in range(max(map(len, columns), default=0)):
|
| 319 |
+
parts=[]
|
| 320 |
+
for c in columns:
|
| 321 |
+
part=c[y] if y<len(c) else ''
|
| 322 |
+
visible=len(re.sub(r'\033\[[0-9;]*m','',part))
|
| 323 |
+
parts.append(part+' '*max(0,cell-visible))
|
| 324 |
+
lines.append(' '.join(parts))
|
| 325 |
+
elif frames:
|
| 326 |
+
lines.extend('图片: '+clean(f[0]) for f in frames)
|
| 327 |
+
if run.summary:
|
| 328 |
+
lines.append('最近记录的摘要/说明: '+clean(run.summary)[:max(20,width-20)])
|
| 329 |
+
if run.outcomes:
|
| 330 |
+
lines.append('已提交结果: '+' · '.join(f'尝试 {a}: '+('成功' if ok else '失败') for a,ok in run.outcomes))
|
| 331 |
+
if run.notice:
|
| 332 |
+
lines.append(run.notice)
|
| 333 |
+
lines.append('最近日志活动: '+age(run.last_activity))
|
| 334 |
+
return '\n'.join(lines)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def main(argv=None):
|
| 338 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 339 |
+
group=parser.add_mutually_exclusive_group(required=True)
|
| 340 |
+
group.add_argument('--batch',type=Path,help='Batch directory; follows the running task then the next one')
|
| 341 |
+
group.add_argument('--run',type=Path,help='One run directory')
|
| 342 |
+
parser.add_argument('--interval',type=float,default=6,help="Refresh interval in seconds (default: 6)")
|
| 343 |
+
parser.add_argument('--once',action='store_true')
|
| 344 |
+
parser.add_argument('--duration',type=float,help='Stop after N seconds (useful for verification)')
|
| 345 |
+
parser.add_argument('--ascii',action='store_true',help='Portable monochrome preview instead of truecolor blocks')
|
| 346 |
+
parser.add_argument('--no-images',action='store_true')
|
| 347 |
+
parser.add_argument('--renderer',choices=['auto','ansi','iterm','kitty'],default='auto',help='Native pixels: iterm (also VS Code with enableImages) or kitty; auto detects known terminals')
|
| 348 |
+
parser.add_argument('--camera',choices=['all','main','wrist'],default='all',help='Select one camera for a larger view')
|
| 349 |
+
parser.add_argument('--width',type=int,default=None)
|
| 350 |
+
parser.add_argument('--image-rows',type=int,default=None)
|
| 351 |
+
a=parser.parse_args(argv)
|
| 352 |
+
if a.interval<0.5:parser.error('--interval must be >= 0.5 seconds')
|
| 353 |
+
if a.width is not None and a.width<24:parser.error('--width must be >= 24')
|
| 354 |
+
if a.image_rows is not None and a.image_rows<2:parser.error('--image-rows must be >= 2')
|
| 355 |
+
if a.duration is not None and a.duration<=0:parser.error('--duration must be positive')
|
| 356 |
+
if not a.no_images:
|
| 357 |
+
try:import PIL
|
| 358 |
+
except ImportError:parser.error('Image preview needs Pillow; use the evaluation Python or --no-images')
|
| 359 |
+
renderer=choose_renderer('ansi' if a.ascii else a.renderer,tty=sys.stdout.isatty())
|
| 360 |
+
if a.no_images:renderer='ansi'
|
| 361 |
+
compatibility_notice = (
|
| 362 |
+
'Claude 内置终端的 iTerm 图片模式未能显示;已切换为字符预览(非原图清晰度)。'
|
| 363 |
+
if os.environ.get('TERM_PROGRAM') == 'claude-desktop'
|
| 364 |
+
and a.renderer == 'iterm' and renderer == 'ansi'
|
| 365 |
+
and not a.ascii and not a.no_images and sys.stdout.isatty() else ''
|
| 366 |
+
)
|
| 367 |
+
interactive=sys.stdout.isatty() and not a.once
|
| 368 |
+
current=None
|
| 369 |
+
started=time.monotonic()
|
| 370 |
+
previous=None
|
| 371 |
+
try:
|
| 372 |
+
if interactive:print('\033[?1049h\033[?25l',end='',flush=True)
|
| 373 |
+
while True:
|
| 374 |
+
label='Agent Viewer · LIVE · Ctrl+C 退出'
|
| 375 |
+
path=a.run
|
| 376 |
+
if a.batch:
|
| 377 |
+
selected,summary=choose_run(a.batch)
|
| 378 |
+
path=Path(selected['log']) if selected else None
|
| 379 |
+
label=f'{a.batch.name} | {summary}'
|
| 380 |
+
if path is not None:
|
| 381 |
+
if current is None or current.path!=path:current=Run(path)
|
| 382 |
+
current.update()
|
| 383 |
+
if a.batch and selected:current.status=selected.get('status',current.status)
|
| 384 |
+
size=shutil.get_terminal_size((100,36))
|
| 385 |
+
width=a.width or max(24,size.columns-1)
|
| 386 |
+
rows=a.image_rows or max(3,size.lines-12-bool(compatibility_notice))
|
| 387 |
+
label += f' | 刷新 {a.interval:g}s · {renderer}'
|
| 388 |
+
output=render(current,label,width,rows,sys.stdout.isatty() and not a.ascii,not a.no_images,renderer,a.camera)
|
| 389 |
+
if compatibility_notice:
|
| 390 |
+
header, _, body = output.partition('\n')
|
| 391 |
+
output = header + '\n' + compatibility_notice + '\n' + body
|
| 392 |
+
else:output=label+'\n等待批次启动下一任务…'
|
| 393 |
+
if output!=previous:
|
| 394 |
+
if interactive:print(clear_native(renderer)+'\033[H\033[J'+output,end='',flush=True)
|
| 395 |
+
else:print(output,flush=True)
|
| 396 |
+
previous=output
|
| 397 |
+
if a.once or a.duration and time.monotonic()-started>=a.duration:break
|
| 398 |
+
delay=a.interval if a.duration is None else min(a.interval,max(0,a.duration-(time.monotonic()-started)))
|
| 399 |
+
time.sleep(delay)
|
| 400 |
+
except KeyboardInterrupt:
|
| 401 |
+
pass
|
| 402 |
+
finally:
|
| 403 |
+
if interactive:print(clear_native(renderer)+'\033[0m\033[?25h\033[?1049l',end='',flush=True)
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/arm_specs/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-task specs for the controlled arms of full5 (2026-10-12, docs/14 §6).
|
| 2 |
+
|
| 3 |
+
One module per task, named exactly like the task (lffbench/arm_specs/<task_name>.py), defining:
|
| 4 |
+
|
| 5 |
+
HIDDEN_KEYS : tuple of instance keys that carry the hidden variable(s)
|
| 6 |
+
h0(inst) -> dict overrides for the H0 twin: same layout, hidden variable at its "ordinary" value, so the
|
| 7 |
+
common-sense first attempt succeeds (scripted naive succeeds)
|
| 8 |
+
twin(inst) -> dict overrides for the mismatched-history source: same layout, the trap is still active (scripted
|
| 9 |
+
naive still fails, visibly) but the right correction is different from the original instance's,
|
| 10 |
+
ideally opposite (e.g. centre of mass on the other side)
|
| 11 |
+
reveal(inst)-> str H+ text appended to the task instruction: the hidden variable stated plainly in robot-frame
|
| 12 |
+
words a careful human could act on, without prescribing the solution
|
| 13 |
+
|
| 14 |
+
All three take the ORIGINAL sampled instance and return only the keys to change (JSON-serialisable). The server
|
| 15 |
+
applies them with dict.update() after sample_instance(); reset_instance() must honour them.
|
| 16 |
+
"""
|
| 17 |
+
import importlib
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load(task_name):
|
| 21 |
+
"""The spec module for task_name, or None if the task has no controlled-arm spec."""
|
| 22 |
+
try:
|
| 23 |
+
return importlib.import_module(f"{__name__}.{task_name}")
|
| 24 |
+
except ModuleNotFoundError as e:
|
| 25 |
+
if e.name == f"{__name__}.{task_name}":
|
| 26 |
+
return None
|
| 27 |
+
raise
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def overrides(task_name, arm, inst):
|
| 31 |
+
"""Instance overrides for arm in (h0, twin); {} for other arms."""
|
| 32 |
+
if arm not in ("h0", "twin"):
|
| 33 |
+
return {}
|
| 34 |
+
spec = load(task_name)
|
| 35 |
+
if spec is None:
|
| 36 |
+
raise SystemExit(f"--arm {arm}: no spec in lffbench/arm_specs/{task_name}.py")
|
| 37 |
+
return getattr(spec, arm)(inst)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def reveal(task_name, inst):
|
| 41 |
+
spec = load(task_name)
|
| 42 |
+
if spec is None:
|
| 43 |
+
raise SystemExit(f"--arm hplus: no spec in lffbench/arm_specs/{task_name}.py")
|
| 44 |
+
return spec.reveal(inst)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def fix(task_name, inst, params):
|
| 48 |
+
"""Fix-rung text of the layer-3 feedback ladder (docs/20): how to succeed on this instance, in robot-frame words,
|
| 49 |
+
built from the task's oracle parameters `params` (task.oracle_params(inst), computed by the caller with the sim)."""
|
| 50 |
+
spec = load(task_name)
|
| 51 |
+
if spec is None or not hasattr(spec, "fix"):
|
| 52 |
+
raise SystemExit(f"ladder fix: no fix() in lffbench/arm_specs/{task_name}.py")
|
| 53 |
+
return spec.fix(inst, params)
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "fbf323682711d7010fa8cd2c9036b1082dab2a6cd4cf80983be1adf64e037d7c",
|
| 4 |
+
"written": "2026-10-20 02:16:00",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 182,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-sonnet-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-sonnet-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "a8c04b0dca902885e52e7e5680c1cf8b782469e79c518f83b72249342285bfb0",
|
| 4 |
+
"written": "2026-10-21 05:19:29",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 5629,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-sonnet-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4",
|
| 4 |
+
"written": "2026-10-13 04:12:38",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 26736,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-sonnet-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-chatgpt|0.163.0|399ff69c431c066e|gpt-6-astra|medium",
|
| 3 |
+
"fingerprint_sha256": "034292e12859cda9de8c2481b91f6c3194b83754303be8c40c3ec775bcabf9ad",
|
| 4 |
+
"written": "2026-10-19 22:12:31",
|
| 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": "medium",
|
| 30 |
+
"model_in_request": "gpt-6-astra",
|
| 31 |
+
"sandbox": {
|
| 32 |
+
"sandbox": "seccomp",
|
| 33 |
+
"sandbox_mode": "read-only"
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/lffbench/harnesses/pins/dsh_0.2.1-rc.5_aa65546cc1f51674_deepseek-flash_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "dsh|0.2.1-rc.5|aa65546cc1f51674|deepseek-flash|high",
|
| 3 |
+
"fingerprint_sha256": "18044f5deb7b4d0d662d620fce120e85e3f94103fa2699346221fa46d093fc8f",
|
| 4 |
+
"written": "2026-10-31 06:05:50",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 109,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "deepseek-flash"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/cs_ir_report.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reproduce the CS/IR audit tables from read-only manifests and hash-bound evidence."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import api_batch
|
| 7 |
+
import outcomes
|
| 8 |
+
from outcome_audit import load_audit, sha256
|
| 9 |
+
|
| 10 |
+
GROUPS = {"GPT": ["cx_main1"], "Sonnet": ["cc_main1"], "Opus": ["cc_opus1"],
|
| 11 |
+
"DeepSeek": ["ds_cx1", "ds_cx1b"]}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def main():
|
| 15 |
+
parser = argparse.ArgumentParser()
|
| 16 |
+
parser.add_argument("--runs-root", required=True)
|
| 17 |
+
parser.add_argument("--audit", required=True)
|
| 18 |
+
parser.add_argument("--out", required=True)
|
| 19 |
+
args = parser.parse_args()
|
| 20 |
+
api_batch.RUNS = str(Path(args.runs_root).resolve())
|
| 21 |
+
audit = load_audit(args.audit)
|
| 22 |
+
output = Path(args.out)
|
| 23 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 24 |
+
all_rows, models, manifests, coverage = [], {}, {}, {}
|
| 25 |
+
for model, batches in GROUPS.items():
|
| 26 |
+
old, new = [], []
|
| 27 |
+
for batch in batches:
|
| 28 |
+
manifest = api_batch.load(batch)
|
| 29 |
+
manifests[batch] = sha256(api_batch.mpath(batch))
|
| 30 |
+
old += outcomes.instance_rows(manifest, batch=batch)
|
| 31 |
+
new += outcomes.instance_rows(manifest, audit=audit, batch=batch)
|
| 32 |
+
for run in manifest["runs"]:
|
| 33 |
+
if not (run["cond"] == "harness" and run.get("followup") and run["status"] == "done"):
|
| 34 |
+
continue
|
| 35 |
+
attempts = outcomes.attempts(run["log"])
|
| 36 |
+
if attempts:
|
| 37 |
+
coverage.setdefault(run["task"], set()).update(
|
| 38 |
+
k for k in outcomes.ERROR_FLAGS + outcomes.ERROR_COUNTS if k in attempts[0][2])
|
| 39 |
+
before, after = outcomes.summary(old), outcomes.summary(new)
|
| 40 |
+
for key in ("n", "A1", "A3", "XR", "F", "n_paired", "A3_paired", "passk_paired", "delta_paired"):
|
| 41 |
+
assert before[key] == after[key], f"Audit unexpectedly changed {model} {key}"
|
| 42 |
+
assert len({(r["task"], r["seed"]) for r in new}) == len(new), "duplicate model/task/seed"
|
| 43 |
+
models[model] = dict(before=before, after=after)
|
| 44 |
+
all_rows += [dict(r, model=model) for r in new]
|
| 45 |
+
payload = dict(schema="lff-cs-ir-report-1", source_manifests_sha256=manifests,
|
| 46 |
+
audit_sha256=sha256(args.audit), models=models, rows=all_rows,
|
| 47 |
+
legacy_counter_coverage={k: sorted(v) for k, v in coverage.items()})
|
| 48 |
+
(output / "summary.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
|
| 49 |
+
lines = ["# CS / IR 证据审计表(2026-10-24)", "",
|
| 50 |
+
"本表由 `scripts/cs_ir_report.py` 生成;定义、局限、合并说明见同目录 `README.md`。",
|
| 51 |
+
"旧口径是 task counter heuristic;新口径是逐 run 的物理失败 + 主动修复证据审计。",
|
| 52 |
+
"A1、A3、XR、F、配对样本及 Δ_hist 均逐项断言保持不变。", "",
|
| 53 |
+
"| 模型 | 旧 CS / IR / S? | 审计 CS / IR / S? | 原 S? 已补 | A1 | A3 |",
|
| 54 |
+
"|---|---|---|---|---|---|"]
|
| 55 |
+
for model, pair in models.items():
|
| 56 |
+
b, a = pair["before"], pair["after"]
|
| 57 |
+
resolved = sum(r["model"] == model and r["legacy_cls"] == "S?" and r["cls"] != "S?" for r in all_rows)
|
| 58 |
+
lines.append(f"| {model} | {b['CS']} / {b['IR']} / {b['S?']} | {a['CS']} / {a['IR']} / {a['S?']} | "
|
| 59 |
+
f"{resolved}/{b['S?']} | {a['A1']}/{a['n']} | {a['A3']}/{a['n']} |")
|
| 60 |
+
lines += ["", "## 每任务新旧分类与原统一字段覆盖", "",
|
| 61 |
+
"`旧→新`;只有一个标签表示未变。`缺失` 不是没有错误;有字段也不代表覆盖抓空/掉落等全部失败。", "",
|
| 62 |
+
"| 任务 | GPT | Sonnet | Opus | DeepSeek | 原统一错误字段 |", "|---|---|---|---|---|---|"]
|
| 63 |
+
for task, counters in coverage.items():
|
| 64 |
+
cells = []
|
| 65 |
+
for model in GROUPS:
|
| 66 |
+
row = next(r for r in all_rows if r["model"] == model and r["task"] == task)
|
| 67 |
+
cells.append(row["cls"] if row["cls"] == row["legacy_cls"] else f"{row['legacy_cls']}→{row['cls']}")
|
| 68 |
+
lines.append("| " + " | ".join([task] + cells + [", ".join(sorted(counters)) or "缺失"]) + " |")
|
| 69 |
+
lines += ["", "## 首次成功的证据链", "", "行号均指原 run 文件,E 为 events.jsonl,T 为 trajectory.jsonl;s 为机器人命令序号。", ""]
|
| 70 |
+
for row in all_rows:
|
| 71 |
+
if not row["a1"]:
|
| 72 |
+
continue
|
| 73 |
+
entry = audit.get((row["batch"], row["run_id"]))
|
| 74 |
+
manifest = api_batch.load(row["batch"])
|
| 75 |
+
run = next(r for r in manifest["runs"] if r["id"] == row["run_id"])
|
| 76 |
+
lines += [f"### {row['model']} · {row['task']} · {row['legacy_cls']} → {row['cls']}", "",
|
| 77 |
+
row["audit_basis"], "", f"[原 events.jsonl]({run['log']}/events.jsonl) · "
|
| 78 |
+
f"[原 trajectory.jsonl]({run['log']}/trajectory.jsonl)", ""]
|
| 79 |
+
if entry:
|
| 80 |
+
lines += [f"证据索引:{entry.get('evidence', '')}", "",
|
| 81 |
+
f"归因范围:`{entry.get('failure_scope', 'not_adjudicated')}`。", ""]
|
| 82 |
+
(output / "TABLES.md").write_text("\n".join(lines) + "\n")
|
| 83 |
+
print(json.dumps(models, ensure_ascii=False, indent=2))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
if __name__ == "__main__":
|
| 87 |
+
main()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/gpt_player.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Old entry point of the GPT player, kept so existing commands keep working: the code now lives in api_player.py
|
| 2 |
+
(the unified harness for every provider). This runs it with --provider openai and the old transcript name.
|
| 3 |
+
|
| 4 |
+
python scripts/gpt_player.py --session runs/claude/<run>/session.json --model gpt-6-astra --effort medium [--style la]
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import traceback
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 11 |
+
from api_player import main # noqa: E402
|
| 12 |
+
|
| 13 |
+
if __name__ == "__main__":
|
| 14 |
+
try:
|
| 15 |
+
main(default_provider="openai", transcript_name="gpt_transcript.jsonl")
|
| 16 |
+
except SystemExit:
|
| 17 |
+
raise
|
| 18 |
+
except Exception:
|
| 19 |
+
traceback.print_exc()
|
| 20 |
+
sys.exit(1)
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/headroom_parts_cart.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Incremental physical headroom evaluation of the composite prototype."""
|
| 2 |
+
import argparse,hashlib,json,time
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from lffbench.tasks.lh_parts_cart import PartsCart
|
| 6 |
+
|
| 7 |
+
def clean(x):
|
| 8 |
+
if isinstance(x,np.ndarray):return x.tolist()
|
| 9 |
+
if isinstance(x,np.generic):return x.item()
|
| 10 |
+
raise TypeError(type(x).__name__)
|
| 11 |
+
p=argparse.ArgumentParser();p.add_argument('--kind',choices=['oracle','naive','adaptive','blind'],required=True);p.add_argument('--n',type=int,default=20);p.add_argument('--k',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args()
|
| 12 |
+
out=Path(a.out);out.parent.mkdir(parents=True,exist_ok=True);x=PartsCart();rows=[];start=time.time()
|
| 13 |
+
source=Path(__file__).parents[1]/'lffbench/tasks/lh_parts_cart.py';code_hash=hashlib.sha256(source.read_bytes()).hexdigest()
|
| 14 |
+
for seed in range(1000,1000+a.n):
|
| 15 |
+
i=x.sample_instance(seed);h=x.run_scripted(a.kind,i,k=a.k,seed=seed)
|
| 16 |
+
rows.append(dict(seed=seed,history=h));succ=sum(any(z['outcome']['success'] for z in row['history']) for row in rows)
|
| 17 |
+
out.write_text(json.dumps(dict(kind=a.kind,n_planned=a.n,n_complete=len(rows),k=a.k,successes=succ,rows=rows,seconds=time.time()-start,task_sha256=code_hash,status='complete' if len(rows)==a.n else 'running',note='scripted privileged-state headroom; fixed geometry, randomized inertia only'),indent=2,default=clean))
|
| 18 |
+
print(seed,a.kind,[z['outcome']['success'] for z in h], 'successes',succ,flush=True)
|
| 19 |
+
x.env.close()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/l6_controls.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""python scripts/l6_controls.py <l6_count_into_box|l6_sequence_resume> [n]
|
| 2 |
+
|
| 3 |
+
Extra controls for the two L6 tasks: thumbnails right after the interruption, extra scripted policies,
|
| 4 |
+
no-injection sanity check, analytic memoryless baselines. Writes results/<task>/controls.json."""
|
| 5 |
+
import sys, json, os, time
|
| 6 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 7 |
+
sys.path.insert(0, ROOT)
|
| 8 |
+
import numpy as np, imageio
|
| 9 |
+
from lffbench import envs
|
| 10 |
+
import lffbench.tasks.l6_count, lffbench.tasks.l6_sequence # noqa
|
| 11 |
+
from lffbench.task_base import TASKS
|
| 12 |
+
name = sys.argv[1]
|
| 13 |
+
n = int(sys.argv[2]) if len(sys.argv) > 2 else 20
|
| 14 |
+
out_dir = os.path.join(ROOT, "results", name)
|
| 15 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 16 |
+
task = TASKS[name](cam_res=384)
|
| 17 |
+
extra = ["skip", "inc1"] if name == "l6_count_into_box" else ["skip"]
|
| 18 |
+
res = dict(task=name, n=n, seeds=list(range(1000, 1000 + n)), extra={}, no_inject={}, analytic={})
|
| 19 |
+
t0 = time.time()
|
| 20 |
+
|
| 21 |
+
# 1) frames right after the interruption (what the agent sees next), seeds 1000-1002, adaptive policy
|
| 22 |
+
def interrupted():
|
| 23 |
+
return (task.slip if name == "l6_count_into_box" else task.stop) is not None
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
for seed in range(1000, 1003):
|
| 27 |
+
inst = task.sample_instance(seed)
|
| 28 |
+
shot = {}
|
| 29 |
+
orig_step = task.env.step
|
| 30 |
+
|
| 31 |
+
def step(a, _o=orig_step):
|
| 32 |
+
r = _o(a)
|
| 33 |
+
if "f" not in shot and interrupted():
|
| 34 |
+
shot["cnt"] = shot.get("cnt", 0) + 1
|
| 35 |
+
if shot["cnt"] >= (4 if name == "l6_count_into_box" else 60): # count: 0.2 s; sequence: arm back home
|
| 36 |
+
shot["f"] = np.concatenate([envs.render(task.env, "agentview", 384),
|
| 37 |
+
envs.render(task.env, "robot0_eye_in_hand", 384)], 1)
|
| 38 |
+
return r
|
| 39 |
+
task.env.step = step
|
| 40 |
+
task.run_scripted("adaptive", inst, k=5, seed=seed)
|
| 41 |
+
task.env.step = orig_step
|
| 42 |
+
if "f" in shot:
|
| 43 |
+
imageio.imwrite(os.path.join(out_dir, f"interrupt_{seed}.png"), shot["f"])
|
| 44 |
+
print("thumbs", f"{time.time()-t0:.0f}s", flush=True)
|
| 45 |
+
|
| 46 |
+
# 2) extra scripted policies
|
| 47 |
+
for kind in extra:
|
| 48 |
+
fs = []
|
| 49 |
+
for i in range(n):
|
| 50 |
+
seed = 1000 + i
|
| 51 |
+
inst = task.sample_instance(seed)
|
| 52 |
+
h = task.run_scripted(kind, inst, k=5, seed=seed)
|
| 53 |
+
s = next((x["attempt"] for x in h if x["outcome"]["success"]), None)
|
| 54 |
+
fs.append(s)
|
| 55 |
+
res["extra"][kind] = dict(first_success=fs, succ_at_k=[float(np.mean([s is not None and s <= j for s in fs])) for j in range(1, 6)])
|
| 56 |
+
print(kind, res["extra"][kind]["succ_at_k"], f"{time.time()-t0:.0f}s", flush=True)
|
| 57 |
+
|
| 58 |
+
# 3) no-injection sanity (oracle + naive, first 10 seeds)
|
| 59 |
+
task.inject = False
|
| 60 |
+
for kind in ("adaptive", "naive"):
|
| 61 |
+
fs = []
|
| 62 |
+
for i in range(10):
|
| 63 |
+
seed = 1000 + i
|
| 64 |
+
inst = task.sample_instance(seed)
|
| 65 |
+
h = task.run_scripted(kind, inst, k=1, seed=seed)
|
| 66 |
+
fs.append(bool(h[0]["outcome"]["success"]))
|
| 67 |
+
res["no_inject"][kind] = float(np.mean(fs))
|
| 68 |
+
print("no inject", kind, res["no_inject"][kind], flush=True)
|
| 69 |
+
task.inject = True
|
| 70 |
+
|
| 71 |
+
# 4) analytic memoryless baselines over the same seeds (perfect execution assumed)
|
| 72 |
+
if name == "l6_count_into_box":
|
| 73 |
+
insts = [task.sample_instance(1000 + i) for i in range(n)]
|
| 74 |
+
res["analytic"]["uniform_guess_0..N-1@1"] = float(np.mean([1 / x["n_target"] for x in insts]))
|
| 75 |
+
best = max(range(0, 6), key=lambda g: np.mean([x["n_target"] - x["p"] == g for x in insts]))
|
| 76 |
+
res["analytic"]["best_fixed_number_to_add@1"] = dict(add=best, rate=float(np.mean([x["n_target"] - x["p"] == best for x in insts])))
|
| 77 |
+
res["analytic"]["p_hist"] = {str(v): int(sum(x["p"] == v for x in insts)) for v in range(1, 6)}
|
| 78 |
+
res["analytic"]["N_hist"] = {str(v): int(sum(x["n_target"] == v for x in insts)) for v in (4, 5)}
|
| 79 |
+
big = [task.sample_instance(5000 + i) for i in range(2000)]
|
| 80 |
+
res["analytic"]["uniform_guess@1_2000inst"] = float(np.mean([1 / x["n_target"] for x in big]))
|
| 81 |
+
res["analytic"]["best_fixed_add@1_2000inst"] = float(max(np.mean([x["n_target"] - x["p"] == g for x in big]) for g in range(1, 5)))
|
| 82 |
+
else:
|
| 83 |
+
insts = [task.sample_instance(1000 + i) for i in range(n)]
|
| 84 |
+
res["analytic"]["w_hist"] = {str(v): int(sum(x["stop_w"] == v for x in insts)) for v in range(1, 5)}
|
| 85 |
+
res["analytic"]["phase_hist"] = {p: int(sum(x["stop_phase"] == p for x in insts)) for p in "AB"}
|
| 86 |
+
res["analytic"]["uniform_guess_0..4@1"] = 0.2
|
| 87 |
+
big = [task.sample_instance(5000 + i) for i in range(2000)]
|
| 88 |
+
res["analytic"]["best_fixed_guess@1_2000inst"] = float(max(np.mean([x["stop_w"] == g for x in big]) for g in range(0, 5)))
|
| 89 |
+
res["analytic"]["skip_expected"] = float(np.mean([x["stop_phase"] == "B" or x["stop_w"] == 3 for x in big]))
|
| 90 |
+
res["seconds"] = time.time() - t0
|
| 91 |
+
json.dump(res, open(os.path.join(out_dir, "controls.json"), "w"), indent=1)
|
| 92 |
+
print(json.dumps(res["analytic"]))
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/mismatch_plan.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mismatched-history control for layer 2 (user 2026-10-27: "错配历史的做一下"; design docs/14 §6 Do / Dm, current protocol).
|
| 2 |
+
|
| 3 |
+
Instances: the 9 hidden-variable tasks that have a twin (l7_key_turn has none), every Claude main-table instance
|
| 4 |
+
(Sonnet 5.5: cc_main1 / cc_sonnet_s2 / cc_sonnet_s3; Opus 5.5: cc_opus1 / cc_opus_s2 / cc_opus_s3) whose attempt 1 failed.
|
| 5 |
+
Arms, all fresh single-attempt agents (= the memory-free retries of the main table) with the same model and CLI:
|
| 6 |
+
tw_<m> twin instance (--arm twin: same layout, the hidden variable takes another value); its failed run is the
|
| 7 |
+
mismatched record. If the twin attempt succeeds there is no record: one more twin run (tw2_<m>), then give up.
|
| 8 |
+
do_<m> own record: history/ = attempt 1 of the instance's main-table history run (scripts/make_dossier.py)
|
| 9 |
+
dm_<m> mismatched record: history/ = the failed twin run. README byte-identical to do_<m>; only history/ differs.
|
| 10 |
+
|
| 11 |
+
python3 scripts/mismatch_plan.py own build own records + write <OUT>/<m>/own.json and tasks_<m>.txt
|
| 12 |
+
python3 scripts/mismatch_plan.py twin <m> build twin records from tw_<m> (+ tw2_<m>) -> <OUT>/<m>/twin.json;
|
| 13 |
+
prints the instances still without a failed twin run
|
| 14 |
+
python3 scripts/mismatch_plan.py report per instance: main-table attempt 2 with history (H2) and first
|
| 15 |
+
memory-free retry (N2), Do, Dm, twin; totals and paired counts
|
| 16 |
+
-> <OUT>/report.json + markdown on stdout
|
| 17 |
+
"""
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import subprocess
|
| 21 |
+
import sys
|
| 22 |
+
|
| 23 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 24 |
+
API = os.path.join(ROOT, "runs", "api")
|
| 25 |
+
OUT = os.path.join(API, "mismatch_20261027")
|
| 26 |
+
TWIN_TASKS = ["l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool",
|
| 27 |
+
"l4_fit_container", "l2_turntable_restore", "l3_card_shelf", "l5_loaded_beam"]
|
| 28 |
+
MAIN = {"opus": ["cc_opus1", "cc_opus_s2", "cc_opus_s3"], "sonnet": ["cc_main1", "cc_sonnet_s2", "cc_sonnet_s3"]}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def runs(batch):
|
| 32 |
+
return json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def attempt1(log):
|
| 36 |
+
for line in open(os.path.join(log, "events.jsonl")):
|
| 37 |
+
e = json.loads(line)
|
| 38 |
+
if e.get("ev") == "done" and e.get("attempt") == 1:
|
| 39 |
+
return e
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def dossier(log, out):
|
| 44 |
+
if not os.path.isdir(out):
|
| 45 |
+
subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, out], check=True,
|
| 46 |
+
capture_output=True)
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def cmd_own():
|
| 51 |
+
for m, batches in MAIN.items():
|
| 52 |
+
own, tasks = {}, []
|
| 53 |
+
for b in batches:
|
| 54 |
+
for r in runs(b):
|
| 55 |
+
if r["cond"] != "harness" or r["task"] not in TWIN_TASKS or r["status"] != "done":
|
| 56 |
+
continue
|
| 57 |
+
d = attempt1(r["log"])
|
| 58 |
+
if d is None or d["success"]:
|
| 59 |
+
continue
|
| 60 |
+
key = f"{r['task']}:{r['seed']}"
|
| 61 |
+
own[key] = dossier(r["log"], os.path.join(OUT, m, "own", f"{r['task']}_s{r['seed']}"))
|
| 62 |
+
tasks.append(key)
|
| 63 |
+
os.makedirs(os.path.join(OUT, m), exist_ok=True)
|
| 64 |
+
json.dump(own, open(os.path.join(OUT, m, "own.json"), "w"), indent=1)
|
| 65 |
+
open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(tasks) + "\n")
|
| 66 |
+
print(m, len(tasks))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def cmd_twin(m):
|
| 70 |
+
want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
|
| 71 |
+
twin = {}
|
| 72 |
+
for b in (f"tw_{m}", f"tw2_{m}"):
|
| 73 |
+
if not os.path.exists(os.path.join(API, b, "manifest.json")):
|
| 74 |
+
continue
|
| 75 |
+
for r in runs(b):
|
| 76 |
+
key = f"{r['task']}:{r['seed']}"
|
| 77 |
+
if key in twin or r["status"] != "done":
|
| 78 |
+
continue
|
| 79 |
+
d = attempt1(r["log"])
|
| 80 |
+
if d is not None and not d["success"]:
|
| 81 |
+
twin[key] = dossier(r["log"], os.path.join(OUT, m, "twin", f"{r['task']}_s{r['seed']}"))
|
| 82 |
+
json.dump(twin, open(os.path.join(OUT, m, "twin.json"), "w"), indent=1)
|
| 83 |
+
print(json.dumps(dict(model=m, with_record=len(twin), missing=[k for k in want if k not in twin])))
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# twin oracle also solves the original instance (docs/14 §6.4, 10-12 validation): mismatch is weak there
|
| 87 |
+
WEAK = {"l3_wall_flush", "l3_under_table_tool"}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def single(batch):
|
| 91 |
+
"""task:seed -> True / False (attempt 1 of the batch's done run), None if not run or not finished."""
|
| 92 |
+
out = {}
|
| 93 |
+
if not os.path.exists(os.path.join(API, batch, "manifest.json")):
|
| 94 |
+
return out
|
| 95 |
+
for r in runs(batch):
|
| 96 |
+
if r["status"] == "done":
|
| 97 |
+
d = attempt1(r["log"])
|
| 98 |
+
out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
|
| 99 |
+
return out
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def main_rows(batches):
|
| 103 |
+
rows = {}
|
| 104 |
+
for b in batches:
|
| 105 |
+
tmp = os.path.join(OUT, f".oc_{b}.json")
|
| 106 |
+
subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "outcomes.py"), "--batch", b, "--json", tmp],
|
| 107 |
+
check=True, capture_output=True)
|
| 108 |
+
for r in json.load(open(tmp))["rows"]:
|
| 109 |
+
rows[f"{r['task']}:{r['seed']}"] = dict(batch=b, history=r["history"], memfree=r["memfree"])
|
| 110 |
+
os.remove(tmp)
|
| 111 |
+
return rows
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def cmd_report():
|
| 115 |
+
rep, md = {}, []
|
| 116 |
+
for m, batches in MAIN.items():
|
| 117 |
+
want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
|
| 118 |
+
main = main_rows(batches)
|
| 119 |
+
do, dm = single(f"do_{m}"), single(f"dm_{m}")
|
| 120 |
+
t1, t2 = single(f"tw_{m}"), single(f"tw2_{m}") # "twin" = F if some twin run failed (a record exists)
|
| 121 |
+
tw = {k: (False if False in (t1.get(k), t2.get(k)) else t1.get(k)) for k in set(t1) | set(t2)}
|
| 122 |
+
rows = []
|
| 123 |
+
for k in want:
|
| 124 |
+
h, mf = main[k]["history"] or "", main[k]["memfree"] or ""
|
| 125 |
+
rows.append(dict(inst=k, task=k.split(":")[0], weak=k.split(":")[0] in WEAK,
|
| 126 |
+
H2=(h[1] == "S") if len(h) > 1 else None, N2=(mf[1] == "S") if len(mf) > 1 and mf[1] in "SF" else None,
|
| 127 |
+
Do=do.get(k), Dm=dm.get(k), twin=tw.get(k)))
|
| 128 |
+
def rate(key, sub):
|
| 129 |
+
v = [r[key] for r in sub if r[key] is not None]
|
| 130 |
+
return f"{sum(v)}/{len(v)}" if v else "-"
|
| 131 |
+
both = [r for r in rows if r["Do"] is not None and r["Dm"] is not None]
|
| 132 |
+
pairs = dict(n=len(both), do_only=sum(r["Do"] and not r["Dm"] for r in both),
|
| 133 |
+
dm_only=sum(r["Dm"] and not r["Do"] for r in both), both=sum(r["Do"] and r["Dm"] for r in both))
|
| 134 |
+
rep[m] = dict(rows=rows, pairs=pairs)
|
| 135 |
+
md += [f"### {m}", "", "| instance | twin run | H2 (history, main) | N2 (memory-free, main) | Do (own record) | Dm (twin record) |",
|
| 136 |
+
"|---|---|---|---|---|---|"]
|
| 137 |
+
f = lambda v: "-" if v is None else ("S" if v else "F")
|
| 138 |
+
for r in rows:
|
| 139 |
+
md.append(f"| {r['inst']}{' (weak)' if r['weak'] else ''} | {f(r['twin'])} | {f(r['H2'])} | {f(r['N2'])} | {f(r['Do'])} | {f(r['Dm'])} |")
|
| 140 |
+
strong = [r for r in rows if not r["weak"]]
|
| 141 |
+
md += ["", f"all: H2 {rate('H2', rows)}, N2 {rate('N2', rows)}, Do {rate('Do', rows)}, Dm {rate('Dm', rows)}; "
|
| 142 |
+
f"strong mismatch only: Do {rate('Do', strong)}, Dm {rate('Dm', strong)}; "
|
| 143 |
+
f"paired Do/Dm n={pairs['n']}: Do only {pairs['do_only']}, Dm only {pairs['dm_only']}, both {pairs['both']}", ""]
|
| 144 |
+
json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
|
| 145 |
+
print("\n".join(md))
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
{"own": lambda: cmd_own(), "twin": lambda: cmd_twin(sys.argv[2]), "report": lambda: cmd_report()}[sys.argv[1]]()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_sonnet/lff/source_closure/scripts/outcomes.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-instance outcomes of api_batch.py --memfree followup batches, in the paper's terms (paper/01 §4 3.6):
|
| 2 |
+
|
| 3 |
+
CS attempt 1 succeeded with no error event in it IR attempt 1 succeeded after an error event (repaired
|
| 4 |
+
XR attempt 1 failed, a later attempt succeeded within the attempt)
|
| 5 |
+
F no attempt succeeded S? attempt 1 succeeded, but the task logs no error events
|
| 6 |
+
(CS or IR cannot be told apart)
|
| 7 |
+
A1 = CS + IR (+ S?), A3 = A1 + XR (history condition); pass@k = the memory-free chain (attempt 1 shared with the
|
| 8 |
+
history run, then fresh agents) succeeded; delta = A3 - pass@k, paired per instance. Tasks whose scene persists
|
| 9 |
+
between attempts (protocol "within") have no memory-free chain and are listed apart (user 2026-10-20).
|
| 10 |
+
|
| 11 |
+
python scripts/outcomes.py --batch cx_main1 [--batch ...] [--json out.json]
|
| 12 |
+
|
| 13 |
+
An error event is read from the task's outcome dict of the successful attempt: trap_fired / recovered_in_attempt
|
| 14 |
+
true, or one of the n_* counters of mistakes (n_bad_pushes, n_wrong_way, n_regressions, n_load_falls, ...) above 0.
|
| 15 |
+
The finish reason of every failed attempt is printed so that false success claims can be judged (not judged here).
|
| 16 |
+
"""
|
| 17 |
+
import argparse
|
| 18 |
+
import ast
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 24 |
+
import api_batch # noqa: E402
|
| 25 |
+
|
| 26 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 27 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 28 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def attempts(log):
|
| 32 |
+
"""[(attempt, success, outcome dict, finish reason)] from the robot server log."""
|
| 33 |
+
out = []
|
| 34 |
+
p = os.path.join(log or "", "events.jsonl")
|
| 35 |
+
if not os.path.exists(p):
|
| 36 |
+
return out
|
| 37 |
+
for line in open(p):
|
| 38 |
+
e = json.loads(line)
|
| 39 |
+
if e.get("ev") != "done":
|
| 40 |
+
continue
|
| 41 |
+
o = e.get("outcome") or {}
|
| 42 |
+
if isinstance(o, str):
|
| 43 |
+
try:
|
| 44 |
+
o = ast.literal_eval(o)
|
| 45 |
+
except (ValueError, SyntaxError):
|
| 46 |
+
o = {}
|
| 47 |
+
out.append((int(e["attempt"]), e["success"] in (True, "True"), o, e.get("reason") or ""))
|
| 48 |
+
return sorted(out, key=lambda x: x[0])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def error_event(o):
|
| 52 |
+
"""True / False if the outcome dict says whether an error happened, None if the task logs no error events."""
|
| 53 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 54 |
+
if not keys:
|
| 55 |
+
return None
|
| 56 |
+
return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def instance_rows(m, audit=None, batch=None):
|
| 60 |
+
rows = []
|
| 61 |
+
for r in m["runs"]:
|
| 62 |
+
if not (r["cond"] == "harness" and r.get("followup")) or r["status"] != "done":
|
| 63 |
+
continue
|
| 64 |
+
att = attempts(r.get("log"))
|
| 65 |
+
if not att:
|
| 66 |
+
continue
|
| 67 |
+
if audit is not None and att[0][0] != 1:
|
| 68 |
+
raise ValueError(f"Cannot audit {r['task']}: first-attempt record is missing")
|
| 69 |
+
hist = "".join("S" if s else "F" for _, s, _, _ in att)
|
| 70 |
+
if att[0][1]:
|
| 71 |
+
ev = error_event(att[0][2])
|
| 72 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 73 |
+
else:
|
| 74 |
+
cls = "XR" if any(s for _, s, _, _ in att) else "F"
|
| 75 |
+
legacy_cls = cls
|
| 76 |
+
audit_basis = None
|
| 77 |
+
if audit is not None and att[0][1]:
|
| 78 |
+
from outcome_audit import adjudicate
|
| 79 |
+
cls, audit_basis = adjudicate(audit, batch, r, True)
|
| 80 |
+
within = api_batch.episode_protocol(r.get("log")) == "within"
|
| 81 |
+
chain = sorted((x for x in m["runs"] if x.get("chain") == r["id"]), key=lambda x: x["rep"])
|
| 82 |
+
mf = None
|
| 83 |
+
if not within:
|
| 84 |
+
mf = hist[0] + "".join("S" if any(api_batch.attempt_results(x.get("log"))) else
|
| 85 |
+
("F" if x["status"] == "done" else "?") for x in chain)
|
| 86 |
+
failed = [(a, reason) for a, s, _, reason in att if not s]
|
| 87 |
+
failed += [(f"mf{x['rep'] + 1}", rr) for x in chain for _, s, _, rr in attempts(x.get("log")) if not s]
|
| 88 |
+
rows.append(dict(task=r["task"], seed=r["seed"], cls=cls, legacy_cls=legacy_cls,
|
| 89 |
+
batch=batch, run_id=r["id"], audit_basis=audit_basis,
|
| 90 |
+
history=hist, memfree=mf, within=within,
|
| 91 |
+
a1=att[0][1], a3=any(s for _, s, _, _ in att),
|
| 92 |
+
passk=None if mf is None else ("S" in mf), failed_reasons=failed))
|
| 93 |
+
return rows
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def summary(rows):
|
| 97 |
+
n = len(rows)
|
| 98 |
+
paired = [x for x in rows if x["passk"] is not None and "?" not in (x["memfree"] or "")]
|
| 99 |
+
cnt = {c: sum(1 for x in rows if x["cls"] == c) for c in ("CS", "IR", "S?", "XR", "F")}
|
| 100 |
+
return dict(n=n, **cnt, A1=sum(x["a1"] for x in rows), A3=sum(x["a3"] for x in rows), n_paired=len(paired),
|
| 101 |
+
A3_paired=sum(x["a3"] for x in paired), passk_paired=sum(x["passk"] for x in paired),
|
| 102 |
+
delta_paired=(sum(x["a3"] for x in paired) - sum(x["passk"] for x in paired)) / max(1, len(paired)))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def main():
|
| 106 |
+
ap = argparse.ArgumentParser()
|
| 107 |
+
ap.add_argument("--batch", action="append", required=True)
|
| 108 |
+
ap.add_argument("--json", default=None)
|
| 109 |
+
ap.add_argument("--runs-root", help="read manifests from another checkout's runs/api directory")
|
| 110 |
+
ap.add_argument("--audit", help="hash-bound reviewed classifications (unreviewed first successes remain S?)")
|
| 111 |
+
a = ap.parse_args()
|
| 112 |
+
if a.runs_root:
|
| 113 |
+
api_batch.RUNS = os.path.abspath(a.runs_root)
|
| 114 |
+
audit = None
|
| 115 |
+
if a.audit:
|
| 116 |
+
from outcome_audit import load_audit
|
| 117 |
+
audit = load_audit(a.audit)
|
| 118 |
+
rows = []
|
| 119 |
+
for b in a.batch:
|
| 120 |
+
rows += instance_rows(api_batch.load(b), audit=audit, batch=b)
|
| 121 |
+
print("Classification: " + ("reviewed evidence (see audit sources)" if audit is not None else
|
| 122 |
+
"legacy task-counter heuristic; CS/IR coverage is task-dependent"))
|
| 123 |
+
print("| task | seed | outcome | history | memory-free | note |\n|---|---|---|---|---|---|")
|
| 124 |
+
for x in rows:
|
| 125 |
+
print(f"| {x['task']} | {x['seed']} | {x['cls']} | {x['history']} | {x['memfree'] or '—'} | "
|
| 126 |
+
f"{'scene persists: no memory-free chain' if x['within'] else ''} |")
|
| 127 |
+
s = summary(rows)
|
| 128 |
+
print(f"\nn={s['n']} CS={s['CS']} IR={s['IR']} S?={s['S?']} XR={s['XR']} F={s['F']} A1={s['A1']}/{s['n']} "
|
| 129 |
+
f"A3={s['A3']}/{s['n']} paired (no persisting scene, chain finished): n={s['n_paired']} "
|
| 130 |
+
f"A3={s['A3_paired']} pass@k={s['passk_paired']} delta={s['delta_paired']:+.3f}")
|
| 131 |
+
print("\nfinish reasons of failed attempts (for judging false success claims):")
|
| 132 |
+
for x in rows:
|
| 133 |
+
for att, reason in x["failed_reasons"]:
|
| 134 |
+
print(f" {x['task']} {att}: {reason[:160]}")
|
| 135 |
+
if a.json:
|
| 136 |
+
with open(a.json, "w") as f:
|
| 137 |
+
json.dump(dict(rows=rows, summary=s), f, indent=1, ensure_ascii=False)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|high",
|
| 3 |
+
"fingerprint_sha256": "41fecee198c38459b5fae54c29ebf99c368e60381b3f11418dea02590bba5222",
|
| 4 |
+
"written": "2026-10-20 02:33:15",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 16979,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"list_mcp_resource_templates",
|
| 9 |
+
"list_mcp_resources",
|
| 10 |
+
"mcp__lff.robot",
|
| 11 |
+
"mcp__lff.shell",
|
| 12 |
+
"mcp__lff.view_images",
|
| 13 |
+
"read_mcp_resource",
|
| 14 |
+
"request_user_input"
|
| 15 |
+
],
|
| 16 |
+
"effort_in_request": "high",
|
| 17 |
+
"model_in_request": "gpt-6-astra",
|
| 18 |
+
"sandbox": {
|
| 19 |
+
"sandbox": "seccomp",
|
| 20 |
+
"sandbox_mode": "read-only"
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/scripts/qwen_vl_server.py
ADDED
|
@@ -0,0 +1,535 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Minimal OpenAI-compatible Chat Completions server (with tool calling) for Qwen3-VL.
|
| 3 |
+
|
| 4 |
+
Runs a local HF-format Qwen3-VL checkpoint with transformers (>= 4.57) on one
|
| 5 |
+
CUDA-compatible device (here: Alibaba PPU) and exposes:
|
| 6 |
+
|
| 7 |
+
POST /v1/chat/completions OpenAI chat.completion (non-streaming; stream=true
|
| 8 |
+
is emulated: the full answer is generated first
|
| 9 |
+
and then sent as SSE chunks)
|
| 10 |
+
GET /v1/models lists the single served model
|
| 11 |
+
GET /health liveness + device memory
|
| 12 |
+
|
| 13 |
+
Request format accepted (subset of OpenAI):
|
| 14 |
+
messages: system / developer / user / assistant (with tool_calls) / tool
|
| 15 |
+
user/tool content may be a string or a list of
|
| 16 |
+
{"type":"text","text":...} and
|
| 17 |
+
{"type":"image_url","image_url":{"url": "data:image/...;base64,..." | http(s) URL | file path}}
|
| 18 |
+
tools: [{"type":"function","function":{"name","description","parameters"}}]
|
| 19 |
+
tool_choice: "auto" (default) | "none" (tools hidden from the prompt) |
|
| 20 |
+
"required" (generation is prefixed with "<tool_call>\n") |
|
| 21 |
+
{"type":"function","function":{"name":X}} (prefixed with the call header for X)
|
| 22 |
+
parallel_tool_calls: false -> only the first parsed tool call is returned
|
| 23 |
+
max_tokens / max_completion_tokens (default --default-max-tokens, 1024)
|
| 24 |
+
temperature (absent or 0 -> greedy), top_p, top_k, seed, stop (str or list)
|
| 25 |
+
Ignored: n (always 1), response_format, logprobs, presence/frequency penalty, user.
|
| 26 |
+
|
| 27 |
+
The model emits Hermes-style <tool_call>{"name":..., "arguments":{...}}</tool_call>
|
| 28 |
+
blocks; they are parsed into choices[0].message.tool_calls with arguments as a JSON
|
| 29 |
+
string, and the remaining text (if any) becomes message.content (else null).
|
| 30 |
+
|
| 31 |
+
Generation is serialised with a lock (one request on the device at a time); the
|
| 32 |
+
HTTP layer is a stdlib ThreadingHTTPServer so /health stays responsive.
|
| 33 |
+
"""
|
| 34 |
+
from __future__ import annotations
|
| 35 |
+
|
| 36 |
+
import argparse
|
| 37 |
+
import base64
|
| 38 |
+
import io
|
| 39 |
+
import json
|
| 40 |
+
import logging
|
| 41 |
+
import os
|
| 42 |
+
import re
|
| 43 |
+
import sys
|
| 44 |
+
import threading
|
| 45 |
+
import time
|
| 46 |
+
import traceback
|
| 47 |
+
import urllib.request
|
| 48 |
+
import uuid
|
| 49 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 50 |
+
|
| 51 |
+
LOG = logging.getLogger("qwen_vl_server")
|
| 52 |
+
|
| 53 |
+
TOOL_CALL_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)
|
| 54 |
+
END_MARKERS = ("<|im_end|>", "<|endoftext|>")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ----------------------------------------------------------------------------
|
| 58 |
+
# Request conversion
|
| 59 |
+
# ----------------------------------------------------------------------------
|
| 60 |
+
class BadRequest(Exception):
|
| 61 |
+
pass
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def load_image(url: str):
|
| 65 |
+
from PIL import Image
|
| 66 |
+
|
| 67 |
+
if url.startswith("data:"):
|
| 68 |
+
try:
|
| 69 |
+
_, b64 = url.split(",", 1)
|
| 70 |
+
except ValueError as e:
|
| 71 |
+
raise BadRequest("malformed data URL") from e
|
| 72 |
+
raw = base64.b64decode(b64)
|
| 73 |
+
elif url.startswith("http://") or url.startswith("https://"):
|
| 74 |
+
with urllib.request.urlopen(url, timeout=30) as r:
|
| 75 |
+
raw = r.read()
|
| 76 |
+
else:
|
| 77 |
+
path = url[len("file://"):] if url.startswith("file://") else url
|
| 78 |
+
with open(path, "rb") as f:
|
| 79 |
+
raw = f.read()
|
| 80 |
+
img = Image.open(io.BytesIO(raw))
|
| 81 |
+
img.load()
|
| 82 |
+
return img.convert("RGB")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def convert_content(content, images: list):
|
| 86 |
+
"""OpenAI content (str | list[part] | None) -> Qwen template content.
|
| 87 |
+
|
| 88 |
+
Images are replaced by {"type": "image"} placeholders and the decoded PIL images
|
| 89 |
+
are appended to `images` in prompt order (the chat template emits one
|
| 90 |
+
<|vision_start|><|image_pad|><|vision_end|> per placeholder, in the same order).
|
| 91 |
+
"""
|
| 92 |
+
if content is None:
|
| 93 |
+
return ""
|
| 94 |
+
if isinstance(content, str):
|
| 95 |
+
return content
|
| 96 |
+
if not isinstance(content, list):
|
| 97 |
+
raise BadRequest(f"unsupported content type: {type(content).__name__}")
|
| 98 |
+
out = []
|
| 99 |
+
for part in content:
|
| 100 |
+
if isinstance(part, str):
|
| 101 |
+
out.append({"type": "text", "text": part})
|
| 102 |
+
continue
|
| 103 |
+
ptype = part.get("type")
|
| 104 |
+
if ptype in ("text", "input_text"):
|
| 105 |
+
out.append({"type": "text", "text": part.get("text", "")})
|
| 106 |
+
elif ptype in ("image_url", "input_image", "image"):
|
| 107 |
+
iu = part.get("image_url", part.get("image"))
|
| 108 |
+
url = iu.get("url") if isinstance(iu, dict) else iu
|
| 109 |
+
if not isinstance(url, str):
|
| 110 |
+
raise BadRequest("image part without url")
|
| 111 |
+
try:
|
| 112 |
+
images.append(load_image(url))
|
| 113 |
+
except BadRequest:
|
| 114 |
+
raise
|
| 115 |
+
except Exception as e: # noqa: BLE001
|
| 116 |
+
raise BadRequest(f"could not load image ({url[:60]}...): {type(e).__name__}: {e}") from e
|
| 117 |
+
out.append({"type": "image"})
|
| 118 |
+
else:
|
| 119 |
+
raise BadRequest(f"unsupported content part type: {ptype}")
|
| 120 |
+
return out
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def text_only(content) -> str:
|
| 124 |
+
if content is None:
|
| 125 |
+
return ""
|
| 126 |
+
if isinstance(content, str):
|
| 127 |
+
return content
|
| 128 |
+
return "".join(p.get("text", "") for p in content if isinstance(p, dict))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def convert_messages(messages: list):
|
| 132 |
+
if not isinstance(messages, list) or not messages:
|
| 133 |
+
raise BadRequest("messages must be a non-empty list")
|
| 134 |
+
images: list = []
|
| 135 |
+
system_texts = []
|
| 136 |
+
conv = []
|
| 137 |
+
for m in messages:
|
| 138 |
+
role = m.get("role")
|
| 139 |
+
if role in ("system", "developer"):
|
| 140 |
+
# The Qwen template only renders a leading system message; merge all of them.
|
| 141 |
+
system_texts.append(text_only(m.get("content")))
|
| 142 |
+
elif role == "user":
|
| 143 |
+
conv.append({"role": "user", "content": convert_content(m.get("content"), images)})
|
| 144 |
+
elif role == "assistant":
|
| 145 |
+
c = m.get("content")
|
| 146 |
+
msg = {"role": "assistant", "content": text_only(c) if not isinstance(c, str) else c}
|
| 147 |
+
tcs = m.get("tool_calls") or []
|
| 148 |
+
if tcs:
|
| 149 |
+
norm = []
|
| 150 |
+
for tc in tcs:
|
| 151 |
+
fn = tc.get("function", tc)
|
| 152 |
+
args = fn.get("arguments", {})
|
| 153 |
+
if not isinstance(args, str):
|
| 154 |
+
args = json.dumps(args, ensure_ascii=False)
|
| 155 |
+
norm.append({"type": "function", "function": {"name": fn.get("name", ""), "arguments": args}})
|
| 156 |
+
msg["tool_calls"] = norm
|
| 157 |
+
conv.append(msg)
|
| 158 |
+
elif role in ("tool", "function"):
|
| 159 |
+
conv.append({"role": "tool", "content": convert_content(m.get("content"), images)})
|
| 160 |
+
else:
|
| 161 |
+
raise BadRequest(f"unsupported role: {role}")
|
| 162 |
+
if system_texts:
|
| 163 |
+
conv.insert(0, {"role": "system", "content": "\n\n".join(system_texts)})
|
| 164 |
+
return conv, images
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# ----------------------------------------------------------------------------
|
| 168 |
+
# Output parsing
|
| 169 |
+
# ----------------------------------------------------------------------------
|
| 170 |
+
def _loads_lenient(s: str):
|
| 171 |
+
s = s.strip()
|
| 172 |
+
try:
|
| 173 |
+
return json.loads(s)
|
| 174 |
+
except json.JSONDecodeError:
|
| 175 |
+
pass
|
| 176 |
+
# common slips: trailing garbage after the object, missing final brace
|
| 177 |
+
start = s.find("{")
|
| 178 |
+
if start >= 0:
|
| 179 |
+
dec = json.JSONDecoder()
|
| 180 |
+
try:
|
| 181 |
+
obj, _ = dec.raw_decode(s[start:])
|
| 182 |
+
return obj
|
| 183 |
+
except json.JSONDecodeError:
|
| 184 |
+
pass
|
| 185 |
+
for extra in ("}", "}}", "\"}}"):
|
| 186 |
+
try:
|
| 187 |
+
return json.loads(s[start:] + extra)
|
| 188 |
+
except json.JSONDecodeError:
|
| 189 |
+
continue
|
| 190 |
+
return None
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def parse_tool_calls(text: str):
|
| 194 |
+
"""Return (content_or_None, tool_calls_list)."""
|
| 195 |
+
calls = []
|
| 196 |
+
spans = []
|
| 197 |
+
for mt in TOOL_CALL_RE.finditer(text):
|
| 198 |
+
spans.append(mt.span())
|
| 199 |
+
calls.append(mt.group(1))
|
| 200 |
+
# an unterminated trailing <tool_call> (e.g. hit max_tokens / model forgot the tag)
|
| 201 |
+
last_end = spans[-1][1] if spans else 0
|
| 202 |
+
tail_idx = text.find("<tool_call>", last_end)
|
| 203 |
+
if tail_idx >= 0:
|
| 204 |
+
spans.append((tail_idx, len(text)))
|
| 205 |
+
calls.append(text[tail_idx + len("<tool_call>"):])
|
| 206 |
+
|
| 207 |
+
tool_calls = []
|
| 208 |
+
keep_raw = [] # unparsable blocks stay in content
|
| 209 |
+
for (a, b), body in zip(spans, calls):
|
| 210 |
+
obj = _loads_lenient(body)
|
| 211 |
+
if not isinstance(obj, dict) or "name" not in obj:
|
| 212 |
+
keep_raw.append((a, b))
|
| 213 |
+
continue
|
| 214 |
+
args = obj.get("arguments", obj.get("parameters", {}))
|
| 215 |
+
if isinstance(args, str):
|
| 216 |
+
parsed = _loads_lenient(args)
|
| 217 |
+
args_str = json.dumps(parsed, ensure_ascii=False) if parsed is not None else args
|
| 218 |
+
else:
|
| 219 |
+
args_str = json.dumps(args, ensure_ascii=False)
|
| 220 |
+
tool_calls.append({
|
| 221 |
+
"id": "call_" + uuid.uuid4().hex[:24],
|
| 222 |
+
"type": "function",
|
| 223 |
+
"function": {"name": str(obj["name"]), "arguments": args_str},
|
| 224 |
+
})
|
| 225 |
+
|
| 226 |
+
# content = text with successfully parsed blocks removed
|
| 227 |
+
parsed_spans = [s for s in spans if s not in keep_raw]
|
| 228 |
+
pieces, pos = [], 0
|
| 229 |
+
for a, b in sorted(parsed_spans):
|
| 230 |
+
pieces.append(text[pos:a])
|
| 231 |
+
pos = b
|
| 232 |
+
pieces.append(text[pos:])
|
| 233 |
+
content = "".join(pieces).strip()
|
| 234 |
+
return (content if content else None), tool_calls
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# ----------------------------------------------------------------------------
|
| 238 |
+
# Model wrapper
|
| 239 |
+
# ----------------------------------------------------------------------------
|
| 240 |
+
class Engine:
|
| 241 |
+
def __init__(self, args):
|
| 242 |
+
import torch
|
| 243 |
+
from transformers import AutoModelForImageTextToText, AutoProcessor
|
| 244 |
+
|
| 245 |
+
self.torch = torch
|
| 246 |
+
self.args = args
|
| 247 |
+
self.device = args.device
|
| 248 |
+
t0 = time.time()
|
| 249 |
+
proc_kwargs = {}
|
| 250 |
+
if args.min_pixels:
|
| 251 |
+
proc_kwargs["min_pixels"] = args.min_pixels
|
| 252 |
+
if args.max_pixels:
|
| 253 |
+
proc_kwargs["max_pixels"] = args.max_pixels
|
| 254 |
+
if args.attn == "sdpa" and not args.sdpa_native_gqa:
|
| 255 |
+
# PPU quirk (measured): torch SDPA with enable_gqa=True fails for decode steps
|
| 256 |
+
# (q_len=1, no mask) with "q must have shape (batch_size, seqlen_q, num_heads,
|
| 257 |
+
# head_size_og)". Make transformers repeat K/V heads itself instead.
|
| 258 |
+
import transformers.integrations.sdpa_attention as _sdpa
|
| 259 |
+
|
| 260 |
+
_sdpa.use_gqa_in_sdpa = lambda attention_mask, key: False
|
| 261 |
+
self.processor = AutoProcessor.from_pretrained(args.model, **proc_kwargs)
|
| 262 |
+
self.tokenizer = self.processor.tokenizer
|
| 263 |
+
self.model = AutoModelForImageTextToText.from_pretrained(
|
| 264 |
+
args.model,
|
| 265 |
+
dtype=torch.bfloat16,
|
| 266 |
+
attn_implementation=args.attn,
|
| 267 |
+
device_map={"": self.device},
|
| 268 |
+
).eval()
|
| 269 |
+
self.load_time = time.time() - t0
|
| 270 |
+
self.eos_ids = [self.tokenizer.convert_tokens_to_ids(t) for t in END_MARKERS]
|
| 271 |
+
self.eos_ids = [i for i in self.eos_ids if isinstance(i, int) and i >= 0]
|
| 272 |
+
self.pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.eos_ids[-1]
|
| 273 |
+
self.lock = threading.Lock()
|
| 274 |
+
LOG.info("model loaded in %.1fs on %s (attn=%s); mem allocated %.2f GiB",
|
| 275 |
+
self.load_time, self.device, args.attn, torch.cuda.memory_allocated(self.device) / 2**30)
|
| 276 |
+
|
| 277 |
+
def mem(self):
|
| 278 |
+
t = self.torch
|
| 279 |
+
return {
|
| 280 |
+
"allocated_gib": round(t.cuda.memory_allocated(self.device) / 2**30, 2),
|
| 281 |
+
"reserved_gib": round(t.cuda.memory_reserved(self.device) / 2**30, 2),
|
| 282 |
+
"max_allocated_gib": round(t.cuda.max_memory_allocated(self.device) / 2**30, 2),
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
def chat(self, req: dict):
|
| 286 |
+
torch = self.torch
|
| 287 |
+
a = self.args
|
| 288 |
+
messages, images = convert_messages(req.get("messages"))
|
| 289 |
+
tools = req.get("tools") or None
|
| 290 |
+
tool_choice = req.get("tool_choice", "auto")
|
| 291 |
+
prefix = ""
|
| 292 |
+
if tools:
|
| 293 |
+
if tool_choice == "none":
|
| 294 |
+
tools = None
|
| 295 |
+
elif tool_choice == "required":
|
| 296 |
+
prefix = "<tool_call>\n"
|
| 297 |
+
elif isinstance(tool_choice, dict):
|
| 298 |
+
fname = (tool_choice.get("function") or {}).get("name") or tool_choice.get("name")
|
| 299 |
+
if fname:
|
| 300 |
+
prefix = '<tool_call>\n{"name": "' + fname + '", "arguments": '
|
| 301 |
+
tmpl_tools = None
|
| 302 |
+
if tools:
|
| 303 |
+
tmpl_tools = []
|
| 304 |
+
for t in tools:
|
| 305 |
+
if isinstance(t, dict) and "function" not in t and "name" in t:
|
| 306 |
+
t = {"type": "function", "function": t}
|
| 307 |
+
tmpl_tools.append(t)
|
| 308 |
+
|
| 309 |
+
prompt = self.processor.apply_chat_template(
|
| 310 |
+
messages, tools=tmpl_tools, tokenize=False, add_generation_prompt=True
|
| 311 |
+
) + prefix
|
| 312 |
+
inputs = self.processor(
|
| 313 |
+
text=[prompt], images=images if images else None, return_tensors="pt"
|
| 314 |
+
).to(self.device)
|
| 315 |
+
n_prompt = int(inputs["input_ids"].shape[1])
|
| 316 |
+
if n_prompt > a.max_prompt_tokens:
|
| 317 |
+
raise BadRequest(f"prompt has {n_prompt} tokens > --max-prompt-tokens {a.max_prompt_tokens}")
|
| 318 |
+
|
| 319 |
+
max_new = req.get("max_completion_tokens") or req.get("max_tokens") or a.default_max_tokens
|
| 320 |
+
max_new = int(min(max_new, a.max_tokens_cap))
|
| 321 |
+
temperature = req.get("temperature")
|
| 322 |
+
if temperature is None:
|
| 323 |
+
temperature = a.default_temperature
|
| 324 |
+
gen_kwargs = dict(
|
| 325 |
+
max_new_tokens=max_new,
|
| 326 |
+
eos_token_id=self.eos_ids,
|
| 327 |
+
pad_token_id=self.pad_id,
|
| 328 |
+
use_cache=True,
|
| 329 |
+
)
|
| 330 |
+
if temperature and float(temperature) > 0:
|
| 331 |
+
gen_kwargs.update(do_sample=True, temperature=float(temperature),
|
| 332 |
+
top_p=float(req.get("top_p") or 0.8), top_k=int(req.get("top_k") or 20))
|
| 333 |
+
else:
|
| 334 |
+
gen_kwargs.update(do_sample=False, temperature=None, top_p=None, top_k=None)
|
| 335 |
+
if req.get("seed") is not None:
|
| 336 |
+
torch.manual_seed(int(req["seed"]))
|
| 337 |
+
|
| 338 |
+
with torch.inference_mode():
|
| 339 |
+
out = self.model.generate(**inputs, **gen_kwargs)
|
| 340 |
+
new_ids = out[0, n_prompt:].tolist()
|
| 341 |
+
# count tokens up to and including the first EOS
|
| 342 |
+
n_completion = len(new_ids)
|
| 343 |
+
hit_eos = False
|
| 344 |
+
for i, tid in enumerate(new_ids):
|
| 345 |
+
if tid in self.eos_ids:
|
| 346 |
+
n_completion = i + 1
|
| 347 |
+
hit_eos = True
|
| 348 |
+
break
|
| 349 |
+
text = self.tokenizer.decode(new_ids[:n_completion], skip_special_tokens=False)
|
| 350 |
+
for mk in END_MARKERS:
|
| 351 |
+
text = text.replace(mk, "")
|
| 352 |
+
text = prefix + text
|
| 353 |
+
|
| 354 |
+
stop = req.get("stop")
|
| 355 |
+
stopped_by_str = False
|
| 356 |
+
if stop:
|
| 357 |
+
for s in ([stop] if isinstance(stop, str) else stop):
|
| 358 |
+
k = text.find(s, len(prefix))
|
| 359 |
+
if k >= 0:
|
| 360 |
+
text = text[:k]
|
| 361 |
+
stopped_by_str = True
|
| 362 |
+
|
| 363 |
+
if tools:
|
| 364 |
+
content, tool_calls = parse_tool_calls(text)
|
| 365 |
+
if tool_calls and req.get("parallel_tool_calls") is False:
|
| 366 |
+
tool_calls = tool_calls[:1]
|
| 367 |
+
else:
|
| 368 |
+
content, tool_calls = (text.strip() or None), []
|
| 369 |
+
|
| 370 |
+
if tool_calls:
|
| 371 |
+
finish = "tool_calls"
|
| 372 |
+
elif hit_eos or stopped_by_str:
|
| 373 |
+
finish = "stop"
|
| 374 |
+
else:
|
| 375 |
+
finish = "length"
|
| 376 |
+
message = {"role": "assistant", "content": content}
|
| 377 |
+
if tool_calls:
|
| 378 |
+
message["tool_calls"] = tool_calls
|
| 379 |
+
usage = {"prompt_tokens": n_prompt, "completion_tokens": n_completion,
|
| 380 |
+
"total_tokens": n_prompt + n_completion}
|
| 381 |
+
return message, finish, usage, len(images), text
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
# ----------------------------------------------------------------------------
|
| 385 |
+
# HTTP
|
| 386 |
+
# ----------------------------------------------------------------------------
|
| 387 |
+
ENGINE: Engine | None = None
|
| 388 |
+
ARGS = None
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
class Handler(BaseHTTPRequestHandler):
|
| 392 |
+
protocol_version = "HTTP/1.1"
|
| 393 |
+
|
| 394 |
+
def log_message(self, fmt, *args): # route http.server logs through logging
|
| 395 |
+
LOG.debug("%s - %s", self.address_string(), fmt % args)
|
| 396 |
+
|
| 397 |
+
def _send_json(self, code: int, obj):
|
| 398 |
+
body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
| 399 |
+
self.send_response(code)
|
| 400 |
+
self.send_header("Content-Type", "application/json")
|
| 401 |
+
self.send_header("Content-Length", str(len(body)))
|
| 402 |
+
self.end_headers()
|
| 403 |
+
self.wfile.write(body)
|
| 404 |
+
|
| 405 |
+
def _error(self, code: int, msg: str, etype: str):
|
| 406 |
+
self._send_json(code, {"error": {"message": msg, "type": etype, "code": code}})
|
| 407 |
+
|
| 408 |
+
def do_GET(self):
|
| 409 |
+
if self.path.rstrip("/") in ("/health", "/v1/health"):
|
| 410 |
+
self._send_json(200, {"status": "ok", "model": ARGS.served_name, "memory": ENGINE.mem(),
|
| 411 |
+
"load_time_s": round(ENGINE.load_time, 1)})
|
| 412 |
+
elif self.path.rstrip("/") == "/v1/models":
|
| 413 |
+
self._send_json(200, {"object": "list", "data": [
|
| 414 |
+
{"id": ARGS.served_name, "object": "model", "created": int(time.time()), "owned_by": "local"}]})
|
| 415 |
+
else:
|
| 416 |
+
self._error(404, f"no route {self.path}", "not_found")
|
| 417 |
+
|
| 418 |
+
def do_POST(self):
|
| 419 |
+
if self.path.rstrip("/") not in ("/v1/chat/completions", "/chat/completions"):
|
| 420 |
+
self._error(404, f"no route {self.path}", "not_found")
|
| 421 |
+
return
|
| 422 |
+
try:
|
| 423 |
+
n = int(self.headers.get("Content-Length", "0"))
|
| 424 |
+
req = json.loads(self.rfile.read(n).decode("utf-8"))
|
| 425 |
+
except Exception as e: # noqa: BLE001
|
| 426 |
+
self._error(400, f"invalid JSON body: {e}", "invalid_request_error")
|
| 427 |
+
return
|
| 428 |
+
t0 = time.time()
|
| 429 |
+
try:
|
| 430 |
+
with ENGINE.lock:
|
| 431 |
+
t_lock = time.time()
|
| 432 |
+
message, finish, usage, n_img, raw = ENGINE.chat(req)
|
| 433 |
+
except BadRequest as e:
|
| 434 |
+
self._error(400, str(e), "invalid_request_error")
|
| 435 |
+
return
|
| 436 |
+
except Exception as e: # noqa: BLE001
|
| 437 |
+
LOG.error("generation failed: %s\n%s", e, traceback.format_exc())
|
| 438 |
+
if "out of memory" in str(e).lower():
|
| 439 |
+
try:
|
| 440 |
+
ENGINE.torch.cuda.empty_cache()
|
| 441 |
+
except Exception: # noqa: BLE001
|
| 442 |
+
pass
|
| 443 |
+
self._error(500, f"{type(e).__name__}: {e}", "server_error")
|
| 444 |
+
return
|
| 445 |
+
dt = time.time() - t0
|
| 446 |
+
LOG.info("req images=%d prompt=%d completion=%d finish=%s tool_calls=%d queue=%.2fs gen=%.2fs mem=%s",
|
| 447 |
+
n_img, usage["prompt_tokens"], usage["completion_tokens"], finish,
|
| 448 |
+
len(message.get("tool_calls", [])), t_lock - t0, time.time() - t_lock, ENGINE.mem())
|
| 449 |
+
if ARGS.log_outputs:
|
| 450 |
+
LOG.info("raw output: %r", raw)
|
| 451 |
+
cid = "chatcmpl-" + uuid.uuid4().hex[:24]
|
| 452 |
+
created = int(time.time())
|
| 453 |
+
model_name = req.get("model") or ARGS.served_name
|
| 454 |
+
if req.get("stream"):
|
| 455 |
+
self._send_stream(cid, created, model_name, message, finish, usage, req)
|
| 456 |
+
return
|
| 457 |
+
self._send_json(200, {
|
| 458 |
+
"id": cid,
|
| 459 |
+
"object": "chat.completion",
|
| 460 |
+
"created": created,
|
| 461 |
+
"model": model_name,
|
| 462 |
+
"choices": [{"index": 0, "message": message, "finish_reason": finish, "logprobs": None}],
|
| 463 |
+
"usage": usage,
|
| 464 |
+
"server_timing": {"latency_s": round(dt, 3)},
|
| 465 |
+
})
|
| 466 |
+
|
| 467 |
+
def _send_stream(self, cid, created, model_name, message, finish, usage, req):
|
| 468 |
+
self.send_response(200)
|
| 469 |
+
self.send_header("Content-Type", "text/event-stream")
|
| 470 |
+
self.send_header("Cache-Control", "no-cache")
|
| 471 |
+
self.send_header("Connection", "close")
|
| 472 |
+
self.end_headers()
|
| 473 |
+
self.close_connection = True
|
| 474 |
+
|
| 475 |
+
def chunk(delta, fr=None, with_usage=False):
|
| 476 |
+
obj = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name,
|
| 477 |
+
"choices": [{"index": 0, "delta": delta, "finish_reason": fr, "logprobs": None}]}
|
| 478 |
+
if with_usage:
|
| 479 |
+
obj["usage"] = usage
|
| 480 |
+
self.wfile.write(b"data: " + json.dumps(obj, ensure_ascii=False).encode() + b"\n\n")
|
| 481 |
+
|
| 482 |
+
chunk({"role": "assistant", "content": message.get("content") or ""})
|
| 483 |
+
for i, tc in enumerate(message.get("tool_calls", [])):
|
| 484 |
+
chunk({"tool_calls": [dict(tc, index=i)]})
|
| 485 |
+
include_usage = bool((req.get("stream_options") or {}).get("include_usage"))
|
| 486 |
+
chunk({}, finish, with_usage=include_usage)
|
| 487 |
+
self.wfile.write(b"data: [DONE]\n\n")
|
| 488 |
+
self.wfile.flush()
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def main():
|
| 492 |
+
global ENGINE, ARGS
|
| 493 |
+
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 494 |
+
p.add_argument("--model", default=os.environ.get("QWEN_VL_MODEL", "Qwen/Qwen3-VL-8B-Instruct"))
|
| 495 |
+
p.add_argument("--served-name", default="Qwen3-VL-8B-Instruct")
|
| 496 |
+
p.add_argument("--host", default="127.0.0.1")
|
| 497 |
+
p.add_argument("--port", type=int, default=8765)
|
| 498 |
+
p.add_argument("--device", default="cuda:0")
|
| 499 |
+
p.add_argument("--attn", default="sdpa", choices=["sdpa", "eager", "flash_attention_2"])
|
| 500 |
+
p.add_argument("--sdpa-native-gqa", action="store_true",
|
| 501 |
+
help="let torch SDPA do GQA (enable_gqa=True); broken on PPU for decode, off by default")
|
| 502 |
+
p.add_argument("--default-max-tokens", type=int, default=1024)
|
| 503 |
+
p.add_argument("--max-tokens-cap", type=int, default=8192)
|
| 504 |
+
p.add_argument("--max-prompt-tokens", type=int, default=65536)
|
| 505 |
+
p.add_argument("--default-temperature", type=float, default=0.0,
|
| 506 |
+
help="used when the request has no temperature; 0 = greedy")
|
| 507 |
+
p.add_argument("--min-pixels", type=int, default=0, help="override image processor min_pixels")
|
| 508 |
+
p.add_argument("--max-pixels", type=int, default=0, help="override image processor max_pixels")
|
| 509 |
+
p.add_argument("--log-outputs", action="store_true", help="log raw model output text per request")
|
| 510 |
+
p.add_argument("--warmup", action="store_true", help="run one tiny generation before serving")
|
| 511 |
+
ARGS = p.parse_args()
|
| 512 |
+
|
| 513 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout)
|
| 514 |
+
import transformers
|
| 515 |
+
|
| 516 |
+
LOG.info("transformers %s from %s", transformers.__version__, os.path.dirname(transformers.__file__))
|
| 517 |
+
ENGINE = Engine(ARGS)
|
| 518 |
+
if ARGS.warmup:
|
| 519 |
+
t = time.time()
|
| 520 |
+
with ENGINE.lock:
|
| 521 |
+
ENGINE.chat({"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 4})
|
| 522 |
+
LOG.info("warmup done in %.1fs", time.time() - t)
|
| 523 |
+
srv = ThreadingHTTPServer((ARGS.host, ARGS.port), Handler)
|
| 524 |
+
srv.daemon_threads = True
|
| 525 |
+
LOG.info("serving %s on http://%s:%d/v1/chat/completions", ARGS.served_name, ARGS.host, ARGS.port)
|
| 526 |
+
try:
|
| 527 |
+
srv.serve_forever()
|
| 528 |
+
except KeyboardInterrupt:
|
| 529 |
+
pass
|
| 530 |
+
finally:
|
| 531 |
+
srv.server_close()
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
if __name__ == "__main__":
|
| 535 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/agent/backends/openai_responses.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI Responses API backend (default model gpt-6-astra).
|
| 2 |
+
|
| 3 |
+
Stateless requests: every call re-sends instructions + tools + the full (pruned) conversation with
|
| 4 |
+
store=False; reasoning items are replayed with their encrypted content so the model keeps its chain
|
| 5 |
+
of thought across tool calls within an attempt. The request prefix (instructions, tools, task text,
|
| 6 |
+
packed history of earlier attempts) is byte-identical across the calls of an attempt, which is what
|
| 7 |
+
OpenAI's automatic prompt caching needs. Images go in as base64 JPEG data URLs.
|
| 8 |
+
|
| 9 |
+
Key and endpoint come from OPENAI_API_KEY / OPENAI_BASE_URL. Nothing here is executed at import time;
|
| 10 |
+
the client is created lazily on the first real call (tests inject a mock client).
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
from ..context import ToolCall, prune_live_images
|
| 17 |
+
from .base import Backend, BackendResponse, import_openai
|
| 18 |
+
|
| 19 |
+
# GPT-6 Astra: reasoning.effort supports low/medium/high/xhigh/max; `none` is NOT supported.
|
| 20 |
+
GPT6_ASTRA_EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _get(obj, key, default=None):
|
| 24 |
+
if isinstance(obj, dict):
|
| 25 |
+
return obj.get(key, default)
|
| 26 |
+
return getattr(obj, key, default)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _to_dict(item):
|
| 30 |
+
if isinstance(item, dict):
|
| 31 |
+
return dict(item)
|
| 32 |
+
if hasattr(item, "to_dict"):
|
| 33 |
+
return item.to_dict(mode="json")
|
| 34 |
+
if hasattr(item, "model_dump"):
|
| 35 |
+
return item.model_dump(mode="json", exclude_none=True)
|
| 36 |
+
return dict(vars(item))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def responses_tools(specs, strict=True):
|
| 40 |
+
return [dict(type="function", name=s["name"], description=s["description"], parameters=s["parameters"],
|
| 41 |
+
strict=strict) for s in specs]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class OpenAIResponsesBackend(Backend):
|
| 45 |
+
name = "openai"
|
| 46 |
+
|
| 47 |
+
def __init__(self, model="gpt-6-astra", reasoning_effort="medium", reasoning_summary=None, image_detail="auto",
|
| 48 |
+
max_output_tokens=None, service_tier=None, prompt_cache_key=None, prompt_cache_retention=None,
|
| 49 |
+
store=False, replay_reasoning=True, max_live_images=16, jpeg_quality=90, timeout=900.0,
|
| 50 |
+
max_retries=4, extra_body=None, strict_tools=True, cache_breakpoints="history+last",
|
| 51 |
+
prompt_cache_options=None, client=None, http_client=None):
|
| 52 |
+
if model.startswith("gpt-6-astra") and reasoning_effort not in GPT6_ASTRA_EFFORTS:
|
| 53 |
+
raise ValueError(f"gpt-6-astra supports reasoning effort {GPT6_ASTRA_EFFORTS} (no 'none'), "
|
| 54 |
+
f"got {reasoning_effort!r}")
|
| 55 |
+
self.model = model
|
| 56 |
+
self.reasoning_effort = reasoning_effort
|
| 57 |
+
self.reasoning_summary = reasoning_summary
|
| 58 |
+
self.image_detail = image_detail
|
| 59 |
+
self.max_output_tokens = max_output_tokens
|
| 60 |
+
self.service_tier = service_tier
|
| 61 |
+
self.prompt_cache_key = prompt_cache_key
|
| 62 |
+
self.prompt_cache_retention = prompt_cache_retention
|
| 63 |
+
self.store = store
|
| 64 |
+
self.replay_reasoning = replay_reasoning
|
| 65 |
+
self.max_live_images = max_live_images
|
| 66 |
+
self.jpeg_quality = jpeg_quality
|
| 67 |
+
self.timeout = timeout
|
| 68 |
+
self.max_retries = max_retries
|
| 69 |
+
self.extra_body = extra_body
|
| 70 |
+
self.strict_tools = strict_tools
|
| 71 |
+
# explicit prompt-cache breakpoints (Responses API, gpt-5.6+): "none" | "history" | "history+last"
|
| 72 |
+
assert cache_breakpoints in ("none", "history", "history+last"), cache_breakpoints
|
| 73 |
+
self.cache_breakpoints = cache_breakpoints
|
| 74 |
+
self.prompt_cache_options = prompt_cache_options
|
| 75 |
+
self._client = client
|
| 76 |
+
self._http_client = http_client # optional custom transport (tests, proxies)
|
| 77 |
+
self._cache_key = prompt_cache_key
|
| 78 |
+
|
| 79 |
+
def config(self):
|
| 80 |
+
return dict(name=self.name, model=self.model, reasoning_effort=self.reasoning_effort,
|
| 81 |
+
reasoning_summary=self.reasoning_summary, image_detail=self.image_detail,
|
| 82 |
+
max_output_tokens=self.max_output_tokens, service_tier=self.service_tier,
|
| 83 |
+
prompt_cache_key=self.prompt_cache_key, prompt_cache_retention=self.prompt_cache_retention,
|
| 84 |
+
store=self.store, replay_reasoning=self.replay_reasoning, max_live_images=self.max_live_images,
|
| 85 |
+
jpeg_quality=self.jpeg_quality, timeout=self.timeout, max_retries=self.max_retries,
|
| 86 |
+
extra_body=self.extra_body, cache_breakpoints=self.cache_breakpoints,
|
| 87 |
+
prompt_cache_options=self.prompt_cache_options, base_url=os.environ.get("OPENAI_BASE_URL"))
|
| 88 |
+
|
| 89 |
+
# ------------------------------------------------------------------ client
|
| 90 |
+
def client(self):
|
| 91 |
+
if self._client is None:
|
| 92 |
+
key = os.environ.get("OPENAI_API_KEY")
|
| 93 |
+
if not key:
|
| 94 |
+
raise RuntimeError("OPENAI_API_KEY is not set; the OpenAI backend cannot run without it")
|
| 95 |
+
openai = import_openai()
|
| 96 |
+
kw = dict(api_key=key, base_url=os.environ.get("OPENAI_BASE_URL") or None, timeout=self.timeout,
|
| 97 |
+
max_retries=self.max_retries)
|
| 98 |
+
if self._http_client is not None:
|
| 99 |
+
kw["http_client"] = self._http_client
|
| 100 |
+
self._client = openai.OpenAI(**kw)
|
| 101 |
+
return self._client
|
| 102 |
+
|
| 103 |
+
def begin_run(self, info):
|
| 104 |
+
if self.prompt_cache_key is None:
|
| 105 |
+
# route all calls of one run to the same cache shard
|
| 106 |
+
self._cache_key = f"lffbench:{getattr(info.task, 'name', 'task')}:{info.seed}"
|
| 107 |
+
|
| 108 |
+
# ------------------------------------------------------------------ request
|
| 109 |
+
def convert_items(self, items):
|
| 110 |
+
out = []
|
| 111 |
+
last_user = max((i for i, it in enumerate(items) if it["kind"] == "user"), default=-1)
|
| 112 |
+
for i, it in enumerate(items):
|
| 113 |
+
kind = it["kind"]
|
| 114 |
+
if kind == "user":
|
| 115 |
+
content = []
|
| 116 |
+
for p in it["parts"]:
|
| 117 |
+
if p["type"] == "text":
|
| 118 |
+
content.append(dict(type="input_text", text=p["text"]))
|
| 119 |
+
else:
|
| 120 |
+
content.append(dict(type="input_image", image_url=p["image"].data_url(self.jpeg_quality),
|
| 121 |
+
detail=self.image_detail))
|
| 122 |
+
# explicit cache breakpoints: end of the stable history item (byte-identical for the whole
|
| 123 |
+
# attempt) and end of the newest input (reused by the next call of the attempt)
|
| 124 |
+
if content and ((self.cache_breakpoints != "none" and not it.get("live"))
|
| 125 |
+
or (self.cache_breakpoints == "history+last" and i == last_user)):
|
| 126 |
+
content[-1]["prompt_cache_breakpoint"] = dict(mode="explicit")
|
| 127 |
+
out.append(dict(role="user", content=content))
|
| 128 |
+
elif kind == "assistant":
|
| 129 |
+
if it.get("raw") and it.get("backend") == self.name:
|
| 130 |
+
for r in it["raw"]:
|
| 131 |
+
if r.get("type") == "reasoning" and not self.replay_reasoning:
|
| 132 |
+
continue
|
| 133 |
+
out.append(r)
|
| 134 |
+
else:
|
| 135 |
+
if it.get("text"):
|
| 136 |
+
out.append(dict(role="assistant", content=it["text"]))
|
| 137 |
+
for tc in it["tool_calls"]:
|
| 138 |
+
out.append(dict(type="function_call", call_id=tc.id, name=tc.name,
|
| 139 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 140 |
+
elif kind == "tool_output":
|
| 141 |
+
out.append(dict(type="function_call_output", call_id=it["call_id"], output=it["text"]))
|
| 142 |
+
else:
|
| 143 |
+
raise ValueError(kind)
|
| 144 |
+
return out
|
| 145 |
+
|
| 146 |
+
def build_request(self, conv, tools):
|
| 147 |
+
items = prune_live_images(conv.items, self.max_live_images)
|
| 148 |
+
req = dict(model=self.model, instructions=conv.system, input=self.convert_items(items),
|
| 149 |
+
tools=responses_tools(tools, self.strict_tools), tool_choice="auto", parallel_tool_calls=False,
|
| 150 |
+
store=self.store)
|
| 151 |
+
reasoning = dict(effort=self.reasoning_effort)
|
| 152 |
+
if self.reasoning_summary:
|
| 153 |
+
reasoning["summary"] = self.reasoning_summary
|
| 154 |
+
req["reasoning"] = reasoning
|
| 155 |
+
if not self.store and self.replay_reasoning:
|
| 156 |
+
req["include"] = ["reasoning.encrypted_content"]
|
| 157 |
+
if self.max_output_tokens:
|
| 158 |
+
req["max_output_tokens"] = int(self.max_output_tokens)
|
| 159 |
+
if self.service_tier:
|
| 160 |
+
req["service_tier"] = self.service_tier
|
| 161 |
+
if self._cache_key:
|
| 162 |
+
req["prompt_cache_key"] = self._cache_key
|
| 163 |
+
if self.prompt_cache_retention:
|
| 164 |
+
req["prompt_cache_retention"] = self.prompt_cache_retention
|
| 165 |
+
if self.prompt_cache_options:
|
| 166 |
+
req["prompt_cache_options"] = dict(self.prompt_cache_options)
|
| 167 |
+
if self.extra_body:
|
| 168 |
+
req["extra_body"] = dict(self.extra_body)
|
| 169 |
+
return req
|
| 170 |
+
|
| 171 |
+
@staticmethod
|
| 172 |
+
def request_stats(req):
|
| 173 |
+
n_img, img_bytes, txt = 0, 0, len(req.get("instructions") or "")
|
| 174 |
+
for it in req["input"]:
|
| 175 |
+
for c in (it.get("content") if isinstance(it.get("content"), list) else []):
|
| 176 |
+
if c.get("type") == "input_image":
|
| 177 |
+
n_img += 1
|
| 178 |
+
img_bytes += len(c["image_url"])
|
| 179 |
+
elif "text" in c:
|
| 180 |
+
txt += len(c["text"])
|
| 181 |
+
if isinstance(it.get("content"), str):
|
| 182 |
+
txt += len(it["content"])
|
| 183 |
+
if it.get("type") == "function_call_output":
|
| 184 |
+
txt += len(it["output"]) if isinstance(it["output"], str) else 0
|
| 185 |
+
if it.get("type") == "function_call":
|
| 186 |
+
txt += len(it.get("arguments", ""))
|
| 187 |
+
tools_chars = len(json.dumps(req.get("tools", [])))
|
| 188 |
+
return dict(n_images=n_img, image_payload_bytes=img_bytes, text_chars=txt + tools_chars,
|
| 189 |
+
n_input_items=len(req["input"]))
|
| 190 |
+
|
| 191 |
+
# ------------------------------------------------------------------ call
|
| 192 |
+
def act(self, conv, tools):
|
| 193 |
+
req = self.build_request(conv, tools)
|
| 194 |
+
stats = self.request_stats(req)
|
| 195 |
+
t0 = time.time()
|
| 196 |
+
resp = self.client().responses.create(**req)
|
| 197 |
+
out = self.parse_response(resp)
|
| 198 |
+
out.latency_s = time.time() - t0
|
| 199 |
+
out.request_stats = stats
|
| 200 |
+
return out
|
| 201 |
+
|
| 202 |
+
def parse_response(self, resp):
|
| 203 |
+
calls, texts, summ = [], [], []
|
| 204 |
+
output = _get(resp, "output") or []
|
| 205 |
+
for item in output:
|
| 206 |
+
t = _get(item, "type")
|
| 207 |
+
if t == "function_call":
|
| 208 |
+
raw = _get(item, "arguments") or ""
|
| 209 |
+
try:
|
| 210 |
+
args = json.loads(raw) if raw else {}
|
| 211 |
+
except json.JSONDecodeError:
|
| 212 |
+
args = {}
|
| 213 |
+
calls.append(ToolCall(id=_get(item, "call_id"), name=_get(item, "name"), arguments=args,
|
| 214 |
+
raw_arguments=raw))
|
| 215 |
+
elif t == "message":
|
| 216 |
+
for c in _get(item, "content") or []:
|
| 217 |
+
if _get(c, "type") == "output_text":
|
| 218 |
+
texts.append(_get(c, "text") or "")
|
| 219 |
+
elif t == "reasoning":
|
| 220 |
+
for s in _get(item, "summary") or []:
|
| 221 |
+
summ.append(_get(s, "text") or "")
|
| 222 |
+
u = _get(resp, "usage")
|
| 223 |
+
usage = {}
|
| 224 |
+
if u is not None:
|
| 225 |
+
itd = _get(u, "input_tokens_details")
|
| 226 |
+
otd = _get(u, "output_tokens_details")
|
| 227 |
+
usage = dict(input_tokens=_get(u, "input_tokens", 0) or 0,
|
| 228 |
+
cached_tokens=(_get(itd, "cached_tokens", 0) or 0) if itd is not None else 0,
|
| 229 |
+
cache_write_tokens=(_get(itd, "cache_write_tokens", 0) or 0) if itd is not None else 0,
|
| 230 |
+
output_tokens=_get(u, "output_tokens", 0) or 0,
|
| 231 |
+
reasoning_tokens=(_get(otd, "reasoning_tokens", 0) or 0) if otd is not None else 0)
|
| 232 |
+
status = _get(resp, "status") or "completed"
|
| 233 |
+
err = None
|
| 234 |
+
if status == "incomplete":
|
| 235 |
+
err = "incomplete: " + str(_get(_get(resp, "incomplete_details"), "reason"))
|
| 236 |
+
elif not output and u is None: # seen through a gateway: no output and no usage; the player asks again
|
| 237 |
+
status, err = "incomplete", "empty response (no output, no usage)"
|
| 238 |
+
return BackendResponse(tool_calls=calls, text="\n".join(t for t in texts if t) or None,
|
| 239 |
+
reasoning_summary="\n".join(s for s in summ if s) or None, usage=usage,
|
| 240 |
+
raw=[_to_dict(i) for i in output], status=status, error=err)
|
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/harnesses/base.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness adapter interface (docs/15 §3).
|
| 2 |
+
|
| 3 |
+
An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log
|
| 4 |
+
dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations).
|
| 5 |
+
Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server /
|
| 6 |
+
reference driver enforce them identically for every harness.
|
| 7 |
+
|
| 8 |
+
name stable harness name (the "harness" column of a table)
|
| 9 |
+
capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source;
|
| 10 |
+
a missing item makes the class definition fail (so the import fails)
|
| 11 |
+
version() the actual installed version (probed before launch)
|
| 12 |
+
prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env
|
| 13 |
+
launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle
|
| 14 |
+
collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason
|
| 15 |
+
audit(h) tool list, preset prompt, memory, state left behind, violations
|
| 16 |
+
"""
|
| 17 |
+
import dataclasses
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import secrets
|
| 21 |
+
import shutil
|
| 22 |
+
import signal
|
| 23 |
+
import subprocess
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
from . import contract as C
|
| 27 |
+
|
| 28 |
+
EVIDENCE = ("launch", "stream", "server", "probe", "preflight")
|
| 29 |
+
|
| 30 |
+
REQUIRED = {
|
| 31 |
+
"only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use",
|
| 32 |
+
"images_reach_model": "view_images returns the image bytes to the model unchanged",
|
| 33 |
+
"non_persistent_session": "nothing of the session is written to disk for later runs",
|
| 34 |
+
"pinned_version": "the harness version (and binary hash) is recorded and pinned",
|
| 35 |
+
"machine_readable_events": "a machine-readable event stream of the whole run",
|
| 36 |
+
"tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)",
|
| 37 |
+
"model_and_effort": "model and reasoning effort can be set and are visible in the request",
|
| 38 |
+
}
|
| 39 |
+
FORBIDDEN = {
|
| 40 |
+
"persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)",
|
| 41 |
+
"instruction_file_injection": "instruction files picked up from the work / config / home dir",
|
| 42 |
+
"web_access": "web search / fetch",
|
| 43 |
+
"host_file_read": "reading host files outside the episode workspace",
|
| 44 |
+
"builtin_shell": "a shell of the harness itself (outside our jailed shell tool)",
|
| 45 |
+
"subagent_delegation": "spawning sub-agents",
|
| 46 |
+
"background_execution": "background tasks that outlive a tool call",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclasses.dataclass(frozen=True)
|
| 51 |
+
class Cap:
|
| 52 |
+
status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial"
|
| 53 |
+
evidence: str # one of EVIDENCE
|
| 54 |
+
note: str = ""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")
|
| 58 |
+
NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
|
| 59 |
+
NO_PROXY_LOCAL = "127.0.0.1,localhost,::1"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def proxy_env(environ=None):
|
| 63 |
+
"""The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines
|
| 64 |
+
that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list.
|
| 65 |
+
Not part of config_sha256 (machine plumbing, not harness configuration)."""
|
| 66 |
+
environ = os.environ if environ is None else environ
|
| 67 |
+
e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)}
|
| 68 |
+
if e:
|
| 69 |
+
e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS})
|
| 70 |
+
return e
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class CapabilityError(TypeError):
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_capabilities(name, caps):
|
| 78 |
+
if not isinstance(caps, dict):
|
| 79 |
+
raise CapabilityError(f"{name}: capabilities must be a dict")
|
| 80 |
+
missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps]
|
| 81 |
+
extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN]
|
| 82 |
+
if missing or extra:
|
| 83 |
+
raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}")
|
| 84 |
+
for k, c in caps.items():
|
| 85 |
+
if not isinstance(c, Cap) or c.evidence not in EVIDENCE:
|
| 86 |
+
raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})")
|
| 87 |
+
ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial")
|
| 88 |
+
if c.status not in ok:
|
| 89 |
+
raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class HarnessRefused(RuntimeError):
|
| 93 |
+
"""Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one."""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@dataclasses.dataclass
|
| 97 |
+
class EpisodeSpec:
|
| 98 |
+
session_path: str
|
| 99 |
+
log_dir: str
|
| 100 |
+
sandbox: str
|
| 101 |
+
port: int
|
| 102 |
+
token: str
|
| 103 |
+
max_tool_calls: int
|
| 104 |
+
model: str
|
| 105 |
+
effort: str
|
| 106 |
+
provider: str = ""
|
| 107 |
+
task: str = ""
|
| 108 |
+
seed: int = 0
|
| 109 |
+
extra: dict = dataclasses.field(default_factory=dict)
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def from_session(cls, session_path, model, effort, provider="", **extra):
|
| 113 |
+
session_path = os.path.abspath(session_path)
|
| 114 |
+
log_dir = os.path.dirname(session_path)
|
| 115 |
+
sess = json.load(open(session_path))
|
| 116 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 117 |
+
st = C.session_start(log_dir)
|
| 118 |
+
return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]),
|
| 119 |
+
token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort,
|
| 120 |
+
provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclasses.dataclass
|
| 124 |
+
class LaunchSpec:
|
| 125 |
+
argv: list # full argv (the first message may be one element)
|
| 126 |
+
env: dict # the complete environment of the harness process (nothing else is inherited)
|
| 127 |
+
cwd: str
|
| 128 |
+
run_dir: str = "" # one-time dir tree, removed after audit
|
| 129 |
+
state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...)
|
| 130 |
+
first_message: str = ""
|
| 131 |
+
config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote
|
| 132 |
+
stdout_path: str = ""
|
| 133 |
+
stderr_path: str = ""
|
| 134 |
+
redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log
|
| 135 |
+
preflight: dict = dataclasses.field(default_factory=dict)
|
| 136 |
+
timeout_s: float = 10800
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclasses.dataclass
|
| 140 |
+
class RunHandle:
|
| 141 |
+
spec: LaunchSpec
|
| 142 |
+
ep: EpisodeSpec
|
| 143 |
+
proc: object = None
|
| 144 |
+
pid: int = 0
|
| 145 |
+
t_start: float = 0.0
|
| 146 |
+
t_end: float = 0.0
|
| 147 |
+
exit_code: int = None
|
| 148 |
+
exit_reason: str = ""
|
| 149 |
+
env_observed_keys: list = None # read from /proc/<pid>/environ right after the start
|
| 150 |
+
info: dict = dataclasses.field(default_factory=dict)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def env_keys_of(pid):
|
| 154 |
+
try:
|
| 155 |
+
raw = open(f"/proc/{pid}/environ", "rb").read()
|
| 156 |
+
except OSError:
|
| 157 |
+
return None
|
| 158 |
+
return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv})
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def new_run_dir(root="/tmp/lffrun"):
|
| 162 |
+
"""/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses)."""
|
| 163 |
+
os.makedirs(root, exist_ok=True)
|
| 164 |
+
while True:
|
| 165 |
+
d = os.path.join(root, secrets.token_hex(6))
|
| 166 |
+
try:
|
| 167 |
+
os.mkdir(d, 0o700)
|
| 168 |
+
return d
|
| 169 |
+
except FileExistsError:
|
| 170 |
+
continue
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def binary_info(path):
|
| 174 |
+
real = os.path.realpath(path)
|
| 175 |
+
return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class HarnessAdapter:
|
| 179 |
+
name = None
|
| 180 |
+
capabilities = None
|
| 181 |
+
uses_mcp = False
|
| 182 |
+
uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for
|
| 183 |
+
# this adapter: MCP adapters through the MCP server, framework adapters
|
| 184 |
+
# (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN
|
| 185 |
+
clean_dirs = () # keys of spec.state_dirs that must be empty at launch
|
| 186 |
+
clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json)
|
| 187 |
+
ancestor_files = () # instruction files that must not exist in the work dir or any ancestor
|
| 188 |
+
unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read)
|
| 189 |
+
jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4)
|
| 190 |
+
can_resume = False # resume(): the CLI can continue its session with one more user message
|
| 191 |
+
|
| 192 |
+
def clean_state_problems(self, spec):
|
| 193 |
+
"""Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an
|
| 194 |
+
ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md)."""
|
| 195 |
+
p = []
|
| 196 |
+
if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd):
|
| 197 |
+
p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}")
|
| 198 |
+
for k in self.clean_dirs:
|
| 199 |
+
d = spec.state_dirs.get(k)
|
| 200 |
+
left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else []
|
| 201 |
+
if left:
|
| 202 |
+
p.append(f"{k} dir not empty: {sorted(left)[:5]}")
|
| 203 |
+
d = spec.cwd
|
| 204 |
+
while d and d != "/":
|
| 205 |
+
d = os.path.dirname(d)
|
| 206 |
+
for f in self.ancestor_files:
|
| 207 |
+
if os.path.exists(os.path.join(d, f)):
|
| 208 |
+
p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}")
|
| 209 |
+
return p
|
| 210 |
+
|
| 211 |
+
def __init_subclass__(cls, **kw):
|
| 212 |
+
super().__init_subclass__(**kw)
|
| 213 |
+
if cls.name is None:
|
| 214 |
+
raise CapabilityError(f"{cls.__name__}: no name")
|
| 215 |
+
check_capabilities(cls.name, cls.capabilities)
|
| 216 |
+
|
| 217 |
+
# -------------------------------------------------------------------------------------------- interface
|
| 218 |
+
def version(self):
|
| 219 |
+
raise NotImplementedError
|
| 220 |
+
|
| 221 |
+
def prepare(self, ep, first_message):
|
| 222 |
+
raise NotImplementedError
|
| 223 |
+
|
| 224 |
+
def preflight(self, spec, ep):
|
| 225 |
+
"""Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused."""
|
| 226 |
+
return dict(skipped=True)
|
| 227 |
+
|
| 228 |
+
def collect(self, h):
|
| 229 |
+
raise NotImplementedError
|
| 230 |
+
|
| 231 |
+
def audit(self, h):
|
| 232 |
+
raise NotImplementedError
|
| 233 |
+
|
| 234 |
+
# -------------------------------------------------------------------------------------------- shared
|
| 235 |
+
def mcp_server_command(self, python, script, args):
|
| 236 |
+
"""(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it."""
|
| 237 |
+
if self.jail is not None:
|
| 238 |
+
return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"})
|
| 239 |
+
return python, [script] + list(args)
|
| 240 |
+
|
| 241 |
+
def jailed_argv(self, argv, env, cwd, dirs):
|
| 242 |
+
"""argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back."""
|
| 243 |
+
return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv)
|
| 244 |
+
|
| 245 |
+
def jail_info(self):
|
| 246 |
+
return self.jail.info() if self.jail is not None else dict(enabled=False)
|
| 247 |
+
|
| 248 |
+
def auth_info(self):
|
| 249 |
+
"""How the harness authenticates to the model API (for harness.json; never a secret)."""
|
| 250 |
+
return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {}))
|
| 251 |
+
|
| 252 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 253 |
+
if not self.unsafe_skip_clean_check:
|
| 254 |
+
probs = self.clean_state_problems(spec)
|
| 255 |
+
if probs:
|
| 256 |
+
spec.preflight = dict(problems=probs)
|
| 257 |
+
raise HarnessRefused("clean-state check: " + "; ".join(probs))
|
| 258 |
+
spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep)
|
| 259 |
+
out = open(spec.stdout_path, "wb")
|
| 260 |
+
err = open(spec.stderr_path, "wb")
|
| 261 |
+
h = RunHandle(spec=spec, ep=ep, t_start=time.time())
|
| 262 |
+
argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 263 |
+
h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 264 |
+
stderr=err, start_new_session=True)
|
| 265 |
+
h.pid = h.proc.pid
|
| 266 |
+
for _ in range(20): # the exec has happened once /proc/<pid>/environ differs from ours
|
| 267 |
+
keys = env_keys_of(h.pid)
|
| 268 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 269 |
+
break
|
| 270 |
+
time.sleep(0.05)
|
| 271 |
+
h.env_observed_keys = 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_original34_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local fake model APIs for offline harness checks (no real model, no cost).
|
| 2 |
+
|
| 3 |
+
Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a
|
| 4 |
+
native harness can be driven turn by turn without a model:
|
| 5 |
+
FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic
|
| 6 |
+
FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider
|
| 7 |
+
|
| 8 |
+
A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get
|
| 9 |
+
the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps:
|
| 10 |
+
("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read")
|
| 11 |
+
("text", s) a text block / assistant message
|
| 12 |
+
("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript
|
| 13 |
+
("fcall", name, args) Responses: a plain function call
|
| 14 |
+
("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP
|
| 15 |
+
tools this way: name "robot", namespace "mcp__lff"; measured with 0.163)
|
| 16 |
+
|
| 17 |
+
srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop()
|
| 18 |
+
"""
|
| 19 |
+
import itertools
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import threading
|
| 23 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 24 |
+
|
| 25 |
+
DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _Base:
|
| 29 |
+
final_text = "done"
|
| 30 |
+
|
| 31 |
+
def __init__(self, script=None, record_dir=None, port=0):
|
| 32 |
+
self.script = list(script or [])
|
| 33 |
+
self.record_dir = record_dir
|
| 34 |
+
self.port = port
|
| 35 |
+
self.lock = threading.Lock()
|
| 36 |
+
self.counter = itertools.count(1)
|
| 37 |
+
self.requests = [] # (n, path, body)
|
| 38 |
+
if record_dir:
|
| 39 |
+
os.makedirs(record_dir, exist_ok=True)
|
| 40 |
+
|
| 41 |
+
# ------------------------------------------------------------------ plumbing
|
| 42 |
+
def start(self):
|
| 43 |
+
outer = self
|
| 44 |
+
|
| 45 |
+
class H(BaseHTTPRequestHandler):
|
| 46 |
+
protocol_version = "HTTP/1.1"
|
| 47 |
+
|
| 48 |
+
def log_message(self, *a):
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
def _record(self, body):
|
| 52 |
+
with outer.lock:
|
| 53 |
+
n = next(outer.counter)
|
| 54 |
+
outer.requests.append((n, self.path, body))
|
| 55 |
+
if outer.record_dir:
|
| 56 |
+
with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f:
|
| 57 |
+
json.dump(dict(method=self.command, path=self.path, body=body,
|
| 58 |
+
headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}),
|
| 59 |
+
f, indent=1, ensure_ascii=False)
|
| 60 |
+
return n
|
| 61 |
+
|
| 62 |
+
def do_GET(self):
|
| 63 |
+
self._record(None)
|
| 64 |
+
self._send(404, b"{}", "application/json")
|
| 65 |
+
|
| 66 |
+
def do_HEAD(self):
|
| 67 |
+
self._send(404, b"", "application/json")
|
| 68 |
+
|
| 69 |
+
def do_POST(self):
|
| 70 |
+
raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0))
|
| 71 |
+
try:
|
| 72 |
+
body = json.loads(raw)
|
| 73 |
+
except ValueError:
|
| 74 |
+
body = raw[:4000].decode("utf-8", "replace")
|
| 75 |
+
n = self._record(body)
|
| 76 |
+
outer.handle(self, n, body)
|
| 77 |
+
|
| 78 |
+
def _send(self, code, data, ctype):
|
| 79 |
+
self.send_response(code)
|
| 80 |
+
self.send_header("content-type", ctype)
|
| 81 |
+
self.send_header("content-length", str(len(data)))
|
| 82 |
+
self.end_headers()
|
| 83 |
+
self.wfile.write(data)
|
| 84 |
+
|
| 85 |
+
self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H)
|
| 86 |
+
self.httpd.daemon_threads = True
|
| 87 |
+
self.port = self.httpd.server_address[1]
|
| 88 |
+
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
| 89 |
+
return self
|
| 90 |
+
|
| 91 |
+
def stop(self):
|
| 92 |
+
self.httpd.shutdown()
|
| 93 |
+
self.httpd.server_close()
|
| 94 |
+
|
| 95 |
+
def turn(self, i):
|
| 96 |
+
return self.script[i] if i < len(self.script) else [("text", self.final_text)]
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def send_sse(h, events):
|
| 100 |
+
data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events)
|
| 101 |
+
h._send(200, data, "text/event-stream")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class FakeAnthropic(_Base):
|
| 105 |
+
@property
|
| 106 |
+
def base_url(self):
|
| 107 |
+
return f"http://127.0.0.1:{self.port}"
|
| 108 |
+
|
| 109 |
+
def handle(self, h, n, body):
|
| 110 |
+
if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict):
|
| 111 |
+
h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json")
|
| 112 |
+
return
|
| 113 |
+
msgs = body.get("messages", [])
|
| 114 |
+
i = sum(1 for m in msgs if m.get("role") == "assistant")
|
| 115 |
+
steps = self.turn(i)
|
| 116 |
+
blocks = []
|
| 117 |
+
for j, st in enumerate(steps):
|
| 118 |
+
if st[0] == "tool":
|
| 119 |
+
blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2]))
|
| 120 |
+
else:
|
| 121 |
+
blocks.append(dict(type="text", text=st[1]))
|
| 122 |
+
stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn"
|
| 123 |
+
model = body.get("model", "fake")
|
| 124 |
+
evs = [("message_start", dict(type="message_start", message=dict(
|
| 125 |
+
id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None,
|
| 126 |
+
stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))]
|
| 127 |
+
for k, b in enumerate(blocks):
|
| 128 |
+
if b["type"] == "tool_use":
|
| 129 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict(
|
| 130 |
+
type="tool_use", id=b["id"], name=b["name"], input={}))))
|
| 131 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict(
|
| 132 |
+
type="input_json_delta", partial_json=json.dumps(b["input"])))))
|
| 133 |
+
else:
|
| 134 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k,
|
| 135 |
+
content_block=dict(type="text", text=""))))
|
| 136 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k,
|
| 137 |
+
delta=dict(type="text_delta", text=b["text"]))))
|
| 138 |
+
evs.append(("content_block_stop", dict(type="content_block_stop", index=k)))
|
| 139 |
+
evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None),
|
| 140 |
+
usage=dict(output_tokens=5))))
|
| 141 |
+
evs.append(("message_stop", dict(type="message_stop")))
|
| 142 |
+
self.send_sse(h, evs)
|
| 143 |
+
|
| 144 |
+
def message_requests(self):
|
| 145 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages")
|
| 146 |
+
and "count_tokens" not in p]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class FakeResponses(_Base):
|
| 150 |
+
@property
|
| 151 |
+
def base_url(self):
|
| 152 |
+
return f"http://127.0.0.1:{self.port}/v1"
|
| 153 |
+
|
| 154 |
+
def handle(self, h, n, body):
|
| 155 |
+
if not isinstance(body, dict) or "input" not in body:
|
| 156 |
+
h._send(404, b"{}", "application/json")
|
| 157 |
+
return
|
| 158 |
+
items = body.get("input") or []
|
| 159 |
+
i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in
|
| 160 |
+
("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message"
|
| 161 |
+
and it.get("role") == "assistant"))
|
| 162 |
+
steps = self.turn(i)
|
| 163 |
+
out = []
|
| 164 |
+
for j, st in enumerate(steps):
|
| 165 |
+
if st[0] == "exec":
|
| 166 |
+
out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 167 |
+
name="exec", status="completed", input=st[1]))
|
| 168 |
+
elif st[0] == "fcall":
|
| 169 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 170 |
+
name=st[1], arguments=json.dumps(st[2]), status="completed"))
|
| 171 |
+
elif st[0] == "nscall":
|
| 172 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 173 |
+
namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed"))
|
| 174 |
+
else:
|
| 175 |
+
out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed",
|
| 176 |
+
content=[dict(type="output_text", text=st[1], annotations=[])]))
|
| 177 |
+
rid = f"resp_fake_{n}"
|
| 178 |
+
evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))]
|
| 179 |
+
for k, it in enumerate(out):
|
| 180 |
+
evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it)))
|
| 181 |
+
evs.append(("response.completed", dict(type="response.completed", response=dict(
|
| 182 |
+
id=rid, status="completed", output=out, usage=dict(
|
| 183 |
+
input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3,
|
| 184 |
+
output_tokens_details=dict(reasoning_tokens=0), total_tokens=103)))))
|
| 185 |
+
self.send_sse(h, evs)
|
| 186 |
+
|
| 187 |
+
def model_requests(self):
|
| 188 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b]
|
leaf/release/source_packages/models-20261115-g56sol_original34_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_original34_20261114/lff/source_closure/lffbench/tasks/l5_iterative.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""[PARKED 2026-10-06 — fails acceptance: oracle 50% (n=12, k=3). The push response is not stationary:
|
| 2 |
+
the same commanded speed carries the cube 7.9 cm on one push and 11.4 cm on the next, because the arm reaches
|
| 3 |
+
different speeds at different extensions. Needs a configuration-independent striker before use.]
|
| 4 |
+
|
| 5 |
+
L5-B iterative_push: several pushes in ONE episode (MemMimic "Iterative Pushing" analogue).
|
| 6 |
+
|
| 7 |
+
The cube starts far from the target zone; each push is a straight strike away from the robot whose
|
| 8 |
+
only free parameter is the speed. Overshooting past the zone is unrecoverable (episode fails).
|
| 9 |
+
Hidden variable: cube-table friction mu, as in l5_slide_to_target. The information needed to choose
|
| 10 |
+
the next push (how far a push of a given speed carries the cube) is only available from the
|
| 11 |
+
outcomes of the previous pushes in the same episode -> within-episode learning from failure.
|
| 12 |
+
|
| 13 |
+
"Attempt" granularity for the history: one push.
|
| 14 |
+
"""
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from .. import envs
|
| 18 |
+
from ..task_base import register_task
|
| 19 |
+
from .l5_slide import CUBE_HALF, V_MAX, V_MIN, Z_PUSH, SlideToTarget
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@register_task
|
| 23 |
+
class IterativePush(SlideToTarget):
|
| 24 |
+
name = "l5_iterative_push"
|
| 25 |
+
level = "L5"
|
| 26 |
+
capabilities = ("Reason", "Save", "Utilize")
|
| 27 |
+
protocol = "within"
|
| 28 |
+
max_attempts = 3 # pushes per episode: too few to creep up on the target with small taps
|
| 29 |
+
instruction = ("Push the red cube away from the robot so that it comes to rest inside the green target zone. "
|
| 30 |
+
"You have at most three separate pushes. If the cube passes the zone, the task fails.")
|
| 31 |
+
instruction_indirect = instruction
|
| 32 |
+
tol_along = 0.015
|
| 33 |
+
|
| 34 |
+
def sample_instance(self, seed):
|
| 35 |
+
rng = np.random.default_rng(seed)
|
| 36 |
+
return dict(seed=int(seed),
|
| 37 |
+
cube_xy=[float(rng.uniform(-0.27, -0.23)), float(rng.uniform(-0.08, 0.08))],
|
| 38 |
+
target_dist=float(rng.uniform(0.22, 0.30)),
|
| 39 |
+
mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.08)))))
|
| 40 |
+
|
| 41 |
+
def make_bddl(self):
|
| 42 |
+
return super().make_bddl()
|
| 43 |
+
|
| 44 |
+
# --------------------------------------------------------------- one push from the current cube pose
|
| 45 |
+
def push_once(self, inst, speed):
|
| 46 |
+
c = envs.obj_pos(self.env, "cube_1")
|
| 47 |
+
x, y = c[0], c[1]
|
| 48 |
+
sk = self.sk
|
| 49 |
+
sk.set_gripper(True, steps=3)
|
| 50 |
+
sk.move_to([x - self.runup, y, Z_PUSH + 0.10], yaw=0.0)
|
| 51 |
+
sk.move_to([x - self.runup, y, Z_PUSH], tol=0.003)
|
| 52 |
+
sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01,
|
| 53 |
+
max_steps=80)
|
| 54 |
+
sk.move_to([x - CUBE_HALF + 0.015, y, Z_PUSH + 0.10], speed=0.3)
|
| 55 |
+
envs.settle(self.env, 40)
|
| 56 |
+
c1 = envs.obj_pos(self.env, "cube_1")
|
| 57 |
+
return float(c1[0] - x)
|
| 58 |
+
|
| 59 |
+
def outcome(self, inst):
|
| 60 |
+
x0, y0 = inst["cube_xy"]
|
| 61 |
+
c = envs.obj_pos(self.env, "cube_1")
|
| 62 |
+
along = (c[0] - x0) - inst["target_dist"]
|
| 63 |
+
across = c[1] - y0
|
| 64 |
+
success = bool(abs(along) <= self.tol_along and abs(across) <= self.tol_across and c[2] > envs.TABLE_Z)
|
| 65 |
+
overshoot = bool(along > self.tol_along)
|
| 66 |
+
if success:
|
| 67 |
+
detail = "The cube is inside the target zone."
|
| 68 |
+
elif overshoot:
|
| 69 |
+
detail = f"The cube passed the target zone: it is {100 * along:.1f} cm beyond its centre. The task has failed."
|
| 70 |
+
else:
|
| 71 |
+
detail = f"The cube is {100 * -along:.1f} cm short of the centre of the target zone."
|
| 72 |
+
return dict(success=success, overshoot=overshoot, along_err=float(along), across_err=float(across),
|
| 73 |
+
detail=detail)
|
| 74 |
+
|
| 75 |
+
# --------------------------------------------------------------- scripted references
|
| 76 |
+
S0 = 0.02 # distance the cube travels during the contact stroke itself
|
| 77 |
+
|
| 78 |
+
def _plan_speed(self, remaining, model, pushes_left=1):
|
| 79 |
+
"""Model: push distance d(v) = s0 + k v^2. With more than one push left, cover all but a short
|
| 80 |
+
final leg (a short push is more predictable); with one push left, aim at the zone centre."""
|
| 81 |
+
if model is None:
|
| 82 |
+
return 0.30
|
| 83 |
+
s0, k = model
|
| 84 |
+
goal = remaining if pushes_left <= 1 else max(remaining - 0.07, 0.0)
|
| 85 |
+
v = np.sqrt(max(goal - s0, 0.0) / max(k, 1e-6))
|
| 86 |
+
return float(np.clip(v, V_MIN, V_MAX))
|
| 87 |
+
|
| 88 |
+
@classmethod
|
| 89 |
+
def _fit(cls, pts):
|
| 90 |
+
"""pts: [(v, d)]. One point -> fix s0; two or more -> least squares on (s0, k)."""
|
| 91 |
+
if len(pts) == 1:
|
| 92 |
+
v, d = pts[0]
|
| 93 |
+
return cls.S0, max(d - cls.S0, 1e-4) / v ** 2
|
| 94 |
+
A = np.array([[1.0, v ** 2] for v, _ in pts])
|
| 95 |
+
b = np.array([d for _, d in pts])
|
| 96 |
+
s0, k = np.linalg.lstsq(A, b, rcond=None)[0]
|
| 97 |
+
if k <= 0:
|
| 98 |
+
return cls.S0, max(np.mean(b) - cls.S0, 1e-4) / np.mean([v ** 2 for v, _ in pts])
|
| 99 |
+
return float(np.clip(s0, 0.0, 0.05)), float(k)
|
| 100 |
+
|
| 101 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 102 |
+
k = k or self.max_attempts
|
| 103 |
+
rng = np.random.default_rng(seed)
|
| 104 |
+
self.reset_instance(inst)
|
| 105 |
+
history = []
|
| 106 |
+
model = None
|
| 107 |
+
if kind == "oracle":
|
| 108 |
+
model = self._oracle_model(inst)
|
| 109 |
+
for a in range(k):
|
| 110 |
+
out0 = self.outcome(inst)
|
| 111 |
+
remaining = -out0["along_err"]
|
| 112 |
+
if kind == "naive" or kind == "blind":
|
| 113 |
+
speed = 0.30 if kind == "naive" else float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX))
|
| 114 |
+
if remaining < 0.06: # naive heuristic: tap gently near the end
|
| 115 |
+
speed = 0.20
|
| 116 |
+
else:
|
| 117 |
+
speed = self._plan_speed(remaining, model, pushes_left=k - a)
|
| 118 |
+
moved = self.push_once(inst, speed)
|
| 119 |
+
out = self.outcome(inst)
|
| 120 |
+
history.append(dict(attempt=a + 1, params=dict(speed=speed), outcome=dict(out, moved=moved)))
|
| 121 |
+
if kind == "adaptive" and moved > 0.005:
|
| 122 |
+
pts = [(h["params"]["speed"], h["outcome"]["moved"]) for h in history if h["outcome"]["moved"] > 0.005]
|
| 123 |
+
model = self._fit(pts)
|
| 124 |
+
if out["success"] or out["overshoot"]:
|
| 125 |
+
break
|
| 126 |
+
# mark only the final state as the episode outcome
|
| 127 |
+
return history
|
| 128 |
+
|
| 129 |
+
def _oracle_model(self, inst):
|
| 130 |
+
"""Privileged: measure the push model with the true mu in scratch rollouts."""
|
| 131 |
+
pts = []
|
| 132 |
+
for v in (0.2, 0.35, 0.5):
|
| 133 |
+
self.reset_instance(inst)
|
| 134 |
+
pts.append((v, self.push_once(inst, v)))
|
| 135 |
+
self.reset_instance(inst)
|
| 136 |
+
return self._fit(pts)
|
leaf/release/source_packages/models-20261115-g56sol_original34_20261114/lff/source_closure/lffbench/tasks/l7_offcenter_push.py
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L7 offcenter_push: push a long box straight forward into a marked rectangle.
|
| 2 |
+
|
| 3 |
+
Category: failed_interaction_inference ("why did this contact not do what I expected?"). The code keeps level "L7";
|
| 4 |
+
the paper files the task under L5 (misjudged physics).
|
| 5 |
+
|
| 6 |
+
Hidden variable: the box's centre of mass is shifted along its long axis by e (|e| ~ U[4.5, 7.5] cm, either
|
| 7 |
+
side; implemented by moving the body's inertial frame, `body_ipos`). The box looks exactly the same for
|
| 8 |
+
every e (uniform colour, a symmetric tape stripe across its middle).
|
| 9 |
+
|
| 10 |
+
Why the prior fails: the natural push is at the middle of the box's back face. On a table the friction
|
| 11 |
+
resultant acts below the centre of mass, so a push whose line does not pass near it turns the box: the
|
| 12 |
+
heavy end lags behind. Measured (closed gripper at yaw 0, 8 cm/s, mu 0.5): pushing at the middle turns the
|
| 13 |
+
box 17 to 41 deg; the rectangle (box + 2 cm margin per side) only holds the box up to FIT_ANGLE = 10.9 deg
|
| 14 |
+
(exact geometry, box centred in the rectangle). Pushing within ~2 cm of the centre of mass gives a straight
|
| 15 |
+
translation (< 1 deg); 3 cm off gives 5-14 deg.
|
| 16 |
+
|
| 17 |
+
What must be learned from the failure: the turning direction tells which end is heavy (the end that
|
| 18 |
+
lagged), the amount tells roughly how far off the push was; push closer to the heavy end. F2 reports the box's
|
| 19 |
+
turn (direction and size, plus how far one end lags the other), where the box's centre ended relative to the
|
| 20 |
+
rectangle's centre, and where on the back face the gripper first touched it -- all relative measurements, never
|
| 21 |
+
absolute coordinates or e itself.
|
| 22 |
+
|
| 23 |
+
Pushes per attempt: not limited (2026-10-19, user). Until then the instruction allowed one push per attempt (one
|
| 24 |
+
move command that moves the box) and an attempt with more failed, so that the agent could not steer the box inside
|
| 25 |
+
an attempt; that moved trial and error that belongs inside an attempt to the next attempt. The attempt now succeeds
|
| 26 |
+
when the box ends completely inside the rectangle and upright, however many pushes it took (and every push was made
|
| 27 |
+
with the closed gripper, see below).
|
| 28 |
+
|
| 29 |
+
Error events (logged; they never end the attempt). A "push" is a move_to that moves the box > 1 cm or turns it
|
| 30 |
+
> 3 deg (unchanged definition). After every push the box is classified against the rectangle (`box_fit`):
|
| 31 |
+
over_turned (|yaw| > FIT_ANGLE: it fits at no position), overshot (a corner past the far edge), sideways (a corner
|
| 32 |
+
past a side edge), short (a corner still in front of the near edge, i.e. not pushed far enough yet), inside. A push
|
| 33 |
+
is `bad` when it leaves the box over_turned, overshot or sideways (or tipped over: upright cos < 0.5) -- not inside,
|
| 34 |
+
and not merely short of the rectangle (pushing straight on can fix "short", so pushing the box in in several steps is
|
| 35 |
+
not an error).
|
| 36 |
+
Outcome: n_pushes, n_bad_pushes, n_turned_pushes (bad pushes that left the box over_turned), n_trap_events (pushes
|
| 37 |
+
that took the box from a good state -- inside or short -- into a bad one, i.e. how often the trap fired anew),
|
| 38 |
+
trap_fired = n_bad_pushes > 0, recovered_in_attempt = trap_fired and success, first_push (record of the first push)
|
| 39 |
+
with first_push_yaw_deg and first_interaction_ok (the first push left the box inside, or short and not turned out).
|
| 40 |
+
irrecoverable: the box tipped over (upright cos < 0.5 after a move, < 0.95 after the final settle), fell off the
|
| 41 |
+
table, or went out of reach (its centre beyond world x = X_LOST, where the gripper can no longer be put down in front
|
| 42 |
+
of it at pushing height to push it back, or beyond |y| = Y_LOST); logged with the control step, the attempt goes on.
|
| 43 |
+
|
| 44 |
+
Closed gripper (2026-10-19): the instruction says "with the closed gripper", and a push made with the fingers open
|
| 45 |
+
(> OPEN_W apart when the move starts) now makes the attempt fail (failure "open_gripper" if the box is otherwise
|
| 46 |
+
inside). Reason, measured: open fingers touch the back face at two points ~8 cm apart, so ONE push at the middle of
|
| 47 |
+
the back face goes straight unless |e| > ~7 cm -- 22 of 25 instances (validation seeds 1000-1019, main 3000-3004)
|
| 48 |
+
succeeded that way without the centre of mass ever mattering. The box cannot be grasped, lifted or dragged by
|
| 49 |
+
pressing on its top (9 cm deep, the gripper opens 8 cm; measured), so no rule is needed for that.
|
| 50 |
+
|
| 51 |
+
Correction cost (measured 2026-10-19, task card): after the natural first push (middle, whole distance) the box is
|
| 52 |
+
turned 17-41 deg and lies across the rectangle. What repairs it: get in front of the leading (light) end and push it
|
| 53 |
+
back -- the box turns back with little translation -- then push the box in near the heavy end. The scripted
|
| 54 |
+
corrector (adaptive) did that in attempt 1 on 19 of 20 instances, 7-15 extra commands (median 7: 2 more pushes).
|
| 55 |
+
What does not: pushing the lagging end forward from behind turns the box back only slowly and carries it past the
|
| 56 |
+
rectangle (0 of 25 instances repaired that way; 11 ended out of reach). Near the reach limit the fingers ride up onto
|
| 57 |
+
the box instead of pushing it back. A cautious first push of 3 cm at the middle turns the box only 6.5-10.9 deg (below
|
| 58 |
+
FIT_ANGLE, so no error event) and shows the heavy end; probe + turn back + push in succeeded on 25 of 25 instances in
|
| 59 |
+
11 commands. So the task does not meet design rule R3 (a cost >= 10 commands for the common-sense first interaction);
|
| 60 |
+
its signal is clean success vs. in-attempt recovery (trap_fired / recovered_in_attempt) and first_push_yaw_deg.
|
| 61 |
+
"""
|
| 62 |
+
import numpy as np
|
| 63 |
+
|
| 64 |
+
from .. import envs
|
| 65 |
+
from ..bddl import write_bddl
|
| 66 |
+
from ..objects import _SOLID, _fmt, _wrap, register_generated
|
| 67 |
+
from ..skills import Skills
|
| 68 |
+
from ..task_base import LFFTask, register_task
|
| 69 |
+
|
| 70 |
+
BOX = "box_1"
|
| 71 |
+
HALF = np.array([0.045, 0.11, 0.02]) # 9 (x) x 22 (y, long axis) x 4 cm: too wide for the 8 cm gripper
|
| 72 |
+
MASS = 0.6
|
| 73 |
+
MU = 0.5
|
| 74 |
+
MARGIN = 0.02 # target rectangle = box footprint + 2 cm on every side
|
| 75 |
+
RECT_HALF = HALF[:2] + MARGIN
|
| 76 |
+
E_MIN, E_MAX = 0.045, 0.075
|
| 77 |
+
Z_PUSH = envs.TABLE_Z + 0.02 # grasp-point height during the push (finger tips ~1 cm above the table)
|
| 78 |
+
Z_SAFE = envs.TABLE_Z + 0.12 # travel height of the scripted corrector (8 cm above the box top)
|
| 79 |
+
PUSH_SPEED = 0.08
|
| 80 |
+
FINGER_AHEAD = 0.009 # the closed fingers' front face is ~0.9 cm ahead of the grasp point (measured, yaw 0)
|
| 81 |
+
RUNUP = 0.04
|
| 82 |
+
MOVE_TOL = 0.01 # a command "moved the box" if its centre moved this much ...
|
| 83 |
+
TURN_TOL = np.radians(3.0) # ... or it turned this much
|
| 84 |
+
TOUCH_TOL = 0.002 # the box "started to move" in a command once its centre moved this much
|
| 85 |
+
OPEN_W = 0.01 # finger opening above which a push counts as made with the gripper open (closed on nothing: 0.002 m)
|
| 86 |
+
TABLE_HALF = (0.5, 0.6) # LIBERO main_table top, centred at the world origin (table_collision geom)
|
| 87 |
+
# Reach at pushing height (grasp point 2 cm above the table, yaw 0; measured 2026-10-19): the gripper gets to world
|
| 88 |
+
# x = 0.10 within 1 cm for |y| <= 0.15; asked for more it stops at x ~ 0.13-0.17, sagging to the table. Pushing a box
|
| 89 |
+
# back from in front of it (measured, box not turned): still works with the box's centre at x = 0.125 (far face at
|
| 90 |
+
# 0.17); with the centre at 0.135 the fingers ride up onto the box or push it further away. A box turned 25 deg with
|
| 91 |
+
# its centre at 0.113 (far corner at 0.20) was still pushed back. So a box whose centre is past X_LOST counts as out of
|
| 92 |
+
# reach. The rectangle's far edge lies at world x = -0.055 ... 0.055.
|
| 93 |
+
X_LOST = 0.13
|
| 94 |
+
Y_LOST = 0.40
|
| 95 |
+
X_DOWN = 0.14 # farthest x at which the scripted corrector puts the gripper down in front of the box
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _fit_angle(half=HALF[:2], rect=RECT_HALF):
|
| 99 |
+
"""Largest |yaw| at which the box's footprint still fits inside the rectangle (box centred in it): the
|
| 100 |
+
rotated footprint's half extents are (a cos t + b sin t, a sin t + b cos t)."""
|
| 101 |
+
t = np.radians(np.arange(0.0, 90.0, 0.01))
|
| 102 |
+
ok = (half[0] * np.cos(t) + half[1] * np.sin(t) <= rect[0]) & (half[0] * np.sin(t) + half[1] * np.cos(t) <= rect[1])
|
| 103 |
+
return float(t[np.argmin(ok)] - np.radians(0.01)) if not ok.all() else np.pi / 2
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
FIT_ANGLE = _fit_angle() # 10.9 deg
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def long_box_xml(name, half=HALF, mass=MASS, rgba=(0.72, 0.53, 0.33, 1.0), tape_rgba=(0.88, 0.80, 0.62, 1.0)):
|
| 110 |
+
"""Solid box with an explicit inertial whose position is offset from the body origin at compile time, so
|
| 111 |
+
MuJoCo keeps the inertial frame separate (sameframe would otherwise ignore later changes of body_ipos)."""
|
| 112 |
+
I = mass / 12 * np.array([4 * (half[1] ** 2 + half[2] ** 2), 4 * (half[0] ** 2 + half[2] ** 2),
|
| 113 |
+
4 * (half[0] ** 2 + half[1] ** 2)])
|
| 114 |
+
tape = (half[0] + 0.0005, 0.012, 0.0006)
|
| 115 |
+
g = (f' <inertial pos="0 0.001 0" mass="{mass}" diaginertia="{_fmt(I)}" />\n'
|
| 116 |
+
f' <geom name="{name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 117 |
+
f'friction="1.0 0.005 0.0001" {_SOLID} group="0" />\n'
|
| 118 |
+
f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />\n'
|
| 119 |
+
f' <geom type="box" pos="0 0 {half[2]:.5f}" size="{_fmt(tape)}" rgba="{_fmt(tape_rgba)}" '
|
| 120 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 121 |
+
return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def rect_frame_xml(name, inner_half=RECT_HALF, line_w=0.006, line_rgba=(0.1, 0.55, 0.15, 1.0),
|
| 125 |
+
fill_rgba=(0.75, 0.92, 0.75, 1.0)):
|
| 126 |
+
"""Flat, visual-only rectangle drawn on the table (light fill + dark outline, no collisions)."""
|
| 127 |
+
hx, hy = inner_half
|
| 128 |
+
ox, oy = hx + line_w, hy + line_w
|
| 129 |
+
parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill_rgba),
|
| 130 |
+
((0, hy + line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba),
|
| 131 |
+
((0, -hy - line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba),
|
| 132 |
+
((hx + line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba),
|
| 133 |
+
((-hx - line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba)]
|
| 134 |
+
g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
|
| 135 |
+
f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
|
| 136 |
+
return _wrap(name, g, 0.0012, float(np.hypot(ox, oy)))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _yaw(quat_wxyz):
|
| 140 |
+
w, x, y, z = quat_wxyz
|
| 141 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _rot(a):
|
| 145 |
+
return np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _wrap_pi(a):
|
| 149 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def box_corners(p_xy, yaw):
|
| 153 |
+
R = _rot(yaw)
|
| 154 |
+
return np.array([np.asarray(p_xy[:2], float) + R @ np.array([sx * HALF[0], sy * HALF[1]])
|
| 155 |
+
for sx in (-1, 1) for sy in (-1, 1)])
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def box_fit(p_xy, yaw, t_xy):
|
| 159 |
+
"""The box's footprint against the (axis-aligned) target rectangle centred at t_xy. bad = it cannot get into the
|
| 160 |
+
rectangle by being pushed straight on: turned beyond FIT_ANGLE, a corner past the far edge, or past a side edge."""
|
| 161 |
+
c = box_corners(p_xy, yaw) - np.asarray(t_xy, float)[:2]
|
| 162 |
+
eps = 1e-6
|
| 163 |
+
inside = bool(np.all(np.abs(c[:, 0]) <= RECT_HALF[0] + eps) and np.all(np.abs(c[:, 1]) <= RECT_HALF[1] + eps))
|
| 164 |
+
yw = (yaw + np.pi / 2) % np.pi - np.pi / 2 # the footprint is symmetric under a half turn
|
| 165 |
+
over = bool(abs(yw) > FIT_ANGLE)
|
| 166 |
+
overshot = bool(np.any(c[:, 0] > RECT_HALF[0] + eps))
|
| 167 |
+
sideways = bool(np.any(np.abs(c[:, 1]) > RECT_HALF[1] + eps))
|
| 168 |
+
short = bool(np.any(c[:, 0] < -RECT_HALF[0] - eps))
|
| 169 |
+
return dict(inside=inside, over_turned=over, overshot=overshot, sideways=sideways, short=short,
|
| 170 |
+
bad=bool(over or overshot or sideways))
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _lr(v, unit="cm"):
|
| 174 |
+
return f"{100 * abs(v):.1f} {unit} to the {'left' if v > 0 else 'right'}"
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _fb(v):
|
| 178 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _turn_words(deg):
|
| 182 |
+
return f"{abs(deg):.0f} degrees {'counterclockwise' if deg > 0 else 'clockwise'}"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class _Budget(Exception):
|
| 186 |
+
"""the scripted policy used up the agent command budget of the attempt"""
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class PushSkills(Skills):
|
| 190 |
+
"""Skills that log, for whoever drives them (scripted policy or agent), which move_to commands moved the
|
| 191 |
+
box (pushes), where the gripper touched it, the box's state after every push, and whether the box was lost."""
|
| 192 |
+
|
| 193 |
+
def __init__(self, env, bias=None, recorder=None, target=None):
|
| 194 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 195 |
+
self.target = None if target is None else np.asarray(target, float)[:2]
|
| 196 |
+
self.first_touch = None # where the gripper's centre was (box frame) when the box first moved
|
| 197 |
+
self._p0, self._yaw0 = self._box_pose()
|
| 198 |
+
self.box_moves = [] # one entry per move_to that moved / turned the box (a "push")
|
| 199 |
+
self.n_moves = 0 # move_to commands (an agent's move_eef with a motion = one move_to)
|
| 200 |
+
self.lost = {} # irrecoverable condition -> control step at which it was first seen
|
| 201 |
+
self._mv = None # the move_to in progress: box pose at its start, first touch inside it
|
| 202 |
+
|
| 203 |
+
def _box_pose(self):
|
| 204 |
+
p = envs.obj_pos(self.env, BOX)
|
| 205 |
+
return p, _yaw(envs.obj_quat(self.env, BOX))
|
| 206 |
+
|
| 207 |
+
def _local(self, p0, yaw0):
|
| 208 |
+
"""gripper centre in the box frame given by (p0, yaw0): (u along the short side, v along the long side)"""
|
| 209 |
+
return (_rot(yaw0).T @ (self.eef_pos()[:2] - p0[:2])).tolist()
|
| 210 |
+
|
| 211 |
+
def _act(self, dpos, drot, grip):
|
| 212 |
+
super()._act(dpos, drot, grip)
|
| 213 |
+
if self.first_touch is None or (self._mv is not None and self._mv["touch"] is None):
|
| 214 |
+
# "touch" = the first control step at which the box has moved 2 mm. Detected from the box's motion,
|
| 215 |
+
# not from contacts: a stiff gripper pushing a box makes a stick-slip contact that is often absent at the
|
| 216 |
+
# control-step boundaries (measured), so contact polling misses pushes.
|
| 217 |
+
p, _ = self._box_pose()
|
| 218 |
+
if self.first_touch is None and np.linalg.norm(p[:2] - self._p0[:2]) > TOUCH_TOL:
|
| 219 |
+
self.first_touch = dict(local=self._local(self._p0, self._yaw0), step=self.n_steps)
|
| 220 |
+
if self._mv is not None and self._mv["touch"] is None and np.linalg.norm(p[:2] - self._mv["p0"][:2]) > TOUCH_TOL:
|
| 221 |
+
self._mv["touch"] = self._local(self._mv["p0"], self._mv["yaw0"])
|
| 222 |
+
|
| 223 |
+
def fit(self, p=None, yaw=None):
|
| 224 |
+
if p is None:
|
| 225 |
+
p, yaw = self._box_pose()
|
| 226 |
+
return box_fit(p[:2], yaw, self.target) if self.target is not None else None
|
| 227 |
+
|
| 228 |
+
def check_lost(self, final=False):
|
| 229 |
+
"""record irrecoverable box states (tipped, off the table, out of reach); returns the current ones"""
|
| 230 |
+
p, _ = self._box_pose()
|
| 231 |
+
up = envs.obj_upright_cos(self.env, BOX)
|
| 232 |
+
now = []
|
| 233 |
+
if up < (0.95 if final else 0.5):
|
| 234 |
+
now.append("tipped")
|
| 235 |
+
if p[2] < envs.TABLE_Z - 0.02 or abs(p[0]) > TABLE_HALF[0] or abs(p[1]) > TABLE_HALF[1]:
|
| 236 |
+
now.append("off_table")
|
| 237 |
+
elif p[0] > X_LOST or abs(p[1]) > Y_LOST:
|
| 238 |
+
now.append("out_of_reach")
|
| 239 |
+
for w in now:
|
| 240 |
+
self.lost.setdefault(w, self.n_steps)
|
| 241 |
+
return now
|
| 242 |
+
|
| 243 |
+
def move_to(self, target, *args, **kwargs):
|
| 244 |
+
p0, y0 = self._box_pose()
|
| 245 |
+
fit0 = self.fit(p0, y0)
|
| 246 |
+
bad0 = fit0 is not None and (fit0["bad"] or envs.obj_upright_cos(self.env, BOX) < 0.5)
|
| 247 |
+
self._mv = dict(p0=p0, yaw0=y0, touch=None)
|
| 248 |
+
width0 = self.gripper_width()
|
| 249 |
+
self.n_moves += 1
|
| 250 |
+
try:
|
| 251 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 252 |
+
finally:
|
| 253 |
+
mv, self._mv = self._mv, None
|
| 254 |
+
p1, y1 = self._box_pose()
|
| 255 |
+
dturn = _wrap_pi(y1 - y0)
|
| 256 |
+
if np.linalg.norm(p1[:2] - p0[:2]) > MOVE_TOL or abs(dturn) > TURN_TOL:
|
| 257 |
+
rec = dict(step=self.n_steps, moved_cm=round(100 * float(np.linalg.norm(p1[:2] - p0[:2])), 1),
|
| 258 |
+
turned_deg=round(float(np.degrees(dturn)), 1), yaw_deg=round(float(np.degrees(y1)), 1),
|
| 259 |
+
gripper_open=bool(width0 > OPEN_W))
|
| 260 |
+
t = mv["touch"]
|
| 261 |
+
if t is not None:
|
| 262 |
+
u, v = t
|
| 263 |
+
face = ("back" if u < -HALF[0] + 0.005 else "front" if u > HALF[0] - 0.005 else
|
| 264 |
+
"left_end" if v > 0 else "right_end")
|
| 265 |
+
rec.update(touch_u=round(float(u), 4), touch_v=round(float(v), 4), face=face)
|
| 266 |
+
fit1 = self.fit(p1, y1)
|
| 267 |
+
if fit1 is not None:
|
| 268 |
+
tipped = envs.obj_upright_cos(self.env, BOX) < 0.5
|
| 269 |
+
bad = bool(fit1["bad"] or tipped)
|
| 270 |
+
rec.update(inside=fit1["inside"] and not tipped, over_turned=fit1["over_turned"],
|
| 271 |
+
overshot=fit1["overshot"], sideways=fit1["sideways"], tipped=bool(tipped), bad=bad,
|
| 272 |
+
new_trap=bool(bad and not bad0))
|
| 273 |
+
self.box_moves.append(rec)
|
| 274 |
+
self.check_lost()
|
| 275 |
+
return rep
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@register_task
|
| 279 |
+
class OffcenterPush(LFFTask):
|
| 280 |
+
name = "l7_offcenter_push"
|
| 281 |
+
level = "L7"
|
| 282 |
+
category = "failed_interaction_inference"
|
| 283 |
+
capabilities = ("Perceive", "Reason", "Utilize")
|
| 284 |
+
protocol = "cross"
|
| 285 |
+
# 2026-10-19 (wording): the instruction states only the end state. "straight forward ... without turning" read as
|
| 286 |
+
# a rule on the motion (no turning on the way, push only forward), but success is judged on the end state alone
|
| 287 |
+
# (completely inside the rectangle -- which bounds the turn to FIT_ANGLE -- upright, every push with the closed
|
| 288 |
+
# gripper), and the repair that works pushes the leading end back from in front of the box.
|
| 289 |
+
instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the "
|
| 290 |
+
"green rectangle ahead of it (farther from the robot).")
|
| 291 |
+
instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up "
|
| 292 |
+
"completely inside the marked green area ahead of it (farther from the robot).")
|
| 293 |
+
|
| 294 |
+
# ------------------------------------------------------------ scene
|
| 295 |
+
def make_bddl(self):
|
| 296 |
+
box = register_generated("LffL7LongBox", long_box_xml("lff_l7_long_box"))
|
| 297 |
+
zone = register_generated("LffL7TargetRect", rect_frame_xml("lff_l7_target_rect"), free=False)
|
| 298 |
+
objs = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))]
|
| 299 |
+
fixtures = [("zone_1", zone, "zone_region", (-0.06, -0.01, -0.04, 0.01))]
|
| 300 |
+
return write_bddl(self.name, "push the long box into the green rectangle", objs, fixtures=fixtures)
|
| 301 |
+
|
| 302 |
+
def sample_instance(self, seed):
|
| 303 |
+
rng = np.random.default_rng(seed)
|
| 304 |
+
e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX))
|
| 305 |
+
return dict(seed=int(seed), box_xy=[float(rng.uniform(-0.20, -0.14)), float(rng.uniform(-0.08, 0.08))],
|
| 306 |
+
target_dist=float(rng.uniform(0.08, 0.13)), com_offset=e)
|
| 307 |
+
|
| 308 |
+
def target_xy(self, inst):
|
| 309 |
+
return np.array([inst["box_xy"][0] + inst["target_dist"], inst["box_xy"][1]])
|
| 310 |
+
|
| 311 |
+
def apply_instance(self, inst):
|
| 312 |
+
m = self.env.sim.model
|
| 313 |
+
zone = self.env.fixtures_dict["zone_1"]
|
| 314 |
+
for g in range(m.ngeom): # the rectangle is a flat marker
|
| 315 |
+
if (m.geom_id2name(g) or "").startswith("zone_1_"):
|
| 316 |
+
m.geom_contype[g] = 0
|
| 317 |
+
m.geom_conaffinity[g] = 0
|
| 318 |
+
t = self.target_xy(inst)
|
| 319 |
+
zb = m.body_name2id(zone.root_body)
|
| 320 |
+
m.body_pos[zb] = [t[0], t[1], envs.TABLE_Z + 0.0002]
|
| 321 |
+
m.body_quat[zb] = [1.0, 0.0, 0.0, 0.0]
|
| 322 |
+
bid = envs.body_id(self.env, BOX)
|
| 323 |
+
m.body_mass[bid] = MASS
|
| 324 |
+
m.body_ipos[bid] = [0.0, inst["com_offset"], 0.0]
|
| 325 |
+
envs.refit_bounds(self.env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds)
|
| 326 |
+
envs.set_friction(self.env, BOX, MU)
|
| 327 |
+
x0, y0 = inst["box_xy"]
|
| 328 |
+
envs.set_obj_pose(self.env, BOX, [x0, y0, envs.TABLE_Z + HALF[2] + 0.001])
|
| 329 |
+
|
| 330 |
+
def reset_instance(self, inst, recorder=None):
|
| 331 |
+
self.env.reset()
|
| 332 |
+
self.apply_instance(inst)
|
| 333 |
+
self.env.sim.forward()
|
| 334 |
+
envs.settle(self.env, 10)
|
| 335 |
+
self.sk = PushSkills(self.env, recorder=recorder, target=self.target_xy(inst))
|
| 336 |
+
self.sim0 = self.sk.n_steps
|
| 337 |
+
return self.sk
|
| 338 |
+
|
| 339 |
+
# ------------------------------------------------------------ outcome
|
| 340 |
+
def outcome(self, inst):
|
| 341 |
+
envs.settle(self.env, 30)
|
| 342 |
+
sk = self.sk
|
| 343 |
+
p = envs.obj_pos(self.env, BOX)
|
| 344 |
+
yaw = _yaw(envs.obj_quat(self.env, BOX))
|
| 345 |
+
t = self.target_xy(inst)
|
| 346 |
+
fit = box_fit(p[:2], yaw, t)
|
| 347 |
+
inside = fit["inside"]
|
| 348 |
+
upright = envs.obj_upright_cos(self.env, BOX) > 0.95
|
| 349 |
+
sk.check_lost(final=True)
|
| 350 |
+
pushes = sk.box_moves
|
| 351 |
+
n_push = len(pushes)
|
| 352 |
+
n_bad = sum(bool(m.get("bad")) for m in pushes)
|
| 353 |
+
n_open = sum(bool(m.get("gripper_open")) for m in pushes)
|
| 354 |
+
off = p[:2] - t
|
| 355 |
+
lag = 2 * HALF[1] * np.sin(yaw) # how far the +y end is behind (+) the -y end along x
|
| 356 |
+
success = bool(inside and upright and n_open == 0)
|
| 357 |
+
first = pushes[0] if pushes else None
|
| 358 |
+
out = dict(success=success, inside=bool(inside), upright=bool(upright),
|
| 359 |
+
n_pushes=n_push, n_bad_pushes=n_bad,
|
| 360 |
+
n_turned_pushes=sum(bool(m.get("over_turned")) for m in pushes),
|
| 361 |
+
n_trap_events=sum(bool(m.get("new_trap")) for m in pushes),
|
| 362 |
+
trap_fired=n_bad > 0, recovered_in_attempt=bool(n_bad and success),
|
| 363 |
+
first_push=first, first_push_yaw_deg=None if first is None else first["yaw_deg"],
|
| 364 |
+
first_interaction_ok=None if first is None else bool(not first.get("bad")),
|
| 365 |
+
n_open_gripper_pushes=n_open,
|
| 366 |
+
irrecoverable=bool(sk.lost), irrecoverable_why=dict(sk.lost),
|
| 367 |
+
n_box_moving_commands=n_push, box_moves=pushes, n_move_commands=sk.n_moves,
|
| 368 |
+
sim_s=round((sk.n_steps - getattr(self, "sim0", 0)) * 0.05, 1),
|
| 369 |
+
yaw_deg=round(float(np.degrees(yaw)), 1),
|
| 370 |
+
centre_offset=[round(float(off[0]), 4), round(float(off[1]), 4)],
|
| 371 |
+
touch_offset=None)
|
| 372 |
+
parts = []
|
| 373 |
+
if sk.first_touch is None:
|
| 374 |
+
out["failure"] = "not_touched"
|
| 375 |
+
parts.append("The box did not move: the gripper never pushed it.")
|
| 376 |
+
else:
|
| 377 |
+
lt = sk.first_touch["local"]
|
| 378 |
+
out["touch_offset"] = round(float(lt[1]), 4)
|
| 379 |
+
if success:
|
| 380 |
+
parts.append("The box is completely inside the rectangle.")
|
| 381 |
+
elif not upright:
|
| 382 |
+
out["failure"] = "tipped"
|
| 383 |
+
parts.append("The box tipped over.")
|
| 384 |
+
elif inside:
|
| 385 |
+
out["failure"] = "open_gripper"
|
| 386 |
+
parts.append("The box is completely inside the rectangle, but it was pushed with the gripper open; "
|
| 387 |
+
"the task asks for pushing with the closed gripper.")
|
| 388 |
+
else:
|
| 389 |
+
out["failure"] = "turned" if abs(np.degrees(yaw)) > 6 else "position"
|
| 390 |
+
parts.append("The box is not completely inside the rectangle.")
|
| 391 |
+
if n_push > 1:
|
| 392 |
+
txt = f"It was moved by {n_push} separate move commands"
|
| 393 |
+
if abs(first["yaw_deg"]) >= 1.0:
|
| 394 |
+
txt += f"; after the first one it had turned {_turn_words(first['yaw_deg'])} (seen from above)"
|
| 395 |
+
parts.append(txt + ".")
|
| 396 |
+
if n_open and out.get("failure") != "open_gripper":
|
| 397 |
+
parts.append("The gripper was open during " + ("that push." if n_push == 1 else
|
| 398 |
+
f"{n_open} of the pushes."))
|
| 399 |
+
turn = np.degrees(yaw)
|
| 400 |
+
if abs(turn) >= 1.0:
|
| 401 |
+
parts.append(f"It {'ended up turned' if n_push > 1 else 'turned'} {_turn_words(turn)} (seen from "
|
| 402 |
+
f"above): its {'left' if lag > 0 else 'right'} end ended {100 * abs(lag):.1f} cm "
|
| 403 |
+
f"further back than its {'right' if lag > 0 else 'left'} end.")
|
| 404 |
+
else:
|
| 405 |
+
parts.append("It did not turn (less than 1 degree)." if n_push <= 1 else
|
| 406 |
+
"It ended up not turned (less than 1 degree).")
|
| 407 |
+
parts.append(f"Its centre ended {_fb(off[0])} and {_lr(off[1])} of the rectangle's centre.")
|
| 408 |
+
parts.append(f"When the box started to move, the gripper's centre was {_lr(lt[1])} of the middle of "
|
| 409 |
+
f"the box (measured along the box's long side).")
|
| 410 |
+
out["detail"] = " ".join(parts)
|
| 411 |
+
return out
|
| 412 |
+
|
| 413 |
+
# ------------------------------------------------------------ scripted primitives (agent-command counted)
|
| 414 |
+
def _cmd(self, target, yaw=None, speed=None, tol=0.004, max_steps=250):
|
| 415 |
+
"""one agent command (move_eef; a gripper change rides on a move)"""
|
| 416 |
+
self.ncmd = getattr(self, "ncmd", 0) + 1
|
| 417 |
+
budget = getattr(self, "budget", None)
|
| 418 |
+
if budget is not None and self.ncmd > budget:
|
| 419 |
+
raise _Budget()
|
| 420 |
+
self.sk.move_to(target, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 421 |
+
if budget is not None and self._sim_used() >= 3.0 * budget: # the server's motion budget (3 s per command)
|
| 422 |
+
raise _Budget()
|
| 423 |
+
|
| 424 |
+
def _sim_used(self):
|
| 425 |
+
return (self.sk.n_steps - getattr(self, "sim0", 0)) * 0.05
|
| 426 |
+
|
| 427 |
+
def _push_at(self, face, v, dist, speed=PUSH_SPEED, runup=RUNUP):
|
| 428 |
+
"""One push on the box as it lies now, with the closed gripper rotated to the face: face "back" (push
|
| 429 |
+
forward along the box's short side), "front" (push backwards) at long-side coordinate v (box frame), or
|
| 430 |
+
"left_end" / "right_end" (push along the long side at the middle of that end face). `dist` = how far the
|
| 431 |
+
fingers' front travels past the face. Commands: up (if low, 1), above the run-up point (1), down (1), push (1)."""
|
| 432 |
+
sk = self.sk
|
| 433 |
+
p, yaw = sk._box_pose()
|
| 434 |
+
R = _rot(yaw)
|
| 435 |
+
if face in ("back", "front"):
|
| 436 |
+
s = -1.0 if face == "back" else 1.0
|
| 437 |
+
n, q, gyaw = R @ np.array([s, 0.0]), p[:2] + R @ np.array([s * HALF[0], v]), yaw
|
| 438 |
+
else:
|
| 439 |
+
s = 1.0 if face == "left_end" else -1.0
|
| 440 |
+
n, q, gyaw = R @ np.array([0.0, s]), p[:2] + R @ np.array([0.0, s * HALF[1]]), yaw + np.pi / 2
|
| 441 |
+
start = q + n * (runup + FINGER_AHEAD)
|
| 442 |
+
end = q - n * (dist - FINGER_AHEAD)
|
| 443 |
+
e = sk.eef_pos()
|
| 444 |
+
if e[2] < Z_PUSH + 0.05:
|
| 445 |
+
self._cmd([e[0], e[1], Z_SAFE], speed=0.2)
|
| 446 |
+
self._cmd([start[0], start[1], Z_SAFE], yaw=gyaw)
|
| 447 |
+
self._cmd([start[0], start[1], Z_PUSH], tol=0.003)
|
| 448 |
+
self._cmd([end[0], end[1], Z_PUSH], speed=speed, tol=0.004, max_steps=400)
|
| 449 |
+
|
| 450 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 451 |
+
def execute(self, inst, params):
|
| 452 |
+
"""Closed gripper behind the box at lateral offset `c` (from the box's middle, along its long axis), then one
|
| 453 |
+
slow straight move_to forward ending `end_dx` beyond the nominal end point (target centre minus half the box
|
| 454 |
+
depth minus the finger offset), then lift. 4 commands (the gripper closes with the first one)."""
|
| 455 |
+
sk = self.sk
|
| 456 |
+
p = envs.obj_pos(self.env, BOX) # perfect perception of the current scene
|
| 457 |
+
t = self.target_xy(inst)
|
| 458 |
+
c = float(params["c"])
|
| 459 |
+
y = p[1] + c
|
| 460 |
+
face = p[0] - HALF[0]
|
| 461 |
+
x_end = t[0] - HALF[0] - FINGER_AHEAD + float(params.get("end_dx", 0.0))
|
| 462 |
+
sk.set_gripper(True, steps=8)
|
| 463 |
+
self._cmd([face - RUNUP, y, Z_PUSH + 0.08], yaw=0.0)
|
| 464 |
+
self._cmd([face - RUNUP, y, Z_PUSH], tol=0.003)
|
| 465 |
+
self._cmd([x_end, y, Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400)
|
| 466 |
+
self._cmd([x_end - 0.03, y, Z_PUSH + 0.10], speed=0.2)
|
| 467 |
+
|
| 468 |
+
def default_params(self, inst):
|
| 469 |
+
return dict(c=0.0, end_dx=0.0) # Sonnet 5.5 (cla2 / cla4 / full5): yaw 0, middle of the back face, one push
|
| 470 |
+
|
| 471 |
+
def oracle_params(self, inst):
|
| 472 |
+
return dict(c=float(inst["com_offset"]), end_dx=0.0)
|
| 473 |
+
|
| 474 |
+
STEP = 0.06 # first correction toward the lagging end (the expected |e| range is unknown to the learner)
|
| 475 |
+
YAW_OK = 3.0 # deg: the corrector turns the box back until it is within this
|
| 476 |
+
GAIN0 = 2.8 # deg of turn per cm of a push at the leading end from the front, 3 cm from the end (measured)
|
| 477 |
+
SAFE_V = HALF[1] - 0.02 # contact points stay 2 cm inside the ends
|
| 478 |
+
|
| 479 |
+
def bracket(self, pushes):
|
| 480 |
+
"""Contact point estimate from logged pushes on the back / front face: a push whose box turned
|
| 481 |
+
counterclockwise passed to the right of the centre of mass when pushing forward (back face) and to its left
|
| 482 |
+
when pushing backwards (front face); a long push that did not turn passed within ~2 cm of it."""
|
| 483 |
+
lo, hi = -self.SAFE_V, self.SAFE_V
|
| 484 |
+
lo_set = hi_set = False
|
| 485 |
+
for m in pushes:
|
| 486 |
+
if m.get("face") not in ("back", "front") or m.get("gripper_open"):
|
| 487 |
+
continue
|
| 488 |
+
v, turn = m["touch_v"], m["turned_deg"] * (1.0 if m["face"] == "back" else -1.0)
|
| 489 |
+
if turn > 3.0:
|
| 490 |
+
lo, lo_set = max(lo, v + 0.01), True
|
| 491 |
+
elif turn < -3.0:
|
| 492 |
+
hi, hi_set = min(hi, v - 0.01), True
|
| 493 |
+
elif abs(turn) < 1.5 and m["moved_cm"] >= 3.0:
|
| 494 |
+
lo, hi, lo_set, hi_set = max(lo, v - 0.02), min(hi, v + 0.02), True, True
|
| 495 |
+
if lo > hi: # inconsistent (contacts slide): trust the newest
|
| 496 |
+
lo, hi = hi, lo
|
| 497 |
+
if lo_set and hi_set:
|
| 498 |
+
c = 0.5 * (lo + hi)
|
| 499 |
+
elif lo_set:
|
| 500 |
+
c = lo + self.STEP
|
| 501 |
+
elif hi_set:
|
| 502 |
+
c = hi - self.STEP
|
| 503 |
+
else:
|
| 504 |
+
c = 0.0
|
| 505 |
+
return float(np.clip(c, -self.SAFE_V, self.SAFE_V))
|
| 506 |
+
|
| 507 |
+
def adapt_params(self, inst, history):
|
| 508 |
+
"""Cross-attempt start point: push where the pushes of the earlier attempts put the centre of mass."""
|
| 509 |
+
return dict(c=round(self.bracket([m for h in history for m in h["outcome"]["box_moves"]]), 4), end_dx=0.0)
|
| 510 |
+
|
| 511 |
+
@staticmethod
|
| 512 |
+
def _front_runup(p, yaw, v):
|
| 513 |
+
"""run-up for a push on the front face at v that keeps the gripper's put-down point within X_DOWN; None when
|
| 514 |
+
even a 1.5 cm run-up does not fit (the box is too far forward to get in front of it)"""
|
| 515 |
+
R = _rot(yaw)
|
| 516 |
+
f, n_out = p[:2] + R @ np.array([HALF[0], v]), R @ np.array([1.0, 0.0])
|
| 517 |
+
runup = min(RUNUP, (X_DOWN - f[0]) / max(n_out[0], 0.2) - FINGER_AHEAD)
|
| 518 |
+
return float(runup) if runup >= 0.015 else None
|
| 519 |
+
|
| 520 |
+
def adaptive_attempt(self, inst, c0, prior_pushes=()):
|
| 521 |
+
"""In-attempt corrector: the first push as `execute` (at c0: the middle in attempt 1, like the naive policy);
|
| 522 |
+
then, after every push, look at the box (perfect perception) and push again until it is inside or the agent
|
| 523 |
+
budget would run out. Turned more than YAW_OK -> push its leading end back from the front (it turns back with
|
| 524 |
+
little translation), or if it is too far forward for that, the lagging end forward from behind; not turned
|
| 525 |
+
but short / past the far edge / out at a side -> push it straight from behind / from the front at the
|
| 526 |
+
estimated centre of mass, or along its long side at an end face. Returns the number of corrective pushes."""
|
| 527 |
+
self.execute(inst, dict(c=c0, end_dx=0.0))
|
| 528 |
+
sk = self.sk
|
| 529 |
+
t = self.target_xy(inst)
|
| 530 |
+
gain = self.GAIN0
|
| 531 |
+
sim_budget = 3.0 * self.budget if self.budget is not None else np.inf
|
| 532 |
+
n = 0
|
| 533 |
+
while True:
|
| 534 |
+
p, yaw = sk._box_pose()
|
| 535 |
+
fit = sk.fit(p, yaw)
|
| 536 |
+
if fit["inside"] or sk.lost:
|
| 537 |
+
return n
|
| 538 |
+
if (self.budget is not None and self.ncmd + 4 > self.budget) or self._sim_used() + 10.0 > sim_budget:
|
| 539 |
+
return n
|
| 540 |
+
n += 1
|
| 541 |
+
yd = np.degrees(yaw)
|
| 542 |
+
c_est = self.bracket(list(prior_pushes) + sk.box_moves)
|
| 543 |
+
if abs(yd) > self.YAW_OK:
|
| 544 |
+
for vm in (HALF[1] - 0.03, 0.06, 0.04, 0.02): # the leading (light) end, or nearer the middle if
|
| 545 |
+
v_lead = -np.sign(yd) * vm # the end is out of reach; +v = the box's left end
|
| 546 |
+
runup = self._front_runup(p, yaw, v_lead)
|
| 547 |
+
if runup is not None:
|
| 548 |
+
break
|
| 549 |
+
if runup is not None:
|
| 550 |
+
d = float(np.clip(abs(yd) / gain, 1.0, 10.0)) / 100
|
| 551 |
+
self._push_at("front", v_lead, d, runup=runup)
|
| 552 |
+
dy = abs(yd) - abs(np.degrees(sk._box_pose()[1]))
|
| 553 |
+
if dy > 1.0:
|
| 554 |
+
gain = float(np.clip(dy / (100 * d), 1.0, 5.0))
|
| 555 |
+
else:
|
| 556 |
+
self._push_at("back", np.sign(yd) * (HALF[1] - 0.01), 0.03)
|
| 557 |
+
else:
|
| 558 |
+
dx = t[0] - p[0]
|
| 559 |
+
if fit["overshot"]:
|
| 560 |
+
runup = self._front_runup(p, yaw, c_est)
|
| 561 |
+
if runup is None:
|
| 562 |
+
return n
|
| 563 |
+
self._push_at("front", c_est, max(0.005, -dx), runup=runup)
|
| 564 |
+
elif fit["sideways"]:
|
| 565 |
+
dyy = t[1] - p[1]
|
| 566 |
+
self._push_at("right_end" if dyy > 0 else "left_end", 0.0, max(0.005, abs(dyy) - 0.005))
|
| 567 |
+
else:
|
| 568 |
+
self._push_at("back", c_est, max(0.005, dx))
|
| 569 |
+
|
| 570 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 571 |
+
"""Cross protocol with the agent's command budget per attempt (agent_max_steps, default 40 commands and
|
| 572 |
+
3 s of motion per command; one move_eef = one command). naive / oracle / blind: one push, then finish.
|
| 573 |
+
adaptive: in-attempt corrector (`adaptive_attempt`); attempt 1 starts with the naive push, later attempts
|
| 574 |
+
at the contact point estimated from all earlier pushes."""
|
| 575 |
+
k = k or self.max_attempts
|
| 576 |
+
rng = np.random.default_rng(seed)
|
| 577 |
+
history = []
|
| 578 |
+
for a in range(k):
|
| 579 |
+
self.reset_instance(inst)
|
| 580 |
+
self.ncmd, self.budget = 0, int(getattr(self, "agent_max_steps", 40))
|
| 581 |
+
if kind == "oracle":
|
| 582 |
+
params = self.oracle_params(inst)
|
| 583 |
+
elif kind == "naive":
|
| 584 |
+
params = self.default_params(inst)
|
| 585 |
+
elif kind == "blind":
|
| 586 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 587 |
+
elif kind == "adaptive":
|
| 588 |
+
params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history)
|
| 589 |
+
else:
|
| 590 |
+
raise ValueError(kind)
|
| 591 |
+
try:
|
| 592 |
+
if kind == "adaptive":
|
| 593 |
+
prior = [m for h in history for m in h["outcome"]["box_moves"]]
|
| 594 |
+
params["corrections"] = self.adaptive_attempt(inst, params["c"], prior)
|
| 595 |
+
else:
|
| 596 |
+
self.execute(inst, params)
|
| 597 |
+
except _Budget:
|
| 598 |
+
params["budget_used_up"] = True
|
| 599 |
+
self.budget = None
|
| 600 |
+
out = self.outcome(inst)
|
| 601 |
+
out["commands"] = self.ncmd
|
| 602 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 603 |
+
if on_attempt:
|
| 604 |
+
on_attempt(a, params, out)
|
| 605 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 606 |
+
break
|
| 607 |
+
return history
|
| 608 |
+
|
| 609 |
+
blind_sigma = 0.008
|
| 610 |
+
|
| 611 |
+
def blind_params(self, inst, attempt, rng):
|
| 612 |
+
"""Same plan (push at the middle) with a small random variation of the contact point; no history."""
|
| 613 |
+
return dict(c=float(rng.normal(0.0, self.blind_sigma)), end_dx=0.0)
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/context.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/agent/runlog.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run directory: config.json, events.jsonl (one JSON object per line), images/, summary.json."""
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from .images import encode_jpeg, resize
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _default(o):
|
| 12 |
+
if isinstance(o, np.ndarray):
|
| 13 |
+
return o.tolist()
|
| 14 |
+
if isinstance(o, (np.floating,)):
|
| 15 |
+
return float(o)
|
| 16 |
+
if isinstance(o, (np.integer,)):
|
| 17 |
+
return int(o)
|
| 18 |
+
if isinstance(o, (np.bool_,)):
|
| 19 |
+
return bool(o)
|
| 20 |
+
if hasattr(o, "__dataclass_fields__"):
|
| 21 |
+
return {k: getattr(o, k) for k in o.__dataclass_fields__}
|
| 22 |
+
return str(o)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def dumps(obj):
|
| 26 |
+
return json.dumps(obj, default=_default)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class RunLogger:
|
| 30 |
+
def __init__(self, run_dir, save_images=True, jpeg_quality=90):
|
| 31 |
+
self.run_dir = run_dir
|
| 32 |
+
self.save_images = save_images
|
| 33 |
+
self.jpeg_quality = jpeg_quality
|
| 34 |
+
os.makedirs(os.path.join(run_dir, "images"), exist_ok=True)
|
| 35 |
+
self.f = open(os.path.join(run_dir, "events.jsonl"), "a")
|
| 36 |
+
self.t0 = time.time()
|
| 37 |
+
|
| 38 |
+
def event(self, type, **fields):
|
| 39 |
+
rec = dict(type=type, t=round(time.time() - self.t0, 3), **fields)
|
| 40 |
+
self.f.write(dumps(rec) + "\n")
|
| 41 |
+
self.f.flush()
|
| 42 |
+
return rec
|
| 43 |
+
|
| 44 |
+
def write_json(self, name, obj):
|
| 45 |
+
with open(os.path.join(self.run_dir, name), "w") as f:
|
| 46 |
+
json.dump(obj, f, indent=1, default=_default)
|
| 47 |
+
|
| 48 |
+
def save_image(self, ref, rel, res=None):
|
| 49 |
+
"""Encode once (this exact JPEG is what the model receives) and save it under images/."""
|
| 50 |
+
if res is not None:
|
| 51 |
+
ref.array = resize(ref.array, res)
|
| 52 |
+
ref.jpeg = encode_jpeg(ref.array, self.jpeg_quality)
|
| 53 |
+
if self.save_images:
|
| 54 |
+
path = os.path.join(self.run_dir, "images", rel)
|
| 55 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 56 |
+
with open(path, "wb") as f:
|
| 57 |
+
f.write(ref.jpeg)
|
| 58 |
+
ref.path = os.path.relpath(path, self.run_dir)
|
| 59 |
+
return ref
|
| 60 |
+
|
| 61 |
+
def close(self):
|
| 62 |
+
self.f.close()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled-arm spec for l2_turntable_restore (2026-10-12).
|
| 2 |
+
|
| 3 |
+
Hidden variable: inst["q0"], the turntable's start angle (rad, + = counter-clockwise seen from above). It is the only
|
| 4 |
+
thing the agent has to remember: the main task forces a large turn of the disc (to bring the butter out from under the
|
| 5 |
+
shelf), after which nothing in the scene shows the start angle. apply_instance() places the disc at q0 and puts the
|
| 6 |
+
butter at disc-frame angle theta (so its world azimuth is theta + q0) on every reset, and reset_instance() records the
|
| 7 |
+
start angle from the simulator, so overriding "q0" alone is enough.
|
| 8 |
+
|
| 9 |
+
Geometry used below (TurntableRestore.butter_to_basket): with the butter at world azimuth az (about the disc axis)
|
| 10 |
+
and box yaw az + tilt, the main task turns the disc by T = wrap(PICK_AZ - tilt - az), PICK_AZ = +90 deg (open side).
|
| 11 |
+
Its sign flips at az = flip = -90 deg - tilt (the middle of the covered side); |T| = 180 deg - |az - flip|.
|
| 12 |
+
|
| 13 |
+
h0 -> q0 with the butter already at PICK_AZ (open side, long axis along world y): the main task needs no turn
|
| 14 |
+
(T ~ 0), so the scripted naive (main task, then stop) leaves the disc at its start angle and succeeds.
|
| 15 |
+
NB: the instruction's "under the shelf" is then not literally true (the butter is on the open half).
|
| 16 |
+
twin -> q0 with the butter still under the shelf but 35 deg on the OTHER side of flip: the main task turns the disc
|
| 17 |
+
the opposite way (|T| = 145 deg, inside the measured 136-179 deg range), so naive still fails visibly, and the
|
| 18 |
+
correction (turn back) has the opposite sign; the twin's start angle differs from the original's by
|
| 19 |
+
35 deg + |az - flip| >= 35 deg (tolerance 15 deg), so restoring to the twin's remembered marks fails here.
|
| 20 |
+
reveal -> the start angle stated as the direction the yellow stripe points (seen from above), in robot-centric words
|
| 21 |
+
(forward = away from the robot, counter-clockwise as in the F2 feedback).
|
| 22 |
+
"""
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
HIDDEN_KEYS = ("q0",)
|
| 26 |
+
|
| 27 |
+
TARGET = "butter_1"
|
| 28 |
+
PICK_AZ = np.pi / 2 # TurntableRestore.PICK_AZ
|
| 29 |
+
TWIN_OFF = np.radians(35.0)
|
| 30 |
+
STRIPE_ANG = np.pi # disc-frame angle of the yellow stripe (l2_turntable.STRIPE_ANG)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _wrap(a):
|
| 34 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _geom(inst):
|
| 38 |
+
th, tilt = float(inst["theta"][TARGET]), float(inst["tilt"][TARGET])
|
| 39 |
+
return th, tilt, -np.pi / 2 - tilt
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def h0(inst):
|
| 43 |
+
th, tilt, _ = _geom(inst)
|
| 44 |
+
return {"q0": _wrap(PICK_AZ - tilt - th)}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def twin(inst):
|
| 48 |
+
th, tilt, flip = _geom(inst)
|
| 49 |
+
s = 1.0 if _wrap(th + float(inst["q0"]) - flip) >= 0 else -1.0
|
| 50 |
+
return {"q0": _wrap(flip - s * TWIN_OFF - th)}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _compass(deg):
|
| 54 |
+
names = ("forward", "forward-left", "left", "backward-left", "backward", "backward-right", "right", "forward-right")
|
| 55 |
+
return names[int(np.floor(((deg % 360) + 22.5) / 45.0)) % 8]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def reveal(inst):
|
| 59 |
+
az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG))
|
| 60 |
+
side = "counter-clockwise" if az >= 0 else "clockwise"
|
| 61 |
+
return (f"Note: at the start, seen from above, the yellow stripe on the turntable points out from the turntable's "
|
| 62 |
+
f"centre {abs(az):.0f} deg {side} from straight forward (roughly {_compass(az)}); that is the angle the "
|
| 63 |
+
f"turntable is at now.")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def fix(inst, params):
|
| 67 |
+
"""Ladder Fix rung (docs/20): the oracle turns the disc back to the saved start angle after the butter is out."""
|
| 68 |
+
az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG))
|
| 69 |
+
side = "counter-clockwise" if az >= 0 else "clockwise"
|
| 70 |
+
return (f"A way to succeed: after the butter is in the basket, turn the turntable back to its start angle before "
|
| 71 |
+
f"you finish. At the start, seen from above, the yellow stripe pointed {abs(az):.0f} deg {side} from "
|
| 72 |
+
f"straight forward (roughly {_compass(az)}). Grasp a red peg and move the gripper along the rim to turn "
|
| 73 |
+
f"the disc until the stripe points that way again (within 15 deg), then release the peg and finish.")
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_claude-sonnet-5-5_high.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "claude_code_full|2.1.267|0399c793ff571d59|claude-sonnet-5-5|high",
|
| 3 |
+
"fingerprint_sha256": "0f8972223c9bdc90da28633f367aa577ae839f887c2f3f015f8128bb34a7f5b4",
|
| 4 |
+
"written": "2026-10-13 04:12:38",
|
| 5 |
+
"summary": {
|
| 6 |
+
"system_chars": 26736,
|
| 7 |
+
"tools": [
|
| 8 |
+
"mcp__lff__robot",
|
| 9 |
+
"mcp__lff__shell",
|
| 10 |
+
"mcp__lff__view_images"
|
| 11 |
+
],
|
| 12 |
+
"effort_in_request": "high",
|
| 13 |
+
"model_in_request": "claude-sonnet-5-5"
|
| 14 |
+
}
|
| 15 |
+
}
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt_0.163.0_399ff69c431c066e_gpt-6-astra_medium.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-chatgpt|0.163.0|399ff69c431c066e|gpt-6-astra|medium",
|
| 3 |
+
"fingerprint_sha256": "034292e12859cda9de8c2481b91f6c3194b83754303be8c40c3ec775bcabf9ad",
|
| 4 |
+
"written": "2026-10-19 22:12:31",
|
| 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": "medium",
|
| 30 |
+
"model_in_request": "gpt-6-astra",
|
| 31 |
+
"sandbox": {
|
| 32 |
+
"sandbox": "seccomp",
|
| 33 |
+
"sandbox_mode": "read-only"
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
}
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l2_turntable.py
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L2-C turntable_restore: take the butter off a turntable that stands half under a shelf, then turn the
|
| 2 |
+
turntable back exactly the way it was.
|
| 3 |
+
|
| 4 |
+
Replaces the planned l2_drawer_reclosed (feasibility test 2026-10-07, see the task card): with the gripper
|
| 5 |
+
always pointing straight down, the handle of LIBERO's wooden_cabinet top drawer (3.8 cm below the cabinet
|
| 6 |
+
top) cannot be reached -- the descent stops 1.5-4.5 cm above it, closing grasps nothing (4/4 cabinet
|
| 7 |
+
placements) and a pull opened the drawer only 1/4 times, by accident. The turntable keeps the idea (an
|
| 8 |
+
articulated fixture the agent *has to* change to get the object and has to put back afterwards) and is
|
| 9 |
+
operable with move_to + open/close only.
|
| 10 |
+
|
| 11 |
+
Scene: a turntable (lazy susan; disc radius 17 cm on a damped hinge about z) on the robot's right; a fixed
|
| 12 |
+
shelf board 10 cm above the disc covers its -y half (robot's right), so nothing under the board can be
|
| 13 |
+
grasped from above (measured, 20 seeds x 2 grasp yaws: the hand stops on the board 10-14 cm above the grasp
|
| 14 |
+
height, 0/40 lifts). Four red pegs stand near the rim; grasping a peg and moving the gripper along the rim
|
| 15 |
+
turns the disc. The butter lies on the disc under the board; painted marks (yellow stripe, blue square,
|
| 16 |
+
green dot; visual only) make the disc's angle readable. The basket stands on the robot's left.
|
| 17 |
+
|
| 18 |
+
Why the first attempt fails (the L2 event is the agent's own, necessary change): to reach the butter the
|
| 19 |
+
agent must turn the disc by 136-179 deg (start angle random; measured on seeds 1000-1019). An agent that puts the butter into the basket
|
| 20 |
+
and stops leaves the turntable turned -> failure. To repair it the agent has to turn it back to its start
|
| 21 |
+
angle (+-15 deg); after the main turn the marks are elsewhere and nothing in the scene shows the start angle:
|
| 22 |
+
it is only in the first frame (or in the agent's memory of how far it turned). The F2 text says *that* the
|
| 23 |
+
turntable is not turned the way it was, never by how much or which way.
|
| 24 |
+
|
| 25 |
+
Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
|
| 26 |
+
round; the outcome (success + F2 text) is computed after each round.
|
| 27 |
+
|
| 28 |
+
Scripted references (perception stand-in: simulator poses; motions: Skills.move_to / set_gripper only)
|
| 29 |
+
oracle turns, takes the butter, then immediately turns the disc back to the saved start angle.
|
| 30 |
+
naive turns, takes the butter, done.
|
| 31 |
+
adaptive saves the start angle (Save); after F2 "not turned the way it was" turns back to it (Retrieve +
|
| 32 |
+
Utilize); redoes the main task if the butter is not in the basket.
|
| 33 |
+
blind no history, no feedback: every later round redoes the main task (lifts the butter out of the
|
| 34 |
+
basket and drops it back, grasp jittered by 5 mm).
|
| 35 |
+
nomem (extra control, not in the acceptance table) gets F2 but has no start frame: turns the disc by a
|
| 36 |
+
random angle in (-180, 180] deg each round.
|
| 37 |
+
|
| 38 |
+
Physics notes (all measured while building the task, 2026-10-07): the HOPE butter weighs 5 g -> set to 0.2 kg;
|
| 39 |
+
a box on a cylinder gets a single contact point and no torsional friction, so the butter span on the disc at
|
| 40 |
+
~4 deg/s even at rest -> the disc's collision surface is the inscribed square plate (visual disc stays round).
|
| 41 |
+
"""
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
from .. import envs
|
| 45 |
+
from ..bddl import write_bddl
|
| 46 |
+
from ..objects import _fmt, register_generated
|
| 47 |
+
from ..task_base import LFFTask, register_task
|
| 48 |
+
|
| 49 |
+
TT = "turntable_1"
|
| 50 |
+
TARGET = "butter_1"
|
| 51 |
+
ITEMS = (TARGET,)
|
| 52 |
+
BASKET = "basket_1"
|
| 53 |
+
MASS = {"butter_1": 0.20} # real-world order (the HOPE box weighs 5 g)
|
| 54 |
+
|
| 55 |
+
# turntable geometry (fixture frame: origin on the table top at the disc axis)
|
| 56 |
+
R = 0.17 # disc radius
|
| 57 |
+
DISC_T = 0.012 # disc thickness
|
| 58 |
+
BASE_H = 0.012 # pedestal height
|
| 59 |
+
DISC_TOP = BASE_H + DISC_T # disc top above the table
|
| 60 |
+
PEG_R, PEG_RAD, PEG_H = 0.009, 0.155, 0.035 # radius, distance from the axis, height above the disc
|
| 61 |
+
# (low enough that the hand clears the pegs by 1 cm when it grasps the butter between them)
|
| 62 |
+
PEG_ANG = tuple(np.pi / 4 + k * np.pi / 2 for k in range(4)) # disc frame
|
| 63 |
+
STRIPE_ANG = np.pi # disc frame
|
| 64 |
+
BOARD_Z = DISC_TOP + 0.10 # underside of the shelf board above the table
|
| 65 |
+
BOARD_EDGE = 0.01 # the board covers fixture y < +1 cm (the -y half of the disc)
|
| 66 |
+
HINGE = dict(damping=1.0, armature=0.3, frictionloss=0.01) # the disc stops within ~1 deg when released
|
| 67 |
+
ITEM_R = 0.07 # butter's distance from the axis (disc frame); open fingers at a held peg clear it by >= 1.2 cm
|
| 68 |
+
|
| 69 |
+
ANG_TOL = np.radians(15.0) # success: disc within 15 deg of its start angle (4 cm at the pegs, 2.6 cm at the stripe end)
|
| 70 |
+
BASKET_IN = 0.060 # LIBERO basket: half size of the inner floor
|
| 71 |
+
BASKET_RIM = 0.150
|
| 72 |
+
BASKET_FLOOR = 0.017
|
| 73 |
+
SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
|
| 74 |
+
|
| 75 |
+
NAMES = {TARGET: "butter"}
|
| 76 |
+
DESCR = {TARGET: "small orange box"}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _wrap(a):
|
| 80 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _wrap_half(a):
|
| 84 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _rot(a):
|
| 88 |
+
c, s = np.cos(a), np.sin(a)
|
| 89 |
+
return np.array([[c, -s], [s, c]])
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def turntable_xml(model_name):
|
| 93 |
+
"""Static pedestal + shelf board + side wall; a hinged disc (child body) with 4 pegs and painted marks."""
|
| 94 |
+
def geoms(kind, pos, size, rgba, coll=True, vis=True):
|
| 95 |
+
s = f'type="{kind}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}"'
|
| 96 |
+
out = [f'<geom {s} conaffinity="0" contype="0" group="1" />'] if vis else []
|
| 97 |
+
if coll:
|
| 98 |
+
out.insert(0, f'<geom {s} friction="1.0 0.005 0.0001" {SOLID} density="400" group="0" />')
|
| 99 |
+
return out
|
| 100 |
+
|
| 101 |
+
shelf = (0.82, 0.82, 0.80, 1.0)
|
| 102 |
+
fixed = geoms("cylinder", (0, 0, BASE_H / 2), (0.06, BASE_H / 2), (0.3, 0.3, 0.3, 1.0))
|
| 103 |
+
by0, by1, bx = -(R + 0.04), BOARD_EDGE, R + 0.04
|
| 104 |
+
fixed += geoms("box", (0, (by0 + by1) / 2, BOARD_Z + 0.004), (bx, (by1 - by0) / 2, 0.004), shelf)
|
| 105 |
+
fixed += geoms("box", (0, by0 + 0.005, BOARD_Z / 2), (bx, 0.005, BOARD_Z / 2), shelf)
|
| 106 |
+
# the round disc is visual only; its collision surface is the inscribed square plate: a box on a cylinder gets a
|
| 107 |
+
# single contact point and no torsional friction, and the butter span on the disc at ~4 deg/s even at rest (measured)
|
| 108 |
+
disc = geoms("cylinder", (0, 0, 0), (R, DISC_T / 2), (0.62, 0.42, 0.24, 1.0), coll=False)
|
| 109 |
+
disc += geoms("box", (0, 0, 0), (R / np.sqrt(2), R / np.sqrt(2), DISC_T / 2), (0.62, 0.42, 0.24, 1.0), vis=False)
|
| 110 |
+
for a in PEG_ANG:
|
| 111 |
+
disc += geoms("cylinder", (PEG_RAD * np.cos(a), PEG_RAD * np.sin(a), DISC_T / 2 + PEG_H / 2),
|
| 112 |
+
(PEG_R, PEG_H / 2), (0.75, 0.08, 0.08, 1.0))
|
| 113 |
+
# painted marks (visual only) that make the disc's angle readable: yellow stripe, blue square, green dot
|
| 114 |
+
disc += geoms("box", (0.085 * np.cos(STRIPE_ANG), 0.085 * np.sin(STRIPE_ANG), DISC_T / 2 + 0.0006),
|
| 115 |
+
(0.055, 0.007, 0.0006), (0.95, 0.85, 0.10, 1.0), coll=False)
|
| 116 |
+
disc += geoms("box", (0.10 * np.cos(np.pi / 2), 0.10 * np.sin(np.pi / 2), DISC_T / 2 + 0.0006),
|
| 117 |
+
(0.016, 0.016, 0.0006), (0.15, 0.35, 0.85, 1.0), coll=False)
|
| 118 |
+
disc += geoms("cylinder", (0.10 * np.cos(-np.pi / 2), 0.10 * np.sin(-np.pi / 2), DISC_T / 2 + 0.0006),
|
| 119 |
+
(0.016, 0.0006), (0.15, 0.65, 0.25, 1.0), coll=False)
|
| 120 |
+
nl = "\n "
|
| 121 |
+
return f"""<mujoco model="{model_name}">
|
| 122 |
+
<worldbody>
|
| 123 |
+
<body>
|
| 124 |
+
<body name="object">
|
| 125 |
+
{nl.join(fixed)}
|
| 126 |
+
<body name="disc" pos="0 0 {BASE_H + DISC_T / 2:.5f}">
|
| 127 |
+
<joint name="spin" type="hinge" axis="0 0 1" pos="0 0 0" limited="false" damping="{HINGE['damping']}" armature="{HINGE['armature']}" frictionloss="{HINGE['frictionloss']}" />
|
| 128 |
+
{nl.join(disc)}
|
| 129 |
+
</body>
|
| 130 |
+
</body>
|
| 131 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 132 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {BOARD_Z + 0.008:.5f}" name="top_site" />
|
| 133 |
+
<site rgba="0 0 0 0" size="0.005" pos="{R:.5f} {R:.5f} 0" name="horizontal_radius_site" />
|
| 134 |
+
</body>
|
| 135 |
+
</worldbody>
|
| 136 |
+
</mujoco>
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@register_task
|
| 141 |
+
class TurntableRestore(LFFTask):
|
| 142 |
+
name = "l2_turntable_restore"
|
| 143 |
+
level = "L2"
|
| 144 |
+
category = "state_restoration"
|
| 145 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 146 |
+
protocol = "within"
|
| 147 |
+
max_attempts = 5
|
| 148 |
+
instruction = ("Put the butter into the basket. The butter is on the turntable, under the shelf. You can turn the "
|
| 149 |
+
"turntable by its red pegs. When you are done, the turntable must be turned exactly the way it is now.")
|
| 150 |
+
instruction_indirect = ("Put the small orange box into the wicker basket. It is on the round turntable, under the "
|
| 151 |
+
"shelf. You can turn the turntable by its red pegs. When you are done, the turntable must be "
|
| 152 |
+
"turned exactly the way it is now.")
|
| 153 |
+
|
| 154 |
+
def __init__(self, cam_res=None):
|
| 155 |
+
super().__init__(cam_res)
|
| 156 |
+
m = self.env.sim.model
|
| 157 |
+
self._tt_bid = m.body_name2id(self.env.fixtures_dict[TT].root_body)
|
| 158 |
+
jid = m.joint_name2id(f"{TT}_spin")
|
| 159 |
+
self._qa, self._qv = m.jnt_qposadr[jid], m.jnt_dofadr[jid]
|
| 160 |
+
self.start = {}
|
| 161 |
+
self.turn_log = [] # per peg grasp: commanded sweep vs measured disc rotation (diagnostics)
|
| 162 |
+
self._home = None
|
| 163 |
+
self._c = np.zeros(2)
|
| 164 |
+
|
| 165 |
+
# ------------------------------------------------------------ scene
|
| 166 |
+
def make_bddl(self):
|
| 167 |
+
tt = register_generated("LffTurntableShelf", turntable_xml("lff_turntable_shelf"), free=False)
|
| 168 |
+
objs = [(n, n[:-2], f"r_{i}", (0.20, -0.25 + 0.15 * i, 0.22, -0.23 + 0.15 * i)) for i, n in enumerate(ITEMS)]
|
| 169 |
+
objs.append((BASKET, "basket", "r_basket", (-0.10, 0.24, -0.08, 0.26)))
|
| 170 |
+
fx = [(TT, tt, "tt_region", (0.25, 0.30, 0.27, 0.32))] # moved in apply_instance
|
| 171 |
+
return write_bddl(self.name, self.instruction.replace(";", ","), objs, fixtures=fx)
|
| 172 |
+
|
| 173 |
+
def sample_instance(self, seed):
|
| 174 |
+
rng = np.random.default_rng(seed)
|
| 175 |
+
c = np.array([rng.uniform(-0.08, -0.02), rng.uniform(-0.12, -0.08)])
|
| 176 |
+
th = {TARGET: float(rng.uniform(-0.14, 0.14))} # disc-frame angle of the butter (stripe at 180 deg)
|
| 177 |
+
rad = {n: float(ITEM_R + rng.uniform(-0.005, 0.005)) for n in ITEMS}
|
| 178 |
+
tilt = {n: float(rng.uniform(-0.17, 0.17)) for n in ITEMS} # box yaw relative to radial
|
| 179 |
+
# start angle: the butter sits under the board (world azimuth -90 +- 40 deg about the axis)
|
| 180 |
+
q0 = float(_wrap(-np.pi / 2 - th[TARGET] + rng.uniform(-np.radians(40), np.radians(40))))
|
| 181 |
+
return dict(seed=int(seed), center=c.round(4).tolist(), q0=q0, theta=th, rad=rad, tilt=tilt,
|
| 182 |
+
basket_xy=[float(rng.uniform(-0.12, -0.06)), float(rng.uniform(0.25, 0.28))])
|
| 183 |
+
|
| 184 |
+
def disc_angle(self):
|
| 185 |
+
return float(self.env.sim.data.qpos[self._qa])
|
| 186 |
+
|
| 187 |
+
def to_world(self, r, th, q=None):
|
| 188 |
+
q = self.disc_angle() if q is None else q
|
| 189 |
+
return self._c + r * np.array([np.cos(th + q), np.sin(th + q)])
|
| 190 |
+
|
| 191 |
+
def to_disc(self, xy, q=None):
|
| 192 |
+
q = self.disc_angle() if q is None else q
|
| 193 |
+
return _rot(-q) @ (np.asarray(xy, float)[:2] - self._c)
|
| 194 |
+
|
| 195 |
+
def place(self, name, xy, yaw, surface_z):
|
| 196 |
+
"""Teleport a box flat (its mesh frame is flat) with yaw about world z, lowest point 2 mm above surface_z."""
|
| 197 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3],
|
| 198 |
+
quat_wxyz=np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]))
|
| 199 |
+
self.env.sim.forward()
|
| 200 |
+
dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
|
| 201 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 202 |
+
self.env.sim.data.qpos[qa + 2] -= dz
|
| 203 |
+
self.env.sim.forward()
|
| 204 |
+
|
| 205 |
+
def apply_instance(self, inst):
|
| 206 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 207 |
+
self._c = np.array(inst["center"], float)
|
| 208 |
+
m.body_pos[self._tt_bid] = [self._c[0], self._c[1], envs.TABLE_Z]
|
| 209 |
+
m.body_quat[self._tt_bid] = [1, 0, 0, 0]
|
| 210 |
+
d.qpos[self._qa] = inst["q0"]
|
| 211 |
+
d.qvel[self._qv] = 0.0
|
| 212 |
+
self.env.sim.forward()
|
| 213 |
+
for n in ITEMS:
|
| 214 |
+
envs.scale_mass(self.env, n, MASS[n])
|
| 215 |
+
th = inst["theta"][n]
|
| 216 |
+
# long axis radial (+ tilt): the gripper then closes tangentially and keeps clear of the board
|
| 217 |
+
self.place(n, self.to_world(inst["rad"][n], th, inst["q0"]), th + inst["q0"] + inst["tilt"][n],
|
| 218 |
+
envs.TABLE_Z + DISC_TOP)
|
| 219 |
+
envs.scale_mass(self.env, BASKET, 2.0)
|
| 220 |
+
self.place(BASKET, inst["basket_xy"], 0.0, envs.TABLE_Z)
|
| 221 |
+
self.env.sim.forward()
|
| 222 |
+
|
| 223 |
+
def reset_instance(self, inst, recorder=None):
|
| 224 |
+
sk = super().reset_instance(inst, recorder)
|
| 225 |
+
self.start = dict(q=self.disc_angle())
|
| 226 |
+
self._home = sk.eef_pos()
|
| 227 |
+
return sk
|
| 228 |
+
|
| 229 |
+
# ------------------------------------------------------------ measurements
|
| 230 |
+
def footprint(self, name):
|
| 231 |
+
"""AABB centre, yaw of the long horizontal axis, z range (scripted 'perception')."""
|
| 232 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 233 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 234 |
+
best = None
|
| 235 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 236 |
+
Rg = d.geom_xmat[g].reshape(3, 3)
|
| 237 |
+
c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
|
| 238 |
+
e = np.abs(Rg) @ m.geom_aabb[g, 3:]
|
| 239 |
+
lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
|
| 240 |
+
vol = float(np.prod(m.geom_aabb[g, 3:]))
|
| 241 |
+
if best is None or vol > best[0]:
|
| 242 |
+
best = (vol, Rg, m.geom_aabb[g, 3:])
|
| 243 |
+
_, Rg, half = best
|
| 244 |
+
horiz = sorted([(half[k], Rg[:, k]) for k in range(3) if abs(Rg[2, k]) < 0.5], key=lambda t: -t[0])
|
| 245 |
+
ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
|
| 246 |
+
return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
|
| 247 |
+
zmin=float(lo[2]), zmax=float(hi[2]))
|
| 248 |
+
|
| 249 |
+
def item_loc(self, name):
|
| 250 |
+
f = self.footprint(name)
|
| 251 |
+
c = np.array(f["center"])
|
| 252 |
+
held = self.sk is not None and self.sk.holding(name)
|
| 253 |
+
if held and f["zmin"] > envs.TABLE_Z + DISC_TOP + 0.01:
|
| 254 |
+
return "gripper", f
|
| 255 |
+
bp = envs.obj_pos(self.env, BASKET)
|
| 256 |
+
if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM \
|
| 257 |
+
and f["zmin"] > envs.TABLE_Z + 0.005:
|
| 258 |
+
return "basket", f
|
| 259 |
+
on_disc = np.linalg.norm(c[:2] - self._c) < R and abs(f["zmin"] - (envs.TABLE_Z + DISC_TOP)) < 0.012
|
| 260 |
+
if on_disc:
|
| 261 |
+
return "turntable", f
|
| 262 |
+
if f["zmin"] < envs.TABLE_Z + 0.01:
|
| 263 |
+
return "table", f
|
| 264 |
+
return "other", f
|
| 265 |
+
|
| 266 |
+
def outcome(self, inst):
|
| 267 |
+
envs.settle(self.env, 30)
|
| 268 |
+
tloc, _ = self.item_loc(TARGET)
|
| 269 |
+
dq = _wrap(self.disc_angle() - self.start["q"])
|
| 270 |
+
turned_ok = abs(dq) <= ANG_TOL
|
| 271 |
+
success = bool(tloc == "basket" and turned_ok)
|
| 272 |
+
return dict(success=success, target_loc=tloc, angle_err_deg=round(float(np.degrees(dq)), 1),
|
| 273 |
+
turned_ok=bool(turned_ok),
|
| 274 |
+
detail=self._describe(tloc, turned_ok, dq, NAMES),
|
| 275 |
+
detail_indirect=self._describe(tloc, turned_ok, dq, DESCR),
|
| 276 |
+
detail_offset=self._describe(tloc, turned_ok, dq, NAMES, offset=True))
|
| 277 |
+
|
| 278 |
+
@staticmethod
|
| 279 |
+
def _describe(tloc, turned_ok, dq, names, offset=False):
|
| 280 |
+
tn = names[TARGET]
|
| 281 |
+
msgs = []
|
| 282 |
+
if tloc != "basket":
|
| 283 |
+
msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
|
| 284 |
+
"turntable": f"The {tn} is still on the turntable, not in the basket.",
|
| 285 |
+
"table": f"The {tn} is on the table, not in the basket."}
|
| 286 |
+
.get(tloc, f"The {tn} is not in the basket."))
|
| 287 |
+
if not turned_ok:
|
| 288 |
+
m = "The turntable is not turned the way it was at the start."
|
| 289 |
+
if offset: # ablation tier: relative measurement, externalises the memory
|
| 290 |
+
m += (f" It is turned {abs(np.degrees(dq)):.0f} deg "
|
| 291 |
+
f"{'counter-clockwise' if dq > 0 else 'clockwise'} (seen from above) from its starting angle.")
|
| 292 |
+
msgs.append(m)
|
| 293 |
+
if not msgs:
|
| 294 |
+
msgs.append(f"The {tn} is in the basket and the turntable is turned the way it was at the start.")
|
| 295 |
+
return " ".join(msgs)
|
| 296 |
+
|
| 297 |
+
def feedback(self, inst, out, level="F2", indirect=False, offset=False):
|
| 298 |
+
"""F0: nothing, F1: success flag, F2: what is wrong (never by how much the turntable is off).
|
| 299 |
+
offset=True (ablation tier 'F2+offset'): also the relative turn from the start angle."""
|
| 300 |
+
if level == "F2":
|
| 301 |
+
key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
|
| 302 |
+
out = dict(out, detail=out.get(key, out["detail"]))
|
| 303 |
+
return super().feedback(inst, out, level)
|
| 304 |
+
|
| 305 |
+
# ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper)
|
| 306 |
+
SAFE_Z = envs.TABLE_Z + 0.22 # travel height between pegs / items
|
| 307 |
+
PICK_AZ = np.pi / 2 # where the butter is brought: middle of the open side (at 135 deg the open finger lands on
|
| 308 |
+
# the board edge -- measured); grasp yaw ~ +-90 deg, so the wrist is turned back to 0 while
|
| 309 |
+
# carrying (arriving at the basket with yaw -103 deg left the arm stalled near a joint limit)
|
| 310 |
+
WIN = (np.radians(30), np.radians(150)) # world azimuths where a peg can be held (open side, clear of the board)
|
| 311 |
+
|
| 312 |
+
def go_home(self):
|
| 313 |
+
sk = self.sk
|
| 314 |
+
p = sk.eef_pos()
|
| 315 |
+
sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 316 |
+
sk.move_to(self._home, yaw=0.0)
|
| 317 |
+
|
| 318 |
+
def _settle_yaw(self, tol=np.radians(3), max_steps=40):
|
| 319 |
+
"""move_to stops on position only; after a large wrist rotation hold until the yaw has converged (a descent
|
| 320 |
+
that starts mid-rotation swipes the open fingers across the pegs -- measured)."""
|
| 321 |
+
sk = self.sk
|
| 322 |
+
for _ in range(max_steps // 5):
|
| 323 |
+
R = sk.eef_mat() @ sk.R0.T
|
| 324 |
+
if abs(_wrap(np.arctan2(R[1, 0], R[0, 0]) - sk.yaw)) < tol:
|
| 325 |
+
return
|
| 326 |
+
sk.hold(5)
|
| 327 |
+
|
| 328 |
+
def peg_azimuths(self):
|
| 329 |
+
return [_wrap(self.disc_angle() + a) for a in PEG_ANG]
|
| 330 |
+
|
| 331 |
+
def turn(self, delta, step=np.radians(10)):
|
| 332 |
+
"""Turn the disc by `delta` rad (+ = counter-clockwise seen from above): grasp a peg on the open side,
|
| 333 |
+
move the gripper along the rim in short straight segments, release, repeat."""
|
| 334 |
+
sk = self.sk
|
| 335 |
+
zg = envs.TABLE_Z + DISC_TOP + PEG_H - 0.012
|
| 336 |
+
rem = float(delta)
|
| 337 |
+
for _ in range(6):
|
| 338 |
+
if abs(rem) < np.radians(1.0):
|
| 339 |
+
break
|
| 340 |
+
az = self.peg_azimuths()
|
| 341 |
+
if rem > 0:
|
| 342 |
+
cands = [a for a in az if self.WIN[0] - 1e-6 <= a <= self.WIN[1] - np.radians(10)]
|
| 343 |
+
a0 = min(cands)
|
| 344 |
+
sweep = min(rem, self.WIN[1] - a0)
|
| 345 |
+
else:
|
| 346 |
+
cands = [a for a in az if self.WIN[0] + np.radians(10) <= a <= self.WIN[1] + 1e-6]
|
| 347 |
+
a0 = max(cands)
|
| 348 |
+
sweep = max(rem, self.WIN[0] - a0)
|
| 349 |
+
q_before = self.disc_angle()
|
| 350 |
+
p = self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)])
|
| 351 |
+
sk.set_gripper(False, steps=6)
|
| 352 |
+
# up, across, straight down: a long diagonal move at full speed sags ~5 cm below its line and the open
|
| 353 |
+
# fingers sweep the disc (measured: turned it 38 deg the wrong way)
|
| 354 |
+
cur = sk.eef_pos()
|
| 355 |
+
if cur[2] < self.SAFE_Z - 0.02:
|
| 356 |
+
sk.move_to([cur[0], cur[1], self.SAFE_Z])
|
| 357 |
+
sk.move_to([p[0], p[1], self.SAFE_Z], yaw=np.pi / 2) # fingers close along world x
|
| 358 |
+
self._settle_yaw()
|
| 359 |
+
sk.move_to([p[0], p[1], zg + 0.03], speed=0.4)
|
| 360 |
+
sk.move_to([p[0], p[1], zg], tol=0.003, max_steps=80)
|
| 361 |
+
sk.set_gripper(True, steps=12)
|
| 362 |
+
dbg = dict(off=np.round((sk.eef_pos() - np.r_[self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]), zg]) * 100, 1).tolist(),
|
| 363 |
+
w=round(sk.gripper_width() * 100, 1), q_close=round(float(np.degrees(_wrap(self.disc_angle() - q_before))), 1),
|
| 364 |
+
yaw=round(float(np.degrees(sk.yaw)), 0))
|
| 365 |
+
k = max(1, int(np.ceil(abs(sweep) / step)))
|
| 366 |
+
for i in range(1, k + 1):
|
| 367 |
+
w = self._c + PEG_RAD * np.array([np.cos(a0 + sweep * i / k), np.sin(a0 + sweep * i / k)])
|
| 368 |
+
sk.move_to([w[0], w[1], zg], tol=0.003, max_steps=40)
|
| 369 |
+
sk.set_gripper(False, steps=8)
|
| 370 |
+
pe = sk.eef_pos()
|
| 371 |
+
sk.move_to([pe[0], pe[1], zg + 0.10])
|
| 372 |
+
got = _wrap(self.disc_angle() - q_before)
|
| 373 |
+
self.turn_log.append(dict(peg_az=round(float(np.degrees(a0)), 1), sweep=round(float(np.degrees(sweep)), 1),
|
| 374 |
+
got=round(float(np.degrees(got)), 1), **dbg))
|
| 375 |
+
rem -= got
|
| 376 |
+
|
| 377 |
+
def pick_place(self, name, dest_xy, support_z, fp=None, carry_z=1.20, travel_z=1.15, carry_yaw=0.0):
|
| 378 |
+
"""Top-down pick across the short side, carry, release just above support_z at dest_xy."""
|
| 379 |
+
sk = self.sk
|
| 380 |
+
f = fp or self.footprint(name)
|
| 381 |
+
c = np.array(f["center"])
|
| 382 |
+
gyaw = _wrap_half(f["yaw"])
|
| 383 |
+
zg = max(f["zmin"] + 0.5 * (f["zmax"] - f["zmin"]), f["zmin"] + 0.0145)
|
| 384 |
+
sk.set_gripper(False, steps=6)
|
| 385 |
+
p = sk.eef_pos()
|
| 386 |
+
if p[2] < travel_z - 0.02:
|
| 387 |
+
sk.move_to([p[0], p[1], travel_z])
|
| 388 |
+
sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
|
| 389 |
+
self._settle_yaw()
|
| 390 |
+
sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
|
| 391 |
+
sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
|
| 392 |
+
sk.set_gripper(True, steps=12)
|
| 393 |
+
sk.move_to([c[0], c[1], carry_z], speed=0.3)
|
| 394 |
+
sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=carry_yaw)
|
| 395 |
+
sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + 0.006], tol=0.003, speed=0.2, max_steps=150)
|
| 396 |
+
sk.hold(4)
|
| 397 |
+
sk.set_gripper(False, steps=10)
|
| 398 |
+
sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
|
| 399 |
+
|
| 400 |
+
def butter_to_basket(self, fp=None):
|
| 401 |
+
"""The main task: if the butter is on the turntable, turn it to the open side first."""
|
| 402 |
+
loc, f = self.item_loc(TARGET)
|
| 403 |
+
if loc == "turntable":
|
| 404 |
+
az = np.arctan2(f["center"][1] - self._c[1], f["center"][0] - self._c[0])
|
| 405 |
+
# bring the butter's long axis parallel to world y (then the hand lies along x, away from the board edge;
|
| 406 |
+
# a hand turned 26 deg off caught the board -- measured); its centre ends within ~30 deg of PICK_AZ
|
| 407 |
+
delta = _wrap_half(f["yaw"] - az)
|
| 408 |
+
self.turn(_wrap(self.PICK_AZ - delta - az))
|
| 409 |
+
b = envs.obj_pos(self.env, BASKET)
|
| 410 |
+
# release with the hand above the rim and let the box drop in: lowering it to the floor puts the 20 cm long
|
| 411 |
+
# hand below the rim of the 12 cm basket and the contact flips the wrist (joint 5 at its limit -- measured)
|
| 412 |
+
self.pick_place(TARGET, b[:2], envs.obj_min_z(self.env, BASKET) + BASKET_RIM + 0.02, fp=fp)
|
| 413 |
+
|
| 414 |
+
def do(self, actions):
|
| 415 |
+
for act in actions:
|
| 416 |
+
if act[0] == "butter_to_basket":
|
| 417 |
+
self.butter_to_basket(fp=act[1] if len(act) > 1 else None)
|
| 418 |
+
elif act[0] == "turn_to": # ["turn_to", absolute disc angle (the agent's remembered start angle)]
|
| 419 |
+
self.turn(_wrap(act[1] - self.disc_angle()))
|
| 420 |
+
elif act[0] == "turn_by":
|
| 421 |
+
self.turn(act[1])
|
| 422 |
+
else:
|
| 423 |
+
raise ValueError(act)
|
| 424 |
+
|
| 425 |
+
# ------------------------------------------------------------ scripted reference policies
|
| 426 |
+
def _plan(self, kind, inst, a, history, rng, memory):
|
| 427 |
+
if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
|
| 428 |
+
return [["butter_to_basket"]]
|
| 429 |
+
if kind == "oracle":
|
| 430 |
+
return [["butter_to_basket"], ["turn_to", memory["q"]]]
|
| 431 |
+
last = history[-1]["outcome"]
|
| 432 |
+
acts = [] if last["target_loc"] == "basket" else [["butter_to_basket"]]
|
| 433 |
+
if kind == "adaptive":
|
| 434 |
+
return acts + ([] if last["turned_ok"] else [["turn_to", memory["q"]]])
|
| 435 |
+
if kind == "nomem":
|
| 436 |
+
return acts + ([] if last["turned_ok"] else [["turn_by", float(rng.uniform(-np.pi, np.pi))]])
|
| 437 |
+
if kind == "blind":
|
| 438 |
+
fp = self.footprint(TARGET)
|
| 439 |
+
fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
|
| 440 |
+
return [["butter_to_basket", fp]]
|
| 441 |
+
raise ValueError(kind)
|
| 442 |
+
|
| 443 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 444 |
+
"""Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
|
| 445 |
+
k = k or self.max_attempts
|
| 446 |
+
rng = np.random.default_rng(seed)
|
| 447 |
+
history = []
|
| 448 |
+
self.reset_instance(inst)
|
| 449 |
+
memory = dict(q=self.disc_angle()) # Save: the start angle (an agent reads it off the first frame)
|
| 450 |
+
for a in range(k):
|
| 451 |
+
actions = self._plan(kind, inst, a, history, rng, memory)
|
| 452 |
+
self.do(actions)
|
| 453 |
+
self.go_home()
|
| 454 |
+
out = self.outcome(inst)
|
| 455 |
+
params = dict(actions=[[x[0]] + ([round(float(np.degrees(x[1])), 1)] if x[0] != "butter_to_basket" else [])
|
| 456 |
+
for x in actions])
|
| 457 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 458 |
+
if on_attempt:
|
| 459 |
+
on_attempt(a, params, out)
|
| 460 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 461 |
+
break
|
| 462 |
+
return history
|
| 463 |
+
|
| 464 |
+
# cross-protocol hooks are not used by this task
|
| 465 |
+
def default_params(self, inst):
|
| 466 |
+
return dict(policy="naive")
|
| 467 |
+
|
| 468 |
+
def oracle_params(self, inst):
|
| 469 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/lffbench/tasks/l3_card_edge.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L3 card_edge: a thin card lying flat on a board cannot be pinched; slide it over the board's edge, then grasp it.
|
| 2 |
+
|
| 3 |
+
Category: strategy_switching ("this way of doing it cannot work"), the user's taxonomy L3 example verbatim:
|
| 4 |
+
"卡片贴着桌面捏不起来 -> 先把卡片滑到桌沿,再夹起来".
|
| 5 |
+
|
| 6 |
+
Scene: a wooden board (22 x 26 x 5 cm) on the table with a thin red card (9.0 x 5.6 x 0.2 cm, 10 g) lying flat on it,
|
| 7 |
+
long side roughly along x or along y (+-10 deg); a grey bin (16 x 16 cm inside) stands on the table beside the board.
|
| 8 |
+
The board stands in for the table edge of the user's example: the real table edge is out of reach (near edge 16 cm
|
| 9 |
+
from the robot base, side edges at |y| = 0.6 m) and the harness does not let the grasp point go below the table top.
|
| 10 |
+
|
| 11 |
+
Why the prior fails (measured): a top-down grasp across the card's short side. The Panda fingertips land on the
|
| 12 |
+
board on either side of the card, but when they close on its 2 mm edge the contact flips to "slide over the top" and
|
| 13 |
+
both fingertips ride up over the card and close above it: 0/36 lifts for 1.5 / 2 / 3 mm cards, grasp-point height
|
| 14 |
+
-6..+3 mm, xy jitter 5 mm, yaw jitter 0.1 rad (prototype, 2026-10-08). Retrying with small variations fails the same
|
| 15 |
+
way. (A 4 mm card could be pinched -- the reason the earlier `l3_flat_card_edge` was dropped.)
|
| 16 |
+
|
| 17 |
+
What must be learned from the failure: the card cannot be picked up while it lies flat -> change the strategy: press
|
| 18 |
+
the closed fingertips onto the card and slide it (move_to with the fingertips pressing on it) until part of it hangs
|
| 19 |
+
over the board's edge, then grasp the overhanging part with the fingertips below the card: then the fingers close on
|
| 20 |
+
the card's full edge and it lifts (18/18 for 2.5-3.5 cm of overhang in the prototype). More than half the card's
|
| 21 |
+
length over the edge and it tips off the board.
|
| 22 |
+
|
| 23 |
+
Protocol: cross (reset to the same instance before every attempt), k = 5.
|
| 24 |
+
"""
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from .. import envs
|
| 28 |
+
from ..bddl import write_bddl
|
| 29 |
+
from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated
|
| 30 |
+
from ..skills import Skills
|
| 31 |
+
from ..task_base import LFFTask, register_task
|
| 32 |
+
|
| 33 |
+
CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm
|
| 34 |
+
CARD_MASS = 0.010
|
| 35 |
+
MU = 0.3 # card and board sliding friction (the fingers' 1.0 / 2.0 win in finger contacts: MuJoCo takes the max)
|
| 36 |
+
BOARD_HALF = (0.11, 0.13, 0.025)
|
| 37 |
+
BOARD_TOP = envs.TABLE_Z + 2 * BOARD_HALF[2]
|
| 38 |
+
BIN_IN = 0.08 # inner half width
|
| 39 |
+
BIN_WALL_H = 0.05
|
| 40 |
+
BIN_GAP = 0.06 # board edge to bin outer wall
|
| 41 |
+
BIN_T = 0.006
|
| 42 |
+
BIN_HALF_OUT = BIN_IN + BIN_T
|
| 43 |
+
TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
|
| 44 |
+
LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
|
| 45 |
+
OVERHANG = 0.03 # scripted target overhang (the grasp works for ~2.5-4.0 cm; the card tips off past ~4.5 cm)
|
| 46 |
+
GRASP_OUT = 0.022 # scripted grasp point: this far beyond the board edge (fingers must clear the edge)
|
| 47 |
+
DRAG_SPEED = 0.08
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
|
| 51 |
+
g = (f' <geom name="{name}_g0" type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" mass="{CARD_MASS}" '
|
| 52 |
+
f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
|
| 53 |
+
f' <geom type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
|
| 54 |
+
return _wrap(name, g, CARD_HALF[2], float(np.hypot(CARD_HALF[0], CARD_HALF[1])))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _yaw_of(quat_wxyz):
|
| 58 |
+
w, x, y, z = quat_wxyz
|
| 59 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
EDGES = ("forward", "backward", "left", "right") # board edges in robot-centric words (+x, -x, +y, -y)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class CardSkills(Skills):
|
| 66 |
+
"""Skills that feed the task's per-step monitor and log every close of the gripper."""
|
| 67 |
+
|
| 68 |
+
def __init__(self, env, task, recorder=None):
|
| 69 |
+
super().__init__(env, recorder=recorder)
|
| 70 |
+
self.task = task
|
| 71 |
+
self.closes = []
|
| 72 |
+
|
| 73 |
+
def _act(self, dpos, drot, grip):
|
| 74 |
+
super()._act(dpos, drot, grip)
|
| 75 |
+
self.task.monitor_step()
|
| 76 |
+
|
| 77 |
+
def set_gripper(self, close, steps=15):
|
| 78 |
+
was_open = self.grip < 0
|
| 79 |
+
before = self.task.close_context() if (close and was_open) else None
|
| 80 |
+
rep = super().set_gripper(close, steps)
|
| 81 |
+
if before is not None:
|
| 82 |
+
before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
|
| 83 |
+
self.closes.append(before)
|
| 84 |
+
return rep
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@register_task
|
| 88 |
+
class CardEdge(LFFTask):
|
| 89 |
+
name = "l3_card_edge"
|
| 90 |
+
level = "L3"
|
| 91 |
+
category = "strategy_switching"
|
| 92 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 93 |
+
protocol = "cross"
|
| 94 |
+
instruction = "Pick up the thin red card lying on the wooden board and put it into the grey bin."
|
| 95 |
+
instruction_indirect = "Put the flat red rectangle that lies on the wooden block into the grey container."
|
| 96 |
+
|
| 97 |
+
# ------------------------------------------------------------ scene
|
| 98 |
+
def make_bddl(self):
|
| 99 |
+
card = register_generated("LffThinCard", card_xml("lff_thin_card"))
|
| 100 |
+
board = register_generated("LffCardBoard", box_xml("lff_card_board", BOARD_HALF, (0.62, 0.45, 0.27, 1.0),
|
| 101 |
+
friction=(MU, 0.005, 0.0001)), free=False)
|
| 102 |
+
bin_ = register_generated("LffCardBin", bin_xml("lff_card_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
|
| 103 |
+
rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
|
| 104 |
+
objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
|
| 105 |
+
fx = [("board_1", board, "board_region", (-0.11, -0.01, -0.09, 0.01)),
|
| 106 |
+
("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
|
| 107 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 108 |
+
|
| 109 |
+
def __init__(self, cam_res=None):
|
| 110 |
+
super().__init__(cam_res)
|
| 111 |
+
m = self.env.sim.model
|
| 112 |
+
self.board_bid = m.body_name2id(self.env.fixtures_dict["board_1"].root_body)
|
| 113 |
+
self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
|
| 114 |
+
self.inst = None
|
| 115 |
+
self.mon = None
|
| 116 |
+
|
| 117 |
+
def sample_instance(self, seed):
|
| 118 |
+
rng = np.random.default_rng(seed)
|
| 119 |
+
bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
|
| 120 |
+
along = str(rng.choice(["x", "y"]))
|
| 121 |
+
yaw = (0.0 if along == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10)))
|
| 122 |
+
if along == "x": # keep the whole card >= 3 cm (long axis) / 2 cm (short axis) inside the board
|
| 123 |
+
off = [rng.uniform(-0.03, 0.03), rng.uniform(-0.07, 0.07)]
|
| 124 |
+
else:
|
| 125 |
+
off = [rng.uniform(-0.055, 0.055), rng.uniform(-0.05, 0.05)]
|
| 126 |
+
side = 1.0 if rng.random() < 0.5 else -1.0
|
| 127 |
+
bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (BOARD_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
|
| 128 |
+
return dict(seed=int(seed), board_xy=[bx, by], card_xy=[bx + float(off[0]), by + float(off[1])],
|
| 129 |
+
card_yaw=float(yaw), card_along=along, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
|
| 130 |
+
|
| 131 |
+
def apply_instance(self, inst):
|
| 132 |
+
self.inst = inst
|
| 133 |
+
m = self.env.sim.model
|
| 134 |
+
bx, by = inst["board_xy"]
|
| 135 |
+
m.body_pos[self.board_bid] = [bx, by, envs.TABLE_Z + BOARD_HALF[2]]
|
| 136 |
+
m.body_quat[self.board_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 137 |
+
cx, cy = inst["bin_xy"]
|
| 138 |
+
m.body_pos[self.bin_bid] = [cx, cy, envs.TABLE_Z + (BIN_WALL_H + BIN_T) / 2]
|
| 139 |
+
m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 140 |
+
x, y = inst["card_xy"]
|
| 141 |
+
envs.set_obj_pose(self.env, "card_1", [x, y, BOARD_TOP + CARD_HALF[2] + 0.0003], yaw=inst["card_yaw"])
|
| 142 |
+
|
| 143 |
+
def reset_instance(self, inst, recorder=None):
|
| 144 |
+
self.env.reset()
|
| 145 |
+
self.apply_instance(inst)
|
| 146 |
+
self.env.sim.forward()
|
| 147 |
+
envs.settle(self.env, 15)
|
| 148 |
+
self.sk = CardSkills(self.env, self, recorder=recorder)
|
| 149 |
+
p = self.card_pose()
|
| 150 |
+
self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False)
|
| 151 |
+
return self.sk
|
| 152 |
+
|
| 153 |
+
# ------------------------------------------------------------ geometry
|
| 154 |
+
def card_pose(self):
|
| 155 |
+
p = envs.obj_pos(self.env, "card_1")
|
| 156 |
+
return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
|
| 157 |
+
|
| 158 |
+
def card_corners(self):
|
| 159 |
+
d = self.env.sim.data
|
| 160 |
+
bid = envs.body_id(self.env, "card_1")
|
| 161 |
+
R = d.body_xmat[bid].reshape(3, 3)
|
| 162 |
+
h = np.array(CARD_HALF)
|
| 163 |
+
return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
|
| 164 |
+
|
| 165 |
+
def overhang(self):
|
| 166 |
+
"""(how far the card sticks out beyond the board's edges (m, max over its corners), edge word)"""
|
| 167 |
+
c = self.card_corners()[:, :2] - np.asarray(self.inst["board_xy"])
|
| 168 |
+
prot = {"forward": c[:, 0].max() - BOARD_HALF[0], "backward": -c[:, 0].min() - BOARD_HALF[0],
|
| 169 |
+
"left": c[:, 1].max() - BOARD_HALF[1], "right": -c[:, 1].min() - BOARD_HALF[1]}
|
| 170 |
+
e = max(prot, key=prot.get)
|
| 171 |
+
return float(prot[e]), e
|
| 172 |
+
|
| 173 |
+
def on_board(self):
|
| 174 |
+
p = self.card_pose()
|
| 175 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["board_xy"]))
|
| 176 |
+
return bool(rel[0] <= BOARD_HALF[0] and rel[1] <= BOARD_HALF[1] and abs(p["z"] - BOARD_TOP) < 0.012)
|
| 177 |
+
|
| 178 |
+
def in_bin(self):
|
| 179 |
+
p = self.card_pose()
|
| 180 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
|
| 181 |
+
return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < envs.TABLE_Z + BIN_T + BIN_WALL_H)
|
| 182 |
+
|
| 183 |
+
# ------------------------------------------------------------ monitor
|
| 184 |
+
def monitor_step(self):
|
| 185 |
+
mon = self.mon
|
| 186 |
+
if mon is None:
|
| 187 |
+
return
|
| 188 |
+
zmin = float(self.card_corners()[:, 2].min())
|
| 189 |
+
mon["max_lift"] = max(mon["max_lift"], zmin - BOARD_TOP)
|
| 190 |
+
if self.on_board() or abs(self.card_pose()["z"] - BOARD_TOP) < 0.012:
|
| 191 |
+
mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
|
| 192 |
+
if self.card_pose()["z"] < BOARD_TOP - 0.02 and not self.sk.holding("card_1"):
|
| 193 |
+
mon["fell"] = True
|
| 194 |
+
|
| 195 |
+
def close_context(self):
|
| 196 |
+
"""Where the gripper is relative to the card and the board just before it closes."""
|
| 197 |
+
sk, p = self.sk, self.card_pose()
|
| 198 |
+
e = sk.eef_pos()
|
| 199 |
+
c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
|
| 200 |
+
rel = e[:2] - p["xy"]
|
| 201 |
+
local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side
|
| 202 |
+
b = e[:2] - np.asarray(self.inst["board_xy"])
|
| 203 |
+
beyond = {"forward": b[0] - BOARD_HALF[0], "backward": -b[0] - BOARD_HALF[0],
|
| 204 |
+
"left": b[1] - BOARD_HALF[1], "right": -b[1] - BOARD_HALF[1]}
|
| 205 |
+
edge = max(beyond, key=beyond.get)
|
| 206 |
+
ov, ov_edge = self.overhang()
|
| 207 |
+
return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
|
| 208 |
+
tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
|
| 209 |
+
beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
|
| 210 |
+
card_on_board=self.on_board(), overhang=round(ov, 4), overhang_edge=ov_edge,
|
| 211 |
+
width_before=round(sk.gripper_width(), 4))
|
| 212 |
+
|
| 213 |
+
# ------------------------------------------------------------ outcome / F2
|
| 214 |
+
def outcome(self, inst):
|
| 215 |
+
envs.settle(self.env, 30)
|
| 216 |
+
sk, mon = self.sk, self.mon
|
| 217 |
+
p = self.card_pose()
|
| 218 |
+
held = bool(sk.holding("card_1"))
|
| 219 |
+
in_bin = self.in_bin() and not held
|
| 220 |
+
success = bool(in_bin)
|
| 221 |
+
moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
|
| 222 |
+
lifted = mon["max_lift"] > 0.02
|
| 223 |
+
tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
|
| 224 |
+
parts, mode = [], "success"
|
| 225 |
+
if success:
|
| 226 |
+
parts.append("The card is in the bin.")
|
| 227 |
+
else:
|
| 228 |
+
rel = p["xy"] - np.asarray(inst["bin_xy"])
|
| 229 |
+
where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
|
| 230 |
+
f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
|
| 231 |
+
if held:
|
| 232 |
+
mode = "held"
|
| 233 |
+
parts.append(f"The card is still held by the gripper, {where}.")
|
| 234 |
+
elif lifted:
|
| 235 |
+
mode = "dropped"
|
| 236 |
+
loc = "on the board" if self.on_board() else ("on the table" if p["z"] < BOARD_TOP - 0.02 else
|
| 237 |
+
"partly on the board")
|
| 238 |
+
parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the board but is not in the "
|
| 239 |
+
f"bin: it lies {loc}, its centre {where}.")
|
| 240 |
+
elif mon["fell"]:
|
| 241 |
+
mode = "fell_off"
|
| 242 |
+
parts.append("The card was never lifted; it fell off the board and lies flat on the table.")
|
| 243 |
+
else:
|
| 244 |
+
mode = "not_lifted"
|
| 245 |
+
parts.append("The card was never lifted; it still lies flat on the board"
|
| 246 |
+
+ (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
|
| 247 |
+
f"{100 * mon['max_overhang']:.1f} cm beyond the board's edge)" if mon["max_overhang"] > 0.003
|
| 248 |
+
else ")") if moved > 0.005 else "") + ".")
|
| 249 |
+
if not lifted:
|
| 250 |
+
if not tries:
|
| 251 |
+
parts.append("The gripper never closed with its fingertips down at the card.")
|
| 252 |
+
else:
|
| 253 |
+
c = tries[-1]
|
| 254 |
+
n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
|
| 255 |
+
if c["card_on_board"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
|
| 256 |
+
txt = ("when the gripper closed on the card lying flat on the board, its fingertips were on "
|
| 257 |
+
"either side of the card, at board level")
|
| 258 |
+
else:
|
| 259 |
+
if c["beyond_edge"] >= 0.0:
|
| 260 |
+
pos = f"{100 * c['beyond_edge']:.1f} cm beyond the board's {c['beyond_edge_name']} edge"
|
| 261 |
+
else:
|
| 262 |
+
pos = f"over the board, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge"
|
| 263 |
+
txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm "
|
| 264 |
+
f"beyond the board's {c['overhang_edge']} edge and the gripper's centre was {pos}")
|
| 265 |
+
txt += (f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the "
|
| 266 |
+
"fingers closed ")
|
| 267 |
+
txt += ("fully, sliding over the top of the card instead of gripping its edges."
|
| 268 |
+
if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
|
| 269 |
+
("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
|
| 270 |
+
parts.append(n + txt if n else txt[0].upper() + txt[1:])
|
| 271 |
+
out = dict(success=success, mode=mode, held=held, lifted=bool(lifted), max_lift=round(mon["max_lift"], 4),
|
| 272 |
+
max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), fell=bool(mon["fell"]),
|
| 273 |
+
grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
|
| 274 |
+
return out
|
| 275 |
+
|
| 276 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 277 |
+
def _edge_plan(self, inst):
|
| 278 |
+
"""the board edge the card is slid to: along its long side; the near (backward) edge for x-cards,
|
| 279 |
+
the closer side edge for y-cards"""
|
| 280 |
+
if inst["card_along"] == "x":
|
| 281 |
+
return "backward"
|
| 282 |
+
return "left" if inst["card_xy"][1] >= inst["board_xy"][1] else "right"
|
| 283 |
+
|
| 284 |
+
def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
|
| 285 |
+
sk = self.sk
|
| 286 |
+
sk.set_gripper(False, steps=8)
|
| 287 |
+
sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
|
| 288 |
+
sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
|
| 289 |
+
sk.set_gripper(True, steps=15)
|
| 290 |
+
sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
|
| 291 |
+
if not sk.holding("card_1"):
|
| 292 |
+
sk.set_gripper(False, steps=8)
|
| 293 |
+
return False
|
| 294 |
+
bx, by = self.inst["bin_xy"]
|
| 295 |
+
hi = envs.TABLE_Z + BIN_WALL_H + 0.12
|
| 296 |
+
sk.move_to([bx, by, hi])
|
| 297 |
+
sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05], speed=0.2)
|
| 298 |
+
sk.set_gripper(False, steps=12)
|
| 299 |
+
sk.move_to([bx, by, hi])
|
| 300 |
+
return True
|
| 301 |
+
|
| 302 |
+
def slide_card(self, delta, press=0.004):
|
| 303 |
+
"""closed fingertips pressed on the card's centre, straight move by `delta` (xy), lift"""
|
| 304 |
+
sk, p = self.sk, self.card_pose()
|
| 305 |
+
z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
|
| 306 |
+
sk.set_gripper(True, steps=8)
|
| 307 |
+
sk.move_to([p["xy"][0], p["xy"][1], z + 0.06], yaw=p["yaw"])
|
| 308 |
+
sk.move_to([p["xy"][0], p["xy"][1], z], tol=0.003, max_steps=100)
|
| 309 |
+
e = p["xy"] + np.asarray(delta, float)
|
| 310 |
+
sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
|
| 311 |
+
sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
|
| 312 |
+
sk.hold(5)
|
| 313 |
+
|
| 314 |
+
def execute(self, inst, params):
|
| 315 |
+
p = self.card_pose()
|
| 316 |
+
if params["mode"] == "grasp":
|
| 317 |
+
xy = p["xy"] + np.asarray(params.get("dxy", (0.0, 0.0)))
|
| 318 |
+
self.grasp_and_bin(xy, p["yaw"] + params.get("dyaw", 0.0), BOARD_TOP + params.get("dz", 0.0))
|
| 319 |
+
return
|
| 320 |
+
# edge: slide the card along its long side until `overhang` of it sticks out over the chosen edge
|
| 321 |
+
edge = params.get("edge") or self._edge_plan(inst)
|
| 322 |
+
u = {"forward": (1, 0), "backward": (-1, 0), "left": (0, 1), "right": (0, -1)}[edge]
|
| 323 |
+
u = np.asarray(u, float)
|
| 324 |
+
c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
|
| 325 |
+
long_ax = np.array([c, s]) if abs(np.array([c, s]) @ u) >= abs(np.array([-s, c]) @ u) else np.array([-s, c])
|
| 326 |
+
long_ax = long_ax * np.sign(long_ax @ u)
|
| 327 |
+
b = np.asarray(inst["board_xy"])
|
| 328 |
+
half = BOARD_HALF[0] if edge in ("forward", "backward") else BOARD_HALF[1]
|
| 329 |
+
edge_pos = (b @ u) + half # coordinate of the edge along u
|
| 330 |
+
ext = CARD_HALF[0] * abs(long_ax @ u) + CARD_HALF[1] * abs(np.array([-long_ax[1], long_ax[0]]) @ u)
|
| 331 |
+
for short in (0.01, 0.0): # slide to 1 cm short, look again, slide the rest (one stroke overshoots ~0.7 cm)
|
| 332 |
+
p = self.card_pose()
|
| 333 |
+
need = edge_pos + float(params["overhang"]) - short - (p["xy"] @ u + ext) # travel still needed along u
|
| 334 |
+
if need > 0.003:
|
| 335 |
+
self.slide_card(long_ax * need / max(long_ax @ u, 1e-6))
|
| 336 |
+
q = self.card_pose()
|
| 337 |
+
cu = float(q["xy"] @ u)
|
| 338 |
+
tip_u = cu + CARD_HALF[0] * float(long_ax @ u) # centre of the card's far end, along u
|
| 339 |
+
target_u = min(tip_u - 0.008, edge_pos + GRASP_OUT)
|
| 340 |
+
g = q["xy"] + long_ax * (target_u - cu) / max(float(long_ax @ u), 1e-6)
|
| 341 |
+
self.grasp_and_bin(g, q["yaw"], BOARD_TOP - 0.003)
|
| 342 |
+
|
| 343 |
+
def default_params(self, inst):
|
| 344 |
+
return dict(mode="grasp")
|
| 345 |
+
|
| 346 |
+
def oracle_params(self, inst):
|
| 347 |
+
return dict(mode="edge", overhang=OVERHANG)
|
| 348 |
+
|
| 349 |
+
def blind_params(self, inst, attempt, rng):
|
| 350 |
+
return dict(mode="grasp", dxy=rng.normal(0.0, 0.006, 2).tolist(), dyaw=float(rng.normal(0.0, 0.12)),
|
| 351 |
+
dz=float(rng.uniform(-0.006, 0.003)))
|
| 352 |
+
|
| 353 |
+
def adapt_params(self, inst, history):
|
| 354 |
+
"""not lifted while flat on the board (fingers slid over it) -> slide it over the edge first, 3 cm.
|
| 355 |
+
Edge tried: card fell off -> 1 cm less; fingers closed without holding and < 4 cm overhang -> 1 cm more."""
|
| 356 |
+
out, prm = history[-1]["outcome"], history[-1]["params"]
|
| 357 |
+
if prm["mode"] == "grasp":
|
| 358 |
+
return dict(mode="edge", overhang=OVERHANG) if out["mode"] in ("not_lifted", "fell_off") else dict(prm)
|
| 359 |
+
h = float(prm["overhang"])
|
| 360 |
+
if out["mode"] == "fell_off":
|
| 361 |
+
h -= 0.01
|
| 362 |
+
elif out["mode"] == "not_lifted":
|
| 363 |
+
h += 0.01 if out["max_overhang"] < 0.04 else -0.005
|
| 364 |
+
return dict(mode="edge", overhang=float(np.clip(h, 0.025, 0.045)))
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/agent_cost.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Project GPT-6 cost / latency of a protocol from a run directory.
|
| 2 |
+
|
| 3 |
+
Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made
|
| 4 |
+
with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES:
|
| 5 |
+
input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption)
|
| 6 |
+
cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) --
|
| 7 |
+
the first call of an attempt is counted as uncached (conservative)
|
| 8 |
+
output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500)
|
| 9 |
+
latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input
|
| 10 |
+
tokens and high/xhigh effort -- treat as an upper-range planning number)
|
| 11 |
+
The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls).
|
| 12 |
+
|
| 13 |
+
python scripts/agent_cost.py runs/agent/l5_slide_to_target/<run> --out-tokens 1500 --latency 20 --calls-scale 2
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
|
| 21 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 22 |
+
|
| 23 |
+
from lffbench.agent.cost import PRICES, call_cost # noqa: E402
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
ap = argparse.ArgumentParser()
|
| 28 |
+
ap.add_argument("run_dir")
|
| 29 |
+
ap.add_argument("--model", default="gpt-6-astra")
|
| 30 |
+
ap.add_argument("--out-tokens", type=float, default=1500)
|
| 31 |
+
ap.add_argument("--latency", type=float, default=20.0)
|
| 32 |
+
ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)")
|
| 33 |
+
a = ap.parse_args()
|
| 34 |
+
ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))]
|
| 35 |
+
calls = [e for e in ev if e["type"] == "llm_call"]
|
| 36 |
+
runs = {e["seed"] for e in ev if e["type"] == "run_start"}
|
| 37 |
+
real = [c for c in calls if c.get("usage")]
|
| 38 |
+
if real and not any("dry_run_request" in c for c in calls):
|
| 39 |
+
cost = sum(call_cost(c["usage"], a.model) or 0 for c in real)
|
| 40 |
+
lat = [c["latency_s"] for c in real]
|
| 41 |
+
u = defaultdict(int)
|
| 42 |
+
for c in real:
|
| 43 |
+
for kk, v in c["usage"].items():
|
| 44 |
+
u[kk] += v
|
| 45 |
+
out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1),
|
| 46 |
+
usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
|
| 47 |
+
latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1))
|
| 48 |
+
else:
|
| 49 |
+
prev = {}
|
| 50 |
+
tot_in = tot_cached = 0
|
| 51 |
+
cost1 = 0.0 # priced per call (the long-context surcharge applies per request)
|
| 52 |
+
for c in calls:
|
| 53 |
+
d = c.get("dry_run_request")
|
| 54 |
+
if not d:
|
| 55 |
+
continue
|
| 56 |
+
key = (c["seed"], c["attempt"])
|
| 57 |
+
tin = d["est_input_tokens"]
|
| 58 |
+
cached = min(prev.get(key, 0), tin)
|
| 59 |
+
prev[key] = tin
|
| 60 |
+
tot_in += tin
|
| 61 |
+
tot_cached += cached
|
| 62 |
+
cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model)
|
| 63 |
+
n = len(calls) * a.calls_scale
|
| 64 |
+
scale = a.calls_scale
|
| 65 |
+
usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens)
|
| 66 |
+
cost = cost1 * scale
|
| 67 |
+
out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1),
|
| 68 |
+
input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1),
|
| 69 |
+
usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
|
| 70 |
+
api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model),
|
| 71 |
+
assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency,
|
| 72 |
+
calls_scale=a.calls_scale, image_tokens_512px=256))
|
| 73 |
+
print(json.dumps(out, indent=1, default=str))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/audit_subagent.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit an isolated policy subagent: every tool call it made must stay inside its sandbox.
|
| 2 |
+
|
| 3 |
+
python scripts/audit_subagent.py <transcript.jsonl> <sandbox_dir> [--out audit.json]
|
| 4 |
+
Allowed: Bash `cd <sandbox> && ./robot ...` (or `<sandbox>/robot ...`); Read of <sandbox>/README.md or <sandbox>/obs/*.
|
| 5 |
+
With --la (LIBERO-Agent-style workspace): also Bash `cd <sandbox> && ./shell '<cmd>'` / `./shell <<'TAG' ... TAG` (the
|
| 6 |
+
command runs inside the jail; anything the OUTER shell would execute or expand is a violation), and Read / Write / Edit
|
| 7 |
+
of any file inside <sandbox>.
|
| 8 |
+
Everything else is reported as a violation. Prints counts + violations only (the transcript itself is large).
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def tool_uses(obj):
|
| 16 |
+
if isinstance(obj, dict):
|
| 17 |
+
if obj.get("type") == "tool_use" and "name" in obj:
|
| 18 |
+
yield obj
|
| 19 |
+
for v in obj.values():
|
| 20 |
+
yield from tool_uses(v)
|
| 21 |
+
elif isinstance(obj, list):
|
| 22 |
+
for v in obj:
|
| 23 |
+
yield from tool_uses(v)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def extra_shell_ops(cmd, sb):
|
| 27 |
+
"""True if the command contains shell operators / substitutions outside quotes, apart from the
|
| 28 |
+
allowed leading `cd <sandbox> &&`."""
|
| 29 |
+
import shlex
|
| 30 |
+
body = re.sub(r"^\s*cd\s+%s\s*&&\s*" % re.escape(sb), "", cmd)
|
| 31 |
+
if "`" in body or "$(" in body:
|
| 32 |
+
return True
|
| 33 |
+
try:
|
| 34 |
+
lex = shlex.shlex(body, posix=True, punctuation_chars=True)
|
| 35 |
+
toks = list(lex)
|
| 36 |
+
except ValueError:
|
| 37 |
+
return True
|
| 38 |
+
return any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def shell_call_ok(cmd, sb):
|
| 42 |
+
"""la: `cd <sb> && ./shell ...` where nothing runs outside the jail: either one heredoc with a QUOTED tag (no outer
|
| 43 |
+
expansion) and nothing after it, or plain arguments without outer operators / substitutions."""
|
| 44 |
+
m = re.match(r"^\s*cd\s+%s\s*&&\s*(\./shell|%s/shell)(.*)$" % (re.escape(sb), re.escape(sb)), cmd, re.S)
|
| 45 |
+
if not m:
|
| 46 |
+
return False
|
| 47 |
+
rest = m.group(2)
|
| 48 |
+
s = rest.strip()
|
| 49 |
+
if rest[:1].isspace() and len(s) >= 2 and s[0] == "'" and s[-1] == "'" and "'" not in s[1:-1]:
|
| 50 |
+
return True # one single-quoted argument: the outer shell expands nothing (an inner `<<EOF` runs in the jail)
|
| 51 |
+
if "<<" in rest:
|
| 52 |
+
first, _, body = rest.partition("\n")
|
| 53 |
+
hm = re.match(r"^\s*<<-?\s*(['\"])(\w+)\1\s*$", first)
|
| 54 |
+
if not hm:
|
| 55 |
+
return False # unquoted tag: the outer shell would expand $(...) inside the heredoc
|
| 56 |
+
tag = hm.group(2)
|
| 57 |
+
lines = body.rstrip("\n").split("\n")
|
| 58 |
+
return bool(lines) and lines[-1].strip() == tag and tag not in [l.strip() for l in lines[:-1]]
|
| 59 |
+
if "`" in rest or "$(" in rest.replace("'", "\x00").split("\x00")[0::2].__str__():
|
| 60 |
+
return False
|
| 61 |
+
import shlex
|
| 62 |
+
try:
|
| 63 |
+
toks = list(shlex.shlex(rest, posix=True, punctuation_chars=True))
|
| 64 |
+
except ValueError:
|
| 65 |
+
return False
|
| 66 |
+
return not any(t in (";", "&&", "||", "|", "&", ">", ">>", "<") for t in toks)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main():
|
| 70 |
+
ap = argparse.ArgumentParser()
|
| 71 |
+
ap.add_argument("transcript")
|
| 72 |
+
ap.add_argument("sandbox")
|
| 73 |
+
ap.add_argument("--out")
|
| 74 |
+
ap.add_argument("--la", action="store_true", help="LIBERO-Agent-style workspace: ./shell and workspace files allowed")
|
| 75 |
+
a = ap.parse_args()
|
| 76 |
+
sb = a.sandbox.rstrip("/")
|
| 77 |
+
ok_bash = re.compile(r"^\s*(cd\s+%s\s*&&\s*)?(\./robot|%s/robot)(\s|$)" % (re.escape(sb), re.escape(sb)))
|
| 78 |
+
seen, calls, viol = set(), [], []
|
| 79 |
+
injected = [] # context Claude Code attached on its own: the user's memory index / identity
|
| 80 |
+
with open(a.transcript) as f:
|
| 81 |
+
for line in f:
|
| 82 |
+
try:
|
| 83 |
+
rec = json.loads(line)
|
| 84 |
+
except ValueError:
|
| 85 |
+
continue
|
| 86 |
+
if rec.get("type") == "attachment":
|
| 87 |
+
at = rec.get("attachment", {})
|
| 88 |
+
if at.get("type") == "instructions":
|
| 89 |
+
for fi in at.get("files", []):
|
| 90 |
+
if "memory" in (fi.get("path") or "").lower() or fi.get("type") == "AutoMem":
|
| 91 |
+
injected.append(dict(kind="memory_index", path=fi.get("path"), chars=len(fi.get("content", ""))))
|
| 92 |
+
elif at.get("type") == "session_context":
|
| 93 |
+
injected.append(dict(kind="session_context", keys=sorted((at.get("context") or {}).keys())))
|
| 94 |
+
for tu in tool_uses(rec):
|
| 95 |
+
if tu.get("id") in seen:
|
| 96 |
+
continue
|
| 97 |
+
seen.add(tu.get("id"))
|
| 98 |
+
name, inp = tu["name"], tu.get("input", {})
|
| 99 |
+
calls.append(name)
|
| 100 |
+
if name == "SubagentHandback": # the final report back to the orchestrator
|
| 101 |
+
continue
|
| 102 |
+
if name == "Bash":
|
| 103 |
+
cmd = inp.get("command", "")
|
| 104 |
+
bad = (not ok_bash.match(cmd)) or extra_shell_ops(cmd, sb)
|
| 105 |
+
if bad and a.la and shell_call_ok(cmd, sb):
|
| 106 |
+
bad = False
|
| 107 |
+
if bad:
|
| 108 |
+
viol.append(dict(tool=name, command=cmd))
|
| 109 |
+
elif name in ("Read", "Write", "Edit") and a.la:
|
| 110 |
+
import os
|
| 111 |
+
p = os.path.normpath(inp.get("file_path", ""))
|
| 112 |
+
if not p.startswith(sb + "/"):
|
| 113 |
+
viol.append(dict(tool=name, path=inp.get("file_path", "")))
|
| 114 |
+
elif name == "Read":
|
| 115 |
+
p = inp.get("file_path", "")
|
| 116 |
+
if not (p == f"{sb}/README.md" or p.startswith(f"{sb}/obs/")):
|
| 117 |
+
viol.append(dict(tool=name, path=p))
|
| 118 |
+
else:
|
| 119 |
+
viol.append(dict(tool=name, input=json.dumps(inp)[:300]))
|
| 120 |
+
from collections import Counter
|
| 121 |
+
res = dict(n_calls=len(calls), by_tool=dict(Counter(calls)), n_violations=len(viol), violations=viol,
|
| 122 |
+
memory_injected=any(i["kind"] == "memory_index" for i in injected), injected=injected)
|
| 123 |
+
print(json.dumps(res, indent=1, ensure_ascii=False))
|
| 124 |
+
if a.out:
|
| 125 |
+
with open(a.out, "w") as f:
|
| 126 |
+
json.dump(res, f, indent=1, ensure_ascii=False)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
main()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_opus/lff/source_closure/scripts/mcp_robot_server.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MCP server (stdio) exposing one robot_server session to a native agent harness (Claude Code, Codex, Gemini CLI, ...).
|
| 2 |
+
|
| 3 |
+
The tools are exactly the unified harness's LA tools (scripts/api_player.py): `robot`, `shell` (jailed, in the episode
|
| 4 |
+
workspace) and `view_images` (returned as MCP image content), with the same per-attempt tool-call budget: when it is
|
| 5 |
+
used up the attempt is finished automatically and the result is appended to that call's output. So a native harness
|
| 6 |
+
and the API harness see the same README, tools and limits; only the agent loop around them differs.
|
| 7 |
+
|
| 8 |
+
python scripts/mcp_robot_server.py --session runs/<...>/session.json
|
| 9 |
+
python scripts/mcp_robot_server.py --schema-only (launch preflight: same tools/list, no session, every call fails)
|
| 10 |
+
Every call is logged to <log dir>/mcp_transcript.jsonl (the first line lists the names of the environment variables the
|
| 11 |
+
harness passed to this process, for the harness self-check). Nothing but JSON-RPC goes to stdout.
|
| 12 |
+
The tools themselves are scripts/tool_gateway.py's ToolCore: through the episode's tool gateway when the launcher
|
| 13 |
+
started one (gateway.json in the log dir; docs/18 §6.1), otherwise in this process.
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
import traceback
|
| 21 |
+
|
| 22 |
+
ENV_AT_START = dict(os.environ) # what the harness passed (before our own imports touch the environment)
|
| 23 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 24 |
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "client"))
|
| 25 |
+
from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA # noqa: E402
|
| 26 |
+
from lffbench_client import Session as Client # noqa: E402
|
| 27 |
+
from tool_gateway import GATEWAY_FILE, ToolCore # noqa: E402
|
| 28 |
+
|
| 29 |
+
PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
| 30 |
+
TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Session:
|
| 34 |
+
"""One episode's tools. With a tool gateway (scripts/tool_gateway.py, started by harness_run.py; its gateway.json is
|
| 35 |
+
in the run's log dir) every call goes to the gateway, which owns the per-attempt budget for the whole episode, also
|
| 36 |
+
across the MCP processes of a resumed CLI. Without one, the same ToolCore runs in this process and the budget is
|
| 37 |
+
carried over from mcp_transcript.jsonl. Either way the tool outputs are the gateway's ToolCore's, byte for byte."""
|
| 38 |
+
|
| 39 |
+
def __init__(self, session_path):
|
| 40 |
+
self.log_dir = os.path.dirname(os.path.abspath(session_path))
|
| 41 |
+
tpath = os.path.join(self.log_dir, "mcp_transcript.jsonl")
|
| 42 |
+
gfile = os.path.join(self.log_dir, GATEWAY_FILE)
|
| 43 |
+
self.gateway = Client.from_gateway_file(gfile, face="mcp") if os.path.exists(gfile) else None
|
| 44 |
+
self.core = None if self.gateway else ToolCore(session_path, carry_from=tpath)
|
| 45 |
+
self.calls_in_attempt = self.core.calls_in_attempt if self.core else None
|
| 46 |
+
self.finished = self.core.finished if self.core else False
|
| 47 |
+
self.tlog = open(tpath, "a")
|
| 48 |
+
|
| 49 |
+
def log(self, d):
|
| 50 |
+
d["t"] = time.time()
|
| 51 |
+
self.tlog.write(json.dumps(d, ensure_ascii=False) + "\n")
|
| 52 |
+
self.tlog.flush()
|
| 53 |
+
|
| 54 |
+
def call(self, name, args):
|
| 55 |
+
"""-> (MCP content list, is_error)"""
|
| 56 |
+
if self.core is not None:
|
| 57 |
+
content, err = self.core.call(name, args)
|
| 58 |
+
self.calls_in_attempt, self.finished = self.core.calls_in_attempt, self.core.finished
|
| 59 |
+
return content, err
|
| 60 |
+
r = self.gateway.call(name, args)
|
| 61 |
+
self.calls_in_attempt, self.finished = r.calls_in_attempt, r.finished
|
| 62 |
+
return r.content, r.is_error
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class SchemaOnly:
|
| 66 |
+
"""No robot session: the harness preflight only needs tools/list (byte-identical to a real session)."""
|
| 67 |
+
finished = False
|
| 68 |
+
|
| 69 |
+
def log(self, d):
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
def call(self, name, args):
|
| 73 |
+
return [dict(type="text", text="schema-only preflight server: no robot session")], True
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def serve(sess):
|
| 77 |
+
def send(obj):
|
| 78 |
+
sys.stdout.write(json.dumps(obj) + "\n")
|
| 79 |
+
sys.stdout.flush()
|
| 80 |
+
|
| 81 |
+
for line in sys.stdin:
|
| 82 |
+
line = line.strip()
|
| 83 |
+
if not line:
|
| 84 |
+
continue
|
| 85 |
+
try:
|
| 86 |
+
msg = json.loads(line)
|
| 87 |
+
except ValueError:
|
| 88 |
+
send(dict(jsonrpc="2.0", id=None, error=dict(code=-32700, message="parse error")))
|
| 89 |
+
continue
|
| 90 |
+
mid, method, params = msg.get("id"), msg.get("method"), msg.get("params") or {}
|
| 91 |
+
if mid is None: # notification (notifications/initialized, cancelled, ...)
|
| 92 |
+
continue
|
| 93 |
+
try:
|
| 94 |
+
if method == "initialize":
|
| 95 |
+
want = params.get("protocolVersion")
|
| 96 |
+
result = dict(protocolVersion=want if want in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0],
|
| 97 |
+
capabilities=dict(tools=dict(listChanged=False)),
|
| 98 |
+
serverInfo=dict(name="lffbench-robot", version="1.0"))
|
| 99 |
+
elif method == "ping":
|
| 100 |
+
result = {}
|
| 101 |
+
elif method == "tools/list":
|
| 102 |
+
result = dict(tools=[dict(name=t["name"], description=t["description"], inputSchema=t["parameters"])
|
| 103 |
+
for t in TOOLS])
|
| 104 |
+
elif method == "tools/call":
|
| 105 |
+
name, args = params.get("name"), params.get("arguments") or {}
|
| 106 |
+
t0 = time.time()
|
| 107 |
+
content, err = sess.call(name, args)
|
| 108 |
+
sess.log(dict(ev="tool", name=name, arguments=args, dt=round(time.time() - t0, 2), is_error=err,
|
| 109 |
+
output=[c["text"] for c in content if c["type"] == "text"],
|
| 110 |
+
images=sum(1 for c in content if c["type"] == "image"), finished=sess.finished,
|
| 111 |
+
calls_in_attempt=getattr(sess, "calls_in_attempt", None)))
|
| 112 |
+
result = dict(content=content, isError=err)
|
| 113 |
+
else:
|
| 114 |
+
send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32601, message=f"method not found: {method}")))
|
| 115 |
+
continue
|
| 116 |
+
send(dict(jsonrpc="2.0", id=mid, result=result))
|
| 117 |
+
except Exception as e:
|
| 118 |
+
sess.log(dict(ev="error", method=method, error=traceback.format_exc()[-2000:]))
|
| 119 |
+
send(dict(jsonrpc="2.0", id=mid, error=dict(code=-32603, message=f"{type(e).__name__}: {e}")))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def main():
|
| 123 |
+
ap = argparse.ArgumentParser()
|
| 124 |
+
ap.add_argument("--session", help="session.json written by start_robot_session.sh (la style)")
|
| 125 |
+
ap.add_argument("--schema-only", action="store_true", help="serve the tool list only (harness launch preflight)")
|
| 126 |
+
a = ap.parse_args()
|
| 127 |
+
if a.schema_only:
|
| 128 |
+
serve(SchemaOnly())
|
| 129 |
+
return
|
| 130 |
+
if not a.session:
|
| 131 |
+
ap.error("--session is required (or --schema-only)")
|
| 132 |
+
sess = Session(a.session)
|
| 133 |
+
import hashlib # names + 8-hex sha256 of each value (enough to tell inherited from fresh values, reveals nothing)
|
| 134 |
+
sess.log(dict(ev="start", session=a.session, pid=os.getpid(), env_keys=sorted(ENV_AT_START),
|
| 135 |
+
env_value_sha8={k: hashlib.sha256(v.encode()).hexdigest()[:8] for k, v in ENV_AT_START.items()}))
|
| 136 |
+
serve(sess)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
main()
|
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_auto_001_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()
|