PeterXie666 commited on
Commit
6b2c3f5
·
verified ·
1 Parent(s): 05ee179

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_000184_image.png +3 -0
  2. leaf/final/episode_000189.npz +3 -0
  3. leaf/final/episode_000302_wrist_image.png +3 -0
  4. leaf/final/episode_000384_wrist_image.png +3 -0
  5. leaf/final/episode_000764.npz +3 -0
  6. leaf/final/episode_000921_wrist_image.png +3 -0
  7. leaf/final/episode_000933.npz +3 -0
  8. leaf/final/episode_001076_image.png +3 -0
  9. leaf/final/episode_001111_wrist_image.png +3 -0
  10. leaf/final/episode_001184_wrist_image.png +3 -0
  11. leaf/final/episode_001239_wrist_image.png +3 -0
  12. leaf/final/episode_001291_image.png +3 -0
  13. leaf/final/episode_001377.npz +3 -0
  14. leaf/final/episode_001804_wrist_image.png +3 -0
  15. leaf/final/episode_001956_wrist_image.png +3 -0
  16. leaf/final/episode_002005_wrist_image.png +3 -0
  17. leaf/final/episode_002024_image.png +3 -0
  18. leaf/final/episode_002370.npz +3 -0
  19. leaf/final/episode_002556_image.png +3 -0
  20. leaf/final/episode_002589.npz +3 -0
  21. leaf/final/episode_002599_wrist_image.png +3 -0
  22. leaf/final/episode_002621.npz +3 -0
  23. leaf/final/episode_002629_image.png +3 -0
  24. leaf/final/episode_002750_image.png +3 -0
  25. leaf/final/episode_002830.npz +3 -0
  26. leaf/final/episode_003060_image.png +3 -0
  27. leaf/final/episode_003096_image.png +3 -0
  28. leaf/final/episode_003113.npz +3 -0
  29. leaf/final/episode_003160_wrist_image.png +3 -0
  30. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/README.md +297 -0
  31. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/__init__.py +1 -0
  32. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/audit_state.py +79 -0
  33. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/camera.py +100 -0
  34. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/context.py +377 -0
  35. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/cost.py +37 -0
  36. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/harness.py +300 -0
  37. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/images.py +47 -0
  38. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/metrics.py +97 -0
  39. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/replay.py +59 -0
  40. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/robot_server.py +966 -0
  41. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/runlog.py +62 -0
  42. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/agent/tools.py +392 -0
  43. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/__init__.py +63 -0
  44. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/base.py +364 -0
  45. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/claude_code.py +514 -0
  46. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/codex.py +687 -0
  47. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/contract.py +160 -0
  48. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/dsh.py +403 -0
  49. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/embodied_evo.py +135 -0
  50. leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
leaf/final/episode_000184_image.png ADDED

Git LFS Details

  • SHA256: ae176dad39d20de834253648a42e7934f19ca12f1bf100dbda44b87d27a97323
  • Pointer size: 130 Bytes
  • Size of remote file: 55.3 kB
leaf/final/episode_000189.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f0b191753faa3bd6effc541163a428030982ae13b3f431bf6415fb6980cca2b
3
+ size 3958
leaf/final/episode_000302_wrist_image.png ADDED

Git LFS Details

  • SHA256: e42e5823dcb9155e75a6fbae42f91323fb5f0f79fcc19b0a54e1f0ae15525e3e
  • Pointer size: 130 Bytes
  • Size of remote file: 37.7 kB
leaf/final/episode_000384_wrist_image.png ADDED

Git LFS Details

  • SHA256: 1eb12afcba78785103525b8c8ad492c388b1c28dd00ba4d14ae66a8f442e9a0e
  • Pointer size: 130 Bytes
  • Size of remote file: 31.4 kB
leaf/final/episode_000764.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5744085bb1d210a9830f9fa20c8834fe9356af515421845bba44df2afb52e8d9
3
+ size 4046
leaf/final/episode_000921_wrist_image.png ADDED

Git LFS Details

  • SHA256: eed2cb76942d42f5df1e8b95adbbb50bc86ca8c9cd758d3596bb6a8eb8c8ff3c
  • Pointer size: 130 Bytes
  • Size of remote file: 45 kB
