PeterXie666 commited on
Commit
b20af45
·
verified ·
1 Parent(s): ffe928a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. leaf/final/episode_000199_image.png +3 -0
  2. leaf/final/episode_000680_wrist_image.png +3 -0
  3. leaf/final/episode_001025_wrist_image.png +3 -0
  4. leaf/final/episode_001177.npz +3 -0
  5. leaf/final/episode_001231.npz +3 -0
  6. leaf/final/episode_001239_image.png +3 -0
  7. leaf/final/episode_001456_wrist_image.png +3 -0
  8. leaf/final/episode_001507.npz +3 -0
  9. leaf/final/episode_001620_wrist_image.png +3 -0
  10. leaf/final/episode_001862.npz +3 -0
  11. leaf/final/episode_001986_wrist_image.png +3 -0
  12. leaf/final/episode_002066_image.png +3 -0
  13. leaf/final/episode_002407.npz +3 -0
  14. leaf/final/episode_002512_image.png +3 -0
  15. leaf/final/episode_002630_image.png +3 -0
  16. leaf/final/episode_002851_wrist_image.png +3 -0
  17. leaf/final/episode_002876.npz +3 -0
  18. leaf/final/episode_002954_wrist_image.png +3 -0
  19. leaf/final/episode_003147.npz +3 -0
  20. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/agent/cost.py +37 -0
  21. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py +61 -0
  22. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/__init__.py +63 -0
  23. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/contract.py +160 -0
  24. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/dsh.py +403 -0
  25. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/fakeapi.py +188 -0
  26. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/framework_codex.py +542 -0
  27. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/jail.py +228 -0
  28. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/pins.py +40 -0
  29. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/reference.py +143 -0
  30. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/harnesses/sensenova.py +24 -0
  31. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/real/executor.py +138 -0
  32. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l2_turntable.py +469 -0
  33. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/gptpolicy_player.sh +37 -0
  34. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/ladder_plan.py +120 -0
  35. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/layer4_plan.py +174 -0
  36. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/make_dossier.py +103 -0
  37. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/qwen_vl_server.py +535 -0
  38. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/qwen_vl_server.sh +17 -0
  39. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/start_robot_session.sh +24 -0
  40. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/tool_gateway.py +331 -0
  41. leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/validate_ladder_fix.py +168 -0
  42. leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins.py +40 -0
  43. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/README.md +12 -0
  44. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/evaluation_evidence/workspace_exposure_audit.json +329 -0
  45. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/__init__.py +63 -0
  46. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/contract.py +160 -0
  47. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/dsh.py +403 -0
  48. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/jail.py +228 -0
  49. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/harnesses/redteam.py +59 -0
  50. leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/source_closure/lffbench/tasks/l4_nest.py +644 -0
leaf/final/episode_000199_image.png ADDED

Git LFS Details

  • SHA256: 506a34fff9b7e25c582d4facb12bd8fb6103d8e5e0dfc104a4dcf05852cdc134
  • Pointer size: 130 Bytes
  • Size of remote file: 54.1 kB
leaf/final/episode_000680_wrist_image.png ADDED

Git LFS Details

  • SHA256: b6284709338260cd5f19aae171d5ff9656b48474f3c37cd5639d02b6271a3b85
  • Pointer size: 130 Bytes
  • Size of remote file: 38.4 kB
leaf/final/episode_001025_wrist_image.png ADDED

Git LFS Details

  • SHA256: 282c83afcbddad7b7bfa1b7acbaf55bb14fe392766d7bc60a5e4df42e15a2b66
  • Pointer size: 130 Bytes
  • Size of remote file: 35.1 kB
leaf/final/episode_001177.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3ca5e27f061e2112390f0c7e50c2c7cbf28e28f3fb446071266a84ca1adb00a
3
+ size 3734
leaf/final/episode_001231.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8910c0b80481009848e708329c584e92c7c609ad8ca2ab85f82f1b1d820f545b
3
+ size 3854
leaf/final/episode_001239_image.png ADDED

Git LFS Details

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

Git LFS Details

  • SHA256: e260aa570c6594930a50479d5fbee9970981c71f997331f4f799a84f630607bc
  • Pointer size: 130 Bytes
  • Size of remote file: 23.9 kB
leaf/final/episode_001507.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cbe211f45a1a22b30606effd10a24b9ddb01639befda3b7c465d21c765733a9f
3
+ size 3734
leaf/final/episode_001620_wrist_image.png ADDED

Git LFS Details

  • SHA256: 064476a6b6c00156ec467df8ccdd081f9f8471a1df09d05bb768081810c77d37
  • Pointer size: 130 Bytes
  • Size of remote file: 47.9 kB
leaf/final/episode_001862.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:190f8f64253e27500a6412f8530b68c41e952cbd56b3f15e6abf4b2a47e9fd1d
3
+ size 4270
leaf/final/episode_001986_wrist_image.png ADDED

Git LFS Details

  • SHA256: c57f75bda8af166a0767376bda35154201fc2153ee03355caca0baf538da184c
  • Pointer size: 130 Bytes
  • Size of remote file: 45.9 kB
leaf/final/episode_002066_image.png ADDED

Git LFS Details

  • SHA256: 881700ec4be093df37d8f6832bdb0999e4d7a64615d2be0756f4023f9f5f6c9f
  • Pointer size: 130 Bytes
  • Size of remote file: 61.1 kB
leaf/final/episode_002407.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57a72c5813b99f81231d972985cce1e2da8aba534ea4a28ecaf69fb0f8ec3830
3
+ size 3870
leaf/final/episode_002512_image.png ADDED

Git LFS Details

  • SHA256: 621cf4157eae29390cecf9082f0764c6ecc468a3a2161bd5f79d28b86a4f0256
  • Pointer size: 130 Bytes
  • Size of remote file: 52.8 kB
leaf/final/episode_002630_image.png ADDED

Git LFS Details

  • SHA256: 8a7d49b4fad4d3df5940d8b22c31d8c0cc271694ce36e9cae437008094ab45ac
  • Pointer size: 130 Bytes
  • Size of remote file: 52.8 kB
leaf/final/episode_002851_wrist_image.png ADDED

Git LFS Details

  • SHA256: ed697f1dcd8a098ac79c874e6ba4f9a9143c935ee4d2046e7aae341ddcde741d
  • Pointer size: 130 Bytes
  • Size of remote file: 43.2 kB
leaf/final/episode_002876.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7c874789d24ce5063108492fb986edf6126f2908a852506c7d0922bc186401fe
3
+ size 4046
leaf/final/episode_002954_wrist_image.png ADDED

Git LFS Details

  • SHA256: f636d49a121d2ec36ddd536917633060defe4ecd4a2f8c503a0edd830905755a
  • Pointer size: 130 Bytes
  • Size of remote file: 33.2 kB
