Skip to content

Commit eef0525

Browse files
fix: declare OpenCode capability strategy (sipyourdrink-ltd#4099)
## What Correct the OpenCode capability strategy declaration for issue sipyourdrink-ltd#3676. ## Why The source matrix currently uses the default `AdapterStrategy()`, which renders OpenCode as: `unsupported | unsupported | text-signals` That contradicts the adapter's current OpenCode invocation and the upstream capabilities verified in version 1.18.16. ## How Declare OpenCode with the same capability axes as Claude: - resume: `flag` - dangerous mode: `cli-flag` - event channel: `stream-json` The generated documentation remains unchanged because it is derived from this source matrix. This PR intentionally does not implement NDJSON consumption, explicit permission configuration, or session resume wiring; those remain separate follow-up changes as requested in the issue. ## Verification The change is limited to the authoritative strategy matrix in `src/bernstein/adapters/_contract.py`. The contract renderer/drift check should now resolve OpenCode to the declared values. Local test commands were not run in this environment. --- ## Update from the maintainers The declaration above is correct on the resume and dangerous-mode axes, and the decomposition in the original description is what made the rest briefable. The remaining wiring has been pushed to this branch so the two halves land together rather than leaving the matrix describing something the adapter does not do. Added on top of the original commit: - **Permission posture is pinned per spawn.** Every spawn carries an explicit `OPENCODE_PERMISSION` policy derived from the declared dangerous-mode strategy — escalated alongside `--auto` when it permits unattended action, a deny policy when it does not — applied after the environment allow-list so the pinned policy is what the worker sees rather than the host's. Neither direction resolves to `ask`, which blocks a headless run indefinitely against upstream `anomalyco/opencode#36762`. - **`--continue` backs the resume axis.** The adapter opts into the continuation path, so the warm retry `checkpoint_retry_capability` already derives from `resume=flag` is backed by a flag the adapter passes. The per-task worktree makes "the prior session here" unambiguous. - **Command construction moved into `_build_command`**, so the argv is assertable without mocking subprocess. The matrix row, the capability profile and the pinned contract move together. - **`event_channel` stays `text-signals`.** The CLI does emit NDJSON under `--format json`, but nothing consumes it yet, and declaring a channel no parser reads would claim a surface that does not exist. Tests: `tests/unit/test_adapter_opencode.py` asserts the escalated flag, the restricted policy, that a host `OPENCODE_PERMISSION` never reaches the worker, and that the continuation flag lands in the constructed command — each failing against the previous adapter. `tests/unit/adapters/test_capability_enums.py` pins the derivation from the resume axis to the retry surface so the declaration and the implementation cannot drift apart again. Because NDJSON consumption is still outstanding, this is a partial implementation and sipyourdrink-ltd#3676 stays open after the merge. Partial implementation of sipyourdrink-ltd#3676. --------- Co-authored-by: chernistry <[email protected]>
1 parent 328f8d0 commit eef0525

11 files changed

Lines changed: 308 additions & 19 deletions

File tree

‎docs/adapters/capability_contract.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ adapters at a glance.
146146
| `ollama` | unsupported | unsupported | text-signals |
147147
| `open_interpreter` | unsupported | unsupported | text-signals |
148148
| `openai_agents` | flag | always-on | hooks |
149-
| `opencode` | unsupported | unsupported | text-signals |
149+
| `opencode` | flag | cli-flag | text-signals |
150150
| `openhands` | unsupported | unsupported | text-signals |
151151
| `pi` | unsupported | unsupported | text-signals |
152152
| `plandex` | unsupported | unsupported | text-signals |

‎docs/adapters/capability_profiles.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,5 +236,5 @@ check the profile against every gate above.
236236
| `pydantic_ai` | `FACTORY` | `clai -m <model> --no-stream <prompt>` |
237237
| `droid` | `MODULE` | `droid <prompt>` |
238238
| `kimi` | `MODULE` | `kimi --yolo -c <prompt>` |
239-
| `opencode` | `MODULE` | `opencode run -m <model> --format json <prompt>` |
239+
| `opencode` | `MODULE` | `opencode run -m <model> --format json --auto <prompt>` |
240240
| `goose` | `MODULE` | `goose run --text <prompt>` |

‎docs/release-notes/unreleased.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ rather than as its own attribution is exempted by hand there, with the reason.
1515
- Volunteer tasks enforce `allowed_paths`, re-run the project's gates, and assemble the signed receipt (#4033). `finish_volunteer_task` takes the patch a run produced plus the project's manifest and returns either a `SignedResultBundle` or a `VolunteerRefusal` — never a bundle marked failed, because a signed bundle is a claim the work is acceptable and one that says otherwise in a boolean field is a misreading away from being treated as a pass. Scope is enforced before any gate subprocess starts, and a glob match is not the whole check: the same filesystem containment barrier the rest of the project uses refuses a path that is not repository-relative (`docs/../src/x.py` is a spelling `docs/**` matches) and a path that resolves out of the worktree through a symlinked component, and only then are the project's globs consulted through the one matcher shared with credential scoping. Matching stays case-sensitive on every platform, so a scope written for `src/` cannot be satisfied by `SRC/` on a case-insensitive filesystem. Gates run as argv under one wall-clock budget shared across them rather than one budget each, stop at the first failure, and take an environment built from the sandbox profile rather than inherited from the donor's shell. A passing run's bundle carries the manifest's own digest as `manifest_sha256` and the profile's digest as its sandbox identifier, continuing the manifest → profile → receipt chain, and its worker identity is derived from the signing key so the bundle cannot name one worker while the signature is by another. Refusals carry stable, append-only reason codes. Part of #3869. Docs: [`docs/reference/volunteer-manifest.md`](../reference/volunteer-manifest.md).
1616
- One answer to "which paths does this diff touch" (`bernstein.core.diff_paths`). The Tier-3 auto-heal cordon and volunteer scope enforcement both fail open on a path an extractor misses, so the extraction moved out of `autofix/tier3.py` into a shared module alongside `path_scope`, and gained the shapes it was missing: a content-preserving rename or copy, a mode change, and a binary file each touch a file while printing no hunk at all, and were previously invisible to the cordon. Quoted non-ASCII paths are decoded rather than handed to a matcher as escape sequences, and an ambiguous `diff --git` header contributes every candidate split — the extractor over-approximates on purpose, since a spurious path costs a readable refusal and a missing one costs an unchallenged write. `bernstein.core.autofix.tier3.extract_paths_from_unified_diff` still resolves for existing callers.
1717
- Parking a task now writes the grant-bound agent checkpoint the resume path has been checking for (#4043). Nothing in the shipped code produced an `AgentCheckpoint`, so the authority check `bernstein task resume` runs — recompute the grant hash from the role and refuse when the permission set has moved — had no input on a live run and passed by having nothing to inspect. `park_task` now writes the checkpoint after the suspend receipt exists, keyed per task rather than per adapter so two tasks parked on one adapter no longer evict each other, and hashes the same permissions the resume re-derives so the two sides agree. The role is read where it is actually recorded, the task log, and the owning run comes from `$BERNSTEIN_RUN_ID`; `--role` and `--parent-run-id` pin either explicitly. When no role can be sourced the checkpoint is written with an empty grant hash rather than one over the unrestricted default permission set, which the resume would re-derive identically — a checkpoint that reads as bound and can never refuse is worse than one that admits it is not bound. Part of #3649. Docs: [`docs/operations/durable-suspend-resume.md`](../operations/durable-suspend-resume.md).
18+
- The OpenCode adapter pins its own tool permissions and can re-enter a prior session (#3676). The contract row for `opencode` read `unsupported | unsupported` on resume and dangerous mode, and the adapter matched it: the spawn was a fixed `opencode run -m <model> --format json <prompt>` with no permission configuration at all, so a worker inherited whatever the operator's personal `opencode` config resolved to and two operators running the same plan got different agent behaviour. Both axes now describe flags the adapter passes. Every spawn carries an explicit `OPENCODE_PERMISSION` policy derived from the declared dangerous-mode strategy — escalated alongside `--auto` when it permits unattended action, tightened to a deny policy when it does not — applied after the environment allow-list so the pinned policy is what the worker sees rather than the host's. Neither policy resolves to `ask`, which would hang a headless run indefinitely against upstream `anomalyco/opencode#36762` and surface as a timeout rather than a blocked permission. `--continue` re-enters the prior session on a continuation retry, which the per-task worktree makes unambiguous, and the adapter opts into the continuation path so the warm retry the resume axis already derives is backed by something real. The event channel deliberately stays `text-signals`: the CLI does emit NDJSON under `--format json`, but nothing consumes it yet, and consuming it is the remaining half of #3676.
1819
## Security
1920

2021
- The agent task-scope gate no longer depends on how FastAPI happens to store

‎src/bernstein/adapters/_contract.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -744,7 +744,15 @@ def to_dict(self) -> StrategyView:
744744
"muse": AdapterStrategy(dangerous_mode=DangerousModeStrategy.CLI_FLAG),
745745
"ollama": AdapterStrategy(),
746746
"open_interpreter": AdapterStrategy(),
747-
"opencode": AdapterStrategy(),
747+
# Resume and dangerous mode are backed by flags ``opencode.py`` passes:
748+
# ``--continue`` and ``--auto`` plus an explicit permission policy. The
749+
# event channel stays ``text-signals``: the CLI does emit NDJSON under
750+
# ``--format json``, but nothing consumes it yet, and declaring a channel
751+
# no parser reads would claim a surface that does not exist.
752+
"opencode": AdapterStrategy(
753+
resume=ResumeStrategy.FLAG,
754+
dangerous_mode=DangerousModeStrategy.CLI_FLAG,
755+
),
748756
"openhands": AdapterStrategy(),
749757
"pi": AdapterStrategy(),
750758
"plandex": AdapterStrategy(),

‎src/bernstein/adapters/capability_profile.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,11 +1139,14 @@ def build_adapter_from_profile(profile: AdapterCapabilityProfile) -> ProfileAdap
11391139
subcommands=("run",),
11401140
model_flag="-m",
11411141
prompt_positional=True,
1142-
extra_args=("--format", "json"),
1142+
extra_args=("--format", "json", "--auto"),
11431143
),
11441144
agents_md=True,
11451145
local_models=True,
1146-
notes="Structured JSON output via --format json.",
1146+
resume=ResumeStrategy.FLAG,
1147+
dangerous_mode=DangerousModeStrategy.CLI_FLAG,
1148+
notes="Structured JSON output via --format json. --continue re-enters the prior session; "
1149+
"--auto plus an explicit OPENCODE_PERMISSION policy pins tool permissions per spawn.",
11471150
),
11481151
AdapterCapabilityProfile(
11491152
name="goose",

‎src/bernstein/adapters/opencode.py‎

Lines changed: 103 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,126 @@
33
Last verified against upstream OpenCode (anomalyco/opencode) 1.18.16 on 2026-08-12.
44
Install: ``curl -fsSL https://opencode.ai/install | bash`` (fastest),
55
``brew install anomalyco/tap/opencode``, or ``npm i -g opencode-ai@latest``.
6+
7+
Permission posture is pinned by this adapter rather than inherited. OpenCode
8+
resolves tool permissions from the operator's own config unless something
9+
overrides it, so an un-pinned spawn means two operators running the same plan
10+
get different agent behaviour. Every spawn therefore carries an explicit
11+
``OPENCODE_PERMISSION`` policy derived from the adapter's declared
12+
:class:`~bernstein.adapters._contract.DangerousModeStrategy`, which is what
13+
keeps that declaration load-bearing instead of descriptive.
14+
15+
Neither policy resolves to ``ask``: a headless run whose permission resolves
16+
that way waits forever (upstream ``anomalyco/opencode#36762``), and the only
17+
backstop would be the timeout watchdog, which reports a timeout rather than a
18+
blocked permission.
619
"""
720

821
from __future__ import annotations
922

23+
import json
1024
import logging
1125
import os
1226
import subprocess
1327
from pathlib import Path
14-
from typing import Any
28+
from typing import TYPE_CHECKING, Any
1529

30+
from bernstein.adapters._contract import DangerousModeStrategy
1631
from bernstein.adapters.base import DEFAULT_TIMEOUT_SECONDS, CLIAdapter, SpawnResult, build_worker_cmd
1732
from bernstein.adapters.env_isolation import build_filtered_env
1833
from bernstein.core.models import ApiTier, ApiTierInfo, ModelConfig, ProviderType, RateLimit
1934

35+
if TYPE_CHECKING:
36+
from collections.abc import Sequence
37+
2038
logger = logging.getLogger(__name__)
2139

2240
_OPENCODE_AUTH_FILE = Path.home() / ".local" / "share" / "opencode" / "auth.json"
2341

42+
#: Env var carrying the permission policy. Preferred over the escalating CLI
43+
#: flags for the *floor* because it is the only surface that can express the
44+
#: restricted direction too, so one mechanism pins both.
45+
_PERMISSION_ENV = "OPENCODE_PERMISSION"
46+
47+
#: The CLI flag named by ``DangerousModeStrategy.CLI_FLAG`` for this adapter.
48+
#: Passed alongside the env policy so the escalation is visible in the spawn
49+
#: record rather than only in the process environment.
50+
_ESCALATED_PERMISSION_FLAG = "--auto"
51+
52+
#: Tool permissions for a run that is allowed to act unattended.
53+
_ESCALATED_PERMISSION: dict[str, str] = {"edit": "allow", "bash": "allow", "webfetch": "allow"}
54+
55+
#: Tool permissions for a run that is not. ``deny`` rather than ``ask`` so the
56+
#: run fails fast and legibly instead of blocking on a prompt nobody answers.
57+
_RESTRICTED_PERMISSION: dict[str, str] = {"edit": "deny", "bash": "deny", "webfetch": "deny"}
58+
2459

2560
class OpenCodeAdapter(CLIAdapter):
2661
"""Spawn and monitor OpenCode CLI sessions."""
2762

63+
#: OpenCode exposes ``--continue`` to re-enter the prior session, which is
64+
#: the flag behind the ``resume`` axis this adapter declares. The retry
65+
#: surface derives a warm continuation from that declaration
66+
#: (``checkpoint_retry_capability``), so the opt-in and the declaration
67+
#: have to move together.
68+
supports_session_continuation = True
69+
70+
def _dangerous_mode(self) -> DangerousModeStrategy:
71+
"""Return the declared dangerous-mode strategy for this adapter."""
72+
declared = getattr(self.strategy(), "dangerous_mode", DangerousModeStrategy.UNSUPPORTED)
73+
return declared if isinstance(declared, DangerousModeStrategy) else DangerousModeStrategy.UNSUPPORTED
74+
75+
def _permission_escalated(self) -> bool:
76+
"""Whether this spawn may skip interactive tool-permission prompts."""
77+
return self._dangerous_mode() in (DangerousModeStrategy.CLI_FLAG, DangerousModeStrategy.ALWAYS_ON)
78+
79+
def _build_command(
80+
self,
81+
*,
82+
model: str,
83+
prompt: str,
84+
continuation_args: Sequence[str] = (),
85+
) -> list[str]:
86+
"""Build the ``opencode run`` argv for one spawn.
87+
88+
Args:
89+
model: Model identifier passed to ``-m``.
90+
prompt: The task prompt; stays positional and last.
91+
continuation_args: Flags that re-enter a prior session, as
92+
returned by :meth:`continuation_args`. Empty for a fresh
93+
spawn, so a first run never claims to continue anything.
94+
95+
Returns:
96+
The full argv, permission flag included when the declared
97+
dangerous-mode strategy escalates.
98+
"""
99+
cmd = ["opencode", "run", "-m", model, "--format", "json"]
100+
if self._permission_escalated():
101+
cmd.append(_ESCALATED_PERMISSION_FLAG)
102+
cmd.extend(continuation_args)
103+
cmd.append(prompt)
104+
return cmd
105+
106+
def _permission_env(self) -> dict[str, str]:
107+
"""Return the explicit permission policy for the spawn environment.
108+
109+
Set on every spawn in both directions. Passing only the escalating
110+
CLI flag would leave the restricted case resolving against the host's
111+
own config, which is the behaviour this pins shut.
112+
"""
113+
policy = _ESCALATED_PERMISSION if self._permission_escalated() else _RESTRICTED_PERMISSION
114+
return {_PERMISSION_ENV: json.dumps(policy, sort_keys=True)}
115+
116+
def continuation_args(self, _session_id: str) -> list[str]:
117+
"""Return the flags that re-enter this adapter's prior session.
118+
119+
OpenCode's ``--continue`` re-enters the most recent session for the
120+
working directory. Bernstein runs every task in its own git worktree,
121+
so "most recent session here" resolves to this task's own session
122+
without explicit id plumbing.
123+
"""
124+
return ["--continue"]
125+
28126
def spawn(
29127
self,
30128
*,
@@ -52,15 +150,7 @@ def spawn(
52150
if mcp_config:
53151
logger.debug("OpenCodeAdapter ignoring runtime MCP config injection for session %s", session_id)
54152

55-
cmd = [
56-
"opencode",
57-
"run",
58-
"-m",
59-
model_config.model,
60-
"--format",
61-
"json",
62-
prompt,
63-
]
153+
cmd = self._build_command(model=model_config.model, prompt=prompt)
64154

65155
pid_dir = workdir / ".sdd" / "runtime" / "pids"
66156
wrapped_cmd = build_worker_cmd(
@@ -87,6 +177,9 @@ def spawn(
87177
"GITLAB_TOKEN",
88178
]
89179
)
180+
# Applied after the allow-list so the pinned policy is what the worker
181+
# sees, whatever the operator's own environment or config file holds.
182+
env.update(self._permission_env())
90183
with log_path.open("w") as log_file:
91184
try:
92185
proc = subprocess.Popen(

‎tests/contract/contracts/opencode.yaml‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
# Contract for the OpenCode CLI (adapter: opencode).
22
#
33
# Always-passed surface from src/bernstein/adapters/opencode.py:
4-
# ``opencode run -m <model> --format json <prompt>``.
4+
# ``opencode run -m <model> --format json --auto <prompt>``.
5+
#
6+
# ``--auto`` is the escalating permission flag; it is dropped and the
7+
# OPENCODE_PERMISSION policy tightened when the adapter's declared
8+
# dangerous-mode strategy does not escalate. ``--continue`` is passed only on
9+
# a continuation retry, so it is required of the binary but not of every spawn.
510
adapter: opencode
611
binary: opencode
712
install:
@@ -14,6 +19,8 @@ auth:
1419
required_flags:
1520
- "-m"
1621
- "--format"
22+
- "--auto"
23+
- "--continue"
1724
required_subcommands:
1825
- "run"
1926
# Opencode sub-flags live under ``opencode run --help``.

‎tests/golden/opencode_adapter.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
#
33
# Pins the observable spawn outcome for the invocation surface the
44
# contract in tests/contract/contracts/opencode.yaml declares
5-
# (``opencode run -m <model> --format json <prompt>``): a SpawnResult
5+
# (``opencode run -m <model> --format json --auto <prompt>``): a SpawnResult
66
# carrying the child PID and a log path under the worktree's
77
# .sdd/runtime/ directory. Replayed under a mocked subprocess, so the
88
# transcript covers adapter-controlled invocation only and never

‎tests/unit/adapters/test_capability_enums.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,12 @@
1818
RESUME_NATIVE,
1919
STRATEGY_MATRIX,
2020
AdapterStrategy,
21+
CheckpointRetryCapability,
2122
DangerousModeStrategy,
2223
EventChannel,
2324
OutputMode,
2425
ResumeStrategy,
26+
checkpoint_retry_capability,
2527
resume_capability,
2628
strategy_for,
2729
strategy_table,
@@ -166,6 +168,41 @@ def test_text_signal_default_for_plain_adapters() -> None:
166168
assert strategy_for(name).event_channel is EventChannel.TEXT_SIGNALS
167169

168170

171+
def test_opencode_declares_native_resume_and_a_dangerous_mode_flag() -> None:
172+
"""Both axes are backed by flags the adapter passes; the event channel is not yet."""
173+
strategy = strategy_for("opencode")
174+
assert strategy.resume is ResumeStrategy.FLAG
175+
assert strategy.dangerous_mode is DangerousModeStrategy.CLI_FLAG
176+
assert strategy.event_channel is EventChannel.TEXT_SIGNALS
177+
178+
179+
def test_opencode_resume_declaration_drives_the_retry_surface() -> None:
180+
"""The resume axis is derived into runtime decisions, not merely rendered.
181+
182+
``checkpoint_retry_capability`` is a pure function of the resume axis, so
183+
declaring ``flag`` promises the retry path a warm continuation. The adapter
184+
backs that promise via ``continuation_args``; this pins the derivation so
185+
the two cannot drift apart silently.
186+
"""
187+
assert resume_capability("opencode") == RESUME_NATIVE
188+
assert checkpoint_retry_capability("opencode") is CheckpointRetryCapability.RESUME
189+
assert get_adapter("opencode").continuation_args("oc-1") != []
190+
191+
192+
def test_continuation_optin_matches_the_resume_declaration() -> None:
193+
"""An adapter declaring native resume must opt into the continuation path.
194+
195+
``adapter_supports_continuation`` reads ``supports_session_continuation``
196+
off the class; a declared-resume adapter that never opted in would leave
197+
the retry surface believing in a warm continuation nothing implements.
198+
"""
199+
for name in ("claude", "opencode"):
200+
adapter = get_adapter(name)
201+
assert strategy_for(name).resume is not ResumeStrategy.UNSUPPORTED
202+
assert adapter.supports_session_continuation is True
203+
assert adapter.continuation_args(f"{name}-1") != []
204+
205+
169206
def test_acp_channel_adapters_declared() -> None:
170207
for name in ("kilo", "goose"):
171208
assert strategy_for(name).event_channel is EventChannel.ACP

0 commit comments

Comments
 (0)