leaf/final/episode_000933.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35fae59d966f550ee9cb4e6f7abd4dd00eb8f43b8b14525891efa13d2a791cd3
3
+ size 4046
leaf/final/episode_001076_image.png ADDED

Git LFS Details

  • SHA256: ed2bf1c800edea79712c679a789f78cd775d9661cb697e46c2f79e2a06af8613
  • Pointer size: 130 Bytes
  • Size of remote file: 57.2 kB
leaf/final/episode_001111_wrist_image.png ADDED

Git LFS Details

  • SHA256: f6f8fe5e8159ae37454e4e8c22eee17ee9f06948175eeecf27680506577ae141
  • Pointer size: 130 Bytes
  • Size of remote file: 40.6 kB
leaf/final/episode_001184_wrist_image.png ADDED

Git LFS Details

  • SHA256: 2c018c6cf05d16d3827cabff5d10bc8c98f1e92b4ee140a2da35ad0b6c0ecd44
  • Pointer size: 130 Bytes
  • Size of remote file: 43.5 kB
leaf/final/episode_001239_wrist_image.png ADDED

Git LFS Details

  • SHA256: 26245509b0f5db5c35f480585898d8fb8aec7d1649707e27b01058e3079b8c18
  • Pointer size: 130 Bytes
  • Size of remote file: 25.1 kB
leaf/final/episode_001291_image.png ADDED

Git LFS Details

  • SHA256: 006b0f45fbbb0d694000a6abe5c2d4574596880515fc1410f3c779062698660e
  • Pointer size: 130 Bytes
  • Size of remote file: 58.8 kB
leaf/final/episode_001377.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4b97b4aea03e63309e3faa121356f22ec169445085e4310a18e6d66960c99bf
3
+ size 3838
leaf/final/episode_001804_wrist_image.png ADDED

Git LFS Details

  • SHA256: c1f1f7d118ae7156396a7e2e8b004512e6d48cca2f70dcc4be824f4055a94bb6
  • Pointer size: 130 Bytes
  • Size of remote file: 30.6 kB
leaf/final/episode_001956_wrist_image.png ADDED

Git LFS Details

  • SHA256: d0bba8dea5d25c36b3bfd9076c5789f28f3ae723985e7876dddc36f0200a7208
  • Pointer size: 130 Bytes
  • Size of remote file: 33.9 kB
leaf/final/episode_002005_wrist_image.png ADDED

Git LFS Details

  • SHA256: 7ff7894e29fee0e21ff2686599be7ab7e2900ab40888a0a453fdc5db3cc2afa5
  • Pointer size: 130 Bytes
  • Size of remote file: 40.9 kB
leaf/final/episode_002024_image.png ADDED

Git LFS Details

  • SHA256: 2c5a3a5ada407486502cbe64ec955d686027a4c5b88f64ff14ce12958e7876cc
  • Pointer size: 130 Bytes
  • Size of remote file: 55 kB
leaf/final/episode_002370.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac11ffdd5ab447423441dc3085d9779eaeeb88ddc20aa68fa3001eea40e93bc2
3
+ size 3942
leaf/final/episode_002556_image.png ADDED

Git LFS Details

  • SHA256: bba0be4aac681d5bdfb4e59e6e825a471daed20833b2db55b5a50604a0c90ff4
  • Pointer size: 130 Bytes
  • Size of remote file: 58.9 kB
leaf/final/episode_002589.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03ef4563fc121bed002e75c3cb9fd70d41335e4f1793c85a8aa78a4fdcb41f9e
3
+ size 3630
leaf/final/episode_002599_wrist_image.png ADDED

Git LFS Details

  • SHA256: 4bd3ad359508015ff00ff19b8cf7fca1644694dbf90f6b99dd37911ce8bbfcf3
  • Pointer size: 130 Bytes
  • Size of remote file: 41.3 kB
leaf/final/episode_002621.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:98bea44ac90acaeb3ebdcba8574dd39cd4bdd26909e5fbc06fbe89fe4c48fe72
3
+ size 4150
leaf/final/episode_002629_image.png ADDED

Git LFS Details

  • SHA256: acbccab6a817dbbe0da77996e8211ef6ba15613946d3ed85287bb5ff36cbb959
  • Pointer size: 130 Bytes
  • Size of remote file: 54 kB
leaf/final/episode_002750_image.png ADDED

