Repository navigation
fix: read OpenCode's tool placeholder in token capture and enforce opencode_agent permissions - #5387
Conversation
run_examples now stamps each unstamped materialized row (task_id.taskset + task_input) with the Environment Server its taskset routes to, as gym eval run does while preprocessing, and raises before any POST when a taskset has no route. Without this, rows a trainer hands straight from the dataset fall through to resolve_task_sources and fail. A row or caller that already names a server keeps it. run_examples (only) also stamps those rows with the server's attributed agent_ref, so callers keyed on agent_ref.name (NeMo RL) work; Gym's own stored records stay unattributed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
run_examples(..., episode_records=True) resolves a materialized row's result to the flat record gym eval run stores (_episode_record plus the row's task_data provenance), on both the awaited and the aclose_and_drain paths, so callers such as NeMo RL stop importing private helpers to unwrap a BaseEpisodeResponse. A handled Environment Server failure comes back with reward 0.0 and mask_sample True. gym eval run and run_examples now share one helper for that record; the default keeps raw replies. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
…o its served call
OpenCode echoes a served call to a tool it does not offer as a call to its `invalid` tool with the
same ID and arguments exactly {tool, error}. The whole-turn fingerprint now hashes such a call under the
served name, so its next request resolves its parent instead of being poisoned as unresolved_parent.
Any other rename still does not match, and no fingerprint version or ledger column changes. The
unresolved-parent warning now also logs the resolution reason and the request item count.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>
OpenCode places a `tools` map's entries before the permission map's "*": allow and applies the last matching rule, so opencode_agent.yaml's tools map voided the default profile's command denies and its webfetch/websearch/skill restrictions. Drop the whole opencode_config block from opencode_agent.yaml (an empty block would null out the profile) and deny webfetch, websearch and skill right after "*" in permissions/default.yaml. This changes behaviour and scores of every opencode_agent run. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
With episode_records, aclose_and_drain converted each drained outcome inline, so one reply the record conversion rejects raised out of the drain and lost every other outcome, which are transferred only once. That outcome now raises when awaited, as it does on the awaited path. The run_examples docstring now says that the taskset route, not a row's agent_ref, picks a materialized row's Environment Server, and when no agent is bound. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
Pin the exact-name, JSON-object and string-type guards of the placeholder mapping at the fingerprint, in the Chat Completions shape OpenCode sends too, and cover terminal attribution's tool-ID reading, which now matches a trailing placeholder to the served call it names. Document that the mapping moves the whole-turn key of a served call that itself has the placeholder's shape (rare), without a fingerprint version change. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
…l tasks Now that the command filters apply, note that they also deny Git history commands and git fetch, which some terminal tasks need, and how to allow them per run. State precisely how a tools map voids permission rules, and update the partner_if comments that pointed at the tools map opencode_agent.yaml no longer sets. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
Drop the run-specific frequency from _served_tool_name's docstring; the rare-collision caveat stays. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
Resolve the conflict with #3302 (persist failures and resume unfinished evaluations) in nemo_gym/rollout_collection.py: - Keep main's gym eval run store loop. The branch's refactor of that loop onto _stored_episode_record no longer applies: main now validates replies at dispatch and stores failures as compatibility rows. - episode_records translates a BaseEpisodeResponse through main's _native_episode_record, so the reply's episode and task identity is checked as gym eval run checks it. - episode_records masks a handled Environment Server failure with matches_failure_class(record, {ENVIRONMENT_SERVER_FAILURE_CLASS}). Since #3302 a failure that names a failure_kind (for example harbor:task_deadline) carries that kind as its class and environment_server_failed as its legacy class; an exact class check would leave it unmasked. - _RowResultIterator keeps the branch's per-outcome conversion with main's wider result type. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
Since #3302 a handled Environment Server failure that names a failure_kind carries the kind as its _ng_failure_class. Test that episode_records still masks it (reward 0.0, mask_sample True) on the awaited and drained paths, and that a reply for another attempt or task raises StaleRolloutResult or InvalidRolloutResult from its own outcome. Rename _stored_episode_record to _flat_episode_record: gym eval run no longer stores this record, so the docstrings now describe it as a flat episode record and say why episode_records exists next to run_outcomes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
The page told users to select OpenCode's tools with an opencode_config.tools map. With opencode_agent, OpenCode places that map's keys before the permission profile's "*": allow, which overrides them. Point to permission rules instead, as the opencode_agent README does. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
|
/ok to test 68dc30d |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE
Two RISK findings remain: episode_records=True can accept malformed Environment Server replies without validating their identity, and the changed fallback hash breaks replay of some existing custody-ledger rows.
I inspected all 15 changed files and their directly affected contracts, callers, and failure paths. I found no additional material issue in the OpenCode permission configuration. This was a static review; I couldn't execute tests or independently verify the reported smoke runs.
Inline comments (escaped v1):
-
nemo_gym/rollout_collection.pyline 691: RISK — Validate every materialized HTTP reply before flattening itFailure: For a materialized row, return HTTP 200 with
{"reward":1.0}or an episode envelope whoseepisode_idis missing/null. Withepisode_records=True,_is_episode_responseis false, so this branch returns the malformed reply with provenance instead of raisingInvalidRolloutResult. Non-object JSON also passes through the caller guard. The HTTP dispatch path doesn't validate these replies becauserun_examplesenables neithertyped_outcomesnorvalidate_results. A trainer can therefore receive an apparent reward without validated task/attempt identity.Correction: Could you distinguish HTTP replies from collector-built outcomes and apply
_native_episode_recordto every materialized HTTP reply when this option is enabled, without first requiring it to look valid? Keep budget-drained and routed transport-failure records outside that validation. The invariant is that only collector-built outcomes may bypass the episode envelope check. The exact origin-metadata plumbing needs verification; validating every dictionary here would incorrectly reject legitimate collector-built records.Preservation and acceptance — proposed tests, not executed: Using the new materialized-row fixture, return
{"reward":1.0},null,[], and envelopes with missing/null identity fields. Each awaited outcome should raiseInvalidRolloutResult; draining should preserve each exception without losing another valid outcome. Retain valid success flattening and digest propagation, stale-attempt/task rejection, handled-failure masking with and withoutfailure_kind, unmasked budget-drained records, routed transport-failure records, unchanged flat-row results, and unchanged raw replies whenepisode_records=False. -
nemo_gym/models/token_capture/lineage.pyline 1184: RISK — Preserve identical ledger replay across the fallback-hash changeFailure: Persist a custody commit using base with served output
[{"type":"function_call","call_id":"c","name":"invalid","arguments":"{\"tool\":\"Read\",\"error\":\"bad\"}"}], then reopen/import that ledger under head and replay the identicalCaptureLedgerCommit. The base fingerprint hashesinvalid; the new normalization hashesRead. Both retain fingerprint version 4._recordrecomputes the persisted key and this equality check raisesconflicting lineage record, violating the identical-replay no-op contract. An old row also loses its argument-tolerant match when only the echoederrorchanges: strict matching misses, and the custody reader compares the old stored key with the new incoming key. This affects existing ledgers containing model-emitted placeholder-shaped calls, not ordinary served tool calls.Correction: Could you preserve legacy fallback-key semantics in
FileLineageStore._recordand_resolve_row, either through explicit fallback-algorithm versioning or by retaining the stored hash algorithm and adding compatible request-side lookup? Identical replay must remain a no-op, genuine payload conflicts must still fail, and compatible fallback candidates must be pooled before deciding uniqueness. The strict fingerprint needn't change. The migration details need verification against checkpoint readers, so I don't have a sufficiently certain small patch to suggest.Preservation and acceptance — proposed tests, not executed: Add a base-format ledger fixture for the output above. Import it into head, replay the identical commit, and expect one row with no exception. Resolve a continuation changing only its echoed
errorand expect the original parent. Retain ordinaryRead→ exactinvalidplaceholder resolution, rejection of other names/malformed shapes, ambiguity for differing-token siblings, and checkpoint custody round-trips. Changing actual commit data must still raise a conflict.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
episode_records now treats every Environment Server reply for a materialized row the same way: - A reply that is not a BaseEpisodeResponse for the dispatched episode and task, or whose reward is present but not a finite number, raises InvalidRolloutResult (StaleRolloutResult for another attempt) from its own outcome. Before, a non-episode payload came back raw and a string or null reward came back as a score. - A reply that carries any failure class is masked (reward 0.0, mask_sample True). That now includes a result marked judge_failed, whose reward is a placeholder; before, only Environment Server failures were masked. Results Gym built itself (drained rows, routed /run failures) stay unmasked. The reject-reply test now checks the exact error type. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
The example rule was already in opencode_agent's profile, and a "*": deny override does not cover edit and bash, which the profile allows after its "*" rule. Use task: deny as the example and name the edit and bash maps. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
|
/ok to test e6cfd10 |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP
No qualifying findings.
The prior public-API import failure is fixed in the OpenCode test imports. The session-export regression retains both outcomes: the matching placeholder selects the served call without masking, while a different tool name remains unattributed and masked.
I inspected all 15 changed files and their directly affected callers, contracts, tests and failure paths. Stored fingerprint semantics remain unchanged, placeholder lookup pools all readings within its bound, and terminal attribution handles following or interleaved tool results. The permission profile reaches both local and session configuration paths. I checked that topic directly because its delegated report wasn't available.
This was a static review; I didn't execute tests or independently verify the reported smoke and replay runs. OpenCode's native permission evaluator isn't included in the supplied tree, so I verified Gym's configuration plumbing rather than upstream rule precedence.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
|
Fix for OpenCode token capture LGTM |
Conflicts: - nemo_gym/models/token_capture/sink.py: main renamed rollout_id to capture_key in the unresolved-parent warning; kept the rename and this branch's reason and request-item count. - responses_api_agents/opencode_agent/configs/opencode_agent.yaml: kept main's new owner-extension keys and this branch's removal of the opencode_config.tools map. Follow-ups for main's API changes: tests build TokenEntry with capture_key, and the opencode_agent test imports the token-capture names from nemo_gym.models.token_capture, their public API since #5525. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
|
/ok to test 46e3563 |
agentic_if (#4959), merged into main alongside this branch, adds the same webfetch/websearch/skill denies after the default permission map and checks that they are the map's last keys. With this profile declaring them right after "*", the merged map kept them in that earlier position. Declaring them last keeps both layouts the same; the denies apply either way, since they do not overlap the edit and bash rules. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adil Asif <[email protected]>
|
/ok to test 22d207e |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42339805160 |
What and why
Two fixes found while training Terminal-Bench 2.1 with OpenCode on NeMo RL. No issue was filed. NeMo RL's side of
running Environment Server tasksets (routing materialized rows and unwrapping episode replies) is
NVIDIA-NeMo/RL#4429. This PR covers the two problems only Gym can fix.
Token capture reads OpenCode's unavailable-tool placeholder.
invalid {tool, error}with thesame call ID. The next request then has no parent, and NeMo RL masks the episode: 16% of OpenCode episodes when
our TB2.1 captures are replayed through main.
sequenceDiagram participant O as OpenCode participant G as Gym model server (token capture) participant M as Model O->>G: call N G->>M: generate M-->>G: tool call str_replace_editor (id call_7) G-->>O: reply (stored key: call_7 → str_replace_editor) Note over O: tool not offered, so OpenCode echoes it back<br/>as invalid {tool: str_replace_editor, error} O->>G: call N+1 (history has call_7 as invalid) Note over G: main: no parent matches → episode masked<br/>this PR: reads the placeholder as str_replace_editor → parent = call N G->>M: generate, starting from call N's exact tokensand picks a parent only if one candidate matches across all readings. Above 6 such calls in one turn it abstains.
Stored keys and
FINGERPRINT_VERSIONare unchanged.and its error result still names its final call. It keeps the strict comparison when another item reuses the call
ID or a reasoning item follows the placeholder. It reads only the last call, so it can attribute a turn with more
than 6 placeholders that the turn-level fallback abstains on.
vLLM's tool parsers make them. Under a scheme that repeats IDs, for example a per-turn
call_0or the same IDs ona retry, two captured calls can share an ID, and the fallback can pick the wrong one or report ambiguity. Lookups
also get slower: up to 65 fingerprint passes for a turn with 6 placeholders, and cubic growth in the turn count
when IDs repeat across turns.
Read->read) or the echo rewritesother harnesses make (for example stripped
<think>blocks). Those need a wider look from the token-captureowners.
opencode_agentenforces its permission profile.opencode_config.toolsmap (feat(agent): run OpenCode in task sandboxes #3639) voided every permission rule in OpenCode 1.17.11. OpenCode places thetool keys before
"*": allow, and the last matching rule wins.webfetch,websearchandskillare denied inpermissions/default.yaml.toolsmap.Compatibility
opencode_agentruns now get the bash deny-list, and 8 tools instead of 10. The deny-listalso blocks Git history commands and
git fetch, which some terminal tasks need; the README shows how to allow themper run.
swe_togetherkeeps its owntoolsmap (pre-existing), andgdpval/opencode.yamlis unaffected.Only lookups change, and only for an echoed turn that contains a placeholder-shaped call.
feat(gym): support Environment Server tasksets RL#4429 at e0822095a on Gym main with this PR merged: #4429's 4,940 Gym-related unit tests give the
same result for every test with and without this PR, and a GRPO smoke trained 2 steps (Rollout evidence). That smoke needed one RL-side change that is
unrelated to this PR: #4429 adds
max_output_tokensto Environment Server rows, andopencode_agentrejects itwith a 422, on Gym main too.
agent_refstamping and anepisode_recordsoption torun_examples. They were removed: RL#4429 does all three on the RL side, and theagent_refstamp would change how#4429 attributes taskset rows.
Validation
On 4ec6a35 (main e12458f merged), Python 3.13,
CPUSunset as in CI:pytest tests/unit_tests -m 'not sandbox' -n 24: 14,613 passed on e758836. On this head the 2,756 token-captureand attribution tests pass, and every other test gives the same result as on e758836.
terminal.pyand tests), run from each server directory asgym env testruns them:opencode_agent: 620 passed, 22 skipped (no Node.js or OpenCode binary on this host);vllm_model: 898 passed;partner_ifconfig tests andswe_togetherrecipe tests: passed.pre-commit run --fileson the changed files: clean.invalidcall, and theabstention above 6 placeholders;
strict fallbacks (reused ID, reasoning after the placeholder); one
opencode_agenttest builds that transcriptthrough
OpenCodeAgent._session_output;347,547 parent decisions, including both 50-step training runs.
placeholder-shaped call.
and its error result, from unattributed to their final call.
opencode_agenttest): unit tests, all 8 server-suite shards andsession routing pass. The non-blocking kilocode harness
conformance probe fails its
model_errorscenario (1 of 8), as on every earlier head of this PR; this PR does nottouch
kilocode_agent.Rollout evidence
Harbor path with
opencode_agent. RL#4429 at e0822095a with the one RL-side change above; Gym main 4aff2e8 withthis PR merged.
NeMo RL would mask; this PR resolves all 46 to the preceding call and changes no other decision.
them, and the other 246 are unchanged.
🤖 Generated with Claude Code