Skip to content

fix(hermes): match sandbox uv to the sandbox arch, accept Harbor row metadata, honour the task agent timeout - #4270

Merged
adil-a merged 6 commits into
mainfrom
adasif/hermes-agent-harbor-readiness
Oct 13, 2026
Merged

adil-a merged 6 commits into
mainfrom
adasif/hermes-agent-harbor-readiness

Conversation

@adil-a

@adil-a adil-a commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Summary

Three responses_api_agents/hermes_agent defects found while preparing the Terminal Bench 2.1 Hermes runs. Harness defects are fixed on main as their own PR, independent of the Harbor stack.

1. The sandbox uv must match the sandbox architecture, not the host

_install_runtime uploaded shutil.which("uv") from the agent host. The TB2.1 run was driven from an aarch64 login node against the upstream amd64 task images, so every sandbox install died with cannot execute binary file: Exec format error before the agent ran (every episode failed at stage=agent, each after paying for a sandbox).

sandbox.py now has uv_for_sandbox(sandbox, workdir, cache_dir): it probes the sandbox's uname -m, reuses the host uv when the architecture matches, and otherwise downloads the matching static uv-<target>.tar.gz of the host's uv --version once into a cache directory (_download_uv, atomic and idempotent). The cache location is the new uv_cache_dir config field (default DEFAULT_UV_CACHE_DIR = ~/.cache/nemo_gym/uv). Unknown architectures and a missing host uv fail with clear errors.

2. Accept the Harbor row metadata

Harbor-materialized rows carry responses_create_params.metadata = {"agent_timeout_sec": "<seconds>"}. _validate_request fails closed on every non-default request field, so each episode got a terminal HTTP 422 (Hermes does not support request field metadata) before any model call.

_validate_request now accepts metadata whose keys are a subset of {"agent_timeout_sec"} (defined once as AGENT_TIMEOUT_METADATA_KEY in app.py; the Harbor materializer constant does not exist on main). Any other metadata key, including the previously pinned extra_body / chat_template_kwargs cases, still gets the existing 422.

3. Honour the task's agent timeout, with a partial response on timeout

The sandbox activation always ran under the flat sandbox_runner_timeout_seconds ceiling (21600 s by default), so a task's [agent].timeout_sec (900 s for most TB2.1 tasks) was never applied: Hermes got up to 24x the budget Terminus had on the same rows, and a long episode was reaped by the sandbox TTL (a 500 and a retry) rather than scored.

_agent_timeout_sec(body) returns min(sandbox_runner_timeout_seconds, agent_timeout_sec), ignoring absent, non-numeric, non-finite or non-positive values with a warning. _run_sandbox_episode passes it to state.execute, so the in-sandbox supervisor stops the runner at the task deadline and the runner's interrupted transcript comes back as an incomplete response with interrupted=true, stop_reason=wall_time, hermes_error_type=TimeoutError and the effective agent_timeout_sec recorded in the response metadata (the way terminus_2 records terminus2_error_type). If the supervisor itself overran but a transcript was captured, that transcript is served the same way instead of raising; an overrun that left no gradable output remains an infrastructure failure (existing behaviour, still pinned by the existing tests). Host (in-process) execution accepts the key for a uniform request contract and logs that it does not bound the run.

How it was found

Preparing the TB2.1 Hermes parity runs: gym eval run ... --agent hermes_agent from an aarch64 MARS login node against the upstream amd64 TB2.1 images (fix 1) and against the Harbor resources server's materialized rows (fixes 2 and 3). The uv fix is the same behaviour already carried on the Harbor stack branch, lifted here without the stack's unrelated changes.

Tests