Git LFS Details

  • SHA256: 3649ea539917eca81b03e61a58dac00cc5947fd8d2d737b42d826b3517e00dd2
  • Pointer size: 130 Bytes
  • Size of remote file: 55.6 kB
leaf/final/episode_002830.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e295f9f846791af5e14461215dff77bab6715743f3ecf337b92805dda97964b2
3
+ size 3630
leaf/final/episode_003060_image.png ADDED

Git LFS Details

  • SHA256: cc349058aafa047309aac28834df9cfd40698421e33d5a62711ad68a2a4df6b3
  • Pointer size: 130 Bytes
  • Size of remote file: 56.1 kB
leaf/final/episode_003096_image.png ADDED

Git LFS Details

  • SHA256: a4cf25d2feeccece16aeb31ea96af6a009673abc285c366a08e80abf2fb7d771
  • Pointer size: 130 Bytes
  • Size of remote file: 54.9 kB
leaf/final/episode_003113.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d81a95b53fd98f8790fac3ade803531ec7982d0d198558ad424fb60897c6f82d
3
+ size 4046
leaf/final/episode_003160_wrist_image.png ADDED

Git LFS Details

  • SHA256: eaf62bb6f1d70afd295f66ce13029f04d35ad9c92d8bab091e2be6c452814a6c
  • Pointer size: 130 Bytes
  • Size of remote file: 48.1 kB
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/lff/source_closure/lffbench/agent/harness.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Protocol controller: runs a backend on task instances, attempt by attempt.
2
+
3
+ cross protocol : reset to the same instance (same layout + hidden variables) before every attempt
4
+ within protocol: one continuous episode; each `done` call closes a segment ("attempt") that is checked;
5
+ the agent continues from the current state if it failed and budget remains
6
+ Both protocols pack finished attempts the same way (keyframes <= 4, action summary, feedback F0/F1/F2) and
7
+ show them according to the memory mode (none / full / last / mismatched).
8
+ """
9
+ import time
10
+ from dataclasses import asdict, dataclass, field
11
+
12
+ from .context import (FEEDBACK_LEVELS, MEMORY_MODES, AttemptRecord, Conversation, PromptBuilder, StepRecord,
13
+ pick_keyframes, select_history, summarize_actions)
14
+ from .cost import call_cost, estimate_request_tokens
15
+ from .metrics import run_summary
16
+ from .backends.base import AttemptInfo, RunInfo
17
+
18
+
19
+ @dataclass
20
+ class HarnessConfig:
21
+ memory: str = "full"
22
+ feedback: str = "F2"
23
+ k: int = None # attempts (cross) / done calls (within); default task.max_attempts
24
+ image_res: int = 512
25
+ keyframe_res: int = None # default = image_res
26
+ n_keyframes: int = 4
27
+ cams: tuple = ("agentview", "wrist")
28
+ auto_obs: bool = True # send new images after every action tool
29
+ max_steps: int = 30 # tool calls per attempt
30
+ max_no_tool: int = 3 # consecutive replies without a tool call before the attempt is ended
31
+ privileged_locate: bool = False
32
+ grasp_report: str = "bool" # "bool" | "name" | "none"
33
+ instruction: str = "direct" # "direct" | "indirect"
34
+ early_stop: str = "auto" # "auto" (stop at first success unless F0), "yes", "no"
35
+ settle_within: int = 20 # control steps held still before checking a within-protocol segment
36
+ jpeg_quality: int = 90
37
+ save_images: bool = True
38
+ model_for_cost: str = "gpt-6-astra"
39
+ extra: dict = field(default_factory=dict)
40
+
41
+ def validate(self):
42
+ assert self.memory in MEMORY_MODES, self.memory
43
+ assert self.feedback in FEEDBACK_LEVELS, self.feedback
44
+ assert self.grasp_report in ("bool", "name", "none")
45
+ assert self.instruction in ("direct", "indirect")
46
+ assert self.early_stop in ("auto", "yes", "no")
47
+ assert 1 <= self.n_keyframes <= 4 or self.n_keyframes == 0
48
+
49
+
50
+ def clean_inst(inst):
51
+ return {k: v for k, v in inst.items() if not str(k).startswith("_")}
52
+
53
+
54
+ class AgentHarness:
55
+ def __init__(self, task, backend, cfg: HarnessConfig, logger, payload_probe=None, executor_factory=None,
56
+ cam_axes=None):
57
+ cfg.validate()
58
+ self.task, self.backend, self.cfg, self.log = task, backend, cfg, logger
59
+ self.protocol = getattr(task, "protocol", "cross")
60
+ self.k = cfg.k or task.max_attempts
61
+ self.payload_probe = payload_probe # optional OpenAIResponsesBackend used only to size requests (dry run)
62
+ self.executor_factory = executor_factory # tests: build a fake executor instead of ToolExecutor
63
+ self._cam_axes = cam_axes
64
+
65
+ # ------------------------------------------------------------------ helpers
66
+ def instruction(self, inst):
67
+ hook = getattr(self.task, "agent_instruction", None)
68
+ if hook is not None:
69
+ return hook(inst, self.cfg.instruction)
70
+ if self.cfg.instruction == "indirect" and getattr(self.task, "instruction_indirect", ""):
71
+ return self.task.instruction_indirect
72
+ return self.task.instruction
73
+
74
+ def feedback(self, inst, out, level):
75
+ import inspect
76
+ fn = self.task.feedback
77
+ if "indirect" in inspect.signature(fn).parameters: # tasks that phrase feedback per instruction variant
78
+ return fn(inst, out, level, indirect=self.cfg.instruction == "indirect")
79
+ return fn(inst, out, level)
80
+
81
+ def early_stop(self):
82
+ if self.cfg.early_stop == "auto":
83
+ return self.cfg.feedback != "F0"
84
+ return self.cfg.early_stop == "yes"
85
+
86
+ def terminal(self, out):
87
+ hook = getattr(self.task, "is_terminal", None)
88
+ if hook is not None:
89
+ return bool(hook(out))
90
+ return bool(out.get("terminal") or out.get("overshoot"))
91
+
92
+ def _executor(self, inst):
93
+ if self.executor_factory is not None:
94
+ return self.executor_factory(self, inst)
95
+ from .tools import ToolExecutor
96
+ return ToolExecutor(self.task, inst, image_res=self.cfg.image_res, cams=self.cfg.cams,
97
+ privileged_locate=self.cfg.privileged_locate, grasp_report=self.cfg.grasp_report,
98
+ jpeg_quality=self.cfg.jpeg_quality, image_sink=self._sink)
99
+
100
+ def _sink(self, ref):
101
+ self._img_counter += 1
102
+ rel = f"seed{self._seed}/a{self._attempt}_s{self._step:02d}_{self._img_counter:03d}_{ref.camera}.jpg"
103
+ return self.log.save_image(ref, rel)
104
+
105
+ def _keyframe(self, ref):
106
+ """Separate (possibly smaller) copy of an agentview frame for the history."""
107
+ from .images import ImageRef
108
+ kres = self.cfg.keyframe_res or self.cfg.image_res
109
+ kf = ImageRef(camera=ref.camera, array=ref.array, label=ref.label)
110
+ if kres == self.cfg.image_res:
111
+ kf.jpeg, kf.path = ref.jpeg, ref.path
112
+ return kf
113
+ self._img_counter += 1
114
+ rel = f"seed{self._seed}/a{self._attempt}_key_{self._img_counter:03d}_{ref.camera}.jpg"
115
+ return self.log.save_image(kf, rel, res=kres)
116
+
117
+ def prompts(self, executor):
118
+ if self._cam_axes is None:
119
+ from . import camera as C
120
+ self._cam_axes = {c: C.describe_axes(self.task.env, c, self.cfg.image_res) for c in C.CAMERAS}
121
+ names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
122
+ return PromptBuilder(self.task, self.protocol, self.k, self.cfg.memory, self.cfg.feedback, self.cfg.image_res,
123
+ self._cam_axes, privileged_locate=self.cfg.privileged_locate, object_names=names,
124
+ grasp_report=self.cfg.grasp_report, cams=self.cfg.cams)
125
+
126
+ # ------------------------------------------------------------------ run
127
+ def run_instance(self, seed, donor=None):
128
+ """donor: AttemptRecords of another instance (memory=mismatched). Returns (summary, records)."""
129
+ task, cfg = self.task, self.cfg
130
+ inst = task.sample_instance(seed)
131
+ self._seed, self._attempt, self._step, self._img_counter = seed, 0, 0, 0
132
+ self._llm_calls = []
133
+ t_run = time.time()
134
+ sim_wall = 0.0
135
+ info = RunInfo(task=task, inst=inst, seed=seed, k=self.k, protocol=self.protocol, feedback=cfg.feedback,
136
+ memory=cfg.memory)
137
+ self.backend.begin_run(info)
138
+ self.log.event("run_start", seed=seed, inst=clean_inst(inst), task=task.name, protocol=self.protocol, k=self.k,
139
+ memory=cfg.memory, feedback=cfg.feedback, donor_seed=donor[0].seed if donor else None)
140
+ records, executor, status = [], None, "ok"
141
+ for a in range(1, self.k + 1):
142
+ self._attempt, self._step = a, 0
143
+ if self.protocol == "cross" or executor is None:
144
+ t0 = time.time()
145
+ task.reset_instance(inst)
146
+ executor = self._executor(inst)
147
+ sim_wall += time.time() - t0
148
+ visible = select_history(cfg.memory, records, donor)
149
+ rec, attempt_sim = self._attempt_loop(inst, seed, a, visible, executor,
150
+ continuing=self.protocol == "within" and a > 1)
151
+ sim_wall += attempt_sim
152
+ records.append(rec)
153
+ if rec.ended_by == "backend_error":
154
+ status = "error"
155
+ break
156
+ if rec.success and self.early_stop():
157
+ break
158
+ if self.protocol == "within" and (rec.success or self.terminal(rec.outcome)):
159
+ break
160
+ self.backend.end_run()
161
+ summ = run_summary(seed, records, self.k, status=status, llm_calls=self._llm_calls,
162
+ extra=dict(sim_wall_s=round(sim_wall, 2), wall_s=round(time.time() - t_run, 2),
163
+ donor_seed=donor[0].seed if donor else None))
164
+ self.log.event("run_end", **summ)
165
+ summ["_llm_calls"] = self._llm_calls
166
+ return summ, records
167
+
168
+ def _attempt_loop(self, inst, seed, a, visible, ex, continuing):
169
+ cfg, task, backend = self.cfg, self.task, self.backend
170
+ P = self.prompts(ex)
171
+ tools = self.tool_specs()
172
+ conv = Conversation(P.system_prompt())
173
+ backend.begin_attempt(AttemptInfo(attempt=a, history=visible, continuing=continuing))
174
+ sim_t = 0.0
175
+ t0 = time.time()
176
+ obs0 = ex.observe(label="start")
177
+ sim_t += time.time() - t0
178
+ conv.add_user(P.history_parts(self.instruction(inst), visible), live=False)
179
+ conv.add_user(P.current_parts(a, obs0, ex.proprio(), continuing), live=True)
180
+ steps, diagnosis, done_reason, ended_by = [], None, None, None
181
+ n_calls, no_tool = 0, 0
182
+ while ended_by is None:
183
+ if len(steps) >= cfg.max_steps:
184
+ ended_by = "step_budget"
185
+ break
186
+ try:
187
+ resp = backend.act(conv, tools)
188
+ except Exception as e: # API failure after retries, crashed scripted policy, ...
189
+ self.log.event("llm_error", seed=seed, attempt=a, call=n_calls + 1, error=repr(e)[:4000])
190
+ ended_by = "backend_error"
191
+ break
192
+ n_calls += 1
193
+ call_rec = self._log_llm_call(seed, a, n_calls, resp, conv, tools)
194
+ self._llm_calls.append(call_rec)
195
+ if n_calls == 1 and resp.text:
196
+ diagnosis = resp.text
197
+ conv.add_assistant(resp.text, resp.tool_calls, raw=resp.raw, backend=backend.name)
198
+ if not resp.tool_calls:
199
+ no_tool += 1
200
+ if no_tool >= cfg.max_no_tool:
201
+ ended_by = "no_tool_call"
202
+ break
203
+ conv.add_user(P.nudge(), live=True)
204
+ continue
205
+ no_tool = 0
206
+ acted = None
207
+ for tc in resp.tool_calls:
208
+ self._step = len(steps) + 1
209
+ res = ex.call(tc.name, tc.raw_arguments or tc.arguments)
210
+ sim_t += res.wall_s
211
+ conv.add_tool_output(tc.id, tc.name, res.text())
212
+ backend.on_tool_result(tc, res)
213
+ st = StepRecord(step=self._step, name=tc.name, args=res.args, report=res.report, ok=res.ok,
214
+ wall_s=round(res.wall_s, 3), sim_steps=res.sim_steps)
215
+ steps.append(st)
216
+ if res.images:
217
+ conv.add_user(P.observation_parts(f"Images returned by get_observation (step {self._step})",
218
+ res.images, ex.proprio()), live=True)
219
+ if tc.name in ("move_to", "open_gripper", "close_gripper", "push") and res.ok:
220
+ acted = st
221
+ self.log.event("tool_call", seed=seed, attempt=a, step=self._step, call_id=tc.id, name=tc.name,
222
+ args=res.args, ok=res.ok, report=res.report, wall_s=round(res.wall_s, 3),
223
+ sim_steps=res.sim_steps, images=[i.path for i in res.images])
224
+ if res.ended:
225
+ done_reason = res.args.get("reason")
226
+ ended_by = "done"
227
+ break
228
+ if len(steps) >= cfg.max_steps:
229
+ break
230
+ if ended_by is None and acted is not None:
231
+ t1 = time.time()
232
+ if cfg.auto_obs:
233
+ obs = ex.observe(label=f"step{acted.step}")
234
+ conv.add_user(P.step_observation(acted.step, acted.name, obs, ex.proprio()), live=True)
235
+ acted.frame = next((o for o in obs if o.camera == "agentview"), obs[0])
236
+ else: # still keep an agentview frame for the history keyframes / logs
237
+ from .images import ImageRef
238
+ acted.frame = self._sink(ImageRef(camera="agentview", array=ex.render("agentview"),
239
+ label=f"step{acted.step}"))
240
+ sim_t += time.time() - t1
241
+ self.log.event("observation", seed=seed, attempt=a, step=acted.step,
242
+ images=[acted.frame.path] if not cfg.auto_obs else [o.path for o in obs],
243
+ proprio=ex.proprio())
244
+ meta = backend.end_attempt() or {}
245
+ # ------------------------------------------------------------ outcome + packing
246
+ t1 = time.time()
247
+ home = getattr(task, "go_home", None) # task-defined end-of-attempt motion (e.g. L6: arm out of view)
248
+ if home is not None and ended_by != "backend_error":
249
+ home()
250
+ if self.protocol == "within" and cfg.settle_within:
251
+ ex.sk.hold(cfg.settle_within)
252
+ out = task.outcome(inst)
253
+ from .images import ImageRef
254
+ self._step = 99
255
+ final = self._sink(ImageRef(camera="agentview", array=ex.render("agentview", cfg.keyframe_res or cfg.image_res),
256
+ label="end"))
257
+ sim_t += time.time() - t1
258
+ fb = self.feedback(inst, out, cfg.feedback)
259
+ fb_full = self.feedback(inst, out, "F2")
260
+ init_frame = next((o for o in obs0 if o.camera == "agentview"), None)
261
+ for s in steps:
262
+ if s.frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res:
263
+ s.frame = self._keyframe(s.frame)
264
+ if init_frame is not None and (cfg.keyframe_res or cfg.image_res) != cfg.image_res:
265
+ init_frame = self._keyframe(init_frame)
266
+ kfs = pick_keyframes(steps, init_frame, final, cfg.n_keyframes) if cfg.n_keyframes else []
267
+ rec = AttemptRecord(seed=seed, attempt=a, steps=steps, keyframes=kfs, outcome=dict(out),
268
+ success=bool(out.get("success")), feedback=fb, done_reason=done_reason, diagnosis=diagnosis,
269
+ ended_by=ended_by, backend_meta=meta)
270
+ calls = [c for c in self._llm_calls if c["attempt"] == a]
271
+ self.log.event("attempt_end", seed=seed, attempt=a, success=rec.success, outcome=out, feedback_shown=fb,
272
+ feedback_f2=fb_full, ended_by=ended_by, done_reason=done_reason, diagnosis=diagnosis,
273
+ n_steps=len(steps), n_llm_calls=len(calls), backend_meta=meta,
274
+ history_shown=[(h.seed, h.attempt) for h in visible],
275
+ keyframes=[(c, r.path) for c, r in kfs], action_summary=summarize_actions(steps),
276
+ llm_latency_s=round(sum(c["latency_s"] for c in calls), 3), sim_wall_s=round(sim_t, 3))
277
+ return rec, sim_t
278
+
279
+ def tool_specs(self):
280
+ from .tools import tool_specs
281
+ names = getattr(self.task, "agent_object_names", None) or list(self.task.env.objects_dict)
282
+ return tool_specs(self.cfg.privileged_locate, names, self.cfg.image_res)
283
+
284
+ def _log_llm_call(self, seed, a, n, resp, conv, tools):
285
+ rec = dict(seed=seed, attempt=a, call=n, latency_s=round(resp.latency_s, 3), usage=resp.usage,
286
+ cost_usd=call_cost(resp.usage, self.cfg.model_for_cost) if resp.usage else None,
287
+ status=resp.status, error=resp.error, text=resp.text, reasoning_summary=resp.reasoning_summary,
288
+ reasoning_summary_status="recorded" if resp.reasoning_summary else "not_returned",
289
+ tool_calls=[dict(id=t.id, name=t.name, arguments=t.arguments) for t in resp.tool_calls],
290
+ request=resp.request_stats, conv_images=conv.n_images())
291
+ if self.payload_probe is not None: # dry run: size of the request GPT-6 would have received
292
+ stats = self.payload_probe.request_stats(self.payload_probe.build_request(conv, tools))
293
+ stats["est_input_tokens"] = estimate_request_tokens(stats, self.cfg.image_res)
294
+ rec["dry_run_request"] = stats
295
+ self.log.event("llm_call", **rec)
296
+ return rec
297
+
298
+
299
+ def config_dict(cfg):
300
+ return asdict(cfg)
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/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_gpt/lff/source_closure/lffbench/agent/metrics.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run-level metrics (design doc 02 §5): succ@k per run, attempt-1 success, first-success attempt,
2
+ fields for ΔICL = succ@k(with history) - pass@k_iid(independent retries), same-mistake (repeated
3
+ action) rate, residuals, tokens / cost / latency."""
4
+ import numpy as np
5
+
6
+ from .context import wilson
7
+
8
+
9
+ def run_summary(seed, records, k, status="ok", llm_calls=(), extra=None):
10
+ """records: list[AttemptRecord] of one run (one instance)."""
11
+ succ = [bool(r.success) for r in records]
12
+ first = next((r.attempt for r in records if r.success), None)
13
+ fails = [r for r in records if not r.success]
14
+ pairs = [(a, b) for a, b in zip(records, records[1:]) if not a.success]
15
+ repeats = [a.action_signature() == b.action_signature() for a, b in pairs]
16
+ residuals = [{kk: v for kk, v in r.outcome.items() if kk.endswith("_err") and isinstance(v, (int, float))}
17
+ for r in records]
18
+ lat = [c.get("latency_s", 0.0) for c in llm_calls]
19
+ usage = {key: int(sum((c.get("usage") or {}).get(key, 0) or 0 for c in llm_calls))
20
+ for key in ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens",
21
+ "reasoning_tokens")}
22
+ cost = [c.get("cost_usd") for c in llm_calls if c.get("cost_usd") is not None]
23
+ out = dict(seed=seed, status=status, k=k, n_attempts=len(records), success_by_attempt=succ,
24
+ first_success=first, success=first is not None, attempt1_success=bool(succ[0]) if succ else False,
25
+ ended_by=[r.ended_by for r in records], n_failed_attempts=len(fails),
26
+ repeated_action_pairs=int(sum(repeats)), failed_pairs=len(pairs), residuals=residuals,
27
+ n_llm_calls=len(llm_calls), llm_latency_s=float(sum(lat)), usage=usage,
28
+ cost_usd=float(sum(cost)) if cost else None,
29
+ n_tool_calls=int(sum(len(r.steps) for r in records)))
30
+ if extra:
31
+ out.update(extra)
32
+ return out
33
+
34
+
35
+ def aggregate(runs, k):
36
+ ok = [r for r in runs if r["status"] == "ok"]
37
+ n = len(ok)
38
+ first = [r["first_success"] for r in ok]
39
+ curve, ci = [], []
40
+ for j in range(1, k + 1):
41
+ s = sum(1 for f in first if f is not None and f <= j)
42
+ curve.append(s / n if n else float("nan"))
43
+ ci.append(wilson(s, n))
44
+ p1 = curve[0] if curve else float("nan")
45
+ succ_first = [f for f in first if f is not None]
46
+ calls = [c for r in ok for c in r.get("_llm_calls", [])]
47
+ lat = np.array([c.get("latency_s", 0.0) for c in calls]) if calls else np.zeros(0)
48
+ pairs = sum(r["failed_pairs"] for r in ok)
49
+ tot = {key: int(sum(r["usage"].get(key, 0) for r in ok))
50
+ for key in ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens", "reasoning_tokens")}
51
+ costs = [r["cost_usd"] for r in ok if r.get("cost_usd") is not None]
52
+ return dict(
53
+ n_runs=n, n_error_runs=len(runs) - n, k=k,
54
+ succ_at=curve, succ_at_ci95=ci, succ_at_k=curve[-1] if curve else float("nan"),
55
+ attempt1_success=p1,
56
+ # ΔICL needs pass@k of independent retries: measure it with --memory none on the same seeds and
57
+ # compare with scripts/agent_compare.py. The analytic value assumes i.i.d. attempts with the
58
+ # attempt-1 success rate of THIS run set (a cheaper but weaker reference).
59
+ pass_at_k_iid_analytic=1 - (1 - p1) ** k if n else float("nan"),
60
+ delta_icl_vs_analytic_iid=(curve[-1] - (1 - (1 - p1) ** k)) if n else float("nan"),
61
+ mean_first_success=float(np.mean(succ_first)) if succ_first else None,
62
+ median_first_success=float(np.median(succ_first)) if succ_first else None,
63
+ repeated_action_rate=(sum(r["repeated_action_pairs"] for r in ok) / pairs) if pairs else None,
64
+ llm_calls_per_run=float(np.mean([r["n_llm_calls"] for r in ok])) if ok else None,
65
+ llm_latency_mean_s=float(lat.mean()) if lat.size else None,
66
+ llm_latency_p50_s=float(np.percentile(lat, 50)) if lat.size else None,
67
+ llm_latency_p95_s=float(np.percentile(lat, 95)) if lat.size else None,
68
+ llm_latency_per_run_s=float(np.mean([r["llm_latency_s"] for r in ok])) if ok else None,
69
+ sim_wall_per_run_s=float(np.mean([r.get("sim_wall_s", 0.0) for r in ok])) if ok else None,
70
+ tool_calls_per_run=float(np.mean([r["n_tool_calls"] for r in ok])) if ok else None,
71
+ usage_total=tot,
72
+ cache_hit_rate=(tot["cached_tokens"] / tot["input_tokens"]) if tot["input_tokens"] else None,
73
+ cost_usd_total=float(sum(costs)) if costs else None,
74
+ cost_usd_per_run=float(np.mean(costs)) if costs else None,
75
+ )
76
+
77
+
78
+ def paired_delta(with_runs, iid_runs, k, n_boot=10000, seed=0):
79
+ """ΔICL = succ@k(with) - succ@k(iid) on the seeds both run sets share, with a paired bootstrap CI."""
80
+ a = {r["seed"]: r for r in with_runs if r["status"] == "ok"}
81
+ b = {r["seed"]: r for r in iid_runs if r["status"] == "ok"}
82
+ seeds = sorted(set(a) & set(b))
83
+ if not seeds:
84
+ return dict(n=0)
85
+
86
+ def ok(r):
87
+ return r["first_success"] is not None and r["first_success"] <= k
88
+
89
+ x = np.array([ok(a[s]) for s in seeds], float)
90
+ y = np.array([ok(b[s]) for s in seeds], float)
91
+ d = x - y
92
+ rng = np.random.default_rng(seed)
93
+ idx = rng.integers(0, len(d), size=(n_boot, len(d)))
94
+ boot = d[idx].mean(1)
95
+ return dict(n=len(seeds), succ_at_k_with=float(x.mean()), succ_at_k_iid=float(y.mean()), delta_icl=float(d.mean()),
96
+ ci95=[float(np.percentile(boot, 2.5)), float(np.percentile(boot, 97.5))],
97
+ discordant=dict(with_only=int(((x == 1) & (y == 0)).sum()), iid_only=int(((x == 0) & (y == 1)).sum())))
leaf/release/source_packages/remaining-lh-20261103-remaining_lh_20261103_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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_gpt/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]