Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
Support OpenCode 2 and migrate native v1 installations (#1840)
Ali Khokhara78d2831dfe0
diff --git a/README.md b/README.mdindex 2b72c8a9..10a6532c 100644--- a/README.md+++ b/README.md@@ -125,12 +125,25 @@ Pi:fcc-pi```-OpenCode:+OpenCode 2:```bashfcc-opencode```+To upgrade from OpenCode 1, rerun the FCC installer with OpenCode selected. It+upgrades the native installation in `~/.opencode/bin`; for npm or other package+managers, follow [OpenCode's migration instructions](https://opencode.ai/v2/docs/migrate-v1/)+first. For npm v1, run `npm uninstall -g opencode-ai`, then rerun the FCC installer.+Close OpenCode before upgrading. OpenCode manages its own data upgrades.++RTK integration is temporarily unavailable for OpenCode 2. The installer saves+the recognized old RTK plugin outside the plugin directory; customized plugins+need manual migration. RTK continues to work with the other supported agents.++Use `fcc-opencode` for coding and sessions. Use plain `opencode` for commands+such as upgrades, service management, ACP, and MCP setup.+Cline:```bashdiff --git a/pyproject.toml b/pyproject.tomlindex 4c97e8d2..312628fb 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "6.2.44"+version = "6.2.45"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/scripts/install.ps1 b/scripts/install.ps1index 825b4557..bd17117c 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -21,7 +21,7 @@ $MinUvVersion = "0.12.13"$ClaudeInstallUrl = "https://claude.ai/install.ps1"$CodexInstallUrl = "https://chatgpt.com/codex/install.ps1"$PiInstallUrl = "https://pi.dev/install.ps1"-$OpenCodeReleaseBaseUrl = "https://github.com/anomalyco/opencode/releases/latest/download"+$OpenCodeReleaseBaseUrl = "https://opencode.ai/files/bin"$HermesInstallUrl = "https://hermes-agent.nousresearch.com/install.ps1"$DshVersion = "0.1.0-rc.8"$DshPackage = "@deepseek-ai/dsh@$DshVersion"@@ -604,9 +604,6 @@ function Configure-RtkForSelectedAgents {if ($script:InstallPi -and $script:PiAvailable) {Invoke-RtkCommand -Arguments @("init", "--global", "--agent", "pi")}- if ($script:InstallOpenCode) {- Invoke-RtkCommand -Arguments @("init", "--global", "--opencode")- }if ($script:InstallCline) {Write-Host "Optional for each project: cd <project>; `$env:RTK_TELEMETRY_DISABLED='1'; rtk init --agent cline"}@@ -701,6 +698,75 @@ function Test-SupportedStableVersion {return ([version] $normalizedVersion) -ge ([version] $normalizedMinimum)}+function Read-OpenCodeVersionOutput {+ param([string] $OpenCodePath)++ $temporaryRoot = Join-Path ([IO.Path]::GetTempPath()) ("fcc-opencode-version-" + [guid]::NewGuid().ToString("N"))+ $stdoutPath = Join-Path $temporaryRoot "stdout.txt"+ $stderrPath = Join-Path $temporaryRoot "stderr.txt"+ $process = $null+ try {+ New-Item -ItemType Directory -Path $temporaryRoot | Out-Null+ $process = Start-Process -FilePath $OpenCodePath -ArgumentList @("--version") -WindowStyle Hidden -PassThru -RedirectStandardOutput $stdoutPath -RedirectStandardError $stderrPath+ # Windows PowerShell needs the handle retained to report the exit code.+ [void] $process.Handle+ if (-not $process.WaitForExit(10000)) {+ & "$env:SYSTEMROOT\System32\taskkill.exe" /PID $process.Id /T /F *> $null+ [void] $process.WaitForExit(5000)+ throw "OpenCode version probe timed out at '$OpenCodePath'."+ }+ if ($process.ExitCode -ne 0) {+ throw "OpenCode version probe failed at '$OpenCodePath' (exit code $($process.ExitCode))."+ }+ return [IO.File]::ReadAllText($stdoutPath)+ }+ finally {+ if ($null -ne $process) { $process.Dispose() }+ Remove-Item -LiteralPath $temporaryRoot -Recurse -Force -ErrorAction SilentlyContinue+ }+}++function Get-OpenCodeVersion {+ param([string] $OpenCodePath)++ $output = Read-OpenCodeVersionOutput $OpenCodePath+ if ($output -match '(?m)^\s*(?:opencode(?:\s+version)?\s+)?v?(?<version>\d+\.\d+\.\d+(?:\+[0-9A-Za-z.-]+)?)\s*$') {+ return $Matches["version"]+ }+ return ""+}++function Get-OpenCodeRtkPlugin {+ $pluginPath = Join-Path $env:USERPROFILE ".config\opencode\plugins\rtk.ts"+ try {+ $plugin = Get-Item -LiteralPath $pluginPath -Force -ErrorAction Stop+ }+ catch [System.Management.Automation.ItemNotFoundException] {+ return $null+ }+ if ($plugin.PSIsContainer -or ($plugin.Attributes -band [IO.FileAttributes]::ReparsePoint)) {+ throw "Disable or migrate the RTK plugin at '$pluginPath' manually, then rerun the installer."+ }+ # These include the backup's parent; a junction must not redirect either move.+ foreach ($relativePath in @(".config", ".config\opencode", ".config\opencode\plugins")) {+ $parent = Get-Item -LiteralPath (Join-Path $env:USERPROFILE $relativePath) -Force -ErrorAction Stop+ if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) {+ throw "The RTK plugin directory is linked: '$($parent.FullName)'. Disable or migrate it manually, then rerun the installer."+ }+ }+ $sha256 = [Security.Cryptography.SHA256]::Create()+ try {+ $hash = [BitConverter]::ToString($sha256.ComputeHash([IO.File]::ReadAllBytes($pluginPath))).Replace("-", "").ToLowerInvariant()+ }+ finally {+ $sha256.Dispose()+ }+ if ($hash -ne "6530c131946c84892f9522abd68d4e513e1e658d8ddbad1f59388c86ebbcb6bb") {+ throw "The RTK plugin at '$pluginPath' was modified or is unrecognized. Disable or migrate it manually, then rerun the installer."+ }+ return $pluginPath+}+function Get-OpenCodeWindowsAssetName {$architecture = $env:PROCESSOR_ARCHITEW6432if ([string]::IsNullOrWhiteSpace($architecture)) {@@ -719,16 +785,27 @@ function Get-OpenCodeWindowsAssetName {}}+function Assert-NoOpenCodeProcessesRunning {+ if (@(Get-Process -Name opencode,opencode2 -ErrorAction SilentlyContinue).Count -gt 0) {+ throw "Close OpenCode before replacing its executable or RTK plugin, then rerun the installer."+ }+}+function Install-OpenCode {$assetName = Get-OpenCodeWindowsAssetName- $archiveUrl = "$OpenCodeReleaseBaseUrl/$assetName"$installDirectory = Join-Path $env:USERPROFILE ".opencode\bin"if ($DryRun) {- Write-Host "+ irm $archiveUrl -OutFile <temporary-archive>"+ Write-Host "+ resolve latest stable OpenCode 2 and download $assetName"Write-Host "+ extract and install opencode.exe to $(Format-Argument $installDirectory)"return}+ $release = Invoke-RestMethod -Uri "https://opencode.ai/update/api/latest/cli/npm" -ErrorAction Stop+ if ($release.version -isnot [string] -or $release.version -notmatch '^2\.\d+\.\d+$') {+ throw "The OpenCode release channel did not return a stable OpenCode 2 version."+ }+ $archiveUrl = "$OpenCodeReleaseBaseUrl/$($release.version)/$assetName"+$temporaryRoot = Join-Path ([IO.Path]::GetTempPath()) ("fcc-opencode-" + [guid]::NewGuid().ToString("N"))$archivePath = Join-Path $temporaryRoot $assetName$extractPath = Join-Path $temporaryRoot "extracted"@@ -746,12 +823,17 @@ function Install-OpenCode {if ($executables.Count -ne 1) {throw "The OpenCode release archive did not contain exactly one opencode.exe."}+ $version = Get-OpenCodeVersion $executables[0].FullName+ if (($version -replace '\+.*$', '') -ne $release.version) {+ throw "The OpenCode archive did not contain the selected stable version $($release.version)."+ }New-Item -ItemType Directory -Force -Path $installDirectory | Out-NullCopy-Item -LiteralPath $executables[0].FullName -Destination $temporaryInstallPathif ((-not (Test-Path -LiteralPath $temporaryInstallPath -PathType Leaf)) -or ((Get-Item -LiteralPath $temporaryInstallPath).Length -eq 0)) {throw "The extracted OpenCode executable was empty."}+ Assert-NoOpenCodeProcessesRunningMove-Item -LiteralPath $temporaryInstallPath -Destination (Join-Path $installDirectory "opencode.exe") -Force}finally {@@ -761,16 +843,64 @@ function Install-OpenCode {}function Ensure-OpenCode {- $command = Get-ApplicationCommand "opencode"+ $command = if ($script:OriginalOpenCode) { $script:OriginalOpenCode } else { Get-ApplicationCommand "opencode" }+ $nativePath = Join-Path $env:USERPROFILE ".opencode\bin\opencode.exe"+ if ($DryRun) {+ Write-Host "+ opencode --version"+ Write-Host "Install stable OpenCode 2 if absent, or migrate v1 at '$nativePath'; external v1 requires manual upgrade."+ Write-Host "Check and back up the recognized old OpenCode RTK plugin if present."+ if (-not $command) { Install-OpenCode }+ return+ }++ $install = $trueif ($command) {- Write-Host "OpenCode already found on PATH; verifying it."+ $version = Get-OpenCodeVersion $command.Source+ if ($version -match '^2\.') {+ $install = $false+ }+ elseif ($version -match '^1\.') {+ if (-not (Test-EquivalentPath $command.Source $nativePath)) {+ throw "OpenCode 1 at '$($command.Source)' requires manual migration. Remove it with its package manager (npm: npm uninstall -g opencode-ai), then rerun this installer. See https://opencode.ai/v2/docs/migrate-v1/"+ }+ }+ else {+ throw "OpenCode at '$($command.Source)' is not a recognized stable v1 or v2. Correct that installation, then rerun the installer. See https://opencode.ai/v2/docs/migrate-v1/"+ }}- else {+ $pluginPath = Get-OpenCodeRtkPlugin+ if ($install -or $pluginPath) {+ Assert-NoOpenCodeProcessesRunning+ }+ if ($install) {+ foreach ($target in @((Join-Path $env:USERPROFILE ".opencode"), (Split-Path -Parent $nativePath), $nativePath)) {+ $item = Get-Item -LiteralPath $target -Force -ErrorAction SilentlyContinue+ if ($null -ne $item -and ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {+ throw "OpenCode installation path is linked: '$target'. Migrate it manually."+ }+ }Install-OpenCodeAdd-KnownBinDirectories+ if ((Get-OpenCodeVersion $nativePath) -notmatch '^2\.') {+ throw "The OpenCode installer did not install stable OpenCode 2 at '$nativePath'."+ }+ }+ # Check the command selected after the installer's PATH additions.+ $command = Get-ApplicationCommand "opencode"+ if (-not $command) { throw "OpenCode is not available on PATH after installation." }+ $version = Get-OpenCodeVersion $command.Source+ if ($version -notmatch '^2\.') {+ throw "OpenCode at '$($command.Source)' is not stable OpenCode 2. Correct PATH, then rerun the installer."+ }+ Write-Host "Verified OpenCode $version at '$($command.Source)'."+ if ($pluginPath) {+ $pluginPath = Get-OpenCodeRtkPlugin+ if (-not $pluginPath) { return }+ $backupPath = Join-Path (Split-Path -Parent (Split-Path -Parent $pluginPath)) ("rtk-v1-" + [guid]::NewGuid().ToString("N") + ".bak")+ Assert-NoOpenCodeProcessesRunning+ Move-Item -LiteralPath $pluginPath -Destination $backupPath -ErrorAction Stop+ Write-Host "OpenCode 2 RTK support is unavailable; the old plugin was saved at '$backupPath'."}-- Confirm-Application -CommandName "opencode" -DisplayName "OpenCode"}function Ensure-Cline {@@ -1401,6 +1531,8 @@ if ((-not [string]::IsNullOrWhiteSpace($TorchBackend)) -and (-not ($VoiceLocal -throw "-TorchBackend requires -VoiceLocal or -VoiceAll."}+# Preserve the user's winning command before adding installer search paths.+$script:OriginalOpenCode = Get-ApplicationCommand "opencode"Add-KnownBinDirectories$script:InstallCline = [bool] ((Get-ApplicationCommand "cline") -or (Get-ApplicationCommand "npm"))Write-Step "Checking for running Free Claude Code processes"diff --git a/scripts/install.sh b/scripts/install.shindex d64ac9dd..7f56cf77 100644--- a/scripts/install.sh+++ b/scripts/install.sh@@ -7,7 +7,7 @@ MIN_UV_VERSION="0.12.13"CLAUDE_INSTALL_URL="https://claude.ai/install.sh"CODEX_INSTALL_URL="https://chatgpt.com/codex/install.sh"PI_INSTALL_URL="https://pi.dev/install.sh"-OPENCODE_INSTALL_URL="https://opencode.ai/install"+OPENCODE_INSTALL_URL="https://opencode.ai/v2/install"HERMES_INSTALL_URL="https://hermes-agent.nousresearch.com/install.sh"DSH_VERSION="0.1.0-rc.8"DSH_PACKAGE="@deepseek-ai/dsh@$DSH_VERSION"@@ -640,9 +640,6 @@ configure_rtk_for_selected_agents() {if [ "$install_pi" -eq 1 ] && [ "$pi_available" -eq 1 ]; thenrun_rtk_init init --global --agent pifi- if [ "$install_opencode" -eq 1 ]; then- run_rtk_init init --global --opencode- fiif [ "$install_cline" -eq 1 ]; thenprintf 'Optional for each project: cd <project> && RTK_TELEMETRY_DISABLED=1 rtk init --agent cline\n'fi@@ -702,15 +699,112 @@ ensure_pi() {pi_available=1}-ensure_opencode() {- if command -v opencode >/dev/null 2>&1; then- printf 'OpenCode already found on PATH; verifying it.\n'+opencode_version() {+ opencode_output=$("$1" --version) || return 1+ printf '%s\n' "$opencode_output" | sed -nE 's/^[[:space:]]*(opencode([[:space:]]+version)?[[:space:]]+)?v?([0-9]+\.[0-9]+\.[0-9]+)(\+[0-9A-Za-z.-]+)?[[:space:]]*$/\3\4/p'+}++opencode_rtk_plugin() {+ opencode_plugin_path="$HOME/.config/opencode/plugins/rtk.ts"+ if [ ! -e "$opencode_plugin_path" ] && [ ! -L "$opencode_plugin_path" ]; then+ return 0+ fi+ [ -f "$opencode_plugin_path" ] && [ ! -L "$opencode_plugin_path" ] ||+ fail "Disable or migrate the RTK plugin at $opencode_plugin_path manually, then rerun the installer."+ # The backup lives in .config/opencode; check its parents as well as the+ # plugin directory so a linked parent cannot redirect either mutation.+ for opencode_parent in "$HOME/.config" "$HOME/.config/opencode" "$HOME/.config/opencode/plugins"; do+ [ ! -L "$opencode_parent" ] ||+ fail "The RTK plugin directory is linked: $opencode_parent. Disable or migrate it manually, then rerun the installer."+ done+ if command -v sha256sum >/dev/null 2>&1; then+ opencode_plugin_hash=$(sha256sum "$opencode_plugin_path") || return 1+ elif command -v shasum >/dev/null 2>&1; then+ opencode_plugin_hash=$(shasum -a 256 "$opencode_plugin_path") || return 1else- download_and_run "$OPENCODE_INSTALL_URL" bash "OpenCode"- add_known_bin_directories+ fail "Checking the old OpenCode RTK plugin requires sha256sum or shasum."fi+ [ "${opencode_plugin_hash%% *}" = "6530c131946c84892f9522abd68d4e513e1e658d8ddbad1f59388c86ebbcb6bb" ] ||+ fail "The RTK plugin at $opencode_plugin_path was modified or is unrecognized. Disable or migrate it manually, then rerun the installer."+ printf '%s\n' "$opencode_plugin_path"+}++assert_no_opencode_processes_running() {+ [ -z "$(fcc_process_ids opencode)$(fcc_process_ids opencode2)" ] ||+ fail "Close OpenCode before replacing its executable or RTK plugin, then rerun the installer."+}- verify_command opencode "OpenCode"+run_opencode_installer() {+ # Recheck after the script download. Upstream owns the actual installation.+ assert_no_opencode_processes_running+ VERSION= bash "$@"+}++ensure_opencode() {+ [ -n "${HOME:-}" ] || fail "HOME is required to install OpenCode."+ opencode_native="$HOME/.opencode/bin/opencode"+ opencode_path=${original_opencode_path:-$(command -v opencode || true)}+ if [ "$dry_run" -eq 1 ]; then+ print_command opencode --version+ printf 'Install stable OpenCode 2 if absent, or migrate v1 at %s; external v1 requires manual upgrade.\n' "$opencode_native"+ printf 'Check and back up the recognized old OpenCode RTK plugin if present.\n'+ if [ -z "$opencode_path" ]; then+ download_and_run "$OPENCODE_INSTALL_URL" bash "OpenCode"+ fi+ return 0+ fi++ opencode_install=1+ if [ -n "$opencode_path" ]; then+ opencode_current=$(opencode_version "$opencode_path") ||+ fail "Could not read OpenCode version at $opencode_path. Correct that installation, then rerun the installer."+ case "$opencode_current" in+ 2.*) opencode_install=0 ;;+ 1.*)+ [ "$opencode_path" = "$opencode_native" ] ||+ fail "OpenCode 1 at $opencode_path requires manual migration. Remove it with its package manager (npm: npm uninstall -g opencode-ai), then rerun this installer. See https://opencode.ai/v2/docs/migrate-v1/"+ ;;+ *) fail "OpenCode at $opencode_path is not a recognized stable v1 or v2. Correct that installation, then rerun the installer. See https://opencode.ai/v2/docs/migrate-v1/" ;;+ esac+ fi+ opencode_plugin=$(opencode_rtk_plugin) || return $?+ if [ "$opencode_install" -eq 1 ] || [ -n "$opencode_plugin" ]; then+ assert_no_opencode_processes_running+ fi+ if [ "$opencode_install" -eq 1 ]; then+ for opencode_target in "$HOME/.opencode" "$HOME/.opencode/bin" "$opencode_native"; do+ [ ! -L "$opencode_target" ] || fail "OpenCode installation path is linked: $opencode_target. Migrate it manually."+ done+ download_and_run "$OPENCODE_INSTALL_URL" run_opencode_installer "OpenCode"+ add_known_bin_directories+ hash -r 2>/dev/null || true+ opencode_installed=$(opencode_version "$opencode_native") || fail "Could not verify installed OpenCode at $opencode_native."+ case "$opencode_installed" in+ 2.*) ;;+ *) fail "The OpenCode installer did not install stable OpenCode 2. See https://opencode.ai/v2/docs/" ;;+ esac+ fi+ # Check the command selected after the installer's PATH additions.+ hash -r 2>/dev/null || true+ opencode_path=$(command -v opencode || true)+ [ -n "$opencode_path" ] || fail "OpenCode is not available on PATH after installation."+ opencode_current=$(opencode_version "$opencode_path") || fail "Could not verify OpenCode at $opencode_path."+ case "$opencode_current" in+ 2.*) printf 'Verified OpenCode %s at %s.\n' "$opencode_current" "$opencode_path" ;;+ *) fail "OpenCode at $opencode_path is not stable OpenCode 2. Correct PATH, then rerun the installer." ;;+ esac+ if [ -n "$opencode_plugin" ]; then+ opencode_plugin=$(opencode_rtk_plugin) || return $?+ [ -n "$opencode_plugin" ] || return 0+ assert_no_opencode_processes_running+ opencode_backup=$(mktemp "$HOME/.config/opencode/rtk-v1-XXXXXX") || fail "Could not create an RTK plugin backup."+ if mv "$opencode_plugin" "$opencode_backup"; then+ printf 'OpenCode 2 RTK support is unavailable; the old plugin was saved at %s.\n' "$opencode_backup"+ else+ rm -f "$opencode_backup"+ fail "Could not disable the old RTK plugin at $opencode_plugin."+ fi+ fi}ensure_cline() {@@ -1313,6 +1407,8 @@ PLISTparse_args "$@"validate_args+# Preserve the user's winning command before adding installer search paths.+original_opencode_path=$(command -v opencode || true)add_known_bin_directoriesif command -v cline >/dev/null 2>&1 || command -v npm >/dev/null 2>&1; theninstall_cline=1diff --git a/smoke/capabilities.py b/smoke/capabilities.pyindex 09c1ecf7..4b47f1ee 100644--- a/smoke/capabilities.py+++ b/smoke/capabilities.py@@ -588,7 +588,7 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = ("opencode_cli_integration","opencode_cli_integration","free_claude_code.cli.launchers.opencode",- "OpenCode V1 binary, live FCC model catalog, and child-process config",+ "OpenCode 2 binary, live FCC model catalog, and child-process config","Responses provider scoped to FCC with bearer authentication","version, proxy, config conflict, or catalog failure exits without fallback",(diff --git a/smoke/features.py b/smoke/features.pyindex c94e083b..78c8f7c2 100644--- a/smoke/features.py+++ b/smoke/features.py@@ -144,7 +144,7 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (("test_opencode_cli_prompt_e2e",),("clients",),(- "stable OpenCode V1 CLI",+ "stable OpenCode 2 CLI","configured provider credentials or local provider endpoint",),"skip only when OpenCode is absent; configured providers must pass",diff --git a/smoke/product/test_client_product_live.py b/smoke/product/test_client_product_live.pyindex 9accae20..7b730923 100644--- a/smoke/product/test_client_product_live.py+++ b/smoke/product/test_client_product_live.py@@ -15,8 +15,10 @@ from pathlib import Pathimport httpximport pytest+from free_claude_code.config.paths import managed_env_pathfrom free_claude_code.config.provider_catalog import PROVIDER_CATALOGfrom free_claude_code.core.json_types import JsonObject, JsonValue+from smoke.lib.child_process import cmd_python_cfrom smoke.lib.claude_cli_matrix import run_claude_clifrom smoke.lib.config import SmokeConfigfrom smoke.lib.e2e import (@@ -144,20 +146,30 @@ def test_pi_cli_prompt_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> None:def test_opencode_cli_prompt_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> None:if not shutil.which("opencode"):pytest.skip("missing_env: OpenCode CLI not found")- uv_bin = shutil.which("uv")- if not uv_bin:- pytest.skip("missing_env: uv not found")provider_model = ProviderMatrixDriver(smoke_config).first_model()auth_token = smoke_config.settings.proxy_auth_tokenisolated_home = tmp_path / "opencode-home"isolated_config = tmp_path / "opencode-config"for path in (isolated_home, isolated_config):path.mkdir()+ isolated_fcc = isolated_home / ".fcc"+ isolated_fcc.mkdir(mode=0o700)+ shutil.copyfile(managed_env_path(), isolated_fcc / ".env")+ isolated_env = {+ "HOME": str(isolated_home),+ "USERPROFILE": str(isolated_home),+ "XDG_CONFIG_HOME": str(isolated_home / "config"),+ "XDG_DATA_HOME": str(isolated_home / "data"),+ "XDG_CACHE_HOME": str(isolated_home / "cache"),+ "XDG_STATE_HOME": str(isolated_home / "state"),+ "OPENCODE_CONFIG_DIR": str(isolated_config),+ }with SmokeServerDriver(smoke_config,name="product-opencode-cli",env_overrides={+ **isolated_env,"MODEL": provider_model.full_model,"ANTHROPIC_AUTH_TOKEN": auth_token,"MESSAGING_PLATFORM": "none",@@ -170,45 +182,70 @@ def test_opencode_cli_prompt_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> N"PORT": str(server.port),"FCC_OPEN_BROWSER": "0","ANTHROPIC_AUTH_TOKEN": auth_token,- "HOME": str(isolated_home),- "USERPROFILE": str(isolated_home),- "XDG_CONFIG_HOME": str(isolated_home / "config"),- "XDG_DATA_HOME": str(isolated_home / "data"),- "XDG_CACHE_HOME": str(isolated_home / "cache"),- "XDG_STATE_HOME": str(isolated_home / "state"),- "OPENCODE_CONFIG_DIR": str(isolated_config),+ **isolated_env,})env.pop("OPENCODE_CONFIG", None)env.pop("OPENCODE_CONFIG_CONTENT", None)- result = subprocess.run(- [- uv_bin,- "run",- "--project",- str(smoke_config.root),- "--no-sync",- "fcc-opencode",- "run",- "--format",- "json",- "--model",- f"free-claude-code/{provider_model.full_model}",- "Reply with exactly FCC_SMOKE_OPENCODE",- ],- cwd=tmp_path,- env=env,- check=False,- capture_output=True,- text=True,- timeout=smoke_config.timeout_s + 15,+ command = cmd_python_c(+ "from free_claude_code.cli.launchers.opencode import launch; launch()"+ )++ def run(*args: str) -> str:+ process = _start_attached_process([*command, *args], cwd=tmp_path, env=env)+ try:+ stdout, stderr = process.communicate(+ timeout=smoke_config.timeout_s + 15+ )+ assert process.returncode == 0, stderr or stdout+ assert stdout.strip(), stderr or "OpenCode returned no output"+ return stdout+ finally:+ _stop_attached_process(process)++ marker = f"FCC_SMOKE_OPENCODE_{uuid.uuid4().hex}"+ (tmp_path / "fcc-smoke-marker.txt").write_text(marker, encoding="utf-8")+ output = run(+ "run",+ "--format",+ "json",+ "--model",+ f"free-claude-code/{provider_model.full_model}",+ "--auto",+ "Use the file-reading tool to read fcc-smoke-marker.txt. "+ "Reply with exactly its contents. Do not modify any files.",+ )+ events = _json_object_lines(output)+ assert any(+ event.get("type") == "text"+ and isinstance(part := event.get("part"), dict)+ and marker in str(part.get("text", ""))+ for event in events+ ), output+ assert any(+ event.get("type") == "tool_use"+ and isinstance(part := event.get("part"), dict)+ and isinstance(state := part.get("state"), dict)+ and state.get("status") == "completed"+ and marker in str(state.get("output", ""))+ for event in events+ ), output+ session_id = events[0]["sessionID"]+ assert isinstance(session_id, str) and session_id+ resumed = run(+ "run",+ "--format",+ "json",+ "--session",+ session_id,+ "Reply with that marker again from our conversation. Do not use tools.",)+ assert marker in resumedserver_log = server.log_path.read_text(encoding="utf-8", errors="replace")- assert result.returncode == 0, result.stderr or result.stdout- assert "FCC_SMOKE_OPENCODE" in result.stdoutassert "POST /v1/responses" in server_logassert "POST /v1/chat/completions" not in server_log+ assert not list((isolated_fcc / "tmp" / "launchers").iterdir())@pytest.mark.smoke_target("clients")diff --git a/src/free_claude_code/cli/launchers/opencode.py b/src/free_claude_code/cli/launchers/opencode.pyindex e0f49bbb..5986d696 100644--- a/src/free_claude_code/cli/launchers/opencode.py+++ b/src/free_claude_code/cli/launchers/opencode.py@@ -12,20 +12,32 @@ from free_claude_code.harnesses.launch import NativeCheck, PreparedLaunchfrom free_claude_code.harnesses.resources import LaunchResourcesfrom .opencode_config import OPENCODE_API_KEY_ENV, build_opencode_config-from .runner import HarnessSpec, LaunchContext, launch_harness, version_at_least+from .runner import HarnessSpec, LaunchContext, launch_harness_VERSION_PATTERN = re.compile(- r"(?m)^\s*(?:(?:opencode(?:\s+version)?\s+)|v)?"- r"(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?\s*$"+ r"(?m)^\s*(?:opencode(?:\s+version)?\s+)?v?"+ r"2\.\d+\.\d+(?:\+[0-9A-Za-z.-]+)?\s*$")_PROCESS_CONFIG_KEYS = ("OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT")+def _standalone_args(args: list[str]) -> list[str]:+ end = args.index("--") if "--" in args else len(args)+ if any(+ arg.partition("=")[0] in {"--standalone", "--no-standalone"}+ for arg in args[:end]+ ):+ raise ValueError("FCC manages OpenCode standalone mode; omit that option.")+ # OpenCode's flag belongs to the leaf command, before literal positionals.+ return [*args[:end], "--standalone", *args[end:]]++def _configure(ctx: LaunchContext, args: list[str], files: LaunchResources) -> PreparedLaunch:catalog = ctx.require_catalog()require_unset_environment(ctx.base_env, _PROCESS_CONFIG_KEYS)+ args = _standalone_args(args)config = build_opencode_config(catalog.models,default_model_id=catalog.default_model_id,@@ -53,13 +65,16 @@ def _configure(SPEC = HarnessSpec(binary_name="opencode",display_name="OpenCode CLI",- install_hint="Install OpenCode from: https://opencode.ai/docs/",+ install_hint=(+ "Install or upgrade by rerunning FCC's installer with OpenCode selected. "+ "For external installations: https://opencode.ai/v2/docs/migrate-v1/"+ ),configure=_configure,catalog_view="responses",compatibility_check=NativeCheck(("--version",),- lambda output: version_at_least(output, _VERSION_PATTERN, (1, 18, 18)),- "FCC requires OpenCode 1.18.18 or newer.",+ lambda output: _VERSION_PATTERN.search(output) is not None,+ "FCC requires stable OpenCode 2.",),)diff --git a/src/free_claude_code/cli/launchers/opencode_config.py b/src/free_claude_code/cli/launchers/opencode_config.pyindex d041f609..fc79874d 100644--- a/src/free_claude_code/cli/launchers/opencode_config.py+++ b/src/free_claude_code/cli/launchers/opencode_config.py@@ -1,4 +1,4 @@-"""Process-local OpenCode v1 configuration for FCC model routing."""+"""Process-local OpenCode v2 configuration for FCC model routing."""from dataclasses import dataclass@@ -22,7 +22,7 @@ class OpenCodeConfig:def build_opencode_config(models: tuple[CatalogModel, ...], *, default_model_id: str, proxy_root_url: str) -> OpenCodeConfig:- """Translate a non-empty FCC model snapshot into OpenCode v1 config."""+ """Translate a non-empty FCC model snapshot into OpenCode v2 config."""if not models:raise ValueError("OpenCode requires at least one routable FCC model")@@ -32,17 +32,30 @@ def build_opencode_config(}provider_config: JsonObject = {"name": "Free Claude Code",- "npm": "@ai-sdk/openai",- "options": {+ "package": "@opencode/ai/providers/openai/responses",+ "settings": {"baseURL": proxy_v1_url(proxy_root_url),"apiKey": f"{{env:{OPENCODE_API_KEY_ENV}}}",},}default_model = f"{OPENCODE_PROVIDER_ID}/{default_model_id}"+ # OpenCode's buffer is global, so it must also fit the smallest selectable+ # model. Leave its native 20K default alone when every known window fits it.+ buffer = min(+ (+ model.context_window_tokens // 4+ for model in models+ if model.context_window_tokens is not None+ ),+ default=20000,+ )+ compaction: JsonObject = (+ {"compaction": {"buffer": buffer}} if buffer < 20000 else {}+ )return OpenCodeConfig(file={- "provider": {+ "providers": {OPENCODE_PROVIDER_ID: {**provider_config,"models": model_config,@@ -50,38 +63,45 @@ def build_opencode_config(}},overlay={- "provider": {OPENCODE_PROVIDER_ID: provider_config},- "enabled_providers": [OPENCODE_PROVIDER_ID],- "disabled_providers": [],+ **compaction,+ "providers": {OPENCODE_PROVIDER_ID: provider_config},+ "experimental": {+ "policies": [+ {"action": "provider.use", "resource": "*", "effect": "deny"},+ {+ "action": "provider.use",+ "resource": OPENCODE_PROVIDER_ID,+ "effect": "allow",+ },+ ]+ },"model": default_model,- "small_model": default_model,+ "agents": {"title": {"model": default_model}},},)def _model_config(model: CatalogModel) -> JsonObject:- config: JsonObject = {- "name": model.display_name,- "reasoning": model.supports_reasoning is not False,- }+ config: JsonObject = {"name": model.display_name}if model.input_modalities is not None:- config["modalities"] = {+ config["capabilities"] = {+ "tools": True,"input": [modality.valuefor modality in ModelInputModalityif modality in model.input_modalities- ]- }- if model.context_window_tokens is not None or model.max_output_tokens is not None:- # OpenCode requires both fields and uses zero when either limit is unknown.- config["limit"] = {- "context": (- model.context_window_tokens- if model.context_window_tokens is not None- else 0- ),- "output": (- model.max_output_tokens if model.max_output_tokens is not None else 0- ),+ ],+ "output": ["text"],}+ limits: JsonObject = {}+ if model.context_window_tokens is not None:+ limits["context"] = model.context_window_tokens+ if model.max_output_tokens is not None:+ limits["output"] = model.max_output_tokens+ elif model.context_window_tokens is not None:+ # An omitted output limit inherits 32K in OpenCode, which can consume+ # the entire known window. This fallback is an OpenCode runtime budget.+ limits["output"] = max(1, min(4096, model.context_window_tokens // 4))+ if limits:+ config["limit"] = limitsreturn configdiff --git a/tests/api/test_opencode_session_headers.py b/tests/api/test_opencode_session_headers.pyindex 1e3b6c8c..8daa2018 100644--- a/tests/api/test_opencode_session_headers.py+++ b/tests/api/test_opencode_session_headers.py@@ -21,7 +21,7 @@ from tests.providers.test_opencode import (pytestmark = pytest.mark.asyncio-OPENCODE_USER_AGENT = "opencode/1.18.25 ai-sdk/provider-utils/4.0.38 runtime/bun/1.3.14"+OPENCODE_USER_AGENT = "opencode/latest/2.0.10/cli"def successful_response(request):diff --git a/tests/cli/conftest.py b/tests/cli/conftest.pyindex 09fb8349..0fd20ba2 100644--- a/tests/cli/conftest.py+++ b/tests/cli/conftest.py@@ -47,7 +47,7 @@ class LaunchCapture:versions: dict[str, str] = field(default_factory=lambda: {"pi": "0.80.4",- "opencode": "1.18.18",+ "opencode": "opencode v2.0.10","cline": "3.0.55","hermes": "Hermes Agent 0.20.4","dsh": "0.1.0-rc.8",diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex 08549c68..5c4ede28 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -283,7 +283,7 @@ def test_load_server_settings_leaves_process_owned_invalid_proxy_explicit(def test_serve_supervisor_restarts_when_app_requests_restart() -> None:from free_claude_code.cli import commands- settings = _launcher_settings()+ settings = _launcher_settings(port=0)get_settings = MagicMock(side_effect=[settings, settings])servers: list[object] = []restart_callbacks: list[Callable[[], None]] = []@@ -346,7 +346,7 @@ def test_serve_supervisor_restarts_when_app_requests_restart() -> None:def test_serve_supervisor_refuses_restart_after_incomplete_shutdown() -> None:from free_claude_code.cli import commands- settings = _launcher_settings()+ settings = _launcher_settings(port=0)get_settings = MagicMock(return_value=settings)servers: list[object] = []restart_callbacks: list[Callable[[], None]] = []diff --git a/tests/cli/test_launcher_checks.py b/tests/cli/test_launcher_checks.pyindex 9f76f7b9..835e52f4 100644--- a/tests/cli/test_launcher_checks.py+++ b/tests/cli/test_launcher_checks.py@@ -15,10 +15,18 @@ from tests.cli.test_launcher_workflow import HARNESSES, launch@pytest.mark.parametrize(("name", "output", "compatible"),[- ("opencode", "1.18.18", True),- ("opencode", "opencode version 1.19.0+build", True),+ ("opencode", "opencode v2.0.9", True),+ ("opencode", "opencode version v2.0.10+build", True),+ ("opencode", "opencode version 2.0.10", True),+ ("opencode", "v2.0.10", True),+ ("opencode", "2.0.10", True),+ ("opencode", "1.18.18", False),+ ("opencode", "opencode version 1.19.0+build", False),("opencode", "1.18.17", False),("opencode", "1.18.18-beta.1", False),+ ("opencode", "opencode v2.0.10-beta.1", False),+ ("opencode", "opencode v3.0.0", False),+ ("opencode", "opaque upstream version output", False),("cline", "cline 3.0.55", True),("cline", "v3.1.0", True),("cline", "3.0.54", False),diff --git a/tests/cli/test_launcher_workflow.py b/tests/cli/test_launcher_workflow.pyindex 05e0021a..8127903f 100644--- a/tests/cli/test_launcher_workflow.py+++ b/tests/cli/test_launcher_workflow.py@@ -78,7 +78,7 @@ def test_launch_default_is_server_selection_not_first_row_or_local_settings(config = json.loads(env["OPENCODE_CONFIG_CONTENT"])assert (config["model"]- == config["small_model"]+ == config["agents"]["title"]["model"]== f"free-claude-code/{selected}")elif name == "cline":@@ -109,7 +109,10 @@ def test_help_receives_normal_fcc_setup() -> None:launch(name, ["--help"])assert launch_capture.requests[0].full_url == "http://127.0.0.1:8182/health"- assert launch_capture.commands[0][-1] == "--help"+ if name == "opencode":+ assert launch_capture.commands[0][-2:] == ["--help", "--standalone"]+ else:+ assert launch_capture.commands[0][-1] == "--help"if name in {"claude", "pi"}:assert len(launch_capture.requests) == 1else:@@ -145,7 +148,10 @@ def test_native_inputs_are_forwarded_without_fcc_model_or_command_policy("literal text",]launch(name, args)- assert launch_capture.commands[0][-len(args) :] == args+ command = launch_capture.commands[0]+ if name == "opencode":+ command = [arg for arg in command if arg != "--standalone"]+ assert command[-len(args) :] == args@pytest.mark.parametrize(diff --git a/tests/cli/test_opencode_launcher.py b/tests/cli/test_opencode_launcher.pyindex 4a6377e5..5be7706f 100644--- a/tests/cli/test_opencode_launcher.py+++ b/tests/cli/test_opencode_launcher.py@@ -10,7 +10,7 @@ from free_claude_code.cli.launchers.opencode_config import build_opencode_configfrom free_claude_code.core.model_capabilities import ModelInputModality-def test_opencode_config_uses_responses_sdk_and_only_known_metadata() -> None:+def test_opencode_config_uses_native_responses_and_model_budgets() -> None:config = build_opencode_config((CatalogModel(@@ -50,59 +50,114 @@ def test_opencode_config_uses_responses_sdk_and_only_known_metadata() -> None:proxy_root_url="http://127.0.0.1:9191",)- provider = config.file["provider"]+ provider = config.file["providers"]assert isinstance(provider, dict)fcc = provider["free-claude-code"]assert isinstance(fcc, dict)- assert fcc["npm"] == "@ai-sdk/openai"- assert fcc["options"] == {+ assert fcc["package"] == "@opencode/ai/providers/openai/responses"+ assert fcc["settings"] == {"baseURL": "http://127.0.0.1:9191/v1","apiKey": "{env:FCC_OPENCODE_API_KEY}",}assert fcc["models"] == {"nvidia_nim/vendor/model": {"name": "Nested model",- "reasoning": True,- "modalities": {"input": ["text", "image"]},+ "capabilities": {+ "tools": True,+ "input": ["text", "image"],+ "output": ["text"],+ },"limit": {"context": 131072, "output": 8192},},"claude-3-freecc-no-thinking/open_router/plain-model": {"name": "No-thinking model",- "reasoning": False,- "modalities": {"input": ["text"]},- "limit": {"context": 65536, "output": 0},+ "capabilities": {"tools": True, "input": ["text"], "output": ["text"]},+ "limit": {"context": 65536, "output": 4096},},"future_provider/unknown-model": {"name": "Unknown model",- "reasoning": True,},"future_provider/output-only": {"name": "Output-only model",- "reasoning": True,- "limit": {"context": 0, "output": 4096},+ "limit": {"output": 4096},},}assert config.overlay == {- "provider": {+ "compaction": {"buffer": 16384},+ "providers": {"free-claude-code": {"name": "Free Claude Code",- "npm": "@ai-sdk/openai",- "options": {+ "package": "@opencode/ai/providers/openai/responses",+ "settings": {"baseURL": "http://127.0.0.1:9191/v1","apiKey": "{env:FCC_OPENCODE_API_KEY}",},}},- "enabled_providers": ["free-claude-code"],- "disabled_providers": [],+ "experimental": {+ "policies": [+ {"action": "provider.use", "resource": "*", "effect": "deny"},+ {+ "action": "provider.use",+ "resource": "free-claude-code",+ "effect": "allow",+ },+ ]+ },"model": "free-claude-code/nvidia_nim/vendor/model",- "small_model": "free-claude-code/nvidia_nim/vendor/model",+ "agents": {"title": {"model": "free-claude-code/nvidia_nim/vendor/model"}},}serialized = json.dumps(config.file | config.overlay)assert "proxy-token" not in serializedassert "attachment" not in serialized+ ("context", "output", "expected_limits", "expected_buffer"),+ [+ (32768, None, {"context": 32768, "output": 4096}, 8192),+ (8192, None, {"context": 8192, "output": 2048}, 2048),+ (16384, 1024, {"context": 16384, "output": 1024}, 4096),+ (131072, 65536, {"context": 131072, "output": 65536}, None),+ (200000, None, {"context": 200000, "output": 4096}, None),+ (None, 4096, {"output": 4096}, None),+ (None, None, None, None),+ ],+)+def test_opencode_context_reserves_fit_small_models(+ context: int | None,+ output: int | None,+ expected_limits: dict[str, int] | None,+ expected_buffer: int | None,+) -> None:+ config = build_opencode_config(+ (+ CatalogModel(+ wire_slug="test/model",+ provider_model_ref="test/model",+ display_name="Test model",+ supports_reasoning=None,+ context_window_tokens=context,+ max_output_tokens=output,+ ),+ ),+ default_model_id="test/model",+ proxy_root_url="http://127.0.0.1:8182",+ )+ provider = config.file["providers"]+ assert isinstance(provider, dict)+ fcc = provider["free-claude-code"]+ assert isinstance(fcc, dict)+ models = fcc["models"]+ assert isinstance(models, dict)+ model = models["test/model"]+ assert isinstance(model, dict)+ assert model.get("limit") == expected_limits+ assert config.overlay.get("compaction") == (+ {"buffer": expected_buffer} if expected_buffer is not None else None+ )++def test_opencode_config_rejects_empty_model_catalog() -> None:with pytest.raises(ValueError, match="at least one"):build_opencode_config(@@ -118,10 +173,10 @@ def test_opencode_child_receives_private_catalog_and_overlay(launch_capture) ->def inspect(command, env):config = json.loads(Path(env["OPENCODE_CONFIG"]).read_text())overlay = json.loads(env["OPENCODE_CONFIG_CONTENT"])- provider = config["provider"]["free-claude-code"]- assert provider["options"]["baseURL"] == "http://127.0.0.1:8182/v1"+ provider = config["providers"]["free-claude-code"]+ assert provider["settings"]["baseURL"] == "http://127.0.0.1:8182/v1"assert "nvidia_nim/catalog-model:variant" in provider["models"]- assert overlay["enabled_providers"] == ["free-claude-code"]+ assert overlay["experimental"]["policies"][-1]["resource"] == "free-claude-code"assert env["FCC_OPENCODE_API_KEY"] == "launcher-test-token"launch_capture.on_start = inspect@@ -137,3 +192,45 @@ def test_existing_opencode_process_configuration_is_not_replaced(monkeypatch.setenv(key, "user-owned-config")launch("opencode", [], exit_code=1)assert not launch_capture.commands+++ "args, expected",+ [+ ([], ["--standalone"]),+ (["run", "hello"], ["run", "hello", "--standalone"]),+ (["models"], ["models", "--standalone"]),+ (["session", "list"], ["session", "list", "--standalone"]),+ (+ ["run", "--", "--standalone=false"],+ ["run", "--standalone", "--", "--standalone=false"],+ ),+ ],+)+def test_opencode_owns_a_private_server_without_rewriting_positionals(+ args, expected, launch_capture+) -> None:+ from tests.cli.test_launcher_workflow import launch++ launch("opencode", args)+ assert launch_capture.commands[0][1:] == expected+++ "option",+ [+ "--standalone",+ "--no-standalone",+ "--standalone=false",+ "--standalone=0",+ "--no-standalone=false",+ ],+)+def test_opencode_rejects_caller_control_of_server_lifetime(+ option, launch_capture, capsys+) -> None:+ from tests.cli.test_launcher_workflow import launch++ launch("opencode", ["run", option, "false", "hello"], exit_code=1)+ assert not launch_capture.commands+ assert "FCC manages OpenCode standalone mode" in capsys.readouterr().errdiff --git a/tests/scripts/fixtures/.gitattributes b/tests/scripts/fixtures/.gitattributesnew file mode 100644index 00000000..960bf11f--- /dev/null+++ b/tests/scripts/fixtures/.gitattributes@@ -0,0 +1 @@+rtk-opencode-v1.ts -textdiff --git a/tests/scripts/fixtures/README.md b/tests/scripts/fixtures/README.mdnew file mode 100644index 00000000..d4716258--- /dev/null+++ b/tests/scripts/fixtures/README.md@@ -0,0 +1,6 @@+`rtk-opencode-v1.ts` is the unchanged RTK 0.44.2 OpenCode plugin template from+[rtk-ai/rtk](https://github.com/rtk-ai/rtk/blob/v0.44.2/hooks/opencode/rtk.ts).+It is covered by the accompanying [Apache 2.0 license](rtk-LICENSE).++The fixture preserves the exact bytes emitted by RTK so installer tests verify+that only the recognized generated plugin is disabled. Keep its LF line endings.diff --git a/tests/scripts/fixtures/rtk-LICENSE b/tests/scripts/fixtures/rtk-LICENSEnew file mode 100644index 00000000..0afaf4b9--- /dev/null+++ b/tests/scripts/fixtures/rtk-LICENSE@@ -0,0 +1,190 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ Copyright 2024 rtk-ai and rtk-ai Labs++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/tests/scripts/fixtures/rtk-opencode-v1.ts b/tests/scripts/fixtures/rtk-opencode-v1.tsnew file mode 100644index 00000000..c4450cfa--- /dev/null+++ b/tests/scripts/fixtures/rtk-opencode-v1.ts@@ -0,0 +1,39 @@+import type { Plugin } from "@opencode-ai/plugin"++// RTK OpenCode plugin — rewrites commands to use rtk for token savings.+// Requires: rtk >= 0.23.0 in PATH.+//+// This is a thin delegating plugin: all rewrite logic lives in `rtk rewrite`,+// which is the single source of truth (src/discover/registry.rs).+// To add or change rewrite rules, edit the Rust registry — not this file.++export const RtkOpenCodePlugin: Plugin = async ({ $ }) => {+ try {+ await $`which rtk`.quiet()+ } catch {+ console.warn("[rtk] rtk binary not found in PATH — plugin disabled")+ return {}+ }++ return {+ "tool.execute.before": async (input, output) => {+ const tool = String(input?.tool ?? "").toLowerCase()+ if (tool !== "bash" && tool !== "shell") return+ const args = output?.args+ if (!args || typeof args !== "object") return++ const command = (args as Record<string, unknown>).command+ if (typeof command !== "string" || !command) return++ try {+ const result = await $`rtk rewrite ${command}`.quiet().nothrow()+ const rewritten = String(result.stdout).trim()+ if (rewritten && rewritten !== command) {+ ;(args as Record<string, unknown>).command = rewritten+ }+ } catch {+ // rtk rewrite failed — pass through unchanged+ }+ },+ }+}diff --git a/tests/scripts/test_installers.py b/tests/scripts/test_installers.pyindex cd2c2919..80ba5bb9 100644--- a/tests/scripts/test_installers.py+++ b/tests/scripts/test_installers.py@@ -60,7 +60,7 @@ def _braced_body(text: str, declaration: str) -> str:def _posix_command(name: str, *, version_output: str | None = None) -> str:version = {- "opencode": "1.18.18",+ "opencode": "v2.0.10","cline": "3.0.55","hermes": "0.20.4","dsh": "0.1.0-rc.8",@@ -88,6 +88,13 @@ fi''')return f"""#!/bin/shecho "{name}:$*" >> "$CALL_LOG"+if [ "{name}" = "opencode" ] && [ "${{FCC_RUNNING_PHASE:-}}" = "opencode-plugin" ]; then+ if [ -e "$FCC_PROCESS_MARKER.probed" ]; then+ : > "$FCC_PROCESS_MARKER"+ else+ : > "$FCC_PROCESS_MARKER.probed"+ fi+fiif [ "$FAIL_STEP" = "{name}-verify" ]; thenexit 31fi@@ -329,11 +336,11 @@ def posix_harness(tmp_path: Path) -> PosixHarness:bin_dir / "pgrep","""#!/bin/sh[ -n "${FCC_RUNNING_COMMAND:-}" ] || exit 1-if [ "${FCC_RUNNING_PHASE:-early}" = "late" ] && [ ! -e "$FCC_PROCESS_MARKER" ]; then+if [ "${FCC_RUNNING_PHASE:-early}" != "early" ] && [ ! -e "$FCC_PROCESS_MARKER" ]; thenexit 1ficase "$*" in- *"$FCC_RUNNING_COMMAND"*) printf '4242\n'; exit 0 ;;+ "-x $FCC_RUNNING_COMMAND"|"-f (^|/)$FCC_RUNNING_COMMAND([[:space:]]|$)") printf '4242\n'; exit 0 ;;*) exit 1 ;;esac""",@@ -372,7 +379,12 @@ case "$url" in*claude.ai*) source="$FAKE_FIXTURES/claude-installer.sh" ;;*chatgpt.com*) source="$FAKE_FIXTURES/codex-installer.sh" ;;*pi.dev*) source="$FAKE_FIXTURES/pi-installer.sh" ;;- *opencode.ai*) source="$FAKE_FIXTURES/opencode-installer.sh" ;;+ *opencode.ai*)+ source="$FAKE_FIXTURES/opencode-installer.sh"+ if [ "${FCC_RUNNING_PHASE:-}" = "opencode-download" ]; then+ : > "$FCC_PROCESS_MARKER"+ fi+ ;;*hermes-agent.nousresearch.com*) source="$FAKE_FIXTURES/hermes-installer.sh" ;;*x.ai*) source="$FAKE_FIXTURES/grok-installer.sh" ;;*dev.meta.ai*) source="$FAKE_FIXTURES/muse-installer.sh" ;;@@ -432,6 +444,9 @@ echo "opencode-install" >> "$CALL_LOG"[ "$FAIL_STEP" = "opencode-install" ] && exit 25mkdir -p "$HOME/.opencode/bin"cp "$FAKE_FIXTURES/opencode-command.sh" "$HOME/.opencode/bin/opencode"+if [ -n "${VERSION:-}" ]; then+ printf '#!/bin/sh\necho "opencode v%s"\n' "$VERSION" > "$HOME/.opencode/bin/opencode"+fichmod +x "$HOME/.opencode/bin/opencode"""",)@@ -557,6 +572,9 @@ esacbin_dir / "sha256sum","""#!/bin/shecho "sha256sum:$*" >> "$CALL_LOG"+case "$1" in+ */rtk.ts) exec /usr/bin/shasum -a 256 "$1" ;;+esacif [ "$FAIL_STEP" = "rtk-checksum" ]; thenchecksum="0000000000000000000000000000000000000000000000000000000000000000"else@@ -705,7 +723,6 @@ def test_install_sh_rejects_unsupported_hermes_platform_before_download(@pytest.mark.parametrize(("client", "install_call"),[- ("opencode", "opencode-install"),("cline", "npm:install -g cline"),("hermes", "hermes-install:--non-interactive --skip-setup"),("grok", "grok-install"),@@ -966,10 +983,9 @@ def test_install_sh_installs_and_configures_rtk_for_selected_agents("rtk:init --global --auto-patch:telemetry=1","rtk:init --global --codex:telemetry=1","rtk:init --global --agent pi:telemetry=1",- "rtk:init --global --opencode:telemetry=1",]assert calls.index("uv:--version") < calls.index(- "rtk:init --global --opencode:telemetry=1"+ "rtk:init --global --agent pi:telemetry=1")assert (Path(posix_harness.env["HOME"]) / ".claude").is_dir()@@ -1740,7 +1756,7 @@ def _windows_shortcut_icon(def _batch_client(name: str, *, version_output: str | None = None) -> str:version = {- "opencode": "1.18.18",+ "opencode": "v2.0.10","cline": "3.0.55","hermes": "0.20.4","dsh": "0.1.0-rc.8",@@ -1778,6 +1794,13 @@ def _batch_client(name: str, *, version_output: str | None = None) -> str:)return f"""@echo offecho {name}:%*>>"%CALL_LOG%"+if "{name}"=="opencode" if "%FCC_RUNNING_PHASE%"=="opencode-plugin" (+ if exist "%FCC_PROCESS_MARKER%.probed" (+ type nul > "%FCC_PROCESS_MARKER%"+ ) else (+ type nul > "%FCC_PROCESS_MARKER%.probed"+ )+)if "%FAIL_STEP%"=="{name}-verify" exit /b 51{version_command}if "%1"=="--help" (@@ -2130,7 +2153,7 @@ function Invoke-RestMethod {($env:FAIL_STEP -eq "claude-download" -and $Uri.Contains("claude.ai")) -or($env:FAIL_STEP -eq "codex-download" -and $Uri.Contains("chatgpt.com")) -or($env:FAIL_STEP -eq "pi-download" -and $Uri.Contains("pi.dev")) -or- ($env:FAIL_STEP -eq "opencode-download" -and $Uri.Contains("anomalyco/opencode")) -or+ ($env:FAIL_STEP -eq "opencode-download" -and $Uri.Contains("opencode.ai/files/bin/")) -or($env:FAIL_STEP -eq "hermes-download" -and $Uri.Contains("hermes-agent.nousresearch.com")) -or($env:FAIL_STEP -eq "grok-download" -and $Uri.Contains("x.ai/cli")) -or($env:FAIL_STEP -eq "muse-download" -and $Uri.Contains("scripts/install-muse.ps1")) -or@@ -2139,6 +2162,9 @@ function Invoke-RestMethod {) {throw "simulated download failure"}+ if ($Uri.Contains("opencode.ai/update/api/latest/cli/npm")) {+ return @{ version = $(if ($env:FAKE_OPENCODE_RELEASE) { $env:FAKE_OPENCODE_RELEASE } else { "2.0.10" }) }+ }if ($Uri.Contains("claude.ai")) {$source = Join-Path $env:FAKE_FIXTURES "claude-installer.ps1"}@@ -2174,6 +2200,9 @@ function Invoke-RestMethod {throw "unexpected installer URL: $Uri"}Copy-Item -LiteralPath $source -Destination $OutFile -Force+ if ($env:FCC_RUNNING_PHASE -eq "opencode-download" -and $Uri.Contains("opencode.ai/files/bin/")) {+ New-Item -ItemType File -Path $env:FCC_PROCESS_MARKER -Force | Out-Null+ }}function Get-Process {[CmdletBinding()]@@ -2183,7 +2212,7 @@ function Get-Process {return}if (- $env:FCC_RUNNING_PHASE -eq "late" -and+ $env:FCC_RUNNING_PHASE -ne "early" -and-not (Test-Path -LiteralPath $env:FCC_PROCESS_MARKER)) {return@@ -2195,10 +2224,21 @@ function Get-Process {}}$installerSource = [IO.File]::ReadAllText($env:FCC_INSTALLER)-$nativeVersionProbe = ' $output = Invoke-Utf8NativeCapture -FilePath $OpenCodePath -Arguments @("--version")'+$nativeVersionProbe = ' $output = Read-OpenCodeVersionOutput $OpenCodePath'$fakeArchiveVersionProbe = @'- $output = if ([IO.Path]::GetFileName($OpenCodePath) -eq "opencode.exe") {- "opencode 1.18.18"+ $output = if ([IO.Path]::GetExtension($OpenCodePath) -eq ".exe") {+ Add-Content -LiteralPath $env:CALL_LOG -Value "opencode:--version"+ if ($env:FCC_RUNNING_PHASE -eq "opencode-publish" -and [IO.File]::ReadAllText($OpenCodePath) -ne "old-opencode-v1") {+ New-Item -ItemType File -Path $env:FCC_PROCESS_MARKER -Force | Out-Null+ }+ if ($env:FAIL_STEP -eq "opencode-verify") { throw "simulated version failure" }+ if ([IO.File]::ReadAllText($OpenCodePath) -eq "old-opencode-v1") {+ "opencode v1.18.31"+ } elseif ($env:FAKE_OPENCODE_ARCHIVE_VERSION) {+ $env:FAKE_OPENCODE_ARCHIVE_VERSION+ } else {+ "opencode v2.0.10"+ }}else {Invoke-Utf8NativeCapture -FilePath $OpenCodePath -Arguments @("--version")@@ -2234,6 +2274,8 @@ $installer = [scriptblock]::Create($installerSource)"PROCESSOR_ARCHITECTURE": "AMD64","PROCESSOR_ARCHITEW6432": "","FAIL_STEP": "",+ "FAKE_OPENCODE_RELEASE": "",+ "FAKE_OPENCODE_ARCHIVE_VERSION": "",})env.pop("XDG_BIN_HOME", None)@@ -2260,7 +2302,10 @@ def test_install_ps1_fresh_install_is_verified(assert calls.index("claude-install") < calls.index("claude:--version")assert calls.index("codex-install:1") < calls.index("codex:--version")assert calls.index("pi-install") < calls.index("pi:--version")- assert any("anomalyco/opencode" in call for call in calls)+ assert (+ "download:https://opencode.ai/files/bin/2.0.10/opencode-windows-x64-baseline.zip"+ in calls+ )assert calls.index("npm:install -g cline") < calls.index("cline:--version")assert any("hermes-agent.nousresearch.com/install.ps1" in call for call in calls)assert "hermes-install:True:True" in calls@@ -2338,7 +2383,6 @@ def test_install_ps1_discovers_grok_in_custom_bin_directory(@pytest.mark.parametrize(("client", "install_call"),[- ("opencode", "anomalyco/opencode"),("cline", "npm:install -g cline"),("hermes", "hermes-install:True:True"),("grok", "grok-install"),@@ -2612,7 +2656,9 @@ def test_install_ps1_rejects_unsupported_opencode_architecture(assert result.returncode != 0assert "does not provide a supported Windows release" in result.stderr- assert not any("anomalyco/opencode" in call for call in powershell_harness.calls())+ assert not any(+ "opencode.ai/files/bin/" in call for call in powershell_harness.calls()+ )def test_install_ps1_preserves_existing_rtk_and_configures_selected_agents(@@ -2632,7 +2678,6 @@ def test_install_ps1_preserves_existing_rtk_and_configures_selected_agents("rtk:init --global --auto-patch:telemetry=1","rtk:init --global --codex:telemetry=1","rtk:init --global --agent pi:telemetry=1",- "rtk:init --global --opencode:telemetry=1",]assert (Path(powershell_harness.env["USERPROFILE"]) / ".claude").is_dir()@@ -3448,6 +3493,510 @@ Ensure-SelectedCodingAgentsassert "No selected coding agent was installed." in result.stderr+def _prepare_native_opencode_v1(harness: PosixHarness | PowerShellHarness) -> Path:+ windows = isinstance(harness, PowerShellHarness)+ home = Path(harness.env["USERPROFILE" if windows else "HOME"])+ (harness.bin_dir / ("opencode.cmd" if windows else "opencode")).unlink()+ binary = home / ".opencode" / "bin" / ("opencode.exe" if windows else "opencode")+ _write_executable(+ binary,+ "old-opencode-v1"+ if windows+ else _posix_command("opencode", version_output="opencode v1.18.31"),+ )+ return binary+++def _assert_native_opencode_migration(+ harness: PosixHarness | PowerShellHarness,+) -> None:+ binary = _prepare_native_opencode_v1(harness)+ original = binary.read_bytes()+ result = harness.run()+ assert result.returncode == 0, result.stderr+ assert binary.read_bytes() != original+ assert any(+ "opencode.ai/v2/install" in call or "opencode.ai/files/bin/2.0.10/" in call+ for call in harness.calls()+ )+ assert not any(+ "anomalyco/opencode" in call or "npm:uninstall" in call+ for call in harness.calls()+ )+ harness.log.unlink()+ result = harness.run()+ assert result.returncode == 0, result.stderr+ assert not any("opencode.ai" in call for call in harness.calls())+++def test_install_sh_opencode_v2_migrates_native_v1(posix_harness: PosixHarness) -> None:+ _assert_native_opencode_migration(posix_harness)+++def test_install_ps1_opencode_v2_migrates_native_v1(+ powershell_harness: PowerShellHarness,+) -> None:+ _assert_native_opencode_migration(powershell_harness)+++ "version",+ ["opencode v1.18.31", "opencode v2.0.10-beta", "opencode v3.0.0", "opaque output"],+)+def test_install_sh_opencode_rejects_external_incompatible_version(+ posix_harness: PosixHarness, version: str+) -> None:+ path = posix_harness.bin_dir / "opencode"+ _write_executable(path, _posix_command("opencode", version_output=version))+ original = path.read_bytes()+ result = posix_harness.run()+ assert result.returncode != 0+ assert str(path) in result.stderr+ assert path.read_bytes() == original+ assert not any("opencode-install" in call for call in posix_harness.calls())+++ "version",+ ["opencode v1.18.31", "opencode v2.0.10-beta", "opencode v3.0.0", "opaque output"],+)+def test_install_ps1_opencode_rejects_external_incompatible_version(+ powershell_harness: PowerShellHarness, version: str+) -> None:+ path = powershell_harness.bin_dir / "opencode.cmd"+ _write_executable(path, _batch_client("opencode", version_output=version))+ original = path.read_bytes()+ result = powershell_harness.run()+ assert result.returncode != 0+ assert str(path) in "".join(result.stderr.split())+ assert path.read_bytes() == original+ assert not any("opencode.ai" in call for call in powershell_harness.calls())+++def _assert_opencode_rtk_cleanup(+ harness: PosixHarness | PowerShellHarness, modified: bool+) -> None:+ native = _prepare_native_opencode_v1(harness) if modified else None+ original = native.read_bytes() if native else None+ windows = isinstance(harness, PowerShellHarness)+ home = Path(harness.env["USERPROFILE" if windows else "HOME"])+ config = home / ".config" / "opencode"+ plugin = config / "plugins" / "rtk.ts"+ plugin.parent.mkdir(parents=True)+ contents = (+ Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()+ )+ assert (+ hashlib.sha256(contents).hexdigest()+ == "6530c131946c84892f9522abd68d4e513e1e658d8ddbad1f59388c86ebbcb6bb"+ )+ if modified:+ contents += b"\n// user customization\n"+ plugin.write_bytes(contents)+ previous_backup = config / "rtk-v1-existing.bak"+ previous_backup.write_bytes(b"prior backup")+ database = home / ".local" / "share" / "opencode" / "opencode.db"+ database.parent.mkdir(parents=True)+ database.write_bytes(b"user-owned database sentinel")+ result = harness.run()+ assert database.read_bytes() == b"user-owned database sentinel"+ assert list(database.parent.iterdir()) == [database]+ assert previous_backup.read_bytes() == b"prior backup"+ if modified:+ assert result.returncode != 0+ assert "rtk.ts" in result.stderr+ assert plugin.read_bytes() == contents+ assert native is not None and native.read_bytes() == original+ assert not any("opencode.ai" in call for call in harness.calls())+ else:+ assert result.returncode == 0, result.stderr+ assert not plugin.exists()+ backups = [path for path in config.glob("rtk-v1-*") if path != previous_backup]+ assert len(backups) == 1+ assert backups[0].read_bytes() == contents+ assert str(backups[0]) in result.stdout+ assert not any("rtk:init --global --opencode" in call for call in harness.calls())++[email protected]("modified", [False, True])+def test_install_sh_opencode_rtk_cleanup_without_rtk_option(+ posix_harness: PosixHarness, modified: bool+) -> None:+ _assert_opencode_rtk_cleanup(posix_harness, modified)++[email protected]("modified", [False, True])+def test_install_ps1_opencode_rtk_cleanup_without_rtk_option(+ powershell_harness: PowerShellHarness, modified: bool+) -> None:+ _assert_opencode_rtk_cleanup(powershell_harness, modified)+++def _assert_opencode_linked_rtk_parent_is_preserved(+ harness: PosixHarness | PowerShellHarness, parent: str+) -> None:+ native = _prepare_native_opencode_v1(harness)+ original = native.read_bytes()+ home = native.parents[2]+ plugin = home / ".config/opencode/plugins/rtk.ts"+ plugin.parent.mkdir(parents=True)+ contents = (+ Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()+ )+ plugin.write_bytes(contents)+ linked = home / parent+ shared = harness.root / "shared-config"+ linked.rename(shared)+ if isinstance(harness, PowerShellHarness):+ subprocess.run(+ [+ harness.powershell,+ "-NoProfile",+ "-Command",+ "New-Item -ItemType Junction -Path $env:FCC_TEST_LINK -Target $env:FCC_TEST_TARGET -ErrorAction Stop | Out-Null",+ ],+ env=harness.env+ | {"FCC_TEST_LINK": str(linked), "FCC_TEST_TARGET": str(shared)},+ capture_output=True,+ text=True,+ check=True,+ )+ else:+ linked.symlink_to(shared, target_is_directory=True)+ try:+ result = harness.run()+ assert result.returncode != 0+ assert "manually" in result.stderr+ assert plugin.read_bytes() == contents+ assert not list((home / ".config/opencode").glob("rtk-v1-*"))+ assert native.read_bytes() == original+ assert not any("opencode.ai" in call for call in harness.calls())+ finally:+ if isinstance(harness, PowerShellHarness):+ linked.rmdir()+ else:+ linked.unlink()+++ "parent", [".config", ".config/opencode", ".config/opencode/plugins"]+)+def test_install_sh_opencode_linked_rtk_parent_is_preserved(+ posix_harness: PosixHarness, parent: str+) -> None:+ _assert_opencode_linked_rtk_parent_is_preserved(posix_harness, parent)+++ "parent", [".config", ".config/opencode", ".config/opencode/plugins"]+)+def test_install_ps1_opencode_linked_rtk_parent_is_preserved(+ powershell_harness: PowerShellHarness, parent: str+) -> None:+ _assert_opencode_linked_rtk_parent_is_preserved(powershell_harness, parent)+++def _assert_opencode_starting_late_blocks_mutation(+ harness: PosixHarness | PowerShellHarness, phase: str, command: str+) -> None:+ plugin_only = phase == "opencode-plugin"+ windows = isinstance(harness, PowerShellHarness)+ home = Path(harness.env["USERPROFILE" if windows else "HOME"])+ native = None if plugin_only else _prepare_native_opencode_v1(harness)+ original = native.read_bytes() if native else None+ plugin = home / ".config/opencode/plugins/rtk.ts"+ plugin.parent.mkdir(parents=True)+ contents = (+ Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()+ )+ plugin.write_bytes(contents)+ harness.env["FCC_RUNNING_COMMAND"] = command+ harness.env["FCC_RUNNING_PHASE"] = phase+ result = harness.run()+ assert Path(harness.env["FCC_PROCESS_MARKER"]).exists()+ assert result.returncode != 0+ assert "Close OpenCode" in result.stderr+ assert plugin.read_bytes() == contents+ assert not list(plugin.parents[1].glob("rtk-v1-*"))+ if native:+ assert native.read_bytes() == original+ assert not list(native.parent.glob(".opencode-*"))++[email protected]("phase", ["opencode-download", "opencode-plugin"])[email protected]("command", ["opencode", "opencode2"])+def test_install_sh_opencode_starting_late_blocks_mutation(+ posix_harness: PosixHarness, phase: str, command: str+) -> None:+ _assert_opencode_starting_late_blocks_mutation(posix_harness, phase, command)+++ "phase", ["opencode-download", "opencode-publish", "opencode-plugin"]+)[email protected]("command", ["opencode", "opencode2"])+def test_install_ps1_opencode_starting_late_blocks_mutation(+ powershell_harness: PowerShellHarness, phase: str, command: str+) -> None:+ _assert_opencode_starting_late_blocks_mutation(powershell_harness, phase, command)+++def test_install_sh_opencode_running_blocks_native_migration(+ posix_harness: PosixHarness,+) -> None:+ binary = _prepare_native_opencode_v1(posix_harness)+ original = binary.read_bytes()+ posix_harness.env["FCC_RUNNING_COMMAND"] = "opencode"+ result = posix_harness.run()+ assert result.returncode != 0+ assert "Close OpenCode" in result.stderr+ assert binary.read_bytes() == original+++def test_install_ps1_opencode_running_blocks_native_migration(+ powershell_harness: PowerShellHarness,+) -> None:+ binary = _prepare_native_opencode_v1(powershell_harness)+ original = binary.read_bytes()+ powershell_harness.env["FCC_RUNNING_COMMAND"] = "opencode"+ result = powershell_harness.run()+ assert result.returncode != 0+ assert "Close OpenCode" in result.stderr+ assert binary.read_bytes() == original+++def _assert_external_opencode_is_not_shadowed(+ harness: PosixHarness | PowerShellHarness,+) -> None:+ windows = isinstance(harness, PowerShellHarness)+ home = Path(harness.env["USERPROFILE" if windows else "HOME"])+ external = harness.bin_dir / ("opencode.cmd" if windows else "opencode")+ _write_executable(+ external,+ (_batch_client if windows else _posix_command)(+ "opencode", version_output="opencode v1.18.31"+ ),+ )+ native = home / ".opencode" / "bin" / ("opencode.exe" if windows else "opencode")+ _write_executable(native, "native-v2" if windows else _posix_command("opencode"))+ original = native.read_bytes()+ result = harness.run()+ assert result.returncode != 0+ assert str(external) in "".join(result.stderr.split())+ assert native.read_bytes() == original+ assert not any("opencode.ai" in call for call in harness.calls())+++def test_install_sh_opencode_does_not_shadow_external_v1(+ posix_harness: PosixHarness,+) -> None:+ _assert_external_opencode_is_not_shadowed(posix_harness)+++def test_install_ps1_opencode_does_not_shadow_external_v1(+ powershell_harness: PowerShellHarness,+) -> None:+ _assert_external_opencode_is_not_shadowed(powershell_harness)+++def _assert_opencode_validates_current_path(+ harness: PosixHarness | PowerShellHarness, native_version: str+) -> None:+ windows = isinstance(harness, PowerShellHarness)+ home = Path(harness.env["USERPROFILE" if windows else "HOME"])+ native = home / ".opencode/bin" / ("opencode.exe" if windows else "opencode")+ _write_executable(+ native,+ ("old-opencode-v1" if native_version.startswith("1.") else "native-v2")+ if windows+ else _posix_command("opencode", version_output=f"opencode v{native_version}"),+ )+ original = native.read_bytes()+ plugin = home / ".config/opencode/plugins/rtk.ts"+ plugin.parent.mkdir(parents=True)+ contents = (+ Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()+ )+ plugin.write_bytes(contents)++ # The external v2 wins initially; adding the native directory puts it first.+ result = harness.run()+ assert native.read_bytes() == original+ assert not any("opencode.ai" in call for call in harness.calls())+ if native_version.startswith("1."):+ assert result.returncode != 0+ assert str(native) in "".join(result.stderr.split())+ assert "Correct PATH" in result.stderr+ assert plugin.read_bytes() == contents+ assert not list(plugin.parents[1].glob("rtk-v1-*"))+ else:+ assert result.returncode == 0, result.stderr+ assert f"Verified OpenCode {native_version} at " in result.stdout+ assert str(native) in result.stdout++[email protected]("native_version", ["1.18.31", "2.0.10"])+def test_install_sh_opencode_validates_current_path(+ posix_harness: PosixHarness, native_version: str+) -> None:+ _assert_opencode_validates_current_path(posix_harness, native_version)++[email protected]("native_version", ["1.18.31", "2.0.10"])+def test_install_ps1_opencode_validates_current_path(+ powershell_harness: PowerShellHarness, native_version: str+) -> None:+ _assert_opencode_validates_current_path(powershell_harness, native_version)++[email protected]("version_pin", ["1.18.31", "0.0.0-dev-19882", "2.0.9"])+def test_install_sh_opencode_ignores_version_pin_only_for_upstream_installer(+ posix_harness: PosixHarness, version_pin: str+) -> None:+ native = _prepare_native_opencode_v1(posix_harness)+ posix_harness.env["VERSION"] = version_pin+ next_installer = posix_harness.fixtures / "hermes-installer.sh"+ with next_installer.open("a", encoding="utf-8") as script:+ script.write(+ '\nprintf "version-after-opencode:%s\\n" "${VERSION:-unset}" >> "$CALL_LOG"\n'+ )+ result = posix_harness.run()+ assert result.returncode == 0, result.stderr+ installed = subprocess.run(+ [str(native), "--version"],+ env=posix_harness.env | {"FAIL_STEP": ""},+ capture_output=True,+ text=True,+ check=True,+ )+ assert installed.stdout.strip() == "opencode v2.0.10"+ assert f"version-after-opencode:{version_pin}" in posix_harness.calls()+++def _assert_opencode_dry_run_preserves_migration_files(+ harness: PosixHarness | PowerShellHarness,+) -> None:+ native = _prepare_native_opencode_v1(harness)+ original = native.read_bytes()+ home = native.parents[2]+ plugin = home / ".config" / "opencode" / "plugins" / "rtk.ts"+ plugin.parent.mkdir(parents=True)+ contents = (+ Path(__file__).with_name("fixtures").joinpath("rtk-opencode-v1.ts").read_bytes()+ )+ plugin.write_bytes(contents)+ result = harness.run(+ "-DryRun" if isinstance(harness, PowerShellHarness) else "--dry-run"+ )+ assert result.returncode == 0, result.stderr+ assert native.read_bytes() == original+ assert plugin.read_bytes() == contents+ assert not list(plugin.parents[1].glob("rtk-v1-*"))+ assert harness.calls() == []+++def test_install_sh_opencode_dry_run_preserves_v1_and_plugin(+ posix_harness: PosixHarness,+) -> None:+ _assert_opencode_dry_run_preserves_migration_files(posix_harness)+++def test_install_ps1_opencode_dry_run_preserves_v1_and_plugin(+ powershell_harness: PowerShellHarness,+) -> None:+ _assert_opencode_dry_run_preserves_migration_files(powershell_harness)+++def _assert_opencode_link_requires_manual_migration(+ harness: PosixHarness | PowerShellHarness,+) -> None:+ native = _prepare_native_opencode_v1(harness)+ target = native.with_name("user-managed" + native.suffix)+ native.rename(target)+ original = target.read_bytes()+ try:+ native.symlink_to(target)+ except OSError as exc:+ pytest.skip(f"symlink creation unavailable: {exc}")+ result = harness.run()+ assert result.returncode != 0+ assert "linked" in result.stderr+ assert target.read_bytes() == original+ assert native.is_symlink()+ assert not any("opencode.ai" in call for call in harness.calls())+++def test_install_sh_opencode_link_requires_manual_migration(+ posix_harness: PosixHarness,+) -> None:+ _assert_opencode_link_requires_manual_migration(posix_harness)+++def test_install_ps1_opencode_link_requires_manual_migration(+ powershell_harness: PowerShellHarness,+) -> None:+ _assert_opencode_link_requires_manual_migration(powershell_harness)++[email protected]("version", ["1.18.31", "2.0.11-beta", "3.0.0", "bad/version"])+def test_install_ps1_opencode_rejects_invalid_release_before_replacement(+ powershell_harness: PowerShellHarness, version: str+) -> None:+ binary = _prepare_native_opencode_v1(powershell_harness)+ original = binary.read_bytes()+ powershell_harness.env["FAKE_OPENCODE_RELEASE"] = version+ result = powershell_harness.run()+ assert result.returncode != 0+ assert binary.read_bytes() == original+ assert not any(+ "opencode.ai/files/bin/" in call for call in powershell_harness.calls()+ )+++def test_install_ps1_opencode_rejects_mismatched_archive_before_replacement(+ powershell_harness: PowerShellHarness,+) -> None:+ binary = _prepare_native_opencode_v1(powershell_harness)+ original = binary.read_bytes()+ powershell_harness.env["FAKE_OPENCODE_ARCHIVE_VERSION"] = "opencode v1.18.31"+ result = powershell_harness.run()+ assert result.returncode != 0+ assert binary.read_bytes() == original++[email protected]("powershell", _powershells())[email protected]("exit_code", [0, 31])[email protected](os.name != "nt", reason="Windows native command probe")+def test_install_ps1_opencode_version_probe_runs_native_command(+ tmp_path: Path, powershell: str, exit_code: int+) -> None:+ binary = tmp_path / "path with spaces" / "opencode.cmd"+ _write_executable(+ binary,+ f"@echo off\necho opencode v2.0.10\nexit /b {exit_code}\n",+ )+ text = (_repo_root() / "scripts" / "install.ps1").read_text(encoding="utf-8")+ body = _braced_body(text, "function Read-OpenCodeVersionOutput")+ script = f"""$ErrorActionPreference = "Stop"+function Read-OpenCodeVersionOutput {{{body}}}+Read-OpenCodeVersionOutput $env:TEST_OPENCODE+"""+ result = subprocess.run(+ [powershell, "-NoProfile", "-Command", script],+ env=os.environ | {"TEST_OPENCODE": str(binary)},+ capture_output=True,+ text=True,+ timeout=20,+ check=False,+ )+ if exit_code:+ assert result.returncode != 0+ assert f"exit code {exit_code}" in result.stderr+ else:+ assert result.returncode == 0, result.stderr+ assert result.stdout.strip() == "opencode v2.0.10"++@pytest.mark.parametrize("powershell", _powershells())def test_install_ps1_falls_back_when_pshome_executable_is_unavailable(tmp_path: Path,diff --git a/uv.lock b/uv.lockindex 8a215021..97907ccb 100644--- a/uv.lock+++ b/uv.lock@@ -599,7 +599,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "6.2.44"+version = "6.2.45"source = { editable = "." }dependencies = [{ name = "aiohttp" },