Skip to content

feat(opencode): support OpenCode v2 alongside v1 - #6001

Merged
yaoyu-33 merged 10 commits into
mainfrom
claude/opencode-v2
Nov 15, 2026
Merged

yaoyu-33 merged 10 commits into
mainfrom
claude/opencode-v2

Conversation

@yaoyu-33

@yaoyu-33 yaoyu-33 commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What

opencode_agent can now run OpenCode 2 next to OpenCode 1. opencode_version: "2.2.7" on the agent selects it; OpenCode 1.17.11 stays the default, so every existing config and recipe runs unchanged. OpenCode 1 will be deprecated later, not in this PR.

Why: users now reach for OpenCode 2, and one team hit a limit in OpenCode 1. Support it beside OpenCode 1 first so old recipes keep working, and move recipes over once the benchmark recipes are validated on the new path. No issue is linked: the request came from a user team directly.

What OpenCode 2 is, and the pin

Upstream (anomalyco/opencode, formerly sst/opencode) releases OpenCode 2 as 2.x: npm @opencode/cli (platform packages @opencode/cli-linux-x64, ...) and the same opencode-linux-* GitHub release assets as 1.x, now with a SHA256SUMS. npm opencode-ai stays on 1.x (latest = 1.19.5). This PR pins 2.2.7 (released 2026-11-10), with the SHA-256 of each Linux asset in runtime.OPENCODE_RELEASE_SHA256.

OpenCode 2 is a rewrite. What an integrator sees:

Area OpenCode 1.17.11 OpenCode 2.2.7
--version 1.17.11 opencode v2.2.7
Process model one process CLI + server; joins a running background service unless --standalone (and session export/import start one)
Plugins plugin: ["file:///x.mjs"], factory with chat.headers, shell.env, chat.params plugins: [{package: "file:///dir", options}], export default {id, setup}, hooks model.request, shell create.before, session context/prompt/compaction; a file path is rejected
Plugin SDK install @opencode-ai/plugin installed into the config dir at every start (~63 MB) none
Session store session, message, part session_v2, typed session_message (one assistant message per model step, content inline), compaction, synthetic, idle, ...
Export / import `opencode export import`
Errors {name: APIError, data: {statusCode, isRetryable}}, ContextOverflowError `{type: provider.rate-limit
Tools bash, task, list, todowrite/read, ... shell, subagent, read (lists dirs), question, Code Mode execute (off in Gym, see below); todowrite off in releases
Per-agent temperature / top_p applied accepted in config but not applied
Image limits attachment.image media.image, plus PNG→JPEG re-encoding unless auto_resize: false
Unknown model's input text text and image
Model retries built in built in: 10 tries for 429/408/409/5xx/transport, no knob

Design: a version switch inside opencode_agent

I chose a switch selected by opencode_version over a separate agent:

  • It is the same harness at a new major version; the add-harness rule is one adapter per harness, and recipes switch with one setting, which is also how OpenCode 1 will be retired later.
  • There is no separate opencode2_agent instance config. Agent variants are the configs directly in configs/, each a separately runnable agent, while overlays such as profiles/ and permissions/ are not variants; the benchmark-profile and permission-profile tests pin opencode_agent to its single variant. The OpenCode version is a setting on that agent like the permission profile, so a recipe selects it in its own opencode_agent block (README "OpenCode 2").
  • Everything Gym-side is shared and unchanged: seed/activation/close, borrowed and agent-owned sandboxes, network policy, pinned files, MCP grant validation, media staging, the continuation state machine, the supervisor/runner, export bookkeeping, OOM reporting and outcome mapping.
  • What OpenCode 2 changed lives in opencode_agent/opencode2/:
    • config.py: the OpenCode 2 configuration (provider/model/plugins/MCP/media in its own schema; the session's opencode_config keys stay in OpenCode 1 form, which OpenCode 2 migrates) and the run --standalone command line.
    • plugin/index.js: one plugin directory replacing task_environment.mjs, required_mcp.mjs and assistant_message_header.js.
    • store.py: translates the OpenCode 2 store into the OpenCode 1 tables, so snapshot, artifacts, observability, usage, output conversion and classify_opencode_run are shared. It also has the OpenCode 2 step-limit count.
  • app.py/sandbox.py branch only where the interfaces differ (installer digests, plugin staging, launch config, session export/import, store translation). The v1 launch block moved into _opencode1_launch unchanged; v1 commands and files are byte-identical (the v1 suite passes unmodified).

Feature parity (every v1 feature on main → OpenCode 2)

v1 feature (main) OpenCode 2 How / notes
Seed with a borrowed sandbox (sandbox_access), network_access: inherit only ✅ shared
Seed with an agent-owned sandbox, model_only / model_and_tools egress ✅ shared
One activation per session, identical retry joins, 409 on conflict; close bundle, fence and saved reply ✅ shared
Workdir and storage-overlap checks; AgentSeedRejectedError refusals ✅ shared; plus 422 for sandbox_plugin_dependencies_* and for a 2.x version without pinned digests (unless a binary is pinned)
Install at seed: version-scoped cache, flock/queue, arch+libc, reuse after --version health check ✅ same installer; accepts opencode v<version>; new: each 2.x download is checked against the pinned SHA-256 (v1 downloads are unchanged, still version-checked only)
sandbox_executable_path/_sha256, sandbox_path_prefix (offline runtime) ✅ shared
Pinned ripgrep (sandbox_ripgrep_*) ✅ OpenCode 2 looks in the same XDG_CACHE_HOME/opencode/bin/rg
Pinned plugin dependencies (sandbox_plugin_dependencies_*) n/a OpenCode 2 installs none; refused with 422
Ready marker (task-environment.ready), runtime.json ✅ the v2 plugin writes the same receipt after registering its hooks
Isolation (OPENCODE_DISABLE_PROJECT_CONFIG/AUTOUPDATE/MODELS_FETCH, private HOME/XDG) ✅ same, plus OPENCODE_DISABLE_FREE_MODELS, a provider.use policy for nemo_gym only, and --standalone on every command
Tool shells keep the task HOME/XDG ✅ plugin shell create.before hook
system_prompt_mode append (instructions file) / replace (agent.build.prompt, { escaped) ✅ same keys; OpenCode 2 still substitutes {env:}/{file:}
sandbox_model_id, thinking, interleaved reasoning_content ✅ capabilities.reasoning, compatibility.reasoningField
context_window / max_output_tokens ✅ limit.{context,input,output}; OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX no longer exists
Request temperature/top_p on every call; max_output_tokens ≥ configured accepted; other controls 422 ✅ sampling through the plugin's context/compaction hooks (OpenCode 2 ignores per-agent sampling); the 1.17.11-only agent list does not apply
opencode_config allowlist (permission, tools, attachment, compaction.auto, agent.build.steps) ✅ passed in OpenCode 1 form and migrated (bash→shell, task→subagent); attachment→media
configs/permissions/default.yaml, configs/profiles/* ✅ unchanged; webfetch/websearch hidden. skill stays listed (OpenCode 2 applies that rule per skill; the private HOME has none)
session_project_config ✅ same env switch
Owner plugins ✅ (changed) must be OpenCode 2 plugin directories ([ -d ] check); OpenCode 1 plugin files cannot load in OpenCode 2
Prompt images: split_text_and_media → stage_media → --file; 422 for system images / URLs / unsupported types ✅ shared; OpenCode 2 sends the text before the images and does not show the path
image_input, IMAGE_INPUT_MODEL_OPTIONS, sticky across activations ✅ capabilities.input; a text-only session now declares ["text"] explicitly (OpenCode 2's default for an unknown model includes images)
UNRESTRICTED_IMAGE_ATTACHMENT (bytes unchanged), attachment override ✅ UNRESTRICTED_MEDIA adds auto_resize: false, which also stops PNG→JPEG re-encoding; probe: a 10.5 MB 2200×1600 PNG reached the model byte-identical
Images tools return (task files via read, MCP image content) ✅ probe: both reach the model unchanged when image input is declared; text-only gets OpenCode's "cannot read image" note
Resumed sessions resend images ✅ probe: the prompt image is resent with the history
MCP grants → remote servers with headers, oauth: false, timeout; tools <grant>_<tool> ✅ mcp.servers, codemode: false (OpenCode 2 otherwise hides MCP tools behind execute), timeout → startup/catalog/execution
required_mcp.mjs: status before the first model call, required → fail, optional → mcp_server_skipped, unconfirmed → fail ✅ plugin prompt/context hooks; it waits for pending servers (OpenCode 2 gives them only a 2 s grace) and writes the same mcp-status.json
X-Session-Id (activation-scoped in continuation) ✅ plugin model.request hook; overrides OpenCode 2's own value, which names the parent for subagents
X-OpenCode-Assistant-Message-Id (call→turn join for capture) ✅ (changed) OpenCode 2 names a reply only after its request is sent, so the plugin sends a label and records the reply it became; Gym's records name the reply by that label. Retries reuse the label
Token capture step-limit note ✅ same text in 2.2.7; added to checked_versions
Store copy after confirmed termination; export.json, observations.db ✅ translated store, same files
Invocations incl. subagent children, tool calls with timing/outcome, compactions, gaps ✅ via the translation; shell exit codes read like bash
Trajectory turns, model-call correlation, usage incl. subagents ✅ translation; token split is the same as v1
Output conversion (reasoning split, empty answer, tool outputs) ✅ recorded tool text = the tool message OpenCode 2 sends (probe-checked byte for byte)
export_dir (sessions.json, per-session export, events) ✅ (changed) opencode session export --standalone, OpenCode 2's JSON format
session_import_path ✅ (changed) opencode session import --standalone --directory <workdir>; takes OpenCode 2 exports only
Continuation (resume_harness_session, --session, per-activation dirs) ✅ shared; probe: --session resumes the same session
Outcomes: completed / incomplete / failed, timeout, length/content-filter ✅ shared classification on the translated export
Permission-denied yield (permission_denied) ⚠️ not reachable OpenCode 2 sends a denied call's error to the model and continues; the run completes
APIError status → model_request_error, retryable transport → model_transport_error, ContextOverflowError → context limit ✅ translated error names; probe: 400 → model_request_error/400, context-length 400 (compaction off) → model_context_limit
compaction.auto: false ✅ same key
agent.build.steps + harness_step_limit_reached ✅ (changed count) OpenCode 2 also sets tool_choice: none at the limit; compaction does not count as a step
Timeout budget incl. staging; OOM reporting ✅ shared
Local CLI path (unseeded /v1/responses) ✅ downloads the pinned Linux release into .opencode_runtime/<version> (checked digest); command may name another binary
/run with resources_server, relay configs ✅ /run goes through the local path
Compaction call joined to its compaction record ❌ gap compaction events carry no message ID before the call, so compaction calls are unlabeled (they are skipped by the join, not reported as unmatched)

Behavior that differs (visible to a recipe)

  • Code Mode is off. The adapter denies execute after every other permission rule, and the Gym plugin removes the tools OpenCode offers only through Code Mode (opencode_*: sessions, worktrees, models, schedules, artifacts, MCP resources). Denying execute alone would offer those tools directly, and opencode_worktree_remove uses the edit permission, so no rule could hide it.
  • When a stream breaks after output started, OpenCode 2 saves the error on that step and continues with a new one. That step keeps the error as recoveredError; only an error on the last reply fails the run.
  • After a reply truncated at max_output_tokens, OpenCode 2 asks the model to continue, twice. A third truncated reply ends the run with an output-limit error and exit code 1, so the run is reported as failed. OpenCode 1 reports a run whose last reply was truncated as incomplete (max_output_tokens).
  • A denied tool call no longer ends the run's turn.
  • At the step limit the model must answer in text.
  • OpenCode 2 retries model calls itself (10 tries; no config knob).
  • With mcp_tool_timeout_seconds unset, an MCP call may run 12 hours (OpenCode 2's default).
  • todowrite is off in OpenCode 2 releases.

Validation

Checks at the current head 7dc08515f (merged with origin/main at 33a4989380; the merge's one conflict was the harness table in integrate-existing-agents.mdx), on a Linux workstation:

  • responses_api_agents/opencode_agent/tests: 974 passed, 1 failed, 23 skipped. The failure, test_pinned.py::test_stage_executable_rejects_wrong_or_broken_bytes_without_installing[format], is environmental: that host's /bin/sh (dash) exits 2 on "Exec format error" where the test expects 126. This PR does not touch pinned.py or its test.
  • Variant and catalog tests (tests/unit_tests/environment/{test_session_harness_benchmark_profiles,test_agent_registry}.py, cli/test_cli_agents.py, tooling/test_agent_environment_{default_configs,session_templates}.py, test_session_contract_repo.py, models/test_token_capture_harness_notes.py, the OpenCode test_existing_benchmarks.py): 125 passed, including test_profile_is_not_a_standalone_agent_variant[opencode_agent], which failed in CI at fc9d9e62b.
  • Full core suite (tests/unit_tests + scripts/harness_conformance/tests) on this branch and on origin/main, same host and environment: the same 454 failures/errors on both and none only on this branch (they need git metadata and packages that environment lacks); 22,159 passed on each.
  • Secrets: detect-secrets 1.5.0 finds nothing new in the changed files; without the # pragma: allowlist secret marks it reports exactly runtime.py:21-24, as CI did. Its one other hit, the apiKey: "dummy_key" line of the OpenCode 1 config in app.py, is unchanged from main.
  • pre-commit run --files <changed files>: passed, no files modified.
  • New tests in this PR: test_opencode2_store.py (12), test_opencode2_session.py (16), 4 OpenCode 2 installer cases in test_install_runtime.py (Linux-only).

Scripted-model probes (no real model): the real OpenCode 2.2.7 binary (macOS arm64 build) with the adapter's own session_config, plugin, translator and readers, against a loopback Chat Completions stub that logs every request:

Scenario Result
shell tool, then answer exit 0, completed; tool shell HOME = task HOME; sampling 0.5/0.9 on every call; label headers = turn IDs; X-Session-Id = session
permission-denied command tool failed/tool_error, run completed; recorded error JSON = the tool message the model got
agent.build.steps: 2 step 2 request has tool_choice: none; harness_step_limit_reached detected
model 400 exit 1; APIError 400 → model_request_error, reported like v1
context-length 400, compaction.auto: false ContextOverflowError → model_context_limit
prompt image + read of a PNG both byte-identical in the requests; prompt image resent with history; also a 10.5 MB 2200×1600 PNG
MCP grant (real MCP server, streamable HTTP) direct tools task_tools_lookup/task_tools_chart; text result and MCP image reach the model; status connected
required MCP grant unreachable status failed (ECONNREFUSED), run exits 1 before any model call
subagent child session linked to its subagent call; per-session X-Session-Id and labels; all calls joined
automatic compaction compaction record with summary, trigger automatic; primary calls joined
--session resume, session export, session import --directory resume keeps the session; export is a JSON object; import binds to the given directory
leftover processes none; no background-service registration left

Real-model smokes, OpenCode 1 (1.17.11) vs OpenCode 2 (2.2.7) on the same rows, this branch at fc9d9e62b (later commits only merge main, mark the digests and drop the instance config; the smoke configs set opencode_version directly): Linux workstation, Docker sandboxes, hosted NIM nvidia/nemotron-3.5-super-vl-120b-a12b through the vLLM Model Server (thinking off), concurrency 1, model-call capture on, gym eval health-check and scripts/inspect_harness_conformance.py --require-sandbox on every run.

Run Sandbox Rows v1 reward v2 reward Health v1 / v2 Evidence TE-1…TE-9 (v1 and v2 alike)
Terminal-Bench 2.1 regex-log (single_agent_turn, README settings: context_window: 32768, max_output_tokens: 8192) lent by the TB 2.1 Resources Server 1 0 0 healthy / healthy all fulfilled
Terminal-Bench 2.1 fix-git lent 1 0 (gave up) 1 healthy / healthy all fulfilled
MCP grant: example_mcp_weather get_weather over the episode's MCP grant (resources_tool_transports: [mcp]) agent-owned 3 3/3 3/3 3 / 3 healthy TE-6 not fulfilled: this example's verify reports no evaluation_completed; the rest fulfilled
Prompt images: circle_count (PNG input_image + text) agent-owned 3 3/3 3/3 3 / 3 healthy TE-6 as above (circle_count); TE-5 where a row makes no tool call
Tool-returned images: the same tasks with the PNG in the sandbox, image_input: true, the model opens it with read agent-owned 3 3/3 2/3 3 / 3 healthy TE-6 as above

What was checked in the saved artifacts:

  • Joins: all 75 captured model calls (35 v1, 40 v2) carry the assistant-message label and join a turn; Model responses: 0 faulted on every run.
  • Tool results: for all 62 recorded tool calls, the recorded output equals the tool message the model received in the next request (v1 bash/write/read, v2 shell/execute/glob/read/edit, and the MCP tool example_mcp_weather_get_weather on both).
  • Images: every image in the captured requests is byte-identical to the task's PNG, for prompt images and for read results, on both versions.
  • Lent sandbox: harness_execution: sandbox, the agent closed before verification, the verifier ran (evaluation_completed: true); no sandbox containers or server processes were left.
  • MCP grant: the Resources Server recorded each get_weather call (tool_call_seen: true) on both versions.
  • The single TB 2.1 rows check the plumbing, not quality: v2's fix-git pass and its tool-image miscount (11 for 10, the same miscount this model gives when asked directly) are model variance.
  • Smoke-only change: on main, example_mcp_weather overrides seed_session with a reply that has no resources_session_id, so a typed seed from an Environment Server fails validation for every harness (v1 and v2 failed identically). For this smoke it was ported locally to the session-state hooks; that fix is not part of this PR.

Not covered

  • The TB 2.1 full evaluation (8 repeats) for OpenCode 2; the smokes above are single rows. allowed_agents declarations match the agent type, so OpenCode 2 inherits opencode_agent's declarations; recipes should be revalidated on OpenCode 2 before switching.
  • Harness conformance probes for OpenCode 2: the registry keys one entry per adapter directory, so an opencode_version variant needs a small runner change (follow-up).
  • Training token IDs (evaluation only, as for OpenCode 1).
  • Bounding OpenCode 2's own model retries (OpenCode 1's bound is fix(opencode,kilocode): bound the CLIs' model request retries #5913, a plugin that does not load in OpenCode 2; OpenCode 2 would use its session.retry hook).

Expected conflicts with open PRs

All build on main; none is changed here. Files they share with this PR:

CI repair validation (2026-11-14)

Merged current main and resolved the app.py import conflict: retain OpenCode 2 imports and use main's explicit legacy_app.py relay. No OpenCode 2 runtime behavior changed.

Linux workstation, Python 3.13.14, Node 22.22.2, frozen component environment:

  • python -m pytest responses_api_agents/opencode_agent/tests -q -o addopts='': 972 passed, 9 skipped, 1 failed. The sole failure is the existing test_pinned.py::test_stage_executable_rejects_wrong_or_broken_bytes_without_installing[format]: this workstation's /bin/sh reports exit 2 for invalid executable bytes; the test expects 126. The production staging helper correctly rejects the bytes with exit 3. Both the helper and the test are byte-identical to current main; this is the previously recorded workstation shell limitation.
  • pre-commit run --all-files (pre-commit 4.2.0): passed.
  • git diff --check: passed. Merge commit has DCO sign-off.
  • No new real-model rollout for an import-conflict resolution; the real-model evidence above remains applicable.

Review round (2026-11-14)

Head e5c53c047b. It merges current main (d4b0b61594; the same tree as 395b4e0278) and addresses @cmunley1's review plus an internal review against the add-harness checklist. Each change was checked against the OpenCode source at tag v2.2.7.

What changed (903ae35d9d):

  • Store translation. translate_store returns what it could not translate: message types, assistant content types, tool or compaction statuses outside the 2.2.7 schema, and a user message's skill text. The adapter records these as a harness_records_untranslated gap instead of dropping them silently.
  • Model-call labels.
    • They are read only when capture is on, and they accumulate across captures.
    • A reply keeps the ID that an earlier capture gave it. Before this, an unreadable label file renamed earlier replies, so they came back as new output in continued sessions.
    • An unreadable label file becomes a model_call_labels_unavailable gap.
    • When a call is retried before any output, its reply takes the last label recorded for it.
  • Code Mode is off (see "Behavior that differs").
  • Recovered errors. An error OpenCode 2 continued after is kept as recoveredError, so only an error on the last reply fails the run.
  • Compaction usage. Completed compactions carry a step-finish part, so local usage counts them.
  • Local calls run with the sandbox isolation variables and a fixed --title. The release download has a 60 s read timeout and a 10-minute deadline.

Validation:

  • responses_api_agents/opencode_agent/tests with test_session_contract_repo.py and test_token_capture_harness_notes.py, on a Linux workstation: 982 passed, 1 failed, 24 skipped.
    • The one failure is the existing test_pinned.py::...[format] workstation-shell case described above.
    • The skipped tests include the Node plugin test, because that host has no Node. It passes on macOS with Node 25.
  • New tests:
    • A Node test that runs plugin/index.js against a stand-in for the 2.2.7 plugin context.
    • Label stability across three captures. It fails if either the cache or the keep-earlier-ID rule is removed.
    • Untranslated-record gaps.
    • A recovered error versus a final error. It fails without the rule.
    • The bounded download: a stall followed by a retry, and a digest mismatch.
  • pre-commit run on the changed files: passed.

Real-model smoke, same rows on both versions:

  • Setup: Terminal-Bench 2.1 regex-log and fix-git through single_agent_turn, in sandboxes lent by its Resources Server, with the README settings. Model: hosted NIM nvidia/nemotron-3.5-super-vl-120b-a12b, thinking off.
  • Each request set temperature: 0.3 and top_p: 0.9. Model-call capture was on, concurrency 1.
OpenCode 1.17.11 OpenCode 2.2.7
Rewards (regex-log, fix-git) 0, 0 0, 1
evaluation_completed, harness_execution true, sandbox true, sandbox
Health 2 healthy, 0/17 responses faulted 2 healthy, 0/36 responses faulted
inspect_harness_conformance.py --require-sandbox all fulfilled all fulfilled
Calls carrying the assistant-message label 17/17 36/36
Calls carrying the request's temperature / top_p 17/17 36/36
Tools offered bash, edit, glob, grep, read, task, todowrite, write edit, glob, grep, question, read, shell, skill, subagent, write
Reported usage = captured usage (input / output tokens) 172,038 / 1,607 225,890 / 3,699

On the v2 servers, a local-path request downloaded the pinned release through the bounded download and answered correctly. No sandbox containers or OpenCode processes were left after either run.

Still not covered, beyond "Not covered" above:

  • A run that exhausts OpenCode 2's output-limit continuations is reported as failed (see "Behavior that differs"). Whether to map it to incomplete max_output_tokens, as OpenCode 1 reports a truncated last reply, is open.
  • Compaction calls stay unlabeled. Each compaction already carries compaction_model_call_boundary_unavailable.

🤖 Generated with Claude Code

yaoyu-33 and others added 3 commits November 10, 2026 23:36
opencode_version 2.x selects OpenCode 2 through the same adapter; 1.17.11
stays the default. OpenCode 2 changed its config schema, plugin API, session
store and export/import commands, so opencode2/ adds the v2 config and
command line, one Gym plugin directory, and a translator from the v2 store
into the OpenCode 1 tables the shared readers parse.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@copy-pr-bot

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

@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test fc9d9e6

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

yaoyu-33 and others added 2 commits November 12, 2026 09:56
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…pinned digests

Drop configs/opencode2_agent.yaml: OpenCode 2 is a value of opencode_agent's
opencode_version, not a separate agent variant, so opencode_agent keeps one
variant as the benchmark-profile and permission-profile tests expect. Mark the
pinned release SHA-256 digests for the secrets detector.

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

Copy link
Copy Markdown
Contributor Author

/ok to test 7dc0851

@cmunley1 cmunley1 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.

Thanks for keeping OpenCode 1 as the default; the v1 launch path and installer args look unchanged, SHA-256 pinning is enforced with a hard fail on mismatch, all four Linux assets match the arch selection, and every v2 command passes --standalone. A few things before this leaves draft:

  1. sandbox.py readable_store (~726-746): any failure reading the label file is treated as "no labels". In continued sessions the earlier activations are then not filtered by message id (snapshot.py:37), so earlier turns come back as new output and are counted again in usage_messages. Could a read failure raise (or mark the observation incomplete) instead of falling back?
  2. opencode2/store.py (translate_store, _content_part): unknown message types, unknown part types, and tool states outside the completed/error branches are dropped silently. If a later 2.x release adds a type, turns would vanish from trajectories with no error. Suggest raising or recording an observation gap on unknown shapes.
  3. opencode2/plugin/index.js has no test that executes it (the tests check the upload). _session_input now forwards temperature/top_p for v2 based on this plugin, so a wrong hook name or event shape (session.hook("context"), shell.hook("create.before"), event.subscribe) would silently sample at defaults. A smoke test against a real 2.2.7 binary, or a check that the hook actually fired, would catch this.
  4. opencode2/config.py:95: Code Mode execute stays enabled, which exposes OpenCode's own tools (sessions, worktrees, models) beyond what v1 offered. Worth disabling by default for RL/eval parity.
  5. opencode2/config.py session_config: only permission, tools, compaction, agent, attachment are forwarded; other opencode_config keys are ignored without a warning.
  6. setup_opencode.py ensure_opencode2: urlretrieve has no timeout and runs under the install lock, so a stalled download blocks every local call.

Could not verify without a 2.2.7 binary: that the store always has a session_part table, that v2 usage matches _session_usage, that the OPENCODE_DISABLE_* env vars are honored, and whether --standalone spawns children in the local path (where proc.kill() only kills the parent).

yaoyu-33 and others added 2 commits November 14, 2026 17:41
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test 395b4e0

yaoyu-33 and others added 2 commits November 14, 2026 18:01
- Store translation reports what it cannot translate (message, content, tool
  and compaction types outside OpenCode 2.2.7's schema, user skill text) as a
  harness_records_untranslated gap instead of dropping it.
- Model-call labels are read only with capture on, accumulate across captures,
  and never rename a reply an earlier capture named; an unreadable label file
  becomes a model_call_labels_unavailable gap. This stops earlier turns from
  coming back as new output in continued sessions.
- Code Mode is off: execute is denied after every other permission rule and
  the plugin removes the tools OpenCode offers only through Code Mode.
- An error OpenCode continued after (a stream that broke after output) is kept
  as recoveredError, so only an error on the last reply fails the run.
- A retried call's last label names its reply; completed compactions carry a
  step-finish part so local usage counts them.
- Local OpenCode 2 calls run with the sandbox isolation and a fixed title, and
  the release download has a read timeout and an overall deadline.
- Tests: a Node test that runs the plugin against a stand-in context, label
  stability across captures, untranslated-record gaps, recovered errors and
  the bounded download.

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

Copy link
Copy Markdown
Contributor Author

/ok to test e5c53c0

@yaoyu-33

Copy link
Copy Markdown
Contributor Author

Thanks @cmunley1, all six are addressed in 903ae35 (README follow-up e5c53c0). I checked each against the 2.2.7 source (anomalyco/opencode at tag v2.2.7) and reran the real-model smoke after the changes.

  1. Label read failure (sandbox.py readable_store)
    • Labels are read only when model-call capture is on. Without capture there is no label file, and none is read.
    • The labels read in earlier captures are cached for the session. A label that was read once still applies even if a later read fails.
    • A reply keeps the ID that an earlier capture gave it, even if a label for it turns up later. So no earlier turn can come back as new output, whatever the label file says.
    • A failed read becomes a model_call_labels_unavailable gap on that capture's observations.
    • test_a_failed_label_read_never_renames_an_earlier_reply runs three captures (labels readable, unreadable, readable again). Removing either the cache or the keep-earlier-ID rule makes it fail.
  2. Unknown shapes in store.py
    • translate_store now returns everything it did not translate: message types, assistant content types, tool or compaction statuses outside the 2.2.7 schema (packages/schema/src/session-message.ts), and a user message's skill text.
    • The adapter reports these as a harness_records_untranslated gap, in sandbox captures and in local calls.
    • Three types are still skipped on purpose, because OpenCode 1's store never held them either: system (instruction updates), idle, and agent-switched.
  3. The plugin is now executed in a test.
    • test_the_plugin_registers_its_hooks_and_acts_on_them runs index.js under Node against a stand-in context. The hook and domain names match packages/plugin/src/promise at 2.2.7.
    • It checks that tool shells get the task environment, that temperature/topP are set by both context and compaction, the Code Mode tool removal, the X-Session-Id override, the labels and the label file, MCP enforcement with the status file, and the ready receipt.
    • Whether the real 2.2.7 binary calls those hooks is checked by the smoke below. Every captured v2 call carries the request's temperature: 0.3 and top_p: 0.9.
  4. Code Mode is off by default.
    • Denying execute alone does not work: Tool.snapshot (packages/core/src/tool.ts) then offers every Code-Mode-only tool directly. One of them, opencode_worktree_remove, uses the edit permission, so no permission rule can hide it without also hiding edit.
    • So the adapter denies execute after every other permission rule, and the Gym plugin removes every tool registered with codemode !== false through ctx.tool.transform. That covers OpenCode's own sessions, worktrees, models, schedules, artifacts and MCP resources.
    • MCP grants keep codemode: false and stay direct tools. Local calls get the same treatment.
    • In the smoke, no captured v2 request offers execute or any opencode_* tool.
  5. Other opencode_config keys
    • These were already refused at seed with a 422, for both versions, by _session_opencode_config_error, which allows only permission, tools, attachment, compaction.auto and agent.build.steps. The v2 config only forwards what passed that check.
    • The opencode2/config.py docstring now says this.
  6. ensure_opencode2 download
    • It now uses urlopen with a 60 s read timeout and a 10-minute overall deadline, both under the install lock.
    • A stalled download raises TimeoutError, releases the lock, and leaves no binary, so a later call retries.
    • Tests cover the bounded read and one-time install, the stall-then-retry case, and a digest mismatch.

On the points you could not verify without a 2.2.7 binary:

  • session_part: created by migration 20261029002625_session_part, so every 2.2.7 store has the table. Both smoke stores had it.
  • OPENCODE_DISABLE_*: all four are read at 2.2.7. OPENCODE_DISABLE_PROJECT_CONFIG and OPENCODE_DISABLE_MODELS_FETCH are read in cli/src/server-process.ts, OPENCODE_DISABLE_AUTOUPDATE in cli/src/services/updater.ts, and OPENCODE_DISABLE_FREE_MODELS in core/src/model.ts and core/src/plugin/provider/opencode.ts.
  • Usage: in the smoke below, the usage the adapter reported on each rollout adds up to the usage of the captured calls, on both versions: 225,890 input and 3,699 output tokens over 36 calls on 2.2.7, and 172,038 / 1,607 over 17 calls on 1.17.11.
  • --standalone children in the local path: run --standalone starts one serve --stdio child (cli/src/services/standalone.ts). That child treats EOF on its stdin pipe as the end of its lease, and the OS closes the pipe when the parent is killed, so proc.kill() on the parent also ends the server. Local calls now also run with the sandbox isolation variables and a fixed --title, so OpenCode 2 makes no title call outside the rollout.

An internal review turned up a few more changes in the same commit:

  • When a stream breaks after output started, OpenCode 2 saves the error on that step and continues with a new one (session/runner/step.ts, Outcome.Continue). Only an error on a session's last reply now fails the run. An earlier one is kept as recoveredError.
  • When a call is retried before any output, the reply takes the last label recorded for it, which is the call whose response it holds.
  • Completed compactions carry a step-finish part, so local usage counts them.

Smoke after the fixes, at e5c53c0:

The workstation used Docker sandboxes lent by the Terminal-Bench 2.1 Resources Server through single_agent_turn, with the README settings (context_window: 32768, max_output_tokens: 8192, timeout: 600). The model was hosted NIM nvidia/nemotron-3.5-super-vl-120b-a12b with thinking off. Each row's request set temperature: 0.3 and top_p: 0.9. Model-call capture was on, concurrency 1, and the rows were the same for both versions (regex-log, fix-git).

OpenCode 1.17.11 OpenCode 2.2.7
Rewards (regex-log, fix-git) 0, 0 0, 1
evaluation_completed, harness_execution true, sandbox (both rows) true, sandbox (both rows)
gym eval health-check 2 healthy, 0/17 responses faulted 2 healthy, 0/36 responses faulted
inspect_harness_conformance.py --require-sandbox all fulfilled all fulfilled
Captured calls with the assistant-message label 17/17 36/36
Calls carrying the request's temperature / top_p 17/17 36/36 (set by the plugin's context hook)
Tools offered bash, edit, glob, grep, read, task, todowrite, write edit, glob, grep, question, read, shell, skill, subagent, write (no execute, no opencode_*)
Reported usage = captured usage 172,038 / 1,607 225,890 / 3,699
New gaps (harness_records_untranslated, model_call_labels_unavailable) none none

A local-path request (unseeded, temperature: 0.3) on the v2 servers downloaded the pinned 2.2.7 release through the bounded download, ran it with the isolation variables and --title, and answered local-opencode-ok. After both runs, no sandbox containers or OpenCode processes were left. One row per task checks the plumbing, not quality.

@yaoyu-33
yaoyu-33 marked this pull request as ready for review November 15, 2026 03:27

@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

Three RISK findings affect local OpenCode 2 execution and setup. I found no additional qualifying issues in the sandbox launch and capture paths.

I inspected all 18 changed files and traced their affected callers and tests. This was static inspection; I did not execute tests or reproduce the reported model smokes. OpenCode 2's upstream source and release assets are not mounted, so I could not independently verify their contracts or digest values. Suggested code below is unexecuted and needs verification before adoption.

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

if self._opencode2:
# OpenCode 2 takes its configuration from the environment, which keeps it out of a persistent repo, and
# its directory from PWD. The sandbox sessions' isolation keeps its hosted free models out of the run.
env["OPENCODE_CONFIG_CONTENT"] = json.dumps(self._build_opencode2_local_config(rollout_id, label_file))

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.

RISK: Preserve the owner's local configuration override

With opencode_version: "2.2.7", configure opencode_config.permission: {"*": "allow"} and env.OPENCODE_CONFIG_CONTENT: '{"permission":{"edit":"deny"},"compaction":{"auto":false}}'. _env carries the owner's override into the environment, but this assignment replaces it. Neither restriction reaches OpenCode. This affects unseeded requests and legacy local episodes. V1 keeps this override, and the existing replacement-config test explicitly protects that precedence.

Could you merge inherited configuration before enforcing the v2 helper's Gym-owned requirements? In _build_opencode2_local_config, add a keyword-only inherited: Mapping[str, Any] | None = None parameter and insert this immediately after building config:

self._deep_merge(config, copy.deepcopy(dict(inherited or {})))

Replace the assignment here with:

inherited = json.loads(env.get("OPENCODE_CONFIG_CONTENT", "{}"))
env["OPENCODE_CONFIG_CONTENT"] = json.dumps(
    self._build_opencode2_local_config(
        rollout_id, label_file, inherited=inherited
    )
)

Keep the rest of the helper after that merge: code_mode_off must still put execute: deny last, and the Gym plugin must still be appended after owner plugins. Keep the invocation's replacement prompt applied last. The invariant is that owner configuration survives unless an explicit Gym-owned requirement overrides it.

Proposed checks, not executed: extend the local-v2 fake-binary test with the override above and nested agent.build.steps. Assert that edit: deny, compaction.auto: false and the step limit survive in the subprocess configuration in both prompt modes. In replacement mode, assert that the request prompt is added without deleting those settings. An inherited execute: allow must still become deny, owner plugins must coexist with the Gym plugin, and the existing v1 assertions must stay unchanged.

if self._opencode2 and db_path.is_file():
translated = data_home / "opencode" / "sessions.db"
labels = message_labels(label_file.read_text()) if label_file.is_file() else {}
untranslated = await asyncio.to_thread(translate_store, db_path, translated, labels=labels)

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.

RISK: Count persisted usage from recovered streaming failures

A local v2 run with a partial reply carrying provider.transport, followed by a successful continuation, under-reports usage. The translator keeps the first reply's token counters in message info, but clears its finish and emits no step-finish part (translation). The local path then uses parse_opencode_session, which counts tokens only from those parts (reader). The broken stream's persisted usage disappears. Sandbox sessions instead count assistant-message counters through _session_usage.

Could you make local v2 accounting use those message counters, without adding a successful finish marker to a recovered reply? One scoped implementation is to add this helper to the translator module:

def local_usage(database: Path) -> dict[str, int]:
    with closing(sqlite3.connect(f"file:{database}?mode=ro", uri=True)) as con:
        infos = [_json(row[0]) for row in con.execute("select data from message")]
    totals = {"input_tokens": 0, "output_tokens": 0, "reasoning_tokens": 0}
    for info in infos:
        if info.get("role") != "assistant":
            continue
        tokens = info.get("tokens") or {}
        cache = tokens.get("cache") or {}
        reasoning = int(tokens.get("reasoning") or 0)
        totals["input_tokens"] += (
            int(tokens.get("input") or 0)
            + int(cache.get("read") or 0)
            + int(cache.get("write") or 0)
        )
        totals["output_tokens"] += int(tokens.get("output") or 0) + reasoning
        totals["reasoning_tokens"] += reasoning
    return totals

Import it in the app and, immediately after the existing output/usage parsing, override only local v2 usage:

if self._opencode2 and not timed_out and db_path.is_file():
    usage = await asyncio.to_thread(local_usage, db_path)

This keeps v1 accounting and timeout behavior unchanged. Every persisted assistant call, including subagents and compactions, must contribute its measured usage once; recovery must not manufacture a successful finish or hide a final error.

Proposed checks, not executed: run the recovered-stream fixture through the local response path. Its two TOKENS values should produce 210 input, 18 output and 4 reasoning tokens, rather than 105, 9 and 2. Retain both turns and the completed recovery outcome. A single successful call should still count once. Keep the completed-compaction usage assertion and the final-error failure assertion unchanged.

"""Write ``url`` to ``target`` within the download bounds, raising ``TimeoutError`` past either."""
deadline = time.monotonic() + _DOWNLOAD_TIMEOUT_S
with urllib.request.urlopen(url, timeout=_DOWNLOAD_READ_TIMEOUT_S) as response, target.open("wb") as file: # noqa: S310
while chunk := response.read(1 << 20):

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.

RISK: Enforce the overall deadline while a download read is pending

_download checks its 600-second deadline only after response.read(1 << 20) returns. A slow-drip response that keeps the read pending beyond that deadline is not interrupted by this check. The timeout passed to urlopen is an inactivity bound, not enforcement of this absolute deadline. Because the download runs under install_lock and local callers share the setup task, this can hold other first calls for that version past the documented ten-minute limit.

Could you enforce the absolute deadline across pending reads as well as between reads? Keep the inactivity timeout, SHA-256 verification and atomic binary publication. The exact bounded-reader implementation needs verification against the supported Python runtime, so I am not proposing an unchecked replacement. The invariant is that continued network progress cannot extend the overall installation-download budget indefinitely.

The current stall test returns immediately from every fake read, so it exercises the deadline check but not a read spanning the deadline.

Proposed regression, not executed: use a local HTTP server with a large response and a shortened overall deadline. Send bytes more frequently than the inactivity timeout while keeping the requested read incomplete past the overall deadline. Expect TimeoutError near that deadline, a released install lock and no published binary. A subsequent normal download must install successfully. Retain the successful reuse and digest-mismatch assertions, and separately verify that a response delivering no data still hits the inactivity timeout.

@cmunley1 cmunley1 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.

Thanks for the quick fixes. Re-checked against a live run (SWE-Pro rows in OpenSandbox, v1.17.11 vs v2.2.7): v2 runs end to end, store translation and message counts match, usage is populated, and v1 is unchanged. Remaining deployment notes are non-blocking.

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

Merged via the queue into main with commit 39d2bde Nov 15, 2026
78 checks passed
@yaoyu-33
yaoyu-33 deleted the claude/opencode-v2 branch November 15, 2026 18:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants