Skip to content

fix(token_capture): keep capture chains through OpenCode's step-limit note and tool-name repair - #5833

Merged
yfw merged 7 commits into
mainfrom
yifuw/token-capture-opencode-notes-and-repair
Nov 10, 2026
Merged

yfw merged 7 commits into
mainfrom
yifuw/token-capture-opencode-notes-and-repair

Conversation

@yfw

@yfw yfw commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

OpenCode 1.17.11 changes its own history in two ways that token capture did not expect. Each one leaves the next model call with no parent, so capture poisons the call and NeMo RL masks the whole rollout. No issue was filed; we found both while training with OpenCode through the Environment Server.

  1. Step-limit note. With agent.build.steps set, OpenCode adds an assistant message to the end of every request from the limit on, and drops it from the next request:

    request 16: [..., assistant(tool_call A), tool(A result), assistant("CRITICAL - MAXIMUM STEPS REACHED ...")]
    

    Capture reads the last message as model output that it never served, so call 16 has no parent.

  2. Tool-name repair. When the model calls Crop and OpenCode offers crop, OpenCode renames the call to crop and echoes that name in every later request:

    served:  function_call(id=call_1, name="Crop", ...)
    echoed:  function_call(id=call_1, name="crop", ...)
    

    The tool-call-turn fallback compares names exactly, so the next call has no parent. fix: read OpenCode's tool placeholder in token capture and enforce opencode_agent permissions #5387 already handles the other repair, where the call becomes OpenCode's invalid placeholder.

The fix:

  • The model server recognizes OpenCode's exact step-limit text. Under capture, it forwards that text as a user message and leaves it out of the items that link calls. The next request still extends the parent's tokens. Any other assistant message keeps the old handling.
  • The notes live in nemo_gym/models/token_capture/harness_notes/, one module per harness (opencode.py), each note with the harness releases checked to send its exact text. A shared matcher reads the registry HARNESS_NOTES. A new harness adds its module and registers it; core tests check every registered note, and the harness's own tests check that its default release is listed. OpenCode's text is the same in every release a config on main pins (1.15.13, 1.17.8, 1.17.11, 1.19.4).
  • The tool-call-turn fallback key compares tool names without case. Call IDs, their order, the content and the request-context digest still have to agree, so a call renamed to a different tool stays unresolved.
  • The poison warning keeps its text and adds the tool names of the last model turn (names only), so a log shows which call broke the match.
  • opencode_agent no longer refuses agent.build.steps under token capture. feat: images in tool replies, a lent-sandbox helper and OpenCode session limits for multi-harness training #5719 added that refusal for as long as this fix was not on main.

Code provenance

nemo_gym/models/token_capture/harness_notes/opencode.py copies OpenCode's max-steps prompt verbatim, so that capture recognizes the exact text OpenCode sends:

Validation

  • Unit tests: three chat calls through external staging and a file ledger, where the model keeps calling tools past the limit, chain with the expected token prefixes. Without the change, call 2 fails with unresolved_parent. A lowercased call resolves to the served call, and a call renamed to another tool stays unresolved.
  • Rebased onto main, which now has feat: images in tool replies, a lent-sandbox helper and OpenCode session limits for multi-harness training #5719, at 9497c4d03: tests/unit_tests/models, the docs link test and the opencode_agent tests pass (2,896 passed, 23 skipped), and so do the vllm_model tests (1,004).
  • pre-commit run on the changed files passes, import-linter included. CI is green at 9497c4d03.

Rollouts

GRPO training with OpenCode through the Environment Server on an image benchmark, 1,024 rollouts per step:

  • OpenCode's own tools, 16-step limit: 0 poisoned rollouts over 40 steps. Without the step-limit fix, a 3-step smoke run had 19 poisoned rollouts of 384.
  • Image tools over MCP, 16-step limit: 11 to 23 poisoned rollouts per step in the first 5 steps, before the tool-name fix. 0 in the 17 steps after it.
  • Image tools over MCP, 17-step limit, both fixes from the start: 0 poisoned rollouts over 26 steps.

Compatibility and benchmark impact

  • Only OpenCode's exact step-limit text is handled as a note. Other harnesses and other assistant messages are unchanged.
  • Fallback keys change only for turns whose served tool names contain capital letters. In a durable ledger written by an older Gym, those turns resolve by the strict fingerprint only; the keys of the other turns still match, now without case.
  • No configuration changes. Without token capture, requests are unchanged. Under capture, the model sees OpenCode's step-limit note as a user message instead of an assistant message.
  • feat: images in tool replies, a lent-sandbox helper and OpenCode session limits for multi-harness training #5719 refused agent.build.steps under token capture unless the nemo_gym.models.token_capture.harness_notes package could be imported. This PR adds that package and removes the check, its tests and the docs sentences about it.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally.
  • Documentation added or updated, or N/A with justification: the opencode_agent README and the harness page no longer limit agent.build.steps under token capture, and ATTRIBUTIONS.md records OpenCode's prompt.
  • Pre-commit checks pass locally.
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s).

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Nov 9, 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.

@yfw

yfw commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test f72f235

@yfw yfw added area:training Training framework integrations and training-data interfaces bug Something isn't working labels Nov 9, 2026
yfw added a commit that referenced this pull request Nov 9, 2026
…Gym #5833's capture fix is installed

A seed with token capture refused agent.build.steps, because OpenCode's step-limit note made capture poison the
next call. Gym #5833 fixes that in token capture and adds nemo_gym/models/token_capture/harness_notes.py. The seed
now refuses the setting only when that file is missing, so a branch that merges both PRs can train with a step
limit. The check reads the installed package's files and imports nothing.

TODO: remove the check once #5833 is on main.

Tests: the refusal without the fix, the acceptance with it, and the file check. opencode_agent: 832 passed,
23 skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
yfw added a commit that referenced this pull request Nov 9, 2026
…entic-MME example

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
yfw added a commit that referenced this pull request Nov 9, 2026
…sion

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
@yfw
yfw marked this pull request as ready for review November 9, 2026 17:02

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

SHIP WITH CARE

I found two RISKs: the fallback-key change breaks identical replay of older durable ledger rows, and the copied OpenCode prompt lacks the required vendoring notices and PR provenance.

I inspected all seven changed files and traced the affected dispatch, lineage, staging, and logging paths. This was a read-only static review; I didn't execute tests or independently reproduce the reported rollouts. The external inference renderer wasn't available for independently checking the exact-token splice.