New, in responses_api_agents/hermes_agent/tests/:

  • test_app.py::TestSandboxUv: same architecture reuses the host uv; another architecture downloads the matching build exactly once and the seed uploads it from the configured uv_cache_dir; unknown architecture and missing host uv are errors; _host_uv_version parsing; _download_uv extracts an executable binary from a release archive.
  • test_sandbox.py: agent_timeout_sec metadata accepted on both the host and sandbox paths and preserved on the validated body; metadata with an extra key still 422s (added to test_unsupported_requests_are_rejected); _agent_timeout_sec is the task budget capped by the ceiling and falls back on absent / non-numeric / zero / negative / infinite values; the activation passes the task budget (or the ceiling) to state.execute and the launch command's --timeout is the task budget; a runner stopped at the deadline yields an incomplete response with the transcript and hermes_error_type=TimeoutError; a supervisor overrun with a captured transcript is a partial response, without one it stays a TimeoutError; the HTTP route serves the partial response rather than raising.
  • Existing install tests updated for the arch probe (uname -m exec call, Path upload argument).

Runs (hermes venv with the pinned hermes-agent):

  • pytest responses_api_agents/hermes_agent/tests -q: 282 passed.
  • pytest over the tests/unit_tests files that reference hermes (test_add_legacy_agent_environment_servers, test_cli_main, test_harness_conformance_checks, test_global_config, test_hermes_reasoning_replay, test_reward_profile, test_rollout_reverification, test_rollout_collection): 1909 passed, 3 skipped, 2 failed. Both failures are in test_reward_profile.py (test_profile_from_data, test_returns_a_wandb_histogram_when_wandb_is_installed), reproduce identically on an untouched main checkout with the same venv, and touch nothing in this PR.
  • pre-commit run --files <the four changed files>: passed.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 8, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@ananthsub
ananthsub requested a review from yaoyu-33 October 8, 2026 22:48
@adil-a
adil-a marked this pull request as ready for review October 9, 2026 20:05
timeout=timeout,
close_timeout=self.config.session_close_timeout_seconds,
)
except TimeoutError:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we require evidence that the agent deadline expired before returning a scored timeout? Providers also raise TimeoutError for transport failures. An early provider timeout with a saved transcript and cleanup.timed_out=false still becomes stop_reason=wall_time here, turning an infrastructure failure into a gradable result. Please preserve the failure when the task deadline was not reached.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, and fixed in c24eb13. A TimeoutError is scored as a wall_time outcome only with evidence that the agent deadline was reached: either the runner's own record that the supervisor stopped it (stop_reason == "wall_time" or an interrupted transcript), or wall-clock time at or past the budget (2 s slack for skew). An early provider timeout with a saved transcript now re-raises and stays an infrastructure failure, with a warning that names the elapsed time and the budget.

Tests: test_early_provider_timeout_with_a_transcript_stays_a_failure (both at the _run_sandbox_episode level and through the HTTP route with a real SandboxSession), test_runner_recorded_interruption_is_deadline_evidence, and the existing overrun tests now carry the clock evidence they implicitly relied on.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One case remains in b962fbd: after an early provider TimeoutError, cleanup writes stop.request, so the runner records stop_reason="cancelled", interrupted=true. _agent_deadline_passed() accepts that even at elapsed=1, timeout=900, and the caller rewrites it to a scoreable wall_time. Could we require explicit deadline evidence instead of bare interrupted, and add a regression for this cleanup-cancellation case?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, that path was real: the shared session's _finish runs on every exception, so an early provider timeout did produce a cancelled interrupted transcript that the check then accepted.

Fixed in 3283653: _agent_deadline_passed now accepts only the runner's own stop_reason == "wall_time" record or the wall clock at or past the budget. A bare interrupted transcript no longer counts, and cancelled is explicitly a consequence of the failure. The runner always sets stop_reason alongside interrupted, so nothing legitimate is lost.

Regressions added at both levels: test_cleanup_cancellation_after_an_early_provider_timeout_stays_a_failure in test_app.py (elapsed 1 s of 900 s, cancelled transcript, TimeoutError still raised) and the same scenario on _run_sandbox_episode in test_sandbox.py. The two earlier tests that relied on bare interrupted now carry stop_reason: wall_time.

os.replace(extracted, destination)


