PeterXie666 commited on
Commit
b7fdb4c
·
verified ·
1 Parent(s): 69db4e1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. leaf/final/episode_000038.npz +3 -0
  2. leaf/final/episode_000147_wrist_image.png +3 -0
  3. leaf/final/episode_000807_image.png +3 -0
  4. leaf/final/episode_000984.npz +3 -0
  5. leaf/final/episode_001385.npz +3 -0
  6. leaf/final/episode_001571.npz +3 -0
  7. leaf/final/episode_001575_image.png +3 -0
  8. leaf/final/episode_002015.npz +3 -0
  9. leaf/final/episode_002675.npz +3 -0
  10. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/README.md +297 -0
  11. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/__init__.py +1 -0
  12. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/audit_state.py +79 -0
  13. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/camera.py +100 -0
  14. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/context.py +377 -0
  15. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/cost.py +37 -0
  16. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/harness.py +300 -0
  17. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/images.py +47 -0
  18. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/metrics.py +97 -0
  19. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/replay.py +59 -0
  20. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/robot_server.py +966 -0
  21. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/runlog.py +62 -0
  22. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/tools.py +392 -0
  23. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/__init__.py +63 -0
  24. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/base.py +364 -0
  25. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/claude_code.py +514 -0
  26. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/codex.py +687 -0
  27. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/contract.py +160 -0
  28. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/dsh.py +403 -0
  29. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/embodied_evo.py +135 -0
  30. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
  31. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/framework_codex.py +542 -0
  32. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/jail.py +228 -0
  33. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins.py +40 -0
  34. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
  35. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/reference.py +143 -0
  36. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/rpent.py +530 -0
  37. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/sensenova.py +24 -0
  38. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/trajectory.py +86 -0
  39. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/DRIVER.md +144 -0
  40. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/__init__.py +10 -0
  41. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/driver_template.py +196 -0
  42. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/executor.py +138 -0
  43. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/fake_driver.py +152 -0
  44. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/protocol.py +364 -0
  45. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/session.py +346 -0
  46. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/tasks.py +123 -0
  47. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/tasks/__init__.py +0 -0
  48. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/tasks/l1_yaw.py +439 -0
  49. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_knock.py +457 -0
  50. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_restore_layout.py +502 -0
leaf/final/episode_000038.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8380feb97447b515527d6adb1a79fa98d749e77dc4e8cc4f7a6138440376b293
3
+ size 4046
leaf/final/episode_000147_wrist_image.png ADDED

Git LFS Details

  • SHA256: 01f04a3c2effac03f2e74a6afba35c7dd1117666162095cae0d5bf34b427783f
  • Pointer size: 130 Bytes
  • Size of remote file: 37.6 kB
leaf/final/episode_000807_image.png ADDED

Git LFS Details

  • SHA256: fa23bc8d3f8eed940b577fb4f6d9e5a716c107dc7a989321495c051d56751de1
  • Pointer size: 130 Bytes
  • Size of remote file: 56.1 kB
leaf/final/episode_000984.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07b0cb55e317f0f9277a9e4c6f8a1cc21a419a98996babc2ef13f48d0d5a740a
3
+ size 3838
leaf/final/episode_001385.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f9476b7ef70508a0bc2d42771ec1aba58ae76b1f2aa826f90b6a3fea7fc61cf1
3
+ size 3958
leaf/final/episode_001571.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aad6aa79a5ecf2e4e90a515ab6116f7bff86a69a5cb396b5c979915fbec41b42
3
+ size 3942
leaf/final/episode_001575_image.png ADDED

Git LFS Details

  • SHA256: a2b5fc9683946813c2210f5dcd267dc94dace21fad61190e44b4d40c995736cf
  • Pointer size: 130 Bytes
  • Size of remote file: 61.6 kB
leaf/final/episode_002015.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30243517296b8d04e295206e13f2a0ff1d6313a27687ddf6449f4a9133617f13
3
+ size 3630
leaf/final/episode_002675.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:850b9341a3b023a8f84a7abbd2565f92c345f4e3a653336e27bcd6e369a17754
3
+ size 3734
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/README.md ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LFF-Bench agent harness(`lffbench/agent/`)
2
+
3
+ 把 VLM 智能体(默认 GPT-6 Astra,经 OpenAI Responses API)接到 LFF-Bench 任务上:工具接口、观测与历史打包、
4
+ 记忆模式、反馈粒度、协议控制(cross / within)、日志与指标。对应设计文档 `docs/02-benchmark设计.md` §4、§5。
5
+
6
+ > 本文档里"实测"指在本机跑出来的结果;"假设 / 估计"是没验证过的,单独标出。
7
+
8
+ ## 1. 文件
9
+
10
+ | 文件 | 内容 |
11
+ |---|---|
12
+ | `tools.py` | 工具 JSON schema(`tool_specs`)和执行器 `ToolExecutor`(底层全部调 `Skills`) |
13
+ | `camera.py` | 相机内外参、深度反投影 `pixel_to_world`、`world_to_pixel`、图像方向说明(robosuite `camera_utils`) |
14
+ | `context.py` | 后端无关的对话结构、尝试记录 `AttemptRecord`、记忆选择 `select_history`、全部提示词文本 `PromptBuilder`、关键帧选择、旧图裁剪 |
15
+ | `harness.py` | 协议控制器 `AgentHarness` + `HarnessConfig` |
16
+ | `backends/openai_responses.py` | `OpenAIResponsesBackend`(GPT-6 Astra) |
17
+ | `backends/scripted.py` | `ScriptedBackend`:不调模型,把任务自带的 scripted 策略经工具接口跑一遍 |
18
+ | `backends/chat_completions.py` | `ChatCompletionsBackend`:OpenAI 兼容 Chat Completions(本地 Qwen3-VL 服务、vLLM 等) |
19
+ | `backends/anthropic_messages.py` | `AnthropicMessagesBackend`:Anthropic Messages API(自适应思考 + effort、思考块原样回放、自动缓存,2026-10-11) |
20
+ | `backends/gemini.py` | `GeminiBackend`:Gemini API(google-genai;thought_signature 原样回放,2026-10-11) |
21
+ | `../../scripts/api_player.py` / `api_batch.py` / `mcp_robot_server.py` | LA 接口的统一驱动、批处理调度、给原生 harness 的 MCP server(见 docs/12-统一harness.md) |
22
+ | `runlog.py` / `replay.py` | 运行目录写入;从运行目录重建尝试记录(给 mismatched 当 donor) |
23
+ | `metrics.py` / `cost.py` | succ@k、ΔICL、重复动作率;token 计价 |
24
+ | `../../scripts/run_agent.py` | 命令行入口 |
25
+ | `../../scripts/agent_compare.py` | 两个运行目录配对算 ΔICL(bootstrap 区间) |
26
+ | `../../scripts/agent_cost.py` | 从运行目录(真实或 dry run)估算 GPT-6 成本 / 延迟 |
27
+ | `../../tests/test_agent_*.py` | 单元测试 + 仿真端到端测试 |
28
+
29
+ ## 2. 快速开始
30
+
31
+ ```bash
32
+ cd <repo> && source run_env.sh && export OMP_NUM_THREADS=1
33
+ # 管线自检(不调模型;同时记录"如果换成 GPT-6,每次请求多大")
34
+ python scripts/run_agent.py --task l5_slide_to_target --backend scripted --memory full --feedback F2 --n 3 --k 5 --dry-run-payload
35
+ # GPT-6(需要 key;见 §6)
36
+ export OPENAI_API_KEY=... # 必需
37
+ export OPENAI_BASE_URL=... # 可选:走网关 / 代理时
38
+ python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory full --feedback F2 --n 20 --k 5 --seed0 5000
39
+ python scripts/run_agent.py --task l5_slide_to_target --backend openai --effort medium --memory none --feedback F2 --n 20 --k 5 --seed0 5000
40
+ python scripts/agent_compare.py --with runs/agent/l5_slide_to_target/<full 运行> --iid runs/agent/l5_slide_to_target/<none 运行>
41
+ # 测试
42
+ python -m pytest -q tests/test_agent_payload.py tests/test_agent_protocol.py # 无仿真,约 1–2 分钟(CPFS 上 import 慢)
43
+ python -m pytest -q tests/test_agent_sim.py # 仿真,含 n=3 端到端
44
+ ```
45
+
46
+ 常用开关:`--instruction direct|indirect`、`--privileged-locate`(消融:给 `locate`)、`--image-res 512`、
47
+ `--keyframes 4`、`--keyframe-res`、`--max-steps 30`(每次尝试的工具调用上限)、`--no-auto-obs`(只在 `get_observation` 时给图)、
48
+ `--grasp-report bool|name|none`、`--early-stop auto|yes|no`、`--donor-run DIR`(mismatched 的 donor)、`--seeds 5000,5001`。
49
+ 种子约定(我定的):1000–1999 开发(validate.py 也用 1000+),5000+ 留作正式测试。
50
+
51
+ ## 3. 工具接口
52
+
53
+ 坐标一律**世界系、米**(按本次任务要求;设计文档 §4 草稿写的是"机器人基座系",两者只差一个平移,这里统一用世界系,与 Skills 和各任务代码一致):桌面 z = 0.90,机器人基座在 x = −0.66, y = 0,+x 远离机器人,+y 机器人左侧,+z 向上。
54
+ 位置指夹爪抓取点(两指尖中点,`gripper0_grip_site`)。夹爪始终竖直向下;`yaw` 单位是**度**(LLM 处理度比弧度少出错),
55
+ yaw 0 时两指沿世界 y 轴开合(实测:手指 body 在 y = ±0.02),yaw 90 沿 x 轴。yaw 按 180° 取模:`Skills.move_to`(共享代码,
56
+ 2026-10-06 协调者改)会取与当前 yaw 最近、且 |yaw| ≤ 90°+0.4 rad(约 113°)的等价角,避免手腕绕 180° 把手臂卷进关节限位;
57
+ `move_to` 报告里的 `yaw_used_deg` 是实际用的角度。
58
+ 肘关节(`robot0_joint4`)上限从 Panda 原厂的 −0.07 rad 收紧到 −0.55(`envs.ELBOW_Q4_MAX`,2026-10-19):原来快速移动越过手臂伸到最远的姿态(约 −0.47)后,肘关节会弯到反方向,被上限挡住,之后的移动都停在离目标 4–17 cm 处。收紧后可达范围不变。
59
+ 方向词:harness 生成的文字里一律以机器人为参照,并在 system prompt 里定义——forward = +x、backward = −x、left = +y(机器人左手)、
60
+ right = −y、up = +z,"不是图像里的左右";同时说明 agentview 图里机器人的左边出现在图像右侧。任务自己的 F2 文本由任务作者统一。
61
+
62
+ | 工具 | 参数 | 底层 | 说明 |
63
+ |---|---|---|---|
64
+ | `move_to` | x, y, z, yaw, speed∣null | `Skills.move_to` | speed 为 null 时按控制器最快(约 0.6 m/s);yaw 按 180° 取模;超出工作空间的目标被裁剪并在报告里注明 |
65
+ | `open_gripper` / `close_gripper` | – | `Skills.set_gripper` | |
66
+ | `push` | x, y, dir_x, dir_y, distance, speed, z∣null, runup∣null | `Skills.push` | 语义与 `Skills.push` 完全一致:闭爪,到 (x,y) 后方 runup(默认 0.06)处、高度 z(默认 0.92),沿方向扫到 (x,y) 前方 distance 处,再抬 12 cm;朝向由 `Skills.push` 自动定 |
67
+ | `get_observation` | – | 渲染 | 返回 agentview + 腕部图像和本体状态 |
68
+ | `pixel_to_world` | camera(agentview∣wrist), u, v | 深度反投影 | u=列(从左数)、v=行(从上数),坐标就是模型看到的那张图(默认 512×512);返回世界点、离桌面高度、深度 |
69
+ | `done` | reason | – | 结束本次尝试(within 协议:结束一个分段,任务被检查) |
70
+ | `locate`(仅 `--privileged-locate`) | object_name(枚举) | 特权 | 物体原点的真实世界坐标 + 碰撞体 AABB;只用于"去掉感知难度"的消融 |
71
+
72
+ 所有工具 schema 都是 OpenAI strict 模式(所有字段 required、可选字段可为 null、禁止额外字段)。
73
+
74
+ **动作工具的执行报告**(JSON 文本,作为 function_call_output 返回):
75
+ ```json
76
+ {"ok": true, "tool": "move_to", "reached": true, "yaw_used_deg": 0.0, "eef_pos": [-0.418, 0.019, 0.920], "eef_yaw_deg": 0.5,
77
+ "gripper": "closed", "gripper_width_m": 0.001, "holding_object": false, "touched_object": false, "sim_time_s": 13.7}
78
+ ```
79
+ - `reached`:控制器是否到达(2 cm 内,`Skills` 的判据);`push` 给 `sweep_reached`。
80
+ - `holding_object` / `touched_object`:默认只给布尔(`--grasp-report bool`)——真实机器人能感知"夹住了东西 / 碰到了东西",
81
+ 但不知道是哪个物体;物体名会泄露识别类任务的答案。`--grasp-report name` 时给物体名(调试 / 消融)。
82
+ 接触在**每个 MuJoCo 子步**检查(包装 `env.sim.step`,一个控制步 = 25 子步):实测快推时手指与方块的接触不到一个控制步,只在控制步边界查会漏掉(l5 上推了 4.4 cm 却一次接触都没记到)。不碰 `Skills.recorder`,任务自己的注入钩子不受影响。
83
+ - 任务若定义 `drain_events()`(L6 有),其返回的事件文本会作为 `events` 加进当次报告(L6 作者的约定)。
84
+ - 参数错误、未知工具、JSON 解析失败都返回 `{"ok": false, "error": ...}`,占一步预算,不中断尝试。
85
+
86
+ **隐藏 bias(L1)怎么处理**:所有命令位置都经 `Skills`,bias 照常加上。本体状态按"机器人自己以为的位置"报告:
87
+ `eef_pos = 真实末端 − bias`。也就是说机器人认为自己准确到了指令点,只有相机能看出偏差——这就是标定误差的本义;
88
+ 如果报告真实末端,agent 对比指令和报告就能直接读出 bias,L1 就失效了。`pixel_to_world` 和 `locate` 给真实世界坐标。
89
+ (测试 `test_tool_reports_and_hidden_bias` 实测:bias (3, −2, 0) cm 时报告与指令差 < 1 cm,真实末端 = 指令 + bias。)
90
+ L1 任务作者在 `l1_bias.py` 的 `TrackedSkills.reported_eef_pos()` 里独立采用了同一约定,两边一致。
91
+
92
+ **`pixel_to_world` 精度(实测,l5 场景方块顶面中心,投影→反投影)**:agentview 512px 误差约 1.5 mm,256px 约 3.4 mm;
93
+ wrist 均 < 0.1 mm。图像方向(由外参算出并写进 system prompt):agentview 图右 = +y、图下 = +x(机器人在图上方);
94
+ wrist 在 yaw 0 时图右 = −y、图下 = −x。
95
+
96
+ ## 4. 观测、消息格式与历史打包
97
+
98
+ 请求由三部分组成,按缓存友好的顺序排列:
99
+ 1. **instructions(system)**:机器人 / 坐标 / 相机 / 工具约定、协议(k 次尝试、重置到同一状态)、反馈粒度说明、
100
+ "新尝试开始前先用 1–3 句话评估前几次尝试"(这句话就是"自报失败原因"的来源,记录为 `diagnosis`)。
101
+ 2. **历史项(user,非 live,不裁剪)**:`TASK: <指令>` + 前几次尝试的打包(按记忆模式选择)。
102
+ 3. **当前尝试(live)**:尝试编号 + 当前 agentview / wrist 图 + 本体状态;之后每一步:模型的 function_call →
103
+ function_call_output(执行报告)→ 新观测(两张图 + 本体状态)。
104
+
105
+ 每次尝试的打包(≤4 张关键帧 + 动作摘要 + 反馈)。下面是 scripted dry run 第 2 次尝试第 1 次调用的 `input`,原样摘自
106
+ `runs/agent/l5_slide_to_target/20261006-060757_scripted-adaptive_full_F2_e2e/requests/request_007.json`(图像以占位符代替,
107
+ `[BREAKPOINT]` 表示该内容块带 `prompt_cache_breakpoint`):
108
+ ```
109
+ == user(历史项,live=False)
110
+ TASK: Push the red cube once, straight away from the robot, so that it slides and comes to rest inside the green target zone.
111
+
112
+ === Your earlier attempts ===
113
+
114
+ --- Attempt 1 ---
115
+ Actions executed:
116
+ 1. close_gripper() -> eef (-0.208, 0.000, 1.173); width 0.002 m
117
+ 2. move_to(x=-0.419, y=0.021, z=1.02, yaw=0, speed=null) -> NOT reached; eef (-0.394, 0.023, 1.032)
118
+ 3. move_to(x=-0.419, y=0.021, z=0.92, yaw=0, speed=null) -> reached; eef (-0.418, 0.019, 0.920)
119
+ 4. move_to(x=-0.204, y=0.021, z=0.92, yaw=0, speed=0.3) -> reached; eef (-0.202, 0.021, 0.921); touched an object
120
+ 5. move_to(x=-0.204, y=0.021, z=1, yaw=0, speed=0.3) -> reached; eef (-0.205, 0.020, 0.997)
121
+ 6. done(reason="scripted adaptive policy finished with params {'speed': 0.3}")
122
+ Outcome feedback: Attempt failed. The cube stopped 5.2 cm past the centre of the target zone.
123
+ Key images (start of attempt, after step 1 (close_gripper), after step 4 (move_to), end of attempt, after objects settled):
124
+ [start of attempt] <image>
125
+ [after step 1 (close_gripper)] <image>
126
+ [after step 4 (move_to)] <image>
127
+ [end of attempt, after objects settled] <image>
128
+ === End of earlier attempts === [BREAKPOINT]
129
+ == user(当前尝试,live=True)
130
+ This is attempt 2 of at most 5. The scene has been reset.
131
+
132
+ Current observation:
133
+ agentview camera: <image>
134
+ wrist camera: <image>
135
+ Proprioception: {"eef_pos": [-0.2085, -0.0, 1.1733], "eef_yaw_deg": 0.0, "gripper": "open", "gripper_width_m": 0.0411, "holding_object": false} [BREAKPOINT]
136
+ ```
137
+ 之后每一步依次追加:模型输出项(reasoning(加密)/ message / function_call)→ `function_call_output`(执行报告 JSON)→
138
+ user 项 `Observation after step N (<tool>):` + 两张图 + 本体状态。完整请求(含 instructions 和 tools)见同目录 `requests/*.json`。
139
+ - 关键帧(agentview):尝试开始、最多 2 张中间帧(优先 push / 开合爪 / 碰到物体的步)、结束帧(`task.outcome()` 让物体静止之后渲染)。
140
+ - 反馈:`task.feedback(inst, outcome, level)`。F0 不给反馈行;F1 只有成功 / 失败;F2 加结构化测量(任务的 `detail`)。
141
+ - 历史头不带计数,所以第 j+1 次尝试的历史项以第 j 次的为前缀(只多一块),前缀可被缓存命中(单测 `test_history_prefix_is_append_only`)。
142
+ - live 图像超过 `max_live_images`(默认 16)时,把最旧的裁到预算的一半(滞回,减少前缀变化);历史关键帧从不裁剪。
143
+ - 一张图就是一个 JPEG(quality 90);发给模型的字节和 `images/` 下存的文件完全相同。
144
+
145
+ **记忆模式**(`--memory`):
146
+
147
+ | 模式 | 下一次尝试看到什么 | 用途 |
148
+ |---|---|---|
149
+ | `none` | 什么都没有;提示词里也不提"多次尝试",每次请求与第 1 次完全相同 | 独立重来,测 pass@k^iid |
150
+ | `full` | 之前全部尝试 | 主条件 |
151
+ | `last` | 只有最近一次 | 记忆长度消融 |
152
+ | `mismatched` | 另一个实例(不同布局和隐变量)的前 j−1 次尝试,措辞与 full 完全相同 | 错配对照:用的是具体信息还是"泛泛练习" |
153
+
154
+ mismatched 的 donor:`--donor-run DIR` 复用一个已跑完的 full 运行(按种子循环错位配对,保证 donor ≠ 自己;不用再付一次钱);
155
+ 不给时自动用同一后端、memory=full 在 `seed + 10000` 上先跑一遍 donor(存到运行目录下 `donors/`)。
156
+
157
+ **早停与 F0**:默认(`--early-stop auto`)F1/F2 在首次成功时结束 run;F0 不早停、跑满 k 次——否则"还有下一次尝试"本身就泄露了"上次失败"。
158
+
159
+ **协议**:`cross` 每次尝试前 `reset_instance`(同布局、同隐变量)。`within` 只在开始重置一次;`done` 结束一个分段:
160
+ (若任务定义 `go_home()` 先调用它,L6 有)→ 保持 20 个控制步 → `outcome()`;未成功且未到终止条件(`outcome["terminal"]` 或
161
+ `outcome["overshoot"]`,或任务的 `is_terminal(out)`)就带着反馈从当前状态继续。within 下各记忆模式的语义同上(none = 每段都清空上下文)。
162
+
163
+ ## 5. 后端
164
+
165
+ - **`OpenAIResponsesBackend`**(`--backend openai`):`client.responses.create(model="gpt-6-astra", instructions, input, tools,
166
+ tool_choice="auto", parallel_tool_calls=False, store=False, include=["reasoning.encrypted_content"], reasoning={"effort": ...})`。
167
+ - 无状态:每次请求重发完整(裁剪后的)上下文;上一轮返回的 reasoning 项(加密内容)原样回放,模型在一次尝试内保留思路。
168
+ - effort 校验:gpt-6-astra 只接受 low / medium / high / xhigh / max(不支持 none)。
169
+ - 缓存:自动把 `prompt_cache_key` 设为 `lffbench:<task>:<seed>`;默认在"历史项末尾"和"最新输入末尾"打显式
170
+ `prompt_cache_breakpoint`(openai SDK 3.24 的字段,gpt-5.6 以后支持)。网关不认这个字段时用 `--cache-breakpoints none`。
171
+ `--prompt-cache-options '{"ttl":"30m"}'`、`--prompt-cache-retention 24h`、`--service-tier`、`--extra-body` 透传。
172
+ - 用量:记录 input / cached / cache_write / output / reasoning tokens 和每次调用的墙钟延迟。
173
+ - **`ScriptedBackend`**(`--backend scripted --scripted-policy adaptive|naive|oracle|blind`):任务自己的 `execute(inst, params)`
174
+ 在工作线程里跑,`task.sk` 换成代理,每个 `Skills` 原语变成一次 schema 合法的工具调用交给 harness 在主线程执行
175
+ (队列交接,同一时刻只有一个线程碰 MuJoCo)。参数来自任务的 `default/adapt/blind/oracle_params`,只看记忆模式允许的历史、
176
+ 只看反馈粒度允许的字段(F2 结构化测量 / F1 成功标志 / F0 无;看不够就退回 blind 规则)。它读实例布局(特权),只用来测管线。
177
+ 支持实现了 `execute` 的 cross 任务;within 任务和只重写了 `run_scripted` 的任务不支持(会报错说明)。
178
+ - **`ChatCompletionsBackend`**(`--backend chat --chat-base-url http://127.0.0.1:8765/v1 --chat-model ...`):OpenAI 兼容
179
+ Chat Completions + function calling,用于本地开源 VLM(见 §8)或任何 vLLM / SGLang 端点。live 图像上限降到 4。
180
+
181
+ ## 6. 怎么接 GPT-6(需要用户提供)
182
+
183
+ 1. `OPENAI_API_KEY`(必需),可选 `OPENAI_BASE_URL`(网关 / 代理)。本机没有 key,代码从未发过真实请求。
184
+ 2. 账号对 `gpt-6-astra` 的访问权限和 Tier(Tier 1 限额 500 RPM / 500K TPM;单个 run 串行,每次调用 ≤ 几十 K token,Tier 1 够用)。
185
+ 3. Python 包:`setup/install.sh` 建的 venv 里直接装了 `openai==3.24.0`。(原开发机的 libero-cpu venv 没有 `openai`,
186
+ 它装在一个 `pip install --target` 目录里,由环境变量 `LFF_OPENAI_SDK_DIR` 指定;后端在 `import openai` 失败时把该目录
187
+ **追加**到 `sys.path` 末尾,venv 里已有的包始终优先。)
188
+ 4. 第一次真跑建议:`--n 2 --k 3 --effort low --dump-requests 5`,看 `requests/*.json`(图像已省略)和 `events.jsonl` 里的
189
+ `llm_call.usage`,确认网关接受 `prompt_cache_breakpoint` / `include` 等字段后再放大。
190
+ 5. 并行:一个进程一个 MuJoCo 环境、串行跑实例;要并行就按 `--seeds` 切分开多个进程(每个进程 `OMP_NUM_THREADS=1`)。
191
+ 6. 代理(实测):本机环境变量里有 `HTTPS_PROXY=http://127.0.0.1:1080` 和 `ALL_PROXY=socks5h://127.0.0.1:1080`。openai SDK 3.x
192
+ 底层的 httpx2 只要看到 socks 代理变量就要 `socksio`,否则建客户端时直接 ImportError;我已把 `socksio==1.0.0` 装进同一目录,
193
+ 现在在这些变量存在时能正常建客户端(实测)。真实请求会走 `HTTPS_PROXY`;能否经这个代理到达 OpenAI / 你的网关没测(没有 key)。
194
+
195
+ ## 7. 日志与指标
196
+
197
+ 运行目录 `runs/agent/<task>/<时间>_<backend>_<memory>_<feedback>[_tag]/`:
198
+ - `config.json`:命令行、harness 配置、后端配置、任务信息。
199
+ - `events.jsonl`:`run_start`(实例参数,去掉 `_` 开头的私有键)、`llm_call`(延迟、usage、成本估计、模型文本、reasoning 摘要、
200
+ 工具调用、请求大小;dry run 时加 `dry_run_request`)、`tool_call`(参数、报告、仿真墙钟、仿真步数)、`observation`(图像路径、本体)、
201
+ `attempt_end`(outcome 全字段、给模型看的反馈、F2 反馈、结束原因、done 理由、自我诊断、显示了哪些历史、关键帧路径、动作摘要、
202
+ 该尝试的 LLM 延迟和仿真时间)、`run_end`(run 级汇总)、`llm_error`。
203
+ - `images/seed<s>/a<attempt>_s<step>_<n>_<cam>.jpg`:模型看到的每一张图。
204
+ - `summary.json`:每个 run 的 `first_success`、`success_by_attempt`、残差(outcome 里所有 `*_err`)、token、成本、延迟;以及汇总:
205
+ `succ_at`(j = 1..k,按 run 计)+ Wilson 95% 区间、`attempt1_success`、首次成功尝试数均值 / 中位数、
206
+ `pass_at_k_iid_analytic = 1 − (1 − p1)^k`、`repeated_action_rate`(失败后下一次动作序列与上次相同(1 cm 取整)的比例,
207
+ "同错复犯"的通用近似)、每 run 调用数 / 延迟 / token / 成本、缓存命中率。
208
+ - ΔICL:正式算法是同种子配对的 `succ@k(full) − succ@k(none)`(`scripts/agent_compare.py`,配对 bootstrap 区间、不一致对计数);
209
+ `delta_icl_vs_analytic_iid` 只是用本组 attempt-1 成功率算的便宜参照。
210
+
211
+ ## 8. 成本 / 延迟估算方法
212
+
213
+ - 真实运行:成本 = Σ调用 [(input − cached − cache_write)·$10 + cache_write·$12.5 + cached·$1 + output·$50] / 1e6
214
+ (gpt-6-astra 价格,>272K 输入时输入 ×2、输出 ×1.5;见 `cost.py`);延迟直接用记录的每次调用墙钟。`scripts/agent_cost.py <运行目录>`。
215
+ - 跑之前:用 scripted 后端加 `--dry-run-payload` 跑同一配置,记录每次��用如果发给 GPT-6 的请求大小,再
216
+ `scripts/agent_cost.py <dry run 目录> --out-tokens 1500 --latency 20 --calls-scale 2` 外推。假设(未验证):图像按 32px patch
217
+ 每 patch 1 token 计(512² ≈ 256 token);文本 4 字符 ≈ 1 token;同一尝试内上一调用的输入全部命中缓存、每次尝试第一调用全不命中(偏保守);
218
+ scripted 的调用次数是 LLM 的下限(LLM 还会看图、反投影、检查),用 `--calls-scale` 放大;每次调用输出 token 和延迟按参数给
219
+ (RoboICL 实测 GPT-6 Astra 每次调用 30–50 s,那是 50–90K 输入、high/xhigh 时的数)。
220
+ - 本机 dry run 实测数字见 §10。
221
+
222
+ ## 9. 已知限制
223
+
224
+ - **l5_slide_to_target 的绿色目标区在图像里看不见(实测,任务侧问题,未改任务文件)**:`apply_instance` 把 zone 的碰撞关掉了,
225
+ 但它是 free joint,`settle` 期间直接穿过桌面掉下去(reset 后 z ≈ 0.81),agentview 和腕部图里都没有绿色区域。
226
+ scripted 测试不受影响(它只看 F2 数字),但 VLM 智能体只能靠 F2 的文字找目标——F0/F1 条件下这个任务对 VLM 不可解。
227
+ 需要任务作者把 zone 固定住(例如不加 free joint、或每步把它放回 / 设 gravcomp / 设为 mocap)。
228
+ - l5 的 scripted 执行里第一个 `move_to`(到推杆起点上方 x≈−0.42, z≈1.02)每次都跑满 250 步(12.5 s 仿真)仍差约 2.5 cm 报 `NOT reached`,
229
+ 下一步下降时又到位了;这是 `Skills.move_to` 在靠近基座处的行为,不是 harness 的问题,但 VLM 会在报告里看到 `NOT reached`。
230
+ - 渲染:每步两张 512² 图(OSMesa CPU)约 0.5 s;本机负载高时更慢。仿真时间对比 LLM 延迟可以忽略。
231
+ - 一个 run 内串行调用模型;没有实现 async tool calling / mid-turn steering / WebSocket(Ultrafast 推荐)。
232
+ - 没有实现"每次尝试后单独问一次模型失败原因"(会多一次调用);自报原因来自每次新尝试开头的那 1–3 句(`diagnosis`)。
233
+ - `ScriptedBackend` 不支持 within 协议任务(L2 / L3-within / L5-B / L6 的 scripted 参照写在各自的 `run_scripted` 里,
234
+ 不是 `execute(params)`);within 协议逻辑用假任务做了单测。
235
+ - 工具里没有 `wait`;scripted 代理遇到 `Skills.hold` 直接执行并计数(`backend_meta.untooled_hold_steps`)。
236
+ - 图像 token 的计法、GPT-6 每次调用的延迟都是假设,第一次真跑后用 `usage` 和 `latency_s` 校准。
237
+ - 本地开源 VLM 后端:见 §11。
238
+
239
+ **任务作者可选的钩子**(harness 会自动使用,没有就跳过):`agent_instruction(inst, variant)`、`agent_object_names`、
240
+ `on_agent_tool(inst, name, args, report)`(每次工具调用后,可用于注入)、`drain_events()`(事件文本进报告)、
241
+ `go_home()`(每次尝试结束、测 outcome 之前调用)、`is_terminal(out)` 或 `outcome["terminal"]`(within 不可恢复失败)、
242
+ `feedback(..., indirect=bool)`(按指令写法改写反馈)。
243
+
244
+ ## 10. 测试与实测结果(2026-10-06,本机实测,8 核负载 30–40)
245
+
246
+ 单元测试(`source run_env.sh` 后 `python -m pytest -q tests/test_agent_*.py`):
247
+ - `test_agent_payload.py` 6 项通过:请求结构、strict 工具、图像 data URL 能解码成 512² JPEG、缓存断点位置、effort 校验、
248
+ 无 key 报错;**真实 openai SDK 3.24 + 进程内 mock HTTP 传输**的两轮往返(URL `…/v1/responses`、`Bearer` 头、body、usage
249
+ 解析含 cache_write、reasoning 加密项回放、function_call / function_call_output 的 call_id 配对);chat 后端消息格式。
250
+ - `test_agent_protocol.py` 9 项通过(假任务、无仿真):full / none / last / mismatched、F0 / F1 / F2、F0 不早停、within 不重置、
251
+ 历史前缀只追加、关键帧选择、配对 ΔICL。
252
+ - `test_agent_sim.py` 5 项通过(单独 143 s;协调者改了 `Skills.move_to` 的 yaw 取模之后,三个文件 20 项一起重跑,305 s,全部通过):像素↔世界往返、bias 隐藏、工具报错 / 裁剪 / locate 门控 / 接触检测、
253
+ **ScriptedBackend 在 l5_slide_to_target 上 n=3、k=5 端到端**、mismatched 自动 donor。
254
+
255
+ 端到端运行(留在 `runs/agent/l5_slide_to_target/` 下,可以直接看图和 events):
256
+
257
+ | 运行 | succ@1..5 | 首次成功(seed 1000/1001/1002) | 每 run 调用数 | 每 run 仿真 + 渲染墙钟 |
258
+ |---|---|---|---|---|
259
+ | `20261006-060757_scripted-adaptive_full_F2_e2e` | 0.33 / 0.67 / 1 / 1 / 1 | 3 / 2 / 1 | 12 | 15.5 s |
260
+ | `20261006-060913_scripted-adaptive_none_F2_e2e` | 0.33 / 0.33 / 0.33 / 0.33 / 0.33 | – / – / 1 | 22 | 16.2 s |
261
+
262
+ - 经工具接口跑的 scripted adaptive 与任务自己的参照 rollout(`results/l5_slide_to_target/validate.json`)**逐次一致**:
263
+ 8 次尝试的推速完全相同,停止误差 along_err 相同到 0.1 mm(如 seed 1000:+5.22 / −1.14 / −0.49 cm)。说明工具接口足以表达
264
+ 这个任务的参照策略,bias / 物理没有被 harness 改变。
265
+ - memory=none 时 scripted 策略每次都用默认推速,结果完全重复(`repeated_action_rate` = 1.0),正好是"独立重来"的退化情形;
266
+ `agent_compare.py` 给出 ΔICL = 1.0 − 0.33 = 0.67(n=3,bootstrap 区间 [0, 1],只是管线演示)。
267
+ - dry run 请求大小(`agent_cost.py`):每次调用约 4.7K 输入 token(估计:文本 /4 + 每张 512² 图 256 token),同一尝试内
268
+ 约 78% 可命中缓存;第 2 次尝试首个请求 6 张图(4 关键帧 + 2 实时),到尝试末尾约 16 张。
269
+ 估计成本(gpt-6-astra 价格,**输出 token 和延迟是假设**):每次调用输出 1500 token、20 s 时,每 run 约 $1.1、API 时间约 4 分钟;
270
+ 按 LLM 调用数是 scripted 的 2 倍算,约 $2.1 / run、8 分钟;输出 4000 token、40 s 时约 $5.1 / run、16 分钟。
271
+ 成本主要在输出(reasoning)token,不在图像。一组条件 20 个实例 ≈ $40–100;ΔICL 至少要 full + none 两组。
272
+
273
+ 另外用 scripted 后端在 **l1_bias_place**(别人刚写的 L1 任务,cross 协议)上跑了 n=2、k=5 的兼容性检查(运行目录在 scratch,未保留):
274
+ 两个种子都在第 2 次尝试成功(第 1 次 F2 反馈"夹爪在奶酪中心右侧 3.9 cm、后方 1.4 cm",adaptive 据此补偿 offset),
275
+ 0 个错误——harness 不需要为 L1 做任何改动;L1 作者的 `TrackedSkills` 记录、bias 都经工具调用照常生效。
276
+
277
+ ## 11. 本地开源 VLM 后端(Qwen3-VL-8B-Instruct,PPU)
278
+
279
+ 能跑(实测)。由子代理在约 1 小时内做通:`scripts/qwen_vl_server.py` + `scripts/qwen_vl_server.sh`(OpenAI 兼容
280
+ `/v1/chat/completions`,支持工具调用 / 多图 / 多轮),用系统 python3.12(torch 2.6 PPU 版)+ 单独目录
281
+ `/mnt/cpfs/workspace/env/qwen3vl-ppu-overlay`(只放 transformers 4.57.6 / tokenizers 0.22.1 / huggingface_hub 0.36.0,
282
+ 只对服务进程加 PYTHONPATH,不改任何已有环境)。PPU 上 SDPA 自带 GQA 在解码步会报错,服务里改成先展开 K/V 头再算(`--sdpa-native-gqa` 可恢复)。
283
+
284
+ ```bash
285
+ nohup bash scripts/qwen_vl_server.sh --port 8765 --warmup > logs/qwen_vl_server.log 2>&1 & # 等日志出现 "serving ..."
286
+ python scripts/run_agent.py --task l5_slide_to_target --backend chat --chat-base-url http://127.0.0.1:8765/v1 \
287
+ --chat-model Qwen3-VL-8B-Instruct --memory full --feedback F2 --n 2 --k 3 --max-steps 15 --keyframes 3
288
+ kill <服务 PID> # 用完停掉,显存约 18 GB
289
+ ```
290
+ - 加载:页缓存热时权重 18 s(本次实测);冷读 CPFS 约 6.5 分钟(子代理实测 385 s)。
291
+ - 端到端实测(`runs/agent/l5_slide_to_target/20261006-061100_chat_full_F2_qwen_smoke`,n=2、k=3、每次尝试 15 步上限):
292
+ 81 次模型调用、0 次后端错误、0 次格式错误的工具调用;每次调用延迟均值 5.1 s(p50 4.9 s,p95 9.5 s),
293
+ 输入均值 6.3K token(最大 10.3K),输出均值 113 token;用到了 move_to / push / close_gripper / get_observation / pixel_to_world / done,
294
+ 新尝试开头都写了对上一次的评估(`diagnosis`)。成功 0/2:模型反复 `move_to(0, 0, 0.9)`、没有先定位方块,
295
+ 加上 l5 的目标区本来就看不见(§9)。这只说明**管线对真实 VLM 是通的**,不说明 8B 模型的能力;之后我在 system prompt 里加了
296
+ "物体位置不会直接给出,用 pixel_to_world 从图像定位"一句(这次运行之后加的,未再测)。
297
+ - 用途:在花 GPT-6 的钱之前,先用本地模型检查提示词、工具描述、日志和指标。
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """LFF-Bench agent harness: tool interface, context packing, model backends, protocol runner."""
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/audit_state.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Host-only, read-only physical evidence for CS/IR review (opt-in).
2
+
3
+ Never call outcome(), forward(), step() or a task measurement here: those can
4
+ settle physics or consume event cursors. Samples are at control-step boundaries,
5
+ not every MuJoCo substep. No sample itself is an error or repair classification.
6
+ """
7
+ import json
8
+
9
+
10
+ def _json_value(value):
11
+ if hasattr(value, "tolist"):
12
+ return value.tolist()
13
+ raise TypeError(f"Unsupported audit value: {type(value).__name__}")
14
+
15
+
16
+ class AuditStateRecorder:
17
+ def __init__(self, path):
18
+ self.path = path
19
+ self.env = None
20
+ self.original_step = None
21
+ self.wrapped_step = None
22
+ self.sequence = 0
23
+
24
+ def write(self, record):
25
+ # A separate host-side file, never copied into the agent's sandbox.
26
+ with open(self.path, "a", encoding="utf-8") as stream:
27
+ stream.write(json.dumps(record, separators=(",", ":"), default=_json_value) + "\n")
28
+
29
+ def detach(self):
30
+ if self.env is not None and self.env.step is self.wrapped_step:
31
+ self.env.step = self.original_step
32
+ self.env = None
33
+
34
+ def attach(self, env, attempt, command_step):
35
+ self.detach()
36
+ self.env, self.attempt, self.command_step = env, attempt, command_step
37
+ self.original_step = env.step
38
+ original_step = self.original_step
39
+ model = env.sim.model
40
+ self.write(dict(kind="attempt_start", schema="lff-audit-state-1", attempt=attempt,
41
+ sampling="after_env_step", bodies=[model.body_id2name(i) for i in range(model.nbody)],
42
+ geoms=[model.geom_id2name(i) for i in range(model.ngeom)]))
43
+
44
+ def wrapped(action):
45
+ result = original_step(action)
46
+ if self.env is env and self.wrapped_step is wrapped:
47
+ self.sample("control_step")
48
+ return result
49
+
50
+ self.wrapped_step = wrapped
51
+ env.step = wrapped
52
+ self.sample("initial")
53
+
54
+ def sample(self, phase):
55
+ data = self.env.sim.data
56
+ self.sequence += 1
57
+ self.write(dict(kind="state", sequence=self.sequence, attempt=self.attempt,
58
+ command_step=self.command_step(), phase=phase, sim_time=float(data.time),
59
+ qpos=data.qpos.tolist(), qvel=data.qvel.tolist(),
60
+ body_xyz=data.body_xpos.tolist(), body_quat_wxyz=data.body_xquat.tolist(),
61
+ contacts=[[int(c.geom1), int(c.geom2), float(c.dist)]
62
+ for c in data.contact[:data.ncon]]))
63
+
64
+ def boundary(self, task, phase):
65
+ """Capture after skill callbacks too (some injections happen after env.step).
66
+
67
+ Copy existing event lists without calling monitor/outcome methods or
68
+ advancing their cursors. These are raw observations, not adjudications.
69
+ """
70
+ self.sample(phase)
71
+ streams = {}
72
+ for name, obj in (("task", task), ("skills", getattr(task, "sk", None)),
73
+ ("monitor", getattr(task, "mon", None))):
74
+ attrs = obj if isinstance(obj, dict) else getattr(obj, "__dict__", {})
75
+ for key in ("events", "turns", "strikes", "box_moves", "lifts", "grasp_tries"):
76
+ if isinstance(attrs.get(key), list):
77
+ streams[f"{name}.{key}"] = attrs[key]
78
+ self.write(dict(kind="event_snapshot", attempt=self.attempt,
79
+ command_step=self.command_step(), phase=phase, streams=streams))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/camera.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Camera geometry for the agent tools: pixel -> world back-projection with the rendered depth map.
2
+
3
+ Conventions (match the images the agent receives, i.e. `envs.render`, which flips MuJoCo's
4
+ bottom-up buffer to an upright image):
5
+ u = column index (0 = left edge), v = row index (0 = top edge), both in pixels of a res x res image.
6
+ Intrinsics / extrinsics / depth linearisation come from robosuite.utils.camera_utils.
7
+ """
8
+ import numpy as np
9
+ from robosuite.utils import camera_utils as CU
10
+
11
+ from .. import envs
12
+
13
+ # agent-facing camera name -> MuJoCo camera name
14
+ CAMERAS = {"agentview": "agentview", "wrist": "robot0_eye_in_hand"}
15
+
16
+
17
+ def mj_cam(name):
18
+ if name in CAMERAS:
19
+ return CAMERAS[name]
20
+ if name in CAMERAS.values():
21
+ return name
22
+ raise KeyError(f"unknown camera {name!r}; use one of {sorted(CAMERAS)}")
23
+
24
+
25
+ def intrinsics(env, cam, res):
26
+ return CU.get_camera_intrinsic_matrix(env.sim, mj_cam(cam), res, res)
27
+
28
+
29
+ def cam_to_world(env, cam):
30
+ """4x4 pose of the camera in the world, OpenCV axes (x right, y down, z forward)."""
31
+ return CU.get_camera_extrinsic_matrix(env.sim, mj_cam(cam))
32
+
33
+
34
+ def render_depth(env, cam, res):
35
+ """Metric depth (distance along the optical axis, metres), upright (res, res)."""
36
+ _, d = envs.render(env, mj_cam(cam), res, depth=True)
37
+ return CU.get_real_depth_map(env.sim, np.clip(d, 0.0, 1.0))
38
+
39
+
40
+ def world_to_pixel(env, cam, xyz, res):
41
+ """Project a world point; returns (u, v) floats (u = column, v = row) and the depth."""
42
+ K = intrinsics(env, cam, res)
43
+ T = np.linalg.inv(cam_to_world(env, cam))
44
+ p = T @ np.append(np.asarray(xyz, float), 1.0)
45
+ uvw = K @ p[:3]
46
+ return float(uvw[0] / uvw[2]), float(uvw[1] / uvw[2]), float(p[2])
47
+
48
+
49
+ def pixel_ray(env, cam, u, v, res):
50
+ """Unit ray direction (world) through pixel (u, v) and the camera origin."""
51
+ K = intrinsics(env, cam, res)
52
+ E = cam_to_world(env, cam)
53
+ d_cam = np.array([(u - K[0, 2]) / K[0, 0], (v - K[1, 2]) / K[1, 1], 1.0])
54
+ d = E[:3, :3] @ d_cam
55
+ return E[:3, 3].copy(), d / np.linalg.norm(d)
56
+
57
+
58
+ def pixel_to_world(env, cam, u, v, res, depth=None):
59
+ """Back-project pixel (u, v) of a res x res image using the depth map. Returns a dict."""
60
+ if depth is None:
61
+ depth = render_depth(env, cam, res)
62
+ iu, iv = int(round(u)), int(round(v))
63
+ if not (0 <= iu < res and 0 <= iv < res):
64
+ raise ValueError(f"pixel ({u}, {v}) outside the {res}x{res} image")
65
+ z = float(depth[iv, iu])
66
+ K = intrinsics(env, cam, res)
67
+ E = cam_to_world(env, cam)
68
+ p_cam = np.array([(u - K[0, 2]) * z / K[0, 0], (v - K[1, 2]) * z / K[1, 1], z, 1.0])
69
+ p = E @ p_cam
70
+ far = env.sim.model.vis.map.zfar * env.sim.model.stat.extent
71
+ return dict(xyz=p[:3], depth=z, valid=bool(z < 0.98 * far))
72
+
73
+
74
+ def image_axes(env, cam, res, plane_z=envs.TABLE_Z):
75
+ """World directions of image-right and image-down at the image centre, projected onto the table
76
+ plane (for describing the camera to the agent). Returns two unit 2-vectors (x, y)."""
77
+ o, d = pixel_ray(env, cam, res / 2, res / 2, res)
78
+ if abs(d[2]) < 1e-6:
79
+ return None
80
+ t = (plane_z - o[2]) / d[2]
81
+ c = o + t * d
82
+ out = []
83
+ for du, dv in ((8, 0), (0, 8)):
84
+ o2, d2 = pixel_ray(env, cam, res / 2 + du, res / 2 + dv, res)
85
+ t2 = (plane_z - o2[2]) / d2[2]
86
+ w = (o2 + t2 * d2 - c)[:2]
87
+ out.append(w / max(np.linalg.norm(w), 1e-9))
88
+ return out
89
+
90
+
91
+ def describe_axes(env, cam, res):
92
+ """Human-readable mapping 'image right ~ +y, image down ~ +x' (dominant axis, sign)."""
93
+ ax = image_axes(env, cam, res)
94
+ if ax is None:
95
+ return None
96
+ names = []
97
+ for w in ax:
98
+ i = int(np.argmax(np.abs(w)))
99
+ names.append(("+" if w[i] > 0 else "-") + "xy"[i])
100
+ return dict(right=names[0], down=names[1])
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/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_20261103_sonnet/lff/source_closure/lffbench/agent/cost.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Token / cost accounting.
2
+
3
+ Prices (USD per 1M tokens) for gpt-6-astra from the OpenAI model page as recorded in
4
+ research_notes/.../seed_papers.md Q8 (2026-10): input 10, cached input 1, cache write 12.5, output 50;
5
+ prompts > 272K input tokens are billed 2x input/cached and 1.5x output. usage.input_tokens_details has
6
+ cached_tokens and (openai SDK >= 3.x) cache_write_tokens; both are priced separately when present.
7
+ Reasoning tokens are billed as output tokens (they are included in output_tokens).
8
+ """
9
+ import math
10
+
11
+ PRICES = {
12
+ "gpt-6-astra": dict(input=10.0, cached=1.0, cache_write=12.5, output=50.0, long_threshold=272_000, long_in=2.0, long_out=1.5),
13
+ }
14
+
15
+
16
+ def call_cost(usage, model="gpt-6-astra"):
17
+ p = PRICES.get(model)
18
+ if p is None or not usage:
19
+ return None
20
+ inp = usage.get("input_tokens", 0) or 0
21
+ cached = usage.get("cached_tokens", 0) or 0
22
+ write = usage.get("cache_write_tokens", 0) or 0 # reported by newer SDKs / API versions
23
+ out = usage.get("output_tokens", 0) or 0
24
+ li, lo = (p["long_in"], p["long_out"]) if inp > p["long_threshold"] else (1.0, 1.0)
25
+ plain = max(inp - cached - write, 0)
26
+ return ((plain * p["input"] + write * p["cache_write"] + cached * p["cached"]) * li + out * p["output"] * lo) / 1e6
27
+
28
+
29
+ def image_tokens(w, h, patch=32, per_patch=1.0, overhead=0):
30
+ """ASSUMPTION (not verified for gpt-6-astra): patch-based image accounting as for the GPT-5 family,
31
+ one token per 32x32 patch (~256 tokens for 512x512). Real numbers come from response.usage."""
32
+ return int(math.ceil(w / patch) * math.ceil(h / patch) * per_patch + overhead)
33
+
34
+
35
+ def estimate_request_tokens(stats, image_res=512):
36
+ """Rough input-token estimate of one request from OpenAIResponsesBackend.request_stats()."""
37
+ return int(stats.get("text_chars", 0) / 4 + stats.get("n_images", 0) * image_tokens(image_res, image_res))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/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/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/images.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Image references and encoding (JPEG bytes are what the model sees and what is saved to disk)."""
2
+ import base64
3
+ import io
4
+ from dataclasses import dataclass
5
+ from typing import Any, Optional
6
+
7
+ import numpy as np
8
+
9
+
10
+ @dataclass
11
+ class ImageRef:
12
+ camera: str # agent-facing camera name ("agentview" / "wrist")
13
+ array: Any = None # uint8 HxWx3
14
+ label: str = ""
15
+ path: Optional[str] = None # where the encoded image was saved
16
+ jpeg: Optional[bytes] = None # encoded bytes actually sent to the model
17
+
18
+ def encoded(self, quality=90):
19
+ if self.jpeg is None:
20
+ if self.array is None and self.path:
21
+ with open(self.path, "rb") as f:
22
+ self.jpeg = f.read()
23
+ else:
24
+ self.jpeg = encode_jpeg(self.array, quality)
25
+ return self.jpeg
26
+
27
+ def data_url(self, quality=90):
28
+ return "data:image/jpeg;base64," + base64.b64encode(self.encoded(quality)).decode("ascii")
29
+
30
+ @property
31
+ def size(self):
32
+ return None if self.array is None else tuple(np.asarray(self.array).shape[:2])
33
+
34
+
35
+ def encode_jpeg(arr, quality=90):
36
+ from PIL import Image
37
+ buf = io.BytesIO()
38
+ Image.fromarray(np.asarray(arr, dtype=np.uint8)).save(buf, format="JPEG", quality=int(quality))
39
+ return buf.getvalue()
40
+
41
+
42
+ def resize(arr, res):
43
+ from PIL import Image
44
+ arr = np.asarray(arr, dtype=np.uint8)
45
+ if arr.shape[0] == res and arr.shape[1] == res:
46
+ return arr
47
+ return np.asarray(Image.fromarray(arr).resize((res, res), Image.BILINEAR))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/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/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/replay.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rebuild AttemptRecords from a finished run directory (events.jsonl + images/), e.g. to use a full-memory
2
+ run as the donor pool of a mismatched-memory run without re-running (and re-paying for) it."""
3
+ import json
4
+ import os
5
+
6
+ from .context import AttemptRecord, StepRecord
7
+ from .images import ImageRef
8
+
9
+
10
+ def load_events(run_dir):
11
+ with open(os.path.join(run_dir, "events.jsonl")) as f:
12
+ return [json.loads(line) for line in f if line.strip()]
13
+
14
+
15
+ def load_records(run_dir, task=None, feedback="F2"):
16
+ """{seed: [AttemptRecord]} with keyframes loaded from disk. Feedback text is re-rendered at the
17
+ requested level with task.feedback() when a task is given (else the logged F2 text / '')."""
18
+ ev = load_events(run_dir)
19
+ insts, steps, out = {}, {}, {}
20
+ for e in ev:
21
+ t = e["type"]
22
+ if t == "run_start":
23
+ insts[e["seed"]] = e["inst"]
24
+ out[e["seed"]] = []
25
+ elif t == "tool_call":
26
+ steps.setdefault((e["seed"], e["attempt"]), []).append(
27
+ StepRecord(step=e["step"], name=e["name"], args=e["args"], report=e["report"], ok=e["ok"]))
28
+ elif t == "attempt_end":
29
+ seed, a = e["seed"], e["attempt"]
30
+ kfs = []
31
+ for cap, rel in e.get("keyframes") or []:
32
+ p = os.path.join(run_dir, rel)
33
+ with open(p, "rb") as f:
34
+ kfs.append((cap, ImageRef(camera="agentview", path=p, jpeg=f.read())))
35
+ o = e["outcome"]
36
+ if task is not None:
37
+ fb = task.feedback(insts.get(seed, {}), o, feedback)
38
+ else:
39
+ fb = {"F0": "", "F1": "Attempt succeeded." if e["success"] else "Attempt failed."}.get(
40
+ feedback, e.get("feedback_f2", ""))
41
+ out.setdefault(seed, []).append(AttemptRecord(
42
+ seed=seed, attempt=a, steps=steps.get((seed, a), []), keyframes=kfs, outcome=o,
43
+ success=bool(e["success"]), feedback=fb, done_reason=e.get("done_reason"),
44
+ diagnosis=e.get("diagnosis"), ended_by=e.get("ended_by", ""), backend_meta=e.get("backend_meta") or {}))
45
+ return out
46
+
47
+
48
+ def derange(target_seeds, donor_seeds):
49
+ """Map each target seed to a donor seed != itself (cyclic shift over the sorted donor pool)."""
50
+ pool = sorted(donor_seeds)
51
+ if not pool:
52
+ raise ValueError("empty donor pool")
53
+ m = {}
54
+ for i, s in enumerate(sorted(target_seeds)):
55
+ j = (pool.index(s) + 1) % len(pool) if s in pool else i % len(pool)
56
+ if pool[j] == s:
57
+ raise ValueError(f"cannot find a donor different from seed {s} (pool {pool})")
58
+ m[s] = pool[j]
59
+ return m
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/agent/robot_server.py ADDED
@@ -0,0 +1,966 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Robot server for driving an LFF-Bench task from an isolated agent (e.g. a Claude Code subagent).
2
+
3
+ The server owns the simulator, the task instance and its hidden variables. The agent only gets a
4
+ sandbox directory containing a tiny `robot` CLI (talks to this server over localhost HTTP), a README
5
+ with the instructions, and the observation images the server writes into `<sandbox>/obs/`.
6
+ Nothing about the benchmark (code paths, hidden variables, success rule, scripted policies) is ever
7
+ written into the sandbox.
8
+
9
+ Attempt protocol (same semantics as harness.py):
10
+ cross `done` -> outcome is measured; if failed and attempts remain, the scene is reset to the same
11
+ initial state + hidden variables and the next attempt starts.
12
+ within `done` -> outcome is measured; if failed and done-calls remain, continue from the current state.
13
+ memory=none: every attempt is meant for a fresh agent; after `done` the server tells the agent to stop
14
+ (no feedback) and waits for the orchestrator to start a new agent (`./robot status` shows the state).
15
+
16
+ Run: python -m lffbench.agent.robot_server --task l5_slide_to_target --seed 1001 --sandbox <dir> --port 8765
17
+ """
18
+ import argparse
19
+ import importlib
20
+ import json
21
+ import os
22
+ import pkgutil
23
+ import shutil
24
+ import sys
25
+ import time
26
+ import traceback
27
+ from http.server import BaseHTTPRequestHandler, HTTPServer
28
+ import signal
29
+ import textwrap
30
+
31
+ import numpy as np
32
+
33
+ from .. import tasks as task_pkg
34
+ from ..task_base import TASKS
35
+ from . import camera as C
36
+ from .context import PromptBuilder
37
+ from .tools import ACTION_TOOLS, WS_HI, WS_LO, ToolExecutor, _json_default
38
+
39
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
40
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
41
+
42
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
43
+
44
+ SHELL_TEMPLATE = r'''#!/bin/bash
45
+ # Run a shell command inside this workspace, in the episode jail (no network, host data hidden):
46
+ # ./shell '<command>' or ./shell <<'EOF' ... EOF (command read from stdin)
47
+ WS="$(cd "$(dirname "$0")" && pwd)"
48
+ if [ $# -gt 0 ]; then CMD="$*"; else CMD="$(cat)"; fi
49
+ exec unshare --user --map-root-user --mount --net -- /opt/lffjail/jail_inner.sh "$WS" timeout -k 5 60 bash -c "$CMD"
50
+ '''
51
+
52
+ CLI_TEMPLATE = r'''#!/usr/bin/env python3
53
+ """Robot command-line interface. Usage: ./robot <command> [key=value ...] (./robot help)"""
54
+ import json, sys, urllib.request
55
+ PORT = __PORT__
56
+ TOKEN = "__TOKEN__"
57
+ def main():
58
+ if len(sys.argv) < 2:
59
+ sys.argv.append("help")
60
+ cmd, args = sys.argv[1], {}
61
+ for a in sys.argv[2:]:
62
+ if "=" not in a:
63
+ print(f"bad argument {a!r}: use key=value"); sys.exit(2)
64
+ k, v = a.split("=", 1)
65
+ try:
66
+ args[k] = json.loads(v)
67
+ except ValueError:
68
+ args[k] = v
69
+ req = urllib.request.Request(f"http://127.0.0.1:{PORT}/call", data=json.dumps({"cmd": cmd, "args": args}).encode(),
70
+ headers={"Content-Type": "application/json", "X-Token": TOKEN})
71
+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
72
+ with opener.open(req, timeout=600) as r:
73
+ print(r.read().decode())
74
+ main()
75
+ '''
76
+
77
+
78
+ def strip_axes(text):
79
+ """v2: keep the robot-centric words of the F2 feedback ("to the robot's left", "forward") but drop the explicit
80
+ coordinate-axis labels ("(+y)", "+x, ", "+yaw"), so the feedback does not hand over the axis convention that the
81
+ v2 instructions deliberately leave out."""
82
+ import re
83
+ t = re.sub(r"\s?\((?:[+-]?[xyz]|[+-]yaw)\)", "", text) # " (+y)", " (x)", " (-yaw)"
84
+ t = re.sub(r"\(([+-][xyz]|[+-]yaw), ", "(", t) # "(+x, away from the robot)"
85
+ t = re.sub(r", [+-](?:[xyz]|yaw)\)", ")", t) # "(... robot's left, +yaw)"
86
+ t = re.sub(r"\s{2,}", " ", t)
87
+ return t
88
+
89
+
90
+ class VideoRec:
91
+ """Records agentview | wrist while the simulator steps (one frame every `every` control steps, played at
92
+ `fps`, i.e. sped up by every * fps / 20). A header shows the attempt, the current robot command and the
93
+ report of the previous one; gripper commands and attempt outcomes get short freeze frames."""
94
+
95
+ BAND = 56
96
+
97
+ def __init__(self, path, env, res=320, every=3, fps=20, title=""):
98
+ import imageio
99
+ from . import camera as _C
100
+ self.env, self.res, self.every, self.fps, self.title = env, res, every, fps, title
101
+ self.cams = [_C.mj_cam("agentview"), _C.mj_cam("wrist")]
102
+ self.w = imageio.get_writer(path, fps=fps, quality=7, macro_block_size=8)
103
+ self.n = 0
104
+ self.lines = ["", "", ""]
105
+ self.last = None
106
+ orig = env.step
107
+
108
+ def step(a):
109
+ out = orig(a)
110
+ self.n += 1
111
+ if self.w is not None and self.n % self.every == 0:
112
+ self.grab()
113
+ return out
114
+
115
+ env.step = step
116
+
117
+ def _font(self, size):
118
+ from PIL import ImageFont
119
+ try:
120
+ return ImageFont.load_default(size=size)
121
+ except TypeError:
122
+ return ImageFont.load_default()
123
+
124
+ def grab(self):
125
+ from PIL import Image, ImageDraw
126
+ from .. import envs as _E
127
+ img = np.concatenate([_E.render(self.env, c, self.res) for c in self.cams], axis=1)
128
+ im = Image.new("RGB", (2 * self.res, self.res + self.BAND), (0, 0, 0))
129
+ im.paste(Image.fromarray(img), (0, self.BAND))
130
+ d = ImageDraw.Draw(im)
131
+ hdr = [self.title] + self.lines[:2]
132
+ for i, s_ in enumerate(hdr):
133
+ d.text((5, 3 + 17 * i), s_[:120], fill=(255, 255, 255) if i else (255, 220, 120), font=self._font(13))
134
+ self.last = np.asarray(im)
135
+ self.w.append_data(self.last)
136
+
137
+ def hold(self, secs):
138
+ if self.w is None:
139
+ return
140
+ self.grab()
141
+ for _ in range(int(secs * self.fps)):
142
+ self.w.append_data(self.last)
143
+
144
+ def card(self, lines, secs=3.0, color=(20, 20, 20)):
145
+ if self.w is None:
146
+ return
147
+ from PIL import Image, ImageDraw
148
+ im = Image.new("RGB", (2 * self.res, self.res + self.BAND), color)
149
+ d = ImageDraw.Draw(im)
150
+ y = 14
151
+ for s_ in lines:
152
+ for part in textwrap.wrap(s_, 62) or [""]:
153
+ d.text((14, y), part, fill=(255, 255, 255), font=self._font(15))
154
+ y += 19
155
+ y += 5
156
+ fr = np.asarray(im)
157
+ for _ in range(int(secs * self.fps)):
158
+ self.w.append_data(fr)
159
+
160
+ def close(self):
161
+ if self.w is not None:
162
+ self.w.close()
163
+ self.w = None
164
+
165
+
166
+ def _short(rep):
167
+ keys = ("touched_object", "holding_object", "gripper_width_m", "eef_pos", "eef_yaw_deg", "error")
168
+ return ", ".join(f"{k}={rep[k]}" for k in keys if k in rep)
169
+
170
+
171
+ class RobotSession:
172
+ def __init__(self, a):
173
+ self.a = a
174
+ self.task = TASKS[a.task](cam_res=a.image_res)
175
+ if a.max_steps is None: # long procedural tasks declare a larger per-attempt budget
176
+ a.max_steps = int(getattr(self.task, "agent_max_steps", 40))
177
+ self.inst = self.task.sample_instance(a.seed)
178
+ if getattr(a, "nominal", False):
179
+ # control condition: same scene, hidden calibration error removed (L1 tasks only) -> plain pick-and-place
180
+ hidden = [k for k in ("bias", "yaw_bias") if k in self.inst]
181
+ if not hidden:
182
+ raise SystemExit(f"--nominal is not supported for {a.task} (no bias / yaw_bias in the instance)")
183
+ for k in [k for k in self.inst if "bias" in k]: # bias, bias_r, yaw_bias, yaw_bias_deg, ...
184
+ v = self.inst[k]
185
+ if isinstance(v, (list, tuple)):
186
+ self.inst[k] = [0.0] * len(v)
187
+ elif isinstance(v, (int, float)):
188
+ self.inst[k] = 0.0
189
+ self.inst["nominal"] = True
190
+ # full5 controlled arms (docs/14 §6): h0 / twin override the hidden variable, hplus states it in the instruction
191
+ self.arm, self.arm_overrides, self.reveal_text = getattr(a, "arm", "none") or "none", {}, ""
192
+ if self.arm in ("h0", "twin"):
193
+ from .. import arm_specs
194
+ self.arm_overrides = arm_specs.overrides(a.task, self.arm, self.inst)
195
+ self.inst.update(self.arm_overrides)
196
+ elif self.arm == "hplus":
197
+ from .. import arm_specs
198
+ self.reveal_text = arm_specs.reveal(a.task, self.inst).strip()
199
+ if a.style in ("v2", "la"): # same rule as the F2 feedback: no axis labels such as "(+y)"
200
+ self.reveal_text = strip_axes(self.reveal_text)
201
+ self.n_mon_events = 0 # regression snapshots: monitor events already inspected
202
+ self.protocol = getattr(self.task, "protocol", "cross")
203
+ self.k = a.k or self.task.max_attempts
204
+ # --hide-k (memory=full): README and status say 1 attempt, exactly like an independent k=1 run, and the other
205
+ # attempts are announced only after a failure, so attempt 1 sees the same thing as the independent run.
206
+ self.k_shown = 1 if getattr(a, "hide_k", False) and a.memory == "full" else self.k
207
+ assert self.k_shown == self.k or a.style in ("v2", "la"), "--hide-k needs --style v2 or la"
208
+ self.sandbox = os.path.abspath(a.sandbox)
209
+ self.obs_dir = os.path.join(self.sandbox, "obs")
210
+ self.log_dir = os.path.abspath(a.log_dir)
211
+ os.makedirs(self.obs_dir, exist_ok=True)
212
+ os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True)
213
+ self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a")
214
+ import secrets
215
+ self.token = secrets.token_hex(8)
216
+ self.n_actions = 0 # robot commands in the current attempt (step budget)
217
+ self.attempt = 1
218
+ self.step = 0
219
+ self.finished = False
220
+ self.waiting_new_agent = False
221
+ self.history = []
222
+ self.last_send = None
223
+ cam_axes = {c: C.describe_axes(self.task.env, c, a.image_res) for c in C.CAMERAS}
224
+ names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
225
+ memory = "none" if a.memory == "none" else "full"
226
+ self.pb = PromptBuilder(self.task, self.protocol, self.k, memory, a.feedback, a.image_res, cam_axes,
227
+ object_names=names, cams=("agentview", "wrist"), depth_tool=a.perception == "depth")
228
+ self.video = None
229
+ if a.video:
230
+ self.video = VideoRec(a.video, self.task.env, every=a.video_every, fps=a.video_fps,
231
+ title=f"{a.task} seed={a.seed} perception={a.perception} (sped up x{a.video_every * a.video_fps // 20})")
232
+ self.video.card([f"Task: {a.task} seed {a.seed} memory={a.memory} feedback={a.feedback} k={self.k}",
233
+ "Instruction: " + self.instruction(),
234
+ "Left: agentview Right: wrist camera. Header: current robot command and the report of "
235
+ "the previous one."], 3)
236
+ self._start_attempt(reset=True)
237
+ # la: agent-facing positions are in the robot-base frame (LIBERO-Agent: "Coordinates are expressed in the
238
+ # robot-base frame and measured in metres"); the LIBERO base is axis-aligned with the world, so a translation
239
+ self.base_off = np.zeros(3)
240
+ if a.style == "la":
241
+ sim = self.task.env.sim
242
+ bid = sim.model.body_name2id("robot0_base")
243
+ assert np.allclose(sim.data.body_xmat[bid].reshape(3, 3), np.eye(3), atol=1e-6), "robot base is rotated"
244
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
245
+ self._write_sandbox()
246
+ self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol,
247
+ memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception,
248
+ inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm,
249
+ arm_overrides=self.arm_overrides, reveal=self.reveal_text, dossier=getattr(a, "dossier", "") or ""))
250
+
251
+ # ------------------------------------------------------------------ helpers
252
+ def log(self, d):
253
+ d["t"] = time.time()
254
+ self.events.write(json.dumps(d, default=_json_default) + "\n")
255
+ self.events.flush()
256
+
257
+ def instruction(self):
258
+ hook = getattr(self.task, "agent_instruction", None)
259
+ if hook is not None:
260
+ text = hook(self.inst, self.a.instruction)
261
+ elif self.a.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""):
262
+ text = self.task.instruction_indirect
263
+ else:
264
+ text = self.task.instruction
265
+ return text + (" " + self.reveal_text if getattr(self, "reveal_text", "") else "")
266
+
267
+ def feedback_text(self, out):
268
+ import inspect
269
+ fn = self.task.feedback
270
+ if "indirect" in inspect.signature(fn).parameters:
271
+ fb = fn(self.inst, out, self.a.feedback, indirect=self.a.instruction == "indirect")
272
+ else:
273
+ fb = fn(self.inst, out, self.a.feedback)
274
+ return strip_axes(fb) if self.a.style in ("v2", "la") else fb
275
+
276
+ def _start_attempt(self, reset):
277
+ self.n_actions = 0
278
+ if reset:
279
+ self.task.reset_instance(self.inst)
280
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.a.image_res, cams=("agentview", "wrist"))
281
+ self.step = 0
282
+ self.sim0 = self.task.sk.n_steps # v2: simulated-time budget is counted per attempt
283
+
284
+ def _save_obs(self, tag):
285
+ """Same bytes as the GPT harness sends (JPEG q90). Under memory=none the file names carry no
286
+ attempt number, so a fresh agent cannot tell it is a retry; --hide-k names attempt 1 the same way."""
287
+ from PIL import Image
288
+ paths = []
289
+ for ref in self.ex.observe(label=tag):
290
+ name = (f"s{self.step:03d}_{ref.camera}.jpg" if self.a.memory == "none" or (self.k_shown < self.k and self.attempt == 1)
291
+ else f"a{self.attempt}_s{self.step:03d}_{ref.camera}.jpg")
292
+ Image.fromarray(ref.array).save(os.path.join(self.obs_dir, name), quality=90)
293
+ shutil.copy(os.path.join(self.obs_dir, name), os.path.join(self.log_dir, "images", f"a{self.attempt}_{name}"))
294
+ paths.append(f"obs/{name}")
295
+ if self.a.style == "la":
296
+ self.last_files = self._write_la_files(f"a{self.attempt}_s{self.step:03d}")
297
+ return paths
298
+
299
+ def readme(self):
300
+ if self.a.style == "la":
301
+ return self.readme_la()
302
+ if self.a.style == "v2":
303
+ return self.readme_v2()
304
+ sp = self.pb.system_prompt()
305
+ sp = sp.replace("You act only by calling the provided tools, exactly one tool call per turn. Every action tool "
306
+ "returns an execution report; after each action you also receive new camera images and the "
307
+ "robot's proprioceptive state.",
308
+ "You act only through the `./robot` command in this directory (one robot command at a time). "
309
+ "Every action command prints an execution report and the paths of new camera images taken "
310
+ "after the action; look at them with your file-reading tool.")
311
+ sp = sp.replace("Finish by calling done(reason)", "Finish by running `./robot done reason=\"...\"`")
312
+ sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the "
313
+ "actions you executed and outcome feedback).",
314
+ "Each attempt ends when you run `./robot done`; that command prints the outcome feedback (if any) "
315
+ "and the images of the reset scene for the next attempt.")
316
+ sp = sp.replace("Each attempt ends when you call done; you will then see a summary of the attempt (key images, the "
317
+ "actions you executed).",
318
+ "Each attempt ends when you run `./robot done`; that command prints the images of the reset "
319
+ "scene for the next attempt.")
320
+ sp = sp.replace("before your first tool call", "before your first robot command")
321
+ tools = "\n".join([
322
+ " ./robot help this text",
323
+ " ./robot status task, current images and proprioception",
324
+ " ./robot observe take new images (agentview + wrist) + proprioception",
325
+ " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)",
326
+ " ./robot open_gripper | ./robot close_gripper",
327
+ " ./robot pixel_to_world camera=agentview|wrist u=.. v=.. (pixel -> 3-D point via depth)",
328
+ " ./robot done reason=\"...\" end the attempt / segment",
329
+ ] if self.a.perception == "depth" else [
330
+ " ./robot help this text",
331
+ " ./robot status task, current images and proprioception",
332
+ " ./robot observe take new images (agentview + wrist) + proprioception",
333
+ " ./robot move_to x=.. y=.. z=.. yaw=.. [speed=..] yaw in degrees; speed m/s (omit = fastest)",
334
+ " ./robot open_gripper | ./robot close_gripper",
335
+ " ./robot done reason=\"...\" end the attempt / segment",
336
+ ])
337
+ return ("# Robot task\n\n" + sp + "\n\n## Commands\n" + tools +
338
+ "\n\nArguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.\n"
339
+ "Images are written to obs/ inside this directory. After every action, look at the new images "
340
+ "before deciding on the next command.\n"
341
+ f"Each attempt allows at most {self.a.max_steps} robot commands (help/status not counted); after that "
342
+ "the attempt ends automatically.\n\n## TASK\n" + self.instruction() + "\n")
343
+
344
+ def _write_sandbox(self):
345
+ os.makedirs(self.sandbox, exist_ok=True)
346
+ if self.a.style == "la":
347
+ with open(os.path.join(self.log_dir, "agent_iface.json"), "w") as f:
348
+ json.dump(dict(token=self.token, port=self.a.port, workspace=self.sandbox, agent_iface=self.a.agent_iface,
349
+ max_tool_calls=self.a.max_tool_calls, perception=self.a.perception), f)
350
+ with open(os.path.join(self.sandbox, "README.md"), "w") as f:
351
+ f.write(self.readme())
352
+ if getattr(self.a, "dossier", ""):
353
+ shutil.copytree(self.a.dossier, os.path.join(self.sandbox, "history"))
354
+ if self.a.agent_iface == "cli": # coding-agent harness (Claude Code): ./robot + ./shell in the workspace
355
+ for name, body in (("robot", CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token)),
356
+ ("shell", SHELL_TEMPLATE)):
357
+ with open(os.path.join(self.sandbox, name), "w") as f:
358
+ f.write(body)
359
+ os.chmod(os.path.join(self.sandbox, name), 0o755)
360
+ return
361
+ cli = os.path.join(self.sandbox, "robot")
362
+ with open(cli, "w") as f:
363
+ f.write(CLI_TEMPLATE.replace("__PORT__", str(self.a.port)).replace("__TOKEN__", self.token))
364
+ os.chmod(cli, 0o755)
365
+ with open(os.path.join(self.sandbox, "README.md"), "w") as f:
366
+ f.write(self.readme())
367
+
368
+ def status(self):
369
+ if self.a.memory == "none":
370
+ return dict(task=self.instruction(), finished=self.finished)
371
+ st = dict(task=self.instruction(), protocol=self.protocol, attempt=self.attempt, max_attempts=self.k,
372
+ finished=self.finished)
373
+ if self.waiting_new_agent:
374
+ st["note"] = "The previous agent finished its attempt. A new attempt is ready; the scene has been reset."
375
+ return st
376
+
377
+ # ------------------------------------------------------------------ dispatch
378
+ def handle(self, cmd, args):
379
+ if self.a.style in ("v2", "la"):
380
+ return self.handle_v2(cmd, args)
381
+ if cmd == "help":
382
+ return dict(text=self.readme())
383
+ if cmd == "status":
384
+ st = self.status()
385
+ st["images"] = self._save_obs("status")
386
+ st.update(self.ex.proprio())
387
+ self.waiting_new_agent = False
388
+ return st
389
+ if self.finished:
390
+ return dict(ok=False, error="The episode is over. Stop now.")
391
+ if self.waiting_new_agent:
392
+ return dict(ok=False, error="This attempt has ended. Stop now.")
393
+ if cmd in ("observe", "pixel_to_world", "move_to", "open_gripper", "close_gripper", "push"):
394
+ self.n_actions += 1
395
+ if self.n_actions > self.a.max_steps:
396
+ rep = self._done("step budget exhausted (automatic)")
397
+ rep["note"] = f"The step budget of {self.a.max_steps} commands for this attempt was used up."
398
+ return rep
399
+ if cmd == "observe":
400
+ self.step += 1
401
+ rep = dict(ok=True, images=self._save_obs("observe"))
402
+ rep.update(self.ex.proprio())
403
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
404
+ return rep
405
+ if cmd == "done":
406
+ return self._done(args.get("reason", ""))
407
+ allowed = tuple(t for t in ACTION_TOOLS if t != "push" or self.a.allow_push)
408
+ if self.a.perception == "depth":
409
+ allowed += ("pixel_to_world",)
410
+ if cmd not in allowed:
411
+ return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help")
412
+ self.step += 1
413
+ if self.video is not None:
414
+ argtxt = " ".join(f"{k}={v}" for k, v in args.items())
415
+ self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}"
416
+ res = self.ex.call(cmd, args)
417
+ rep = dict(res.report)
418
+ if self.video is not None:
419
+ self.video.lines[1] = f" -> {_short(rep)}"
420
+ if cmd in ("close_gripper", "open_gripper"):
421
+ self.video.hold(1.2)
422
+ if res.ok and cmd in ACTION_TOOLS:
423
+ rep["images"] = self._save_obs(cmd)
424
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep,
425
+ wall_s=res.wall_s, sim_steps=res.sim_steps))
426
+ return rep
427
+
428
+ def _done(self, reason):
429
+ out = self.task.outcome(self.inst)
430
+ succ = bool(out["success"])
431
+ fb = self.feedback_text(out)
432
+ self.history.append(dict(attempt=self.attempt, success=succ, feedback=fb, reason=reason))
433
+ self.log(dict(ev="done", attempt=self.attempt, step=self.step, reason=reason, success=succ, feedback=fb,
434
+ outcome={k: v for k, v in out.items() if k != "feedback"}))
435
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
436
+ if self.video is not None:
437
+ self.video.lines = [f"attempt {self.attempt}/{self.k}: done", f" reason: {reason}", ""]
438
+ self.video.hold(1.0)
439
+ self.video.card([f"Attempt {self.attempt}: {'SUCCESS' if succ else 'FAILED'}",
440
+ f"Commands used in this attempt: {self.n_actions}", "Agent's reason: " + str(reason)[:300],
441
+ "Feedback: " + (fb if self.a.memory != "none" and self.a.feedback != "F0" else "(not shown)")],
442
+ 3.5, (20, 50, 20) if succ else (60, 20, 20))
443
+ if last:
444
+ self.video.close()
445
+ else:
446
+ self.video.lines = ["", "", ""]
447
+ if self.a.memory == "none":
448
+ # independent attempts: no feedback to the agent; orchestrator starts a fresh agent
449
+ if last:
450
+ self.finished = True
451
+ else:
452
+ self.attempt += 1
453
+ self._start_attempt(reset=self.protocol == "cross")
454
+ self.waiting_new_agent = True
455
+ return dict(ok=True, ended=True, message="Attempt recorded. Stop now and report what you did.")
456
+ rep = dict(ok=True, ended=True)
457
+ if self.a.feedback != "F0":
458
+ rep["feedback"] = fb
459
+ if last and (succ or self.a.feedback != "F0"):
460
+ self.finished = True
461
+ rep["message"] = "The episode is over. Stop now and report."
462
+ return rep
463
+ if self.attempt >= self.k or out.get("terminal"):
464
+ self.finished = True
465
+ rep["message"] = ("The failure cannot be undone, so the episode is over. Stop now and report."
466
+ if out.get("terminal") else "No attempts left. The episode is over. Stop now and report.")
467
+ return rep
468
+ self.attempt += 1
469
+ reveal = ""
470
+ if self.k_shown < self.k: # --hide-k: first failure, announce the extra attempts now
471
+ self.k_shown = self.k
472
+ reveal = f"You get more attempts than README.md says: up to {self.k} in total. "
473
+ if self.protocol == "cross":
474
+ self._start_attempt(reset=True)
475
+ rep["message"] = reveal + (f"Attempt {self.attempt} of {self.k} starts now. The scene has been reset to exactly the "
476
+ f"same initial state.")
477
+ else:
478
+ self._start_attempt(reset=False)
479
+ rep["message"] = reveal + (f"Continue from the current state (segment {self.attempt}; you may call done at most "
480
+ f"{self.k} times in total).")
481
+ self.step += 1
482
+ rep["images"] = self._save_obs("attempt_start")
483
+ rep.update(self._la_files())
484
+ if self.a.style in ("v2", "la"):
485
+ rep.update(self._state_v2())
486
+ else:
487
+ rep.update(self.ex.proprio())
488
+ return rep
489
+
490
+
491
+ V2_DROP = ("holding", "touched", "events", "sim_time_s", "tool", "reached", "yaw_used_deg", "target_clipped_to")
492
+
493
+
494
+ class _V2:
495
+ """Interface v2 (2026-10-07, aligned with LIBERO-Agent / RoboDojo-L3 at the user's request):
496
+ - priors: only the task instruction, the attempt rules, the budgets and the command definitions (no axes,
497
+ table height, camera orientation or robot geometry);
498
+ - observations: two RGB images published as files after every command + end-effector state (position,
499
+ yaw, gripper width) + how far the arm stopped from the commanded target + budget left; no
500
+ held/touched flags and no per-step task events;
501
+ - action: move_eef = absolute target (omitted coordinates keep their value; gripper after the motion;
502
+ optional speed); unreachable targets are rejected and the arm does not move;
503
+ - an attempt ends with `finish` (alias `done`) or when a budget runs out; the environment judges it."""
504
+
505
+
506
+ def _readme_v2(self):
507
+ sec = self.sim_budget()
508
+ proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the "
509
+ f"same initial state." if self.protocol == "cross" else
510
+ f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a "
511
+ f"failed attempt you continue from the current state.")
512
+ return "\n".join([
513
+ "# Robot task", "",
514
+ "You control a robot arm with a two-finger gripper in a physics simulation, only through the `./robot` "
515
+ "command in this directory (one command at a time).", "",
516
+ "## Task", self.instruction(), "",
517
+ "## Attempts", proto + " An attempt ends when you run `./robot finish reason=\"...\"` or when its budget "
518
+ "is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the last "
519
+ "attempt.", "",
520
+ "## Budget (per attempt)",
521
+ f"- at most {self.a.max_steps} robot commands (status and help are free);",
522
+ f"- at most {sec:.0f} s of simulated robot motion.",
523
+ "Every reply shows what is left.", "",
524
+ "## Observations",
525
+ "Every command writes two new camera images into obs/ and prints their paths: 'agentview' (a fixed camera "
526
+ "looking at the table) and 'wrist' (a camera on the gripper). It also reports the end-effector state: "
527
+ "eef_pos = [x, y, z] of the gripper's grasp point in metres, eef_yaw_deg = rotation of the gripper about "
528
+ "the vertical axis in degrees, gripper_width_m = opening of the fingers in metres, and after a motion how "
529
+ "far the gripper stopped from your target.", "",
530
+ "## Commands",
531
+ " ./robot status task, attempt, budget, current state and images",
532
+ " ./robot observe new images and state without moving",
533
+ " ./robot move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]",
534
+ " move the grasp point to an absolute target in the same frame as eef_pos (metres; yaw in degrees);",
535
+ " omitted coordinates keep their current value; the gripper command is executed after the motion;",
536
+ " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.",
537
+ " ./robot finish reason=\"...\" end the current attempt",
538
+ "",
539
+ "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""])
540
+
541
+
542
+ def _sim_budget(self):
543
+ return 3.0 * self.a.max_steps # seconds of simulated motion per attempt
544
+
545
+
546
+ def _budget_left(self):
547
+ used = (self.task.sk.n_steps - self.sim0) * 0.05
548
+ return dict(commands=max(self.a.max_steps - self.n_actions, 0), sim_seconds=round(max(self.sim_budget() - used, 0.0), 1))
549
+
550
+
551
+ def _state_v2(self):
552
+ p = self.ex.proprio()
553
+ pos = p["eef_pos"]
554
+ if self.a.style == "la":
555
+ pos = [round(float(v), 4) for v in np.asarray(pos, float) - self.base_off]
556
+ st = dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
557
+ if self.a.style == "la": # read-only joint angles, as LIBERO-Agent (all levels) and RoboDojo give them
558
+ st["joint_pos_rad"] = [round(float(v), 4) for v in self._believed_joints()]
559
+ st["budget_left"] = self._budget_left()
560
+ return st
561
+
562
+
563
+ def _clean_v2(rep):
564
+ return {k: v for k, v in rep.items() if not k.startswith(V2_DROP)}
565
+
566
+
567
+ def _handle_v2(self, cmd, args):
568
+ if cmd == "help":
569
+ return dict(text=self.readme())
570
+ if cmd == "status":
571
+ st = dict(task=self.instruction(), attempt=self.attempt, max_attempts=self.k_shown, finished=self.finished)
572
+ st["images"] = self._save_obs("status")
573
+ st.update(self._la_files())
574
+ st.update(self._state_v2())
575
+ return st
576
+ if self.finished:
577
+ return dict(ok=False, error="The episode is over. Stop now.")
578
+ if cmd in ("finish", "done"):
579
+ return self._done(args.get("reason", ""))
580
+ if cmd not in ("observe", "move_eef"):
581
+ return dict(ok=False, error=f"unknown command {cmd!r}; run ./robot help")
582
+ self.n_actions += 1
583
+ if self.n_actions > self.a.max_steps:
584
+ rep = self._done("command budget used up (automatic)")
585
+ rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up."
586
+ return rep
587
+ self.step += 1
588
+ if cmd == "observe":
589
+ rep = dict(ok=True, images=self._save_obs("observe"))
590
+ rep.update(self._la_files())
591
+ rep.update(self._state_v2())
592
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
593
+ return rep
594
+ # ---------------- move_eef
595
+ p = self.ex.proprio()
596
+ unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}
597
+ if unknown:
598
+ rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed")
599
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
600
+ return rep
601
+ off = self.base_off # zero except la (robot-base frame)
602
+ try:
603
+ cur = np.asarray(p["eef_pos"], float) - off
604
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
605
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
606
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
607
+ except (TypeError, ValueError):
608
+ rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers")
609
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
610
+ return rep
611
+ grip = args.get("gripper")
612
+ if grip not in (None, "open", "close"):
613
+ rep = dict(ok=False, error="gripper must be open or close")
614
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
615
+ return rep
616
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
617
+ tgt_w = np.asarray(tgt) + off # simulator (world) frame
618
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
619
+ rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move")
620
+ rep.update(self._state_v2())
621
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
622
+ return rep
623
+ if self.video is not None:
624
+ argtxt = " ".join(f"{k}={v}" for k, v in args.items())
625
+ self.video.lines[0] = f"attempt {self.attempt}/{self.k} command #{self.n_actions}: {cmd} {argtxt}"
626
+ left = self._budget_left()["sim_seconds"]
627
+ raw = {}
628
+ if moving:
629
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
630
+ if speed is not None:
631
+ mv["speed"] = speed
632
+ res = self.ex.call("move_to", mv)
633
+ raw.update(res.report)
634
+ if grip is not None:
635
+ res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {})
636
+ raw.update(res.report)
637
+ rep = dict(ok=bool(raw.get("ok", True)))
638
+ if raw.get("error"):
639
+ rep["error"] = raw["error"]
640
+ rep.update(self._state_v2())
641
+ if moving:
642
+ err = np.asarray(tgt) - np.asarray(rep["eef_pos"])
643
+ dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0
644
+ rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1))
645
+ if self.video is not None:
646
+ self.video.lines[1] = f" -> eef={rep['eef_pos']} width={rep['gripper_width_m']} {rep.get('stopped_from_target', '')}"
647
+ if grip is not None:
648
+ self.video.hold(1.2)
649
+ rep["images"] = self._save_obs(cmd)
650
+ rep.update(self._la_files())
651
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw))
652
+ self._snap_regressions()
653
+ if rep["budget_left"]["sim_seconds"] <= 0 and left > 0:
654
+ fin = self._done("motion budget used up (automatic)")
655
+ fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up."
656
+ rep["attempt_ended"] = fin
657
+ return rep
658
+
659
+
660
+ LOSS_EVENTS = ("lost", "toppled", "tipped", "load_fell", "load_displaced")
661
+
662
+
663
+ def _snap_regressions(self):
664
+ """Save the simulator state right after a command during which the task monitor registered a loss of earlier
665
+ progress (lost / toppled / tipped / load_fell ...), for the "self-inflicted vs handed-over" experiment (docs/14 §6).
666
+ Server-side only: snapshots go to <log>/snapshots/, never to the agent's workspace."""
667
+ try: # bookkeeping only: it must never change what the agent gets back
668
+ self._snap_regressions_inner()
669
+ except Exception:
670
+ self.log(dict(ev="snapshot_error", error=traceback.format_exc()[-1500:]))
671
+
672
+
673
+ def _snap_regressions_inner(self):
674
+ mon = getattr(self.task, "mon", None)
675
+ evs = mon.get("events") if isinstance(mon, dict) else None
676
+ if not isinstance(evs, list):
677
+ return
678
+ new = evs[self.n_mon_events:]
679
+ self.n_mon_events = len(evs)
680
+ loss = [e for e in new if isinstance(e, dict) and str(e.get("ev", e.get("event", ""))) in LOSS_EVENTS]
681
+ if not loss:
682
+ return
683
+ import copy
684
+ d = os.path.join(self.log_dir, "snapshots")
685
+ os.makedirs(d, exist_ok=True)
686
+ name = f"a{self.attempt}_s{self.step:03d}"
687
+ try:
688
+ flat = np.asarray(self.task.env.sim.get_state().flatten(), float)
689
+ except Exception: # keep the run going even if a simulator binding lacks get_state
690
+ flat = np.concatenate([self.task.env.sim.data.qpos, self.task.env.sim.data.qvel]).astype(float)
691
+ np.save(os.path.join(d, name + "_sim.npy"), flat)
692
+ meta = dict(attempt=self.attempt, step=self.step, n_actions=self.n_actions, sim_steps=int(self.task.sk.n_steps - self.sim0),
693
+ loss_events=loss, mon=copy.deepcopy(mon))
694
+ def _dflt(o): # task monitors keep sets (ever / lost / lid_hits ...)
695
+ return sorted(o, key=str) if isinstance(o, (set, frozenset)) else _json_default(o)
696
+ with open(os.path.join(d, name + "_meta.json"), "w") as f:
697
+ json.dump(meta, f, default=_dflt)
698
+ self.log(dict(ev="regression_snapshot", attempt=self.attempt, step=self.step, file=f"snapshots/{name}", n_loss=len(loss)))
699
+
700
+
701
+ def _la_files(self):
702
+ """la: paths of the non-image observation files written with the last images (empty for other styles)."""
703
+ return dict(self.last_files) if self.a.style == "la" and getattr(self, "last_files", None) else {}
704
+
705
+
706
+ def _believed_pose(self):
707
+ """4x4 pose of the grasp point as the ROBOT believes it (the frame of eef_pos / move_eef): the true pose shifted by
708
+ the task's hidden calibration errors (Skills.bias, and YawSkills.yaw_bias about the vertical axis). A real robot
709
+ computes its wrist-camera pose from its own (miscalibrated) kinematics, so the wrist calibration uses this pose."""
710
+ sk = self.task.sk
711
+ beta = float(getattr(sk, "yaw_bias", 0.0))
712
+ c, s_ = np.cos(-beta), np.sin(-beta)
713
+ Rz = np.array([[c, -s_, 0.0], [s_, c, 0.0], [0.0, 0.0, 1.0]])
714
+ T_true = np.eye(4)
715
+ T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos()
716
+ T_b = np.eye(4)
717
+ T_b[:3, :3], T_b[:3, 3] = Rz @ sk.eef_mat(), sk.eef_pos() - np.asarray(sk.bias, float)
718
+ return T_b, T_true
719
+
720
+
721
+ def _believed_joints(self, iters=30):
722
+ """The 7 arm joint angles as the robot's encoders report them. For tasks with a hidden calibration error (L1) these
723
+ are the angles consistent with the robot's own belief: standard forward kinematics of them gives exactly the
724
+ reported (believed) grasp pose, as on a real arm whose encoder offsets are miscalibrated; true joint angles would
725
+ hand the hidden error to anyone who runs the public Franka kinematics. Without a calibration error they are the true
726
+ angles. Solved by damped least squares on a scratch copy of the simulator state (2-3 iterations)."""
727
+ import mujoco
728
+ env, sk = self.task.env, self.task.sk
729
+ rob = env.robots[0]
730
+ idx, dof, site = np.array(rob._ref_joint_pos_indexes), np.array(rob._ref_joint_vel_indexes), rob.eef_site_id
731
+ m, d0 = env.sim.model._model, env.sim.data._data
732
+ T_b, _ = self._believed_pose()
733
+ if np.allclose(T_b[:3, 3], d0.site_xpos[site]) and np.allclose(T_b[:3, :3], d0.site_xmat[site].reshape(3, 3)):
734
+ return d0.qpos[idx].copy()
735
+ d = mujoco.MjData(m)
736
+ d.qpos[:] = d0.qpos
737
+ jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv))
738
+ for _ in range(iters):
739
+ mujoco.mj_kinematics(m, d)
740
+ mujoco.mj_comPos(m, d)
741
+ ep = T_b[:3, 3] - d.site_xpos[site]
742
+ Re = T_b[:3, :3] @ d.site_xmat[site].reshape(3, 3).T
743
+ er = 0.5 * np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]])
744
+ if np.linalg.norm(ep) < 1e-7 and np.linalg.norm(er) < 1e-7:
745
+ break
746
+ mujoco.mj_jacSite(m, d, jp, jr, site)
747
+ J = np.vstack([jp[:, dof], jr[:, dof]])
748
+ d.qpos[idx] += J.T @ np.linalg.solve(J @ J.T + 1e-6 * np.eye(6), np.concatenate([ep, er]))
749
+ return d.qpos[idx].copy()
750
+
751
+
752
+ def _write_la_files(self, prefix):
753
+ """la observation files besides the two JPEGs: <prefix>_state.json always; with --perception rgbd also metric
754
+ depth for both cameras (<prefix>_<cam>_depth.npy, float32 metres along the optical axis, same upright pixels as
755
+ the JPEG) and <prefix>_camera.json (K and cam_to_world in the eef_pos frame, OpenCV camera axes).
756
+ The fixed agentview camera is calibrated in the true frame; the wrist camera pose is computed from the robot's
757
+ believed gripper pose (so neither file reveals the hidden calibration error of the L1 tasks)."""
758
+ out = {}
759
+ st = self._state_v2()
760
+ st = dict(eef_pos=st["eef_pos"], eef_yaw_deg=st["eef_yaw_deg"], gripper_width_m=st["gripper_width_m"],
761
+ joint_pos_rad=st["joint_pos_rad"], attempt=self.attempt, step=self.step)
762
+ with open(os.path.join(self.obs_dir, f"{prefix}_state.json"), "w") as f:
763
+ json.dump(st, f, default=_json_default)
764
+ out["state_file"] = f"obs/{prefix}_state.json"
765
+ if self.a.perception == "rgbd":
766
+ res = self.a.image_res
767
+ cams, depth_files = {}, []
768
+ T_b, T_true = self._believed_pose()
769
+ for cam in ("agentview", "wrist"):
770
+ d = C.render_depth(self.task.env, cam, res).astype(np.float32)
771
+ np.save(os.path.join(self.obs_dir, f"{prefix}_{cam}_depth.npy"), d)
772
+ depth_files.append(f"obs/{prefix}_{cam}_depth.npy")
773
+ E = C.cam_to_world(self.task.env, cam)
774
+ if cam == "wrist":
775
+ E = T_b @ np.linalg.inv(T_true) @ E
776
+ E = E.copy()
777
+ E[:3, 3] -= self.base_off # robot-base frame
778
+ cams[cam] = dict(K=np.round(C.intrinsics(self.task.env, cam, res), 6).tolist(),
779
+ cam_to_base=np.round(E, 6).tolist(), width=res, height=res)
780
+ with open(os.path.join(self.obs_dir, f"{prefix}_camera.json"), "w") as f:
781
+ json.dump(cams, f)
782
+ out["depth_files"] = depth_files
783
+ out["camera_file"] = f"obs/{prefix}_camera.json"
784
+ return out
785
+
786
+
787
+
788
+ def _fb_sentence(level):
789
+ """README sentence for the feedback level. F1 (default since 2026-10-08): success / failure only, like
790
+ LIBERO-Agent's finish_episode outcome; F2 (measured error, e.g. "2.5 cm past the centre") is privileged
791
+ simulator information that neither LIBERO-Agent nor RoboDojo gives, kept only as an ablation."""
792
+ return {"F0": "The environment then checks the result.",
793
+ "F1": "The environment then checks the result and tells you only whether the attempt succeeded.",
794
+ "F2": "The environment then checks the result and tells you whether the attempt succeeded and, if not, "
795
+ "what went wrong."}[level]
796
+
797
+ def _readme_la(self):
798
+ """LIBERO-Agent-style instructions: the agent works in an episode workspace (observations are files, it can run
799
+ programs on them); the robot itself is driven only through the harness's `robot` tool."""
800
+ sec = self.sim_budget()
801
+ rgbd = self.a.perception == "rgbd"
802
+ cli = self.a.agent_iface == "cli"
803
+ pre = "./robot " if cli else ""
804
+ proto = (f"You have up to {self.k_shown} attempts at this task. Before every attempt the scene is reset to exactly the "
805
+ f"same initial state." if self.protocol == "cross" else
806
+ f"Everything happens in one continuous scene. You may end an attempt up to {self.k_shown} times; after a "
807
+ f"failed attempt you continue from the current state.")
808
+ files = [
809
+ "- obs/a<attempt>_s<step>_agentview.jpg and obs/a<attempt>_s<step>_wrist.jpg: 512x512 RGB images from "
810
+ "'agentview' (a fixed camera looking at the table) and 'wrist' (a camera on the gripper);",
811
+ "- obs/a<attempt>_s<step>_state.json: the end-effector state: eef_pos = [x, y, z] of the gripper's grasp "
812
+ "point (midway between the two fingers, about 1 cm above the fingertips), eef_yaw_deg = rotation of the gripper about the vertical axis in degrees, gripper_width_m = opening "
813
+ "of the fingers in metres, joint_pos_rad = the 7 arm joint angles (radians, base to wrist; read-only).",
814
+ ]
815
+ if rgbd:
816
+ files += [
817
+ "- obs/a<attempt>_s<step>_agentview_depth.npy and obs/a<attempt>_s<step>_wrist_depth.npy: metric depth "
818
+ "(numpy float32 array, 512x512, metres along each camera's optical axis), pixel-aligned with the images "
819
+ "(row 0 = top of the image);",
820
+ "- obs/a<attempt>_s<step>_camera.json: for each camera, K (3x3 intrinsics of the 512x512 image) and "
821
+ "cam_to_base (4x4 pose of the camera in the robot-base frame; camera axes: x right, y down, z forward).",
822
+ ]
823
+ return "\n".join([
824
+ "# Robot task", "",
825
+ "You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics "
826
+ "simulation.", "",
827
+ "## Task", self.instruction(), "",
828
+ "## Attempts", proto + f" An attempt ends when you run the robot command `{pre}finish reason=\"...\"` or when its "
829
+ "budget is used up. " + _fb_sentence(self.a.feedback) + " The episode ends at the first success or after the "
830
+ "last attempt.", "",
831
+ *(["## Earlier attempt",
832
+ "Before this episode, an earlier attempt at this task, starting from a scene that looked the same as yours, "
833
+ "failed. Its record is in history/: history/README.md lists every robot command of that attempt with the "
834
+ "robot's reply and its closing remark, and history/obs/ holds the camera images it produced.", ""]
835
+ if getattr(self.a, "dossier", "") else []),
836
+ "## Budget (per attempt)",
837
+ f"- at most {self.a.max_steps} robot commands (status and help are free);",
838
+ f"- at most {sec:.0f} s of simulated robot motion;",
839
+ *([] if cli else [f"- at most {self.a.max_tool_calls} tool calls in total (robot, shell and view_image together)."]),
840
+ "Every robot reply shows the robot budgets that are left.", "",
841
+ "## Coordinates",
842
+ "Coordinates are expressed in the robot-base frame and measured in metres; angles are in degrees.", "",
843
+ "## Workspace and observations",
844
+ "This directory is your workspace for the whole episode. Every robot command writes its observation into "
845
+ "obs/ and prints the paths of the new files:",
846
+ *files,
847
+ "Robot replies also include the end-effector state and, after a motion, how far the gripper stopped from your "
848
+ "target. " + ("You can look at any image with your file-reading tool, run shell commands and programs in this "
849
+ "workspace with `./shell '<command>'` (python3 with numpy, scipy, Pillow and OpenCV; no network; "
850
+ "programs cannot control the robot), and keep your own files and notes in this directory; they "
851
+ "persist across attempts." if cli else
852
+ "You can look at any image with view_image, run shell commands and programs here (python3 with "
853
+ "numpy, scipy, Pillow and OpenCV; no network; programs cannot control the robot), and keep your "
854
+ "own files and notes in this directory; they persist across attempts."), "",
855
+ "## Robot commands " + ("(run from this directory as `./robot <command>`, one command at a time)" if cli
856
+ else "(argument of the `robot` tool)"),
857
+ f" {pre}status task, attempt, budget, current state and observation files",
858
+ f" {pre}observe new observation without moving",
859
+ f" {pre}move_eef [x=..] [y=..] [z=..] [yaw=..] [gripper=open|close] [speed=..]",
860
+ " move the grasp point to an absolute target (robot-base frame, metres; yaw in degrees);",
861
+ " omitted coordinates keep their current value; the gripper command is executed after the motion;",
862
+ " speed in m/s (omit = fastest); a target the arm cannot reach is rejected and the arm does not move.",
863
+ f" {pre}finish reason=\"...\" end the current attempt",
864
+ "",
865
+ "Arguments are key=value; numbers are plain (e.g. x=0.12). Quote strings with spaces.", ""])
866
+
867
+
868
+ for _n, _f in (("_believed_joints", _believed_joints), ("readme_la", _readme_la), ("_la_files", _la_files), ("_believed_pose", _believed_pose),
869
+ ("_write_la_files", _write_la_files), ("readme_v2", _readme_v2), ("sim_budget", _sim_budget), ("_budget_left", _budget_left),
870
+ ("_state_v2", _state_v2), ("handle_v2", _handle_v2), ("_snap_regressions", _snap_regressions),
871
+ ("_snap_regressions_inner", _snap_regressions_inner)):
872
+ setattr(RobotSession, _n, _f)
873
+ RobotSession._clean_v2 = staticmethod(_clean_v2)
874
+
875
+
876
+ def serve(a):
877
+ sess = RobotSession(a)
878
+
879
+ class H(BaseHTTPRequestHandler):
880
+ def log_message(self, *x):
881
+ pass
882
+
883
+ def do_POST(self):
884
+ t_recv = time.time()
885
+ cmd = ""
886
+ try:
887
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
888
+ cmd = body.get("cmd", "")
889
+ if self.headers.get("X-Token") != sess.token:
890
+ rep = dict(ok=False, error="unauthorised")
891
+ else:
892
+ rep = sess.handle(cmd, body.get("args", {}) or {})
893
+ except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent
894
+ sess.log(dict(ev="error", error=traceback.format_exc()))
895
+ rep = dict(ok=False, error=f"internal error: {type(e).__name__}")
896
+ data = json.dumps(rep, default=_json_default, indent=None).encode()
897
+ if "text" in rep:
898
+ data = rep["text"].encode()
899
+ self.send_response(200)
900
+ self.send_header("Content-Type", "application/json")
901
+ self.end_headers()
902
+ self.wfile.write(data)
903
+ t_send = time.time()
904
+ # think time = gap between the previous reply and this request (model inference + its own tool overhead)
905
+ sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send,
906
+ server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None))
907
+ sess.last_send = t_send
908
+
909
+ def _term(*_):
910
+ if sess.video is not None:
911
+ sess.video.close()
912
+ os._exit(0)
913
+
914
+ signal.signal(signal.SIGTERM, _term)
915
+ srv = HTTPServer(("127.0.0.1", a.port), H)
916
+ print(f"robot server ready on 127.0.0.1:{a.port} sandbox={sess.sandbox} log={sess.log_dir}", flush=True)
917
+ with open(os.path.join(sess.log_dir, "READY"), "w") as f:
918
+ f.write(str(os.getpid()))
919
+ srv.serve_forever()
920
+
921
+
922
+ def main():
923
+ ap = argparse.ArgumentParser()
924
+ ap.add_argument("--task", required=True)
925
+ ap.add_argument("--seed", type=int, required=True)
926
+ ap.add_argument("--k", type=int, default=None)
927
+ ap.add_argument("--memory", default="full", choices=["full", "none"])
928
+ ap.add_argument("--hide-k", action="store_true",
929
+ help="memory=full: README/status say 1 attempt (same as an independent k=1 run); the remaining "
930
+ "attempts are announced only after a failed attempt")
931
+ ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
932
+ ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"])
933
+ ap.add_argument("--image-res", type=int, default=512)
934
+ ap.add_argument("--port", type=int, default=8765)
935
+ ap.add_argument("--sandbox", required=True)
936
+ ap.add_argument("--log-dir", required=True)
937
+ ap.add_argument("--max-steps", type=int, default=None,
938
+ help="robot commands per attempt (default: the task's agent_max_steps, else 40)")
939
+ ap.add_argument("--allow-push", action="store_true", help="expose the composite push primitive (off by default)")
940
+ ap.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"],
941
+ help="rgb: images only (no pixel_to_world / depth); depth: adds the depth back-projection tool "
942
+ "(v1); rgbd (la): also writes metric depth and camera calibration files")
943
+ ap.add_argument("--style", default="v1", choices=["v1", "v2", "la"],
944
+ help="v2: LIBERO-Agent / RoboDojo-aligned interface (see _V2); la: v2 + LIBERO-Agent workspace "
945
+ "(observation files, programs in the workspace, robot only through the harness tool)")
946
+ ap.add_argument("--nominal", action="store_true",
947
+ help="control: remove the hidden calibration error of an L1 task (bias / yaw_bias = 0)")
948
+ ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"],
949
+ help="la: tools = harness tools (robot / shell / view_images, our GPT driver); cli = ./robot and "
950
+ "./shell in the workspace for a coding agent such as Claude Code")
951
+ ap.add_argument("--max-tool-calls", type=int, default=100,
952
+ help="la: tool calls per attempt (robot + shell + view_image), enforced by the harness")
953
+ ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
954
+ help="full5 controlled arms (lffbench/arm_specs/<task>.py): h0 = hidden variable at its ordinary value; "
955
+ "hplus = hidden variable stated in the instruction; twin = mismatched-history source instance")
956
+ ap.add_argument("--dossier", default="",
957
+ help="la: copy this directory into the workspace as history/ (record of an earlier failed attempt, "
958
+ "made by scripts/make_dossier.py) and say so in README.md")
959
+ ap.add_argument("--video", default="", help="record agentview|wrist mp4 to this path")
960
+ ap.add_argument("--video-every", type=int, default=3, help="one frame every N control steps (20 Hz)")
961
+ ap.add_argument("--video-fps", type=int, default=20)
962
+ serve(ap.parse_args())
963
+
964
+
965
+ if __name__ == "__main__":
966
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/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_20261103_sonnet/lff/source_closure/lffbench/agent/tools.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Agent-facing tool interface on top of `Skills`.
2
+
3
+ Every action tool calls the task's `Skills` object, so the task's hidden calibration `bias` keeps
4
+ acting on every commanded position. Proprioception is reported in the robot's own (possibly
5
+ miscalibrated) frame: reported eef = true eef - bias, i.e. the robot "believes" it reached the
6
+ commanded point; only the cameras show the truth. Camera-derived quantities (pixel_to_world) and
7
+ the privileged `locate` tool are in the true world frame.
8
+
9
+ Tool schemas are plain JSON schema (OpenAI strict-mode compatible: every property listed in
10
+ `required`, optional ones nullable, no additional properties).
11
+ """
12
+ import json
13
+ import math
14
+ import time
15
+ from dataclasses import dataclass, field
16
+
17
+ import numpy as np
18
+
19
+ from .. import envs
20
+ from . import camera as C
21
+ from .images import ImageRef
22
+
23
+ TABLE_Z = envs.TABLE_Z
24
+ # Workspace limits for commanded grasp-point positions (world frame, metres). Targets outside are
25
+ # clipped and the report says so.
26
+ WS_LO = np.array([-0.55, -0.45, TABLE_Z + 0.005])
27
+ WS_HI = np.array([0.35, 0.45, TABLE_Z + 0.50])
28
+ SPEED_RANGE = (0.02, 1.0)
29
+ PUSH_DIST_RANGE = (0.0, 0.40)
30
+ RUNUP_RANGE = (0.02, 0.30)
31
+
32
+ ACTION_TOOLS = ("move_to", "open_gripper", "close_gripper", "push")
33
+
34
+
35
+ def _num(desc):
36
+ return {"type": "number", "description": desc}
37
+
38
+
39
+ def _opt_num(desc):
40
+ return {"type": ["number", "null"], "description": desc}
41
+
42
+
43
+ def _fn(name, desc, props=None):
44
+ props = props or {}
45
+ return dict(name=name, description=desc,
46
+ parameters={"type": "object", "properties": props, "required": list(props),
47
+ "additionalProperties": False})
48
+
49
+
50
+ def tool_specs(privileged_locate=False, object_names=None, image_res=512):
51
+ """Backend-neutral tool list: [{name, description, parameters}]."""
52
+ specs = [
53
+ _fn("move_to",
54
+ "Move the gripper's grasp point (midway between the fingertips) in a straight line to the world "
55
+ "position (x, y, z) with the gripper pointing straight down and rotated to `yaw`. The gripper "
56
+ "opening is not changed. Returns whether the target was reached, the end-effector position, gripper "
57
+ "width, whether an object is held and whether the arm touched an object during the motion.",
58
+ {"x": _num("target x, metres (world frame; +x away from the robot)"),
59
+ "y": _num("target y, metres (world frame; +y to the robot's left)"),
60
+ "z": _num(f"target z, metres (table top is z = {TABLE_Z:.2f})"),
61
+ "yaw": _num("gripper rotation about the vertical axis in DEGREES; 0 = fingers close along the world "
62
+ "y axis, 90 = fingers close along the world x axis. Taken modulo 180 (the two-finger "
63
+ "gripper is symmetric): the controller uses the equivalent angle closest to the current "
64
+ "yaw within +-113 deg; the report gives the yaw actually used"),
65
+ "speed": _opt_num("straight-line speed in m/s (0.02-1.0); null = as fast as the controller allows "
66
+ "(about 0.6 m/s)")}),
67
+ _fn("open_gripper", "Open the gripper fully (the arm holds its position)."),
68
+ _fn("close_gripper", "Close the gripper (the arm holds its position). Closing on an object grasps it."),
69
+ _fn("push",
70
+ "Straight-line push with the closed gripper. The gripper closes, moves above the point `runup` metres "
71
+ "behind (x, y) (opposite to the push direction), descends to height z, sweeps along (dir_x, dir_y) "
72
+ "through (x, y) and stops `distance` metres past (x, y), moving at `speed` m/s, then lifts 12 cm. The "
73
+ "gripper is rotated automatically to a fixed orientation relative to the push direction.",
74
+ {"x": _num("x of the point where the push should start acting (e.g. the near face of the object), m"),
75
+ "y": _num("y of that point, m"),
76
+ "dir_x": _num("x component of the push direction (normalised internally)"),
77
+ "dir_y": _num("y component of the push direction"),
78
+ "distance": _num("how far past (x, y) the gripper travels, metres (0-0.40)"),
79
+ "speed": _num("sweep speed, m/s (0.02-1.0; the controller saturates near 0.6)"),
80
+ "z": _opt_num(f"height of the grasp point during the sweep, m; null = {TABLE_Z + 0.02:.2f} "
81
+ "(2 cm above the table)"),
82
+ "runup": _opt_num("distance behind (x, y) where the sweep starts, m (0.02-0.30); null = 0.06. A longer "
83
+ "run-up lets the gripper reach the commanded speed before contact.")}),
84
+ _fn("get_observation",
85
+ "Return the current camera images (agentview and wrist) and the robot's proprioceptive state."),
86
+ _fn("pixel_to_world",
87
+ f"Back-project an image pixel to a 3-D world point using the camera's depth map. (u, v) are pixel "
88
+ f"coordinates in the {image_res}x{image_res} image exactly as you received it: u = column from the "
89
+ f"left edge, v = row from the top edge. Returns the world point (x, y, z) of the surface seen at that "
90
+ f"pixel and its height above the table.",
91
+ {"camera": {"type": "string", "enum": ["agentview", "wrist"], "description": "which image"},
92
+ "u": _num("column (0 = left edge)"), "v": _num("row (0 = top edge)")}),
93
+ _fn("done",
94
+ "Finish the current attempt. Call this when you believe the task is complete (or you want to stop). "
95
+ "Give a short reason: what you did and whether you think it worked.",
96
+ {"reason": {"type": "string", "description": "short explanation"}}),
97
+ ]
98
+ if privileged_locate:
99
+ names = list(object_names or [])
100
+ prop = {"type": "string", "description": "object name"}
101
+ if names:
102
+ prop["enum"] = names
103
+ specs.insert(-1, _fn("locate",
104
+ "PRIVILEGED (ablation): return the true world position of an object's origin and its "
105
+ "axis-aligned bounding box.", {"object_name": prop}))
106
+ return specs
107
+
108
+
109
+ @dataclass
110
+ class ToolResult:
111
+ name: str
112
+ args: dict
113
+ ok: bool
114
+ report: dict
115
+ images: list = field(default_factory=list)
116
+ ended: bool = False
117
+ wall_s: float = 0.0
118
+ sim_steps: int = 0
119
+
120
+ def text(self):
121
+ return json.dumps(self.report, separators=(", ", ": "), default=_json_default)
122
+
123
+
124
+ def _json_default(o):
125
+ if isinstance(o, (np.floating,)):
126
+ return float(o)
127
+ if isinstance(o, (np.integer,)):
128
+ return int(o)
129
+ if isinstance(o, np.ndarray):
130
+ return o.tolist()
131
+ if isinstance(o, (np.bool_,)):
132
+ return bool(o)
133
+ raise TypeError(type(o))
134
+
135
+
136
+ def _r(v, nd=4):
137
+ return [round(float(x), nd) for x in v]
138
+
139
+
140
+ class ContactTracker:
141
+ """Collects the objects the robot touches. Contacts are checked after every MuJoCo substep (a control
142
+ step is 25 substeps; a fast push touches the object for less than one control step, so checking only at
143
+ control-step boundaries misses it -- measured). Implemented by wrapping `env.sim.step` once per env; the
144
+ wrapper only reads contacts and dispatches to the currently active tracker."""
145
+
146
+ def __init__(self, env):
147
+ self.env = env
148
+ m = env.sim.model
149
+ self.is_robot = np.zeros(m.ngeom, bool)
150
+ self.is_robot[envs.robot_geom_ids(env)] = True
151
+ self.names = []
152
+ self.obj_of = np.full(m.ngeom, -1, int)
153
+ for name in list(env.objects_dict) + list(getattr(env, "fixtures_dict", {}) or {}):
154
+ try:
155
+ ids = envs.obj_geom_ids(env, name)
156
+ except Exception: # fixtures without contact geoms
157
+ continue
158
+ self.obj_of[ids] = len(self.names)
159
+ self.names.append(name)
160
+ self.touched = set()
161
+ sim = env.sim
162
+ if not getattr(sim, "_lff_step_wrapped", False):
163
+ orig = sim.step
164
+
165
+ def step(*a, **k):
166
+ orig(*a, **k)
167
+ t = getattr(sim, "_lff_tracker", None)
168
+ if t is not None:
169
+ t.check()
170
+ sim.step = step
171
+ sim._lff_step_wrapped = True
172
+ sim._lff_tracker = self
173
+
174
+ def reset(self):
175
+ self.touched = set()
176
+
177
+ def check(self):
178
+ d = self.env.sim.data
179
+ n = d.ncon
180
+ if not n:
181
+ return
182
+ g1 = np.asarray(d.contact.geom1)[:n]
183
+ g2 = np.asarray(d.contact.geom2)[:n]
184
+ hit = np.concatenate([self.obj_of[g2[self.is_robot[g1]]], self.obj_of[g1[self.is_robot[g2]]]])
185
+ for i in set(hit[hit >= 0].tolist()):
186
+ self.touched.add(self.names[i])
187
+
188
+
189
+ def parse_args(raw):
190
+ if raw is None:
191
+ return {}
192
+ if isinstance(raw, dict):
193
+ return dict(raw)
194
+ raw = raw.strip()
195
+ return json.loads(raw) if raw else {}
196
+
197
+
198
+ class ToolExecutor:
199
+ """Executes agent tool calls on a task whose instance has just been reset (task.sk is live)."""
200
+
201
+ def __init__(self, task, inst, image_res=512, cams=("agentview", "wrist"), privileged_locate=False,
202
+ grasp_report="bool", jpeg_quality=90, image_sink=None):
203
+ self.task = task
204
+ self.inst = inst
205
+ self.env = task.env
206
+ self.sk = task.sk # keep our own reference: the scripted backend may swap task.sk for a proxy
207
+ self.image_res = int(image_res)
208
+ self.cams = tuple(cams)
209
+ self.privileged_locate = privileged_locate
210
+ self.grasp_report = grasp_report # "bool" | "name" | "none"
211
+ self.jpeg_quality = jpeg_quality
212
+ self.image_sink = image_sink # callable(ImageRef) -> path (saves the image)
213
+ self.objects = list(self.env.objects_dict)
214
+ self.tracker = ContactTracker(self.env) # task recorders / hooks on Skills are left untouched
215
+ self._depth_cache = {}
216
+ self.n_calls = 0
217
+
218
+ # ------------------------------------------------------------------ state
219
+ def eef_yaw_deg(self):
220
+ R = self.sk.eef_mat() @ self.sk.R0.T
221
+ return math.degrees(math.atan2(R[1, 0], R[0, 0]))
222
+
223
+ def held(self):
224
+ names = [o for o in self.objects if self.sk.holding(o)]
225
+ return names
226
+
227
+ def _holding_field(self, names):
228
+ if self.grasp_report == "name":
229
+ return names[0] if names else None
230
+ if self.grasp_report == "none":
231
+ return None
232
+ return bool(names)
233
+
234
+ def proprio(self):
235
+ believed = self.sk.eef_pos() - self.sk.bias
236
+ p = dict(eef_pos=_r(believed), eef_yaw_deg=round(self.eef_yaw_deg(), 1),
237
+ gripper="closed" if self.sk.grip > 0 else "open",
238
+ gripper_width_m=round(self.sk.gripper_width(), 4))
239
+ if self.grasp_report != "none":
240
+ p["holding_object"] = self._holding_field(self.held())
241
+ return p
242
+
243
+ def render(self, cam, res=None):
244
+ res = res or self.image_res
245
+ return envs.render(self.env, C.mj_cam(cam), res)
246
+
247
+ def observe(self, label=""):
248
+ imgs = []
249
+ for cam in self.cams:
250
+ ref = ImageRef(camera=cam, array=self.render(cam), label=f"{label} {cam}".strip())
251
+ if self.image_sink is not None:
252
+ self.image_sink(ref)
253
+ imgs.append(ref)
254
+ self._depth_cache = {}
255
+ return imgs
256
+
257
+ # ------------------------------------------------------------------ dispatch
258
+ def call(self, name, raw_args):
259
+ t0 = time.time()
260
+ n0 = self.sk.n_steps
261
+ self.n_calls += 1
262
+ try:
263
+ args = parse_args(raw_args)
264
+ except Exception as e:
265
+ return ToolResult(name, {"_raw": str(raw_args)}, False, dict(ok=False, error=f"arguments are not valid JSON: {e}"),
266
+ wall_s=time.time() - t0)
267
+ fn = getattr(self, f"_t_{name}", None)
268
+ if fn is None or (name == "locate" and not self.privileged_locate):
269
+ return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
270
+ try:
271
+ res = fn(**args)
272
+ except TypeError as e:
273
+ res = ToolResult(name, args, False, dict(ok=False, error=f"bad arguments: {e}"))
274
+ except ValueError as e:
275
+ res = ToolResult(name, args, False, dict(ok=False, error=str(e)))
276
+ res.args = args
277
+ res.wall_s = time.time() - t0
278
+ res.sim_steps = self.sk.n_steps - n0
279
+ if res.sim_steps:
280
+ self._depth_cache = {}
281
+ hook = getattr(self.task, "on_agent_tool", None)
282
+ if hook is not None:
283
+ hook(self.inst, name, args, res.report)
284
+ drain = getattr(self.task, "drain_events", None) # task-side events (e.g. L6: an item slipped)
285
+ if drain is not None:
286
+ ev = drain()
287
+ if ev:
288
+ res.report["events"] = list(ev)
289
+ return res
290
+
291
+ # ------------------------------------------------------------------ helpers
292
+ def _clip_xyz(self, xyz):
293
+ xyz = np.asarray(xyz, float)
294
+ if not np.all(np.isfinite(xyz)):
295
+ raise ValueError("non-finite coordinates")
296
+ c = np.clip(xyz, WS_LO, WS_HI)
297
+ return c, (None if np.allclose(c, xyz) else _r(c))
298
+
299
+ @staticmethod
300
+ def _clip(v, lo_hi, what):
301
+ v = float(v)
302
+ if not math.isfinite(v):
303
+ raise ValueError(f"{what} must be finite")
304
+ return float(np.clip(v, *lo_hi))
305
+
306
+ def _action_report(self, name, extra=None):
307
+ names = self.held()
308
+ rep = dict(ok=True, tool=name)
309
+ if extra:
310
+ rep.update(extra)
311
+ rep.update(self.proprio())
312
+ if self.grasp_report == "name":
313
+ rep["touched_objects"] = sorted(self.tracker.touched)
314
+ elif self.grasp_report == "bool":
315
+ rep["touched_object"] = bool(self.tracker.touched)
316
+ rep["sim_time_s"] = round(self.sk.n_steps * 0.05, 2)
317
+ return rep
318
+
319
+ # ------------------------------------------------------------------ tools
320
+ def _t_move_to(self, x, y, z, yaw, speed=None):
321
+ tgt, clipped = self._clip_xyz([x, y, z])
322
+ spd = None if speed is None else self._clip(speed, SPEED_RANGE, "speed")
323
+ self.tracker.reset()
324
+ rep = self.sk.move_to(tgt, yaw=math.radians(float(yaw)), speed=spd) # Skills wraps yaw mod pi
325
+ extra = dict(reached=bool(rep["reached"]), yaw_used_deg=round(math.degrees(self.sk.yaw), 1))
326
+ if clipped:
327
+ extra["target_clipped_to"] = clipped
328
+ return ToolResult("move_to", {}, True, self._action_report("move_to", extra))
329
+
330
+ def _t_open_gripper(self):
331
+ self.tracker.reset()
332
+ self.sk.set_gripper(False)
333
+ return ToolResult("open_gripper", {}, True, self._action_report("open_gripper"))
334
+
335
+ def _t_close_gripper(self):
336
+ self.tracker.reset()
337
+ self.sk.set_gripper(True)
338
+ return ToolResult("close_gripper", {}, True, self._action_report("close_gripper"))
339
+
340
+ def _t_push(self, x, y, dir_x, dir_y, distance, speed, z=None, runup=None):
341
+ d = np.array([float(dir_x), float(dir_y)])
342
+ if not np.all(np.isfinite(d)) or np.linalg.norm(d) < 1e-6:
343
+ raise ValueError("push direction must be a non-zero vector")
344
+ start, clipped = self._clip_xyz([x, y, TABLE_Z + 0.02 if z is None else z])
345
+ dist = self._clip(distance, PUSH_DIST_RANGE, "distance")
346
+ spd = self._clip(speed, SPEED_RANGE, "speed")
347
+ pre = 0.06 if runup is None else self._clip(runup, RUNUP_RANGE, "runup")
348
+ self.tracker.reset()
349
+ rep = self.sk.push(start[:2], d, dist, spd, z=float(start[2]), pre=pre)
350
+ extra = dict(sweep_reached=bool(rep["reached"]))
351
+ if clipped:
352
+ extra["start_clipped_to"] = clipped
353
+ return ToolResult("push", {}, True, self._action_report("push", extra))
354
+
355
+ def _t_get_observation(self):
356
+ imgs = self.observe(label="requested")
357
+ return ToolResult("get_observation", {}, True, dict(ok=True, images=[i.camera for i in imgs], **self.proprio()),
358
+ images=imgs)
359
+
360
+ def _t_pixel_to_world(self, camera, u, v):
361
+ cam = str(camera)
362
+ if cam not in C.CAMERAS:
363
+ raise ValueError(f"camera must be one of {sorted(C.CAMERAS)}")
364
+ if cam not in self._depth_cache:
365
+ self._depth_cache[cam] = C.render_depth(self.env, cam, self.image_res)
366
+ r = C.pixel_to_world(self.env, cam, float(u), float(v), self.image_res, depth=self._depth_cache[cam])
367
+ rep = dict(ok=True, camera=cam, u=float(u), v=float(v), world_xyz=_r(r["xyz"]),
368
+ height_above_table_m=round(float(r["xyz"][2] - TABLE_Z), 4), depth_m=round(r["depth"], 4))
369
+ if not r["valid"]:
370
+ rep["warning"] = "pixel shows the far background; the point is unreliable"
371
+ return ToolResult("pixel_to_world", {}, True, rep)
372
+
373
+ def _t_locate(self, object_name):
374
+ if object_name not in self.env.objects_dict:
375
+ raise ValueError(f"unknown object {object_name!r}; known: {self.objects}")
376
+ lo, hi = self._aabb(object_name)
377
+ p = envs.obj_pos(self.env, object_name)
378
+ return ToolResult("locate", {}, True, dict(ok=True, object=object_name, position=_r(p), bbox_min=_r(lo),
379
+ bbox_max=_r(hi)))
380
+
381
+ def _aabb(self, name):
382
+ m, d = self.env.sim.model, self.env.sim.data
383
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
384
+ for g in envs.obj_geom_ids(self.env, name):
385
+ R = d.geom_xmat[g].reshape(3, 3)
386
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
387
+ h = np.abs(R) @ m.geom_aabb[g, 3:]
388
+ lo, hi = np.minimum(lo, c - h), np.maximum(hi, c + h)
389
+ return lo, hi
390
+
391
+ def _t_done(self, reason=""):
392
+ return ToolResult("done", {}, True, dict(ok=True, ended=True), ended=True)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/__init__.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness adapters (docs/15): one way to plug any agent harness into a robot_server session.
2
+
3
+ ours reference driver scripts/api_player.py (main table)
4
+ claude_code Claude Code CLI, --bare, only our MCP tools (arm B)
5
+ claude_code_full Claude Code CLI without --bare: full system prompt, still one-time dirs and only MCP (arm B')
6
+ codex Codex CLI exec (+ exec resume on early exit), one-time CODEX_HOME, only our MCP tools (arm F)
7
+ rpent_codex RPent (robot harness framework) on Codex: RPent's loop and prompt, the main table's Codex config,
8
+ tools through the episode's tool gateway (docs/18, lffbench/harnesses/rpent.py)
9
+ dsh DeepSeek Harness (`dsh --profile headless`), only our MCP tools, one-time dirs
10
+
11
+ Use scripts/harness_run.py (one session) or scripts/api_batch.py start --harness ... (batches).
12
+ """
13
+ import json
14
+ import importlib
15
+ import os
16
+ import sys
17
+
18
+ from .base import EpisodeSpec, HarnessAdapter, HarnessRefused, first_message_text # noqa: F401
19
+
20
+ # A new Codex-based Robot Harness registers here; both single-run and batch CLIs
21
+ # derive their choices, provider and common options from this registry.
22
+ ROBOT_HARNESSES = {
23
+ "rpent_codex": ("rpent", "RPentCodex"),
24
+ "sensenova_codex": ("sensenova", "SenseNovaCodex"),
25
+ "embodied_evo_codex": ("embodied_evo", "EmbodiedEvoCodex"),
26
+ }
27
+ NAMES = ("ours", "claude_code", "claude_code_full", "codex", "dsh", *ROBOT_HARNESSES)
28
+ PROVIDER = dict(claude_code="anthropic", claude_code_full="anthropic", codex="openai", dsh="deepseek",
29
+ **{name: "openai" for name in ROBOT_HARNESSES})
30
+
31
+
32
+ def get_adapter(name, **kw):
33
+ if name == "ours":
34
+ from .reference import Reference
35
+ return Reference(**kw)
36
+ if name == "claude_code":
37
+ from .claude_code import ClaudeCode
38
+ return ClaudeCode(**kw)
39
+ if name == "claude_code_full":
40
+ from .claude_code import ClaudeCodeFull
41
+ return ClaudeCodeFull(**kw)
42
+ if name == "codex":
43
+ from .codex import Codex
44
+ return Codex(**kw)
45
+ if name == "dsh":
46
+ from .dsh import DeepSeekHarness
47
+ return DeepSeekHarness(**kw)
48
+ if name in ROBOT_HARNESSES:
49
+ module, cls = ROBOT_HARNESSES[name]
50
+ return getattr(importlib.import_module("." + module, __name__), cls)(**kw)
51
+ raise ValueError(f"unknown harness {name!r}; one of {NAMES}")
52
+
53
+
54
+ def render_first_message(ep):
55
+ """Call `status` once over HTTP (exactly as the reference driver does before its first turn) and build the first
56
+ user message for a native harness. Returns (text, status_json)."""
57
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
58
+ "scripts"))
59
+ from api_player import call_server # noqa: E402
60
+ st = json.loads(call_server(ep.port, ep.token, "status", {}))
61
+ readme = open(os.path.join(ep.sandbox, "README.md")).read()
62
+ status_json = json.dumps(st)
63
+ return first_message_text(readme, status_json), status_json
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/base.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness adapter interface (docs/15 §3).
2
+
3
+ An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log
4
+ dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations).
5
+ Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server /
6
+ reference driver enforce them identically for every harness.
7
+
8
+ name stable harness name (the "harness" column of a table)
9
+ capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source;
10
+ a missing item makes the class definition fail (so the import fails)
11
+ version() the actual installed version (probed before launch)
12
+ prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env
13
+ launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle
14
+ collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason
15
+ audit(h) tool list, preset prompt, memory, state left behind, violations
16
+ """
17
+ import dataclasses
18
+ import json
19
+ import os
20
+ import secrets
21
+ import shutil
22
+ import signal
23
+ import subprocess
24
+ import time
25
+
26
+ from . import contract as C
27
+
28
+ EVIDENCE = ("launch", "stream", "server", "probe", "preflight")
29
+
30
+ REQUIRED = {
31
+ "only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use",
32
+ "images_reach_model": "view_images returns the image bytes to the model unchanged",
33
+ "non_persistent_session": "nothing of the session is written to disk for later runs",
34
+ "pinned_version": "the harness version (and binary hash) is recorded and pinned",
35
+ "machine_readable_events": "a machine-readable event stream of the whole run",
36
+ "tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)",
37
+ "model_and_effort": "model and reasoning effort can be set and are visible in the request",
38
+ }
39
+ FORBIDDEN = {
40
+ "persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)",
41
+ "instruction_file_injection": "instruction files picked up from the work / config / home dir",
42
+ "web_access": "web search / fetch",
43
+ "host_file_read": "reading host files outside the episode workspace",
44
+ "builtin_shell": "a shell of the harness itself (outside our jailed shell tool)",
45
+ "subagent_delegation": "spawning sub-agents",
46
+ "background_execution": "background tasks that outlive a tool call",
47
+ }
48
+
49
+
50
+ @dataclasses.dataclass(frozen=True)
51
+ class Cap:
52
+ status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial"
53
+ evidence: str # one of EVIDENCE
54
+ note: str = ""
55
+
56
+
57
+ PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")
58
+ NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
59
+ NO_PROXY_LOCAL = "127.0.0.1,localhost,::1"
60
+
61
+
62
+ def proxy_env(environ=None):
63
+ """The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines
64
+ that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list.
65
+ Not part of config_sha256 (machine plumbing, not harness configuration)."""
66
+ environ = os.environ if environ is None else environ
67
+ e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)}
68
+ if e:
69
+ e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS})
70
+ return e
71
+
72
+
73
+ class CapabilityError(TypeError):
74
+ pass
75
+
76
+
77
+ def check_capabilities(name, caps):
78
+ if not isinstance(caps, dict):
79
+ raise CapabilityError(f"{name}: capabilities must be a dict")
80
+ missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps]
81
+ extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN]
82
+ if missing or extra:
83
+ raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}")
84
+ for k, c in caps.items():
85
+ if not isinstance(c, Cap) or c.evidence not in EVIDENCE:
86
+ raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})")
87
+ ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial")
88
+ if c.status not in ok:
89
+ raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}")
90
+
91
+
92
+ class HarnessRefused(RuntimeError):
93
+ """Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one."""
94
+
95
+
96
+ @dataclasses.dataclass
97
+ class EpisodeSpec:
98
+ session_path: str
99
+ log_dir: str
100
+ sandbox: str
101
+ port: int
102
+ token: str
103
+ max_tool_calls: int
104
+ model: str
105
+ effort: str
106
+ provider: str = ""
107
+ task: str = ""
108
+ seed: int = 0
109
+ extra: dict = dataclasses.field(default_factory=dict)
110
+
111
+ @classmethod
112
+ def from_session(cls, session_path, model, effort, provider="", **extra):
113
+ session_path = os.path.abspath(session_path)
114
+ log_dir = os.path.dirname(session_path)
115
+ sess = json.load(open(session_path))
116
+ iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
117
+ st = C.session_start(log_dir)
118
+ return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]),
119
+ token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort,
120
+ provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra)
121
+
122
+
123
+ @dataclasses.dataclass
124
+ class LaunchSpec:
125
+ argv: list # full argv (the first message may be one element)
126
+ env: dict # the complete environment of the harness process (nothing else is inherited)
127
+ cwd: str
128
+ run_dir: str = "" # one-time dir tree, removed after audit
129
+ state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...)
130
+ first_message: str = ""
131
+ config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote
132
+ stdout_path: str = ""
133
+ stderr_path: str = ""
134
+ redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log
135
+ preflight: dict = dataclasses.field(default_factory=dict)
136
+ timeout_s: float = 10800
137
+
138
+
139
+ @dataclasses.dataclass
140
+ class RunHandle:
141
+ spec: LaunchSpec
142
+ ep: EpisodeSpec
143
+ proc: object = None
144
+ pid: int = 0
145
+ t_start: float = 0.0
146
+ t_end: float = 0.0
147
+ exit_code: int = None
148
+ exit_reason: str = ""
149
+ env_observed_keys: list = None # read from /proc/<pid>/environ right after the start
150
+ info: dict = dataclasses.field(default_factory=dict)
151
+
152
+
153
+ def env_keys_of(pid):
154
+ try:
155
+ raw = open(f"/proc/{pid}/environ", "rb").read()
156
+ except OSError:
157
+ return None
158
+ return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv})
159
+
160
+
161
+ def new_run_dir(root="/tmp/lffrun"):
162
+ """/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses)."""
163
+ os.makedirs(root, exist_ok=True)
164
+ while True:
165
+ d = os.path.join(root, secrets.token_hex(6))
166
+ try:
167
+ os.mkdir(d, 0o700)
168
+ return d
169
+ except FileExistsError:
170
+ continue
171
+
172
+
173
+ def binary_info(path):
174
+ real = os.path.realpath(path)
175
+ return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None)
176
+
177
+
178
+ class HarnessAdapter:
179
+ name = None
180
+ capabilities = None
181
+ uses_mcp = False
182
+ uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for
183
+ # this adapter: MCP adapters through the MCP server, framework adapters
184
+ # (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN
185
+ clean_dirs = () # keys of spec.state_dirs that must be empty at launch
186
+ clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json)
187
+ ancestor_files = () # instruction files that must not exist in the work dir or any ancestor
188
+ unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read)
189
+ jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4)
190
+ can_resume = False # resume(): the CLI can continue its session with one more user message
191
+
192
+ def clean_state_problems(self, spec):
193
+ """Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an
194
+ ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md)."""
195
+ p = []
196
+ if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd):
197
+ p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}")
198
+ for k in self.clean_dirs:
199
+ d = spec.state_dirs.get(k)
200
+ left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else []
201
+ if left:
202
+ p.append(f"{k} dir not empty: {sorted(left)[:5]}")
203
+ d = spec.cwd
204
+ while d and d != "/":
205
+ d = os.path.dirname(d)
206
+ for f in self.ancestor_files:
207
+ if os.path.exists(os.path.join(d, f)):
208
+ p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}")
209
+ return p
210
+
211
+ def __init_subclass__(cls, **kw):
212
+ super().__init_subclass__(**kw)
213
+ if cls.name is None:
214
+ raise CapabilityError(f"{cls.__name__}: no name")
215
+ check_capabilities(cls.name, cls.capabilities)
216
+
217
+ # -------------------------------------------------------------------------------------------- interface
218
+ def version(self):
219
+ raise NotImplementedError
220
+
221
+ def prepare(self, ep, first_message):
222
+ raise NotImplementedError
223
+
224
+ def preflight(self, spec, ep):
225
+ """Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused."""
226
+ return dict(skipped=True)
227
+
228
+ def collect(self, h):
229
+ raise NotImplementedError
230
+
231
+ def audit(self, h):
232
+ raise NotImplementedError
233
+
234
+ # -------------------------------------------------------------------------------------------- shared
235
+ def mcp_server_command(self, python, script, args):
236
+ """(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it."""
237
+ if self.jail is not None:
238
+ return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"})
239
+ return python, [script] + list(args)
240
+
241
+ def jailed_argv(self, argv, env, cwd, dirs):
242
+ """argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back."""
243
+ return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv)
244
+
245
+ def jail_info(self):
246
+ return self.jail.info() if self.jail is not None else dict(enabled=False)
247
+
248
+ def auth_info(self):
249
+ """How the harness authenticates to the model API (for harness.json; never a secret)."""
250
+ return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {}))
251
+
252
+ def launch(self, spec, ep, skip_preflight=False):
253
+ if not self.unsafe_skip_clean_check:
254
+ probs = self.clean_state_problems(spec)
255
+ if probs:
256
+ spec.preflight = dict(problems=probs)
257
+ raise HarnessRefused("clean-state check: " + "; ".join(probs))
258
+ spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep)
259
+ out = open(spec.stdout_path, "wb")
260
+ err = open(spec.stderr_path, "wb")
261
+ h = RunHandle(spec=spec, ep=ep, t_start=time.time())
262
+ argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
263
+ h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
264
+ stderr=err, start_new_session=True)
265
+ h.pid = h.proc.pid
266
+ for _ in range(20): # the exec has happened once /proc/<pid>/environ differs from ours
267
+ keys = env_keys_of(h.pid)
268
+ if keys is not None and set(keys) == set(spec.env):
269
+ break
270
+ time.sleep(0.05)
271
+ h.env_observed_keys = env_keys_of(h.pid)
272
+ return h
273
+
274
+ def resume_argv(self, h, message):
275
+ """argv that continues the run's session with one more user message (adapters with can_resume)."""
276
+ raise NotImplementedError
277
+
278
+ def resume(self, h, message):
279
+ """Continue the run's session with one more user message, after the CLI exited before the episode was over
280
+ (scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output
281
+ is appended to the same stdout / stderr files."""
282
+ spec = h.spec
283
+ argv = self.resume_argv(h, message)
284
+ out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab")
285
+ jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
286
+ h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
287
+ stderr=err, start_new_session=True)
288
+ h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, ""
289
+ keys = None
290
+ for _ in range(20):
291
+ keys = env_keys_of(h.pid)
292
+ if keys is not None and set(keys) == set(spec.env):
293
+ break
294
+ time.sleep(0.05)
295
+ h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message,
296
+ argv=[("<message>" if x == message else x) for x in argv],
297
+ env_observed_keys=keys))
298
+ return h
299
+
300
+ def wait(self, h, timeout=None):
301
+ try:
302
+ h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s)
303
+ h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}"
304
+ except subprocess.TimeoutExpired:
305
+ self.kill(h)
306
+ h.exit_reason = "timeout"
307
+ h.t_end = time.time()
308
+ return h
309
+
310
+ @staticmethod
311
+ def kill(h):
312
+ try:
313
+ os.killpg(h.proc.pid, signal.SIGTERM)
314
+ h.exit_code = h.proc.wait(timeout=20)
315
+ except ProcessLookupError:
316
+ pass
317
+ except subprocess.TimeoutExpired:
318
+ os.killpg(h.proc.pid, signal.SIGKILL)
319
+ h.exit_code = h.proc.wait()
320
+
321
+ def logged_argv(self, spec):
322
+ return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)]
323
+
324
+ def cleanup(self, spec):
325
+ if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir):
326
+ shutil.rmtree(spec.run_dir, ignore_errors=True)
327
+ for d in spec.state_dirs.values():
328
+ if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d):
329
+ shutil.rmtree(d, ignore_errors=True)
330
+ if self.jail is not None:
331
+ self.jail.close()
332
+
333
+
334
+ def gateway_env(log_dir):
335
+ """{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose
336
+ process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before
337
+ launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the
338
+ gateway's, never robot_server's."""
339
+ d = json.load(open(os.path.join(log_dir, "gateway.json")))
340
+ return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]}
341
+
342
+
343
+ def snapshot_tree(root):
344
+ """Relative paths of all files under root (to list what a harness left behind)."""
345
+ out = []
346
+ for dp, dn, fn in os.walk(root):
347
+ for f in fn:
348
+ out.append(os.path.relpath(os.path.join(dp, f), root))
349
+ return sorted(out)
350
+
351
+
352
+ def first_message_text(readme, status_json):
353
+ """What a native harness gets as its first user message: the reference driver's instructions (preamble + README,
354
+ byte-identical) followed by its first user turn (the status report). The reference driver sends the same two
355
+ strings as system prompt and first user message; native harnesses keep their own system prompt."""
356
+ from .contract import tool_schemas
357
+ _, preamble = tool_schemas()
358
+ return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json
359
+
360
+
361
+ def reference_instructions(readme):
362
+ from .contract import tool_schemas
363
+ _, preamble = tool_schemas()
364
+ return preamble + readme
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/claude_code.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Claude Code CLI as a native harness (docs/15 §3.3; flags measured in research_notes/harness接入调研/02 §2.1).
2
+
3
+ Two variants:
4
+ claude_code arm B : -p --bare (system prompt ~400 chars, no CLAUDE.md / auto-memory / hooks / plugins)
5
+ claude_code_full arm B': same but without --bare: Claude Code's full system prompt; still a one-time config dir and
6
+ HOME, an empty opaque work dir, --tools "" and only our MCP server
7
+ Both: process env is exactly the whitelist (env -i equivalent; plus the calling HTTP(S) proxy, base.proxy_env),
8
+ HOME / CLAUDE_CONFIG_DIR / TMPDIR are one-time dirs
9
+ under /tmp/lffstate/<hex>, the work dir is /tmp/lffrun/<12 hex> (its path is written into the system prompt), the MCP
10
+ server is scripts/mcp_robot_server.py on the run's session.
11
+
12
+ Two ways to authenticate (auth=):
13
+ apikey ANTHROPIC_API_KEY (api_env)
14
+ oauth a Claude subscription: the long-lived token of `claude setup-token`, passed as CLAUDE_CODE_OAUTH_TOKEN
15
+ (api_env; never taken from the calling environment). claude_code_full only: --bare reads nothing but
16
+ ANTHROPIC_API_KEY / apiKeyHelper (2.1.267 --help).
17
+ Measured with 2.1.267 against the fake server (2026-10-20): the same single request in both modes, identical system
18
+ prompt, tools, messages and parameters; oauth sends Authorization: Bearer instead of x-api-key, two more beta flags
19
+ (oauth-2025-04-20, extended-cache-ttl-2025-04-11) and cache_control ttl=1h. Pins are per auth mode (pin name
20
+ claude_code_full-oauth).
21
+
22
+ Early exit: `claude -p` ends when the model replies without a tool call, also mid-episode. scripts/harness_run.py then
23
+ sends the reference driver's nudge with `claude -p <nudge> --resume <session>` (resume_argv), as for Codex. Hence no
24
+ --no-session-persistence: the session transcript is kept in the one-time CLAUDE_CONFIG_DIR (removed after the run);
25
+ the audit allows only this run's session. Measured against the fake server: the resumed request has the same system
26
+ prompt, tools, parameters and headers, then the earlier turns and the nudge as a user message.
27
+
28
+ Fail-closed launch: before the real run the same argv / env is started once against a local fake Anthropic server
29
+ (free) with a schema-only MCP server; the first request's tool list, system prompt, harness-added message prefix and
30
+ request parameters are normalised and hashed, and the launch is refused unless the hash equals the pinned one
31
+ (pins/claude_code*.json, written by tests/harness_selfcheck after the self-check passed). During the real run the
32
+ stream's init event is checked again (tool list); on a mismatch the process is killed.
33
+ """
34
+ import copy
35
+ import json
36
+ import os
37
+ import re
38
+ import shutil
39
+ import subprocess
40
+ import sys
41
+ import time
42
+
43
+ from . import contract as C
44
+ from . import pins
45
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
46
+ new_run_dir, proxy_env, snapshot_tree)
47
+ from .fakeapi import FakeAnthropic
48
+ from .trajectory import TrajWriter, strip_mcp
49
+
50
+ ROOT = C.ROOT
51
+ MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
52
+ MCP_TOOLS = ["mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images"]
53
+ BASE_PATH = "/usr/bin:/bin"
54
+ OAUTH_KEY = "CLAUDE_CODE_OAUTH_TOKEN"
55
+ PREFLIGHT_CREDENTIAL = dict(apikey=("ANTHROPIC_API_KEY", "sk-preflight-not-a-key"),
56
+ oauth=(OAUTH_KEY, "sk-ant-oat01-" + "x" * 95 + "AA")) # dummies, only for the fake server
57
+
58
+
59
+ def claude_bin():
60
+ return os.environ.get("LFF_CLAUDE_BIN") or shutil.which("claude") or "claude"
61
+
62
+
63
+ def _norm(s, spec):
64
+ """Remove what legitimately differs between runs from preset prompt text: paths of the one-time dirs, dates."""
65
+ for k, v in sorted(dict(spec.state_dirs, cwd=spec.cwd).items(), key=lambda kv: -len(kv[1])):
66
+ s = s.replace(v, f"<{k.upper()}>")
67
+ s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
68
+ s = re.sub(r"-tmp-lffrun-[0-9a-f]{12}", "<RUNDIR_SLUG>", s) # auto-memory dir name derived from the cwd
69
+ s = re.sub(r"(cc_version=\d+\.\d+\.\d+)\.[0-9a-f]+", r"\1.<X>", s) # billing header suffix varies per request
70
+ s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
71
+ s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
72
+ s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "<UUID>", s)
73
+ return s
74
+
75
+
76
+ def request_fingerprint(body, headers, spec, first_message):
77
+ """Normalised preset part of the first request + the checks that do not need a pin."""
78
+ problems = []
79
+ system = body.get("system")
80
+ if isinstance(system, str):
81
+ system = [dict(type="text", text=system)]
82
+ sys_blocks = [dict(text=_norm(b.get("text", ""), spec), cache=bool(b.get("cache_control"))) for b in system or []]
83
+ tools = [dict(name=t.get("name"), description=t.get("description"), input_schema=t.get("input_schema"))
84
+ for t in body.get("tools") or []]
85
+ if [t["name"] for t in tools] != MCP_TOOLS:
86
+ problems.append(f"tool list is {[t['name'] for t in tools]}, expected {MCP_TOOLS}")
87
+ msgs = body.get("messages") or []
88
+ first = msgs[0] if msgs else {}
89
+ content = first.get("content")
90
+ if isinstance(content, str):
91
+ content = [dict(type="text", text=content)]
92
+ prefix, found = [], False
93
+ for b in content or []:
94
+ if b.get("type") == "text" and b.get("text") == first_message:
95
+ found = True
96
+ break
97
+ prefix.append(_norm(b.get("text", "") if b.get("type") == "text" else json.dumps(b, sort_keys=True), spec))
98
+ if not found:
99
+ problems.append("the first user message does not contain our first message byte-for-byte as one block")
100
+ params = {k: body.get(k) for k in ("model", "max_tokens", "thinking", "output_config", "context_management",
101
+ "temperature", "top_p", "top_k", "tool_choice")}
102
+ fp = dict(system=sys_blocks, tools=tools, user_prefix=prefix, params=params,
103
+ anthropic_beta=sorted((headers.get("anthropic-beta") or headers.get("Anthropic-Beta") or "").split(",")),
104
+ system_chars=sum(len(b.get("text", "")) for b in system or []))
105
+ return fp, problems
106
+
107
+
108
+ class ClaudeCode(HarnessAdapter):
109
+ name = "claude_code"
110
+ bare = True
111
+ uses_mcp = True
112
+ clean_dirs = ("home", "config", "tmp")
113
+ ancestor_files = ("CLAUDE.md", "CLAUDE.local.md", ".claude", "AGENTS.md")
114
+ can_resume = True
115
+ capabilities = dict(
116
+ only_benchmark_tools=Cap("yes", "preflight", '--tools "" + --strict-mcp-config: request tools = 3 MCP tools'),
117
+ images_reach_model=Cap("yes", "probe", "MCP image content forwarded as image blocks, md5 equal"),
118
+ non_persistent_session=Cap("yes", "probe", "only this run's session (kept for -p --resume) in the one-time "
119
+ "config dir, removed after the run"),
120
+ pinned_version=Cap("yes", "launch", "claude --version + binary sha256 in harness.json; pin per version"),
121
+ machine_readable_events=Cap("yes", "stream", "--output-format stream-json --verbose"),
122
+ tool_calls_logged=Cap("yes", "stream", "tool_use / tool_result in stream + mcp_transcript + events.jsonl"),
123
+ model_and_effort=Cap("yes", "preflight", "--model / --effort; request output_config.effort checked"),
124
+ persistent_memory=Cap("absent", "probe", "--bare: no auto-memory; canaries never reach the request"),
125
+ instruction_file_injection=Cap("absent", "probe", "--bare: CLAUDE.md discovery off; canaries absent"),
126
+ web_access=Cap("absent", "preflight", "no WebFetch / WebSearch tool in the request"),
127
+ host_file_read=Cap("absent", "probe", "no Read tool; MCP shell is jailed; view_images confined"),
128
+ builtin_shell=Cap("absent", "preflight", "no Bash tool in the request"),
129
+ subagent_delegation=Cap("absent", "preflight", "no Agent / Task tool in the request"),
130
+ background_execution=Cap("absent", "preflight", "no Bash / Monitor tool in the request"),
131
+ )
132
+
133
+ def __init__(self, api_env=None, max_budget_usd=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
134
+ python=None, extra_args=None, jail=False, auth="apikey"):
135
+ """api_env: the only API variables passed to the harness: {"ANTHROPIC_API_KEY": ...} (auth="apikey") or
136
+ {"CLAUDE_CODE_OAUTH_TOKEN": ...} (auth="oauth", a subscription token of `claude setup-token`), optional
137
+ "ANTHROPIC_BASE_URL". Never inherited from the calling environment. jail: run the CLI in the
138
+ native-harness jail (lffbench/harnesses/jail.py; /proc stays the host's: Bun needs it)."""
139
+ if auth not in PREFLIGHT_CREDENTIAL:
140
+ raise ValueError(f"auth must be one of {sorted(PREFLIGHT_CREDENTIAL)}, not {auth!r}")
141
+ if auth == "oauth" and self.bare:
142
+ raise ValueError("claude_code (--bare) authenticates only with ANTHROPIC_API_KEY / apiKeyHelper; "
143
+ "use claude_code_full for a subscription token")
144
+ other = PREFLIGHT_CREDENTIAL["oauth" if auth == "apikey" else "apikey"][0]
145
+ if other in (api_env or {}):
146
+ raise ValueError(f"auth={auth}: api_env must not hold {other} (the CLI would use it instead)")
147
+ self.auth = auth
148
+ if jail:
149
+ from .jail import HarnessJail
150
+ self.jail = HarnessJail(claude_bin(), proc="host")
151
+ self.api_env = dict(api_env or {})
152
+ self.proxy = proxy_env()
153
+ self.max_budget_usd = max_budget_usd
154
+ self.timeout_s = timeout_s
155
+ self.pins_dir = pins_dir
156
+ self.allow_unpinned = allow_unpinned
157
+ self.python = python or sys.executable
158
+ self.extra_args = list(extra_args or [])
159
+ self._version = None
160
+
161
+ # ------------------------------------------------------------------------------------------------ version
162
+ def version(self):
163
+ if self._version is None:
164
+ b = claude_bin()
165
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent"), capture_output=True,
166
+ text=True, timeout=60)
167
+ v = (out.stdout.strip().split() or ["?"])[0]
168
+ self._version = dict(version=v, binary=binary_info(b))
169
+ return self._version
170
+
171
+ def pin_key(self, ep):
172
+ v = self.version()
173
+ name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
174
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
175
+
176
+ def auth_info(self):
177
+ key = PREFLIGHT_CREDENTIAL[self.auth][0]
178
+ return dict(mode=self.auth, credential_var=key, credential_set=bool(self.api_env.get(key)),
179
+ keys=sorted(self.api_env))
180
+
181
+ # ------------------------------------------------------------------------------------------------ prepare
182
+ def mcp_config(self, session_path=None, describe=False):
183
+ """describe: for config_sha256 only (jailed, no relay is set up for it)."""
184
+ args = ["--session", session_path] if session_path else ["--schema-only"]
185
+ if describe or self.jail is None:
186
+ cmd, a = ("<jail relay>" if self.jail is not None else self.python), [MCP_SCRIPT] + args
187
+ else:
188
+ cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args)
189
+ return {"mcpServers": {"lff": {"type": "stdio", "command": cmd, "args": a, "env": {"PATH": BASE_PATH}}}}
190
+
191
+ def argv(self, spec_paths, ep, first_message):
192
+ a = [claude_bin(), "-p", first_message]
193
+ if self.bare:
194
+ a.append("--bare")
195
+ a += ["--tools", "", "--strict-mcp-config", "--mcp-config", spec_paths["mcp_config"],
196
+ "--allowedTools", ",".join(MCP_TOOLS), "--permission-mode", "dontAsk", "--disable-slash-commands",
197
+ "--output-format", "stream-json", "--verbose", "--model", ep.model, "--effort", ep.effort]
198
+ if self.max_budget_usd:
199
+ a += ["--max-budget-usd", str(self.max_budget_usd)]
200
+ return a + self.extra_args
201
+
202
+ @staticmethod
203
+ def session_ids(stdout_path):
204
+ """Session ids of the init events in the stream, in order (one per launch / resume)."""
205
+ out = []
206
+ try:
207
+ for line in open(stdout_path, encoding="utf-8", errors="replace"):
208
+ if line.startswith("{") and '"init"' in line:
209
+ d = json.loads(line)
210
+ if d.get("type") == "system" and d.get("subtype") == "init" and d.get("session_id"):
211
+ out.append(d["session_id"])
212
+ except (OSError, ValueError):
213
+ pass
214
+ return out
215
+
216
+ def resume_argv(self, h, message):
217
+ """`claude -p <message> ... --resume <session>`: the launch's flags unchanged, the message in the place of the
218
+ first message (right after -p, before the variadic --allowedTools)."""
219
+ sids = self.session_ids(h.spec.stdout_path)
220
+ if not sids:
221
+ raise HarnessRefused("resume: no session id in the stream")
222
+ a = list(h.spec.argv)
223
+ return a[:2] + [message] + a[3:] + ["--resume", sids[0]]
224
+
225
+ def env(self, state):
226
+ # CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: measured 2026-10-21 with 2.1.299 and claude-fable-5-1: when the model's
227
+ # safeguards flag a request, the CLI otherwise answers it, and the rest of the session, with another model
228
+ # (claude-opus-4-8) under the requested model's name; with it, a flagged request ends as a refusal
229
+ # (system event model_refusal_no_fallback) and the run stays on the model under test
230
+ e = dict(PATH=BASE_PATH, HOME=state["home"], CLAUDE_CONFIG_DIR=state["config"], TMPDIR=state["tmp"],
231
+ LANG="C.UTF-8", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1", DISABLE_AUTOUPDATER="1",
232
+ DISABLE_TELEMETRY="1", DISABLE_ERROR_REPORTING="1", MCP_TIMEOUT="60000", MCP_TOOL_TIMEOUT="900000",
233
+ CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK="1")
234
+ e.update(self.proxy)
235
+ e.update(self.api_env)
236
+ return e
237
+
238
+ def _state_dirs(self, hexname=None):
239
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
240
+ os.makedirs(root, exist_ok=True)
241
+ state = dict(state=root, home=os.path.join(root, "home"), config=os.path.join(root, "config"),
242
+ tmp=os.path.join(root, "tmp"))
243
+ for k in ("home", "config", "tmp"):
244
+ os.makedirs(state[k], exist_ok=True)
245
+ return state
246
+
247
+ def prepare(self, ep, first_message, reuse_state=None):
248
+ work = new_run_dir("/tmp/lffrun")
249
+ state = reuse_state or self._state_dirs(os.path.basename(work))
250
+ if self.jail is not None:
251
+ self.jail.stderr_dir = ep.log_dir
252
+ mcp_path = os.path.join(state["state"], "mcp.json")
253
+ with open(mcp_path, "w") as f:
254
+ json.dump(self.mcp_config(ep.session_path), f)
255
+ argv = self.argv(dict(mcp_config=mcp_path), ep, first_message)
256
+ spec = LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
257
+ first_message=first_message, config_files=dict(mcp_config=mcp_path),
258
+ stdout_path=os.path.join(ep.log_dir, "claude_stream.jsonl"),
259
+ stderr_path=os.path.join(ep.log_dir, "claude_stderr.txt"),
260
+ redact_argv={2: f"<first message: sha256={C.sha256_text(first_message)}>"},
261
+ timeout_s=self.timeout_s)
262
+ return spec
263
+
264
+ def config_sha256(self, spec, ep):
265
+ """Hash of everything configurable (argv without the first message, MCP config, env values except keys /
266
+ one-time dirs)."""
267
+ argv = [("<MCP_CONFIG>" if a == spec.config_files["mcp_config"] else a) for a in self.logged_argv(spec)[3:]]
268
+ env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
269
+ if k not in ("HOME", "CLAUDE_CONFIG_DIR", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
270
+ return C.sha256_json(dict(argv=argv, mcp=self.mcp_config("<SESSION>", describe=True), env=env))
271
+
272
+ # ------------------------------------------------------------------------------------------------ preflight
273
+ def preflight(self, spec, ep, record_dir=None):
274
+ """Run the identical command against a fake API (free); refuse on any mismatch with the pin."""
275
+ t0 = time.time()
276
+ fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start()
277
+ pre_state = self._state_dirs()
278
+ try:
279
+ mcp_path = os.path.join(pre_state["state"], "mcp.json")
280
+ with open(mcp_path, "w") as f:
281
+ json.dump(self.mcp_config(None), f)
282
+ argv = self.argv(dict(mcp_config=mcp_path), ep, spec.first_message)
283
+ env = {k: v for k, v in self.env(pre_state).items() if k not in self.api_env} # no real credential
284
+ cred_key, cred_dummy = PREFLIGHT_CREDENTIAL[self.auth]
285
+ env.update({"ANTHROPIC_BASE_URL": fake.base_url, cred_key: cred_dummy})
286
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre_state.values())), env=env, cwd=spec.cwd,
287
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
288
+ reqs = fake.message_requests()
289
+ if not reqs:
290
+ raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): "
291
+ f"{r.stderr.decode('utf-8', 'replace')[-500:]}")
292
+ n, body = reqs[0]
293
+ headers = {}
294
+ if record_dir:
295
+ headers = json.load(open(os.path.join(record_dir, f"req_{n:03d}.json"))).get("headers", {})
296
+ fp, problems = request_fingerprint(body, headers, spec, spec.first_message)
297
+ init = next((json.loads(x) for x in r.stdout.decode("utf-8", "replace").splitlines()
298
+ if x.startswith('{"type":"system"') and '"init"' in x), {})
299
+ if init.get("tools") != MCP_TOOLS:
300
+ problems.append(f"init event tools {init.get('tools')}")
301
+ want_src = "ANTHROPIC_API_KEY" if self.auth == "apikey" else "none" # none = no API key: the OAuth token
302
+ if init.get("apiKeySource") != want_src:
303
+ problems.append(f"init apiKeySource {init.get('apiKeySource')!r}, expected {want_src!r} for "
304
+ f"auth={self.auth}")
305
+ if self.bare and "memory_paths" in init:
306
+ problems.append("init event has memory_paths under --bare")
307
+ if [s.get("status") for s in init.get("mcp_servers", [])] != ["connected"]:
308
+ problems.append(f"MCP servers {init.get('mcp_servers')}")
309
+ if os.listdir(spec.cwd):
310
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
311
+ fp_sha = C.sha256_json(fp)
312
+ out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs),
313
+ tools=[t["name"] for t in fp["tools"]], effort_in_request=(fp["params"].get("output_config")
314
+ or {}).get("effort"),
315
+ model_in_request=fp["params"].get("model"), init_tools=init.get("tools"),
316
+ memory_paths=init.get("memory_paths"), dt_s=round(time.time() - t0, 1), problems=problems)
317
+ if out["effort_in_request"] != ep.effort:
318
+ problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}")
319
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
320
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
321
+ out["fingerprint"] = fp
322
+ if problems:
323
+ raise HarnessRefused("preflight: " + "; ".join(problems))
324
+ if pin is None:
325
+ if not self.allow_unpinned:
326
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
327
+ f"with --write-pins after the self-check passes)")
328
+ out["pin_status"] = "unpinned (allowed)"
329
+ elif pin["fingerprint_sha256"] != fp_sha:
330
+ raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
331
+ f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
332
+ else:
333
+ out["pin_status"] = "match"
334
+ return out
335
+ finally:
336
+ fake.stop()
337
+ shutil.rmtree(pre_state["state"], ignore_errors=True)
338
+
339
+ def launch(self, spec, ep, skip_preflight=False):
340
+ try:
341
+ h = super().launch(spec, ep, skip_preflight)
342
+ except HarnessRefused:
343
+ raise
344
+ # second line of defence: the init event of the real run
345
+ deadline = time.time() + 120
346
+ while time.time() < deadline and h.proc.poll() is None:
347
+ init = self._init_event(spec)
348
+ if init is not None:
349
+ h.info["init"] = {k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version",
350
+ "permissionMode", "memory_paths", "apiKeySource")}
351
+ if init.get("tools") != MCP_TOOLS:
352
+ self.kill(h)
353
+ h.exit_reason = "refused: init tools " + json.dumps(init.get("tools"))
354
+ raise HarnessRefused(h.exit_reason)
355
+ break
356
+ time.sleep(0.2)
357
+ return h
358
+
359
+ @staticmethod
360
+ def _init_event(spec):
361
+ try:
362
+ with open(spec.stdout_path) as f:
363
+ for line in f:
364
+ if line.startswith("{"):
365
+ d = json.loads(line)
366
+ if d.get("type") == "system" and d.get("subtype") == "init":
367
+ return d
368
+ except (OSError, ValueError):
369
+ return None
370
+ return None
371
+
372
+ # ------------------------------------------------------------------------------------------------ collect
373
+ def collect(self, h):
374
+ spec, ep = h.spec, h.ep
375
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
376
+ init, result, by_id, compactions, other = None, None, {}, 0, []
377
+ inits, results = [], [] # one init / result per launch or resume
378
+ lines = open(spec.stdout_path, encoding="utf-8", errors="replace").read().splitlines()
379
+ for line in lines:
380
+ if not line.startswith("{"):
381
+ continue
382
+ d = json.loads(line)
383
+ t = d.get("type")
384
+ if t == "system" and d.get("subtype") == "init":
385
+ init = init or d
386
+ inits.append(d)
387
+ elif t == "system":
388
+ if "compact" in str(d.get("subtype", "")):
389
+ compactions += 1
390
+ other.append(d.get("subtype"))
391
+ elif t == "assistant":
392
+ m = d.get("message") or {}
393
+ mid = m.get("id") or d.get("uuid")
394
+ st = by_id.get(mid)
395
+ if st is None:
396
+ u = m.get("usage") or {}
397
+ st = tw.add_step("agent", timestamp=d.get("timestamp"), model_name=m.get("model"),
398
+ metrics=dict(prompt_tokens=u.get("input_tokens"),
399
+ completion_tokens=u.get("output_tokens"),
400
+ cached_tokens=u.get("cache_read_input_tokens")))
401
+ by_id[mid] = st
402
+ for b in m.get("content") or []:
403
+ if b.get("type") == "text":
404
+ st["message"] += b.get("text", "")
405
+ elif b.get("type") == "thinking":
406
+ st["reasoning_content"] += b.get("thinking", "")
407
+ elif b.get("type") == "tool_use":
408
+ st["tool_calls"].append(dict(tool_call_id=b.get("id"), function_name=strip_mcp(b.get("name")),
409
+ native_name=b.get("name"), arguments=b.get("input")))
410
+ elif t == "user":
411
+ for b in (d.get("message") or {}).get("content") or []:
412
+ if isinstance(b, dict) and b.get("type") == "tool_result":
413
+ c = b.get("content")
414
+ texts, imgs = [], 0
415
+ for x in (c if isinstance(c, list) else [dict(type="text", text=c)]):
416
+ if x.get("type") == "text":
417
+ texts.append(x.get("text") or "")
418
+ elif x.get("type") == "image":
419
+ imgs += 1
420
+ tw.add_result(b.get("tool_use_id"), "\n".join(texts), bool(b.get("is_error")), imgs)
421
+ elif t == "result":
422
+ result = d
423
+ results.append(d)
424
+ v = self.version()
425
+ tw.set_header(session_id=(init or {}).get("session_id"), source=os.path.basename(spec.stdout_path),
426
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
427
+ tools=(init or {}).get("tools"))
428
+
429
+ def tot(key, sub=None): # summed over the segments (each resume reports its own usage)
430
+ vals = [((r.get("usage") or {}).get(key) if sub is None else r.get(key)) for r in results]
431
+ vals = [x for x in vals if isinstance(x, (int, float))]
432
+ return sum(vals) if vals else None
433
+ cost = tot("total_cost_usd", sub=True)
434
+ tw.set_final(h.exit_reason, native_result={k: (result or {}).get(k) for k in
435
+ ("subtype", "is_error", "num_turns", "duration_ms",
436
+ "duration_api_ms", "total_cost_usd", "usage", "modelUsage")},
437
+ total_prompt_tokens=(tot("input_tokens") or 0) + (tot("cache_read_input_tokens") or 0)
438
+ + (tot("cache_creation_input_tokens") or 0),
439
+ total_completion_tokens=tot("output_tokens"), total_cached_tokens=tot("cache_read_input_tokens"),
440
+ total_cost_usd=cost, compactions=compactions, segments=len(results))
441
+ tw.write()
442
+ h.info.update(init_full=init, inits=inits, result=result, results=results, compactions=compactions,
443
+ other_system=other, traj=tw)
444
+ return tw
445
+
446
+ # ------------------------------------------------------------------------------------------------ audit
447
+ def audit(self, h):
448
+ spec, ep = h.spec, h.ep
449
+ init = h.info.get("init_full") or {}
450
+ tw = h.info.get("traj")
451
+ v, problems, notes = [], [], []
452
+ inits = h.info.get("inits") or [init]
453
+ for i, x in enumerate(inits): # every launch / resume
454
+ if x.get("tools") != MCP_TOOLS:
455
+ v.append(f"init {i} tools {x.get('tools')}")
456
+ sids = sorted({x.get("session_id") for x in inits if x.get("session_id")})
457
+ if len(sids) > 1:
458
+ v.append(f"several sessions in one run: {sids}")
459
+ if h.info.get("resumes"):
460
+ notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
461
+ f"episode was over)")
462
+ if self.bare and init.get("memory_paths"):
463
+ v.append(f"memory_paths {init.get('memory_paths')}")
464
+ if not self.bare and init.get("memory_paths"):
465
+ mp = json.dumps(init.get("memory_paths"))
466
+ if spec.state_dirs["state"] not in mp and spec.cwd not in mp:
467
+ v.append(f"memory_paths outside the one-time dirs: {mp}")
468
+ notes.append("full variant: memory_paths point into the one-time dirs (empty at start)")
469
+ names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]]
470
+ bad = sorted({n for n in names if n not in MCP_TOOLS})
471
+ if bad:
472
+ notes.append(f"model asked for unavailable tools (all rejected by the harness): {bad}")
473
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
474
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
475
+ left = dict(config=snapshot_tree(spec.state_dirs["config"]), home=snapshot_tree(spec.state_dirs["home"]),
476
+ work=snapshot_tree(spec.cwd))
477
+ mcp_logs = [p for p in left["home"] if "/mcp-logs-" in p]
478
+ own = [p for p in left["config"] if sids and p.startswith("projects/")
479
+ and (p.endswith(f"/{sids[0]}.jsonl") or f"/{sids[0]}/" in p)] # this run's session (for --resume)
480
+ transcripts = [p for p in left["config"] + left["home"] if p.endswith(".jsonl") and p not in mcp_logs
481
+ and p not in own]
482
+ if transcripts:
483
+ v.append(f"session transcripts other than this run's session: {transcripts}")
484
+ if own:
485
+ notes.append(f"this run's own session kept in the one-time config dir (for --resume): {own}")
486
+ if mcp_logs: # MCP connection log of the CLI in the one-time HOME (removed after the run, never read back)
487
+ notes.append(f"Claude Code wrote its MCP log into the one-time HOME: {mcp_logs}")
488
+ if left["work"]:
489
+ v.append(f"files in the work dir: {left['work']}")
490
+ mcp_env = None
491
+ mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
492
+ if os.path.exists(mt):
493
+ for line in open(mt):
494
+ d = json.loads(line)
495
+ if d.get("ev") == "start" and "env_keys" in d:
496
+ mcp_env = d["env_keys"]
497
+ out = dict(harness=self.name, violations=v, problems=problems, notes=notes, files_left=left,
498
+ mcp_server_env_keys=mcp_env, compactions=h.info.get("compactions"),
499
+ init={k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version",
500
+ "permissionMode", "memory_paths", "apiKeySource")},
501
+ tool_calls=len(names), unavailable_tool_requests=bad, ok=not v)
502
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
503
+ json.dump(out, f, indent=1)
504
+ return out
505
+
506
+
507
+ class ClaudeCodeFull(ClaudeCode):
508
+ name = "claude_code_full"
509
+ bare = False
510
+ capabilities = dict(ClaudeCode.capabilities,
511
+ persistent_memory=Cap("partial", "probe", "auto-memory is on in the harness, but its dirs are "
512
+ "one-time and empty; canaries outside them never reach the request"),
513
+ instruction_file_injection=Cap("partial", "probe", "CLAUDE.md discovery is on, but work / "
514
+ "config / home are empty one-time dirs; canaries outside absent"))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/codex.py ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Codex CLI as a native harness (arm F; flags measured in research_notes/harness接入调研/02 §2.3, Codex 0.156).
2
+
3
+ Launch: process env exactly the whitelist (env -i equivalent), a brand-new empty CODEX_HOME and HOME (one-time, under
4
+ /tmp/lffstate/<hex>), work dir /tmp/lffrun/<12 hex>, `codex exec --json --skip-git-repo-check --ignore-user-config
5
+ --ignore-rules -s read-only`, ~20 features disabled, project docs / permissions / environment context /
6
+ collaboration-mode / skills instructions off, web search off, and only our MCP server with
7
+ default_tools_approval_mode="approve" (otherwise exec mode silently denies MCP calls).
8
+
9
+ Early exit: `codex exec` ends when the model replies without a tool call, also when the episode is not over (measured
10
+ 2026-10-19, cx_pilot6b: gpt-6-astra stopped after a failed first attempt, "I stopped after the one authorized
11
+ attempt", although the finish reply said attempt 2 of 3 starts now). scripts/harness_run.py then sends the reference
12
+ driver's nudge as a user turn with `codex exec resume <thread>` (resume_argv), at most api_player.MAX_NO_TOOL times in
13
+ a row. Hence no --ephemeral: the session is kept in the one-time CODEX_HOME (memories off; removed after the run).
14
+ Measured with 0.163 against the fake server: the resumed request has the same developer messages, tools, model and
15
+ parameters as the first, then the earlier turns and the nudge as a user message.
16
+
17
+ The model API is a custom Responses provider "lffapi", so the preflight can point exactly the same config at a local
18
+ fake server by changing only base_url. Two ways to authenticate (auth=):
19
+ apikey env_key OPENAI_API_KEY (api_env), default endpoint the official API
20
+ chatgpt a ChatGPT subscription login (no API key; same as RPent's codex planner reusing `codex login`): the
21
+ provider gets requires_openai_auth=true (requests carry the login's bearer + chatgpt-account-id), default
22
+ endpoint the ChatGPT Codex backend; a copy of auth.json from the source CODEX_HOME is put into the one-time
23
+ CODEX_HOME (the only file allowed there at launch). If Codex refreshes the login during a run, the refreshed
24
+ auth.json is written back to the source (refresh tokens rotate), unless the source changed meanwhile.
25
+ Launch is refused when the source login is close to its refresh (parallel copies would each rotate it).
26
+ Measured with 0.163 against the fake server: same body keys and headers in both modes plus chatgpt-account-id; the
27
+ preset differs (exec tool description), so pins are per auth mode (pin name codex-chatgpt).
28
+ The calling environment's HTTP(S) proxy is passed through (base.proxy_env; NO_PROXY = loopback only).
29
+
30
+ Model configuration (catalog=, user 2026-10-20): Codex picks the system prompt, tool form and context window per
31
+ model from its model catalog. We always pass an explicit model_catalog_json written into the one-time CODEX_HOME, so
32
+ nothing depends on the catalog the subscription backend serves on the day:
33
+ generic (main table, every model) one entry built from codex_catalogs/generic_<version>.json: what Codex sends for a
34
+ model it has no entry for (its generic Codex CLI prompt, plain function tools, no code mode); per model only
35
+ slug, input modalities and reasoning levels. Measured with 0.163 against the fake server: the request equals
36
+ the no-catalog fallback for an unknown slug apart from message ids.
37
+ native (control) codex_catalogs/native_<version>.json = `codex debug models --bundled` of that binary: the request
38
+ equals the one without any catalog (GPT: code mode, its own prompt). The pins of before 10-20 stay valid.
39
+ Pins are per catalog (pin name codex[-chatgpt][-generic]).
40
+
41
+ Known, accepted differences in native (code mode) catalogs (reported, not fixable by config in 0.156):
42
+ - code mode: the model sees one `exec` tool (JavaScript in a V8 isolate without fs / network); our tools are nested
43
+ and listed only in ALL_TOOLS; MCP images reach the model only if the model's JS calls image(...)
44
+ - apply_patch (blocked by the read-only sandbox), clock, 3 MCP-resource tools (our server has no resources),
45
+ request_user_input, and 6 collaboration.* sub-agent tools cannot be removed; a sub-agent call is an audit violation
46
+ - --json has tokens but no dollar cost
47
+ Fail-closed launch: the preflight checks the top-level tools, the exec nested-tool list (ALL_TOOLS, printed by a
48
+ scripted exec call), the developer (preset) messages and request parameters against the pin.
49
+ """
50
+ import base64
51
+ import datetime
52
+ import fcntl
53
+ import json
54
+ import os
55
+ import re
56
+ import shutil
57
+ import sqlite3
58
+ import subprocess
59
+ import sys
60
+ import time
61
+
62
+ from . import contract as C
63
+ from . import pins
64
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
65
+ new_run_dir, proxy_env, snapshot_tree)
66
+ from .fakeapi import FakeResponses
67
+ from .trajectory import TrajWriter
68
+
69
+ ROOT = C.ROOT
70
+ MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
71
+ BASE_PATH = "/usr/bin:/bin"
72
+ OFFICIAL_API = "https://api.openai.com/v1"
73
+ CHATGPT_BACKEND = "https://chatgpt.com/backend-api/codex"
74
+ AUTH_FILE = "auth.json"
75
+ AUTH_LOCK = "/tmp/lffstate/.codex_auth.lock"
76
+ MAX_LOGIN_AGE_H = 8 * 24 # codex-rs TOKEN_REFRESH_INTERVAL (8 days, from the source, not measured here): a login
77
+ # older than this is refreshed at start, by every parallel copy
78
+ MIN_ACCESS_LEFT_H = 24 # an access token expiring during a run makes the run's copy refresh it
79
+
80
+
81
+ def _jwt_claims(tok):
82
+ try:
83
+ p = tok.split(".")[1]
84
+ return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
85
+ except (IndexError, ValueError, AttributeError):
86
+ return {}
87
+
88
+
89
+ def chatgpt_login_status(home):
90
+ """-> dict(ok, problem, last_refresh_h, access_token_valid_h) of the ChatGPT login in home/auth.json. No secret
91
+ leaves this function."""
92
+ src = os.path.join(home, AUTH_FILE)
93
+ try:
94
+ with open(src) as f:
95
+ a = json.load(f)
96
+ except (OSError, ValueError) as e:
97
+ return dict(ok=False, problem=f"cannot read {src}: {type(e).__name__}")
98
+ tok = a.get("tokens") or {}
99
+ if a.get("auth_mode") != "chatgpt" or not tok.get("access_token") or not tok.get("refresh_token"):
100
+ return dict(ok=False, problem=f"{src} is not a ChatGPT login (auth_mode={a.get('auth_mode')!r})")
101
+ now = time.time()
102
+ try:
103
+ lr = datetime.datetime.fromisoformat(str(a.get("last_refresh")).replace("Z", "+00:00")).timestamp()
104
+ age_h = (now - lr) / 3600
105
+ except ValueError:
106
+ age_h = float("inf")
107
+ left_h = (float(_jwt_claims(tok["access_token"]).get("exp") or 0) - now) / 3600
108
+ out = dict(ok=True, problem=None, last_refresh_h=round(age_h, 1), access_token_valid_h=round(left_h, 1))
109
+ if age_h >= MAX_LOGIN_AGE_H or left_h < MIN_ACCESS_LEFT_H:
110
+ out.update(ok=False, problem=f"the ChatGPT login in {home} is due for a refresh (last refresh {age_h:.0f} h ago, "
111
+ f"access token valid {left_h:.0f} h): refresh it once outside the benchmark (use "
112
+ f"codex with CODEX_HOME={home}), so that parallel runs do not each rotate it")
113
+ return out
114
+ DISABLE = ["shell_tool", "unified_exec", "view_image", "multi_agent", "multi_agent_v2", "apps", "browser_use",
115
+ "browser_use_external", "computer_use", "image_generation", "plugins", "hooks", "skill_search",
116
+ "tool_suggest", "goals", "sleep_tool", "in_app_browser", "memories", "skill_mcp_dependency_install",
117
+ "realtime_conversation"]
118
+ # what remains in 0.156 after the lock-down (measured): anything else is refused at launch
119
+ EXPECTED_TOP = ["collaboration.followup_task", "collaboration.interrupt_agent", "collaboration.list_agents",
120
+ "collaboration.send_message", "collaboration.spawn_agent", "collaboration.wait_agent",
121
+ "functions.exec", "functions.request_user_input", "functions.request_user_input_async",
122
+ "functions.wait"]
123
+ EXPECTED_ALL_TOOLS = ["apply_patch", "clock__curr_time", "list_mcp_resource_templates", "list_mcp_resources",
124
+ "mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images", "read_mcp_resource"]
125
+ # generic catalog (no code mode), measured with 0.163: our tools are plain functions in the mcp__lff namespace
126
+ EXPECTED_TOP_GENERIC = ["list_mcp_resource_templates", "list_mcp_resources", "mcp__lff.robot", "mcp__lff.shell",
127
+ "mcp__lff.view_images", "read_mcp_resource", "request_user_input"]
128
+ CATALOG_DIR = os.path.join(ROOT, "lffbench", "harnesses", "codex_catalogs")
129
+ CATALOG_FILE = "lff_model_catalog.json" # written into the one-time CODEX_HOME before launch
130
+ CATALOGS = ("generic", "native")
131
+ # generic catalog: the per-model fields (input modalities; the run's reasoning level is always listed)
132
+ TEXT_ONLY_MODELS = {"deepseek-v4-pro": ["text"]} # DeepSeek's Codex guide (read 2026-10-20): v4-pro takes no images
133
+ DEEPSEEK_URL = "https://api.deepseek.com/" # same guide: base_url, wire_api = "responses"
134
+ OPENCODE_GO_URL = "https://opencode.ai/inference/go/openai/v1" # OpenCode Go, Responses API (checked 2026-10-29)
135
+ MCP_TOOLS = ["robot", "shell", "view_images"]
136
+ OK_ITEMS = ("agent_message", "reasoning", "mcp_tool_call", "error")
137
+ PREFLIGHT_JS = "text(JSON.stringify(ALL_TOOLS));"
138
+
139
+
140
+ def codex_bin():
141
+ return os.environ.get("LFF_CODEX_BIN") or shutil.which("codex") or "codex"
142
+
143
+
144
+ def toml_str(s):
145
+ return json.dumps(s) # a JSON string literal is a valid TOML basic string
146
+
147
+
148
+ def _norm(s, cwd):
149
+ s = s.replace(cwd, "<CWD>")
150
+ s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
151
+ s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
152
+ s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
153
+ s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "<UUID>", s)
154
+ return s
155
+
156
+
157
+ def _walk_tools(ts, prefix=""):
158
+ out = []
159
+ for t in ts or []:
160
+ if t.get("type") == "namespace":
161
+ out += _walk_tools(t.get("tools"), prefix + t.get("name", "") + ".")
162
+ else:
163
+ out.append(dict(name=prefix + (t.get("name") or t.get("type") or "?"), type=t.get("type"),
164
+ description=t.get("description"), parameters=t.get("parameters"), format=t.get("format")))
165
+ return out
166
+
167
+
168
+ def request_fingerprint(body, cwd, first_message, expected_top=None):
169
+ problems = []
170
+ items = body.get("input") or []
171
+ top = _walk_tools(body.get("tools"))
172
+ dev, users = [], []
173
+ for it in items:
174
+ if it.get("type") == "additional_tools":
175
+ top += _walk_tools(it.get("tools"))
176
+ elif it.get("type") == "message" and it.get("role") in ("developer", "system"):
177
+ dev.append(_norm("\n".join(c.get("text", "") for c in it.get("content") or []), cwd))
178
+ elif it.get("type") == "message" and it.get("role") == "user":
179
+ users.append(it)
180
+ names = sorted(t["name"] for t in top)
181
+ expected_top = EXPECTED_TOP if expected_top is None else expected_top
182
+ if names != expected_top:
183
+ problems.append(f"top-level tools {names} != expected {expected_top}")
184
+ texts = [c.get("text") for u in users for c in u.get("content") or []]
185
+ if texts != [first_message]:
186
+ problems.append(f"user input is not exactly our first message ({len(texts)} user text blocks)")
187
+ for t in top:
188
+ if t.get("description"):
189
+ t["description"] = _norm(t["description"], cwd)
190
+ params = {k: body.get(k) for k in ("model", "reasoning", "parallel_tool_calls", "store", "include", "text",
191
+ "tool_choice", "instructions", "max_output_tokens", "temperature")}
192
+ meta = body.get("client_metadata") or {}
193
+ try:
194
+ turn_meta = json.loads(meta.get("x-codex-turn-metadata") or "{}")
195
+ except ValueError:
196
+ turn_meta = {}
197
+ sandbox = {k: turn_meta.get(k) for k in ("sandbox", "sandbox_mode")}
198
+ if sandbox.get("sandbox_mode") != "read-only":
199
+ problems.append(f"sandbox {sandbox}")
200
+ fp = dict(tools=sorted(top, key=lambda t: t["name"]), developer=dev, params=params, sandbox=sandbox,
201
+ developer_chars=sum(len(d) for d in dev))
202
+ return fp, problems
203
+
204
+
205
+ def model_catalog(mode, version, model, modalities=None, effort=None):
206
+ """-> (catalog dict for model_catalog_json, source file). Refuses (fail-closed) when the version has no catalog
207
+ file or, for native, when the model has no entry."""
208
+ if mode not in CATALOGS:
209
+ raise ValueError(f"catalog must be one of {CATALOGS}, not {mode!r}")
210
+ src = os.path.join(CATALOG_DIR, f"{mode}_{version}.json")
211
+ if not os.path.exists(src):
212
+ raise HarnessRefused(f"no {mode} model catalog for Codex {version} ({os.path.relpath(src, ROOT)})")
213
+ d = json.load(open(src))
214
+ if mode == "native":
215
+ if not any(m.get("slug") == model for m in d.get("models") or []):
216
+ raise HarnessRefused(f"native catalog {os.path.basename(src)} has no entry for {model}")
217
+ return d, src
218
+ e = dict(d["entry"], slug=model, display_name=model)
219
+ modalities = modalities or TEXT_ONLY_MODELS.get(model)
220
+ if modalities:
221
+ e["input_modalities"] = list(modalities)
222
+ levels = [dict(x) for x in e.get("supported_reasoning_levels") or []]
223
+ if effort and effort not in [x.get("effort") for x in levels]:
224
+ levels.append(dict(effort=effort, description=effort))
225
+ e["supported_reasoning_levels"] = levels
226
+ return dict(models=[e]), src
227
+
228
+
229
+ def all_tools_from(body):
230
+ """The ALL_TOOLS list printed by the preflight exec call (in the second request)."""
231
+ for it in body.get("input") or []:
232
+ if it.get("type") == "custom_tool_call_output":
233
+ out = it.get("output")
234
+ parts = out if isinstance(out, list) else [dict(text=out)]
235
+ for p in parts:
236
+ t = (p.get("text") or "").strip()
237
+ if t.startswith("["):
238
+ try:
239
+ return json.loads(t)
240
+ except ValueError:
241
+ pass
242
+ return None
243
+
244
+
245
+ class Codex(HarnessAdapter):
246
+ name = "codex"
247
+ uses_mcp = True
248
+ can_resume = True
249
+ clean_dirs = ("home", "codex_home", "tmp")
250
+ ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
251
+ capabilities = dict(
252
+ only_benchmark_tools=Cap("partial", "preflight", "generic catalog: our 3 MCP tools as functions + residual "
253
+ "resource×3 / request_user_input; native (code mode): reachable only via exec(JS), "
254
+ "residual apply_patch(blocked) / clock / resource×3 / request_user_input / "
255
+ "collaboration×6"),
256
+ images_reach_model=Cap("partial", "probe", "generic: MCP images go to the model; native (code mode): only if "
257
+ "the model's JS calls image(); bytes unchanged either way"),
258
+ non_persistent_session=Cap("yes", "probe", "only this run's thread, in the one-time CODEX_HOME (for exec "
259
+ "resume), removed after the run; memories off"),
260
+ pinned_version=Cap("yes", "launch", "codex --version + binary sha256 in harness.json; pin per version"),
261
+ machine_readable_events=Cap("yes", "stream", "exec --json (items + usage, no cost)"),
262
+ tool_calls_logged=Cap("yes", "stream", "mcp_tool_call items + mcp_transcript + events.jsonl"),
263
+ model_and_effort=Cap("yes", "preflight", "-m / model_reasoning_effort; request reasoning.effort checked"),
264
+ persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; canaries absent"),
265
+ instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0 + empty CODEX_HOME (AGENTS.md)"),
266
+ web_access=Cap("absent", "probe", "web_search disabled; exec isolate has no fetch"),
267
+ host_file_read=Cap("absent", "probe", "shell / unified_exec / view_image off; exec has no require; "
268
+ "read-only sandbox"),
269
+ builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
270
+ subagent_delegation=Cap("partial", "preflight", "collaboration.* tools cannot be disabled in 0.156; any use "
271
+ "is an audit violation"),
272
+ background_execution=Cap("partial", "preflight", "functions.wait / long exec yields exist; audited"),
273
+ )
274
+
275
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
276
+ python=None, extra_args=None, jail=False, auth="apikey", auth_home=None, catalog="generic",
277
+ modalities=None):
278
+ """api_env: {"OPENAI_API_KEY": ...} (the provider's env_key, auth="apikey"); base_url: Responses endpoint
279
+ (default: official API / ChatGPT Codex backend by auth). auth="chatgpt": a ChatGPT login copied from
280
+ auth_home (default LFF_CODEX_AUTH_HOME, else the calling CODEX_HOME, else ~/.codex), no API key.
281
+ jail: run the CLI in the native-harness jail (lffbench/harnesses/jail.py, static /proc).
282
+ catalog: "generic" (shared configuration of the main table) or "native" (Codex's own entry for the model);
283
+ modalities: input modalities of a generic entry (default text + image)."""
284
+ if catalog not in CATALOGS:
285
+ raise ValueError(f"catalog must be one of {CATALOGS}, not {catalog!r}")
286
+ self.catalog, self.modalities = catalog, (list(modalities) if modalities else None)
287
+ self._catalog_sha = {} # one-time CODEX_HOME -> sha256 of the catalog written there
288
+ if auth not in ("apikey", "chatgpt"):
289
+ raise ValueError(f"auth must be apikey or chatgpt, not {auth!r}")
290
+ if jail:
291
+ from .jail import HarnessJail
292
+ self.jail = HarnessJail(codex_bin(), proc="static")
293
+ self.auth = auth
294
+ self.auth_home = None
295
+ self._auth_copies = {} # one-time CODEX_HOME -> sha256 of the auth.json copied into it
296
+ if auth == "chatgpt":
297
+ self.auth_home = os.path.abspath(auth_home or os.environ.get("LFF_CODEX_AUTH_HOME")
298
+ or os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"))
299
+ self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
300
+ self.api_env = dict(api_env or {}) if auth == "apikey" else {}
301
+ self.base_url = base_url or (OFFICIAL_API if auth == "apikey" else CHATGPT_BACKEND)
302
+ self.proxy = proxy_env()
303
+ self.timeout_s = timeout_s
304
+ self.pins_dir = pins_dir
305
+ self.allow_unpinned = allow_unpinned
306
+ self.python = python or sys.executable
307
+ self.extra_args = list(extra_args or [])
308
+ self._version = None
309
+
310
+ # ------------------------------------------------------------------------------------------------ auth
311
+ def auth_info(self):
312
+ if self.auth == "apikey":
313
+ return dict(mode="apikey", keys=sorted(self.api_env))
314
+ st = chatgpt_login_status(self.auth_home)
315
+ return dict(mode="chatgpt", source=self.auth_home, **{k: v for k, v in st.items() if k != "ok"})
316
+
317
+ def config_info(self):
318
+ """For harness.json: which model catalog the run used."""
319
+ return dict(catalog=self.catalog, modalities=self.modalities)
320
+
321
+ def _install_catalog(self, codex_home, ep):
322
+ """Write the run's model catalog into the one-time CODEX_HOME (the only file besides auth.json allowed there
323
+ at launch). -> (path, sha256, source file, code mode)."""
324
+ cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, self.modalities, ep.effort)
325
+ path = os.path.join(codex_home, CATALOG_FILE)
326
+ with open(path, "w") as f:
327
+ json.dump(cat, f)
328
+ sha = C.sha256_file(path)
329
+ self._catalog_sha[codex_home] = sha
330
+ entry = next(m for m in cat["models"] if m.get("slug") == ep.model)
331
+ return path, sha, os.path.relpath(src, ROOT), entry.get("tool_mode") == "code_mode_only"
332
+
333
+ def _install_auth(self, codex_home):
334
+ """auth="chatgpt": copy the source login into a one-time CODEX_HOME (refused if it is due for a refresh)."""
335
+ if self.auth != "chatgpt":
336
+ return
337
+ st = chatgpt_login_status(self.auth_home)
338
+ if not st["ok"]:
339
+ raise HarnessRefused("ChatGPT login: " + st["problem"])
340
+ dst = os.path.join(codex_home, AUTH_FILE)
341
+ with open(os.path.join(self.auth_home, AUTH_FILE), "rb") as f:
342
+ data = f.read()
343
+ fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
344
+ with os.fdopen(fd, "wb") as f:
345
+ f.write(data)
346
+ self._auth_copies[codex_home] = C.sha256_file(dst)
347
+
348
+ def _sync_auth_back(self, codex_home):
349
+ """After a run: if Codex refreshed the login in the run's copy, write it back to the source (refresh tokens
350
+ rotate, the source's old one may no longer work), unless the source changed since the copy. -> note or None."""
351
+ copied = self._auth_copies.pop(codex_home, None)
352
+ p = os.path.join(codex_home, AUTH_FILE)
353
+ if copied is None or not os.path.exists(p) or C.sha256_file(p) == copied:
354
+ return None
355
+ try:
356
+ with open(p, "rb") as f:
357
+ data = f.read()
358
+ new = json.loads(data)
359
+ except (OSError, ValueError):
360
+ return "auth.json in the run's CODEX_HOME changed and is unreadable: not written back"
361
+ if new.get("auth_mode") != "chatgpt" or not (new.get("tokens") or {}).get("refresh_token"):
362
+ return "auth.json in the run's CODEX_HOME changed but holds no ChatGPT login: not written back"
363
+ src = os.path.join(self.auth_home, AUTH_FILE)
364
+ os.makedirs(os.path.dirname(AUTH_LOCK), exist_ok=True)
365
+ with open(AUTH_LOCK, "a") as lk:
366
+ fcntl.flock(lk, fcntl.LOCK_EX)
367
+ if C.sha256_file(src) != copied:
368
+ return "the run refreshed its login copy, but the source auth.json changed meanwhile: not written back"
369
+ tmp = src + ".lff-tmp"
370
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
371
+ with os.fdopen(fd, "wb") as f:
372
+ f.write(data)
373
+ os.replace(tmp, src)
374
+ return "the run refreshed the ChatGPT login: refreshed auth.json written back to the source"
375
+
376
+ def version(self):
377
+ if self._version is None:
378
+ b = codex_bin()
379
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
380
+ CODEX_HOME="/nonexistent"),
381
+ capture_output=True, text=True, timeout=60)
382
+ v = (out.stdout.strip().split() or ["?"])[-1]
383
+ self._version = dict(version=v, binary=binary_info(b))
384
+ return self._version
385
+
386
+ def pin_key(self, ep):
387
+ v = self.version()
388
+ name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
389
+ name += "" if self.catalog == "native" else f"-{self.catalog}"
390
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
391
+
392
+ # ------------------------------------------------------------------------------------------------ prepare
393
+ def config_args(self, ep, session_path, base_url, codex_home):
394
+ mcp_cmd, mcp_args = self.mcp_server_command(self.python, MCP_SCRIPT, ["--session", session_path] if session_path
395
+ else ["--schema-only"])
396
+ c = ["model_reasoning_effort=" + toml_str(ep.effort),
397
+ "project_doc_max_bytes=0", "include_permissions_instructions=false", "include_environment_context=false",
398
+ "include_collaboration_mode_instructions=false", "skills.include_instructions=false",
399
+ "skills.bundled.enabled=false", 'web_search="disabled"',
400
+ 'model_provider="lffapi"', 'model_providers.lffapi.name="lffapi"',
401
+ "model_providers.lffapi.base_url=" + toml_str(base_url), 'model_providers.lffapi.wire_api="responses"',
402
+ ('model_providers.lffapi.env_key="OPENAI_API_KEY"' if self.auth == "apikey"
403
+ else "model_providers.lffapi.requires_openai_auth=true"),
404
+ "mcp_servers.lff.command=" + toml_str(mcp_cmd),
405
+ "mcp_servers.lff.args=[" + ",".join(toml_str(x) for x in mcp_args) + "]",
406
+ "mcp_servers.lff.env={PATH=" + toml_str(BASE_PATH) + "}",
407
+ 'mcp_servers.lff.enabled_tools=["robot","shell","view_images"]',
408
+ 'mcp_servers.lff.default_tools_approval_mode="approve"', "mcp_servers.lff.required=true",
409
+ "mcp_servers.lff.startup_timeout_sec=60", "mcp_servers.lff.tool_timeout_sec=900",
410
+ "model_catalog_json=" + toml_str(os.path.join(codex_home, CATALOG_FILE))]
411
+ return c
412
+
413
+ def argv(self, ep, session_path, base_url, first_message, codex_home):
414
+ a = [codex_bin(), "exec", "--json", "--skip-git-repo-check", "--ignore-user-config",
415
+ "--ignore-rules", "-s", "read-only", "-m", ep.model]
416
+ for f in DISABLE:
417
+ a += ["--disable", f]
418
+ for c in self.config_args(ep, session_path, base_url, codex_home):
419
+ a += ["-c", c]
420
+ return a + self.extra_args + [first_message]
421
+
422
+ @staticmethod
423
+ def thread_id(stdout_path):
424
+ t = None
425
+ for line in open(stdout_path, encoding="utf-8", errors="replace"):
426
+ if line.startswith("{") and '"thread.started"' in line:
427
+ t = json.loads(line).get("thread_id") or t
428
+ return t
429
+
430
+ def resume_argv(self, h, message):
431
+ """`codex exec resume <thread> <message>` with the launch's flags and config; resume has no -s, so the
432
+ sandbox goes in as sandbox_mode."""
433
+ thread = self.thread_id(h.spec.stdout_path)
434
+ if not thread:
435
+ raise HarnessRefused("resume: no thread id in the event stream")
436
+ a = list(h.spec.argv[:-1]) # without the first message
437
+ i = a.index("exec")
438
+ rest = a[i + 1:]
439
+ j = rest.index("-s")
440
+ mode = rest[j + 1]
441
+ del rest[j:j + 2]
442
+ return a[:i + 1] + ["resume"] + rest + ["-c", "sandbox_mode=" + toml_str(mode), thread, message]
443
+
444
+ def env(self, state):
445
+ e = dict(PATH=BASE_PATH, HOME=state["home"], CODEX_HOME=state["codex_home"], TMPDIR=state["tmp"],
446
+ LANG="C.UTF-8")
447
+ e.update(self.proxy)
448
+ e.update(self.api_env)
449
+ return e
450
+
451
+ def _state_dirs(self, hexname=None):
452
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
453
+ os.makedirs(root, exist_ok=True)
454
+ state = dict(state=root, home=os.path.join(root, "home"), codex_home=os.path.join(root, "codex_home"),
455
+ tmp=os.path.join(root, "tmp"))
456
+ for k in ("home", "codex_home", "tmp"):
457
+ os.makedirs(state[k], exist_ok=True)
458
+ return state
459
+
460
+ def prepare(self, ep, first_message, reuse_state=None):
461
+ work = new_run_dir("/tmp/lffrun")
462
+ state = reuse_state or self._state_dirs(os.path.basename(work))
463
+ if self.jail is not None:
464
+ self.jail.stderr_dir = ep.log_dir
465
+ if not reuse_state and os.listdir(state["codex_home"]):
466
+ raise HarnessRefused("CODEX_HOME is not empty")
467
+ cat_path, cat_sha, cat_src, code_mode = self._install_catalog(state["codex_home"], ep)
468
+ argv = self.argv(ep, ep.session_path, self.base_url, first_message, state["codex_home"])
469
+ return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
470
+ first_message=first_message, stdout_path=os.path.join(ep.log_dir, "codex_events.jsonl"),
471
+ stderr_path=os.path.join(ep.log_dir, "codex_stderr.txt"),
472
+ redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
473
+ config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
474
+ catalog=self.catalog, code_mode=code_mode)),
475
+ timeout_s=self.timeout_s)
476
+
477
+ def launch(self, spec, ep, skip_preflight=False):
478
+ self._install_auth(spec.state_dirs["codex_home"])
479
+ return super().launch(spec, ep, skip_preflight=skip_preflight)
480
+
481
+ def cleanup(self, spec):
482
+ self._sync_auth_back(spec.state_dirs.get("codex_home", ""))
483
+ super().cleanup(spec)
484
+
485
+ def config_sha256(self, spec, ep):
486
+ """Hash of everything configurable (argv without the first message, env values except keys / one-time dirs)."""
487
+ argv = [re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", a.replace(ep.session_path, "<SESSION>"))
488
+ .replace(spec.state_dirs["codex_home"], "<CODEX_HOME>") for a in self.logged_argv(spec)[1:-1]]
489
+ env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
490
+ if k not in ("HOME", "CODEX_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
491
+ cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
492
+ return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat))
493
+
494
+ # ------------------------------------------------------------------------------------------------ preflight
495
+ def preflight(self, spec, ep, record_dir=None):
496
+ t0 = time.time()
497
+ code_mode = (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True)
498
+ script = [[("exec", PREFLIGHT_JS)], [("text", "preflight ok")]] if code_mode else [[("text", "preflight ok")]]
499
+ fake = FakeResponses(script, record_dir=record_dir).start()
500
+ pre = self._state_dirs()
501
+ try:
502
+ self._install_auth(pre["codex_home"])
503
+ self._install_catalog(pre["codex_home"], ep)
504
+ argv = self.argv(ep, None, fake.base_url, spec.first_message, pre["codex_home"])
505
+ env = self.env(pre)
506
+ if self.auth == "apikey":
507
+ env["OPENAI_API_KEY"] = "sk-preflight-not-a-key"
508
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
509
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
510
+ reqs = fake.model_requests()
511
+ if len(reqs) < (2 if code_mode else 1):
512
+ raise HarnessRefused(f"preflight: {len(reqs)} model requests (rc={r.returncode}): "
513
+ f"{r.stderr.decode('utf-8', 'replace')[-800:]}")
514
+ fp, problems = request_fingerprint(reqs[0][1], spec.cwd, spec.first_message,
515
+ EXPECTED_TOP if code_mode else EXPECTED_TOP_GENERIC)
516
+ at_names = None
517
+ if code_mode: # our tools are nested in exec: the scripted exec call prints them
518
+ at = all_tools_from(reqs[1][1])
519
+ if at is None:
520
+ problems.append("exec preflight did not print ALL_TOOLS")
521
+ at = []
522
+ at_names = sorted(t.get("name") if isinstance(t, dict) else str(t) for t in at)
523
+ if at_names != EXPECTED_ALL_TOOLS:
524
+ problems.append(f"ALL_TOOLS {at_names} != expected {EXPECTED_ALL_TOOLS}")
525
+ fp["all_tools"] = [({k: (_norm(v, spec.cwd) if isinstance(v, str) else v) for k, v in t.items()}
526
+ if isinstance(t, dict) else t) for t in sorted(at, key=lambda t: json.dumps(t))]
527
+ effort = (fp["params"].get("reasoning") or {}).get("effort")
528
+ if effort != ep.effort:
529
+ problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
530
+ if os.listdir(spec.cwd):
531
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
532
+ fp_sha = C.sha256_json(fp)
533
+ out = dict(fingerprint_sha256=fp_sha, developer_chars=fp["developer_chars"], n_requests=len(reqs),
534
+ top_tools=[t["name"] for t in fp["tools"]], all_tools=at_names, code_mode=code_mode,
535
+ catalog=self.catalog, effort_in_request=effort,
536
+ model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], dt_s=round(time.time() - t0, 1),
537
+ problems=problems)
538
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
539
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
540
+ out["fingerprint"] = fp
541
+ if problems:
542
+ raise HarnessRefused("preflight: " + "; ".join(problems))
543
+ if pin is None:
544
+ if not self.allow_unpinned:
545
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
546
+ f"with --write-pins after the self-check passes)")
547
+ out["pin_status"] = "unpinned (allowed)"
548
+ elif pin["fingerprint_sha256"] != fp_sha:
549
+ raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
550
+ f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
551
+ else:
552
+ out["pin_status"] = "match"
553
+ return out
554
+ finally:
555
+ fake.stop()
556
+ self._sync_auth_back(pre["codex_home"])
557
+ shutil.rmtree(pre["state"], ignore_errors=True)
558
+
559
+ # ------------------------------------------------------------------------------------------------ collect
560
+ def collect(self, h):
561
+ spec, ep = h.spec, h.ep
562
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
563
+ thread, usage, items, errors = None, dict(input=0, cached=0, output=0, reasoning=0), [], []
564
+ for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
565
+ if not line.startswith("{"):
566
+ continue
567
+ d = json.loads(line)
568
+ t = d.get("type")
569
+ if t == "thread.started":
570
+ thread = d.get("thread_id")
571
+ elif t == "turn.completed":
572
+ u = d.get("usage") or {}
573
+ usage["input"] += u.get("input_tokens") or 0
574
+ usage["cached"] += u.get("cached_input_tokens") or 0
575
+ usage["output"] += u.get("output_tokens") or 0
576
+ usage["reasoning"] += u.get("reasoning_output_tokens") or 0
577
+ elif t in ("error", "turn.failed"):
578
+ errors.append(d)
579
+ elif t == "item.completed":
580
+ it = d.get("item") or {}
581
+ items.append(it.get("type"))
582
+ if it.get("type") == "agent_message":
583
+ tw.add_step("agent", message=it.get("text", ""))
584
+ elif it.get("type") == "reasoning":
585
+ tw.add_step("agent", reasoning=it.get("text", ""))
586
+ else:
587
+ name = it.get("tool") if it.get("type") == "mcp_tool_call" else it.get("type")
588
+ args = it.get("arguments") if it.get("type") == "mcp_tool_call" else {
589
+ k: v for k, v in it.items() if k not in ("id", "type", "status")}
590
+ st = tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
591
+ native_name=f"{it.get('server', '')}.{name}"
592
+ if it.get("type") == "mcp_tool_call" else name,
593
+ item_type=it.get("type"), arguments=args)])
594
+ res = it.get("result") or {}
595
+ texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
596
+ imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
597
+ tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
598
+ bool(it.get("error")) or it.get("status") == "failed", imgs)
599
+ del st
600
+ v = self.version()
601
+ tw.set_header(session_id=thread, source=os.path.basename(spec.stdout_path),
602
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
603
+ tools=EXPECTED_ALL_TOOLS if (spec.config_files.get("model_catalog_json") or {}).get(
604
+ "code_mode", True) else EXPECTED_TOP_GENERIC)
605
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items))),
606
+ total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
607
+ total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
608
+ tw.write()
609
+ h.info.update(items=items, traj=tw, thread=thread, errors=errors)
610
+ return tw
611
+
612
+ # ------------------------------------------------------------------------------------------------ audit
613
+ @staticmethod
614
+ def sqlite_rows(path, table):
615
+ """Row count of `table`, read from a copy (the db may be in WAL mode and still open)."""
616
+ import tempfile
617
+ try:
618
+ with tempfile.TemporaryDirectory() as td:
619
+ for suf in ("", "-wal", "-shm"):
620
+ if os.path.exists(path + suf):
621
+ shutil.copy(path + suf, os.path.join(td, "db.sqlite" + suf))
622
+ con = sqlite3.connect(os.path.join(td, "db.sqlite"))
623
+ n = con.execute(f"select count(*) from {table}").fetchone()[0]
624
+ con.close()
625
+ return n
626
+ except (sqlite3.Error, OSError) as e:
627
+ return f"n/a ({e})"
628
+
629
+ def audit(self, h):
630
+ spec, ep = h.spec, h.ep
631
+ v, notes = [], []
632
+ items = h.info.get("items") or []
633
+ bad = sorted({i for i in items if i not in OK_ITEMS})
634
+ if bad:
635
+ v.append(f"non-MCP items in the event stream: {bad}")
636
+ tw = h.info.get("traj")
637
+ residual = []
638
+ for st in (tw.steps if tw else []):
639
+ for tc in st["tool_calls"]:
640
+ if tc.get("item_type") != "mcp_tool_call":
641
+ continue
642
+ if tc["native_name"].startswith("lff.") and tc["function_name"] in MCP_TOOLS:
643
+ continue
644
+ if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
645
+ residual.append(tc["function_name"]) # our server has no resources: always empty
646
+ else:
647
+ v.append(f"unexpected MCP call {tc['native_name']}")
648
+ if residual:
649
+ notes.append(f"residual MCP-resource tool calls (empty, our server has no resources): {residual}")
650
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
651
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
652
+ ch = spec.state_dirs["codex_home"]
653
+ note = self._sync_auth_back(ch)
654
+ if note:
655
+ notes.append(note)
656
+ left = dict(codex_home=snapshot_tree(ch), home=snapshot_tree(spec.state_dirs["home"]),
657
+ work=snapshot_tree(spec.cwd))
658
+ threads = None
659
+ for f in left["codex_home"]:
660
+ if re.match(r"state_\d+\.sqlite$", f):
661
+ threads = self.sqlite_rows(os.path.join(ch, f), "threads")
662
+ if isinstance(threads, int) and threads > 1:
663
+ v.append(f"{threads} threads persisted in CODEX_HOME (only this run's one is expected)")
664
+ thread = h.info.get("thread")
665
+ sessions = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))]
666
+ foreign = [f for f in sessions if not (thread and f.startswith("sessions/") and f.endswith(f"-{thread}.jsonl"))]
667
+ if foreign:
668
+ v.append(f"session files other than this run's thread: {foreign}")
669
+ if h.info.get("resumes"):
670
+ notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
671
+ f"episode was over)")
672
+ if left["work"]:
673
+ v.append(f"files in the work dir: {left['work']}")
674
+ if (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True):
675
+ notes.append("image forwarding (model calls image()) is not visible in --json; needs the model proxy (P1)")
676
+ mcp_env = None
677
+ mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
678
+ if os.path.exists(mt):
679
+ for line in open(mt):
680
+ d = json.loads(line)
681
+ if d.get("ev") == "start" and "env_keys" in d:
682
+ mcp_env = d["env_keys"]
683
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, threads_rows=threads,
684
+ mcp_server_env_keys=mcp_env, item_types=sorted(set(items)), errors=h.info.get("errors"), ok=not v)
685
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
686
+ json.dump(out, f, indent=1)
687
+ return out
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/contract.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Information contract of one run (docs/15 §1 layer 2) and its hash `contract_sha256`.
2
+
3
+ The contract is everything the agent is given that must be identical across harnesses and models for the same
4
+ instance and condition: the README text, the three tool schemas, the image spec, the feedback level, --hide-k, the
5
+ budgets, the memory condition, the task and seed, and the code that builds the scene and judges it. Two runs whose
6
+ `contract_sha256` differ must not share a table cell.
7
+
8
+ What is NOT in the contract on purpose: the harness (it is the thing being compared), the model, the port, the
9
+ sandbox / log paths, timestamps.
10
+
11
+ contract = build_contract(log_dir) # reads session.json, agent_iface.json, events.jsonl, README.md
12
+ contract_sha256(contract) # sha256 of the canonical JSON
13
+ write_contract(log_dir) # -> <log_dir>/contract.json, returns (contract, sha)
14
+ """
15
+ import glob
16
+ import hashlib
17
+ import json
18
+ import os
19
+ import re
20
+ import sys
21
+
22
+ ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # the lffbench repo
23
+ CONTRACT_VERSION = 1
24
+ IMAGE_SPEC = dict(cameras=["agentview", "wrist"], width=512, height=512, format="JPEG", jpeg_quality=90,
25
+ delivery="files in the workspace, viewed with view_images (bytes unchanged)")
26
+ # code that builds the scene, runs the robot and judges the result (task modules are added per task)
27
+ SERVER_CODE = ["lffbench/agent/robot_server.py", "lffbench/agent/tools.py", "lffbench/agent/camera.py",
28
+ "lffbench/agent/context.py", "lffbench/agent/images.py", "lffbench/envs.py", "lffbench/skills.py",
29
+ "lffbench/task_base.py", "lffbench/bddl.py", "lffbench/objects.py"]
30
+ # real-robot backend (added for real_* tasks only; the driver itself is recorded as contract["real_driver"])
31
+ REAL_CODE = ["lffbench/real/tasks.py", "lffbench/real/session.py", "lffbench/real/executor.py", "lffbench/real/protocol.py"]
32
+
33
+
34
+ def sha256_bytes(b):
35
+ return hashlib.sha256(b).hexdigest()
36
+
37
+
38
+ def sha256_text(s):
39
+ return sha256_bytes(s.encode("utf-8"))
40
+
41
+
42
+ def sha256_file(path):
43
+ h = hashlib.sha256()
44
+ with open(path, "rb") as f:
45
+ for chunk in iter(lambda: f.read(1 << 20), b""):
46
+ h.update(chunk)
47
+ return h.hexdigest()
48
+
49
+
50
+ def canonical(obj):
51
+ return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
52
+
53
+
54
+ def sha256_json(obj):
55
+ return sha256_text(canonical(obj))
56
+
57
+
58
+ def tool_schemas():
59
+ """The three LA tools exactly as the reference driver and the MCP server define them."""
60
+ sys.path.insert(0, os.path.join(ROOT, "scripts"))
61
+ from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, PREAMBLE_LA # noqa: E402
62
+ return [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA], PREAMBLE_LA
63
+
64
+
65
+ def task_module_files(task):
66
+ """Source files of the task class `task` (found by its `name = "<task>"` line; .bak files are ignored)."""
67
+ pat = re.compile(r"""^\s*name\s*=\s*["']%s["']""" % re.escape(task), re.M)
68
+ hits = []
69
+ for p in sorted(glob.glob(os.path.join(ROOT, "lffbench", "tasks", "*.py"))):
70
+ try:
71
+ if pat.search(open(p, encoding="utf-8").read()):
72
+ hits.append(os.path.relpath(p, ROOT))
73
+ except OSError:
74
+ pass
75
+ arm = os.path.join(ROOT, "lffbench", "arm_specs", f"{task}.py")
76
+ if os.path.exists(arm):
77
+ hits.append(os.path.relpath(arm, ROOT))
78
+ real = os.path.join(ROOT, "lffbench", "real", "tasks.py") # real-robot tasks (docs/17): add the real backend's code
79
+ if not hits and os.path.exists(real) and pat.search(open(real, encoding="utf-8").read()):
80
+ hits += REAL_CODE
81
+ return hits
82
+
83
+
84
+ def server_code_sha(task):
85
+ files = SERVER_CODE + task_module_files(task)
86
+ per = {f: (sha256_file(os.path.join(ROOT, f)) if os.path.exists(os.path.join(ROOT, f)) else None) for f in files}
87
+ return sha256_json(per), per
88
+
89
+
90
+ def session_start(log_dir):
91
+ with open(os.path.join(log_dir, "events.jsonl")) as f:
92
+ for line in f:
93
+ d = json.loads(line)
94
+ if d.get("ev") == "session_start":
95
+ return d
96
+ raise RuntimeError(f"no session_start event in {log_dir}/events.jsonl")
97
+
98
+
99
+ def readme_budget(readme):
100
+ """The per-attempt budgets as the README states them (what the agent is told)."""
101
+ out = {}
102
+ for key, pat in (("robot_commands", r"at most (\d+) robot commands"),
103
+ ("sim_seconds", r"at most ([\d.]+) s of (?:simulated )?robot motion"), # real robot: "s of robot motion"
104
+ ("tool_calls", r"at most (\d+) tool calls")):
105
+ m = re.search(pat, readme)
106
+ out[key] = float(m.group(1)) if m and "." in m.group(1) else (int(m.group(1)) if m else None)
107
+ return out
108
+
109
+
110
+ def build_contract(log_dir):
111
+ log_dir = os.path.abspath(log_dir)
112
+ sess = json.load(open(os.path.join(log_dir, "session.json")))
113
+ iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
114
+ st = session_start(log_dir)
115
+ readme = open(os.path.join(sess["sandbox"], "README.md"), encoding="utf-8").read()
116
+ tools, preamble = tool_schemas()
117
+ code_sha, code_files = server_code_sha(st["task"])
118
+ out = dict(
119
+ contract_version=CONTRACT_VERSION,
120
+ task=st["task"], seed=st["seed"],
121
+ readme_sha256=sha256_text(readme),
122
+ preamble_sha256=sha256_text(preamble),
123
+ tools=tools,
124
+ image_spec=dict(IMAGE_SPEC, perception=st.get("perception", iface.get("perception"))),
125
+ feedback=st.get("feedback"), instruction=st.get("instruction"),
126
+ memory=st.get("memory"), k=st.get("k"), k_shown=st.get("k_shown"), hide_k=st.get("k_shown") != st.get("k"),
127
+ protocol=st.get("protocol"), arm=st.get("arm"), dossier_sha256=sha256_text(st.get("dossier") or ""),
128
+ budget=dict(readme_budget(readme), max_tool_calls=iface.get("max_tool_calls"),
129
+ tool_call_budget_enforced_by="mcp_robot_server / api_player (per attempt)"),
130
+ agent_iface=iface.get("agent_iface"),
131
+ server_code_sha256=code_sha, server_code_files=code_files,
132
+ )
133
+ if st.get("backend") == "real": # only real-robot runs get this key, so simulated contracts are unchanged
134
+ di = st.get("driver_info") or {}
135
+ out["real_driver"] = {k: di.get(k) for k in ("protocol", "robot", "n_joints", "workspace", "yaw_range_deg",
136
+ "max_speed", "ik", "driver_version")}
137
+ out["real_agent_workspace"] = st.get("agent_workspace")
138
+ from .redteam import marker # adversarial acceptance runs only (harness_run --red-team): others are unchanged
139
+ rt = marker(log_dir)
140
+ if rt:
141
+ out["red_team"] = rt
142
+ return out
143
+
144
+
145
+ def contract_sha256(contract):
146
+ return sha256_json(contract)
147
+
148
+
149
+ def write_contract(log_dir):
150
+ c = build_contract(log_dir)
151
+ sha = contract_sha256(c)
152
+ with open(os.path.join(log_dir, "contract.json"), "w") as f:
153
+ json.dump(dict(contract_sha256=sha, contract=c), f, indent=1, ensure_ascii=False)
154
+ return c, sha
155
+
156
+
157
+ if __name__ == "__main__":
158
+ for d in sys.argv[1:]:
159
+ c, sha = write_contract(d)
160
+ print(sha, d)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/dsh.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DeepSeek Harness (`dsh`, deepseek-ai/deepseek-harness, developer preview) as a native harness.
2
+
3
+ Launch: `node <dsh>/lib/bin.js --profile headless --patch <one-time patch> --json <first message>`, process env exactly
4
+ the whitelist, a brand-new empty DSH_HOME and HOME under /tmp/lffstate/<hex>, work dir /tmp/lffrun/<12 hex>. The patch
5
+ is a Cordis overlay on the shipped headless profile: it switches off every built-in tool plugin and what serves only
6
+ them (memory-like instructions, skills, goals, web, sub-agents, plan mode, code-mode tool calls) and adds our MCP
7
+ server. What stays as shipped is the harness under test: its system prompt, agent loop, retry policy, compaction,
8
+ tool-result pruning and image offload.
9
+
10
+ Two more plugins are off because they are provider telemetry, not agent behaviour (model-hidden top-level request
11
+ fields, docs/deepseek-llm-api-wire-extensions.md): session-log-deepseek (`dsh_session_log`: the session log on every
12
+ request) and plugin-package-inventory-deepseek (`dsh_plugin_packages`). session-title-llm is off: an extra model call
13
+ that only names the session.
14
+
15
+ The model API is the direct DeepSeek adapter (Anthropic Messages, default root https://api.deepseek.com/anthropic, or
16
+ OpenCode Go's https://opencode.ai/inference/go; model id passed through, `output_config.effort`). DeepSeek's adapter uploads each request image through /v1/files and
17
+ sends file ids, falling back to inline base64; the model gateway allows the Files path for this harness
18
+ (scripts/model_gateway.py --allow-files), otherwise each image would first fail an upload.
19
+
20
+ Release layout (LFF_DSH_HOME, default /mnt/cpfs/workspace/env/dsh-<version>): bin/node (official Node.js build, no
21
+ dependency on /etc/dsw, so it runs in the jail) + node_modules/ from `npm install @deepseek-ai/dsh@<version>`. The pin
22
+ key's hash covers bin/node and package-lock.json.
23
+
24
+ Early exit: as for the other CLIs, the process ends when the model replies without a tool call, also mid-episode;
25
+ scripts/harness_run.py then sends the reference driver's nudge with `--session-id <id> <nudge>` (resume_argv).
26
+
27
+ The --json stream caps strings at 8 KiB and is not lossless, so the durable session log (session.v4.jsonl.zstd) is
28
+ copied into the run's log dir in audit(), before the one-time dirs are removed.
29
+
30
+ Fail-closed launch: as Claude Code (claude_code.py): the same argv / env against a local fake Anthropic server with a
31
+ schema-only MCP server; tools, system prompt, harness-added message prefix and parameters are hashed against the pin.
32
+ """
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import subprocess
38
+ import sys
39
+ import time
40
+
41
+ from . import contract as C
42
+ from . import pins
43
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
44
+ new_run_dir, proxy_env, snapshot_tree)
45
+ from .claude_code import MCP_TOOLS, request_fingerprint
46
+ from .fakeapi import FakeAnthropic
47
+ from .trajectory import TrajWriter, strip_mcp
48
+
49
+ ROOT = C.ROOT
50
+ MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
51
+ BASE_PATH = "/usr/bin:/bin"
52
+ DEFAULT_RELEASE = "/mnt/cpfs/workspace/env/dsh-0.2.1-rc.5"
53
+ DEEPSEEK_ANTHROPIC_URL = "https://api.deepseek.com/anthropic"
54
+ BIN_JS = os.path.join("node_modules", "@deepseek-ai", "dsh", "lib", "bin.js")
55
+ PACKAGE_JSON = os.path.join("node_modules", "@deepseek-ai", "dsh", "package.json")
56
+ CONTEXT_WINDOW = 1048576 # GET https://api.deepseek.com/models, DeepSeek-V4.1-Flash, 2026-10-30
57
+ SESSION_LOG = "session.v4.jsonl.zstd"
58
+ OK_EVENTS = ("session", "status", "text", "thinking", "tool_call", "tool_result", "final", "error")
59
+ # request fields of the provider telemetry plugins switched off in the patch: their return is a launch refusal
60
+ TELEMETRY_FIELDS = ("dsh_session_log", "dsh_plugin_packages")
61
+ DISABLE = ["tool-bash", "tool-pwsh", "tool-jobs", "tool-fs", "tool-fs-search", "tool-skill", "tool-todo", "tool-goal",
62
+ "tool-web", "tool-subagent", "tool-subagent-fork", "tool-subagent-control", "tool-workflow",
63
+ "tool-working-directory", "mcp-resources", "agent-instructions", "skill-filesystem", "skill",
64
+ "goal-round-driver", "command-goal", "goal", "plan-mode", "subagent-fork-in-process",
65
+ "subagent-spawn-in-process", "subagent", "workflow-ptc", "tool-executor-ptc", "ptc-runtime",
66
+ "web-fetch-http", "web-deepseek-api", "web-search-deepseek", "web", "session-title-llm",
67
+ "session-log-deepseek", "plugin-package-inventory-deepseek", "llm-deepseek-account"]
68
+
69
+
70
+ def release_dir():
71
+ return os.environ.get("LFF_DSH_HOME") or DEFAULT_RELEASE
72
+
73
+
74
+ def node_bin():
75
+ return os.path.join(release_dir(), "bin", "node")
76
+
77
+
78
+ def _yaml_str(s):
79
+ return json.dumps(s) # a JSON string is a valid YAML flow scalar
80
+
81
+
82
+ def patch_yaml(mcp_cmd, mcp_args, cwd, effort, base_url, model):
83
+ """The Cordis overlay of a run. A config override replaces the whole entry config, hence the full llm-deepseek row.
84
+ The model is declared in `models` because dsh treats a model id outside its built-in catalog as text-only
85
+ (docs/user/guide/providers.md), and the OpenCode Go id is one; capacity and image input from DeepSeek's /models."""
86
+ out = [f"- id: {name}\n disabled: true\n" for name in DISABLE]
87
+ out.append("- id: llm-deepseek\n config:\n"
88
+ f" baseURL: {_yaml_str(base_url)}\n apiKeyEnv: DEEPSEEK_API_KEY\n"
89
+ f" reasoningEffort: {_yaml_str(effort)}\n"
90
+ f" models:\n - id: {_yaml_str(model)}\n contextWindow: {CONTEXT_WINDOW}\n"
91
+ " inputModalities: [text, image]\n")
92
+ out.append("- insert:\n - id: mcp-lff\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n"
93
+ " serverName: lff\n transport: stdio\n"
94
+ f" command: {_yaml_str(mcp_cmd)}\n"
95
+ f" args: {json.dumps(list(mcp_args))}\n"
96
+ f" env: {{PATH: {_yaml_str(BASE_PATH)}}}\n"
97
+ f" cwd: {_yaml_str(cwd)}\n"
98
+ " toolCallTimeoutMs: 900000\n failOnStartupError: true\n")
99
+ return "".join(out)
100
+
101
+
102
+ class DeepSeekHarness(HarnessAdapter):
103
+ name = "dsh"
104
+ uses_mcp = True
105
+ can_resume = True
106
+ clean_dirs = ("home", "dsh_home", "tmp")
107
+ ancestor_files = ("AGENTS.md", "CLAUDE.md", ".dsh", ".agents")
108
+ capabilities = dict(
109
+ only_benchmark_tools=Cap("yes", "preflight", "built-in tool plugins off in the patch: request tools = 3 MCP "
110
+ "tools"),
111
+ images_reach_model=Cap("partial", "probe", "MCP images reach the model through dsh's request-image pipeline, "
112
+ "which resizes to DeepSeek's vision grid (at most 1024 tokens an image) and may offload "
113
+ "the oldest images of a long run; not byte-identical above that size"),
114
+ non_persistent_session=Cap("yes", "probe", "only this run's session (for --session-id) in the one-time "
115
+ "DSH_HOME, removed after the run"),
116
+ pinned_version=Cap("yes", "launch", "package version + hash of bin/node and package-lock.json in harness.json"),
117
+ machine_readable_events=Cap("partial", "stream", "--json NDJSON, strings capped at 8 KiB; the lossless session "
118
+ "log is copied into the log dir"),
119
+ tool_calls_logged=Cap("yes", "stream", "tool_call / tool_result in stream + mcp_transcript + events.jsonl"),
120
+ model_and_effort=Cap("yes", "preflight", "agent default model / llm-deepseek reasoningEffort; request "
121
+ "output_config.effort checked"),
122
+ persistent_memory=Cap("absent", "probe", "no memory plugin in the profile; empty one-time DSH_HOME"),
123
+ instruction_file_injection=Cap("absent", "preflight", "agent-instructions and skills plugins off; empty dirs"),
124
+ web_access=Cap("absent", "preflight", "web plugins off; no web tool in the request"),
125
+ host_file_read=Cap("absent", "preflight", "tool-fs / tool-fs-search off; MCP shell is jailed"),
126
+ builtin_shell=Cap("absent", "preflight", "tool-bash / tool-pwsh off; not in the request"),
127
+ subagent_delegation=Cap("absent", "preflight", "subagent plugins off; not in the request"),
128
+ background_execution=Cap("absent", "preflight", "tool-jobs off; not in the request"),
129
+ )
130
+
131
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, python=None,
132
+ extra_args=None, jail=False):
133
+ """api_env: {"DEEPSEEK_API_KEY": ...}; base_url: Messages root (default the official one; never read from the
134
+ calling environment)."""
135
+ self.release = release_dir()
136
+ self.node = node_bin()
137
+ if not os.access(self.node, os.X_OK):
138
+ raise HarnessRefused(f"dsh: no {self.node} (see lffbench/harnesses/dsh.py, release layout)")
139
+ if jail:
140
+ from .jail import HarnessJail
141
+ self.jail = HarnessJail(self.node, proc="host") # /proc: Node reads the host's cgroup / cpu files
142
+ self.api_env = dict(api_env or {})
143
+ self.base_url = base_url or DEEPSEEK_ANTHROPIC_URL
144
+ self.proxy = proxy_env()
145
+ self.timeout_s = timeout_s
146
+ self.pins_dir = pins_dir
147
+ self.allow_unpinned = allow_unpinned
148
+ self.python = python or sys.executable
149
+ self.extra_args = list(extra_args or [])
150
+ self._version = None
151
+
152
+ # ------------------------------------------------------------------------------------------------ version
153
+ def version(self):
154
+ if self._version is None:
155
+ pkg = json.load(open(os.path.join(self.release, PACKAGE_JSON)))
156
+ lock = C.sha256_file(os.path.join(self.release, "package-lock.json"))
157
+ node = binary_info(self.node)
158
+ self._version = dict(version=pkg["version"], binary=node, package_lock_sha256=lock,
159
+ pin_sha256=C.sha256_text(node["sha256"] + lock))
160
+ return self._version
161
+
162
+ def pin_key(self, ep):
163
+ v = self.version()
164
+ return pins.key(self.name, v["version"], v["pin_sha256"], ep.model, ep.effort)
165
+
166
+ def auth_info(self):
167
+ return dict(mode="apikey", keys=sorted(self.api_env))
168
+
169
+ # ------------------------------------------------------------------------------------------------ prepare
170
+ def bin_js(self):
171
+ """lib/bin.js as the process sees it: in the jail, inside the verified copy of the release dir."""
172
+ if self.jail is not None:
173
+ root = os.path.dirname(os.path.dirname(self.jail.binary_jailed))
174
+ return os.path.join(root, BIN_JS)
175
+ return os.path.join(self.release, BIN_JS)
176
+
177
+ def argv(self, patch_path, first_message):
178
+ return [self.node, self.bin_js(), "--profile", "headless", "--patch", patch_path, "--json"] + self.extra_args + [
179
+ first_message]
180
+
181
+ def write_patch(self, state, session_path, cwd, ep, base_url):
182
+ args = ["--session", session_path] if session_path else ["--schema-only"]
183
+ cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args)
184
+ path = os.path.join(state["state"], "patch.yml")
185
+ with open(path, "w") as f:
186
+ f.write(patch_yaml(cmd, a, cwd, ep.effort, base_url, ep.model))
187
+ return path
188
+
189
+ def env(self, state, base_url_unused=None):
190
+ e = dict(PATH=BASE_PATH, HOME=state["home"], DSH_HOME=state["dsh_home"], TMPDIR=state["tmp"], LANG="C.UTF-8",
191
+ NO_UPDATE_NOTIFIER="1")
192
+ e.update(self.proxy)
193
+ e.update(self.api_env)
194
+ return e
195
+
196
+ def _state_dirs(self, hexname=None):
197
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
198
+ os.makedirs(root, exist_ok=True)
199
+ state = dict(state=root, home=os.path.join(root, "home"), dsh_home=os.path.join(root, "dsh_home"),
200
+ tmp=os.path.join(root, "tmp"))
201
+ for k in ("home", "dsh_home", "tmp"):
202
+ os.makedirs(state[k], exist_ok=True)
203
+ return state
204
+
205
+ def _write_profile_default(self, state, ep):
206
+ """The run's model as the profile's default (a config override of agent-default-model) goes into the patch of
207
+ the same directory: dsh has no --model flag in headless mode."""
208
+ path = os.path.join(state["state"], "patch.yml")
209
+ with open(path, "a") as f:
210
+ f.write("- id: agent-default-model\n config:\n provider: deepseek-official\n"
211
+ f" model: {_yaml_str(ep.model)}\n")
212
+
213
+ def prepare(self, ep, first_message, reuse_state=None):
214
+ work = new_run_dir("/tmp/lffrun")
215
+ state = reuse_state or self._state_dirs(os.path.basename(work))
216
+ if self.jail is not None:
217
+ self.jail.stderr_dir = ep.log_dir
218
+ patch = self.write_patch(state, ep.session_path, work, ep, self.base_url)
219
+ self._write_profile_default(state, ep)
220
+ argv = self.argv(patch, first_message)
221
+ return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
222
+ first_message=first_message, config_files=dict(patch=patch),
223
+ stdout_path=os.path.join(ep.log_dir, "dsh_events.jsonl"),
224
+ stderr_path=os.path.join(ep.log_dir, "dsh_stderr.txt"),
225
+ redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
226
+ timeout_s=self.timeout_s)
227
+
228
+ def config_sha256(self, spec, ep):
229
+ """Hash of everything configurable: argv without the first message, the patch with the run's paths normalised,
230
+ env values except keys / one-time dirs."""
231
+ def norm(s):
232
+ s = s.replace(spec.state_dirs["state"], "<STATE>").replace(spec.cwd, "<CWD>").replace(ep.session_path,
233
+ "<SESSION>")
234
+ s = re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", s)
235
+ return re.sub(r"http://127\.0\.0\.1:\d+[^\"\s]*", "<MODEL_ENDPOINT>", s)
236
+ argv = [norm(a) for a in self.logged_argv(spec)[1:-1]]
237
+ patch = norm(open(spec.config_files["patch"]).read())
238
+ env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
239
+ if k not in ("HOME", "DSH_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
240
+ return C.sha256_json(dict(argv=argv, patch=patch, env=env))
241
+
242
+ # ------------------------------------------------------------------------------------------------ preflight
243
+ def preflight(self, spec, ep, record_dir=None):
244
+ t0 = time.time()
245
+ fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start()
246
+ pre = self._state_dirs()
247
+ try:
248
+ patch = self.write_patch(pre, None, spec.cwd, ep, fake.base_url)
249
+ self._write_profile_default(pre, ep)
250
+ argv = self.argv(patch, spec.first_message)
251
+ env = {k: v for k, v in self.env(pre).items() if k not in self.api_env}
252
+ env["DEEPSEEK_API_KEY"] = "sk-preflight-not-a-key"
253
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
254
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
255
+ reqs = fake.message_requests()
256
+ if not reqs:
257
+ raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): "
258
+ f"{r.stderr.decode('utf-8', 'replace')[-800:]}"
259
+ f"{r.stdout.decode('utf-8', 'replace')[-400:]}")
260
+ n, body = reqs[0]
261
+ fp, problems = request_fingerprint(body, {}, spec, spec.first_message)
262
+ fp.pop("anthropic_beta", None)
263
+ fp["body_keys"] = sorted(body)
264
+ for f in TELEMETRY_FIELDS:
265
+ if f in body:
266
+ problems.append(f"request carries the telemetry field {f}")
267
+ if os.listdir(spec.cwd):
268
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
269
+ fp_sha = C.sha256_json(fp)
270
+ out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs),
271
+ tools=[t["name"] for t in fp["tools"]],
272
+ effort_in_request=(fp["params"].get("output_config") or {}).get("effort"),
273
+ model_in_request=fp["params"].get("model"), dt_s=round(time.time() - t0, 1), problems=problems)
274
+ if out["effort_in_request"] != ep.effort:
275
+ problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}")
276
+ if out["model_in_request"] != ep.model:
277
+ problems.append(f"model in request {out['model_in_request']!r} != {ep.model!r}")
278
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
279
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
280
+ out["fingerprint"] = fp
281
+ if problems:
282
+ raise HarnessRefused("preflight: " + "; ".join(problems))
283
+ if pin is None:
284
+ if not self.allow_unpinned:
285
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
286
+ f"with --write-pins after the self-check passes)")
287
+ out["pin_status"] = "unpinned (allowed)"
288
+ elif pin["fingerprint_sha256"] != fp_sha:
289
+ raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
290
+ f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
291
+ else:
292
+ out["pin_status"] = "match"
293
+ return out
294
+ finally:
295
+ fake.stop()
296
+ shutil.rmtree(pre["state"], ignore_errors=True)
297
+
298
+ # ------------------------------------------------------------------------------------------------ resume
299
+ @staticmethod
300
+ def session_ids(stdout_path):
301
+ out = []
302
+ try:
303
+ for line in open(stdout_path, encoding="utf-8", errors="replace"):
304
+ if line.startswith('{"type":"session"'):
305
+ out.append(json.loads(line)["sessionId"])
306
+ except (OSError, ValueError, KeyError):
307
+ pass
308
+ return out
309
+
310
+ def resume_argv(self, h, message):
311
+ sids = self.session_ids(h.spec.stdout_path)
312
+ if not sids:
313
+ raise HarnessRefused("resume: no session id in the stream")
314
+ return list(h.spec.argv[:-1]) + ["--session-id", sids[0], message]
315
+
316
+ # ------------------------------------------------------------------------------------------------ collect
317
+ def collect(self, h):
318
+ spec, ep = h.spec, h.ep
319
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
320
+ usage, sid, kinds, errors, turn_ends, truncated = dict(input=0, cached=0, output=0, cache_write=0), None, [], [], [], 0
321
+ cur = None
322
+ for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
323
+ if not line.startswith("{"):
324
+ continue
325
+ d = json.loads(line)
326
+ t = d.get("type")
327
+ kinds.append(t)
328
+ truncated += bool(d.get("truncated"))
329
+ if t == "session":
330
+ sid = sid or d.get("sessionId")
331
+ elif t == "text":
332
+ cur = tw.add_step("agent", message=d.get("text", ""))
333
+ elif t == "thinking":
334
+ cur = tw.add_step("agent", reasoning=d.get("text", ""))
335
+ elif t == "tool_call":
336
+ tw.add_step("agent", tool_calls=[dict(tool_call_id=d.get("callId"), function_name=strip_mcp(d.get("tool")),
337
+ native_name=d.get("tool"), arguments=d.get("input"))])
338
+ elif t == "tool_result":
339
+ tw.add_result(d.get("callId"), d.get("result", ""), d.get("status") == "error", 0)
340
+ elif t == "status" and d.get("phase") == "step_end":
341
+ u = d.get("usage") or {}
342
+ usage["input"] += u.get("inputTokens") or 0
343
+ usage["output"] += u.get("outputTokens") or 0
344
+ usage["cached"] += u.get("cacheReadTokens") or 0
345
+ usage["cache_write"] += u.get("cacheWriteTokens") or 0
346
+ elif t == "status" and d.get("phase") == "turn_end":
347
+ turn_ends.append(d.get("reason"))
348
+ elif t == "error":
349
+ errors.append(d)
350
+ del cur
351
+ v = self.version()
352
+ tw.set_header(session_id=sid, source=os.path.basename(spec.stdout_path),
353
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
354
+ tools=MCP_TOOLS)
355
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], turn_ends=turn_ends[-5:]),
356
+ total_prompt_tokens=usage["input"] + usage["cached"] + usage["cache_write"],
357
+ total_completion_tokens=usage["output"], total_cached_tokens=usage["cached"],
358
+ total_cost_usd=None, segments=len(turn_ends), truncated_events=truncated)
359
+ tw.write()
360
+ h.info.update(kinds=kinds, traj=tw, session=sid, errors=errors, turn_ends=turn_ends)
361
+ return tw
362
+
363
+ # ------------------------------------------------------------------------------------------------ audit
364
+ def audit(self, h):
365
+ spec, ep = h.spec, h.ep
366
+ v, notes = [], []
367
+ bad = sorted({k for k in h.info.get("kinds") or [] if k not in OK_EVENTS})
368
+ if bad:
369
+ notes.append(f"unknown event types in the stream: {bad}")
370
+ tw = h.info.get("traj")
371
+ names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]]
372
+ badt = sorted({n for n in names if n not in MCP_TOOLS})
373
+ if badt:
374
+ notes.append(f"model asked for unavailable tools: {badt}")
375
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
376
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
377
+ left = dict(dsh_home=snapshot_tree(spec.state_dirs["dsh_home"]), home=snapshot_tree(spec.state_dirs["home"]),
378
+ work=snapshot_tree(spec.cwd))
379
+ sid = h.info.get("session")
380
+ logs = [p for p in left["dsh_home"] if p.endswith(SESSION_LOG)]
381
+ foreign = [p for p in logs if not (sid and f"/{sid}/" in p)]
382
+ if foreign:
383
+ v.append(f"session logs other than this run's: {foreign}")
384
+ for p in logs:
385
+ shutil.copy(os.path.join(spec.state_dirs["dsh_home"], p), os.path.join(ep.log_dir, SESSION_LOG))
386
+ if h.info.get("resumes"):
387
+ notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
388
+ f"episode was over)")
389
+ if left["work"]:
390
+ v.append(f"files in the work dir: {left['work']}")
391
+ mcp_env = None
392
+ mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
393
+ if os.path.exists(mt):
394
+ for line in open(mt):
395
+ d = json.loads(line)
396
+ if d.get("ev") == "start" and "env_keys" in d:
397
+ mcp_env = d["env_keys"]
398
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, mcp_server_env_keys=mcp_env,
399
+ errors=h.info.get("errors"), turn_ends=h.info.get("turn_ends"), tool_calls=len(names),
400
+ unavailable_tool_requests=badt, ok=not v)
401
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
402
+ json.dump(out, f, indent=1)
403
+ return out
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/embodied_evo.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """EmbodiedEvo's Codex launcher and skills/lessons workflow on LFF's MCP.
2
+
3
+ Controlled port: same-episode knowledge only, no Playground pretraining, recipes,
4
+ native simulator execution or reset. Programs generate/revise action plans in
5
+ shell; individual robot commands are executed through MCP. This is explicitly
6
+ not EmbodiedEvo's full native code-as-policy evaluation.
7
+ """
8
+ import copy
9
+ import hashlib
10
+ import importlib.util
11
+ import json
12
+ import os
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from . import contract as C, pins
18
+ from .base import HarnessRefused
19
+ from .codex import Codex, DISABLE, codex_bin
20
+ from .rpent import tree_sha256
21
+
22
+ DEFAULT_SOURCE = "/mnt/cpfs/workspace/env/embodied-evo/src"
23
+
24
+
25
+ def load_source(path, module_name):
26
+ if sys.version_info < (3, 11):
27
+ import tomli
28
+ sys.modules.setdefault("tomllib", tomli)
29
+ spec = importlib.util.spec_from_file_location(module_name, path)
30
+ mod = importlib.util.module_from_spec(spec)
31
+ spec.loader.exec_module(mod)
32
+ return mod
33
+
34
+
35
+ def workflow(source):
36
+ text = (Path(source) / "tasks/RoboDojo/Workspace/playground.md").read_text()
37
+ loop = text.split("Organize your work as an iterative loop:", 1)[1].split("# Environment and Primitives", 1)[0]
38
+ evolution = text.split("# Evolution: skills and lessons", 1)[1].split("# Playground rules", 1)[0]
39
+ evolution = evolution.replace("Read `skills/example.md` and `lessons/example.md` first.",
40
+ "Start with empty skills/ and lessons/; create them through shell when needed.")
41
+ return ("You are an embodied coding agent. Follow the EmbodiedEvo workflow below, adapted to the "
42
+ "benchmark's MCP interface. The benchmark instructions following this workflow are authoritative.\n\n"
43
+ "Organize your work as an iterative loop:" + loop + "\n# Skills and lessons\n" + evolution +
44
+ "\n# MCP adaptation\n"
45
+ "Use shell to write and run Python for visual analysis and incremental action-plan generation. "
46
+ "Keep reusable helpers and preconditions in skills/, failure evidence and corrections in lessons/, "
47
+ "and current plans in submission/. Execute each robot command with the robot MCP tool and inspect "
48
+ "its feedback before the next stage; Python in shell cannot contact the robot. Use view_images "
49
+ "for obs/ images. Do not assume scripts/env.py, native step(), get_observation(), reset(), or "
50
+ "Playground records exist. No preloaded recipes or skills are supplied. Preserve and revise your "
51
+ "skills and lessons across attempts of this episode only; the benchmark controls resets and "
52
+ "termination. Never replay earlier actions just because you rewrote a plan.\n\n")
53
+
54
+
55
+ class EmbodiedEvoCodex(Codex):
56
+ name = "embodied_evo_codex"
57
+
58
+ def __init__(self, *args, source=None, **kwargs):
59
+ self.source = source or os.environ.get("LFF_EMBODIED_EVO_SOURCE", DEFAULT_SOURCE)
60
+ self._source_info = None
61
+ self.prefix = workflow(self.source)
62
+ self.native_launch = load_source(Path(self.source) / "orchestrator/launch_agent.py", "lff_evo_launch")
63
+ self.native_recovery = load_source(Path(self.source) / "orchestrator/agent_recovery.py", "lff_evo_recovery")
64
+ super().__init__(*args, **kwargs)
65
+ if self.catalog != "generic":
66
+ raise HarnessRefused("EmbodiedEvo controlled variant requires generic catalog")
67
+
68
+ def source_info(self):
69
+ if self._source_info is None:
70
+ commit = subprocess.check_output(["git", "-C", self.source, "rev-parse", "HEAD"], text=True).strip()
71
+ self._source_info = dict(commit=commit, tree_sha256=tree_sha256(self.source),
72
+ workflow_sha256=hashlib.sha256(self.prefix.encode()).hexdigest())
73
+ return self._source_info
74
+
75
+ def version(self):
76
+ return dict(super().version(), framework=self.source_info())
77
+
78
+ def pin_key(self, ep):
79
+ v = self.version()
80
+ identity = C.sha256_json(v["framework"])[:12]
81
+ mode = "" if self.auth == "apikey" else "-chatgpt"
82
+ return pins.key(self.name + mode + "-generic-" + identity, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
83
+
84
+ def config_info(self):
85
+ return dict(super().config_info(), framework=self.source_info(), variant="mcp-skills-lessons",
86
+ history="same-thread", cross_episode_memory=False, native_code_execution=False)
87
+
88
+ def argv(self, ep, session_path, base_url, first_message, codex_home):
89
+ prompt = first_message if first_message.startswith(self.prefix) else self.prefix + first_message
90
+ args = self.native_launch.agent_argv("codex", prompt, model=ep.model, effort=ep.effort)
91
+ args[0] = codex_bin()
92
+ args[args.index("--sandbox") + 1] = "read-only"
93
+ # The benchmark fixes the middle layer; native orchestration provides the workflow and launch.
94
+ extra = ["--json", "--ignore-user-config", "--ignore-rules"]
95
+ for feature in DISABLE:
96
+ extra += ["--disable", feature]
97
+ for setting in self.config_args(ep, session_path, base_url, codex_home):
98
+ extra += ["-c", setting]
99
+ return args[:-1] + extra + [prompt]
100
+
101
+ def resume_argv(self, handle, message):
102
+ thread = self.thread_id(handle.spec.stdout_path)
103
+ if not thread:
104
+ raise HarnessRefused("EmbodiedEvo resume: missing current thread ID")
105
+ args = list(handle.spec.argv)
106
+ binary, args[0] = args[0], "codex"
107
+ i = args.index("--sandbox")
108
+ mode = args[i+1]
109
+ del args[i:i+2]
110
+ args[-1:-1] = ["-c", "sandbox_mode=" + json.dumps(mode)]
111
+ args = self.native_recovery.resume_argv(args, thread)
112
+ args[0], args[-1] = binary, message # benchmark-owned continuation; same native resume construction
113
+ return args
114
+
115
+ def preflight(self, spec, ep, record_dir=None):
116
+ proxy = copy.copy(spec)
117
+ proxy.first_message = self.prefix + spec.first_message
118
+ # super checks all middle-layer fields; this adapter's pin binds the source and workflow hash too.
119
+ out = super().preflight(proxy, ep, record_dir)
120
+ v = self.version()
121
+ anchor_name = "codex-generic" if self.auth == "apikey" else "codex-chatgpt-generic"
122
+ anchor_key = pins.key(anchor_name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
123
+ anchor = pins.load(anchor_key, self.pins_dir)
124
+ if anchor is None or anchor["fingerprint_sha256"] != out["fingerprint_sha256"]:
125
+ raise HarnessRefused("EmbodiedEvo middle layer does not match the pinned Codex baseline")
126
+ out.update(anchor_status="match", middle_fingerprint_sha256=out["fingerprint_sha256"],
127
+ framework_prefix_sha256=self.source_info()["workflow_sha256"],
128
+ framework_prefix_chars=len(self.prefix))
129
+ return out
130
+
131
+ def collect(self, handle):
132
+ traj = super().collect(handle)
133
+ # Preserve provenance alongside native CLI traces.
134
+ (Path(handle.ep.log_dir) / "framework.json").write_text(json.dumps(self.config_info(), indent=2))
135
+ return traj
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/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/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/framework_codex.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared launcher for robot frameworks using a native Codex backend.
2
+
3
+ The external integration contract is Session.first_message(), Session.tool_specs(),
4
+ and Session.call(name, arguments). This launcher owns isolation, model configuration,
5
+ pins, trajectory collection and audits; framework plugins own their native loop.
6
+ Based on the validated RPent launcher; RPent's historical launcher remains frozen.
7
+ """
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import time
14
+
15
+ from . import contract as C
16
+ from . import pins
17
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
18
+ gateway_env, new_run_dir, proxy_env, snapshot_tree)
19
+ from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
20
+ request_fingerprint, toml_str)
21
+ from .fakeapi import FakeResponses
22
+ from .trajectory import TrajWriter
23
+
24
+ ROOT = C.ROOT
25
+ JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework"
26
+ BASE_PATH = "/usr/bin:/bin"
27
+ MCP_SERVER = "lff"
28
+ MCP_TOOLS = ["robot", "shell", "view_images"]
29
+ TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"}
30
+
31
+
32
+
33
+ def tree_sha256(root, skip=TREE_SKIP):
34
+ """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
35
+ h = hashlib.sha256()
36
+ for dp, dn, fn in os.walk(root):
37
+ dn[:] = sorted(d for d in dn if d not in skip)
38
+ for f in sorted(fn):
39
+ if f.endswith(".pyc"):
40
+ continue
41
+ p = os.path.join(dp, f)
42
+ rel = os.path.relpath(p, root)
43
+ if os.path.islink(p):
44
+ h.update(f"L {rel} {os.readlink(p)}\n".encode())
45
+ else:
46
+ h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
47
+ return h.hexdigest()
48
+
49
+
50
+ def runtime_info(home):
51
+ """The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
52
+ src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
53
+ for d in (src, venv):
54
+ if not os.path.isdir(d):
55
+ raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)")
56
+
57
+ def git(*a):
58
+ r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
59
+ return r.stdout.strip() if r.returncode == 0 else None
60
+ commit = git("rev-parse", "HEAD")
61
+ patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
62
+ untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
63
+ return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
64
+ untracked=sorted(u for u in untracked if "__pycache__" not in u),
65
+ tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
66
+
67
+
68
+ def jail_runtime_copy(home, tree):
69
+ """A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not)."""
70
+ dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}")
71
+ stamp = os.path.join(dst, ".tree_sha256")
72
+ if os.path.exists(stamp) and open(stamp).read().strip() == tree:
73
+ return dst
74
+ os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True)
75
+ tmp = dst + ".tmp-" + os.urandom(3).hex()
76
+ shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
77
+ ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
78
+ shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
79
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
80
+ got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
81
+ ).hexdigest()
82
+ if got != tree:
83
+ shutil.rmtree(tmp, ignore_errors=True)
84
+ raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
85
+ for dp, dn, fn in os.walk(tmp):
86
+ os.chmod(dp, 0o755)
87
+ for f in fn:
88
+ p = os.path.join(dp, f)
89
+ if not os.path.islink(p):
90
+ os.chmod(p, os.stat(p).st_mode | 0o444)
91
+ with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
92
+ f.write(tree)
93
+ if os.path.exists(dst):
94
+ shutil.rmtree(dst)
95
+ os.rename(tmp, dst)
96
+ return dst
97
+
98
+
99
+ def codex_overrides(effort, catalog_path):
100
+ """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
101
+ overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process)."""
102
+ return (["model_reasoning_effort=" + toml_str(effort),
103
+ "include_permissions_instructions=false", "include_environment_context=false",
104
+ "include_collaboration_mode_instructions=false", "skills.include_instructions=false",
105
+ "skills.bundled.enabled=false", 'web_search="disabled"',
106
+ f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
107
+ f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
108
+ f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
109
+ f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
110
+ "model_catalog_json=" + toml_str(catalog_path)]
111
+ + [f"features.{f}=false" for f in DISABLE])
112
+
113
+
114
+ def _items(stream_path):
115
+ """Codex app-server notifications of one robot framework session (robot framework writes them as JSONL)."""
116
+ out = []
117
+ if not os.path.exists(stream_path):
118
+ return out
119
+ for line in open(stream_path, encoding="utf-8", errors="replace"):
120
+ try:
121
+ out.append(json.loads(line))
122
+ except ValueError:
123
+ continue
124
+ return out
125
+
126
+
127
+ def _item_of(ev):
128
+ it = (ev.get("payload") or {}).get("item") or {}
129
+ return it.get("root", it) if isinstance(it, dict) else {}
130
+
131
+
132
+ class RobotFrameworkCodex(HarnessAdapter):
133
+ name = "framework_codex"
134
+ runtime_home = "/nonexistent"
135
+ runtime_module = "lff_integration.run"
136
+ default_steps = 500
137
+ uses_mcp = False
138
+ uses_gateway = True
139
+ can_resume = False
140
+ clean_dirs = ("home", "codex_home", "tmp", "out")
141
+ clean_allowed = {"codex_home": (CATALOG_FILE,)}
142
+ ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
143
+ capabilities = dict(
144
+ only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
145
+ "mcp__lff functions + residual resource×3 / request_user_input; robot framework registers "
146
+ "no tool of its own (no file tools, no finish)"),
147
+ images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, "
148
+ "JPEG with its own MIME type"),
149
+ non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the "
150
+ "run; no preloaded or cross-episode framework memory"),
151
+ pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in "
152
+ "harness.json; pin per version and tree"),
153
+ machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session "
154
+ "(codex.out.stream.jsonl) + robot framework run.json"),
155
+ tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"),
156
+ model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
157
+ persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not "
158
+ "constructed"),
159
+ instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
160
+ web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
161
+ host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
162
+ builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
163
+ subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
164
+ background_execution=Cap("absent", "preflight", "no background tool in the request"),
165
+ )
166
+
167
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
168
+ jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500,
169
+ home=None, provider=None, auth_home=None):
170
+ """Common controlled Codex SDK launcher.
171
+
172
+ The plugin entrypoint interprets its declared loop options. For SenseNova,
173
+ max_turns is the upstream SDK-step limit, not a provider-response count.
174
+ Robot commands, simulation time and tool budgets are always server-owned.
175
+ """
176
+ if auth not in ("apikey", "chatgpt"):
177
+ raise ValueError("framework_codex auth must be apikey or chatgpt")
178
+ if catalog not in CATALOGS:
179
+ raise ValueError(f"catalog must be one of {CATALOGS}")
180
+ self.auth, self.catalog = auth, catalog
181
+ self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog)
182
+ self.api_env = self._auth_manager.api_env
183
+ self.base_url = self._auth_manager.base_url
184
+ self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
185
+ self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
186
+ self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
187
+ int(max_turns)
188
+ self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home
189
+ self.proxy = proxy_env()
190
+ self._version = None
191
+ self._runtime = None
192
+ self.runtime_dir = self.home
193
+ if jail:
194
+ from .jail import HarnessJail
195
+ self.jail = HarnessJail(codex_bin(), proc="static")
196
+
197
+ # ------------------------------------------------------------------------------------------------ identity
198
+ def runtime(self):
199
+ if self._runtime is None:
200
+ self._runtime = runtime_info(self.home)
201
+ if self.jail is not None:
202
+ self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
203
+ return self._runtime
204
+
205
+ def version(self):
206
+ if self._version is None:
207
+ b = codex_bin()
208
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
209
+ CODEX_HOME="/nonexistent"),
210
+ capture_output=True, text=True, timeout=60)
211
+ v = (out.stdout.strip().split() or ["?"])[-1]
212
+ rt = self.runtime()
213
+ self._version = dict(version=v, binary=binary_info(b),
214
+ framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
215
+ tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
216
+ return self._version
217
+
218
+ def pin_key(self, ep):
219
+ v = self.version()
220
+ mode = "" if self.auth == "apikey" else "-chatgpt"
221
+ name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}"
222
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
223
+
224
+ def anchor_pin_key(self, ep):
225
+ """The main table's codex pin for the same model / effort (apikey, same catalog)."""
226
+ v = self.version()
227
+ name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}")
228
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
229
+
230
+ def auth_info(self):
231
+ if self.auth == "chatgpt":
232
+ return self._auth_manager.auth_info()
233
+ return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
234
+ "OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
235
+
236
+ def config_info(self):
237
+ return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
238
+ max_turns=self.max_turns, framework=self.version()["framework"])
239
+
240
+ # ------------------------------------------------------------------------------------------------ prepare
241
+ def _state_dirs(self, hexname=None):
242
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
243
+ os.makedirs(root, exist_ok=True)
244
+ state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
245
+ for k in ("home", "codex_home", "tmp", "out"):
246
+ os.makedirs(state[k], exist_ok=True)
247
+ return state
248
+
249
+ def _install_catalog(self, codex_home, ep):
250
+ cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
251
+ path = os.path.join(codex_home, CATALOG_FILE)
252
+ with open(path, "w") as f:
253
+ json.dump(cat, f)
254
+ return path, C.sha256_file(path), os.path.relpath(src, ROOT)
255
+
256
+ def argv(self, ep, out_dir, sessions=None, preflight=False):
257
+ py = os.path.join(self.runtime_dir, "venv", "bin", "python")
258
+ return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
259
+ "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
260
+ "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
261
+ + (["--no-continue"] if preflight else [])
262
+
263
+ def env(self, state, ep, base_url, work):
264
+ e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
265
+ CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
266
+ CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER,
267
+ FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
268
+ ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
269
+ FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
270
+ PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
271
+ if self.auth == "chatgpt":
272
+ # The native API provider declares env_key. Codex app-server still requires that
273
+ # variable even with requires_openai_auth=true, so select a separate provider
274
+ # with no env_key. Do not inject a dummy key or modify the upstream runtime.
275
+ provider_id = "lffsubscription"
276
+ overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"])
277
+ overrides += ["model_provider=" + toml_str(provider_id),
278
+ f"model_providers.{provider_id}.name=" + toml_str(provider_id),
279
+ f"model_providers.{provider_id}.wire_api=\"responses\"",
280
+ f"model_providers.{provider_id}.base_url=" + toml_str(base_url),
281
+ f"model_providers.{provider_id}.requires_openai_auth=true"]
282
+ e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides)
283
+ e.update(self.proxy)
284
+ if self.api_env.get("OPENAI_API_KEY"):
285
+ e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
286
+ return e
287
+
288
+ def prepare(self, ep, first_message, reuse_state=None):
289
+ self.version()
290
+ work = new_run_dir("/tmp/lffrun")
291
+ state = reuse_state or self._state_dirs(os.path.basename(work))
292
+ if self.jail is not None:
293
+ self.jail.stderr_dir = ep.log_dir
294
+ if not reuse_state and os.listdir(state["codex_home"]):
295
+ raise HarnessRefused("CODEX_HOME is not empty")
296
+ cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
297
+ return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
298
+ run_dir=work, state_dirs=state, first_message=first_message,
299
+ stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"),
300
+ stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"),
301
+ config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
302
+ catalog=self.catalog, code_mode=False)),
303
+ timeout_s=self.timeout_s)
304
+
305
+ def config_sha256(self, spec, ep):
306
+ argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<FRAMEWORK>")
307
+ for a in spec.argv]
308
+ hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH",
309
+ "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
310
+ env = {k: v for k, v in spec.env.items() if k not in hidden}
311
+ env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace(
312
+ spec.state_dirs["codex_home"], "<CODEX_HOME>")
313
+ cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
314
+ return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
315
+ framework_tree_sha256=self.version()["framework"]["tree_sha256"]))
316
+
317
+ # ------------------------------------------------------------------------------------------------ launch
318
+ def launch(self, spec, ep, skip_preflight=False):
319
+ """harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
320
+ self._auth_manager._install_auth(spec.state_dirs["codex_home"])
321
+ spec.env.update(gateway_env(ep.log_dir))
322
+ return super().launch(spec, ep, skip_preflight=skip_preflight)
323
+
324
+ def cleanup(self, spec):
325
+ self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", ""))
326
+ super().cleanup(spec)
327
+
328
+ def preflight(self, spec, ep, record_dir=None):
329
+ """The same framework process, one session, against a local fake Responses server that answers with text
330
+ only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
331
+ sandbox, robot framework's prefix + our first message) against the pins."""
332
+ t0 = time.time()
333
+ fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
334
+ pre = self._state_dirs()
335
+ try:
336
+ self._auth_manager._install_auth(pre["codex_home"])
337
+ self._install_catalog(pre["codex_home"], ep)
338
+ env = self.env(pre, ep, fake.base_url, spec.cwd)
339
+ if self.auth == "apikey":
340
+ env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
341
+ env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
342
+ argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
343
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
344
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
345
+ reqs = fake.model_requests()
346
+ if not reqs:
347
+ # Native planners may record failures only in run.json, with empty stdout/stderr.
348
+ record = os.path.join(pre["out"], "run.json")
349
+ detail = ""
350
+ if os.path.isfile(record):
351
+ with open(record) as f:
352
+ failed_run = json.load(f)
353
+ detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error"))
354
+ raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
355
+ f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}")
356
+ body = reqs[0][1]
357
+ fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
358
+ problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
359
+ users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
360
+ and it.get("role") == "user" for c in it.get("content") or []]
361
+ prefix = None
362
+ if len(users) != 1 or not users[0].endswith(spec.first_message):
363
+ problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
364
+ else:
365
+ prefix = users[0][:-len(spec.first_message)]
366
+ effort = (fp["params"].get("reasoning") or {}).get("effort")
367
+ if effort != ep.effort:
368
+ problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
369
+ if fp["params"].get("model") != ep.model:
370
+ problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
371
+ if os.listdir(spec.cwd):
372
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
373
+ mid_sha = C.sha256_json(fp)
374
+ full = dict(middle=fp, framework_prefix=prefix)
375
+ fp_sha = C.sha256_json(full)
376
+ anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
377
+ out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
378
+ framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
379
+ framework_prefix_chars=len(prefix) if prefix is not None else None,
380
+ developer_chars=fp["developer_chars"], n_requests=len(reqs),
381
+ top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
382
+ model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
383
+ dt_s=round(time.time() - t0, 1), problems=problems,
384
+ anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
385
+ if anchor is None:
386
+ out["anchor_status"] = "no main-table pin for this model / effort"
387
+ elif anchor["fingerprint_sha256"] != mid_sha:
388
+ problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
389
+ f"({anchor['key']}): the middle layer is not the main table's")
390
+ else:
391
+ out["anchor_status"] = "match"
392
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
393
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
394
+ out["fingerprint"] = full
395
+ if problems:
396
+ raise HarnessRefused("preflight: " + "; ".join(problems))
397
+ if pin is None:
398
+ if not self.allow_unpinned:
399
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
400
+ f"with --write-pins after the self-check passes)")
401
+ out["pin_status"] = "unpinned (allowed)"
402
+ elif pin["fingerprint_sha256"] != fp_sha:
403
+ raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
404
+ f"({pin['key']})")
405
+ else:
406
+ out["pin_status"] = "match"
407
+ return out
408
+ finally:
409
+ fake.stop()
410
+ self._auth_manager._sync_auth_back(pre["codex_home"])
411
+ shutil.rmtree(pre["state"], ignore_errors=True)
412
+
413
+ # ------------------------------------------------------------------------------------------------ collect
414
+ def collect(self, h):
415
+ spec, ep = h.spec, h.ep
416
+ dst = os.path.join(ep.log_dir, "framework")
417
+ if os.path.isdir(spec.state_dirs["out"]):
418
+ shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
419
+ run = {}
420
+ if os.path.exists(os.path.join(dst, "run.json")):
421
+ run = json.load(open(os.path.join(dst, "run.json")))
422
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
423
+ usage = dict(input=0, cached=0, output=0, reasoning=0)
424
+ items, threads, errors = [], [], []
425
+ for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
426
+ else []:
427
+ last = None
428
+ for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
429
+ m = ev.get("method") or ev.get("type")
430
+ p = ev.get("payload") or {}
431
+ if m == "thread/tokenUsage/updated":
432
+ last = (p.get("token_usage") or {}).get("total") or last
433
+ if p.get("thread_id") and p["thread_id"] not in threads:
434
+ threads.append(p["thread_id"])
435
+ elif m in ("error", "fatal", "timeout"):
436
+ errors.append(ev)
437
+ elif m == "item/completed":
438
+ it = _item_of(ev)
439
+ t = it.get("type")
440
+ items.append(t)
441
+ if t == "agentMessage":
442
+ tw.add_step("agent", message=it.get("text", ""))
443
+ elif t == "reasoning":
444
+ tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
445
+ elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
446
+ name = it.get("tool") or t
447
+ tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
448
+ native_name=f"{it.get('server', '')}.{name}",
449
+ item_type=t, arguments=it.get("arguments"),
450
+ session=sdir)])
451
+ res = it.get("result") or {}
452
+ texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
453
+ imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
454
+ tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
455
+ bool(it.get("error")) or it.get("status") == "failed", imgs)
456
+ if last:
457
+ usage["input"] += last.get("input_tokens") or 0
458
+ usage["cached"] += last.get("cached_input_tokens") or 0
459
+ usage["output"] += last.get("output_tokens") or 0
460
+ usage["reasoning"] += last.get("reasoning_output_tokens") or 0
461
+ # Framework close-out uses the same counted gateway shell, outside
462
+ # the model stream. Keep it visible in trajectories and tool totals.
463
+ session_record = next((s for s in run.get("sessions", [])
464
+ if sdir == f"session_{s['number']:03d}"), {})
465
+ handoff = session_record.get("handoff") or {}
466
+ if handoff:
467
+ call_id = f"framework-handoff-{sdir}"
468
+ tw.add_step("framework", tool_calls=[dict(
469
+ tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
470
+ item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
471
+ tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
472
+ if c.get("type") == "text"))
473
+ v = self.version()
474
+ tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl",
475
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
476
+ framework=v["framework"]), tools=EXPECTED_TOP_GENERIC)
477
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
478
+ run={k: run.get(k) for k in ("stop", "finished",
479
+ "attempts_failed", "tool_calls")},
480
+ sessions=len(run.get("sessions") or [])),
481
+ total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
482
+ total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
483
+ tw.write()
484
+ h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
485
+ return tw
486
+
487
+ # ------------------------------------------------------------------------------------------------ audit
488
+ def audit(self, h):
489
+ spec, ep = h.spec, h.ep
490
+ v, notes = [], []
491
+ items = h.info.get("items") or []
492
+ bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
493
+ "plan", "hookPrompt")})
494
+ if bad:
495
+ v.append(f"items other than messages / reasoning / MCP calls: {bad}")
496
+ residual = []
497
+ tw = h.info.get("traj")
498
+ for st in (tw.steps if tw else []):
499
+ for tc in st["tool_calls"]:
500
+ if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
501
+ continue
502
+ if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
503
+ residual.append(tc["function_name"])
504
+ else:
505
+ v.append(f"unexpected tool call {tc['native_name']}")
506
+ if residual:
507
+ notes.append(f"residual MCP-resource tool calls (empty): {residual}")
508
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
509
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
510
+ run = h.info.get("run") or {}
511
+ nsess = len(run.get("sessions") or [])
512
+ if len(h.info.get("threads") or []) > max(1, nsess):
513
+ v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions")
514
+ if nsess > 1:
515
+ notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)")
516
+ if run.get("stop") not in (None, "episode over"):
517
+ notes.append(f"robot framework stopped: {run.get('stop')}")
518
+ left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
519
+ work=snapshot_tree(spec.cwd))
520
+ if left["work"]:
521
+ v.append(f"files in the work dir: {left['work']}")
522
+ foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
523
+ and not any(t in f for t in (h.info.get("threads") or []))]
524
+ if foreign:
525
+ v.append(f"session files other than this run's threads: {foreign}")
526
+ gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
527
+ faces = set()
528
+ if os.path.exists(gt):
529
+ for line in open(gt):
530
+ try:
531
+ d = json.loads(line)
532
+ except ValueError:
533
+ continue
534
+ if d.get("ev") == "tool" and d.get("face"):
535
+ faces.add(d["face"])
536
+ if faces - {self.name}:
537
+ v.append(f"gateway calls from other access paths: {sorted(faces)}")
538
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
539
+ item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
540
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
541
+ json.dump(out, f, indent=1)
542
+ return out
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/jail.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Jail for native harness processes (docs/15 §3.4): the harness sees no host path at all, instead of only "having no
2
+ tool that reads files".
3
+
4
+ Without it, Claude Code / Codex run as root on the host with /mnt visible (task code with the hidden-variable rules,
5
+ task cards, earlier runs' logs, .secrets); isolation then rests on every built-in tool being switched off. With it
6
+ (adapter option jail=True, `harness_run.py --jail`, `api_batch.py start --jail`):
7
+ - the harness runs as the unprivileged host user nobody (uid 65534) in new user + mount namespaces
8
+ (jail/harness_jail_inner.sh, installed under /opt/lffjail/hjail by jail/setup_harness_jail.sh): /mnt /home /root
9
+ /tmp /run/secrets /etc/dsw are empty tmpfs, system dirs read-only, all capabilities dropped; the network stays
10
+ (model API);
11
+ - /proc: "static" (Codex) = a read-only tmpfs with static copies of host-wide files (CPU, memory, kernel version) and
12
+ the process's own self/ entries, no other pid; "host" (Claude Code, a Bun executable that aborts without a real
13
+ procfs; a fresh procfs cannot be mounted in this container because its /proc has locked submounts) = the host
14
+ procfs, where as uid 65534 the harness can list processes and read their command lines but not their environ, fd,
15
+ cwd or root (checked in tests/harness_selfcheck/jail_probe.py);
16
+ - visible again, at their original paths: the one-time work dir, the one-time state dir and the socket dir of the
17
+ MCP relay (chowned to uid 65534); the harness binary runs from a verified copy of its release dir under
18
+ /opt/lffjail/hjail/bin (the original lives under 0700 dirs in /mnt);
19
+ - the MCP server (scripts/mcp_robot_server.py) runs outside the jail; the harness starts the relay
20
+ /opt/lffjail/hjail/mcp_fwd.py, which connects to a Unix socket served here: every connection gets its own MCP
21
+ server process with stdin / stdout on the socket and the environment {PATH} only.
22
+ The harness command line (except argv[0] = the copy), its environment (exact whitelist) and the paths it sees are
23
+ unchanged; only the MCP server entry of its config points to the relay.
24
+ """
25
+ import hashlib
26
+ import os
27
+ import secrets
28
+ import shutil
29
+ import socket
30
+ import subprocess
31
+ import threading
32
+
33
+ JAIL_DIR = "/opt/lffjail/hjail"
34
+ INNER = os.path.join(JAIL_DIR, "inner.sh")
35
+ RELAY = os.path.join(JAIL_DIR, "mcp_fwd.py")
36
+ BIN_DIR = os.path.join(JAIL_DIR, "bin")
37
+ RELAY_PYTHON = "/usr/bin/python3"
38
+ SOCK_ROOT = "/tmp/lffsock"
39
+ JAIL_UID = 65534
40
+ MAX_BINDS = 16
41
+
42
+
43
+ class JailError(RuntimeError):
44
+ pass
45
+
46
+
47
+ def installed_problems():
48
+ p = []
49
+ for f in (INNER, RELAY):
50
+ if not os.path.exists(f):
51
+ p.append(f"{f} missing (sudo bash jail/setup_harness_jail.sh)")
52
+ if not os.path.isdir(os.path.join(JAIL_DIR, "stage", str(MAX_BINDS - 1))):
53
+ p.append(f"{JAIL_DIR}/stage/0..{MAX_BINDS - 1} missing (sudo bash jail/setup_harness_jail.sh)")
54
+ if not os.access(RELAY_PYTHON, os.X_OK):
55
+ p.append(f"{RELAY_PYTHON} missing")
56
+ for t in ("unshare", "setpriv"):
57
+ if not shutil.which(t):
58
+ p.append(f"{t} not found")
59
+ return p
60
+
61
+
62
+ def sha256_file(path):
63
+ h = hashlib.sha256()
64
+ with open(path, "rb") as f:
65
+ for b in iter(lambda: f.read(1 << 20), b""):
66
+ h.update(b)
67
+ return h.hexdigest()
68
+
69
+
70
+ def _outermost(dirs):
71
+ """Drop directories that lie inside another one of the list (one bind mount covers them)."""
72
+ ds = sorted({os.path.realpath(d) for d in dirs if d}, key=len)
73
+ out = []
74
+ for d in ds:
75
+ if not any(d == o or d.startswith(o.rstrip("/") + "/") for o in out):
76
+ out.append(d)
77
+ return out
78
+
79
+
80
+ def _chown_tree(root, uid):
81
+ os.chown(root, uid, uid)
82
+ for dp, dn, fn in os.walk(root):
83
+ for n in dn + fn:
84
+ try:
85
+ os.lchown(os.path.join(dp, n), uid, uid)
86
+ except FileNotFoundError:
87
+ pass
88
+
89
+
90
+ def binary_copy(binary):
91
+ """A verified copy of the binary's release dir under /opt/lffjail/hjail/bin (readable by uid 65534); returns
92
+ (path of the binary in the copy, info). The release dir is the binary's dir, or its parent if that is a bin/."""
93
+ real = os.path.realpath(binary)
94
+ if not os.path.isfile(real):
95
+ raise JailError(f"harness binary {binary} -> {real} not found")
96
+ sha = sha256_file(real)
97
+ rel_root = os.path.dirname(real)
98
+ if os.path.basename(rel_root) == "bin":
99
+ rel_root = os.path.dirname(rel_root)
100
+ dst_root = os.path.join(BIN_DIR, f"{os.path.basename(rel_root)}-{sha[:12]}")
101
+ dst = os.path.join(dst_root, os.path.relpath(real, rel_root))
102
+ if not (os.path.isfile(dst) and sha256_file(dst) == sha):
103
+ os.makedirs(BIN_DIR, mode=0o755, exist_ok=True)
104
+ tmp = dst_root + ".tmp-" + secrets.token_hex(3)
105
+ shutil.copytree(rel_root, tmp, symlinks=True)
106
+ for dp, dn, fn in os.walk(tmp):
107
+ os.chmod(dp, 0o755)
108
+ if os.path.exists(dst_root):
109
+ shutil.rmtree(dst_root)
110
+ os.rename(tmp, dst_root)
111
+ if sha256_file(dst) != sha:
112
+ raise JailError(f"copy of {real} does not match its sha256")
113
+ return dst, dict(original=real, copy=dst, sha256=sha)
114
+
115
+
116
+ class _Relay:
117
+ """Serves one Unix socket; each connection gets a fresh MCP server process attached to it."""
118
+
119
+ def __init__(self, sock_path, argv, env, stderr_path, uid):
120
+ self.path, self.argv, self.env, self.stderr_path = sock_path, argv, env, stderr_path
121
+ self.procs = []
122
+ self.closed = False
123
+ self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
124
+ self.srv.bind(sock_path)
125
+ os.chown(sock_path, uid, uid)
126
+ os.chmod(sock_path, 0o600)
127
+ self.srv.listen(8)
128
+ self.t = threading.Thread(target=self._serve, daemon=True)
129
+ self.t.start()
130
+
131
+ def _serve(self):
132
+ while not self.closed:
133
+ try:
134
+ conn, _ = self.srv.accept()
135
+ except OSError:
136
+ return
137
+ try:
138
+ err = open(self.stderr_path, "ab") if self.stderr_path else subprocess.DEVNULL
139
+ p = subprocess.Popen(self.argv, stdin=conn.fileno(), stdout=conn.fileno(), stderr=err, env=self.env,
140
+ cwd="/", start_new_session=True)
141
+ self.procs.append(p)
142
+ if err is not subprocess.DEVNULL:
143
+ err.close()
144
+ finally:
145
+ conn.close()
146
+
147
+ def close(self):
148
+ self.closed = True
149
+ try:
150
+ self.srv.close()
151
+ except OSError:
152
+ pass
153
+ for p in self.procs:
154
+ if p.poll() is None:
155
+ p.terminate()
156
+ for p in self.procs:
157
+ try:
158
+ p.wait(timeout=10)
159
+ except subprocess.TimeoutExpired:
160
+ p.kill()
161
+
162
+
163
+ class HarnessJail:
164
+ """One per adapter instance. mcp_command() registers a real MCP server command and returns the relay command for
165
+ the harness config; wrap() turns the harness argv into the jailed one; close() stops relays and removes sockets."""
166
+
167
+ def __init__(self, binary, proc="static", uid=JAIL_UID, stderr_dir=None):
168
+ probs = installed_problems()
169
+ if probs:
170
+ raise JailError("; ".join(probs))
171
+ if proc not in ("static", "host"):
172
+ raise JailError(f"proc must be static or host, not {proc!r}")
173
+ self.binary_real = os.path.realpath(binary)
174
+ self.binary_jailed, self.binary_info = binary_copy(binary)
175
+ self.proc, self.uid = proc, uid
176
+ self.sock_dir = None
177
+ self.relays = []
178
+ self.stderr_dir = stderr_dir
179
+
180
+ def info(self):
181
+ return dict(enabled=True, uid=self.uid, proc=self.proc, binary=self.binary_info, inner=INNER,
182
+ inner_sha256=sha256_file(INNER), relay=RELAY)
183
+
184
+ def _sock_dir(self):
185
+ if self.sock_dir is None:
186
+ os.makedirs(SOCK_ROOT, mode=0o711, exist_ok=True)
187
+ os.chmod(SOCK_ROOT, 0o711)
188
+ d = os.path.join(SOCK_ROOT, secrets.token_hex(6))
189
+ os.mkdir(d, 0o700)
190
+ os.chown(d, self.uid, self.uid)
191
+ self.sock_dir = d
192
+ return self.sock_dir
193
+
194
+ def mcp_command(self, real_argv, env=None, label="mcp"):
195
+ """-> (command, args) for the harness's MCP config: the relay on a new socket served by real_argv."""
196
+ d = self._sock_dir()
197
+ path = os.path.join(d, f"{label}-{len(self.relays)}.sock")
198
+ err = os.path.join(self.stderr_dir, f"jail_{label}_stderr.log") if self.stderr_dir else None
199
+ self.relays.append(_Relay(path, list(real_argv), dict(env or {"PATH": "/usr/bin:/bin"}), err, self.uid))
200
+ return RELAY_PYTHON, [RELAY, path]
201
+
202
+ def wrap(self, argv, env, cwd, rw_dirs):
203
+ """The jailed argv. Popen it with the same env: the jail forwards exactly those variables. Chowns the
204
+ directories that are mounted back (one-time dirs only) to the jail uid."""
205
+ rw = _outermost(list(rw_dirs) + ([self.sock_dir] if self.sock_dir else []) + ([cwd] if cwd else []))
206
+ if len(rw) > MAX_BINDS:
207
+ raise JailError(f"too many bind mounts ({len(rw)} > {MAX_BINDS})")
208
+ for d in rw:
209
+ if not os.path.isdir(d):
210
+ raise JailError(f"bind source {d} is not a directory")
211
+ if not d.startswith(("/tmp/lffrun/", "/tmp/lffstate/", SOCK_ROOT + "/")):
212
+ raise JailError(f"refusing to mount {d} into the jail (only one-time dirs)")
213
+ _chown_tree(d, self.uid)
214
+ cmd = [self.binary_jailed if os.path.realpath(argv[0]) == self.binary_real else argv[0]] + list(argv[1:])
215
+ out = ["setpriv", f"--reuid={self.uid}", f"--regid={self.uid}", "--clear-groups", "--",
216
+ "unshare", "--user", "--map-root-user", "--mount", "--fork", "--kill-child",
217
+ INNER, "--keep", ",".join(sorted(env)), "--proc", self.proc]
218
+ for d in rw:
219
+ out += ["--rw", d]
220
+ return out + ["--cwd", cwd or "/", "--exe", self.binary_jailed, "--"] + cmd
221
+
222
+ def close(self):
223
+ for r in self.relays:
224
+ r.close()
225
+ self.relays = []
226
+ if self.sock_dir and self.sock_dir.startswith(SOCK_ROOT + "/"):
227
+ shutil.rmtree(self.sock_dir, ignore_errors=True)
228
+ self.sock_dir = None
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/pins.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned launch fingerprints (fail-closed launch, docs/15 §0.4).
2
+
3
+ A pin says: "harness <name> at version <v> (binary sha256 <b>) with model <m> and effort <e> sends exactly this preset
4
+ prompt and tool list" (the normalised fingerprint of the first request, see claude_code.request_fingerprint /
5
+ codex.request_fingerprint). Pins are written only by tests/harness_selfcheck/selfcheck.py --write-pins after every
6
+ offline check passed for that adapter; a launch without a matching pin is refused.
7
+
8
+ Only hashes and sizes are stored here (the repo is public); the full fingerprint of each launch is in the run's
9
+ harness_preflight.json.
10
+ """
11
+ import json
12
+ import os
13
+ import re
14
+ import time
15
+
16
+ PINS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pins")
17
+
18
+
19
+ def key(adapter, version, binary_sha, model, effort):
20
+ return f"{adapter}|{version}|{(binary_sha or 'nobin')[:16]}|{model}|{effort}"
21
+
22
+
23
+ def _path(k, pins_dir=None):
24
+ return os.path.join(pins_dir or PINS_DIR, re.sub(r"[^A-Za-z0-9.-]+", "_", k) + ".json")
25
+
26
+
27
+ def load(k, pins_dir=None):
28
+ p = _path(k, pins_dir)
29
+ if not os.path.exists(p):
30
+ return None
31
+ with open(p) as f:
32
+ return json.load(f)
33
+
34
+
35
+ def write(k, fingerprint_sha256, summary, pins_dir=None):
36
+ os.makedirs(pins_dir or PINS_DIR, exist_ok=True)
37
+ d = dict(key=k, fingerprint_sha256=fingerprint_sha256, written=time.strftime("%Y-%m-%d %H:%M:%S"), summary=summary)
38
+ with open(_path(k, pins_dir), "w") as f:
39
+ json.dump(d, f, indent=1)
40
+ return d
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/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/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/reference.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness).
2
+
3
+ Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its
4
+ own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only
5
+ adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness.
6
+ """
7
+ import json
8
+ import os
9
+ import sys
10
+
11
+ from . import contract as C
12
+ from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions
13
+ from .trajectory import TrajWriter
14
+
15
+ ROOT = C.ROOT
16
+ PLAYER = os.path.join(ROOT, "scripts", "api_player.py")
17
+ DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py",
18
+ "lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py",
19
+ "lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"]
20
+
21
+
22
+ class Reference(HarnessAdapter):
23
+ name = "ours"
24
+ capabilities = dict(
25
+ only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"),
26
+ images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"),
27
+ non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"),
28
+ pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"),
29
+ machine_readable_events=Cap("yes", "stream", "transcript.jsonl"),
30
+ tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"),
31
+ model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"),
32
+ persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"),
33
+ instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"),
34
+ web_access=Cap("absent", "launch", "no such tool"),
35
+ host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"),
36
+ builtin_shell=Cap("absent", "launch", "only the jailed shell tool"),
37
+ subagent_delegation=Cap("absent", "launch", "no such tool"),
38
+ background_execution=Cap("absent", "launch", "no such tool"),
39
+ )
40
+
41
+ def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_):
42
+ self.provider = provider
43
+ self.base_env = dict(env if env is not None else os.environ)
44
+ self.timeout_s = timeout_s
45
+ self.python = python or sys.executable
46
+
47
+ def version(self):
48
+ per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))}
49
+ sha = C.sha256_json(per)
50
+ return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get(
51
+ "scripts/api_player.py")))
52
+
53
+ def prepare(self, ep, first_message=None):
54
+ argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider,
55
+ "--model", ep.model, "--effort", ep.effort, "--style", "la"]
56
+ return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="",
57
+ stdout_path=os.path.join(ep.log_dir, "api_player.log"),
58
+ stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s)
59
+
60
+ def config_sha256(self, spec, ep):
61
+ return C.sha256_json(dict(argv=[a.replace(ep.session_path, "<SESSION>") for a in spec.argv[1:]]))
62
+
63
+ def launch(self, spec, ep, skip_preflight=True):
64
+ # stdout and stderr go to the same api_player.log (as before the adapter layer)
65
+ import subprocess
66
+ import time
67
+ from .base import RunHandle, env_keys_of
68
+ spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code")
69
+ log = open(spec.stdout_path, "ab")
70
+ h = RunHandle(spec=spec, ep=ep, t_start=time.time())
71
+ h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log,
72
+ stderr=subprocess.STDOUT, start_new_session=True)
73
+ h.pid = h.proc.pid
74
+ time.sleep(0.2)
75
+ h.env_observed_keys = env_keys_of(h.pid)
76
+ return h
77
+
78
+ def collect(self, h):
79
+ ep = h.ep
80
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
81
+ p = os.path.join(ep.log_dir, "transcript.jsonl")
82
+ start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0)
83
+ last_agent = None
84
+ for line in (open(p) if os.path.exists(p) else []):
85
+ d = json.loads(line)
86
+ e = d.get("ev")
87
+ if e == "start":
88
+ start = d
89
+ elif e == "user":
90
+ if first_user is None:
91
+ first_user = d.get("text")
92
+ tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t"))
93
+ elif e == "assistant":
94
+ u = d.get("usage") or {}
95
+ tot["inp"] += u.get("input_tokens", 0)
96
+ tot["out"] += u.get("output_tokens", 0)
97
+ tot["cached"] += u.get("cached_tokens", 0)
98
+ last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "",
99
+ timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"],
100
+ function_name=c["name"],
101
+ native_name=c["name"],
102
+ arguments=c["arguments"])
103
+ for c in d.get("tool_calls") or []],
104
+ metrics=dict(prompt_tokens=u.get("input_tokens"),
105
+ completion_tokens=u.get("output_tokens"),
106
+ cached_tokens=u.get("cached_tokens")))
107
+ elif e == "tool" and last_agent is not None:
108
+ pending = [tc for tc in last_agent["tool_calls"]
109
+ if not any(r["source_call_id"] == tc["tool_call_id"]
110
+ for r in last_agent["observation"]["results"])]
111
+ if pending:
112
+ tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or []))
113
+ elif e in ("end", "abort"):
114
+ end = d
115
+ tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl",
116
+ agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model,
117
+ effort=ep.effort, provider=ep.provider or self.provider),
118
+ tools=[t["name"] for t in (start or {}).get("tools") or []])
119
+ tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")),
120
+ native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"],
121
+ total_cached_tokens=tot["cached"])
122
+ tw.write()
123
+ h.info.update(traj=tw, start=start, first_user=first_user)
124
+ if start and first_user is not None: # the same string a native harness gets as its first message
125
+ readme = open(os.path.join(ep.sandbox, "README.md")).read()
126
+ h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme)
127
+ # the same composition as base.first_message_text: identical sha256 for the same instance
128
+ h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user
129
+ return tw
130
+
131
+ def audit(self, h):
132
+ ep = h.ep
133
+ start = h.info.get("start") or {}
134
+ tools, _ = C.tool_schemas()
135
+ v = []
136
+ if start and start.get("tools") != tools:
137
+ v.append("driver tools differ from the contract's tool schemas")
138
+ if h.info.get("instructions_match_readme") is False:
139
+ v.append("driver instructions != preamble + README")
140
+ out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"])
141
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
142
+ json.dump(out, f, indent=1)
143
+ return out
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/rpent.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RPent (a robot harness framework, RLinf/RPent v0.1) on Codex as an upper-layer harness (docs/18; research note
2
+ harness接入调研/04 §13.7-13.9).
3
+
4
+ rpent_codex RPent's session loop, prompt and archive / handoff rules (robots/lffbench in an RPent checkout with our
5
+ patch), driving Codex through RPent's own Codex planner (openai_codex SDK -> `codex app-server`)
6
+
7
+ What the run is made of:
8
+ - the RPent runtime (LFF_RPENT_HOME, default /mnt/cpfs/workspace/env/rpent-v0.1): src/ = RPent at a pinned commit
9
+ plus our patch (integrations/rpent-v0.1), venv/ = its locked dependencies on /usr/bin/python3.12, no simulator;
10
+ hashed into rpent_tree_sha256 (recorded, and part of the pin);
11
+ - the framework process `python -m robots.lffbench.run` (one per episode), whose only way to the robot is the
12
+ episode's tool gateway (uses_gateway: LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN, lffbench_client, face "rpent");
13
+ - Codex: the same pinned binary and the same configuration as the main table's `codex` adapter (generic model
14
+ catalog in a one-time CODEX_HOME, the same disabled features and instruction switches, read-only sandbox, MCP
15
+ tools approved), passed to RPent's planner as RPENT_CODEX_CONFIG_OVERRIDES; RPent's in-process MCP server is named
16
+ "lff", so the model sees mcp__lff.robot / .shell / .view_images exactly as with `codex exec`.
17
+ Measured 2026-10-21 (fake API, Codex 0.163.0, gpt-6.1-sol / high): the first request of this path has the same
18
+ normalised fingerprint (tools, developer message, parameters, sandbox) as the `codex` adapter's preflight request;
19
+ the only difference is RPent's system prompt in front of the first user message (RPent puts system prompt and first
20
+ message into one user turn). The preflight checks both: the middle-layer fingerprint against the main table's codex
21
+ pin for the same model / effort (when it exists) and the whole fingerprint (incl. RPent's prefix) against this
22
+ adapter's own pin.
23
+
24
+ The framework owns its loop (sessions, handoff, archive): harness_run's resume / nudge does not apply (can_resume
25
+ False). Episode budgets and attempt switching stay with robot_server and the gateway. Only an API key is supported
26
+ (auth="apikey"; the side table runs gpt-6.1-sol on an OpenAI key, user 2026-10-21).
27
+ """
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import shutil
32
+ import subprocess
33
+ import time
34
+
35
+ from . import contract as C
36
+ from . import pins
37
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
38
+ gateway_env, new_run_dir, proxy_env, snapshot_tree)
39
+ from .codex import (CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
40
+ request_fingerprint, toml_str)
41
+ from .fakeapi import FakeResponses
42
+ from .trajectory import TrajWriter
43
+
44
+ ROOT = C.ROOT
45
+ RPENT_HOME = "/mnt/cpfs/workspace/env/rpent-v0.1"
46
+ JAIL_RPENT_DIR = "/opt/lffjail/hjail/rpent"
47
+ BASE_PATH = "/usr/bin:/bin"
48
+ MCP_SERVER = "lff"
49
+ MCP_TOOLS = ["robot", "shell", "view_images"]
50
+ TREE_SKIP = {".git", "__pycache__", "docs", "tests", ".github"}
51
+
52
+
53
+ def rpent_home():
54
+ return os.environ.get("LFF_RPENT_HOME") or RPENT_HOME
55
+
56
+
57
+ def tree_sha256(root, skip=TREE_SKIP):
58
+ """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
59
+ h = hashlib.sha256()
60
+ for dp, dn, fn in os.walk(root):
61
+ dn[:] = sorted(d for d in dn if d not in skip)
62
+ for f in sorted(fn):
63
+ if f.endswith(".pyc"):
64
+ continue
65
+ p = os.path.join(dp, f)
66
+ rel = os.path.relpath(p, root)
67
+ if os.path.islink(p):
68
+ h.update(f"L {rel} {os.readlink(p)}\n".encode())
69
+ else:
70
+ h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
71
+ return h.hexdigest()
72
+
73
+
74
+ def runtime_info(home):
75
+ """The RPent runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
76
+ src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
77
+ for d in (src, venv):
78
+ if not os.path.isdir(d):
79
+ raise HarnessRefused(f"RPent runtime incomplete: {d} missing (integrations/rpent-v0.1/setup.sh)")
80
+
81
+ def git(*a):
82
+ r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
83
+ return r.stdout.strip() if r.returncode == 0 else None
84
+ commit = git("rev-parse", "HEAD")
85
+ patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
86
+ untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
87
+ return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
88
+ untracked=sorted(u for u in untracked if "__pycache__" not in u),
89
+ tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
90
+
91
+
92
+ def jail_runtime_copy(home, tree):
93
+ """A verified read-only copy of the runtime under /opt/lffjail/hjail/rpent (visible in the jail; /mnt is not)."""
94
+ dst = os.path.join(JAIL_RPENT_DIR, f"rpent-{tree[:12]}")
95
+ stamp = os.path.join(dst, ".tree_sha256")
96
+ if os.path.exists(stamp) and open(stamp).read().strip() == tree:
97
+ return dst
98
+ os.makedirs(JAIL_RPENT_DIR, mode=0o755, exist_ok=True)
99
+ tmp = dst + ".tmp-" + os.urandom(3).hex()
100
+ shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
101
+ ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
102
+ shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
103
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
104
+ got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
105
+ ).hexdigest()
106
+ if got != tree:
107
+ shutil.rmtree(tmp, ignore_errors=True)
108
+ raise HarnessRefused(f"copy of the RPent runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
109
+ for dp, dn, fn in os.walk(tmp):
110
+ os.chmod(dp, 0o755)
111
+ for f in fn:
112
+ p = os.path.join(dp, f)
113
+ if not os.path.islink(p):
114
+ os.chmod(p, os.stat(p).st_mode | 0o444)
115
+ with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
116
+ f.write(tree)
117
+ if os.path.exists(dst):
118
+ shutil.rmtree(dst)
119
+ os.rename(tmp, dst)
120
+ return dst
121
+
122
+
123
+ def codex_overrides(effort, catalog_path):
124
+ """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
125
+ overrides for RPent's planner; the provider and the MCP server URL are RPent's own (CODEX_BASE_URL, in-process)."""
126
+ return (["model_reasoning_effort=" + toml_str(effort),
127
+ "include_permissions_instructions=false", "include_environment_context=false",
128
+ "include_collaboration_mode_instructions=false", "skills.include_instructions=false",
129
+ "skills.bundled.enabled=false", 'web_search="disabled"',
130
+ f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
131
+ f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
132
+ f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
133
+ f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
134
+ "model_catalog_json=" + toml_str(catalog_path)]
135
+ + [f"features.{f}=false" for f in DISABLE])
136
+
137
+
138
+ def _items(stream_path):
139
+ """Codex app-server notifications of one RPent session (RPent writes them as JSONL)."""
140
+ out = []
141
+ if not os.path.exists(stream_path):
142
+ return out
143
+ for line in open(stream_path, encoding="utf-8", errors="replace"):
144
+ try:
145
+ out.append(json.loads(line))
146
+ except ValueError:
147
+ continue
148
+ return out
149
+
150
+
151
+ def _item_of(ev):
152
+ it = (ev.get("payload") or {}).get("item") or {}
153
+ return it.get("root", it) if isinstance(it, dict) else {}
154
+
155
+
156
+ class RPentCodex(HarnessAdapter):
157
+ name = "rpent_codex"
158
+ uses_mcp = False
159
+ uses_gateway = True
160
+ can_resume = False
161
+ clean_dirs = ("home", "codex_home", "tmp", "out")
162
+ clean_allowed = {"codex_home": (CATALOG_FILE,)}
163
+ ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
164
+ capabilities = dict(
165
+ only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
166
+ "mcp__lff functions + residual resource×3 / request_user_input; RPent registers "
167
+ "no tool of its own (no file tools, no finish)"),
168
+ images_reach_model=Cap("yes", "probe", "gateway content blocks passed through verbatim (ToolResult.content), "
169
+ "JPEG with its own MIME type"),
170
+ non_persistent_session=Cap("yes", "probe", "RPent's threads only in the one-time CODEX_HOME, removed after the "
171
+ "run; no RPent memory (no MemoryManager, no HF memory)"),
172
+ pinned_version=Cap("yes", "launch", "codex binary sha256 + RPent commit / patch / tree hash (src + venv) in "
173
+ "harness.json; pin per version and tree"),
174
+ machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per RPent session "
175
+ "(codex.out.stream.jsonl) + RPent run.json"),
176
+ tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (face rpent) + events.jsonl"),
177
+ model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
178
+ persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; RPent memory not "
179
+ "constructed"),
180
+ instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
181
+ web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
182
+ host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
183
+ builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
184
+ subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
185
+ background_execution=Cap("absent", "preflight", "no background tool in the request"),
186
+ )
187
+
188
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
189
+ jail=False, auth="apikey", catalog="generic", sessions=5, attempts_per_session=1, max_turns=100,
190
+ home=None, provider=None):
191
+ """api_env: {"OPENAI_API_KEY": ...}; base_url: Responses endpoint (default: the official API). sessions /
192
+ attempts_per_session / max_turns: RPent's --explore-sessions / --explore-attempts-per-session / --max-turns.
193
+ Defaults = the side table's setting (user 2026-10-21): variant H (one attempt per session, then a fresh session
194
+ with RPent's handoff), up to 5 sessions (k=3 + 2 spare), 100 model responses per session; within a session the
195
+ reference driver's continue rule (robots/lffbench/toolkit.py)."""
196
+ if auth != "apikey":
197
+ raise ValueError("rpent_codex supports auth=apikey only")
198
+ if catalog not in CATALOGS:
199
+ raise ValueError(f"catalog must be one of {CATALOGS}")
200
+ self.auth, self.catalog = auth, catalog
201
+ self.api_env = dict(api_env or {})
202
+ self.base_url = base_url or OFFICIAL_API
203
+ self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
204
+ self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
205
+ int(max_turns)
206
+ self.home = home or rpent_home()
207
+ self.proxy = proxy_env()
208
+ self._version = None
209
+ self._runtime = None
210
+ self.runtime_dir = self.home
211
+ if jail:
212
+ from .jail import HarnessJail
213
+ self.jail = HarnessJail(codex_bin(), proc="static")
214
+
215
+ # ------------------------------------------------------------------------------------------------ identity
216
+ def runtime(self):
217
+ if self._runtime is None:
218
+ self._runtime = runtime_info(self.home)
219
+ if self.jail is not None:
220
+ self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
221
+ return self._runtime
222
+
223
+ def version(self):
224
+ if self._version is None:
225
+ b = codex_bin()
226
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
227
+ CODEX_HOME="/nonexistent"),
228
+ capture_output=True, text=True, timeout=60)
229
+ v = (out.stdout.strip().split() or ["?"])[-1]
230
+ rt = self.runtime()
231
+ self._version = dict(version=v, binary=binary_info(b),
232
+ rpent=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
233
+ tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
234
+ return self._version
235
+
236
+ def pin_key(self, ep):
237
+ v = self.version()
238
+ name = f"{self.name}-{self.catalog}-{v['rpent']['tree_sha256'][:12]}"
239
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
240
+
241
+ def anchor_pin_key(self, ep):
242
+ """The main table's codex pin for the same model / effort (apikey, same catalog)."""
243
+ v = self.version()
244
+ name = "codex" + ("" if self.catalog == "native" else f"-{self.catalog}")
245
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
246
+
247
+ def auth_info(self):
248
+ return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
249
+ "OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
250
+
251
+ def config_info(self):
252
+ return dict(catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
253
+ max_turns=self.max_turns, rpent=self.version()["rpent"])
254
+
255
+ # ------------------------------------------------------------------------------------------------ prepare
256
+ def _state_dirs(self, hexname=None):
257
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
258
+ os.makedirs(root, exist_ok=True)
259
+ state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
260
+ for k in ("home", "codex_home", "tmp", "out"):
261
+ os.makedirs(state[k], exist_ok=True)
262
+ return state
263
+
264
+ def _install_catalog(self, codex_home, ep):
265
+ cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
266
+ path = os.path.join(codex_home, CATALOG_FILE)
267
+ with open(path, "w") as f:
268
+ json.dump(cat, f)
269
+ return path, C.sha256_file(path), os.path.relpath(src, ROOT)
270
+
271
+ def argv(self, ep, out_dir, sessions=None, preflight=False):
272
+ py = os.path.join(self.runtime_dir, "venv", "bin", "python")
273
+ return [py, "-m", "robots.lffbench.run", "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
274
+ "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
275
+ "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
276
+ + (["--no-continue"] if preflight else [])
277
+
278
+ def env(self, state, ep, base_url, work):
279
+ e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
280
+ CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
281
+ CODEX_BASE_URL=base_url, RPENT_CODEX_SANDBOX="read_only", RPENT_MCP_SERVER_NAME=MCP_SERVER,
282
+ RPENT_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
283
+ ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
284
+ RPENT_REPO_ROOT=work, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
285
+ PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
286
+ e.update(self.proxy)
287
+ if self.api_env.get("OPENAI_API_KEY"):
288
+ e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
289
+ return e
290
+
291
+ def prepare(self, ep, first_message, reuse_state=None):
292
+ self.version()
293
+ work = new_run_dir("/tmp/lffrun")
294
+ state = reuse_state or self._state_dirs(os.path.basename(work))
295
+ if self.jail is not None:
296
+ self.jail.stderr_dir = ep.log_dir
297
+ if not reuse_state and os.listdir(state["codex_home"]):
298
+ raise HarnessRefused("CODEX_HOME is not empty")
299
+ cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
300
+ return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
301
+ run_dir=work, state_dirs=state, first_message=first_message,
302
+ stdout_path=os.path.join(ep.log_dir, "rpent_stdout.txt"),
303
+ stderr_path=os.path.join(ep.log_dir, "rpent_stderr.txt"),
304
+ config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
305
+ catalog=self.catalog, code_mode=False)),
306
+ timeout_s=self.timeout_s)
307
+
308
+ def config_sha256(self, spec, ep):
309
+ argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<RPENT>")
310
+ for a in spec.argv]
311
+ hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "RPENT_REPO_ROOT", "PYTHONPATH",
312
+ "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
313
+ env = {k: v for k, v in spec.env.items() if k not in hidden}
314
+ env["RPENT_CODEX_CONFIG_OVERRIDES"] = env.get("RPENT_CODEX_CONFIG_OVERRIDES", "").replace(
315
+ spec.state_dirs["codex_home"], "<CODEX_HOME>")
316
+ cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
317
+ return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
318
+ rpent_tree_sha256=self.version()["rpent"]["tree_sha256"]))
319
+
320
+ # ------------------------------------------------------------------------------------------------ launch
321
+ def launch(self, spec, ep, skip_preflight=False):
322
+ """harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
323
+ spec.env.update(gateway_env(ep.log_dir))
324
+ return super().launch(spec, ep, skip_preflight=skip_preflight)
325
+
326
+ def preflight(self, spec, ep, record_dir=None):
327
+ """The same framework process, one session, against a local fake Responses server that answers with text
328
+ only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
329
+ sandbox, RPent's prefix + our first message) against the pins."""
330
+ t0 = time.time()
331
+ fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
332
+ pre = self._state_dirs()
333
+ try:
334
+ self._install_catalog(pre["codex_home"], ep)
335
+ env = self.env(pre, ep, fake.base_url, spec.cwd)
336
+ env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
337
+ env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
338
+ argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
339
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
340
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
341
+ reqs = fake.model_requests()
342
+ if not reqs:
343
+ raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
344
+ f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]}")
345
+ body = reqs[0][1]
346
+ fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
347
+ problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
348
+ users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
349
+ and it.get("role") == "user" for c in it.get("content") or []]
350
+ prefix = None
351
+ if len(users) != 1 or not users[0].endswith(spec.first_message):
352
+ problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
353
+ else:
354
+ prefix = users[0][:-len(spec.first_message)]
355
+ effort = (fp["params"].get("reasoning") or {}).get("effort")
356
+ if effort != ep.effort:
357
+ problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
358
+ if fp["params"].get("model") != ep.model:
359
+ problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
360
+ if os.listdir(spec.cwd):
361
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
362
+ mid_sha = C.sha256_json(fp)
363
+ full = dict(middle=fp, rpent_prefix=prefix)
364
+ fp_sha = C.sha256_json(full)
365
+ anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
366
+ out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
367
+ rpent_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
368
+ rpent_prefix_chars=len(prefix) if prefix is not None else None,
369
+ developer_chars=fp["developer_chars"], n_requests=len(reqs),
370
+ top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
371
+ model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
372
+ dt_s=round(time.time() - t0, 1), problems=problems,
373
+ anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
374
+ if anchor is None:
375
+ out["anchor_status"] = "no main-table pin for this model / effort"
376
+ elif anchor["fingerprint_sha256"] != mid_sha:
377
+ problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
378
+ f"({anchor['key']}): the middle layer is not the main table's")
379
+ else:
380
+ out["anchor_status"] = "match"
381
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
382
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
383
+ out["fingerprint"] = full
384
+ if problems:
385
+ raise HarnessRefused("preflight: " + "; ".join(problems))
386
+ if pin is None:
387
+ if not self.allow_unpinned:
388
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
389
+ f"with --write-pins after the self-check passes)")
390
+ out["pin_status"] = "unpinned (allowed)"
391
+ elif pin["fingerprint_sha256"] != fp_sha:
392
+ raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
393
+ f"({pin['key']})")
394
+ else:
395
+ out["pin_status"] = "match"
396
+ return out
397
+ finally:
398
+ fake.stop()
399
+ shutil.rmtree(pre["state"], ignore_errors=True)
400
+
401
+ # ------------------------------------------------------------------------------------------------ collect
402
+ def collect(self, h):
403
+ spec, ep = h.spec, h.ep
404
+ dst = os.path.join(ep.log_dir, "rpent")
405
+ if os.path.isdir(spec.state_dirs["out"]):
406
+ shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
407
+ run = {}
408
+ if os.path.exists(os.path.join(dst, "run.json")):
409
+ run = json.load(open(os.path.join(dst, "run.json")))
410
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
411
+ usage = dict(input=0, cached=0, output=0, reasoning=0)
412
+ items, threads, errors = [], [], []
413
+ for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
414
+ else []:
415
+ last = None
416
+ for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
417
+ m = ev.get("method") or ev.get("type")
418
+ p = ev.get("payload") or {}
419
+ if m == "thread/tokenUsage/updated":
420
+ last = (p.get("token_usage") or {}).get("total") or last
421
+ if p.get("thread_id") and p["thread_id"] not in threads:
422
+ threads.append(p["thread_id"])
423
+ elif m in ("error", "fatal", "timeout"):
424
+ errors.append(ev)
425
+ elif m == "item/completed":
426
+ it = _item_of(ev)
427
+ t = it.get("type")
428
+ items.append(t)
429
+ if t == "agentMessage":
430
+ tw.add_step("agent", message=it.get("text", ""))
431
+ elif t == "reasoning":
432
+ tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
433
+ elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
434
+ name = it.get("tool") or t
435
+ tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
436
+ native_name=f"{it.get('server', '')}.{name}",
437
+ item_type=t, arguments=it.get("arguments"),
438
+ session=sdir)])
439
+ res = it.get("result") or {}
440
+ texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
441
+ imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
442
+ tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
443
+ bool(it.get("error")) or it.get("status") == "failed", imgs)
444
+ if last:
445
+ usage["input"] += last.get("input_tokens") or 0
446
+ usage["cached"] += last.get("cached_input_tokens") or 0
447
+ usage["output"] += last.get("output_tokens") or 0
448
+ usage["reasoning"] += last.get("reasoning_output_tokens") or 0
449
+ # Framework close-out uses the same counted gateway shell, outside
450
+ # the model stream. Keep it visible in trajectories and tool totals.
451
+ session_record = next((s for s in run.get("sessions", [])
452
+ if sdir == f"session_{s['number']:03d}"), {})
453
+ handoff = session_record.get("handoff") or {}
454
+ if handoff:
455
+ call_id = f"framework-handoff-{sdir}"
456
+ tw.add_step("framework", tool_calls=[dict(
457
+ tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
458
+ item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
459
+ tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
460
+ if c.get("type") == "text"))
461
+ v = self.version()
462
+ tw.set_header(session_id=",".join(threads), source="rpent/sessions/*/codex.out.stream.jsonl",
463
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
464
+ rpent=v["rpent"]), tools=EXPECTED_TOP_GENERIC)
465
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
466
+ run={k: run.get(k) for k in ("stop", "finished",
467
+ "attempts_failed", "tool_calls")},
468
+ sessions=len(run.get("sessions") or [])),
469
+ total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
470
+ total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
471
+ tw.write()
472
+ h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
473
+ return tw
474
+
475
+ # ------------------------------------------------------------------------------------------------ audit
476
+ def audit(self, h):
477
+ spec, ep = h.spec, h.ep
478
+ v, notes = [], []
479
+ items = h.info.get("items") or []
480
+ bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
481
+ "plan", "hookPrompt")})
482
+ if bad:
483
+ v.append(f"items other than messages / reasoning / MCP calls: {bad}")
484
+ residual = []
485
+ tw = h.info.get("traj")
486
+ for st in (tw.steps if tw else []):
487
+ for tc in st["tool_calls"]:
488
+ if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
489
+ continue
490
+ if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
491
+ residual.append(tc["function_name"])
492
+ else:
493
+ v.append(f"unexpected tool call {tc['native_name']}")
494
+ if residual:
495
+ notes.append(f"residual MCP-resource tool calls (empty): {residual}")
496
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
497
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
498
+ run = h.info.get("run") or {}
499
+ nsess = len(run.get("sessions") or [])
500
+ if len(h.info.get("threads") or []) > max(1, nsess):
501
+ v.append(f"{len(h.info['threads'])} Codex threads for {nsess} RPent sessions")
502
+ if nsess > 1:
503
+ notes.append(f"{nsess} RPent sessions (handoff after a session ended before the episode was over)")
504
+ if run.get("stop") not in (None, "episode over"):
505
+ notes.append(f"RPent stopped: {run.get('stop')}")
506
+ left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
507
+ work=snapshot_tree(spec.cwd))
508
+ if left["work"]:
509
+ v.append(f"files in the work dir: {left['work']}")
510
+ foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
511
+ and not any(t in f for t in (h.info.get("threads") or []))]
512
+ if foreign:
513
+ v.append(f"session files other than this run's threads: {foreign}")
514
+ gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
515
+ faces = set()
516
+ if os.path.exists(gt):
517
+ for line in open(gt):
518
+ try:
519
+ d = json.loads(line)
520
+ except ValueError:
521
+ continue
522
+ if d.get("ev") == "tool" and d.get("face"):
523
+ faces.add(d["face"])
524
+ if faces - {"rpent"}:
525
+ v.append(f"gateway calls from other access paths: {sorted(faces)}")
526
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
527
+ item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
528
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
529
+ json.dump(out, f, indent=1)
530
+ return out
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/sensenova.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SenseNova-RoboRSI native Codex SDK planner, controlled MCP variant."""
2
+ from .framework_codex import RobotFrameworkCodex
3
+
4
+ class SenseNovaCodex(RobotFrameworkCodex):
5
+ name = "sensenova_codex"
6
+ runtime_home = "/mnt/cpfs/workspace/env/sensenova-roborsi"
7
+
8
+ def __init__(self, **kwargs):
9
+ kwargs.setdefault("sessions", 1)
10
+ kwargs.setdefault("attempts_per_session", 0)
11
+ if kwargs["sessions"] != 1 or kwargs["attempts_per_session"] != 0:
12
+ raise ValueError("SenseNova controlled variant uses one persistent session for all attempts")
13
+ super().__init__(**kwargs)
14
+
15
+ def env(self, state, ep, base_url, work):
16
+ env = super().env(state, ep, base_url, work)
17
+ env["LFF_CONTROLLED_CODEX"] = "1"
18
+ return env
19
+
20
+ def config_info(self):
21
+ info = super().config_info()
22
+ info.update(variant="native-codex-planner-mcp", max_sdk_steps=self.max_turns,
23
+ history="same-thread", cross_episode_memory=False)
24
+ return info
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/harnesses/trajectory.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unified trajectory (minimal, field names follow Harbor's ATIF where there is one).
2
+
3
+ <log_dir>/trajectory.jsonl, one JSON object per line:
4
+ line 1 {"kind": "header", "schema": "lff-traj-0", "atif_like": "ATIF v1.x field names", "session_id",
5
+ "agent": {"name", "version", "model_name", "effort"}, "tools": [...], "source": "<native log file>"}
6
+ steps {"kind": "step", "step_id", "timestamp", "source": "user"|"agent"|"system", "message",
7
+ "reasoning_content", "tool_calls": [{"tool_call_id", "function_name", "arguments"}],
8
+ "observation": {"results": [{"source_call_id", "content", "is_error", "images"}]},
9
+ "metrics": {"prompt_tokens", "completion_tokens", "cached_tokens", "cost_usd"}}
10
+ last {"kind": "final", "final_metrics": {"total_prompt_tokens", "total_completion_tokens",
11
+ "total_cached_tokens", "total_cost_usd", "total_steps"}, "exit_reason", "native_result"}
12
+ Not full ATIF: no per-step model name, no subagent trajectories, images only counted (bytes stay in the workspace).
13
+ Tool names are reported without the MCP prefix (robot / shell / view_images), so all harnesses line up.
14
+ """
15
+ import json
16
+ import os
17
+
18
+ SCHEMA = "lff-traj-0"
19
+
20
+
21
+ def strip_mcp(name):
22
+ for p in ("mcp__lff__", "lff."):
23
+ if name and name.startswith(p):
24
+ return name[len(p):]
25
+ return name
26
+
27
+
28
+ class TrajWriter:
29
+ def __init__(self, path):
30
+ self.path = path
31
+ self.steps = []
32
+ self.header = None
33
+ self.final = None
34
+
35
+ def set_header(self, **kw):
36
+ self.header = dict(kind="header", schema=SCHEMA, atif_like="field names follow Harbor ATIF", **kw)
37
+
38
+ def add_step(self, source, message="", reasoning="", tool_calls=None, timestamp=None, metrics=None, **extra):
39
+ st = dict(kind="step", step_id=len(self.steps) + 1, timestamp=timestamp, source=source, message=message or "",
40
+ reasoning_content=reasoning or "", tool_calls=tool_calls or [],
41
+ observation=dict(results=[]), metrics=metrics or {})
42
+ st.update(extra)
43
+ self.steps.append(st)
44
+ return st
45
+
46
+ def add_result(self, call_id, content, is_error=False, images=0):
47
+ for st in reversed(self.steps):
48
+ if any(tc["tool_call_id"] == call_id for tc in st["tool_calls"]):
49
+ st["observation"]["results"].append(dict(source_call_id=call_id, content=content, is_error=is_error,
50
+ images=images))
51
+ return True
52
+ return False
53
+
54
+ def set_final(self, exit_reason, native_result=None, **metrics):
55
+ fm = dict(total_prompt_tokens=0, total_completion_tokens=0, total_cached_tokens=0, total_cost_usd=None,
56
+ total_steps=len(self.steps))
57
+ fm.update({k: v for k, v in metrics.items() if v is not None})
58
+ self.final = dict(kind="final", final_metrics=fm, exit_reason=exit_reason, native_result=native_result)
59
+
60
+ def write(self):
61
+ with open(self.path, "w") as f:
62
+ for d in [self.header] + self.steps + [self.final]:
63
+ if d is not None:
64
+ f.write(json.dumps(d, ensure_ascii=False) + "\n")
65
+ return self.path
66
+
67
+ def tool_call_names(self):
68
+ return [tc["function_name"] for st in self.steps for tc in st["tool_calls"]]
69
+
70
+
71
+ def read(path):
72
+ with open(path) as f:
73
+ return [json.loads(line) for line in f if line.strip()]
74
+
75
+
76
+ def usage_summary(log_dir):
77
+ """Token / cost totals from trajectory.jsonl (None if missing)."""
78
+ p = os.path.join(log_dir or "", "trajectory.jsonl")
79
+ if not os.path.exists(p):
80
+ return None
81
+ rows = read(p)
82
+ fin = next((r for r in rows if r.get("kind") == "final"), None)
83
+ steps = [r for r in rows if r.get("kind") == "step" and r.get("source") == "agent"]
84
+ out = dict(calls=len(steps), exit_reason=(fin or {}).get("exit_reason"))
85
+ out.update((fin or {}).get("final_metrics") or {})
86
+ return out
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/DRIVER.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LFF-Bench 真机驱动说明(给负责机械臂的同学)
2
+
3
+ > 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`,
4
+ > 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。
5
+
6
+ ## 0. 一句话
7
+
8
+ 你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。
9
+ 模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。
10
+
11
+ ```
12
+ 评测机(跑模型的人) 机器人电脑(你)
13
+ Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改
14
+ └ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……)
15
+ └ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist
16
+ └ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败)
17
+ ```
18
+
19
+ 模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。
20
+
21
+ ## 1. 你要交付的东西
22
+
23
+ 1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。
24
+ 2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。
25
+ 3. 场景道具,见 §6。
26
+ 4. `scripts/real_check_driver.py` 全部 PASS(§7)。
27
+ 5. 一位操作员,按 §8 的规程操作。可以就是你。
28
+
29
+ 需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。
30
+ 放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。
31
+
32
+ ## 2. 坐标与约定(最重要的一节)
33
+
34
+ | 量 | 约定 |
35
+ |---|---|
36
+ | 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 |
37
+ | 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 |
38
+ | 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** |
39
+ | yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) |
40
+ | `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) |
41
+ | `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` |
42
+ | `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) |
43
+
44
+ 这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是
45
+ "You control a real `<robot>` robot arm (`<n_joints>` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。
46
+
47
+ ## 3. 接口
48
+
49
+ 所有请求都是 `POST http://127.0.0.1:<port>/<endpoint>`,带 JSON body,请求头 `X-Driver-Token: <token>`。
50
+ 所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。
51
+ 模板里任何未捕获的异常都会自动变成 fault。
52
+
53
+ | 接口 | 请求 | 回复(`ok` 之外) | 说明 |
54
+ |---|---|---|---|
55
+ | `info` | `{}` | `protocol` = 1,`robot`,`n_joints`,`cameras` = `["agentview","wrist"]`,`workspace` = `{lo:[x,y,z], hi:[x,y,z]}`,`yaw_range_deg` = `[lo,hi]`,`max_speed`(m/s),`ik`(bool),`driver_version` | 启动时调一次,内容写进每个 run 的契约 |
56
+ | `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 |
57
+ | `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) |
58
+ | `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 |
59
+ | `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 |
60
+ | `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会���心裁成正方形、缩到 512²,再存成 JPEG q90 |
61
+ | `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 |
62
+ | `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) |
63
+ | `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 |
64
+
65
+ 驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。
66
+
67
+ ## 4. 安全(必须做)
68
+
69
+ - **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。
70
+ - **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。
71
+ - **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。
72
+ - **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。
73
+ - `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。
74
+
75
+ ## 5. 模型那边看到的和你有关的东西
76
+
77
+ - 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。
78
+ 光照要稳定;模型运行时,画面里不要有人和多余的东西。
79
+ - 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。
80
+ - 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。
81
+
82
+ ## 6. 两个任务的场景
83
+
84
+ 实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。
85
+
86
+ ### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`)
87
+
88
+ 模型看到的指令(与仿真相同):*Slowly push the long brown box with the closed gripper so that it ends up completely inside the green rectangle ahead of it (farther from the robot).*
89
+
90
+ - **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。
91
+ 可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。
92
+ - **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。
93
+ 合上盖子,两端外观一模一样,贴同样的胶带。
94
+ - **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。
95
+ - **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。
96
+ - **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。
97
+ - **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框);
98
+ 对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。
99
+ - **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。
100
+
101
+ ### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`)
102
+
103
+ 模型看到的指令:*Pick up the red cube and put it into the bowl.*
104
+
105
+ - 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。
106
+ - 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。
107
+ - **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。
108
+ 但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。
109
+ - **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方��。
110
+
111
+ ## 7. 联调步骤
112
+
113
+ 1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。
114
+ 2. 启动驱动(token 自己定,私下发给跑评测的人):
115
+ ```bash
116
+ python driver_template.py --port 9900 --token <token> --log driver_logs
117
+ ```
118
+ 3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上:
119
+ ```bash
120
+ python real_check_driver.py --driver http://127.0.0.1:9900 --token <token> --operator
121
+ ```
122
+ 全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。
123
+ 4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一:
124
+ - 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 <user>@<机器人电脑>`
125
+ - 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 <user>@<评测机>`
126
+ 5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。
127
+ 6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。
128
+ 一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。
129
+
130
+ ## 8. 操作员规程
131
+
132
+ - 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。
133
+ - 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。
134
+ - 判 y / n 只看清单本身,不看模型"努力了没有"。
135
+ - `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。
136
+ - 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。
137
+
138
+ ## 9. 常见问题
139
+
140
+ - **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。
141
+ - **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。
142
+ - **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。
143
+ - **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。
144
+ - **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real-robot backend of LFF-Bench (docs/17): the same agent interface as simulation, with a robot driver underneath.
2
+
3
+ protocol.py driver protocol v1 (both sides; stdlib + numpy + Pillow only)
4
+ executor.py RealToolExecutor: robot_server's executor on top of a driver (calibration bias injected here)
5
+ session.py RealRobotSession: robot_server's LA session without the simulator; python -m lffbench.real.session
6
+ tasks.py real-robot tasks (setup sheet, operator checklist, hidden variable from the seed)
7
+ fake_driver.py a driver backed by the simulator (no hardware)
8
+ driver_template.py skeleton for a hardware driver (copy to the robot PC with protocol.py)
9
+ DRIVER.md spec for the driver author and the operator
10
+ """
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/driver_template.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Skeleton of a hardware driver for LFF-Bench (spec: DRIVER.md). Copy this file and protocol.py to the robot PC,
2
+ fill in the five methods marked TODO, run scripts/real_check_driver.py until every check passes.
3
+
4
+ python driver_template.py --port 9900 [--token <t>] [--log <dir>]
5
+
6
+ Only Python 3 + numpy + Pillow are needed here (plus your robot / camera SDKs). Keep the server on 127.0.0.1; the
7
+ benchmark machine reaches it through an SSH tunnel (DRIVER.md §7).
8
+
9
+ What is already done for you: the HTTP protocol, the token, the operator's terminal prompts, the safety checks that
10
+ must run before every motion (hard workspace box, speed limit), the motion timing, and an optional recorder that saves
11
+ both cameras to an mp4 per attempt. Everything robot-specific is in the TODO methods.
12
+ """
13
+ import argparse
14
+ import os
15
+ import threading
16
+ import time
17
+
18
+ import numpy as np
19
+
20
+ try: # copied next to protocol.py on the robot PC
21
+ from protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
22
+ except ImportError: # inside the repo (python -m lffbench.real.driver_template)
23
+ from .protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
24
+
25
+ # ---------------------------------------------------------------------------------------------- your setup (edit)
26
+ ROBOT = "AgileX PiPER" # TODO: the arm's name as the agent will read it ("You control a real <ROBOT> robot arm")
27
+ N_JOINTS = 6 # TODO
28
+ # Hard workspace of the GRASP POINT in the robot-base frame (metres). Rejected targets never move the arm. Choose it so
29
+ # that every point inside is reachable with the gripper pointing straight down at any yaw in YAW_RANGE_DEG, and the
30
+ # lower z bound keeps the fingertips >= 5 mm above the table (the boxes are pushed with the fingertips ~1 cm up).
31
+ WORKSPACE_LO = [0.15, -0.25, 0.00] # TODO: measure on your table
32
+ WORKSPACE_HI = [0.45, 0.25, 0.30] # TODO
33
+ YAW_RANGE_DEG = [-120.0, 120.0] # TODO: gripper yaw your wrist reaches (span >= 180)
34
+ MAX_SPEED = 0.25 # m/s, the fastest straight-line speed you allow (the agent may ask for less)
35
+ HOME = dict(x=0.25, y=0.0, z=0.20, yaw_deg=0.0) # TODO: above the table centre, out of the agentview's way if possible
36
+ REACH_TOL = 0.004 # m: a move counts as finished when within this of the target and stopped
37
+ MOVE_TIMEOUT = 30.0 # s
38
+ DRIVER_VERSION = "template-0" # TODO: your git commit / date
39
+
40
+
41
+ class MyDriver(DriverServer):
42
+ image_format = "jpeg" # "png" is lossless but ~5x larger; jpeg q95 is fine over a LAN / SSH tunnel
43
+
44
+ def __init__(self, record_dir=""):
45
+ self.lock = threading.RLock() # hardware access from the recorder thread and from requests
46
+ self.record_dir = record_dir
47
+ self.recorder = None
48
+ # TODO: connect to the arm, enable it, set the TCP (grasp point = midway between the fingertips, about 1 cm
49
+ # above their tips), open the cameras. Example for PiPER (piper_sdk; check the SDK docs, not verified here):
50
+ # from piper_sdk import C_PiperInterface_V2
51
+ # self.arm = C_PiperInterface_V2("can0"); self.arm.ConnectPort(); ... enable ...
52
+ # Cameras: "agentview" = fixed camera looking at the table from the front/side (sees the whole work area);
53
+ # "wrist" = camera on the gripper. E.g. cv2.VideoCapture / pyrealsense2 colour stream.
54
+ raise NotImplementedError("connect the arm and the cameras")
55
+
56
+ # ------------------------------------------------------------------ TODO 1: low-level hardware
57
+ def _send_cartesian(self, x, y, z, yaw_deg, speed):
58
+ """Start a straight-line (MoveL) motion of the grasp point to (x, y, z) with the gripper pointing straight down
59
+ and rotated by yaw_deg about the base z axis (0 = fingers close along the base y axis, +90 = along the base x
60
+ axis, counter-clockwise seen from above). Return False if the controller refuses (no IK)."""
61
+ raise NotImplementedError
62
+
63
+ def _read_pose(self):
64
+ """-> (xyz of the grasp point in the base frame [m], yaw_deg, joint angles [rad], is_moving: bool)."""
65
+ raise NotImplementedError
66
+
67
+ def _set_gripper(self, close):
68
+ """Close (force-limited, stop when blocked) or open fully; return when the fingers have stopped."""
69
+ raise NotImplementedError
70
+
71
+ def _gripper_width(self):
72
+ """Opening between the fingertips, metres."""
73
+ raise NotImplementedError
74
+
75
+ def _grab(self):
76
+ """-> {"agentview": HxWx3 uint8 RGB, "wrist": ...}: the newest frames (flush camera buffers first)."""
77
+ raise NotImplementedError
78
+
79
+ def ik(self, eef_pos, yaw_deg):
80
+ """Optional (set info()["ik"] = True), needed only for real_bias_place: joint angles that put the grasp point
81
+ at eef_pos / yaw_deg (pointing down), the solution closest to the current joints. Do NOT move the arm."""
82
+ raise NotImplementedError
83
+
84
+ # ------------------------------------------------------------------ protocol (normally no need to edit)
85
+ def info(self):
86
+ return dict(protocol=PROTOCOL_VERSION, robot=ROBOT, n_joints=N_JOINTS, cameras=list(CAMERAS),
87
+ workspace=dict(lo=WORKSPACE_LO, hi=WORKSPACE_HI), yaw_range_deg=YAW_RANGE_DEG, max_speed=MAX_SPEED,
88
+ ik=False, driver_version=DRIVER_VERSION)
89
+
90
+ def state(self):
91
+ with self.lock:
92
+ xyz, yaw, q, _ = self._read_pose()
93
+ return dict(eef_pos=[float(v) for v in xyz], eef_yaw_deg=float(yaw), gripper_width_m=float(self._gripper_width()),
94
+ joint_pos_rad=[float(v) for v in q])
95
+
96
+ def _inside(self, x, y, z, yaw_deg):
97
+ p = np.array([x, y, z])
98
+ return (bool(np.all(p >= WORKSPACE_LO) and np.all(p <= WORKSPACE_HI))
99
+ and YAW_RANGE_DEG[0] <= yaw_deg <= YAW_RANGE_DEG[1])
100
+
101
+ def move(self, x, y, z, yaw_deg, speed):
102
+ if not self._inside(x, y, z, yaw_deg):
103
+ return False, "outside the hard workspace", 0.0
104
+ speed = MAX_SPEED if speed is None else float(np.clip(speed, 0.005, MAX_SPEED))
105
+ with self.lock:
106
+ t0 = time.time()
107
+ if not self._send_cartesian(x, y, z, yaw_deg, speed):
108
+ return False, "no IK solution", 0.0
109
+ tgt = np.array([x, y, z])
110
+ while True: # blocking: return only once the arm has stopped
111
+ xyz, _, _, moving = self._read_pose()
112
+ if not moving and np.linalg.norm(np.asarray(xyz) - tgt) < REACH_TOL:
113
+ break
114
+ if time.time() - t0 > MOVE_TIMEOUT:
115
+ if not moving:
116
+ break # stopped short (blocked by an object): a normal outcome, the agent sees the pose
117
+ raise RuntimeError("move timed out while still moving") # -> fault: the run stops
118
+ time.sleep(0.02)
119
+ return True, None, time.time() - t0
120
+
121
+ def gripper(self, close):
122
+ with self.lock:
123
+ t0 = time.time()
124
+ self._set_gripper(close)
125
+ return time.time() - t0
126
+
127
+ def home(self):
128
+ ok, err, _ = self.move(HOME["x"], HOME["y"], HOME["z"], HOME["yaw_deg"], 0.15)
129
+ if not ok:
130
+ raise RuntimeError(f"cannot reach the home pose: {err}")
131
+ self.gripper(False)
132
+ return self.state()
133
+
134
+ def images(self):
135
+ with self.lock:
136
+ return self._grab()
137
+
138
+ def event(self, ev, run="", attempt=None, **kw):
139
+ if not self.record_dir:
140
+ return
141
+ if ev == "attempt_start":
142
+ self._stop_recording()
143
+ try:
144
+ self.recorder = Recorder(self, os.path.join(self.record_dir, f"{run}_a{attempt}.mp4"))
145
+ except Exception as e: # the video is only for the record: a missing imageio must not end a run as a fault
146
+ print(f"WARNING: recorder not started ({type(e).__name__}: {e}); "
147
+ "pip install imageio imageio-ffmpeg", flush=True)
148
+ elif ev in ("attempt_end", "episode_end", "session_end", "run_invalid"):
149
+ self._stop_recording()
150
+
151
+ def _stop_recording(self):
152
+ if self.recorder is not None:
153
+ self.recorder.stop()
154
+ self.recorder = None
155
+
156
+
157
+ class Recorder(threading.Thread):
158
+ """agentview | wrist side by side at ~5 fps while an attempt runs (needs imageio + imageio-ffmpeg)."""
159
+
160
+ def __init__(self, drv, path, fps=5, res=360):
161
+ super().__init__(daemon=True)
162
+ import imageio
163
+ self.drv, self.fps, self.res, self.halt = drv, fps, res, threading.Event()
164
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
165
+ self.w = imageio.get_writer(path, fps=fps, macro_block_size=8)
166
+ self.start()
167
+
168
+ def run(self):
169
+ while not self.halt.is_set():
170
+ t0 = time.time()
171
+ try:
172
+ with self.drv.lock:
173
+ f = self.drv._grab()
174
+ self.w.append_data(np.concatenate([square_resize(f[c], self.res) for c in CAMERAS], axis=1))
175
+ except Exception as e: # never let the recorder break a run
176
+ print("recorder:", e)
177
+ self.halt.wait(max(0.0, 1.0 / self.fps - (time.time() - t0)))
178
+
179
+ def stop(self):
180
+ self.halt.set()
181
+ self.join(timeout=5)
182
+ self.w.close()
183
+
184
+
185
+ def main():
186
+ ap = argparse.ArgumentParser()
187
+ ap.add_argument("--port", type=int, default=9900)
188
+ ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
189
+ ap.add_argument("--log", default="driver_logs", help="operator answers (operator.jsonl) and attempt videos")
190
+ a = ap.parse_args()
191
+ os.makedirs(a.log, exist_ok=True)
192
+ MyDriver(record_dir=a.log).serve(a.port, token=a.token or None, operator_log=os.path.join(a.log, "operator.jsonl"))
193
+
194
+
195
+ if __name__ == "__main__":
196
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/executor.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor.
2
+
3
+ robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and
4
+ call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver
5
+ (lffbench/real/protocol.py) instead of the simulator.
6
+
7
+ Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and
8
+ reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the
9
+ ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation.
10
+ """
11
+ import math
12
+ import time
13
+
14
+ import numpy as np
15
+
16
+ from ..agent.images import ImageRef
17
+ from ..agent.tools import ToolResult, parse_args
18
+ from .protocol import CAMERAS, DriverError, square_resize, state_problems
19
+
20
+ SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful
21
+
22
+
23
+ def _r(v, nd=4):
24
+ return [round(float(x), nd) for x in v]
25
+
26
+
27
+ class RealToolExecutor:
28
+ def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS):
29
+ self.driver, self.info = driver, info
30
+ self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
31
+ self.image_res = int(image_res)
32
+ self.cams = tuple(cams)
33
+ self.n_joints = int(info["n_joints"])
34
+ self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"])
35
+ self.max_speed = float(info["max_speed"])
36
+ self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver
37
+ self.n_calls = 0
38
+ self._state = None
39
+ self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open)
40
+ self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents
41
+ self.refresh()
42
+ self.yaw_cmd = float(self._state["eef_yaw_deg"])
43
+
44
+ # ------------------------------------------------------------------ state
45
+ def _set_state(self, st):
46
+ prob = state_problems(st, self.n_joints)
47
+ if prob:
48
+ raise DriverError("driver state: " + "; ".join(prob))
49
+ self._state = st
50
+
51
+ def refresh(self):
52
+ self._set_state(self.driver.state())
53
+
54
+ def true_eef(self):
55
+ return np.asarray(self._state["eef_pos"], float)
56
+
57
+ def believed_eef(self):
58
+ return self.true_eef() - self.bias
59
+
60
+ def proprio(self):
61
+ st = self._state
62
+ return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1),
63
+ gripper="closed" if self.grip_closed else "open",
64
+ gripper_width_m=round(float(st["gripper_width_m"]), 4))
65
+
66
+ def joints(self):
67
+ """Joint angles as the robot's encoders would report them under the hidden calibration error."""
68
+ if not np.any(self.bias):
69
+ return [float(v) for v in self._state["joint_pos_rad"]]
70
+ key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"]))
71
+ if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command)
72
+ self._ik_key = key
73
+ self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])]
74
+ return list(self._ik_val)
75
+
76
+ def observe(self, label=""):
77
+ frames, st = self.driver.observe()
78
+ self._set_state(st)
79
+ return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip())
80
+ for c in self.cams]
81
+
82
+ # ------------------------------------------------------------------ helpers
83
+ def wrap_yaw(self, yaw):
84
+ """The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to
85
+ the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit)."""
86
+ cands = [yaw + 180.0 * k for k in range(-3, 4)]
87
+ ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands
88
+ return float(min(ok, key=lambda c: abs(c - self.yaw_cmd)))
89
+
90
+ # ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call)
91
+ def call(self, name, raw_args):
92
+ t0 = time.time()
93
+ self.n_calls += 1
94
+ args = parse_args(raw_args)
95
+ fn = getattr(self, f"_t_{name}", None)
96
+ if fn is None:
97
+ return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
98
+ res = fn(**args)
99
+ res.args, res.wall_s = args, time.time() - t0
100
+ return res
101
+
102
+ def _report(self, name, extra=None):
103
+ rep = dict(ok=True, tool=name)
104
+ rep.update(extra or {})
105
+ rep.update(self.proprio())
106
+ return rep
107
+
108
+ def _t_move_to(self, x, y, z, yaw, speed=None):
109
+ tgt = np.array([x, y, z], float)
110
+ if not np.all(np.isfinite(tgt)):
111
+ return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates"))
112
+ spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed))
113
+ yaw_used = self.wrap_yaw(float(yaw))
114
+ cmd = tgt + self.bias # the hidden calibration error acts on every commanded position
115
+ rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd)
116
+ self.motion_s += float(rep.get("motion_s") or 0.0)
117
+ self._set_state(rep["state"])
118
+ if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution)
119
+ return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; "
120
+ "the arm did not move", driver_error=rep.get("error", "")))
121
+ self.yaw_cmd = yaw_used
122
+ reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02)
123
+ return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached,
124
+ yaw_used_deg=round(yaw_used, 1))))
125
+
126
+ def _gripper(self, close):
127
+ rep = self.driver.gripper(close)
128
+ self.grip_closed = bool(close)
129
+ self.motion_s += float(rep.get("motion_s") or 0.0)
130
+ self._set_state(rep["state"])
131
+ name = "close_gripper" if close else "open_gripper"
132
+ return ToolResult(name, {}, True, self._report(name))
133
+
134
+ def _t_open_gripper(self):
135
+ return self._gripper(False)
136
+
137
+ def _t_close_gripper(self):
138
+ return self._gripper(True)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/fake_driver.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fake robot driver backed by the simulator: answers the driver protocol (lffbench/real/protocol.py) with a simulated
2
+ LFF-Bench task, so the whole real-robot path (harness -> MCP -> real robot server -> driver) runs without hardware.
3
+
4
+ It behaves like a real driver: it reports the TRUE pose in the robot-base frame (no calibration bias of its own; the
5
+ benchmark injects the bias), sends lossless PNG frames, rejects targets outside its hard workspace, and has an
6
+ operator. The operator is the simulator unless --operator console: "reset" resets the simulated scene, "judge" is the
7
+ task's own success rule (task.outcome).
8
+
9
+ python -m lffbench.real.fake_driver --task l7_offcenter_push --seed 3000 --port 9900 --token <t> [--nominal]
10
+ [--operator auto|console] [--log <dir>]
11
+
12
+ --nominal removes the task's hidden calibration bias (L1 tasks), which is what a real arm looks like when the benchmark
13
+ injects the bias in software (real_bias_place).
14
+ """
15
+ import argparse
16
+ import json
17
+ import math
18
+ import os
19
+ import time
20
+ import types
21
+
22
+ import numpy as np
23
+
24
+ from .protocol import CAMERAS, PROTOCOL_VERSION, ConsoleOperator, DriverServer
25
+
26
+
27
+ class SimDriver(DriverServer):
28
+ def __init__(self, task, seed, nominal=False, image_res=512, operator="auto", log_dir=""):
29
+ from ..agent import robot_server as RS # registers every simulated task
30
+ from ..agent.tools import SPEED_RANGE, WS_HI, WS_LO, ToolExecutor
31
+ from ..task_base import TASKS
32
+ self.RS, self.ToolExecutor = RS, ToolExecutor
33
+ self.task_name, self.seed, self.image_res = task, int(seed), int(image_res)
34
+ self.task = TASKS[task](cam_res=self.image_res)
35
+ self.inst = self.task.sample_instance(self.seed)
36
+ if nominal: # same rule as robot_server --nominal
37
+ for k in [k for k in self.inst if "bias" in k]:
38
+ v = self.inst[k]
39
+ self.inst[k] = [0.0] * len(v) if isinstance(v, (list, tuple)) else 0.0 if isinstance(v, (int, float)) else v
40
+ self.operator_mode = operator
41
+ self.log_dir = log_dir
42
+ if log_dir:
43
+ os.makedirs(log_dir, exist_ok=True)
44
+ self.console_op = ConsoleOperator(os.path.join(log_dir, "operator.jsonl") if log_dir else None)
45
+ self._reset()
46
+ sim = self.task.env.sim
47
+ bid = sim.model.body_name2id("robot0_base")
48
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
49
+ self.ws_lo, self.ws_hi = WS_LO - self.base_off, WS_HI - self.base_off
50
+ self.max_speed = float(SPEED_RANGE[1])
51
+ self.yaw_limit_deg = math.degrees(self.task.sk.YAW_LIMIT)
52
+
53
+ def _reset(self):
54
+ self.task.reset_instance(self.inst)
55
+ self.ex = self.ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=CAMERAS)
56
+
57
+ def _log(self, d):
58
+ if self.log_dir:
59
+ with open(os.path.join(self.log_dir, "driver_events.jsonl"), "a") as f:
60
+ f.write(json.dumps(dict(d, t=time.time()), default=str) + "\n")
61
+
62
+ # ------------------------------------------------------------------ protocol
63
+ def info(self):
64
+ return dict(protocol=PROTOCOL_VERSION, robot="Franka Emika Panda (fake driver, simulated)", n_joints=7,
65
+ cameras=list(CAMERAS), workspace=dict(lo=self.ws_lo.round(6).tolist(), hi=self.ws_hi.round(6).tolist()),
66
+ yaw_range_deg=[-self.yaw_limit_deg, self.yaw_limit_deg], max_speed=self.max_speed, ik=True,
67
+ driver_version=f"fake_driver sim:{self.task_name} seed:{self.seed}")
68
+
69
+ def home(self):
70
+ # the simulated arm goes home with the scene reset that always follows (operator "reset")
71
+ return self.state()
72
+
73
+ def move(self, x, y, z, yaw_deg, speed):
74
+ tgt = np.array([x, y, z], float)
75
+ if not (np.all(tgt >= self.ws_lo - 1e-9) and np.all(tgt <= self.ws_hi + 1e-9)):
76
+ return False, "outside the hard workspace", 0.0
77
+ w = tgt + self.base_off
78
+ n0 = self.task.sk.n_steps
79
+ mv = dict(x=float(w[0]), y=float(w[1]), z=float(w[2]), yaw=float(yaw_deg))
80
+ if speed is not None:
81
+ mv["speed"] = float(speed)
82
+ res = self.ex.call("move_to", mv)
83
+ if not res.ok:
84
+ return False, res.report.get("error", "rejected"), 0.0
85
+ return True, None, (self.task.sk.n_steps - n0) * 0.05
86
+
87
+ def gripper(self, close):
88
+ n0 = self.task.sk.n_steps
89
+ self.ex.call("close_gripper" if close else "open_gripper", {})
90
+ return (self.task.sk.n_steps - n0) * 0.05
91
+
92
+ def _joints(self):
93
+ rob = self.task.env.robots[0]
94
+ return self.task.env.sim.data.qpos[np.array(rob._ref_joint_pos_indexes)].copy()
95
+
96
+ def state(self):
97
+ sk = self.task.sk
98
+ return dict(eef_pos=[float(v) for v in sk.eef_pos() - self.base_off], eef_yaw_deg=float(self.ex.eef_yaw_deg()),
99
+ gripper_width_m=float(sk.gripper_width()), joint_pos_rad=[float(v) for v in self._joints()])
100
+
101
+ def images(self):
102
+ return {r.camera: r.array for r in self.ex.observe()}
103
+
104
+ def ik(self, eef_pos, yaw_deg):
105
+ """Joint angles for the grasp point at eef_pos (base frame) with the current orientation: the same damped
106
+ least squares as robot_server._believed_joints (yaw_deg is the current yaw here)."""
107
+ sk = self.task.sk
108
+ T_true = np.eye(4)
109
+ T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos()
110
+ T_b = T_true.copy()
111
+ T_b[:3, 3] = np.asarray(eef_pos, float) + self.base_off
112
+ shim = types.SimpleNamespace(task=self.task, _believed_pose=lambda: (T_b, T_true))
113
+ return [float(v) for v in self.RS._believed_joints(shim)]
114
+
115
+ def operator(self, kind, **kw):
116
+ self._log(dict(ev="operator", kind=kind, **{k: v for k, v in kw.items() if k != "checklist"}))
117
+ if kind == "reset":
118
+ if self.operator_mode == "console":
119
+ self.console_op(kind, **kw)
120
+ self._reset()
121
+ return dict(ok=True)
122
+ if kind == "judge":
123
+ out = self.task.outcome(self.inst)
124
+ if self.operator_mode == "console":
125
+ kw = dict(kw, text=(kw.get("text", "") + f"\n(simulator says: success={bool(out['success'])}, "
126
+ f"{out.get('failure') or out.get('detail') or ''})"))
127
+ return self.console_op(kind, **kw)
128
+ return dict(ok=True, success=bool(out["success"]),
129
+ note=str(out.get("failure") or ("ok" if out["success"] else "")))
130
+ return dict(ok=True)
131
+
132
+ def event(self, ev, **kw):
133
+ self._log(dict(ev=ev, **kw))
134
+
135
+
136
+ def main():
137
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
138
+ ap.add_argument("--task", default="l7_offcenter_push", help="simulated LFF-Bench task that plays the real scene")
139
+ ap.add_argument("--seed", type=int, default=3000)
140
+ ap.add_argument("--port", type=int, default=9900)
141
+ ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
142
+ ap.add_argument("--nominal", action="store_true", help="remove the simulated task's calibration bias")
143
+ ap.add_argument("--operator", default="auto", choices=["auto", "console"])
144
+ ap.add_argument("--image-res", type=int, default=512)
145
+ ap.add_argument("--log", default="", help="directory for driver_events.jsonl / operator.jsonl")
146
+ a = ap.parse_args()
147
+ drv = SimDriver(a.task, a.seed, nominal=a.nominal, image_res=a.image_res, operator=a.operator, log_dir=a.log)
148
+ drv.serve(a.port, token=a.token or None)
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/protocol.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Robot-driver protocol v1: what a real arm (or a fake one) must answer so that LFF-Bench can run on it.
2
+
3
+ The benchmark side (lffbench/real/session.py, on the machine that runs the agent harness) talks to one *driver*
4
+ process (on the robot PC) over HTTP. The driver only moves the arm, reads its state, grabs camera frames and talks
5
+ to the human operator; budgets, attempts, README, logs and the agent interface stay on the benchmark side, so the
6
+ agent sees exactly the same tools as in simulation. Spec for driver authors: lffbench/real/DRIVER.md.
7
+
8
+ This file is shared by both sides and needs only the Python standard library + numpy + Pillow (no simulator):
9
+ DriverClient benchmark side: typed calls to a driver
10
+ DriverServer driver side: HTTP plumbing; subclass it and implement the hardware methods (driver_template.py)
11
+ ConsoleOperator driver side: the operator's terminal (blocking prompts for reset / judging)
12
+
13
+ Every request is POST <url>/<endpoint> with a JSON body and header X-Driver-Token: <token>.
14
+ Every reply is JSON with "ok": true|false. A reply with "fault": true means the robot can no longer be trusted
15
+ (protective stop, e-stop, lost connection, ...): the benchmark ends the run and marks it invalid.
16
+ """
17
+ import base64
18
+ import io
19
+ import json
20
+ import math
21
+ import os
22
+ import secrets
23
+ import sys
24
+ import time
25
+ import traceback
26
+ import urllib.error
27
+ import urllib.request
28
+ from http.server import BaseHTTPRequestHandler, HTTPServer
29
+
30
+ import numpy as np
31
+
32
+ PROTOCOL_VERSION = 1
33
+ CAMERAS = ("agentview", "wrist")
34
+ TOKEN_HEADER = "X-Driver-Token"
35
+ ENDPOINTS = ("info", "home", "move", "gripper", "state", "observe", "ik", "operator", "event")
36
+ OPERATOR_KINDS = ("reset", "judge", "notice")
37
+ EVENTS = ("session_start", "attempt_start", "attempt_end", "episode_end", "session_end", "run_invalid")
38
+
39
+
40
+ class DriverError(RuntimeError):
41
+ """The driver answered something that breaks the protocol (or did not answer)."""
42
+
43
+
44
+ class DriverFault(DriverError):
45
+ """The driver reports a robot fault: the run must stop and is invalid."""
46
+
47
+
48
+ # ------------------------------------------------------------------------------------------------ images
49
+ def encode_image(arr, fmt="png", quality=95):
50
+ """uint8 HxWx3 -> {"format": "png"|"jpeg", "data": base64}. PNG is lossless (the benchmark re-encodes every frame
51
+ as 512x512 JPEG q90 itself, so a JPEG from the driver is compressed twice); JPEG is smaller over a slow link."""
52
+ from PIL import Image
53
+ buf = io.BytesIO()
54
+ im = Image.fromarray(np.asarray(arr, dtype=np.uint8))
55
+ if fmt == "jpeg":
56
+ im.save(buf, format="JPEG", quality=int(quality))
57
+ else:
58
+ im.save(buf, format="PNG")
59
+ return dict(format=fmt, data=base64.b64encode(buf.getvalue()).decode("ascii"))
60
+
61
+
62
+ def decode_image(obj):
63
+ """{"format", "data"} -> uint8 HxWx3 (RGB)."""
64
+ from PIL import Image
65
+ if not isinstance(obj, dict) or "data" not in obj:
66
+ raise DriverError("image must be {\"format\": \"png\"|\"jpeg\", \"data\": <base64>}")
67
+ im = Image.open(io.BytesIO(base64.b64decode(obj["data"])))
68
+ return np.asarray(im.convert("RGB"), dtype=np.uint8)
69
+
70
+
71
+ def square_resize(arr, res):
72
+ """Centre-crop to a square, then resize to res x res. A frame that is already res x res is returned unchanged
73
+ (bit for bit), so a simulator-backed driver gives exactly the simulator's pixels."""
74
+ from PIL import Image
75
+ arr = np.asarray(arr, dtype=np.uint8)
76
+ h, w = arr.shape[:2]
77
+ if h == res and w == res:
78
+ return arr
79
+ s = min(h, w)
80
+ y0, x0 = (h - s) // 2, (w - s) // 2
81
+ arr = arr[y0:y0 + s, x0:x0 + s]
82
+ if s == res:
83
+ return np.ascontiguousarray(arr)
84
+ return np.asarray(Image.fromarray(arr).resize((res, res), Image.BICUBIC))
85
+
86
+
87
+ # ------------------------------------------------------------------------------------------------ validation
88
+ def _vec(v, n):
89
+ return isinstance(v, (list, tuple)) and len(v) == n and all(isinstance(x, (int, float)) and math.isfinite(x) for x in v)
90
+
91
+
92
+ def info_problems(info):
93
+ """-> list of problems with an /info reply (empty = fine)."""
94
+ p = []
95
+ if info.get("protocol") != PROTOCOL_VERSION:
96
+ p.append(f"protocol must be {PROTOCOL_VERSION}, got {info.get('protocol')!r}")
97
+ if not isinstance(info.get("robot"), str) or not info["robot"].strip():
98
+ p.append("robot: non-empty string (e.g. \"AgileX PiPER\")")
99
+ if not isinstance(info.get("n_joints"), int) or not 4 <= info["n_joints"] <= 8:
100
+ p.append("n_joints: integer 4..8")
101
+ if sorted(info.get("cameras") or []) != sorted(CAMERAS):
102
+ p.append(f"cameras must be exactly {list(CAMERAS)}")
103
+ ws = info.get("workspace") or {}
104
+ if not (_vec(ws.get("lo"), 3) and _vec(ws.get("hi"), 3) and all(a < b for a, b in zip(ws["lo"], ws["hi"]))):
105
+ p.append("workspace: {lo: [x, y, z], hi: [x, y, z]} with lo < hi (robot-base frame, metres)")
106
+ yr = info.get("yaw_range_deg")
107
+ if not (_vec(yr, 2) and yr[0] < yr[1] and yr[1] - yr[0] >= 180.0):
108
+ p.append("yaw_range_deg: [lo, hi] with hi - lo >= 180 (the gripper is symmetric, every yaw must be reachable)")
109
+ if not (isinstance(info.get("max_speed"), (int, float)) and 0.01 <= info["max_speed"] <= 1.0):
110
+ p.append("max_speed: m/s, 0.01..1.0")
111
+ if not isinstance(info.get("ik"), bool):
112
+ p.append("ik: true|false (whether /ik is implemented; needed only for tasks with a calibration bias)")
113
+ if not isinstance(info.get("driver_version"), str):
114
+ p.append("driver_version: string (your git commit or a date; it is written into every run's log)")
115
+ return p
116
+
117
+
118
+ def state_problems(st, n_joints):
119
+ p = []
120
+ if not _vec(st.get("eef_pos"), 3):
121
+ p.append("state.eef_pos: [x, y, z] metres")
122
+ if not (isinstance(st.get("eef_yaw_deg"), (int, float)) and math.isfinite(st["eef_yaw_deg"])):
123
+ p.append("state.eef_yaw_deg: number")
124
+ if not (isinstance(st.get("gripper_width_m"), (int, float)) and 0.0 <= st["gripper_width_m"] <= 0.2):
125
+ p.append("state.gripper_width_m: number 0..0.2")
126
+ if not _vec(st.get("joint_pos_rad"), n_joints):
127
+ p.append(f"state.joint_pos_rad: {n_joints} numbers (radians)")
128
+ return p
129
+
130
+
131
+ # ------------------------------------------------------------------------------------------------ benchmark side
132
+ class DriverClient:
133
+ """Typed calls to a driver. `url` like http://127.0.0.1:9900 (an SSH tunnel to the robot PC)."""
134
+
135
+ def __init__(self, url, token, timeout=120.0):
136
+ self.url, self.token, self.timeout = url.rstrip("/"), token, float(timeout)
137
+ self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never through a web proxy
138
+
139
+ def call(self, endpoint, payload=None, timeout=None, allow_not_ok=False):
140
+ req = urllib.request.Request(f"{self.url}/{endpoint}", data=json.dumps(payload or {}).encode(),
141
+ headers={"Content-Type": "application/json", TOKEN_HEADER: self.token})
142
+ try:
143
+ with self.opener.open(req, timeout=timeout if timeout is not None else self.timeout) as r:
144
+ rep = json.loads(r.read().decode())
145
+ except (urllib.error.URLError, OSError, ValueError) as e:
146
+ raise DriverError(f"/{endpoint}: no valid reply from the driver ({type(e).__name__}: {e})") from e
147
+ if not isinstance(rep, dict) or "ok" not in rep:
148
+ raise DriverError(f"/{endpoint}: reply is not a JSON object with \"ok\"")
149
+ if rep.get("fault"):
150
+ raise DriverFault(f"/{endpoint}: robot fault: {rep.get('error', '')}")
151
+ if not rep["ok"] and not allow_not_ok:
152
+ raise DriverError(f"/{endpoint}: {rep.get('error', 'not ok')}")
153
+ return rep
154
+
155
+ def info(self):
156
+ rep = self.call("info")
157
+ prob = info_problems(rep)
158
+ if prob:
159
+ raise DriverError("/info: " + "; ".join(prob))
160
+ return rep
161
+
162
+ def home(self):
163
+ return self.call("home", timeout=max(self.timeout, 300))
164
+
165
+ def move(self, x, y, z, yaw_deg, speed=None):
166
+ """-> reply; ok=false (not a fault) means the target was rejected and the arm did not move."""
167
+ return self.call("move", dict(x=float(x), y=float(y), z=float(z), yaw_deg=float(yaw_deg),
168
+ speed=None if speed is None else float(speed)), allow_not_ok=True)
169
+
170
+ def gripper(self, close):
171
+ return self.call("gripper", dict(close=bool(close)))
172
+
173
+ def state(self):
174
+ return self.call("state")["state"]
175
+
176
+ def observe(self):
177
+ rep = self.call("observe")
178
+ imgs = rep.get("images") or {}
179
+ missing = [c for c in CAMERAS if c not in imgs]
180
+ if missing:
181
+ raise DriverError(f"/observe: missing camera(s) {missing}")
182
+ return {c: decode_image(imgs[c]) for c in CAMERAS}, rep["state"]
183
+
184
+ def ik(self, eef_pos, yaw_deg):
185
+ return self.call("ik", dict(eef_pos=[float(v) for v in eef_pos], yaw_deg=float(yaw_deg)))["joint_pos_rad"]
186
+
187
+ def operator(self, kind, **kw):
188
+ """Blocks until the operator has answered (no timeout)."""
189
+ assert kind in OPERATOR_KINDS, kind
190
+ return self.call("operator", dict(kind=kind, **kw), timeout=24 * 3600)
191
+
192
+ def event(self, ev, **kw):
193
+ assert ev in EVENTS, ev
194
+ return self.call("event", dict(ev=ev, **kw))
195
+
196
+
197
+ # ------------------------------------------------------------------------------------------------ driver side
198
+ class ConsoleOperator:
199
+ """The operator's terminal on the robot PC. Prompts block the driver (the robot must not move while the operator
200
+ resets the scene). Answers are appended to `log_path` (JSON lines)."""
201
+
202
+ def __init__(self, log_path=None, stream_in=None, stream_out=None):
203
+ self.log_path = log_path
204
+ self.inp = stream_in or sys.stdin
205
+ self.out = stream_out or sys.stdout
206
+
207
+ def _say(self, s=""):
208
+ self.out.write(s + "\n")
209
+ self.out.flush()
210
+
211
+ def _ask(self, prompt):
212
+ self.out.write(prompt)
213
+ self.out.flush()
214
+ line = self.inp.readline()
215
+ if not line:
216
+ raise EOFError("operator input closed")
217
+ return line.strip()
218
+
219
+ def _log(self, d):
220
+ if self.log_path:
221
+ os.makedirs(os.path.dirname(os.path.abspath(self.log_path)), exist_ok=True)
222
+ with open(self.log_path, "a") as f:
223
+ f.write(json.dumps(dict(d, t=time.time()), ensure_ascii=False) + "\n")
224
+
225
+ def __call__(self, kind, run="", attempt=None, text="", setup="", checklist=None, **_):
226
+ bar = "=" * 72
227
+ self._say("\n" + bar)
228
+ self._say(f"[{time.strftime('%H:%M:%S')}] run {run} attempt {attempt} -- {kind.upper()}")
229
+ if text:
230
+ self._say(text)
231
+ if kind == "reset":
232
+ if setup:
233
+ self._say("\nScene for this attempt (do it exactly; do not talk to anyone about it):\n" + setup)
234
+ self._ask("\nArm is at home. Put the scene back as described, step out of the cameras, press Enter... ")
235
+ self._log(dict(kind=kind, run=run, attempt=attempt))
236
+ return dict(ok=True)
237
+ if kind == "judge":
238
+ for i, c in enumerate(checklist or [], 1):
239
+ self._say(f" {i}. {c}")
240
+ while True:
241
+ a = self._ask("\nAll conditions met? y = success, n = failure, x = run invalid (robot / camera "
242
+ "problem): ").lower()
243
+ if a in ("y", "n", "x"):
244
+ break
245
+ note = self._ask("Note (one line, optional): ")
246
+ self._log(dict(kind=kind, run=run, attempt=attempt, answer=a, note=note))
247
+ if a == "x":
248
+ return dict(ok=False, fault=True, error=f"operator marked the run invalid: {note}")
249
+ return dict(ok=True, success=a == "y", note=note)
250
+ self._log(dict(kind=kind, run=run, attempt=attempt, text=text))
251
+ return dict(ok=True)
252
+
253
+
254
+ class DriverServer:
255
+ """HTTP plumbing for a driver. Subclass and implement the hardware methods below; see driver_template.py.
256
+ The server is single-threaded on purpose: requests are executed one at a time, and an operator prompt blocks
257
+ every other request until it is answered."""
258
+
259
+ # ---- implement these ------------------------------------------------------------------------------
260
+ def info(self):
261
+ """-> dict (see DRIVER.md §3): protocol, robot, n_joints, cameras, workspace, yaw_range_deg, max_speed, ik,
262
+ driver_version."""
263
+ raise NotImplementedError
264
+
265
+ def home(self):
266
+ """Move to the home pose (gripper open, pointing down). -> state dict."""
267
+ raise NotImplementedError
268
+
269
+ def move(self, x, y, z, yaw_deg, speed):
270
+ """Blocking straight-line move of the grasp point; speed m/s or None (= max_speed).
271
+ -> (ok, error_or_None, motion_s). ok=False: rejected BEFORE moving (outside the hard limits / no IK)."""
272
+ raise NotImplementedError
273
+
274
+ def gripper(self, close):
275
+ """Blocking open / close (force-limited close). -> motion_s."""
276
+ raise NotImplementedError
277
+
278
+ def state(self):
279
+ """-> dict eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad."""
280
+ raise NotImplementedError
281
+
282
+ def images(self):
283
+ """-> {"agentview": uint8 HxWx3 RGB, "wrist": ...}, taken now (after the arm has stopped)."""
284
+ raise NotImplementedError
285
+
286
+ def ik(self, eef_pos, yaw_deg):
287
+ """Optional (info()["ik"] = True): joint angles that put the grasp point at eef_pos / yaw_deg (pointing
288
+ down), close to the current joint angles. -> list of n_joints floats."""
289
+ raise NotImplementedError
290
+
291
+ def operator(self, kind, **kw):
292
+ """Default: the terminal. -> dict (reset: {ok}; judge: {ok, success, note}; notice: {ok})."""
293
+ return self.console(kind, **kw)
294
+
295
+ def event(self, ev, **kw):
296
+ """Start / stop your own recordings here (attempt_start / attempt_end / episode_end ...)."""
297
+ return None
298
+
299
+ image_format = "png"
300
+
301
+ # ---- plumbing -------------------------------------------------------------------------------------
302
+ def dispatch(self, endpoint, a):
303
+ if endpoint == "info":
304
+ return dict(ok=True, **self.info())
305
+ if endpoint == "home":
306
+ return dict(ok=True, state=self.home())
307
+ if endpoint == "move":
308
+ ok, err, motion_s = self.move(float(a["x"]), float(a["y"]), float(a["z"]), float(a["yaw_deg"]),
309
+ None if a.get("speed") is None else float(a["speed"]))
310
+ rep = dict(ok=bool(ok), motion_s=float(motion_s or 0.0), state=self.state())
311
+ if not ok:
312
+ rep["error"] = err or "rejected"
313
+ return rep
314
+ if endpoint == "gripper":
315
+ motion_s = self.gripper(bool(a["close"]))
316
+ return dict(ok=True, motion_s=float(motion_s or 0.0), state=self.state())
317
+ if endpoint == "state":
318
+ return dict(ok=True, state=self.state())
319
+ if endpoint == "observe":
320
+ imgs = self.images()
321
+ return dict(ok=True, images={c: encode_image(imgs[c], self.image_format) for c in CAMERAS},
322
+ state=self.state())
323
+ if endpoint == "ik":
324
+ return dict(ok=True, joint_pos_rad=[float(v) for v in self.ik(a["eef_pos"], float(a["yaw_deg"]))])
325
+ if endpoint == "operator":
326
+ kw = {k: v for k, v in a.items() if k != "kind"}
327
+ return self.operator(a["kind"], **kw)
328
+ if endpoint == "event":
329
+ self.event(a.get("ev", ""), **{k: v for k, v in a.items() if k != "ev"})
330
+ return dict(ok=True)
331
+ return dict(ok=False, error=f"unknown endpoint {endpoint!r}")
332
+
333
+ def serve(self, port, token=None, host="127.0.0.1", operator_log=None):
334
+ """Serve forever on host:port (keep 127.0.0.1 and reach it through an SSH tunnel)."""
335
+ self.token = token or os.environ.get("LFF_DRIVER_TOKEN") or secrets.token_hex(12)
336
+ self.console = ConsoleOperator(operator_log)
337
+ drv = self
338
+
339
+ class H(BaseHTTPRequestHandler):
340
+ def log_message(self, *x):
341
+ pass
342
+
343
+ def do_POST(self):
344
+ try:
345
+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
346
+ if self.headers.get(TOKEN_HEADER) != drv.token:
347
+ rep = dict(ok=False, error="unauthorised")
348
+ else:
349
+ rep = drv.dispatch(self.path.strip("/"), body)
350
+ except NotImplementedError as e:
351
+ rep = dict(ok=False, error=f"not implemented: {self.path} {e}")
352
+ except Exception as e: # anything unexpected on the robot side is a fault: stop the run
353
+ traceback.print_exc()
354
+ rep = dict(ok=False, fault=True, error=f"{type(e).__name__}: {e}")
355
+ data = json.dumps(rep).encode()
356
+ self.send_response(200)
357
+ self.send_header("Content-Type", "application/json")
358
+ self.send_header("Content-Length", str(len(data)))
359
+ self.end_headers()
360
+ self.wfile.write(data)
361
+
362
+ srv = HTTPServer((host, int(port)), H)
363
+ print(f"driver ready on http://{host}:{port} token={self.token}", flush=True)
364
+ srv.serve_forever()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/session.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Robot server for a real arm: robot_server's LA interface (README, robot commands, budgets, attempts, F1, --hide-k,
2
+ memory conditions, events.jsonl, observation files) with a robot driver instead of the simulator.
3
+
4
+ Everything above this server is unchanged: the MCP server (scripts/mcp_robot_server.py), the native-harness adapters
5
+ (Codex / Claude Code, with or without the jail), api_player. They talk to this server exactly as to the simulated one
6
+ (POST /call on 127.0.0.1, same token file, same workspace layout). Below it, lffbench/real/protocol.py talks to the
7
+ driver on the robot PC (usually through an SSH tunnel).
8
+
9
+ What differs from simulation, all of it on purpose (docs/17):
10
+ - README: "a real <robot> arm (<n> joints)" instead of "Franka Emika Panda (7 joints) ... in a physics simulation";
11
+ "a person resets the scene"; "s of robot motion" (budget_left key motion_seconds instead of sim_seconds).
12
+ - outcome: the operator judges the end state against the task's checklist (F1 only; F2 needs simulator measurements).
13
+ - reset: arm to home, then the operator rebuilds the scene from the task's setup sheet.
14
+ - a driver fault ends the episode and marks the run invalid (events.jsonl ev=run_invalid).
15
+ - no video, no regression snapshots here (the driver side records video).
16
+
17
+ python -m lffbench.real.session --task real_offcenter_push --seed 5000 --driver http://127.0.0.1:9900 \
18
+ --sandbox <dir> --log-dir <dir> --port 9800 [robot_server's la options]
19
+ (scripts/start_real_session.sh does this and writes session.json, like scripts/start_robot_session.sh.)
20
+ """
21
+ import argparse
22
+ import json
23
+ import os
24
+ import signal
25
+ import time
26
+ import traceback
27
+ from http.server import BaseHTTPRequestHandler, HTTPServer
28
+
29
+ import numpy as np
30
+
31
+ from ..agent import robot_server as RS
32
+ from ..agent.tools import _json_default
33
+ from .executor import RealToolExecutor
34
+ from .protocol import DriverClient, DriverError, DriverFault
35
+ from .tasks import REAL_TASKS
36
+
37
+ SIM_TEXT = { # robot_server._readme_la sentence -> real-robot sentence (each must occur, else refuse to start)
38
+ "embodiment": ("You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics "
39
+ "simulation.", "You control a real {robot} robot arm ({n} joints) with a two-finger parallel gripper."),
40
+ "reset": ("Before every attempt the scene is reset to exactly the same initial state.",
41
+ "Before every attempt a person resets the scene to the same initial state."),
42
+ "motion": (" s of simulated robot motion;", " s of robot motion;"),
43
+ "joints": ("joint_pos_rad = the 7 arm joint angles", "joint_pos_rad = the {n} arm joint angles"),
44
+ }
45
+ REPLY_TEXT = [("The scene has been reset to exactly the same initial state.",
46
+ "A person has reset the scene to the same initial state.")]
47
+ FAULT_MSG = "The robot stopped because of a hardware problem. The episode is over. Stop now and report."
48
+
49
+
50
+ def _realify(o):
51
+ """Agent-facing reply wording for the real robot (see module doc)."""
52
+ if isinstance(o, dict):
53
+ return {("motion_seconds" if k == "sim_seconds" else k): _realify(v) for k, v in o.items()}
54
+ if isinstance(o, list):
55
+ return [_realify(v) for v in o]
56
+ if isinstance(o, str):
57
+ for a, b in REPLY_TEXT:
58
+ o = o.replace(a, b)
59
+ return o
60
+
61
+
62
+ class RealRobotSession(RS.RobotSession):
63
+ def __init__(self, a): # robot_server.RobotSession.__init__ minus the simulator
64
+ bad = [m for m, c in (("--style la", a.style != "la"), ("--perception rgb", a.perception != "rgb"),
65
+ ("--feedback F0|F1", a.feedback == "F2"), ("--arm none", a.arm != "none"),
66
+ ("no --nominal", a.nominal)) if c]
67
+ if bad:
68
+ raise SystemExit("real robot needs " + ", ".join(bad))
69
+ self.a = a
70
+ self.task = REAL_TASKS[a.task]()
71
+ self.task.judge = self._judge
72
+ if a.max_steps is None:
73
+ a.max_steps = int(self.task.agent_max_steps)
74
+ self.inst = self.task.sample_instance(a.seed)
75
+ self.inst_override = json.loads(a.inst_override) if a.inst_override else {}
76
+ self.inst.update(self.inst_override) # tests only (logged)
77
+ self.arm, self.arm_overrides, self.reveal_text = "none", {}, ""
78
+ self.n_mon_events = 0
79
+ self.protocol = self.task.protocol
80
+ self.k = a.k or self.task.max_attempts
81
+ self.k_shown = 1 if a.hide_k and a.memory == "full" else self.k
82
+ self.sandbox = os.path.abspath(a.sandbox)
83
+ self.obs_dir = os.path.join(self.sandbox, "obs")
84
+ self.log_dir = os.path.abspath(a.log_dir)
85
+ os.makedirs(self.obs_dir, exist_ok=True)
86
+ os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True)
87
+ self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a")
88
+ import secrets
89
+ self.token = secrets.token_hex(8)
90
+ self.n_actions, self.attempt, self.step = 0, 1, 0
91
+ self.finished, self.waiting_new_agent, self.invalid = False, False, ""
92
+ self.history, self.last_send, self.video = [], None, None
93
+ self.base_off = np.zeros(3) # the driver already reports the robot-base frame
94
+ self.run = a.run_name or os.path.basename(self.log_dir)
95
+ self.driver = DriverClient(a.driver, a.driver_token, timeout=a.driver_timeout)
96
+ self.dinfo = self.driver.info()
97
+ if self.task.needs_ik and np.any(self.task.bias(self.inst)) and not self.dinfo["ik"]:
98
+ raise SystemExit(f"{a.task} has a calibration bias: the driver must implement /ik (believed joint angles)")
99
+ m = float(self.task.bias_margin)
100
+ self.ws_lo = np.asarray(self.dinfo["workspace"]["lo"], float) + [m, m, 0.0]
101
+ self.ws_hi = np.asarray(self.dinfo["workspace"]["hi"], float) - [m, m, 0.0]
102
+ self.driver.event("session_start", run=self.run, task=a.task, seed=a.seed, k=self.k)
103
+ self._start_attempt(reset=True)
104
+ self._write_sandbox()
105
+ self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol,
106
+ memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception,
107
+ inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm,
108
+ arm_overrides={}, reveal="", dossier=a.dossier or "", backend="real",
109
+ driver_info={k: v for k, v in self.dinfo.items() if k != "ok"},
110
+ agent_workspace=dict(lo=self.ws_lo.round(4).tolist(), hi=self.ws_hi.round(4).tolist()),
111
+ inst_override=self.inst_override, sim_counterpart=self.task.sim_counterpart,
112
+ video_ignored=bool(a.video)))
113
+
114
+ # ------------------------------------------------------------------ simulator-dependent parts, replaced
115
+ def _start_attempt(self, reset):
116
+ self.n_actions = 0
117
+ if reset:
118
+ self.driver.home()
119
+ self.driver.operator("reset", run=self.run, attempt=self.attempt, setup=self.task.setup_text(self.inst),
120
+ text=f"task {self.a.task} seed {self.a.seed}")
121
+ self.driver.event("attempt_start", run=self.run, attempt=self.attempt)
122
+ self.ex = RealToolExecutor(self.driver, self.dinfo, bias=self.task.bias(self.inst), image_res=self.a.image_res)
123
+ self.step = 0
124
+
125
+ def _judge(self, inst):
126
+ self.driver.event("attempt_end", run=self.run, attempt=self.attempt)
127
+ rep = self.driver.operator("judge", run=self.run, attempt=self.attempt, checklist=self.task.checklist(inst),
128
+ text=f"task {self.a.task} seed {self.a.seed}: judge the scene as it is now")
129
+ if not isinstance(rep.get("success"), bool):
130
+ raise DriverError("/operator judge: reply needs \"success\": true|false")
131
+ return dict(success=rep["success"], note=str(rep.get("note", "")), judged_by="operator",
132
+ motion_s=round(self.ex.motion_s, 2))
133
+
134
+ def _budget_left(self):
135
+ used = self.ex.motion_s
136
+ return dict(commands=max(self.a.max_steps - self.n_actions, 0),
137
+ sim_seconds=round(max(self.sim_budget() - used, 0.0), 1)) # renamed to motion_seconds in replies
138
+
139
+ def _state_v2(self):
140
+ p = self.ex.proprio()
141
+ st = dict(eef_pos=p["eef_pos"], eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
142
+ st["joint_pos_rad"] = [round(float(v), 4) for v in self.ex.joints()]
143
+ st["budget_left"] = self._budget_left()
144
+ return st
145
+
146
+ def _snap_regressions(self):
147
+ return None
148
+
149
+ def readme_la(self):
150
+ text = RS._readme_la(self)
151
+ n = int(self.dinfo["n_joints"])
152
+ for key, (old, new) in SIM_TEXT.items():
153
+ if key == "reset" and self.protocol != "cross":
154
+ continue
155
+ if old not in text: # robot_server's README changed: update SIM_TEXT rather than ship a half-sim README
156
+ raise SystemExit(f"README sentence for {key!r} not found in robot_server._readme_la: {old!r}")
157
+ text = text.replace(old, new.format(robot=self.dinfo["robot"], n=n))
158
+ return text
159
+
160
+ def _done(self, reason):
161
+ rep = RS.RobotSession._done(self, reason)
162
+ if self.finished:
163
+ self.driver.event("episode_end", run=self.run, attempt=self.attempt)
164
+ return rep
165
+
166
+ # ------------------------------------------------------------------ dispatch
167
+ def handle(self, cmd, args):
168
+ if self.invalid:
169
+ return dict(ok=False, error=FAULT_MSG)
170
+ try:
171
+ return _realify(RS.RobotSession.handle(self, cmd, args))
172
+ except DriverError as e: # robot fault, operator marked the run invalid, or the driver broke the protocol
173
+ self.invalid, self.finished = str(e), True
174
+ self.log(dict(ev="run_invalid", attempt=self.attempt, step=self.step, cmd=cmd, args=args,
175
+ fault=isinstance(e, DriverFault), error=str(e), traceback=traceback.format_exc()[-2000:]))
176
+ try:
177
+ self.driver.event("run_invalid", run=self.run, attempt=self.attempt, error=str(e))
178
+ except DriverError:
179
+ pass
180
+ return dict(ok=False, error=FAULT_MSG)
181
+
182
+ def handle_v2(self, cmd, args):
183
+ if cmd != "move_eef" or self.finished:
184
+ return RS._handle_v2(self, cmd, args)
185
+ return self._move_eef(args)
186
+
187
+ def _move_eef(self, args):
188
+ """robot_server._handle_v2's move_eef branch (same checks, order, replies and log lines) with the driver's
189
+ workspace instead of the simulator's WS_LO / WS_HI. tests/real_selfcheck.py compares the two paths reply by
190
+ reply; keep them in step."""
191
+ cmd = "move_eef"
192
+ self.n_actions += 1
193
+ if self.n_actions > self.a.max_steps:
194
+ rep = self._done("command budget used up (automatic)")
195
+ rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up."
196
+ return rep
197
+ self.step += 1
198
+ p = self.ex.proprio()
199
+ unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}
200
+ if unknown:
201
+ rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed")
202
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
203
+ return rep
204
+ try:
205
+ cur = np.asarray(p["eef_pos"], float)
206
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
207
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
208
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
209
+ except (TypeError, ValueError):
210
+ rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers")
211
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
212
+ return rep
213
+ grip = args.get("gripper")
214
+ if grip not in (None, "open", "close"):
215
+ rep = dict(ok=False, error="gripper must be open or close")
216
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
217
+ return rep
218
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
219
+ tgt = np.asarray(tgt)
220
+ if moving and not (np.all(tgt >= self.ws_lo) and np.all(tgt <= self.ws_hi)):
221
+ rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move")
222
+ rep.update(self._state_v2())
223
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
224
+ return rep
225
+ left = self._budget_left()["sim_seconds"]
226
+ raw = {}
227
+ rejected = False
228
+ if moving:
229
+ mv = dict(x=float(tgt[0]), y=float(tgt[1]), z=float(tgt[2]), yaw=yaw)
230
+ if speed is not None:
231
+ mv["speed"] = speed
232
+ res = self.ex.call("move_to", mv)
233
+ raw.update(res.report)
234
+ rejected = not res.ok # the driver refused (no IK solution ...): the arm did not move, skip the gripper
235
+ if grip is not None and not rejected:
236
+ res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {})
237
+ raw.update(res.report)
238
+ rep = dict(ok=bool(raw.get("ok", True)))
239
+ if raw.get("error"):
240
+ rep["error"] = raw["error"]
241
+ rep.update(self._state_v2())
242
+ if moving:
243
+ err = tgt - np.asarray(rep["eef_pos"])
244
+ dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0
245
+ rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1))
246
+ rep["images"] = self._save_obs(cmd)
247
+ rep.update(self._la_files())
248
+ self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw))
249
+ if rep["budget_left"]["sim_seconds"] <= 0 and left > 0:
250
+ fin = self._done("motion budget used up (automatic)")
251
+ fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up."
252
+ rep["attempt_ended"] = fin
253
+ return rep
254
+
255
+
256
+ def serve(a):
257
+ """robot_server.serve with the real session (same HTTP contract: POST /call, X-Token, 127.0.0.1)."""
258
+ sess = RealRobotSession(a)
259
+
260
+ class H(BaseHTTPRequestHandler):
261
+ def log_message(self, *x):
262
+ pass
263
+
264
+ def do_POST(self):
265
+ t_recv = time.time()
266
+ cmd = ""
267
+ try:
268
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
269
+ cmd = body.get("cmd", "")
270
+ if self.headers.get("X-Token") != sess.token:
271
+ rep = dict(ok=False, error="unauthorised")
272
+ else:
273
+ rep = sess.handle(cmd, body.get("args", {}) or {})
274
+ except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent
275
+ sess.log(dict(ev="error", error=traceback.format_exc()))
276
+ rep = dict(ok=False, error=f"internal error: {type(e).__name__}")
277
+ data = json.dumps(rep, default=_json_default, indent=None).encode()
278
+ if "text" in rep:
279
+ data = rep["text"].encode()
280
+ self.send_response(200)
281
+ self.send_header("Content-Type", "application/json")
282
+ self.end_headers()
283
+ self.wfile.write(data)
284
+ t_send = time.time()
285
+ sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send,
286
+ server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None))
287
+ sess.last_send = t_send
288
+
289
+ def _term(*_):
290
+ try: # short timeout: the driver may be blocked on an operator prompt
291
+ sess.driver.call("event", dict(ev="session_end", run=sess.run, attempt=sess.attempt), timeout=5)
292
+ except Exception:
293
+ pass
294
+ os._exit(0)
295
+
296
+ signal.signal(signal.SIGTERM, _term)
297
+ srv = HTTPServer(("127.0.0.1", a.port), H)
298
+ print(f"real robot server ready on 127.0.0.1:{a.port} driver={a.driver} sandbox={sess.sandbox} log={sess.log_dir}",
299
+ flush=True)
300
+ with open(os.path.join(sess.log_dir, "READY"), "w") as f:
301
+ f.write(str(os.getpid()))
302
+ srv.serve_forever()
303
+
304
+
305
+ def parser():
306
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
307
+ ap.add_argument("--task", required=True, choices=sorted(REAL_TASKS))
308
+ ap.add_argument("--seed", type=int, required=True)
309
+ ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900"),
310
+ help="driver URL (default $LFF_REAL_DRIVER or http://127.0.0.1:9900, i.e. an SSH tunnel)")
311
+ ap.add_argument("--driver-token", default=os.environ.get("LFF_DRIVER_TOKEN", ""),
312
+ help="driver token (default $LFF_DRIVER_TOKEN)")
313
+ ap.add_argument("--driver-timeout", type=float, default=180.0, help="seconds per driver call (operator: no limit)")
314
+ ap.add_argument("--run-name", default="", help="shown to the operator (default: the log dir name)")
315
+ ap.add_argument("--inst-override", default=os.environ.get("LFF_REAL_INST_OVERRIDE", ""),
316
+ help="TESTS ONLY: JSON merged into the instance (logged; default $LFF_REAL_INST_OVERRIDE)")
317
+ # robot_server's options that apply to the real robot (same names and defaults as there, except perception/style)
318
+ ap.add_argument("--k", type=int, default=None)
319
+ ap.add_argument("--memory", default="full", choices=["full", "none"])
320
+ ap.add_argument("--hide-k", action="store_true")
321
+ ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
322
+ ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"])
323
+ ap.add_argument("--image-res", type=int, default=512)
324
+ ap.add_argument("--port", type=int, default=8765)
325
+ ap.add_argument("--sandbox", required=True)
326
+ ap.add_argument("--log-dir", required=True)
327
+ ap.add_argument("--max-steps", type=int, default=None)
328
+ ap.add_argument("--perception", default="rgb", choices=["depth", "rgb", "rgbd"])
329
+ ap.add_argument("--style", default="la", choices=["v1", "v2", "la"])
330
+ ap.add_argument("--nominal", action="store_true")
331
+ ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"])
332
+ ap.add_argument("--max-tool-calls", type=int, default=100)
333
+ ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"])
334
+ ap.add_argument("--dossier", default="")
335
+ ap.add_argument("--video", default="", help="ignored (the driver side records video)")
336
+ ap.add_argument("--video-every", type=int, default=3)
337
+ ap.add_argument("--video-fps", type=int, default=20)
338
+ return ap
339
+
340
+
341
+ def main():
342
+ serve(parser().parse_args())
343
+
344
+
345
+ if __name__ == "__main__":
346
+ main()
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/real/tasks.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Real-robot tasks. Same idea as lffbench/tasks/ (an instruction, a hidden variable the agent cannot see before it acts,
2
+ a success rule), but the scene is physical: the instance is a setup sheet the operator follows, and the operator
3
+ judges the end state. The hidden variable is drawn from the seed, so the instance list of a run is reproducible and
4
+ nobody has to choose it by hand.
5
+
6
+ Seeds: 5000+ for real-robot runs (same convention as simulation: 1000-1999 development, 3000 pilots, 5000+ test).
7
+ """
8
+ import numpy as np
9
+
10
+ REAL_TASKS = {}
11
+
12
+
13
+ def register_real(cls):
14
+ REAL_TASKS[cls.name] = cls
15
+ return cls
16
+
17
+
18
+ class RealTask:
19
+ name = "real_base"
20
+ sim_counterpart = "" # the simulated task with the same hidden variable (for the paper's mapping only)
21
+ protocol = "cross"
22
+ max_attempts = 3
23
+ agent_max_steps = 40
24
+ instruction = ""
25
+ instruction_indirect = ""
26
+ needs_ik = False # True if the instance carries a calibration bias (believed joint angles need the driver's /ik)
27
+ bias_margin = 0.0 # largest possible |bias| (m): the agent-facing workspace is shrunk by it, so a rejected target
28
+ # never depends on the hidden bias
29
+ judge = None # set by RealRobotSession: inst -> outcome dict, asks the operator
30
+
31
+ def outcome(self, inst):
32
+ """Same role as LFFTask.outcome: called by robot_server's _done when an attempt ends."""
33
+ return self.judge(inst)
34
+
35
+ def sample_instance(self, seed):
36
+ raise NotImplementedError
37
+
38
+ def setup_text(self, inst):
39
+ """What the operator builds before every attempt (shown on the robot PC only, never to the agent)."""
40
+ raise NotImplementedError
41
+
42
+ def checklist(self, inst):
43
+ """Conditions the operator checks when an attempt ends; success = all of them."""
44
+ raise NotImplementedError
45
+
46
+ def bias(self, inst):
47
+ """Hidden calibration error added to every commanded position (robot-base frame, metres)."""
48
+ return np.zeros(3)
49
+
50
+ def feedback(self, inst, out, level="F1"):
51
+ # same text as LFFTask.feedback (F0 / F1); F2 needs simulator measurements and is refused at session start
52
+ if level == "F0":
53
+ return ""
54
+ return "Attempt succeeded." if out["success"] else "Attempt failed."
55
+
56
+
57
+ @register_real
58
+ class RealOffcenterPush(RealTask):
59
+ """L7 l7_offcenter_push on a real arm: a long opaque box with a hidden weight at one end. Pushing the middle of
60
+ its back face turns it (visible in the agentview); the fix is to push nearer the heavy end or to straighten it
61
+ afterwards. Physical build and scene layout: DRIVER.md §6.1."""
62
+ name = "real_offcenter_push"
63
+ sim_counterpart = "l7_offcenter_push"
64
+ # same wording as the simulated task (2026-10-19): end state only, no hint about the weight or where to push
65
+ instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the "
66
+ "green rectangle ahead of it (farther from the robot).")
67
+ instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up "
68
+ "completely inside the marked green area ahead of it (farther from the robot).")
69
+ SLOTS = ("end", "inner") # weight compartments per side: at the very end, or one compartment further in
70
+
71
+ def sample_instance(self, seed):
72
+ rng = np.random.default_rng(seed)
73
+ return dict(seed=int(seed), weight_side=str(rng.choice(["left", "right"])), weight_slot=str(rng.choice(self.SLOTS)))
74
+
75
+ def setup_text(self, inst):
76
+ side = {"left": "LEFT (the robot's left, +y)", "right": "RIGHT (the robot's right, -y)"}[inst["weight_side"]]
77
+ slot = {"end": "the outermost compartment", "inner": "the second compartment from that end"}[inst["weight_slot"]]
78
+ return "\n".join([
79
+ f"- weight block inside the box: {side} end, in {slot};",
80
+ "- the other compartments stay empty; close the lid; both ends look the same from outside;",
81
+ "- box on the START tape marks: long side across the robot (left-right), back face on the back mark;",
82
+ "- nothing else on the table; the green target rectangle tape unchanged.",
83
+ ])
84
+
85
+ def checklist(self, inst):
86
+ return ["all four bottom corners of the box are inside the green rectangle (a corner on the tape = outside)",
87
+ "the box is standing on its bottom face (not tipped over)",
88
+ "the box was only pushed with the closed gripper (no pushes with the fingers open)",
89
+ "the gripper is not touching the box"]
90
+
91
+
92
+ @register_real
93
+ class RealBiasPlace(RealTask):
94
+ """L1 l1_bias_place on a real arm: pick-and-place with a calibration error injected in software (the benchmark
95
+ adds `bias` to every commanded position and subtracts it from every reported one, exactly as in simulation).
96
+ The arm itself is unchanged; the cameras show where the gripper really is. Physical build: DRIVER.md §6.2."""
97
+ name = "real_bias_place"
98
+ sim_counterpart = "l1_bias_place"
99
+ instruction = "Pick up the red cube and put it into the bowl."
100
+ instruction_indirect = "Pick up the small red block and put it into the round bowl."
101
+ needs_ik = True
102
+ R_MIN, R_MAX = 0.025, 0.040 # bias magnitude (m), as l1_bias_place
103
+ bias_margin = R_MAX
104
+ LAYOUTS = ("A", "B", "C", "D") # taped (cube mark, bowl mark) pairs; DRIVER.md §6.2
105
+
106
+ def sample_instance(self, seed):
107
+ rng = np.random.default_rng(seed)
108
+ r, th = float(rng.uniform(self.R_MIN, self.R_MAX)), float(rng.uniform(-np.pi, np.pi))
109
+ return dict(seed=int(seed), layout=str(rng.choice(self.LAYOUTS)),
110
+ bias=[round(r * np.cos(th), 4), round(r * np.sin(th), 4), 0.0], bias_r=round(r, 4),
111
+ bias_theta=round(th, 4))
112
+
113
+ def bias(self, inst):
114
+ return np.asarray(inst["bias"], float)
115
+
116
+ def setup_text(self, inst):
117
+ L = inst["layout"]
118
+ return "\n".join([f"- red cube on mark {L}1, bowl on mark {L}2 (layout {L});",
119
+ "- nothing else on the table."])
120
+
121
+ def checklist(self, inst):
122
+ return ["the red cube is inside the bowl (resting in it, not on the rim)",
123
+ "the gripper is open and not holding the cube"]
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/tasks/__init__.py ADDED
File without changes
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/tasks/l1_yaw.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L1-C yaw_bias: put a long bar into a narrow holder, with an arm whose wrist rotation is miscalibrated.
2
+
3
+ Category system_identification (level L1, action fine-tuning): the method (top-down pick across the bar, carry,
4
+ line the bar up with the holder, release just above the holder) and the scene understanding are right; only the
5
+ robot's own wrist rotation is off.
6
+
7
+ Hidden variable: a fixed wrist-yaw calibration offset beta, |beta| ~ U[15, 30] deg with a random sign: every
8
+ commanded gripper yaw theta is executed as theta + beta. The robot reports its yaw in its own (miscalibrated) frame,
9
+ so the agent's proprioception says "yaw = theta" (implemented by shifting the robot's notion of yaw 0, `Skills.R0`,
10
+ by beta: the agent harness computes the reported yaw from R0, so beta never shows up in a reading). At reset the
11
+ wrist is turned to the robot's own yaw 0 (true yaw beta), so the first reading is 0.
12
+
13
+ Why the prior fails: the bar is 14 cm long and 1.8 cm wide; the holder's opening is 3.2 cm wide (16 cm long).
14
+ Commanded to grasp square across the bar, the jaws actually come down rotated by beta; closing turns the bar until it
15
+ lies square in the jaws, so the bar ends up rotated by beta relative to where the robot thinks it is. Lined up
16
+ "exactly" with the holder, the bar is then beta off the holder's axis; its footprint across the opening
17
+ (14 sin beta + 1.8 cos beta >= 5.4 cm for beta >= 15 deg) is wider than the holder (4.4 cm outside), so it comes
18
+ down across the walls and stays on top of the holder at an angle -- clearly visible from both cameras. The
19
+ alignment tolerance is about +-5 deg (geometry; measured: see the task card).
20
+
21
+ What has to be learned: F2 reports by how many degrees, and in which sense, the bar's long axis was rotated from the
22
+ holder's long axis when the gripper opened (and how far the jaws were turned from square to the bar when they
23
+ closed). That angle is beta itself, so after one failure beta can be estimated and subtracted from every commanded
24
+ yaw.
25
+ """
26
+ import re
27
+
28
+ import numpy as np
29
+
30
+ from .. import envs
31
+ from ..bddl import write_bddl
32
+ from ..objects import bin_xml, box_xml, register_generated
33
+ from ..skills import Skills, _rotz
34
+ from ..task_base import LFFTask, register_task
35
+
36
+ BAR, HOLDER = "bar_1", "holder_1"
37
+ DISTRACTORS = ("cream_cheese_1", "butter_1")
38
+ FREE_OBJECTS = (BAR,) + DISTRACTORS
39
+ NAMES = {BAR: "blue bar", HOLDER: "holder", "cream_cheese_1": "cream cheese", "butter_1": "butter"}
40
+ DESCR = {BAR: "long blue stick", HOLDER: "narrow grey trough", "cream_cheese_1": "flat blue box",
41
+ "butter_1": "small orange box"}
42
+
43
+ BAR_HALF = (0.070, 0.009, 0.009) # 14 x 1.8 x 1.8 cm, long side along the bar's x axis
44
+ HOLDER_IN = (0.080, 0.016) # inner half extents of the holder's opening: 16 x 3.2 cm
45
+ WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030
46
+ HOLDER_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height
47
+ RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
48
+ MASS = {BAR: 0.070, "cream_cheese_1": 0.227, "butter_1": 0.250}
49
+ # Bar friction 0.5 with geom priority, so it is used for all bar contacts (also against the finger pads, mu 2). With
50
+ # the pads' mu 2 the jaws pinch a misaligned bar at their corners and it stays skewed in the hand (measured: turned
51
+ # 3-13 deg of beta 15-25 deg while closing); with 0.5 the closing jaws square it up (turned = beta, measured).
52
+ BAR_MU = 0.5
53
+
54
+ SITE_ABOVE_TABLE = 0.0105 # grasp point 1.05 cm above the table: fingertips ~1 mm above it
55
+ Z_CARRY = envs.TABLE_Z + 0.15
56
+ RELEASE_GAP = 0.012 # bar bottom this far above the holder's rim at release
57
+ BETA_MIN, BETA_MAX = np.deg2rad(15), np.deg2rad(30)
58
+ AXIS_MAX = np.deg2rad(45) # bar / holder long axes within +-45 deg of the forward (x) direction
59
+ HOME_XY = np.array([-0.21, 0.0])
60
+ REHOME_STEPS = 40
61
+
62
+
63
+ def wrap_half(a):
64
+ """angle modulo pi into [-pi/2, pi/2) (the bar, the holder and the jaws are 180-deg symmetric)"""
65
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
66
+
67
+
68
+ def _yaw_of_xmat(xmat):
69
+ return float(np.arctan2(xmat[1, 0], xmat[0, 0]))
70
+
71
+
72
+ def _seg_dist(p, a, b):
73
+ ab = b - a
74
+ u = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0, 1)
75
+ return float(np.linalg.norm(a + u * ab - p))
76
+
77
+
78
+ def _q(axis, a):
79
+ h = a / 2
80
+ return {"z": np.array([np.cos(h), 0, 0, np.sin(h)])}[axis]
81
+
82
+
83
+ def _qmul(a, b):
84
+ w1, x1, y1, z1 = a
85
+ w2, x2, y2, z2 = b
86
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
87
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
88
+
89
+
90
+ def dir_words(dx, dy):
91
+ """Robot-frame description: +x = forward (away from the robot), +y = the robot's left."""
92
+ parts = []
93
+ if abs(dy) >= 0.0005:
94
+ parts.append(f"{100 * abs(dy):.1f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'}")
95
+ if abs(dx) >= 0.0005:
96
+ parts.append(f"{100 * abs(dx):.1f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'}")
97
+ return " and ".join(parts) if parts else "exactly at the position"
98
+
99
+
100
+ def rot_words(a):
101
+ """Sense of a rotation about the vertical axis. Positive = counter-clockwise seen from above = from forward (+x)
102
+ towards the robot's left (+y) = increasing yaw."""
103
+ d = np.degrees(a)
104
+ if abs(d) < 0.5:
105
+ return "not rotated (within 0.5 deg)"
106
+ if d > 0:
107
+ return f"rotated {d:.0f} deg counter-clockwise seen from above (from forward towards the robot's left, +yaw)"
108
+ return f"rotated {-d:.0f} deg clockwise seen from above (from forward towards the robot's right, -yaw)"
109
+
110
+
111
+ class YawSkills(Skills):
112
+ """Skills with a miscalibrated wrist: commanded yaw theta is executed as theta + yaw_bias. Implemented by shifting
113
+ the robot's notion of yaw 0 (`R0`, which Skills uses to build every orientation target and the agent harness uses
114
+ to report the yaw) by yaw_bias; `R0_true` is the real top-down orientation at yaw 0. Also logs what the outcome
115
+ measurement needs, whoever drives the skills (scripted policy or agent)."""
116
+
117
+ def __init__(self, env, yaw_bias=0.0, recorder=None):
118
+ super().__init__(env, bias=None, recorder=recorder)
119
+ self.yaw_bias = float(yaw_bias)
120
+ self.R0_true = self.R0.copy()
121
+ self.R0 = _rotz(self.yaw_bias) @ self.R0_true
122
+ self.events = []
123
+ m = env.sim.model
124
+ self._finger_geoms = {
125
+ side: [m.geom_name2id(g) for g in env.robots[0].gripper.important_geoms[side]]
126
+ for side in ("left_finger", "right_finger")}
127
+ self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_")]
128
+ self._obj_geoms = {n: envs.obj_geom_ids(env, n) for n in FREE_OBJECTS}
129
+ self.bar_z0 = float(envs.obj_pos(env, BAR)[2])
130
+ self.bar_zmax = self.bar_z0
131
+ self.bar_ref_yaw = self.bar_yaw()
132
+ self.bar_ref = envs.obj_pos(env, BAR) # bar pose before the fingers last touched it
133
+
134
+ # ------------------------------------------------------------------ state
135
+ def true_yaw(self):
136
+ return _yaw_of_xmat(self.eef_mat() @ self.R0_true.T)
137
+
138
+ def reported_yaw(self):
139
+ """Yaw as the miscalibrated robot believes it to be. Anything shown to the agent must use this."""
140
+ return _yaw_of_xmat(self.eef_mat() @ self.R0.T)
141
+
142
+ def bar_yaw(self):
143
+ return _yaw_of_xmat(self.env.sim.data.body_xmat[envs.body_id(self.env, BAR)].reshape(3, 3))
144
+
145
+ def touching(self):
146
+ return [n for n, gs in self._obj_geoms.items() if envs.contacts_between(self.env, self._grip_geoms, gs)]
147
+
148
+ def holding_bar(self):
149
+ bg = self._obj_geoms[BAR]
150
+ return all(envs.contacts_between(self.env, gs, bg) for gs in self._finger_geoms.values())
151
+
152
+ def holding(self, obj_name):
153
+ """The agent harness reports `holding_object` through this; same finger-contact test as the outcome."""
154
+ if obj_name == BAR:
155
+ return self.holding_bar()
156
+ return super().holding(obj_name)
157
+
158
+ def wrap_yaw(self, yaw):
159
+ """Like Skills.wrap_yaw (the gripper is symmetric under pi), but the window |yaw| <= YAW_LIMIT is applied
160
+ to the TRUE wrist yaw (commanded + yaw_bias): the joint-7 limit is a property of the real wrist. Without
161
+ this, a commanded -113 deg with yaw_bias -30 deg drives joint 7 into its limit (measured: stops at true
162
+ -137 deg, reported -107 deg)."""
163
+ cands = [yaw + k * np.pi for k in range(-3, 4)]
164
+ ok = [c for c in cands if abs(c + self.yaw_bias) <= self.YAW_LIMIT] or cands
165
+ return float(min(ok, key=lambda c: abs(c - self.yaw)))
166
+
167
+ def move_to(self, target, *args, **kwargs):
168
+ rep = super().move_to(target, *args, **kwargs)
169
+ rep["yaw_reported_deg"] = round(float(np.degrees(self.reported_yaw())), 1)
170
+ return rep
171
+
172
+ def _act(self, dpos, drot, grip):
173
+ super()._act(dpos, drot, grip)
174
+ self.bar_zmax = max(self.bar_zmax, float(envs.obj_pos(self.env, BAR)[2]))
175
+ if self.grip < 0 and not envs.contacts_between(self.env, self._grip_geoms, self._obj_geoms[BAR]):
176
+ self.bar_ref_yaw = self.bar_yaw()
177
+ self.bar_ref = envs.obj_pos(self.env, BAR)
178
+
179
+ def set_gripper(self, close, steps=15):
180
+ if close and self.grip < 0:
181
+ self.events.append(dict(kind="close", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(),
182
+ bar=envs.obj_pos(self.env, BAR).tolist(), bar_ref_yaw=self.bar_ref_yaw,
183
+ bar_ref=np.asarray(self.bar_ref).tolist(), touching=self.touching(),
184
+ step=self.n_steps))
185
+ elif not close and self.grip > 0 and self.holding_bar():
186
+ self.events.append(dict(kind="release", eef=self.eef_pos().tolist(), true_yaw=self.true_yaw(),
187
+ bar=envs.obj_pos(self.env, BAR).tolist(), bar_yaw=self.bar_yaw(),
188
+ step=self.n_steps))
189
+ rep = super().set_gripper(close, steps)
190
+ if close and self.events and self.events[-1]["kind"] == "close":
191
+ self.events[-1]["bar_yaw_after"] = self.bar_yaw()
192
+ return rep
193
+
194
+
195
+ @register_task
196
+ class YawBias(LFFTask):
197
+ name = "l1_yaw_bias"
198
+ level = "L1"
199
+ category = "system_identification"
200
+ capabilities = ("Perceive", "Utilize")
201
+ protocol = "cross"
202
+ instruction = "Pick up the blue bar and put it into the holder."
203
+ instruction_indirect = "Pick up the long blue stick and drop it into the narrow grey trough so that it lies inside."
204
+ pick_lift_min = 0.03
205
+
206
+ # ------------------------------------------------------------ scene
207
+ def make_bddl(self):
208
+ bar = register_generated("LffYbBar", box_xml("lff_yb_bar", BAR_HALF, (0.15, 0.35, 0.85, 1.0), density=1500))
209
+ holder = register_generated("LffYbHolder", bin_xml("lff_yb_holder", HOLDER_IN, WALL_H, wall_t=WALL_T,
210
+ floor_t=FLOOR_T, rgba=(0.55, 0.56, 0.60, 1.0),
211
+ density=2000), free=False)
212
+ objs = [(BAR, bar, "bar_region", (-0.21, -0.26, -0.19, -0.24)),
213
+ ("cream_cheese_1", "cream_cheese", "cheese_region", (-0.21, 0.24, -0.19, 0.26)),
214
+ ("butter_1", "butter", "butter_region", (0.15, -0.26, 0.17, -0.24))]
215
+ fx = [(HOLDER, holder, "holder_region", (0.09, -0.01, 0.11, 0.01))]
216
+ return write_bddl(self.name, self.instruction, objs, fx)
217
+
218
+ def __init__(self, cam_res=None):
219
+ super().__init__(cam_res)
220
+ self._base_quat = {n: envs.obj_quat(self.env, n) for n in FREE_OBJECTS}
221
+ m = self.env.sim.model
222
+ self._holder_bid = m.body_name2id(self.env.fixtures_dict[HOLDER].root_body)
223
+
224
+ def _place(self, name, xy, yaw, z0=envs.TABLE_Z):
225
+ q = _qmul(_q("z", yaw), self._base_quat[name])
226
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], z0 + 0.3], quat_wxyz=q)
227
+ self.env.sim.forward()
228
+ qa, _ = envs.free_joint_addr(self.env, name)
229
+ self.env.sim.data.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (z0 + 0.0005)
230
+ self.env.sim.forward()
231
+
232
+ def sample_instance(self, seed):
233
+ rng = np.random.default_rng(seed)
234
+ while True:
235
+ b = np.array([rng.uniform(-0.16, 0.04), rng.uniform(-0.20, 0.20)])
236
+ h = np.array([rng.uniform(-0.14, 0.06), rng.uniform(-0.22, 0.22)])
237
+ if np.linalg.norm(h - b) < 0.22:
238
+ continue
239
+ placed = [b, h]
240
+ dis = {}
241
+ for name in DISTRACTORS:
242
+ for _ in range(300):
243
+ p = np.array([rng.uniform(-0.22, 0.12), rng.uniform(-0.27, 0.27)])
244
+ if any(np.linalg.norm(p - o) < 0.15 for o in placed):
245
+ continue
246
+ if any(_seg_dist(p, a, c) < 0.10 for a, c in ((b, h), (HOME_XY, b))):
247
+ continue
248
+ break
249
+ else:
250
+ break
251
+ placed.append(p)
252
+ dis[name] = dict(xy=p.round(5).tolist(), yaw=float(rng.uniform(-np.pi, np.pi)))
253
+ if len(dis) == len(DISTRACTORS):
254
+ break
255
+ bar_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX))
256
+ holder_yaw = float(rng.uniform(-AXIS_MAX, AXIS_MAX))
257
+ beta = float(rng.choice([-1.0, 1.0]) * rng.uniform(BETA_MIN, BETA_MAX))
258
+ return dict(seed=int(seed), bar_xy=b.round(5).tolist(), bar_yaw=bar_yaw, holder_xy=h.round(5).tolist(),
259
+ holder_yaw=holder_yaw, distractors=dis, yaw_bias=beta, yaw_bias_deg=float(np.degrees(beta)))
260
+
261
+ def apply_instance(self, inst):
262
+ m = self.env.sim.model
263
+ m.body_pos[self._holder_bid] = [inst["holder_xy"][0], inst["holder_xy"][1], envs.TABLE_Z + HOLDER_HALF_H]
264
+ m.body_quat[self._holder_bid] = _q("z", inst["holder_yaw"])
265
+ for name, mass in MASS.items():
266
+ envs.scale_mass(self.env, name, mass)
267
+ self.env.sim.forward()
268
+ self._place(BAR, inst["bar_xy"], inst["bar_yaw"])
269
+ envs.set_friction(self.env, BAR, BAR_MU, priority=3)
270
+ for name, v in inst["distractors"].items():
271
+ self._place(name, v["xy"], v["yaw"])
272
+
273
+ def reset_instance(self, inst, recorder=None):
274
+ self.env.reset()
275
+ self.apply_instance(inst)
276
+ self.env.sim.forward()
277
+ envs.settle(self.env, 10)
278
+ self.sk = YawSkills(self.env, yaw_bias=inst["yaw_bias"], recorder=recorder)
279
+ self.sk.hold(REHOME_STEPS) # turn the wrist to the robot's own yaw 0 (true yaw = beta)
280
+ self.sk.n_steps = 0
281
+ self.sk.events = []
282
+ self.start_pos = {n: envs.obj_pos(self.env, n) for n in FREE_OBJECTS}
283
+ return self.sk
284
+
285
+ # ------------------------------------------------------------ outcome
286
+ def holder_frame(self, xy):
287
+ """xy (world) -> (along, across) in the holder frame, relative to the holder centre"""
288
+ c = self.env.sim.model.body_pos[self._holder_bid][:2].copy()
289
+ a = self.holder_yaw()
290
+ R = np.array([[np.cos(a), np.sin(a)], [-np.sin(a), np.cos(a)]])
291
+ return R @ (np.asarray(xy[:2]) - c)
292
+
293
+ def holder_yaw(self):
294
+ q = self.env.sim.model.body_quat[self._holder_bid]
295
+ return float(2 * np.arctan2(q[3], q[0]))
296
+
297
+ def in_holder(self):
298
+ p = envs.obj_pos(self.env, BAR)
299
+ u, v = self.holder_frame(p)
300
+ return bool(abs(u) < HOLDER_IN[0] and abs(v) < HOLDER_IN[1] and p[2] < RIM_Z
301
+ and envs.obj_upright_cos(self.env, BAR) > 0.95)
302
+
303
+ def outcome(self, inst):
304
+ envs.settle(self.env, 40)
305
+ sk = self.sk
306
+ p = envs.obj_pos(self.env, BAR)
307
+ held = sk.holding_bar()
308
+ success = bool(self.in_holder() and not held)
309
+ picked = sk.bar_zmax > sk.bar_z0 + self.pick_lift_min
310
+ closes = [e for e in sk.events if e["kind"] == "close"]
311
+ last_close = closes[-1] if closes else None
312
+ releases = [e for e in sk.events if e["kind"] == "release" and last_close and e["step"] >= last_close["step"]]
313
+ hy = self.holder_yaw()
314
+ end_mis = wrap_half(sk.bar_yaw() - hy)
315
+ hc = self.env.sim.model.body_pos[self._holder_bid][:2]
316
+ out = dict(success=success, picked=bool(picked), held_at_end=bool(held), bar_end=p.round(4).tolist(),
317
+ bar_end_misalign_deg=round(float(np.degrees(end_mis)), 1), grasp_misalign=None,
318
+ bar_turned_in_grasp=None, release_misalign=None, release_offset=None, touched_at_close=None)
319
+ grasp_txt = ""
320
+ if last_close is not None:
321
+ gm = wrap_half(last_close["true_yaw"] - last_close["bar_ref_yaw"])
322
+ turned = wrap_half(last_close.get("bar_yaw_after", last_close["bar_ref_yaw"]) - last_close["bar_ref_yaw"])
323
+ out["grasp_misalign"] = round(gm, 4)
324
+ out["bar_turned_in_grasp"] = round(turned, 4)
325
+ out["touched_at_close"] = last_close["touching"]
326
+ go = np.array(last_close["eef"][:2]) - np.array(last_close.get("bar_ref", last_close["bar"])[:2])
327
+ a = last_close["bar_ref_yaw"]
328
+ along, across = go @ [np.cos(a), np.sin(a)], go @ [-np.sin(a), np.cos(a)]
329
+ over_bar = bool(abs(along) <= BAR_HALF[0] and abs(across) <= BAR_HALF[1] + 0.02)
330
+ out["grasp_xy_offset"] = go.round(4).tolist()
331
+ out["grasp_over_bar"] = over_bar
332
+ if over_bar:
333
+ grasp_txt = f"When the jaws closed on the blue bar, they were {rot_words(gm)} from square across the bar"
334
+ if np.linalg.norm(go) >= 0.015:
335
+ grasp_txt += f" (the grasp point was {dir_words(*go)} of the bar's centre)"
336
+ else:
337
+ grasp_txt = (f"When the jaws closed, the grasp point was {dir_words(*go)} of the blue bar's centre, i.e. "
338
+ f"not over the bar, and the jaws were {rot_words(gm)} from square across the bar")
339
+ if abs(np.degrees(turned)) >= 2:
340
+ grasp_txt += f", and the closing fingers turned the bar by {abs(np.degrees(turned)):.0f} deg"
341
+ if releases:
342
+ r = releases[-1]
343
+ rm = wrap_half(r["bar_yaw"] - hy)
344
+ out["release_misalign"] = round(rm, 4)
345
+ out["release_offset"] = (np.array(r["bar"][:2]) - hc).round(4).tolist()
346
+ if success:
347
+ out["failure"] = None
348
+ detail = "The blue bar is inside the holder."
349
+ if out["release_misalign"] is not None:
350
+ detail += (f" When the gripper opened, the bar's long axis was {rot_words(out['release_misalign'])} "
351
+ f"from the holder's long axis.")
352
+ elif not picked:
353
+ out["failure"] = "missed_grasp"
354
+ if last_close is None:
355
+ detail = "The gripper never closed; the blue bar was not picked up."
356
+ else:
357
+ detail = f"{grasp_txt}, but the bar was not picked up. It is still on the table."
358
+ elif held:
359
+ out["failure"] = "not_released"
360
+ detail = f"{grasp_txt}. The bar was picked up but it is still in the gripper."
361
+ elif releases:
362
+ out["failure"] = "missed_place"
363
+ if p[2] > RIM_Z - 0.002:
364
+ where = (f"The bar came down across the holder's walls instead of dropping in; it is now lying on top "
365
+ f"of the holder, its long axis {rot_words(end_mis)} from the holder's long axis.")
366
+ else:
367
+ where = (f"The bar did not end up inside the holder (its centre is now "
368
+ f"{dir_words(*(p[:2] - hc))} of the holder's centre).")
369
+ detail = (f"{grasp_txt}. When the gripper opened above the holder, the bar's long axis was "
370
+ f"{rot_words(out['release_misalign'])} from the holder's long axis, and the bar's centre was "
371
+ f"{dir_words(*out['release_offset'])} of the holder's centre. {where}")
372
+ else:
373
+ out["failure"] = "dropped"
374
+ detail = (f"{grasp_txt}. The bar was lifted but slipped out of the fingers before the gripper opened; it is "
375
+ f"now {dir_words(*(p[:2] - hc))} of the holder's centre.")
376
+ out["detail"] = detail
377
+ ind = detail
378
+ for k in sorted(NAMES, key=lambda n: -len(NAMES[n])):
379
+ ind = ind.replace(NAMES[k], DESCR[k])
380
+ ind = re.sub(r"\bbar\b", "stick", ind) # the bare noun would give the direct name away
381
+ out["detail_indirect"] = ind
382
+ return out
383
+
384
+ def feedback(self, inst, out, level="F2", indirect=False):
385
+ if indirect and level == "F2":
386
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
387
+ return super().feedback(inst, out, level)
388
+
389
+ # ------------------------------------------------------------ scripted execution (cross protocol)
390
+ def execute(self, inst, params):
391
+ """Top-down pick square across the bar at its centre, carry, line the bar up with the holder and release it
392
+ just above the holder's rim. params['dyaw'] (rad) is the policy's own yaw correction, added to every
393
+ commanded yaw."""
394
+ sk = self.sk
395
+ dy = float(params.get("dyaw", 0.0))
396
+ b = envs.obj_pos(self.env, BAR) # perfect perception of the current scene
397
+ psi = sk.bar_yaw()
398
+ hc = self.env.sim.model.body_pos[self._holder_bid][:2].copy()
399
+ phi = self.holder_yaw()
400
+ z_grasp = envs.TABLE_Z + SITE_ABOVE_TABLE
401
+ z_rel = RIM_Z + RELEASE_GAP + SITE_ABOVE_TABLE
402
+ sk.set_gripper(False, steps=8)
403
+ sk.move_to([b[0], b[1], Z_CARRY], yaw=wrap_half(psi) + dy)
404
+ sk.move_to([b[0], b[1], z_grasp + 0.06], tol=0.002)
405
+ sk.move_to([b[0], b[1], z_grasp], tol=0.003, max_steps=80)
406
+ sk.set_gripper(True, steps=15)
407
+ sk.move_to([b[0], b[1], Z_CARRY], speed=0.3)
408
+ if not sk.holding_bar(): # missed: a real controller sees the jaws closed on nothing and stops
409
+ return
410
+ sk.move_to([hc[0], hc[1], Z_CARRY], yaw=wrap_half(phi) + dy, tol=0.003)
411
+ sk.move_to([hc[0], hc[1], z_rel], tol=0.003, max_steps=100)
412
+ sk.hold(5)
413
+ sk.set_gripper(False, steps=12)
414
+ sk.move_to([hc[0], hc[1], Z_CARRY], speed=0.3)
415
+
416
+ def default_params(self, inst):
417
+ return dict(dyaw=0.0)
418
+
419
+ def oracle_params(self, inst):
420
+ return dict(dyaw=-float(inst["yaw_bias"]))
421
+
422
+ def adapt_params(self, inst, history):
423
+ """Scripted F2 learner: the reported angle between the bar and the holder when the gripper opened is the
424
+ part of the wrist offset not yet corrected; accumulate it into the correction subtracted from every
425
+ commanded yaw. If the bar was never released, use the jaw angle at the grasp instead."""
426
+ last = history[-1]
427
+ dy = float(last["params"]["dyaw"])
428
+ o = last["outcome"]
429
+ if o.get("release_misalign") is not None:
430
+ dy -= o["release_misalign"]
431
+ elif o.get("grasp_misalign") is not None:
432
+ dy -= o["grasp_misalign"]
433
+ return dict(dyaw=round(dy, 4))
434
+
435
+ blind_sigma = np.deg2rad(4.0)
436
+
437
+ def blind_params(self, inst, attempt, rng):
438
+ """Retry the same plan with a small random perturbation of the commanded yaws; no use of history."""
439
+ return dict(dyaw=round(float(rng.normal(0.0, self.blind_sigma)), 4))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_knock.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-A knock_restore: move the ketchup from the tray into the basket; everything else must stay on the tray.
2
+
3
+ Constructed L2 event: the first time the ketchup is lifted off the tray (grasped and raised 3 cm), one of
4
+ its two neighbours on the tray is "knocked" off the tray and lands upright on the table beside it. Which
5
+ neighbour and to which side of the tray (left / right in the camera image) it falls are hidden per-instance
6
+ variables; only the scene *after* the failure shows which item is missing and where it is. The main task itself still succeeds, so an agent that stops after
7
+ the main task fails; it has to notice the side effect and put the item back (within-episode recovery).
8
+
9
+ Protocols
10
+ within (default, `l2_knock_restore`) one episode; attempt 1 = the main task, every later attempt is one
11
+ corrective round chosen by the policy; the outcome (success + F2 text) is computed after each round.
12
+ cross (`l2_knock_restore_cross`) reset to the same instance between attempts; the knock happens again
13
+ on every attempt, so a learner must anticipate it. Validated strategy: restore the reported item
14
+ right after the main task. The rule also allows prevention (the knock only hits a neighbour that is
15
+ still within 12 cm of the ketchup's start spot), but picking a neighbour up in place is mostly blocked
16
+ by the tray's end wall (Panda hand), so prevention is not a validated strategy (see the task card).
17
+ """
18
+ import numpy as np
19
+
20
+ from .. import envs
21
+ from ..bddl import write_bddl
22
+ from ..skills import Skills
23
+ from ..task_base import LFFTask, register_task
24
+
25
+ TARGET = "ketchup_1"
26
+ NEIGHBOR_POOL = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
27
+ TRAY, BASKET = "wooden_tray_1", "basket_1"
28
+ PARK_XY = {"cream_cheese_1": (0.0, 1.2), "butter_1": (0.2, 1.2), "chocolate_pudding_1": (-0.2, 1.2)}
29
+
30
+ # wooden_tray collision geometry in its body frame (from the LIBERO MJCF; long axis = body x)
31
+ TRAY_IN_X = (-0.128, 0.143)
32
+ TRAY_IN_Y = (-0.081, 0.072)
33
+ TRAY_OUT_X = (-0.142, 0.156)
34
+ TRAY_OUT_Y = (-0.088, 0.080)
35
+ TRAY_CX, TRAY_CY = 0.0075, -0.0045 # centre of the inner floor
36
+ TRAY_FLOOR = 0.0072 # floor top above the tray's lowest point
37
+ BASKET_IN = 0.060 # half size of the basket's inner floor (square, centred on the body origin)
38
+ BASKET_RIM = 0.150 # rim height above the basket's lowest point
39
+ BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
40
+
41
+ NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
42
+ "chocolate_pudding_1": "chocolate pudding"}
43
+ DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
44
+ "chocolate_pudding_1": "brown box"}
45
+ SIDES = ("left", "right") # side of the tray in the agentview image: left = world -y, right = world +y
46
+
47
+
48
+ def _qz(a):
49
+ return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
50
+
51
+
52
+ def _wrap_half(a):
53
+ """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
54
+ return (a + np.pi / 2) % np.pi - np.pi / 2
55
+
56
+
57
+ class KnockSkills(Skills):
58
+ """Skills with a hook called after every control step (used for the failure injection)."""
59
+
60
+ def __init__(self, env, bias=None, recorder=None, hook=None):
61
+ super().__init__(env, bias=bias, recorder=recorder)
62
+ self.hook = hook
63
+
64
+ def _act(self, dpos, drot, grip):
65
+ super()._act(dpos, drot, grip)
66
+ if self.hook is not None:
67
+ self.hook()
68
+
69
+
70
+ @register_task
71
+ class KnockRestore(LFFTask):
72
+ name = "l2_knock_restore"
73
+ level = "L2"
74
+ category = "state_restoration"
75
+ capabilities = ("Perceive", "Plan")
76
+ protocol = "within"
77
+ instruction = "Move the ketchup from the tray into the basket. Everything else must stay on the tray."
78
+ instruction_indirect = ("Move the red bottle from the wooden tray into the wicker basket. "
79
+ "Everything else must stay on the tray.")
80
+ knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
81
+ knock_radius = 0.12 # only a victim still within this distance of the ketchup's start spot is knocked
82
+
83
+ def __init__(self, cam_res=None):
84
+ super().__init__(cam_res)
85
+ # upright orientations (wxyz), fixed here so the task does not depend on LIBERO's placement convention:
86
+ # the ketchup mesh is modelled lying down; tray / basket / boxes are upright in their mesh frame
87
+ # (identity => tray long axis along world x, as the TRAY_* constants assume).
88
+ self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
89
+ self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
90
+ self._inj = None
91
+ self.start = {}
92
+
93
+ # ------------------------------------------------------------ scene
94
+ def make_bddl(self):
95
+ names = [TARGET, *NEIGHBOR_POOL, TRAY, BASKET]
96
+ objs = []
97
+ for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
98
+ x0 = -0.30 + 0.13 * (i % 3)
99
+ y0 = -0.25 + 0.25 * (i // 3)
100
+ objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
101
+ return write_bddl(self.name, self.instruction, objs)
102
+
103
+ def sample_instance(self, seed):
104
+ rng = np.random.default_rng(seed)
105
+ nb = [str(x) for x in rng.choice(NEIGHBOR_POOL, size=2, replace=False)] # [robot side, far side]
106
+ victim = int(rng.integers(2))
107
+ side = str(rng.choice(SIDES))
108
+ return dict(seed=int(seed),
109
+ tray_xy=[float(rng.uniform(-0.07, 0.01)), float(rng.uniform(-0.11, -0.08))],
110
+ tray_yaw=float(rng.uniform(-0.10, 0.10)),
111
+ basket_xy=[float(rng.uniform(-0.08, 0.02)), float(rng.uniform(0.24, 0.26))],
112
+ target_dx=float(rng.uniform(-0.01, 0.01)),
113
+ target_yaw=float(np.pi / 2 + rng.uniform(-0.2, 0.2)),
114
+ neighbors=nb,
115
+ nb_gap=[float(rng.uniform(0.066, 0.078)) for _ in range(2)],
116
+ nb_dy=[float(rng.uniform(-0.012, 0.012)) for _ in range(2)],
117
+ nb_yaw=[float(np.pi / 2 + rng.uniform(-0.15, 0.15)) for _ in range(2)],
118
+ # hidden variables of the injected failure
119
+ victim=nb[victim], side=side,
120
+ land_gap=float(rng.uniform(0.015, 0.035 if side == "right" else 0.04)), # wall -> object
121
+ land_off=float(rng.uniform(-0.025, 0.025)), # along the wall, from the victim's spot
122
+ land_dyaw=float(rng.uniform(-0.35, 0.35)))
123
+
124
+ def _tray_frame(self):
125
+ p = envs.obj_pos(self.env, TRAY)
126
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, TRAY)].reshape(3, 3)
127
+ return p, R
128
+
129
+ def tray_yaw(self):
130
+ _, R = self._tray_frame()
131
+ return float(np.arctan2(R[1, 0], R[0, 0]))
132
+
133
+ def tray_to_world(self, lx, ly):
134
+ p, R = self._tray_frame()
135
+ return p[:2] + R[:2, :2] @ np.array([lx, ly])
136
+
137
+ def world_to_tray(self, xy):
138
+ p, R = self._tray_frame()
139
+ return R[:2, :2].T @ (np.asarray(xy[:2]) - p[:2])
140
+
141
+ def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
142
+ """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z."""
143
+ q = envs._quat_mul(_qz(yaw), self.q_up[name])
144
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
145
+ self.env.sim.forward()
146
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
147
+ qa, _ = envs.free_joint_addr(self.env, name)
148
+ self.env.sim.data.qpos[qa + 2] -= dz
149
+ self.env.sim.forward()
150
+
151
+ def apply_instance(self, inst):
152
+ env = self.env
153
+ envs.scale_mass(env, TRAY, 2.0) # heavy enough not to be dragged around by the gripper
154
+ envs.scale_mass(env, BASKET, 2.0)
155
+ for n in NEIGHBOR_POOL:
156
+ if n not in inst["neighbors"]:
157
+ self.place(n, PARK_XY[n], 0.0, surface_z=0.0) # unused neighbour: on the floor, out of view
158
+ self.place(TRAY, inst["tray_xy"], inst["tray_yaw"])
159
+ self.place(BASKET, inst["basket_xy"], 0.0)
160
+ floor = envs.TABLE_Z + TRAY_FLOOR
161
+ ty = inst["tray_yaw"]
162
+ cx = TRAY_CX + inst["target_dx"]
163
+ self.place(TARGET, self.tray_to_world(cx, TRAY_CY), ty + inst["target_yaw"], floor)
164
+ for i, n in enumerate(inst["neighbors"]): # in a row along the tray: [robot side, ketchup, far side]
165
+ lx = cx + (-1 if i == 0 else 1) * inst["nb_gap"][i]
166
+ self.place(n, self.tray_to_world(lx, TRAY_CY + inst["nb_dy"][i]), ty + inst["nb_yaw"][i], floor)
167
+ env.sim.forward()
168
+
169
+ def reset_instance(self, inst, recorder=None):
170
+ self.env.reset()
171
+ self.apply_instance(inst)
172
+ self.env.sim.forward()
173
+ envs.settle(self.env, 10)
174
+ self.start = {n: self.footprint(n) for n in [TARGET] + inst["neighbors"]}
175
+ self._inj = dict(inst=inst, done=False, knocked=False, step=None)
176
+ self.sk = KnockSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, hook=self._knock_hook)
177
+ return self.sk
178
+
179
+ # ------------------------------------------------------------ measurements
180
+ def footprint(self, name):
181
+ """Measured pose summary of an object: AABB centre, yaw of the long horizontal axis, half sizes, z range.
182
+ Scripted policies use it as a stand-in for perception."""
183
+ m, d = self.env.sim.model, self.env.sim.data
184
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
185
+ best = None
186
+ for g in envs.obj_geom_ids(self.env, name):
187
+ R = d.geom_xmat[g].reshape(3, 3)
188
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
189
+ e = np.abs(R) @ m.geom_aabb[g, 3:]
190
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
191
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
192
+ if best is None or vol > best[0]:
193
+ best = (vol, R, m.geom_aabb[g, 3:])
194
+ _, R, half = best
195
+ horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
196
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
197
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
198
+ half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
199
+
200
+ def _corners_tray(self, name):
201
+ """All collision-box corners of `name` in tray coordinates."""
202
+ m, d = self.env.sim.model, self.env.sim.data
203
+ pts = []
204
+ for g in envs.obj_geom_ids(self.env, name):
205
+ Rg = d.geom_xmat[g].reshape(3, 3)
206
+ c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
207
+ h = m.geom_aabb[g, 3:]
208
+ for sx in (-1, 1):
209
+ for sy in (-1, 1):
210
+ for sz in (-1, 1):
211
+ pts.append(self.world_to_tray(c + Rg @ (h * np.array([sx, sy, sz]))))
212
+ return np.array(pts)
213
+
214
+ # ------------------------------------------------------------ failure injection
215
+ def _knock_hook(self):
216
+ st = self._inj
217
+ if st is None or st["done"] or self.sk is None:
218
+ return
219
+ if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
220
+ return
221
+ if not self.sk.holding(TARGET):
222
+ return
223
+ st["done"] = True
224
+ inst = st["inst"]
225
+ vxy = np.array(self.footprint(inst["victim"])["center"][:2])
226
+ if np.linalg.norm(vxy - np.array(self.start[TARGET]["center"][:2])) > self.knock_radius:
227
+ return # the victim was moved out of the way beforehand: nothing happens
228
+ self.knock(inst)
229
+ st["knocked"] = True
230
+ st["step"] = self.sk.n_steps
231
+
232
+ def knock(self, inst):
233
+ """Teleport the victim off the tray onto the table beside the long wall on `side`: upright, long axis
234
+ roughly perpendicular to the wall (so a gripper closing along the wall can pick it up), nearest point
235
+ `land_gap` from the wall's outer face, `land_off` along the wall from where it stood.
236
+ (The robot-side end of the tray was tried too: the end wall hides a flat box there from agentview.)"""
237
+ v, side = inst["victim"], inst["side"]
238
+ loc = self.world_to_tray(self.footprint(v)["center"])
239
+ axis, sgn = 1, (1 if side == "right" else -1)
240
+ wall = TRAY_OUT_Y[1] if sgn > 0 else TRAY_OUT_Y[0]
241
+ self.place(v, self.tray_to_world(loc[0] + inst["land_off"], wall + sgn * 0.08),
242
+ self.tray_yaw() + np.pi / 2 + inst["land_dyaw"])
243
+ pts = self._corners_tray(v)
244
+ near = pts[:, axis].min() if sgn > 0 else pts[:, axis].max()
245
+ shift = (wall + sgn * inst["land_gap"]) - near
246
+ _, R = self._tray_frame()
247
+ qa, _ = envs.free_joint_addr(self.env, v)
248
+ self.env.sim.data.qpos[qa:qa + 2] += R[:2, axis] * shift
249
+ self.env.sim.forward()
250
+
251
+ # ------------------------------------------------------------ outcome
252
+ def where(self, name):
253
+ """Classify where an object is: 'tray', 'basket', 'gripper', 'table' or 'other'."""
254
+ f = self.footprint(name)
255
+ c = np.array(f["center"])
256
+ lt = self.world_to_tray(c)
257
+ if self.sk is not None and self.sk.holding(name) and f["zmin"] > envs.TABLE_Z + 0.02:
258
+ return "gripper", f
259
+ if (TRAY_IN_X[0] - 0.005 <= lt[0] <= TRAY_IN_X[1] + 0.005 and TRAY_IN_Y[0] - 0.005 <= lt[1] <= TRAY_IN_Y[1] + 0.005
260
+ and f["zmin"] > envs.obj_min_z(self.env, TRAY) + 0.002):
261
+ return "tray", f
262
+ bp = envs.obj_pos(self.env, BASKET)
263
+ if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM:
264
+ return "basket", f
265
+ if f["zmin"] < envs.TABLE_Z + 0.01:
266
+ return "table", f
267
+ return "other", f
268
+
269
+ def rel_to_tray(self, c):
270
+ """Where a point on the table is relative to the tray, in robot-centric words (never image left/right).
271
+ Distances are from the tray's outer edge to the object's centre."""
272
+ lt = self.world_to_tray(c)
273
+ dy = lt[1] - TRAY_OUT_Y[1] if lt[1] > TRAY_OUT_Y[1] else (lt[1] - TRAY_OUT_Y[0] if lt[1] < TRAY_OUT_Y[0] else 0.0)
274
+ dx = lt[0] - TRAY_OUT_X[1] if lt[0] > TRAY_OUT_X[1] else (lt[0] - TRAY_OUT_X[0] if lt[0] < TRAY_OUT_X[0] else 0.0)
275
+ # robot-centric words (tray yaw is within +-0.1 rad, so tray axes ~ world axes): +y = robot's left,
276
+ # +x = forward (away from the robot)
277
+ parts = []
278
+ if dy:
279
+ parts.append(f"{100 * abs(dy):.0f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'} of the tray")
280
+ if dx:
281
+ parts.append(f"{100 * abs(dx):.0f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'} "
282
+ f"of the tray")
283
+ return " and ".join(parts) if parts else "right next to the tray"
284
+
285
+ def _describe(self, inst, loc, names):
286
+ t_loc = loc[TARGET][0]
287
+ tn = names[TARGET]
288
+ msgs = []
289
+ if t_loc != "basket":
290
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
291
+ "tray": f"The {tn} is still on the tray, not in the basket.",
292
+ "table": f"The {tn} is on the table ({self.rel_to_tray(loc[TARGET][1]['center'])}), "
293
+ "not in the basket."}.get(t_loc, f"The {tn} is not in the basket."))
294
+ for n in inst["neighbors"]:
295
+ l, f = loc[n]
296
+ if l == "tray":
297
+ continue
298
+ msgs.append({"table": f"The {names[n]} is no longer on the tray: it is on the table "
299
+ f"{self.rel_to_tray(f['center'])}.",
300
+ "basket": f"The {names[n]} is no longer on the tray: it is in the basket.",
301
+ "gripper": f"The {names[n]} is no longer on the tray: it is still in the gripper."}
302
+ .get(l, f"The {names[n]} is no longer on the tray."))
303
+ if not msgs:
304
+ msgs.append(f"The {tn} is in the basket and everything else is on the tray.")
305
+ return " ".join(msgs)
306
+
307
+ def outcome(self, inst):
308
+ envs.settle(self.env, 30)
309
+ loc = {n: self.where(n) for n in [TARGET] + inst["neighbors"]}
310
+ off = [n for n in inst["neighbors"] if loc[n][0] != "tray"]
311
+ success = bool(loc[TARGET][0] == "basket" and not off)
312
+ return dict(success=success,
313
+ target_loc=loc[TARGET][0],
314
+ locations={n: l for n, (l, _) in loc.items()},
315
+ off_tray=off,
316
+ footprints={n: f for n, (_, f) in loc.items()},
317
+ knocked=bool(self._inj and self._inj["knocked"]),
318
+ detail=self._describe(inst, loc, NAMES),
319
+ detail_indirect=self._describe(inst, loc, DESCR))
320
+
321
+ def feedback(self, inst, out, level="F2", indirect=False):
322
+ """F0: nothing, F1: success flag, F2: which item is where. `indirect` uses descriptive names."""
323
+ if indirect and level == "F2":
324
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
325
+ return super().feedback(inst, out, level)
326
+
327
+ # ------------------------------------------------------------ scripted motions
328
+ def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.012, fp=None,
329
+ travel_z=1.15):
330
+ """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
331
+ object bottom `clearance` above `support_z` at dest_xy. Moves between places at `travel_z` (above the
332
+ basket rim) so the arm does not sweep through the scene."""
333
+ sk = self.sk
334
+ f = fp or self.footprint(name)
335
+ c = np.array(f["center"])
336
+ h = f["zmax"] - f["zmin"]
337
+ gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
338
+ if name == TARGET:
339
+ zg = f["zmax"] - 0.035
340
+ else:
341
+ zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # fingertips reach ~1.3 cm below the grip site
342
+ sk.set_gripper(False, steps=6)
343
+ p = sk.eef_pos()
344
+ if p[2] < travel_z - 0.02:
345
+ sk.move_to([p[0], p[1], travel_z])
346
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
347
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
348
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
349
+ sk.set_gripper(True, steps=12)
350
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
351
+ gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
352
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
353
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.004, speed=0.25,
354
+ max_steps=120)
355
+ sk.set_gripper(False, steps=10)
356
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
357
+
358
+ def main_task(self, fp=None):
359
+ """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
360
+ b = envs.obj_pos(self.env, BASKET)
361
+ floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
362
+ self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
363
+
364
+ def restore_spot(self, name, inst):
365
+ """A free spot on the tray for `name`: the ketchup's start spot or `name`'s own start spot, whichever
366
+ is further from everything else currently on the tray."""
367
+ others = [n for n in [TARGET] + inst["neighbors"] if n != name and self.where(n)[0] == "tray"]
368
+ best, best_d = None, -1.0
369
+ for cand in (TARGET, name):
370
+ xy = np.array(self.start[cand]["center"][:2])
371
+ dmin = min([np.linalg.norm(xy - np.array(self.footprint(o)["center"][:2])) for o in others] + [1.0])
372
+ if dmin > best_d + 0.01:
373
+ best, best_d = xy, dmin
374
+ return best
375
+
376
+ def restore(self, name, inst):
377
+ """Put `name` back onto the tray (long axis across the tray, fingers closing along the tray)."""
378
+ xy = self.restore_spot(name, inst)
379
+ self.pick_place(name, xy, envs.TABLE_Z + TRAY_FLOOR, dest_yaw=self.tray_yaw() + np.pi / 2, carry_z=1.08,
380
+ clearance=0.013)
381
+
382
+ def do(self, actions, inst):
383
+ for act in actions:
384
+ if act[0] == "ketchup_to_basket":
385
+ self.main_task(fp=act[1] if len(act) > 1 else None)
386
+ elif act[0] == "restore":
387
+ self.restore(act[1], inst)
388
+ else:
389
+ raise ValueError(act)
390
+
391
+ # ------------------------------------------------------------ scripted reference policies
392
+ def _plan(self, kind, inst, a, history, rng):
393
+ """Actions of one attempt. JSON-friendly lists: ["ketchup_to_basket"] / ["restore", name]."""
394
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind")):
395
+ return [["ketchup_to_basket"]]
396
+ if kind == "oracle": # knows the victim: restores it right after the main task, without feedback
397
+ return [["ketchup_to_basket"], ["restore", inst["victim"]]]
398
+ if kind == "adaptive": # F2 says what is wrong; perception (measured pose) says where it is
399
+ last = history[-1]["outcome"]
400
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
401
+ return acts + [["restore", n] for n in last["off_tray"]]
402
+ if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
403
+ fp = self.footprint(TARGET)
404
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
405
+ return [["ketchup_to_basket", fp]]
406
+ raise ValueError(kind)
407
+
408
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
409
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.
410
+ After every attempt the outcome (success + F2 detail) is measured; stops at success
411
+ (oracle / naive stop after attempt 1)."""
412
+ k = k or self.max_attempts
413
+ rng = np.random.default_rng(seed)
414
+ history = []
415
+ self.reset_instance(inst)
416
+ for a in range(k):
417
+ actions = self._plan(kind, inst, a, history, rng)
418
+ self.do(actions, inst)
419
+ out = self.outcome(inst)
420
+ params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
421
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
422
+ if on_attempt:
423
+ on_attempt(a, params, out)
424
+ if out["success"] or kind in ("oracle", "naive"):
425
+ break
426
+ return history
427
+
428
+
429
+ @register_task
430
+ class KnockRestoreCross(KnockRestore):
431
+ """Cross-attempt variant: reset to the same instance before every attempt; the knock happens again each
432
+ time. Learned behaviour: anticipate it (restore the reported item right after the main task)."""
433
+ name = "l2_knock_restore_cross"
434
+ protocol = "cross"
435
+
436
+ def _plan(self, kind, inst, a, history, rng):
437
+ if kind == "adaptive" and a > 0: # remembers which item(s) fell last time; finds them by looking
438
+ fallen = sorted({n for h in history for n in h["outcome"]["off_tray"]})
439
+ return [["ketchup_to_basket"]] + [["restore", n] for n in fallen]
440
+ return super()._plan(kind, inst, a, history, rng)
441
+
442
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
443
+ k = k or self.max_attempts
444
+ rng = np.random.default_rng(seed)
445
+ history = []
446
+ for a in range(k):
447
+ self.reset_instance(inst)
448
+ actions = self._plan(kind, inst, a, history, rng)
449
+ self.do(actions, inst)
450
+ out = self.outcome(inst)
451
+ params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
452
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
453
+ if on_attempt:
454
+ on_attempt(a, params, out)
455
+ if out["success"] or kind in ("oracle", "naive"):
456
+ break
457
+ return history
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_sonnet/lff/source_closure/lffbench/tasks/l2_restore_layout.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was.
2
+
3
+ Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare
4
+ table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the
5
+ robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the
6
+ first frame.
7
+
8
+ Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the
9
+ neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the
10
+ ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is
11
+ real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still
12
+ succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim
13
+ back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in
14
+ its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was).
15
+
16
+ Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
17
+ round chosen by the policy; the outcome (success + F2 text) is computed after each round.
18
+
19
+ Scripted references
20
+ oracle knows the victim: right after the main task it puts the victim back at its saved start pose.
21
+ naive main task, then done.
22
+ adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are
23
+ out of place (Retrieve their saved poses) and puts them back (Utilize).
24
+ blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the
25
+ basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind.
26
+ nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows
27
+ which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw).
28
+ """
29
+ import numpy as np
30
+
31
+ from .. import envs
32
+ from ..bddl import write_bddl
33
+ from ..task_base import LFFTask, register_task
34
+
35
+ TARGET = "ketchup_1"
36
+ BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
37
+ BASKET = "basket_1"
38
+ ITEMS = (TARGET,) + BOXES
39
+
40
+ # LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer
41
+ BASKET_IN = 0.060 # half size of the inner floor
42
+ BASKET_RIM = 0.150 # rim height above the basket's lowest point
43
+ BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
44
+ BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout)
45
+
46
+ POS_TOL = 0.03 # success: box centre within 3 cm of its start
47
+ YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180)
48
+ STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start
49
+
50
+ REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres
51
+ KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest
52
+ MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base
53
+ BASE_X = -0.66
54
+ R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm)
55
+ GAP = 0.03 # free space between footprints (finger room)
56
+ SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table
57
+ SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached
58
+
59
+ NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
60
+ "chocolate_pudding_1": "chocolate pudding", BASKET: "basket"}
61
+ DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
62
+ "chocolate_pudding_1": "brown box", BASKET: "wicker basket"}
63
+
64
+
65
+ def _qz(a):
66
+ return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
67
+
68
+
69
+ def _wrap_half(a):
70
+ """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
71
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
72
+
73
+
74
+ def _seg_dist(p, a, b):
75
+ """distance from point p to segment a-b (2D)"""
76
+ p, a, b = (np.asarray(v, float) for v in (p, a, b))
77
+ ab = b - a
78
+ t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0)
79
+ return float(np.linalg.norm(p - (a + t * ab)))
80
+
81
+
82
+ def _in_rect(xy, r):
83
+ return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3]
84
+
85
+
86
+ def _reach_ok(xy):
87
+ return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH
88
+
89
+
90
+ @register_task
91
+ class RestoreLayout(LFFTask):
92
+ name = "l2_restore_layout"
93
+ level = "L2"
94
+ category = "state_restoration"
95
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
96
+ protocol = "within"
97
+ max_attempts = 5
98
+ instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it "
99
+ "is now, in the same position and orientation.")
100
+ instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay "
101
+ "exactly where it is now, in the same position and orientation.")
102
+ knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
103
+
104
+ def __init__(self, cam_res=None):
105
+ super().__init__(cam_res)
106
+ # upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down;
107
+ # basket and boxes are upright in their mesh frame
108
+ self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
109
+ self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
110
+ self._inj = None
111
+ self.start = {}
112
+ self._home = None
113
+ # per-control-step monitor on env.step: also sees attempts driven by the agent harness
114
+ orig_step = self.env.step
115
+
116
+ def step(action):
117
+ ret = orig_step(action)
118
+ if self._inj is not None:
119
+ self._knock_step()
120
+ return ret
121
+
122
+ self.env.step = step
123
+
124
+ # ------------------------------------------------------------ scene
125
+ def make_bddl(self):
126
+ names = [*ITEMS, BASKET]
127
+ objs = []
128
+ for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
129
+ x0 = -0.30 + 0.13 * (i % 3)
130
+ y0 = -0.25 + 0.25 * (i // 3)
131
+ objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
132
+ return write_bddl(self.name, self.instruction, objs)
133
+
134
+ def sample_instance(self, seed):
135
+ rng = np.random.default_rng(seed)
136
+ for _ in range(5000):
137
+ basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)])
138
+ k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)])
139
+ victim = str(rng.choice(BOXES))
140
+ others = [b for b in BOXES if b != victim]
141
+ a_v = rng.uniform(0, 2 * np.pi)
142
+ r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02)
143
+ pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])}
144
+ ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim])
145
+ for o in others:
146
+ if not ok:
147
+ break
148
+ for _ in range(200):
149
+ p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])])
150
+ if not _reach_ok(p):
151
+ continue
152
+ if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP:
153
+ continue
154
+ if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET):
155
+ continue
156
+ pos[o] = p
157
+ break
158
+ else:
159
+ ok = False
160
+ if not ok:
161
+ continue
162
+ if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS):
163
+ continue
164
+ # the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign)
165
+ ang = a_v + rng.uniform(-np.radians(35), np.radians(35))
166
+ dist = rng.uniform(0.09, 0.14)
167
+ u = np.array([np.cos(ang), np.sin(ang)])
168
+ end = pos[victim] + dist * u
169
+ if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)):
170
+ continue
171
+ if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03:
172
+ continue
173
+ # the path and the resting spot keep clear of the other boxes (finger room around the victim too)
174
+ if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others):
175
+ continue
176
+ if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others):
177
+ continue
178
+ if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP:
179
+ continue
180
+ turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80)))
181
+ return dict(seed=int(seed),
182
+ basket_xy=basket.round(4).tolist(),
183
+ xy={n: pos[n].round(4).tolist() for n in ITEMS},
184
+ yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES},
185
+ TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))},
186
+ # hidden variables of the injected failure
187
+ victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn,
188
+ knock_end=end.round(4).tolist())
189
+ raise RuntimeError("could not sample a layout")
190
+
191
+ def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
192
+ """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only)."""
193
+ q = envs._quat_mul(_qz(yaw), self.q_up[name])
194
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
195
+ self.env.sim.forward()
196
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
197
+ qa, _ = envs.free_joint_addr(self.env, name)
198
+ self.env.sim.data.qpos[qa + 2] -= dz
199
+ self.env.sim.forward()
200
+
201
+ def apply_instance(self, inst):
202
+ envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock)
203
+ self.place(BASKET, inst["basket_xy"], 0.0)
204
+ for n in ITEMS:
205
+ self.place(n, inst["xy"][n], inst["yaw"][n])
206
+ self.env.sim.forward()
207
+
208
+ def reset_instance(self, inst, recorder=None):
209
+ self._inj = None
210
+ sk = super().reset_instance(inst, recorder)
211
+ self.start = {n: self.footprint(n) for n in ITEMS}
212
+ self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0)
213
+ self._home = sk.eef_pos()
214
+ return sk
215
+
216
+ # ------------------------------------------------------------ measurements
217
+ def footprint(self, name):
218
+ """Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range.
219
+ Scripted policies use it as a stand-in for perception."""
220
+ m, d = self.env.sim.model, self.env.sim.data
221
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
222
+ best = None
223
+ for g in envs.obj_geom_ids(self.env, name):
224
+ R = d.geom_xmat[g].reshape(3, 3)
225
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
226
+ e = np.abs(R) @ m.geom_aabb[g, 3:]
227
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
228
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
229
+ if best is None or vol > best[0]:
230
+ best = (vol, R, m.geom_aabb[g, 3:])
231
+ _, R, half = best
232
+ horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
233
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
234
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
235
+ half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
236
+
237
+ def body_yaw(self, name):
238
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
239
+ return float(np.arctan2(R[1, 0], R[0, 0]))
240
+
241
+ # ------------------------------------------------------------ failure injection (physical knock)
242
+ def _knock_step(self):
243
+ st = self._inj
244
+ if st["done"]:
245
+ if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps)
246
+ self._spin(st)
247
+ return
248
+ if self.sk is None:
249
+ return
250
+ if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
251
+ return
252
+ if not self.sk.holding(TARGET):
253
+ return
254
+ st["done"] = True
255
+ inst = st["inst"]
256
+ v = inst["victim"]
257
+ if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL:
258
+ return # the victim was moved beforehand: nothing happens
259
+ qa, da = envs.free_joint_addr(self.env, v)
260
+ v0 = np.sqrt(inst["knock_dist"] / SLIDE_K)
261
+ dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])])
262
+ d = self.env.sim.data
263
+ d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0]
264
+ st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"],
265
+ spin_steps=6)
266
+ self._spin(st)
267
+
268
+ def _spin(self, st):
269
+ v = st["inst"]["victim"]
270
+ _, da = envs.free_joint_addr(self.env, v)
271
+ turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0
272
+ rest = st["spin_left"] - turned
273
+ st["spin_steps"] -= 1
274
+ if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]):
275
+ st["spin_steps"] = 0
276
+ return
277
+ # measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short
278
+ w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W))
279
+ self.env.sim.data.qvel[da + 5] = np.sign(rest) * w
280
+
281
+ # ------------------------------------------------------------ outcome
282
+ def where_target(self):
283
+ """'basket', 'gripper', 'table' or 'other' for the ketchup."""
284
+ f = self.footprint(TARGET)
285
+ c = np.array(f["center"])
286
+ if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02:
287
+ return "gripper", f
288
+ bp = envs.obj_pos(self.env, BASKET)
289
+ 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:
290
+ return "basket", f
291
+ if f["zmin"] < envs.TABLE_Z + 0.01:
292
+ return "table", f
293
+ return "other", f
294
+
295
+ def box_state(self, name):
296
+ """Pose error of a box w.r.t. its start pose and where it is."""
297
+ f = self.footprint(name)
298
+ s = self.start[name]
299
+ c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2])
300
+ dpos = float(np.linalg.norm(c - c0))
301
+ dyaw = _wrap_half(f["yaw"] - s["yaw"])
302
+ held = bool(self.sk is not None and self.sk.holding(name))
303
+ upright = envs.obj_upright_cos(self.env, name) > 0.9
304
+ on_table = f["zmin"] < envs.TABLE_Z + 0.01
305
+ bp = envs.obj_pos(self.env, BASKET)
306
+ loc = ("gripper" if held else
307
+ "basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else
308
+ "table" if on_table and upright else
309
+ "table_tipped" if on_table else "other")
310
+ ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL)
311
+ return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"],
312
+ offset=(c - c0).tolist())
313
+
314
+ @staticmethod
315
+ def _offset_words(off, dyaw):
316
+ """robot-centric words for a displacement (current - start) and turn (for the offset tier only)"""
317
+ parts = []
318
+ if abs(off[0]) >= 0.005:
319
+ parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}")
320
+ if abs(off[1]) >= 0.005:
321
+ parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}")
322
+ s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot"
323
+ if abs(dyaw) >= np.radians(3):
324
+ s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)"
325
+ return s
326
+
327
+ def _describe(self, tloc, boxes, names, offset=False):
328
+ tn = names[TARGET]
329
+ msgs = []
330
+ if tloc != "basket":
331
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
332
+ "table": f"The {tn} is on the table, not in the basket."}
333
+ .get(tloc, f"The {tn} is not in the basket."))
334
+ for n in BOXES:
335
+ b = boxes[n]
336
+ if b["ok"]:
337
+ continue
338
+ if b["loc"] == "gripper":
339
+ msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.")
340
+ continue
341
+ if b["loc"] == "basket":
342
+ msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.")
343
+ continue
344
+ if b["loc"] == "table_tipped":
345
+ msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.")
346
+ continue
347
+ if b["loc"] != "table":
348
+ msgs.append(f"The {names[n]} is not where it was at the start.")
349
+ continue
350
+ what = []
351
+ if b["dpos"] > POS_TOL:
352
+ what.append("position")
353
+ if abs(b["dyaw"]) > YAW_TOL:
354
+ what.append("orientation")
355
+ m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)."
356
+ if offset:
357
+ m += f" It is {self._offset_words(b['offset'], b['dyaw'])}."
358
+ msgs.append(m)
359
+ if not msgs:
360
+ msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.")
361
+ return " ".join(msgs)
362
+
363
+ def outcome(self, inst):
364
+ envs.settle(self.env, 30)
365
+ tloc, tf = self.where_target()
366
+ boxes = {n: self.box_state(n) for n in BOXES}
367
+ moved = [n for n in BOXES if not boxes[n]["ok"]]
368
+ success = bool(tloc == "basket" and not moved)
369
+ return dict(success=success, target_loc=tloc, moved=moved,
370
+ boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4),
371
+ dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()},
372
+ knocked=bool(self._inj and self._inj["knocked"]),
373
+ detail=self._describe(tloc, boxes, NAMES),
374
+ detail_indirect=self._describe(tloc, boxes, DESCR),
375
+ detail_offset=self._describe(tloc, boxes, NAMES, offset=True))
376
+
377
+ def feedback(self, inst, out, level="F2", indirect=False, offset=False):
378
+ """F0: nothing, F1: success flag, F2: which item is out of place (never where it was).
379
+ offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric
380
+ words -- this externalises the memory and is not the default."""
381
+ if level == "F2":
382
+ key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
383
+ out = dict(out, detail=out.get(key, out["detail"]))
384
+ return super().feedback(inst, out, level)
385
+
386
+ # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only)
387
+ def go_home(self):
388
+ """End of an attempt: lift the arm out of the camera's way."""
389
+ sk = self.sk
390
+ p = sk.eef_pos()
391
+ sk.move_to([p[0], p[1], max(p[2], self._home[2])])
392
+ sk.move_to(self._home)
393
+
394
+ def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None,
395
+ travel_z=1.15):
396
+ """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
397
+ object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis."""
398
+ sk = self.sk
399
+ f = fp or self.footprint(name)
400
+ c = np.array(f["center"])
401
+ h = f["zmax"] - f["zmin"]
402
+ gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
403
+ if name == TARGET:
404
+ zg = f["zmax"] - 0.035
405
+ else:
406
+ zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site
407
+ sk.set_gripper(False, steps=6)
408
+ p = sk.eef_pos()
409
+ if p[2] < travel_z - 0.02:
410
+ sk.move_to([p[0], p[1], travel_z])
411
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
412
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
413
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
414
+ sk.set_gripper(True, steps=12)
415
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
416
+ gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
417
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
418
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2,
419
+ max_steps=150)
420
+ sk.hold(4)
421
+ sk.set_gripper(False, steps=10)
422
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
423
+
424
+ def main_task(self, fp=None):
425
+ """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
426
+ b = envs.obj_pos(self.env, BASKET)
427
+ floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
428
+ self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
429
+
430
+ def restore(self, name, pose):
431
+ """Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw)."""
432
+ self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05,
433
+ clearance=0.004)
434
+
435
+ def do(self, actions, inst):
436
+ for act in actions:
437
+ if act[0] == "ketchup_to_basket":
438
+ self.main_task(fp=act[1] if len(act) > 1 else None)
439
+ elif act[0] == "restore": # ["restore", name, pose]
440
+ self.restore(act[1], act[2])
441
+ else:
442
+ raise ValueError(act)
443
+
444
+ # ------------------------------------------------------------ scripted reference policies
445
+ def _guess_pose(self, name, rng):
446
+ """nomem control: a random free spot within 15 cm of where the box is now, random yaw."""
447
+ cur = np.array(self.footprint(name)["center"][:2])
448
+ others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name]
449
+ for _ in range(200):
450
+ r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi)
451
+ p = cur + r * np.array([np.cos(a), np.sin(a)])
452
+ if _in_rect(p, KNOCK_REGION) and _reach_ok(p) and all(np.linalg.norm(p - o) > 2 * R_BOX + 0.01 for o in others):
453
+ return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
454
+ return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
455
+
456
+ def _plan(self, kind, inst, a, history, rng, memory):
457
+ """Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose]."""
458
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
459
+ return [["ketchup_to_basket"]]
460
+ if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory)
461
+ return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]]
462
+ last = history[-1]["outcome"]
463
+ if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were
464
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
465
+ return acts + [["restore", n, memory[n]] for n in last["moved"]]
466
+ if kind == "nomem": # F2 but no start frame: guesses
467
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
468
+ return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]]
469
+ if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
470
+ fp = self.footprint(TARGET)
471
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
472
+ return [["ketchup_to_basket", fp]]
473
+ raise ValueError(kind)
474
+
475
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
476
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
477
+ k = k or self.max_attempts
478
+ rng = np.random.default_rng(seed)
479
+ history = []
480
+ self.reset_instance(inst)
481
+ memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save
482
+ for a in range(k):
483
+ actions = self._plan(kind, inst, a, history, rng, memory)
484
+ self.do(actions, inst)
485
+ self.go_home()
486
+ out = self.outcome(inst)
487
+ params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else
488
+ [x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)]
489
+ for x in actions])
490
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
491
+ if on_attempt:
492
+ on_attempt(a, params, out)
493
+ if out["success"] or kind in ("oracle", "naive"):
494
+ break
495
+ return history
496
+
497
+ # cross-protocol hooks are not used by this task
498
+ def default_params(self, inst):
499
+ return dict(policy="naive")
500
+
501
+ def oracle_params(self, inst):
502
+ return dict(policy="oracle")