Inline comments (escaped v1):

  • nemo_gym/models/token_capture/lineage.py line 1187: RISK — Preserve identical replay of older durable rows

    The new lowercase hash changes a persisted field that this comparison still requires to match exactly. Export a custody row from the base revision for the existing Bash/Read fixture, import it under this head, and replay its original CaptureLedgerCommit: record() now raises ValueError: conflicting lineage record although the payload is identical. That breaks the identical-replay contract, beyond the documented strict-only lookup limitation for older rows.

    Could you accept a legacy case-sensitive key during replay only when it matches the supplied response items and every other persisted field still agrees? Leave the existing row unchanged and retain lowercase keys for new rows. Don't simply ignore key differences: this key also distinguishes empty assistant items that the strict fingerprint doesn't distinguish.

    A small suggested correction is to add keyword-only case_sensitive: bool = False to tool_call_turn_fingerprint and replace its name-hash write with:

    _update_field(hasher, b"\x03", served if case_sensitive else served.lower())

    Then, after the existing comparable assignment here and before the equality check, add:

    if (
        "tool_call_turn_fingerprint" in existing
        and existing["tool_call_turn_fingerprint"] != record["tool_call_turn_fingerprint"]
    ):
        legacy_key = tool_call_turn_fingerprint(
            list(commit.response_items), case_sensitive=True
        )
        if existing["tool_call_turn_fingerprint"] == legacy_key:
            comparable = {**record, "tool_call_turn_fingerprint": legacy_key}

    This retains the current comparison of all other fields and the pre-column compatibility branch. The legacy calculation must use the old case-sensitive layout without interpreting served output as placeholders.

    Proposed acceptance: import a fixed row exported by the base revision, replay the identical commit, and assert no exception, one unchanged row, and successful strict lookup. Retain rejection of changed tokens, metadata, or an added empty assistant item; new-row Bash→bash resolution; Bash→grep rejection; and mixed repaired-placeholder/own-invalid handling. Extend the checkpoint-replay test with a genuine old-key fixture—computing both keys with the head implementation misses this transition. The patch and checks are source-derived, not executed; verify the suggestion before adopting it.

  • nemo_gym/models/token_capture/harness_notes.py line 23: RISK — Complete the copied prompt's provenance and notices

    This header identifies the prompt as copied verbatim from MIT-licensed OpenCode, but includes only the license name and copyright attribution, not the upstream permission notice. OpenCode is also absent from the vendored-component register, and the supplied PR description omits the upstream source URL, exact revision, and license. The trusted provenance rules and vendoring requirements require these records when distributing copied material.

    Could you retain the upstream copyright and applicable license notice with the copied constant, distinguish Gym's Apache-2.0 additions, register the copied prompt in the attribution file, and add the source URL, full SHA, license, upstream file, and affected Gym file to the PR description? Use the notice from the pinned upstream revision; its exact text wasn't available for verification here, so I haven't supplied a replacement notice.

    Acceptance is a static check that those records agree on the pinned source and scope. Keep OPENCODE_MAX_STEPS_PROMPT byte-for-byte unchanged: the existing tests must still recognize its string and text-part forms while rejecting the near-match, tool-call, and reasoning-bearing cases. No runtime behavior change is needed for this correction.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

@yfw

yfw commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 8208d6a

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 9, 2026 18:53
yfw added a commit that referenced this pull request Nov 9, 2026
…Gym #5833's capture fix is installed

A seed with token capture refused agent.build.steps, because OpenCode's step-limit note made capture poison the
next call. Gym #5833 fixes that in token capture and adds nemo_gym/models/token_capture/harness_notes.py. The seed
now refuses the setting only when that file is missing, so a branch that merges both PRs can train with a step
limit. The check reads the installed package's files and imports nothing.

TODO: remove the check once #5833 is on main.

Tests: the refusal without the fix, the acceptance with it, and the file check. opencode_agent: 832 passed,
23 skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
@yfw

yfw commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 1c0cd40

@yaoyu-33

yaoyu-33 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

FYI for merge order: moving harness_notes.py into the harness_notes/ package breaks #5719's check, which tests for that file to decide whether agent.build.steps may run under token capture. Details are on #5719. Landing this PR first, then removing the check in #5719, keeps the two in step.

@yfw

yfw commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Since then, the branch is rebased onto main, which now has #5719:

  • a658f78: the fingerprint docstring (see the inline thread). Also a sentence in the harness_notes docstring on where calls stay chained:
    • External staging or prefix supply keeps them chained.
    • With source_history, each call past the limit starts a new chain.
    • In-process capture without prefix supply fails closed with parent_digest_mismatch.
  • 827d1bf: an ATTRIBUTIONS.md row, a note and OpenCode's MIT license text. The description has a Code provenance section with the source URL, revision and license.
  • 9497c4d: removes feat: images in tool replies, a lent-sandbox helper and OpenCode session limits for multi-harness training #5719's agent.build.steps check in opencode_agent, which this PR makes always pass, together with its tests and docs sentences.
  • The description no longer says harness_notes.py.

@github-actions

Copy link
Copy Markdown
Contributor

@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 10, 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/42853159683

@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/42855584986

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 10, 2026
@yfw
yfw added this pull request to the merge queue Nov 10, 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/42860482341

Merged via the queue into main with commit ab2ef4d Nov 10, 2026
69 checks passed
@yfw
yfw deleted the yifuw/token-capture-opencode-notes-and-repair branch November 10, 2026 17:16
yfw added a commit that referenced this pull request Nov 10, 2026
…mages in training, OpenCode-only pairing