async def uv_for_sandbox(sandbox: AsyncSandbox, workdir: str | None, cache_dir: str) -> Path:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: could the uv selection/download/cache live in a small shared sandbox utility? miniswe_sandboxed_agent/bootstrap.py already downloads target-architecture uv (using the musl build). Hermes and mini-SWE could share that part while keeping their own runtime installs. Please account for OS/libc as well as CPU architecture; Codex/Pi use Node and should not acquire a uv dependency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in c24eb13: the selection, download and cache now live in nemo_gym/agent_utils/uv_bootstrap.py, with the Hermes sandbox module only calling uv_for_sandbox.

It probes the sandbox once (uname -s, uname -m, musl loader check, the same test mini-SWE uses) and uploads the static musl build for the sandbox's architecture, which runs on glibc and musl images alike, so libc no longer needs a separate table. The host's own binary is reused only when it is known to run there: a Linux host of the same architecture driving a glibc sandbox. Non-Linux sandboxes and unknown machines are refused with a clear error, and a sandbox that cannot answer the probe falls back to the host binary as before. Codex and Pi do not import it. tests/unit_tests/test_uv_bootstrap.py covers the matrix.

mini-SWE keeps its pinned uv 0.10.12 and its own asset cache for now, since its bootstrap also pins a Python build with checksums; moving its uv download onto this module is a small follow-up I would rather not fold into this PR. Happy to open it right after.

@yaoyu-33 yaoyu-33 added area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:medium Single-domain change with interacting parts or a moderate review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 9, 2026
adil-a and others added 2 commits October 13, 2026 08:38
…metadata, honour the task agent timeout

Three defects found while preparing Terminal Bench 2.1 Hermes runs from an
aarch64 login node against amd64 task images and the Harbor resources server.

1. The sandbox runtime install uploaded the host's `uv`. When the agent host
   and the task image differ in architecture the install dies with "Exec
   format error" before the agent runs. `uv_for_sandbox` now probes the
   sandbox's `uname -m`, reuses the host uv when it matches, and otherwise
   downloads the matching static build of the host's uv version once into a
   cache (`uv_cache_dir`, default `~/.cache/nemo_gym/uv`).

2. `_validate_request` rejected the `metadata` field that every materialized
   Harbor row carries, so each episode failed with a terminal 422. It now
   accepts metadata whose keys are a subset of {"agent_timeout_sec"} and keeps
   failing closed for anything else.

3. The sandbox activation always ran under the flat
   `sandbox_runner_timeout_seconds` ceiling. It is now bounded by the task's
   `agent_timeout_sec` when present (capped by the ceiling; invalid values are
   ignored with a warning). The in-sandbox supervisor stops the runner at that
   deadline and its interrupted transcript is returned as an incomplete
   response with `hermes_error_type=TimeoutError`; a supervisor overrun that
   still captured a transcript is served the same way instead of failing the
   episode, while an overrun with no output remains an infrastructure error.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
…e sandbox uv bootstrap

Review follow-ups from Yu Yao.

A provider TimeoutError is scored as a wall_time outcome only when the agent deadline
was reached: the runner recorded the interruption, or the wall clock is at or past the
budget. An early transport timeout with a saved transcript stays an infrastructure failure.

The uv selection moves to nemo_gym/agent_utils/uv_bootstrap.py so harnesses that install a
Python runtime in the sandbox can share it. It probes the sandbox's kernel, machine and C
library, uploads the static musl build for the sandbox architecture, which runs on glibc
and musl alike, and reuses the host's binary only on a Linux host of the same architecture
driving a glibc sandbox. Codex and Pi are untouched.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a
adil-a force-pushed the adasif/hermes-agent-harbor-readiness branch from 9487a17 to c24eb13 Compare October 13, 2026 15:48
@adil-a

adil-a commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test c24eb13

@adil-a

adil-a commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

CI on c24eb13: 33 checks pass, the unit test shards are still running, and the one failure is the Hermes model_error conformance probe (verifier.saved_outcome: completed verification must retain evaluation_completed=true and mask_sample=false).