leaf/final/episode_003147.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aab42ff2af9b92c422d9d3f2656cec9e4f36f454612bf9fc143b9eaf99de768b
3
+ size 3854
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l3_wall_flush (2026-10-12).
2
+
3
+ Hidden variable: inst["gap"] -- the box-wall gap, 0-3 mm (below camera resolution), far less than the ~1.2 cm a
4
+ finger needs, so the wall-side finger lands on the wall top. sample_instance caches the wall position derived from it
5
+ (wall_x = box_x + side * (wall half thickness + box half width + gap)) and apply_instance reads only inst["wall_xy"],
6
+ so every override below sets wall_xy as well.
7
+
8
+ h0 gap = 5 cm: box, plate, wall length and wall y unchanged, the wall moved 4.7-5 cm away from the box (on the
9
+ same side). There is room for the whole finger and the prior (grasp across the width where the box lies) works.
10
+ (2.5 cm was not enough: the open fingers reach 6.6 cm from the grasp centre, so with the wall on the far side
11
+ the outer edge of the finger still caught the wall top and the box slipped out on the way, seeds 3000 / 3003.)
12
+ twin Gap unchanged (box still flush, trap active), box / plate / wall length / wall x unchanged, but the wall slid
13
+ along y so that the box sits near the OTHER end of the wall, 2 cm of wall beyond the box's end (the sampler's
14
+ extreme). The original's nearer wall end is +y (or -y); the twin's is -y (or +y): the push that clears the
15
+ wall goes the opposite way, and is the shortest possible push (about 10 + 4.5 cm).
16
+ Note: pushing the original's box towards its FAR end also clears the wall (just a longer push), so the cross
17
+ check "twin oracle on the original" succeeds (measured 5/5, seeds 3000-3004; results/l3_wall_flush/arms/
18
+ validate.json). The twin changes which way to push, not whether pushing works.
19
+ reveal The gap, and on which side of the box the wall is, in the task's F2 frame words.
20
+ """
21
+ BOX_HALF_X, BOX_HALF_Y, WALL_HALF_T = 0.03, 0.08, 0.015
22
+ H0_GAP = 0.05
23
+
24
+ HIDDEN_KEYS = ("gap",)
25
+
26
+
27
+ def _wall_x(inst, gap):
28
+ return inst["box_xy"][0] + inst["side"] * (WALL_HALF_T + BOX_HALF_X + gap)
29
+
30
+
31
+ def h0(inst):
32
+ return {"gap": H0_GAP, "wall_xy": [_wall_x(inst, H0_GAP), inst["wall_xy"][1]]}
33
+
34
+
35
+ def twin(inst):
36
+ wy, by = inst["wall_xy"][1], inst["box_xy"][1]
37
+ u_max = inst["wall_hl"] - BOX_HALF_Y - 0.02
38
+ nearer = 1 if by - wy > 0 else -1 # same rule as WallFlush._nearer_end
39
+ u_twin = -nearer * u_max # box offset from the wall centre in the twin: near the other end
40
+ return {"wall_xy": [inst["wall_xy"][0], by - u_twin]}
41
+
42
+
43
+ def reveal(inst):
44
+ side = "far side (away from the robot)" if inst["side"] > 0 else "near side (toward the robot)"
45
+ return (f"The long box is pressed against the wall on its {side} along its whole length: the gap between box "
46
+ f"and wall is only about {max(100 * inst['gap'], 0.1):.1f} cm.")
47
+
48
+
49
+ def fix(inst, params):
50
+ """Ladder Fix rung (docs/20): push the box along the wall past its nearer end (oracle end, margin 4.5 cm), then
51
+ grasp across the width and place."""
52
+ end, margin = int(params["end"]), float(params["margin"])
53
+ wy, hl, by = float(inst["wall_xy"][1]), float(inst["wall_hl"]), float(inst["box_xy"][1])
54
+ wall_end = wy + hl if end > 0 else wy - hl
55
+ dist = max(0.0, end * (wall_end + end * margin - by))
56
+ side, other = ("left", "right") if end > 0 else ("right", "left")
57
+ return (f"A way to succeed: first get the box away from the wall, then grasp it. With the gripper closed and the "
58
+ f"fingertips about 1 cm above the table, push on the box's end face on the robot's {other} side and slide "
59
+ f"the box slowly (speed about 0.08) along the wall towards the robot's {side}, about {100 * dist:.0f} cm, "
60
+ f"until the whole box is past the end of the wall (its centre about {100 * margin:.1f} cm beyond the "
61
+ f"wall's end). Then lift, open the gripper, grasp the box across its 6 cm width and put it on the plate.")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/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/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/lffbench/tasks/l2_turntable.py ADDED
@@ -0,0 +1,469 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-C turntable_restore: take the butter off a turntable that stands half under a shelf, then turn the
2
+ turntable back exactly the way it was.
3
+
4
+ Replaces the planned l2_drawer_reclosed (feasibility test 2026-10-07, see the task card): with the gripper
5
+ always pointing straight down, the handle of LIBERO's wooden_cabinet top drawer (3.8 cm below the cabinet
6
+ top) cannot be reached -- the descent stops 1.5-4.5 cm above it, closing grasps nothing (4/4 cabinet
7
+ placements) and a pull opened the drawer only 1/4 times, by accident. The turntable keeps the idea (an
8
+ articulated fixture the agent *has to* change to get the object and has to put back afterwards) and is
9
+ operable with move_to + open/close only.
10
+
11
+ Scene: a turntable (lazy susan; disc radius 17 cm on a damped hinge about z) on the robot's right; a fixed
12
+ shelf board 10 cm above the disc covers its -y half (robot's right), so nothing under the board can be
13
+ grasped from above (measured, 20 seeds x 2 grasp yaws: the hand stops on the board 10-14 cm above the grasp
14
+ height, 0/40 lifts). Four red pegs stand near the rim; grasping a peg and moving the gripper along the rim
15
+ turns the disc. The butter lies on the disc under the board; painted marks (yellow stripe, blue square,
16
+ green dot; visual only) make the disc's angle readable. The basket stands on the robot's left.
17
+
18
+ Why the first attempt fails (the L2 event is the agent's own, necessary change): to reach the butter the
19
+ agent must turn the disc by 136-179 deg (start angle random; measured on seeds 1000-1019). An agent that puts the butter into the basket
20
+ and stops leaves the turntable turned -> failure. To repair it the agent has to turn it back to its start
21
+ angle (+-15 deg); after the main turn the marks are elsewhere and nothing in the scene shows the start angle:
22
+ it is only in the first frame (or in the agent's memory of how far it turned). The F2 text says *that* the
23
+ turntable is not turned the way it was, never by how much or which way.
24
+
25
+ Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
26
+ round; the outcome (success + F2 text) is computed after each round.
27
+
28
+ Scripted references (perception stand-in: simulator poses; motions: Skills.move_to / set_gripper only)
29
+ oracle turns, takes the butter, then immediately turns the disc back to the saved start angle.
30
+ naive turns, takes the butter, done.
31
+ adaptive saves the start angle (Save); after F2 "not turned the way it was" turns back to it (Retrieve +
32
+ Utilize); redoes the main task if the butter is not in the basket.
33
+ blind no history, no feedback: every later round redoes the main task (lifts the butter out of the
34
+ basket and drops it back, grasp jittered by 5 mm).
35
+ nomem (extra control, not in the acceptance table) gets F2 but has no start frame: turns the disc by a
36
+ random angle in (-180, 180] deg each round.
37
+
38
+ Physics notes (all measured while building the task, 2026-10-07): the HOPE butter weighs 5 g -> set to 0.2 kg;
39
+ a box on a cylinder gets a single contact point and no torsional friction, so the butter span on the disc at
40
+ ~4 deg/s even at rest -> the disc's collision surface is the inscribed square plate (visual disc stays round).
41
+ """
42
+ import numpy as np
43
+
44
+ from .. import envs
45
+ from ..bddl import write_bddl
46
+ from ..objects import _fmt, register_generated
47
+ from ..task_base import LFFTask, register_task
48
+
49
+ TT = "turntable_1"
50
+ TARGET = "butter_1"
51
+ ITEMS = (TARGET,)
52
+ BASKET = "basket_1"
53
+ MASS = {"butter_1": 0.20} # real-world order (the HOPE box weighs 5 g)
54
+
55
+ # turntable geometry (fixture frame: origin on the table top at the disc axis)
56
+ R = 0.17 # disc radius
57
+ DISC_T = 0.012 # disc thickness
58
+ BASE_H = 0.012 # pedestal height
59
+ DISC_TOP = BASE_H + DISC_T # disc top above the table
60
+ PEG_R, PEG_RAD, PEG_H = 0.009, 0.155, 0.035 # radius, distance from the axis, height above the disc
61
+ # (low enough that the hand clears the pegs by 1 cm when it grasps the butter between them)
62
+ PEG_ANG = tuple(np.pi / 4 + k * np.pi / 2 for k in range(4)) # disc frame
63
+ STRIPE_ANG = np.pi # disc frame
64
+ BOARD_Z = DISC_TOP + 0.10 # underside of the shelf board above the table
65
+ BOARD_EDGE = 0.01 # the board covers fixture y < +1 cm (the -y half of the disc)
66
+ HINGE = dict(damping=1.0, armature=0.3, frictionloss=0.01) # the disc stops within ~1 deg when released
67
+ ITEM_R = 0.07 # butter's distance from the axis (disc frame); open fingers at a held peg clear it by >= 1.2 cm
68
+
69
+ ANG_TOL = np.radians(15.0) # success: disc within 15 deg of its start angle (4 cm at the pegs, 2.6 cm at the stripe end)
70
+ BASKET_IN = 0.060 # LIBERO basket: half size of the inner floor
71
+ BASKET_RIM = 0.150
72
+ BASKET_FLOOR = 0.017
73
+ SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
74
+
75
+ NAMES = {TARGET: "butter"}
76
+ DESCR = {TARGET: "small orange box"}
77
+
78
+
79
+ def _wrap(a):
80
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
81
+
82
+
83
+ def _wrap_half(a):
84
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
85
+
86
+
87
+ def _rot(a):
88
+ c, s = np.cos(a), np.sin(a)
89
+ return np.array([[c, -s], [s, c]])
90
+
91
+
92
+ def turntable_xml(model_name):
93
+ """Static pedestal + shelf board + side wall; a hinged disc (child body) with 4 pegs and painted marks."""
94
+ def geoms(kind, pos, size, rgba, coll=True, vis=True):
95
+ s = f'type="{kind}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(rgba)}"'
96
+ out = [f'<geom {s} conaffinity="0" contype="0" group="1" />'] if vis else []
97
+ if coll:
98
+ out.insert(0, f'<geom {s} friction="1.0 0.005 0.0001" {SOLID} density="400" group="0" />')
99
+ return out
100
+
101
+ shelf = (0.82, 0.82, 0.80, 1.0)
102
+ fixed = geoms("cylinder", (0, 0, BASE_H / 2), (0.06, BASE_H / 2), (0.3, 0.3, 0.3, 1.0))
103
+ by0, by1, bx = -(R + 0.04), BOARD_EDGE, R + 0.04
104
+ fixed += geoms("box", (0, (by0 + by1) / 2, BOARD_Z + 0.004), (bx, (by1 - by0) / 2, 0.004), shelf)
105
+ fixed += geoms("box", (0, by0 + 0.005, BOARD_Z / 2), (bx, 0.005, BOARD_Z / 2), shelf)
106
+ # the round disc is visual only; its collision surface is the inscribed square plate: a box on a cylinder gets a
107
+ # single contact point and no torsional friction, and the butter span on the disc at ~4 deg/s even at rest (measured)
108
+ disc = geoms("cylinder", (0, 0, 0), (R, DISC_T / 2), (0.62, 0.42, 0.24, 1.0), coll=False)
109
+ disc += geoms("box", (0, 0, 0), (R / np.sqrt(2), R / np.sqrt(2), DISC_T / 2), (0.62, 0.42, 0.24, 1.0), vis=False)
110
+ for a in PEG_ANG:
111
+ disc += geoms("cylinder", (PEG_RAD * np.cos(a), PEG_RAD * np.sin(a), DISC_T / 2 + PEG_H / 2),
112
+ (PEG_R, PEG_H / 2), (0.75, 0.08, 0.08, 1.0))
113
+ # painted marks (visual only) that make the disc's angle readable: yellow stripe, blue square, green dot
114
+ disc += geoms("box", (0.085 * np.cos(STRIPE_ANG), 0.085 * np.sin(STRIPE_ANG), DISC_T / 2 + 0.0006),
115
+ (0.055, 0.007, 0.0006), (0.95, 0.85, 0.10, 1.0), coll=False)
116
+ disc += geoms("box", (0.10 * np.cos(np.pi / 2), 0.10 * np.sin(np.pi / 2), DISC_T / 2 + 0.0006),
117
+ (0.016, 0.016, 0.0006), (0.15, 0.35, 0.85, 1.0), coll=False)
118
+ disc += geoms("cylinder", (0.10 * np.cos(-np.pi / 2), 0.10 * np.sin(-np.pi / 2), DISC_T / 2 + 0.0006),
119
+ (0.016, 0.0006), (0.15, 0.65, 0.25, 1.0), coll=False)
120
+ nl = "\n "
121
+ return f"""<mujoco model="{model_name}">
122
+ <worldbody>
123
+ <body>
124
+ <body name="object">
125
+ {nl.join(fixed)}
126
+ <body name="disc" pos="0 0 {BASE_H + DISC_T / 2:.5f}">
127
+ <joint name="spin" type="hinge" axis="0 0 1" pos="0 0 0" limited="false" damping="{HINGE['damping']}" armature="{HINGE['armature']}" frictionloss="{HINGE['frictionloss']}" />
128
+ {nl.join(disc)}
129
+ </body>
130
+ </body>
131
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
132
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {BOARD_Z + 0.008:.5f}" name="top_site" />
133
+ <site rgba="0 0 0 0" size="0.005" pos="{R:.5f} {R:.5f} 0" name="horizontal_radius_site" />
134
+ </body>
135
+ </worldbody>
136
+ </mujoco>
137
+ """
138
+
139
+
140
+ @register_task
141
+ class TurntableRestore(LFFTask):
142
+ name = "l2_turntable_restore"
143
+ level = "L2"
144
+ category = "state_restoration"
145
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
146
+ protocol = "within"
147
+ max_attempts = 5
148
+ instruction = ("Put the butter into the basket. The butter is on the turntable, under the shelf. You can turn the "
149
+ "turntable by its red pegs. When you are done, the turntable must be turned exactly the way it is now.")
150
+ instruction_indirect = ("Put the small orange box into the wicker basket. It is on the round turntable, under the "
151
+ "shelf. You can turn the turntable by its red pegs. When you are done, the turntable must be "
152
+ "turned exactly the way it is now.")
153
+
154
+ def __init__(self, cam_res=None):
155
+ super().__init__(cam_res)
156
+ m = self.env.sim.model
157
+ self._tt_bid = m.body_name2id(self.env.fixtures_dict[TT].root_body)
158
+ jid = m.joint_name2id(f"{TT}_spin")
159
+ self._qa, self._qv = m.jnt_qposadr[jid], m.jnt_dofadr[jid]
160
+ self.start = {}
161
+ self.turn_log = [] # per peg grasp: commanded sweep vs measured disc rotation (diagnostics)
162
+ self._home = None
163
+ self._c = np.zeros(2)
164
+
165
+ # ------------------------------------------------------------ scene
166
+ def make_bddl(self):
167
+ tt = register_generated("LffTurntableShelf", turntable_xml("lff_turntable_shelf"), free=False)
168
+ objs = [(n, n[:-2], f"r_{i}", (0.20, -0.25 + 0.15 * i, 0.22, -0.23 + 0.15 * i)) for i, n in enumerate(ITEMS)]
169
+ objs.append((BASKET, "basket", "r_basket", (-0.10, 0.24, -0.08, 0.26)))
170
+ fx = [(TT, tt, "tt_region", (0.25, 0.30, 0.27, 0.32))] # moved in apply_instance
171
+ return write_bddl(self.name, self.instruction.replace(";", ","), objs, fixtures=fx)
172
+
173
+ def sample_instance(self, seed):
174
+ rng = np.random.default_rng(seed)
175
+ c = np.array([rng.uniform(-0.08, -0.02), rng.uniform(-0.12, -0.08)])
176
+ th = {TARGET: float(rng.uniform(-0.14, 0.14))} # disc-frame angle of the butter (stripe at 180 deg)
177
+ rad = {n: float(ITEM_R + rng.uniform(-0.005, 0.005)) for n in ITEMS}
178
+ tilt = {n: float(rng.uniform(-0.17, 0.17)) for n in ITEMS} # box yaw relative to radial
179
+ # start angle: the butter sits under the board (world azimuth -90 +- 40 deg about the axis)
180
+ q0 = float(_wrap(-np.pi / 2 - th[TARGET] + rng.uniform(-np.radians(40), np.radians(40))))
181
+ return dict(seed=int(seed), center=c.round(4).tolist(), q0=q0, theta=th, rad=rad, tilt=tilt,
182
+ basket_xy=[float(rng.uniform(-0.12, -0.06)), float(rng.uniform(0.25, 0.28))])
183
+
184
+ def disc_angle(self):
185
+ return float(self.env.sim.data.qpos[self._qa])
186
+
187
+ def to_world(self, r, th, q=None):
188
+ q = self.disc_angle() if q is None else q
189
+ return self._c + r * np.array([np.cos(th + q), np.sin(th + q)])
190
+
191
+ def to_disc(self, xy, q=None):
192
+ q = self.disc_angle() if q is None else q
193
+ return _rot(-q) @ (np.asarray(xy, float)[:2] - self._c)
194
+
195
+ def place(self, name, xy, yaw, surface_z):
196
+ """Teleport a box flat (its mesh frame is flat) with yaw about world z, lowest point 2 mm above surface_z."""
197
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3],
198
+ quat_wxyz=np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]))
199
+ self.env.sim.forward()
200
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
201
+ qa, _ = envs.free_joint_addr(self.env, name)
202
+ self.env.sim.data.qpos[qa + 2] -= dz
203
+ self.env.sim.forward()
204
+
205
+ def apply_instance(self, inst):
206
+ m, d = self.env.sim.model, self.env.sim.data
207
+ self._c = np.array(inst["center"], float)
208
+ m.body_pos[self._tt_bid] = [self._c[0], self._c[1], envs.TABLE_Z]
209
+ m.body_quat[self._tt_bid] = [1, 0, 0, 0]
210
+ d.qpos[self._qa] = inst["q0"]
211
+ d.qvel[self._qv] = 0.0
212
+ self.env.sim.forward()
213
+ for n in ITEMS:
214
+ envs.scale_mass(self.env, n, MASS[n])
215
+ th = inst["theta"][n]
216
+ # long axis radial (+ tilt): the gripper then closes tangentially and keeps clear of the board
217
+ self.place(n, self.to_world(inst["rad"][n], th, inst["q0"]), th + inst["q0"] + inst["tilt"][n],
218
+ envs.TABLE_Z + DISC_TOP)
219
+ envs.scale_mass(self.env, BASKET, 2.0)
220
+ self.place(BASKET, inst["basket_xy"], 0.0, envs.TABLE_Z)
221
+ self.env.sim.forward()
222
+
223
+ def reset_instance(self, inst, recorder=None):
224
+ sk = super().reset_instance(inst, recorder)
225
+ self.start = dict(q=self.disc_angle())
226
+ self._home = sk.eef_pos()
227
+ return sk
228
+
229
+ # ------------------------------------------------------------ measurements
230
+ def footprint(self, name):
231
+ """AABB centre, yaw of the long horizontal axis, z range (scripted 'perception')."""
232
+ m, d = self.env.sim.model, self.env.sim.data
233
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
234
+ best = None
235
+ for g in envs.obj_geom_ids(self.env, name):
236
+ Rg = d.geom_xmat[g].reshape(3, 3)
237
+ c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
238
+ e = np.abs(Rg) @ m.geom_aabb[g, 3:]
239
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
240
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
241
+ if best is None or vol > best[0]:
242
+ best = (vol, Rg, m.geom_aabb[g, 3:])
243
+ _, Rg, half = best
244
+ horiz = sorted([(half[k], Rg[:, k]) for k in range(3) if abs(Rg[2, k]) < 0.5], key=lambda t: -t[0])
245
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
246
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
247
+ zmin=float(lo[2]), zmax=float(hi[2]))
248
+
249
+ def item_loc(self, name):
250
+ f = self.footprint(name)
251
+ c = np.array(f["center"])
252
+ held = self.sk is not None and self.sk.holding(name)
253
+ if held and f["zmin"] > envs.TABLE_Z + DISC_TOP + 0.01:
254
+ return "gripper", f
255
+ bp = envs.obj_pos(self.env, BASKET)
256
+ if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM \
257
+ and f["zmin"] > envs.TABLE_Z + 0.005:
258
+ return "basket", f
259
+ on_disc = np.linalg.norm(c[:2] - self._c) < R and abs(f["zmin"] - (envs.TABLE_Z + DISC_TOP)) < 0.012
260
+ if on_disc:
261
+ return "turntable", f
262
+ if f["zmin"] < envs.TABLE_Z + 0.01:
263
+ return "table", f
264
+ return "other", f
265
+
266
+ def outcome(self, inst):
267
+ envs.settle(self.env, 30)
268
+ tloc, _ = self.item_loc(TARGET)
269
+ dq = _wrap(self.disc_angle() - self.start["q"])
270
+ turned_ok = abs(dq) <= ANG_TOL
271
+ success = bool(tloc == "basket" and turned_ok)
272
+ return dict(success=success, target_loc=tloc, angle_err_deg=round(float(np.degrees(dq)), 1),
273
+ turned_ok=bool(turned_ok),
274
+ detail=self._describe(tloc, turned_ok, dq, NAMES),
275
+ detail_indirect=self._describe(tloc, turned_ok, dq, DESCR),
276
+ detail_offset=self._describe(tloc, turned_ok, dq, NAMES, offset=True))
277
+
278
+ @staticmethod
279
+ def _describe(tloc, turned_ok, dq, names, offset=False):
280
+ tn = names[TARGET]
281
+ msgs = []
282
+ if tloc != "basket":
283
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
284
+ "turntable": f"The {tn} is still on the turntable, not in the basket.",
285
+ "table": f"The {tn} is on the table, not in the basket."}
286
+ .get(tloc, f"The {tn} is not in the basket."))
287
+ if not turned_ok:
288
+ m = "The turntable is not turned the way it was at the start."
289
+ if offset: # ablation tier: relative measurement, externalises the memory
290
+ m += (f" It is turned {abs(np.degrees(dq)):.0f} deg "
291
+ f"{'counter-clockwise' if dq > 0 else 'clockwise'} (seen from above) from its starting angle.")
292
+ msgs.append(m)
293
+ if not msgs:
294
+ msgs.append(f"The {tn} is in the basket and the turntable is turned the way it was at the start.")
295
+ return " ".join(msgs)
296
+
297
+ def feedback(self, inst, out, level="F2", indirect=False, offset=False):
298
+ """F0: nothing, F1: success flag, F2: what is wrong (never by how much the turntable is off).
299
+ offset=True (ablation tier 'F2+offset'): also the relative turn from the start angle."""
300
+ if level == "F2":
301
+ key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
302
+ out = dict(out, detail=out.get(key, out["detail"]))
303
+ return super().feedback(inst, out, level)
304
+
305
+ # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper)
306
+ SAFE_Z = envs.TABLE_Z + 0.22 # travel height between pegs / items
307
+ PICK_AZ = np.pi / 2 # where the butter is brought: middle of the open side (at 135 deg the open finger lands on
308
+ # the board edge -- measured); grasp yaw ~ +-90 deg, so the wrist is turned back to 0 while
309
+ # carrying (arriving at the basket with yaw -103 deg left the arm stalled near a joint limit)
310
+ WIN = (np.radians(30), np.radians(150)) # world azimuths where a peg can be held (open side, clear of the board)
311
+
312
+ def go_home(self):
313
+ sk = self.sk
314
+ p = sk.eef_pos()
315
+ sk.move_to([p[0], p[1], max(p[2], self._home[2])])
316
+ sk.move_to(self._home, yaw=0.0)
317
+
318
+ def _settle_yaw(self, tol=np.radians(3), max_steps=40):
319
+ """move_to stops on position only; after a large wrist rotation hold until the yaw has converged (a descent
320
+ that starts mid-rotation swipes the open fingers across the pegs -- measured)."""
321
+ sk = self.sk
322
+ for _ in range(max_steps // 5):
323
+ R = sk.eef_mat() @ sk.R0.T
324
+ if abs(_wrap(np.arctan2(R[1, 0], R[0, 0]) - sk.yaw)) < tol:
325
+ return
326
+ sk.hold(5)
327
+
328
+ def peg_azimuths(self):
329
+ return [_wrap(self.disc_angle() + a) for a in PEG_ANG]
330
+
331
+ def turn(self, delta, step=np.radians(10)):
332
+ """Turn the disc by `delta` rad (+ = counter-clockwise seen from above): grasp a peg on the open side,
333
+ move the gripper along the rim in short straight segments, release, repeat."""
334
+ sk = self.sk
335
+ zg = envs.TABLE_Z + DISC_TOP + PEG_H - 0.012
336
+ rem = float(delta)
337
+ for _ in range(6):
338
+ if abs(rem) < np.radians(1.0):
339
+ break
340
+ az = self.peg_azimuths()
341
+ if rem > 0:
342
+ cands = [a for a in az if self.WIN[0] - 1e-6 <= a <= self.WIN[1] - np.radians(10)]
343
+ a0 = min(cands)
344
+ sweep = min(rem, self.WIN[1] - a0)
345
+ else:
346
+ cands = [a for a in az if self.WIN[0] + np.radians(10) <= a <= self.WIN[1] + 1e-6]
347
+ a0 = max(cands)
348
+ sweep = max(rem, self.WIN[0] - a0)
349
+ q_before = self.disc_angle()
350
+ p = self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)])
351
+ sk.set_gripper(False, steps=6)
352
+ # up, across, straight down: a long diagonal move at full speed sags ~5 cm below its line and the open
353
+ # fingers sweep the disc (measured: turned it 38 deg the wrong way)
354
+ cur = sk.eef_pos()
355
+ if cur[2] < self.SAFE_Z - 0.02:
356
+ sk.move_to([cur[0], cur[1], self.SAFE_Z])
357
+ sk.move_to([p[0], p[1], self.SAFE_Z], yaw=np.pi / 2) # fingers close along world x
358
+ self._settle_yaw()
359
+ sk.move_to([p[0], p[1], zg + 0.03], speed=0.4)
360
+ sk.move_to([p[0], p[1], zg], tol=0.003, max_steps=80)
361
+ sk.set_gripper(True, steps=12)
362
+ dbg = dict(off=np.round((sk.eef_pos() - np.r_[self._c + PEG_RAD * np.array([np.cos(a0), np.sin(a0)]), zg]) * 100, 1).tolist(),
363
+ w=round(sk.gripper_width() * 100, 1), q_close=round(float(np.degrees(_wrap(self.disc_angle() - q_before))), 1),
364
+ yaw=round(float(np.degrees(sk.yaw)), 0))
365
+ k = max(1, int(np.ceil(abs(sweep) / step)))
366
+ for i in range(1, k + 1):
367
+ w = self._c + PEG_RAD * np.array([np.cos(a0 + sweep * i / k), np.sin(a0 + sweep * i / k)])
368
+ sk.move_to([w[0], w[1], zg], tol=0.003, max_steps=40)
369
+ sk.set_gripper(False, steps=8)
370
+ pe = sk.eef_pos()
371
+ sk.move_to([pe[0], pe[1], zg + 0.10])
372
+ got = _wrap(self.disc_angle() - q_before)
373
+ self.turn_log.append(dict(peg_az=round(float(np.degrees(a0)), 1), sweep=round(float(np.degrees(sweep)), 1),
374
+ got=round(float(np.degrees(got)), 1), **dbg))
375
+ rem -= got
376
+
377
+ def pick_place(self, name, dest_xy, support_z, fp=None, carry_z=1.20, travel_z=1.15, carry_yaw=0.0):
378
+ """Top-down pick across the short side, carry, release just above support_z at dest_xy."""
379
+ sk = self.sk
380
+ f = fp or self.footprint(name)
381
+ c = np.array(f["center"])
382
+ gyaw = _wrap_half(f["yaw"])
383
+ zg = max(f["zmin"] + 0.5 * (f["zmax"] - f["zmin"]), f["zmin"] + 0.0145)
384
+ sk.set_gripper(False, steps=6)
385
+ p = sk.eef_pos()
386
+ if p[2] < travel_z - 0.02:
387
+ sk.move_to([p[0], p[1], travel_z])
388
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
389
+ self._settle_yaw()
390
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
391
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
392
+ sk.set_gripper(True, steps=12)
393
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
394
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=carry_yaw)
395
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + 0.006], tol=0.003, speed=0.2, max_steps=150)
396
+ sk.hold(4)
397
+ sk.set_gripper(False, steps=10)
398
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
399
+
400
+ def butter_to_basket(self, fp=None):
401
+ """The main task: if the butter is on the turntable, turn it to the open side first."""
402
+ loc, f = self.item_loc(TARGET)
403
+ if loc == "turntable":
404
+ az = np.arctan2(f["center"][1] - self._c[1], f["center"][0] - self._c[0])
405
+ # bring the butter's long axis parallel to world y (then the hand lies along x, away from the board edge;
406
+ # a hand turned 26 deg off caught the board -- measured); its centre ends within ~30 deg of PICK_AZ
407
+ delta = _wrap_half(f["yaw"] - az)
408
+ self.turn(_wrap(self.PICK_AZ - delta - az))
409
+ b = envs.obj_pos(self.env, BASKET)
410
+ # release with the hand above the rim and let the box drop in: lowering it to the floor puts the 20 cm long
411
+ # hand below the rim of the 12 cm basket and the contact flips the wrist (joint 5 at its limit -- measured)
412
+ self.pick_place(TARGET, b[:2], envs.obj_min_z(self.env, BASKET) + BASKET_RIM + 0.02, fp=fp)
413
+
414
+ def do(self, actions):
415
+ for act in actions:
416
+ if act[0] == "butter_to_basket":
417
+ self.butter_to_basket(fp=act[1] if len(act) > 1 else None)
418
+ elif act[0] == "turn_to": # ["turn_to", absolute disc angle (the agent's remembered start angle)]
419
+ self.turn(_wrap(act[1] - self.disc_angle()))
420
+ elif act[0] == "turn_by":
421
+ self.turn(act[1])
422
+ else:
423
+ raise ValueError(act)
424
+
425
+ # ------------------------------------------------------------ scripted reference policies
426
+ def _plan(self, kind, inst, a, history, rng, memory):
427
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
428
+ return [["butter_to_basket"]]
429
+ if kind == "oracle":
430
+ return [["butter_to_basket"], ["turn_to", memory["q"]]]
431
+ last = history[-1]["outcome"]
432
+ acts = [] if last["target_loc"] == "basket" else [["butter_to_basket"]]
433
+ if kind == "adaptive":
434
+ return acts + ([] if last["turned_ok"] else [["turn_to", memory["q"]]])
435
+ if kind == "nomem":
436
+ return acts + ([] if last["turned_ok"] else [["turn_by", float(rng.uniform(-np.pi, np.pi))]])
437
+ if kind == "blind":
438
+ fp = self.footprint(TARGET)
439
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
440
+ return [["butter_to_basket", fp]]
441
+ raise ValueError(kind)
442
+
443
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
444
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
445
+ k = k or self.max_attempts
446
+ rng = np.random.default_rng(seed)
447
+ history = []
448
+ self.reset_instance(inst)
449
+ memory = dict(q=self.disc_angle()) # Save: the start angle (an agent reads it off the first frame)
450
+ for a in range(k):
451
+ actions = self._plan(kind, inst, a, history, rng, memory)
452
+ self.do(actions)
453
+ self.go_home()
454
+ out = self.outcome(inst)
455
+ params = dict(actions=[[x[0]] + ([round(float(np.degrees(x[1])), 1)] if x[0] != "butter_to_basket" else [])
456
+ for x in actions])
457
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
458
+ if on_attempt:
459
+ on_attempt(a, params, out)
460
+ if out["success"] or kind in ("oracle", "naive"):
461
+ break
462
+ return history
463
+
464
+ # cross-protocol hooks are not used by this task
465
+ def default_params(self, inst):
466
+ return dict(policy="naive")
467
+
468
+ def oracle_params(self, inst):
469
+ return dict(policy="oracle")
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/gptpolicy_player.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Drive one robot_server session with the GPT-Policy harness (frameworks/gpt-policy, simulated
3
+ # lffbench_sim adapter + OpenAI Responses provider, GPT-6 Astra, reasoning effort medium).
4
+ #
5
+ # usage: scripts/gptpolicy_player.sh <LOG>/session.json [extra gpt-policy-lffbench options]
6
+ # e.g. LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10340 direct 3 gptpolicy rgb 1
7
+ # scripts/gptpolicy_player.sh runs/claude/gptpolicy_l1_bias_place_s3000_..._p10340/session.json
8
+ # The robot_server interface (v1 / v2) is detected from the first status reply.
9
+ #
10
+ # Writes into the session's LOG directory: gptpolicy_transcript.jsonl (every model request/response,
11
+ # images as file paths + sha256, every robot-server call), final_report.md, gptpolicy_player.log and
12
+ # GPT-Policy's own recording gptpolicy_run_*/. The robot server writes events.jsonl and rollout.mp4.
13
+ # The server is stopped at the end (it has finished the episode, and rollout.mp4 is closed by then).
14
+ set -uo pipefail
15
+ [ $# -ge 1 ] || { echo "usage: $0 <LOG>/session.json [options]"; exit 2; }
16
+ SESSION=$(readlink -f "$1"); shift
17
+ LOG=$(dirname "$SESSION")
18
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
19
+ [ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh"
20
+ # GPT-Policy checkout + venv from integrations/gpt-policy/setup.sh (override: GPTPOLICY_VENV)
21
+ VENV=${GPTPOLICY_VENV:-$ROOT/third_party/gpt-policy/.venv}
22
+ ENVF=${LFF_ENV_FILE:-$ROOT/.env}
23
+ [ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } # OPENAI_API_KEY / OPENAI_BASE_URL / SSL_CERT_FILE (never echoed)
24
+ export PYTHONUNBUFFERED=1
25
+ stop_server() { # also on abnormal exit; SIGTERM makes the server close rollout.mp4 first
26
+ if [ "${GPTPOLICY_KEEP_SERVER:-0}" != "1" ] && [ -f "$LOG/server.pid" ]; then
27
+ kill "$(cat "$LOG/server.pid")" 2>/dev/null || true
28
+ fi
29
+ }
30
+ trap stop_server EXIT
31
+ trap 'exit 143' TERM INT HUP
32
+ cd /tmp # neutral working directory; the model has no file access anyway
33
+ "$VENV/bin/gpt-policy-lffbench" --session "$SESSION" --model "${GPTPOLICY_MODEL:-gpt-6-astra}" \
34
+ --effort "${GPTPOLICY_EFFORT:-medium}" "$@" 2>&1 | tee -a "$LOG/gptpolicy_player.log"
35
+ RC=${PIPESTATUS[0]}
36
+ echo "gptpolicy_player.sh: gpt-policy-lffbench exit code $RC" >> "$LOG/gptpolicy_player.log"
37
+ exit $RC
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/ladder_plan.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-3 feedback ladder (user 2026-10-27; design docs/20). Same instances and records as the mismatched-history
2
+ control (scripts/mismatch_plan.py): the main-table attempt 1 of every Claude instance in the 9 twin tasks whose
3
+ attempt 1 failed. Fresh single-attempt agents (Claude Code B', jail, high, F1), README byte-identical to the Do arm;
4
+ only the Result section of history/README.md grows, one rung at a time:
5
+
6
+ F1 "The environment judged that attempt: failed." = the Do arm (do_<m>), not re-run
7
+ F2 + the measured error of that attempt (outcome.detail, axis labels stripped) batch lf2_<m>
8
+ hplus + "Cause: " the hidden variable (arm_specs reveal, as --arm hplus states it) batch lhp_<m>
9
+ fix + how to succeed (arm_specs fix, from the oracle parameters; results/_ladder/fix_validate.json) lfx_<m>
10
+
11
+ python scripts/ladder_plan.py build records -> runs/api/ladder_20261027/<m>/<rung>.json (+ tasks_<m>.txt)
12
+ python scripts/ladder_plan.py report per instance F1 / F2 / H+ / Fix, totals, adjacent paired counts
13
+ -> runs/api/ladder_20261027/report.json + markdown on stdout
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+ API = os.path.join(ROOT, "runs", "api")
23
+ SRC = os.path.join(API, "mismatch_20261027")
24
+ OUT = os.path.join(API, "ladder_20261027")
25
+ FIXV = os.path.join(ROOT, "results", "_ladder", "fix_validate.json")
26
+ MODELS = ("opus", "sonnet")
27
+ RUNGS = ("F2", "hplus", "fix")
28
+ BATCH = {"F1": "do", "F2": "lf2", "hplus": "lhp", "fix": "lfx"}
29
+ WITHIN = {"l2_turntable_restore"} # reported separately (docs/20 §2)
30
+
31
+
32
+ def events(log):
33
+ return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip()]
34
+
35
+
36
+ def texts(src, fixes):
37
+ """rung -> result_extra for one record source (the logged attempt 1)"""
38
+ from lffbench import arm_specs
39
+ from lffbench.agent.robot_server import strip_axes
40
+ ev = events(src["log"])
41
+ start = next(e for e in ev if e["ev"] == "session_start")
42
+ done = next(e for e in ev if e["ev"] == "done" and e.get("attempt") == 1)
43
+ detail = strip_axes((done.get("outcome") or {}).get("detail") or "").strip()
44
+ if not detail:
45
+ raise SystemExit(f"{src['task']}:{src['seed']}: attempt 1 has no outcome detail for F2")
46
+ cause = "Cause: " + strip_axes(arm_specs.reveal(start["task"], start["inst"]).strip())
47
+ fx = fixes.get(f"{start['task']}:{start['seed']}")
48
+ if fx is None or not fx["ok"]:
49
+ raise SystemExit(f"{start['task']}:{start['seed']}: no validated fix text in {FIXV}")
50
+ return {"F2": detail, "hplus": detail + "\n\n" + cause, "fix": detail + "\n\n" + cause + "\n\n" + fx["fix"]}
51
+
52
+
53
+ def cmd_build():
54
+ fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
55
+ for m in MODELS:
56
+ own = json.load(open(os.path.join(SRC, m, "own.json")))
57
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
58
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(own) + "\n")
59
+ out = {r: {} for r in RUNGS}
60
+ for key, d in own.items():
61
+ src = json.load(open(d + ".source.json"))
62
+ tx = texts(src, fixes)
63
+ for r in RUNGS:
64
+ dst = os.path.join(OUT, m, r, f"{src['task']}_s{src['seed']}")
65
+ if not os.path.isdir(dst):
66
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), src["log"],
67
+ dst, "--result-extra", tx[r]], check=True, capture_output=True)
68
+ out[r][key] = dst
69
+ for r in RUNGS:
70
+ json.dump(out[r], open(os.path.join(OUT, m, f"{r}.json"), "w"), indent=1)
71
+ print(m, len(own), "instances x", len(RUNGS), "rungs")
72
+
73
+
74
+ def single(batch):
75
+ """task:seed -> True / False (attempt 1 of the batch's done run)"""
76
+ out = {}
77
+ p = os.path.join(API, batch, "manifest.json")
78
+ if not os.path.exists(p):
79
+ return out
80
+ for r in json.load(open(p))["runs"]:
81
+ if r["status"] != "done":
82
+ continue
83
+ d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
84
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
85
+ return out
86
+
87
+
88
+ def cmd_report():
89
+ rep, md = {}, []
90
+ order = ("F1", "F2", "hplus", "fix")
91
+ f = lambda v: "-" if v is None else ("S" if v else "F")
92
+ for m in MODELS:
93
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
94
+ res = {r: single(f"{BATCH[r]}_{m}") for r in order}
95
+ rows = [dict(inst=k, within=k.split(":")[0] in WITHIN, **{r: res[r].get(k) for r in order}) for k in want]
96
+ tot = {}
97
+ for part, sub in (("all", rows), ("cross", [r for r in rows if not r["within"]]),
98
+ ("within", [r for r in rows if r["within"]])):
99
+ tot[part] = {r: [sum(x[r] for x in sub if x[r] is not None), sum(x[r] is not None for x in sub)] for r in order}
100
+ steps = {}
101
+ cross = [r for r in rows if not r["within"]]
102
+ for lo, hi in zip(order, order[1:]):
103
+ both = [r for r in cross if r[lo] is not None and r[hi] is not None]
104
+ steps[f"{lo}->{hi}"] = dict(n=len(both), up=sum(r[hi] and not r[lo] for r in both),
105
+ down=sum(r[lo] and not r[hi] for r in both))
106
+ rep[m] = dict(rows=rows, totals=tot, steps=steps)
107
+ md += [f"### {m}", "", "| instance | F1 | F2 | H+ | Fix |", "|---|---|---|---|---|"]
108
+ md += [f"| {r['inst']}{' (within)' if r['within'] else ''} | " + " | ".join(f(r[x]) for x in order) + " |"
109
+ for r in rows]
110
+ for part in ("cross", "within"):
111
+ md.append(f"{part}: " + ", ".join(f"{x} {tot[part][x][0]}/{tot[part][x][1]}" for x in order))
112
+ md.append("adjacent (cross, paired): " + "; ".join(f"{k} n={v['n']} up {v['up']} down {v['down']}"
113
+ for k, v in steps.items()))
114
+ md.append("")
115
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
116
+ print("\n".join(md))
117
+
118
+
119
+ if __name__ == "__main__":
120
+ {"build": cmd_build, "report": cmd_report}[sys.argv[1]]()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/layer4_plan.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-4 minimal intervention (user 2026-10-30: 先用 opus; design reports/layer4_intervention_20261030/PLAN.md). Opus only, on the
2
+ two tasks whose every main-table instance failed all three attempts. Same protocol as the layer-3 ladder (a fresh
3
+ single-attempt agent, the instance's own failed attempt 1 in history/, F1), only the Result section differs:
4
+
5
+ f1 "The environment judged that attempt: failed."
6
+ v + a generic reminder to check the goal before ending; no cause
7
+ hp + "Cause: " the hidden variable (arm_specs reveal)
8
+ fx + cause + how to succeed (arm_specs fix, validated below)
9
+
10
+ python scripts/layer4_plan.py validate texts + oracle + LA push, debug and test seeds -> results/_layer4/fix_validate.json
11
+ python scripts/layer4_plan.py build debug records -> runs/api/layer4i_20261030/debug/<cond>.json + tasks.txt
12
+ python scripts/layer4_plan.py build test the same from the failed attempts of batch l4i_first (test seeds)
13
+ python scripts/layer4_plan.py report debug|test per instance per condition: outcome, process events, closing claim
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+ API = os.path.join(ROOT, "runs", "api")
23
+ OUT = os.path.join(API, "layer4i_20261030")
24
+ FIXV = os.path.join(ROOT, "results", "_layer4", "fix_validate.json")
25
+ CONDS = ("f1", "v", "hp", "fx")
26
+ DEBUG = {"lh_clear_cover": {3000: "cc_opus1", 3001: "cc_opus_s2", 3003: "cc_opus_s3"},
27
+ "lh_tidy_stack": {3000: "cc_opus1", 3002: "cc_opus_s2", 3003: "cc_opus_s3"}}
28
+ # frozen before any test-seed run: first four seeds from 3100 with the trap active (clear_cover: covered, (seed * 7) % 20 < 10;
29
+ # tidy_stack: a soft box that is not on top of a nearest-first pile, (seed * 7) % 20 < 18 and % 4 != 3)
30
+ TEST = {"lh_clear_cover": [3100, 3101, 3103, 3104], "lh_tidy_stack": [3100, 3102, 3103, 3104]}
31
+ REMINDER = ("Before you end an attempt, use your observations to check whether every part of the goal is actually met; "
32
+ "if it is not, keep working.")
33
+
34
+
35
+ def events(log):
36
+ return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip() and "\0" not in line]
37
+
38
+
39
+ def batch_log(batch, task, seed):
40
+ runs = json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
41
+ return next(r["log"] for r in runs if r["task"] == task and r["seed"] == seed and r.get("status") == "done"
42
+ and r.get("cond") == "harness")
43
+
44
+
45
+ def la_push(task, inst):
46
+ """the Fix text's lid push as LA commands; returns (z_push, sweep length, lid off?)"""
47
+ import numpy as np
48
+ from lffbench.agent.tools import ToolExecutor
49
+ from lffbench.tasks import lh_clear_cover as cc
50
+ from scripts.validate_ladder_fix import la_move
51
+ task.reset_instance(inst)
52
+ sim = task.env.sim
53
+ off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy()
54
+ ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",))
55
+ cov = task.covering()
56
+ lp = task.lid_pos()
57
+ b = np.asarray(inst["boxes"][cov], float)
58
+ o = np.asarray(inst["boxes"][[c for c in cc.COLORS if c != cov][0]], float)
59
+ d = np.array((0.0, float(np.sign(b[1] - o[1]))))
60
+ back = cc.LID_HALF + 0.03
61
+ s = lp[:2] - d * back
62
+ z = lp[2] + cc.LID_T / 2 - cc.PUSH_DEPTH + cc.TIP
63
+ need = float((b - lp[:2]) @ d) + cc.BOX_OUT + back + 0.03
64
+ e = s + d * need
65
+ sb, eb, zb = s - off[:2], e - off[:2], z - off[2]
66
+ la_move(task, ex, off, gripper="close")
67
+ la_move(task, ex, off, x=sb[0], y=sb[1], z=zb + 0.08, yaw=0)
68
+ la_move(task, ex, off, x=sb[0], y=sb[1], z=zb)
69
+ la_move(task, ex, off, x=eb[0], y=eb[1], z=zb, speed=cc.PUSH_SPEED)
70
+ la_move(task, ex, off, z=zb + 0.10, speed=0.2)
71
+ return float(zb), float(need), task.covering() is None
72
+
73
+
74
+ def cmd_validate():
75
+ import importlib
76
+ import pkgutil
77
+ from lffbench import arm_specs
78
+ from lffbench import tasks as task_pkg
79
+ from lffbench.agent.robot_server import strip_axes
80
+ from lffbench.task_base import TASKS
81
+ for m in pkgutil.iter_modules(task_pkg.__path__):
82
+ importlib.import_module(f"lffbench.tasks.{m.name}")
83
+ rows = []
84
+ for name, seeds in ((t, sorted(DEBUG[t]) + TEST[t]) for t in DEBUG):
85
+ task = TASKS[name](cam_res=64)
86
+ for seed in seeds:
87
+ inst = task.sample_instance(seed)
88
+ clean = {k: v for k, v in inst.items() if not k.startswith("_")}
89
+ params = dict(task.oracle_params(inst))
90
+ row = dict(key=f"{name}:{seed}", hidden=clean.get("cover") or clean.get("soft_colour"))
91
+ row["oracle_success"] = bool(task.run_scripted("oracle", inst, k=1)[0]["outcome"]["success"])
92
+ row["naive_success"] = bool(task.run_scripted("naive", inst, k=1)[0]["outcome"]["success"])
93
+ if name == "lh_clear_cover":
94
+ params["z_push"], params["push_len"], row["la_lid_off"] = la_push(task, inst)
95
+ task.execute(inst, dict(plan="naive", check="side")) # the placing part, after the LA push
96
+ row["la_then_place_success"] = bool(task.outcome(inst)["success"])
97
+ cause, fx = arm_specs.reveal(name, clean), arm_specs.fix(name, clean, params)
98
+ row.update(cause=cause, fix=fx, no_axis_labels=strip_axes(cause + fx) == cause + fx)
99
+ row["ok"] = bool(row["oracle_success"] and not row["naive_success"] and row["hidden"] and row["no_axis_labels"]
100
+ and row.get("la_lid_off", True) and row.get("la_then_place_success", True))
101
+ rows.append(row)
102
+ print("OK " if row["ok"] else "BAD", json.dumps({k: v for k, v in row.items() if k not in ("cause", "fix")}), flush=True)
103
+ os.makedirs(os.path.dirname(FIXV), exist_ok=True)
104
+ json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(FIXV, "w"), indent=1)
105
+ print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {FIXV}")
106
+
107
+
108
+ def sources(stage):
109
+ if stage == "debug":
110
+ return [(t, s, batch_log(b, t, s)) for t, d in DEBUG.items() for s, b in sorted(d.items())]
111
+ out = []
112
+ for r in json.load(open(os.path.join(API, "l4i_first", "manifest.json")))["runs"]:
113
+ if r["status"] == "done":
114
+ d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
115
+ if d is not None and not d["success"]:
116
+ out.append((r["task"], r["seed"], r["log"]))
117
+ return out
118
+
119
+
120
+ def cmd_build(stage):
121
+ fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
122
+ base = os.path.join(OUT, stage)
123
+ os.makedirs(base, exist_ok=True)
124
+ maps, tasks = {c: {} for c in CONDS}, []
125
+ for task, seed, log in sources(stage):
126
+ key = f"{task}:{seed}"
127
+ if not fixes[key]["ok"]:
128
+ raise SystemExit(f"{key}: fix text not validated")
129
+ tasks.append(key)
130
+ cause = "Cause: " + fixes[key]["cause"]
131
+ extra = dict(f1="", v=REMINDER, hp=cause, fx=cause + "\n\n" + fixes[key]["fix"])
132
+ for c in CONDS:
133
+ dst = os.path.join(base, c, f"{task}_s{seed}")
134
+ if not os.path.isdir(dst):
135
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst,
136
+ "--result-extra", extra[c]], check=True, capture_output=True)
137
+ maps[c][key] = dst
138
+ for c in CONDS:
139
+ json.dump(maps[c], open(os.path.join(base, f"{c}.json"), "w"), indent=1)
140
+ open(os.path.join(base, "tasks.txt"), "w").write("\n".join(tasks) + "\n")
141
+ print(stage, len(tasks), "instances x", len(CONDS), "conditions")
142
+
143
+
144
+ def cmd_report(stage):
145
+ rows = {}
146
+ for c in CONDS:
147
+ p = os.path.join(API, f"l4i_{c}_{stage}", "manifest.json")
148
+ if not os.path.exists(p):
149
+ continue
150
+ for r in json.load(open(p))["runs"]:
151
+ key = f"{r['task']}:{r['seed']}"
152
+ cell = dict(status=r["status"])
153
+ if r["status"] == "done":
154
+ ev = events(r["log"])
155
+ d = next((e for e in ev if e["ev"] == "done"), {})
156
+ o = d.get("outcome") or {}
157
+ cell.update(success=bool(d.get("success")), calls=d.get("step"), reason=(d.get("reason") or "")[:300],
158
+ failure=o.get("failure"), detail=(o.get("detail") or "")[:300], log=r["log"],
159
+ events=[e.get("ev") for e in o.get("events", []) if isinstance(e, dict)][:40],
160
+ cover_removed=o.get("cover_removed"))
161
+ rows.setdefault(key, {})[c] = cell
162
+ print("| instance | " + " | ".join(CONDS) + " |")
163
+ print("|---|" + "---|" * len(CONDS))
164
+ f = lambda x: "-" if x is None else ("S" if x.get("success") else ("F" if x.get("status") == "done" else x.get("status")))
165
+ for k, v in sorted(rows.items()):
166
+ print(f"| {k} | " + " | ".join(f(v.get(c)) for c in CONDS) + " |")
167
+ for c in CONDS:
168
+ xs = [v[c] for v in rows.values() if c in v and v[c].get("status") == "done"]
169
+ print(c, f"{sum(x['success'] for x in xs)}/{len(xs)}")
170
+ json.dump(rows, open(os.path.join(OUT, f"report_{stage}.json"), "w"), indent=1)
171
+
172
+
173
+ if __name__ == "__main__":
174
+ {"validate": cmd_validate, "build": lambda: cmd_build(sys.argv[2]), "report": lambda: cmd_report(sys.argv[2])}[sys.argv[1]]()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/make_dossier.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the record of an earlier failed attempt for the full5 history arms (docs/14 §6).
2
+
3
+ python scripts/make_dossier.py <run log dir> <out dir> [--attempt 1] [--allow-success]
4
+
5
+ The record contains only what the agent of that attempt saw: the starting images, every robot command with the
6
+ robot's reply (as logged by robot_server), the images those commands produced, the agent's closing remark and the
7
+ F1 verdict ("failed"). No outcome codes, measurements or hidden variables. The same builder is used for the own-history
8
+ arm (record of a failed independent run on the same instance) and the mismatched arm (record of a failed run on the
9
+ twin instance: same layout, different hidden variable), so the two dossiers differ only in content.
10
+ """
11
+ import argparse
12
+ import json
13
+ import os
14
+ import shutil
15
+
16
+ DROP = ("state_file", "attempt_ended", "camera_file")
17
+
18
+
19
+ def shell_args(args):
20
+ out = []
21
+ for k, v in args.items():
22
+ v = json.dumps(v) if not isinstance(v, str) else v
23
+ out.append(f'{k}="{v}"' if (" " in v or not v) else f"{k}={v}")
24
+ return " ".join(out)
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("log")
30
+ ap.add_argument("out")
31
+ ap.add_argument("--attempt", type=int, default=1)
32
+ ap.add_argument("--allow-success", action="store_true")
33
+ ap.add_argument("--result-extra", default="",
34
+ help="layer-3 ladder (docs/20): text appended to the verdict in the Result section (paragraphs "
35
+ "separated by blank lines; the first one continues the verdict line). Empty = F1 record, "
36
+ "byte-identical to the record built without this option.")
37
+ a = ap.parse_args()
38
+ evs = [json.loads(line) for line in open(os.path.join(a.log, "events.jsonl")) if line.strip()]
39
+ start = next(e for e in evs if e["ev"] == "session_start")
40
+ if start.get("style", "la") not in ("la", None) and "style" in start:
41
+ raise SystemExit("only la-style runs are supported")
42
+ calls = [e for e in evs if e["ev"] == "call" and e.get("attempt") == a.attempt]
43
+ done = [e for e in evs if e["ev"] == "done" and e.get("attempt") == a.attempt]
44
+ if not done:
45
+ raise SystemExit(f"attempt {a.attempt} has no done event (run unfinished?)")
46
+ done = done[0]
47
+ if done["success"] and not a.allow_success:
48
+ raise SystemExit(f"attempt {a.attempt} succeeded; nothing to learn from (use --allow-success to force)")
49
+ imgs = os.path.join(a.log, "images")
50
+ # commands as that agent issued them: `./robot <cmd>` in a CLI workspace, the `robot` tool's argument otherwise
51
+ try:
52
+ iface = json.load(open(os.path.join(a.log, "agent_iface.json"))).get("agent_iface", "cli")
53
+ except OSError:
54
+ iface = "cli"
55
+ pre = "./robot " if iface == "cli" else ""
56
+ os.makedirs(os.path.join(a.out, "obs"), exist_ok=False)
57
+
58
+ def copy(rel):
59
+ base = os.path.basename(rel)
60
+ src = os.path.join(imgs, f"a{a.attempt}_{base}")
61
+ if not os.path.exists(src):
62
+ return None
63
+ shutil.copy(src, os.path.join(a.out, "obs", base))
64
+ return f"obs/{base}"
65
+
66
+ # starting images: the first images the agent saw (status at step 0)
67
+ first = sorted(f for f in os.listdir(imgs) if f.startswith(f"a{a.attempt}_") and "s000_" in f)
68
+ start_imgs = [copy(f.split("_", 1)[1]) for f in first]
69
+ lines = ["# Record of the earlier attempt", "",
70
+ "Starting scene: " + ", ".join(p for p in start_imgs if p), "",
71
+ "## Robot commands and replies", ""]
72
+ rec = []
73
+ for i, e in enumerate(calls, 1):
74
+ rep = {k: v for k, v in (e.get("report") or {}).items() if k not in DROP}
75
+ if "images" in rep:
76
+ rep["images"] = [p2 for p2 in (copy(p) for p in rep["images"]) if p2]
77
+ cmd = f"{pre}{e['cmd']} {shell_args(e.get('args') or {})}".strip()
78
+ lines += [f"{i}. `{cmd}`", " reply: `" + json.dumps(rep) + "`", ""]
79
+ rec.append(dict(n=i, command=cmd, reply=rep))
80
+ lines += [f"{len(calls) + 1}. `{pre}finish reason=\"{done.get('reason', '')}\"`", "",
81
+ "## Closing remark of that attempt", "", str(done.get("reason", "")), "",
82
+ "## Result", ""]
83
+ verdict = "The environment judged that attempt: " + ("succeeded." if done["success"] else "failed.")
84
+ extra = [x.strip() for x in a.result_extra.split("\n\n") if x.strip()]
85
+ if extra:
86
+ verdict += " " + extra[0]
87
+ lines += [verdict, ""]
88
+ for x in extra[1:]:
89
+ lines += [x, ""]
90
+ with open(os.path.join(a.out, "README.md"), "w") as f:
91
+ f.write("\n".join(lines))
92
+ with open(os.path.join(a.out, "record.jsonl"), "w") as f:
93
+ for r in rec:
94
+ f.write(json.dumps(r) + "\n")
95
+ with open(os.path.join(os.path.dirname(os.path.abspath(a.out)), os.path.basename(a.out) + ".source.json"), "w") as f:
96
+ json.dump(dict(log=os.path.abspath(a.log), attempt=a.attempt, task=start.get("task"), seed=start.get("seed"),
97
+ arm=start.get("arm", "none"), n_commands=len(calls), success=done["success"],
98
+ result_extra=a.result_extra), f)
99
+ print(json.dumps(dict(out=a.out, n_commands=len(calls), n_images=len(os.listdir(os.path.join(a.out, "obs"))))))
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/qwen_vl_server.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Minimal OpenAI-compatible Chat Completions server (with tool calling) for Qwen3-VL.
3
+
4
+ Runs a local HF-format Qwen3-VL checkpoint with transformers (>= 4.57) on one
5
+ CUDA-compatible device (here: Alibaba PPU) and exposes:
6
+
7
+ POST /v1/chat/completions OpenAI chat.completion (non-streaming; stream=true
8
+ is emulated: the full answer is generated first
9
+ and then sent as SSE chunks)
10
+ GET /v1/models lists the single served model
11
+ GET /health liveness + device memory
12
+
13
+ Request format accepted (subset of OpenAI):
14
+ messages: system / developer / user / assistant (with tool_calls) / tool
15
+ user/tool content may be a string or a list of
16
+ {"type":"text","text":...} and
17
+ {"type":"image_url","image_url":{"url": "data:image/...;base64,..." | http(s) URL | file path}}
18
+ tools: [{"type":"function","function":{"name","description","parameters"}}]
19
+ tool_choice: "auto" (default) | "none" (tools hidden from the prompt) |
20
+ "required" (generation is prefixed with "<tool_call>\n") |
21
+ {"type":"function","function":{"name":X}} (prefixed with the call header for X)
22
+ parallel_tool_calls: false -> only the first parsed tool call is returned
23
+ max_tokens / max_completion_tokens (default --default-max-tokens, 1024)
24
+ temperature (absent or 0 -> greedy), top_p, top_k, seed, stop (str or list)
25
+ Ignored: n (always 1), response_format, logprobs, presence/frequency penalty, user.
26
+
27
+ The model emits Hermes-style <tool_call>{"name":..., "arguments":{...}}</tool_call>
28
+ blocks; they are parsed into choices[0].message.tool_calls with arguments as a JSON
29
+ string, and the remaining text (if any) becomes message.content (else null).
30
+
31
+ Generation is serialised with a lock (one request on the device at a time); the
32
+ HTTP layer is a stdlib ThreadingHTTPServer so /health stays responsive.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import argparse
37
+ import base64
38
+ import io
39
+ import json
40
+ import logging
41
+ import os
42
+ import re
43
+ import sys
44
+ import threading
45
+ import time
46
+ import traceback
47
+ import urllib.request
48
+ import uuid
49
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
50
+
51
+ LOG = logging.getLogger("qwen_vl_server")
52
+
53
+ TOOL_CALL_RE = re.compile(r"<tool_call>\s*(.*?)\s*</tool_call>", re.DOTALL)
54
+ END_MARKERS = ("<|im_end|>", "<|endoftext|>")
55
+
56
+
57
+ # ----------------------------------------------------------------------------
58
+ # Request conversion
59
+ # ----------------------------------------------------------------------------
60
+ class BadRequest(Exception):
61
+ pass
62
+
63
+
64
+ def load_image(url: str):
65
+ from PIL import Image
66
+
67
+ if url.startswith("data:"):
68
+ try:
69
+ _, b64 = url.split(",", 1)
70
+ except ValueError as e:
71
+ raise BadRequest("malformed data URL") from e
72
+ raw = base64.b64decode(b64)
73
+ elif url.startswith("http://") or url.startswith("https://"):
74
+ with urllib.request.urlopen(url, timeout=30) as r:
75
+ raw = r.read()
76
+ else:
77
+ path = url[len("file://"):] if url.startswith("file://") else url
78
+ with open(path, "rb") as f:
79
+ raw = f.read()
80
+ img = Image.open(io.BytesIO(raw))
81
+ img.load()
82
+ return img.convert("RGB")
83
+
84
+
85
+ def convert_content(content, images: list):
86
+ """OpenAI content (str | list[part] | None) -> Qwen template content.
87
+
88
+ Images are replaced by {"type": "image"} placeholders and the decoded PIL images
89
+ are appended to `images` in prompt order (the chat template emits one
90
+ <|vision_start|><|image_pad|><|vision_end|> per placeholder, in the same order).
91
+ """
92
+ if content is None:
93
+ return ""
94
+ if isinstance(content, str):
95
+ return content
96
+ if not isinstance(content, list):
97
+ raise BadRequest(f"unsupported content type: {type(content).__name__}")
98
+ out = []
99
+ for part in content:
100
+ if isinstance(part, str):
101
+ out.append({"type": "text", "text": part})
102
+ continue
103
+ ptype = part.get("type")
104
+ if ptype in ("text", "input_text"):
105
+ out.append({"type": "text", "text": part.get("text", "")})
106
+ elif ptype in ("image_url", "input_image", "image"):
107
+ iu = part.get("image_url", part.get("image"))
108
+ url = iu.get("url") if isinstance(iu, dict) else iu
109
+ if not isinstance(url, str):
110
+ raise BadRequest("image part without url")
111
+ try:
112
+ images.append(load_image(url))
113
+ except BadRequest:
114
+ raise
115
+ except Exception as e: # noqa: BLE001
116
+ raise BadRequest(f"could not load image ({url[:60]}...): {type(e).__name__}: {e}") from e
117
+ out.append({"type": "image"})
118
+ else:
119
+ raise BadRequest(f"unsupported content part type: {ptype}")
120
+ return out
121
+
122
+
123
+ def text_only(content) -> str:
124
+ if content is None:
125
+ return ""
126
+ if isinstance(content, str):
127
+ return content
128
+ return "".join(p.get("text", "") for p in content if isinstance(p, dict))
129
+
130
+
131
+ def convert_messages(messages: list):
132
+ if not isinstance(messages, list) or not messages:
133
+ raise BadRequest("messages must be a non-empty list")
134
+ images: list = []
135
+ system_texts = []
136
+ conv = []
137
+ for m in messages:
138
+ role = m.get("role")
139
+ if role in ("system", "developer"):
140
+ # The Qwen template only renders a leading system message; merge all of them.
141
+ system_texts.append(text_only(m.get("content")))
142
+ elif role == "user":
143
+ conv.append({"role": "user", "content": convert_content(m.get("content"), images)})
144
+ elif role == "assistant":
145
+ c = m.get("content")
146
+ msg = {"role": "assistant", "content": text_only(c) if not isinstance(c, str) else c}
147
+ tcs = m.get("tool_calls") or []
148
+ if tcs:
149
+ norm = []
150
+ for tc in tcs:
151
+ fn = tc.get("function", tc)
152
+ args = fn.get("arguments", {})
153
+ if not isinstance(args, str):
154
+ args = json.dumps(args, ensure_ascii=False)
155
+ norm.append({"type": "function", "function": {"name": fn.get("name", ""), "arguments": args}})
156
+ msg["tool_calls"] = norm
157
+ conv.append(msg)
158
+ elif role in ("tool", "function"):
159
+ conv.append({"role": "tool", "content": convert_content(m.get("content"), images)})
160
+ else:
161
+ raise BadRequest(f"unsupported role: {role}")
162
+ if system_texts:
163
+ conv.insert(0, {"role": "system", "content": "\n\n".join(system_texts)})
164
+ return conv, images
165
+
166
+
167
+ # ----------------------------------------------------------------------------
168
+ # Output parsing
169
+ # ----------------------------------------------------------------------------
170
+ def _loads_lenient(s: str):
171
+ s = s.strip()
172
+ try:
173
+ return json.loads(s)
174
+ except json.JSONDecodeError:
175
+ pass
176
+ # common slips: trailing garbage after the object, missing final brace
177
+ start = s.find("{")
178
+ if start >= 0:
179
+ dec = json.JSONDecoder()
180
+ try:
181
+ obj, _ = dec.raw_decode(s[start:])
182
+ return obj
183
+ except json.JSONDecodeError:
184
+ pass
185
+ for extra in ("}", "}}", "\"}}"):
186
+ try:
187
+ return json.loads(s[start:] + extra)
188
+ except json.JSONDecodeError:
189
+ continue
190
+ return None
191
+
192
+
193
+ def parse_tool_calls(text: str):
194
+ """Return (content_or_None, tool_calls_list)."""
195
+ calls = []
196
+ spans = []
197
+ for mt in TOOL_CALL_RE.finditer(text):
198
+ spans.append(mt.span())
199
+ calls.append(mt.group(1))
200
+ # an unterminated trailing <tool_call> (e.g. hit max_tokens / model forgot the tag)
201
+ last_end = spans[-1][1] if spans else 0
202
+ tail_idx = text.find("<tool_call>", last_end)
203
+ if tail_idx >= 0:
204
+ spans.append((tail_idx, len(text)))
205
+ calls.append(text[tail_idx + len("<tool_call>"):])
206
+
207
+ tool_calls = []
208
+ keep_raw = [] # unparsable blocks stay in content
209
+ for (a, b), body in zip(spans, calls):
210
+ obj = _loads_lenient(body)
211
+ if not isinstance(obj, dict) or "name" not in obj:
212
+ keep_raw.append((a, b))
213
+ continue
214
+ args = obj.get("arguments", obj.get("parameters", {}))
215
+ if isinstance(args, str):
216
+ parsed = _loads_lenient(args)
217
+ args_str = json.dumps(parsed, ensure_ascii=False) if parsed is not None else args
218
+ else:
219
+ args_str = json.dumps(args, ensure_ascii=False)
220
+ tool_calls.append({
221
+ "id": "call_" + uuid.uuid4().hex[:24],
222
+ "type": "function",
223
+ "function": {"name": str(obj["name"]), "arguments": args_str},
224
+ })
225
+
226
+ # content = text with successfully parsed blocks removed
227
+ parsed_spans = [s for s in spans if s not in keep_raw]
228
+ pieces, pos = [], 0
229
+ for a, b in sorted(parsed_spans):
230
+ pieces.append(text[pos:a])
231
+ pos = b
232
+ pieces.append(text[pos:])
233
+ content = "".join(pieces).strip()
234
+ return (content if content else None), tool_calls
235
+
236
+
237
+ # ----------------------------------------------------------------------------
238
+ # Model wrapper
239
+ # ----------------------------------------------------------------------------
240
+ class Engine:
241
+ def __init__(self, args):
242
+ import torch
243
+ from transformers import AutoModelForImageTextToText, AutoProcessor
244
+
245
+ self.torch = torch
246
+ self.args = args
247
+ self.device = args.device
248
+ t0 = time.time()
249
+ proc_kwargs = {}
250
+ if args.min_pixels:
251
+ proc_kwargs["min_pixels"] = args.min_pixels
252
+ if args.max_pixels:
253
+ proc_kwargs["max_pixels"] = args.max_pixels
254
+ if args.attn == "sdpa" and not args.sdpa_native_gqa:
255
+ # PPU quirk (measured): torch SDPA with enable_gqa=True fails for decode steps
256
+ # (q_len=1, no mask) with "q must have shape (batch_size, seqlen_q, num_heads,
257
+ # head_size_og)". Make transformers repeat K/V heads itself instead.
258
+ import transformers.integrations.sdpa_attention as _sdpa
259
+
260
+ _sdpa.use_gqa_in_sdpa = lambda attention_mask, key: False
261
+ self.processor = AutoProcessor.from_pretrained(args.model, **proc_kwargs)
262
+ self.tokenizer = self.processor.tokenizer
263
+ self.model = AutoModelForImageTextToText.from_pretrained(
264
+ args.model,
265
+ dtype=torch.bfloat16,
266
+ attn_implementation=args.attn,
267
+ device_map={"": self.device},
268
+ ).eval()
269
+ self.load_time = time.time() - t0
270
+ self.eos_ids = [self.tokenizer.convert_tokens_to_ids(t) for t in END_MARKERS]
271
+ self.eos_ids = [i for i in self.eos_ids if isinstance(i, int) and i >= 0]
272
+ self.pad_id = self.tokenizer.pad_token_id if self.tokenizer.pad_token_id is not None else self.eos_ids[-1]
273
+ self.lock = threading.Lock()
274
+ LOG.info("model loaded in %.1fs on %s (attn=%s); mem allocated %.2f GiB",
275
+ self.load_time, self.device, args.attn, torch.cuda.memory_allocated(self.device) / 2**30)
276
+
277
+ def mem(self):
278
+ t = self.torch
279
+ return {
280
+ "allocated_gib": round(t.cuda.memory_allocated(self.device) / 2**30, 2),
281
+ "reserved_gib": round(t.cuda.memory_reserved(self.device) / 2**30, 2),
282
+ "max_allocated_gib": round(t.cuda.max_memory_allocated(self.device) / 2**30, 2),
283
+ }
284
+
285
+ def chat(self, req: dict):
286
+ torch = self.torch
287
+ a = self.args
288
+ messages, images = convert_messages(req.get("messages"))
289
+ tools = req.get("tools") or None
290
+ tool_choice = req.get("tool_choice", "auto")
291
+ prefix = ""
292
+ if tools:
293
+ if tool_choice == "none":
294
+ tools = None
295
+ elif tool_choice == "required":
296
+ prefix = "<tool_call>\n"
297
+ elif isinstance(tool_choice, dict):
298
+ fname = (tool_choice.get("function") or {}).get("name") or tool_choice.get("name")
299
+ if fname:
300
+ prefix = '<tool_call>\n{"name": "' + fname + '", "arguments": '
301
+ tmpl_tools = None
302
+ if tools:
303
+ tmpl_tools = []
304
+ for t in tools:
305
+ if isinstance(t, dict) and "function" not in t and "name" in t:
306
+ t = {"type": "function", "function": t}
307
+ tmpl_tools.append(t)
308
+
309
+ prompt = self.processor.apply_chat_template(
310
+ messages, tools=tmpl_tools, tokenize=False, add_generation_prompt=True
311
+ ) + prefix
312
+ inputs = self.processor(
313
+ text=[prompt], images=images if images else None, return_tensors="pt"
314
+ ).to(self.device)
315
+ n_prompt = int(inputs["input_ids"].shape[1])
316
+ if n_prompt > a.max_prompt_tokens:
317
+ raise BadRequest(f"prompt has {n_prompt} tokens > --max-prompt-tokens {a.max_prompt_tokens}")
318
+
319
+ max_new = req.get("max_completion_tokens") or req.get("max_tokens") or a.default_max_tokens
320
+ max_new = int(min(max_new, a.max_tokens_cap))
321
+ temperature = req.get("temperature")
322
+ if temperature is None:
323
+ temperature = a.default_temperature
324
+ gen_kwargs = dict(
325
+ max_new_tokens=max_new,
326
+ eos_token_id=self.eos_ids,
327
+ pad_token_id=self.pad_id,
328
+ use_cache=True,
329
+ )
330
+ if temperature and float(temperature) > 0:
331
+ gen_kwargs.update(do_sample=True, temperature=float(temperature),
332
+ top_p=float(req.get("top_p") or 0.8), top_k=int(req.get("top_k") or 20))
333
+ else:
334
+ gen_kwargs.update(do_sample=False, temperature=None, top_p=None, top_k=None)
335
+ if req.get("seed") is not None:
336
+ torch.manual_seed(int(req["seed"]))
337
+
338
+ with torch.inference_mode():
339
+ out = self.model.generate(**inputs, **gen_kwargs)
340
+ new_ids = out[0, n_prompt:].tolist()
341
+ # count tokens up to and including the first EOS
342
+ n_completion = len(new_ids)
343
+ hit_eos = False
344
+ for i, tid in enumerate(new_ids):
345
+ if tid in self.eos_ids:
346
+ n_completion = i + 1
347
+ hit_eos = True
348
+ break
349
+ text = self.tokenizer.decode(new_ids[:n_completion], skip_special_tokens=False)
350
+ for mk in END_MARKERS:
351
+ text = text.replace(mk, "")
352
+ text = prefix + text
353
+
354
+ stop = req.get("stop")
355
+ stopped_by_str = False
356
+ if stop:
357
+ for s in ([stop] if isinstance(stop, str) else stop):
358
+ k = text.find(s, len(prefix))
359
+ if k >= 0:
360
+ text = text[:k]
361
+ stopped_by_str = True
362
+
363
+ if tools:
364
+ content, tool_calls = parse_tool_calls(text)
365
+ if tool_calls and req.get("parallel_tool_calls") is False:
366
+ tool_calls = tool_calls[:1]
367
+ else:
368
+ content, tool_calls = (text.strip() or None), []
369
+
370
+ if tool_calls:
371
+ finish = "tool_calls"
372
+ elif hit_eos or stopped_by_str:
373
+ finish = "stop"
374
+ else:
375
+ finish = "length"
376
+ message = {"role": "assistant", "content": content}
377
+ if tool_calls:
378
+ message["tool_calls"] = tool_calls
379
+ usage = {"prompt_tokens": n_prompt, "completion_tokens": n_completion,
380
+ "total_tokens": n_prompt + n_completion}
381
+ return message, finish, usage, len(images), text
382
+
383
+
384
+ # ----------------------------------------------------------------------------
385
+ # HTTP
386
+ # ----------------------------------------------------------------------------
387
+ ENGINE: Engine | None = None
388
+ ARGS = None
389
+
390
+
391
+ class Handler(BaseHTTPRequestHandler):
392
+ protocol_version = "HTTP/1.1"
393
+
394
+ def log_message(self, fmt, *args): # route http.server logs through logging
395
+ LOG.debug("%s - %s", self.address_string(), fmt % args)
396
+
397
+ def _send_json(self, code: int, obj):
398
+ body = json.dumps(obj, ensure_ascii=False).encode("utf-8")
399
+ self.send_response(code)
400
+ self.send_header("Content-Type", "application/json")
401
+ self.send_header("Content-Length", str(len(body)))
402
+ self.end_headers()
403
+ self.wfile.write(body)
404
+
405
+ def _error(self, code: int, msg: str, etype: str):
406
+ self._send_json(code, {"error": {"message": msg, "type": etype, "code": code}})
407
+
408
+ def do_GET(self):
409
+ if self.path.rstrip("/") in ("/health", "/v1/health"):
410
+ self._send_json(200, {"status": "ok", "model": ARGS.served_name, "memory": ENGINE.mem(),
411
+ "load_time_s": round(ENGINE.load_time, 1)})
412
+ elif self.path.rstrip("/") == "/v1/models":
413
+ self._send_json(200, {"object": "list", "data": [
414
+ {"id": ARGS.served_name, "object": "model", "created": int(time.time()), "owned_by": "local"}]})
415
+ else:
416
+ self._error(404, f"no route {self.path}", "not_found")
417
+
418
+ def do_POST(self):
419
+ if self.path.rstrip("/") not in ("/v1/chat/completions", "/chat/completions"):
420
+ self._error(404, f"no route {self.path}", "not_found")
421
+ return
422
+ try:
423
+ n = int(self.headers.get("Content-Length", "0"))
424
+ req = json.loads(self.rfile.read(n).decode("utf-8"))
425
+ except Exception as e: # noqa: BLE001
426
+ self._error(400, f"invalid JSON body: {e}", "invalid_request_error")
427
+ return
428
+ t0 = time.time()
429
+ try:
430
+ with ENGINE.lock:
431
+ t_lock = time.time()
432
+ message, finish, usage, n_img, raw = ENGINE.chat(req)
433
+ except BadRequest as e:
434
+ self._error(400, str(e), "invalid_request_error")
435
+ return
436
+ except Exception as e: # noqa: BLE001
437
+ LOG.error("generation failed: %s\n%s", e, traceback.format_exc())
438
+ if "out of memory" in str(e).lower():
439
+ try:
440
+ ENGINE.torch.cuda.empty_cache()
441
+ except Exception: # noqa: BLE001
442
+ pass
443
+ self._error(500, f"{type(e).__name__}: {e}", "server_error")
444
+ return
445
+ dt = time.time() - t0
446
+ LOG.info("req images=%d prompt=%d completion=%d finish=%s tool_calls=%d queue=%.2fs gen=%.2fs mem=%s",
447
+ n_img, usage["prompt_tokens"], usage["completion_tokens"], finish,
448
+ len(message.get("tool_calls", [])), t_lock - t0, time.time() - t_lock, ENGINE.mem())
449
+ if ARGS.log_outputs:
450
+ LOG.info("raw output: %r", raw)
451
+ cid = "chatcmpl-" + uuid.uuid4().hex[:24]
452
+ created = int(time.time())
453
+ model_name = req.get("model") or ARGS.served_name
454
+ if req.get("stream"):
455
+ self._send_stream(cid, created, model_name, message, finish, usage, req)
456
+ return
457
+ self._send_json(200, {
458
+ "id": cid,
459
+ "object": "chat.completion",
460
+ "created": created,
461
+ "model": model_name,
462
+ "choices": [{"index": 0, "message": message, "finish_reason": finish, "logprobs": None}],
463
+ "usage": usage,
464
+ "server_timing": {"latency_s": round(dt, 3)},
465
+ })
466
+
467
+ def _send_stream(self, cid, created, model_name, message, finish, usage, req):
468
+ self.send_response(200)
469
+ self.send_header("Content-Type", "text/event-stream")
470
+ self.send_header("Cache-Control", "no-cache")
471
+ self.send_header("Connection", "close")
472
+ self.end_headers()
473
+ self.close_connection = True
474
+
475
+ def chunk(delta, fr=None, with_usage=False):
476
+ obj = {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name,
477
+ "choices": [{"index": 0, "delta": delta, "finish_reason": fr, "logprobs": None}]}
478
+ if with_usage:
479
+ obj["usage"] = usage
480
+ self.wfile.write(b"data: " + json.dumps(obj, ensure_ascii=False).encode() + b"\n\n")
481
+
482
+ chunk({"role": "assistant", "content": message.get("content") or ""})
483
+ for i, tc in enumerate(message.get("tool_calls", [])):
484
+ chunk({"tool_calls": [dict(tc, index=i)]})
485
+ include_usage = bool((req.get("stream_options") or {}).get("include_usage"))
486
+ chunk({}, finish, with_usage=include_usage)
487
+ self.wfile.write(b"data: [DONE]\n\n")
488
+ self.wfile.flush()
489
+
490
+
491
+ def main():
492
+ global ENGINE, ARGS
493
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
494
+ p.add_argument("--model", default=os.environ.get("QWEN_VL_MODEL", "Qwen/Qwen3-VL-8B-Instruct"))
495
+ p.add_argument("--served-name", default="Qwen3-VL-8B-Instruct")
496
+ p.add_argument("--host", default="127.0.0.1")
497
+ p.add_argument("--port", type=int, default=8765)
498
+ p.add_argument("--device", default="cuda:0")
499
+ p.add_argument("--attn", default="sdpa", choices=["sdpa", "eager", "flash_attention_2"])
500
+ p.add_argument("--sdpa-native-gqa", action="store_true",
501
+ help="let torch SDPA do GQA (enable_gqa=True); broken on PPU for decode, off by default")
502
+ p.add_argument("--default-max-tokens", type=int, default=1024)
503
+ p.add_argument("--max-tokens-cap", type=int, default=8192)
504
+ p.add_argument("--max-prompt-tokens", type=int, default=65536)
505
+ p.add_argument("--default-temperature", type=float, default=0.0,
506
+ help="used when the request has no temperature; 0 = greedy")
507
+ p.add_argument("--min-pixels", type=int, default=0, help="override image processor min_pixels")
508
+ p.add_argument("--max-pixels", type=int, default=0, help="override image processor max_pixels")
509
+ p.add_argument("--log-outputs", action="store_true", help="log raw model output text per request")
510
+ p.add_argument("--warmup", action="store_true", help="run one tiny generation before serving")
511
+ ARGS = p.parse_args()
512
+
513
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout)
514
+ import transformers
515
+
516
+ LOG.info("transformers %s from %s", transformers.__version__, os.path.dirname(transformers.__file__))
517
+ ENGINE = Engine(ARGS)
518
+ if ARGS.warmup:
519
+ t = time.time()
520
+ with ENGINE.lock:
521
+ ENGINE.chat({"messages": [{"role": "user", "content": "Hi"}], "max_tokens": 4})
522
+ LOG.info("warmup done in %.1fs", time.time() - t)
523
+ srv = ThreadingHTTPServer((ARGS.host, ARGS.port), Handler)
524
+ srv.daemon_threads = True
525
+ LOG.info("serving %s on http://%s:%d/v1/chat/completions", ARGS.served_name, ARGS.host, ARGS.port)
526
+ try:
527
+ srv.serve_forever()
528
+ except KeyboardInterrupt:
529
+ pass
530
+ finally:
531
+ srv.server_close()
532
+
533
+
534
+ if __name__ == "__main__":
535
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/qwen_vl_server.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Launch the Qwen3-VL OpenAI-compatible server on the local PPU.
3
+ # Usage: bash scripts/qwen_vl_server.sh [--port 8765] [--host 127.0.0.1] [other qwen_vl_server.py args]
4
+ # Uses the system python3.12 (torch 2.6 PPU build) + a private overlay dir that only
5
+ # holds transformers==4.57.6 / tokenizers==0.22.1 / huggingface_hub==0.36.0; the
6
+ # overlay is put on PYTHONPATH for this process only.
7
+ set -eo pipefail
8
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
9
+ # PPU runtime libs (libhggcrt1.so etc.); without this torch spins printing load errors.
10
+ source /usr/local/PPU_SDK/envsetup.sh cuda >/dev/null
11
+ [ -n "${QWEN_OVERLAY:-}" ] && export PYTHONPATH="${QWEN_OVERLAY}${PYTHONPATH:+:${PYTHONPATH}}"
12
+ export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}"
13
+ export MKL_NUM_THREADS="${MKL_NUM_THREADS:-1}"
14
+ export TOKENIZERS_PARALLELISM=false
15
+ export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
16
+ export PYTHONUNBUFFERED=1
17
+ exec /usr/local/bin/python3.12 "${HERE}/qwen_vl_server.py" "$@"
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/start_robot_session.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Start a robot server + isolated sandbox for one task instance.
3
+ # usage: scripts/start_robot_session.sh <task> <seed> <memory full|none> <feedback F0|F1|F2> <port> [instruction direct|indirect] [k] [tag] [perception depth|rgb] [video 0|1]
4
+ # The sandbox gets an opaque random name (no task / condition in the path); the readable run name is only in LOG.
5
+ set -e
6
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
7
+ TASK=$1; SEED=$2; MEM=$3; FB=$4; PORT=$5; INSTR=${6:-direct}; K=${7:-}; TAG=${8:-}; PERC=${9:-depth}; VID=${10:-0}
8
+ RUN=${TAG:+${TAG}_}${TASK}_s${SEED}_${MEM}_${FB}_${INSTR}_k${K:-d}_$(date +%m%d-%H%M%S)_p${PORT}
9
+ SANDBOX=${LFF_SANDBOX_ROOT:-/tmp/robotlab}/$(python3 -c 'import secrets;print(secrets.token_hex(6))')
10
+ LOG=${LFF_RUNS_DIR:-$ROOT/runs/claude}/$RUN
11
+ mkdir -p "$SANDBOX" "$LOG"
12
+ cd "$ROOT" && source run_env.sh && export OMP_NUM_THREADS=1
13
+ KARG=""; [ -n "$K" ] && KARG="--k $K"
14
+ VARG=""; [ "$VID" = "1" ] && VARG="--video $LOG/rollout.mp4"
15
+ nohup python -m lffbench.agent.robot_server --task "$TASK" --seed "$SEED" --memory "$MEM" --feedback "$FB" \
16
+ --instruction "$INSTR" --port "$PORT" --sandbox "$SANDBOX" --log-dir "$LOG" --perception "$PERC" --style "${LFF_STYLE:-v1}" ${LFF_EXTRA_ARGS:-} $KARG $VARG > "$LOG/server.log" 2>&1 &
17
+ echo $! > "$LOG/server.pid"
18
+ # wait for the scene (long-horizon scenes on a loaded machine took > 2 min, 2026-10-20); on failure stop the server
19
+ # so that it does not keep the port
20
+ for i in $(seq 1 "${LFF_SERVER_WAIT_S:-600}"); do [ -f "$LOG/READY" ] && break; sleep 1; done
21
+ [ -f "$LOG/READY" ] || { echo "server failed"; tail -20 "$LOG/server.log"; kill "$(cat "$LOG/server.pid")" 2>/dev/null; exit 1; }
22
+ echo "{\"run\": \"$RUN\", \"sandbox\": \"$SANDBOX\", \"port\": $PORT}" > "$LOG/session.json"
23
+ echo "SANDBOX=$SANDBOX"
24
+ echo "LOG=$LOG"
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/tool_gateway.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-episode tool gateway (docs/18 §6.1): the one implementation of the three LA tools for every access path.
2
+
3
+ `robot` (forwarded to robot_server), `shell` (jailed, in the episode workspace) and `view_images` (workspace image files),
4
+ with the per-attempt tool-call budget counted here once for the whole episode: when it is used up the attempt is
5
+ finished automatically and the result is appended to that call's output. The MCP server (scripts/mcp_robot_server.py)
6
+ and the Python SDK (client/lffbench_client) are thin clients of this process, so a native harness (Codex, Claude Code)
7
+ and a robot harness framework (RPent, ...) get the same tools, outputs and limits. The gateway runs outside the harness
8
+ jail next to robot_server; harness processes only see its HTTP port and token, never robot_server's token, the
9
+ workspace files or a shell of their own.
10
+
11
+ python scripts/tool_gateway.py --session runs/<...>/session.json
12
+ writes <log dir>/gateway.json {url, port, pid, token} (mode 600) once it listens and logs every call to
13
+ <log dir>/gateway_transcript.jsonl. HTTP on 127.0.0.1, header "Authorization: Bearer <token>":
14
+ POST /tool {"name": ..., "arguments": {...}} -> {"content": [...], "is_error", "finished", "calls_in_attempt"}
15
+ content items: {"type": "text", "text"} / {"type": "image", "mimeType", "data" (base64)}
16
+ GET /tool_specs?style=raw|mcp|anthropic|openai_responses|openai_chat the three tool schemas, descriptions verbatim
17
+ GET /readme README.md of the episode workspace
18
+ GET /first_message preamble + README + first status report, byte-identical to the native harnesses' first
19
+ message (taken from <log dir>/first_message.txt when the launcher already rendered it)
20
+ GET /health
21
+ GET /status robot_server's `status`, for a framework's own loop (e.g. the reference driver's "Continue ..."
22
+ nudge, which needs the attempt number): not a tool call, not counted in the per-attempt budget,
23
+ logged as ev=status; the native harnesses' launcher makes the same call directly
24
+ (scripts/harness_run.py continue_episode)
25
+ Header "X-LFF-Face" labels the access path in the transcript (mcp, sdk, ...). Contract: like mcp_robot_server.py and
26
+ api_player.py the gateway is an access path, not part of contract_sha256 (docs/15 §8.4); the "oracle through every
27
+ access path" self-check keeps the paths equal.
28
+ """
29
+ import argparse
30
+ import base64
31
+ import hmac
32
+ import json
33
+ import os
34
+ import secrets
35
+ import subprocess
36
+ import sys
37
+ import threading
38
+ import time
39
+ import traceback
40
+ import urllib.parse
41
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
42
+
43
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
44
+ from api_player import (SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, call_server, parse_command, run_shell, # noqa: E402
45
+ workspace_image)
46
+
47
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
48
+ TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA]
49
+ GATEWAY_FILE = "gateway.json"
50
+ TRANSCRIPT = "gateway_transcript.jsonl"
51
+
52
+
53
+ def tool_specs(style="raw"):
54
+ """The three tool schemas in the format a framework registers them in; names, descriptions and parameter schemas
55
+ are the reference driver's, verbatim."""
56
+ if style == "raw":
57
+ return [dict(t) for t in TOOLS]
58
+ if style == "mcp":
59
+ return [dict(name=t["name"], description=t["description"], inputSchema=t["parameters"]) for t in TOOLS]
60
+ if style == "anthropic":
61
+ return [dict(name=t["name"], description=t["description"], input_schema=t["parameters"]) for t in TOOLS]
62
+ if style == "openai_responses":
63
+ return [dict(type="function", name=t["name"], description=t["description"], parameters=t["parameters"])
64
+ for t in TOOLS]
65
+ if style == "openai_chat":
66
+ return [dict(type="function", function=dict(name=t["name"], description=t["description"],
67
+ parameters=t["parameters"])) for t in TOOLS]
68
+ raise ValueError(f"unknown style {style!r}: raw, mcp, anthropic, openai_responses or openai_chat")
69
+
70
+
71
+ class ToolCore:
72
+ """The three tools on one robot_server session, with the per-attempt tool-call budget. Same semantics and output
73
+ text as the reference driver's LA tools (and, before the gateway, mcp_robot_server.Session)."""
74
+
75
+ def __init__(self, session_path, carry_from=None):
76
+ """carry_from: a transcript (jsonl with ev=tool, calls_in_attempt, finished) to continue the budget from, for an
77
+ in-process host that is restarted within one episode (mcp_robot_server without a gateway)."""
78
+ sess = json.load(open(session_path))
79
+ self.session_path = os.path.abspath(session_path)
80
+ self.sb, self.port = sess["sandbox"], sess["port"]
81
+ self.log_dir = os.path.dirname(self.session_path)
82
+ iface = json.load(open(os.path.join(self.log_dir, "agent_iface.json")))
83
+ self.token, self.max_tool_calls = iface["token"], int(iface["max_tool_calls"])
84
+ self.calls_in_attempt, self.finished = 0, False
85
+ if carry_from and os.path.exists(carry_from):
86
+ for line in open(carry_from):
87
+ try:
88
+ d = json.loads(line)
89
+ except ValueError:
90
+ continue
91
+ if d.get("ev") == "tool" and d.get("calls_in_attempt") is not None:
92
+ self.calls_in_attempt, self.finished = int(d["calls_in_attempt"]), bool(d.get("finished"))
93
+
94
+ def robot(self, cmdline):
95
+ cmd, args = parse_command(cmdline)
96
+ if cmd is None:
97
+ return json.dumps(dict(ok=False, error=args))
98
+ raw = call_server(self.port, self.token, cmd, args)
99
+ try:
100
+ rep = json.loads(raw)
101
+ except ValueError: # help text
102
+ return raw
103
+ msg = (rep.get("message", "") + " " + rep.get("error", "")) if isinstance(rep, dict) else ""
104
+ if isinstance(rep, dict) and isinstance(rep.get("attempt_ended"), dict):
105
+ msg += " " + rep["attempt_ended"].get("message", "")
106
+ if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
107
+ self.finished = True
108
+ if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)):
109
+ self.calls_in_attempt = 0
110
+ return json.dumps(rep)
111
+
112
+ def call(self, name, args):
113
+ """-> (content list, is_error); content items as in MCP (text / image with base64 data)."""
114
+ args = args if isinstance(args, dict) else {}
115
+ if not self.finished:
116
+ self.calls_in_attempt += 1
117
+ if name == "robot":
118
+ content, err = [dict(type="text", text=self.robot(str(args.get("command", ""))))], False
119
+ elif name == "shell":
120
+ code, out, dt = run_shell(self.sb, str(args.get("command", "")))
121
+ content, err = [dict(type="text", text=json.dumps(dict(exit_code=code, output=out)))], False
122
+ elif name == "view_images":
123
+ paths = [str(x) for x in (args.get("paths") or [])][:8]
124
+ full = [(x, workspace_image(self.sb, x)) for x in paths]
125
+ ok = [x for x, f in full if f]
126
+ out = dict(ok=bool(ok), attached=ok)
127
+ if len(ok) < len(paths):
128
+ out["not_viewable"] = [x for x, f in full if not f]
129
+ content, err = [dict(type="text", text=json.dumps(out))], False
130
+ for x, f in full:
131
+ if f:
132
+ mime = "image/png" if f.lower().endswith(".png") else "image/jpeg"
133
+ content.append(dict(type="image", mimeType=mime, data=base64.b64encode(open(f, "rb").read()).decode()))
134
+ else:
135
+ return [dict(type="text", text=f"unknown tool {name!r}")], True
136
+ if not self.finished and self.calls_in_attempt >= self.max_tool_calls:
137
+ raw = call_server(self.port, self.token, "finish", dict(reason="tool-call budget used up (automatic)"))
138
+ try:
139
+ rep = json.loads(raw)
140
+ except ValueError:
141
+ rep = dict(raw=raw)
142
+ msg = rep.get("message", "") + " " + rep.get("error", "")
143
+ if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
144
+ self.finished = True
145
+ self.calls_in_attempt = 0
146
+ content.append(dict(type="text", text=(f"The budget of {self.max_tool_calls} tool calls for this attempt was "
147
+ f"used up, so the attempt was finished automatically. Result: "
148
+ + json.dumps(rep))))
149
+ return content, err
150
+
151
+ def readme(self):
152
+ return open(os.path.join(self.sb, "README.md"), encoding="utf-8").read()
153
+
154
+ def first_message(self):
155
+ """The native harnesses' first user message. Rendered by the launcher (harness_run.py) into first_message.txt;
156
+ otherwise rendered here once, with the same single `status` call, and saved there."""
157
+ path = os.path.join(self.log_dir, "first_message.txt")
158
+ if os.path.exists(path):
159
+ return open(path, encoding="utf-8").read()
160
+ sys.path.insert(0, ROOT)
161
+ from lffbench.harnesses.base import first_message_text
162
+ status_json = json.dumps(json.loads(call_server(self.port, self.token, "status", {})))
163
+ text = first_message_text(self.readme(), status_json)
164
+ with open(path, "w", encoding="utf-8") as f:
165
+ f.write(text)
166
+ return text
167
+
168
+
169
+ def log_line(f, d):
170
+ d["t"] = time.time()
171
+ f.write(json.dumps(d, ensure_ascii=False) + "\n")
172
+ f.flush()
173
+
174
+
175
+ def serve(core, port=0, gateway_file=None, watch_parent=True):
176
+ token = secrets.token_hex(16)
177
+ lock = threading.Lock()
178
+ tlog = open(os.path.join(core.log_dir, TRANSCRIPT), "a")
179
+ fm_cache = {}
180
+
181
+ class H(BaseHTTPRequestHandler):
182
+ protocol_version = "HTTP/1.1"
183
+
184
+ def log_message(self, *a):
185
+ pass
186
+
187
+ def _send(self, code, body, ctype="application/json"):
188
+ data = body if isinstance(body, bytes) else (body if isinstance(body, str) else json.dumps(body)).encode()
189
+ self.send_response(code)
190
+ self.send_header("Content-Type", ctype + ("; charset=utf-8" if ctype.startswith("text") or
191
+ ctype == "application/json" else ""))
192
+ self.send_header("Content-Length", str(len(data)))
193
+ self.end_headers()
194
+ self.wfile.write(data)
195
+
196
+ def _authorized(self):
197
+ got = self.headers.get("Authorization", "")
198
+ return hmac.compare_digest(got.encode(), f"Bearer {token}".encode())
199
+
200
+ def do_GET(self):
201
+ u = urllib.parse.urlparse(self.path)
202
+ if u.path == "/health":
203
+ return self._send(200, dict(ok=True))
204
+ if not self._authorized():
205
+ return self._send(401, dict(error="unauthorized"))
206
+ try:
207
+ if u.path == "/tool_specs":
208
+ style = (urllib.parse.parse_qs(u.query).get("style") or ["raw"])[0]
209
+ return self._send(200, dict(style=style, tools=tool_specs(style)))
210
+ if u.path == "/readme":
211
+ return self._send(200, core.readme(), "text/markdown")
212
+ if u.path == "/first_message":
213
+ with lock:
214
+ if "text" not in fm_cache:
215
+ fm_cache["text"] = core.first_message()
216
+ return self._send(200, fm_cache["text"], "text/plain")
217
+ if u.path == "/status": # a framework's own status call (not the model's): not counted
218
+ face = (self.headers.get("X-LFF-Face") or "http")[:32]
219
+ with lock:
220
+ raw = call_server(core.port, core.token, "status", {})
221
+ log_line(tlog, dict(ev="status", face=face))
222
+ status = json.loads(raw)
223
+ return self._send(200, {k: status.get(k) for k in ("attempt", "max_attempts", "finished")})
224
+ except ValueError as e:
225
+ return self._send(400, dict(error=str(e)))
226
+ except Exception as e:
227
+ log_line(tlog, dict(ev="error", path=u.path, error=traceback.format_exc()[-2000:]))
228
+ return self._send(500, dict(error=f"{type(e).__name__}: {e}"))
229
+ return self._send(404, dict(error=f"no such path {u.path}"))
230
+
231
+ def do_POST(self):
232
+ u = urllib.parse.urlparse(self.path)
233
+ if not self._authorized():
234
+ return self._send(401, dict(error="unauthorized"))
235
+ if u.path != "/tool":
236
+ return self._send(404, dict(error=f"no such path {u.path}"))
237
+ try:
238
+ req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0) or 0)) or b"{}")
239
+ name, args = req.get("name"), req.get("arguments") or {}
240
+ except (ValueError, AttributeError):
241
+ return self._send(400, dict(error="body must be JSON {name, arguments}"))
242
+ face = (self.headers.get("X-LFF-Face") or "http")[:32]
243
+ try:
244
+ with lock: # one tool call at a time per episode, as in the MCP server and the reference driver
245
+ t0 = time.time()
246
+ content, err = core.call(name, args)
247
+ out = dict(content=content, is_error=err, finished=core.finished,
248
+ calls_in_attempt=core.calls_in_attempt)
249
+ log_line(tlog, dict(ev="tool", face=face, name=name, arguments=args, dt=round(time.time() - t0, 2),
250
+ is_error=err, output=[c["text"] for c in content if c["type"] == "text"],
251
+ images=sum(1 for c in content if c["type"] == "image"),
252
+ finished=core.finished, calls_in_attempt=core.calls_in_attempt))
253
+ except Exception as e:
254
+ log_line(tlog, dict(ev="error", face=face, name=name, error=traceback.format_exc()[-2000:]))
255
+ return self._send(500, dict(error=f"{type(e).__name__}: {e}"))
256
+ return self._send(200, out)
257
+
258
+ srv = ThreadingHTTPServer(("127.0.0.1", port), H)
259
+ srv.daemon_threads = True
260
+ port = srv.server_address[1]
261
+ info = dict(url=f"http://127.0.0.1:{port}", port=port, pid=os.getpid(), token=token)
262
+ gateway_file = gateway_file or os.path.join(core.log_dir, GATEWAY_FILE)
263
+ tmp = gateway_file + ".tmp"
264
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
265
+ with os.fdopen(fd, "w") as f:
266
+ json.dump(info, f)
267
+ os.replace(tmp, gateway_file)
268
+ log_line(tlog, dict(ev="start", pid=os.getpid(), port=port, session=core.session_path,
269
+ max_tool_calls=core.max_tool_calls))
270
+ import signal
271
+ signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=srv.shutdown, daemon=True).start())
272
+ if watch_parent: # exit with the launcher, also when it is killed without cleaning up
273
+ ppid = os.getppid()
274
+
275
+ def watch():
276
+ while os.getppid() == ppid:
277
+ time.sleep(2)
278
+ srv.shutdown()
279
+ threading.Thread(target=watch, daemon=True).start()
280
+ try:
281
+ srv.serve_forever(poll_interval=0.5)
282
+ finally:
283
+ log_line(tlog, dict(ev="stop"))
284
+ srv.server_close()
285
+
286
+
287
+ # ------------------------------------------------------------------------------------------------ launcher helpers
288
+ def start_gateway(session_path, python=None, timeout_s=30, env=None):
289
+ """Start a gateway for one episode (child of the caller) and wait until it listens. -> (Popen, info dict with url,
290
+ port, pid, token). The caller stops it with stop_gateway()."""
291
+ log_dir = os.path.dirname(os.path.abspath(session_path))
292
+ gfile = os.path.join(log_dir, GATEWAY_FILE)
293
+ if os.path.exists(gfile):
294
+ os.remove(gfile)
295
+ err = open(os.path.join(log_dir, "gateway_stderr.txt"), "ab")
296
+ p = subprocess.Popen([python or sys.executable, os.path.abspath(__file__), "--session", os.path.abspath(session_path)],
297
+ stdin=subprocess.DEVNULL, stdout=err, stderr=err, env=env)
298
+ deadline = time.time() + timeout_s
299
+ while time.time() < deadline:
300
+ if p.poll() is not None:
301
+ raise RuntimeError(f"tool gateway exited with code {p.returncode}; see {log_dir}/gateway_stderr.txt")
302
+ if os.path.exists(gfile):
303
+ return p, json.load(open(gfile))
304
+ time.sleep(0.05)
305
+ stop_gateway(p)
306
+ raise RuntimeError(f"tool gateway did not start within {timeout_s} s")
307
+
308
+
309
+ def stop_gateway(p):
310
+ if p is None or p.poll() is not None:
311
+ return
312
+ p.terminate()
313
+ try:
314
+ p.wait(timeout=10)
315
+ except subprocess.TimeoutExpired:
316
+ p.kill()
317
+ p.wait()
318
+
319
+
320
+ def main():
321
+ ap = argparse.ArgumentParser()
322
+ ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh (la style)")
323
+ ap.add_argument("--port", type=int, default=0, help="0 = pick a free port")
324
+ ap.add_argument("--gateway-file", default=None, help=f"default <log dir>/{GATEWAY_FILE}")
325
+ ap.add_argument("--no-watch-parent", action="store_true", help="keep running when the launcher exits")
326
+ a = ap.parse_args()
327
+ serve(ToolCore(a.session), port=a.port, gateway_file=a.gateway_file, watch_parent=not a.no_watch_parent)
328
+
329
+
330
+ if __name__ == "__main__":
331
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_deepseek/lff/source_closure/scripts/validate_ladder_fix.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check the Fix-rung texts of the layer-3 feedback ladder (docs/20 §4) on every ladder instance.
2
+
3
+ python scripts/validate_ladder_fix.py [--out results/_ladder/fix_validate.json] [--only TASK]
4
+
5
+ Per instance (task:seed from runs/api/mismatch_20261027/<model>/own.json, both models, deduplicated):
6
+ 1. the sampled instance equals the one logged in the main-table run (session_start inst);
7
+ 2. the scripted oracle succeeds in one attempt; the Fix text is built from the parameters that oracle executed;
8
+ 3. the text has no coordinate-axis labels (strip_axes leaves it unchanged) and no internal instance key names;
9
+ 4. slide_to_target / tablecloth_pull only: the strike / pull the text describes, issued as LA `move_eef`
10
+ commands in the robot-base frame through the same path as robot_server (ToolExecutor move_to with the given
11
+ speed), also succeeds -- this checks that "speed" in the text means what move_eef does. The success window is
12
+ narrow (~+-0.02) and the LA path does not hit it at exactly the oracle's speed (tablecloth 3001: oracle 0.475
13
+ fails as LA commands, 0.48-0.52 succeed), so for these two the text's speed is the middle of the longest run of
14
+ LA successes on a 0.01 grid within +-0.10 of the oracle speed (`la_speed`).
15
+ """
16
+ import argparse
17
+ import importlib
18
+ import json
19
+ import os
20
+ import pkgutil
21
+ import sys
22
+ import time
23
+
24
+ import numpy as np
25
+
26
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
27
+ sys.path.insert(0, ROOT)
28
+
29
+ from lffbench import arm_specs, envs # noqa: E402
30
+ from lffbench import tasks as task_pkg # noqa: E402
31
+ from lffbench.agent.robot_server import strip_axes # noqa: E402
32
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor # noqa: E402
33
+ from lffbench.task_base import TASKS # noqa: E402
34
+
35
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
36
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
37
+
38
+ OUT = os.path.join(ROOT, "runs", "api", "mismatch_20261027")
39
+ BANNED = ("com_offset", "com_total", "heavy_edge", "heavy_near", "pane_side", "_oracle", " mu ", "inst[")
40
+
41
+
42
+ def instances():
43
+ seen = {}
44
+ for m in ("opus", "sonnet"):
45
+ for key, d in json.load(open(os.path.join(OUT, m, "own.json"))).items():
46
+ src = json.load(open(d + ".source.json"))
47
+ start = json.loads(open(os.path.join(src["log"], "events.jsonl")).readline())
48
+ seen.setdefault(key, dict(task=src["task"], seed=src["seed"], logged=start["inst"], models=[]))
49
+ seen[key]["models"].append(m)
50
+ return seen
51
+
52
+
53
+ def same(a, b):
54
+ if isinstance(a, dict):
55
+ return isinstance(b, dict) and set(a) == set(b) and all(same(a[k], b[k]) for k in a)
56
+ if isinstance(a, (list, tuple)):
57
+ return isinstance(b, (list, tuple)) and len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))
58
+ if isinstance(a, float) or isinstance(b, float):
59
+ return abs(float(a) - float(b)) < 1e-9
60
+ return a == b
61
+
62
+
63
+ def la_move(task, ex, off, **args):
64
+ """one LA move_eef, as robot_server._handle_v2: absolute base-frame target, move then gripper"""
65
+ p = ex.proprio()
66
+ cur = np.asarray(p["eef_pos"], float) - off
67
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
68
+ tgt_w = np.asarray(tgt) + off
69
+ if any(k in args for k in ("x", "y", "z", "yaw")):
70
+ assert np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI), f"target rejected {tgt}"
71
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=float(args.get("yaw", p["eef_yaw_deg"])))
72
+ if args.get("speed") is not None:
73
+ mv["speed"] = float(args["speed"])
74
+ ex.call("move_to", mv)
75
+ if args.get("gripper"):
76
+ ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {})
77
+
78
+
79
+ def la_replay(task, inst, params):
80
+ """the Fix text of slide / tablecloth as LA commands; returns the outcome"""
81
+ task.reset_instance(inst)
82
+ sim = task.env.sim
83
+ off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy()
84
+ ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",))
85
+ zt = envs.TABLE_Z - off[2] # tabletop height in the base frame
86
+ v = float(params["speed"])
87
+ if task.name == "l5_slide_to_target":
88
+ x0, y0 = (np.asarray(inst["cube_xy"], float) - off[:2])
89
+ la_move(task, ex, off, gripper="close")
90
+ la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.12, yaw=0)
91
+ la_move(task, ex, off, x=x0 - 0.22, y=y0, z=zt + 0.02)
92
+ la_move(task, ex, off, x=x0 - 0.005, y=y0, z=zt + 0.02, speed=v)
93
+ la_move(task, ex, off, z=zt + 0.10, speed=0.3)
94
+ else:
95
+ from lffbench.tasks.l5_tablecloth_pull import B_HALF, BOARD, H_HALF
96
+ b = envs.obj_pos(task.env, BOARD) - off
97
+ hx, hy, zg = b[0] - B_HALF[0] + H_HALF[0], b[1], zt + 2 * B_HALF[2] + H_HALF[2]
98
+ la_move(task, ex, off, gripper="open")
99
+ la_move(task, ex, off, x=hx, y=hy, z=zg + 0.08, yaw=0)
100
+ la_move(task, ex, off, x=hx, y=hy, z=zg, gripper="close")
101
+ la_move(task, ex, off, x=hx - 0.25, y=hy, z=zg, speed=v, gripper="open")
102
+ la_move(task, ex, off, z=zg + 0.10, speed=0.3)
103
+ return task.outcome(inst)
104
+
105
+
106
+ def la_speed(task, inst, v0):
107
+ """middle of the longest run of LA-replay successes on a 0.01 grid around the oracle speed"""
108
+ from importlib import import_module
109
+ mod = import_module(type(task).__module__)
110
+ grid = [round(v, 2) for v in np.arange(round(v0 - 0.10, 2), round(v0 + 0.10, 2) + 1e-9, 0.01)
111
+ if mod.V_MIN <= v <= mod.V_MAX]
112
+ ok = [bool(la_replay(task, inst, dict(speed=v))["success"]) for v in grid]
113
+ best, run = [], []
114
+ for v, s in zip(grid, ok):
115
+ run = run + [v] if s else []
116
+ if len(run) > len(best):
117
+ best = run
118
+ if not best:
119
+ return None, dict(zip(map(str, grid), ok))
120
+ return best[len(best) // 2], dict(zip(map(str, grid), ok))
121
+
122
+
123
+ def main():
124
+ ap = argparse.ArgumentParser()
125
+ ap.add_argument("--out", default=os.path.join(ROOT, "results", "_ladder", "fix_validate.json"))
126
+ ap.add_argument("--only", default="")
127
+ a = ap.parse_args()
128
+ rows, tasks = [], {}
129
+ for key, it in sorted(instances().items()):
130
+ if a.only and it["task"] != a.only:
131
+ continue
132
+ t0 = time.time()
133
+ task = tasks.setdefault(it["task"], TASKS[it["task"]](cam_res=64))
134
+ inst = task.sample_instance(it["seed"])
135
+ clean = {k: v for k, v in inst.items() if not k.startswith("_")}
136
+ row = dict(key=key, models=it["models"], inst_matches_log=same(json.loads(json.dumps(clean, default=float)),
137
+ it["logged"]))
138
+ hist = task.run_scripted("oracle", inst, k=1)
139
+ params = hist[0]["params"]
140
+ row["oracle_success"] = bool(hist[0]["outcome"]["success"])
141
+ row["oracle_failure"] = hist[0]["outcome"].get("failure")
142
+ row["params"] = json.loads(json.dumps(params, default=float))
143
+ if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"):
144
+ v, sweep = la_speed(task, inst, float(params["speed"]))
145
+ row["oracle_speed"], row["la_sweep"] = float(params["speed"]), sweep
146
+ params = dict(params, speed=v if v is not None else float(params["speed"]))
147
+ row["params"] = json.loads(json.dumps(params, default=float))
148
+ text = arm_specs.fix(it["task"], clean, params)
149
+ row["fix"] = text
150
+ row["no_axis_labels"] = strip_axes(text) == text
151
+ row["no_internal_names"] = not any(b in text for b in BANNED)
152
+ if it["task"] in ("l5_slide_to_target", "l5_tablecloth_pull"):
153
+ out = la_replay(task, inst, params)
154
+ row["la_replay_success"] = bool(out["success"])
155
+ row["la_replay_failure"] = out.get("failure")
156
+ row["ok"] = bool(row["inst_matches_log"] and row["oracle_success"] and row["no_axis_labels"]
157
+ and row["no_internal_names"] and row.get("la_replay_success", True))
158
+ row["seconds"] = round(time.time() - t0, 1)
159
+ rows.append(row)
160
+ print(f"{'OK ' if row['ok'] else 'BAD'} {key:28s} oracle={row['oracle_success']} "
161
+ f"la={row.get('la_replay_success', '-')} inst={row['inst_matches_log']} ({row['seconds']}s)", flush=True)
162
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
163
+ json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(a.out, "w"), indent=1)
164
+ print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {a.out}")
165
+
166
+
167
+ if __name__ == "__main__":
168
+ main()
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pinned launch fingerprints (fail-closed launch, docs/15 §0.4).
2
+
3
+ A pin says: "harness <name> at version <v> (binary sha256 <b>) with model <m> and effort <e> sends exactly this preset
4
+ prompt and tool list" (the normalised fingerprint of the first request, see claude_code.request_fingerprint /
5
+ codex.request_fingerprint). Pins are written only by tests/harness_selfcheck/selfcheck.py --write-pins after every
6
+ offline check passed for that adapter; a launch without a matching pin is refused.
7
+
8
+ Only hashes and sizes are stored here (the repo is public); the full fingerprint of each launch is in the run's
9
+ harness_preflight.json.
10
+ """
11
+ import json
12
+ import os
13
+ import re
14
+ import time
15
+
16
+ PINS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pins")
17
+
18
+
19
+ def key(adapter, version, binary_sha, model, effort):
20
+ return f"{adapter}|{version}|{(binary_sha or 'nobin')[:16]}|{model}|{effort}"
21
+
22
+
23
+ def _path(k, pins_dir=None):
24
+ return os.path.join(pins_dir or PINS_DIR, re.sub(r"[^A-Za-z0-9.-]+", "_", k) + ".json")
25
+
26
+
27
+ def load(k, pins_dir=None):
28
+ p = _path(k, pins_dir)
29
+ if not os.path.exists(p):
30
+ return None
31
+ with open(p) as f:
32
+ return json.load(f)
33
+
34
+
35
+ def write(k, fingerprint_sha256, summary, pins_dir=None):
36
+ os.makedirs(pins_dir or PINS_DIR, exist_ok=True)
37
+ d = dict(key=k, fingerprint_sha256=fingerprint_sha256, written=time.strftime("%Y-%m-%d %H:%M:%S"), summary=summary)
38
+ with open(_path(k, pins_dir), "w") as f:
39
+ json.dump(d, f, indent=1)
40
+ return d
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LFF benchmark replay supplement: g56sol_canary_20261114
2
+
3
+ Source: completed evaluation runs in /mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_canary_20261114.
4
+ Immutable inventory and frozen matching source: /mnt/cpfs/workspace/agentic-robotics/ops/new_model_exports_20261115/inventories/gpt56.json.
5
+ Generated with `/usr/local/bin/python3 /mnt/cpfs/workspace/agentic-robotics/ops/new_model_exports_20261115/export_models.py` (started 2026-11-15 UTC).
6
+ LeRobot v3, 20 Hz, Franka Panda simulation, two 256x256 cameras.
7
+ Contains 1 runs, 3 episodes, 4142 frames; 84540409 bytes before manifest.
8
+ Success and failure episodes retained; model batches retain their original condition and dossier metadata.
9
+ All admitted runs pass server-code hash, instance, robot-report and outcome replay checks.
10
+ LeRobot reader validation: {"codebase_version": "v3.0", "episodes": 3, "frames": 4142, "plan_episodes": 3, "plan_frames": 4142, "samples": 60, "max_state_action_abs_err": 1.1748318140547553e-07, "max_mean_abs_pixel_err": 0.0, "status": "pass"}.
11
+ Replay rejections: /mnt/cpfs/workspace/agentic-robotics/ops/new_model_exports_20261115/exports/g56sol_canary_20261114/replay_rejections.json. Export-plan episode exclusions: /mnt/cpfs/workspace/agentic-robotics/ops/new_model_exports_20261115/exports/g56sol_canary_20261114/work/plan.json.
12
+ Incremental supplement only. Earlier versions remain unchanged. Development smoke/debug/pilot runs excluded.
leaf/release/source_packages/models-20261115-g56sol_compound2_20261114/lff/evaluation_evidence/workspace_exposure_audit.json ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checked_utc": "2026-11-14T21:05:01.852355+00:00",
3
+ "scope": "All model-visible tool events in 15 started runs; every shell command manually inspected; no shared workspace access observed. This is transcript evidence, not proof of old sandbox isolation.",
4
+ "runs": [
5
+ {
6
+ "task": "l7_offcenter_push",
7
+ "status": "done",
8
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_canary_20261114/g56sol_canary_20261114-gpt-5.6-sol-codex-harness-hidek_l7_offcenter_push_s3000_full_F1_direct_k3_1114-195251_p31100",
9
+ "transcript_sha256": "ff13e7dca12bb46335f3b32913392fc2a88360dc450c06e05afbc81dca5fe34d",
10
+ "shell_calls": [
11
+ {
12
+ "line": 23,
13
+ "arguments": {
14
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nimport numpy as np\nfor i in [0,7,8,9,10]:\n p='obs/s000_agentview.jpg' if i==0 else f'obs/s{i:03d}_agentview.jpg'\n a=np.array(Image.open(p))\n # brown: R moderately > G, G > B, within central tabletop\n m=(a[:,:,0]>90)&(a[:,:,0]<190)&(a[:,:,0]>a[:,:,1]*1.15)&(a[:,:,1]>a[:,:,2]*1.05)\n ys,xs=np.where(m)\n # central object pixels\n q=(xs>100)&(xs<400)&(ys>200)&(ys<380)\n print(i, (xs[q].min(),ys[q].min(),xs[q].max(),ys[q].max(),q.sum()) if q.any() else None)\nPY"
15
+ },
16
+ "result": null
17
+ },
18
+ {
19
+ "line": 27,
20
+ "arguments": {
21
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nimport numpy as np\nfor i in [0,7,10,13]:\n p='obs/s000_agentview.jpg' if i==0 else f'obs/s{i:03d}_agentview.jpg'\n a=np.array(Image.open(p))\n print('\\n',i)\n for xy in [(170,245),(170,260),(170,280),(220,245),(290,245),(150,300)]: print(xy,a[xy[1],xy[0]])\nPY"
22
+ },
23
+ "result": null
24
+ }
25
+ ],
26
+ "suspect_events": []
27
+ },
28
+ {
29
+ "task": "l5_slide_to_target",
30
+ "status": "done",
31
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_slide_to_target_s3000_full_F1_direct_k3_1114-200622_p31110",
32
+ "transcript_sha256": "00e5357f7e48705545f05ba71f9dd2f2feb94e7c014971a00038fec2e3e77411",
33
+ "shell_calls": [
34
+ {
35
+ "line": 5,
36
+ "arguments": {
37
+ "command": "python3 - <<'PY'\nimport cv2\nfor f in ['obs/s000_wrist.jpg','obs/s001_wrist.jpg','obs/s000_agentview.jpg']:\n im=cv2.imread(f)\n hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n # print rough color masks bbox\n masks={\n 'red': ((0,80,50),(10,255,255)),\n 'green': ((35,50,40),(90,255,255)),\n }\n print(f)\n for name,(lo,hi) in masks.items():\n m=cv2.inRange(hsv,lo,hi)\n n,lab,st,cent=cv2.connectedComponentsWithStats(m)\n comps=sorted([(s[4],tuple(s[:4]),tuple(c)) for s,c in zip(st[1:],cent[1:])],reverse=True)[:3]\n print(name,comps)\nPY"
38
+ },
39
+ "result": null
40
+ },
41
+ {
42
+ "line": 6,
43
+ "arguments": {
44
+ "command": "find . -maxdepth 3 -type f -not -path './obs/*' -print; du -sh obs"
45
+ },
46
+ "result": null
47
+ },
48
+ {
49
+ "line": 7,
50
+ "arguments": {
51
+ "command": "cat README.md"
52
+ },
53
+ "result": null
54
+ }
55
+ ],
56
+ "suspect_events": []
57
+ },
58
+ {
59
+ "task": "l5_tablecloth_pull",
60
+ "status": "done",
61
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_tablecloth_pull_s3000_full_F1_direct_k3_1114-200624_p31111",
62
+ "transcript_sha256": "9e47b3755fe735d26629665d1bb41417ef36ab8e321859e18e9c99a20c914daf",
63
+ "shell_calls": [
64
+ {
65
+ "line": 57,
66
+ "arguments": {
67
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor p in ['obs/a2_s001_agentview.jpg','obs/a2_s006_agentview.jpg']:\n im=cv2.imread(p)\n hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n red=( ((hsv[:,:,0]<10)|(hsv[:,:,0]>170)) & (hsv[:,:,1]>100) & (hsv[:,:,2]>80))\n green=((hsv[:,:,0]>35)&(hsv[:,:,0]<90)&(hsv[:,:,1]>50)&(hsv[:,:,2]>50))\n for name,m in [('red',red),('green',green)]:\n ys,xs=np.where(m)\n print(p,name,'bbox',xs.min(),ys.min(),xs.max(),ys.max(),'center',xs.mean(),ys.mean(),'n',len(xs))\nPY"
68
+ },
69
+ "result": null
70
+ }
71
+ ],
72
+ "suspect_events": []
73
+ },
74
+ {
75
+ "task": "l3_wall_flush",
76
+ "status": "done",
77
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_wall_flush_s3000_full_F1_direct_k3_1114-200626_p31112",
78
+ "transcript_sha256": "ee20e9a81ffc5893481e36b7c285b9ccbc9d24c2054eade0262f307f71da4844",
79
+ "shell_calls": [],
80
+ "suspect_events": []
81
+ },
82
+ {
83
+ "task": "l3_under_table_tool",
84
+ "status": "done",
85
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_under_table_tool_s3000_full_F1_direct_k3_1114-201615_p31113",
86
+ "transcript_sha256": "754dbfff9751f38dcd077ebb6b14dbbaf944520c26a86630b6fecedff25a2109",
87
+ "shell_calls": [
88
+ {
89
+ "line": 3,
90
+ "arguments": {
91
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor p in ['obs/s000_wrist.jpg','obs/s000_agentview.jpg']:\n im=cv2.imread(p); hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n # red low saturation due lighting; compare R dominance\n b,g,r=cv2.split(im)\n m=(r.astype(int)>g.astype(int)+25)&(r.astype(int)>b.astype(int)+25)&(r>90)\n n, lab, stats, cen=cv2.connectedComponentsWithStats(m.astype('uint8'))\n print(p, sorted([(stats[i,4],tuple(cen[i])) for i in range(1,n)], reverse=True)[:5])\nPY"
92
+ },
93
+ "result": null
94
+ },
95
+ {
96
+ "line": 5,
97
+ "arguments": {
98
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor p in ['obs/s000_wrist.jpg','obs/s001_wrist.jpg']:\n im=cv2.imread(p); b,g,r=cv2.split(im); m=(r.astype(int)>g.astype(int)+25)&(r.astype(int)>b.astype(int)+25)&(r>90)\n n,l,s,c=cv2.connectedComponentsWithStats(m.astype('uint8'))\n print(p, sorted([(int(s[i,4]),tuple(np.round(c[i],1))) for i in range(1,n)], reverse=True)[:5])\nPY"
99
+ },
100
+ "result": null
101
+ },
102
+ {
103
+ "line": 7,
104
+ "arguments": {
105
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor p in ['obs/s001_wrist.jpg','obs/s002_wrist.jpg']:\n im=cv2.imread(p); b,g,r=cv2.split(im); m=(r.astype(int)>g.astype(int)+25)&(r.astype(int)>b.astype(int)+25)&(r>90)\n n,l,s,c=cv2.connectedComponentsWithStats(m.astype('uint8'))\n print(p, sorted([(int(s[i,4]),tuple(np.round(c[i],1))) for i in range(1,n)], reverse=True)[:4])\nPY"
106
+ },
107
+ "result": null
108
+ }
109
+ ],
110
+ "suspect_events": []
111
+ },
112
+ {
113
+ "task": "l4_fit_container",
114
+ "status": "done",
115
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l4_fit_container_s3000_full_F1_direct_k3_1114-202316_p31111",
116
+ "transcript_sha256": "8310191cdcad297fa5684dd1d4551b7b45adeac1f47bb81a8c22fe6a1776d2c4",
117
+ "shell_calls": [],
118
+ "suspect_events": []
119
+ },
120
+ {
121
+ "task": "l7_key_turn",
122
+ "status": "done",
123
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l7_key_turn_s3001_full_F1_direct_k3_1114-202453_p31112",
124
+ "transcript_sha256": "06879853d29403f818c7778ef9f7916581c4725b137cf23d237defb0467443b0",
125
+ "shell_calls": [
126
+ {
127
+ "line": 26,
128
+ "arguments": {
129
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor f in ['obs/s008_agentview.jpg','obs/s009_agentview.jpg','obs/s011_agentview.jpg','obs/s012_agentview.jpg']:\n im=cv2.imread(f); hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n # yellow/gold\n m=cv2.inRange(hsv,np.array([15,80,80]),np.array([45,255,255]))\n n,lab,st,cen=cv2.connectedComponentsWithStats(m)\n inds=np.argsort(st[:,cv2.CC_STAT_AREA])[::-1]\n print(f)\n for i in inds[1:4]:\n if st[i,4]<10: continue\n ys,xs=np.where(lab==i); pts=np.c_[xs,ys].astype(np.float32)\n rect=cv2.minAreaRect(pts)\n print(' area',st[i,4],'bbox',st[i,:4].tolist(),'rect',rect)\nPY"
130
+ },
131
+ "result": null
132
+ },
133
+ {
134
+ "line": 27,
135
+ "arguments": {
136
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in range(3,13):\n f=f'obs/s{s:03d}_wrist.jpg'; im=cv2.imread(f)\n if im is None: continue\n hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(hsv,np.array([15,60,80]),np.array([45,255,255]))\n n,l,st,c=cv2.connectedComponentsWithStats(m)\n i=1+np.argmax(st[1:,4]); print(s, 'bbox', st[i,:4].tolist(), 'cent',c[i].round(1).tolist(),'area',st[i,4])\nPY"
137
+ },
138
+ "result": null
139
+ },
140
+ {
141
+ "line": 29,
142
+ "arguments": {
143
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nf='obs/s013_wrist.jpg'; im=cv2.imread(f); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,60,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); print(st[i,:4].tolist(),c[i].tolist(),st[i,4])\nPY"
144
+ },
145
+ "result": null
146
+ },
147
+ {
148
+ "line": 32,
149
+ "arguments": {
150
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [13,14,15]:\n im=cv2.imread(f'obs/s{s:03d}_wrist.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,60,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); print(s,c[i],st[i,:4])\nPY"
151
+ },
152
+ "result": null
153
+ },
154
+ {
155
+ "line": 35,
156
+ "arguments": {
157
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [16,17]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,80,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); r=cv2.minAreaRect(np.c_[xs,ys].astype('float32')); print(s,st[i,4],st[i,:4],r)\nPY"
158
+ },
159
+ "result": null
160
+ },
161
+ {
162
+ "line": 38,
163
+ "arguments": {
164
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [18,19]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,80,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,4],st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
165
+ },
166
+ "result": null
167
+ },
168
+ {
169
+ "line": 39,
170
+ "arguments": {
171
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nfor s in [15,16,18,19]:\n im=Image.open(f'obs/s{s:03d}_agentview.jpg')\n im.crop((270,255,370,340)).resize((600,510)).save(f'obs/crop{s}.png')\nPY"
172
+ },
173
+ "result": null
174
+ },
175
+ {
176
+ "line": 46,
177
+ "arguments": {
178
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [22,23]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,80,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,4],st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
179
+ },
180
+ "result": null
181
+ },
182
+ {
183
+ "line": 47,
184
+ "arguments": {
185
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nfor s in [20,21,22,23]: Image.open(f'obs/s{s:03d}_agentview.jpg').crop((270,255,370,340)).resize((600,510)).save(f'obs/crop{s}.png')\nPY"
186
+ },
187
+ "result": null
188
+ },
189
+ {
190
+ "line": 51,
191
+ "arguments": {
192
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [24,25]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,80,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,4],st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
193
+ },
194
+ "result": null
195
+ },
196
+ {
197
+ "line": 56,
198
+ "arguments": {
199
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [24,25,26,27]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m)\n print('\\n',s)\n for i in np.argsort(st[1:,4])[::-1][:3]+1:\n if st[i,4]<10:continue\n ys,xs=np.where(l==i); print(st[i,4],st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
200
+ },
201
+ "result": null
202
+ },
203
+ {
204
+ "line": 59,
205
+ "arguments": {
206
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [24,25,26,27,28]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
207
+ },
208
+ "result": null
209
+ },
210
+ {
211
+ "line": 65,
212
+ "arguments": {
213
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [31,32]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
214
+ },
215
+ "result": null
216
+ },
217
+ {
218
+ "line": 67,
219
+ "arguments": {
220
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [32,33]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,cv2.minAreaRect(np.c_[xs,ys].astype('float32')),st[i,:4])\nPY"
221
+ },
222
+ "result": null
223
+ },
224
+ {
225
+ "line": 72,
226
+ "arguments": {
227
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [35,36]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
228
+ },
229
+ "result": null
230
+ }
231
+ ],
232
+ "suspect_events": []
233
+ },
234
+ {
235
+ "task": "l2_turntable_restore",
236
+ "status": "done",
237
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l2_turntable_restore_s3000_full_F1_direct_k3_1114-203338_p31110",
238
+ "transcript_sha256": "4b427e6ad19bbb92dced14b973ebdd79b517ba14013792b8f6e2dd31af995b1c",
239
+ "shell_calls": [],
240
+ "suspect_events": []
241
+ },
242
+ {
243
+ "task": "l3_card_shelf",
244
+ "status": "done",
245
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_card_shelf_s3003_full_F1_direct_k3_1114-203509_p31113",
246
+ "transcript_sha256": "985885708df8a33f7a1648ad52eff88e9204483d79d5a1bdecd13ac7b59b37ae",
247
+ "shell_calls": [],
248
+ "suspect_events": []
249
+ },
250
+ {
251
+ "task": "l5_loaded_beam",
252
+ "status": "done",
253
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_loaded_beam_s3000_full_F1_direct_k3_1114-204811_p31112",
254
+ "transcript_sha256": "7420e004d8ecd689c883252ed81eba2f6956dc6b63e9acc50bb155c199b5a3c8",
255
+ "shell_calls": [],
256
+ "suspect_events": []
257
+ },
258
+ {
259
+ "task": "lh_lid_box",
260
+ "status": "running",
261
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_lid_box_s3000_full_F1_direct_k3_1114-204823_p31114",
262
+ "transcript_sha256": "77f95f0c13659c848307af71f71a9607d8f34afe119a50108117878001c13fda",
263
+ "shell_calls": [],
264
+ "suspect_events": []
265
+ },
266
+ {
267
+ "task": "lh_bridge",
268
+ "status": "running",
269
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_bridge_s3001_full_F1_direct_k3_1114-205050_p31111",
270
+ "transcript_sha256": "02819aa964a34d49c4a0f30add274d9a7db4875f945f3d742724e72cb72a8350",
271
+ "shell_calls": [],
272
+ "suspect_events": []
273
+ },
274
+ {
275
+ "task": "lh_tray_delivery",
276
+ "status": "running",
277
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_tray_delivery_s3000_full_F1_direct_k3_1114-205403_p31112",
278
+ "transcript_sha256": "b71b7a6e3c0c0ac5d66b4d7b88d8b7b5ad604dda669f610173608b47a9a7b1f6",
279
+ "shell_calls": [
280
+ {
281
+ "line": 53,
282
+ "arguments": {
283
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nfor n in ['obs/s027_agentview.jpg','obs/s019_agentview.jpg','obs/s013_agentview.jpg']:\n im=Image.open(n)\n im.crop((0,150,180,300)).resize((720,600)).save('/tmp/'+n.split('/')[-1])\nPY"
284
+ },
285
+ "result": null
286
+ },
287
+ {
288
+ "line": 55,
289
+ "arguments": {
290
+ "command": "mkdir -p zoom && cp /tmp/s*_agentview.jpg zoom/"
291
+ },
292
+ "result": null
293
+ },
294
+ {
295
+ "line": 56,
296
+ "arguments": {
297
+ "command": "mkdir -p zoom; python3 - <<'PY'\nfrom PIL import Image\nfor n in ['obs/s027_agentview.jpg','obs/s019_agentview.jpg','obs/s013_agentview.jpg']:\n im=Image.open(n)\n im.crop((0,150,180,300)).resize((720,600)).save('zoom/'+n.split('/')[-1])\nPY"
298
+ },
299
+ "result": null
300
+ }
301
+ ],
302
+ "suspect_events": []
303
+ },
304
+ {
305
+ "task": "lh_order_dispatch",
306
+ "status": "done",
307
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/runs/api/g56sol_compound2_20261114/g56sol_compound2_20261114-gpt-5.6-sol-codex-harness-hidek_lh_order_dispatch_s3000_full_F1_direct_k3_1114-200623_p31200",
308
+ "transcript_sha256": "4ce2827a409e84e064c3c86187728ddaf5376643c8d51aa48cdfd600af362b3c",
309
+ "shell_calls": [],
310
+ "suspect_events": []
311
+ },
312
+ {
313
+ "task": "lh_parts_cart",
314
+ "status": "running",
315
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/runs/api/g56sol_compound2_20261114/g56sol_compound2_20261114-gpt-5.6-sol-codex-harness-hidek_lh_parts_cart_s3000_full_F1_direct_k3_1114-205125_p31201",
316
+ "transcript_sha256": "c7a006004bbe587e4ed1c0b7f0b7152379007c2a7ee9dbfb5e300e4d4c3dcba3",
317
+ "shell_calls": [
318
+ {
319
+ "line": 50,
320
+ "arguments": {
321
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nimport numpy as np\nfor f in ['obs/s000_agentview.jpg','obs/s026_agentview.jpg','obs/s029_agentview.jpg']:\n a=np.array(Image.open(f))\n # print row 304 runs where brown tool-ish R 100-190 G70-160 B<80\n m=(a[:,:,0]>100)&(a[:,:,0]<210)&(a[:,:,1]>60)&(a[:,:,1]<170)&(a[:,:,2]<90)\n ys,xs=np.where(m)\n print(f, xs.min(),xs.max(),ys.min(),ys.max(), [(y,int((m[y]).sum())) for y in range(295,312) if m[y].sum()])\nPY"
322
+ },
323
+ "result": null
324
+ }
325
+ ],
326
+ "suspect_events": []
327
+ }
328
+ ]
329
+ }
leaf/release/source_packages/models-20261115-g56sol_compound2_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_compound2_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_compound2_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_compound2_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_compound2_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_compound2_20261114/lff/source_closure/lffbench/tasks/l4_nest.py ADDED
@@ -0,0 +1,644 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L4-C nest_order: nest three cups one inside another; the tallest cup is not the widest.
2
+
3
+ Scene: three open round cups (red, green, blue; 1.5 mm walls leaning outwards by TAPER_DEG = 5 deg, like slightly
4
+ flared tumblers) stand apart on the table. Each cup has its own bottom width and its own height (re-drawn per
5
+ instance, 3.5-10 cm tall). Cups are resized per instance by editing their geoms in sim.model (wall segments +
6
+ floor), so one env serves every instance (same technique as l4_fit_container).
7
+
8
+ Trap (common sense): "the bigger cup goes outside", and a cup looks big mostly by its height. On (1 - P_AGREE) of
9
+ the instances the tallest cup is the middle one by width: it is at least INV_DH = 3.5 cm taller than the widest cup.
10
+ Their openings then differ by only 3-9 mm in diameter, and from the wrist camera at its start height the taller
11
+ one's opening is closer to the camera and looks about as big (about half the instances: bigger); from the front
12
+ camera the taller one looks clearly bigger. The narrowest cup is the shortest, so the very first move of the naive
13
+ order (widest cup into the tallest one) already fails, out on the table.
14
+
15
+ A variant where the innermost cup was taller than the middle one (and the widest cup the tallest) was dropped
16
+ 2026-10-08: its failure (middle cup on the rim of the innermost cup, both inside the outer one) looked like a nest
17
+ from both cameras -- the same flaw as the 14-deg version.
18
+
19
+ What the failure looks like (the point of this version, user review 2026-10-08): which cup fits into which is
20
+ decided by the bottoms (same flare for all cups), and the sizes are drawn so that a cup whose bottom is too wide
21
+ does not go in at all -- it stays on the other cup's rim or wedges in the opening, its bottom at most STUCK_MAX
22
+ = 0.5 cm below the rim. So a wrong placement leaves a cup standing on top of another one, its whole body above the
23
+ rim: visible in both cameras without any text feedback. A cup that fits goes down to the floor (centring tolerance
24
+ >= TOL_MIN = 7.5 mm thanks to the flare); in the right nest the taller, narrower cups stick out of the shorter,
25
+ wider ones, but each stands inside the next.
26
+
27
+ Prior (naive): tallest cup outermost, then the next tallest. Learner: a cup that ended up on top of another cup
28
+ must go outside it; swap that pair. Feedback F1 (default) says only failed / succeeded; F2 (ablation) describes
29
+ which cup stands in / on which, in words, with no sizes or positions.
30
+
31
+ Only move_to / open / close are needed: grasp a cup across its upper wall, carry it over the other cup, release it
32
+ just above that cup's rim.
33
+ """
34
+ import itertools
35
+
36
+ import numpy as np
37
+
38
+ from .. import envs
39
+ from ..bddl import write_bddl
40
+ from ..objects import _SOLID, _fmt, _wrap, register_generated
41
+ from ..skills import _rot_err
42
+ from ..task_base import LFFTask, register_task
43
+
44
+ N_SEG = 20 # wall segments per cup (regular polygon)
45
+ TAN_SEG = float(np.tan(np.pi / N_SEG))
46
+ COS_SEG = float(np.cos(np.pi / N_SEG))
47
+ TAPER_DEG = 5.0 # wall lean (from vertical)
48
+ TAPER = float(np.radians(TAPER_DEG))
49
+ TT = float(np.tan(TAPER))
50
+ WALL_T = 0.0015 # wall thickness (normal to the wall)
51
+ WALL_TH = WALL_T / float(np.cos(TAPER)) # horizontal wall thickness
52
+ FLOOR_T = 0.003
53
+ Z0 = 0.0003 # walls start this far above the cup's underside (the floor disc carries the cup)
54
+ H_RANGE = (0.035, 0.100) # total cup height
55
+ RB_WIDE = (0.023, 0.030) # bottom outer apothem of the cup with the widest bottom
56
+ STEP = (0.0055, 0.0075) # bottom apothem difference between neighbours in the true order
57
+ RIM_MAX = 0.033 # outer apothem of the widest opening (gripper opens 7.9 cm)
58
+ CLEAR_MIN = 0.003 # radial gap (worst case) of a fitting cup standing on the other cup's floor
59
+ TOL_MIN = 0.0075 # a fitting cup goes in if its bottom lands within this of the other cup's axis
60
+ STUCK_MAX = 0.005 # a too-wide cup's bottom stops no deeper than this below the other cup's rim (5-deg walls
61
+ # self-lock: a cup pressed 1.2 cm into the opening wedged, and the narrow cup tipped over with it)
62
+ INV_DH = 0.035 # in the swapped pair the narrower cup is taller by at least this
63
+ KEEP_DH = 0.010 # in an unswapped pair the wider cup is taller by at least this
64
+ P_AGREE = 0.15 # share of instances whose height order is the right nesting order
65
+ SEAT_H = 0.010 # "standing on the floor": bottom less than this above the other cup's floor
66
+ SEAT_TILT = 15.0 # deg; a tall cup in a short, wider one can lean a little
67
+ WRIST_CAM_H = 0.367 # wrist camera height above the table at the start pose (measured 2026-10-08)
68
+ COLORS = {"red": (0.78, 0.22, 0.20, 1.0), "green": (0.28, 0.62, 0.32, 1.0), "blue": (0.22, 0.42, 0.80, 1.0)}
69
+ CUP_NAMES = ("cup_1", "cup_2", "cup_3")
70
+ DENSITY = 600.0
71
+ # execution
72
+ GRASP_BELOW_RIM = 0.012 # gripper site this far below the rim when grasping
73
+ Z_CARRY = envs.TABLE_Z + 0.24
74
+ DROP = 0.006 # held cup's bottom this far above the receiving rim at release
75
+ FINGER_CLEAR = 0.015 # gripper site at least this far above any rim around the target at release: fingers opened
76
+ # inside a taller outer cup press on its wall and carry it away on the way up (seed 1009, 2026-10-08)
77
+ PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35)
78
+ H_NOISE = 0.03 # relative noise of the blind policy's height judgement
79
+
80
+
81
+ # ---------------------------------------------------------------- cup geometry
82
+ def _quat_mul(a, b):
83
+ w1, x1, y1, z1 = a
84
+ w2, x2, y2, z2 = b
85
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
86
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
87
+
88
+
89
+ def _seg_quat(phi):
90
+ """segment frame: about z by phi, then tilted about its own y (tangential) axis by TAPER, so that its local z
91
+ (along the wall) leans outwards and its local x is the wall's outward normal"""
92
+ qz = np.array([np.cos(phi / 2), 0.0, 0.0, np.sin(phi / 2)])
93
+ qy = np.array([np.cos(TAPER / 2), 0.0, np.sin(TAPER / 2), 0.0])
94
+ return _quat_mul(qz, qy)
95
+
96
+
97
+ def seg_half_len(rb, H):
98
+ """tangential half length of a wall segment: one polygon side at the rim (+0.2 mm overlap)"""
99
+ return (rb + TT * H) * TAN_SEG + 0.0002
100
+
101
+
102
+ def rim_radius(rb, H):
103
+ """outer apothem of the opening"""
104
+ return rb + TT * H
105
+
106
+
107
+ def inner_radius(rb, z):
108
+ """inner apothem at height z above the cup's underside"""
109
+ return rb + TT * z - WALL_TH
110
+
111
+
112
+ def bottom_reach(rb, H):
113
+ """largest horizontal radius of the cup's outside at its bottom (the segment tips stick out a little beyond
114
+ the polygon because every segment is as wide as a rim-level polygon side)"""
115
+ return float(np.hypot(rb + TT * Z0, seg_half_len(rb, H)))
116
+
117
+
118
+ def fit_clearance(rb_in, H_in, rb_out):
119
+ """radial clearance (worst case over relative yaw) of cup `in` standing on the floor of cup `out`;
120
+ negative = does not go down to the floor. The flare is the same for both cups, so the bottom is the tightest
121
+ height."""
122
+ return inner_radius(rb_out, FLOOR_T) - bottom_reach(rb_in, H_in)
123
+
124
+
125
+ def centring_tol(rb_in, H_in, rb_out, H_out):
126
+ """how far (worst case) cup `in`'s bottom centre may be off cup `out`'s axis when it is lowered in at the rim
127
+ and still get inside (the flared wall then guides it down)"""
128
+ return inner_radius(rb_out, H_out) - bottom_reach(rb_in, H_in)
129
+
130
+
131
+ def stop_height(rb_in, rb_out, H_out):
132
+ """height (above cup `out`'s underside) where a too-wide cup `in`, lowered centred, stops: where its bottom
133
+ meets the sloping inner wall, or on the rim if that is higher than the cup"""
134
+ return min((rb_in - rb_out + WALL_TH) / TT, H_out)
135
+
136
+
137
+ def _cup_parts(rb, H):
138
+ """[(pos, half size, quat)] of the wall segments in the cup body frame (origin at mid height)."""
139
+ zc = (Z0 + H) / 2
140
+ hs = (H - Z0) / (2 * np.cos(TAPER))
141
+ rc = rb + TT * zc - WALL_T / 2 * np.cos(TAPER)
142
+ zz = zc + WALL_T / 2 * np.sin(TAPER) - H / 2
143
+ hl = seg_half_len(rb, H)
144
+ out = []
145
+ for k in range(N_SEG):
146
+ phi = 2 * np.pi * k / N_SEG
147
+ out.append(((rc * np.cos(phi), rc * np.sin(phi), zz), (WALL_T / 2, hl, hs), _seg_quat(phi)))
148
+ return out
149
+
150
+
151
+ def _floor_part(rb, H):
152
+ return (0.0, 0.0, -H / 2 + FLOOR_T / 2), (rb - 0.0003, FLOOR_T / 2, 0.0), np.array([1.0, 0.0, 0.0, 0.0])
153
+
154
+
155
+ def cup_xml(model_name, rgba):
156
+ """Open flared cup: N_SEG tilted wall boxes + a cylinder floor (sizes are overwritten per instance)."""
157
+ geoms = []
158
+ rb, H = RB_WIDE[1], H_RANGE[1]
159
+ for k, (p, s, q) in enumerate(_cup_parts(rb, H)):
160
+ geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" '
161
+ f'quat="{_fmt(q)}" rgba="{_fmt(rgba)}" density="{DENSITY:.0f}" friction="0.8 0.005 0.0001" '
162
+ f'{_SOLID} group="0" />')
163
+ geoms.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" quat="{_fmt(q)}" rgba="{_fmt(rgba)}" '
164
+ f'conaffinity="0" contype="0" group="1" />')
165
+ fp, fs, _ = _floor_part(rb, H)
166
+ geoms.append(f' <geom name="{model_name}_g{N_SEG}" type="cylinder" pos="{_fmt(fp)}" size="{_fmt(fs[:2])}" '
167
+ f'rgba="{_fmt(rgba)}" density="{DENSITY:.0f}" friction="0.8 0.005 0.0001" {_SOLID} group="0" />')
168
+ geoms.append(f' <geom type="cylinder" pos="{_fmt(fp)}" size="{_fmt(fs[:2])}" rgba="{_fmt(rgba)}" '
169
+ f'conaffinity="0" contype="0" group="1" />')
170
+ return _wrap(model_name, "\n".join(geoms), H / 2, rim_radius(rb, H) / COS_SEG)
171
+
172
+
173
+ def disable_midphase(env):
174
+ """The cups are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding
175
+ volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered
176
+ maximum size. A resized wall that lies outside its compiled leaf box is silently skipped: the gripper fingers
177
+ passed straight through the walls of the smaller cups (found 2026-10-07). Without the mid-phase MuJoCo tests all
178
+ geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set in _reshape_cup)."""
179
+ import mujoco
180
+ m = env.sim.model._model
181
+ m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
182
+
183
+
184
+ def kendall(a, b):
185
+ """number of pairs ordered differently in the two orders"""
186
+ pa, pb = {c: k for k, c in enumerate(a)}, {c: k for k, c in enumerate(b)}
187
+ return sum((pa[x] < pa[y]) != (pb[x] < pb[y]) for x, y in itertools.combinations(a, 2))
188
+
189
+
190
+ @register_task
191
+ class NestOrder(LFFTask):
192
+ name = "l4_nest_order"
193
+ level = "L4"
194
+ category = "geometry_inference"
195
+ capabilities = ("Perceive", "Reason", "Plan")
196
+ instruction = "Nest the red, green and blue cups one inside another."
197
+ instruction_indirect = "Put the three cups one inside another, like a set of nesting cups."
198
+
199
+ # ------------------------------------------------------------ scene
200
+ def make_bddl(self):
201
+ cats = [register_generated(f"LffNestCup{c.capitalize()}", cup_xml(f"lff_nest_cup_{c}", COLORS[c]))
202
+ for c in COLORS]
203
+ regions = [(-0.25, -0.15), (-0.05, 0.0), (-0.25, 0.15)]
204
+ objs = [(n, cat, f"{n}_region", (x - 0.01, y - 0.01, x + 0.01, y + 0.01))
205
+ for n, cat, (x, y) in zip(CUP_NAMES, cats, regions)]
206
+ return write_bddl(self.name, self.instruction, objs)
207
+
208
+ @staticmethod
209
+ def _heights_ok(case, h):
210
+ """h[s] = height of the cup with the s-th narrowest bottom (0 = innermost in the true nest)"""
211
+ if case == "agree": # taller = wider: the height order is the nesting order
212
+ return h[2] >= h[1] + KEEP_DH and h[1] >= h[0] + KEEP_DH
213
+ if case == "swap_wide": # the middle cup is the tallest, the narrowest one the shortest
214
+ return h[1] >= h[2] + INV_DH and h[2] >= h[0] + KEEP_DH
215
+ raise ValueError(case)
216
+
217
+ def sample_instance(self, seed):
218
+ rng = np.random.default_rng(seed)
219
+ u = rng.random()
220
+ case = "agree" if u < P_AGREE else "swap_wide"
221
+ for _ in range(200000):
222
+ heights = [float(rng.uniform(*H_RANGE)) for _ in range(3)] # by true size: 0 = narrowest bottom
223
+ if not self._heights_ok(case, heights):
224
+ continue
225
+ rb3 = float(rng.uniform(*RB_WIDE))
226
+ rb2 = rb3 - float(rng.uniform(*STEP))
227
+ rb1 = rb2 - float(rng.uniform(*STEP))
228
+ rbs = [rb1, rb2, rb3]
229
+ rims = [rim_radius(rb, h) for rb, h in zip(rbs, heights)]
230
+ if max(rims) > RIM_MAX:
231
+ continue
232
+ ok = True
233
+ for p, q in itertools.permutations(range(3), 2): # p into q
234
+ if p < q:
235
+ ok &= (fit_clearance(rbs[p], heights[p], rbs[q]) >= CLEAR_MIN
236
+ and centring_tol(rbs[p], heights[p], rbs[q], heights[q]) >= TOL_MIN)
237
+ else:
238
+ ok &= heights[q] - stop_height(rbs[p], rbs[q], heights[q]) <= STUCK_MAX
239
+ if ok:
240
+ break
241
+ else:
242
+ raise RuntimeError("could not sample cup sizes")
243
+ xy = []
244
+ while len(xy) < 3:
245
+ xy = []
246
+ for _k in range(3):
247
+ for _t in range(200):
248
+ p = [float(rng.uniform(-0.27, 0.02)), float(rng.uniform(-0.17, 0.17))]
249
+ if all(np.hypot(p[0] - q[0], p[1] - q[1]) >= 0.14 for q in xy):
250
+ xy.append(p)
251
+ break
252
+ # the colour is fixed per object (cup_1 red, cup_2 green, cup_3 blue: one generated class each); shuffle
253
+ # which object gets which size / height / position
254
+ perm = [int(i) for i in rng.permutation(3)] # perm[size index] = object slot
255
+ cups = [None] * 3
256
+ for s in range(3):
257
+ cups[perm[s]] = dict(name=CUP_NAMES[perm[s]], color=list(COLORS)[perm[s]], rb=rbs[s], height=heights[s],
258
+ rim=rims[s], xy=xy[s], size_rank=s)
259
+ order = sorted(range(3), key=lambda j: -cups[j]["rb"]) # outermost first (indices into cups)
260
+ naive = sorted(range(3), key=lambda j: -cups[j]["height"])
261
+ assert (naive == order) == (case == "agree"), (seed, case)
262
+ by = lambda s: perm[s] # noqa: E731 object index of size rank s
263
+ return dict(seed=int(seed), case=case, cups=cups, order=order, naive_order=naive,
264
+ bottom_cm=[round(200 * c["rb"], 2) for c in cups],
265
+ opening_cm=[round(200 * c["rim"], 2) for c in cups],
266
+ height_cm=[round(100 * c["height"], 2) for c in cups],
267
+ # relative size of each opening in the wrist camera at its start height (1 = largest)
268
+ wrist_apparent=[round(float(v), 3) for v in (lambda a: a / a.max())(np.array(
269
+ [c["rim"] / (WRIST_CAM_H - c["height"]) for c in cups]))],
270
+ clear_mm=[round(1000 * fit_clearance(rbs[s], heights[s], rbs[s + 1]), 2) for s in range(2)],
271
+ tol_mm=[round(1000 * centring_tol(rbs[s], heights[s], rbs[s + 1], heights[s + 1]), 2)
272
+ for s in range(2)],
273
+ # wrong neighbour pairs: how deep (cm) the wider cup's bottom gets below the narrower cup's rim
274
+ stuck_cm={f"{by(s + 1)}in{by(s)}": round(100 * (heights[s] - stop_height(
275
+ rbs[s + 1], rbs[s], heights[s])), 2) for s in range(2)})
276
+
277
+ def _reshape_cup(self, name, rb, H):
278
+ m = self.env.sim.model
279
+ o = self.env.objects_dict[name]
280
+ parts = _cup_parts(rb, H) + [_floor_part(rb, H)]
281
+ for names in (o.contact_geoms, o.visual_geoms):
282
+ assert len(names) == len(parts), (name, len(names))
283
+ for k, n in enumerate(names):
284
+ g = m.geom_name2id(n)
285
+ pos, size, quat = parts[k]
286
+ m.geom_pos[g] = pos
287
+ m.geom_size[g] = size
288
+ m.geom_quat[g] = quat
289
+ if k < N_SEG:
290
+ m.geom_rbound[g] = float(np.linalg.norm(size))
291
+ m.geom_aabb[g] = [0, 0, 0, *size]
292
+ else:
293
+ m.geom_rbound[g] = float(np.hypot(size[0], size[1]))
294
+ m.geom_aabb[g] = [0, 0, 0, size[0], size[0], size[1]]
295
+ # mass / inertia of the resized cup: conical shell + disc floor
296
+ bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])])
297
+ slant = (H - Z0) / np.cos(TAPER)
298
+ r_mid = rb + TT * (H + Z0) / 2
299
+ wall_m = DENSITY * 2 * np.pi * r_mid * WALL_T * slant
300
+ floor_m = DENSITY * np.pi * rb ** 2 * FLOOR_T
301
+ mass = wall_m + floor_m
302
+ # wall centroid height (from the underside): area-weighted, r grows linearly with z
303
+ r0, r1 = rb + TT * Z0, rb + TT * H
304
+ z_w = Z0 + (H - Z0) * (r0 + 2 * r1) / (3 * (r0 + r1))
305
+ z_cm = (wall_m * z_w + floor_m * FLOOR_T / 2) / mass
306
+ Izz = wall_m * r_mid ** 2 + floor_m * rb ** 2 / 2
307
+ Ixx = (wall_m * (r_mid ** 2 / 2 + (H - Z0) ** 2 / 12 + (z_w - z_cm) ** 2)
308
+ + floor_m * (rb ** 2 / 4 + (FLOOR_T / 2 - z_cm) ** 2))
309
+ m.body_mass[bid] = mass
310
+ m.body_inertia[bid] = [Ixx, Ixx, Izz]
311
+ m.body_ipos[bid] = [0.0, 0.0, z_cm - H / 2]
312
+ m.body_iquat[bid] = [1.0, 0.0, 0.0, 0.0]
313
+
314
+ def apply_instance(self, inst):
315
+ disable_midphase(self.env)
316
+ for c in inst["cups"]:
317
+ self._reshape_cup(c["name"], c["rb"], c["height"])
318
+ envs.set_obj_pose(self.env, c["name"], [*c["xy"], envs.TABLE_Z + c["height"] / 2 + 0.0005])
319
+
320
+ # ------------------------------------------------------------ state
321
+ def _cup_state(self, inst, j):
322
+ c = inst["cups"][j]
323
+ bid = envs.body_id(self.env, c["name"])
324
+ p = self.env.sim.data.body_xpos[bid].copy()
325
+ R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
326
+ tilt = float(np.degrees(np.arccos(np.clip(R[2, 2], -1, 1))))
327
+ bottom = p - R[:, 2] * c["height"] / 2 # centre of the floor's underside
328
+ rim = p + R[:, 2] * c["height"] / 2
329
+ return dict(p=p, tilt=tilt, bottom=bottom, rim=rim, floor_top=bottom[2] + FLOOR_T * R[2, 2])
330
+
331
+ def relations(self, inst):
332
+ """For each cup: which cup it stands in / on (if any), how high, seated or not."""
333
+ st = [self._cup_state(inst, j) for j in range(3)]
334
+ rel = []
335
+ for j in range(3):
336
+ sj = st[j]
337
+ best = None
338
+ for i in range(3):
339
+ if i == j:
340
+ continue
341
+ ci, si = inst["cups"][i], st[i]
342
+ if si["tilt"] > 45:
343
+ continue
344
+ d = float(np.hypot(*(sj["bottom"][:2] - si["p"][:2])))
345
+ if d > rim_radius(ci["rb"], ci["height"]) + 0.01:
346
+ continue # not above / in cup i
347
+ hb = float(sj["bottom"][2] - si["floor_top"]) # j's bottom above i's floor
348
+ # (the last test keeps a cup from being reported as standing in the cup it contains)
349
+ if hb < -0.004 or hb > ci["height"] + 0.02 or sj["bottom"][2] < si["bottom"][2] + FLOOR_T / 2:
350
+ continue
351
+ if best is None or hb < best[1]:
352
+ best = (i, hb, d)
353
+ if best is None:
354
+ on_table = sj["bottom"][2] < envs.TABLE_Z + 0.01 and sj["tilt"] < 30
355
+ rel.append(dict(cup=j, on=None, table=bool(on_table), tilt=sj["tilt"], xy=sj["p"][:2].tolist(),
356
+ fallen=bool(sj["tilt"] > 45)))
357
+ continue
358
+ i, hb, d = best
359
+ ci = inst["cups"][i]
360
+ seated = hb < SEAT_H and sj["tilt"] < SEAT_TILT
361
+ on_rim = hb > ci["height"] - FLOOR_T - 0.004
362
+ rel.append(dict(cup=j, on=i, height=hb, seated=bool(seated), on_rim=bool(on_rim), tilt=sj["tilt"],
363
+ offset=d, xy=sj["p"][:2].tolist(), fallen=bool(sj["tilt"] > 45)))
364
+ return rel
365
+
366
+ def outcome(self, inst):
367
+ envs.settle(self.env, 40)
368
+ cups = inst["cups"]
369
+ rel = self.relations(inst)
370
+ held = [j for j in range(3) if self.sk is not None and self.sk.holding(cups[j]["name"])]
371
+ col = [c["color"] for c in cups]
372
+ seated_in = {r["cup"]: r["on"] for r in rel if r.get("on") is not None and r["seated"]}
373
+ # success: a chain outer <- mid <- inner, all seated and upright, the outer cup standing on the table
374
+ success = False
375
+ for a, b, c in itertools.permutations(range(3)):
376
+ if seated_in.get(b) == a and seated_in.get(c) == b and _on_table_upright(rel, a):
377
+ success = True
378
+ success = bool(success and not held)
379
+ fb = dict(seated=[[j, i] for j, i in seated_in.items()], blocked=[], offcentre=[], held=held)
380
+ lines = []
381
+ res = dict(success=success, relations=rel, feedback=fb)
382
+ if held:
383
+ lines.append(f"The {col[held[0]]} cup is still in the gripper.")
384
+ if success:
385
+ a = [j for j in range(3) if j not in seated_in][0]
386
+ b = [j for j, i in seated_in.items() if i == a][0]
387
+ c = [j for j, i in seated_in.items() if i == b][0]
388
+ res["detail"] = (f"All three cups are nested: the {col[c]} cup stands inside the {col[b]} cup, "
389
+ f"which stands inside the {col[a]} cup.")
390
+ res["failure"] = None
391
+ return res
392
+ # bottom-up description
393
+ st = {r["cup"]: self._cup_state(inst, r["cup"]) for r in rel}
394
+ for r in sorted(rel, key=lambda r: st[r["cup"]]["bottom"][2]):
395
+ j = r["cup"]
396
+ if j in held:
397
+ continue
398
+ if r.get("on") is None:
399
+ if r["fallen"]:
400
+ lines.append(f"The {col[j]} cup has fallen over.")
401
+ elif r["table"]:
402
+ lines.append(f"The {col[j]} cup is standing on the table, not in another cup.")
403
+ else:
404
+ lines.append(f"The {col[j]} cup is neither standing on the table nor inside another cup.")
405
+ continue
406
+ i = r["on"]
407
+ if r["seated"]:
408
+ lines.append(f"The {col[j]} cup is inside the {col[i]} cup, standing on its bottom.")
409
+ continue
410
+ # did not go in. The text says only what a camera shows (no sizes); the structured field keeps the
411
+ # nominal verdict for the scripted learner
412
+ tilt = f", tilted about {r['tilt']:.0f} degrees" if r["tilt"] >= 8 else ""
413
+ if r["on_rim"]:
414
+ lines.append(f"The {col[j]} cup is sitting on the rim of the {col[i]} cup, not inside it{tilt}.")
415
+ else:
416
+ lines.append(f"The {col[j]} cup is stuck in the opening of the {col[i]} cup, not down inside "
417
+ f"it{tilt}.")
418
+ over = cups[j]["rb"] - cups[i]["rb"]
419
+ if over > 0:
420
+ fb["blocked"].append([j, i, round(100 * r["height"], 1)])
421
+ else:
422
+ fb["offcentre"].append([j, i, round(100 * r["height"], 1)])
423
+ res["detail"] = " ".join(lines) if lines else "The cups are not nested."
424
+ res["failure"] = "blocked" if fb["blocked"] else ("offcentre" if fb["offcentre"] else
425
+ ("held" if held else "incomplete"))
426
+ return res
427
+
428
+ # ------------------------------------------------------------ execution
429
+ def execute(self, inst, params):
430
+ """params: order = [outer, middle, inner] (indices into inst['cups']). Puts the middle cup into the outer
431
+ one; if it went in (judged from the scene, as an agent would see it), puts the inner cup into the middle
432
+ one. Optional (robustness checks): dxy = (dx, dy) release offset (m), drop (m), grasp_below (m),
433
+ carry_speed (m/s or None = as fast as the controller allows)."""
434
+ o, mid, inn = [int(v) for v in params["order"]]
435
+ ok = self._move_cup(inst, mid, o, params)
436
+ if ok:
437
+ self._move_cup(inst, inn, mid, params)
438
+ self.sk.move_to(list(PARK), yaw=0.0)
439
+
440
+ def _move_cup(self, inst, j, i, params):
441
+ sk = self.sk
442
+ sj = self._cup_state(inst, j)
443
+ x, y = sj["p"][:2]
444
+ rim = sj["rim"][2]
445
+ sk.set_gripper(False, steps=5)
446
+ sk.move_to([x, y, Z_CARRY], yaw=0.0)
447
+ sk.move_to([x, y, rim + 0.06], tol=0.004)
448
+ sk.move_to([x, y, rim - params.get("grasp_below", GRASP_BELOW_RIM)], tol=0.003)
449
+ sk.set_gripper(True, steps=15)
450
+ sk.move_to([x, y, Z_CARRY], speed=params.get("carry_speed", 0.3))
451
+ si = self._cup_state(inst, i)
452
+ dx, dy = params.get("dxy", (0.0, 0.0))
453
+ tx, ty = si["p"][0] + dx, si["p"][1] + dy
454
+ drop = params.get("drop", DROP)
455
+ sk.move_to([tx, ty, Z_CARRY], tol=0.004)
456
+ off = self._cup_state(inst, j)["bottom"] - sk.eef_pos()
457
+ # approach above the highest rim there (the target cup may stand inside a taller one)
458
+ top = max(s["rim"][2] for s in (self._cup_state(inst, q) for q in range(3) if q != j)
459
+ if np.hypot(s["p"][0] - tx, s["p"][1] - ty) < 0.04)
460
+ sk.move_to([tx - off[0], ty - off[1], max(top, si["rim"][2]) + drop + 0.03 - off[2]], tol=0.003)
461
+ z_rel = si["rim"][2] + drop
462
+ if top > si["rim"][2] + 0.002: # the target stands inside a taller cup: let go above that rim
463
+ z_rel = max(z_rel, top + FINGER_CLEAR - (inst["cups"][j]["height"]
464
+ - params.get("grasp_below", GRASP_BELOW_RIM)))
465
+ tgt = self._servo_cup(inst, j, [tx, ty], z_rel)
466
+ sk.grip = -1.0
467
+ self._hold_at(tgt, 12)
468
+ sk.move_to([tgt[0], tgt[1], Z_CARRY], speed=0.3)
469
+ envs.settle(self.env, 20)
470
+ r = [q for q in self.relations(inst) if q["cup"] == j][0]
471
+ return bool(r.get("on") == i and r["seated"])
472
+
473
+ def _hold_at(self, target, steps):
474
+ sk = self.sk
475
+ R = sk._R()
476
+ for _ in range(steps):
477
+ sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
478
+
479
+ def _servo_cup(self, inst, j, xy, z_bottom, max_steps=60, tol=0.0015):
480
+ """closed loop on the held cup's bottom centre (scripted policies only). Stops where the cup is held up
481
+ (a too-wide cup on / in another cup's rim) instead of pressing on: a person lets go there too, and
482
+ pressing on tips the cups over."""
483
+ sk = self.sk
484
+ R = sk._R()
485
+ goal = np.array([xy[0], xy[1], z_bottom])
486
+ tgt = e_prev = sk.eef_pos()
487
+ zs = []
488
+ for k in range(max_steps):
489
+ b, e = self._cup_state(inst, j)["bottom"], sk.eef_pos()
490
+ if k >= 8 and np.linalg.norm(b - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
491
+ break
492
+ zs.append(b[2])
493
+ if k >= 12 and b[2] - goal[2] > 0.003 and zs[-6] - b[2] < 0.0005:
494
+ return e # blocked: release here
495
+ tgt = goal - (b - e)
496
+ sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
497
+ e_prev = e
498
+ return tgt
499
+
500
+ # ------------------------------------------------------------ scripted policies
501
+ def default_params(self, inst):
502
+ """prior: the bigger-looking cup goes outside, and the cups look big by their height: tallest outermost"""
503
+ return dict(order=list(inst["naive_order"]))
504
+
505
+ def oracle_params(self, inst):
506
+ return dict(order=list(inst["order"]))
507
+
508
+ def blind_params(self, inst, attempt, rng):
509
+ """no history: the same height judgement again, with a little noise"""
510
+ est = [c["height"] * (1 + rng.normal(0, H_NOISE)) for c in inst["cups"]]
511
+ return dict(order=[int(i) for i in np.argsort(est)[::-1]])
512
+
513
+ @staticmethod
514
+ def constraints(history):
515
+ """pairs (outer, inner) implied by the F2 feedback of earlier attempts"""
516
+ pairs = set()
517
+ for h in history:
518
+ fb = h["outcome"].get("feedback") or {}
519
+ for j, i in fb.get("seated", []):
520
+ pairs.add((int(i), int(j))) # j sits in i -> i is outside j
521
+ for j, i, _ in fb.get("blocked", []):
522
+ pairs.add((int(j), int(i))) # j does not fit into i -> j must be outside i
523
+ for j, i, _ in fb.get("offcentre", []):
524
+ pairs.add((int(i), int(j))) # j would fit into i
525
+ return pairs
526
+
527
+ def adapt_params(self, inst, history):
528
+ """Scripted learner. It does not perceive the bottoms at all; it uses only which cup went into / stayed on
529
+ top of which (visible in the camera images; the structured part of the outcome): every such relation gives
530
+ an (outer, inner) pair; among the untried orders consistent with all pairs it takes the one closest (fewest
531
+ swapped pairs) to its prior, the height order; ties go to the larger height agreement."""
532
+ pairs = self.constraints(history)
533
+ rims = [c["height"] for c in inst["cups"]]
534
+ prior = list(inst["naive_order"])
535
+ tried = {tuple(h["params"]["order"]) for h in history if (h["outcome"].get("feedback") or {}).get("blocked")}
536
+ cands = []
537
+ for order in itertools.permutations(range(3)):
538
+ pos = {c: k for k, c in enumerate(order)}
539
+ consistent = all(pos[a] < pos[b] for a, b in pairs)
540
+ agree = sum(rims[order[k]] - rims[order[k + 1]] for k in range(2))
541
+ cands.append((consistent, tuple(order) not in tried, -kendall(order, prior), agree, order))
542
+ best = max(cands)
543
+ return dict(order=list(best[4]))
544
+
545
+ def random_order_params(self, inst, history, rng):
546
+ """sensitivity variant: a random order each retry, no history"""
547
+ return dict(order=[int(i) for i in rng.permutation(3)])
548
+
549
+ EXTRA_KINDS = ("random_order",)
550
+
551
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
552
+ if kind not in self.EXTRA_KINDS:
553
+ return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
554
+ k = k or self.max_attempts
555
+ rng = np.random.default_rng(seed)
556
+ history = []
557
+ for a in range(k):
558
+ self.reset_instance(inst)
559
+ params = self.default_params(inst) if a == 0 else self.random_order_params(inst, history, rng)
560
+ self.execute(inst, params)
561
+ out = self.outcome(inst)
562
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
563
+ if on_attempt:
564
+ on_attempt(a, params, out)
565
+ if out["success"]:
566
+ break
567
+ return history
568
+
569
+
570
+ def _on_table_upright(rel, j):
571
+ r = [q for q in rel if q["cup"] == j][0]
572
+ return r.get("on") is None and r["table"] and r["tilt"] < 8.0 and not r["fallen"]
573
+
574
+
575
+ # ---------------------------------------------------------------- physical validity checks
576
+ def physics_check(seed0=1000, n=8, out=None):
577
+ """All 6 orders on each instance; expect success iff the order is the true one."""
578
+ import json
579
+ task = NestOrder()
580
+ rows = []
581
+ for seed in range(seed0, seed0 + n):
582
+ inst = task.sample_instance(seed)
583
+ for order in itertools.permutations(range(3)):
584
+ task.reset_instance(inst)
585
+ task.execute(inst, dict(order=list(order)))
586
+ o = task.outcome(inst)
587
+ expect = list(order) == inst["order"]
588
+ # for a cup that did not go in: how far (cm) its bottom is below the other cup's rim
589
+ below_rim = [round(100 * (inst["cups"][r["on"]]["height"] - FLOOR_T - r["height"]), 2)
590
+ for r in o["relations"] if r.get("on") is not None and not r["seated"]]
591
+ rows.append(dict(seed=seed, case=inst["case"], order=list(order), success=o["success"], expect=expect,
592
+ failure=o["failure"], detail=o["detail"], below_rim_cm=below_rim,
593
+ clear_mm=inst["clear_mm"], tol_mm=inst["tol_mm"], bottom_cm=inst["bottom_cm"],
594
+ opening_cm=inst["opening_cm"], height_cm=inst["height_cm"]))
595
+ print(f"seed {seed} order {order} succ={o['success']} expect={expect} | {o['detail']}"
596
+ + ("" if o["success"] == expect else " <-- MISMATCH"), flush=True)
597
+ if out:
598
+ with open(out, "w") as f:
599
+ json.dump(rows, f, indent=1)
600
+ print("total", len(rows), "mismatches", sum(r["success"] != r["expect"] for r in rows))
601
+ return rows
602
+
603
+
604
+ def robustness_check(seed0=1000, n=6, out=None):
605
+ """True order with execution errors: release off-centre (both moves) by 0-9 mm in a random direction, released
606
+ 3 cm above the rim, grasped lower, carried at full controller speed."""
607
+ import json
608
+ task = NestOrder()
609
+ rows = []
610
+ cases = [("centred", {}), ("off3", dict(off=0.003)), ("off5", dict(off=0.005)), ("off7", dict(off=0.007)),
611
+ ("off9", dict(off=0.009)), ("drop3cm", dict(drop=0.03)), ("off4_drop3cm", dict(off=0.004, drop=0.03)),
612
+ ("grasp2cm", dict(grasp_below=0.02)), ("fast_carry", dict(carry_speed=None))]
613
+ for seed in range(seed0, seed0 + n):
614
+ inst = task.sample_instance(seed)
615
+ rng = np.random.default_rng(seed)
616
+ for name, c in cases:
617
+ a = rng.uniform(0, 2 * np.pi)
618
+ off = c.get("off", 0.0)
619
+ params = dict(order=list(inst["order"]), dxy=(off * np.cos(a), off * np.sin(a)))
620
+ params.update({k: v for k, v in c.items() if k != "off"})
621
+ task.reset_instance(inst)
622
+ task.execute(inst, params)
623
+ o = task.outcome(inst)
624
+ rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"], tol_mm=inst["tol_mm"],
625
+ height_cm=inst["height_cm"]))
626
+ print(f"seed {seed} {name:13s} succ={o['success']} | {o['detail']}", flush=True)
627
+ if out:
628
+ with open(out, "w") as f:
629
+ json.dump(rows, f, indent=1)
630
+ for name, _ in cases:
631
+ r = [x["success"] for x in rows if x["case"] == name]
632
+ print(f"{name:13s} {sum(r)}/{len(r)}")
633
+ return rows
634
+
635
+
636
+ if __name__ == "__main__":
637
+ # python -m lffbench.tasks.l4_nest physics results/l4_nest_order/physics_check.json [n]
638
+ # python -m lffbench.tasks.l4_nest robust results/l4_nest_order/robustness_check.json [n]
639
+ import sys
640
+ n_arg = int(sys.argv[3]) if len(sys.argv) > 3 else None
641
+ if sys.argv[1] == "physics":
642
+ physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 8)
643
+ elif sys.argv[1] == "robust":
644
+ robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=n_arg or 6)