Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Support OpenCode V2 in unsloth start (#9275)

Pascal André489fab4a71f8
diff --git a/.github/scripts/agent-guides-drive.sh b/.github/scripts/agent-guides-drive.sh
index a1f1936118a..9d55900c8d7 100755
--- a/.github/scripts/agent-guides-drive.sh
+++ b/.github/scripts/agent-guides-drive.sh
@@ -396,6 +396,12 @@ invoke_via_connect() { # $1=outfile, rest=extra args appended to the command
# CONNECT_ENV_EXTRA / CONNECT_CMD_OVERRIDE let a caller (attribution-ab) flip a
# session knob without editing the user's config; empty -> use what start.py emitted.
local cmd="${CONNECT_CMD_OVERRIDE:-$CONNECT_CMD}"
+ # A bare V2 recipe ends in --standalone for the TUI. Once this driver adds the
+ # run subcommand, V2 requires that option after run instead of before it.
+ if [ "$AGENT" = opencode ] && [[ "$cmd" == *" --standalone" ]] && [ "${1:-}" = run ]; then
+ cmd="${cmd% --standalone}"
+ set -- run --standalone "${@:2}"
+ fi
{
echo "set -uo pipefail"
echo "$CONNECT_ENV"
diff --git a/.github/scripts/agent-guides-install.sh b/.github/scripts/agent-guides-install.sh
index daf4bacd3e5..66c0b6ef040 100755
--- a/.github/scripts/agent-guides-install.sh
+++ b/.github/scripts/agent-guides-install.sh
@@ -71,8 +71,18 @@ case "$AGENT" in
npm_retry "@openai/codex" || install_fail "npm install -g @openai/codex failed"
;;
opencode)
- # start.py install_hint: npm install -g opencode-ai
- npm_retry "opencode-ai" || install_fail "npm install -g opencode-ai failed"
+ case "${OPENCODE_CHANNEL:-stable}" in
+ stable) package="opencode-ai" ;;
+ v2)
+ package="@opencode-ai/cli@beta"
+ if latest_bin="$(npm view @opencode-ai/cli@latest bin --json 2>>"$LOG")" \
+ && grep -q '"opencode2"' <<<"$latest_bin"; then
+ package="@opencode-ai/cli@latest"
+ fi
+ ;;
+ *) install_fail "unknown OpenCode channel '${OPENCODE_CHANNEL}'" ;;
+ esac
+ npm_retry "$package" || install_fail "npm install -g $package failed"
;;
openclaw)
# start.py install_hint: curl -fsSL https://openclaw.ai/install.sh | bash
diff --git a/.github/workflows/local-agent-guides-ci.yml b/.github/workflows/local-agent-guides-ci.yml
index 20cfd02dd52..8b6ecd99a8f 100644
--- a/.github/workflows/local-agent-guides-ci.yml
+++ b/.github/workflows/local-agent-guides-ci.yml
@@ -125,17 +125,21 @@ jobs:
# it serves exactly one model on its own port.
# ═════════════════════════════════════════════════════════════════════
connection:
- name: connection (${{ matrix.agent }})
+ name: connection (${{ matrix.agent }}, ${{ matrix.opencode_channel }})
runs-on: ubuntu-latest
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
agent: [claude, codex, hermes, openclaw, opencode, pi]
+ opencode_channel: [stable]
include:
# OpenClaw needs Node 24; everything else is happy on 22.
- agent: openclaw
node: '24'
+ # V2 uses beta until @opencode-ai/cli@latest publishes opencode2.
+ - agent: opencode
+ opencode_channel: v2
env:
# gemma-4-E4B (128K context, capable enough to drive every agent for a
# trivial reply; the 270m model produced empty/failed responses for
@@ -286,6 +290,7 @@ jobs:
- name: Install agent CLI (class-b isolation)
env:
AGENT: ${{ matrix.agent }}
+ OPENCODE_CHANNEL: ${{ matrix.opencode_channel }}
run: bash .github/scripts/agent-guides-install.sh "$AGENT"
# ── (c) drive the agent via start.py and assert a reply ──────────
@@ -333,7 +338,7 @@ jobs:
continue-on-error: true
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
- name: connection-${{ matrix.agent }}-log
+ name: connection-${{ matrix.agent }}-${{ matrix.opencode_channel }}-log
path: |
logs/
redacted-configs/
diff --git a/tests/studio/test_agent_guides_verdicts.py b/tests/studio/test_agent_guides_verdicts.py
index 54fd414b83b..4bf8718f8bf 100644
--- a/tests/studio/test_agent_guides_verdicts.py
+++ b/tests/studio/test_agent_guides_verdicts.py
@@ -119,3 +119,10 @@ def test_guide_fail_still_names_the_recipe() -> None:
"""It is the right message for the case it is now reserved for."""
body = _block("guide_fail")
assert "guide drift" in body and "CONNECT_REF" in body
+
+
+def test_opencode_v2_guide_moves_standalone_after_run() -> None:
+ """Appending run to the bare V2 recipe must keep standalone a run option."""
+ body = _block("invoke_via_connect")
+ assert '[[ "$cmd" == *" --standalone" ]]' in body
+ assert 'set -- run --standalone "${@:2}"' in body
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 68ad3fd12cd..a4321a532d4 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -366,17 +366,30 @@ _OPENCODE_NON_AUTO_SUBCOMMANDS = frozenset(
"completion acp mcp attach debug providers auth agent upgrade uninstall serve web "
"models stats export import github pr session plugin plug db console generate".split()
)
+_OPENCODE_V2_SUBCOMMANDS = frozenset(
+ "acp api debug console auth mcp plugin models export import mini run service pair serve".split()
+)
+_OPENCODE_V2_STANDALONE_SUBCOMMANDS = frozenset("api models export import mini run".split())
_OPENCODE_GLOBAL_BOOLEAN_OPTIONS = frozenset(
- "-h --help -v --version --print-logs --pure --mdns".split()
+ "-h --help -v --version --print-logs --pure --mdns --standalone --wizard".split()
)
_OPENCODE_GLOBAL_VALUE_OPTIONS = frozenset(
- "--log-level --port --hostname --mdns-domain --cors".split()
+ "--log-level --port --hostname --mdns-domain --cors --server --completions --cpu-profile".split()
)
_OPENCODE_NATIVE_AUTO_MIN_VERSION = (1, 17, 12)
-def _opencode_supports_native_auto() -> bool:
- executable = _which_with_install_dirs("opencode")
+def _opencode_command() -> tuple[str, bool]:
+ resolved_v2 = _which_with_install_dirs("opencode2")
+ if resolved_v2:
+ return resolved_v2, True
+ return "opencode", False
+
+
+def _opencode_supports_native_auto(command: str = "opencode") -> bool:
+ if Path(command).stem.lower() == "opencode2":
+ return True
+ executable = _which_with_install_dirs(command)
if executable is None:
# No local binary: a --no-launch recipe may run elsewhere, and _run installs the
# current release on launch -- either way assume native --auto is available.
@@ -397,13 +410,13 @@ def _opencode_supports_native_auto() -> bool:
)
-def _opencode_subcommand(args: list[str]) -> Optional[str]:
- """Return an explicit OpenCode subcommand after supported global options."""
+def _opencode_subcommand(args: list[str]) -> tuple[Optional[str], Optional[int]]:
+ """Return an explicit OpenCode subcommand and its index after global options."""
index = 0
while index < len(args):
arg = args[index]
if arg == "--":
- return None
+ return None, None
if arg in _OPENCODE_GLOBAL_BOOLEAN_OPTIONS:
index += 1
continue
@@ -416,17 +429,25 @@ def _opencode_subcommand(args: list[str]) -> Optional[str]:
# A non-global option (e.g. --session) is a TUI flag; stop before its value is
# mistaken for a subcommand.
if arg.startswith("-"):
- return None
- return arg
- return None
+ return None, None
+ return arg, index
+ return None, None
-def _opencode_native_auto_args(args: list[str], yolo: bool) -> tuple[list[str], bool]:
+def _opencode_native_auto_args(
+ args: list[str],
+ yolo: bool,
+ *,
+ v2: bool = False,
+) -> tuple[list[str], bool]:
"""Add OpenCode's native --auto when the selected command supports it."""
routed = list(args)
if not yolo:
return routed, False
- if _opencode_subcommand(routed) in _OPENCODE_NON_AUTO_SUBCOMMANDS:
+ subcommand, _ = _opencode_subcommand(routed)
+ if v2 and subcommand in _OPENCODE_V2_SUBCOMMANDS and subcommand != "run":
+ return routed, False
+ if not v2 and subcommand in _OPENCODE_NON_AUTO_SUBCOMMANDS:
return routed, False
separator = routed.index("--") if "--" in routed else len(routed)
# --mini's runMini TUI forces auto=false and never forwards --auto, so appending it is
@@ -438,6 +459,30 @@ def _opencode_native_auto_args(args: list[str], yolo: bool) -> tuple[list[str],
return routed, True
+def _opencode_v2_standalone_args(args: list[str]) -> list[str]:
+ """Keep session-only config on the V2 server that consumes it."""
+ routed = list(args)
+ separator = routed.index("--") if "--" in routed else len(routed)
+ head = routed[:separator]
+ if (
+ "--standalone" in head
+ or "--server" in head
+ or any(arg.startswith("--server=") for arg in head)
+ ):
+ return routed
+ subcommand, subcommand_index = _opencode_subcommand(routed)
+ if (
+ subcommand in _OPENCODE_V2_SUBCOMMANDS
+ and subcommand not in _OPENCODE_V2_STANDALONE_SUBCOMMANDS
+ ):
+ return routed
+ insert_at = (
+ subcommand_index + 1 if subcommand in _OPENCODE_V2_STANDALONE_SUBCOMMANDS else separator
+ )
+ routed.insert(insert_at, "--standalone")
+ return routed
+
+
def _hermes_install_hint() -> str:
return _HERMES_WINDOWS_INSTALL_HINT if os.name == "nt" else _HERMES_POSIX_INSTALL_HINT
@@ -2726,7 +2771,12 @@ def _agent_config_path(path: Path, command: list) -> str:
return _wsl_windows_path(path) if _wsl_windows_executable(command) else str(path)
-def _opencode_subagent_inline_config(path: Path, permission: dict) -> dict:
+def _opencode_subagent_inline_config(
+ path: Path,
+ permission: dict,
+ command: str = "opencode",
+ v2: bool = False,
+) -> dict:
"""Keep the local provider visible without hiding the parent's allowed providers."""
inline: dict = {}
inherited = os.environ.get("OPENCODE_CONFIG_CONTENT")
@@ -2757,20 +2807,33 @@ def _opencode_subagent_inline_config(path: Path, permission: dict) -> dict:
provider for provider in disabled if provider != _OPENCODE_PROVIDER
]
- # The inherited inline layer is already highest priority. Merge it even when
- # OpenCode is not installed yet, as in fresh-install and --no-launch flows.
+ # Keep an inherited inline allowlist usable by the local provider. V2 turns these
+ # filters into policies where global/project rules still intentionally outrank this
+ # content; the message at launch makes that boundary explicit.
merge_provider_filters(inline)
effective = inline
- executable = _which_with_install_dirs("opencode")
- if executable is None:
+ executable = None if v2 else _which_with_install_dirs(command)
+ if v2:
+ legacy_depth = inline.pop("subagent_depth", None)
+ if (
+ isinstance(legacy_depth, int)
+ and not isinstance(legacy_depth, bool)
+ and legacy_depth > 0
+ ):
+ experimental = inline.get("experimental")
+ if not isinstance(experimental, dict):
+ experimental = {}
+ experimental.setdefault("subagent_depth", legacy_depth)
+ inline["experimental"] = experimental
+ elif executable is None:
typer.echo(
f"Warning: OpenCode is not installed, so provider filters could not be checked. "
f"The target configuration must allow '{_OPENCODE_PROVIDER}'.",
err = True,
)
else:
- env = _probe_env(OPENCODE_CONFIG = _agent_config_path(path, ["opencode"]))
+ env = _probe_env(OPENCODE_CONFIG = _agent_config_path(path, [command]))
try:
resolved = subprocess.run(
[executable, "debug", "config"],
@@ -2793,10 +2856,11 @@ def _opencode_subagent_inline_config(path: Path, permission: dict) -> dict:
merge_provider_filters(effective)
- depth = effective.get("subagent_depth")
- inline["subagent_depth"] = (
- depth if isinstance(depth, int) and not isinstance(depth, bool) and depth > 0 else 1
- )
+ if not v2:
+ depth = effective.get("subagent_depth")
+ inline["subagent_depth"] = (
+ depth if isinstance(depth, int) and not isinstance(depth, bool) and depth > 0 else 1
+ )
if permission:
inline["permission"] = permission
return inline
@@ -3149,7 +3213,7 @@ def _augment_path_with_install_dirs() -> None:
home = Path.home()
except (RuntimeError, OSError):
home = None
- candidates = [home / ".local" / "bin"] if home is not None else []
+ candidates = [home / ".local" / "bin", home / ".opencode" / "bin"] if home is not None else []
if os.name == "nt":
appdata = os.environ.get("APPDATA")
if appdata:
@@ -4609,8 +4673,9 @@ def opencode(
"""Point OpenCode at the running Unsloth server and start it."""
# Route a leading `org/name` positional to --model; forward the rest to the agent.
model, ctx.args[:] = _consume_positional_model(model, ctx.args)
- install_hint = _npm_install_hint("opencode-ai")
- _require_agent_for_launch("opencode", install_hint, launch)
+ command_name, opencode_v2 = _opencode_command()
+ install_hint = _npm_install_hint("@opencode-ai/cli@beta" if opencode_v2 else "opencode-ai")
+ _require_agent_for_launch(command_name, install_hint, launch)
base, key, entry = _connect(
api_key,
model,
@@ -4630,14 +4695,26 @@ def opencode(
presence_penalty = presence_penalty,
),
)
+ if opencode_v2:
+ typer.echo(
+ f"OpenCode V2 provider policies must allow '{_OPENCODE_PROVIDER}'.",
+ err = True,
+ )
if as_subagent:
subagent_id = _subagent_model_id(base, key, entry, model, gguf_variant)
subagent_model = {**entry, "id": subagent_id}
# Stay append-safe for a bare no-launch recipe: a later `run <prompt>` would make
# `opencode --auto run ...` parse as the TUI, so keep yolo in the inline fallback.
- route_native_auto = yolo and _opencode_supports_native_auto() and (launch or bool(ctx.args))
- opencode_args, native_auto = _opencode_native_auto_args(list(ctx.args), route_native_auto)
- command = ["opencode", *opencode_args]
+ route_native_auto = (
+ yolo and _opencode_supports_native_auto(command_name) and (launch or bool(ctx.args))
+ )
+ opencode_args = list(ctx.args)
+ if opencode_v2:
+ opencode_args = _opencode_v2_standalone_args(opencode_args)
+ opencode_args, native_auto = _opencode_native_auto_args(
+ opencode_args, route_native_auto, v2 = opencode_v2
+ )
+ command = [command_name, *opencode_args]
with _session_config("opencode-subagent", launch, persist = persist) as cfg:
config_path = cfg / "opencode.json"
session_permission = write_opencode_config(
@@ -4649,7 +4726,12 @@ def opencode(
as_subagent = True,
)
env = {"OPENCODE_CONFIG": str(config_path)}
- inline_config = _opencode_subagent_inline_config(config_path, session_permission)
+ inline_config = _opencode_subagent_inline_config(
+ config_path,
+ session_permission,
+ command = command_name,
+ v2 = opencode_v2,
+ )
# A project opencode.json outranks the session file and could field-merge its
# own agent.unsloth over ours. Pin ours in the inline overlay so it wins.
inline_config.setdefault("agent", {})[_SUBAGENT_NAME] = {
@@ -4678,20 +4760,30 @@ def opencode(
# subcommand such as `run <prompt>`; a leading --model would land before that
# subcommand and break it. Those paths rely on the inline pin instead.
native_auto = False
- route_native_auto = yolo and _opencode_supports_native_auto()
+ route_native_auto = yolo and _opencode_supports_native_auto(command_name)
if ctx.args:
- opencode_args, native_auto = _opencode_native_auto_args(list(ctx.args), route_native_auto)
- command = ["opencode", *opencode_args]
+ opencode_args = list(ctx.args)
+ if opencode_v2:
+ opencode_args = _opencode_v2_standalone_args(opencode_args)
+ opencode_args, native_auto = _opencode_native_auto_args(
+ opencode_args, route_native_auto, v2 = opencode_v2
+ )
+ command = [command_name, *opencode_args]
elif launch:
+ opencode_args = [] if opencode_v2 else ["--model", opencode_model]
+ if opencode_v2:
+ opencode_args = _opencode_v2_standalone_args(opencode_args)
opencode_args, native_auto = _opencode_native_auto_args(
- ["--model", opencode_model],
+ opencode_args,
route_native_auto,
+ v2 = opencode_v2,
)
- command = ["opencode", *opencode_args]
+ command = [command_name, *opencode_args]
else:
# Append-safe base: `opencode --auto run ...` parses as the TUI with a project
# "run", not the run subcommand. Command unknown here, so keep the config fallback.
- command = ["opencode"]
+ opencode_args = _opencode_v2_standalone_args([]) if opencode_v2 else []
+ command = [command_name, *opencode_args]
# opencode keeps sessions in ~/.local/share/opencode (never relocated), so resume
# already survives exit; reopen the last one by passing `opencode --continue` through.
with _session_config("opencode", launch, persist = persist) as cfg:
@@ -4711,16 +4803,9 @@ def opencode(
# outranks project config; the API key stays in the private file, never the env.
# Only the config fallback carries a permission. Native --auto omits it (auto-approve
# asks, keep explicit denies); a non-yolo session omits it too, honoring project rules.
- # opencode filters every provider (a config-defined custom one included) through
- # its enabled_providers allowlist and disabled_providers denylist, and a model pin
- # does not bypass that gate -- a filtered provider resolves to ModelNotFoundError.
- # To guarantee the session model loads without reading or modifying the user's real
- # config, scope THIS session to our provider alone: allowlist _OPENCODE_PROVIDER and
- # clear the denylist. These arrays are replaced (not merged) by higher layers, so
- # setting them in the highest-priority inline overlay neutralizes any user allowlist
- # or denylist for the launch. It is session-only: it lives in OPENCODE_CONFIG_CONTENT
- # for this invocation and never touches the user's config files, so their normal
- # `opencode` is unchanged; only this session is limited to the Unsloth provider.
+ # V1 filters are ordinary overlays, so scope that session to our provider. V2 turns
+ # filters into security policies where global/project rules intentionally win; keep
+ # those policies intact and tell the user above that they must allow our provider.
# small_model is opencode's separate model for lightweight tasks; pin it to the
# session model too, or a user/project small_model on another (now filtered)
# provider would resolve a not-found error mid-session. The session serves one
@@ -4728,9 +4813,10 @@ def opencode(
inline_config: dict = {
"model": opencode_model,
"small_model": opencode_model,
- "enabled_providers": [_OPENCODE_PROVIDER],
- "disabled_providers": [],
}
+ if not opencode_v2:
+ inline_config["enabled_providers"] = [_OPENCODE_PROVIDER]
+ inline_config["disabled_providers"] = []
if session_permission:
inline_config["permission"] = session_permission
env = {
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index b877210347b..79ddb2eb7ad 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -723,6 +723,31 @@ def test_opencode_native_auto_probes_old_opencode_only_in_install_dir(monkeypatc
assert start._opencode_supports_native_auto() is False
+def test_opencode_command_prefers_installed_v2(monkeypatch):
+ monkeypatch.setattr(
+ start,
+ "_which_with_install_dirs",
+ lambda name: "/usr/local/bin/opencode2" if name == "opencode2" else None,
+ )
+ assert start._opencode_command() == ("/usr/local/bin/opencode2", True)
+
+
+def test_opencode_command_falls_back_to_v1(monkeypatch):
+ monkeypatch.setattr(start, "_which_with_install_dirs", lambda _: None)
+ assert start._opencode_command() == ("opencode", False)
+
+
+def test_opencode_command_finds_official_v2_install_dir(monkeypatch, tmp_path):
+ install_dir = tmp_path / ".opencode" / "bin"
+ install_dir.mkdir(parents = True)
+ monkeypatch.setattr(start.Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("APPDATA", str(tmp_path / "no-appdata"))
+ monkeypatch.setenv("PATH", str(tmp_path / "existing"))
+ monkeypatch.setattr(start.shutil, "which", _path_aware_which({"opencode2": install_dir}))
+
+ assert start._opencode_command() == (str(install_dir / "opencode2"), True)
+
+
def test_augment_path_preserves_defpath_when_path_unset(monkeypatch, tmp_path):
# PATH unset: shutil.which() and exec*p* fall back to os.defpath (e.g. /bin:/usr/bin), so the
# augmentation must keep those default dirs instead of collapsing to just the install dir
@@ -1179,6 +1204,8 @@ def test_unsupported_agents_reject_as_subagent(agent, flag):
@pytest.mark.parametrize("agent", ["claude", "codex", "openclaw", "opencode", "hermes", "pi"])
def test_launch_preflights_agent_before_connect(agent, monkeypatch):
events = []
+ if agent == "opencode":
+ monkeypatch.setattr(start, "_opencode_command", lambda *_: ("opencode", False))
def require(name, hint, launch):
assert name == agent
@@ -1240,7 +1267,7 @@ def test_noninteractive_missing_agent_stops_before_connect(agent, monkeypatch):
assert f"`{agent}` not found on PATH" in result.output
[email protected]("agent", ["claude", "codex", "openclaw", "opencode", "hermes", "pi"])
[email protected]("agent", ["claude", "codex", "openclaw", "hermes", "pi"])
def test_no_launch_skips_agent_resolution(agent, monkeypatch):
monkeypatch.setattr(
start,
@@ -1264,6 +1291,30 @@ def test_no_launch_skips_agent_resolution(agent, monkeypatch):
assert isinstance(result.exception, RuntimeError)
+def test_opencode_no_launch_resolves_generation_without_installing(monkeypatch):
+ resolved = []
+ monkeypatch.setattr(
+ start,
+ "_which_with_install_dirs",
+ lambda name: resolved.append(name)
+ or ("/home/me/.opencode/bin/opencode2" if name == "opencode2" else None),
+ )
+ monkeypatch.setattr(
+ start,
+ "_install_agent",
+ lambda *args: pytest.fail("--no-launch must not install an agent"),
+ )
+ monkeypatch.setattr(
+ start, "_connect", lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError)
+ )
+
+ result = CliRunner().invoke(start.start_app, ["opencode", "--no-launch"])
+
+ assert result.exit_code == 1
+ assert isinstance(result.exception, RuntimeError)
+ assert resolved == ["opencode2"]
+
+
def test_missing_pi_subagent_extension_fails_before_install_or_connect(monkeypatch, tmp_path):
monkeypatch.setattr(start, "_PI_SUBAGENT_EXTENSION", tmp_path / "missing.ts")
monkeypatch.setattr(
@@ -1327,6 +1378,8 @@ def fake_studio(tmp_path, monkeypatch):
# --no-launch session configs land under tmp instead of the real Unsloth dir.
monkeypatch.setattr(start, "_agents_config_root", lambda: tmp_path / "agents")
monkeypatch.setattr(start, "_require_agent_for_launch", lambda *args: None)
+ # Most existing assertions cover the stable V1 command; V2 has focused cases below.
+ monkeypatch.setattr(start, "_opencode_command", lambda *_: ("opencode", False))
# No `claude` on PATH, so _claude_flags never probes the real binary.
monkeypatch.setattr(start.shutil, "which", lambda _: None)
monkeypatch.delenv("UNSLOTH_API_KEY", raising = False)
@@ -4435,6 +4488,36 @@ def test_opencode_subagent_inline_merges_inherited_filters_without_binary(monkey
assert inline["subagent_depth"] == 1
+def test_opencode_v2_subagent_uses_native_depth_without_debug_probe(monkeypatch, tmp_path):
+ monkeypatch.setenv(
+ "OPENCODE_CONFIG_CONTENT",
+ json.dumps({"enabled_providers": ["anthropic"], "subagent_depth": 2}),
+ )
+ monkeypatch.setattr(
+ start.subprocess,
+ "run",
+ lambda *args, **kwargs: pytest.fail("V2 debug config is not a resolved object"),
+ )
+
+ inline = start._opencode_subagent_inline_config(
+ tmp_path / "opencode.json", {}, command = "opencode2", v2 = True
+ )
+
+ assert "subagent_depth" not in inline
+ assert inline["enabled_providers"] == ["anthropic", start._OPENCODE_PROVIDER]
+ assert inline["experimental"] == {"subagent_depth": 2}
+
+
+def test_opencode_v2_subagent_does_not_override_configured_depth(monkeypatch, tmp_path):
+ monkeypatch.delenv("OPENCODE_CONFIG_CONTENT", raising = False)
+
+ inline = start._opencode_subagent_inline_config(
+ tmp_path / "opencode.json", {}, command = "opencode2", v2 = True
+ )
+
+ assert "experimental" not in inline
+
+
def _opencode_inline_config(output: str) -> dict:
# --no-launch prints OPENCODE_CONFIG_CONTENT as a POSIX `export NAME=<shell-quoted>`
# line on Unix/WSL and a PowerShell `$env:NAME = "<escaped>"` line on native Windows;
@@ -4523,8 +4606,50 @@ def test_connect_opencode_no_launch(fake_studio, tmp_path):
assert not any(c[1].endswith("/api/inference/status") for c in fake_studio)
+def test_connect_opencode_v2_no_launch_uses_private_server(fake_studio, monkeypatch):
+ monkeypatch.setattr(start, "_opencode_command", lambda *_: ("opencode2", True))
+
+ result = CliRunner().invoke(start.start_app, ["opencode", "--no-launch"])
+
+ assert result.exit_code == 0, result.output
+ assert _launch_command(result.output) == ["opencode2", "--standalone"]
+ assert _opencode_inline_config(result.output)["model"] == (
+ f"{start._OPENCODE_PROVIDER}/{MODEL['id']}"
+ )
+ assert "enabled_providers" not in _opencode_inline_config(result.output)
+ assert "disabled_providers" not in _opencode_inline_config(result.output)
+ assert f"provider policies must allow '{start._OPENCODE_PROVIDER}'" in result.output
+
+
+def test_connect_opencode_v2_no_launch_uses_resolved_off_path_binary(
+ fake_studio, monkeypatch, tmp_path
+):
+ binary = tmp_path / ".opencode" / "bin" / "opencode2"
+ monkeypatch.setattr(
+ start,
+ "_opencode_command",
+ lambda: (str(binary), True),
+ )
+
+ result = CliRunner().invoke(start.start_app, ["opencode", "--no-launch"])
+
+ assert result.exit_code == 0, result.output
+ assert _launch_command(result.output) == [str(binary), "--standalone"]
+
+
+def test_connect_opencode_v2_models_uses_private_server(fake_studio, monkeypatch):
+ monkeypatch.setattr(start, "_opencode_command", lambda *_: ("opencode2", True))
+
+ result = CliRunner().invoke(start.start_app, ["opencode", "--no-launch", "models"])
+
+ assert result.exit_code == 0, result.output
+ assert _launch_command(result.output) == ["opencode2", "models", "--standalone"]
+
+
def test_connect_opencode_as_subagent_preserves_cloud_parent(fake_studio, tmp_path, monkeypatch):
- monkeypatch.setattr(start, "_opencode_subagent_inline_config", lambda path, permission: {})
+ monkeypatch.setattr(
+ start, "_opencode_subagent_inline_config", lambda path, permission, **kwargs: {}
+ )
result = CliRunner().invoke(
start.start_app,
[
@@ -4590,7 +4715,7 @@ def test_opencode_subagent_installs_binary_before_filter_inspection(fake_studio,
monkeypatch.setattr(start, "_require_agent_for_launch", require)
inspected = {}
- def inline(path, permission):
+ def inline(path, permission, **kwargs):
inspected["binary"] = start._which_with_install_dirs("opencode")
return {}
@@ -4607,7 +4732,9 @@ def test_opencode_subagent_installs_binary_before_filter_inspection(fake_studio,
def test_opencode_subagent_pins_agent_in_inline_overlay(fake_studio, monkeypatch):
# A project opencode.json outranks the session file, so the agent must ride in
# OPENCODE_CONFIG_CONTENT where a repo's own agent.unsloth cannot field-merge over it.
- monkeypatch.setattr(start, "_opencode_subagent_inline_config", lambda path, permission: {})
+ monkeypatch.setattr(
+ start, "_opencode_subagent_inline_config", lambda path, permission, **kwargs: {}
+ )
result = CliRunner().invoke(
start.start_app,
["opencode", "--as-subagent", "--no-launch", "--model", MODEL["id"] + ":UD-Q4_K_XL"],
@@ -4621,10 +4748,10 @@ def test_opencode_subagent_pins_agent_in_inline_overlay(fake_studio, monkeypatch
def test_connect_opencode_subagent_yolo_no_launch_stays_append_safe(fake_studio, monkeypatch):
- monkeypatch.setattr(start, "_opencode_supports_native_auto", lambda: True)
+ monkeypatch.setattr(start, "_opencode_supports_native_auto", lambda *_: True)
captured = {}
- def inline(path, permission):
+ def inline(path, permission, **kwargs):
captured["permission"] = permission
return {"permission": permission}
@@ -4973,6 +5100,38 @@ def test_yolo_opencode_run_uses_native_auto(fake_studio):
assert "permission" not in _opencode_inline_config(result.output)
+def test_yolo_opencode_v2_run_uses_standalone_and_native_auto(fake_studio, monkeypatch):
+ monkeypatch.setattr(start, "_opencode_command", lambda *_: ("opencode2", True))
+
+ result = CliRunner().invoke(
+ start.start_app,
+ ["opencode", "--yolo", "--no-launch", "run", "hello"],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert _launch_command(result.output) == [
+ "opencode2",
+ "run",
+ "--standalone",
+ "hello",
+ "--auto",
+ ]
+ assert "permission" not in _opencode_inline_config(result.output)
+
+
+def test_yolo_opencode_v2_mini_uses_permission_fallback(fake_studio, monkeypatch):
+ monkeypatch.setattr(start, "_opencode_command", lambda *_: ("opencode2", True))
+
+ result = CliRunner().invoke(
+ start.start_app,
+ ["opencode", "--yolo", "--no-launch", "mini"],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert _launch_command(result.output) == ["opencode2", "mini", "--standalone"]
+ assert _opencode_inline_config(result.output)["permission"]["edit"] == "allow"
+
+
def test_yolo_opencode_tui_resume_uses_native_auto(fake_studio):
result = CliRunner().invoke(
start.start_app,
@@ -4996,7 +5155,7 @@ def test_no_yolo_opencode_run_omits_native_auto(fake_studio):
def test_yolo_opencode_bare_launch_uses_native_auto(fake_studio, monkeypatch):
monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/opencode")
- monkeypatch.setattr(start, "_opencode_supports_native_auto", lambda: True)
+ monkeypatch.setattr(start, "_opencode_supports_native_auto", lambda *_: True)
captured = _capture_launch(monkeypatch, ["opencode", "--yolo"])
assert captured["command"][1:] == [
"--model",
@@ -5006,6 +5165,16 @@ def test_yolo_opencode_bare_launch_uses_native_auto(fake_studio, monkeypatch):
assert "permission" not in json.loads(captured["env"]["OPENCODE_CONFIG_CONTENT"])
+def test_yolo_opencode_v2_bare_launch_omits_root_model(fake_studio, monkeypatch):
+ monkeypatch.setattr(start, "_opencode_command", lambda *_: ("opencode2", True))
+ monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/opencode2")
+ captured = _capture_launch(monkeypatch, ["opencode", "--yolo"])
+
+ assert captured["command"][0].endswith("opencode2")
+ assert captured["command"][1:] == ["--standalone", "--auto"]
+ assert "--model" not in captured["command"]
+
+
def test_yolo_opencode_native_auto_clears_prior_config_fallback(fake_studio, tmp_path):
fallback = CliRunner().invoke(
start.start_app,