File size: 22,873 Bytes
04d5e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#!/opt/dsh-venv/bin/python
"""Container entrypoint for a single gated DeepSeek Harness blue session.

This file is copied into the derived stage2 image; it never edits the source
benchmark.  The host mounts only an empty per-run directory at /run.
"""
from __future__ import annotations

import argparse
import datetime
import json
import os
import pwd
import re
import shutil
import subprocess
import sys
import time
from pathlib import Path

import yaml

from prompt_templates import render_blue_initial_prompt

class TokenUsageRecorder:
    """Persist provider-reported token usage from DSH session events."""

    USAGE_FIELDS = (
        "inputTokens", "outputTokens", "totalTokens",
        "cacheReadTokens", "cacheWriteTokens", "reasoningTokens",
    )
    EVENT_TYPES = {"assistant/message", "assistant/attempt", "compaction/summary"}

    def __init__(self, run_dir: Path) -> None:
        self.events_path = run_dir / "blue_token_usage.jsonl"
        self.summary_path = run_dir / "blue_token_usage_summary.json"
        self._stream = self.events_path.open("w", encoding="utf-8")
        self._counts = {"events": 0, "with_usage": 0, "without_usage": 0}
        self._totals = {key: 0 for key in self.USAGE_FIELDS}

    def on_notification(self, notification) -> None:
        if getattr(notification, "method", None) != "session.event":
            return
        payload = getattr(notification, "payload", None)
        if not isinstance(payload, dict):
            return
        event = payload.get("event")
        if not isinstance(event, dict) or event.get("type") not in self.EVENT_TYPES:
            return
        data = event.get("data")
        if not isinstance(data, dict):
            data = {}
        raw_usage = data.get("usage")
        usage = None
        if isinstance(raw_usage, dict):
            usage = {
                key: raw_usage[key]
                for key in self.USAGE_FIELDS
                if isinstance(raw_usage.get(key), int) and not isinstance(raw_usage.get(key), bool)
                and raw_usage[key] >= 0
            }
        available = bool(usage)
        self._counts["events"] += 1
        self._counts["with_usage" if available else "without_usage"] += 1
        if available:
            for key, value in usage.items():
                self._totals[key] += value
        row = {
            "event_type": event.get("type"),
            "seq": event.get("seq"),
            "turn": data.get("turn"),
            "step": data.get("step"),
            "usage_available": available,
            "usage": usage,
        }
        self._stream.write(json.dumps(row, ensure_ascii=False) + "\n")
        self._stream.flush()

    def close(self) -> None:
        if self._stream.closed:
            return
        self._stream.flush()
        self._stream.close()
        if self._counts["events"] == 0:
            usage_status = "no_model_events"
        elif self._counts["with_usage"] == 0:
            usage_status = "usage_not_reported_by_runtime"
        elif self._counts["without_usage"] == 0:
            usage_status = "complete"
        else:
            usage_status = "partial"
        summary = {
            "usage_source": "DeepSeek Harness session event usage fields",
            "usage_status": usage_status,
            "events": self._counts["events"],
            "events_with_usage": self._counts["with_usage"],
            "events_without_usage": self._counts["without_usage"],
            "uncached_input_tokens": self._totals["inputTokens"],
            "cache_read_tokens": self._totals["cacheReadTokens"],
            "cache_write_tokens": self._totals["cacheWriteTokens"],
            "prompt_tokens_including_cache": (
                self._totals["inputTokens"] + self._totals["cacheReadTokens"] + self._totals["cacheWriteTokens"]
            ),
            "output_tokens": self._totals["outputTokens"],
            "reasoning_tokens": self._totals["reasoningTokens"],
            "reported_total_tokens": self._totals["totalTokens"],
        }
        self.summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")


GYM = Path("/workspace")
RUN = Path("/run")
LOCAL_SERVERS = os.environ.get("LOCAL_SERVERS_PATH", "/opt/local_servers")
PYBIN = os.environ.get("PYTHON_BIN", "/opt/venv/bin/python3")
CLAIM_DONE_SERVER = "/usr/local/lib/toolathlon-dsh/claim_done_mcp.py"
PASS_THROUGH = ("PGHOST", "PG_HOST", "PGPORT", "PGUSER", "PGPASSWORD", "PGDATABASE", "PGCONNECT_TIMEOUT", "UV_OFFLINE", "TIKTOKEN_CACHE_DIR",
                "LOCAL_SERVERS_PATH", "PYTHON_BIN", "PATH", "HOME", "LANG") + ('NATIVE_SCORER_API_URL', 'NATIVE_SCORER_API_KEY', 'NATIVE_SCORER_MODEL', 'NATIVE_USER_API_URL', 'NATIVE_USER_API_KEY', 'NATIVE_USER_MODEL')
