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
Add OpenCode as a first-class FCC client (#1440)
Ali Khokharc5bc88b24133
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 67ad5de1..b386648d 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -12,15 +12,15 @@ and how contributors should extend it.Free Claude Code is a local proxy for agent clients. It accepts AnthropicMessages traffic from Claude Code and Pi clients and OpenAI Responses traffic-from Codex CLI, IDE, and App clients, routes the request to a configured-upstream provider, and preserves the wire protocol expected by the caller.+from Codex and OpenCode clients, routes the request to a configured upstream+provider, and preserves the wire protocol expected by the caller.There are three runtime surfaces:- HTTP proxy: FastAPI routes expose Anthropic-compatible, Responses-compatible,health, model-listing, stop, and admin endpoints.-- CLI launchers: wrapper entrypoints prepare Claude Code, Codex, and Pi sessions- so they target the local proxy.+- CLI launchers: wrapper entrypoints prepare Claude Code, Codex, Pi, and+ OpenCode sessions so they target the local proxy.- Messaging bridge: optional Discord or Telegram adapters turn chat messagesinto managed client CLI sessions.@@ -29,6 +29,7 @@ flowchart LRClaudeCode[Claude Code CLI and Extensions] --> ProxyAPI[FastAPI Proxy]Codex[Codex CLI, IDE, and App] --> ProxyAPIPi[Pi Coding Agent] --> ProxyAPI+ OpenCode[OpenCode CLI] --> ProxyAPIAdminUI[Local Admin UI] --> ProxyAPIBots[Discord or Telegram Bots] --> Messaging[Messaging Bridge]Messaging --> ClientCLI[Managed Client CLI Sessions]@@ -168,6 +169,9 @@ for real prompts against supported providers:- `fcc-pi`, Pi, and the Anthropic-compatible proxy behavior Pi relies on,including an FCC-scoped model catalog, streaming text and reasoning, and tooluse/results.+- `fcc-opencode`, stable OpenCode V1, and the OpenAI Responses behavior it+ relies on, including an FCC-scoped model catalog and process-local provider+ configuration.- Configured Discord and Telegram messaging bridges, including command handling,reply-based conversation branches, status updates, transcript rendering,managed Claude/Codex task execution where configured, task stop/clear flows,@@ -222,6 +226,7 @@ Console scripts are registered in [pyproject.toml](pyproject.toml):- `fcc-claude` calls `free_claude_code.cli.launchers.claude:launch`.- `fcc-codex` calls `free_claude_code.cli.launchers.codex:launch`.- `fcc-pi` calls `free_claude_code.cli.launchers.pi:launch`.+- `fcc-opencode` calls `free_claude_code.cli.launchers.opencode:launch`.[scripts/install.sh](scripts/install.sh) and [scripts/install.ps1](scripts/install.ps1)install or update the uv tool plus optional voice extras. On Windows the@@ -230,7 +235,7 @@ per-user application bundle and desktop link. [scripts/uninstall.sh](scripts/uniand [scripts/uninstall.ps1](scripts/uninstall.ps1) remove those exact desktopartifacts, the FCC uv tool, and the managed `~/.fcc/` tree from[config/paths.py](src/free_claude_code/config/paths.py); they do not remove-uv, Claude Code, Codex, Pi, or uv-managed Python runtimes. [scripts/ci.sh](scripts/ci.sh) and+uv, Claude Code, Codex, Pi, OpenCode, or uv-managed Python runtimes. [scripts/ci.sh](scripts/ci.sh) and[scripts/ci.ps1](scripts/ci.ps1) mirror [.github/workflows/tests.yml](.github/workflows/tests.yml)for local pre-push verification.@@ -1189,6 +1194,13 @@ client environment.Codex surface one credential owner instead of competing with Codex's signed-inOpenAI authorization.+[cli/launchers/model_catalog.py](src/free_claude_code/cli/launchers/model_catalog.py)+owns the client-neutral projection from FCC's `/v1/models` response to direct,+nested `provider/model` routes. It removes Claude-only compatibility aliases,+deduplicates normal and no-thinking forms deterministically, and is shared by+Codex and OpenCode. Each launcher remains responsible for translating those+neutral entries into its client's configuration format.+[cli/launchers/pi.py](src/free_claude_code/cli/launchers/pi.py) owns the installed`fcc-pi` launcher and [cli/launchers/pi_extension.ts](src/free_claude_code/cli/launchers/pi_extension.ts)is its bundled Pi adapter:@@ -1207,6 +1219,25 @@ is its bundled Pi adapter:- Pi package-management, configuration, help, and version commands pass throughunchanged because they do not create an FCC-backed session.+[cli/launchers/opencode.py](src/free_claude_code/cli/launchers/opencode.py) and+[cli/launchers/opencode_config.py](src/free_claude_code/cli/launchers/opencode_config.py)+own the installed `fcc-opencode` launcher for stable OpenCode V1:++- Inference commands require OpenCode V1 1.18.18 or newer, a reachable FCC+ server, and a non-empty routable `/v1/models` snapshot. Preparation is+ fail-closed so OpenCode cannot fall back to a native provider.+- The launcher creates a temporary, secret-free `free-claude-code` provider+ catalog and a protected process overlay. The provider uses `@ai-sdk/openai`+ against FCC's `/v1` Responses surface, and bearer material is carried only in+ the child environment.+- Existing `OPENCODE_CONFIG` or `OPENCODE_CONFIG_CONTENT` overrides are rejected+ because their precedence would make FCC routing ambiguous. Persistent OpenCode+ config, data, credentials, plugins, and sessions remain OpenCode-owned and are+ never rewritten.+- Native help, version, authentication, upgrade, uninstall, and completion+ commands pass through without requiring FCC. Other arguments are forwarded+ unchanged after the FCC process configuration is ready.+[cli/managed/](src/free_claude_code/cli/managed/) owns managed Claude Code subprocesses used byDiscord and Telegram messaging. Managed task invocations extend the same proxyenvironment only with non-interactive terminal settings, optional `--resume`,@@ -1230,9 +1261,9 @@ reports a count-only failure, and leaves failures available for the next cleanupattempt. Real-session registration is collision-safe and becomes durable treestate only after the manager accepts it.-Codex and Pi are supported through their installed launchers. FCC does not keep-internal managed session runners for them because no user-facing messaging-setting selects either client for Discord or Telegram.+Codex, Pi, and OpenCode are supported through their installed launchers. FCC+does not keep internal managed session runners for them because no user-facing+messaging setting selects those clients for Discord or Telegram.## Messaging Architecturediff --git a/README.md b/README.mdindex e3496858..1e86c27c 100644--- a/README.md+++ b/README.md@@ -21,7 +21,7 @@## What You Get-- **Use your preferred coding agent.** Run Claude Code, Codex, or Pi with FCC.+- **Use your preferred coding agent.** Run Claude Code, Codex, Pi, or OpenCode with FCC.- **Choose your own models.** Connect free, paid, or local providers and search their models from one Admin UI.- **Route work your way.** Set one default model or map Fable, Opus, Sonnet, and Haiku separately.- **Save time and tokens.** Five built-in optimizations handle quota probes, command-prefix detection, title generation, suggestion mode, and filepath extraction locally instead of calling your provider; optionally enable [RTK](https://github.com/rtk-ai/rtk) to filter noisy terminal output before it reaches the model.@@ -127,13 +127,20 @@ Pi:fcc-pi```-All three launchers use the current Admin UI settings. Use the agent's model picker to choose from the models FCC exposes. Normal CLI arguments still work, for example:+OpenCode:++```bash+fcc-opencode+```++All four launchers use the current Admin UI settings. Use the agent's model picker to choose from the models FCC exposes. Normal CLI arguments still work, for example:```bashfcc-codex exec "hello"```-`fcc-pi` registers FCC only for that Pi process; your existing Pi settings, sessions, credentials, and extensions remain unchanged.+`fcc-pi` and `fcc-opencode` register FCC only for the launched process; your+existing agent settings, sessions, credentials, and extensions remain unchanged.<a id="model-picker"></a>@@ -279,7 +286,7 @@ Open **Admin UI → Model Config → Reasoning** and select the behavior you wan| Selection | Behavior || --- | --- |-| **From client** (default) | Use the effort sent by Claude Code, Codex, or Pi. If none is sent, keep the provider default. |+| **From client** (default) | Use the effort sent by Claude Code, Codex, Pi, or OpenCode. If none is sent, keep the provider default. || **Off** | Request reasoning to be disabled. || **Low**, **Medium**, **High**, **X-High**, or **Max** | Override the client with the selected reasoning level. || **Inherit** (Fable, Opus, Sonnet, and Haiku only) | Use the root Reasoning selection. |@@ -292,7 +299,8 @@ Providers that do not support a selected control retain their own behavior.## Connect Your Client-For terminal use, start `fcc-server`, then run `fcc-claude`, `fcc-codex`, or `fcc-pi`. Use the guides below for editor integrations.+For terminal use, start `fcc-server`, then run `fcc-claude`, `fcc-codex`,+`fcc-pi`, or `fcc-opencode`. Use the guides below for editor integrations.<details><summary><strong>Claude Code in VS Code</strong></summary>@@ -527,7 +535,7 @@ Stop every running FCC command before uninstalling.**Keeps**- uv and Python-- Claude Code, Codex, Pi, and RTK+- Claude Code, Codex, Pi, OpenCode, and RTK- Shared PATH entriesmacOS/Linux:diff --git a/pyproject.toml b/pyproject.tomlindex d849e886..e1d763f9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "5.4.0"+version = "5.5.0"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"@@ -33,6 +33,7 @@ fcc-server = "free_claude_code.cli.entrypoints:serve"fcc-claude = "free_claude_code.cli.launchers.claude:launch"fcc-codex = "free_claude_code.cli.launchers.codex:launch"fcc-pi = "free_claude_code.cli.launchers.pi:launch"+fcc-opencode = "free_claude_code.cli.launchers.opencode:launch"[project.gui-scripts]fcc-desktop = "free_claude_code.cli.desktop_entrypoint:launch"diff --git a/scripts/install.ps1 b/scripts/install.ps1index c591e012..3253bb8a 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -21,6 +21,8 @@ $MinUvVersion = "0.11.16"$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"+$MinOpenCodeVersion = "1.18.18"$RtkVersion = "0.44.2"$RtkReleaseBaseUrl = "https://github.com/rtk-ai/rtk/releases/download/v$RtkVersion"$RtkWindowsAssetName = "rtk-x86_64-pc-windows-msvc.zip"@@ -29,6 +31,7 @@ $UvInstallUrl = "https://astral.sh/uv/install.ps1"$script:InstallClaudeCode = $true$script:InstallCodex = $true$script:InstallPi = $true+$script:InstallOpenCode = $true$script:PiAvailable = $false$script:EnableRtk = $Rtk.IsPresent$FccCommands = @(@@ -38,6 +41,7 @@ $FccCommands = @("fcc-claude","fcc-codex","fcc-pi",+ "fcc-opencode","fcc-init","free-claude-code")@@ -97,8 +101,9 @@ function Select-CodingAgents {$script:InstallClaudeCode = Read-YesNo "Install or verify Claude Code for fcc-claude?"$script:InstallCodex = Read-YesNo "Install or verify Codex for fcc-codex?"$script:InstallPi = Read-YesNo "Install or verify Pi for fcc-pi?"+ $script:InstallOpenCode = Read-YesNo "Install or verify OpenCode for fcc-opencode?"- if ($script:InstallClaudeCode -or $script:InstallCodex -or $script:InstallPi) {+ if ($script:InstallClaudeCode -or $script:InstallCodex -or $script:InstallPi -or $script:InstallOpenCode) {break}Write-Host "Select at least one coding agent."@@ -231,6 +236,7 @@ function Add-PathEntry {function Add-KnownBinDirectories {if (-not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {Add-PathEntry (Join-Path $env:USERPROFILE ".local\bin")+ Add-PathEntry (Join-Path $env:USERPROFILE ".opencode\bin")}if (-not [string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {Add-PathEntry (Join-Path $env:LOCALAPPDATA "Programs\OpenAI\Codex\bin")@@ -534,6 +540,9 @@ 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")+ }}function Ensure-ClaudeCode {@@ -593,6 +602,157 @@ function Ensure-Pi {$script:PiAvailable = $true}+function Convert-SemanticVersionOutput {+ param([string] $Output)++ if ([string]::IsNullOrWhiteSpace($Output)) {+ return ""+ }+ if ($Output -match '(?m)^\s*(?:(?:uv|opencode)(?:\s+version)?\s+|v)?(?<version>\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?)(?:\s+\([^\r\n]*\))?\s*$') {+ return $Matches["version"]+ }+ return ""+}++function Test-SupportedStableVersion {+ param(+ [string] $Version,+ [string] $Minimum+ )++ $parsedVersion = Convert-SemanticVersionOutput $Version+ $parsedMinimum = Convert-SemanticVersionOutput $Minimum+ if ([string]::IsNullOrWhiteSpace($parsedVersion) -or [string]::IsNullOrWhiteSpace($parsedMinimum)) {+ throw "Unable to compare semantic versions."+ }+ if ($parsedVersion.Contains("-")) {+ return $false+ }++ $normalizedVersion = $parsedVersion -replace '\+.*$', ''+ $normalizedMinimum = $parsedMinimum -replace '\+.*$', ''+ return ([version] $normalizedVersion) -ge ([version] $normalizedMinimum)+}++function Get-OpenCodeVersion {+ param([string] $OpenCodePath)++ $output = Invoke-Utf8NativeCapture -FilePath $OpenCodePath -Arguments @("--version")+ $version = Convert-SemanticVersionOutput $output+ if ([string]::IsNullOrWhiteSpace($version)) {+ throw "OpenCode is present, but 'opencode --version' did not return a valid semantic version."+ }+ return $version+}++function Confirm-OpenCodeApplication {+ if ($DryRun) {+ Write-Host "+ opencode --version"+ return+ }++ $command = Get-ApplicationCommand "opencode"+ if (-not $command) {+ throw "OpenCode was installed, but 'opencode' is not available on PATH."+ }+ $version = Get-OpenCodeVersion $command.Source+ if (-not (Test-SupportedStableVersion -Version $version -Minimum $MinOpenCodeVersion)) {+ throw "Stable OpenCode V1 $MinOpenCodeVersion or newer is required; found OpenCode $version after installation."+ }+ Write-Host "Verified OpenCode $version."+}++function Get-OpenCodeWindowsAssetName {+ $architecture = $env:PROCESSOR_ARCHITEW6432+ if ([string]::IsNullOrWhiteSpace($architecture)) {+ $architecture = $env:PROCESSOR_ARCHITECTURE+ }+ if ([string]::IsNullOrWhiteSpace($architecture)) {+ $architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()+ }++ switch ($architecture.ToUpperInvariant()) {+ "ARM64" { return "opencode-windows-arm64.zip" }+ "AMD64" { return "opencode-windows-x64-baseline.zip" }+ "X64" { return "opencode-windows-x64-baseline.zip" }+ "X86_64" { return "opencode-windows-x64-baseline.zip" }+ default { throw "OpenCode does not provide a supported Windows release for architecture '$architecture'." }+ }+}++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 "+ extract and install opencode.exe to $(Format-Argument $installDirectory)"+ return+ }++ $temporaryRoot = Join-Path ([IO.Path]::GetTempPath()) ("fcc-opencode-" + [guid]::NewGuid().ToString("N"))+ $archivePath = Join-Path $temporaryRoot $assetName+ $extractPath = Join-Path $temporaryRoot "extracted"+ $temporaryInstallPath = Join-Path $installDirectory (".opencode-" + [guid]::NewGuid().ToString("N") + ".exe")+ try {+ New-Item -ItemType Directory -Path $temporaryRoot | Out-Null+ Write-Host "+ irm $archiveUrl -OutFile $(Format-Argument $archivePath)"+ Invoke-RestMethod -Uri $archiveUrl -OutFile $archivePath -ErrorAction Stop+ if ((-not (Test-Path -LiteralPath $archivePath -PathType Leaf)) -or ((Get-Item -LiteralPath $archivePath).Length -eq 0)) {+ throw "The OpenCode release archive was empty."+ }++ Expand-Archive -LiteralPath $archivePath -DestinationPath $extractPath+ $executables = @(Get-ChildItem -LiteralPath $extractPath -Recurse -File -Filter "opencode.exe")+ if ($executables.Count -ne 1) {+ throw "The OpenCode release archive did not contain exactly one opencode.exe."+ }++ New-Item -ItemType Directory -Force -Path $installDirectory | Out-Null+ Copy-Item -LiteralPath $executables[0].FullName -Destination $temporaryInstallPath+ if ((-not (Test-Path -LiteralPath $temporaryInstallPath -PathType Leaf)) -or ((Get-Item -LiteralPath $temporaryInstallPath).Length -eq 0)) {+ throw "The extracted OpenCode executable was empty."+ }+ Move-Item -LiteralPath $temporaryInstallPath -Destination (Join-Path $installDirectory "opencode.exe") -Force+ }+ finally {+ Remove-Item -LiteralPath $temporaryInstallPath -Force -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $temporaryRoot -Recurse -Force -ErrorAction SilentlyContinue+ }+}++function Ensure-OpenCode {+ if ($DryRun) {+ if (Get-ApplicationCommand "opencode") {+ Write-Host "+ opencode --version"+ Write-Host "A compatible OpenCode will be preserved; an older version will be upgraded with opencode upgrade."+ }+ else {+ Install-OpenCode+ }+ Confirm-OpenCodeApplication+ return+ }++ $command = Get-ApplicationCommand "opencode"+ if ($command) {+ $version = Get-OpenCodeVersion $command.Source+ if (Test-SupportedStableVersion -Version $version -Minimum $MinOpenCodeVersion) {+ Write-Host "OpenCode $version already satisfies >=$MinOpenCodeVersion; leaving it unchanged."+ return+ }+ Write-Host "OpenCode $version does not satisfy stable V1 >=$MinOpenCodeVersion; upgrading it with OpenCode."+ Invoke-NativeCommand -FilePath $command.Source -Arguments @("upgrade")+ Add-KnownBinDirectories+ }+ else {+ Install-OpenCode+ Add-KnownBinDirectories+ }++ Confirm-OpenCodeApplication+}+function Ensure-SelectedCodingAgents {if ($script:InstallClaudeCode) {Write-Step "Ensuring Claude Code is installed"@@ -609,30 +769,21 @@ function Ensure-SelectedCodingAgents {Ensure-Pi}- if ((-not $script:InstallClaudeCode) -and (-not $script:InstallCodex) -and (-not $script:PiAvailable)) {- throw "No selected coding agent was installed. Re-run the installer and choose at least one."- }-}--function Convert-UvVersionOutput {- param([string] $Output)-- if ([string]::IsNullOrWhiteSpace($Output)) {- return ""+ if ($script:InstallOpenCode) {+ Write-Step "Ensuring OpenCode is installed"+ Ensure-OpenCode}- if ($Output -match '(?m)(?:^|\s)(?:uv\s+)?(?<version>\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?)\b') {- return $Matches["version"]+ if ((-not $script:InstallClaudeCode) -and (-not $script:InstallCodex) -and (-not $script:PiAvailable) -and (-not $script:InstallOpenCode)) {+ throw "No selected coding agent was installed. Re-run the installer and choose at least one."}-- return ""}function Get-UvVersion {param([string] $UvPath)$output = Invoke-Utf8NativeCapture -FilePath $UvPath -Arguments @("--version")- $version = Convert-UvVersionOutput $output+ $version = Convert-SemanticVersionOutput $outputif ([string]::IsNullOrWhiteSpace($version)) {throw "uv is present, but 'uv --version' did not return a valid version."}@@ -640,27 +791,6 @@ function Get-UvVersion {return $version}-function Test-SupportedUvVersion {- param(- [string] $Version,- [string] $Minimum- )-- $parsedVersion = Convert-UvVersionOutput $Version- $parsedMinimum = Convert-UvVersionOutput $Minimum- if ([string]::IsNullOrWhiteSpace($parsedVersion) -or [string]::IsNullOrWhiteSpace($parsedMinimum)) {- throw "Unable to compare uv versions."- }- if ($parsedVersion.Contains("-")) {- return $false- }-- $normalizedVersion = $parsedVersion -replace '\+.*$', ''- $normalizedMinimum = $parsedMinimum -replace '\+.*$', ''-- return ([version] $normalizedVersion) -ge ([version] $normalizedMinimum)-}-function Confirm-Uv {if ($DryRun) {Write-Host "+ uv --version"@@ -673,7 +803,7 @@ function Confirm-Uv {}$version = Get-UvVersion $uvCommand.Source- if (-not (Test-SupportedUvVersion -Version $version -Minimum $MinUvVersion)) {+ if (-not (Test-SupportedStableVersion -Version $version -Minimum $MinUvVersion)) {throw "Stable uv $MinUvVersion or newer is required; found uv $version after installation."}Write-Host "Verified uv $version."@@ -696,7 +826,7 @@ function Ensure-Uv {$uvCommand = Get-ApplicationCommand "uv"if ($uvCommand) {$version = Get-UvVersion $uvCommand.Source- if (Test-SupportedUvVersion -Version $version -Minimum $MinUvVersion) {+ if (Test-SupportedStableVersion -Version $version -Minimum $MinUvVersion) {Write-Host "uv $version already satisfies >=$MinUvVersion; leaving it unchanged."return}@@ -799,7 +929,7 @@ function Configure-AndConfirmFreeClaudeCode {if ($DryRun) {Write-Host "+ uv tool update-shell"Write-Host "+ uv tool dir --bin"- Write-Host "+ verify fcc-desktop, fcc-server, fcc-claude, fcc-codex, and fcc-pi in the uv tool bin directory"+ Write-Host "+ verify fcc-desktop, fcc-server, fcc-claude, fcc-codex, fcc-pi, and fcc-opencode in the uv tool bin directory"Write-Host "+ fcc-server --version"Export-FccDesktopIcon `-DesktopCommand "<uv-tool-bin>\fcc-desktop.exe" `@@ -826,7 +956,7 @@ function Configure-AndConfirmFreeClaudeCode {[IO.Path]::AltDirectorySeparatorChar)$installedCommands = @{}- foreach ($commandName in @("fcc-desktop", "fcc-server", "fcc-claude", "fcc-codex", "fcc-pi")) {+ foreach ($commandName in @("fcc-desktop", "fcc-server", "fcc-claude", "fcc-codex", "fcc-pi", "fcc-opencode")) {$command = Get-ApplicationCommand $commandNameif (-not $command) {throw "Free Claude Code installation did not create '$commandName'."@@ -966,4 +1096,7 @@ else {if ($script:PiAvailable) {Write-Host "Run Pi with: fcc-pi"}+ if ($script:InstallOpenCode) {+ Write-Host "Run OpenCode with: fcc-opencode"+ }}diff --git a/scripts/install.sh b/scripts/install.shindex 53c6f875..02e3266a 100644--- a/scripts/install.sh+++ b/scripts/install.sh@@ -7,13 +7,15 @@ MIN_UV_VERSION="0.11.16"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"+MIN_OPENCODE_VERSION="1.18.18"RTK_VERSION="0.44.2"RTK_RELEASE_BASE_URL="https://github.com/rtk-ai/rtk/releases/download/v$RTK_VERSION"UV_INSTALL_URL="https://astral.sh/uv/install.sh"FCC_MACOS_BUNDLE_ID="io.github.alishahryar1.free-claude-code"FCC_MACOS_OWNER_FILE=".free-claude-code-owner"# Include retired entry points so updates reject older FCC processes before replacement.-FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-init free-claude-code"+FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-init free-claude-code"dry_run=0voice_nim=0@@ -22,6 +24,7 @@ voice_all=0install_claude=1install_codex=1install_pi=1+install_opencode=1enable_rtk=0torch_backend=""temporary_file=""@@ -106,8 +109,13 @@ choose_coding_agents() {elseinstall_pi=0fi+ if prompt_yes_no "Install or verify OpenCode for fcc-opencode?"; then+ install_opencode=1+ else+ install_opencode=0+ fi- if [ "$install_claude" -eq 1 ] || [ "$install_codex" -eq 1 ] || [ "$install_pi" -eq 1 ]; then+ if [ "$install_claude" -eq 1 ] || [ "$install_codex" -eq 1 ] || [ "$install_pi" -eq 1 ] || [ "$install_opencode" -eq 1 ]; thenbreakfiprintf 'Select at least one coding agent.\n\n' >&4@@ -191,6 +199,7 @@ add_known_bin_directories() {if [ -n "${HOME:-}" ]; thenadd_path_entry "$HOME/.local/bin"add_path_entry "$HOME/.cargo/bin"+ add_path_entry "$HOME/.opencode/bin"add_path_entry "${XDG_DATA_HOME:-$HOME/.local/share}/pi-node/current/bin"fi@@ -513,6 +522,9 @@ 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+ fi}ensure_claude() {@@ -569,6 +581,67 @@ ensure_pi() {pi_available=1}+current_opencode_version() {+ if output=$(opencode --version 2>/dev/null); then+ :+ else+ return 1+ fi++ version=$(printf '%s\n' "$output" | awk '+ /^[[:space:]]*((opencode( version)?[[:space:]]+)|v)?[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?[[:space:]]*$/ &&+ match($0, /[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?/) {+ print substr($0, RSTART, RLENGTH)+ exit+ }+ ')+ [ -n "$version" ] || return 1+ printf '%s\n' "$version"+}++verify_opencode_command() {+ if [ "$dry_run" -eq 1 ]; then+ print_command opencode --version+ return 0+ fi++ command_path=$(command -v opencode 2>/dev/null) || fail "OpenCode was installed, but 'opencode' is not available on PATH."+ version=$(current_opencode_version) || fail "OpenCode is present, but 'opencode --version' did not return a valid semantic version."+ if ! stable_version_is_supported "$version" "$MIN_OPENCODE_VERSION"; then+ fail "Stable OpenCode V1 $MIN_OPENCODE_VERSION or newer is required; found OpenCode $version after installation."+ fi+ printf 'Verified OpenCode %s.\n' "$version"+}++ensure_opencode() {+ if [ "$dry_run" -eq 1 ]; then+ if command -v opencode >/dev/null 2>&1; then+ print_command opencode --version+ printf 'A compatible OpenCode will be preserved; an older version will be upgraded with opencode upgrade.\n'+ else+ download_and_run "$OPENCODE_INSTALL_URL" bash "OpenCode"+ fi+ verify_opencode_command+ return 0+ fi++ if command -v opencode >/dev/null 2>&1; then+ version=$(current_opencode_version) || fail "OpenCode is present, but 'opencode --version' did not return a valid semantic version."+ if stable_version_is_supported "$version" "$MIN_OPENCODE_VERSION"; then+ printf 'OpenCode %s already satisfies >=%s; leaving it unchanged.\n' "$version" "$MIN_OPENCODE_VERSION"+ return 0+ fi+ printf 'OpenCode %s does not satisfy stable V1 >=%s; upgrading it with OpenCode.\n' "$version" "$MIN_OPENCODE_VERSION"+ run opencode upgrade+ add_known_bin_directories+ else+ download_and_run "$OPENCODE_INSTALL_URL" bash "OpenCode"+ add_known_bin_directories+ fi++ verify_opencode_command+}+ensure_selected_coding_agents() {if [ "$install_claude" -eq 1 ]; thenstep "Ensuring Claude Code is installed"@@ -585,7 +658,12 @@ ensure_selected_coding_agents() {ensure_pifi- if [ "$install_claude" -eq 0 ] && [ "$install_codex" -eq 0 ] && [ "$pi_available" -eq 0 ]; then+ if [ "$install_opencode" -eq 1 ]; then+ step "Ensuring OpenCode is installed"+ ensure_opencode+ fi++ if [ "$install_claude" -eq 0 ] && [ "$install_codex" -eq 0 ] && [ "$pi_available" -eq 0 ] && [ "$install_opencode" -eq 0 ]; thenfail "No selected coding agent was installed. Re-run the installer and choose at least one."fi}@@ -609,7 +687,7 @@ current_uv_version() {esac}-uv_version_is_supported() {+stable_version_is_supported() {case "$1" in*-*) return 1 ;;esac@@ -648,7 +726,7 @@ verify_uv() {command -v uv >/dev/null 2>&1 || fail "uv was installed, but it is not available on PATH."version=$(current_uv_version) || fail "uv is present, but 'uv --version' did not return a valid version."- if ! uv_version_is_supported "$version" "$MIN_UV_VERSION"; then+ if ! stable_version_is_supported "$version" "$MIN_UV_VERSION"; thenfail "Stable uv $MIN_UV_VERSION or newer is required; found uv $version after installation."fi@@ -670,7 +748,7 @@ ensure_uv() {if command -v uv >/dev/null 2>&1; thenversion=$(current_uv_version) || fail "uv is present, but 'uv --version' did not return a valid version."- if uv_version_is_supported "$version" "$MIN_UV_VERSION"; then+ if stable_version_is_supported "$version" "$MIN_UV_VERSION"; thenprintf 'uv %s already satisfies >=%s; leaving it unchanged.\n' "$version" "$MIN_UV_VERSION"return 0fi@@ -772,7 +850,7 @@ configure_and_verify_free_claude_code() {if [ "$dry_run" -eq 1 ]; thenprint_command uv tool dir --bin- printf '+ verify fcc-desktop, fcc-server, fcc-claude, fcc-codex, and fcc-pi in the uv tool bin directory\n'+ printf '+ verify fcc-desktop, fcc-server, fcc-claude, fcc-codex, fcc-pi, and fcc-opencode in the uv tool bin directory\n'print_command fcc-server --versionreturn 0fi@@ -790,7 +868,7 @@ configure_and_verify_free_claude_code() {export PATHhash -r 2>/dev/null || true- for command_name in fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi; do+ for command_name in fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode; do[ -x "$tool_bin/$command_name" ] || fail "Free Claude Code installation did not create $tool_bin/$command_name."done@@ -900,7 +978,7 @@ fistep "Checking installation prerequisites"require_command curl-if [ "$install_claude" -eq 1 ]; then+if [ "$install_claude" -eq 1 ] || [ "$install_opencode" -eq 1 ]; thenrequire_command bashfirequire_command sh@@ -949,4 +1027,7 @@ elseif [ "$pi_available" -eq 1 ]; thenprintf 'Run Pi with: fcc-pi\n'fi+ if [ "$install_opencode" -eq 1 ]; then+ printf 'Run OpenCode with: fcc-opencode\n'+ fifidiff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1index 7d9884e0..885f80d7 100644--- a/scripts/uninstall.ps1+++ b/scripts/uninstall.ps1@@ -17,6 +17,7 @@ $FccCommands = @("fcc-claude","fcc-codex","fcc-pi",+ "fcc-opencode","fcc-init","free-claude-code")@@ -28,7 +29,7 @@ function Show-Usage {Usage: uninstall.ps1 [options]Removes the Free Claude Code uv tool and deletes ~/.fcc/ after removal is verified.-Does not remove uv, Claude Code, Codex, Pi, the uv-managed Python runtime, or shared PATH entries.+Does not remove uv, Claude Code, Codex, Pi, OpenCode, the uv-managed Python runtime, or shared PATH entries.Options:-DryRun Print commands without running them.@@ -333,5 +334,5 @@ if ($DryRun) {}else {Write-Host "Free Claude Code has been removed and verified."- Write-Host "uv, Claude Code, Codex, Pi, the uv-managed Python runtime, and shared PATH entries were left installed."+ Write-Host "uv, Claude Code, Codex, Pi, OpenCode, the uv-managed Python runtime, and shared PATH entries were left installed."}diff --git a/scripts/uninstall.sh b/scripts/uninstall.shindex e2c3434f..1c551cf9 100644--- a/scripts/uninstall.sh+++ b/scripts/uninstall.sh@@ -6,7 +6,7 @@ FCC_HOME_DIRNAME=".fcc"FCC_MACOS_BUNDLE_ID="io.github.alishahryar1.free-claude-code"FCC_MACOS_OWNER_FILE=".free-claude-code-owner"# Include retired entry points so older installations are fully stopped and removed.-FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-init free-claude-code"+FCC_COMMANDS="fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-init free-claude-code"dry_run=0uv_tool_bin=""@@ -16,7 +16,7 @@ show_usage() {Usage: uninstall.sh [options]Removes the Free Claude Code uv tool and deletes ~/.fcc/ after removal is verified.-Does not remove uv, Claude Code, Codex, Pi, the uv-managed Python runtime, or shared PATH entries.+Does not remove uv, Claude Code, Codex, Pi, OpenCode, the uv-managed Python runtime, or shared PATH entries.Options:--dry-run Print commands without running them.@@ -298,5 +298,5 @@ if [ "$dry_run" -eq 1 ]; thenprintf '\nDry run complete. No changes were made.\n'elseprintf '\nFree Claude Code has been removed and verified.\n'- printf 'uv, Claude Code, Codex, Pi, the uv-managed Python runtime, and shared PATH entries were left installed.\n'+ printf 'uv, Claude Code, Codex, Pi, OpenCode, the uv-managed Python runtime, and shared PATH entries were left installed.\n'fidiff --git a/smoke/README.md b/smoke/README.mdindex 2a3e08b8..49b376f3 100644--- a/smoke/README.md+++ b/smoke/README.md@@ -56,7 +56,7 @@ Default targets do not send real bot messages or load voice backends:| `api` | messages, count_tokens full payload, errors, `/stop`, optimizations | configured provider only for streaming messages || `auth` | canonical bearer auth, conflicting legacy headers, invalid/missing auth | none; test sets an isolated token || `cli` | server entrypoint, Claude CLI adaptive thinking, session cleanup | Claude CLI binary and provider only for real CLI |-| `clients` | VS Code and JetBrains protocol payloads | configured provider |+| `clients` | VS Code and JetBrains protocol payloads; Pi and OpenCode CLI prompts | configured provider; installed Pi/OpenCode binaries for their CLI scenarios || `config` | env precedence, removed-env migration, proxy/timeouts | none || `extensibility` | provider runtime and platform factory construction | none || `messaging` | fake Discord/Telegram full flow, literal clear scopes, trees, persistence, voice cancel | none |diff --git a/smoke/capabilities.py b/smoke/capabilities.pyindex 19ff43b1..ac6f5300 100644--- a/smoke/capabilities.py+++ b/smoke/capabilities.py@@ -500,6 +500,20 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (("tests/cli/test_entrypoints.py",),("test_pi_cli_prompt_e2e",),),+ CapabilityContract(+ "cli",+ "opencode_cli_integration",+ "opencode_cli_integration",+ "free_claude_code.cli.launchers.opencode",+ "OpenCode V1 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",+ (+ "tests/cli/test_opencode_launcher.py",+ "tests/cli/test_model_catalog.py",+ ),+ ("test_opencode_cli_prompt_e2e",),+ ),CapabilityContract("extensibility","provider_platform_abcs",diff --git a/smoke/features.py b/smoke/features.pyindex 607fb43d..5cb0f48c 100644--- a/smoke/features.py+++ b/smoke/features.py@@ -85,6 +85,22 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (("Pi CLI", "configured provider credentials or local provider endpoint"),"skip only when Pi is absent; configured providers must pass",),+ FeatureCoverage(+ "opencode_cli_integration",+ "OpenCode discovers FCC models and sends Responses through the proxy",+ (+ "tests/cli/test_opencode_launcher.py",+ "tests/cli/test_model_catalog.py",+ ),+ ("test_probe_and_models_routes",),+ ("test_opencode_cli_prompt_e2e",),+ ("clients",),+ (+ "stable OpenCode V1 CLI",+ "configured provider credentials or local provider endpoint",+ ),+ "skip only when OpenCode is absent; configured providers must pass",+ ),FeatureCoverage("provider_matrix","Every configured provider prefix can satisfy conversation scenarios",diff --git a/smoke/product/test_client_product_live.py b/smoke/product/test_client_product_live.pyindex b6ee1c10..b606a205 100644--- a/smoke/product/test_client_product_live.py+++ b/smoke/product/test_client_product_live.py@@ -118,6 +118,77 @@ def test_pi_cli_prompt_e2e(smoke_config: SmokeConfig, tmp_path: Path) -> None:assert "POST /v1/messages" in server_log[email protected]_target("clients")+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 = "fcc-opencode-smoke-token"+ isolated_home = tmp_path / "opencode-home"+ isolated_config = tmp_path / "opencode-config"+ for path in (isolated_home, isolated_config):+ path.mkdir()++ with SmokeServerDriver(+ smoke_config,+ name="product-opencode-cli",+ env_overrides={+ "MODEL": provider_model.full_model,+ "ANTHROPIC_AUTH_TOKEN": auth_token,+ "MESSAGING_PLATFORM": "none",+ },+ ).run() as server:+ env = os.environ.copy()+ env.update(+ {+ "HOST": "127.0.0.1",+ "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),+ }+ )+ 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,+ )+ server_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.stdout+ assert "POST /v1/responses" in server_log+ assert "POST /v1/chat/completions" not in server_log++@pytest.mark.smoke_target("cli")def test_claude_cli_adaptive_thinking_e2e(smoke_config: SmokeConfig, tmp_path: Pathdiff --git a/src/free_claude_code/cli/launchers/codex.py b/src/free_claude_code/cli/launchers/codex.pyindex 8bb12789..dfb07186 100644--- a/src/free_claude_code/cli/launchers/codex.py+++ b/src/free_claude_code/cli/launchers/codex.py@@ -4,25 +4,20 @@ import jsonimport osimport sysfrom collections.abc import Mapping, Sequence-from urllib.request import Request-from free_claude_code.cli.local_http import (- open_local_request,- with_local_proxy_bypass,-)+from free_claude_code.cli.local_http import with_local_proxy_bypassfrom free_claude_code.config.loader import get_settingsfrom free_claude_code.config.paths import codex_model_catalog_pathfrom free_claude_code.config.server_urls import local_proxy_root_urlfrom free_claude_code.config.settings import Settings-from free_claude_code.core.json_types import JsonObject, JsonValuefrom .codex_model_catalog import build_codex_model_catalog, write_codex_model_catalogfrom .common import (- PROXY_PREFLIGHT_TIMEOUT_SECONDS,preflight_proxy,resolve_client_binary,run_client_process,)+from .model_catalog import fetch_proxy_models_response_PRINT_PROXY_AUTH_TOKEN_FLAG = "--print-proxy-auth-token"_DISPLAY_NAME = "Codex CLI"@@ -164,23 +159,6 @@ def codex_model_catalog_config_args(return build_model_catalog_config_args(str(catalog_path))-def fetch_proxy_models_response(proxy_root_url: str, auth_token: str) -> JsonObject:- """Fetch the local proxy `/v1/models` response for Codex catalog generation."""-- url = f"{proxy_root_url.rstrip('/')}/v1/models"- headers = {"Authorization": f"Bearer {auth_token}"}-- request = Request(url, headers=headers, method="GET")- with open_local_request(- request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS- ) as response:- payload: JsonValue = json.loads(response.read().decode("utf-8"))-- if not isinstance(payload, dict):- raise ValueError("model list response was not a JSON object")- return payload--def build_model_catalog_config_args(catalog_path: str) -> list[str]:"""Return Codex config args for a generated model catalog."""diff --git a/src/free_claude_code/cli/launchers/codex_model_catalog.py b/src/free_claude_code/cli/launchers/codex_model_catalog.pyindex 9252663a..6fd00684 100644--- a/src/free_claude_code/cli/launchers/codex_model_catalog.py+++ b/src/free_claude_code/cli/launchers/codex_model_catalog.py@@ -3,16 +3,12 @@import jsonimport uuidfrom collections.abc import Mapping-from dataclasses import dataclassfrom pathlib import Path-from free_claude_code.config.provider_catalog import SUPPORTED_PROVIDER_IDS-from free_claude_code.core.gateway_model_ids import (- GATEWAY_MODEL_ID_PREFIX,- NO_THINKING_GATEWAY_MODEL_ID_PREFIX,-)from free_claude_code.core.json_types import JsonObject, JsonValue+from .model_catalog import ClientModel, client_models_from_response+SUPPORTED_REASONING_LEVELS: list[JsonObject] = [{"effort": "low", "description": "Fast responses with lighter reasoning"},{@@ -33,38 +29,17 @@ CODEX_BASE_INSTRUCTIONS = ()-@dataclass(frozen=True, slots=True)-class _CatalogCandidate:- slug: str- provider_model_ref: str- display_name: str- force_no_thinking: bool--def build_codex_model_catalog(models_response: Mapping[str, JsonValue]) -> JsonObject:"""Convert FCC `/v1/models` data into Codex `model_catalog_json` payload."""- candidates = list(_catalog_candidates(models_response))- normal_provider_refs = {- candidate.provider_model_ref- for candidate in candidates- if not candidate.force_no_thinking+ return {+ "models": [+ _codex_catalog_entry(model, priority=priority)+ for priority, model in enumerate(+ client_models_from_response(models_response)+ )+ ]}- models: list[JsonObject] = []- seen_slugs: set[str] = set()-- for candidate in candidates:- if (- candidate.force_no_thinking- and candidate.provider_model_ref in normal_provider_refs- ):- continue- if candidate.slug in seen_slugs:- continue- seen_slugs.add(candidate.slug)- models.append(_codex_catalog_entry(candidate, priority=len(models)))-- return {"models": models}def write_codex_model_catalog(@@ -89,70 +64,9 @@ def write_codex_model_catalog(return True-def _catalog_candidates(- models_response: Mapping[str, JsonValue],-) -> list[_CatalogCandidate]:- data = models_response.get("data")- if not isinstance(data, list):- return []-- candidates: list[_CatalogCandidate] = []- for item in data:- if not isinstance(item, Mapping):- continue- model_id = _string_value(item.get("id"))- if model_id is None:- continue- candidate = _candidate_from_model_id(- model_id,- display_name=_string_value(item.get("display_name")) or model_id,- )- if candidate is not None:- candidates.append(candidate)- return candidates---def _candidate_from_model_id(- model_id: str, *, display_name: str-) -> _CatalogCandidate | None:- prefix, separator, remainder = model_id.partition("/")- if not separator:- return None-- if prefix == GATEWAY_MODEL_ID_PREFIX:- if not _is_provider_model_ref(remainder):- return None- return _CatalogCandidate(- slug=remainder,- provider_model_ref=remainder,- display_name=display_name,- force_no_thinking=False,- )-- if prefix == NO_THINKING_GATEWAY_MODEL_ID_PREFIX:- if not _is_provider_model_ref(remainder):- return None- return _CatalogCandidate(- slug=model_id,- provider_model_ref=remainder,- display_name=display_name,- force_no_thinking=True,- )-- if prefix in SUPPORTED_PROVIDER_IDS and remainder:- return _CatalogCandidate(- slug=model_id,- provider_model_ref=model_id,- display_name=display_name,- force_no_thinking=False,- )-- return None---def _codex_catalog_entry(candidate: _CatalogCandidate, *, priority: int) -> JsonObject:+def _codex_catalog_entry(candidate: ClientModel, *, priority: int) -> JsonObject:return {- "slug": candidate.slug,+ "slug": candidate.wire_slug,"display_name": candidate.display_name,"description": "Free Claude Code provider model","default_reasoning_level": "medium",@@ -181,12 +95,3 @@ def _codex_catalog_entry(candidate: _CatalogCandidate, *, priority: int) -> Json"supports_search_tool": True,"use_responses_lite": False,}---def _is_provider_model_ref(value: str) -> bool:- provider_id, separator, provider_model = value.partition("/")- return bool(separator and provider_model and provider_id in SUPPORTED_PROVIDER_IDS)---def _string_value(value: object) -> str | None:- return value if isinstance(value, str) else Nonediff --git a/src/free_claude_code/cli/launchers/model_catalog.py b/src/free_claude_code/cli/launchers/model_catalog.pynew file mode 100644index 00000000..8a1182a4--- /dev/null+++ b/src/free_claude_code/cli/launchers/model_catalog.py@@ -0,0 +1,141 @@+"""Shared FCC model-catalog projection for installed client launchers."""++import json+from collections.abc import Mapping+from dataclasses import dataclass+from urllib.request import Request++from free_claude_code.cli.local_http import open_local_request+from free_claude_code.config.provider_catalog import SUPPORTED_PROVIDER_IDS+from free_claude_code.core.gateway_model_ids import (+ GATEWAY_MODEL_ID_PREFIX,+ NO_THINKING_GATEWAY_MODEL_ID_PREFIX,+)+from free_claude_code.core.json_types import JsonObject, JsonValue++from .common import PROXY_PREFLIGHT_TIMEOUT_SECONDS+++@dataclass(frozen=True, slots=True)+class ClientModel:+ """One direct FCC model reference suitable for a client-side catalog."""++ wire_slug: str+ provider_model_ref: str+ display_name: str+ allows_reasoning: bool+++def client_models_from_response(+ models_response: Mapping[str, JsonValue],+) -> tuple[ClientModel, ...]:+ """Project an FCC `/v1/models` response into direct client model records."""++ candidates = _catalog_candidates(models_response)+ normal_provider_refs = {+ candidate.provider_model_ref+ for candidate in candidates+ if candidate.allows_reasoning+ }+ models: list[ClientModel] = []+ seen_slugs: set[str] = set()++ for candidate in candidates:+ if (+ not candidate.allows_reasoning+ and candidate.provider_model_ref in normal_provider_refs+ ):+ continue+ if candidate.wire_slug in seen_slugs:+ continue+ seen_slugs.add(candidate.wire_slug)+ models.append(candidate)++ return tuple(models)+++def fetch_proxy_models_response(proxy_root_url: str, auth_token: str) -> JsonObject:+ """Fetch the authenticated FCC-local `/v1/models` response directly."""++ url = f"{proxy_root_url.rstrip('/')}/v1/models"+ request = Request(+ url,+ headers={"Authorization": f"Bearer {auth_token}"},+ method="GET",+ )+ with open_local_request(+ request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS+ ) as response:+ payload: JsonValue = json.loads(response.read().decode("utf-8"))++ if not isinstance(payload, dict):+ raise ValueError("model list response was not a JSON object")+ return payload+++def _catalog_candidates(+ models_response: Mapping[str, JsonValue],+) -> list[ClientModel]:+ data = models_response.get("data")+ if not isinstance(data, list):+ return []++ candidates: list[ClientModel] = []+ for item in data:+ if not isinstance(item, Mapping):+ continue+ model_id = _string_value(item.get("id"))+ if model_id is None:+ continue+ candidate = _candidate_from_model_id(+ model_id,+ display_name=_string_value(item.get("display_name")) or model_id,+ )+ if candidate is not None:+ candidates.append(candidate)+ return candidates+++def _candidate_from_model_id(model_id: str, *, display_name: str) -> ClientModel | None:+ prefix, separator, remainder = model_id.partition("/")+ if not separator:+ return None++ if prefix == GATEWAY_MODEL_ID_PREFIX:+ if not _is_provider_model_ref(remainder):+ return None+ return ClientModel(+ wire_slug=remainder,+ provider_model_ref=remainder,+ display_name=display_name,+ allows_reasoning=True,+ )++ if prefix == NO_THINKING_GATEWAY_MODEL_ID_PREFIX:+ if not _is_provider_model_ref(remainder):+ return None+ return ClientModel(+ wire_slug=model_id,+ provider_model_ref=remainder,+ display_name=display_name,+ allows_reasoning=False,+ )++ if prefix in SUPPORTED_PROVIDER_IDS and remainder:+ return ClientModel(+ wire_slug=model_id,+ provider_model_ref=model_id,+ display_name=display_name,+ allows_reasoning=True,+ )++ return None+++def _is_provider_model_ref(value: str) -> bool:+ provider_id, separator, provider_model = value.partition("/")+ return bool(separator and provider_model and provider_id in SUPPORTED_PROVIDER_IDS)+++def _string_value(value: object) -> str | None:+ return value if isinstance(value, str) else Nonediff --git a/src/free_claude_code/cli/launchers/opencode.py b/src/free_claude_code/cli/launchers/opencode.pynew file mode 100644index 00000000..403ce352--- /dev/null+++ b/src/free_claude_code/cli/launchers/opencode.py@@ -0,0 +1,229 @@+"""Installed `fcc-opencode` launcher for stable OpenCode v1."""++import json+import os+import re+import subprocess+import sys+import tempfile+from collections.abc import Mapping, Sequence+from pathlib import Path+from typing import Never++from free_claude_code.cli.local_http import with_local_proxy_bypass+from free_claude_code.config.loader import get_settings+from free_claude_code.config.server_urls import local_proxy_root_url+from free_claude_code.core.json_types import JsonValue++from .common import preflight_proxy, resolve_client_binary, run_client_process+from .model_catalog import client_models_from_response, fetch_proxy_models_response+from .opencode_config import OPENCODE_API_KEY_ENV, OpenCodeConfig, build_opencode_config++_BINARY_NAME = "opencode"+_DISPLAY_NAME = "OpenCode CLI"+_INSTALL_HINT = "Install OpenCode from: https://opencode.ai/docs/"+_MINIMUM_VERSION = (1, 18, 18)+_VERSION_TIMEOUT_SECONDS = 5.0+_VERSION_PATTERN = re.compile(+ r"(?m)^\s*(?:(?:opencode(?:\s+version)?\s+)|v)?"+ r"(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?\s*$"+)+_PASSTHROUGH_COMMANDS = frozenset({"auth", "upgrade", "uninstall", "completion"})+_PASSTHROUGH_FLAGS = frozenset({"--help", "-h", "--version", "-v"})+_PROCESS_CONFIG_KEYS = ("OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT")+++def launch(argv: Sequence[str] | None = None) -> None:+ """Launch OpenCode with one child-scoped FCC provider and model catalog."""++ args = list(sys.argv[1:] if argv is None else argv)+ binary_path = resolve_client_binary(+ binary_name=_BINARY_NAME,+ display_name=_DISPLAY_NAME,+ install_hint=_INSTALL_HINT,+ )++ if is_opencode_passthrough(args):+ run_client_process(+ command=[binary_path, *args],+ env=os.environ,+ binary_name=_BINARY_NAME,+ display_name=_DISPLAY_NAME,+ install_hint=_INSTALL_HINT,+ )+ return++ require_compatible_opencode(binary_path)+ _reject_process_config_conflicts(os.environ)++ settings = get_settings()+ auth_token = settings.proxy_auth_token.strip()+ if not auth_token:+ print(+ "Free Claude Code proxy authentication token is empty.",+ file=sys.stderr,+ )+ raise SystemExit(1)++ proxy_root_url = local_proxy_root_url(settings)+ if error := preflight_proxy(proxy_root_url):+ print(+ f"Free Claude Code proxy is not reachable at {proxy_root_url}: {error}",+ file=sys.stderr,+ )+ print("Start it in another terminal with: fcc-server", file=sys.stderr)+ raise SystemExit(1)++ try:+ models = client_models_from_response(+ fetch_proxy_models_response(proxy_root_url, auth_token)+ )+ config = build_opencode_config(models, proxy_root_url=proxy_root_url)+ except Exception as exc:+ print(+ f"Could not prepare the OpenCode FCC model catalog: {exc}",+ file=sys.stderr,+ )+ raise SystemExit(1) from None++ _run_with_temporary_config(+ binary_path=binary_path,+ args=args,+ config=config,+ proxy_root_url=proxy_root_url,+ auth_token=auth_token,+ )+++def is_opencode_passthrough(argv: Sequence[str]) -> bool:+ """Return whether OpenCode should run without requiring a live FCC server."""++ return bool(argv) and (+ argv[0] in _PASSTHROUGH_COMMANDS+ or any(argument in _PASSTHROUGH_FLAGS for argument in argv)+ )+++def require_compatible_opencode(binary_path: str) -> None:+ """Exit unless the installed OpenCode satisfies FCC's stable-v1 contract."""++ version = opencode_binary_version(binary_path)+ if version is not None and version >= _MINIMUM_VERSION:+ return++ minimum = ".".join(str(part) for part in _MINIMUM_VERSION)+ print(+ f"The OpenCode CLI at {binary_path} must be a stable release "+ f"at least version {minimum}.",+ file=sys.stderr,+ )+ print("Upgrade it with: opencode upgrade", file=sys.stderr)+ raise SystemExit(126)+++def opencode_binary_version(binary_path: str) -> tuple[int, int, int] | None:+ """Read a semantic OpenCode version without invoking a shell."""++ try:+ result = subprocess.run(+ [binary_path, "--version"],+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ text=True,+ timeout=_VERSION_TIMEOUT_SECONDS,+ )+ except OSError, subprocess.TimeoutExpired:+ return None+ if result.returncode != 0:+ return None++ match = _VERSION_PATTERN.search(result.stdout)+ if match is None:+ return None+ return int(match.group(1)), int(match.group(2)), int(match.group(3))+++def build_opencode_launcher_env(+ *,+ proxy_root_url: str,+ auth_token: str,+ config_path: Path,+ overlay: Mapping[str, JsonValue],+ base_env: Mapping[str, str],+) -> dict[str, str]:+ """Build an isolated child environment without persisting FCC credentials."""++ env = with_local_proxy_bypass(+ {+ key: value+ for key, value in base_env.items()+ if not key.startswith("FCC_OPENCODE_") and key not in _PROCESS_CONFIG_KEYS+ },+ proxy_root_url=proxy_root_url,+ )+ env["OPENCODE_CONFIG"] = str(config_path)+ env["OPENCODE_CONFIG_CONTENT"] = json.dumps(+ overlay,+ ensure_ascii=True,+ separators=(",", ":"),+ )+ env[OPENCODE_API_KEY_ENV] = auth_token+ return env+++def _reject_process_config_conflicts(base_env: Mapping[str, str]) -> None:+ for key in _PROCESS_CONFIG_KEYS:+ if base_env.get(key, "").strip():+ print(+ f"{key} is already set. Unset it before running fcc-opencode; "+ "ordinary opencode remains unchanged.",+ file=sys.stderr,+ )+ raise SystemExit(1)+++def _run_with_temporary_config(+ *,+ binary_path: str,+ args: Sequence[str],+ config: OpenCodeConfig,+ proxy_root_url: str,+ auth_token: str,+) -> None:+ try:+ temp_config = tempfile.TemporaryDirectory(prefix="fcc-opencode-")+ except OSError as exc:+ _temporary_config_error(exc)++ with temp_config as temp_directory:+ config_path = Path(temp_directory, "opencode.json")+ try:+ config_path.write_text(+ json.dumps(config.file, ensure_ascii=True, indent=2) + "\n",+ encoding="utf-8",+ )+ except OSError as exc:+ _temporary_config_error(exc)++ run_client_process(+ command=[binary_path, *args],+ env=build_opencode_launcher_env(+ proxy_root_url=proxy_root_url,+ auth_token=auth_token,+ config_path=config_path,+ overlay=config.overlay,+ base_env=os.environ,+ ),+ binary_name=_BINARY_NAME,+ display_name=_DISPLAY_NAME,+ install_hint=_INSTALL_HINT,+ )+++def _temporary_config_error(exc: OSError) -> Never:+ print(+ f"Could not create temporary OpenCode configuration: {exc}",+ file=sys.stderr,+ )+ raise SystemExit(1) from Nonediff --git a/src/free_claude_code/cli/launchers/opencode_config.py b/src/free_claude_code/cli/launchers/opencode_config.pynew file mode 100644index 00000000..9f410096--- /dev/null+++ b/src/free_claude_code/cli/launchers/opencode_config.py@@ -0,0 +1,67 @@+"""Process-local OpenCode v1 configuration for FCC model routing."""++from dataclasses import dataclass++from free_claude_code.core.json_types import JsonObject++from .model_catalog import ClientModel++OPENCODE_API_KEY_ENV = "FCC_OPENCODE_API_KEY"+OPENCODE_PROVIDER_ID = "free-claude-code"+++@dataclass(frozen=True, slots=True)+class OpenCodeConfig:+ """Secret-free file and overlay configuration for one OpenCode process."""++ file: JsonObject+ overlay: JsonObject+++def build_opencode_config(+ models: tuple[ClientModel, ...], *, proxy_root_url: str+) -> OpenCodeConfig:+ """Translate a non-empty FCC model snapshot into OpenCode v1 config."""++ if not models:+ raise ValueError("OpenCode requires at least one routable FCC model")++ model_config: JsonObject = {+ model.wire_slug: {+ "name": model.display_name,+ "reasoning": model.allows_reasoning,+ }+ for model in models+ }+ provider_config: JsonObject = {+ "name": "Free Claude Code",+ "npm": "@ai-sdk/openai",+ "options": {+ "baseURL": _ensure_v1_url(proxy_root_url),+ "apiKey": f"{{env:{OPENCODE_API_KEY_ENV}}}",+ },+ }+ default_model = f"{OPENCODE_PROVIDER_ID}/{models[0].wire_slug}"++ return OpenCodeConfig(+ file={+ "provider": {+ OPENCODE_PROVIDER_ID: {+ **provider_config,+ "models": model_config,+ }+ }+ },+ overlay={+ "provider": {OPENCODE_PROVIDER_ID: provider_config},+ "enabled_providers": [OPENCODE_PROVIDER_ID],+ "disabled_providers": [],+ "model": default_model,+ "small_model": default_model,+ },+ )+++def _ensure_v1_url(url: str) -> str:+ stripped = url.rstrip("/")+ return stripped if stripped.endswith("/v1") else f"{stripped}/v1"diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex 4786966b..800e14d8 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -64,6 +64,7 @@ def test_cli_scripts_are_registered() -> None:"fcc-claude": "free_claude_code.cli.launchers.claude:launch","fcc-codex": "free_claude_code.cli.launchers.codex:launch","fcc-pi": "free_claude_code.cli.launchers.pi:launch",+ "fcc-opencode": "free_claude_code.cli.launchers.opencode:launch",}assert pyproject["project"]["gui-scripts"] == {"fcc-desktop": "free_claude_code.cli.desktop_entrypoint:launch",@@ -431,7 +432,7 @@ def test_launch_codex_passes_responses_config_and_child_env(return_value=catalog_path,),patch(- "free_claude_code.cli.launchers.codex.open_local_request",+ "free_claude_code.cli.launchers.model_catalog.open_local_request",side_effect=fake_urlopen,),patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,@@ -490,7 +491,9 @@ def test_codex_proxy_auth_command_prints_only_current_token(patch.object(codex, "get_settings", return_value=settings) as get_settings,patch.object(codex, "preflight_proxy") as preflight_proxy,patch.object(codex, "resolve_client_binary") as resolve_client_binary,- patch.object(codex, "open_local_request") as open_local_request,+ patch(+ "free_claude_code.cli.launchers.model_catalog.open_local_request"+ ) as open_local_request,patch.object(codex, "run_client_process") as run_client_process,):codex.launch(["--print-proxy-auth-token"])@@ -527,7 +530,7 @@ def test_launch_codex_catalog_failure_warns_and_continues(return_value=tmp_path / "codex-model-catalog.json",),patch(- "free_claude_code.cli.launchers.codex.open_local_request",+ "free_claude_code.cli.launchers.model_catalog.open_local_request",side_effect=URLError("boom"),),patch("free_claude_code.cli.launchers.common.subprocess.Popen") as popen,diff --git a/tests/cli/test_model_catalog.py b/tests/cli/test_model_catalog.pynew file mode 100644index 00000000..ce7e6612--- /dev/null+++ b/tests/cli/test_model_catalog.py@@ -0,0 +1,137 @@+from unittest.mock import patch++import pytest++from free_claude_code.cli.launchers.model_catalog import (+ ClientModel,+ client_models_from_response,+ fetch_proxy_models_response,+)+from free_claude_code.core.json_types import JsonObject+++def _models_payload(*model_ids: str) -> JsonObject:+ return {+ "data": [+ {+ "id": model_id,+ "display_name": f"Display {index}",+ }+ for index, model_id in enumerate(model_ids)+ ]+ }+++def test_client_models_project_nested_direct_refs_in_source_order() -> None:+ assert client_models_from_response(+ _models_payload(+ "anthropic/nvidia_nim/nvidia/nemotron-3-super",+ "open_router/meta-llama/llama-3.3-70b",+ )+ ) == (+ ClientModel(+ wire_slug="nvidia_nim/nvidia/nemotron-3-super",+ provider_model_ref="nvidia_nim/nvidia/nemotron-3-super",+ display_name="Display 0",+ allows_reasoning=True,+ ),+ ClientModel(+ wire_slug="open_router/meta-llama/llama-3.3-70b",+ provider_model_ref="open_router/meta-llama/llama-3.3-70b",+ display_name="Display 1",+ allows_reasoning=True,+ ),+ )+++def test_client_models_suppress_no_thinking_alias_when_normal_model_exists() -> None:+ models = client_models_from_response(+ _models_payload(+ "claude-3-freecc-no-thinking/nvidia_nim/provider-model",+ "anthropic/nvidia_nim/provider-model",+ )+ )++ assert [model.wire_slug for model in models] == ["nvidia_nim/provider-model"]+++def test_client_models_keep_no_thinking_only_route() -> None:+ assert client_models_from_response(+ _models_payload("claude-3-freecc-no-thinking/open_router/plain-model")+ ) == (+ ClientModel(+ wire_slug="claude-3-freecc-no-thinking/open_router/plain-model",+ provider_model_ref="open_router/plain-model",+ display_name="Display 0",+ allows_reasoning=False,+ ),+ )+++def test_client_models_ignore_compatibility_unknown_and_malformed_entries() -> None:+ payload: JsonObject = {+ "data": [+ {"id": "claude-opus-4-20250514"},+ {"id": "anthropic/unknown/model"},+ {"id": 123},+ "not-an-object",+ ]+ }++ assert client_models_from_response(payload) == ()+ assert client_models_from_response({"data": "not-a-list"}) == ()+++def test_client_models_deduplicate_wire_slugs_deterministically() -> None:+ models = client_models_from_response(+ _models_payload(+ "anthropic/gemini/models/gemini-test",+ "gemini/models/gemini-test",+ "anthropic/open_router/provider/test",+ )+ )++ assert [model.wire_slug for model in models] == [+ "gemini/models/gemini-test",+ "open_router/provider/test",+ ]+ assert models[0].display_name == "Display 0"+++class _ModelsResponse:+ def __init__(self, body: bytes) -> None:+ self._body = body++ def __enter__(self) -> _ModelsResponse:+ return self++ def __exit__(self, *exc_info: object) -> None:+ del exc_info++ def read(self) -> bytes:+ return self._body+++def test_fetch_proxy_models_uses_canonical_bearer_request() -> None:+ with patch(+ "free_claude_code.cli.launchers.model_catalog.open_local_request",+ return_value=_ModelsResponse(b'{"data": []}'),+ ) as open_local_request:+ response = fetch_proxy_models_response("http://127.0.0.1:9191/", "proxy-token")++ assert response == {"data": []}+ request = open_local_request.call_args.args[0]+ assert request.full_url == "http://127.0.0.1:9191/v1/models"+ assert request.get_method() == "GET"+ assert request.get_header("Authorization") == "Bearer proxy-token"+++def test_fetch_proxy_models_rejects_non_object_json() -> None:+ with (+ patch(+ "free_claude_code.cli.launchers.model_catalog.open_local_request",+ return_value=_ModelsResponse(b"[]"),+ ),+ pytest.raises(ValueError, match="JSON object"),+ ):+ fetch_proxy_models_response("http://127.0.0.1:9191", "proxy-token")diff --git a/tests/cli/test_opencode_launcher.py b/tests/cli/test_opencode_launcher.pynew file mode 100644index 00000000..5db1ea13--- /dev/null+++ b/tests/cli/test_opencode_launcher.py@@ -0,0 +1,511 @@+"""OpenCode launcher contract tests."""++import json+import subprocess+from collections.abc import Mapping+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from free_claude_code.cli.launchers.model_catalog import ClientModel+from free_claude_code.cli.launchers.opencode_config import build_opencode_config+from free_claude_code.config.settings import Settings+from free_claude_code.core.json_types import JsonObject+++def _settings() -> Settings:+ return Settings(+ host="0.0.0.0",+ port=9191,+ proxy_auth_enabled=False,+ proxy_auth_token="proxy-token",+ model="nvidia_nim/test-model",+ )+++def _models_payload() -> JsonObject:+ return {+ "data": [+ {+ "id": "anthropic/nvidia_nim/vendor/model",+ "display_name": "Nested model",+ },+ {+ "id": "claude-3-freecc-no-thinking/open_router/plain-model",+ "display_name": "No-thinking model",+ },+ ]+ }+++def test_opencode_config_uses_responses_sdk_and_only_known_metadata() -> None:+ config = build_opencode_config(+ (+ ClientModel(+ wire_slug="nvidia_nim/vendor/model",+ provider_model_ref="nvidia_nim/vendor/model",+ display_name="Nested model",+ allows_reasoning=True,+ ),+ ClientModel(+ wire_slug="claude-3-freecc-no-thinking/open_router/plain-model",+ provider_model_ref="open_router/plain-model",+ display_name="No-thinking model",+ allows_reasoning=False,+ ),+ ),+ proxy_root_url="http://127.0.0.1:9191",+ )++ provider = config.file["provider"]+ assert isinstance(provider, dict)+ fcc = provider["free-claude-code"]+ assert isinstance(fcc, dict)+ assert fcc["npm"] == "@ai-sdk/openai"+ assert fcc["options"] == {+ "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,+ },+ "claude-3-freecc-no-thinking/open_router/plain-model": {+ "name": "No-thinking model",+ "reasoning": False,+ },+ }+ assert config.overlay == {+ "provider": {+ "free-claude-code": {+ "name": "Free Claude Code",+ "npm": "@ai-sdk/openai",+ "options": {+ "baseURL": "http://127.0.0.1:9191/v1",+ "apiKey": "{env:FCC_OPENCODE_API_KEY}",+ },+ }+ },+ "enabled_providers": ["free-claude-code"],+ "disabled_providers": [],+ "model": "free-claude-code/nvidia_nim/vendor/model",+ "small_model": "free-claude-code/nvidia_nim/vendor/model",+ }+ serialized = json.dumps(config.file | config.overlay)+ assert "proxy-token" not in serialized+ assert "context" not in serialized+ assert "attachment" not in serialized+++def test_opencode_config_rejects_empty_model_catalog() -> None:+ with pytest.raises(ValueError, match="at least one"):+ build_opencode_config((), proxy_root_url="http://127.0.0.1:9191")+++def test_opencode_child_env_is_process_local_and_preserves_user_state(+ tmp_path: Path,+) -> None:+ from free_claude_code.cli.launchers.opencode import build_opencode_launcher_env++ config_path = tmp_path / "opencode.json"+ env = build_opencode_launcher_env(+ proxy_root_url="http://127.0.0.1:9191",+ auth_token="proxy-token",+ config_path=config_path,+ overlay={"model": "free-claude-code/nvidia_nim/vendor/model"},+ base_env={+ "PATH": "keep",+ "OPENCODE_CONFIG": "",+ "OPENCODE_CONFIG_CONTENT": "",+ "OPENCODE_CONFIG_DIR": "keep-user-state",+ "FCC_OPENCODE_API_KEY": "stale-token",+ "FCC_OPENCODE_OTHER": "stale-value",+ "HTTP_PROXY": "http://proxy.example",+ },+ )++ assert env["PATH"] == "keep"+ assert env["OPENCODE_CONFIG"] == str(config_path)+ assert json.loads(env["OPENCODE_CONFIG_CONTENT"]) == {+ "model": "free-claude-code/nvidia_nim/vendor/model"+ }+ assert env["OPENCODE_CONFIG_DIR"] == "keep-user-state"+ assert env["FCC_OPENCODE_API_KEY"] == "proxy-token"+ assert "FCC_OPENCODE_OTHER" not in env+ assert env["HTTP_PROXY"] == "http://proxy.example"+ assert env["NO_PROXY"] == "127.0.0.1,localhost,::1"+ assert env["no_proxy"] == env["NO_PROXY"]+++ ("output", "return_code", "expected"),+ [+ ("1.18.18\n", 0, (1, 18, 18)),+ ("opencode version 1.19.0\n", 0, (1, 19, 0)),+ ("v1.19.0+release.1\n", 0, (1, 19, 0)),+ ("v2.0.0-beta.1\n", 0, None),+ ("unexpected text 1.19.0\n", 0, None),+ ("not-a-version\n", 0, None),+ ("1.18.18\n", 1, None),+ ],+)+def test_opencode_version_probe(+ output: str,+ return_code: int,+ expected: tuple[int, int, int] | None,+) -> None:+ from free_claude_code.cli.launchers.opencode import opencode_binary_version++ with patch(+ "free_claude_code.cli.launchers.opencode.subprocess.run",+ return_value=SimpleNamespace(stdout=output, returncode=return_code),+ ):+ assert opencode_binary_version("resolved-opencode") == expected+++def test_opencode_version_probe_handles_timeout() -> None:+ from free_claude_code.cli.launchers.opencode import opencode_binary_version++ with patch(+ "free_claude_code.cli.launchers.opencode.subprocess.run",+ side_effect=subprocess.TimeoutExpired("opencode", 5),+ ):+ assert opencode_binary_version("resolved-opencode") is None+++ "argv",+ [+ ["--help"],+ ["run", "--help"],+ ["--version"],+ ["auth", "login"],+ ["upgrade"],+ ["uninstall"],+ ["completion", "bash"],+ ],+)+def test_opencode_management_commands_pass_through_without_fcc(+ argv: list[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "get_settings") as get_settings,+ patch.object(opencode, "preflight_proxy") as preflight_proxy,+ patch.object(opencode, "run_client_process") as run_client_process,+ ):+ opencode.launch(argv)++ run_client_process.assert_called_once()+ assert run_client_process.call_args.kwargs["command"] == [+ "resolved-opencode",+ *argv,+ ]+ get_settings.assert_not_called()+ preflight_proxy.assert_not_called()+++ "argv",+ [[], ["models"], ["run", "hello"], ["serve"], ["web"], ["acp"]],+)+def test_opencode_inference_commands_are_never_raw_passthrough(+ argv: list[str],+) -> None:+ from free_claude_code.cli.launchers.opencode import is_opencode_passthrough++ assert not is_opencode_passthrough(argv)+++def test_opencode_models_is_fcc_configured_and_temp_config_is_cleaned(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from free_claude_code.cli.launchers import opencode++ monkeypatch.setenv("KEEP_ME", "yes")+ observed_path: Path | None = None+ observed_file: JsonObject | None = None+ observed_env: dict[str, str] | None = None++ def observe_process(+ *,+ command: list[str],+ env: Mapping[str, str],+ binary_name: str,+ display_name: str,+ install_hint: str,+ ) -> None:+ nonlocal observed_path, observed_file, observed_env+ del binary_name, display_name, install_hint+ observed_path = Path(env["OPENCODE_CONFIG"])+ payload = json.loads(observed_path.read_text(encoding="utf-8"))+ assert isinstance(payload, dict)+ observed_file = payload+ observed_env = dict(env)+ assert command == ["resolved-opencode", "models"]++ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "require_compatible_opencode"),+ patch.object(opencode, "get_settings", return_value=_settings()),+ patch.object(opencode, "preflight_proxy", return_value=None),+ patch.object(+ opencode,+ "fetch_proxy_models_response",+ return_value=_models_payload(),+ ) as fetch_models,+ patch.object(opencode, "run_client_process", side_effect=observe_process),+ ):+ opencode.launch(["models"])++ fetch_models.assert_called_once_with("http://127.0.0.1:9191", "proxy-token")+ assert observed_path is not None+ assert not observed_path.exists()+ assert observed_file is not None+ providers = observed_file["provider"]+ assert isinstance(providers, dict)+ assert "free-claude-code" in providers+ assert observed_env is not None+ assert observed_env["FCC_OPENCODE_API_KEY"] == "proxy-token"+ assert observed_env["KEEP_ME"] == "yes"+ assert "proxy-token" not in json.dumps(observed_file)+ assert "proxy-token" not in observed_env["OPENCODE_CONFIG_CONTENT"]++[email protected]("key", ["OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT"])+def test_opencode_rejects_inherited_process_config_before_fcc_calls(+ key: str,+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ monkeypatch.setenv(key, "user-config")+ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "require_compatible_opencode"),+ patch.object(opencode, "get_settings") as get_settings,+ patch.object(opencode, "preflight_proxy") as preflight_proxy,+ patch.object(opencode, "run_client_process") as run_client_process,+ pytest.raises(SystemExit) as exc_info,+ ):+ opencode.launch([])++ assert exc_info.value.code == 1+ assert key in capsys.readouterr().err+ get_settings.assert_not_called()+ preflight_proxy.assert_not_called()+ run_client_process.assert_not_called()+++def test_opencode_fails_closed_when_catalog_has_no_routable_models(+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "require_compatible_opencode"),+ patch.object(opencode, "get_settings", return_value=_settings()),+ patch.object(opencode, "preflight_proxy", return_value=None),+ patch.object(+ opencode,+ "fetch_proxy_models_response",+ return_value={"data": [{"id": "claude-opus-4-20250514"}]},+ ),+ patch.object(opencode, "run_client_process") as run_client_process,+ pytest.raises(SystemExit) as exc_info,+ ):+ opencode.launch([])++ assert exc_info.value.code == 1+ run_client_process.assert_not_called()+ assert "at least one routable FCC model" in capsys.readouterr().err+++def test_opencode_fails_closed_when_proxy_is_unreachable(+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "require_compatible_opencode"),+ patch.object(opencode, "get_settings", return_value=_settings()),+ patch.object(opencode, "preflight_proxy", return_value="connection refused"),+ patch.object(opencode, "fetch_proxy_models_response") as fetch_models,+ patch.object(opencode, "run_client_process") as run_client_process,+ pytest.raises(SystemExit) as exc_info,+ ):+ opencode.launch(["run", "hello"])++ assert exc_info.value.code == 1+ captured = capsys.readouterr()+ assert "connection refused" in captured.err+ assert "fcc-server" in captured.err+ fetch_models.assert_not_called()+ run_client_process.assert_not_called()+++def test_opencode_fails_closed_when_catalog_fetch_fails(+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "require_compatible_opencode"),+ patch.object(opencode, "get_settings", return_value=_settings()),+ patch.object(opencode, "preflight_proxy", return_value=None),+ patch.object(+ opencode,+ "fetch_proxy_models_response",+ side_effect=OSError("catalog unavailable"),+ ),+ patch.object(opencode, "run_client_process") as run_client_process,+ pytest.raises(SystemExit) as exc_info,+ ):+ opencode.launch(["run", "hello"])++ assert exc_info.value.code == 1+ assert "catalog unavailable" in capsys.readouterr().err+ run_client_process.assert_not_called()+++def test_opencode_reports_temporary_config_creation_failure(+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "require_compatible_opencode"),+ patch.object(opencode, "get_settings", return_value=_settings()),+ patch.object(opencode, "preflight_proxy", return_value=None),+ patch.object(+ opencode,+ "fetch_proxy_models_response",+ return_value=_models_payload(),+ ),+ patch.object(+ opencode.tempfile,+ "TemporaryDirectory",+ side_effect=OSError("temporary directory unavailable"),+ ),+ patch.object(opencode, "run_client_process") as run_client_process,+ pytest.raises(SystemExit) as exc_info,+ ):+ opencode.launch(["run", "hello"])++ assert exc_info.value.code == 1+ assert "temporary directory unavailable" in capsys.readouterr().err+ run_client_process.assert_not_called()+++def test_opencode_reports_temporary_config_write_failure(+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "require_compatible_opencode"),+ patch.object(opencode, "get_settings", return_value=_settings()),+ patch.object(opencode, "preflight_proxy", return_value=None),+ patch.object(+ opencode,+ "fetch_proxy_models_response",+ return_value=_models_payload(),+ ),+ patch.object(+ opencode.Path,+ "write_text",+ side_effect=OSError("temporary file unavailable"),+ ),+ patch.object(opencode, "run_client_process") as run_client_process,+ pytest.raises(SystemExit) as exc_info,+ ):+ opencode.launch(["run", "hello"])++ assert exc_info.value.code == 1+ assert "temporary file unavailable" in capsys.readouterr().err+ run_client_process.assert_not_called()+++def test_opencode_rejects_empty_proxy_token_before_network_calls(+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with (+ patch.object(+ opencode, "resolve_client_binary", return_value="resolved-opencode"+ ),+ patch.object(opencode, "require_compatible_opencode"),+ patch.object(+ opencode,+ "get_settings",+ return_value=SimpleNamespace(+ host="0.0.0.0",+ port=9191,+ proxy_auth_token=" ",+ ),+ ),+ patch.object(opencode, "preflight_proxy") as preflight_proxy,+ patch.object(opencode, "run_client_process") as run_client_process,+ pytest.raises(SystemExit) as exc_info,+ ):+ opencode.launch([])++ assert exc_info.value.code == 1+ assert "token is empty" in capsys.readouterr().err+ preflight_proxy.assert_not_called()+ run_client_process.assert_not_called()+++def test_opencode_rejects_incompatible_version_with_upgrade_hint(+ capsys: pytest.CaptureFixture[str],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with (+ patch.object(opencode, "opencode_binary_version", return_value=(1, 18, 17)),+ pytest.raises(SystemExit) as exc_info,+ ):+ opencode.require_compatible_opencode("resolved-opencode")++ assert exc_info.value.code == 126+ captured = capsys.readouterr()+ assert "stable release at least version 1.18.18" in captured.err+ assert "opencode upgrade" in captured.err++[email protected]("version", [(1, 18, 18), (1, 19, 0), (2, 0, 0)])+def test_opencode_accepts_stable_minimum_and_newer_versions(+ version: tuple[int, int, int],+) -> None:+ from free_claude_code.cli.launchers import opencode++ with patch.object(opencode, "opencode_binary_version", return_value=version):+ opencode.require_compatible_opencode("resolved-opencode")diff --git a/tests/scripts/test_installers.py b/tests/scripts/test_installers.pyindex 2467c883..aaa15a2b 100644--- a/tests/scripts/test_installers.py+++ b/tests/scripts/test_installers.py@@ -17,6 +17,7 @@ FCC_COMMANDS = ("fcc-claude","fcc-codex","fcc-pi",+ "fcc-opencode","fcc-init","free-claude-code",)@@ -47,6 +48,7 @@ def _braced_body(text: str, declaration: str) -> str:def _posix_command(name: str) -> str:+ version = "1.18.18" if name == "opencode" else "1.0.0"help_output = (' echo " --extension, -e <path> Load an extension"\n'' echo " --models <patterns> Scope models"'@@ -59,7 +61,7 @@ if [ "$FAIL_STEP" = "{name}-verify" ]; thenexit 31fiif [ "${{1:-}}" = "--version" ]; then- echo "{name} 1.0.0"+ echo "{name} {version}"fiif [ "${{1:-}}" = "--help" ]; then{help_output}@@ -104,6 +106,7 @@ if [ "${{1:-}}" = "tool" ] && [ "${{2:-}}" = "install" ]; thencp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-desktop"cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-claude"cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-pi"+ cp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-opencode"if [ "$FAIL_STEP" != "fcc-missing" ]; thencp "$FAKE_FIXTURES/fcc-command.sh" "$FAKE_TOOL_BIN/fcc-codex"fi@@ -138,6 +141,7 @@ case "$*:$FAIL_STEP" in"init --global --auto-patch:rtk-init-claude") exit 73 ;;"init --global --codex:rtk-init-codex") exit 74 ;;"init --global --agent pi:rtk-init-pi") exit 75 ;;+ "init --global --opencode:rtk-init-opencode") exit 76 ;;esacif [ "${1:-}" = "--version" ]; thenecho "rtk 0.44.2"@@ -292,7 +296,7 @@ while [ "$#" -gt 0 ]; dodoneecho "download:$url" >> "$CALL_LOG"case "$url:$FAIL_STEP" in- *claude.ai*:claude-download|*chatgpt.com*:codex-download|*pi.dev*:pi-download|*rtk-ai*:rtk-download|*astral.sh*:uv-download)+ *claude.ai*:claude-download|*chatgpt.com*:codex-download|*pi.dev*:pi-download|*opencode.ai*:opencode-download|*rtk-ai*:rtk-download|*astral.sh*:uv-download)exit 41;;esac@@ -300,6 +304,7 @@ 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" ;;*rtk-ai*)if [ "$FAIL_STEP" = "rtk-install" ]; thenprintf 'invalid archive\n' > "$output"@@ -347,6 +352,16 @@ fimkdir -p "$pi_bin"cp "$FAKE_FIXTURES/pi-command.sh" "$pi_bin/pi"chmod +x "$pi_bin/pi"+""",+ )+ _write_executable(+ fixtures / "opencode-installer.sh",+ """#!/bin/sh+echo "opencode-install" >> "$CALL_LOG"+[ "$FAIL_STEP" = "opencode-install" ] && exit 25+mkdir -p "$HOME/.opencode/bin"+cp "$FAKE_FIXTURES/opencode-command.sh" "$HOME/.opencode/bin/opencode"+chmod +x "$HOME/.opencode/bin/opencode"""",)_write_executable(@@ -362,6 +377,7 @@ chmod +x "$HOME/.local/bin/uv"_write_executable(fixtures / "claude-command.sh", _posix_command("claude"))_write_executable(fixtures / "codex-command.sh", _posix_command("codex"))_write_executable(fixtures / "pi-command.sh", _posix_command("pi"))+ _write_executable(fixtures / "opencode-command.sh", _posix_command("opencode"))rtk_command = _posix_rtk_command().encode()with tarfile.open(fixtures / "rtk-x86_64-unknown-linux-musl.tar.gz", "w:gz"@@ -398,6 +414,7 @@ case "${1:-}" inesac""",)+ _write_executable(bin_dir / "opencode", _posix_command("opencode"))_write_executable(bin_dir / "sha256sum","""#!/bin/sh@@ -432,6 +449,7 @@ printf '%s %s\n' "$checksum" "$1"def test_install_sh_fresh_install_is_verified(posix_harness: PosixHarness) -> None:+ (posix_harness.bin_dir / "opencode").unlink()result = posix_harness.run()assert result.returncode == 0, result.stderr@@ -440,6 +458,7 @@ def test_install_sh_fresh_install_is_verified(posix_harness: PosixHarness) -> Noassert 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 calls.index("opencode-install") < calls.index("opencode:--version")assert calls.index("uv-install") < calls.index("uv:--version")assert any(call.startswith(@@ -479,8 +498,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("rtk:init --global --agent pi:telemetry=1") < calls.index(+ assert calls.index("rtk:init --global --opencode:telemetry=1") < calls.index("uv-install")assert (Path(posix_harness.env["HOME"]) / ".claude").is_dir()@@ -542,7 +562,7 @@ def test_install_sh_preserves_existing_rtk_and_configures_only_selected_agent() -> None:posix_harness.add_rtk()- result = posix_harness.run_interactive("n\ny\nn\ny\n")+ result = posix_harness.run_interactive("n\ny\nn\nn\ny\n")assert result.returncode == 0, result.stdoutassert "verifying it without updating it" in result.stdout@@ -589,13 +609,14 @@ def test_install_sh_stops_when_rtk_setup_fails(def test_install_sh_reprompts_then_installs_only_selected_agent(posix_harness: PosixHarness,) -> None:- result = posix_harness.run_interactive("n\nn\nn\nn\ny\nn\nn\n")+ result = posix_harness.run_interactive("n\nn\nn\nn\nn\ny\nn\nn\nn\n")assert result.returncode == 0, result.stdoutassert "Select at least one coding agent." in result.stdoutassert "Run Codex with: fcc-codex" in result.stdoutassert "Run Claude Code with: fcc-claude" not in result.stdoutassert "Run Pi with: fcc-pi" not in result.stdout+ assert "Run OpenCode with: fcc-opencode" not in result.stdoutcalls = posix_harness.calls()assert "codex-install:1" in callsassert not any("claude.ai" in call for call in calls)@@ -606,7 +627,7 @@ def test_install_sh_reprompts_then_installs_only_selected_agent(def test_install_sh_rejects_uninstalled_only_selection(posix_harness: PosixHarness,) -> None:- result = posix_harness.run_interactive("n\nn\ny\nn\n", fail_step="pi-skip")+ result = posix_harness.run_interactive("n\nn\ny\nn\nn\n", fail_step="pi-skip")assert result.returncode != 0assert "No selected coding agent was installed." in result.stdout@@ -842,6 +863,9 @@ def test_install_sh_replaces_prerelease_uv("pi-download","pi-install","pi-verify",+ "opencode-download",+ "opencode-install",+ "opencode-verify","uv-download","uv-install","uv-verify",@@ -855,6 +879,8 @@ def test_install_sh_stops_without_success_on_each_failure(posix_harness: PosixHarness,failure: str,) -> None:+ if failure.startswith("opencode-"):+ (posix_harness.bin_dir / "opencode").unlink()result = posix_harness.run(fail_step=failure)assert result.returncode != 0@@ -869,6 +895,9 @@ def test_install_sh_stops_without_success_on_each_failure("pi-download": "pi-install","pi-install": "pi:--version","pi-verify": "astral.sh",+ "opencode-download": "opencode-install",+ "opencode-install": "opencode:--version",+ "opencode-verify": "astral.sh","uv-download": "uv-install","uv-install": "uv:--version","uv-verify": "uv:tool install",@@ -1132,6 +1161,7 @@ def _windows_shortcut_icon(def _batch_client(name: str) -> str:+ version = "1.18.18" if name == "opencode" else "1.0.0"help_output = ("echo --extension, -e ^<path^> Load an extension\n""echo --models ^<patterns^> Scope models"@@ -1141,7 +1171,7 @@ def _batch_client(name: str) -> str:return f"""@echo offecho {name}:%*>>"%CALL_LOG%"if "%FAIL_STEP%"=="{name}-verify" exit /b 51-if "%1"=="--version" echo {name} 1.0.0+if "%1"=="--version" echo {name} {version}if "%1"=="--help" ({help_output})@@ -1178,6 +1208,7 @@ copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-server.cmd" >nulcopy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-desktop.cmd" >nulcopy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-claude.cmd" >nulcopy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-pi.cmd" >nul+copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-opencode.cmd" >nulif not "%FAIL_STEP%"=="fcc-missing" copy /y "%FAKE_FIXTURES%\fcc-command.cmd" "%FAKE_TOOL_BIN%\fcc-codex.cmd" >nulexit /b 0:update_shell@@ -1199,6 +1230,7 @@ if "%FAIL_STEP%"=="rtk-verify" if "%1"=="gain" exit /b 72if "%FAIL_STEP%"=="rtk-init-claude" if "%*"=="init --global --auto-patch" exit /b 73if "%FAIL_STEP%"=="rtk-init-codex" if "%*"=="init --global --codex" exit /b 74if "%FAIL_STEP%"=="rtk-init-pi" if "%*"=="init --global --agent pi" exit /b 75+if "%FAIL_STEP%"=="rtk-init-opencode" if "%*"=="init --global --opencode" exit /b 76if "%1"=="--version" echo rtk 0.44.2exit /b 0"""@@ -1298,6 +1330,9 @@ def powershell_harness(_batch_client("codex"), encoding="utf-8")(fixtures / "pi-command.cmd").write_text(_batch_client("pi"), encoding="utf-8")+ (fixtures / "opencode-command.cmd").write_text(+ _batch_client("opencode"), encoding="utf-8"+ )(fixtures / "rtk-command.cmd").write_text(_batch_rtk(), encoding="utf-8")(fixtures / "uv-command.cmd").write_text(_batch_uv("0.11.28"), encoding="utf-8")(fixtures / "fcc-command.cmd").write_text(@@ -1358,6 +1393,18 @@ Add-Content -LiteralPath $env:CALL_LOG -Value "uv-install"rtk_archive = fixtures / "rtk-x86_64-pc-windows-msvc.zip"with zipfile.ZipFile(rtk_archive, "w") as archive:archive.writestr("rtk.exe", b"fake RTK executable")+ for asset_name in (+ "opencode-windows-x64-baseline.zip",+ "opencode-windows-arm64.zip",+ ):+ with zipfile.ZipFile(+ fixtures / asset_name, "w", zipfile.ZIP_DEFLATED+ ) as archive:+ archive.write(+ Path(sys.executable).with_name("fcc-server.exe"),+ arcname="opencode.exe",+ )+ (bin_dir / "opencode.cmd").write_text(_batch_client("opencode"), encoding="utf-8")wrapper = tmp_path / "run-installer.ps1"wrapper.write_text(@@ -1372,6 +1419,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 "rtk-download" -and $Uri.Contains("rtk-ai/rtk")) -or($env:FAIL_STEP -eq "uv-download" -and $Uri.Contains("astral.sh"))) {@@ -1386,6 +1434,13 @@ function Invoke-RestMethod {elseif ($Uri.Contains("pi.dev")) {$source = Join-Path $env:FAKE_FIXTURES "pi-installer.ps1"}+ elseif ($Uri.Contains("opencode-windows-")) {+ if ($env:FAIL_STEP -eq "opencode-archive") {+ Set-Content -LiteralPath $OutFile -Value "not a zip"+ return+ }+ $source = Join-Path $env:FAKE_FIXTURES ([IO.Path]::GetFileName($Uri))+ }elseif ($Uri.EndsWith("rtk-x86_64-pc-windows-msvc.zip")) {$source = Join-Path $env:FAKE_FIXTURES "rtk-x86_64-pc-windows-msvc.zip"}@@ -1416,7 +1471,18 @@ function Get-Process {}}}-$installer = [scriptblock]::Create([IO.File]::ReadAllText($env:FCC_INSTALLER))+$installerSource = [IO.File]::ReadAllText($env:FCC_INSTALLER)+$nativeVersionProbe = ' $output = Invoke-Utf8NativeCapture -FilePath $OpenCodePath -Arguments @("--version")'+$fakeArchiveVersionProbe = @'+ $output = if ([IO.Path]::GetFileName($OpenCodePath) -eq "opencode.exe") {+ "opencode 1.18.18"+ }+ else {+ Invoke-Utf8NativeCapture -FilePath $OpenCodePath -Arguments @("--version")+ }+'@+$installerSource = $installerSource.Replace($nativeVersionProbe, $fakeArchiveVersionProbe.TrimEnd())+$installer = [scriptblock]::Create($installerSource)& $installer @args""",encoding="utf-8",@@ -1441,6 +1507,8 @@ $installer = [scriptblock]::Create([IO.File]::ReadAllText($env:FCC_INSTALLER))"FCC_PROCESS_MARKER": str(tmp_path / "fcc-process-ready"),"FCC_RUNNING_COMMAND": "","FCC_RUNNING_PHASE": "early",+ "PROCESSOR_ARCHITECTURE": "AMD64",+ "PROCESSOR_ARCHITEW6432": "","FAIL_STEP": "",})@@ -1452,6 +1520,7 @@ $installer = [scriptblock]::Create([IO.File]::ReadAllText($env:FCC_INSTALLER))def test_install_ps1_fresh_install_is_verified(powershell_harness: PowerShellHarness,) -> None:+ (powershell_harness.bin_dir / "opencode.cmd").unlink()result = powershell_harness.run()assert result.returncode == 0, result.stderr@@ -1460,6 +1529,7 @@ 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 calls.index("uv-install") < calls.index("uv:--version")assert any(call.startswith(@@ -1501,6 +1571,34 @@ def test_install_ps1_fresh_install_is_verified().is_file()+def test_install_ps1_selects_official_opencode_arm64_archive(+ powershell_harness: PowerShellHarness,+) -> None:+ (powershell_harness.bin_dir / "opencode.cmd").unlink()+ powershell_harness.env["PROCESSOR_ARCHITEW6432"] = "ARM64"++ result = powershell_harness.run()++ assert result.returncode == 0, result.stderr+ assert any(+ call.endswith("opencode-windows-arm64.zip")+ for call in powershell_harness.calls()+ )+++def test_install_ps1_rejects_unsupported_opencode_architecture(+ powershell_harness: PowerShellHarness,+) -> None:+ (powershell_harness.bin_dir / "opencode.cmd").unlink()+ powershell_harness.env["PROCESSOR_ARCHITEW6432"] = "X86"++ result = powershell_harness.run()++ assert result.returncode != 0+ assert "does not provide a supported Windows release" in result.stderr+ assert not any("anomalyco/opencode" in call for call in powershell_harness.calls())++def test_install_ps1_preserves_existing_rtk_and_configures_selected_agents(powershell_harness: PowerShellHarness,) -> None:@@ -1518,6 +1616,7 @@ 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()@@ -1805,6 +1904,9 @@ def test_install_ps1_replaces_prerelease_uv("pi-download","pi-install","pi-verify",+ "opencode-download",+ "opencode-archive",+ "opencode-verify","uv-download","uv-install","uv-verify",@@ -1818,6 +1920,8 @@ def test_install_ps1_stops_without_success_on_each_failure(powershell_harness: PowerShellHarness,failure: str,) -> None:+ if failure in {"opencode-download", "opencode-archive"}:+ (powershell_harness.bin_dir / "opencode.cmd").unlink()result = powershell_harness.run(fail_step=failure)assert result.returncode != 0@@ -1832,6 +1936,9 @@ def test_install_ps1_stops_without_success_on_each_failure("pi-download": "pi-install","pi-install": "pi:--version","pi-verify": "astral.sh",+ "opencode-download": "uv-install",+ "opencode-archive": "uv-install",+ "opencode-verify": "astral.sh","uv-download": "uv-install","uv-install": "uv:--version","uv-verify": "uv:tool install",@@ -2023,10 +2130,10 @@ Invoke-DownloadedPowerShellInstaller `@pytest.mark.parametrize(("answers", "expected", "expected_messages"),[- (("", "", "", ""), "True,True,True,False", ()),+ (("", "", "", "", ""), "True,True,True,True,False", ()),(- ("maybe", "n", "n", "n", "n", "y", "n", "y"),- "False,True,False,True",+ ("maybe", "n", "n", "n", "n", "n", "y", "n", "n", "y"),+ "False,True,False,False,True",("Please answer Y or N.", "Select at least one coding agent."),),],@@ -2048,6 +2155,7 @@ $script:AnswerIndex = 0$script:InstallClaudeCode = $true$script:InstallCodex = $true$script:InstallPi = $true+$script:InstallOpenCode = $true$script:EnableRtk = $falsefunction Read-Host {{param([string] $Prompt)@@ -2058,7 +2166,7 @@ function Read-Host {{function Read-YesNo {{{read_yes_no}}}function Select-CodingAgents {{{select_agents}}}Select-CodingAgents-Write-Output "selection:$($script:InstallClaudeCode),$($script:InstallCodex),$($script:InstallPi),$($script:EnableRtk)"+Write-Output "selection:$($script:InstallClaudeCode),$($script:InstallCodex),$($script:InstallPi),$($script:InstallOpenCode),$($script:EnableRtk)""""result = subprocess.run(@@ -2083,12 +2191,14 @@ $ErrorActionPreference = "Stop"$script:InstallClaudeCode = $false$script:InstallCodex = $true$script:InstallPi = $false+$script:InstallOpenCode = $false$script:PiAvailable = $false$script:Calls = @()function Write-Step {{ param([string] $Message) }}function Ensure-ClaudeCode {{ $script:Calls += "claude" }}function Ensure-Codex {{ $script:Calls += "codex" }}function Ensure-Pi {{ $script:Calls += "pi"; $script:PiAvailable = $true }}+function Ensure-OpenCode {{ $script:Calls += "opencode" }}function Ensure-SelectedCodingAgents {{{body}}}Ensure-SelectedCodingAgentsWrite-Output "calls:$($script:Calls -join ',')"@@ -2117,6 +2227,7 @@ $script:EnableRtk = $true$script:InstallClaudeCode = $false$script:InstallCodex = $true$script:InstallPi = $true+$script:InstallOpenCode = $false$script:PiAvailable = $false$script:Calls = @()function Write-Step {{ param([string] $Message) }}@@ -2150,11 +2261,13 @@ $ErrorActionPreference = "Stop"$script:InstallClaudeCode = $false$script:InstallCodex = $false$script:InstallPi = $true+$script:InstallOpenCode = $false$script:PiAvailable = $falsefunction Write-Step {{ param([string] $Message) }}function Ensure-ClaudeCode {{ }}function Ensure-Codex {{ }}function Ensure-Pi {{ }}+function Ensure-OpenCode {{ }}function Ensure-SelectedCodingAgents {{{body}}}Ensure-SelectedCodingAgents"""diff --git a/tests/scripts/test_uninstallers.py b/tests/scripts/test_uninstallers.pyindex 52e3f393..60b4246e 100644--- a/tests/scripts/test_uninstallers.py+++ b/tests/scripts/test_uninstallers.py@@ -12,6 +12,7 @@ FCC_COMMANDS = ("fcc-claude","fcc-codex","fcc-pi",+ "fcc-opencode","fcc-init","free-claude-code",)@@ -132,6 +133,7 @@ def posix_uninstall_harness(tmp_path: Path) -> PosixUninstallHarness:_write_executable(bin_dir / "claude", "#!/bin/sh\nexit 0\n")_write_executable(bin_dir / "codex", "#!/bin/sh\nexit 0\n")_write_executable(bin_dir / "pi", "#!/bin/sh\nexit 0\n")+ _write_executable(bin_dir / "opencode", "#!/bin/sh\nexit 0\n")_write_executable(bin_dir / "pgrep","""#!/bin/sh@@ -163,7 +165,7 @@ if [ "${1:-}" = "tool" ] && [ "${2:-}" = "uninstall" ]; thenecho 'Tool `free-claude-code` is not installed' >&2exit 2fi- for name in fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-init free-claude-code; do+ for name in fcc-desktop fcc-server fcc-claude fcc-codex fcc-pi fcc-opencode fcc-init free-claude-code; do/bin/rm -f "$FAKE_TOOL_BIN/$name"doneecho "Uninstalled free-claude-code"@@ -232,6 +234,7 @@ def test_uninstall_sh_removes_and_verifies_only_fcc(assert (posix_uninstall_harness.bin_dir / "claude").exists()assert (posix_uninstall_harness.bin_dir / "codex").exists()assert (posix_uninstall_harness.bin_dir / "pi").exists()+ assert (posix_uninstall_harness.bin_dir / "opencode").exists()assert posix_uninstall_harness.calls() == ["uv:tool dir --bin","uv:tool uninstall free-claude-code",@@ -477,7 +480,7 @@ def powershell_uninstall_harness((tool_bin / f"{name}.cmd").write_text("@echo off\nexit /b 0\n", encoding="utf-8")- for name in ("claude", "codex", "pi"):+ for name in ("claude", "codex", "pi", "opencode"):(bin_dir / f"{name}.cmd").write_text("@echo off\nexit /b 0\n", encoding="utf-8")uv_commands = " ".join(FCC_COMMANDS)@@ -588,6 +591,7 @@ def test_uninstall_ps1_removes_and_verifies_only_fcc(assert (powershell_uninstall_harness.bin_dir / "claude.cmd").exists()assert (powershell_uninstall_harness.bin_dir / "codex.cmd").exists()assert (powershell_uninstall_harness.bin_dir / "pi.cmd").exists()+ assert (powershell_uninstall_harness.bin_dir / "opencode.cmd").exists()assert powershell_uninstall_harness.calls() == ["uv:tool dir --bin","uv:tool uninstall free-claude-code",diff --git a/uv.lock b/uv.lockindex 23a5241a..f0a6b297 100644--- a/uv.lock+++ b/uv.lock@@ -607,7 +607,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "5.4.0"+version = "5.5.0"source = { editable = "." }dependencies = [{ name = "aiohttp" },