- Under NeMo RL the lent sandbox can reach Gym's head server, whose /global_config_dict_yaml returns the merged config. The README, tutorial and config comment state this limit.
- The images that read returns are staged by NeMo RL's single controller and recorded by local capture only with #5837. Saved rollouts keep only the tool's text.
- The step-limit reason is gone (Gym #5833 joins OpenCode's step-limit note under capture). Only the compaction reason stays.
- Only the policy model server advertises the host address. The question-only variant still sends the image. The pairing is OpenCode-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Nov 11, 2026
…n on OpenCode sandbox sessions (NVIDIA-NeMo#5839)

* feat(visual_coding_opencode): visual-coding environment and BabyVision benchmarks on OpenCode sandbox sessions

A multi-turn visual-coding environment: OpenCode answers a question about an image in a sandbox whose shell has
Python with pillow, numpy, scipy and opencv, and a GPT judge grades the final \boxed{} answer against the gold
answer. BabyVision (388 visual-reasoning puzzles) and its question-only variant run on it.

- `resources_servers/visual_coding_opencode`: the judge (`equivalent` scores 1; a failed call or a reply without a
  valid verdict is masked as `judge_failed`, not scored 0), the task-data schema, and a typed seed and close that
  lend each episode a sandbox through `LentSandboxes` with `sandbox_network_access: model_only`, so the sandbox
  reaches only the policy model. A sandbox image (`sandbox_image/Dockerfile`) carries the toolkit and OpenCode
  1.17.11, pinned by its SHA-256.
- The environment config runs each task with `opencode_agent` in a sandbox session behind the
  `single_agent_turn_legacy` Environment Server. The prompt image is attached with `opencode run --file`.
  Compaction is off and there is no step limit, so Gym's token capture joins every model call and the same config
  serves evaluation and RL.
- `benchmarks/babyvision_opencode` and `benchmarks/babyvision_opencode_question_only`: prepare scripts for
  VLMEvalKit's BabyVision TSV (checked by md5), configs and manifests.
- The "Evaluate Visual Coding with OpenCode" tutorial and its index entry.
- Tests: the judge, the lent sandbox and the session contract, the BabyVision configs, the prepare scripts, and the
  example rows run through a seeded `opencode_agent` session.

Based on NVIDIA-NeMo#5712 by Danial MohseniTaheri, moved from a host-CLI agent path onto sandbox sessions.

Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(visual_coding_opencode): five example rows with metrics and rollouts

The server test's data check expects 5 example rows, their metrics and 5 example rollouts.

- example.jsonl: three small synthetic puzzles, and BabyVision tasks 4624 (Spatial Perception, Count 3D blocks) and
  487 (Visual Pattern Recognition, Logic Patterns) from the UnipatAI/BabyVision dataset on Hugging Face (MIT
  license), revision 849cbeea2b1d00ad334e9e1e2b49a1960c9ff3f3, in prepare.py's format. The README names the source.
- example_metrics.json comes from `gym dataset collate ... +mode=example_validation`.
- example_rollouts.jsonl is one rollout of each row: OpenCode in a lent, model-only sandbox, a hosted
  vision-language policy and a gpt-4o-mini judge. Four rows score 1.0; task 4624 ends incomplete and scores 0.

Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(visual_coding_opencode): declare image input in the OpenCode config

The model looks at its crops and plots through OpenCode's read tool, and OpenCode passes those images to the model
only when the model declares image input. Since NVIDIA-NeMo#4922, opencode_agent declares it when the prompt has images or
image_input is true. The prompt image already declared it; image_input: true keeps it declared for any row, as NVIDIA-NeMo#4922
asks of configs whose tools return images. The session tests now run with the setting.

Tests: visual_coding_opencode, BabyVision, docs link and session contract tests: 73 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(babyvision_opencode): give rows a task_id, license the manifests MIT, and run the prepare tests in CI

- prepare.py writes the TSV index as task_id, which `gym eval plan` needs (it raised ConfigError for every row);
  TaskData declares it, optional, so the example rows stay valid.
- Both manifests say `licensing: MIT`, the license of UnipatAI/BabyVision, so `gym env publish` accepts them.
- The prepare tests move to tests/unit_tests/benchmarks/, where the core test suite runs them; no CI job collected
  benchmarks/babyvision_opencode/tests. A new check covers task_id.
- The README says that mean/reward leaves judge failures out, and that scores are not comparable to the BabyVision
  leaderboard, whose scorer judges only the last \boxed{} with another judge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(visual_coding_opencode): keep the sandbox off every server but the policy model, and grade only a finished final answer

Network and seeds:
- The lent sandbox's egress rule opens every port of the policy model's host, and NeMo RL gives every server
  without its own host that address. The judge, the agent, the resources server and the Environment Server now set
  host 127.0.0.1, so sandbox code cannot spend the judge's key, run OpenCode on the host, or start sandboxes and
  episodes. All their callers run on the same host. A config test checks that only the policy model takes
  NeMo RL's default_host.
- While the server lends sandboxes, it refuses a cookie seed (an agent's own /run, which would run OpenCode on its
  host without the image) and a malformed typed seed with 422; the stateless server refuses only the latter.

Grading:
- A run whose status is incomplete (a timeout, an output cap or a context limit) scores 0 without a judge call, as the
  docs promised; an early \boxed{} guess no longer reaches the judge.
- `extracted` is the last \boxed{}, the answer the prompt asks for, not string_match's last "answer:".
- The verdict comes from every JSON object in the reply that has one: a brace ahead of it no longer masks the row,
  and objects that disagree stay a judge failure. A reply with no choices is a judge failure too.
- Judge calls run inside observe_llm_judge_grading, so judged rows carry a grading record.
- judge_model is removed: the judge's model server picks the model.

Config and docs:
- The Environment Server admits 64 episodes at a time (the agent's concurrency), and an episode has 5400 s, below the
  sandbox's 7200 s TTL; before, all rows started sandboxes at once with a 21600 s deadline.
- The docs say that model_only keeps the model off the internet only on an OpenSandbox server that enforces egress
  at the IP layer (dns+nft), what `thinking` does, and how NeMo RL's masked_reward_policy treats a judge failure.

Tests: verdict parsing, empty choices, incomplete runs, the last \boxed{}, the gold answer in the judge prompt, the
exported verifier fixture, seed refusals, hosts and admission. Ten new cases fail on the old code. 86 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(visual_coding_opencode): bake OpenCode's plugin dependencies into the sandbox image

opencode_agent always configures a plugin, so OpenCode 1.17.11 installs @opencode-ai/plugin from npm at each start
unless the dependencies are present. The lent sandbox reaches only the model server, so each start waited about 70 s
for that install to fail before the first model call.

The image now builds the dependency archive in two stages, from a copy of benchmarks/agentic_if/opencode's lockfile
with the recipe in benchmarks/agentic_if/README.md: npm ci with Node 24.15.0 (npm 11.12.1), then GNU tar 1.34 and
GNU gzip 1.10 (Debian 11). The build checks the archive against the pinned SHA-256 (77b03eba..., the same bytes
agentic_if pins), and the config sets sandbox_plugin_dependencies_path and _sha256 to it. The docker build context
is sandbox_image/, so the two lockfile files are copied there; a test keeps them equal to agentic_if's.

Checked: the image builds and holds the archive with the pinned digest. Offline (docker --network none), with one
plugin configured and the adapter's OpenCode environment, the first model request came 1.0 s after start with the
archive unpacked into XDG_CONFIG_HOME/opencode, and 71.1 s without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_if_realworld): skip hidden directories in the runtime source fingerprint

Other test runs in the same checkout install tools into hidden directories
(pi_agent's .pi_node holds node-gyp .py files) and delete them. Hashing them
made the resume fingerprint change mid-test, which failed
test_observed_driver and test_driver in the sharded server suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(agentic_if_realworld): pin the driver's source fingerprint in tests

The driver tests run and then resume within one test. In CI, other
servers' tests share the checkout and add or delete .py files, so the
source hash could change between the run and the resume. The
runtime_identity tests still cover the hash itself.

A conftest fixture pins it for every test in the folder, so the pin
that NVIDIA-NeMo#5088 added inside test_adaptive_capture_selected_parameters_and_resume
is no longer needed. The fixture also covers
test_observed_driver.py::test_http_resume_and_connection_recovery,
which failed the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(babyvision_opencode): prepare BabyVision from the public Hugging Face release

prepare.py read BabyVision from one of two VLMEvalKit-style TSVs that have
no public download. It now downloads UnipatAI/BabyVision (MIT license) at
revision 849cbeea2b1d, checks the parquet file's SHA-256 and builds each row
from the release record: the options listed as (A), (B), ... after
"Choices:", the option's letter as the answer, type, subtype and ansType as
category, l2_category and ans_type, and every image as an RGB PNG.
BABYVISION_PARQUET reads a local copy of the file on a host without
internet access.

Both prepared files (babyvision_opencode and the question-only variant) are
byte-identical to the ones the TSV with md5 4216333e produced, so scores on
that copy stay comparable.

Both benchmarks declare prepare_dependencies: [pillow], as agentic_mme
does, since a dev install of Gym has no Pillow.

Signed-off-by: Danial MohseniTaheri <[email protected]>

* fix(visual_coding_opencode): grade only completed runs, count only the judge's own verdict, refuse several workers

- A response whose status is not completed (incomplete, or failed but still sent to verify by the outcome policy) scores 0 without a judge call, so an early \boxed{} guess in a failed run cannot score.
- parse_verdict takes the judge's last verdict object, and the judge prompt marks the model's text as data. A verdict object quoted from the model's text no longer masks the row, so a wrong answer cannot leave the loss by writing one.
- multiple_workers_unsupported_reason refuses num_workers > 1 before launch: lent sandboxes live in one worker's memory.
- Local copies of the response-text and last-\boxed{} helpers replace string_match's private ones. The string_match_reward diagnostic is dropped with them.
- Tests: the judge grading record (completed, failed, none), the close order after a failed stop, a failed run, the worker refusal. The session test moves from opencode_agent's suite into this environment's tests, without the two tests that restated YAML values, and with a text-only row for image_input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* build(visual_coding_opencode): check the OpenCode binary against its pin when the sandbox image builds

The Dockerfile downloads OpenCode 1.17.11 without a build argument and checks the binary against the SHA-256 that the config pins (sandbox_executable_sha256), so a mismatched image fails at build time instead of at the first episode. The config test requires both pins in the Dockerfile.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(visual_coding_opencode): head server reach under NeMo RL, tool images in training, OpenCode-only pairing

- Under NeMo RL the lent sandbox can reach Gym's head server, whose /global_config_dict_yaml returns the merged config. The README, tutorial and config comment state this limit.
- The images that read returns are staged by NeMo RL's single controller and recorded by local capture only with NVIDIA-NeMo#5837. Saved rollouts keep only the tool's text.
- The step-limit reason is gone (Gym NVIDIA-NeMo#5833 joins OpenCode's step-limit note under capture). Only the compaction reason stays.
- Only the policy model server advertises the host address. The question-only variant still sends the image. The pairing is OpenCode-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(agentic_if_realworld): drop the driver-test fingerprint pin

Main's NVIDIA-NeMo#5909 fixed the cause: the runtime fingerprint skips hidden folders and ignores the checkout's dirty flag. This PR no longer changes agentic_if_realworld.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* data(visual_coding_opencode): regenerate the example rollouts at the head

One OpenCode rollout of each of the 5 example rows, collected at 8a39cda.
All 5 runs complete; 4 are correct, and the 3D cube-counting row answers 20
where 19 is right (judge: different, reward 0). The prompt image is attached
to the first message, so no row reads the old input-media/None path. The rows
carry task_id and no longer carry string_match_reward.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* build(visual_coding_opencode): relock for openai 2.45.0

Main's NVIDIA-NeMo#5464 moved the shared openai pin to 2.45.0 and relocked every
component on main. This component was not on main yet, so its lock still had
2.44.0, and both the component-lock check and the server suite's
`uv sync --locked` failed in the merge queue. Regenerated with
scripts/component_locks.py (check_project, update=True); the only change is
openai 2.44.0 -> 2.45.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

---------

Signed-off-by: Yi-Fu Wu <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
Signed-off-by: Danial MohseniTaheri <[email protected]>
Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
yaoyu-33 added a commit that referenced this pull request Nov 11, 2026
…pture rule

Hermes passes prompt images as ordered Chat Completions image_url parts without
staging files; give it its own row and describe that path beside the staged one.
With #5833 merged, token capture keeps OpenCode's step-limit note chained, so
opencode_agent no longer refuses agent.build.steps under token capture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
gwarmstrong added a commit to gwarmstrong/Gym that referenced this pull request Nov 12, 2026
Main (NVIDIA-NeMo#5719, NVIDIA-NeMo#5833) now lets a session's opencode_config set
compaction.auto and agent.build.steps, through
_session_opencode_config_error. That validator replaces this branch's
permission/tools/compaction allowlist, so a session still refuses
compaction.prune, which rewrites old tool output and breaks the token
prefix. max_steps stays: it sets agent.build.steps in both execution
modes, over any value in opencode_config. The session test now uses
compaction {auto: false} and checks that max_steps replaces a configured
agent.build.steps.

Signed-off-by: gwarmstrong <[email protected]>
yfw added a commit that referenced this pull request Nov 13, 2026
#5719, which this branch was stacked on, is on main as 13881ca. Files this
PR does not change take main's version, which holds #5719's final form.
Conflicts in this PR's files were import lists only:
resources_servers/agentic_mme/app.py keeps this PR's imports (main added
is_nemo_gym_fastapi_entrypoint, which they include), and
test_existing_benchmarks.py imports both OpenCodeAgentConfig (main) and
_session_opencode_config_error (this PR).

opencode.yaml's step-limit comment now says what main does since #5833:
token capture keeps the calls after OpenCode's step-limit note chained,
instead of refusing a step limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
pzelasko pushed a commit to pzelasko/Gym that referenced this pull request Nov 16, 2026
…ough agent sessions (NVIDIA-NeMo#5720)

* feat(core): let a tool reply return images to the model

A resources-server tool can list images under tool_output_images, each a data URL with an optional label. Gym's
MCP layer returns them as MCP image content after the reply's text, each after its label. simple_agent shows them
to the model in a user message after the turn's tool outputs, since a Chat Completions tool message carries only
text.

A result with images carries no structured content unless the tool declares an output schema. OpenCode 1.17.11
replaces an MCP result's content with its structured content when that is present, which would drop the images.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(core): add LentSandboxes, a shared helper for the sandbox a resources server lends

Nine servers lend a per-episode sandbox, and each writes its own code to start it from config, describe it as
SandboxAccess, stop it at close (keeping it when the stop fails, so close can retry) and stop the rest at shutdown.
LentSandboxes holds that part. The server keeps its own ResourcesSessionFence and any other session state, and
calls lend() in its typed seed and release() in its typed close. Files are optional, so the same call lends a
sandbox with the task files or an empty one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(opencode_agent): allow compaction.auto and agent.build.steps in a session's config

Training on OpenCode rollouts needs one chain of model calls per rollout, and a fair comparison
with other harnesses needs a step budget. The session path accepted only permission and tools,
so neither could be set.

A session's opencode_config now also accepts compaction.auto (a boolean) and agent.build.steps
(a positive integer), and still refuses everything else, including compaction.prune (it rewrites
old tool output, which breaks the token prefix) and other agent fields (they would replace the
adapter's prompt, model or sampling). The replacement system prompt and the request sampling now
join each agent's entry instead of overwriting it, and the session copies opencode_config instead
of mutating the shared one.

Tests: the allowlist, both prompt modes, request sampling beside a step limit, and the real
OpenCode 1.17.11 binary reading steps from the session config (GYM_TEST_OPENCODE_BINARY).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(core): name ResourcesSessionLocks in the LentSandboxes docstring

Main split ResourcesSessionFence into ResourcesSessionLocks and ResourcesSessionFences (NVIDIA-NeMo#5083).
A server holds the session's ResourcesSessionLocks lock around lend() and release().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(core): finish LentSandboxes stops under cancellation and lend an operate descriptor

A lent sandbox now stops as SandboxSessionResourcesServer's do:

- Every stop is shielded from the cancellation of its request and bounded by STOP_TIMEOUT_S, so a close whose
  client disconnects still stops the sandbox, and a hung provider does not hold the close forever.
- release_all() stops the sandboxes concurrently, at most SHUTDOWN_STOP_CONCURRENCY at a time, because the
  supervisor gives a server about a second to exit.
- The harness gets an operate descriptor (serialize(scope="operate")): it may use the sandbox but not destroy it.

Each new test fails without its change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(core): say that providers without leases ignore the operate scope of a lent sandbox

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(opencode_agent): refuse agent.build.steps with token capture, and describe the step limit as OpenCode applies it

From the call at the step limit on, OpenCode 1.17.11 adds an assistant message (MAX_STEPS_PROMPT) to each request.
The fingerprint join of token capture finds no earlier call for such a request and records a capture failure, so
NeMo-RL drops the rollout as poisoned, with only the finalize/capture_poisoned_rollouts metric to show it. With
forest training the call starts a new chain instead, the same break that compaction.auto: false avoids. So with token
capture on, a session's seed now refuses agent.build.steps with 422. Eval without token capture is unchanged.

OpenCode also still offers the tools at the limit, with tool_choice auto, so a model that keeps calling them runs past
it. The docstring and the README now say so instead of "caps the model calls". The harness guide's OpenCode row lists
the session keys the README lists.

Test: with token capture on, a seed with agent.build.steps gets 422 and starts nothing; compaction.auto alone still
seeds. The test fails on the previous code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(core): read a null tool_output_images as no images, and keep a tool reply's JSON format

- A reply model may declare an optional image list, so FastAPI sends "tool_output_images": null in a reply without
  images. split_tool_output_images raised on it: simple_agent failed the rollout with HTTP 500, and MCP returned an
  error result for every call without an image. Null now means no images.
- simple_agent wrote the rest of an image reply with json.dumps defaults (spaces, \uXXXX escapes). It now uses the
  compact UTF-8 form FastAPI sends, so a tool's text is the same with and without images, and the same as the MCP
  tool result.
- The module docstring names the two readers of the key (simple_agent and the MCP endpoint), says where each puts
  the label and the image, and says that an agent that does not read the key passes the base64 data as text.

Tests: a null image list; the JSON format of an image reply; a plain-text or nested tool output that only names the
key stays unchanged (the JSONDecodeError and top-level-key fallbacks). The first two fail on the previous code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(core): cover the shielded stop of a lend that cannot describe its sandbox

lend() stops a new sandbox when serialize fails or the seed is cancelled while it runs. No test failed if that stop
went back to an unshielded sandbox.stop(): a cancelled seed then left the sandbox running until ttl_s, and
release_all() could not stop it because lend() had not stored it. The new test cancels the seed during serialize
and fails with that change.

The docstring now says "episode seed" and "episode close", the glossary names, and says what a stop does: it goes
on when its request is cancelled and gives up after STOP_TIMEOUT_S.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(core): document tool_output_images on the MCP Resources Server page

A new section says how a tool returns images (the key, ToolOutputImage, a short example), what the model gets from
the /mcp endpoint, from simple_agent and from an agent that does not read the key, that null means no images, and
that an agent which puts the images inside its tool output (Codex) needs inline_tool_output_images on vllm_model.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(opencode): accept NeMo RL's row output limit when OpenCode stays within it

NeMo RL sets max_output_tokens on every row (its generation limit). An OpenCode sandbox
session refused the field, so an OpenCode training run under NeMo RL failed its first
episode with 422 "does not support request field max_output_tokens", and RL stopped the run.

A session now accepts max_output_tokens when it is at least the configured
max_output_tokens, which is OpenCode's own limit for each model call. A smaller value is
still refused, so nothing is silently ignored.

Test: a NeMo RL row (temperature 1.0, top_p 1.0, max_output_tokens 4096 or 16384 with a
configured limit of 4096) passes, and OpenCode keeps the limit of 4096. The test fails
without this change. The existing refusal of max_output_tokens 123 still passes.
819 OpenCode tests pass. The same change ran in the run C and D smokes (3 steps each).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(core): let LentSandboxes lend a sandbox that reaches only the model server

A harness that creates its own sandbox can set network_access model_only, so the sandbox reaches only the model
server. A sandbox that a resources server lends kept the provider's network, and the harness that borrows it cannot
change that, so a lent sandbox could reach the internet.

LentSandboxes now takes network_access ("inherit" by default, or "model_only") and model_server. With model_only,
lend() adds the same egress rule that an agent-owned sandbox gets: deny by default, and allow the model server's host
on every port. A provider without network policies, or a model server on a loopback address, refuses the seed with
HTTP 422 before any sandbox starts. Setting model_only together with an explicit
sandbox_config.provider_options.network_policy is a configuration error.

restricted_network_policy and its host check move from nemo_gym.agents.agent_tools to nemo_gym.utils.network_policy,
since server_runtime sits below agents in the package layers. agent_tools imports them, so the old names still work.

Test: tests/unit_tests/server_runtime/test_sandbox_lending.py (13 passed), the agents and server_runtime unit tests,
and the import-linter hook.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
(cherry picked from commit b0abe8e)

* feat(opencode_agent): mark a response whose prompt reached OpenCode's step limit

With agent.build.steps set, OpenCode 1.17.11's `opencode run` appends a note that asks for a final
answer from call number `steps` on. It still offers the tools, so the model may answer or keep calling
tools. An environment whose own agent scores an episode that runs out of rounds as 0 needs to know
when a rollout reached the limit, because otherwise the harness rewards long tool loops: a policy
trained with the answer at the limit scored learned to use every step.

The OpenCode agent now sets response metadata `harness_step_limit_reached: "true"` when the last
prompt made at least `steps` model calls (one saved assistant message per call). The new
HARNESS_STEP_LIMIT_METADATA_KEY in nemo_gym.agents names it for any harness adapter. The mark only
reports the limit; the environment decides how to score it.

Tests: opencode_agent 825 passed, 23 skipped (new: the mark at, above and below the limit, and
counting only the last prompt). tests/unit_tests/agents and test_public_api: 660 passed; the 3
test_outcome_policy failures need cloudpickle, which the local environment lacks, and fail the same
without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(opencode_agent): allow agent.build.steps with token capture when Gym NVIDIA-NeMo#5833's capture fix is installed

A seed with token capture refused agent.build.steps, because OpenCode's step-limit note made capture poison the
next call. Gym NVIDIA-NeMo#5833 fixes that in token capture and adds nemo_gym/models/token_capture/harness_notes.py. The seed
now refuses the setting only when that file is missing, so a branch that merges both PRs can train with a step
limit. The check reads the installed package's files and imports nothing.

TODO: remove the check once NVIDIA-NeMo#5833 is on main.

Tests: the refusal without the fix, the acceptance with it, and the file check. opencode_agent: 832 passed,
23 skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(opencode_agent): return a session's own turns at close by default

return_session_trajectory now defaults to true, in the agent config class and in configs/opencode_agent.yaml.
Close then returns OpenCode's own turns (one per saved assistant reply, compaction summaries left out), so rollout
collection joins each captured model call to the step that made it. With false, every call is reported as an
unmatched assistant message and the harness evidence checks become noise. Training data does not change, because
training uses the captured calls.

Tests: the default in the config class and the shipped config; the existing parametrized test keeps both values.
opencode_agent, rollouts and the repo session contract: 3428 passed, 23 skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(sandbox): let a lent sandbox reach the servers whose tools the harness calls

LentSandboxes takes network_access="model_and_tools" with tool_servers,
as agent-owned sandboxes already do. The egress rule allows the model
server's host and the host of each tool server, such as the resources
server that serves its tools over MCP. Before, a lent sandbox whose
harness calls MCP tools could only keep the provider's network.

tool_servers is refused without model_and_tools, and model_and_tools is
refused without tool_servers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(opencode_agent): find Gym NVIDIA-NeMo#5833's harness notes by import, in either layout

The check for NVIDIA-NeMo#5833's capture fix probed for nemo_gym/models/token_capture/harness_notes.py. NVIDIA-NeMo#5833 now keeps the
notes in a harness_notes/ package, so the probe returned False even with the fix installed, and a seed with token
capture would refuse agent.build.steps for good. The check now imports the module and looks for an OpenCode entry in
HARNESS_NOTES, which works for a module or a package and does not turn on for an unrelated file at that path.

Tests: no module; a module or a package with an OpenCode note, a Pi note only, or no notes. Checked by hand against
NVIDIA-NeMo#5833's package at 1c0cd40: False without it, True with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(core): check a tool's images as prompt images are checked

ToolOutputImage checked only the data URL's prefix, so invalid base64 or JPEG bytes labeled image/png passed and
failed later, at the model server or in the harness, as a rollout error. It now decodes the URL with
MediaFile.from_data_uri, the rule for prompt images: valid base64 holding a PNG, JPEG, GIF or WebP image, any case,
image/jpg allowed. The URL is written again from the content, so its label always matches the bytes. A bad image is
again a ValidationError, an error of the tool.

Tests: invalid base64, base64 that is not an image, and a PNG signature without IHDR are refused; a mislabeled JPEG
and image/JPG are relabeled. Tool-image fixtures use a real 1x1 PNG. The MCP page says how images are checked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* chore(opencode_agent): say what return_session_trajectory false costs, and drop agentic_if's copy of the default

The opencode_agent config's comment now says what false costs: one turn per captured call, so evidence checks report
every call as unmatched, and compaction summaries count as steps. agentic_if set the same value as the new default,
so its line goes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(opencode_agent): count compaction passes toward OpenCode's step limit, as OpenCode does

reached_step_limit() took the last user message as the prompt and counted the assistant messages after it. An
automatic compaction adds user messages (the compaction marker, then a synthetic "Continue" text or a replay of the
prompt), so the count restarted after a compaction, and a prompt that reached the limit was not marked.

OpenCode 1.17.11's session loop (session/prompt.ts) counts passes: each build call, each compaction summary call,
and a pass that only starts a compaction after a finished call overflowed (session/compaction.ts saves its marker
without an overflow field). The counter is not reset by compaction. The check now skips the user messages that
compaction adds when it finds the prompt, and counts those passes.

Tests: five exports in OpenCode's message shapes, the overflow-pass and in-call compaction paths, a compaction with
no continuing message, and a new prompt after a compacted one. Four fail on the old count. The README says how the
limit is counted and when token capture allows it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(core): stop a lent sandbox whose seed is cancelled during file delivery, and keep a failed seed's stop for retry

Two cleanup gaps in LentSandboxes.lend():

- A seed cancelled while the new sandbox received its files left the sandbox running. AsyncSandbox.start() stops
  the sandbox when an upload fails, but that stop is not shielded, so it is cancelled with the request. lend() now
  runs start() inside its own failure path, whose shielded, bounded _stop() finishes the stop; after a stop that
  did finish, _stop() does nothing.
- When a failed seed's stop failed or timed out, the sandbox was dropped, so no close or shutdown could stop it.
  It is now kept apart from the lent sandboxes: get() never returns it, release() and release_all() retry its stop,
  and the session's next lend stops it before it starts another sandbox (a failed stop there fails the lend).

Tests: a seed cancelled during upload_file() with the real AsyncSandbox.start() and a provider close that crosses an
AnyIO checkpoint; a failed seed whose first stop fails or hangs, stopped later by release() or release_all(); a
repeated seed that stops the earlier sandbox first, and one that fails while that stop still fails. The seven new
tests fail without the fix. test_sandbox_lending.py and tests/unit_tests/sandbox: 2028 passed, 8 skipped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(agent-server): list attachment in OpenCode's session settings, and when token capture allows the step limit

The harness guide's OpenCode row now matches the README: a session's opencode_config also accepts attachment (from
NVIDIA-NeMo#4922), and agent.build.steps works with token capture once the harness notes know OpenCode's step-limit message.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* refactor(agentic_mme): move the image tools from the agent to the resources server

The resources server serves the same 14 image tools to session harnesses (next commit), so the tools move to
resources_servers/agentic_mme/image_tools.py, unchanged. The Agentic-MME agent imports them from there. Both
components pin the same OpenCV build in their lock policy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(agentic_mme): run Agentic-MME with several harnesses through agent sessions

The resources server now supports agent sessions and three new settings next to the Agentic-MME agent:
- server_tools.yaml: simple_agent with the 14 image tools served by the resources server, which return their new
  image in the tool reply (tool_output_images).
- opencode.yaml: OpenCode in a sandbox that the server lends at seed (LentSandboxes), with the task images as files;
  sandbox_no_internet.yaml closes its network to the model server.
- opencode_server_tools.yaml: OpenCode with the 14 image tools over MCP.

prepare.py writes the rows of every setting. score_step_limit_answer (default false) scores an answer at OpenCode's
step limit 0, as the Agentic-MME agent scores an episode that runs out of rounds; step_limit_reached shows the share
of such rollouts. The OpenCode settings set an episode deadline below the sandbox TTL, and a test keeps it there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(agentic_mme_agent): run the Agentic-MME agent as an agent session

The agent now serves agent sessions under the Environment Server: one activation per session, an identical retry
joins it, and close cancels it. Under a session, a failed model call fails the response with its cause (the shared
agent outcome), and the Environment Server grades or retries it. On /run the behavior stays as on main: a context or
request-size refusal ends the episode unanswered, and any other failure raises PolicyRequestError into the failures
sidecar.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): pass the schema and agent-session checks on main

Main now checks that every committed dataset row matches its schema and
that the list of agents with agent sessions matches the agent apps.

- Declare image_files in the agentic_mme task schema. The image file
  model moves from app.py to task_data.py so both use one definition.
- Add agentic_mme_agent to AGENT_SESSION_AGENT_TYPES.
- The OpenCode configs name the agentic_mme resources server on the
  agent block, so their example rows are checked against its schema
  (an agent with no resources_server reference must ship its own).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(agentic_mme): set the lent sandbox's network from config

sandbox_network_access (inherit, model_only or model_and_tools) and
sandbox_model_server pass through to LentSandboxes; model_and_tools adds
this resources server as a tool server and needs expose_tools_over_mcp.

opencode.yaml now lends a model_only sandbox and runs the OpenCode copy
that the sandbox image holds; opencode_server_tools.yaml lends a
model_and_tools sandbox, so OpenCode reaches the model and this server's
/mcp and nothing else. sandbox_no_internet.yaml, which did this with a
hand-written allow list of one address, is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(agentic_mme): declare image input in the OpenCode recipes

OpenCode passes an image that a tool returns to the model only when the model declares image input; otherwise it
sends an error text in its place. Since NVIDIA-NeMo#4922, opencode_agent declares it when the prompt has images or when
image_input is true. Agentic-MME prompts hold the task images, so it was declared already; image_input: true keeps it
declared for any row, as NVIDIA-NeMo#4922 asks of configs whose tools return images. Both recipes get it from opencode.yaml.

Tests: both recipes load with image_input true. agentic_mme tests: 151 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(agentic_mme): bake OpenCode's plugin dependencies into the sandbox image

opencode_agent always configures a plugin, so OpenCode 1.17.11 installs @opencode-ai/plugin from npm at each start
unless the dependencies are present. The lent sandbox reaches only the model server (and, with server tools, this
server), so each start waited about 70 s for that install to fail before the first model call.

The image now builds the dependency archive as visual_coding_opencode's does: from a copy of
benchmarks/agentic_if/opencode's lockfile with the recipe in benchmarks/agentic_if/README.md (Node 24.15.0 with
npm 11.12.1, then GNU tar 1.34 and GNU gzip 1.10). The build checks the archive against agentic_if's pin
(77b03eba...), and opencode.yaml sets sandbox_plugin_dependencies_path and _sha256; opencode_server_tools.yaml
inherits them.

Checked: the plugin-archive stage builds and its sha256sum -c passes. A test keeps the lockfile copy, the Dockerfile
and the pin in step. agentic_mme tests: 152 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): keep the OpenCode sandbox off every server but the ones it calls

The lent sandbox's egress rule opens every port of the policy model's host, and NeMo RL gives every server without
its own host that address. So sandbox code could call the judge (spending its API key), the agent's /run (which runs
OpenCode on the host), and the resources and Environment Servers (which start sandboxes and episodes).

opencode.yaml now sets host 127.0.0.1 on the judge, the agent, the resources server and the Environment Server. All
their callers run on the same host. opencode_server_tools.yaml sets the resources server's host back to null, because
OpenCode calls its /mcp route from the sandbox; it then takes the reachable address as before.

Tests: a parse with NeMo RL's default_host gives the node's address only to the policy model (and, for server tools,
the resources server). agentic_mme tests: 154 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): refuse cookie seeds when the server keeps episode state, harden the judge, and admit episodes at the agent's rate

The visual_coding_opencode review (NVIDIA-NeMo#5839) found these in code that Agentic-MME shares in shape:

- Seeds. The cookie arm has BeforeValidator(reject_partial_typed_seed), so a malformed typed seed gets 422. A server
  that lends a sandbox or serves the image tools refuses a cookie seed with 422 too: it would get neither, and an
  agent's own /run, which seeds that way, runs its harness on its own host.
- Judge. The verdict comes from every JSON object in the reply that has one, so a brace ahead of it no longer masks
  the row, and objects that disagree stay a judge failure. A reply with no choices is a judge failure. Judged rows
  are graded inside observe_llm_judge_grading with record_parsed_judge_verdict, so they carry a grading record.
  judge_model is removed: the judge's model server picks the model.
- Admission. opencode.yaml's Environment Server admits 32 episodes at a time (the agent's concurrency), because
  each seed starts a sandbox; the deadline stays 5400 s, below the sandbox's 7200 s TTL.
- Data. prepare.py also writes task_id at the row's top level, where `gym eval plan` reads it.
- README: a network rule opens every port of an allowed host (hence the 127.0.0.1 pins), blocks raw IPs only with
  dns+nft, and admission follows the agent's concurrency.

Tests: verdict parsing, empty choices, no model in the judge request, seed refusals with and without server tools,
the stateless server, admission and the top-level task_id. Ten new cases fail on the old code. 165 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(agentic_mme): import the parser config from nemo_gym.config

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): keep the head server on loopback in the OpenCode recipes

The lent sandbox's network rule opens every port of the policy model's host,
and a launcher's default_host also becomes the head server's address. The
head server returns the whole config, keys included, without authentication,
so sandbox code could read the credentials. opencode.yaml now sets
head_server.host 127.0.0.1, which opencode_server_tools.yaml inherits; the
policy model and, with server tools, the resources server keep the reachable
address. NeMo RL sets head_server in its own initial config, which wins over
the recipe, so under NeMo RL the head server stays on the node's address; the
README says so.

Tests: the launcher-host test checks the head server, and a new test checks it
for both recipes with and without absolute_ip_server_types.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): grade only a context-limit refusal under agent sessions

On /run, the Agentic-MME agent scores a model call refused for its context or
request size as 0 and raises any other failed call into the failures sidecar.
Under an agent session it reported every refusal as model_request_error with
its status, and the Environment Server's default policy grades a 400, so a
serving limit (vLLM's per-prompt image limit) or an unsupported parameter
scored 0.

The agent now reports a context or request-size refusal as
model_context_limit, and configs/agentic_mme.yaml sets the Environment
Server's agent_outcome_policy: model_context_limit is graded, and 400, 413 and
422 fail ungraded. The policy applies to every harness of the benchmark:
OpenCode already reports a context overflow as model_context_limit, so it now
scores 0 there too; simple_agent reports a context limit as a plain 400, so in
server_tools.yaml that rollout fails ungraded. The benchmark README says so.

Tests: a session drives a crop and then a context-limit 400 and 413, an
image-limit 400, an unsupported-parameter 400, a 503 and a 401, and checks the
reported outcome, the kept tool work and the action under the benchmark's
policy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): prepare each recipe's own file in the locked project

gym eval prepare requires prepare() to return the dataset's jsonl_fpath, but
prepare.py returns the atomic track's file, so the three new recipes failed
with ConfigError. prepare_server_tools.py, prepare_opencode.py and
prepare_opencode_server_tools.py run the shared conversion and return their
track's file, and each recipe points prepare_script at its own.

prepare.py also builds the server-tools rows from the image tools, which import
OpenCV, and the recipes declared no preparation dependencies. config.yaml now
sets prepare_project: resources_servers/agentic_mme in place of
prepare_dependencies: [pillow], and each recipe's benchmark dataset sets it.

Tests: for all four recipes, the preparer returns the dataset's jsonl_fpath and
the dataset sets prepare_project. Checked: gym eval prepare of all four recipes
on a one-task local release finishes in the locked project's environment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): release state on retire, order tool calls with close, refuse unreadable images

- Retire. The server keeps its own sessions, so the inherited
  retire_session_state did nothing, and a retired attempt kept its workspace
  and lent sandbox. It now stops the sandbox and drops the workspace under the
  session lock, without close's fence; a failed stop keeps both for a retry.
- Tool calls. A call checked the fence before it waited on its own lock, which
  close did not take, so a call queued behind close changed the dropped
  workspace and returned success. A call now takes the session's lifecycle
  lock and checks the fence and the session under it. A client disconnect
  cancelled the await but not the worker thread, so the next call could run
  beside it; the await now runs in a shielded anyio cancel scope, so the lock
  is held until the worker finishes.
- Seed. A task image that exists but cannot be read raised a 500, which the
  Environment Server retries with the same input; it is now a 422.

Tests: retire with a failing first stop; close against a running and a queued
call; a call cancelled through an anyio cancel scope; an unreadable image. All
four fail on the old code.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): keep the tool trace and its counts under agent sessions

The default recipe runs the agent through agent sessions, and the session
path dropped the tool trace: the Environment Server sends verify only the
task data and the response, and the model's tool outputs leave out each
retrieval call's provider answer, leak-guard count and cache outcome. A
collected row therefore lost tool_trace, the counts and overthink.

The agent now puts the trace in response.metrics, which the model never
sees. Verify moves it into the result and derives the counts and
overthink from it, so /run and a session give the same fields, and the
row stores the trace once. /run takes them from verify instead of
computing them itself.

A test collects a rollout of the default recipe through collection, the
single-agent-turn Environment Server and the agent's session routes, with
a live search result, and checks the trace, its raw, contaminated and
cache keys, and the counts. It fails on the previous head.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): mask a lost image session and record policy_error under sessions

- A tool call for a session this server does not hold (never seeded, or lost to
  a restart or a retired attempt) raises ResourcesSessionLostError (404,
  session_lost) instead of 409, which harnesses passed to the model as an
  ordinary tool error. The session middleware gives every request an ID, so the
  two cases look alike; this follows automationbench, enterpriseops_gym and
  gdpval.
- With serve_image_tools on, verify masks a session this server does not hold
  (lost_session_verification), as for a closed session.
- verify records a failed response (a context-limit refusal that the outcome
  policy grades) as failure_reason "policy_error" with the harness's message in
  policy_error, as the agent's /run does.