That probe fails on main as well. #4473 added the check on 12 Oct and its own validation table records hermes_agent at 6/7 with exactly this failure, described there as the previously hidden producer gap where Hermes saves reward 0.0 and evaluation_completed=true and then masks the sample. This PR does not touch that path, so the result is the same with or without it. I am happy to take the masking fix as a separate PR if nobody has it in flight.

A model endpoint that refuses the request for what it asked (HTTP 400, 413 or 422 after
Hermes's own retries) is a model outcome: the episode reaches the verifier and keeps an
unmasked zero, as the conformance model_error scenario requires since #4473. Auth, routing,
rate-limit and server errors stay provider failures and are masked as #4048 intended. The
response records the status under metadata.model_rejected.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a

adil-a commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 81ee9e9

@adil-a

adil-a commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

Took the masking gap here after all, since it blocks the merge: a terminal HTTP 400, 413 or 422 from the model endpoint is now a graded model rejection (metadata.model_rejected), while auth, routing, rate-limit and server errors keep #4048's masking. Local run of the Hermes model_error probe at this commit: verdict fulfilled, reward 0.0, evaluation_completed=true, mask_sample=false. CI re-triggered.

Comment thread nemo_gym/agent_utils/uv_bootstrap.py Outdated
Comment on lines +139 to +140
if not cached.is_file():
await asyncio.to_thread(download_uv, version, target, cached)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we deduplicate downloads per cache path and recheck the cache under the lock? With mocked downloads, 8 concurrent cold-cache calls here triggered 8 downloads of the same binary. Atomic replacement prevents partial files, but not this download burst during large rollout starts. Please add a concurrent cache-fill regression test too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in b962fbd. uv_for_sandbox now takes a per-cache-path asyncio.Lock and rechecks cached.is_file() under it, so the first cold-cache caller downloads and the rest wait and find the file. Atomic replacement in download_uv still covers other processes filling the same path.

Regression test test_concurrent_cold_cache_calls_share_one_download: eight concurrent cold-cache calls, the download is held open until the others have queued, exactly one download recorded and all eight return the same path. Verified it fails on the previous commit (8 downloads) and passes now.

…llers

Many rollouts start at once on a cold cache. Each caller found the cache
empty and fetched the same uv binary, so a large rollout start issued one
download per task. A per-cache-path asyncio.Lock with a recheck under it
lets the first caller download while the rest wait and find the file.
Atomic replacement in download_uv still covers other processes filling
the same path.

Adds a regression test: eight concurrent cold-cache calls perform one
download and all return the same cached path.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a

adil-a commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test b962fbd

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 13, 2026 17:42


async def probe_sandbox_platform(sandbox: _Sandbox, workdir: str | None, *, timeout_s: float = 30) -> SandboxPlatform:
"""Ask the sandbox for its kernel, machine and C library."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: could we keep uv_for_sandbox as the only public entry point and prefix the other helpers/types with _ (e.g. _probe_sandbox_platform, _uv_release_target, _SandboxPlatform)? That makes the intended harness API clearer while keeping the implementation details free to evolve.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in fe6563f: uv_for_sandbox and DEFAULT_UV_CACHE_DIR are the only public names. The probe, target selection, host reuse check, version read and download now carry a leading underscore, and the module docstring says so.

adil-a and others added 2 commits October 13, 2026 11:18
An early provider TimeoutError makes the session clean up: close
publishes stop.request, the supervisor signals the runner, and the
runner records an interrupted transcript with stop_reason "cancelled".
The deadline check accepted any interrupted transcript, so that
cleanup turned the failure into a scoreable wall_time outcome even at
elapsed 1 s of a 900 s budget.

Only the runner's own wall_time record, or the wall clock at or past
the budget, now counts. Two regression tests cover the cleanup
cancellation case at the app and sandbox-episode levels.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
…point

The probe, target selection, host reuse check, version read and
download are implementation details and now carry a leading
underscore. Harnesses call uv_for_sandbox and the cache dir default.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
@adil-a

adil-a commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test fe6563f

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Rechecked the cancellation/deadline fix and uv follow-ups; focused checks and current-head CI pass.

@yaoyu-33 yaoyu-33 added ready-to-merge PR is approved, current, and waiting for final CI or merge and removed needs-review PR is ready for code review and waiting on a reviewer labels Oct 13, 2026
@adil-a
adil-a added this pull request to the merge queue Oct 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/38458348342

Merged via the queue into main with commit f6681a6 Oct 13, 2026
54 checks passed
@adil-a
adil-a deleted the adasif/hermes-agent-harbor-readiness branch October 13, 2026 20:09
pthombre pushed a commit to linj-glitch/Gym that referenced this pull request Oct 16, 2026
…DIA-NeMo#4653)

## What does this PR do?

Fresh Codex, Pi and OpenClaw environments omit the OpenSandbox SDK, so
sandbox sessions fail when the provider first imports it. Add the
existing `sandbox` extra to their requirements and an unmocked SDK
initialization test in each agent's isolated test environment.

Harbor materializes `metadata.agent_timeout_sec`, but
Pi/OpenCode/OpenClaw reject it and Codex ignores it. Accept this one
metadata key in the strict adapters and apply the task budget in all
four adapters' sandbox supervisors and local subprocess waits. Reuse the
policy established by Hermes in NVIDIA-NeMo#4270: a positive finite task budget is
capped by the configured timeout; absent/invalid values retain that
configured timeout. OpenClaw receives integer CLI seconds, with the
supervisor enforcing the precise fractional limit.

No separate issue is needed: this focused bug fix includes reproductions
for both reported failures. Execution, cleanup and failure
classification stay with the existing runtime; replacing the Environment
Server's RPC wait with an outer timeout would require a separate
partial-result retrieval contract.

CI missed the dependency defect because session tests mock provider
connection, bypassing the lazy SDK import. Conformance uses the local
provider. The new unskipped tests exercise the installed SDK without
contacting a sandbox service.

## Validation

- Three fresh Python 3.13.14 component venvs, each installed from its
own `requirements.txt`: all three SDK checks pass. A separate fresh venv
using the original `[dev]` declaration fails all three checks with `No
module named 'opensandbox'`.
- Focused adapter/session and timeout tests: **871 passed, 12 Linux-only
skips** on macOS. Added cases cover actual Harbor materialization
through HTTP validation into supervisor budgets, local propagation,
invalid/default/capped budgets, fractional OpenClaw arguments, and
rejection without consuming the session activation.
- `pre-commit run --all-files`: passed, including all new tracked files.
- `git diff --check`: passed. Commit has DCO sign-off.
- Follow-up commit 13073d2 (budget recorded in response metadata): on
macOS, Python 3.13, the full test directories of
Codex/Pi/OpenCode/OpenClaw/Hermes gave **1551 passed, 155 Linux-only
skips**, and the focused suite above plus Hermes gave **1259 passed, 48
skipped**; `pre-commit run --files` on the changed files passed. No new
rollouts: the change adds a metadata key and does not alter execution.
- Follow-up commit 232cdf4 (`pi_sandboxed_agent` accepts and applies the
task budget; fixes the CI `TypeError` in its `_run_pi` override):
`responses_api_agents/pi_sandboxed_agent/tests` gave **49 passed** on
macOS, Python 3.13, including new cases for absent, shorter and capped
budgets; `pre-commit run --files` on the changed files passed. No new
rollouts.
- Final Linux focused adapter/session/shared-supervisor suite: **999
passed, 3 skipped** (three Pi JavaScript extension tests: Node absent
from that SSH PATH; these passed in the macOS run). All changed-source
hashes matched the reviewed commit.

Dependency checks run from each component directory:

```bash
uv venv --python 3.13.14 "$VENV"
uv pip install --python "$VENV/bin/python" -r requirements.txt
"$VENV/bin/python" -m pytest -o addopts= -q tests/test_runtime_dependencies.py
```

Final Linux suite (Python 3.13.14; reviewed source explicitly first on
`PYTHONPATH`, isolated component site-packages, `-S` to exclude
editable-import hooks):

```bash
python -S -m pytest --import-mode=importlib -q -o log_cli=false -o addopts= \
  tests/unit_tests/test_task_timeout.py \
  responses_api_agents/{codex,pi,openclaw,opencode}_agent/tests/test_app.py \
  responses_api_agents/codex_agent/tests/test_sandbox_sessions.py \
  responses_api_agents/{pi,openclaw}_agent/tests/test_sandbox.py \
  responses_api_agents/opencode_agent/tests/test_sandbox_sessions.py \
  responses_api_agents/{codex,pi,openclaw}_agent/tests/test_runtime_dependencies.py \
  tests/unit_tests/test_process_supervisor.py \
  tests/unit_tests/test_sandbox_session.py \
  tests/unit_tests/test_sandbox_supervisor_client.py
```

## Rollouts

Executed eight synthetic episodes against this commit with the real
pinned CLIs, Gym model/Environment servers, Docker execution, and a file
verifier. Harbor `load_task`/`materialize_task` produced each request
from `task.toml`; the configured agent ceiling was 300s. The model was
Qwen/Qwen2.5-7B-Instruct at `a09a35458c702b33eeacc393d103063234e8bc28`,
served locally by vLLM 0.8.5 / transformers 4.51.3.

| Harness | Normal task budget / result | Deadline task budget / result
| Retained output items at deadline |
| --- | --- | --- | --- |
| Codex 0.144.4 | 120s / completed, reward 1 | 5.5s / incomplete, reward
1 | 2 |
| Pi 0.80.2 | 120s / completed, reward 1 | 20.5s / incomplete, reward 1
| 1 |
| OpenCode 1.17.11 | 120s / completed, reward 1 | 20.5s / incomplete,
reward 1 | 2 |
| OpenClaw 2026.6.11 | 120s / completed, reward 1 | 20.5s / incomplete,
reward 1 | 3 |

The model was instructed to write `42` to a file using its shell tool.
Deadline cases then ran `sleep 90`; verification checked the retained
file after agent close. All eight had `evaluation_completed=true`,
`mask_sample=false`, retained tool calls, and no fallback container
removal. Codex's initial 20.5s case completed early, so the 5.5s case
separately exercised actual expiration. These are synthetic contract
checks, not benchmark scores. OpenSandbox was checked through clean SDK
installation/initialization; the real-model runs used Docker. Complete
training token-ID round trips were not asserted.

The task model and containers were stopped afterward; cleanup confirmed
no remaining task containers and a closed model port.

## Compatibility and benchmark impact

Rows without timeout metadata retain their configured budget. Codex
still accepts ordinary metadata; the strict adapters still reject
unrelated metadata. Task budgets may shorten runs and change benchmark
results: for example, task 900s/config 1800s now runs at 900s; task
900s/config 600s remains capped at 600s. Historical runs with different
effective budgets should not be compared as equal-budget results. This
does not redesign existing timeout response/artifact semantics or move
agent budgets into the session control protocol.

Responses from Codex, Pi, OpenCode and OpenClaw now record the applied
budget as `metadata.agent_timeout_sec` (seconds as a string, after
capping), on both sandbox and local paths, matching Hermes sandbox
responses. Consumers that compare response metadata exactly will see
this new key. Unlike these four adapters' local paths, Hermes host
execution still does not apply the task budget. Hermes now uses the
shared `resolve_agent_timeout` helper with unchanged behavior, and Codex
no longer writes its unused `timeout`/`cleanup_timeout` fields into the
sandbox runner's `input.json`. `pi_sandboxed_agent`, which inherits Pi's
request handling, now also bounds its Pi run by the task budget; its
sandbox setup commands keep the configured timeout.

## Timeout boundaries

Where each timer starts and ends in one foreground sandbox episode that
reaches the task budget, with T = 900 s and C =
`session_close_timeout_seconds` = 60 s. This PR only changes how T is
chosen (the task budget, capped by the configured `timeout`). P, ③ and ②
are computed from T, so they shrink with it. Durations after the
deadline are illustrative; each label gives its limit.

```mermaid
gantt
    title Whole episode (mm:ss), deadline case, T=900s, C=60s
    dateFormat HH:mm:ss
    axisFormat %M:%S
    section Gym host
    ① Episode deadline                       :e1, 00:00:00, 00:16:40
    ② Provider hard cap (limit 2130s)        :p2, 00:00:40, 00:15:58
    ③ SDK operation (limit 1050s/attempt)    :p3, 00:00:40, 00:15:57
    section Sandbox
    ④ Remote command (limit P=990s)          :s4, 00:00:42, 00:15:56
    ⑤ Harness budget T=min(task, ceiling)    :active, s5, 00:00:45, 00:15:45
    OpenClaw CLI --timeout ceil(T)           :done, oc, 00:00:50, 00:15:45
```

```mermaid
gantt
    title Zoom on T deadline to episode end (mm:ss)
    dateFormat HH:mm:ss
    axisFormat %M:%S
    section Gym host
    ① Episode deadline (continues)           :e1, 00:15:40, 00:16:40
    ② Provider hard cap ends                 :p2, 00:15:40, 00:15:58
    ③ SDK operation ends                     :p3, 00:15:40, 00:15:57
    ⑦ Stop confirmation (limit C)            :p7, 00:16:00, 00:16:05
    ⑧ Artifact collection (limit C)          :p8, 00:16:05, 00:16:15
    Close, verify                             :cv, 00:16:15, 00:16:40
    section Sandbox
    ⑤ Harness budget ends, SIGTERM           :active, s5, 00:15:40, 00:15:45
    ⑥ TERM grace (up to C/3)                 :s6a, 00:15:45, 00:15:50
    ⑥ Direct reap (up to C/3)                :s6b, 00:15:50, 00:15:52
    ⑥ Group reap (up to C/3)                 :s6c, 00:15:52, 00:15:54
    ④ Remote command ends                    :s4, 00:15:40, 00:15:56
    OpenClaw CLI timer, killed before ceil(T) :done, oc, 00:15:40, 00:15:45
```

| ID | Timer | Starts | Ends |
| --- | --- | --- | --- |
| ① | Episode deadline | Environment enters the episode | `run()`
returns, after verify |
| ② | Provider hard cap, 2×(P+60)+30 | OpenSandbox `_dispatch()` begins
| dispatch returns, including retries |
| ③ | SDK operation, P+60 per attempt | each SDK call begins | that call
returns; a retry gets a new ③ |
| ④ | Remote command, P = T+C+30 | the remote service starts the
supervisor | the supervisor exits |
| ⑤ | Harness budget T | supervisor `Popen()` starts the runner | runner
exits, a stop arrives, or T passes (then SIGTERM) |
| ⑥ | Cleanup phases, C/3 each | TERM grace, direct reap, group reap |
each phase separately |
| ⑦ | Stop confirmation, C | `stop_harness()` begins | termination is
confirmed |
| ⑧ | Artifact collection, C | `_collect()` begins | collection finishes
|

② and ③ start together at provider dispatch, and with one successful
attempt they also end together. OpenClaw's own `--timeout ceil(T)`
starts after Node boots and is never shorter than T, so the supervisor
always stops the run first. Local (non-sandbox) runs use a single
`asyncio.wait_for(..., timeout=T)` that starts once the subprocess is
launched; ② to ④ and ⑥ to ⑧ do not apply there.

## Checklist

- [x] I have read the contributing guidelines.
- [x] The change is focused.
- [x] Tests added and focused macOS/Linux checks pass with the skips
recorded above.
- [x] Documentation N/A: repair of an existing materialized request
contract; compatibility is described above.
- [x] Pre-commit checks pass locally.
- [x] New source files include the required SPDX header.
- [x] All commits have DCO sign-off.

---------

Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was previously deployed

1 inactive deployment
public — fe6563fa Deployed Oct 13, 2026 by copy-pr-bot[bot] via release / finalize / notify #5196
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:medium Single-domain change with interacting parts or a moderate review surface QA_verified ready-to-merge PR is approved, current, and waiting for final CI or merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants