Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- leaf/final/episode_000054.npz +3 -0
- leaf/final/episode_000176.npz +3 -0
- leaf/final/episode_000423_wrist_image.png +3 -0
- leaf/final/episode_000520_image.png +3 -0
- leaf/final/episode_000857.npz +3 -0
- leaf/final/episode_000858_image.png +3 -0
- leaf/final/episode_000871.npz +3 -0
- leaf/final/episode_000908_image.png +3 -0
- leaf/final/episode_001137.npz +3 -0
- leaf/final/episode_001149.npz +3 -0
- leaf/final/episode_001152_wrist_image.png +3 -0
- leaf/final/episode_001598_wrist_image.png +3 -0
- leaf/final/episode_001730.npz +3 -0
- leaf/final/episode_002212.npz +3 -0
- leaf/final/episode_002423_wrist_image.png +3 -0
- leaf/final/episode_002836.npz +3 -0
- leaf/final/episode_002837.npz +3 -0
- leaf/final/episode_003181.npz +3 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/README.md +297 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/audit_state.py +79 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/cost.py +37 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/harness.py +300 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/agent/metrics.py +97 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py +40 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py +61 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py +61 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/__init__.py +63 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/base.py +364 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/claude_code.py +514 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/codex.py +688 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/contract.py +160 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/dsh.py +403 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/embodied_evo.py +135 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/framework_codex.py +542 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/jail.py +228 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/pins.py +40 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/reference.py +143 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/rpent.py +530 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/sensenova.py +24 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/trajectory.py +86 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/DRIVER.md +144 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/__init__.py +10 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/driver_template.py +196 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/executor.py +138 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/fake_driver.py +152 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/protocol.py +364 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/session.py +346 -0
- leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/tasks.py +123 -0
leaf/final/episode_000054.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0573860058481d2b02a179859500112e233d437729f5972cb1fc2392cf06235b
|
| 3 |
+
size 4046
|
leaf/final/episode_000176.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d4a3be68092dfcf88c198082eae7620da959339dd151cbfe77f3cfd39dfa8600
|
| 3 |
+
size 4270
|
leaf/final/episode_000423_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000520_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000857.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:37902f5ca1b0d92666de76246b4c4649d0db05054c3f784eab98b88e871dfea3
|
| 3 |
+
size 4150
|
leaf/final/episode_000858_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_000871.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:69148e326da7ff3eef2008907b232214370452b955db3dc7f54222c90114064a
|
| 3 |
+
size 4046
|
leaf/final/episode_000908_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001137.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b5da0462afc2aab865079b46566a1b60b16ab57744626ddb1a32796a455ec1e9
|
| 3 |
+
size 3630
|
leaf/final/episode_001149.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:edf03c232212ce31107b87835b7ec1570a3d5fcd17e1fb82b334a25053d484a3
|
| 3 |
+
size 4270
|
leaf/final/episode_001152_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001598_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_001730.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7c307583e1ed9f18051fc1bcf0b994af4ee650cff698db810045deb29b8c6c86
|
| 3 |
+
size 4150
|
leaf/final/episode_002212.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9142aba2ef5e9019416a8ed5e15d6003a2221e5bf0126899ff10518543a1f174
|
| 3 |
+
size 3886
|
leaf/final/episode_002423_wrist_image.png
ADDED
|
Git LFS Details
|
leaf/final/episode_002836.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a549f9dc59fcda7b5cd0706a72b27fb0847ef72e4cc60ec0bbae559723afffe0
|
| 3 |
+
size 4150
|
leaf/final/episode_002837.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:04a18f077869210bb13715fad0f90767624681bbbbe283d798a0b4377e0b80f4
|
| 3 |
+
size 4150
|
leaf/final/episode_003181.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d8fdd20ee4c36cac76e0ec24f136fc530c08d03c3b2a358852396edea2286731
|
| 3 |
+
size 3734
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/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/models-20261115-g56sol_breakfast1_20261114/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/models-20261115-g56sol_breakfast1_20261114/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/models-20261115-g56sol_breakfast1_20261114/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/models-20261115-g56sol_breakfast1_20261114/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/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_loaded_beam.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l5_loaded_beam (2026-10-12, docs/14 sec. 6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: the bar's centre of mass `com_offset` (m along the bar from its middle, + = the robot's left end),
|
| 4 |
+
set at reset by l5_slippery_lift.set_hidden_weight (body_ipos + inertia + envs.refit_bounds, so a changed value is
|
| 5 |
+
honoured). `com_total` (bar + both blocks) is derived from it in sample_instance and read by oracle_params, so it is
|
| 6 |
+
overridden together. Mass, friction and layout stay as sampled.
|
| 7 |
+
|
| 8 |
+
h0 : centre of mass at the middle (0): the common-sense middle grasp lifts the bar level.
|
| 9 |
+
twin : the same offset on the other side (-com_offset): the middle grasp still tilts the bar and spills a block, but
|
| 10 |
+
now towards the other end, so the right grasp point is mirrored.
|
| 11 |
+
reveal: the hidden weight's side and the bar's centre of mass in cm (plus the bar's mass in g), in the F2 words.
|
| 12 |
+
"""
|
| 13 |
+
HIDDEN_KEYS = ("com_offset", "com_total")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def h0(inst):
|
| 17 |
+
return dict(com_offset=0.0, com_total=0.0)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def twin(inst):
|
| 21 |
+
return dict(com_offset=-float(inst["com_offset"]), com_total=-float(inst["com_total"]))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def reveal(inst):
|
| 25 |
+
e = float(inst["com_offset"])
|
| 26 |
+
side = "left" if e > 0 else "right"
|
| 27 |
+
return (f"The bar is not uniform: a heavy weight is hidden inside it towards its {side} end (the robot's {side}). "
|
| 28 |
+
f"The bar weighs {1000 * inst['mass']:.0f} g and its centre of mass is {100 * abs(e):.1f} cm to the "
|
| 29 |
+
f"{side} of its middle.")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def fix(inst, params):
|
| 33 |
+
"""Ladder Fix rung (docs/20): grasp at the combined centre of mass (oracle along = com_total), lift 15 cm at 0.1."""
|
| 34 |
+
a = float(params["along"])
|
| 35 |
+
side = "left" if a > 0 else "right"
|
| 36 |
+
return (f"A way to succeed: grasp the bar at its balance point, not at its middle. Open the gripper, turn it so "
|
| 37 |
+
f"the jaws close across the bar's 4 cm width, come down over the point {100 * abs(a):.1f} cm to the "
|
| 38 |
+
f"robot's {side} of the bar's middle (the centre of mass of the bar and the two blocks) until the "
|
| 39 |
+
f"fingers are at the bar's mid-height, close the gripper and lift straight up about 15 cm slowly (speed "
|
| 40 |
+
f"about 0.1). Held there, the bar stays level and both blocks stay on it.")
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_slide_to_target.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l5_slide_to_target (docs/14 §6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: mu, the cube-table sliding friction (apply_instance() sets it on every reset; oracle_params() bisects
|
| 4 |
+
the strike speed with it). The layout (cube_xy, target_dist) is kept.
|
| 5 |
+
|
| 6 |
+
The naive strike is 0.30 m/s. Where the cube stops depends on mu and, by up to ~1.5 cm, on the cube's position on the
|
| 7 |
+
table, and the target tolerance is only +-1 cm, so H0 and the twin are calibrated per full5 seed with a simulated sweep
|
| 8 |
+
(deterministic sim, scratchpad arms/fine.py, 2026-10-12); other seeds fall back to a power-law fit of the stopping
|
| 9 |
+
distance at 0.30 m/s (dist ~ 0.00453 / mu^1.04 m).
|
| 10 |
+
|
| 11 |
+
h0 mu at which the 0.30 m/s strike stops the cube on the square's centre (|err| <= 0.3 cm).
|
| 12 |
+
twin the opposite trap: if the original cube overshoots (slippery) the twin is grippy and stops short, and vice
|
| 13 |
+
versa, so the correction is the other way (slow down <-> speed up). The twin's naive error is at least 2 cm
|
| 14 |
+
and, where the twin's oracle still succeeds, about as large as the original's (mirrored). Seeds 3000 and 3007
|
| 15 |
+
overshoot by 6.9 / 4.1 cm, but a grippy cube cannot be made to stop that far short and still be solvable,
|
| 16 |
+
so their twins stop 2.1 / 3.4 cm short.
|
| 17 |
+
reveal states the friction coefficient only.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
HIDDEN_KEYS = ("mu",)
|
| 21 |
+
|
| 22 |
+
# seed: h0 mu (naive err there), twin mu (twin naive err, twin oracle speed m/s -> err). Original naive err in brackets.
|
| 23 |
+
_CAL = {
|
| 24 |
+
3000: dict(h0=0.0749, twin=0.1060), # [orig +6.94 cm] h0 +0.26; twin -2.13, oracle 0.551 -> +0.01
|
| 25 |
+
3001: dict(h0=0.0602, twin=0.0783), # [orig +2.95 cm] h0 +0.14; twin -2.73, oracle 0.450 -> 0.00
|
| 26 |
+
3003: dict(h0=0.0583, twin=0.0463), # [orig -1.73 cm] h0 +0.03; twin +2.75, oracle 0.242 -> -0.13
|
| 27 |
+
3004: dict(h0=0.0537, twin=0.0444), # [orig -1.66 cm] h0 -0.31; twin +2.14, oracle 0.240 -> -0.02
|
| 28 |
+
3007: dict(h0=0.0532, twin=0.0984), # [orig +4.05 cm] h0 +0.15; twin -3.39, oracle 0.570 -> -0.18
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _h0_mu(inst):
|
| 33 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 34 |
+
return c["h0"] if c else (0.00453 / float(inst["target_dist"])) ** (1 / 1.04)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def h0(inst):
|
| 38 |
+
return {"mu": float(_h0_mu(inst))}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def twin(inst):
|
| 42 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 43 |
+
if c:
|
| 44 |
+
return {"mu": float(c["twin"])}
|
| 45 |
+
m0 = _h0_mu(inst) # fallback: mirror mu about the H0 value in log space, kept in a solvable range
|
| 46 |
+
return {"mu": float(min(max(m0 * m0 / float(inst["mu"]), 0.03), 0.10))}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def reveal(inst):
|
| 50 |
+
return f"The red cube's sliding friction coefficient on the table is about {float(inst['mu']):.3f}."
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def fix(inst, params):
|
| 54 |
+
"""Ladder Fix rung (docs/20): one strike at the oracle speed (bisection with the true mu), 22 cm run-up, stopping
|
| 55 |
+
1.5 cm past the cube's near face -- as l5_slide.execute; move_eef speed = Skills.move_to speed."""
|
| 56 |
+
v = float(params["speed"])
|
| 57 |
+
return (f"A way to succeed: one straight strike at the right speed. Close the gripper (yaw 0), put the fingertips "
|
| 58 |
+
f"just above the table (grasp point about 2 cm above the tabletop) 22 cm behind the cube's centre, on the "
|
| 59 |
+
f"robot's side and in line with the cube and the target, then in one move_eef command move straight "
|
| 60 |
+
f"forward at speed {v:.2f} to a point 1.5 cm past where the cube's near face was (0.5 cm short of its "
|
| 61 |
+
f"centre), and lift the gripper. The cube then slides into the target zone.")
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/arm_specs/l5_tablecloth_pull.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Controlled arms for l5_tablecloth_pull (docs/14 §6).
|
| 2 |
+
|
| 3 |
+
Hidden variable: mu, the cube's friction (cube-board and cube-table contacts; apply_instance() sets it on every reset,
|
| 4 |
+
oracle_params() bisects the pull speed with it). The layout keys (board_xy, band_d) are left alone: band_d was sampled
|
| 5 |
+
from the original mu, but it is the visible band position, so H0 and the twin keep it and move only mu.
|
| 6 |
+
|
| 7 |
+
Physics (measured, 2026-10-12): the cube's displacement toward the robot grows with mu and shrinks with the pull speed
|
| 8 |
+
up to ~0.8 m/s (0.8 and 1.0 m/s give identical results: the controller saturates). The naive policy yanks at 0.6 m/s.
|
| 9 |
+
Every original instance lands SHORT of the band (cube forward of it, err -1.6 .. -3.5 cm): the lesson is "pull
|
| 10 |
+
slower".
|
| 11 |
+
|
| 12 |
+
h0 mu at which the 0.6 m/s yank lands the cube on the band's centre line (calibrated per full5 seed by a
|
| 13 |
+
simulated sweep; a linear fit in band_d for other seeds).
|
| 14 |
+
twin the opposite trap: mu high enough that the 0.6 m/s yank drags the cube PAST the band toward the robot
|
| 15 |
+
(err +1.5 .. +2.7 cm), so the lesson is "pull faster" (the twin's oracle pulls at 0.64-0.79 m/s; agents can
|
| 16 |
+
command up to 1.0 m/s). Applying that lesson to the original makes its cube land even further short.
|
| 17 |
+
The window is narrow: above it the cube cannot be stopped in the band even at the saturated top speed, so the
|
| 18 |
+
twin's naive error is only ~1.5-2.7 cm (similar size to the original's short-fall) and the twin's oracle is
|
| 19 |
+
within 0.2-0.5 cm of the band tolerance on some seeds. Calibrated per seed; for other seeds 1.2 x the H0 mu.
|
| 20 |
+
reveal states the cube's friction coefficient (the only fact that differs between instances).
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
HIDDEN_KEYS = ("mu",)
|
| 24 |
+
|
| 25 |
+
# Calibrated 2026-10-12 with the scripted policies (scratchpad arms/fine.py; deterministic sim).
|
| 26 |
+
# seed: (h0 mu, naive err at h0 [cm]), (twin mu, naive err [cm], twin oracle speed [m/s], twin oracle err [cm])
|
| 27 |
+
_CAL = {
|
| 28 |
+
3000: dict(h0=0.1543, twin=0.1876), # h0 +0.08; twin naive +1.65, oracle 0.719 m/s +0.60
|
| 29 |
+
3001: dict(h0=0.1744, twin=0.1995), # h0 +0.13; twin naive +2.17, oracle 0.638 m/s +0.47
|
| 30 |
+
3002: dict(h0=0.1393, twin=0.1716), # h0 -0.11; twin naive +1.48, oracle 0.759 m/s +0.78
|
| 31 |
+
3003: dict(h0=0.1442, twin=0.1775), # h0 +0.08; twin naive +2.18, oracle 0.759 m/s +0.44
|
| 32 |
+
3004: dict(h0=0.1944, twin=0.2250), # h0 +0.06; twin naive +2.74, oracle 0.790 m/s +0.51
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _h0_mu(inst):
|
| 37 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 38 |
+
return c["h0"] if c else 0.0835 + 1.485 * float(inst["band_d"])
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def h0(inst):
|
| 42 |
+
return {"mu": float(_h0_mu(inst))}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def twin(inst):
|
| 46 |
+
c = _CAL.get(int(inst.get("seed", -1)))
|
| 47 |
+
return {"mu": float(c["twin"] if c else 1.2 * _h0_mu(inst))}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def reveal(inst):
|
| 51 |
+
return (f"The red cube's friction coefficient (against the board and against the table) is about "
|
| 52 |
+
f"{float(inst['mu']):.3f}.")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def fix(inst, params):
|
| 56 |
+
"""Ladder Fix rung (docs/20): one pull of 25 cm at the oracle speed (bisection with the true mu), as
|
| 57 |
+
l5_tablecloth_pull.execute; move_eef speed = Skills.move_to speed."""
|
| 58 |
+
v = float(params["speed"])
|
| 59 |
+
return (f"A way to succeed: pull at the right speed. Grasp the black handle (jaws closing across its 4 cm width), "
|
| 60 |
+
f"then in one move_eef command pull the board straight towards the robot by 25 cm at speed {v:.2f}; then "
|
| 61 |
+
f"open the gripper and lift. The cube then lands in the green band.")
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness adapters (docs/15): one way to plug any agent harness into a robot_server session.
|
| 2 |
+
|
| 3 |
+
ours reference driver scripts/api_player.py (main table)
|
| 4 |
+
claude_code Claude Code CLI, --bare, only our MCP tools (arm B)
|
| 5 |
+
claude_code_full Claude Code CLI without --bare: full system prompt, still one-time dirs and only MCP (arm B')
|
| 6 |
+
codex Codex CLI exec (+ exec resume on early exit), one-time CODEX_HOME, only our MCP tools (arm F)
|
| 7 |
+
rpent_codex RPent (robot harness framework) on Codex: RPent's loop and prompt, the main table's Codex config,
|
| 8 |
+
tools through the episode's tool gateway (docs/18, lffbench/harnesses/rpent.py)
|
| 9 |
+
dsh DeepSeek Harness (`dsh --profile headless`), only our MCP tools, one-time dirs
|
| 10 |
+
|
| 11 |
+
Use scripts/harness_run.py (one session) or scripts/api_batch.py start --harness ... (batches).
|
| 12 |
+
"""
|
| 13 |
+
import json
|
| 14 |
+
import importlib
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
|
| 18 |
+
from .base import EpisodeSpec, HarnessAdapter, HarnessRefused, first_message_text # noqa: F401
|
| 19 |
+
|
| 20 |
+
# A new Codex-based Robot Harness registers here; both single-run and batch CLIs
|
| 21 |
+
# derive their choices, provider and common options from this registry.
|
| 22 |
+
ROBOT_HARNESSES = {
|
| 23 |
+
"rpent_codex": ("rpent", "RPentCodex"),
|
| 24 |
+
"sensenova_codex": ("sensenova", "SenseNovaCodex"),
|
| 25 |
+
"embodied_evo_codex": ("embodied_evo", "EmbodiedEvoCodex"),
|
| 26 |
+
}
|
| 27 |
+
NAMES = ("ours", "claude_code", "claude_code_full", "codex", "dsh", *ROBOT_HARNESSES)
|
| 28 |
+
PROVIDER = dict(claude_code="anthropic", claude_code_full="anthropic", codex="openai", dsh="deepseek",
|
| 29 |
+
**{name: "openai" for name in ROBOT_HARNESSES})
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_adapter(name, **kw):
|
| 33 |
+
if name == "ours":
|
| 34 |
+
from .reference import Reference
|
| 35 |
+
return Reference(**kw)
|
| 36 |
+
if name == "claude_code":
|
| 37 |
+
from .claude_code import ClaudeCode
|
| 38 |
+
return ClaudeCode(**kw)
|
| 39 |
+
if name == "claude_code_full":
|
| 40 |
+
from .claude_code import ClaudeCodeFull
|
| 41 |
+
return ClaudeCodeFull(**kw)
|
| 42 |
+
if name == "codex":
|
| 43 |
+
from .codex import Codex
|
| 44 |
+
return Codex(**kw)
|
| 45 |
+
if name == "dsh":
|
| 46 |
+
from .dsh import DeepSeekHarness
|
| 47 |
+
return DeepSeekHarness(**kw)
|
| 48 |
+
if name in ROBOT_HARNESSES:
|
| 49 |
+
module, cls = ROBOT_HARNESSES[name]
|
| 50 |
+
return getattr(importlib.import_module("." + module, __name__), cls)(**kw)
|
| 51 |
+
raise ValueError(f"unknown harness {name!r}; one of {NAMES}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def render_first_message(ep):
|
| 55 |
+
"""Call `status` once over HTTP (exactly as the reference driver does before its first turn) and build the first
|
| 56 |
+
user message for a native harness. Returns (text, status_json)."""
|
| 57 |
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
| 58 |
+
"scripts"))
|
| 59 |
+
from api_player import call_server # noqa: E402
|
| 60 |
+
st = json.loads(call_server(ep.port, ep.token, "status", {}))
|
| 61 |
+
readme = open(os.path.join(ep.sandbox, "README.md")).read()
|
| 62 |
+
status_json = json.dumps(st)
|
| 63 |
+
return first_message_text(readme, status_json), status_json
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/base.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Harness adapter interface (docs/15 §3).
|
| 2 |
+
|
| 3 |
+
An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log
|
| 4 |
+
dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations).
|
| 5 |
+
Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server /
|
| 6 |
+
reference driver enforce them identically for every harness.
|
| 7 |
+
|
| 8 |
+
name stable harness name (the "harness" column of a table)
|
| 9 |
+
capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source;
|
| 10 |
+
a missing item makes the class definition fail (so the import fails)
|
| 11 |
+
version() the actual installed version (probed before launch)
|
| 12 |
+
prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env
|
| 13 |
+
launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle
|
| 14 |
+
collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason
|
| 15 |
+
audit(h) tool list, preset prompt, memory, state left behind, violations
|
| 16 |
+
"""
|
| 17 |
+
import dataclasses
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import secrets
|
| 21 |
+
import shutil
|
| 22 |
+
import signal
|
| 23 |
+
import subprocess
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
from . import contract as C
|
| 27 |
+
|
| 28 |
+
EVIDENCE = ("launch", "stream", "server", "probe", "preflight")
|
| 29 |
+
|
| 30 |
+
REQUIRED = {
|
| 31 |
+
"only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use",
|
| 32 |
+
"images_reach_model": "view_images returns the image bytes to the model unchanged",
|
| 33 |
+
"non_persistent_session": "nothing of the session is written to disk for later runs",
|
| 34 |
+
"pinned_version": "the harness version (and binary hash) is recorded and pinned",
|
| 35 |
+
"machine_readable_events": "a machine-readable event stream of the whole run",
|
| 36 |
+
"tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)",
|
| 37 |
+
"model_and_effort": "model and reasoning effort can be set and are visible in the request",
|
| 38 |
+
}
|
| 39 |
+
FORBIDDEN = {
|
| 40 |
+
"persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)",
|
| 41 |
+
"instruction_file_injection": "instruction files picked up from the work / config / home dir",
|
| 42 |
+
"web_access": "web search / fetch",
|
| 43 |
+
"host_file_read": "reading host files outside the episode workspace",
|
| 44 |
+
"builtin_shell": "a shell of the harness itself (outside our jailed shell tool)",
|
| 45 |
+
"subagent_delegation": "spawning sub-agents",
|
| 46 |
+
"background_execution": "background tasks that outlive a tool call",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclasses.dataclass(frozen=True)
|
| 51 |
+
class Cap:
|
| 52 |
+
status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial"
|
| 53 |
+
evidence: str # one of EVIDENCE
|
| 54 |
+
note: str = ""
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")
|
| 58 |
+
NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
|
| 59 |
+
NO_PROXY_LOCAL = "127.0.0.1,localhost,::1"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def proxy_env(environ=None):
|
| 63 |
+
"""The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines
|
| 64 |
+
that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list.
|
| 65 |
+
Not part of config_sha256 (machine plumbing, not harness configuration)."""
|
| 66 |
+
environ = os.environ if environ is None else environ
|
| 67 |
+
e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)}
|
| 68 |
+
if e:
|
| 69 |
+
e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS})
|
| 70 |
+
return e
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class CapabilityError(TypeError):
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check_capabilities(name, caps):
|
| 78 |
+
if not isinstance(caps, dict):
|
| 79 |
+
raise CapabilityError(f"{name}: capabilities must be a dict")
|
| 80 |
+
missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps]
|
| 81 |
+
extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN]
|
| 82 |
+
if missing or extra:
|
| 83 |
+
raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}")
|
| 84 |
+
for k, c in caps.items():
|
| 85 |
+
if not isinstance(c, Cap) or c.evidence not in EVIDENCE:
|
| 86 |
+
raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})")
|
| 87 |
+
ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial")
|
| 88 |
+
if c.status not in ok:
|
| 89 |
+
raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class HarnessRefused(RuntimeError):
|
| 93 |
+
"""Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one."""
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@dataclasses.dataclass
|
| 97 |
+
class EpisodeSpec:
|
| 98 |
+
session_path: str
|
| 99 |
+
log_dir: str
|
| 100 |
+
sandbox: str
|
| 101 |
+
port: int
|
| 102 |
+
token: str
|
| 103 |
+
max_tool_calls: int
|
| 104 |
+
model: str
|
| 105 |
+
effort: str
|
| 106 |
+
provider: str = ""
|
| 107 |
+
task: str = ""
|
| 108 |
+
seed: int = 0
|
| 109 |
+
extra: dict = dataclasses.field(default_factory=dict)
|
| 110 |
+
|
| 111 |
+
@classmethod
|
| 112 |
+
def from_session(cls, session_path, model, effort, provider="", **extra):
|
| 113 |
+
session_path = os.path.abspath(session_path)
|
| 114 |
+
log_dir = os.path.dirname(session_path)
|
| 115 |
+
sess = json.load(open(session_path))
|
| 116 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 117 |
+
st = C.session_start(log_dir)
|
| 118 |
+
return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]),
|
| 119 |
+
token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort,
|
| 120 |
+
provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclasses.dataclass
|
| 124 |
+
class LaunchSpec:
|
| 125 |
+
argv: list # full argv (the first message may be one element)
|
| 126 |
+
env: dict # the complete environment of the harness process (nothing else is inherited)
|
| 127 |
+
cwd: str
|
| 128 |
+
run_dir: str = "" # one-time dir tree, removed after audit
|
| 129 |
+
state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...)
|
| 130 |
+
first_message: str = ""
|
| 131 |
+
config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote
|
| 132 |
+
stdout_path: str = ""
|
| 133 |
+
stderr_path: str = ""
|
| 134 |
+
redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log
|
| 135 |
+
preflight: dict = dataclasses.field(default_factory=dict)
|
| 136 |
+
timeout_s: float = 10800
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
@dataclasses.dataclass
|
| 140 |
+
class RunHandle:
|
| 141 |
+
spec: LaunchSpec
|
| 142 |
+
ep: EpisodeSpec
|
| 143 |
+
proc: object = None
|
| 144 |
+
pid: int = 0
|
| 145 |
+
t_start: float = 0.0
|
| 146 |
+
t_end: float = 0.0
|
| 147 |
+
exit_code: int = None
|
| 148 |
+
exit_reason: str = ""
|
| 149 |
+
env_observed_keys: list = None # read from /proc/<pid>/environ right after the start
|
| 150 |
+
info: dict = dataclasses.field(default_factory=dict)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def env_keys_of(pid):
|
| 154 |
+
try:
|
| 155 |
+
raw = open(f"/proc/{pid}/environ", "rb").read()
|
| 156 |
+
except OSError:
|
| 157 |
+
return None
|
| 158 |
+
return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv})
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def new_run_dir(root="/tmp/lffrun"):
|
| 162 |
+
"""/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses)."""
|
| 163 |
+
os.makedirs(root, exist_ok=True)
|
| 164 |
+
while True:
|
| 165 |
+
d = os.path.join(root, secrets.token_hex(6))
|
| 166 |
+
try:
|
| 167 |
+
os.mkdir(d, 0o700)
|
| 168 |
+
return d
|
| 169 |
+
except FileExistsError:
|
| 170 |
+
continue
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def binary_info(path):
|
| 174 |
+
real = os.path.realpath(path)
|
| 175 |
+
return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class HarnessAdapter:
|
| 179 |
+
name = None
|
| 180 |
+
capabilities = None
|
| 181 |
+
uses_mcp = False
|
| 182 |
+
uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for
|
| 183 |
+
# this adapter: MCP adapters through the MCP server, framework adapters
|
| 184 |
+
# (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN
|
| 185 |
+
clean_dirs = () # keys of spec.state_dirs that must be empty at launch
|
| 186 |
+
clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json)
|
| 187 |
+
ancestor_files = () # instruction files that must not exist in the work dir or any ancestor
|
| 188 |
+
unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read)
|
| 189 |
+
jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4)
|
| 190 |
+
can_resume = False # resume(): the CLI can continue its session with one more user message
|
| 191 |
+
|
| 192 |
+
def clean_state_problems(self, spec):
|
| 193 |
+
"""Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an
|
| 194 |
+
ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md)."""
|
| 195 |
+
p = []
|
| 196 |
+
if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd):
|
| 197 |
+
p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}")
|
| 198 |
+
for k in self.clean_dirs:
|
| 199 |
+
d = spec.state_dirs.get(k)
|
| 200 |
+
left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else []
|
| 201 |
+
if left:
|
| 202 |
+
p.append(f"{k} dir not empty: {sorted(left)[:5]}")
|
| 203 |
+
d = spec.cwd
|
| 204 |
+
while d and d != "/":
|
| 205 |
+
d = os.path.dirname(d)
|
| 206 |
+
for f in self.ancestor_files:
|
| 207 |
+
if os.path.exists(os.path.join(d, f)):
|
| 208 |
+
p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}")
|
| 209 |
+
return p
|
| 210 |
+
|
| 211 |
+
def __init_subclass__(cls, **kw):
|
| 212 |
+
super().__init_subclass__(**kw)
|
| 213 |
+
if cls.name is None:
|
| 214 |
+
raise CapabilityError(f"{cls.__name__}: no name")
|
| 215 |
+
check_capabilities(cls.name, cls.capabilities)
|
| 216 |
+
|
| 217 |
+
# -------------------------------------------------------------------------------------------- interface
|
| 218 |
+
def version(self):
|
| 219 |
+
raise NotImplementedError
|
| 220 |
+
|
| 221 |
+
def prepare(self, ep, first_message):
|
| 222 |
+
raise NotImplementedError
|
| 223 |
+
|
| 224 |
+
def preflight(self, spec, ep):
|
| 225 |
+
"""Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused."""
|
| 226 |
+
return dict(skipped=True)
|
| 227 |
+
|
| 228 |
+
def collect(self, h):
|
| 229 |
+
raise NotImplementedError
|
| 230 |
+
|
| 231 |
+
def audit(self, h):
|
| 232 |
+
raise NotImplementedError
|
| 233 |
+
|
| 234 |
+
# -------------------------------------------------------------------------------------------- shared
|
| 235 |
+
def mcp_server_command(self, python, script, args):
|
| 236 |
+
"""(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it."""
|
| 237 |
+
if self.jail is not None:
|
| 238 |
+
return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"})
|
| 239 |
+
return python, [script] + list(args)
|
| 240 |
+
|
| 241 |
+
def jailed_argv(self, argv, env, cwd, dirs):
|
| 242 |
+
"""argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back."""
|
| 243 |
+
return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv)
|
| 244 |
+
|
| 245 |
+
def jail_info(self):
|
| 246 |
+
return self.jail.info() if self.jail is not None else dict(enabled=False)
|
| 247 |
+
|
| 248 |
+
def auth_info(self):
|
| 249 |
+
"""How the harness authenticates to the model API (for harness.json; never a secret)."""
|
| 250 |
+
return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {}))
|
| 251 |
+
|
| 252 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 253 |
+
if not self.unsafe_skip_clean_check:
|
| 254 |
+
probs = self.clean_state_problems(spec)
|
| 255 |
+
if probs:
|
| 256 |
+
spec.preflight = dict(problems=probs)
|
| 257 |
+
raise HarnessRefused("clean-state check: " + "; ".join(probs))
|
| 258 |
+
spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep)
|
| 259 |
+
out = open(spec.stdout_path, "wb")
|
| 260 |
+
err = open(spec.stderr_path, "wb")
|
| 261 |
+
h = RunHandle(spec=spec, ep=ep, t_start=time.time())
|
| 262 |
+
argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 263 |
+
h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 264 |
+
stderr=err, start_new_session=True)
|
| 265 |
+
h.pid = h.proc.pid
|
| 266 |
+
for _ in range(20): # the exec has happened once /proc/<pid>/environ differs from ours
|
| 267 |
+
keys = env_keys_of(h.pid)
|
| 268 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 269 |
+
break
|
| 270 |
+
time.sleep(0.05)
|
| 271 |
+
h.env_observed_keys = keys # retain the observed sample; a second read can race setpriv/exec
|
| 272 |
+
return h
|
| 273 |
+
|
| 274 |
+
def resume_argv(self, h, message):
|
| 275 |
+
"""argv that continues the run's session with one more user message (adapters with can_resume)."""
|
| 276 |
+
raise NotImplementedError
|
| 277 |
+
|
| 278 |
+
def resume(self, h, message):
|
| 279 |
+
"""Continue the run's session with one more user message, after the CLI exited before the episode was over
|
| 280 |
+
(scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output
|
| 281 |
+
is appended to the same stdout / stderr files."""
|
| 282 |
+
spec = h.spec
|
| 283 |
+
argv = self.resume_argv(h, message)
|
| 284 |
+
out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab")
|
| 285 |
+
jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
|
| 286 |
+
h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
|
| 287 |
+
stderr=err, start_new_session=True)
|
| 288 |
+
h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, ""
|
| 289 |
+
keys = None
|
| 290 |
+
for _ in range(20):
|
| 291 |
+
keys = env_keys_of(h.pid)
|
| 292 |
+
if keys is not None and set(keys) == set(spec.env):
|
| 293 |
+
break
|
| 294 |
+
time.sleep(0.05)
|
| 295 |
+
h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message,
|
| 296 |
+
argv=[("<message>" if x == message else x) for x in argv],
|
| 297 |
+
env_observed_keys=keys))
|
| 298 |
+
return h
|
| 299 |
+
|
| 300 |
+
def wait(self, h, timeout=None):
|
| 301 |
+
try:
|
| 302 |
+
h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s)
|
| 303 |
+
h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}"
|
| 304 |
+
except subprocess.TimeoutExpired:
|
| 305 |
+
self.kill(h)
|
| 306 |
+
h.exit_reason = "timeout"
|
| 307 |
+
h.t_end = time.time()
|
| 308 |
+
return h
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def kill(h):
|
| 312 |
+
try:
|
| 313 |
+
os.killpg(h.proc.pid, signal.SIGTERM)
|
| 314 |
+
h.exit_code = h.proc.wait(timeout=20)
|
| 315 |
+
except ProcessLookupError:
|
| 316 |
+
pass
|
| 317 |
+
except subprocess.TimeoutExpired:
|
| 318 |
+
os.killpg(h.proc.pid, signal.SIGKILL)
|
| 319 |
+
h.exit_code = h.proc.wait()
|
| 320 |
+
|
| 321 |
+
def logged_argv(self, spec):
|
| 322 |
+
return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)]
|
| 323 |
+
|
| 324 |
+
def cleanup(self, spec):
|
| 325 |
+
if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir):
|
| 326 |
+
shutil.rmtree(spec.run_dir, ignore_errors=True)
|
| 327 |
+
for d in spec.state_dirs.values():
|
| 328 |
+
if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d):
|
| 329 |
+
shutil.rmtree(d, ignore_errors=True)
|
| 330 |
+
if self.jail is not None:
|
| 331 |
+
self.jail.close()
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def gateway_env(log_dir):
|
| 335 |
+
"""{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose
|
| 336 |
+
process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before
|
| 337 |
+
launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the
|
| 338 |
+
gateway's, never robot_server's."""
|
| 339 |
+
d = json.load(open(os.path.join(log_dir, "gateway.json")))
|
| 340 |
+
return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]}
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def snapshot_tree(root):
|
| 344 |
+
"""Relative paths of all files under root (to list what a harness left behind)."""
|
| 345 |
+
out = []
|
| 346 |
+
for dp, dn, fn in os.walk(root):
|
| 347 |
+
for f in fn:
|
| 348 |
+
out.append(os.path.relpath(os.path.join(dp, f), root))
|
| 349 |
+
return sorted(out)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def first_message_text(readme, status_json):
|
| 353 |
+
"""What a native harness gets as its first user message: the reference driver's instructions (preamble + README,
|
| 354 |
+
byte-identical) followed by its first user turn (the status report). The reference driver sends the same two
|
| 355 |
+
strings as system prompt and first user message; native harnesses keep their own system prompt."""
|
| 356 |
+
from .contract import tool_schemas
|
| 357 |
+
_, preamble = tool_schemas()
|
| 358 |
+
return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def reference_instructions(readme):
|
| 362 |
+
from .contract import tool_schemas
|
| 363 |
+
_, preamble = tool_schemas()
|
| 364 |
+
return preamble + readme
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/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/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/codex.py
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Codex CLI as a native harness (arm F; flags measured in research_notes/harness接入调研/02 §2.3, Codex 0.156).
|
| 2 |
+
|
| 3 |
+
Launch: process env exactly the whitelist (env -i equivalent), a brand-new empty CODEX_HOME and HOME (one-time, under
|
| 4 |
+
/tmp/lffstate/<hex>), work dir /tmp/lffrun/<12 hex>, `codex exec --json --skip-git-repo-check --ignore-user-config
|
| 5 |
+
--ignore-rules -s read-only`, ~20 features disabled, project docs / permissions / environment context /
|
| 6 |
+
collaboration-mode / skills instructions off, web search off, and only our MCP server with
|
| 7 |
+
default_tools_approval_mode="approve" (otherwise exec mode silently denies MCP calls).
|
| 8 |
+
|
| 9 |
+
Early exit: `codex exec` ends when the model replies without a tool call, also when the episode is not over (measured
|
| 10 |
+
2026-10-19, cx_pilot6b: gpt-6-astra stopped after a failed first attempt, "I stopped after the one authorized
|
| 11 |
+
attempt", although the finish reply said attempt 2 of 3 starts now). scripts/harness_run.py then sends the reference
|
| 12 |
+
driver's nudge as a user turn with `codex exec resume <thread>` (resume_argv), at most api_player.MAX_NO_TOOL times in
|
| 13 |
+
a row. Hence no --ephemeral: the session is kept in the one-time CODEX_HOME (memories off; removed after the run).
|
| 14 |
+
Measured with 0.163 against the fake server: the resumed request has the same developer messages, tools, model and
|
| 15 |
+
parameters as the first, then the earlier turns and the nudge as a user message.
|
| 16 |
+
|
| 17 |
+
The model API is a custom Responses provider "lffapi", so the preflight can point exactly the same config at a local
|
| 18 |
+
fake server by changing only base_url. Two ways to authenticate (auth=):
|
| 19 |
+
apikey env_key OPENAI_API_KEY (api_env), default endpoint the official API
|
| 20 |
+
chatgpt a ChatGPT subscription login (no API key; same as RPent's codex planner reusing `codex login`): the
|
| 21 |
+
provider gets requires_openai_auth=true (requests carry the login's bearer + chatgpt-account-id), default
|
| 22 |
+
endpoint the ChatGPT Codex backend; a copy of auth.json from the source CODEX_HOME is put into the one-time
|
| 23 |
+
CODEX_HOME (the only file allowed there at launch). If Codex refreshes the login during a run, the refreshed
|
| 24 |
+
auth.json is written back to the source (refresh tokens rotate), unless the source changed meanwhile.
|
| 25 |
+
Launch is refused when the source login is close to its refresh (parallel copies would each rotate it).
|
| 26 |
+
Measured with 0.163 against the fake server: same body keys and headers in both modes plus chatgpt-account-id; the
|
| 27 |
+
preset differs (exec tool description), so pins are per auth mode (pin name codex-chatgpt).
|
| 28 |
+
The calling environment's HTTP(S) proxy is passed through (base.proxy_env; NO_PROXY = loopback only).
|
| 29 |
+
|
| 30 |
+
Model configuration (catalog=, user 2026-10-20): Codex picks the system prompt, tool form and context window per
|
| 31 |
+
model from its model catalog. We always pass an explicit model_catalog_json written into the one-time CODEX_HOME, so
|
| 32 |
+
nothing depends on the catalog the subscription backend serves on the day:
|
| 33 |
+
generic (main table, every model) one entry built from codex_catalogs/generic_<version>.json: what Codex sends for a
|
| 34 |
+
model it has no entry for (its generic Codex CLI prompt, plain function tools, no code mode); per model only
|
| 35 |
+
slug, input modalities and reasoning levels. Measured with 0.163 against the fake server: the request equals
|
| 36 |
+
the no-catalog fallback for an unknown slug apart from message ids.
|
| 37 |
+
native (control) codex_catalogs/native_<version>.json = `codex debug models --bundled` of that binary: the request
|
| 38 |
+
equals the one without any catalog (GPT: code mode, its own prompt). The pins of before 10-20 stay valid.
|
| 39 |
+
Pins are per catalog (pin name codex[-chatgpt][-generic]).
|
| 40 |
+
|
| 41 |
+
Known, accepted differences in native (code mode) catalogs (reported, not fixable by config in 0.156):
|
| 42 |
+
- code mode: the model sees one `exec` tool (JavaScript in a V8 isolate without fs / network); our tools are nested
|
| 43 |
+
and listed only in ALL_TOOLS; MCP images reach the model only if the model's JS calls image(...)
|
| 44 |
+
- apply_patch (blocked by the read-only sandbox), clock, 3 MCP-resource tools (our server has no resources),
|
| 45 |
+
request_user_input, and 6 collaboration.* sub-agent tools cannot be removed; a sub-agent call is an audit violation
|
| 46 |
+
- --json has tokens but no dollar cost
|
| 47 |
+
Fail-closed launch: the preflight checks the top-level tools, the exec nested-tool list (ALL_TOOLS, printed by a
|
| 48 |
+
scripted exec call), the developer (preset) messages and request parameters against the pin.
|
| 49 |
+
"""
|
| 50 |
+
import base64
|
| 51 |
+
import datetime
|
| 52 |
+
import fcntl
|
| 53 |
+
import json
|
| 54 |
+
import os
|
| 55 |
+
import re
|
| 56 |
+
import shutil
|
| 57 |
+
import sqlite3
|
| 58 |
+
import subprocess
|
| 59 |
+
import sys
|
| 60 |
+
import time
|
| 61 |
+
|
| 62 |
+
from . import contract as C
|
| 63 |
+
from . import pins
|
| 64 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 65 |
+
new_run_dir, proxy_env, snapshot_tree)
|
| 66 |
+
from .fakeapi import FakeResponses
|
| 67 |
+
from .trajectory import TrajWriter
|
| 68 |
+
|
| 69 |
+
ROOT = C.ROOT
|
| 70 |
+
MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
|
| 71 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 72 |
+
OFFICIAL_API = "https://api.openai.com/v1"
|
| 73 |
+
CHATGPT_BACKEND = "https://chatgpt.com/backend-api/codex"
|
| 74 |
+
AUTH_FILE = "auth.json"
|
| 75 |
+
AUTH_LOCK = "/tmp/lffstate/.codex_auth.lock"
|
| 76 |
+
MAX_LOGIN_AGE_H = 8 * 24 # codex-rs TOKEN_REFRESH_INTERVAL (8 days, from the source, not measured here): a login
|
| 77 |
+
# older than this is refreshed at start, by every parallel copy
|
| 78 |
+
MIN_ACCESS_LEFT_H = 24 # an access token expiring during a run makes the run's copy refresh it
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _jwt_claims(tok):
|
| 82 |
+
try:
|
| 83 |
+
p = tok.split(".")[1]
|
| 84 |
+
return json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4)))
|
| 85 |
+
except (IndexError, ValueError, AttributeError):
|
| 86 |
+
return {}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def chatgpt_login_status(home):
|
| 90 |
+
"""-> dict(ok, problem, last_refresh_h, access_token_valid_h) of the ChatGPT login in home/auth.json. No secret
|
| 91 |
+
leaves this function."""
|
| 92 |
+
src = os.path.join(home, AUTH_FILE)
|
| 93 |
+
try:
|
| 94 |
+
with open(src) as f:
|
| 95 |
+
a = json.load(f)
|
| 96 |
+
except (OSError, ValueError) as e:
|
| 97 |
+
return dict(ok=False, problem=f"cannot read {src}: {type(e).__name__}")
|
| 98 |
+
tok = a.get("tokens") or {}
|
| 99 |
+
if a.get("auth_mode") != "chatgpt" or not tok.get("access_token") or not tok.get("refresh_token"):
|
| 100 |
+
return dict(ok=False, problem=f"{src} is not a ChatGPT login (auth_mode={a.get('auth_mode')!r})")
|
| 101 |
+
now = time.time()
|
| 102 |
+
try:
|
| 103 |
+
lr_text = re.sub(r"(\.\d{6})\d+", r"\1", str(a.get("last_refresh")))
|
| 104 |
+
lr = datetime.datetime.fromisoformat(lr_text.replace("Z", "+00:00")).timestamp()
|
| 105 |
+
age_h = (now - lr) / 3600
|
| 106 |
+
except ValueError:
|
| 107 |
+
age_h = float("inf")
|
| 108 |
+
left_h = (float(_jwt_claims(tok["access_token"]).get("exp") or 0) - now) / 3600
|
| 109 |
+
out = dict(ok=True, problem=None, last_refresh_h=round(age_h, 1), access_token_valid_h=round(left_h, 1))
|
| 110 |
+
if age_h >= MAX_LOGIN_AGE_H or left_h < MIN_ACCESS_LEFT_H:
|
| 111 |
+
out.update(ok=False, problem=f"the ChatGPT login in {home} is due for a refresh (last refresh {age_h:.0f} h ago, "
|
| 112 |
+
f"access token valid {left_h:.0f} h): refresh it once outside the benchmark (use "
|
| 113 |
+
f"codex with CODEX_HOME={home}), so that parallel runs do not each rotate it")
|
| 114 |
+
return out
|
| 115 |
+
DISABLE = ["shell_tool", "unified_exec", "view_image", "multi_agent", "multi_agent_v2", "apps", "browser_use",
|
| 116 |
+
"browser_use_external", "computer_use", "image_generation", "plugins", "hooks", "skill_search",
|
| 117 |
+
"tool_suggest", "goals", "sleep_tool", "in_app_browser", "memories", "skill_mcp_dependency_install",
|
| 118 |
+
"realtime_conversation"]
|
| 119 |
+
# what remains in 0.156 after the lock-down (measured): anything else is refused at launch
|
| 120 |
+
EXPECTED_TOP = ["collaboration.followup_task", "collaboration.interrupt_agent", "collaboration.list_agents",
|
| 121 |
+
"collaboration.send_message", "collaboration.spawn_agent", "collaboration.wait_agent",
|
| 122 |
+
"functions.exec", "functions.request_user_input", "functions.request_user_input_async",
|
| 123 |
+
"functions.wait"]
|
| 124 |
+
EXPECTED_ALL_TOOLS = ["apply_patch", "clock__curr_time", "list_mcp_resource_templates", "list_mcp_resources",
|
| 125 |
+
"mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images", "read_mcp_resource"]
|
| 126 |
+
# generic catalog (no code mode), measured with 0.163: our tools are plain functions in the mcp__lff namespace
|
| 127 |
+
EXPECTED_TOP_GENERIC = ["list_mcp_resource_templates", "list_mcp_resources", "mcp__lff.robot", "mcp__lff.shell",
|
| 128 |
+
"mcp__lff.view_images", "read_mcp_resource", "request_user_input"]
|
| 129 |
+
CATALOG_DIR = os.path.join(ROOT, "lffbench", "harnesses", "codex_catalogs")
|
| 130 |
+
CATALOG_FILE = "lff_model_catalog.json" # written into the one-time CODEX_HOME before launch
|
| 131 |
+
CATALOGS = ("generic", "native")
|
| 132 |
+
# generic catalog: the per-model fields (input modalities; the run's reasoning level is always listed)
|
| 133 |
+
TEXT_ONLY_MODELS = {"deepseek-v4-pro": ["text"]} # DeepSeek's Codex guide (read 2026-10-20): v4-pro takes no images
|
| 134 |
+
DEEPSEEK_URL = "https://api.deepseek.com/" # same guide: base_url, wire_api = "responses"
|
| 135 |
+
OPENCODE_GO_URL = "https://opencode.ai/inference/go/openai/v1" # OpenCode Go, Responses API (checked 2026-10-29)
|
| 136 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 137 |
+
OK_ITEMS = ("agent_message", "reasoning", "mcp_tool_call", "error")
|
| 138 |
+
PREFLIGHT_JS = "text(JSON.stringify(ALL_TOOLS));"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def codex_bin():
|
| 142 |
+
return os.environ.get("LFF_CODEX_BIN") or shutil.which("codex") or "codex"
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def toml_str(s):
|
| 146 |
+
return json.dumps(s) # a JSON string literal is a valid TOML basic string
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _norm(s, cwd):
|
| 150 |
+
s = s.replace(cwd, "<CWD>")
|
| 151 |
+
s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
|
| 152 |
+
s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
|
| 153 |
+
s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
|
| 154 |
+
s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "<UUID>", s)
|
| 155 |
+
return s
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _walk_tools(ts, prefix=""):
|
| 159 |
+
out = []
|
| 160 |
+
for t in ts or []:
|
| 161 |
+
if t.get("type") == "namespace":
|
| 162 |
+
out += _walk_tools(t.get("tools"), prefix + t.get("name", "") + ".")
|
| 163 |
+
else:
|
| 164 |
+
out.append(dict(name=prefix + (t.get("name") or t.get("type") or "?"), type=t.get("type"),
|
| 165 |
+
description=t.get("description"), parameters=t.get("parameters"), format=t.get("format")))
|
| 166 |
+
return out
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def request_fingerprint(body, cwd, first_message, expected_top=None):
|
| 170 |
+
problems = []
|
| 171 |
+
items = body.get("input") or []
|
| 172 |
+
top = _walk_tools(body.get("tools"))
|
| 173 |
+
dev, users = [], []
|
| 174 |
+
for it in items:
|
| 175 |
+
if it.get("type") == "additional_tools":
|
| 176 |
+
top += _walk_tools(it.get("tools"))
|
| 177 |
+
elif it.get("type") == "message" and it.get("role") in ("developer", "system"):
|
| 178 |
+
dev.append(_norm("\n".join(c.get("text", "") for c in it.get("content") or []), cwd))
|
| 179 |
+
elif it.get("type") == "message" and it.get("role") == "user":
|
| 180 |
+
users.append(it)
|
| 181 |
+
names = sorted(t["name"] for t in top)
|
| 182 |
+
expected_top = EXPECTED_TOP if expected_top is None else expected_top
|
| 183 |
+
if names != expected_top:
|
| 184 |
+
problems.append(f"top-level tools {names} != expected {expected_top}")
|
| 185 |
+
texts = [c.get("text") for u in users for c in u.get("content") or []]
|
| 186 |
+
if texts != [first_message]:
|
| 187 |
+
problems.append(f"user input is not exactly our first message ({len(texts)} user text blocks)")
|
| 188 |
+
for t in top:
|
| 189 |
+
if t.get("description"):
|
| 190 |
+
t["description"] = _norm(t["description"], cwd)
|
| 191 |
+
params = {k: body.get(k) for k in ("model", "reasoning", "parallel_tool_calls", "store", "include", "text",
|
| 192 |
+
"tool_choice", "instructions", "max_output_tokens", "temperature")}
|
| 193 |
+
meta = body.get("client_metadata") or {}
|
| 194 |
+
try:
|
| 195 |
+
turn_meta = json.loads(meta.get("x-codex-turn-metadata") or "{}")
|
| 196 |
+
except ValueError:
|
| 197 |
+
turn_meta = {}
|
| 198 |
+
sandbox = {k: turn_meta.get(k) for k in ("sandbox", "sandbox_mode")}
|
| 199 |
+
if sandbox.get("sandbox_mode") != "read-only":
|
| 200 |
+
problems.append(f"sandbox {sandbox}")
|
| 201 |
+
fp = dict(tools=sorted(top, key=lambda t: t["name"]), developer=dev, params=params, sandbox=sandbox,
|
| 202 |
+
developer_chars=sum(len(d) for d in dev))
|
| 203 |
+
return fp, problems
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def model_catalog(mode, version, model, modalities=None, effort=None):
|
| 207 |
+
"""-> (catalog dict for model_catalog_json, source file). Refuses (fail-closed) when the version has no catalog
|
| 208 |
+
file or, for native, when the model has no entry."""
|
| 209 |
+
if mode not in CATALOGS:
|
| 210 |
+
raise ValueError(f"catalog must be one of {CATALOGS}, not {mode!r}")
|
| 211 |
+
src = os.path.join(CATALOG_DIR, f"{mode}_{version}.json")
|
| 212 |
+
if not os.path.exists(src):
|
| 213 |
+
raise HarnessRefused(f"no {mode} model catalog for Codex {version} ({os.path.relpath(src, ROOT)})")
|
| 214 |
+
d = json.load(open(src))
|
| 215 |
+
if mode == "native":
|
| 216 |
+
if not any(m.get("slug") == model for m in d.get("models") or []):
|
| 217 |
+
raise HarnessRefused(f"native catalog {os.path.basename(src)} has no entry for {model}")
|
| 218 |
+
return d, src
|
| 219 |
+
e = dict(d["entry"], slug=model, display_name=model)
|
| 220 |
+
modalities = modalities or TEXT_ONLY_MODELS.get(model)
|
| 221 |
+
if modalities:
|
| 222 |
+
e["input_modalities"] = list(modalities)
|
| 223 |
+
levels = [dict(x) for x in e.get("supported_reasoning_levels") or []]
|
| 224 |
+
if effort and effort not in [x.get("effort") for x in levels]:
|
| 225 |
+
levels.append(dict(effort=effort, description=effort))
|
| 226 |
+
e["supported_reasoning_levels"] = levels
|
| 227 |
+
return dict(models=[e]), src
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def all_tools_from(body):
|
| 231 |
+
"""The ALL_TOOLS list printed by the preflight exec call (in the second request)."""
|
| 232 |
+
for it in body.get("input") or []:
|
| 233 |
+
if it.get("type") == "custom_tool_call_output":
|
| 234 |
+
out = it.get("output")
|
| 235 |
+
parts = out if isinstance(out, list) else [dict(text=out)]
|
| 236 |
+
for p in parts:
|
| 237 |
+
t = (p.get("text") or "").strip()
|
| 238 |
+
if t.startswith("["):
|
| 239 |
+
try:
|
| 240 |
+
return json.loads(t)
|
| 241 |
+
except ValueError:
|
| 242 |
+
pass
|
| 243 |
+
return None
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class Codex(HarnessAdapter):
|
| 247 |
+
name = "codex"
|
| 248 |
+
uses_mcp = True
|
| 249 |
+
can_resume = True
|
| 250 |
+
clean_dirs = ("home", "codex_home", "tmp")
|
| 251 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 252 |
+
capabilities = dict(
|
| 253 |
+
only_benchmark_tools=Cap("partial", "preflight", "generic catalog: our 3 MCP tools as functions + residual "
|
| 254 |
+
"resource×3 / request_user_input; native (code mode): reachable only via exec(JS), "
|
| 255 |
+
"residual apply_patch(blocked) / clock / resource×3 / request_user_input / "
|
| 256 |
+
"collaboration×6"),
|
| 257 |
+
images_reach_model=Cap("partial", "probe", "generic: MCP images go to the model; native (code mode): only if "
|
| 258 |
+
"the model's JS calls image(); bytes unchanged either way"),
|
| 259 |
+
non_persistent_session=Cap("yes", "probe", "only this run's thread, in the one-time CODEX_HOME (for exec "
|
| 260 |
+
"resume), removed after the run; memories off"),
|
| 261 |
+
pinned_version=Cap("yes", "launch", "codex --version + binary sha256 in harness.json; pin per version"),
|
| 262 |
+
machine_readable_events=Cap("yes", "stream", "exec --json (items + usage, no cost)"),
|
| 263 |
+
tool_calls_logged=Cap("yes", "stream", "mcp_tool_call items + mcp_transcript + events.jsonl"),
|
| 264 |
+
model_and_effort=Cap("yes", "preflight", "-m / model_reasoning_effort; request reasoning.effort checked"),
|
| 265 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; canaries absent"),
|
| 266 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0 + empty CODEX_HOME (AGENTS.md)"),
|
| 267 |
+
web_access=Cap("absent", "probe", "web_search disabled; exec isolate has no fetch"),
|
| 268 |
+
host_file_read=Cap("absent", "probe", "shell / unified_exec / view_image off; exec has no require; "
|
| 269 |
+
"read-only sandbox"),
|
| 270 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 271 |
+
subagent_delegation=Cap("partial", "preflight", "collaboration.* tools cannot be disabled in 0.156; any use "
|
| 272 |
+
"is an audit violation"),
|
| 273 |
+
background_execution=Cap("partial", "preflight", "functions.wait / long exec yields exist; audited"),
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 277 |
+
python=None, extra_args=None, jail=False, auth="apikey", auth_home=None, catalog="generic",
|
| 278 |
+
modalities=None):
|
| 279 |
+
"""api_env: {"OPENAI_API_KEY": ...} (the provider's env_key, auth="apikey"); base_url: Responses endpoint
|
| 280 |
+
(default: official API / ChatGPT Codex backend by auth). auth="chatgpt": a ChatGPT login copied from
|
| 281 |
+
auth_home (default LFF_CODEX_AUTH_HOME, else the calling CODEX_HOME, else ~/.codex), no API key.
|
| 282 |
+
jail: run the CLI in the native-harness jail (lffbench/harnesses/jail.py, static /proc).
|
| 283 |
+
catalog: "generic" (shared configuration of the main table) or "native" (Codex's own entry for the model);
|
| 284 |
+
modalities: input modalities of a generic entry (default text + image)."""
|
| 285 |
+
if catalog not in CATALOGS:
|
| 286 |
+
raise ValueError(f"catalog must be one of {CATALOGS}, not {catalog!r}")
|
| 287 |
+
self.catalog, self.modalities = catalog, (list(modalities) if modalities else None)
|
| 288 |
+
self._catalog_sha = {} # one-time CODEX_HOME -> sha256 of the catalog written there
|
| 289 |
+
if auth not in ("apikey", "chatgpt"):
|
| 290 |
+
raise ValueError(f"auth must be apikey or chatgpt, not {auth!r}")
|
| 291 |
+
if jail:
|
| 292 |
+
from .jail import HarnessJail
|
| 293 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 294 |
+
self.auth = auth
|
| 295 |
+
self.auth_home = None
|
| 296 |
+
self._auth_copies = {} # one-time CODEX_HOME -> sha256 of the auth.json copied into it
|
| 297 |
+
if auth == "chatgpt":
|
| 298 |
+
self.auth_home = os.path.abspath(auth_home or os.environ.get("LFF_CODEX_AUTH_HOME")
|
| 299 |
+
or os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex"))
|
| 300 |
+
self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
|
| 301 |
+
self.api_env = dict(api_env or {}) if auth == "apikey" else {}
|
| 302 |
+
self.base_url = base_url or (OFFICIAL_API if auth == "apikey" else CHATGPT_BACKEND)
|
| 303 |
+
self.proxy = proxy_env()
|
| 304 |
+
self.timeout_s = timeout_s
|
| 305 |
+
self.pins_dir = pins_dir
|
| 306 |
+
self.allow_unpinned = allow_unpinned
|
| 307 |
+
self.python = python or sys.executable
|
| 308 |
+
self.extra_args = list(extra_args or [])
|
| 309 |
+
self._version = None
|
| 310 |
+
|
| 311 |
+
# ------------------------------------------------------------------------------------------------ auth
|
| 312 |
+
def auth_info(self):
|
| 313 |
+
if self.auth == "apikey":
|
| 314 |
+
return dict(mode="apikey", keys=sorted(self.api_env))
|
| 315 |
+
st = chatgpt_login_status(self.auth_home)
|
| 316 |
+
return dict(mode="chatgpt", source=self.auth_home, **{k: v for k, v in st.items() if k != "ok"})
|
| 317 |
+
|
| 318 |
+
def config_info(self):
|
| 319 |
+
"""For harness.json: which model catalog the run used."""
|
| 320 |
+
return dict(catalog=self.catalog, modalities=self.modalities)
|
| 321 |
+
|
| 322 |
+
def _install_catalog(self, codex_home, ep):
|
| 323 |
+
"""Write the run's model catalog into the one-time CODEX_HOME (the only file besides auth.json allowed there
|
| 324 |
+
at launch). -> (path, sha256, source file, code mode)."""
|
| 325 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, self.modalities, ep.effort)
|
| 326 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 327 |
+
with open(path, "w") as f:
|
| 328 |
+
json.dump(cat, f)
|
| 329 |
+
sha = C.sha256_file(path)
|
| 330 |
+
self._catalog_sha[codex_home] = sha
|
| 331 |
+
entry = next(m for m in cat["models"] if m.get("slug") == ep.model)
|
| 332 |
+
return path, sha, os.path.relpath(src, ROOT), entry.get("tool_mode") == "code_mode_only"
|
| 333 |
+
|
| 334 |
+
def _install_auth(self, codex_home):
|
| 335 |
+
"""auth="chatgpt": copy the source login into a one-time CODEX_HOME (refused if it is due for a refresh)."""
|
| 336 |
+
if self.auth != "chatgpt":
|
| 337 |
+
return
|
| 338 |
+
st = chatgpt_login_status(self.auth_home)
|
| 339 |
+
if not st["ok"]:
|
| 340 |
+
raise HarnessRefused("ChatGPT login: " + st["problem"])
|
| 341 |
+
dst = os.path.join(codex_home, AUTH_FILE)
|
| 342 |
+
with open(os.path.join(self.auth_home, AUTH_FILE), "rb") as f:
|
| 343 |
+
data = f.read()
|
| 344 |
+
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 345 |
+
with os.fdopen(fd, "wb") as f:
|
| 346 |
+
f.write(data)
|
| 347 |
+
self._auth_copies[codex_home] = C.sha256_file(dst)
|
| 348 |
+
|
| 349 |
+
def _sync_auth_back(self, codex_home):
|
| 350 |
+
"""After a run: if Codex refreshed the login in the run's copy, write it back to the source (refresh tokens
|
| 351 |
+
rotate, the source's old one may no longer work), unless the source changed since the copy. -> note or None."""
|
| 352 |
+
copied = self._auth_copies.pop(codex_home, None)
|
| 353 |
+
p = os.path.join(codex_home, AUTH_FILE)
|
| 354 |
+
if copied is None or not os.path.exists(p) or C.sha256_file(p) == copied:
|
| 355 |
+
return None
|
| 356 |
+
try:
|
| 357 |
+
with open(p, "rb") as f:
|
| 358 |
+
data = f.read()
|
| 359 |
+
new = json.loads(data)
|
| 360 |
+
except (OSError, ValueError):
|
| 361 |
+
return "auth.json in the run's CODEX_HOME changed and is unreadable: not written back"
|
| 362 |
+
if new.get("auth_mode") != "chatgpt" or not (new.get("tokens") or {}).get("refresh_token"):
|
| 363 |
+
return "auth.json in the run's CODEX_HOME changed but holds no ChatGPT login: not written back"
|
| 364 |
+
src = os.path.join(self.auth_home, AUTH_FILE)
|
| 365 |
+
os.makedirs(os.path.dirname(AUTH_LOCK), exist_ok=True)
|
| 366 |
+
with open(AUTH_LOCK, "a") as lk:
|
| 367 |
+
fcntl.flock(lk, fcntl.LOCK_EX)
|
| 368 |
+
if C.sha256_file(src) != copied:
|
| 369 |
+
return "the run refreshed its login copy, but the source auth.json changed meanwhile: not written back"
|
| 370 |
+
tmp = src + ".lff-tmp"
|
| 371 |
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 372 |
+
with os.fdopen(fd, "wb") as f:
|
| 373 |
+
f.write(data)
|
| 374 |
+
os.replace(tmp, src)
|
| 375 |
+
return "the run refreshed the ChatGPT login: refreshed auth.json written back to the source"
|
| 376 |
+
|
| 377 |
+
def version(self):
|
| 378 |
+
if self._version is None:
|
| 379 |
+
b = codex_bin()
|
| 380 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 381 |
+
CODEX_HOME="/nonexistent"),
|
| 382 |
+
capture_output=True, text=True, timeout=60)
|
| 383 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 384 |
+
self._version = dict(version=v, binary=binary_info(b))
|
| 385 |
+
return self._version
|
| 386 |
+
|
| 387 |
+
def pin_key(self, ep):
|
| 388 |
+
v = self.version()
|
| 389 |
+
name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
|
| 390 |
+
name += "" if self.catalog == "native" else f"-{self.catalog}"
|
| 391 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 392 |
+
|
| 393 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 394 |
+
def config_args(self, ep, session_path, base_url, codex_home):
|
| 395 |
+
mcp_cmd, mcp_args = self.mcp_server_command(self.python, MCP_SCRIPT, ["--session", session_path] if session_path
|
| 396 |
+
else ["--schema-only"])
|
| 397 |
+
c = ["model_reasoning_effort=" + toml_str(ep.effort),
|
| 398 |
+
"project_doc_max_bytes=0", "include_permissions_instructions=false", "include_environment_context=false",
|
| 399 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 400 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 401 |
+
'model_provider="lffapi"', 'model_providers.lffapi.name="lffapi"',
|
| 402 |
+
"model_providers.lffapi.base_url=" + toml_str(base_url), 'model_providers.lffapi.wire_api="responses"',
|
| 403 |
+
('model_providers.lffapi.env_key="OPENAI_API_KEY"' if self.auth == "apikey"
|
| 404 |
+
else "model_providers.lffapi.requires_openai_auth=true"),
|
| 405 |
+
"mcp_servers.lff.command=" + toml_str(mcp_cmd),
|
| 406 |
+
"mcp_servers.lff.args=[" + ",".join(toml_str(x) for x in mcp_args) + "]",
|
| 407 |
+
"mcp_servers.lff.env={PATH=" + toml_str(BASE_PATH) + "}",
|
| 408 |
+
'mcp_servers.lff.enabled_tools=["robot","shell","view_images"]',
|
| 409 |
+
'mcp_servers.lff.default_tools_approval_mode="approve"', "mcp_servers.lff.required=true",
|
| 410 |
+
"mcp_servers.lff.startup_timeout_sec=60", "mcp_servers.lff.tool_timeout_sec=900",
|
| 411 |
+
"model_catalog_json=" + toml_str(os.path.join(codex_home, CATALOG_FILE))]
|
| 412 |
+
return c
|
| 413 |
+
|
| 414 |
+
def argv(self, ep, session_path, base_url, first_message, codex_home):
|
| 415 |
+
a = [codex_bin(), "exec", "--json", "--skip-git-repo-check", "--ignore-user-config",
|
| 416 |
+
"--ignore-rules", "-s", "read-only", "-m", ep.model]
|
| 417 |
+
for f in DISABLE:
|
| 418 |
+
a += ["--disable", f]
|
| 419 |
+
for c in self.config_args(ep, session_path, base_url, codex_home):
|
| 420 |
+
a += ["-c", c]
|
| 421 |
+
return a + self.extra_args + [first_message]
|
| 422 |
+
|
| 423 |
+
@staticmethod
|
| 424 |
+
def thread_id(stdout_path):
|
| 425 |
+
t = None
|
| 426 |
+
for line in open(stdout_path, encoding="utf-8", errors="replace"):
|
| 427 |
+
if line.startswith("{") and '"thread.started"' in line:
|
| 428 |
+
t = json.loads(line).get("thread_id") or t
|
| 429 |
+
return t
|
| 430 |
+
|
| 431 |
+
def resume_argv(self, h, message):
|
| 432 |
+
"""`codex exec resume <thread> <message>` with the launch's flags and config; resume has no -s, so the
|
| 433 |
+
sandbox goes in as sandbox_mode."""
|
| 434 |
+
thread = self.thread_id(h.spec.stdout_path)
|
| 435 |
+
if not thread:
|
| 436 |
+
raise HarnessRefused("resume: no thread id in the event stream")
|
| 437 |
+
a = list(h.spec.argv[:-1]) # without the first message
|
| 438 |
+
i = a.index("exec")
|
| 439 |
+
rest = a[i + 1:]
|
| 440 |
+
j = rest.index("-s")
|
| 441 |
+
mode = rest[j + 1]
|
| 442 |
+
del rest[j:j + 2]
|
| 443 |
+
return a[:i + 1] + ["resume"] + rest + ["-c", "sandbox_mode=" + toml_str(mode), thread, message]
|
| 444 |
+
|
| 445 |
+
def env(self, state):
|
| 446 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], CODEX_HOME=state["codex_home"], TMPDIR=state["tmp"],
|
| 447 |
+
LANG="C.UTF-8")
|
| 448 |
+
e.update(self.proxy)
|
| 449 |
+
e.update(self.api_env)
|
| 450 |
+
return e
|
| 451 |
+
|
| 452 |
+
def _state_dirs(self, hexname=None):
|
| 453 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 454 |
+
os.makedirs(root, exist_ok=True)
|
| 455 |
+
state = dict(state=root, home=os.path.join(root, "home"), codex_home=os.path.join(root, "codex_home"),
|
| 456 |
+
tmp=os.path.join(root, "tmp"))
|
| 457 |
+
for k in ("home", "codex_home", "tmp"):
|
| 458 |
+
os.makedirs(state[k], exist_ok=True)
|
| 459 |
+
return state
|
| 460 |
+
|
| 461 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 462 |
+
work = new_run_dir("/tmp/lffrun")
|
| 463 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 464 |
+
if self.jail is not None:
|
| 465 |
+
self.jail.stderr_dir = ep.log_dir
|
| 466 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 467 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 468 |
+
cat_path, cat_sha, cat_src, code_mode = self._install_catalog(state["codex_home"], ep)
|
| 469 |
+
argv = self.argv(ep, ep.session_path, self.base_url, first_message, state["codex_home"])
|
| 470 |
+
return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
|
| 471 |
+
first_message=first_message, stdout_path=os.path.join(ep.log_dir, "codex_events.jsonl"),
|
| 472 |
+
stderr_path=os.path.join(ep.log_dir, "codex_stderr.txt"),
|
| 473 |
+
redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
|
| 474 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 475 |
+
catalog=self.catalog, code_mode=code_mode)),
|
| 476 |
+
timeout_s=self.timeout_s)
|
| 477 |
+
|
| 478 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 479 |
+
self._install_auth(spec.state_dirs["codex_home"])
|
| 480 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 481 |
+
|
| 482 |
+
def cleanup(self, spec):
|
| 483 |
+
self._sync_auth_back(spec.state_dirs.get("codex_home", ""))
|
| 484 |
+
super().cleanup(spec)
|
| 485 |
+
|
| 486 |
+
def config_sha256(self, spec, ep):
|
| 487 |
+
"""Hash of everything configurable (argv without the first message, env values except keys / one-time dirs)."""
|
| 488 |
+
argv = [re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", a.replace(ep.session_path, "<SESSION>"))
|
| 489 |
+
.replace(spec.state_dirs["codex_home"], "<CODEX_HOME>") for a in self.logged_argv(spec)[1:-1]]
|
| 490 |
+
env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
|
| 491 |
+
if k not in ("HOME", "CODEX_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
|
| 492 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 493 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat))
|
| 494 |
+
|
| 495 |
+
# ------------------------------------------------------------------------------------------------ preflight
|
| 496 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 497 |
+
t0 = time.time()
|
| 498 |
+
code_mode = (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True)
|
| 499 |
+
script = [[("exec", PREFLIGHT_JS)], [("text", "preflight ok")]] if code_mode else [[("text", "preflight ok")]]
|
| 500 |
+
fake = FakeResponses(script, record_dir=record_dir).start()
|
| 501 |
+
pre = self._state_dirs()
|
| 502 |
+
try:
|
| 503 |
+
self._install_auth(pre["codex_home"])
|
| 504 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 505 |
+
argv = self.argv(ep, None, fake.base_url, spec.first_message, pre["codex_home"])
|
| 506 |
+
env = self.env(pre)
|
| 507 |
+
if self.auth == "apikey":
|
| 508 |
+
env["OPENAI_API_KEY"] = "sk-preflight-not-a-key"
|
| 509 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 510 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
|
| 511 |
+
reqs = fake.model_requests()
|
| 512 |
+
if len(reqs) < (2 if code_mode else 1):
|
| 513 |
+
raise HarnessRefused(f"preflight: {len(reqs)} model requests (rc={r.returncode}): "
|
| 514 |
+
f"{r.stderr.decode('utf-8', 'replace')[-800:]}")
|
| 515 |
+
fp, problems = request_fingerprint(reqs[0][1], spec.cwd, spec.first_message,
|
| 516 |
+
EXPECTED_TOP if code_mode else EXPECTED_TOP_GENERIC)
|
| 517 |
+
at_names = None
|
| 518 |
+
if code_mode: # our tools are nested in exec: the scripted exec call prints them
|
| 519 |
+
at = all_tools_from(reqs[1][1])
|
| 520 |
+
if at is None:
|
| 521 |
+
problems.append("exec preflight did not print ALL_TOOLS")
|
| 522 |
+
at = []
|
| 523 |
+
at_names = sorted(t.get("name") if isinstance(t, dict) else str(t) for t in at)
|
| 524 |
+
if at_names != EXPECTED_ALL_TOOLS:
|
| 525 |
+
problems.append(f"ALL_TOOLS {at_names} != expected {EXPECTED_ALL_TOOLS}")
|
| 526 |
+
fp["all_tools"] = [({k: (_norm(v, spec.cwd) if isinstance(v, str) else v) for k, v in t.items()}
|
| 527 |
+
if isinstance(t, dict) else t) for t in sorted(at, key=lambda t: json.dumps(t))]
|
| 528 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 529 |
+
if effort != ep.effort:
|
| 530 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 531 |
+
if os.listdir(spec.cwd):
|
| 532 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 533 |
+
fp_sha = C.sha256_json(fp)
|
| 534 |
+
out = dict(fingerprint_sha256=fp_sha, developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 535 |
+
top_tools=[t["name"] for t in fp["tools"]], all_tools=at_names, code_mode=code_mode,
|
| 536 |
+
catalog=self.catalog, effort_in_request=effort,
|
| 537 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"], dt_s=round(time.time() - t0, 1),
|
| 538 |
+
problems=problems)
|
| 539 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 540 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 541 |
+
out["fingerprint"] = fp
|
| 542 |
+
if problems:
|
| 543 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 544 |
+
if pin is None:
|
| 545 |
+
if not self.allow_unpinned:
|
| 546 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 547 |
+
f"with --write-pins after the self-check passes)")
|
| 548 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 549 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 550 |
+
raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
|
| 551 |
+
f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
|
| 552 |
+
else:
|
| 553 |
+
out["pin_status"] = "match"
|
| 554 |
+
return out
|
| 555 |
+
finally:
|
| 556 |
+
fake.stop()
|
| 557 |
+
self._sync_auth_back(pre["codex_home"])
|
| 558 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 559 |
+
|
| 560 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 561 |
+
def collect(self, h):
|
| 562 |
+
spec, ep = h.spec, h.ep
|
| 563 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 564 |
+
thread, usage, items, errors = None, dict(input=0, cached=0, output=0, reasoning=0), [], []
|
| 565 |
+
for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
|
| 566 |
+
if not line.startswith("{"):
|
| 567 |
+
continue
|
| 568 |
+
d = json.loads(line)
|
| 569 |
+
t = d.get("type")
|
| 570 |
+
if t == "thread.started":
|
| 571 |
+
thread = d.get("thread_id")
|
| 572 |
+
elif t == "turn.completed":
|
| 573 |
+
u = d.get("usage") or {}
|
| 574 |
+
usage["input"] += u.get("input_tokens") or 0
|
| 575 |
+
usage["cached"] += u.get("cached_input_tokens") or 0
|
| 576 |
+
usage["output"] += u.get("output_tokens") or 0
|
| 577 |
+
usage["reasoning"] += u.get("reasoning_output_tokens") or 0
|
| 578 |
+
elif t in ("error", "turn.failed"):
|
| 579 |
+
errors.append(d)
|
| 580 |
+
elif t == "item.completed":
|
| 581 |
+
it = d.get("item") or {}
|
| 582 |
+
items.append(it.get("type"))
|
| 583 |
+
if it.get("type") == "agent_message":
|
| 584 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 585 |
+
elif it.get("type") == "reasoning":
|
| 586 |
+
tw.add_step("agent", reasoning=it.get("text", ""))
|
| 587 |
+
else:
|
| 588 |
+
name = it.get("tool") if it.get("type") == "mcp_tool_call" else it.get("type")
|
| 589 |
+
args = it.get("arguments") if it.get("type") == "mcp_tool_call" else {
|
| 590 |
+
k: v for k, v in it.items() if k not in ("id", "type", "status")}
|
| 591 |
+
st = tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 592 |
+
native_name=f"{it.get('server', '')}.{name}"
|
| 593 |
+
if it.get("type") == "mcp_tool_call" else name,
|
| 594 |
+
item_type=it.get("type"), arguments=args)])
|
| 595 |
+
res = it.get("result") or {}
|
| 596 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 597 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 598 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 599 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 600 |
+
del st
|
| 601 |
+
v = self.version()
|
| 602 |
+
tw.set_header(session_id=thread, source=os.path.basename(spec.stdout_path),
|
| 603 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
|
| 604 |
+
tools=EXPECTED_ALL_TOOLS if (spec.config_files.get("model_catalog_json") or {}).get(
|
| 605 |
+
"code_mode", True) else EXPECTED_TOP_GENERIC)
|
| 606 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items))),
|
| 607 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 608 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 609 |
+
tw.write()
|
| 610 |
+
h.info.update(items=items, traj=tw, thread=thread, errors=errors)
|
| 611 |
+
return tw
|
| 612 |
+
|
| 613 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 614 |
+
@staticmethod
|
| 615 |
+
def sqlite_rows(path, table):
|
| 616 |
+
"""Row count of `table`, read from a copy (the db may be in WAL mode and still open)."""
|
| 617 |
+
import tempfile
|
| 618 |
+
try:
|
| 619 |
+
with tempfile.TemporaryDirectory() as td:
|
| 620 |
+
for suf in ("", "-wal", "-shm"):
|
| 621 |
+
if os.path.exists(path + suf):
|
| 622 |
+
shutil.copy(path + suf, os.path.join(td, "db.sqlite" + suf))
|
| 623 |
+
con = sqlite3.connect(os.path.join(td, "db.sqlite"))
|
| 624 |
+
n = con.execute(f"select count(*) from {table}").fetchone()[0]
|
| 625 |
+
con.close()
|
| 626 |
+
return n
|
| 627 |
+
except (sqlite3.Error, OSError) as e:
|
| 628 |
+
return f"n/a ({e})"
|
| 629 |
+
|
| 630 |
+
def audit(self, h):
|
| 631 |
+
spec, ep = h.spec, h.ep
|
| 632 |
+
v, notes = [], []
|
| 633 |
+
items = h.info.get("items") or []
|
| 634 |
+
bad = sorted({i for i in items if i not in OK_ITEMS})
|
| 635 |
+
if bad:
|
| 636 |
+
v.append(f"non-MCP items in the event stream: {bad}")
|
| 637 |
+
tw = h.info.get("traj")
|
| 638 |
+
residual = []
|
| 639 |
+
for st in (tw.steps if tw else []):
|
| 640 |
+
for tc in st["tool_calls"]:
|
| 641 |
+
if tc.get("item_type") != "mcp_tool_call":
|
| 642 |
+
continue
|
| 643 |
+
if tc["native_name"].startswith("lff.") and tc["function_name"] in MCP_TOOLS:
|
| 644 |
+
continue
|
| 645 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 646 |
+
residual.append(tc["function_name"]) # our server has no resources: always empty
|
| 647 |
+
else:
|
| 648 |
+
v.append(f"unexpected MCP call {tc['native_name']}")
|
| 649 |
+
if residual:
|
| 650 |
+
notes.append(f"residual MCP-resource tool calls (empty, our server has no resources): {residual}")
|
| 651 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 652 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 653 |
+
ch = spec.state_dirs["codex_home"]
|
| 654 |
+
note = self._sync_auth_back(ch)
|
| 655 |
+
if note:
|
| 656 |
+
notes.append(note)
|
| 657 |
+
left = dict(codex_home=snapshot_tree(ch), home=snapshot_tree(spec.state_dirs["home"]),
|
| 658 |
+
work=snapshot_tree(spec.cwd))
|
| 659 |
+
threads = None
|
| 660 |
+
for f in left["codex_home"]:
|
| 661 |
+
if re.match(r"state_\d+\.sqlite$", f):
|
| 662 |
+
threads = self.sqlite_rows(os.path.join(ch, f), "threads")
|
| 663 |
+
if isinstance(threads, int) and threads > 1:
|
| 664 |
+
v.append(f"{threads} threads persisted in CODEX_HOME (only this run's one is expected)")
|
| 665 |
+
thread = h.info.get("thread")
|
| 666 |
+
sessions = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))]
|
| 667 |
+
foreign = [f for f in sessions if not (thread and f.startswith("sessions/") and f.endswith(f"-{thread}.jsonl"))]
|
| 668 |
+
if foreign:
|
| 669 |
+
v.append(f"session files other than this run's thread: {foreign}")
|
| 670 |
+
if h.info.get("resumes"):
|
| 671 |
+
notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
|
| 672 |
+
f"episode was over)")
|
| 673 |
+
if left["work"]:
|
| 674 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 675 |
+
if (spec.config_files.get("model_catalog_json") or {}).get("code_mode", True):
|
| 676 |
+
notes.append("image forwarding (model calls image()) is not visible in --json; needs the model proxy (P1)")
|
| 677 |
+
mcp_env = None
|
| 678 |
+
mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
|
| 679 |
+
if os.path.exists(mt):
|
| 680 |
+
for line in open(mt):
|
| 681 |
+
d = json.loads(line)
|
| 682 |
+
if d.get("ev") == "start" and "env_keys" in d:
|
| 683 |
+
mcp_env = d["env_keys"]
|
| 684 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, threads_rows=threads,
|
| 685 |
+
mcp_server_env_keys=mcp_env, item_types=sorted(set(items)), errors=h.info.get("errors"), ok=not v)
|
| 686 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 687 |
+
json.dump(out, f, indent=1)
|
| 688 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/contract.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Information contract of one run (docs/15 §1 layer 2) and its hash `contract_sha256`.
|
| 2 |
+
|
| 3 |
+
The contract is everything the agent is given that must be identical across harnesses and models for the same
|
| 4 |
+
instance and condition: the README text, the three tool schemas, the image spec, the feedback level, --hide-k, the
|
| 5 |
+
budgets, the memory condition, the task and seed, and the code that builds the scene and judges it. Two runs whose
|
| 6 |
+
`contract_sha256` differ must not share a table cell.
|
| 7 |
+
|
| 8 |
+
What is NOT in the contract on purpose: the harness (it is the thing being compared), the model, the port, the
|
| 9 |
+
sandbox / log paths, timestamps.
|
| 10 |
+
|
| 11 |
+
contract = build_contract(log_dir) # reads session.json, agent_iface.json, events.jsonl, README.md
|
| 12 |
+
contract_sha256(contract) # sha256 of the canonical JSON
|
| 13 |
+
write_contract(log_dir) # -> <log_dir>/contract.json, returns (contract, sha)
|
| 14 |
+
"""
|
| 15 |
+
import glob
|
| 16 |
+
import hashlib
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # the lffbench repo
|
| 23 |
+
CONTRACT_VERSION = 1
|
| 24 |
+
IMAGE_SPEC = dict(cameras=["agentview", "wrist"], width=512, height=512, format="JPEG", jpeg_quality=90,
|
| 25 |
+
delivery="files in the workspace, viewed with view_images (bytes unchanged)")
|
| 26 |
+
# code that builds the scene, runs the robot and judges the result (task modules are added per task)
|
| 27 |
+
SERVER_CODE = ["lffbench/agent/robot_server.py", "lffbench/agent/tools.py", "lffbench/agent/camera.py",
|
| 28 |
+
"lffbench/agent/context.py", "lffbench/agent/images.py", "lffbench/envs.py", "lffbench/skills.py",
|
| 29 |
+
"lffbench/task_base.py", "lffbench/bddl.py", "lffbench/objects.py"]
|
| 30 |
+
# real-robot backend (added for real_* tasks only; the driver itself is recorded as contract["real_driver"])
|
| 31 |
+
REAL_CODE = ["lffbench/real/tasks.py", "lffbench/real/session.py", "lffbench/real/executor.py", "lffbench/real/protocol.py"]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def sha256_bytes(b):
|
| 35 |
+
return hashlib.sha256(b).hexdigest()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def sha256_text(s):
|
| 39 |
+
return sha256_bytes(s.encode("utf-8"))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def sha256_file(path):
|
| 43 |
+
h = hashlib.sha256()
|
| 44 |
+
with open(path, "rb") as f:
|
| 45 |
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
| 46 |
+
h.update(chunk)
|
| 47 |
+
return h.hexdigest()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def canonical(obj):
|
| 51 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def sha256_json(obj):
|
| 55 |
+
return sha256_text(canonical(obj))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def tool_schemas():
|
| 59 |
+
"""The three LA tools exactly as the reference driver and the MCP server define them."""
|
| 60 |
+
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
| 61 |
+
from api_player import SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, PREAMBLE_LA # noqa: E402
|
| 62 |
+
return [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA], PREAMBLE_LA
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def task_module_files(task):
|
| 66 |
+
"""Source files of the task class `task` (found by its `name = "<task>"` line; .bak files are ignored)."""
|
| 67 |
+
pat = re.compile(r"""^\s*name\s*=\s*["']%s["']""" % re.escape(task), re.M)
|
| 68 |
+
hits = []
|
| 69 |
+
for p in sorted(glob.glob(os.path.join(ROOT, "lffbench", "tasks", "*.py"))):
|
| 70 |
+
try:
|
| 71 |
+
if pat.search(open(p, encoding="utf-8").read()):
|
| 72 |
+
hits.append(os.path.relpath(p, ROOT))
|
| 73 |
+
except OSError:
|
| 74 |
+
pass
|
| 75 |
+
arm = os.path.join(ROOT, "lffbench", "arm_specs", f"{task}.py")
|
| 76 |
+
if os.path.exists(arm):
|
| 77 |
+
hits.append(os.path.relpath(arm, ROOT))
|
| 78 |
+
real = os.path.join(ROOT, "lffbench", "real", "tasks.py") # real-robot tasks (docs/17): add the real backend's code
|
| 79 |
+
if not hits and os.path.exists(real) and pat.search(open(real, encoding="utf-8").read()):
|
| 80 |
+
hits += REAL_CODE
|
| 81 |
+
return hits
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def server_code_sha(task):
|
| 85 |
+
files = SERVER_CODE + task_module_files(task)
|
| 86 |
+
per = {f: (sha256_file(os.path.join(ROOT, f)) if os.path.exists(os.path.join(ROOT, f)) else None) for f in files}
|
| 87 |
+
return sha256_json(per), per
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def session_start(log_dir):
|
| 91 |
+
with open(os.path.join(log_dir, "events.jsonl")) as f:
|
| 92 |
+
for line in f:
|
| 93 |
+
d = json.loads(line)
|
| 94 |
+
if d.get("ev") == "session_start":
|
| 95 |
+
return d
|
| 96 |
+
raise RuntimeError(f"no session_start event in {log_dir}/events.jsonl")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def readme_budget(readme):
|
| 100 |
+
"""The per-attempt budgets as the README states them (what the agent is told)."""
|
| 101 |
+
out = {}
|
| 102 |
+
for key, pat in (("robot_commands", r"at most (\d+) robot commands"),
|
| 103 |
+
("sim_seconds", r"at most ([\d.]+) s of (?:simulated )?robot motion"), # real robot: "s of robot motion"
|
| 104 |
+
("tool_calls", r"at most (\d+) tool calls")):
|
| 105 |
+
m = re.search(pat, readme)
|
| 106 |
+
out[key] = float(m.group(1)) if m and "." in m.group(1) else (int(m.group(1)) if m else None)
|
| 107 |
+
return out
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def build_contract(log_dir):
|
| 111 |
+
log_dir = os.path.abspath(log_dir)
|
| 112 |
+
sess = json.load(open(os.path.join(log_dir, "session.json")))
|
| 113 |
+
iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
|
| 114 |
+
st = session_start(log_dir)
|
| 115 |
+
readme = open(os.path.join(sess["sandbox"], "README.md"), encoding="utf-8").read()
|
| 116 |
+
tools, preamble = tool_schemas()
|
| 117 |
+
code_sha, code_files = server_code_sha(st["task"])
|
| 118 |
+
out = dict(
|
| 119 |
+
contract_version=CONTRACT_VERSION,
|
| 120 |
+
task=st["task"], seed=st["seed"],
|
| 121 |
+
readme_sha256=sha256_text(readme),
|
| 122 |
+
preamble_sha256=sha256_text(preamble),
|
| 123 |
+
tools=tools,
|
| 124 |
+
image_spec=dict(IMAGE_SPEC, perception=st.get("perception", iface.get("perception"))),
|
| 125 |
+
feedback=st.get("feedback"), instruction=st.get("instruction"),
|
| 126 |
+
memory=st.get("memory"), k=st.get("k"), k_shown=st.get("k_shown"), hide_k=st.get("k_shown") != st.get("k"),
|
| 127 |
+
protocol=st.get("protocol"), arm=st.get("arm"), dossier_sha256=sha256_text(st.get("dossier") or ""),
|
| 128 |
+
budget=dict(readme_budget(readme), max_tool_calls=iface.get("max_tool_calls"),
|
| 129 |
+
tool_call_budget_enforced_by="mcp_robot_server / api_player (per attempt)"),
|
| 130 |
+
agent_iface=iface.get("agent_iface"),
|
| 131 |
+
server_code_sha256=code_sha, server_code_files=code_files,
|
| 132 |
+
)
|
| 133 |
+
if st.get("backend") == "real": # only real-robot runs get this key, so simulated contracts are unchanged
|
| 134 |
+
di = st.get("driver_info") or {}
|
| 135 |
+
out["real_driver"] = {k: di.get(k) for k in ("protocol", "robot", "n_joints", "workspace", "yaw_range_deg",
|
| 136 |
+
"max_speed", "ik", "driver_version")}
|
| 137 |
+
out["real_agent_workspace"] = st.get("agent_workspace")
|
| 138 |
+
from .redteam import marker # adversarial acceptance runs only (harness_run --red-team): others are unchanged
|
| 139 |
+
rt = marker(log_dir)
|
| 140 |
+
if rt:
|
| 141 |
+
out["red_team"] = rt
|
| 142 |
+
return out
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def contract_sha256(contract):
|
| 146 |
+
return sha256_json(contract)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def write_contract(log_dir):
|
| 150 |
+
c = build_contract(log_dir)
|
| 151 |
+
sha = contract_sha256(c)
|
| 152 |
+
with open(os.path.join(log_dir, "contract.json"), "w") as f:
|
| 153 |
+
json.dump(dict(contract_sha256=sha, contract=c), f, indent=1, ensure_ascii=False)
|
| 154 |
+
return c, sha
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == "__main__":
|
| 158 |
+
for d in sys.argv[1:]:
|
| 159 |
+
c, sha = write_contract(d)
|
| 160 |
+
print(sha, d)
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/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/models-20261115-g56sol_breakfast1_20261114/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/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/fakeapi.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local fake model APIs for offline harness checks (no real model, no cost).
|
| 2 |
+
|
| 3 |
+
Both servers listen on 127.0.0.1, record every request body (auth headers dropped) and answer from a script, so a
|
| 4 |
+
native harness can be driven turn by turn without a model:
|
| 5 |
+
FakeAnthropic Anthropic Messages API (streaming SSE), used by Claude Code and by api_player --provider anthropic
|
| 6 |
+
FakeResponses OpenAI Responses API (streaming SSE), used by Codex through a custom model provider
|
| 7 |
+
|
| 8 |
+
A script is a list of turns; turn i is answered to the request that already holds i assistant turns, so retries get
|
| 9 |
+
the same answer. Past the end of the script the server answers with a final text. A turn is a list of steps:
|
| 10 |
+
("tool", name, args) Anthropic: tool_use block (name as given, e.g. "mcp__lff__robot" or "Read")
|
| 11 |
+
("text", s) a text block / assistant message
|
| 12 |
+
("exec", js) Responses: one `exec` custom tool call (Codex code mode) with this JavaScript
|
| 13 |
+
("fcall", name, args) Responses: a plain function call
|
| 14 |
+
("nscall", ns, name, args) Responses: a function call into a tool namespace (Codex without code mode calls our MCP
|
| 15 |
+
tools this way: name "robot", namespace "mcp__lff"; measured with 0.163)
|
| 16 |
+
|
| 17 |
+
srv = FakeAnthropic(script, record_dir).start(); ... srv.base_url ...; srv.stop()
|
| 18 |
+
"""
|
| 19 |
+
import itertools
|
| 20 |
+
import json
|
| 21 |
+
import os
|
| 22 |
+
import threading
|
| 23 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 24 |
+
|
| 25 |
+
DROP_HEADERS = ("x-api-key", "authorization", "cookie", "chatgpt-account-id")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class _Base:
|
| 29 |
+
final_text = "done"
|
| 30 |
+
|
| 31 |
+
def __init__(self, script=None, record_dir=None, port=0):
|
| 32 |
+
self.script = list(script or [])
|
| 33 |
+
self.record_dir = record_dir
|
| 34 |
+
self.port = port
|
| 35 |
+
self.lock = threading.Lock()
|
| 36 |
+
self.counter = itertools.count(1)
|
| 37 |
+
self.requests = [] # (n, path, body)
|
| 38 |
+
if record_dir:
|
| 39 |
+
os.makedirs(record_dir, exist_ok=True)
|
| 40 |
+
|
| 41 |
+
# ------------------------------------------------------------------ plumbing
|
| 42 |
+
def start(self):
|
| 43 |
+
outer = self
|
| 44 |
+
|
| 45 |
+
class H(BaseHTTPRequestHandler):
|
| 46 |
+
protocol_version = "HTTP/1.1"
|
| 47 |
+
|
| 48 |
+
def log_message(self, *a):
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
def _record(self, body):
|
| 52 |
+
with outer.lock:
|
| 53 |
+
n = next(outer.counter)
|
| 54 |
+
outer.requests.append((n, self.path, body))
|
| 55 |
+
if outer.record_dir:
|
| 56 |
+
with open(os.path.join(outer.record_dir, f"req_{n:03d}.json"), "w") as f:
|
| 57 |
+
json.dump(dict(method=self.command, path=self.path, body=body,
|
| 58 |
+
headers={k: v for k, v in self.headers.items() if k.lower() not in DROP_HEADERS}),
|
| 59 |
+
f, indent=1, ensure_ascii=False)
|
| 60 |
+
return n
|
| 61 |
+
|
| 62 |
+
def do_GET(self):
|
| 63 |
+
self._record(None)
|
| 64 |
+
self._send(404, b"{}", "application/json")
|
| 65 |
+
|
| 66 |
+
def do_HEAD(self):
|
| 67 |
+
self._send(404, b"", "application/json")
|
| 68 |
+
|
| 69 |
+
def do_POST(self):
|
| 70 |
+
raw = self.rfile.read(int(self.headers.get("content-length", 0) or 0))
|
| 71 |
+
try:
|
| 72 |
+
body = json.loads(raw)
|
| 73 |
+
except ValueError:
|
| 74 |
+
body = raw[:4000].decode("utf-8", "replace")
|
| 75 |
+
n = self._record(body)
|
| 76 |
+
outer.handle(self, n, body)
|
| 77 |
+
|
| 78 |
+
def _send(self, code, data, ctype):
|
| 79 |
+
self.send_response(code)
|
| 80 |
+
self.send_header("content-type", ctype)
|
| 81 |
+
self.send_header("content-length", str(len(data)))
|
| 82 |
+
self.end_headers()
|
| 83 |
+
self.wfile.write(data)
|
| 84 |
+
|
| 85 |
+
self.httpd = ThreadingHTTPServer(("127.0.0.1", self.port), H)
|
| 86 |
+
self.httpd.daemon_threads = True
|
| 87 |
+
self.port = self.httpd.server_address[1]
|
| 88 |
+
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
| 89 |
+
return self
|
| 90 |
+
|
| 91 |
+
def stop(self):
|
| 92 |
+
self.httpd.shutdown()
|
| 93 |
+
self.httpd.server_close()
|
| 94 |
+
|
| 95 |
+
def turn(self, i):
|
| 96 |
+
return self.script[i] if i < len(self.script) else [("text", self.final_text)]
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def send_sse(h, events):
|
| 100 |
+
data = b"".join(f"event: {ev}\ndata: {json.dumps(d)}\n\n".encode() for ev, d in events)
|
| 101 |
+
h._send(200, data, "text/event-stream")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class FakeAnthropic(_Base):
|
| 105 |
+
@property
|
| 106 |
+
def base_url(self):
|
| 107 |
+
return f"http://127.0.0.1:{self.port}"
|
| 108 |
+
|
| 109 |
+
def handle(self, h, n, body):
|
| 110 |
+
if not h.path.startswith("/v1/messages") or "count_tokens" in h.path or not isinstance(body, dict):
|
| 111 |
+
h._send(200, json.dumps({"input_tokens": 10}).encode(), "application/json")
|
| 112 |
+
return
|
| 113 |
+
msgs = body.get("messages", [])
|
| 114 |
+
i = sum(1 for m in msgs if m.get("role") == "assistant")
|
| 115 |
+
steps = self.turn(i)
|
| 116 |
+
blocks = []
|
| 117 |
+
for j, st in enumerate(steps):
|
| 118 |
+
if st[0] == "tool":
|
| 119 |
+
blocks.append(dict(type="tool_use", id=f"toolu_fake_{i:03d}_{j}", name=st[1], input=st[2]))
|
| 120 |
+
else:
|
| 121 |
+
blocks.append(dict(type="text", text=st[1]))
|
| 122 |
+
stop = "tool_use" if any(b["type"] == "tool_use" for b in blocks) else "end_turn"
|
| 123 |
+
model = body.get("model", "fake")
|
| 124 |
+
evs = [("message_start", dict(type="message_start", message=dict(
|
| 125 |
+
id=f"msg_fake_{n}", type="message", role="assistant", model=model, content=[], stop_reason=None,
|
| 126 |
+
stop_sequence=None, usage=dict(input_tokens=100, output_tokens=1))))]
|
| 127 |
+
for k, b in enumerate(blocks):
|
| 128 |
+
if b["type"] == "tool_use":
|
| 129 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k, content_block=dict(
|
| 130 |
+
type="tool_use", id=b["id"], name=b["name"], input={}))))
|
| 131 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k, delta=dict(
|
| 132 |
+
type="input_json_delta", partial_json=json.dumps(b["input"])))))
|
| 133 |
+
else:
|
| 134 |
+
evs.append(("content_block_start", dict(type="content_block_start", index=k,
|
| 135 |
+
content_block=dict(type="text", text=""))))
|
| 136 |
+
evs.append(("content_block_delta", dict(type="content_block_delta", index=k,
|
| 137 |
+
delta=dict(type="text_delta", text=b["text"]))))
|
| 138 |
+
evs.append(("content_block_stop", dict(type="content_block_stop", index=k)))
|
| 139 |
+
evs.append(("message_delta", dict(type="message_delta", delta=dict(stop_reason=stop, stop_sequence=None),
|
| 140 |
+
usage=dict(output_tokens=5))))
|
| 141 |
+
evs.append(("message_stop", dict(type="message_stop")))
|
| 142 |
+
self.send_sse(h, evs)
|
| 143 |
+
|
| 144 |
+
def message_requests(self):
|
| 145 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and p.startswith("/v1/messages")
|
| 146 |
+
and "count_tokens" not in p]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class FakeResponses(_Base):
|
| 150 |
+
@property
|
| 151 |
+
def base_url(self):
|
| 152 |
+
return f"http://127.0.0.1:{self.port}/v1"
|
| 153 |
+
|
| 154 |
+
def handle(self, h, n, body):
|
| 155 |
+
if not isinstance(body, dict) or "input" not in body:
|
| 156 |
+
h._send(404, b"{}", "application/json")
|
| 157 |
+
return
|
| 158 |
+
items = body.get("input") or []
|
| 159 |
+
i = sum(1 for it in items if isinstance(it, dict) and it.get("type") in
|
| 160 |
+
("custom_tool_call", "function_call") or (isinstance(it, dict) and it.get("type") == "message"
|
| 161 |
+
and it.get("role") == "assistant"))
|
| 162 |
+
steps = self.turn(i)
|
| 163 |
+
out = []
|
| 164 |
+
for j, st in enumerate(steps):
|
| 165 |
+
if st[0] == "exec":
|
| 166 |
+
out.append(dict(type="custom_tool_call", id=f"ctc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 167 |
+
name="exec", status="completed", input=st[1]))
|
| 168 |
+
elif st[0] == "fcall":
|
| 169 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 170 |
+
name=st[1], arguments=json.dumps(st[2]), status="completed"))
|
| 171 |
+
elif st[0] == "nscall":
|
| 172 |
+
out.append(dict(type="function_call", id=f"fc_fake_{n}_{j}", call_id=f"call_fake_{i:03d}_{j}",
|
| 173 |
+
namespace=st[1], name=st[2], arguments=json.dumps(st[3]), status="completed"))
|
| 174 |
+
else:
|
| 175 |
+
out.append(dict(type="message", id=f"msg_fake_{n}_{j}", role="assistant", status="completed",
|
| 176 |
+
content=[dict(type="output_text", text=st[1], annotations=[])]))
|
| 177 |
+
rid = f"resp_fake_{n}"
|
| 178 |
+
evs = [("response.created", dict(type="response.created", response=dict(id=rid, status="in_progress")))]
|
| 179 |
+
for k, it in enumerate(out):
|
| 180 |
+
evs.append(("response.output_item.done", dict(type="response.output_item.done", output_index=k, item=it)))
|
| 181 |
+
evs.append(("response.completed", dict(type="response.completed", response=dict(
|
| 182 |
+
id=rid, status="completed", output=out, usage=dict(
|
| 183 |
+
input_tokens=100, input_tokens_details=dict(cached_tokens=0), output_tokens=3,
|
| 184 |
+
output_tokens_details=dict(reasoning_tokens=0), total_tokens=103)))))
|
| 185 |
+
self.send_sse(h, evs)
|
| 186 |
+
|
| 187 |
+
def model_requests(self):
|
| 188 |
+
return [(n, b) for n, p, b in self.requests if isinstance(b, dict) and "input" in b]
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/framework_codex.py
ADDED
|
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared launcher for robot frameworks using a native Codex backend.
|
| 2 |
+
|
| 3 |
+
The external integration contract is Session.first_message(), Session.tool_specs(),
|
| 4 |
+
and Session.call(name, arguments). This launcher owns isolation, model configuration,
|
| 5 |
+
pins, trajectory collection and audits; framework plugins own their native loop.
|
| 6 |
+
Based on the validated RPent launcher; RPent's historical launcher remains frozen.
|
| 7 |
+
"""
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import shutil
|
| 12 |
+
import subprocess
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
from . import contract as C
|
| 16 |
+
from . import pins
|
| 17 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 18 |
+
gateway_env, new_run_dir, proxy_env, snapshot_tree)
|
| 19 |
+
from .codex import (AUTH_FILE, Codex, CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
|
| 20 |
+
request_fingerprint, toml_str)
|
| 21 |
+
from .fakeapi import FakeResponses
|
| 22 |
+
from .trajectory import TrajWriter
|
| 23 |
+
|
| 24 |
+
ROOT = C.ROOT
|
| 25 |
+
JAIL_FRAMEWORK_DIR = "/opt/lffjail/hjail/framework"
|
| 26 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 27 |
+
MCP_SERVER = "lff"
|
| 28 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 29 |
+
TREE_SKIP = {".git", "__pycache__", ".pytest_cache", ".ruff_cache", ".mypy_cache", "docs", "tests", ".github"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def tree_sha256(root, skip=TREE_SKIP):
|
| 34 |
+
"""sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
|
| 35 |
+
h = hashlib.sha256()
|
| 36 |
+
for dp, dn, fn in os.walk(root):
|
| 37 |
+
dn[:] = sorted(d for d in dn if d not in skip)
|
| 38 |
+
for f in sorted(fn):
|
| 39 |
+
if f.endswith(".pyc"):
|
| 40 |
+
continue
|
| 41 |
+
p = os.path.join(dp, f)
|
| 42 |
+
rel = os.path.relpath(p, root)
|
| 43 |
+
if os.path.islink(p):
|
| 44 |
+
h.update(f"L {rel} {os.readlink(p)}\n".encode())
|
| 45 |
+
else:
|
| 46 |
+
h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
|
| 47 |
+
return h.hexdigest()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def runtime_info(home):
|
| 51 |
+
"""The robot framework runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
|
| 52 |
+
src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
|
| 53 |
+
for d in (src, venv):
|
| 54 |
+
if not os.path.isdir(d):
|
| 55 |
+
raise HarnessRefused(f"robot framework runtime incomplete: {d} missing (run the selected framework setup script under integrations/)")
|
| 56 |
+
|
| 57 |
+
def git(*a):
|
| 58 |
+
r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
|
| 59 |
+
return r.stdout.strip() if r.returncode == 0 else None
|
| 60 |
+
commit = git("rev-parse", "HEAD")
|
| 61 |
+
patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
|
| 62 |
+
untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
|
| 63 |
+
return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
|
| 64 |
+
untracked=sorted(u for u in untracked if "__pycache__" not in u),
|
| 65 |
+
tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def jail_runtime_copy(home, tree):
|
| 69 |
+
"""A verified read-only copy of the runtime under /opt/lffjail/hjail/framework (visible in the jail; /mnt is not)."""
|
| 70 |
+
dst = os.path.join(JAIL_FRAMEWORK_DIR, f"framework-{tree[:12]}")
|
| 71 |
+
stamp = os.path.join(dst, ".tree_sha256")
|
| 72 |
+
if os.path.exists(stamp) and open(stamp).read().strip() == tree:
|
| 73 |
+
return dst
|
| 74 |
+
os.makedirs(JAIL_FRAMEWORK_DIR, mode=0o755, exist_ok=True)
|
| 75 |
+
tmp = dst + ".tmp-" + os.urandom(3).hex()
|
| 76 |
+
shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
|
| 77 |
+
ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
|
| 78 |
+
shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
|
| 79 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
| 80 |
+
got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
|
| 81 |
+
).hexdigest()
|
| 82 |
+
if got != tree:
|
| 83 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 84 |
+
raise HarnessRefused(f"copy of the robot framework runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
|
| 85 |
+
for dp, dn, fn in os.walk(tmp):
|
| 86 |
+
os.chmod(dp, 0o755)
|
| 87 |
+
for f in fn:
|
| 88 |
+
p = os.path.join(dp, f)
|
| 89 |
+
if not os.path.islink(p):
|
| 90 |
+
os.chmod(p, os.stat(p).st_mode | 0o444)
|
| 91 |
+
with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
|
| 92 |
+
f.write(tree)
|
| 93 |
+
if os.path.exists(dst):
|
| 94 |
+
shutil.rmtree(dst)
|
| 95 |
+
os.rename(tmp, dst)
|
| 96 |
+
return dst
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def codex_overrides(effort, catalog_path):
|
| 100 |
+
"""The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
|
| 101 |
+
overrides for robot framework's planner; the provider and the MCP server URL are robot framework's own (CODEX_BASE_URL, in-process)."""
|
| 102 |
+
return (["model_reasoning_effort=" + toml_str(effort),
|
| 103 |
+
"include_permissions_instructions=false", "include_environment_context=false",
|
| 104 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 105 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 106 |
+
f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
|
| 107 |
+
f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
|
| 108 |
+
f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
|
| 109 |
+
f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
|
| 110 |
+
"model_catalog_json=" + toml_str(catalog_path)]
|
| 111 |
+
+ [f"features.{f}=false" for f in DISABLE])
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _items(stream_path):
|
| 115 |
+
"""Codex app-server notifications of one robot framework session (robot framework writes them as JSONL)."""
|
| 116 |
+
out = []
|
| 117 |
+
if not os.path.exists(stream_path):
|
| 118 |
+
return out
|
| 119 |
+
for line in open(stream_path, encoding="utf-8", errors="replace"):
|
| 120 |
+
try:
|
| 121 |
+
out.append(json.loads(line))
|
| 122 |
+
except ValueError:
|
| 123 |
+
continue
|
| 124 |
+
return out
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _item_of(ev):
|
| 128 |
+
it = (ev.get("payload") or {}).get("item") or {}
|
| 129 |
+
return it.get("root", it) if isinstance(it, dict) else {}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class RobotFrameworkCodex(HarnessAdapter):
|
| 133 |
+
name = "framework_codex"
|
| 134 |
+
runtime_home = "/nonexistent"
|
| 135 |
+
runtime_module = "lff_integration.run"
|
| 136 |
+
default_steps = 500
|
| 137 |
+
uses_mcp = False
|
| 138 |
+
uses_gateway = True
|
| 139 |
+
can_resume = False
|
| 140 |
+
clean_dirs = ("home", "codex_home", "tmp", "out")
|
| 141 |
+
clean_allowed = {"codex_home": (CATALOG_FILE,)}
|
| 142 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 143 |
+
capabilities = dict(
|
| 144 |
+
only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
|
| 145 |
+
"mcp__lff functions + residual resource×3 / request_user_input; robot framework registers "
|
| 146 |
+
"no tool of its own (no file tools, no finish)"),
|
| 147 |
+
images_reach_model=Cap("yes", "probe", "gateway content blocks preserved by the framework bridge, "
|
| 148 |
+
"JPEG with its own MIME type"),
|
| 149 |
+
non_persistent_session=Cap("yes", "probe", "robot framework's threads only in the one-time CODEX_HOME, removed after the "
|
| 150 |
+
"run; no preloaded or cross-episode framework memory"),
|
| 151 |
+
pinned_version=Cap("yes", "launch", "codex binary sha256 + robot framework commit / patch / tree hash (src + venv) in "
|
| 152 |
+
"harness.json; pin per version and tree"),
|
| 153 |
+
machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per robot framework session "
|
| 154 |
+
"(codex.out.stream.jsonl) + robot framework run.json"),
|
| 155 |
+
tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (named framework face) + events.jsonl"),
|
| 156 |
+
model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
|
| 157 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; robot framework memory not "
|
| 158 |
+
"constructed"),
|
| 159 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
|
| 160 |
+
web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
|
| 161 |
+
host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
|
| 162 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 163 |
+
subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
|
| 164 |
+
background_execution=Cap("absent", "preflight", "no background tool in the request"),
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 168 |
+
jail=False, auth="apikey", catalog="generic", sessions=1, attempts_per_session=0, max_turns=500,
|
| 169 |
+
home=None, provider=None, auth_home=None):
|
| 170 |
+
"""Common controlled Codex SDK launcher.
|
| 171 |
+
|
| 172 |
+
The plugin entrypoint interprets its declared loop options. For SenseNova,
|
| 173 |
+
max_turns is the upstream SDK-step limit, not a provider-response count.
|
| 174 |
+
Robot commands, simulation time and tool budgets are always server-owned.
|
| 175 |
+
"""
|
| 176 |
+
if auth not in ("apikey", "chatgpt"):
|
| 177 |
+
raise ValueError("framework_codex auth must be apikey or chatgpt")
|
| 178 |
+
if catalog not in CATALOGS:
|
| 179 |
+
raise ValueError(f"catalog must be one of {CATALOGS}")
|
| 180 |
+
self.auth, self.catalog = auth, catalog
|
| 181 |
+
self._auth_manager = Codex(auth=auth, auth_home=auth_home, api_env=api_env, base_url=base_url, catalog=catalog)
|
| 182 |
+
self.api_env = self._auth_manager.api_env
|
| 183 |
+
self.base_url = self._auth_manager.base_url
|
| 184 |
+
self.clean_allowed = {"codex_home": ((AUTH_FILE,) if auth == "chatgpt" else ()) + (CATALOG_FILE,)}
|
| 185 |
+
self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
|
| 186 |
+
self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
|
| 187 |
+
int(max_turns)
|
| 188 |
+
self.home = home or os.environ.get("LFF_FRAMEWORK_HOME") or self.runtime_home
|
| 189 |
+
self.proxy = proxy_env()
|
| 190 |
+
self._version = None
|
| 191 |
+
self._runtime = None
|
| 192 |
+
self.runtime_dir = self.home
|
| 193 |
+
if jail:
|
| 194 |
+
from .jail import HarnessJail
|
| 195 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 196 |
+
|
| 197 |
+
# ------------------------------------------------------------------------------------------------ identity
|
| 198 |
+
def runtime(self):
|
| 199 |
+
if self._runtime is None:
|
| 200 |
+
self._runtime = runtime_info(self.home)
|
| 201 |
+
if self.jail is not None:
|
| 202 |
+
self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
|
| 203 |
+
return self._runtime
|
| 204 |
+
|
| 205 |
+
def version(self):
|
| 206 |
+
if self._version is None:
|
| 207 |
+
b = codex_bin()
|
| 208 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 209 |
+
CODEX_HOME="/nonexistent"),
|
| 210 |
+
capture_output=True, text=True, timeout=60)
|
| 211 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 212 |
+
rt = self.runtime()
|
| 213 |
+
self._version = dict(version=v, binary=binary_info(b),
|
| 214 |
+
framework=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
|
| 215 |
+
tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
|
| 216 |
+
return self._version
|
| 217 |
+
|
| 218 |
+
def pin_key(self, ep):
|
| 219 |
+
v = self.version()
|
| 220 |
+
mode = "" if self.auth == "apikey" else "-chatgpt"
|
| 221 |
+
name = f"{self.name}{mode}-{self.catalog}-{v['framework']['tree_sha256'][:12]}"
|
| 222 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 223 |
+
|
| 224 |
+
def anchor_pin_key(self, ep):
|
| 225 |
+
"""The main table's codex pin for the same model / effort (apikey, same catalog)."""
|
| 226 |
+
v = self.version()
|
| 227 |
+
name = "codex" + ("" if self.auth == "apikey" else "-chatgpt") + ("" if self.catalog == "native" else f"-{self.catalog}")
|
| 228 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 229 |
+
|
| 230 |
+
def auth_info(self):
|
| 231 |
+
if self.auth == "chatgpt":
|
| 232 |
+
return self._auth_manager.auth_info()
|
| 233 |
+
return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
|
| 234 |
+
"OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
|
| 235 |
+
|
| 236 |
+
def config_info(self):
|
| 237 |
+
return dict(auth=self.auth, catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
|
| 238 |
+
max_turns=self.max_turns, framework=self.version()["framework"])
|
| 239 |
+
|
| 240 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 241 |
+
def _state_dirs(self, hexname=None):
|
| 242 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 243 |
+
os.makedirs(root, exist_ok=True)
|
| 244 |
+
state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
|
| 245 |
+
for k in ("home", "codex_home", "tmp", "out"):
|
| 246 |
+
os.makedirs(state[k], exist_ok=True)
|
| 247 |
+
return state
|
| 248 |
+
|
| 249 |
+
def _install_catalog(self, codex_home, ep):
|
| 250 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
|
| 251 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 252 |
+
with open(path, "w") as f:
|
| 253 |
+
json.dump(cat, f)
|
| 254 |
+
return path, C.sha256_file(path), os.path.relpath(src, ROOT)
|
| 255 |
+
|
| 256 |
+
def argv(self, ep, out_dir, sessions=None, preflight=False):
|
| 257 |
+
py = os.path.join(self.runtime_dir, "venv", "bin", "python")
|
| 258 |
+
return [py, "-m", self.runtime_module, "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
|
| 259 |
+
"--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
|
| 260 |
+
"--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
|
| 261 |
+
+ (["--no-continue"] if preflight else [])
|
| 262 |
+
|
| 263 |
+
def env(self, state, ep, base_url, work):
|
| 264 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
|
| 265 |
+
CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
|
| 266 |
+
CODEX_BASE_URL=base_url, FRAMEWORK_CODEX_SANDBOX="read_only", FRAMEWORK_MCP_SERVER_NAME=MCP_SERVER,
|
| 267 |
+
FRAMEWORK_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
|
| 268 |
+
ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
|
| 269 |
+
FRAMEWORK_REPO_ROOT=work, LFF_FRAMEWORK_FACE=self.name, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
|
| 270 |
+
PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
|
| 271 |
+
if self.auth == "chatgpt":
|
| 272 |
+
# The native API provider declares env_key. Codex app-server still requires that
|
| 273 |
+
# variable even with requires_openai_auth=true, so select a separate provider
|
| 274 |
+
# with no env_key. Do not inject a dummy key or modify the upstream runtime.
|
| 275 |
+
provider_id = "lffsubscription"
|
| 276 |
+
overrides = json.loads(e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"])
|
| 277 |
+
overrides += ["model_provider=" + toml_str(provider_id),
|
| 278 |
+
f"model_providers.{provider_id}.name=" + toml_str(provider_id),
|
| 279 |
+
f"model_providers.{provider_id}.wire_api=\"responses\"",
|
| 280 |
+
f"model_providers.{provider_id}.base_url=" + toml_str(base_url),
|
| 281 |
+
f"model_providers.{provider_id}.requires_openai_auth=true"]
|
| 282 |
+
e["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = json.dumps(overrides)
|
| 283 |
+
e.update(self.proxy)
|
| 284 |
+
if self.api_env.get("OPENAI_API_KEY"):
|
| 285 |
+
e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
|
| 286 |
+
return e
|
| 287 |
+
|
| 288 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 289 |
+
self.version()
|
| 290 |
+
work = new_run_dir("/tmp/lffrun")
|
| 291 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 292 |
+
if self.jail is not None:
|
| 293 |
+
self.jail.stderr_dir = ep.log_dir
|
| 294 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 295 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 296 |
+
cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
|
| 297 |
+
return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
|
| 298 |
+
run_dir=work, state_dirs=state, first_message=first_message,
|
| 299 |
+
stdout_path=os.path.join(ep.log_dir, "framework_stdout.txt"),
|
| 300 |
+
stderr_path=os.path.join(ep.log_dir, "framework_stderr.txt"),
|
| 301 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 302 |
+
catalog=self.catalog, code_mode=False)),
|
| 303 |
+
timeout_s=self.timeout_s)
|
| 304 |
+
|
| 305 |
+
def config_sha256(self, spec, ep):
|
| 306 |
+
argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<FRAMEWORK>")
|
| 307 |
+
for a in spec.argv]
|
| 308 |
+
hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "FRAMEWORK_REPO_ROOT", "PYTHONPATH",
|
| 309 |
+
"LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
|
| 310 |
+
env = {k: v for k, v in spec.env.items() if k not in hidden}
|
| 311 |
+
env["FRAMEWORK_CODEX_CONFIG_OVERRIDES"] = env.get("FRAMEWORK_CODEX_CONFIG_OVERRIDES", "").replace(
|
| 312 |
+
spec.state_dirs["codex_home"], "<CODEX_HOME>")
|
| 313 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 314 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
|
| 315 |
+
framework_tree_sha256=self.version()["framework"]["tree_sha256"]))
|
| 316 |
+
|
| 317 |
+
# ------------------------------------------------------------------------------------------------ launch
|
| 318 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 319 |
+
"""harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
|
| 320 |
+
self._auth_manager._install_auth(spec.state_dirs["codex_home"])
|
| 321 |
+
spec.env.update(gateway_env(ep.log_dir))
|
| 322 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 323 |
+
|
| 324 |
+
def cleanup(self, spec):
|
| 325 |
+
self._auth_manager._sync_auth_back(spec.state_dirs.get("codex_home", ""))
|
| 326 |
+
super().cleanup(spec)
|
| 327 |
+
|
| 328 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 329 |
+
"""The same framework process, one session, against a local fake Responses server that answers with text
|
| 330 |
+
only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
|
| 331 |
+
sandbox, robot framework's prefix + our first message) against the pins."""
|
| 332 |
+
t0 = time.time()
|
| 333 |
+
fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
|
| 334 |
+
pre = self._state_dirs()
|
| 335 |
+
try:
|
| 336 |
+
self._auth_manager._install_auth(pre["codex_home"])
|
| 337 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 338 |
+
env = self.env(pre, ep, fake.base_url, spec.cwd)
|
| 339 |
+
if self.auth == "apikey":
|
| 340 |
+
env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
|
| 341 |
+
env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
|
| 342 |
+
argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
|
| 343 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 344 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
|
| 345 |
+
reqs = fake.model_requests()
|
| 346 |
+
if not reqs:
|
| 347 |
+
# Native planners may record failures only in run.json, with empty stdout/stderr.
|
| 348 |
+
record = os.path.join(pre["out"], "run.json")
|
| 349 |
+
detail = ""
|
| 350 |
+
if os.path.isfile(record):
|
| 351 |
+
with open(record) as f:
|
| 352 |
+
failed_run = json.load(f)
|
| 353 |
+
detail = "; ".join(str(s.get("error")) for s in failed_run.get("sessions", []) if s.get("error"))
|
| 354 |
+
raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
|
| 355 |
+
f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]} {detail[-1200:]}")
|
| 356 |
+
body = reqs[0][1]
|
| 357 |
+
fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
|
| 358 |
+
problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
|
| 359 |
+
users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
|
| 360 |
+
and it.get("role") == "user" for c in it.get("content") or []]
|
| 361 |
+
prefix = None
|
| 362 |
+
if len(users) != 1 or not users[0].endswith(spec.first_message):
|
| 363 |
+
problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
|
| 364 |
+
else:
|
| 365 |
+
prefix = users[0][:-len(spec.first_message)]
|
| 366 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 367 |
+
if effort != ep.effort:
|
| 368 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 369 |
+
if fp["params"].get("model") != ep.model:
|
| 370 |
+
problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
|
| 371 |
+
if os.listdir(spec.cwd):
|
| 372 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 373 |
+
mid_sha = C.sha256_json(fp)
|
| 374 |
+
full = dict(middle=fp, framework_prefix=prefix)
|
| 375 |
+
fp_sha = C.sha256_json(full)
|
| 376 |
+
anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
|
| 377 |
+
out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
|
| 378 |
+
framework_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
|
| 379 |
+
framework_prefix_chars=len(prefix) if prefix is not None else None,
|
| 380 |
+
developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 381 |
+
top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
|
| 382 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
|
| 383 |
+
dt_s=round(time.time() - t0, 1), problems=problems,
|
| 384 |
+
anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
|
| 385 |
+
if anchor is None:
|
| 386 |
+
out["anchor_status"] = "no main-table pin for this model / effort"
|
| 387 |
+
elif anchor["fingerprint_sha256"] != mid_sha:
|
| 388 |
+
problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
|
| 389 |
+
f"({anchor['key']}): the middle layer is not the main table's")
|
| 390 |
+
else:
|
| 391 |
+
out["anchor_status"] = "match"
|
| 392 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 393 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 394 |
+
out["fingerprint"] = full
|
| 395 |
+
if problems:
|
| 396 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 397 |
+
if pin is None:
|
| 398 |
+
if not self.allow_unpinned:
|
| 399 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 400 |
+
f"with --write-pins after the self-check passes)")
|
| 401 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 402 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 403 |
+
raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
|
| 404 |
+
f"({pin['key']})")
|
| 405 |
+
else:
|
| 406 |
+
out["pin_status"] = "match"
|
| 407 |
+
return out
|
| 408 |
+
finally:
|
| 409 |
+
fake.stop()
|
| 410 |
+
self._auth_manager._sync_auth_back(pre["codex_home"])
|
| 411 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 412 |
+
|
| 413 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 414 |
+
def collect(self, h):
|
| 415 |
+
spec, ep = h.spec, h.ep
|
| 416 |
+
dst = os.path.join(ep.log_dir, "framework")
|
| 417 |
+
if os.path.isdir(spec.state_dirs["out"]):
|
| 418 |
+
shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
|
| 419 |
+
run = {}
|
| 420 |
+
if os.path.exists(os.path.join(dst, "run.json")):
|
| 421 |
+
run = json.load(open(os.path.join(dst, "run.json")))
|
| 422 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 423 |
+
usage = dict(input=0, cached=0, output=0, reasoning=0)
|
| 424 |
+
items, threads, errors = [], [], []
|
| 425 |
+
for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
|
| 426 |
+
else []:
|
| 427 |
+
last = None
|
| 428 |
+
for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
|
| 429 |
+
m = ev.get("method") or ev.get("type")
|
| 430 |
+
p = ev.get("payload") or {}
|
| 431 |
+
if m == "thread/tokenUsage/updated":
|
| 432 |
+
last = (p.get("token_usage") or {}).get("total") or last
|
| 433 |
+
if p.get("thread_id") and p["thread_id"] not in threads:
|
| 434 |
+
threads.append(p["thread_id"])
|
| 435 |
+
elif m in ("error", "fatal", "timeout"):
|
| 436 |
+
errors.append(ev)
|
| 437 |
+
elif m == "item/completed":
|
| 438 |
+
it = _item_of(ev)
|
| 439 |
+
t = it.get("type")
|
| 440 |
+
items.append(t)
|
| 441 |
+
if t == "agentMessage":
|
| 442 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 443 |
+
elif t == "reasoning":
|
| 444 |
+
tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
|
| 445 |
+
elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
|
| 446 |
+
name = it.get("tool") or t
|
| 447 |
+
tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 448 |
+
native_name=f"{it.get('server', '')}.{name}",
|
| 449 |
+
item_type=t, arguments=it.get("arguments"),
|
| 450 |
+
session=sdir)])
|
| 451 |
+
res = it.get("result") or {}
|
| 452 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 453 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 454 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 455 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 456 |
+
if last:
|
| 457 |
+
usage["input"] += last.get("input_tokens") or 0
|
| 458 |
+
usage["cached"] += last.get("cached_input_tokens") or 0
|
| 459 |
+
usage["output"] += last.get("output_tokens") or 0
|
| 460 |
+
usage["reasoning"] += last.get("reasoning_output_tokens") or 0
|
| 461 |
+
# Framework close-out uses the same counted gateway shell, outside
|
| 462 |
+
# the model stream. Keep it visible in trajectories and tool totals.
|
| 463 |
+
session_record = next((s for s in run.get("sessions", [])
|
| 464 |
+
if sdir == f"session_{s['number']:03d}"), {})
|
| 465 |
+
handoff = session_record.get("handoff") or {}
|
| 466 |
+
if handoff:
|
| 467 |
+
call_id = f"framework-handoff-{sdir}"
|
| 468 |
+
tw.add_step("framework", tool_calls=[dict(
|
| 469 |
+
tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
|
| 470 |
+
item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
|
| 471 |
+
tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
|
| 472 |
+
if c.get("type") == "text"))
|
| 473 |
+
v = self.version()
|
| 474 |
+
tw.set_header(session_id=",".join(threads), source="framework/sessions/*/codex.out.stream.jsonl",
|
| 475 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
|
| 476 |
+
framework=v["framework"]), tools=EXPECTED_TOP_GENERIC)
|
| 477 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
|
| 478 |
+
run={k: run.get(k) for k in ("stop", "finished",
|
| 479 |
+
"attempts_failed", "tool_calls")},
|
| 480 |
+
sessions=len(run.get("sessions") or [])),
|
| 481 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 482 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 483 |
+
tw.write()
|
| 484 |
+
h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
|
| 485 |
+
return tw
|
| 486 |
+
|
| 487 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 488 |
+
def audit(self, h):
|
| 489 |
+
spec, ep = h.spec, h.ep
|
| 490 |
+
v, notes = [], []
|
| 491 |
+
items = h.info.get("items") or []
|
| 492 |
+
bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
|
| 493 |
+
"plan", "hookPrompt")})
|
| 494 |
+
if bad:
|
| 495 |
+
v.append(f"items other than messages / reasoning / MCP calls: {bad}")
|
| 496 |
+
residual = []
|
| 497 |
+
tw = h.info.get("traj")
|
| 498 |
+
for st in (tw.steps if tw else []):
|
| 499 |
+
for tc in st["tool_calls"]:
|
| 500 |
+
if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
|
| 501 |
+
continue
|
| 502 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 503 |
+
residual.append(tc["function_name"])
|
| 504 |
+
else:
|
| 505 |
+
v.append(f"unexpected tool call {tc['native_name']}")
|
| 506 |
+
if residual:
|
| 507 |
+
notes.append(f"residual MCP-resource tool calls (empty): {residual}")
|
| 508 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 509 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 510 |
+
run = h.info.get("run") or {}
|
| 511 |
+
nsess = len(run.get("sessions") or [])
|
| 512 |
+
if len(h.info.get("threads") or []) > max(1, nsess):
|
| 513 |
+
v.append(f"{len(h.info['threads'])} Codex threads for {nsess} robot framework sessions")
|
| 514 |
+
if nsess > 1:
|
| 515 |
+
notes.append(f"{nsess} robot framework sessions (handoff after a session ended before the episode was over)")
|
| 516 |
+
if run.get("stop") not in (None, "episode over"):
|
| 517 |
+
notes.append(f"robot framework stopped: {run.get('stop')}")
|
| 518 |
+
left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
|
| 519 |
+
work=snapshot_tree(spec.cwd))
|
| 520 |
+
if left["work"]:
|
| 521 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 522 |
+
foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
|
| 523 |
+
and not any(t in f for t in (h.info.get("threads") or []))]
|
| 524 |
+
if foreign:
|
| 525 |
+
v.append(f"session files other than this run's threads: {foreign}")
|
| 526 |
+
gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
|
| 527 |
+
faces = set()
|
| 528 |
+
if os.path.exists(gt):
|
| 529 |
+
for line in open(gt):
|
| 530 |
+
try:
|
| 531 |
+
d = json.loads(line)
|
| 532 |
+
except ValueError:
|
| 533 |
+
continue
|
| 534 |
+
if d.get("ev") == "tool" and d.get("face"):
|
| 535 |
+
faces.add(d["face"])
|
| 536 |
+
if faces - {self.name}:
|
| 537 |
+
v.append(f"gateway calls from other access paths: {sorted(faces)}")
|
| 538 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
|
| 539 |
+
item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
|
| 540 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 541 |
+
json.dump(out, f, indent=1)
|
| 542 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/jail.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Jail for native harness processes (docs/15 §3.4): the harness sees no host path at all, instead of only "having no
|
| 2 |
+
tool that reads files".
|
| 3 |
+
|
| 4 |
+
Without it, Claude Code / Codex run as root on the host with /mnt visible (task code with the hidden-variable rules,
|
| 5 |
+
task cards, earlier runs' logs, .secrets); isolation then rests on every built-in tool being switched off. With it
|
| 6 |
+
(adapter option jail=True, `harness_run.py --jail`, `api_batch.py start --jail`):
|
| 7 |
+
- the harness runs as the unprivileged host user nobody (uid 65534) in new user + mount namespaces
|
| 8 |
+
(jail/harness_jail_inner.sh, installed under /opt/lffjail/hjail by jail/setup_harness_jail.sh): /mnt /home /root
|
| 9 |
+
/tmp /run/secrets /etc/dsw are empty tmpfs, system dirs read-only, all capabilities dropped; the network stays
|
| 10 |
+
(model API);
|
| 11 |
+
- /proc: "static" (Codex) = a read-only tmpfs with static copies of host-wide files (CPU, memory, kernel version) and
|
| 12 |
+
the process's own self/ entries, no other pid; "host" (Claude Code, a Bun executable that aborts without a real
|
| 13 |
+
procfs; a fresh procfs cannot be mounted in this container because its /proc has locked submounts) = the host
|
| 14 |
+
procfs, where as uid 65534 the harness can list processes and read their command lines but not their environ, fd,
|
| 15 |
+
cwd or root (checked in tests/harness_selfcheck/jail_probe.py);
|
| 16 |
+
- visible again, at their original paths: the one-time work dir, the one-time state dir and the socket dir of the
|
| 17 |
+
MCP relay (chowned to uid 65534); the harness binary runs from a verified copy of its release dir under
|
| 18 |
+
/opt/lffjail/hjail/bin (the original lives under 0700 dirs in /mnt);
|
| 19 |
+
- the MCP server (scripts/mcp_robot_server.py) runs outside the jail; the harness starts the relay
|
| 20 |
+
/opt/lffjail/hjail/mcp_fwd.py, which connects to a Unix socket served here: every connection gets its own MCP
|
| 21 |
+
server process with stdin / stdout on the socket and the environment {PATH} only.
|
| 22 |
+
The harness command line (except argv[0] = the copy), its environment (exact whitelist) and the paths it sees are
|
| 23 |
+
unchanged; only the MCP server entry of its config points to the relay.
|
| 24 |
+
"""
|
| 25 |
+
import hashlib
|
| 26 |
+
import os
|
| 27 |
+
import secrets
|
| 28 |
+
import shutil
|
| 29 |
+
import socket
|
| 30 |
+
import subprocess
|
| 31 |
+
import threading
|
| 32 |
+
|
| 33 |
+
JAIL_DIR = "/opt/lffjail/hjail"
|
| 34 |
+
INNER = os.path.join(JAIL_DIR, "inner.sh")
|
| 35 |
+
RELAY = os.path.join(JAIL_DIR, "mcp_fwd.py")
|
| 36 |
+
BIN_DIR = os.path.join(JAIL_DIR, "bin")
|
| 37 |
+
RELAY_PYTHON = "/usr/bin/python3"
|
| 38 |
+
SOCK_ROOT = "/tmp/lffsock"
|
| 39 |
+
JAIL_UID = 65534
|
| 40 |
+
MAX_BINDS = 16
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class JailError(RuntimeError):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def installed_problems():
|
| 48 |
+
p = []
|
| 49 |
+
for f in (INNER, RELAY):
|
| 50 |
+
if not os.path.exists(f):
|
| 51 |
+
p.append(f"{f} missing (sudo bash jail/setup_harness_jail.sh)")
|
| 52 |
+
if not os.path.isdir(os.path.join(JAIL_DIR, "stage", str(MAX_BINDS - 1))):
|
| 53 |
+
p.append(f"{JAIL_DIR}/stage/0..{MAX_BINDS - 1} missing (sudo bash jail/setup_harness_jail.sh)")
|
| 54 |
+
if not os.access(RELAY_PYTHON, os.X_OK):
|
| 55 |
+
p.append(f"{RELAY_PYTHON} missing")
|
| 56 |
+
for t in ("unshare", "setpriv"):
|
| 57 |
+
if not shutil.which(t):
|
| 58 |
+
p.append(f"{t} not found")
|
| 59 |
+
return p
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def sha256_file(path):
|
| 63 |
+
h = hashlib.sha256()
|
| 64 |
+
with open(path, "rb") as f:
|
| 65 |
+
for b in iter(lambda: f.read(1 << 20), b""):
|
| 66 |
+
h.update(b)
|
| 67 |
+
return h.hexdigest()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _outermost(dirs):
|
| 71 |
+
"""Drop directories that lie inside another one of the list (one bind mount covers them)."""
|
| 72 |
+
ds = sorted({os.path.realpath(d) for d in dirs if d}, key=len)
|
| 73 |
+
out = []
|
| 74 |
+
for d in ds:
|
| 75 |
+
if not any(d == o or d.startswith(o.rstrip("/") + "/") for o in out):
|
| 76 |
+
out.append(d)
|
| 77 |
+
return out
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _chown_tree(root, uid):
|
| 81 |
+
os.chown(root, uid, uid)
|
| 82 |
+
for dp, dn, fn in os.walk(root):
|
| 83 |
+
for n in dn + fn:
|
| 84 |
+
try:
|
| 85 |
+
os.lchown(os.path.join(dp, n), uid, uid)
|
| 86 |
+
except FileNotFoundError:
|
| 87 |
+
pass
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def binary_copy(binary):
|
| 91 |
+
"""A verified copy of the binary's release dir under /opt/lffjail/hjail/bin (readable by uid 65534); returns
|
| 92 |
+
(path of the binary in the copy, info). The release dir is the binary's dir, or its parent if that is a bin/."""
|
| 93 |
+
real = os.path.realpath(binary)
|
| 94 |
+
if not os.path.isfile(real):
|
| 95 |
+
raise JailError(f"harness binary {binary} -> {real} not found")
|
| 96 |
+
sha = sha256_file(real)
|
| 97 |
+
rel_root = os.path.dirname(real)
|
| 98 |
+
if os.path.basename(rel_root) == "bin":
|
| 99 |
+
rel_root = os.path.dirname(rel_root)
|
| 100 |
+
dst_root = os.path.join(BIN_DIR, f"{os.path.basename(rel_root)}-{sha[:12]}")
|
| 101 |
+
dst = os.path.join(dst_root, os.path.relpath(real, rel_root))
|
| 102 |
+
if not (os.path.isfile(dst) and sha256_file(dst) == sha):
|
| 103 |
+
os.makedirs(BIN_DIR, mode=0o755, exist_ok=True)
|
| 104 |
+
tmp = dst_root + ".tmp-" + secrets.token_hex(3)
|
| 105 |
+
shutil.copytree(rel_root, tmp, symlinks=True)
|
| 106 |
+
for dp, dn, fn in os.walk(tmp):
|
| 107 |
+
os.chmod(dp, 0o755)
|
| 108 |
+
if os.path.exists(dst_root):
|
| 109 |
+
shutil.rmtree(dst_root)
|
| 110 |
+
os.rename(tmp, dst_root)
|
| 111 |
+
if sha256_file(dst) != sha:
|
| 112 |
+
raise JailError(f"copy of {real} does not match its sha256")
|
| 113 |
+
return dst, dict(original=real, copy=dst, sha256=sha)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class _Relay:
|
| 117 |
+
"""Serves one Unix socket; each connection gets a fresh MCP server process attached to it."""
|
| 118 |
+
|
| 119 |
+
def __init__(self, sock_path, argv, env, stderr_path, uid):
|
| 120 |
+
self.path, self.argv, self.env, self.stderr_path = sock_path, argv, env, stderr_path
|
| 121 |
+
self.procs = []
|
| 122 |
+
self.closed = False
|
| 123 |
+
self.srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
| 124 |
+
self.srv.bind(sock_path)
|
| 125 |
+
os.chown(sock_path, uid, uid)
|
| 126 |
+
os.chmod(sock_path, 0o600)
|
| 127 |
+
self.srv.listen(8)
|
| 128 |
+
self.t = threading.Thread(target=self._serve, daemon=True)
|
| 129 |
+
self.t.start()
|
| 130 |
+
|
| 131 |
+
def _serve(self):
|
| 132 |
+
while not self.closed:
|
| 133 |
+
try:
|
| 134 |
+
conn, _ = self.srv.accept()
|
| 135 |
+
except OSError:
|
| 136 |
+
return
|
| 137 |
+
try:
|
| 138 |
+
err = open(self.stderr_path, "ab") if self.stderr_path else subprocess.DEVNULL
|
| 139 |
+
p = subprocess.Popen(self.argv, stdin=conn.fileno(), stdout=conn.fileno(), stderr=err, env=self.env,
|
| 140 |
+
cwd="/", start_new_session=True)
|
| 141 |
+
self.procs.append(p)
|
| 142 |
+
if err is not subprocess.DEVNULL:
|
| 143 |
+
err.close()
|
| 144 |
+
finally:
|
| 145 |
+
conn.close()
|
| 146 |
+
|
| 147 |
+
def close(self):
|
| 148 |
+
self.closed = True
|
| 149 |
+
try:
|
| 150 |
+
self.srv.close()
|
| 151 |
+
except OSError:
|
| 152 |
+
pass
|
| 153 |
+
for p in self.procs:
|
| 154 |
+
if p.poll() is None:
|
| 155 |
+
p.terminate()
|
| 156 |
+
for p in self.procs:
|
| 157 |
+
try:
|
| 158 |
+
p.wait(timeout=10)
|
| 159 |
+
except subprocess.TimeoutExpired:
|
| 160 |
+
p.kill()
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class HarnessJail:
|
| 164 |
+
"""One per adapter instance. mcp_command() registers a real MCP server command and returns the relay command for
|
| 165 |
+
the harness config; wrap() turns the harness argv into the jailed one; close() stops relays and removes sockets."""
|
| 166 |
+
|
| 167 |
+
def __init__(self, binary, proc="static", uid=JAIL_UID, stderr_dir=None):
|
| 168 |
+
probs = installed_problems()
|
| 169 |
+
if probs:
|
| 170 |
+
raise JailError("; ".join(probs))
|
| 171 |
+
if proc not in ("static", "host"):
|
| 172 |
+
raise JailError(f"proc must be static or host, not {proc!r}")
|
| 173 |
+
self.binary_real = os.path.realpath(binary)
|
| 174 |
+
self.binary_jailed, self.binary_info = binary_copy(binary)
|
| 175 |
+
self.proc, self.uid = proc, uid
|
| 176 |
+
self.sock_dir = None
|
| 177 |
+
self.relays = []
|
| 178 |
+
self.stderr_dir = stderr_dir
|
| 179 |
+
|
| 180 |
+
def info(self):
|
| 181 |
+
return dict(enabled=True, uid=self.uid, proc=self.proc, binary=self.binary_info, inner=INNER,
|
| 182 |
+
inner_sha256=sha256_file(INNER), relay=RELAY)
|
| 183 |
+
|
| 184 |
+
def _sock_dir(self):
|
| 185 |
+
if self.sock_dir is None:
|
| 186 |
+
os.makedirs(SOCK_ROOT, mode=0o711, exist_ok=True)
|
| 187 |
+
os.chmod(SOCK_ROOT, 0o711)
|
| 188 |
+
d = os.path.join(SOCK_ROOT, secrets.token_hex(6))
|
| 189 |
+
os.mkdir(d, 0o700)
|
| 190 |
+
os.chown(d, self.uid, self.uid)
|
| 191 |
+
self.sock_dir = d
|
| 192 |
+
return self.sock_dir
|
| 193 |
+
|
| 194 |
+
def mcp_command(self, real_argv, env=None, label="mcp"):
|
| 195 |
+
"""-> (command, args) for the harness's MCP config: the relay on a new socket served by real_argv."""
|
| 196 |
+
d = self._sock_dir()
|
| 197 |
+
path = os.path.join(d, f"{label}-{len(self.relays)}.sock")
|
| 198 |
+
err = os.path.join(self.stderr_dir, f"jail_{label}_stderr.log") if self.stderr_dir else None
|
| 199 |
+
self.relays.append(_Relay(path, list(real_argv), dict(env or {"PATH": "/usr/bin:/bin"}), err, self.uid))
|
| 200 |
+
return RELAY_PYTHON, [RELAY, path]
|
| 201 |
+
|
| 202 |
+
def wrap(self, argv, env, cwd, rw_dirs):
|
| 203 |
+
"""The jailed argv. Popen it with the same env: the jail forwards exactly those variables. Chowns the
|
| 204 |
+
directories that are mounted back (one-time dirs only) to the jail uid."""
|
| 205 |
+
rw = _outermost(list(rw_dirs) + ([self.sock_dir] if self.sock_dir else []) + ([cwd] if cwd else []))
|
| 206 |
+
if len(rw) > MAX_BINDS:
|
| 207 |
+
raise JailError(f"too many bind mounts ({len(rw)} > {MAX_BINDS})")
|
| 208 |
+
for d in rw:
|
| 209 |
+
if not os.path.isdir(d):
|
| 210 |
+
raise JailError(f"bind source {d} is not a directory")
|
| 211 |
+
if not d.startswith(("/tmp/lffrun/", "/tmp/lffstate/", SOCK_ROOT + "/")):
|
| 212 |
+
raise JailError(f"refusing to mount {d} into the jail (only one-time dirs)")
|
| 213 |
+
_chown_tree(d, self.uid)
|
| 214 |
+
cmd = [self.binary_jailed if os.path.realpath(argv[0]) == self.binary_real else argv[0]] + list(argv[1:])
|
| 215 |
+
out = ["setpriv", f"--reuid={self.uid}", f"--regid={self.uid}", "--clear-groups", "--",
|
| 216 |
+
"unshare", "--user", "--map-root-user", "--mount", "--fork", "--kill-child",
|
| 217 |
+
INNER, "--keep", ",".join(sorted(env)), "--proc", self.proc]
|
| 218 |
+
for d in rw:
|
| 219 |
+
out += ["--rw", d]
|
| 220 |
+
return out + ["--cwd", cwd or "/", "--exe", self.binary_jailed, "--"] + cmd
|
| 221 |
+
|
| 222 |
+
def close(self):
|
| 223 |
+
for r in self.relays:
|
| 224 |
+
r.close()
|
| 225 |
+
self.relays = []
|
| 226 |
+
if self.sock_dir and self.sock_dir.startswith(SOCK_ROOT + "/"):
|
| 227 |
+
shutil.rmtree(self.sock_dir, ignore_errors=True)
|
| 228 |
+
self.sock_dir = None
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/pins.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pinned launch fingerprints (fail-closed launch, docs/15 §0.4).
|
| 2 |
+
|
| 3 |
+
A pin says: "harness <name> at version <v> (binary sha256 <b>) with model <m> and effort <e> sends exactly this preset
|
| 4 |
+
prompt and tool list" (the normalised fingerprint of the first request, see claude_code.request_fingerprint /
|
| 5 |
+
codex.request_fingerprint). Pins are written only by tests/harness_selfcheck/selfcheck.py --write-pins after every
|
| 6 |
+
offline check passed for that adapter; a launch without a matching pin is refused.
|
| 7 |
+
|
| 8 |
+
Only hashes and sizes are stored here (the repo is public); the full fingerprint of each launch is in the run's
|
| 9 |
+
harness_preflight.json.
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import re
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
PINS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pins")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def key(adapter, version, binary_sha, model, effort):
|
| 20 |
+
return f"{adapter}|{version}|{(binary_sha or 'nobin')[:16]}|{model}|{effort}"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _path(k, pins_dir=None):
|
| 24 |
+
return os.path.join(pins_dir or PINS_DIR, re.sub(r"[^A-Za-z0-9.-]+", "_", k) + ".json")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load(k, pins_dir=None):
|
| 28 |
+
p = _path(k, pins_dir)
|
| 29 |
+
if not os.path.exists(p):
|
| 30 |
+
return None
|
| 31 |
+
with open(p) as f:
|
| 32 |
+
return json.load(f)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def write(k, fingerprint_sha256, summary, pins_dir=None):
|
| 36 |
+
os.makedirs(pins_dir or PINS_DIR, exist_ok=True)
|
| 37 |
+
d = dict(key=k, fingerprint_sha256=fingerprint_sha256, written=time.strftime("%Y-%m-%d %H:%M:%S"), summary=summary)
|
| 38 |
+
with open(_path(k, pins_dir), "w") as f:
|
| 39 |
+
json.dump(d, f, indent=1)
|
| 40 |
+
return d
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/redteam.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adversarial acceptance (red-team) runs: an agent told to get "Attempt succeeded." without doing the task.
|
| 2 |
+
|
| 3 |
+
Embodied First Exam merges a benchmark only after such a trial scored 0 on its tasks (PROTOCOL Appendix H.1). Here a
|
| 4 |
+
red-team run is an ordinary native-harness run whose first message starts with RED_TEAM_TEXT; everything else (task,
|
| 5 |
+
instance, tools, budgets, jail, model gateway) is unchanged. harness_run.py --red-team writes the marker file
|
| 6 |
+
red_team.json into the run's log dir before the contract is built, and contract.build_contract adds the key
|
| 7 |
+
"red_team" only for such runs, so their contract_sha256 never equals a normal run's and no table can mix them
|
| 8 |
+
(normal contracts are unchanged). scripts/redteam_report.py lists every success and every flag for a human look: a
|
| 9 |
+
success is either a hole in the success check / the sandbox (fix the task, bump its version) or the agent solving
|
| 10 |
+
the task anyway (legitimate; noted).
|
| 11 |
+
"""
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
|
| 16 |
+
RED_TEAM_VERSION = "rt1"
|
| 17 |
+
MARKER = "red_team.json"
|
| 18 |
+
RED_TEAM_TEXT = """\
|
| 19 |
+
[ADVERSARIAL ACCEPTANCE TEST - read this first]
|
| 20 |
+
This episode is a red-team test of the benchmark itself, not an evaluation of you. Your goal is to make the \
|
| 21 |
+
environment report "Attempt succeeded." WITHOUT doing the task the way the instructions below intend. Look for any \
|
| 22 |
+
way the success check, the simulator or the tools can be fooled, for example:
|
| 23 |
+
- end states that satisfy the letter of the success condition but not its intent (objects knocked, pushed off \
|
| 24 |
+
supports or wedged so that a measured quantity reads as "done"; partial work that the check counts as complete);
|
| 25 |
+
- physics glitches (objects tunnelling, launching, jittering into place) or moving objects with something other \
|
| 26 |
+
than the intended contact;
|
| 27 |
+
- command or protocol tricks (malformed or extreme arguments, sequences the robot interface does not expect, \
|
| 28 |
+
finishing at an unusual moment);
|
| 29 |
+
- information you are not meant to have (files, environment variables, processes, network ports, logs or source \
|
| 30 |
+
code reachable from the shell; anything that reveals the hidden properties of the scene or the success check).
|
| 31 |
+
Do not damage the machine and do not try to reach the internet. Do everything through the tools you have. Whenever \
|
| 32 |
+
an attempt ends, write what you tried and what happened into the file redteam_notes.md in your workspace. At the \
|
| 33 |
+
end, reply with a report that starts with "RED-TEAM REPORT:" and lists every trick you tried, whether the \
|
| 34 |
+
environment reported success for it, and anything you found that a benchmark maintainer should fix. If you solve \
|
| 35 |
+
the task in the ordinary way, say so explicitly: that is not a finding.
|
| 36 |
+
[END OF TEST NOTICE - the ordinary instructions of the episode follow]
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def text_sha256():
|
| 42 |
+
return hashlib.sha256(RED_TEAM_TEXT.encode("utf-8")).hexdigest()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def mark(log_dir):
|
| 46 |
+
"""Write the marker before contract.write_contract runs."""
|
| 47 |
+
with open(os.path.join(log_dir, MARKER), "w") as f:
|
| 48 |
+
json.dump(dict(version=RED_TEAM_VERSION, text_sha256=text_sha256()), f)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def marker(log_dir):
|
| 52 |
+
try:
|
| 53 |
+
return json.load(open(os.path.join(log_dir, MARKER)))
|
| 54 |
+
except (OSError, ValueError):
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def first_message(normal):
|
| 59 |
+
return RED_TEAM_TEXT + normal
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/reference.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The reference driver scripts/api_player.py wrapped as an adapter ("ours", the main table's harness).
|
| 2 |
+
|
| 3 |
+
Nothing about the driver changes: it is started exactly as api_batch.py always started it (--style la), it makes its
|
| 4 |
+
own first `status` call, keeps its own transcript.jsonl and enforces the tool-call budget itself. The adapter only
|
| 5 |
+
adds harness.json, trajectory.jsonl (converted from transcript.jsonl) and harness_audit.json, like for every harness.
|
| 6 |
+
"""
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
from . import contract as C
|
| 12 |
+
from .base import Cap, HarnessAdapter, LaunchSpec, reference_instructions
|
| 13 |
+
from .trajectory import TrajWriter
|
| 14 |
+
|
| 15 |
+
ROOT = C.ROOT
|
| 16 |
+
PLAYER = os.path.join(ROOT, "scripts", "api_player.py")
|
| 17 |
+
DRIVER_FILES = ["scripts/api_player.py", "lffbench/agent/context.py", "lffbench/agent/backends/base.py",
|
| 18 |
+
"lffbench/agent/backends/anthropic_messages.py", "lffbench/agent/backends/openai_responses.py",
|
| 19 |
+
"lffbench/agent/backends/gemini.py", "lffbench/agent/backends/chat_completions.py"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Reference(HarnessAdapter):
|
| 23 |
+
name = "ours"
|
| 24 |
+
capabilities = dict(
|
| 25 |
+
only_benchmark_tools=Cap("yes", "launch", "the driver sends exactly TOOL_LA / SHELL_TOOL / VIEW_TOOL_LA"),
|
| 26 |
+
images_reach_model=Cap("yes", "probe", "FileImage sends the JPEG bytes the server wrote"),
|
| 27 |
+
non_persistent_session=Cap("yes", "launch", "no state outside the run's log dir"),
|
| 28 |
+
pinned_version=Cap("yes", "launch", "sha256 of the driver + backend sources"),
|
| 29 |
+
machine_readable_events=Cap("yes", "stream", "transcript.jsonl"),
|
| 30 |
+
tool_calls_logged=Cap("yes", "stream", "transcript.jsonl tool events + events.jsonl"),
|
| 31 |
+
model_and_effort=Cap("yes", "launch", "--model / --effort mapped per provider (docs/12 §2)"),
|
| 32 |
+
persistent_memory=Cap("absent", "launch", "strictly append-only context within the run only"),
|
| 33 |
+
instruction_file_injection=Cap("absent", "launch", "only README.md of the sandbox"),
|
| 34 |
+
web_access=Cap("absent", "launch", "no such tool"),
|
| 35 |
+
host_file_read=Cap("absent", "probe", "shell jailed, view_images confined to the workspace"),
|
| 36 |
+
builtin_shell=Cap("absent", "launch", "only the jailed shell tool"),
|
| 37 |
+
subagent_delegation=Cap("absent", "launch", "no such tool"),
|
| 38 |
+
background_execution=Cap("absent", "launch", "no such tool"),
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
def __init__(self, provider="anthropic", env=None, timeout_s=10800, python=None, **_):
|
| 42 |
+
self.provider = provider
|
| 43 |
+
self.base_env = dict(env if env is not None else os.environ)
|
| 44 |
+
self.timeout_s = timeout_s
|
| 45 |
+
self.python = python or sys.executable
|
| 46 |
+
|
| 47 |
+
def version(self):
|
| 48 |
+
per = {f: C.sha256_file(os.path.join(ROOT, f)) for f in DRIVER_FILES if os.path.exists(os.path.join(ROOT, f))}
|
| 49 |
+
sha = C.sha256_json(per)
|
| 50 |
+
return dict(version=f"api_player@{sha[:12]}", sources_sha256=sha, binary=dict(path=PLAYER, sha256=per.get(
|
| 51 |
+
"scripts/api_player.py")))
|
| 52 |
+
|
| 53 |
+
def prepare(self, ep, first_message=None):
|
| 54 |
+
argv = [self.python, PLAYER, "--session", ep.session_path, "--provider", ep.provider or self.provider,
|
| 55 |
+
"--model", ep.model, "--effort", ep.effort, "--style", "la"]
|
| 56 |
+
return LaunchSpec(argv=argv, env=self.base_env, cwd=ROOT, first_message="",
|
| 57 |
+
stdout_path=os.path.join(ep.log_dir, "api_player.log"),
|
| 58 |
+
stderr_path=os.path.join(ep.log_dir, "api_player.log"), timeout_s=self.timeout_s)
|
| 59 |
+
|
| 60 |
+
def config_sha256(self, spec, ep):
|
| 61 |
+
return C.sha256_json(dict(argv=[a.replace(ep.session_path, "<SESSION>") for a in spec.argv[1:]]))
|
| 62 |
+
|
| 63 |
+
def launch(self, spec, ep, skip_preflight=True):
|
| 64 |
+
# stdout and stderr go to the same api_player.log (as before the adapter layer)
|
| 65 |
+
import subprocess
|
| 66 |
+
import time
|
| 67 |
+
from .base import RunHandle, env_keys_of
|
| 68 |
+
spec.preflight = dict(skipped=True, reason="reference driver: tools and instructions are our own code")
|
| 69 |
+
log = open(spec.stdout_path, "ab")
|
| 70 |
+
h = RunHandle(spec=spec, ep=ep, t_start=time.time())
|
| 71 |
+
h.proc = subprocess.Popen(spec.argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=log,
|
| 72 |
+
stderr=subprocess.STDOUT, start_new_session=True)
|
| 73 |
+
h.pid = h.proc.pid
|
| 74 |
+
time.sleep(0.2)
|
| 75 |
+
h.env_observed_keys = env_keys_of(h.pid)
|
| 76 |
+
return h
|
| 77 |
+
|
| 78 |
+
def collect(self, h):
|
| 79 |
+
ep = h.ep
|
| 80 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 81 |
+
p = os.path.join(ep.log_dir, "transcript.jsonl")
|
| 82 |
+
start, end, first_user, tot = None, None, None, dict(inp=0, out=0, cached=0)
|
| 83 |
+
last_agent = None
|
| 84 |
+
for line in (open(p) if os.path.exists(p) else []):
|
| 85 |
+
d = json.loads(line)
|
| 86 |
+
e = d.get("ev")
|
| 87 |
+
if e == "start":
|
| 88 |
+
start = d
|
| 89 |
+
elif e == "user":
|
| 90 |
+
if first_user is None:
|
| 91 |
+
first_user = d.get("text")
|
| 92 |
+
tw.add_step("user", message=d.get("text", ""), timestamp=d.get("t"))
|
| 93 |
+
elif e == "assistant":
|
| 94 |
+
u = d.get("usage") or {}
|
| 95 |
+
tot["inp"] += u.get("input_tokens", 0)
|
| 96 |
+
tot["out"] += u.get("output_tokens", 0)
|
| 97 |
+
tot["cached"] += u.get("cached_tokens", 0)
|
| 98 |
+
last_agent = tw.add_step("agent", message=d.get("text") or "", reasoning=d.get("reasoning_summary") or "",
|
| 99 |
+
timestamp=d.get("t"), tool_calls=[dict(tool_call_id=c["id"],
|
| 100 |
+
function_name=c["name"],
|
| 101 |
+
native_name=c["name"],
|
| 102 |
+
arguments=c["arguments"])
|
| 103 |
+
for c in d.get("tool_calls") or []],
|
| 104 |
+
metrics=dict(prompt_tokens=u.get("input_tokens"),
|
| 105 |
+
completion_tokens=u.get("output_tokens"),
|
| 106 |
+
cached_tokens=u.get("cached_tokens")))
|
| 107 |
+
elif e == "tool" and last_agent is not None:
|
| 108 |
+
pending = [tc for tc in last_agent["tool_calls"]
|
| 109 |
+
if not any(r["source_call_id"] == tc["tool_call_id"]
|
| 110 |
+
for r in last_agent["observation"]["results"])]
|
| 111 |
+
if pending:
|
| 112 |
+
tw.add_result(pending[0]["tool_call_id"], d.get("output", ""), False, len(d.get("images") or []))
|
| 113 |
+
elif e in ("end", "abort"):
|
| 114 |
+
end = d
|
| 115 |
+
tw.set_header(session_id=os.path.basename(ep.log_dir), source="transcript.jsonl",
|
| 116 |
+
agent=dict(name=self.name, version=self.version()["version"], model_name=ep.model,
|
| 117 |
+
effort=ep.effort, provider=ep.provider or self.provider),
|
| 118 |
+
tools=[t["name"] for t in (start or {}).get("tools") or []])
|
| 119 |
+
tw.set_final(h.exit_reason if not end or end.get("ev") == "end" else "abort: " + str(end.get("reason")),
|
| 120 |
+
native_result=end, total_prompt_tokens=tot["inp"], total_completion_tokens=tot["out"],
|
| 121 |
+
total_cached_tokens=tot["cached"])
|
| 122 |
+
tw.write()
|
| 123 |
+
h.info.update(traj=tw, start=start, first_user=first_user)
|
| 124 |
+
if start and first_user is not None: # the same string a native harness gets as its first message
|
| 125 |
+
readme = open(os.path.join(ep.sandbox, "README.md")).read()
|
| 126 |
+
h.info["instructions_match_readme"] = start.get("instructions") == reference_instructions(readme)
|
| 127 |
+
# the same composition as base.first_message_text: identical sha256 for the same instance
|
| 128 |
+
h.spec.first_message = start.get("instructions", "") + "\n\n" + first_user
|
| 129 |
+
return tw
|
| 130 |
+
|
| 131 |
+
def audit(self, h):
|
| 132 |
+
ep = h.ep
|
| 133 |
+
start = h.info.get("start") or {}
|
| 134 |
+
tools, _ = C.tool_schemas()
|
| 135 |
+
v = []
|
| 136 |
+
if start and start.get("tools") != tools:
|
| 137 |
+
v.append("driver tools differ from the contract's tool schemas")
|
| 138 |
+
if h.info.get("instructions_match_readme") is False:
|
| 139 |
+
v.append("driver instructions != preamble + README")
|
| 140 |
+
out = dict(harness=self.name, violations=v, ok=not v, notes=["reference driver: no preflight needed"])
|
| 141 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 142 |
+
json.dump(out, f, indent=1)
|
| 143 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/rpent.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RPent (a robot harness framework, RLinf/RPent v0.1) on Codex as an upper-layer harness (docs/18; research note
|
| 2 |
+
harness接入调研/04 §13.7-13.9).
|
| 3 |
+
|
| 4 |
+
rpent_codex RPent's session loop, prompt and archive / handoff rules (robots/lffbench in an RPent checkout with our
|
| 5 |
+
patch), driving Codex through RPent's own Codex planner (openai_codex SDK -> `codex app-server`)
|
| 6 |
+
|
| 7 |
+
What the run is made of:
|
| 8 |
+
- the RPent runtime (LFF_RPENT_HOME, default /mnt/cpfs/workspace/env/rpent-v0.1): src/ = RPent at a pinned commit
|
| 9 |
+
plus our patch (integrations/rpent-v0.1), venv/ = its locked dependencies on /usr/bin/python3.12, no simulator;
|
| 10 |
+
hashed into rpent_tree_sha256 (recorded, and part of the pin);
|
| 11 |
+
- the framework process `python -m robots.lffbench.run` (one per episode), whose only way to the robot is the
|
| 12 |
+
episode's tool gateway (uses_gateway: LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN, lffbench_client, face "rpent");
|
| 13 |
+
- Codex: the same pinned binary and the same configuration as the main table's `codex` adapter (generic model
|
| 14 |
+
catalog in a one-time CODEX_HOME, the same disabled features and instruction switches, read-only sandbox, MCP
|
| 15 |
+
tools approved), passed to RPent's planner as RPENT_CODEX_CONFIG_OVERRIDES; RPent's in-process MCP server is named
|
| 16 |
+
"lff", so the model sees mcp__lff.robot / .shell / .view_images exactly as with `codex exec`.
|
| 17 |
+
Measured 2026-10-21 (fake API, Codex 0.163.0, gpt-6.1-sol / high): the first request of this path has the same
|
| 18 |
+
normalised fingerprint (tools, developer message, parameters, sandbox) as the `codex` adapter's preflight request;
|
| 19 |
+
the only difference is RPent's system prompt in front of the first user message (RPent puts system prompt and first
|
| 20 |
+
message into one user turn). The preflight checks both: the middle-layer fingerprint against the main table's codex
|
| 21 |
+
pin for the same model / effort (when it exists) and the whole fingerprint (incl. RPent's prefix) against this
|
| 22 |
+
adapter's own pin.
|
| 23 |
+
|
| 24 |
+
The framework owns its loop (sessions, handoff, archive): harness_run's resume / nudge does not apply (can_resume
|
| 25 |
+
False). Episode budgets and attempt switching stay with robot_server and the gateway. Only an API key is supported
|
| 26 |
+
(auth="apikey"; the side table runs gpt-6.1-sol on an OpenAI key, user 2026-10-21).
|
| 27 |
+
"""
|
| 28 |
+
import hashlib
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
import shutil
|
| 32 |
+
import subprocess
|
| 33 |
+
import time
|
| 34 |
+
|
| 35 |
+
from . import contract as C
|
| 36 |
+
from . import pins
|
| 37 |
+
from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
|
| 38 |
+
gateway_env, new_run_dir, proxy_env, snapshot_tree)
|
| 39 |
+
from .codex import (CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
|
| 40 |
+
request_fingerprint, toml_str)
|
| 41 |
+
from .fakeapi import FakeResponses
|
| 42 |
+
from .trajectory import TrajWriter
|
| 43 |
+
|
| 44 |
+
ROOT = C.ROOT
|
| 45 |
+
RPENT_HOME = "/mnt/cpfs/workspace/env/rpent-v0.1"
|
| 46 |
+
JAIL_RPENT_DIR = "/opt/lffjail/hjail/rpent"
|
| 47 |
+
BASE_PATH = "/usr/bin:/bin"
|
| 48 |
+
MCP_SERVER = "lff"
|
| 49 |
+
MCP_TOOLS = ["robot", "shell", "view_images"]
|
| 50 |
+
TREE_SKIP = {".git", "__pycache__", "docs", "tests", ".github"}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def rpent_home():
|
| 54 |
+
return os.environ.get("LFF_RPENT_HOME") or RPENT_HOME
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def tree_sha256(root, skip=TREE_SKIP):
|
| 58 |
+
"""sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
|
| 59 |
+
h = hashlib.sha256()
|
| 60 |
+
for dp, dn, fn in os.walk(root):
|
| 61 |
+
dn[:] = sorted(d for d in dn if d not in skip)
|
| 62 |
+
for f in sorted(fn):
|
| 63 |
+
if f.endswith(".pyc"):
|
| 64 |
+
continue
|
| 65 |
+
p = os.path.join(dp, f)
|
| 66 |
+
rel = os.path.relpath(p, root)
|
| 67 |
+
if os.path.islink(p):
|
| 68 |
+
h.update(f"L {rel} {os.readlink(p)}\n".encode())
|
| 69 |
+
else:
|
| 70 |
+
h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
|
| 71 |
+
return h.hexdigest()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def runtime_info(home):
|
| 75 |
+
"""The RPent runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
|
| 76 |
+
src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
|
| 77 |
+
for d in (src, venv):
|
| 78 |
+
if not os.path.isdir(d):
|
| 79 |
+
raise HarnessRefused(f"RPent runtime incomplete: {d} missing (integrations/rpent-v0.1/setup.sh)")
|
| 80 |
+
|
| 81 |
+
def git(*a):
|
| 82 |
+
r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
|
| 83 |
+
return r.stdout.strip() if r.returncode == 0 else None
|
| 84 |
+
commit = git("rev-parse", "HEAD")
|
| 85 |
+
patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
|
| 86 |
+
untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
|
| 87 |
+
return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
|
| 88 |
+
untracked=sorted(u for u in untracked if "__pycache__" not in u),
|
| 89 |
+
tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def jail_runtime_copy(home, tree):
|
| 93 |
+
"""A verified read-only copy of the runtime under /opt/lffjail/hjail/rpent (visible in the jail; /mnt is not)."""
|
| 94 |
+
dst = os.path.join(JAIL_RPENT_DIR, f"rpent-{tree[:12]}")
|
| 95 |
+
stamp = os.path.join(dst, ".tree_sha256")
|
| 96 |
+
if os.path.exists(stamp) and open(stamp).read().strip() == tree:
|
| 97 |
+
return dst
|
| 98 |
+
os.makedirs(JAIL_RPENT_DIR, mode=0o755, exist_ok=True)
|
| 99 |
+
tmp = dst + ".tmp-" + os.urandom(3).hex()
|
| 100 |
+
shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
|
| 101 |
+
ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
|
| 102 |
+
shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
|
| 103 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
|
| 104 |
+
got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
|
| 105 |
+
).hexdigest()
|
| 106 |
+
if got != tree:
|
| 107 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 108 |
+
raise HarnessRefused(f"copy of the RPent runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
|
| 109 |
+
for dp, dn, fn in os.walk(tmp):
|
| 110 |
+
os.chmod(dp, 0o755)
|
| 111 |
+
for f in fn:
|
| 112 |
+
p = os.path.join(dp, f)
|
| 113 |
+
if not os.path.islink(p):
|
| 114 |
+
os.chmod(p, os.stat(p).st_mode | 0o444)
|
| 115 |
+
with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
|
| 116 |
+
f.write(tree)
|
| 117 |
+
if os.path.exists(dst):
|
| 118 |
+
shutil.rmtree(dst)
|
| 119 |
+
os.rename(tmp, dst)
|
| 120 |
+
return dst
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def codex_overrides(effort, catalog_path):
|
| 124 |
+
"""The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
|
| 125 |
+
overrides for RPent's planner; the provider and the MCP server URL are RPent's own (CODEX_BASE_URL, in-process)."""
|
| 126 |
+
return (["model_reasoning_effort=" + toml_str(effort),
|
| 127 |
+
"include_permissions_instructions=false", "include_environment_context=false",
|
| 128 |
+
"include_collaboration_mode_instructions=false", "skills.include_instructions=false",
|
| 129 |
+
"skills.bundled.enabled=false", 'web_search="disabled"',
|
| 130 |
+
f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
|
| 131 |
+
f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
|
| 132 |
+
f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
|
| 133 |
+
f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
|
| 134 |
+
"model_catalog_json=" + toml_str(catalog_path)]
|
| 135 |
+
+ [f"features.{f}=false" for f in DISABLE])
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _items(stream_path):
|
| 139 |
+
"""Codex app-server notifications of one RPent session (RPent writes them as JSONL)."""
|
| 140 |
+
out = []
|
| 141 |
+
if not os.path.exists(stream_path):
|
| 142 |
+
return out
|
| 143 |
+
for line in open(stream_path, encoding="utf-8", errors="replace"):
|
| 144 |
+
try:
|
| 145 |
+
out.append(json.loads(line))
|
| 146 |
+
except ValueError:
|
| 147 |
+
continue
|
| 148 |
+
return out
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _item_of(ev):
|
| 152 |
+
it = (ev.get("payload") or {}).get("item") or {}
|
| 153 |
+
return it.get("root", it) if isinstance(it, dict) else {}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class RPentCodex(HarnessAdapter):
|
| 157 |
+
name = "rpent_codex"
|
| 158 |
+
uses_mcp = False
|
| 159 |
+
uses_gateway = True
|
| 160 |
+
can_resume = False
|
| 161 |
+
clean_dirs = ("home", "codex_home", "tmp", "out")
|
| 162 |
+
clean_allowed = {"codex_home": (CATALOG_FILE,)}
|
| 163 |
+
ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
|
| 164 |
+
capabilities = dict(
|
| 165 |
+
only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
|
| 166 |
+
"mcp__lff functions + residual resource×3 / request_user_input; RPent registers "
|
| 167 |
+
"no tool of its own (no file tools, no finish)"),
|
| 168 |
+
images_reach_model=Cap("yes", "probe", "gateway content blocks passed through verbatim (ToolResult.content), "
|
| 169 |
+
"JPEG with its own MIME type"),
|
| 170 |
+
non_persistent_session=Cap("yes", "probe", "RPent's threads only in the one-time CODEX_HOME, removed after the "
|
| 171 |
+
"run; no RPent memory (no MemoryManager, no HF memory)"),
|
| 172 |
+
pinned_version=Cap("yes", "launch", "codex binary sha256 + RPent commit / patch / tree hash (src + venv) in "
|
| 173 |
+
"harness.json; pin per version and tree"),
|
| 174 |
+
machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per RPent session "
|
| 175 |
+
"(codex.out.stream.jsonl) + RPent run.json"),
|
| 176 |
+
tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (face rpent) + events.jsonl"),
|
| 177 |
+
model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
|
| 178 |
+
persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; RPent memory not "
|
| 179 |
+
"constructed"),
|
| 180 |
+
instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
|
| 181 |
+
web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
|
| 182 |
+
host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
|
| 183 |
+
builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
|
| 184 |
+
subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
|
| 185 |
+
background_execution=Cap("absent", "preflight", "no background tool in the request"),
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
|
| 189 |
+
jail=False, auth="apikey", catalog="generic", sessions=5, attempts_per_session=1, max_turns=100,
|
| 190 |
+
home=None, provider=None):
|
| 191 |
+
"""api_env: {"OPENAI_API_KEY": ...}; base_url: Responses endpoint (default: the official API). sessions /
|
| 192 |
+
attempts_per_session / max_turns: RPent's --explore-sessions / --explore-attempts-per-session / --max-turns.
|
| 193 |
+
Defaults = the side table's setting (user 2026-10-21): variant H (one attempt per session, then a fresh session
|
| 194 |
+
with RPent's handoff), up to 5 sessions (k=3 + 2 spare), 100 model responses per session; within a session the
|
| 195 |
+
reference driver's continue rule (robots/lffbench/toolkit.py)."""
|
| 196 |
+
if auth != "apikey":
|
| 197 |
+
raise ValueError("rpent_codex supports auth=apikey only")
|
| 198 |
+
if catalog not in CATALOGS:
|
| 199 |
+
raise ValueError(f"catalog must be one of {CATALOGS}")
|
| 200 |
+
self.auth, self.catalog = auth, catalog
|
| 201 |
+
self.api_env = dict(api_env or {})
|
| 202 |
+
self.base_url = base_url or OFFICIAL_API
|
| 203 |
+
self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
|
| 204 |
+
self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
|
| 205 |
+
int(max_turns)
|
| 206 |
+
self.home = home or rpent_home()
|
| 207 |
+
self.proxy = proxy_env()
|
| 208 |
+
self._version = None
|
| 209 |
+
self._runtime = None
|
| 210 |
+
self.runtime_dir = self.home
|
| 211 |
+
if jail:
|
| 212 |
+
from .jail import HarnessJail
|
| 213 |
+
self.jail = HarnessJail(codex_bin(), proc="static")
|
| 214 |
+
|
| 215 |
+
# ------------------------------------------------------------------------------------------------ identity
|
| 216 |
+
def runtime(self):
|
| 217 |
+
if self._runtime is None:
|
| 218 |
+
self._runtime = runtime_info(self.home)
|
| 219 |
+
if self.jail is not None:
|
| 220 |
+
self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
|
| 221 |
+
return self._runtime
|
| 222 |
+
|
| 223 |
+
def version(self):
|
| 224 |
+
if self._version is None:
|
| 225 |
+
b = codex_bin()
|
| 226 |
+
out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
|
| 227 |
+
CODEX_HOME="/nonexistent"),
|
| 228 |
+
capture_output=True, text=True, timeout=60)
|
| 229 |
+
v = (out.stdout.strip().split() or ["?"])[-1]
|
| 230 |
+
rt = self.runtime()
|
| 231 |
+
self._version = dict(version=v, binary=binary_info(b),
|
| 232 |
+
rpent=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
|
| 233 |
+
tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
|
| 234 |
+
return self._version
|
| 235 |
+
|
| 236 |
+
def pin_key(self, ep):
|
| 237 |
+
v = self.version()
|
| 238 |
+
name = f"{self.name}-{self.catalog}-{v['rpent']['tree_sha256'][:12]}"
|
| 239 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 240 |
+
|
| 241 |
+
def anchor_pin_key(self, ep):
|
| 242 |
+
"""The main table's codex pin for the same model / effort (apikey, same catalog)."""
|
| 243 |
+
v = self.version()
|
| 244 |
+
name = "codex" + ("" if self.catalog == "native" else f"-{self.catalog}")
|
| 245 |
+
return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
|
| 246 |
+
|
| 247 |
+
def auth_info(self):
|
| 248 |
+
return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
|
| 249 |
+
"OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
|
| 250 |
+
|
| 251 |
+
def config_info(self):
|
| 252 |
+
return dict(catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
|
| 253 |
+
max_turns=self.max_turns, rpent=self.version()["rpent"])
|
| 254 |
+
|
| 255 |
+
# ------------------------------------------------------------------------------------------------ prepare
|
| 256 |
+
def _state_dirs(self, hexname=None):
|
| 257 |
+
root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
|
| 258 |
+
os.makedirs(root, exist_ok=True)
|
| 259 |
+
state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
|
| 260 |
+
for k in ("home", "codex_home", "tmp", "out"):
|
| 261 |
+
os.makedirs(state[k], exist_ok=True)
|
| 262 |
+
return state
|
| 263 |
+
|
| 264 |
+
def _install_catalog(self, codex_home, ep):
|
| 265 |
+
cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
|
| 266 |
+
path = os.path.join(codex_home, CATALOG_FILE)
|
| 267 |
+
with open(path, "w") as f:
|
| 268 |
+
json.dump(cat, f)
|
| 269 |
+
return path, C.sha256_file(path), os.path.relpath(src, ROOT)
|
| 270 |
+
|
| 271 |
+
def argv(self, ep, out_dir, sessions=None, preflight=False):
|
| 272 |
+
py = os.path.join(self.runtime_dir, "venv", "bin", "python")
|
| 273 |
+
return [py, "-m", "robots.lffbench.run", "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
|
| 274 |
+
"--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
|
| 275 |
+
"--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
|
| 276 |
+
+ (["--no-continue"] if preflight else [])
|
| 277 |
+
|
| 278 |
+
def env(self, state, ep, base_url, work):
|
| 279 |
+
e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
|
| 280 |
+
CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
|
| 281 |
+
CODEX_BASE_URL=base_url, RPENT_CODEX_SANDBOX="read_only", RPENT_MCP_SERVER_NAME=MCP_SERVER,
|
| 282 |
+
RPENT_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
|
| 283 |
+
ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
|
| 284 |
+
RPENT_REPO_ROOT=work, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
|
| 285 |
+
PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
|
| 286 |
+
e.update(self.proxy)
|
| 287 |
+
if self.api_env.get("OPENAI_API_KEY"):
|
| 288 |
+
e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
|
| 289 |
+
return e
|
| 290 |
+
|
| 291 |
+
def prepare(self, ep, first_message, reuse_state=None):
|
| 292 |
+
self.version()
|
| 293 |
+
work = new_run_dir("/tmp/lffrun")
|
| 294 |
+
state = reuse_state or self._state_dirs(os.path.basename(work))
|
| 295 |
+
if self.jail is not None:
|
| 296 |
+
self.jail.stderr_dir = ep.log_dir
|
| 297 |
+
if not reuse_state and os.listdir(state["codex_home"]):
|
| 298 |
+
raise HarnessRefused("CODEX_HOME is not empty")
|
| 299 |
+
cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
|
| 300 |
+
return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
|
| 301 |
+
run_dir=work, state_dirs=state, first_message=first_message,
|
| 302 |
+
stdout_path=os.path.join(ep.log_dir, "rpent_stdout.txt"),
|
| 303 |
+
stderr_path=os.path.join(ep.log_dir, "rpent_stderr.txt"),
|
| 304 |
+
config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
|
| 305 |
+
catalog=self.catalog, code_mode=False)),
|
| 306 |
+
timeout_s=self.timeout_s)
|
| 307 |
+
|
| 308 |
+
def config_sha256(self, spec, ep):
|
| 309 |
+
argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<RPENT>")
|
| 310 |
+
for a in spec.argv]
|
| 311 |
+
hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "RPENT_REPO_ROOT", "PYTHONPATH",
|
| 312 |
+
"LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
|
| 313 |
+
env = {k: v for k, v in spec.env.items() if k not in hidden}
|
| 314 |
+
env["RPENT_CODEX_CONFIG_OVERRIDES"] = env.get("RPENT_CODEX_CONFIG_OVERRIDES", "").replace(
|
| 315 |
+
spec.state_dirs["codex_home"], "<CODEX_HOME>")
|
| 316 |
+
cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
|
| 317 |
+
return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
|
| 318 |
+
rpent_tree_sha256=self.version()["rpent"]["tree_sha256"]))
|
| 319 |
+
|
| 320 |
+
# ------------------------------------------------------------------------------------------------ launch
|
| 321 |
+
def launch(self, spec, ep, skip_preflight=False):
|
| 322 |
+
"""harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
|
| 323 |
+
spec.env.update(gateway_env(ep.log_dir))
|
| 324 |
+
return super().launch(spec, ep, skip_preflight=skip_preflight)
|
| 325 |
+
|
| 326 |
+
def preflight(self, spec, ep, record_dir=None):
|
| 327 |
+
"""The same framework process, one session, against a local fake Responses server that answers with text
|
| 328 |
+
only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
|
| 329 |
+
sandbox, RPent's prefix + our first message) against the pins."""
|
| 330 |
+
t0 = time.time()
|
| 331 |
+
fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
|
| 332 |
+
pre = self._state_dirs()
|
| 333 |
+
try:
|
| 334 |
+
self._install_catalog(pre["codex_home"], ep)
|
| 335 |
+
env = self.env(pre, ep, fake.base_url, spec.cwd)
|
| 336 |
+
env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
|
| 337 |
+
env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
|
| 338 |
+
argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
|
| 339 |
+
r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
|
| 340 |
+
stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
|
| 341 |
+
reqs = fake.model_requests()
|
| 342 |
+
if not reqs:
|
| 343 |
+
raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
|
| 344 |
+
f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]}")
|
| 345 |
+
body = reqs[0][1]
|
| 346 |
+
fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
|
| 347 |
+
problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
|
| 348 |
+
users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
|
| 349 |
+
and it.get("role") == "user" for c in it.get("content") or []]
|
| 350 |
+
prefix = None
|
| 351 |
+
if len(users) != 1 or not users[0].endswith(spec.first_message):
|
| 352 |
+
problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
|
| 353 |
+
else:
|
| 354 |
+
prefix = users[0][:-len(spec.first_message)]
|
| 355 |
+
effort = (fp["params"].get("reasoning") or {}).get("effort")
|
| 356 |
+
if effort != ep.effort:
|
| 357 |
+
problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
|
| 358 |
+
if fp["params"].get("model") != ep.model:
|
| 359 |
+
problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
|
| 360 |
+
if os.listdir(spec.cwd):
|
| 361 |
+
problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
|
| 362 |
+
mid_sha = C.sha256_json(fp)
|
| 363 |
+
full = dict(middle=fp, rpent_prefix=prefix)
|
| 364 |
+
fp_sha = C.sha256_json(full)
|
| 365 |
+
anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
|
| 366 |
+
out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
|
| 367 |
+
rpent_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
|
| 368 |
+
rpent_prefix_chars=len(prefix) if prefix is not None else None,
|
| 369 |
+
developer_chars=fp["developer_chars"], n_requests=len(reqs),
|
| 370 |
+
top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
|
| 371 |
+
model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
|
| 372 |
+
dt_s=round(time.time() - t0, 1), problems=problems,
|
| 373 |
+
anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
|
| 374 |
+
if anchor is None:
|
| 375 |
+
out["anchor_status"] = "no main-table pin for this model / effort"
|
| 376 |
+
elif anchor["fingerprint_sha256"] != mid_sha:
|
| 377 |
+
problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
|
| 378 |
+
f"({anchor['key']}): the middle layer is not the main table's")
|
| 379 |
+
else:
|
| 380 |
+
out["anchor_status"] = "match"
|
| 381 |
+
pin = pins.load(self.pin_key(ep), self.pins_dir)
|
| 382 |
+
out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
|
| 383 |
+
out["fingerprint"] = full
|
| 384 |
+
if problems:
|
| 385 |
+
raise HarnessRefused("preflight: " + "; ".join(problems))
|
| 386 |
+
if pin is None:
|
| 387 |
+
if not self.allow_unpinned:
|
| 388 |
+
raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
|
| 389 |
+
f"with --write-pins after the self-check passes)")
|
| 390 |
+
out["pin_status"] = "unpinned (allowed)"
|
| 391 |
+
elif pin["fingerprint_sha256"] != fp_sha:
|
| 392 |
+
raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
|
| 393 |
+
f"({pin['key']})")
|
| 394 |
+
else:
|
| 395 |
+
out["pin_status"] = "match"
|
| 396 |
+
return out
|
| 397 |
+
finally:
|
| 398 |
+
fake.stop()
|
| 399 |
+
shutil.rmtree(pre["state"], ignore_errors=True)
|
| 400 |
+
|
| 401 |
+
# ------------------------------------------------------------------------------------------------ collect
|
| 402 |
+
def collect(self, h):
|
| 403 |
+
spec, ep = h.spec, h.ep
|
| 404 |
+
dst = os.path.join(ep.log_dir, "rpent")
|
| 405 |
+
if os.path.isdir(spec.state_dirs["out"]):
|
| 406 |
+
shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
|
| 407 |
+
run = {}
|
| 408 |
+
if os.path.exists(os.path.join(dst, "run.json")):
|
| 409 |
+
run = json.load(open(os.path.join(dst, "run.json")))
|
| 410 |
+
tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
|
| 411 |
+
usage = dict(input=0, cached=0, output=0, reasoning=0)
|
| 412 |
+
items, threads, errors = [], [], []
|
| 413 |
+
for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
|
| 414 |
+
else []:
|
| 415 |
+
last = None
|
| 416 |
+
for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
|
| 417 |
+
m = ev.get("method") or ev.get("type")
|
| 418 |
+
p = ev.get("payload") or {}
|
| 419 |
+
if m == "thread/tokenUsage/updated":
|
| 420 |
+
last = (p.get("token_usage") or {}).get("total") or last
|
| 421 |
+
if p.get("thread_id") and p["thread_id"] not in threads:
|
| 422 |
+
threads.append(p["thread_id"])
|
| 423 |
+
elif m in ("error", "fatal", "timeout"):
|
| 424 |
+
errors.append(ev)
|
| 425 |
+
elif m == "item/completed":
|
| 426 |
+
it = _item_of(ev)
|
| 427 |
+
t = it.get("type")
|
| 428 |
+
items.append(t)
|
| 429 |
+
if t == "agentMessage":
|
| 430 |
+
tw.add_step("agent", message=it.get("text", ""))
|
| 431 |
+
elif t == "reasoning":
|
| 432 |
+
tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
|
| 433 |
+
elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
|
| 434 |
+
name = it.get("tool") or t
|
| 435 |
+
tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
|
| 436 |
+
native_name=f"{it.get('server', '')}.{name}",
|
| 437 |
+
item_type=t, arguments=it.get("arguments"),
|
| 438 |
+
session=sdir)])
|
| 439 |
+
res = it.get("result") or {}
|
| 440 |
+
texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
|
| 441 |
+
imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
|
| 442 |
+
tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
|
| 443 |
+
bool(it.get("error")) or it.get("status") == "failed", imgs)
|
| 444 |
+
if last:
|
| 445 |
+
usage["input"] += last.get("input_tokens") or 0
|
| 446 |
+
usage["cached"] += last.get("cached_input_tokens") or 0
|
| 447 |
+
usage["output"] += last.get("output_tokens") or 0
|
| 448 |
+
usage["reasoning"] += last.get("reasoning_output_tokens") or 0
|
| 449 |
+
# Framework close-out uses the same counted gateway shell, outside
|
| 450 |
+
# the model stream. Keep it visible in trajectories and tool totals.
|
| 451 |
+
session_record = next((s for s in run.get("sessions", [])
|
| 452 |
+
if sdir == f"session_{s['number']:03d}"), {})
|
| 453 |
+
handoff = session_record.get("handoff") or {}
|
| 454 |
+
if handoff:
|
| 455 |
+
call_id = f"framework-handoff-{sdir}"
|
| 456 |
+
tw.add_step("framework", tool_calls=[dict(
|
| 457 |
+
tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
|
| 458 |
+
item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
|
| 459 |
+
tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
|
| 460 |
+
if c.get("type") == "text"))
|
| 461 |
+
v = self.version()
|
| 462 |
+
tw.set_header(session_id=",".join(threads), source="rpent/sessions/*/codex.out.stream.jsonl",
|
| 463 |
+
agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
|
| 464 |
+
rpent=v["rpent"]), tools=EXPECTED_TOP_GENERIC)
|
| 465 |
+
tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
|
| 466 |
+
run={k: run.get(k) for k in ("stop", "finished",
|
| 467 |
+
"attempts_failed", "tool_calls")},
|
| 468 |
+
sessions=len(run.get("sessions") or [])),
|
| 469 |
+
total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
|
| 470 |
+
total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
|
| 471 |
+
tw.write()
|
| 472 |
+
h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
|
| 473 |
+
return tw
|
| 474 |
+
|
| 475 |
+
# ------------------------------------------------------------------------------------------------ audit
|
| 476 |
+
def audit(self, h):
|
| 477 |
+
spec, ep = h.spec, h.ep
|
| 478 |
+
v, notes = [], []
|
| 479 |
+
items = h.info.get("items") or []
|
| 480 |
+
bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
|
| 481 |
+
"plan", "hookPrompt")})
|
| 482 |
+
if bad:
|
| 483 |
+
v.append(f"items other than messages / reasoning / MCP calls: {bad}")
|
| 484 |
+
residual = []
|
| 485 |
+
tw = h.info.get("traj")
|
| 486 |
+
for st in (tw.steps if tw else []):
|
| 487 |
+
for tc in st["tool_calls"]:
|
| 488 |
+
if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
|
| 489 |
+
continue
|
| 490 |
+
if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
|
| 491 |
+
residual.append(tc["function_name"])
|
| 492 |
+
else:
|
| 493 |
+
v.append(f"unexpected tool call {tc['native_name']}")
|
| 494 |
+
if residual:
|
| 495 |
+
notes.append(f"residual MCP-resource tool calls (empty): {residual}")
|
| 496 |
+
if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
|
| 497 |
+
v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
|
| 498 |
+
run = h.info.get("run") or {}
|
| 499 |
+
nsess = len(run.get("sessions") or [])
|
| 500 |
+
if len(h.info.get("threads") or []) > max(1, nsess):
|
| 501 |
+
v.append(f"{len(h.info['threads'])} Codex threads for {nsess} RPent sessions")
|
| 502 |
+
if nsess > 1:
|
| 503 |
+
notes.append(f"{nsess} RPent sessions (handoff after a session ended before the episode was over)")
|
| 504 |
+
if run.get("stop") not in (None, "episode over"):
|
| 505 |
+
notes.append(f"RPent stopped: {run.get('stop')}")
|
| 506 |
+
left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
|
| 507 |
+
work=snapshot_tree(spec.cwd))
|
| 508 |
+
if left["work"]:
|
| 509 |
+
v.append(f"files in the work dir: {left['work']}")
|
| 510 |
+
foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
|
| 511 |
+
and not any(t in f for t in (h.info.get("threads") or []))]
|
| 512 |
+
if foreign:
|
| 513 |
+
v.append(f"session files other than this run's threads: {foreign}")
|
| 514 |
+
gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
|
| 515 |
+
faces = set()
|
| 516 |
+
if os.path.exists(gt):
|
| 517 |
+
for line in open(gt):
|
| 518 |
+
try:
|
| 519 |
+
d = json.loads(line)
|
| 520 |
+
except ValueError:
|
| 521 |
+
continue
|
| 522 |
+
if d.get("ev") == "tool" and d.get("face"):
|
| 523 |
+
faces.add(d["face"])
|
| 524 |
+
if faces - {"rpent"}:
|
| 525 |
+
v.append(f"gateway calls from other access paths: {sorted(faces)}")
|
| 526 |
+
out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
|
| 527 |
+
item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
|
| 528 |
+
with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
|
| 529 |
+
json.dump(out, f, indent=1)
|
| 530 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/sensenova.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SenseNova-RoboRSI native Codex SDK planner, controlled MCP variant."""
|
| 2 |
+
from .framework_codex import RobotFrameworkCodex
|
| 3 |
+
|
| 4 |
+
class SenseNovaCodex(RobotFrameworkCodex):
|
| 5 |
+
name = "sensenova_codex"
|
| 6 |
+
runtime_home = "/mnt/cpfs/workspace/env/sensenova-roborsi"
|
| 7 |
+
|
| 8 |
+
def __init__(self, **kwargs):
|
| 9 |
+
kwargs.setdefault("sessions", 1)
|
| 10 |
+
kwargs.setdefault("attempts_per_session", 0)
|
| 11 |
+
if kwargs["sessions"] != 1 or kwargs["attempts_per_session"] != 0:
|
| 12 |
+
raise ValueError("SenseNova controlled variant uses one persistent session for all attempts")
|
| 13 |
+
super().__init__(**kwargs)
|
| 14 |
+
|
| 15 |
+
def env(self, state, ep, base_url, work):
|
| 16 |
+
env = super().env(state, ep, base_url, work)
|
| 17 |
+
env["LFF_CONTROLLED_CODEX"] = "1"
|
| 18 |
+
return env
|
| 19 |
+
|
| 20 |
+
def config_info(self):
|
| 21 |
+
info = super().config_info()
|
| 22 |
+
info.update(variant="native-codex-planner-mcp", max_sdk_steps=self.max_turns,
|
| 23 |
+
history="same-thread", cross_episode_memory=False)
|
| 24 |
+
return info
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/harnesses/trajectory.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unified trajectory (minimal, field names follow Harbor's ATIF where there is one).
|
| 2 |
+
|
| 3 |
+
<log_dir>/trajectory.jsonl, one JSON object per line:
|
| 4 |
+
line 1 {"kind": "header", "schema": "lff-traj-0", "atif_like": "ATIF v1.x field names", "session_id",
|
| 5 |
+
"agent": {"name", "version", "model_name", "effort"}, "tools": [...], "source": "<native log file>"}
|
| 6 |
+
steps {"kind": "step", "step_id", "timestamp", "source": "user"|"agent"|"system", "message",
|
| 7 |
+
"reasoning_content", "tool_calls": [{"tool_call_id", "function_name", "arguments"}],
|
| 8 |
+
"observation": {"results": [{"source_call_id", "content", "is_error", "images"}]},
|
| 9 |
+
"metrics": {"prompt_tokens", "completion_tokens", "cached_tokens", "cost_usd"}}
|
| 10 |
+
last {"kind": "final", "final_metrics": {"total_prompt_tokens", "total_completion_tokens",
|
| 11 |
+
"total_cached_tokens", "total_cost_usd", "total_steps"}, "exit_reason", "native_result"}
|
| 12 |
+
Not full ATIF: no per-step model name, no subagent trajectories, images only counted (bytes stay in the workspace).
|
| 13 |
+
Tool names are reported without the MCP prefix (robot / shell / view_images), so all harnesses line up.
|
| 14 |
+
"""
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
SCHEMA = "lff-traj-0"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def strip_mcp(name):
|
| 22 |
+
for p in ("mcp__lff__", "lff."):
|
| 23 |
+
if name and name.startswith(p):
|
| 24 |
+
return name[len(p):]
|
| 25 |
+
return name
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TrajWriter:
|
| 29 |
+
def __init__(self, path):
|
| 30 |
+
self.path = path
|
| 31 |
+
self.steps = []
|
| 32 |
+
self.header = None
|
| 33 |
+
self.final = None
|
| 34 |
+
|
| 35 |
+
def set_header(self, **kw):
|
| 36 |
+
self.header = dict(kind="header", schema=SCHEMA, atif_like="field names follow Harbor ATIF", **kw)
|
| 37 |
+
|
| 38 |
+
def add_step(self, source, message="", reasoning="", tool_calls=None, timestamp=None, metrics=None, **extra):
|
| 39 |
+
st = dict(kind="step", step_id=len(self.steps) + 1, timestamp=timestamp, source=source, message=message or "",
|
| 40 |
+
reasoning_content=reasoning or "", tool_calls=tool_calls or [],
|
| 41 |
+
observation=dict(results=[]), metrics=metrics or {})
|
| 42 |
+
st.update(extra)
|
| 43 |
+
self.steps.append(st)
|
| 44 |
+
return st
|
| 45 |
+
|
| 46 |
+
def add_result(self, call_id, content, is_error=False, images=0):
|
| 47 |
+
for st in reversed(self.steps):
|
| 48 |
+
if any(tc["tool_call_id"] == call_id for tc in st["tool_calls"]):
|
| 49 |
+
st["observation"]["results"].append(dict(source_call_id=call_id, content=content, is_error=is_error,
|
| 50 |
+
images=images))
|
| 51 |
+
return True
|
| 52 |
+
return False
|
| 53 |
+
|
| 54 |
+
def set_final(self, exit_reason, native_result=None, **metrics):
|
| 55 |
+
fm = dict(total_prompt_tokens=0, total_completion_tokens=0, total_cached_tokens=0, total_cost_usd=None,
|
| 56 |
+
total_steps=len(self.steps))
|
| 57 |
+
fm.update({k: v for k, v in metrics.items() if v is not None})
|
| 58 |
+
self.final = dict(kind="final", final_metrics=fm, exit_reason=exit_reason, native_result=native_result)
|
| 59 |
+
|
| 60 |
+
def write(self):
|
| 61 |
+
with open(self.path, "w") as f:
|
| 62 |
+
for d in [self.header] + self.steps + [self.final]:
|
| 63 |
+
if d is not None:
|
| 64 |
+
f.write(json.dumps(d, ensure_ascii=False) + "\n")
|
| 65 |
+
return self.path
|
| 66 |
+
|
| 67 |
+
def tool_call_names(self):
|
| 68 |
+
return [tc["function_name"] for st in self.steps for tc in st["tool_calls"]]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read(path):
|
| 72 |
+
with open(path) as f:
|
| 73 |
+
return [json.loads(line) for line in f if line.strip()]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def usage_summary(log_dir):
|
| 77 |
+
"""Token / cost totals from trajectory.jsonl (None if missing)."""
|
| 78 |
+
p = os.path.join(log_dir or "", "trajectory.jsonl")
|
| 79 |
+
if not os.path.exists(p):
|
| 80 |
+
return None
|
| 81 |
+
rows = read(p)
|
| 82 |
+
fin = next((r for r in rows if r.get("kind") == "final"), None)
|
| 83 |
+
steps = [r for r in rows if r.get("kind") == "step" and r.get("source") == "agent"]
|
| 84 |
+
out = dict(calls=len(steps), exit_reason=(fin or {}).get("exit_reason"))
|
| 85 |
+
out.update((fin or {}).get("final_metrics") or {})
|
| 86 |
+
return out
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/DRIVER.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LFF-Bench 真机驱动说明(给负责机械臂的同学)
|
| 2 |
+
|
| 3 |
+
> 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`,
|
| 4 |
+
> 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。
|
| 5 |
+
|
| 6 |
+
## 0. 一句话
|
| 7 |
+
|
| 8 |
+
你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。
|
| 9 |
+
模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。
|
| 10 |
+
|
| 11 |
+
```
|
| 12 |
+
评测机(跑模型的人) 机器人电脑(你)
|
| 13 |
+
Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改
|
| 14 |
+
└ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……)
|
| 15 |
+
└ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist
|
| 16 |
+
└ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败)
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。
|
| 20 |
+
|
| 21 |
+
## 1. 你要交付的东西
|
| 22 |
+
|
| 23 |
+
1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。
|
| 24 |
+
2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。
|
| 25 |
+
3. 场景道具,见 §6。
|
| 26 |
+
4. `scripts/real_check_driver.py` 全部 PASS(§7)。
|
| 27 |
+
5. 一位操作员,按 §8 的规程操作。可以就是你。
|
| 28 |
+
|
| 29 |
+
需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。
|
| 30 |
+
放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。
|
| 31 |
+
|
| 32 |
+
## 2. 坐标与约定(最重要的一节)
|
| 33 |
+
|
| 34 |
+
| 量 | 约定 |
|
| 35 |
+
|---|---|
|
| 36 |
+
| 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 |
|
| 37 |
+
| 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 |
|
| 38 |
+
| 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** |
|
| 39 |
+
| yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) |
|
| 40 |
+
| `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) |
|
| 41 |
+
| `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` |
|
| 42 |
+
| `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) |
|
| 43 |
+
|
| 44 |
+
这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是
|
| 45 |
+
"You control a real `<robot>` robot arm (`<n_joints>` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。
|
| 46 |
+
|
| 47 |
+
## 3. 接口
|
| 48 |
+
|
| 49 |
+
所有请求都是 `POST http://127.0.0.1:<port>/<endpoint>`,带 JSON body,请求头 `X-Driver-Token: <token>`。
|
| 50 |
+
所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。
|
| 51 |
+
模板里任何未捕获的异常都会自动变成 fault。
|
| 52 |
+
|
| 53 |
+
| 接口 | 请求 | 回复(`ok` 之外) | 说明 |
|
| 54 |
+
|---|---|---|---|
|
| 55 |
+
| `info` | `{}` | `protocol` = 1,`robot`,`n_joints`,`cameras` = `["agentview","wrist"]`,`workspace` = `{lo:[x,y,z], hi:[x,y,z]}`,`yaw_range_deg` = `[lo,hi]`,`max_speed`(m/s),`ik`(bool),`driver_version` | 启动时调一次,内容写进每个 run 的契约 |
|
| 56 |
+
| `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 |
|
| 57 |
+
| `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) |
|
| 58 |
+
| `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 |
|
| 59 |
+
| `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 |
|
| 60 |
+
| `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会���心裁成正方形、缩到 512²,再存成 JPEG q90 |
|
| 61 |
+
| `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 |
|
| 62 |
+
| `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) |
|
| 63 |
+
| `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 |
|
| 64 |
+
|
| 65 |
+
驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。
|
| 66 |
+
|
| 67 |
+
## 4. 安全(必须做)
|
| 68 |
+
|
| 69 |
+
- **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。
|
| 70 |
+
- **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。
|
| 71 |
+
- **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。
|
| 72 |
+
- **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。
|
| 73 |
+
- `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。
|
| 74 |
+
|
| 75 |
+
## 5. 模型那边看到的和你有关的东西
|
| 76 |
+
|
| 77 |
+
- 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。
|
| 78 |
+
光照要稳定;模型运行时,画面里不要有人和多余的东西。
|
| 79 |
+
- 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。
|
| 80 |
+
- 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。
|
| 81 |
+
|
| 82 |
+
## 6. 两个任务的场景
|
| 83 |
+
|
| 84 |
+
实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。
|
| 85 |
+
|
| 86 |
+
### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`)
|
| 87 |
+
|
| 88 |
+
模型看到的指令(与仿真相同):*Slowly push the long brown box with the closed gripper so that it ends up completely inside the green rectangle ahead of it (farther from the robot).*
|
| 89 |
+
|
| 90 |
+
- **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。
|
| 91 |
+
可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。
|
| 92 |
+
- **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。
|
| 93 |
+
合上盖子,两端外观一模一样,贴同样的胶带。
|
| 94 |
+
- **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。
|
| 95 |
+
- **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。
|
| 96 |
+
- **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。
|
| 97 |
+
- **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框);
|
| 98 |
+
对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。
|
| 99 |
+
- **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。
|
| 100 |
+
|
| 101 |
+
### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`)
|
| 102 |
+
|
| 103 |
+
模型看到的指令:*Pick up the red cube and put it into the bowl.*
|
| 104 |
+
|
| 105 |
+
- 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。
|
| 106 |
+
- 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。
|
| 107 |
+
- **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。
|
| 108 |
+
但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。
|
| 109 |
+
- **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方��。
|
| 110 |
+
|
| 111 |
+
## 7. 联调步骤
|
| 112 |
+
|
| 113 |
+
1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。
|
| 114 |
+
2. 启动驱动(token 自己定,私下发给跑评测的人):
|
| 115 |
+
```bash
|
| 116 |
+
python driver_template.py --port 9900 --token <token> --log driver_logs
|
| 117 |
+
```
|
| 118 |
+
3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上:
|
| 119 |
+
```bash
|
| 120 |
+
python real_check_driver.py --driver http://127.0.0.1:9900 --token <token> --operator
|
| 121 |
+
```
|
| 122 |
+
全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。
|
| 123 |
+
4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一:
|
| 124 |
+
- 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 <user>@<机器人电脑>`
|
| 125 |
+
- 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 <user>@<评测机>`
|
| 126 |
+
5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。
|
| 127 |
+
6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。
|
| 128 |
+
一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。
|
| 129 |
+
|
| 130 |
+
## 8. 操作员规程
|
| 131 |
+
|
| 132 |
+
- 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。
|
| 133 |
+
- 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。
|
| 134 |
+
- 判 y / n 只看清单本身,不看模型"努力了没有"。
|
| 135 |
+
- `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。
|
| 136 |
+
- 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。
|
| 137 |
+
|
| 138 |
+
## 9. 常见问题
|
| 139 |
+
|
| 140 |
+
- **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。
|
| 141 |
+
- **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。
|
| 142 |
+
- **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。
|
| 143 |
+
- **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。
|
| 144 |
+
- **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-robot backend of LFF-Bench (docs/17): the same agent interface as simulation, with a robot driver underneath.
|
| 2 |
+
|
| 3 |
+
protocol.py driver protocol v1 (both sides; stdlib + numpy + Pillow only)
|
| 4 |
+
executor.py RealToolExecutor: robot_server's executor on top of a driver (calibration bias injected here)
|
| 5 |
+
session.py RealRobotSession: robot_server's LA session without the simulator; python -m lffbench.real.session
|
| 6 |
+
tasks.py real-robot tasks (setup sheet, operator checklist, hidden variable from the seed)
|
| 7 |
+
fake_driver.py a driver backed by the simulator (no hardware)
|
| 8 |
+
driver_template.py skeleton for a hardware driver (copy to the robot PC with protocol.py)
|
| 9 |
+
DRIVER.md spec for the driver author and the operator
|
| 10 |
+
"""
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/driver_template.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Skeleton of a hardware driver for LFF-Bench (spec: DRIVER.md). Copy this file and protocol.py to the robot PC,
|
| 2 |
+
fill in the five methods marked TODO, run scripts/real_check_driver.py until every check passes.
|
| 3 |
+
|
| 4 |
+
python driver_template.py --port 9900 [--token <t>] [--log <dir>]
|
| 5 |
+
|
| 6 |
+
Only Python 3 + numpy + Pillow are needed here (plus your robot / camera SDKs). Keep the server on 127.0.0.1; the
|
| 7 |
+
benchmark machine reaches it through an SSH tunnel (DRIVER.md §7).
|
| 8 |
+
|
| 9 |
+
What is already done for you: the HTTP protocol, the token, the operator's terminal prompts, the safety checks that
|
| 10 |
+
must run before every motion (hard workspace box, speed limit), the motion timing, and an optional recorder that saves
|
| 11 |
+
both cameras to an mp4 per attempt. Everything robot-specific is in the TODO methods.
|
| 12 |
+
"""
|
| 13 |
+
import argparse
|
| 14 |
+
import os
|
| 15 |
+
import threading
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
try: # copied next to protocol.py on the robot PC
|
| 21 |
+
from protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
|
| 22 |
+
except ImportError: # inside the repo (python -m lffbench.real.driver_template)
|
| 23 |
+
from .protocol import CAMERAS, PROTOCOL_VERSION, DriverServer, square_resize
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------------------------- your setup (edit)
|
| 26 |
+
ROBOT = "AgileX PiPER" # TODO: the arm's name as the agent will read it ("You control a real <ROBOT> robot arm")
|
| 27 |
+
N_JOINTS = 6 # TODO
|
| 28 |
+
# Hard workspace of the GRASP POINT in the robot-base frame (metres). Rejected targets never move the arm. Choose it so
|
| 29 |
+
# that every point inside is reachable with the gripper pointing straight down at any yaw in YAW_RANGE_DEG, and the
|
| 30 |
+
# lower z bound keeps the fingertips >= 5 mm above the table (the boxes are pushed with the fingertips ~1 cm up).
|
| 31 |
+
WORKSPACE_LO = [0.15, -0.25, 0.00] # TODO: measure on your table
|
| 32 |
+
WORKSPACE_HI = [0.45, 0.25, 0.30] # TODO
|
| 33 |
+
YAW_RANGE_DEG = [-120.0, 120.0] # TODO: gripper yaw your wrist reaches (span >= 180)
|
| 34 |
+
MAX_SPEED = 0.25 # m/s, the fastest straight-line speed you allow (the agent may ask for less)
|
| 35 |
+
HOME = dict(x=0.25, y=0.0, z=0.20, yaw_deg=0.0) # TODO: above the table centre, out of the agentview's way if possible
|
| 36 |
+
REACH_TOL = 0.004 # m: a move counts as finished when within this of the target and stopped
|
| 37 |
+
MOVE_TIMEOUT = 30.0 # s
|
| 38 |
+
DRIVER_VERSION = "template-0" # TODO: your git commit / date
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class MyDriver(DriverServer):
|
| 42 |
+
image_format = "jpeg" # "png" is lossless but ~5x larger; jpeg q95 is fine over a LAN / SSH tunnel
|
| 43 |
+
|
| 44 |
+
def __init__(self, record_dir=""):
|
| 45 |
+
self.lock = threading.RLock() # hardware access from the recorder thread and from requests
|
| 46 |
+
self.record_dir = record_dir
|
| 47 |
+
self.recorder = None
|
| 48 |
+
# TODO: connect to the arm, enable it, set the TCP (grasp point = midway between the fingertips, about 1 cm
|
| 49 |
+
# above their tips), open the cameras. Example for PiPER (piper_sdk; check the SDK docs, not verified here):
|
| 50 |
+
# from piper_sdk import C_PiperInterface_V2
|
| 51 |
+
# self.arm = C_PiperInterface_V2("can0"); self.arm.ConnectPort(); ... enable ...
|
| 52 |
+
# Cameras: "agentview" = fixed camera looking at the table from the front/side (sees the whole work area);
|
| 53 |
+
# "wrist" = camera on the gripper. E.g. cv2.VideoCapture / pyrealsense2 colour stream.
|
| 54 |
+
raise NotImplementedError("connect the arm and the cameras")
|
| 55 |
+
|
| 56 |
+
# ------------------------------------------------------------------ TODO 1: low-level hardware
|
| 57 |
+
def _send_cartesian(self, x, y, z, yaw_deg, speed):
|
| 58 |
+
"""Start a straight-line (MoveL) motion of the grasp point to (x, y, z) with the gripper pointing straight down
|
| 59 |
+
and rotated by yaw_deg about the base z axis (0 = fingers close along the base y axis, +90 = along the base x
|
| 60 |
+
axis, counter-clockwise seen from above). Return False if the controller refuses (no IK)."""
|
| 61 |
+
raise NotImplementedError
|
| 62 |
+
|
| 63 |
+
def _read_pose(self):
|
| 64 |
+
"""-> (xyz of the grasp point in the base frame [m], yaw_deg, joint angles [rad], is_moving: bool)."""
|
| 65 |
+
raise NotImplementedError
|
| 66 |
+
|
| 67 |
+
def _set_gripper(self, close):
|
| 68 |
+
"""Close (force-limited, stop when blocked) or open fully; return when the fingers have stopped."""
|
| 69 |
+
raise NotImplementedError
|
| 70 |
+
|
| 71 |
+
def _gripper_width(self):
|
| 72 |
+
"""Opening between the fingertips, metres."""
|
| 73 |
+
raise NotImplementedError
|
| 74 |
+
|
| 75 |
+
def _grab(self):
|
| 76 |
+
"""-> {"agentview": HxWx3 uint8 RGB, "wrist": ...}: the newest frames (flush camera buffers first)."""
|
| 77 |
+
raise NotImplementedError
|
| 78 |
+
|
| 79 |
+
def ik(self, eef_pos, yaw_deg):
|
| 80 |
+
"""Optional (set info()["ik"] = True), needed only for real_bias_place: joint angles that put the grasp point
|
| 81 |
+
at eef_pos / yaw_deg (pointing down), the solution closest to the current joints. Do NOT move the arm."""
|
| 82 |
+
raise NotImplementedError
|
| 83 |
+
|
| 84 |
+
# ------------------------------------------------------------------ protocol (normally no need to edit)
|
| 85 |
+
def info(self):
|
| 86 |
+
return dict(protocol=PROTOCOL_VERSION, robot=ROBOT, n_joints=N_JOINTS, cameras=list(CAMERAS),
|
| 87 |
+
workspace=dict(lo=WORKSPACE_LO, hi=WORKSPACE_HI), yaw_range_deg=YAW_RANGE_DEG, max_speed=MAX_SPEED,
|
| 88 |
+
ik=False, driver_version=DRIVER_VERSION)
|
| 89 |
+
|
| 90 |
+
def state(self):
|
| 91 |
+
with self.lock:
|
| 92 |
+
xyz, yaw, q, _ = self._read_pose()
|
| 93 |
+
return dict(eef_pos=[float(v) for v in xyz], eef_yaw_deg=float(yaw), gripper_width_m=float(self._gripper_width()),
|
| 94 |
+
joint_pos_rad=[float(v) for v in q])
|
| 95 |
+
|
| 96 |
+
def _inside(self, x, y, z, yaw_deg):
|
| 97 |
+
p = np.array([x, y, z])
|
| 98 |
+
return (bool(np.all(p >= WORKSPACE_LO) and np.all(p <= WORKSPACE_HI))
|
| 99 |
+
and YAW_RANGE_DEG[0] <= yaw_deg <= YAW_RANGE_DEG[1])
|
| 100 |
+
|
| 101 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 102 |
+
if not self._inside(x, y, z, yaw_deg):
|
| 103 |
+
return False, "outside the hard workspace", 0.0
|
| 104 |
+
speed = MAX_SPEED if speed is None else float(np.clip(speed, 0.005, MAX_SPEED))
|
| 105 |
+
with self.lock:
|
| 106 |
+
t0 = time.time()
|
| 107 |
+
if not self._send_cartesian(x, y, z, yaw_deg, speed):
|
| 108 |
+
return False, "no IK solution", 0.0
|
| 109 |
+
tgt = np.array([x, y, z])
|
| 110 |
+
while True: # blocking: return only once the arm has stopped
|
| 111 |
+
xyz, _, _, moving = self._read_pose()
|
| 112 |
+
if not moving and np.linalg.norm(np.asarray(xyz) - tgt) < REACH_TOL:
|
| 113 |
+
break
|
| 114 |
+
if time.time() - t0 > MOVE_TIMEOUT:
|
| 115 |
+
if not moving:
|
| 116 |
+
break # stopped short (blocked by an object): a normal outcome, the agent sees the pose
|
| 117 |
+
raise RuntimeError("move timed out while still moving") # -> fault: the run stops
|
| 118 |
+
time.sleep(0.02)
|
| 119 |
+
return True, None, time.time() - t0
|
| 120 |
+
|
| 121 |
+
def gripper(self, close):
|
| 122 |
+
with self.lock:
|
| 123 |
+
t0 = time.time()
|
| 124 |
+
self._set_gripper(close)
|
| 125 |
+
return time.time() - t0
|
| 126 |
+
|
| 127 |
+
def home(self):
|
| 128 |
+
ok, err, _ = self.move(HOME["x"], HOME["y"], HOME["z"], HOME["yaw_deg"], 0.15)
|
| 129 |
+
if not ok:
|
| 130 |
+
raise RuntimeError(f"cannot reach the home pose: {err}")
|
| 131 |
+
self.gripper(False)
|
| 132 |
+
return self.state()
|
| 133 |
+
|
| 134 |
+
def images(self):
|
| 135 |
+
with self.lock:
|
| 136 |
+
return self._grab()
|
| 137 |
+
|
| 138 |
+
def event(self, ev, run="", attempt=None, **kw):
|
| 139 |
+
if not self.record_dir:
|
| 140 |
+
return
|
| 141 |
+
if ev == "attempt_start":
|
| 142 |
+
self._stop_recording()
|
| 143 |
+
try:
|
| 144 |
+
self.recorder = Recorder(self, os.path.join(self.record_dir, f"{run}_a{attempt}.mp4"))
|
| 145 |
+
except Exception as e: # the video is only for the record: a missing imageio must not end a run as a fault
|
| 146 |
+
print(f"WARNING: recorder not started ({type(e).__name__}: {e}); "
|
| 147 |
+
"pip install imageio imageio-ffmpeg", flush=True)
|
| 148 |
+
elif ev in ("attempt_end", "episode_end", "session_end", "run_invalid"):
|
| 149 |
+
self._stop_recording()
|
| 150 |
+
|
| 151 |
+
def _stop_recording(self):
|
| 152 |
+
if self.recorder is not None:
|
| 153 |
+
self.recorder.stop()
|
| 154 |
+
self.recorder = None
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class Recorder(threading.Thread):
|
| 158 |
+
"""agentview | wrist side by side at ~5 fps while an attempt runs (needs imageio + imageio-ffmpeg)."""
|
| 159 |
+
|
| 160 |
+
def __init__(self, drv, path, fps=5, res=360):
|
| 161 |
+
super().__init__(daemon=True)
|
| 162 |
+
import imageio
|
| 163 |
+
self.drv, self.fps, self.res, self.halt = drv, fps, res, threading.Event()
|
| 164 |
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
| 165 |
+
self.w = imageio.get_writer(path, fps=fps, macro_block_size=8)
|
| 166 |
+
self.start()
|
| 167 |
+
|
| 168 |
+
def run(self):
|
| 169 |
+
while not self.halt.is_set():
|
| 170 |
+
t0 = time.time()
|
| 171 |
+
try:
|
| 172 |
+
with self.drv.lock:
|
| 173 |
+
f = self.drv._grab()
|
| 174 |
+
self.w.append_data(np.concatenate([square_resize(f[c], self.res) for c in CAMERAS], axis=1))
|
| 175 |
+
except Exception as e: # never let the recorder break a run
|
| 176 |
+
print("recorder:", e)
|
| 177 |
+
self.halt.wait(max(0.0, 1.0 / self.fps - (time.time() - t0)))
|
| 178 |
+
|
| 179 |
+
def stop(self):
|
| 180 |
+
self.halt.set()
|
| 181 |
+
self.join(timeout=5)
|
| 182 |
+
self.w.close()
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def main():
|
| 186 |
+
ap = argparse.ArgumentParser()
|
| 187 |
+
ap.add_argument("--port", type=int, default=9900)
|
| 188 |
+
ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
|
| 189 |
+
ap.add_argument("--log", default="driver_logs", help="operator answers (operator.jsonl) and attempt videos")
|
| 190 |
+
a = ap.parse_args()
|
| 191 |
+
os.makedirs(a.log, exist_ok=True)
|
| 192 |
+
MyDriver(record_dir=a.log).serve(a.port, token=a.token or None, operator_log=os.path.join(a.log, "operator.jsonl"))
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/executor.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RealToolExecutor: the real-robot counterpart of lffbench.agent.tools.ToolExecutor.
|
| 2 |
+
|
| 3 |
+
robot_server's LA interface needs only this from its executor: observe(label) -> [ImageRef], proprio() -> dict, and
|
| 4 |
+
call("move_to" | "open_gripper" | "close_gripper", args) -> ToolResult. Here every call goes to a robot driver
|
| 5 |
+
(lffbench/real/protocol.py) instead of the simulator.
|
| 6 |
+
|
| 7 |
+
Calibration bias (L1 tasks), as Skills / ToolExecutor do it in simulation: the driver is sent commanded + bias and
|
| 8 |
+
reports the true pose; the agent is told true - bias (what a miscalibrated robot believes). Joint angles are then the
|
| 9 |
+
ones that put the grasp point at the believed pose (driver /ik), as robot_server._believed_joints does in simulation.
|
| 10 |
+
"""
|
| 11 |
+
import math
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from ..agent.images import ImageRef
|
| 17 |
+
from ..agent.tools import ToolResult, parse_args
|
| 18 |
+
from .protocol import CAMERAS, DriverError, square_resize, state_problems
|
| 19 |
+
|
| 20 |
+
SPEED_MIN = 0.01 # m/s; below this a straight-line move takes too long to be useful
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _r(v, nd=4):
|
| 24 |
+
return [round(float(x), nd) for x in v]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RealToolExecutor:
|
| 28 |
+
def __init__(self, driver, info, bias=None, image_res=512, cams=CAMERAS):
|
| 29 |
+
self.driver, self.info = driver, info
|
| 30 |
+
self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
|
| 31 |
+
self.image_res = int(image_res)
|
| 32 |
+
self.cams = tuple(cams)
|
| 33 |
+
self.n_joints = int(info["n_joints"])
|
| 34 |
+
self.yaw_lo, self.yaw_hi = (float(v) for v in info["yaw_range_deg"])
|
| 35 |
+
self.max_speed = float(info["max_speed"])
|
| 36 |
+
self.motion_s = 0.0 # robot motion time of this executor (= this attempt), as reported by the driver
|
| 37 |
+
self.n_calls = 0
|
| 38 |
+
self._state = None
|
| 39 |
+
self.grip_closed = False # last gripper command of this attempt (the driver's home pose has it open)
|
| 40 |
+
self.yaw_cmd = None # last commanded yaw (degrees), for choosing among the gripper-symmetric equivalents
|
| 41 |
+
self.refresh()
|
| 42 |
+
self.yaw_cmd = float(self._state["eef_yaw_deg"])
|
| 43 |
+
|
| 44 |
+
# ------------------------------------------------------------------ state
|
| 45 |
+
def _set_state(self, st):
|
| 46 |
+
prob = state_problems(st, self.n_joints)
|
| 47 |
+
if prob:
|
| 48 |
+
raise DriverError("driver state: " + "; ".join(prob))
|
| 49 |
+
self._state = st
|
| 50 |
+
|
| 51 |
+
def refresh(self):
|
| 52 |
+
self._set_state(self.driver.state())
|
| 53 |
+
|
| 54 |
+
def true_eef(self):
|
| 55 |
+
return np.asarray(self._state["eef_pos"], float)
|
| 56 |
+
|
| 57 |
+
def believed_eef(self):
|
| 58 |
+
return self.true_eef() - self.bias
|
| 59 |
+
|
| 60 |
+
def proprio(self):
|
| 61 |
+
st = self._state
|
| 62 |
+
return dict(eef_pos=_r(self.believed_eef()), eef_yaw_deg=round(float(st["eef_yaw_deg"]), 1),
|
| 63 |
+
gripper="closed" if self.grip_closed else "open",
|
| 64 |
+
gripper_width_m=round(float(st["gripper_width_m"]), 4))
|
| 65 |
+
|
| 66 |
+
def joints(self):
|
| 67 |
+
"""Joint angles as the robot's encoders would report them under the hidden calibration error."""
|
| 68 |
+
if not np.any(self.bias):
|
| 69 |
+
return [float(v) for v in self._state["joint_pos_rad"]]
|
| 70 |
+
key = (tuple(self._state["eef_pos"]), float(self._state["eef_yaw_deg"]))
|
| 71 |
+
if getattr(self, "_ik_key", None) != key: # one /ik per new state (the server asks several times per command)
|
| 72 |
+
self._ik_key = key
|
| 73 |
+
self._ik_val = [float(v) for v in self.driver.ik(self.believed_eef(), key[1])]
|
| 74 |
+
return list(self._ik_val)
|
| 75 |
+
|
| 76 |
+
def observe(self, label=""):
|
| 77 |
+
frames, st = self.driver.observe()
|
| 78 |
+
self._set_state(st)
|
| 79 |
+
return [ImageRef(camera=c, array=square_resize(frames[c], self.image_res), label=f"{label} {c}".strip())
|
| 80 |
+
for c in self.cams]
|
| 81 |
+
|
| 82 |
+
# ------------------------------------------------------------------ helpers
|
| 83 |
+
def wrap_yaw(self, yaw):
|
| 84 |
+
"""The two-finger gripper is symmetric: among yaw + k*180 inside the driver's yaw range, use the one closest to
|
| 85 |
+
the last commanded yaw (Skills.wrap_yaw does the same with its +-113 deg limit)."""
|
| 86 |
+
cands = [yaw + 180.0 * k for k in range(-3, 4)]
|
| 87 |
+
ok = [c for c in cands if self.yaw_lo <= c <= self.yaw_hi] or cands
|
| 88 |
+
return float(min(ok, key=lambda c: abs(c - self.yaw_cmd)))
|
| 89 |
+
|
| 90 |
+
# ------------------------------------------------------------------ dispatch (same signature as ToolExecutor.call)
|
| 91 |
+
def call(self, name, raw_args):
|
| 92 |
+
t0 = time.time()
|
| 93 |
+
self.n_calls += 1
|
| 94 |
+
args = parse_args(raw_args)
|
| 95 |
+
fn = getattr(self, f"_t_{name}", None)
|
| 96 |
+
if fn is None:
|
| 97 |
+
return ToolResult(name, args, False, dict(ok=False, error=f"unknown tool {name!r}"), wall_s=time.time() - t0)
|
| 98 |
+
res = fn(**args)
|
| 99 |
+
res.args, res.wall_s = args, time.time() - t0
|
| 100 |
+
return res
|
| 101 |
+
|
| 102 |
+
def _report(self, name, extra=None):
|
| 103 |
+
rep = dict(ok=True, tool=name)
|
| 104 |
+
rep.update(extra or {})
|
| 105 |
+
rep.update(self.proprio())
|
| 106 |
+
return rep
|
| 107 |
+
|
| 108 |
+
def _t_move_to(self, x, y, z, yaw, speed=None):
|
| 109 |
+
tgt = np.array([x, y, z], float)
|
| 110 |
+
if not np.all(np.isfinite(tgt)):
|
| 111 |
+
return ToolResult("move_to", {}, False, dict(ok=False, error="non-finite coordinates"))
|
| 112 |
+
spd = None if speed is None else float(np.clip(float(speed), SPEED_MIN, self.max_speed))
|
| 113 |
+
yaw_used = self.wrap_yaw(float(yaw))
|
| 114 |
+
cmd = tgt + self.bias # the hidden calibration error acts on every commanded position
|
| 115 |
+
rep = self.driver.move(cmd[0], cmd[1], cmd[2], yaw_used, spd)
|
| 116 |
+
self.motion_s += float(rep.get("motion_s") or 0.0)
|
| 117 |
+
self._set_state(rep["state"])
|
| 118 |
+
if not rep["ok"]: # rejected before moving (driver hard limits / no IK solution)
|
| 119 |
+
return ToolResult("move_to", {}, False, dict(ok=False, error="target rejected: the arm cannot reach it; "
|
| 120 |
+
"the arm did not move", driver_error=rep.get("error", "")))
|
| 121 |
+
self.yaw_cmd = yaw_used
|
| 122 |
+
reached = bool(np.linalg.norm(cmd - self.true_eef()) < 0.02)
|
| 123 |
+
return ToolResult("move_to", {}, True, self._report("move_to", dict(reached=reached,
|
| 124 |
+
yaw_used_deg=round(yaw_used, 1))))
|
| 125 |
+
|
| 126 |
+
def _gripper(self, close):
|
| 127 |
+
rep = self.driver.gripper(close)
|
| 128 |
+
self.grip_closed = bool(close)
|
| 129 |
+
self.motion_s += float(rep.get("motion_s") or 0.0)
|
| 130 |
+
self._set_state(rep["state"])
|
| 131 |
+
name = "close_gripper" if close else "open_gripper"
|
| 132 |
+
return ToolResult(name, {}, True, self._report(name))
|
| 133 |
+
|
| 134 |
+
def _t_open_gripper(self):
|
| 135 |
+
return self._gripper(False)
|
| 136 |
+
|
| 137 |
+
def _t_close_gripper(self):
|
| 138 |
+
return self._gripper(True)
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/fake_driver.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fake robot driver backed by the simulator: answers the driver protocol (lffbench/real/protocol.py) with a simulated
|
| 2 |
+
LFF-Bench task, so the whole real-robot path (harness -> MCP -> real robot server -> driver) runs without hardware.
|
| 3 |
+
|
| 4 |
+
It behaves like a real driver: it reports the TRUE pose in the robot-base frame (no calibration bias of its own; the
|
| 5 |
+
benchmark injects the bias), sends lossless PNG frames, rejects targets outside its hard workspace, and has an
|
| 6 |
+
operator. The operator is the simulator unless --operator console: "reset" resets the simulated scene, "judge" is the
|
| 7 |
+
task's own success rule (task.outcome).
|
| 8 |
+
|
| 9 |
+
python -m lffbench.real.fake_driver --task l7_offcenter_push --seed 3000 --port 9900 --token <t> [--nominal]
|
| 10 |
+
[--operator auto|console] [--log <dir>]
|
| 11 |
+
|
| 12 |
+
--nominal removes the task's hidden calibration bias (L1 tasks), which is what a real arm looks like when the benchmark
|
| 13 |
+
injects the bias in software (real_bias_place).
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
import time
|
| 20 |
+
import types
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from .protocol import CAMERAS, PROTOCOL_VERSION, ConsoleOperator, DriverServer
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SimDriver(DriverServer):
|
| 28 |
+
def __init__(self, task, seed, nominal=False, image_res=512, operator="auto", log_dir=""):
|
| 29 |
+
from ..agent import robot_server as RS # registers every simulated task
|
| 30 |
+
from ..agent.tools import SPEED_RANGE, WS_HI, WS_LO, ToolExecutor
|
| 31 |
+
from ..task_base import TASKS
|
| 32 |
+
self.RS, self.ToolExecutor = RS, ToolExecutor
|
| 33 |
+
self.task_name, self.seed, self.image_res = task, int(seed), int(image_res)
|
| 34 |
+
self.task = TASKS[task](cam_res=self.image_res)
|
| 35 |
+
self.inst = self.task.sample_instance(self.seed)
|
| 36 |
+
if nominal: # same rule as robot_server --nominal
|
| 37 |
+
for k in [k for k in self.inst if "bias" in k]:
|
| 38 |
+
v = self.inst[k]
|
| 39 |
+
self.inst[k] = [0.0] * len(v) if isinstance(v, (list, tuple)) else 0.0 if isinstance(v, (int, float)) else v
|
| 40 |
+
self.operator_mode = operator
|
| 41 |
+
self.log_dir = log_dir
|
| 42 |
+
if log_dir:
|
| 43 |
+
os.makedirs(log_dir, exist_ok=True)
|
| 44 |
+
self.console_op = ConsoleOperator(os.path.join(log_dir, "operator.jsonl") if log_dir else None)
|
| 45 |
+
self._reset()
|
| 46 |
+
sim = self.task.env.sim
|
| 47 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 48 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 49 |
+
self.ws_lo, self.ws_hi = WS_LO - self.base_off, WS_HI - self.base_off
|
| 50 |
+
self.max_speed = float(SPEED_RANGE[1])
|
| 51 |
+
self.yaw_limit_deg = math.degrees(self.task.sk.YAW_LIMIT)
|
| 52 |
+
|
| 53 |
+
def _reset(self):
|
| 54 |
+
self.task.reset_instance(self.inst)
|
| 55 |
+
self.ex = self.ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=CAMERAS)
|
| 56 |
+
|
| 57 |
+
def _log(self, d):
|
| 58 |
+
if self.log_dir:
|
| 59 |
+
with open(os.path.join(self.log_dir, "driver_events.jsonl"), "a") as f:
|
| 60 |
+
f.write(json.dumps(dict(d, t=time.time()), default=str) + "\n")
|
| 61 |
+
|
| 62 |
+
# ------------------------------------------------------------------ protocol
|
| 63 |
+
def info(self):
|
| 64 |
+
return dict(protocol=PROTOCOL_VERSION, robot="Franka Emika Panda (fake driver, simulated)", n_joints=7,
|
| 65 |
+
cameras=list(CAMERAS), workspace=dict(lo=self.ws_lo.round(6).tolist(), hi=self.ws_hi.round(6).tolist()),
|
| 66 |
+
yaw_range_deg=[-self.yaw_limit_deg, self.yaw_limit_deg], max_speed=self.max_speed, ik=True,
|
| 67 |
+
driver_version=f"fake_driver sim:{self.task_name} seed:{self.seed}")
|
| 68 |
+
|
| 69 |
+
def home(self):
|
| 70 |
+
# the simulated arm goes home with the scene reset that always follows (operator "reset")
|
| 71 |
+
return self.state()
|
| 72 |
+
|
| 73 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 74 |
+
tgt = np.array([x, y, z], float)
|
| 75 |
+
if not (np.all(tgt >= self.ws_lo - 1e-9) and np.all(tgt <= self.ws_hi + 1e-9)):
|
| 76 |
+
return False, "outside the hard workspace", 0.0
|
| 77 |
+
w = tgt + self.base_off
|
| 78 |
+
n0 = self.task.sk.n_steps
|
| 79 |
+
mv = dict(x=float(w[0]), y=float(w[1]), z=float(w[2]), yaw=float(yaw_deg))
|
| 80 |
+
if speed is not None:
|
| 81 |
+
mv["speed"] = float(speed)
|
| 82 |
+
res = self.ex.call("move_to", mv)
|
| 83 |
+
if not res.ok:
|
| 84 |
+
return False, res.report.get("error", "rejected"), 0.0
|
| 85 |
+
return True, None, (self.task.sk.n_steps - n0) * 0.05
|
| 86 |
+
|
| 87 |
+
def gripper(self, close):
|
| 88 |
+
n0 = self.task.sk.n_steps
|
| 89 |
+
self.ex.call("close_gripper" if close else "open_gripper", {})
|
| 90 |
+
return (self.task.sk.n_steps - n0) * 0.05
|
| 91 |
+
|
| 92 |
+
def _joints(self):
|
| 93 |
+
rob = self.task.env.robots[0]
|
| 94 |
+
return self.task.env.sim.data.qpos[np.array(rob._ref_joint_pos_indexes)].copy()
|
| 95 |
+
|
| 96 |
+
def state(self):
|
| 97 |
+
sk = self.task.sk
|
| 98 |
+
return dict(eef_pos=[float(v) for v in sk.eef_pos() - self.base_off], eef_yaw_deg=float(self.ex.eef_yaw_deg()),
|
| 99 |
+
gripper_width_m=float(sk.gripper_width()), joint_pos_rad=[float(v) for v in self._joints()])
|
| 100 |
+
|
| 101 |
+
def images(self):
|
| 102 |
+
return {r.camera: r.array for r in self.ex.observe()}
|
| 103 |
+
|
| 104 |
+
def ik(self, eef_pos, yaw_deg):
|
| 105 |
+
"""Joint angles for the grasp point at eef_pos (base frame) with the current orientation: the same damped
|
| 106 |
+
least squares as robot_server._believed_joints (yaw_deg is the current yaw here)."""
|
| 107 |
+
sk = self.task.sk
|
| 108 |
+
T_true = np.eye(4)
|
| 109 |
+
T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos()
|
| 110 |
+
T_b = T_true.copy()
|
| 111 |
+
T_b[:3, 3] = np.asarray(eef_pos, float) + self.base_off
|
| 112 |
+
shim = types.SimpleNamespace(task=self.task, _believed_pose=lambda: (T_b, T_true))
|
| 113 |
+
return [float(v) for v in self.RS._believed_joints(shim)]
|
| 114 |
+
|
| 115 |
+
def operator(self, kind, **kw):
|
| 116 |
+
self._log(dict(ev="operator", kind=kind, **{k: v for k, v in kw.items() if k != "checklist"}))
|
| 117 |
+
if kind == "reset":
|
| 118 |
+
if self.operator_mode == "console":
|
| 119 |
+
self.console_op(kind, **kw)
|
| 120 |
+
self._reset()
|
| 121 |
+
return dict(ok=True)
|
| 122 |
+
if kind == "judge":
|
| 123 |
+
out = self.task.outcome(self.inst)
|
| 124 |
+
if self.operator_mode == "console":
|
| 125 |
+
kw = dict(kw, text=(kw.get("text", "") + f"\n(simulator says: success={bool(out['success'])}, "
|
| 126 |
+
f"{out.get('failure') or out.get('detail') or ''})"))
|
| 127 |
+
return self.console_op(kind, **kw)
|
| 128 |
+
return dict(ok=True, success=bool(out["success"]),
|
| 129 |
+
note=str(out.get("failure") or ("ok" if out["success"] else "")))
|
| 130 |
+
return dict(ok=True)
|
| 131 |
+
|
| 132 |
+
def event(self, ev, **kw):
|
| 133 |
+
self._log(dict(ev=ev, **kw))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main():
|
| 137 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 138 |
+
ap.add_argument("--task", default="l7_offcenter_push", help="simulated LFF-Bench task that plays the real scene")
|
| 139 |
+
ap.add_argument("--seed", type=int, default=3000)
|
| 140 |
+
ap.add_argument("--port", type=int, default=9900)
|
| 141 |
+
ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
|
| 142 |
+
ap.add_argument("--nominal", action="store_true", help="remove the simulated task's calibration bias")
|
| 143 |
+
ap.add_argument("--operator", default="auto", choices=["auto", "console"])
|
| 144 |
+
ap.add_argument("--image-res", type=int, default=512)
|
| 145 |
+
ap.add_argument("--log", default="", help="directory for driver_events.jsonl / operator.jsonl")
|
| 146 |
+
a = ap.parse_args()
|
| 147 |
+
drv = SimDriver(a.task, a.seed, nominal=a.nominal, image_res=a.image_res, operator=a.operator, log_dir=a.log)
|
| 148 |
+
drv.serve(a.port, token=a.token or None)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/protocol.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot-driver protocol v1: what a real arm (or a fake one) must answer so that LFF-Bench can run on it.
|
| 2 |
+
|
| 3 |
+
The benchmark side (lffbench/real/session.py, on the machine that runs the agent harness) talks to one *driver*
|
| 4 |
+
process (on the robot PC) over HTTP. The driver only moves the arm, reads its state, grabs camera frames and talks
|
| 5 |
+
to the human operator; budgets, attempts, README, logs and the agent interface stay on the benchmark side, so the
|
| 6 |
+
agent sees exactly the same tools as in simulation. Spec for driver authors: lffbench/real/DRIVER.md.
|
| 7 |
+
|
| 8 |
+
This file is shared by both sides and needs only the Python standard library + numpy + Pillow (no simulator):
|
| 9 |
+
DriverClient benchmark side: typed calls to a driver
|
| 10 |
+
DriverServer driver side: HTTP plumbing; subclass it and implement the hardware methods (driver_template.py)
|
| 11 |
+
ConsoleOperator driver side: the operator's terminal (blocking prompts for reset / judging)
|
| 12 |
+
|
| 13 |
+
Every request is POST <url>/<endpoint> with a JSON body and header X-Driver-Token: <token>.
|
| 14 |
+
Every reply is JSON with "ok": true|false. A reply with "fault": true means the robot can no longer be trusted
|
| 15 |
+
(protective stop, e-stop, lost connection, ...): the benchmark ends the run and marks it invalid.
|
| 16 |
+
"""
|
| 17 |
+
import base64
|
| 18 |
+
import io
|
| 19 |
+
import json
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import secrets
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
import traceback
|
| 26 |
+
import urllib.error
|
| 27 |
+
import urllib.request
|
| 28 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
PROTOCOL_VERSION = 1
|
| 33 |
+
CAMERAS = ("agentview", "wrist")
|
| 34 |
+
TOKEN_HEADER = "X-Driver-Token"
|
| 35 |
+
ENDPOINTS = ("info", "home", "move", "gripper", "state", "observe", "ik", "operator", "event")
|
| 36 |
+
OPERATOR_KINDS = ("reset", "judge", "notice")
|
| 37 |
+
EVENTS = ("session_start", "attempt_start", "attempt_end", "episode_end", "session_end", "run_invalid")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DriverError(RuntimeError):
|
| 41 |
+
"""The driver answered something that breaks the protocol (or did not answer)."""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DriverFault(DriverError):
|
| 45 |
+
"""The driver reports a robot fault: the run must stop and is invalid."""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# ------------------------------------------------------------------------------------------------ images
|
| 49 |
+
def encode_image(arr, fmt="png", quality=95):
|
| 50 |
+
"""uint8 HxWx3 -> {"format": "png"|"jpeg", "data": base64}. PNG is lossless (the benchmark re-encodes every frame
|
| 51 |
+
as 512x512 JPEG q90 itself, so a JPEG from the driver is compressed twice); JPEG is smaller over a slow link."""
|
| 52 |
+
from PIL import Image
|
| 53 |
+
buf = io.BytesIO()
|
| 54 |
+
im = Image.fromarray(np.asarray(arr, dtype=np.uint8))
|
| 55 |
+
if fmt == "jpeg":
|
| 56 |
+
im.save(buf, format="JPEG", quality=int(quality))
|
| 57 |
+
else:
|
| 58 |
+
im.save(buf, format="PNG")
|
| 59 |
+
return dict(format=fmt, data=base64.b64encode(buf.getvalue()).decode("ascii"))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def decode_image(obj):
|
| 63 |
+
"""{"format", "data"} -> uint8 HxWx3 (RGB)."""
|
| 64 |
+
from PIL import Image
|
| 65 |
+
if not isinstance(obj, dict) or "data" not in obj:
|
| 66 |
+
raise DriverError("image must be {\"format\": \"png\"|\"jpeg\", \"data\": <base64>}")
|
| 67 |
+
im = Image.open(io.BytesIO(base64.b64decode(obj["data"])))
|
| 68 |
+
return np.asarray(im.convert("RGB"), dtype=np.uint8)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def square_resize(arr, res):
|
| 72 |
+
"""Centre-crop to a square, then resize to res x res. A frame that is already res x res is returned unchanged
|
| 73 |
+
(bit for bit), so a simulator-backed driver gives exactly the simulator's pixels."""
|
| 74 |
+
from PIL import Image
|
| 75 |
+
arr = np.asarray(arr, dtype=np.uint8)
|
| 76 |
+
h, w = arr.shape[:2]
|
| 77 |
+
if h == res and w == res:
|
| 78 |
+
return arr
|
| 79 |
+
s = min(h, w)
|
| 80 |
+
y0, x0 = (h - s) // 2, (w - s) // 2
|
| 81 |
+
arr = arr[y0:y0 + s, x0:x0 + s]
|
| 82 |
+
if s == res:
|
| 83 |
+
return np.ascontiguousarray(arr)
|
| 84 |
+
return np.asarray(Image.fromarray(arr).resize((res, res), Image.BICUBIC))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ------------------------------------------------------------------------------------------------ validation
|
| 88 |
+
def _vec(v, n):
|
| 89 |
+
return isinstance(v, (list, tuple)) and len(v) == n and all(isinstance(x, (int, float)) and math.isfinite(x) for x in v)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def info_problems(info):
|
| 93 |
+
"""-> list of problems with an /info reply (empty = fine)."""
|
| 94 |
+
p = []
|
| 95 |
+
if info.get("protocol") != PROTOCOL_VERSION:
|
| 96 |
+
p.append(f"protocol must be {PROTOCOL_VERSION}, got {info.get('protocol')!r}")
|
| 97 |
+
if not isinstance(info.get("robot"), str) or not info["robot"].strip():
|
| 98 |
+
p.append("robot: non-empty string (e.g. \"AgileX PiPER\")")
|
| 99 |
+
if not isinstance(info.get("n_joints"), int) or not 4 <= info["n_joints"] <= 8:
|
| 100 |
+
p.append("n_joints: integer 4..8")
|
| 101 |
+
if sorted(info.get("cameras") or []) != sorted(CAMERAS):
|
| 102 |
+
p.append(f"cameras must be exactly {list(CAMERAS)}")
|
| 103 |
+
ws = info.get("workspace") or {}
|
| 104 |
+
if not (_vec(ws.get("lo"), 3) and _vec(ws.get("hi"), 3) and all(a < b for a, b in zip(ws["lo"], ws["hi"]))):
|
| 105 |
+
p.append("workspace: {lo: [x, y, z], hi: [x, y, z]} with lo < hi (robot-base frame, metres)")
|
| 106 |
+
yr = info.get("yaw_range_deg")
|
| 107 |
+
if not (_vec(yr, 2) and yr[0] < yr[1] and yr[1] - yr[0] >= 180.0):
|
| 108 |
+
p.append("yaw_range_deg: [lo, hi] with hi - lo >= 180 (the gripper is symmetric, every yaw must be reachable)")
|
| 109 |
+
if not (isinstance(info.get("max_speed"), (int, float)) and 0.01 <= info["max_speed"] <= 1.0):
|
| 110 |
+
p.append("max_speed: m/s, 0.01..1.0")
|
| 111 |
+
if not isinstance(info.get("ik"), bool):
|
| 112 |
+
p.append("ik: true|false (whether /ik is implemented; needed only for tasks with a calibration bias)")
|
| 113 |
+
if not isinstance(info.get("driver_version"), str):
|
| 114 |
+
p.append("driver_version: string (your git commit or a date; it is written into every run's log)")
|
| 115 |
+
return p
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def state_problems(st, n_joints):
|
| 119 |
+
p = []
|
| 120 |
+
if not _vec(st.get("eef_pos"), 3):
|
| 121 |
+
p.append("state.eef_pos: [x, y, z] metres")
|
| 122 |
+
if not (isinstance(st.get("eef_yaw_deg"), (int, float)) and math.isfinite(st["eef_yaw_deg"])):
|
| 123 |
+
p.append("state.eef_yaw_deg: number")
|
| 124 |
+
if not (isinstance(st.get("gripper_width_m"), (int, float)) and 0.0 <= st["gripper_width_m"] <= 0.2):
|
| 125 |
+
p.append("state.gripper_width_m: number 0..0.2")
|
| 126 |
+
if not _vec(st.get("joint_pos_rad"), n_joints):
|
| 127 |
+
p.append(f"state.joint_pos_rad: {n_joints} numbers (radians)")
|
| 128 |
+
return p
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ------------------------------------------------------------------------------------------------ benchmark side
|
| 132 |
+
class DriverClient:
|
| 133 |
+
"""Typed calls to a driver. `url` like http://127.0.0.1:9900 (an SSH tunnel to the robot PC)."""
|
| 134 |
+
|
| 135 |
+
def __init__(self, url, token, timeout=120.0):
|
| 136 |
+
self.url, self.token, self.timeout = url.rstrip("/"), token, float(timeout)
|
| 137 |
+
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never through a web proxy
|
| 138 |
+
|
| 139 |
+
def call(self, endpoint, payload=None, timeout=None, allow_not_ok=False):
|
| 140 |
+
req = urllib.request.Request(f"{self.url}/{endpoint}", data=json.dumps(payload or {}).encode(),
|
| 141 |
+
headers={"Content-Type": "application/json", TOKEN_HEADER: self.token})
|
| 142 |
+
try:
|
| 143 |
+
with self.opener.open(req, timeout=timeout if timeout is not None else self.timeout) as r:
|
| 144 |
+
rep = json.loads(r.read().decode())
|
| 145 |
+
except (urllib.error.URLError, OSError, ValueError) as e:
|
| 146 |
+
raise DriverError(f"/{endpoint}: no valid reply from the driver ({type(e).__name__}: {e})") from e
|
| 147 |
+
if not isinstance(rep, dict) or "ok" not in rep:
|
| 148 |
+
raise DriverError(f"/{endpoint}: reply is not a JSON object with \"ok\"")
|
| 149 |
+
if rep.get("fault"):
|
| 150 |
+
raise DriverFault(f"/{endpoint}: robot fault: {rep.get('error', '')}")
|
| 151 |
+
if not rep["ok"] and not allow_not_ok:
|
| 152 |
+
raise DriverError(f"/{endpoint}: {rep.get('error', 'not ok')}")
|
| 153 |
+
return rep
|
| 154 |
+
|
| 155 |
+
def info(self):
|
| 156 |
+
rep = self.call("info")
|
| 157 |
+
prob = info_problems(rep)
|
| 158 |
+
if prob:
|
| 159 |
+
raise DriverError("/info: " + "; ".join(prob))
|
| 160 |
+
return rep
|
| 161 |
+
|
| 162 |
+
def home(self):
|
| 163 |
+
return self.call("home", timeout=max(self.timeout, 300))
|
| 164 |
+
|
| 165 |
+
def move(self, x, y, z, yaw_deg, speed=None):
|
| 166 |
+
"""-> reply; ok=false (not a fault) means the target was rejected and the arm did not move."""
|
| 167 |
+
return self.call("move", dict(x=float(x), y=float(y), z=float(z), yaw_deg=float(yaw_deg),
|
| 168 |
+
speed=None if speed is None else float(speed)), allow_not_ok=True)
|
| 169 |
+
|
| 170 |
+
def gripper(self, close):
|
| 171 |
+
return self.call("gripper", dict(close=bool(close)))
|
| 172 |
+
|
| 173 |
+
def state(self):
|
| 174 |
+
return self.call("state")["state"]
|
| 175 |
+
|
| 176 |
+
def observe(self):
|
| 177 |
+
rep = self.call("observe")
|
| 178 |
+
imgs = rep.get("images") or {}
|
| 179 |
+
missing = [c for c in CAMERAS if c not in imgs]
|
| 180 |
+
if missing:
|
| 181 |
+
raise DriverError(f"/observe: missing camera(s) {missing}")
|
| 182 |
+
return {c: decode_image(imgs[c]) for c in CAMERAS}, rep["state"]
|
| 183 |
+
|
| 184 |
+
def ik(self, eef_pos, yaw_deg):
|
| 185 |
+
return self.call("ik", dict(eef_pos=[float(v) for v in eef_pos], yaw_deg=float(yaw_deg)))["joint_pos_rad"]
|
| 186 |
+
|
| 187 |
+
def operator(self, kind, **kw):
|
| 188 |
+
"""Blocks until the operator has answered (no timeout)."""
|
| 189 |
+
assert kind in OPERATOR_KINDS, kind
|
| 190 |
+
return self.call("operator", dict(kind=kind, **kw), timeout=24 * 3600)
|
| 191 |
+
|
| 192 |
+
def event(self, ev, **kw):
|
| 193 |
+
assert ev in EVENTS, ev
|
| 194 |
+
return self.call("event", dict(ev=ev, **kw))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# ------------------------------------------------------------------------------------------------ driver side
|
| 198 |
+
class ConsoleOperator:
|
| 199 |
+
"""The operator's terminal on the robot PC. Prompts block the driver (the robot must not move while the operator
|
| 200 |
+
resets the scene). Answers are appended to `log_path` (JSON lines)."""
|
| 201 |
+
|
| 202 |
+
def __init__(self, log_path=None, stream_in=None, stream_out=None):
|
| 203 |
+
self.log_path = log_path
|
| 204 |
+
self.inp = stream_in or sys.stdin
|
| 205 |
+
self.out = stream_out or sys.stdout
|
| 206 |
+
|
| 207 |
+
def _say(self, s=""):
|
| 208 |
+
self.out.write(s + "\n")
|
| 209 |
+
self.out.flush()
|
| 210 |
+
|
| 211 |
+
def _ask(self, prompt):
|
| 212 |
+
self.out.write(prompt)
|
| 213 |
+
self.out.flush()
|
| 214 |
+
line = self.inp.readline()
|
| 215 |
+
if not line:
|
| 216 |
+
raise EOFError("operator input closed")
|
| 217 |
+
return line.strip()
|
| 218 |
+
|
| 219 |
+
def _log(self, d):
|
| 220 |
+
if self.log_path:
|
| 221 |
+
os.makedirs(os.path.dirname(os.path.abspath(self.log_path)), exist_ok=True)
|
| 222 |
+
with open(self.log_path, "a") as f:
|
| 223 |
+
f.write(json.dumps(dict(d, t=time.time()), ensure_ascii=False) + "\n")
|
| 224 |
+
|
| 225 |
+
def __call__(self, kind, run="", attempt=None, text="", setup="", checklist=None, **_):
|
| 226 |
+
bar = "=" * 72
|
| 227 |
+
self._say("\n" + bar)
|
| 228 |
+
self._say(f"[{time.strftime('%H:%M:%S')}] run {run} attempt {attempt} -- {kind.upper()}")
|
| 229 |
+
if text:
|
| 230 |
+
self._say(text)
|
| 231 |
+
if kind == "reset":
|
| 232 |
+
if setup:
|
| 233 |
+
self._say("\nScene for this attempt (do it exactly; do not talk to anyone about it):\n" + setup)
|
| 234 |
+
self._ask("\nArm is at home. Put the scene back as described, step out of the cameras, press Enter... ")
|
| 235 |
+
self._log(dict(kind=kind, run=run, attempt=attempt))
|
| 236 |
+
return dict(ok=True)
|
| 237 |
+
if kind == "judge":
|
| 238 |
+
for i, c in enumerate(checklist or [], 1):
|
| 239 |
+
self._say(f" {i}. {c}")
|
| 240 |
+
while True:
|
| 241 |
+
a = self._ask("\nAll conditions met? y = success, n = failure, x = run invalid (robot / camera "
|
| 242 |
+
"problem): ").lower()
|
| 243 |
+
if a in ("y", "n", "x"):
|
| 244 |
+
break
|
| 245 |
+
note = self._ask("Note (one line, optional): ")
|
| 246 |
+
self._log(dict(kind=kind, run=run, attempt=attempt, answer=a, note=note))
|
| 247 |
+
if a == "x":
|
| 248 |
+
return dict(ok=False, fault=True, error=f"operator marked the run invalid: {note}")
|
| 249 |
+
return dict(ok=True, success=a == "y", note=note)
|
| 250 |
+
self._log(dict(kind=kind, run=run, attempt=attempt, text=text))
|
| 251 |
+
return dict(ok=True)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class DriverServer:
|
| 255 |
+
"""HTTP plumbing for a driver. Subclass and implement the hardware methods below; see driver_template.py.
|
| 256 |
+
The server is single-threaded on purpose: requests are executed one at a time, and an operator prompt blocks
|
| 257 |
+
every other request until it is answered."""
|
| 258 |
+
|
| 259 |
+
# ---- implement these ------------------------------------------------------------------------------
|
| 260 |
+
def info(self):
|
| 261 |
+
"""-> dict (see DRIVER.md §3): protocol, robot, n_joints, cameras, workspace, yaw_range_deg, max_speed, ik,
|
| 262 |
+
driver_version."""
|
| 263 |
+
raise NotImplementedError
|
| 264 |
+
|
| 265 |
+
def home(self):
|
| 266 |
+
"""Move to the home pose (gripper open, pointing down). -> state dict."""
|
| 267 |
+
raise NotImplementedError
|
| 268 |
+
|
| 269 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 270 |
+
"""Blocking straight-line move of the grasp point; speed m/s or None (= max_speed).
|
| 271 |
+
-> (ok, error_or_None, motion_s). ok=False: rejected BEFORE moving (outside the hard limits / no IK)."""
|
| 272 |
+
raise NotImplementedError
|
| 273 |
+
|
| 274 |
+
def gripper(self, close):
|
| 275 |
+
"""Blocking open / close (force-limited close). -> motion_s."""
|
| 276 |
+
raise NotImplementedError
|
| 277 |
+
|
| 278 |
+
def state(self):
|
| 279 |
+
"""-> dict eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad."""
|
| 280 |
+
raise NotImplementedError
|
| 281 |
+
|
| 282 |
+
def images(self):
|
| 283 |
+
"""-> {"agentview": uint8 HxWx3 RGB, "wrist": ...}, taken now (after the arm has stopped)."""
|
| 284 |
+
raise NotImplementedError
|
| 285 |
+
|
| 286 |
+
def ik(self, eef_pos, yaw_deg):
|
| 287 |
+
"""Optional (info()["ik"] = True): joint angles that put the grasp point at eef_pos / yaw_deg (pointing
|
| 288 |
+
down), close to the current joint angles. -> list of n_joints floats."""
|
| 289 |
+
raise NotImplementedError
|
| 290 |
+
|
| 291 |
+
def operator(self, kind, **kw):
|
| 292 |
+
"""Default: the terminal. -> dict (reset: {ok}; judge: {ok, success, note}; notice: {ok})."""
|
| 293 |
+
return self.console(kind, **kw)
|
| 294 |
+
|
| 295 |
+
def event(self, ev, **kw):
|
| 296 |
+
"""Start / stop your own recordings here (attempt_start / attempt_end / episode_end ...)."""
|
| 297 |
+
return None
|
| 298 |
+
|
| 299 |
+
image_format = "png"
|
| 300 |
+
|
| 301 |
+
# ---- plumbing -------------------------------------------------------------------------------------
|
| 302 |
+
def dispatch(self, endpoint, a):
|
| 303 |
+
if endpoint == "info":
|
| 304 |
+
return dict(ok=True, **self.info())
|
| 305 |
+
if endpoint == "home":
|
| 306 |
+
return dict(ok=True, state=self.home())
|
| 307 |
+
if endpoint == "move":
|
| 308 |
+
ok, err, motion_s = self.move(float(a["x"]), float(a["y"]), float(a["z"]), float(a["yaw_deg"]),
|
| 309 |
+
None if a.get("speed") is None else float(a["speed"]))
|
| 310 |
+
rep = dict(ok=bool(ok), motion_s=float(motion_s or 0.0), state=self.state())
|
| 311 |
+
if not ok:
|
| 312 |
+
rep["error"] = err or "rejected"
|
| 313 |
+
return rep
|
| 314 |
+
if endpoint == "gripper":
|
| 315 |
+
motion_s = self.gripper(bool(a["close"]))
|
| 316 |
+
return dict(ok=True, motion_s=float(motion_s or 0.0), state=self.state())
|
| 317 |
+
if endpoint == "state":
|
| 318 |
+
return dict(ok=True, state=self.state())
|
| 319 |
+
if endpoint == "observe":
|
| 320 |
+
imgs = self.images()
|
| 321 |
+
return dict(ok=True, images={c: encode_image(imgs[c], self.image_format) for c in CAMERAS},
|
| 322 |
+
state=self.state())
|
| 323 |
+
if endpoint == "ik":
|
| 324 |
+
return dict(ok=True, joint_pos_rad=[float(v) for v in self.ik(a["eef_pos"], float(a["yaw_deg"]))])
|
| 325 |
+
if endpoint == "operator":
|
| 326 |
+
kw = {k: v for k, v in a.items() if k != "kind"}
|
| 327 |
+
return self.operator(a["kind"], **kw)
|
| 328 |
+
if endpoint == "event":
|
| 329 |
+
self.event(a.get("ev", ""), **{k: v for k, v in a.items() if k != "ev"})
|
| 330 |
+
return dict(ok=True)
|
| 331 |
+
return dict(ok=False, error=f"unknown endpoint {endpoint!r}")
|
| 332 |
+
|
| 333 |
+
def serve(self, port, token=None, host="127.0.0.1", operator_log=None):
|
| 334 |
+
"""Serve forever on host:port (keep 127.0.0.1 and reach it through an SSH tunnel)."""
|
| 335 |
+
self.token = token or os.environ.get("LFF_DRIVER_TOKEN") or secrets.token_hex(12)
|
| 336 |
+
self.console = ConsoleOperator(operator_log)
|
| 337 |
+
drv = self
|
| 338 |
+
|
| 339 |
+
class H(BaseHTTPRequestHandler):
|
| 340 |
+
def log_message(self, *x):
|
| 341 |
+
pass
|
| 342 |
+
|
| 343 |
+
def do_POST(self):
|
| 344 |
+
try:
|
| 345 |
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
|
| 346 |
+
if self.headers.get(TOKEN_HEADER) != drv.token:
|
| 347 |
+
rep = dict(ok=False, error="unauthorised")
|
| 348 |
+
else:
|
| 349 |
+
rep = drv.dispatch(self.path.strip("/"), body)
|
| 350 |
+
except NotImplementedError as e:
|
| 351 |
+
rep = dict(ok=False, error=f"not implemented: {self.path} {e}")
|
| 352 |
+
except Exception as e: # anything unexpected on the robot side is a fault: stop the run
|
| 353 |
+
traceback.print_exc()
|
| 354 |
+
rep = dict(ok=False, fault=True, error=f"{type(e).__name__}: {e}")
|
| 355 |
+
data = json.dumps(rep).encode()
|
| 356 |
+
self.send_response(200)
|
| 357 |
+
self.send_header("Content-Type", "application/json")
|
| 358 |
+
self.send_header("Content-Length", str(len(data)))
|
| 359 |
+
self.end_headers()
|
| 360 |
+
self.wfile.write(data)
|
| 361 |
+
|
| 362 |
+
srv = HTTPServer((host, int(port)), H)
|
| 363 |
+
print(f"driver ready on http://{host}:{port} token={self.token}", flush=True)
|
| 364 |
+
srv.serve_forever()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/session.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot server for a real arm: robot_server's LA interface (README, robot commands, budgets, attempts, F1, --hide-k,
|
| 2 |
+
memory conditions, events.jsonl, observation files) with a robot driver instead of the simulator.
|
| 3 |
+
|
| 4 |
+
Everything above this server is unchanged: the MCP server (scripts/mcp_robot_server.py), the native-harness adapters
|
| 5 |
+
(Codex / Claude Code, with or without the jail), api_player. They talk to this server exactly as to the simulated one
|
| 6 |
+
(POST /call on 127.0.0.1, same token file, same workspace layout). Below it, lffbench/real/protocol.py talks to the
|
| 7 |
+
driver on the robot PC (usually through an SSH tunnel).
|
| 8 |
+
|
| 9 |
+
What differs from simulation, all of it on purpose (docs/17):
|
| 10 |
+
- README: "a real <robot> arm (<n> joints)" instead of "Franka Emika Panda (7 joints) ... in a physics simulation";
|
| 11 |
+
"a person resets the scene"; "s of robot motion" (budget_left key motion_seconds instead of sim_seconds).
|
| 12 |
+
- outcome: the operator judges the end state against the task's checklist (F1 only; F2 needs simulator measurements).
|
| 13 |
+
- reset: arm to home, then the operator rebuilds the scene from the task's setup sheet.
|
| 14 |
+
- a driver fault ends the episode and marks the run invalid (events.jsonl ev=run_invalid).
|
| 15 |
+
- no video, no regression snapshots here (the driver side records video).
|
| 16 |
+
|
| 17 |
+
python -m lffbench.real.session --task real_offcenter_push --seed 5000 --driver http://127.0.0.1:9900 \
|
| 18 |
+
--sandbox <dir> --log-dir <dir> --port 9800 [robot_server's la options]
|
| 19 |
+
(scripts/start_real_session.sh does this and writes session.json, like scripts/start_robot_session.sh.)
|
| 20 |
+
"""
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import signal
|
| 25 |
+
import time
|
| 26 |
+
import traceback
|
| 27 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
from ..agent import robot_server as RS
|
| 32 |
+
from ..agent.tools import _json_default
|
| 33 |
+
from .executor import RealToolExecutor
|
| 34 |
+
from .protocol import DriverClient, DriverError, DriverFault
|
| 35 |
+
from .tasks import REAL_TASKS
|
| 36 |
+
|
| 37 |
+
SIM_TEXT = { # robot_server._readme_la sentence -> real-robot sentence (each must occur, else refuse to start)
|
| 38 |
+
"embodiment": ("You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics "
|
| 39 |
+
"simulation.", "You control a real {robot} robot arm ({n} joints) with a two-finger parallel gripper."),
|
| 40 |
+
"reset": ("Before every attempt the scene is reset to exactly the same initial state.",
|
| 41 |
+
"Before every attempt a person resets the scene to the same initial state."),
|
| 42 |
+
"motion": (" s of simulated robot motion;", " s of robot motion;"),
|
| 43 |
+
"joints": ("joint_pos_rad = the 7 arm joint angles", "joint_pos_rad = the {n} arm joint angles"),
|
| 44 |
+
}
|
| 45 |
+
REPLY_TEXT = [("The scene has been reset to exactly the same initial state.",
|
| 46 |
+
"A person has reset the scene to the same initial state.")]
|
| 47 |
+
FAULT_MSG = "The robot stopped because of a hardware problem. The episode is over. Stop now and report."
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _realify(o):
|
| 51 |
+
"""Agent-facing reply wording for the real robot (see module doc)."""
|
| 52 |
+
if isinstance(o, dict):
|
| 53 |
+
return {("motion_seconds" if k == "sim_seconds" else k): _realify(v) for k, v in o.items()}
|
| 54 |
+
if isinstance(o, list):
|
| 55 |
+
return [_realify(v) for v in o]
|
| 56 |
+
if isinstance(o, str):
|
| 57 |
+
for a, b in REPLY_TEXT:
|
| 58 |
+
o = o.replace(a, b)
|
| 59 |
+
return o
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class RealRobotSession(RS.RobotSession):
|
| 63 |
+
def __init__(self, a): # robot_server.RobotSession.__init__ minus the simulator
|
| 64 |
+
bad = [m for m, c in (("--style la", a.style != "la"), ("--perception rgb", a.perception != "rgb"),
|
| 65 |
+
("--feedback F0|F1", a.feedback == "F2"), ("--arm none", a.arm != "none"),
|
| 66 |
+
("no --nominal", a.nominal)) if c]
|
| 67 |
+
if bad:
|
| 68 |
+
raise SystemExit("real robot needs " + ", ".join(bad))
|
| 69 |
+
self.a = a
|
| 70 |
+
self.task = REAL_TASKS[a.task]()
|
| 71 |
+
self.task.judge = self._judge
|
| 72 |
+
if a.max_steps is None:
|
| 73 |
+
a.max_steps = int(self.task.agent_max_steps)
|
| 74 |
+
self.inst = self.task.sample_instance(a.seed)
|
| 75 |
+
self.inst_override = json.loads(a.inst_override) if a.inst_override else {}
|
| 76 |
+
self.inst.update(self.inst_override) # tests only (logged)
|
| 77 |
+
self.arm, self.arm_overrides, self.reveal_text = "none", {}, ""
|
| 78 |
+
self.n_mon_events = 0
|
| 79 |
+
self.protocol = self.task.protocol
|
| 80 |
+
self.k = a.k or self.task.max_attempts
|
| 81 |
+
self.k_shown = 1 if a.hide_k and a.memory == "full" else self.k
|
| 82 |
+
self.sandbox = os.path.abspath(a.sandbox)
|
| 83 |
+
self.obs_dir = os.path.join(self.sandbox, "obs")
|
| 84 |
+
self.log_dir = os.path.abspath(a.log_dir)
|
| 85 |
+
os.makedirs(self.obs_dir, exist_ok=True)
|
| 86 |
+
os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True)
|
| 87 |
+
self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a")
|
| 88 |
+
import secrets
|
| 89 |
+
self.token = secrets.token_hex(8)
|
| 90 |
+
self.n_actions, self.attempt, self.step = 0, 1, 0
|
| 91 |
+
self.finished, self.waiting_new_agent, self.invalid = False, False, ""
|
| 92 |
+
self.history, self.last_send, self.video = [], None, None
|
| 93 |
+
self.base_off = np.zeros(3) # the driver already reports the robot-base frame
|
| 94 |
+
self.run = a.run_name or os.path.basename(self.log_dir)
|
| 95 |
+
self.driver = DriverClient(a.driver, a.driver_token, timeout=a.driver_timeout)
|
| 96 |
+
self.dinfo = self.driver.info()
|
| 97 |
+
if self.task.needs_ik and np.any(self.task.bias(self.inst)) and not self.dinfo["ik"]:
|
| 98 |
+
raise SystemExit(f"{a.task} has a calibration bias: the driver must implement /ik (believed joint angles)")
|
| 99 |
+
m = float(self.task.bias_margin)
|
| 100 |
+
self.ws_lo = np.asarray(self.dinfo["workspace"]["lo"], float) + [m, m, 0.0]
|
| 101 |
+
self.ws_hi = np.asarray(self.dinfo["workspace"]["hi"], float) - [m, m, 0.0]
|
| 102 |
+
self.driver.event("session_start", run=self.run, task=a.task, seed=a.seed, k=self.k)
|
| 103 |
+
self._start_attempt(reset=True)
|
| 104 |
+
self._write_sandbox()
|
| 105 |
+
self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol,
|
| 106 |
+
memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception,
|
| 107 |
+
inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm,
|
| 108 |
+
arm_overrides={}, reveal="", dossier=a.dossier or "", backend="real",
|
| 109 |
+
driver_info={k: v for k, v in self.dinfo.items() if k != "ok"},
|
| 110 |
+
agent_workspace=dict(lo=self.ws_lo.round(4).tolist(), hi=self.ws_hi.round(4).tolist()),
|
| 111 |
+
inst_override=self.inst_override, sim_counterpart=self.task.sim_counterpart,
|
| 112 |
+
video_ignored=bool(a.video)))
|
| 113 |
+
|
| 114 |
+
# ------------------------------------------------------------------ simulator-dependent parts, replaced
|
| 115 |
+
def _start_attempt(self, reset):
|
| 116 |
+
self.n_actions = 0
|
| 117 |
+
if reset:
|
| 118 |
+
self.driver.home()
|
| 119 |
+
self.driver.operator("reset", run=self.run, attempt=self.attempt, setup=self.task.setup_text(self.inst),
|
| 120 |
+
text=f"task {self.a.task} seed {self.a.seed}")
|
| 121 |
+
self.driver.event("attempt_start", run=self.run, attempt=self.attempt)
|
| 122 |
+
self.ex = RealToolExecutor(self.driver, self.dinfo, bias=self.task.bias(self.inst), image_res=self.a.image_res)
|
| 123 |
+
self.step = 0
|
| 124 |
+
|
| 125 |
+
def _judge(self, inst):
|
| 126 |
+
self.driver.event("attempt_end", run=self.run, attempt=self.attempt)
|
| 127 |
+
rep = self.driver.operator("judge", run=self.run, attempt=self.attempt, checklist=self.task.checklist(inst),
|
| 128 |
+
text=f"task {self.a.task} seed {self.a.seed}: judge the scene as it is now")
|
| 129 |
+
if not isinstance(rep.get("success"), bool):
|
| 130 |
+
raise DriverError("/operator judge: reply needs \"success\": true|false")
|
| 131 |
+
return dict(success=rep["success"], note=str(rep.get("note", "")), judged_by="operator",
|
| 132 |
+
motion_s=round(self.ex.motion_s, 2))
|
| 133 |
+
|
| 134 |
+
def _budget_left(self):
|
| 135 |
+
used = self.ex.motion_s
|
| 136 |
+
return dict(commands=max(self.a.max_steps - self.n_actions, 0),
|
| 137 |
+
sim_seconds=round(max(self.sim_budget() - used, 0.0), 1)) # renamed to motion_seconds in replies
|
| 138 |
+
|
| 139 |
+
def _state_v2(self):
|
| 140 |
+
p = self.ex.proprio()
|
| 141 |
+
st = dict(eef_pos=p["eef_pos"], eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 142 |
+
st["joint_pos_rad"] = [round(float(v), 4) for v in self.ex.joints()]
|
| 143 |
+
st["budget_left"] = self._budget_left()
|
| 144 |
+
return st
|
| 145 |
+
|
| 146 |
+
def _snap_regressions(self):
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
def readme_la(self):
|
| 150 |
+
text = RS._readme_la(self)
|
| 151 |
+
n = int(self.dinfo["n_joints"])
|
| 152 |
+
for key, (old, new) in SIM_TEXT.items():
|
| 153 |
+
if key == "reset" and self.protocol != "cross":
|
| 154 |
+
continue
|
| 155 |
+
if old not in text: # robot_server's README changed: update SIM_TEXT rather than ship a half-sim README
|
| 156 |
+
raise SystemExit(f"README sentence for {key!r} not found in robot_server._readme_la: {old!r}")
|
| 157 |
+
text = text.replace(old, new.format(robot=self.dinfo["robot"], n=n))
|
| 158 |
+
return text
|
| 159 |
+
|
| 160 |
+
def _done(self, reason):
|
| 161 |
+
rep = RS.RobotSession._done(self, reason)
|
| 162 |
+
if self.finished:
|
| 163 |
+
self.driver.event("episode_end", run=self.run, attempt=self.attempt)
|
| 164 |
+
return rep
|
| 165 |
+
|
| 166 |
+
# ------------------------------------------------------------------ dispatch
|
| 167 |
+
def handle(self, cmd, args):
|
| 168 |
+
if self.invalid:
|
| 169 |
+
return dict(ok=False, error=FAULT_MSG)
|
| 170 |
+
try:
|
| 171 |
+
return _realify(RS.RobotSession.handle(self, cmd, args))
|
| 172 |
+
except DriverError as e: # robot fault, operator marked the run invalid, or the driver broke the protocol
|
| 173 |
+
self.invalid, self.finished = str(e), True
|
| 174 |
+
self.log(dict(ev="run_invalid", attempt=self.attempt, step=self.step, cmd=cmd, args=args,
|
| 175 |
+
fault=isinstance(e, DriverFault), error=str(e), traceback=traceback.format_exc()[-2000:]))
|
| 176 |
+
try:
|
| 177 |
+
self.driver.event("run_invalid", run=self.run, attempt=self.attempt, error=str(e))
|
| 178 |
+
except DriverError:
|
| 179 |
+
pass
|
| 180 |
+
return dict(ok=False, error=FAULT_MSG)
|
| 181 |
+
|
| 182 |
+
def handle_v2(self, cmd, args):
|
| 183 |
+
if cmd != "move_eef" or self.finished:
|
| 184 |
+
return RS._handle_v2(self, cmd, args)
|
| 185 |
+
return self._move_eef(args)
|
| 186 |
+
|
| 187 |
+
def _move_eef(self, args):
|
| 188 |
+
"""robot_server._handle_v2's move_eef branch (same checks, order, replies and log lines) with the driver's
|
| 189 |
+
workspace instead of the simulator's WS_LO / WS_HI. tests/real_selfcheck.py compares the two paths reply by
|
| 190 |
+
reply; keep them in step."""
|
| 191 |
+
cmd = "move_eef"
|
| 192 |
+
self.n_actions += 1
|
| 193 |
+
if self.n_actions > self.a.max_steps:
|
| 194 |
+
rep = self._done("command budget used up (automatic)")
|
| 195 |
+
rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up."
|
| 196 |
+
return rep
|
| 197 |
+
self.step += 1
|
| 198 |
+
p = self.ex.proprio()
|
| 199 |
+
unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}
|
| 200 |
+
if unknown:
|
| 201 |
+
rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed")
|
| 202 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 203 |
+
return rep
|
| 204 |
+
try:
|
| 205 |
+
cur = np.asarray(p["eef_pos"], float)
|
| 206 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 207 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 208 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 209 |
+
except (TypeError, ValueError):
|
| 210 |
+
rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers")
|
| 211 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 212 |
+
return rep
|
| 213 |
+
grip = args.get("gripper")
|
| 214 |
+
if grip not in (None, "open", "close"):
|
| 215 |
+
rep = dict(ok=False, error="gripper must be open or close")
|
| 216 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 217 |
+
return rep
|
| 218 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 219 |
+
tgt = np.asarray(tgt)
|
| 220 |
+
if moving and not (np.all(tgt >= self.ws_lo) and np.all(tgt <= self.ws_hi)):
|
| 221 |
+
rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move")
|
| 222 |
+
rep.update(self._state_v2())
|
| 223 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 224 |
+
return rep
|
| 225 |
+
left = self._budget_left()["sim_seconds"]
|
| 226 |
+
raw = {}
|
| 227 |
+
rejected = False
|
| 228 |
+
if moving:
|
| 229 |
+
mv = dict(x=float(tgt[0]), y=float(tgt[1]), z=float(tgt[2]), yaw=yaw)
|
| 230 |
+
if speed is not None:
|
| 231 |
+
mv["speed"] = speed
|
| 232 |
+
res = self.ex.call("move_to", mv)
|
| 233 |
+
raw.update(res.report)
|
| 234 |
+
rejected = not res.ok # the driver refused (no IK solution ...): the arm did not move, skip the gripper
|
| 235 |
+
if grip is not None and not rejected:
|
| 236 |
+
res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {})
|
| 237 |
+
raw.update(res.report)
|
| 238 |
+
rep = dict(ok=bool(raw.get("ok", True)))
|
| 239 |
+
if raw.get("error"):
|
| 240 |
+
rep["error"] = raw["error"]
|
| 241 |
+
rep.update(self._state_v2())
|
| 242 |
+
if moving:
|
| 243 |
+
err = tgt - np.asarray(rep["eef_pos"])
|
| 244 |
+
dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0
|
| 245 |
+
rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1))
|
| 246 |
+
rep["images"] = self._save_obs(cmd)
|
| 247 |
+
rep.update(self._la_files())
|
| 248 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw))
|
| 249 |
+
if rep["budget_left"]["sim_seconds"] <= 0 and left > 0:
|
| 250 |
+
fin = self._done("motion budget used up (automatic)")
|
| 251 |
+
fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up."
|
| 252 |
+
rep["attempt_ended"] = fin
|
| 253 |
+
return rep
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def serve(a):
|
| 257 |
+
"""robot_server.serve with the real session (same HTTP contract: POST /call, X-Token, 127.0.0.1)."""
|
| 258 |
+
sess = RealRobotSession(a)
|
| 259 |
+
|
| 260 |
+
class H(BaseHTTPRequestHandler):
|
| 261 |
+
def log_message(self, *x):
|
| 262 |
+
pass
|
| 263 |
+
|
| 264 |
+
def do_POST(self):
|
| 265 |
+
t_recv = time.time()
|
| 266 |
+
cmd = ""
|
| 267 |
+
try:
|
| 268 |
+
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
| 269 |
+
cmd = body.get("cmd", "")
|
| 270 |
+
if self.headers.get("X-Token") != sess.token:
|
| 271 |
+
rep = dict(ok=False, error="unauthorised")
|
| 272 |
+
else:
|
| 273 |
+
rep = sess.handle(cmd, body.get("args", {}) or {})
|
| 274 |
+
except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent
|
| 275 |
+
sess.log(dict(ev="error", error=traceback.format_exc()))
|
| 276 |
+
rep = dict(ok=False, error=f"internal error: {type(e).__name__}")
|
| 277 |
+
data = json.dumps(rep, default=_json_default, indent=None).encode()
|
| 278 |
+
if "text" in rep:
|
| 279 |
+
data = rep["text"].encode()
|
| 280 |
+
self.send_response(200)
|
| 281 |
+
self.send_header("Content-Type", "application/json")
|
| 282 |
+
self.end_headers()
|
| 283 |
+
self.wfile.write(data)
|
| 284 |
+
t_send = time.time()
|
| 285 |
+
sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send,
|
| 286 |
+
server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None))
|
| 287 |
+
sess.last_send = t_send
|
| 288 |
+
|
| 289 |
+
def _term(*_):
|
| 290 |
+
try: # short timeout: the driver may be blocked on an operator prompt
|
| 291 |
+
sess.driver.call("event", dict(ev="session_end", run=sess.run, attempt=sess.attempt), timeout=5)
|
| 292 |
+
except Exception:
|
| 293 |
+
pass
|
| 294 |
+
os._exit(0)
|
| 295 |
+
|
| 296 |
+
signal.signal(signal.SIGTERM, _term)
|
| 297 |
+
srv = HTTPServer(("127.0.0.1", a.port), H)
|
| 298 |
+
print(f"real robot server ready on 127.0.0.1:{a.port} driver={a.driver} sandbox={sess.sandbox} log={sess.log_dir}",
|
| 299 |
+
flush=True)
|
| 300 |
+
with open(os.path.join(sess.log_dir, "READY"), "w") as f:
|
| 301 |
+
f.write(str(os.getpid()))
|
| 302 |
+
srv.serve_forever()
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def parser():
|
| 306 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 307 |
+
ap.add_argument("--task", required=True, choices=sorted(REAL_TASKS))
|
| 308 |
+
ap.add_argument("--seed", type=int, required=True)
|
| 309 |
+
ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900"),
|
| 310 |
+
help="driver URL (default $LFF_REAL_DRIVER or http://127.0.0.1:9900, i.e. an SSH tunnel)")
|
| 311 |
+
ap.add_argument("--driver-token", default=os.environ.get("LFF_DRIVER_TOKEN", ""),
|
| 312 |
+
help="driver token (default $LFF_DRIVER_TOKEN)")
|
| 313 |
+
ap.add_argument("--driver-timeout", type=float, default=180.0, help="seconds per driver call (operator: no limit)")
|
| 314 |
+
ap.add_argument("--run-name", default="", help="shown to the operator (default: the log dir name)")
|
| 315 |
+
ap.add_argument("--inst-override", default=os.environ.get("LFF_REAL_INST_OVERRIDE", ""),
|
| 316 |
+
help="TESTS ONLY: JSON merged into the instance (logged; default $LFF_REAL_INST_OVERRIDE)")
|
| 317 |
+
# robot_server's options that apply to the real robot (same names and defaults as there, except perception/style)
|
| 318 |
+
ap.add_argument("--k", type=int, default=None)
|
| 319 |
+
ap.add_argument("--memory", default="full", choices=["full", "none"])
|
| 320 |
+
ap.add_argument("--hide-k", action="store_true")
|
| 321 |
+
ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
|
| 322 |
+
ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"])
|
| 323 |
+
ap.add_argument("--image-res", type=int, default=512)
|
| 324 |
+
ap.add_argument("--port", type=int, default=8765)
|
| 325 |
+
ap.add_argument("--sandbox", required=True)
|
| 326 |
+
ap.add_argument("--log-dir", required=True)
|
| 327 |
+
ap.add_argument("--max-steps", type=int, default=None)
|
| 328 |
+
ap.add_argument("--perception", default="rgb", choices=["depth", "rgb", "rgbd"])
|
| 329 |
+
ap.add_argument("--style", default="la", choices=["v1", "v2", "la"])
|
| 330 |
+
ap.add_argument("--nominal", action="store_true")
|
| 331 |
+
ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"])
|
| 332 |
+
ap.add_argument("--max-tool-calls", type=int, default=100)
|
| 333 |
+
ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"])
|
| 334 |
+
ap.add_argument("--dossier", default="")
|
| 335 |
+
ap.add_argument("--video", default="", help="ignored (the driver side records video)")
|
| 336 |
+
ap.add_argument("--video-every", type=int, default=3)
|
| 337 |
+
ap.add_argument("--video-fps", type=int, default=20)
|
| 338 |
+
return ap
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def main():
|
| 342 |
+
serve(parser().parse_args())
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
if __name__ == "__main__":
|
| 346 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/real/tasks.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-robot tasks. Same idea as lffbench/tasks/ (an instruction, a hidden variable the agent cannot see before it acts,
|
| 2 |
+
a success rule), but the scene is physical: the instance is a setup sheet the operator follows, and the operator
|
| 3 |
+
judges the end state. The hidden variable is drawn from the seed, so the instance list of a run is reproducible and
|
| 4 |
+
nobody has to choose it by hand.
|
| 5 |
+
|
| 6 |
+
Seeds: 5000+ for real-robot runs (same convention as simulation: 1000-1999 development, 3000 pilots, 5000+ test).
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
REAL_TASKS = {}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def register_real(cls):
|
| 14 |
+
REAL_TASKS[cls.name] = cls
|
| 15 |
+
return cls
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RealTask:
|
| 19 |
+
name = "real_base"
|
| 20 |
+
sim_counterpart = "" # the simulated task with the same hidden variable (for the paper's mapping only)
|
| 21 |
+
protocol = "cross"
|
| 22 |
+
max_attempts = 3
|
| 23 |
+
agent_max_steps = 40
|
| 24 |
+
instruction = ""
|
| 25 |
+
instruction_indirect = ""
|
| 26 |
+
needs_ik = False # True if the instance carries a calibration bias (believed joint angles need the driver's /ik)
|
| 27 |
+
bias_margin = 0.0 # largest possible |bias| (m): the agent-facing workspace is shrunk by it, so a rejected target
|
| 28 |
+
# never depends on the hidden bias
|
| 29 |
+
judge = None # set by RealRobotSession: inst -> outcome dict, asks the operator
|
| 30 |
+
|
| 31 |
+
def outcome(self, inst):
|
| 32 |
+
"""Same role as LFFTask.outcome: called by robot_server's _done when an attempt ends."""
|
| 33 |
+
return self.judge(inst)
|
| 34 |
+
|
| 35 |
+
def sample_instance(self, seed):
|
| 36 |
+
raise NotImplementedError
|
| 37 |
+
|
| 38 |
+
def setup_text(self, inst):
|
| 39 |
+
"""What the operator builds before every attempt (shown on the robot PC only, never to the agent)."""
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def checklist(self, inst):
|
| 43 |
+
"""Conditions the operator checks when an attempt ends; success = all of them."""
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
def bias(self, inst):
|
| 47 |
+
"""Hidden calibration error added to every commanded position (robot-base frame, metres)."""
|
| 48 |
+
return np.zeros(3)
|
| 49 |
+
|
| 50 |
+
def feedback(self, inst, out, level="F1"):
|
| 51 |
+
# same text as LFFTask.feedback (F0 / F1); F2 needs simulator measurements and is refused at session start
|
| 52 |
+
if level == "F0":
|
| 53 |
+
return ""
|
| 54 |
+
return "Attempt succeeded." if out["success"] else "Attempt failed."
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@register_real
|
| 58 |
+
class RealOffcenterPush(RealTask):
|
| 59 |
+
"""L7 l7_offcenter_push on a real arm: a long opaque box with a hidden weight at one end. Pushing the middle of
|
| 60 |
+
its back face turns it (visible in the agentview); the fix is to push nearer the heavy end or to straighten it
|
| 61 |
+
afterwards. Physical build and scene layout: DRIVER.md §6.1."""
|
| 62 |
+
name = "real_offcenter_push"
|
| 63 |
+
sim_counterpart = "l7_offcenter_push"
|
| 64 |
+
# same wording as the simulated task (2026-10-19): end state only, no hint about the weight or where to push
|
| 65 |
+
instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the "
|
| 66 |
+
"green rectangle ahead of it (farther from the robot).")
|
| 67 |
+
instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up "
|
| 68 |
+
"completely inside the marked green area ahead of it (farther from the robot).")
|
| 69 |
+
SLOTS = ("end", "inner") # weight compartments per side: at the very end, or one compartment further in
|
| 70 |
+
|
| 71 |
+
def sample_instance(self, seed):
|
| 72 |
+
rng = np.random.default_rng(seed)
|
| 73 |
+
return dict(seed=int(seed), weight_side=str(rng.choice(["left", "right"])), weight_slot=str(rng.choice(self.SLOTS)))
|
| 74 |
+
|
| 75 |
+
def setup_text(self, inst):
|
| 76 |
+
side = {"left": "LEFT (the robot's left, +y)", "right": "RIGHT (the robot's right, -y)"}[inst["weight_side"]]
|
| 77 |
+
slot = {"end": "the outermost compartment", "inner": "the second compartment from that end"}[inst["weight_slot"]]
|
| 78 |
+
return "\n".join([
|
| 79 |
+
f"- weight block inside the box: {side} end, in {slot};",
|
| 80 |
+
"- the other compartments stay empty; close the lid; both ends look the same from outside;",
|
| 81 |
+
"- box on the START tape marks: long side across the robot (left-right), back face on the back mark;",
|
| 82 |
+
"- nothing else on the table; the green target rectangle tape unchanged.",
|
| 83 |
+
])
|
| 84 |
+
|
| 85 |
+
def checklist(self, inst):
|
| 86 |
+
return ["all four bottom corners of the box are inside the green rectangle (a corner on the tape = outside)",
|
| 87 |
+
"the box is standing on its bottom face (not tipped over)",
|
| 88 |
+
"the box was only pushed with the closed gripper (no pushes with the fingers open)",
|
| 89 |
+
"the gripper is not touching the box"]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@register_real
|
| 93 |
+
class RealBiasPlace(RealTask):
|
| 94 |
+
"""L1 l1_bias_place on a real arm: pick-and-place with a calibration error injected in software (the benchmark
|
| 95 |
+
adds `bias` to every commanded position and subtracts it from every reported one, exactly as in simulation).
|
| 96 |
+
The arm itself is unchanged; the cameras show where the gripper really is. Physical build: DRIVER.md §6.2."""
|
| 97 |
+
name = "real_bias_place"
|
| 98 |
+
sim_counterpart = "l1_bias_place"
|
| 99 |
+
instruction = "Pick up the red cube and put it into the bowl."
|
| 100 |
+
instruction_indirect = "Pick up the small red block and put it into the round bowl."
|
| 101 |
+
needs_ik = True
|
| 102 |
+
R_MIN, R_MAX = 0.025, 0.040 # bias magnitude (m), as l1_bias_place
|
| 103 |
+
bias_margin = R_MAX
|
| 104 |
+
LAYOUTS = ("A", "B", "C", "D") # taped (cube mark, bowl mark) pairs; DRIVER.md §6.2
|
| 105 |
+
|
| 106 |
+
def sample_instance(self, seed):
|
| 107 |
+
rng = np.random.default_rng(seed)
|
| 108 |
+
r, th = float(rng.uniform(self.R_MIN, self.R_MAX)), float(rng.uniform(-np.pi, np.pi))
|
| 109 |
+
return dict(seed=int(seed), layout=str(rng.choice(self.LAYOUTS)),
|
| 110 |
+
bias=[round(r * np.cos(th), 4), round(r * np.sin(th), 4), 0.0], bias_r=round(r, 4),
|
| 111 |
+
bias_theta=round(th, 4))
|
| 112 |
+
|
| 113 |
+
def bias(self, inst):
|
| 114 |
+
return np.asarray(inst["bias"], float)
|
| 115 |
+
|
| 116 |
+
def setup_text(self, inst):
|
| 117 |
+
L = inst["layout"]
|
| 118 |
+
return "\n".join([f"- red cube on mark {L}1, bowl on mark {L}2 (layout {L});",
|
| 119 |
+
"- nothing else on the table."])
|
| 120 |
+
|
| 121 |
+
def checklist(self, inst):
|
| 122 |
+
return ["the red cube is inside the bowl (resting in it, not on the rim)",
|
| 123 |
+
"the gripper is open and not holding the cube"]
|