- serve_image_tools sets cv2.setNumThreads(1), as the agent does, since the
  tools run in to_thread workers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): classify a failed model reply as simple_agent's session branch does

ServerClient.post returns a non-ok reply without raising, so the
ClientResponseError branch never ran and a confirmed policy timeout was
reported as model_request_error/500 without its failure report.

- The agent now calls raise_for_status on each model reply. A refusal is
  classified from the error: model_context_limit for a context or request-size
  refusal, model_policy_response_timeout when the model server's report shows
  every attempt timed out, model_request_error with the status for another 4xx
  or 5xx, and unknown for a 3xx (a redirect loop), which AgentOutcome cannot
  carry. The response keeps the failure report, merged with the model server's.
- PolicyCallError becomes PolicyCallFailure: it holds an AgentOutcome and the
  message, and derives infrastructure from the outcome. It stays local.
- Tests: a timed-out 500 keeps its cause and the model server's report; a
  default-recipe rollout collected through the Environment Server that ends on
  a context-limit refusal after one crop scores 0, is graded, counts the crop
  and records policy_error. The refused-reply fakes now raise as aiohttp does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(agentic_mme): bound server-tools episodes and correct replay and head-server notes

- server_tools.yaml: the header says the track matches config.yaml only on
  rollouts without a context overflow (simple_agent reports one as a plain 400,
  which this benchmark fails ungraded) and asks for each track's failed-rollout
  count. The Environment Server admits 32 episodes at a time
  (max_concurrent_episodes, queue_timeout_seconds), which bounds the image
  workspaces on the resources server.