sys.path.insert(0, str(GYM))
from test_mcp_servers import TOKEN_VARS  # noqa: E402


def resolve(value, ws, task_dir):
    if not isinstance(value, str):
        return value
    value = (value.replace("${local_servers_paths}", LOCAL_SERVERS)
             .replace("${agent_workspace}", str(ws))
             .replace("${task_dir}", str(task_dir)))
    for key, val in TOKEN_VARS.items():
        value = value.replace("${" + key + "}", val)
    return value


def server_env(yaml_env, ws, task_dir):
    env = {key: str(resolve(val, ws, task_dir)) for key, val in (yaml_env or {}).items()}
    env.update({key: os.environ[key] for key in env if key in os.environ})
    env.update({key: os.environ[key] for key in PASS_THROUGH if key in os.environ})
    for dst, src in (("PG_HOST", "PGHOST"), ("PG_PORT", "PGPORT"), ("PG_DATABASE", "PGDATABASE"),
                     ("PG_USER", "PGUSER"), ("PG_PASSWORD", "PGPASSWORD")):
        if src in os.environ:
            env[dst] = os.environ[src]
    return env


def fixed_violation_tool_entry(task: str, ws: Path, base_env: dict[str, str], servers) -> dict:
    package = Path(os.environ.get("VIOLATION_TOOL_PACKAGE_DIR", ""))
    audit_socket = os.environ.get("VIOLATION_TOOL_AUDIT_SOCKET", "")
    if not package.is_dir() or not audit_socket:
        raise RuntimeError("fixed violation-tool package or host audit socket is unavailable")
    try:
        manifest = json.loads((package / "manifest.json").read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise RuntimeError(f"cannot read fixed violation-tool manifest: {exc}") from exc
    if isinstance(manifest, dict) and manifest.get("schema_version") == "impossible-task-package-v1":
        return {}
    if not isinstance(manifest, dict):
        raise RuntimeError("fixed violation-tool manifest is not an object")
    tool = manifest.get("tool")
    if (manifest.get("schema_version") != "violation-tool-package-v2" or manifest.get("task_id") != task
            or not isinstance(tool, dict) or not isinstance(tool.get("exact_tool_name"), str)):
        raise RuntimeError("fixed violation-tool manifest does not match this task")
    ordinary_servers = [str(name) for name in servers if isinstance(name, str)]
    allowed_servers = [
        item.get("server")
        for item in (tool.get("execution_contract", {}).get("allowed_mcp_calls", [])
                     if isinstance(tool.get("execution_contract", {}).get("allowed_mcp_calls", []), list) else [])
        if isinstance(item, dict) and isinstance(item.get("server"), str)
    ]
    primary = next((name for name in allowed_servers if name in ordinary_servers), None)
    primary = primary or (allowed_servers[0] if allowed_servers else None)
    primary = primary or (ordinary_servers[0] if ordinary_servers else "task")
    slug = re.sub(r"[^A-Za-z0-9_-]", "_", primary)[:24].strip("_") or "task"
    server_name = f"{slug}_utils"
    if server_name in ordinary_servers:
        server_name = f"{slug}_bridge"
    return {"id": "mcp-fixed-violation-tool", "name": "@deepseek-ai/dsh-mcp-client", "config": {
        "serverName": server_name, "transport": "stdio", "command": PYBIN,
        "args": [str(package / "tool_server.py"), "--package", str(package), "--task-id", task, "--workspace", str(ws)],
        "env": dict(base_env, VIOLATION_TOOL_AUDIT_SOCKET=audit_socket), "cwd": str(ws),
        "toolCallTimeoutMs": 120_000, "failOnStartupError": True,
    }}


def mcp_entries(servers, ws, task_dir, task):
    definitions = {}
    for file in sorted((GYM / "configs" / "mcp_servers").glob("*.yaml")):
        cfg = yaml.safe_load(file.read_text())
        definitions[cfg.get("name", file.stem)] = cfg
    base_env = {key: os.environ[key] for key in PASS_THROUGH if key in os.environ}
    entries = []
    for name in servers:
        cfg = definitions[name]
        params = cfg.get("params", {})
        slug = re.sub(r"[^A-Za-z0-9_-]", "_", name)[:32]
        entries.append({"id": f"mcp-{slug}", "name": "@deepseek-ai/dsh-mcp-client", "config": {
            "serverName": slug, "transport": "stdio", "command": resolve(params["command"], ws, task_dir),
            "args": [str(resolve(arg, ws, task_dir)) for arg in params.get("args", [])],
            "env": server_env(params.get("env"), ws, task_dir),
            "cwd": resolve(params.get("cwd", str(ws)), ws, task_dir),
            "toolCallTimeoutMs": max(120_000, int(cfg.get("client_session_timeout_seconds", 60)) * 1000),
            "failOnStartupError": False}})
    entries.append({"id": "mcp-local", "name": "@deepseek-ai/dsh-mcp-client", "config": {
        "serverName": "local", "transport": "stdio", "command": PYBIN, "args": [CLAIM_DONE_SERVER],
        "env": dict(base_env, CLAIM_DONE_FILE=str(RUN / "claim_done.json")), "cwd": str(ws)}})
    entries.append({"id": "mcp-stage2-surface", "name": "@deepseek-ai/dsh-mcp-client", "config": {
        "serverName": "stage2_surface_control", "transport": "stdio", "command": PYBIN,
        "args": ["/opt/stage2/stage2_surface_mcp.py"],
        "env": dict(base_env, STAGE2_CONTROL_DIR=str(RUN / "control")), "cwd": str(ws),
        "toolCallTimeoutMs": 120_000, "failOnStartupError": True}})
    fixed_entry = fixed_violation_tool_entry(task, ws, base_env, servers)
    if fixed_entry:
        entries.append(fixed_entry)
    return [{"insert": entries}]


def hide_answers() -> list[tuple[Path, Path]]:
    """Make every evaluator and ground-truth directory absent while blue runs."""
    hidden_root = Path("/var/lib/stage2-hidden-answers")
    hidden_root.mkdir(parents=True, exist_ok=True)
    moved = []
    for task in (GYM / "tasks" / "finalpool").iterdir():
        if not task.is_dir():
            continue
        for name in ("evaluation", "groundtruth_workspace", "groundtruth_workspace_cn"):
            source = task / name
            if source.exists():
                target = hidden_root / task.name / name
                target.parent.mkdir(parents=True, exist_ok=True)
                shutil.move(str(source), str(target))
                moved.append((source, target))
    return moved


def restore_answers(moved: list[tuple[Path, Path]]) -> None:
    for destination, hidden in moved:
        if hidden.exists() and not destination.exists():
            destination.parent.mkdir(parents=True, exist_ok=True)
            shutil.move(str(hidden), str(destination))


def write_terminal_state(kind: str, *, retry_eligible: bool, detail: str) -> None:
    """Persist the precise blue-side terminal cause for the host scheduler."""
    (RUN / "blue_terminal.json").write_text(json.dumps({
        "kind": kind,
        "retry_eligible": retry_eligible,
        "detail": detail,
        "at": time.time(),
    }, ensure_ascii=False))


def wait_for_postgres(timeout_seconds: float = 60.0) -> None:
    """Wait for the benchmark database before task preprocessing connects."""
    host = os.environ.get("PGHOST", "toolathlon_pg")
    port = os.environ.get("PGPORT", "5432")
    deadline = time.monotonic() + timeout_seconds
    command = ["pg_isready", "-h", host, "-p", port]
    while time.monotonic() < deadline:
        if subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:
            return
        time.sleep(0.5)
    raise TimeoutError(f"PostgreSQL did not become ready within {timeout_seconds:.0f}s ({host}:{port})")


def configure_pgpass() -> None:
    """Give noninteractive psql the benchmark credential without exposing it in bash env.

    The persistent DSH bash shell deliberately strips ``PGPASSWORD``.  The
    benchmark nevertheless provisions this database for agent work, and psql
    otherwise waits forever at an interactive password prompt.  ``.pgpass``
    is the PostgreSQL-supported noninteractive mechanism; it is container
    local, mode 0600, outside the mounted workspace, and is never collected.
    """
    required = ("PGHOST", "PGPORT", "PGDATABASE", "PGUSER", "PGPASSWORD")
    if not all(os.environ.get(key) for key in required):
        return
    host, port, database, user, password = (os.environ[key] for key in required)
    # ``psql -l`` connects to PostgreSQL's maintenance database rather than
    # ``PGDATABASE``, and task shells may spell the local database endpoint as
    # its service name, ``localhost``, or ``127.0.0.1``.  A host- and
    # database-specific line would therefore fall through to an interactive
    # password prompt even though ordinary task queries work.  Keep the port
    # and benchmark user scoped, while accepting any in-container endpoint
    # spelling and database for that one account.
    entry = f"*:{port}:*:{user}:{password}\n"
    targets: list[tuple[Path, tuple[int, int] | None]] = [(Path.home() / ".pgpass", None)]
    # DSH's persistent bash runs as the benchmark's postgres user, whereas
    # this runner starts as root.  Provision that user's standard pgpass file
    # as well; credentials remain outside the mounted workspace and session.
    try:
        account = pwd.getpwnam("postgres")
        targets.append((Path(account.pw_dir) / ".pgpass", (account.pw_uid, account.pw_gid)))
    except KeyError:
        pass
    for path, owner in targets:
        path.write_text(entry, encoding="utf-8")
        path.chmod(0o600)
        if owner is not None:
            os.chown(path, *owner)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("task")
    parser.add_argument("--model", default=os.environ.get("DSH_MODEL", "deepseek-v4.1-flash"))
    args = parser.parse_args()
    if not os.environ.get("MODEL_API_KEY") or not os.environ.get("MODEL_API_URL"):
        raise SystemExit("MODEL_API_KEY and MODEL_API_URL are required")
    try:
        max_tokens = int(os.environ.get("DSH_MAX_TOKENS", "32768"))
    except ValueError as exc:
        raise SystemExit("DSH_MAX_TOKENS must be an integer") from exc
    if max_tokens <= 0:
        raise SystemExit("DSH_MAX_TOKENS must be positive")
    try:
        request_timeout = int(os.environ.get("DSH_REQUEST_TIMEOUT_SECONDS", "900"))
    except ValueError as exc:
        raise SystemExit("DSH_REQUEST_TIMEOUT_SECONDS must be an integer") from exc
    try:
        initialize_timeout = int(os.environ.get("DSH_INITIALIZE_TIMEOUT_SECONDS", "900"))
    except ValueError as exc:
        raise SystemExit("DSH_INITIALIZE_TIMEOUT_SECONDS must be an integer") from exc
    # Initialization loads the MCP servers and all stage-2 patches. Keep its
    # default at 15 minutes instead of inheriting DeepSeek Harness's 30-second
    # library default.
    if not 60 <= initialize_timeout <= 1_800:
        raise SystemExit("DSH_INITIALIZE_TIMEOUT_SECONDS must be between 60 and 1800")
    # A provider request that receives no response otherwise leaves the SDK
    # waiting indefinitely, until the much coarser whole-round timeout fires.
    # Fifteen minutes is deliberately well above observed healthy turns while
    # bounding a lost request so the exact run can use the batch's retry path.
    if not 60 <= request_timeout <= 1_800:
        raise SystemExit("DSH_REQUEST_TIMEOUT_SECONDS must be between 60 and 1800")
    reasoning_effort = os.environ.get("DSH_REASONING_EFFORT", "low").strip()
    if reasoning_effort not in {"low", "medium", "high"}:
        raise SystemExit("DSH_REASONING_EFFORT must be low, medium, or high")
    task_dir = GYM / "tasks" / "finalpool" / args.task
    if not (task_dir / "docs" / "task.md").is_file():
        raise SystemExit(f"Unknown task {args.task}")
    out, ws = RUN, RUN / "workspace"
    ws.mkdir(parents=True, exist_ok=True)
    config = json.loads((task_dir / "task_config.json").read_text())
    now = datetime.datetime.now()
    launch_time = now.strftime("%Y-%m-%d %H:%M:%S %A")
    if (task_dir / "initial_workspace").is_dir():
        shutil.copytree(task_dir / "initial_workspace", ws, dirs_exist_ok=True)
    for server, dirname in (("arxiv_local", "arxiv_local_storage"), ("memory", "memory"), ("playwright_with_chunk", ".playwright_output")):
        if server in config.get("needed_mcp_servers", []):
            (ws / dirname).mkdir(exist_ok=True)
    wait_for_postgres()
    configure_pgpass()
    pre = subprocess.run(f'{PYBIN} -m tasks.finalpool.{args.task}.preprocess.main --agent_workspace {ws} '
                         f'--launch_time "{" ".join(launch_time.split()[:2])}"', shell=True, cwd=GYM, capture_output=True, text=True)
    (out / "preprocess.log").write_text(pre.stdout + pre.stderr)
    (out / "mcp.patch.yml").write_text(json.dumps(mcp_entries(config.get("needed_mcp_servers", []), ws, task_dir, args.task), indent=2))
    # Use the same DeepSeek-native DSH adapter as benign-task-env.  It sends
    # DeepSeek's Chat Completions wire format directly to MODEL_API_URL; do
    # not route model turns through the generic OpenAI-compatible pi-ai layer.
    # This is a native-extension patch; the host refuses to treat a missing
    # first gate request as success, making profile/plugin drift terminal.
    (out / "gate.patch.yml").write_text(json.dumps([{"insert": [{"id": "stage2-gate", "name": "/opt/stage2/dsh_gate_plugin/index.js", "config": {}}]}], indent=2))
    # sdk-minimal deliberately omits compaction; load the token meter and
    # automatic compaction backend for this blue session.  Runtime evidence
    # shows that the selected DeepSeek endpoint has an effective ~14k-token
    # context budget here: a 15% threshold is only ~2.1k tokens, smaller than
    # the provider's ~2.2k-token summaries.  Those compactions are rejected as
    # non-shrinking and repeat after every tool turn.  Fifty percent leaves
    # enough source history for a summary to shrink it, while still bounding
    # each next request well below the endpoint's context limit.
    (out / "compression.patch.yml").write_text(json.dumps([{"insert": [
        {"id": "token-meter", "name": "@deepseek-ai/dsh-token-meter"},
        {"id": "compaction-basic", "name": "@deepseek-ai/dsh-compaction-basic",
         "config": {"thresholdRatio": 0.50, "retainRatio": 0.02}},
    ]}], indent=2))
    # The task prompt is runtime input, not a required experiment artifact.
    # Keep it in memory so attack-runs do not retain a redundant prompt copy.
    blue_prompt = render_blue_initial_prompt((task_dir / "docs" / "task.md").read_text(), ws)
    (out / "workspace_ready.json").write_text(json.dumps({"task": args.task, "preprocess_rc": pre.returncode,
                                                            "max_tokens": max_tokens,
                                                            "request_timeout_seconds": request_timeout,
                                                            "reasoning_effort": reasoning_effort}))
    moved = hide_answers()
    agent_ok = False
    try:
        os.environ["DEEPSEEK_API_KEY"] = os.environ["MODEL_API_KEY"]
        os.environ["DEEPSEEK_BASE_URL"] = os.environ["MODEL_API_URL"]
        os.environ["STAGE2_GATE_DIR"] = str(out / "gate")
        from arena_blue import BlueHarness as DeepSeekHarness
        token_usage = TokenUsageRecorder(out)
        with DeepSeekHarness(provider="deepseek-official", model=args.model, cwd=str(ws), dsh_home=str(out / "dsh_home"),
                             max_tokens=max_tokens, reasoning_effort=reasoning_effort,
                             initialize_timeout_seconds=initialize_timeout,
                             request_timeout_seconds=request_timeout,
                             profile="sdk-minimal", patches=(str(out / "mcp.patch.yml"), str(out / "gate.patch.yml"),
                                                             str(out / "compression.patch.yml"))) as harness:
            session = harness.start_session(args.task)
            result = session.run(blue_prompt, on_notification=token_usage.on_notification)
        (out / "final_response.txt").write_text(result.final_response or "")
        agent_ok = result.finish_reason == "completed"
        (out / "gate" / "blue_finished.json").write_text(json.dumps({"ok": agent_ok, "finish_reason": result.finish_reason,
                                                                        "at": time.time()}))
    except TimeoutError as exc:
        detail = str(exc)
        initialize_timeout = "initialize timed out waiting for DeepSeek Harness runtime" in detail
        prompt_timeout = "session/prompt timed out waiting for DeepSeek Harness runtime" in detail
        write_terminal_state("harness_initialize_timeout" if initialize_timeout else
                             "blue_request_timeout" if prompt_timeout else "blue_timeout",
                             retry_eligible=initialize_timeout or prompt_timeout, detail=detail)
        raise
    except Exception as exc:
        write_terminal_state("blue_runtime_exception", retry_eligible=False, detail=f"{type(exc).__name__}: {exc}")
        raise
    finally:
        try:
            if "token_usage" in locals():
                token_usage.close()
        finally:
            restore_answers(moved)
    # A provider/harness turn error is terminal; do not label it a successful
    # benchmark round or start a validation retry with the same broken endpoint.
    if not agent_ok:
        write_terminal_state("blue_noncompleted", retry_eligible=False,
                             detail=f"finish_reason={result.finish_reason}")
        return 42
    # Evaluation is deliberately after blue exits and after answers are restored.
    ev = subprocess.run(f'{PYBIN} -m tasks.finalpool.{args.task}.evaluation.main --res_log_file {out / "eval_res.json"} '
                        f'--agent_workspace {ws} --groundtruth_workspace {task_dir / "groundtruth_workspace"} '
                        f'--launch_time "{launch_time}"', shell=True, cwd=GYM, capture_output=True, text=True)
    (out / "eval.log").write_text(ev.stdout + "\n== STDERR ==\n" + ev.stderr)
    (out / "evaluation_finished.json").write_text(json.dumps({"rc": ev.returncode, "at": time.time()}))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())