- READMEs: replay works only on the agent's own /run; repeatable runs use the
  shared cache with cache_write: false.
- Resources README: under NeMo RL, do not run opencode.yaml with real keys
  until the head server stops returning secrets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): keep a context-limit refusal graded when the reply carries a report

The policy model server is a Gym server, so its 400 carries a failure report
that selects the refused model request (model_request_error). The Environment
Server fails a reply whose selected cause does not match its outcome
(model_context_limit), so the context-limit rule stopped grading once the agent
attached the report. The agent now keeps that report's events but selects no
cause for a context-limit refusal, and the outcome policy grades it.

The collected context-limit test now gives the refusal a model-server report;
it fails without this change. The timeout test checks that the Environment
Server rebuilds the timeout as the reply's selected cause, so its timeout rule
(retry by default) applies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(agentic_mme): drop the test that only fixes the OpenCode recipes' image_input

The review asked for fewer tests of config values. The deadline and admission tests stay, because each compares
settings in two blocks that gym env validate does not compare.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* chore(agentic_mme): regenerate the example rollouts through the agent session config

The old rows came from the relay to the agent's /run and named the old Environment Server instance. These come from
resources_servers/agentic_mme/configs/agentic_mme.yaml at a67d4e0: the agent's session routes under
single_agent_turn_legacy, instance agentic_mme_environment_server, 5 example rows, a hosted vision-language policy.
All 5 score 1 after one crop; the rows now carry evaluation_completed, step_limit_reached and failure_report.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_mme): report a model server queue timeout with its own kind

Main's NVIDIA-NeMo#5686 makes policy_timeout_failure return model_server_queue_timeout when every attempt waited in the
model server's queue, and simple_agent's session branch now reports the failure's own kind. The agent still
reported model_policy_response_timeout, which no longer matches the cause its report selects, so the Environment
Server would fail the reply instead of applying the queue timeout's rule (retry by default). The agent now reports
the timeout's own kind, as simple_agent does.

The timeout test covers a report without a queue reading, with an empty queue, and with requests waiting; the
queued case fails without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

---------

Signed-off-by: Yi-Fu Wu <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
gwarmstrong added a commit to gwarmstrong/Gym that referenced this pull request Nov 16, 2026
… reports

Main's NVIDIA-NeMo#5719 already admits compaction.auto and agent.build.steps in a
session's opencode_config, so this PR keeps only max_steps. The new test
covers the step-limit metadata with max_steps alone and over a configured
agent.build.steps. The README no longer says a session with token capture
refuses agent.build.steps: since NVIDIA-NeMo#5833, token capture keeps the calls after
OpenCode's step-limit note chained.

Signed-off-by: gwarmstrong <[email protected]>

This branch was previously deployed

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

Labels

area:training Training framework integrations and training-data interfaces bug Something isn't working 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