# Official OpenCode v2 Universal Installer for Chuhai365 API (Windows) # Portal: https://opencode.chuhai365.cc # Gateway: https://api.chuhai365.cc/v1 # Supports: Windows PowerShell 5.1 & PowerShell 7 (x64 / ARM64) # 100% No-VPN workflow: official OpenCode binaries & config both served via chuhai365.cc # # Quick usage: # irm https://opencode.chuhai365.cc/install.ps1 | iex # & ([scriptblock]::Create((irm https://opencode.chuhai365.cc/install.ps1))) -InstallCli # $env:NEWAPI_API_KEY='sk-xxx'; irm https://opencode.chuhai365.cc/install.ps1 | iex # & ([scriptblock]::Create((irm https://opencode.chuhai365.cc/install.ps1))) -Check # & ([scriptblock]::Create((irm https://opencode.chuhai365.cc/install.ps1))) -FixProxy # & ([scriptblock]::Create((irm https://opencode.chuhai365.cc/install.ps1))) -Uninstall # # Pure ASCII source (no UTF-8 BOM, no top-level param() block) for PowerShell 5.1 safety. Set-StrictMode -Version 1.0 $ErrorActionPreference = 'Stop' try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) } catch { } try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072 } catch { } try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 12288 } catch { } $script:ScriptVersion = '1.0.0' $script:OpenCodeVersion = '2.4.3' $script:DefaultAuthOrigin = 'https://opencode.chuhai365.cc' $script:DefaultBaseUrl = 'https://api.chuhai365.cc/v1' $script:DefaultModel = 'chuhai365-claude/claude-sonnet-5-5' $script:ManagedProviders = @('chuhai365-claude', 'chuhai365-openai', 'chuhai365-gemini', 'chuhai365-grok', 'chuhai365-other') $script:NonChatPattern = '(?i)(dall-e|whisper|tts|embedding|rerank|moderation|sora|audio|realtime|transcribe|flux|seedance|gpt-image|grok-imagine|nano-banana|-image($|[-._])|image-generation|imagen|veo-|kling|runway)' $script:FallbackModels = @( 'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5', 'claude-fable-5-2', 'gpt-6.2-sol', 'gpt-6.2-astra', 'gpt-6.1-terra', 'gpt-6-luna', 'o3', 'o4-mini', 'gemini-4-carbon', 'gemini-4-neon', 'gemini-4-hydrogen', 'gemini-4-argon', 'gemini-3.8-flash', 'gemini-3.5-flash-lite', 'grok-4.7', 'grok-4.6', 'grok-4.20-reasoning', 'grok-4.20-non-reasoning' ) $script:KnownMeta = @{ 'claude-opus-5-5' = @('Claude Opus 5.5', @('text','image','pdf'), 200000, 32000, @('low','medium','high','max')) 'claude-sonnet-5-5' = @('Claude Sonnet 5.5', @('text','image','pdf'), 200000, 32000, @('low','medium','high')) 'claude-haiku-5-5' = @('Claude Haiku 5.5', @('text','image','pdf'), 200000, 16384, @('low','medium','high')) 'claude-fable-5-2' = @('Claude Fable 5.2', @('text','image','pdf'), 200000, 32000, @('low','medium','high','max')) 'claude-fable-5-1' = @('Claude Fable 5.1', @('text','image','pdf'), 200000, 32000, @('low','medium','high')) 'claude-fable-5' = @('Claude Fable 5', @('text','image','pdf'), 200000, 32000, @('low','medium','high')) 'gpt-6.2-astra' = @('GPT-6.2 Astra', @('text','image'), 1000000, 64000, @('low','medium','high','xhigh')) 'gpt-6.2-sol' = @('GPT-6.2 Sol', @('text','image'), 400000, 64000, @('low','medium','high','xhigh')) 'gpt-6.1-terra' = @('GPT-6.1 Terra', @('text','image'), 400000, 32000, @('low','medium','high')) 'gpt-6-luna' = @('GPT-6 Luna', @('text','image'), 200000, 32000, @('low','medium','high')) 'o3' = @('OpenAI o3', @('text','image'), 200000, 32000, @('low','medium','high')) 'o4-mini' = @('OpenAI o4-mini', @('text','image'), 200000, 32000, @('low','medium','high')) 'gemini-4-carbon' = @('Gemini 4 Carbon', @('text','image','pdf'),1000000, 65536, @('low','medium','high')) 'gemini-4-neon' = @('Gemini 4 Neon', @('text','image','pdf'),1000000, 65536, @('low','medium','high')) 'gemini-4-hydrogen' = @('Gemini 4 Hydrogen', @('text','image','pdf'),1000000, 65536, @('low','medium','high')) 'gemini-4-argon' = @('Gemini 4 Argon', @('text','image','pdf'),1000000, 65536, @('low','medium','high')) 'gemini-3.8-flash' = @('Gemini 3.8 Flash', @('text','image','pdf'),1000000, 65536, @('low','medium','high')) 'gemini-3.5-flash-lite' = @('Gemini 3.5 Flash Lite', @('text','image'), 1000000, 32768, $null) 'grok-4.7' = @('Grok 4.7', @('text','image'), 256000, 32768, @('low','medium','high')) 'grok-4.6' = @('Grok 4.6', @('text','image'), 256000, 32768, @('low','medium','high')) 'grok-4.20-reasoning' = @('Grok 4.20 Reasoning', @('text','image'), 256000, 32768, @('low','medium','high')) 'grok-4.20-non-reasoning' = @('Grok 4.20 Non-Reasoning', @('text','image'), 256000, 32768, $null) } function U([string]$Escaped) { if ([string]::IsNullOrEmpty($Escaped)) { return '' } return [regex]::Unescape($Escaped) } function Say([string]$m) { Write-Host (' ' + $m) } function Say-Step([string]$m) { Write-Host ''; Write-Host ('==> ' + $m) -ForegroundColor Cyan } function Say-Ok([string]$m) { Write-Host (' [OK] ' + $m) -ForegroundColor Green } function Say-Warn([string]$m) { Write-Host (' [!] ' + $m) -ForegroundColor Yellow } function Say-Err([string]$m) { Write-Host (' [X] ' + $m) -ForegroundColor Red } function Fail([string]$m) { throw ('CHUHAI_FAIL::' + $m) } function Mask-Secret([string]$s) { if ([string]::IsNullOrEmpty($s)) { return (U '(\u672a\u63d0\u4f9b)') } if ($s.Length -le 12) { return '****' } return ($s.Substring(0, 8) + '...' + $s.Substring($s.Length - 4)) } function Normalize-BaseUrl([string]$u) { if ([string]::IsNullOrWhiteSpace($u)) { return $script:DefaultBaseUrl } $clean = $u.Trim().TrimEnd('/') if ($clean -ieq 'https://api.chuhai365.cc') { return 'https://api.chuhai365.cc/v1' } return $clean } function Resolve-HomeDir { try { $p = [Environment]::GetFolderPath('UserProfile') if (-not [string]::IsNullOrWhiteSpace($p)) { return $p } } catch { } if ($env:USERPROFILE) { return [string]$env:USERPROFILE } if ($env:HOME) { return [string]$env:HOME } Fail (U '\u65e0\u6cd5\u89e3\u6790\u5f53\u524d\u7528\u6237\u4e3b\u76ee\u5f55\u3002') } $script:UserHome = Resolve-HomeDir $script:DefaultConfigDir = if ($env:OPENCODE_CONFIG_DIR) { [string]$env:OPENCODE_CONFIG_DIR } elseif ($env:XDG_CONFIG_HOME) { Join-Path ([string]$env:XDG_CONFIG_HOME) 'opencode' } else { Join-Path (Join-Path $script:UserHome '.config') 'opencode' } $script:DefaultBinDir = if ($env:OPENCODE_INSTALL_DIR) { [string]$env:OPENCODE_INSTALL_DIR } else { Join-Path (Join-Path $script:UserHome '.opencode') 'bin' } $script:Opt = [pscustomobject]@{ ApiKey = '' AuthOrigin = if ($env:CHUHAI_AUTH_ORIGIN) { ([string]$env:CHUHAI_AUTH_ORIGIN).TrimEnd('/') } else { $script:DefaultAuthOrigin } BaseUrl = if ($env:NEWAPI_BASE_URL) { Normalize-BaseUrl ([string]$env:NEWAPI_BASE_URL) } else { $script:DefaultBaseUrl } Model = if ($env:CHUHAI_MODEL) { [string]$env:CHUHAI_MODEL } else { $script:DefaultModel } Client = if ($env:CHUHAI_CLIENT) { [string]$env:CHUHAI_CLIENT } else { 'desktop' } ConfigDir = $script:DefaultConfigDir BinDir = $script:DefaultBinDir ModelExplicit = [bool]$env:CHUHAI_MODEL BaseExplicit = [bool]$env:NEWAPI_BASE_URL KeepFree = $false KeepFreeExplicit = $false InstallCli = $false NoPath = $false Paste = $false Check = $false FixProxy = $false Uninstall = $false NoVerify = $false Help = $false BadArgs = @() } foreach ($ev in @($env:NEWAPI_API_KEY, $env:CHUHAI_API_KEY, $env:OPENCODE_CHUHAI_API_KEY)) { if (-not $script:Opt.ApiKey -and -not [string]::IsNullOrWhiteSpace([string]$ev)) { $script:Opt.ApiKey = [string]$ev } } function Parse-CliArgs([object[]]$RawArgs) { if (-not $RawArgs -or $RawArgs.Count -eq 0) { return } for ($i = 0; $i -lt $RawArgs.Count; $i++) { $arg = [string]$RawArgs[$i] if ([string]::IsNullOrWhiteSpace($arg)) { continue } $name = $arg $inlineVal = $null if ($arg -match '^(--?[A-Za-z0-9_-]+)[:=](.*)$') { $name = $Matches[1] $inlineVal = $Matches[2] } switch -Regex ($name) { '^--?(?i)(ApiKey|Key)$' { if ($null -ne $inlineVal) { $script:Opt.ApiKey = $inlineVal } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.ApiKey = [string]$RawArgs[$i] } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)(BaseUrl|ApiBase|Gateway|Url)$' { if ($null -ne $inlineVal) { $script:Opt.BaseUrl = Normalize-BaseUrl $inlineVal; $script:Opt.BaseExplicit = $true } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.BaseUrl = Normalize-BaseUrl ([string]$RawArgs[$i]); $script:Opt.BaseExplicit = $true } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)AuthOrigin$' { if ($null -ne $inlineVal) { $script:Opt.AuthOrigin = $inlineVal.TrimEnd('/') } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.AuthOrigin = ([string]$RawArgs[$i]).TrimEnd('/') } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)Model$' { if ($null -ne $inlineVal) { $script:Opt.Model = $inlineVal; $script:Opt.ModelExplicit = $true } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.Model = [string]$RawArgs[$i]; $script:Opt.ModelExplicit = $true } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)Client$' { if ($null -ne $inlineVal) { $script:Opt.Client = $inlineVal.ToLowerInvariant() } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.Client = ([string]$RawArgs[$i]).ToLowerInvariant() } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)ConfigDir$' { if ($null -ne $inlineVal) { $script:Opt.ConfigDir = $inlineVal } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.ConfigDir = [string]$RawArgs[$i] } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)(InstallCli|Install-Cli)$' { $script:Opt.InstallCli = $true; $script:Opt.Client = 'cli' } '^--?(?i)(KeepFreeModels|Keep-Free-Models)$' { $script:Opt.KeepFree = $true; $script:Opt.KeepFreeExplicit = $true } '^--?(?i)(NoPath|NoModifyPath)$' { $script:Opt.NoPath = $true } '^--?(?i)Paste$' { $script:Opt.Paste = $true } '^--?(?i)(Check|Status)$' { $script:Opt.Check = $true } '^--?(?i)(FixProxy|Fix-Proxy|Doctor)$' { $script:Opt.FixProxy = $true } '^--?(?i)Uninstall$' { $script:Opt.Uninstall = $true } '^--?(?i)(NoVerify|No-Verify|Offline)$' { $script:Opt.NoVerify = $true } '^--?(?i)(Help|H|\?)$' { $script:Opt.Help = $true } default { $script:Opt.BadArgs += $arg } } } } function Show-Usage { Write-Host ((U '\u51fa\u6d77365 API \u00b7 \u5b98\u65b9 OpenCode v') + $script:OpenCodeVersion + (U ' \u56fd\u5185\u514d VPN \u4e00\u952e\u63a5\u5165\u811a\u672c (Windows) v') + $script:ScriptVersion) -ForegroundColor Cyan Write-Host ((U ' \u9ed8\u8ba4\u7f51\u5173: ') + $script:DefaultBaseUrl) Write-Host ((U ' \u9ed8\u8ba4\u6a21\u578b: ') + $script:DefaultModel) Write-Host '' Write-Host (U '\u5e38\u7528\u7528\u6cd5:') -ForegroundColor Yellow Write-Host ' 1) irm https://opencode.chuhai365.cc/install.ps1 | iex' Write-Host ' 2) & ([scriptblock]::Create((irm https://opencode.chuhai365.cc/install.ps1))) -InstallCli' Write-Host ' 3) $env:NEWAPI_API_KEY=''sk-xxx''; irm https://opencode.chuhai365.cc/install.ps1 | iex' Write-Host ' 4) & ([scriptblock]::Create((irm https://opencode.chuhai365.cc/install.ps1))) -Check' Write-Host ' 5) & ([scriptblock]::Create((irm https://opencode.chuhai365.cc/install.ps1))) -FixProxy' Write-Host ' 6) & ([scriptblock]::Create((irm https://opencode.chuhai365.cc/install.ps1))) -Uninstall' Write-Host '' Write-Host (U '\u53ef\u9009\u53c2\u6570:') -ForegroundColor Yellow Write-Host ' -ApiKey / -Key API Key' Write-Host ' -Model Default model (e.g. chuhai365-claude/claude-sonnet-5-5)' Write-Host ' -InstallCli Download & install official OpenCode CLI v2.4.3 without VPN' Write-Host ' -KeepFreeModels Keep built-in opencode/* free models' Write-Host ' -ConfigDir Custom config directory (default %USERPROFILE%\.config\opencode)' Write-Host ' -Paste Read key in terminal instead of opening browser' Write-Host ' -Check / -Status Read-only diagnostics' Write-Host ' -FixProxy / -Doctor Diagnose and clean dead proxy env vars' Write-Host ' -Uninstall Remove chuhai365 providers and restore original config' Write-Host ' -NoVerify / -Offline Skip online verification and write standard catalog' } # ---------------------------------------------------------------- File & Crypto Helpers function Get-Sha256Hex([string]$Text) { $sha = [System.Security.Cryptography.SHA256]::Create() try { $bytes = [Text.Encoding]::UTF8.GetBytes($Text) $hash = $sha.ComputeHash($bytes) return ([BitConverter]::ToString($hash)).Replace('-', '').ToLowerInvariant() } finally { $sha.Dispose() } } function Get-FileSha256Hex([string]$Path) { $sha = [System.Security.Cryptography.SHA256]::Create() $fs = [IO.File]::OpenRead($Path) try { $hash = $sha.ComputeHash($fs) return ([BitConverter]::ToString($hash)).Replace('-', '').ToLowerInvariant() } finally { $fs.Dispose() $sha.Dispose() } } function Write-Utf8NoBomAtomic([string]$Path, [string]$Text) { $dir = Split-Path -Parent $Path if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } $tmp = $Path + '.' + [Guid]::NewGuid().ToString('N') + '.tmp' $made = $false try { $enc = New-Object System.Text.UTF8Encoding($false) $bytes = $enc.GetBytes($Text) $fs = [IO.File]::Open($tmp, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None) $made = $true try { $fs.Write($bytes, 0, $bytes.Length) $fs.Flush() } finally { $fs.Dispose() } if ([IO.File]::Exists($Path)) { try { [IO.File]::Replace($tmp, $Path, [NullString]::Value) } catch { [IO.File]::Delete($Path); [IO.File]::Move($tmp, $Path) } } else { [IO.File]::Move($tmp, $Path) } $made = $false } finally { if ($made -and [IO.File]::Exists($tmp)) { try { [IO.File]::Delete($tmp) } catch { } } } } function Read-Utf8NoBom([string]$Path) { if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return '' } $bytes = [IO.File]::ReadAllBytes($Path) $text = [Text.Encoding]::UTF8.GetString($bytes) if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) } return $text } function ConvertTo-OrderedMap($Obj) { $ht = [ordered]@{} if ($null -eq $Obj) { return $ht } if ($Obj -is [System.Collections.IDictionary]) { foreach ($k in $Obj.Keys) { $ht[[string]$k] = $Obj[$k] } return $ht } foreach ($p in $Obj.PSObject.Properties) { $ht[[string]$p.Name] = $p.Value } return $ht } function Test-TcpPort([string]$HostName, [int]$Port, [int]$TimeoutMs = 700) { $tcp = New-Object System.Net.Sockets.TcpClient try { $ar = $tcp.BeginConnect($HostName, $Port, $null, $null) if (-not $ar.AsyncWaitHandle.WaitOne($TimeoutMs, $false)) { return $false } $tcp.EndConnect($ar) return $true } catch { return $false } finally { try { $tcp.Close() } catch { } } } function Open-ChuhaiUrl([string]$Url) { try { $progId = '' foreach ($regPath in @( 'HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoiceLatest\ProgId', 'HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice' )) { if (Test-Path -LiteralPath $regPath) { $v = (Get-ItemProperty -LiteralPath $regPath -Name 'ProgId' -ErrorAction SilentlyContinue).ProgId if (-not [string]::IsNullOrWhiteSpace([string]$v)) { $progId = [string]$v; break } } } $exe = '' if ($progId) { foreach ($clsRoot in @('HKCU:\Software\Classes', 'HKLM:\Software\Classes')) { $cmdKey = Join-Path $clsRoot ($progId + '\shell\open\command') if (Test-Path -LiteralPath $cmdKey) { $rawCmd = [string](Get-ItemProperty -LiteralPath $cmdKey -ErrorAction SilentlyContinue).'(default)' if ($rawCmd -match '^"([^"]+\.exe)"' -or $rawCmd -match '^([^\s]+\.exe)') { $cand = $Matches[1] if ($cand -notmatch '(?i)(explorer|rundll32|LaunchWinApp)\.exe$' -and (Test-Path -LiteralPath $cand -PathType Leaf)) { $exe = $cand; break } } } } } if (-not $exe) { foreach ($browser in @('msedge.exe', 'chrome.exe', 'firefox.exe')) { foreach ($apRoot in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths')) { $ap = Join-Path $apRoot $browser if (Test-Path -LiteralPath $ap) { $p = [string](Get-ItemProperty -LiteralPath $ap -ErrorAction SilentlyContinue).'(default)' if ($p) { $p = $p.Trim('"') } if ($p -and (Test-Path -LiteralPath $p -PathType Leaf)) { $exe = $p; break } } } if ($exe) { break } } } if ($exe) { $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $exe $psi.Arguments = '"' + $Url + '"' $psi.UseShellExecute = $false [void][System.Diagnostics.Process]::Start($psi) return $true } Start-Process -FilePath $Url -ErrorAction Stop return $true } catch { return $false } } # ---------------------------------------------------------------- Model Classification & V2 Config function Classify-Model([string]$ModelId) { $c = ([string]$ModelId).Trim() if ([string]::IsNullOrEmpty($c)) { return '' } if ($c -match $script:NonChatPattern) { return '' } $l = $c.ToLowerInvariant() if (($l -match '(^|/)(gpt-|codex|o[134]($|[-._])|chatgpt-)') -or ($l.Contains('codex'))) { return 'chuhai365-openai' } if ($l -match '(^|/)gemini-') { return 'chuhai365-gemini' } if ($l -match '(^|/)grok-') { return 'chuhai365-grok' } if ($l -match '(claude|anthropic|opus|sonnet|haiku|fable)') { return 'chuhai365-claude' } return 'chuhai365-other' } function Build-ModelEntry([string]$ModelId, [string]$ProviderId) { $baseKey = $ModelId.ToLowerInvariant() -replace '\[1m\]$', '' $meta = $null if ($script:KnownMeta.ContainsKey($ModelId)) { $meta = $script:KnownMeta[$ModelId] } elseif ($script:KnownMeta.ContainsKey($baseKey)) { $meta = $script:KnownMeta[$baseKey] } if ($null -ne $meta) { $name = [string]$meta[0] $inputs = @($meta[1]) $ctx = [int]$meta[2] $outLim = [int]$meta[3] $efforts = $meta[4] if ($ModelId.ToLowerInvariant().EndsWith('[1m]')) { $name = $name + ' (1M)' $ctx = 1000000 } } else { $name = $ModelId $inputs = if ($ProviderId -eq 'chuhai365-claude' -or $ProviderId -eq 'chuhai365-gemini') { @('text','image','pdf') } else { @('text','image') } $ctx = if ($ProviderId -eq 'chuhai365-gemini' -or $ModelId.ToLowerInvariant().Contains('[1m]')) { 1000000 } else { 200000 } $outLim = 32000 $efforts = if ($ModelId -match '(?i)(opus|sonnet|fable|gpt-6|o[134]|codex|gemini-4|reasoning|r1|thinking)') { @('low','medium','high') } else { $null } } $caps = [ordered]@{ tools = $true input = $inputs output = @('text') } if ($null -ne $efforts) { $caps['reasoning'] = [ordered]@{ supported = $true effort = @($efforts) } } return [ordered]@{ name = $name capabilities = $caps limit = [ordered]@{ context = $ctx; output = $outLim } } } function Test-SameFreePolicy($Item) { if ($null -eq $Item) { return $false } $ht = ConvertTo-OrderedMap $Item return ($ht['action'] -eq 'integration.use' -and $ht['resource'] -eq 'opencode' -and $ht['effect'] -eq 'deny') } function Apply-OpenCodeConfig([string]$ConfigDir, [string]$BaseUrl, [string]$ReqModel, [bool]$KeepFree, [string]$ApiKey, [string[]]$Models) { if (-not (Test-Path -LiteralPath $ConfigDir)) { New-Item -ItemType Directory -Path $ConfigDir -Force | Out-Null } $cfgPath = Join-Path $ConfigDir 'opencode.json' $jsoncPath = Join-Path $ConfigDir 'opencode.jsonc' $statePath = Join-Path $ConfigDir '.chuhai365-opencode-state.json' $ts = (Get-Date).ToString('yyyyMMdd-HHmmss') $prevState = [ordered]@{} if (Test-Path -LiteralPath $statePath -PathType Leaf) { try { $prevState = ConvertTo-OrderedMap ((Read-Utf8NoBom $statePath) | ConvertFrom-Json) } catch { $prevState = [ordered]@{} } } $cfg = [ordered]@{} $cfgBackup = '' if (Test-Path -LiteralPath $cfgPath -PathType Leaf) { $cfgBackup = $cfgPath + '.bak.chuhai365.' + $ts Copy-Item -LiteralPath $cfgPath -Destination $cfgBackup -Force try { $cfg = ConvertTo-OrderedMap ((Read-Utf8NoBom $cfgPath) | ConvertFrom-Json) } catch { $cfg = [ordered]@{} } } $hadPrevModel = $cfg.Contains('model') $prevModelVal = if ($hadPrevModel) { $cfg['model'] } else { $null } $hadPrevUpdate = $cfg.Contains('update') $prevUpdateVal = if ($hadPrevUpdate) { $cfg['update'] } else { $null } $modelList = if ($Models -and $Models.Count -gt 0) { $Models } else { $script:FallbackModels } $buckets = [ordered]@{} foreach ($mp in $script:ManagedProviders) { $buckets[$mp] = [ordered]@{} } foreach ($mid in $modelList) { $p = Classify-Model $mid if (-not $p) { continue } if (-not $buckets[$p].Contains($mid)) { $buckets[$p][$mid] = Build-ModelEntry $mid $p } } $totalFound = 0 foreach ($mp in $script:ManagedProviders) { $totalFound += $buckets[$mp].Count } if ($totalFound -eq 0) { foreach ($mid in $script:FallbackModels) { $p = Classify-Model $mid if ($p -and -not $buckets[$p].Contains($mid)) { $buckets[$p][$mid] = Build-ModelEntry $mid $p } } } $provs = if ($cfg.Contains('providers') -and $null -ne $cfg['providers']) { ConvertTo-OrderedMap $cfg['providers'] } else { [ordered]@{} } foreach ($mp in $script:ManagedProviders) { if ($provs.Contains($mp)) { $provs.Remove($mp) } } $specs = @( @('chuhai365-claude', (U '\u51fa\u6d77365 \u00b7 Claude'), '@opencode/ai/providers/anthropic', [ordered]@{ baseURL = $BaseUrl; apiKey = $ApiKey }), @('chuhai365-openai', (U '\u51fa\u6d77365 \u00b7 OpenAI'), '@opencode/ai/providers/openai/responses', [ordered]@{ baseURL = $BaseUrl; apiKey = $ApiKey; transport = 'http' }), @('chuhai365-gemini', (U '\u51fa\u6d77365 \u00b7 Gemini'), '@opencode/ai/providers/openai-compatible',[ordered]@{ baseURL = $BaseUrl; apiKey = $ApiKey }), @('chuhai365-grok', (U '\u51fa\u6d77365 \u00b7 Grok'), '@opencode/ai/providers/openai-compatible',[ordered]@{ baseURL = $BaseUrl; apiKey = $ApiKey }), @('chuhai365-other', (U '\u51fa\u6d77365 \u00b7 \u5176\u4ed6\u6a21\u578b'), '@opencode/ai/providers/openai-compatible',[ordered]@{ baseURL = $BaseUrl; apiKey = $ApiKey }) ) $activeCounts = [ordered]@{} $totalModels = 0 foreach ($sp in $specs) { $pid = $sp[0] if ($buckets[$pid].Count -gt 0) { $provs[$pid] = [ordered]@{ name = $sp[1] package = $sp[2] settings = $sp[3] models = $buckets[$pid] } $activeCounts[$pid] = $buckets[$pid].Count $totalModels += $buckets[$pid].Count } } $resolvedModel = '' if (-not [string]::IsNullOrWhiteSpace($ReqModel)) { if ($ReqModel.Contains('/')) { $idx = $ReqModel.IndexOf('/') $rp = $ReqModel.Substring(0, $idx) $rm = $ReqModel.Substring($idx + 1) if ($buckets.Contains($rp) -and $buckets[$rp].Contains($rm)) { $resolvedModel = $rp + '/' + $rm } else { $bp = Classify-Model $rm if ($bp -and $buckets[$bp].Contains($rm)) { $resolvedModel = $bp + '/' + $rm } } } else { $bp2 = Classify-Model $ReqModel if ($bp2 -and $buckets[$bp2].Contains($ReqModel)) { $resolvedModel = $bp2 + '/' + $ReqModel } } } if (-not $resolvedModel) { foreach ($pref in @( 'chuhai365-claude/claude-sonnet-5-5', 'chuhai365-claude/claude-opus-5-5', 'chuhai365-openai/gpt-6.2-sol', 'chuhai365-gemini/gemini-4-neon', 'chuhai365-grok/grok-4.7' )) { $parts = $pref.Split('/') if ($buckets[$parts[0]].Contains($parts[1])) { $resolvedModel = $pref; break } } } if (-not $resolvedModel) { foreach ($mp in $script:ManagedProviders) { if ($buckets[$mp].Count -gt 0) { foreach ($k in $buckets[$mp].Keys) { $resolvedModel = $mp + '/' + $k; break } break } } } $cfg['$schema'] = 'https://opencode.ai/config.json' $cfg['update'] = 'disable' if ($resolvedModel) { $cfg['model'] = $resolvedModel } $cfg['providers'] = $provs $pols = New-Object System.Collections.Generic.List[object] if ($cfg.Contains('policies') -and $null -ne $cfg['policies']) { foreach ($item in @($cfg['policies'])) { if (-not (Test-SameFreePolicy $item)) { [void]$pols.Add($item) } } } if (-not $KeepFree) { [void]$pols.Add([ordered]@{ action = 'integration.use'; resource = 'opencode'; effect = 'deny' }) } if ($pols.Count -gt 0) { $cfg['policies'] = @($pols.ToArray()) } elseif ($cfg.Contains('policies')) { $cfg.Remove('policies') } Write-Utf8NoBomAtomic $cfgPath (($cfg | ConvertTo-Json -Depth 16) + "`n") $newState = [ordered]@{ schema_version = 1 managed_providers = @($activeCounts.Keys) base_url = $BaseUrl model = $resolvedModel free_policy_managed = (-not $KeepFree) installed_key_sha256 = (Get-Sha256Hex $ApiKey) had_prev_model = if ($prevState.Contains('had_prev_model')) { [bool]$prevState['had_prev_model'] } else { $hadPrevModel } prev_model = if ($prevState.Contains('prev_model')) { $prevState['prev_model'] } else { $prevModelVal } had_prev_update = if ($prevState.Contains('had_prev_update')) { [bool]$prevState['had_prev_update'] } else { $hadPrevUpdate } prev_update = if ($prevState.Contains('prev_update')) { $prevState['prev_update'] } else { $prevUpdateVal } updated_at = (Get-Date).ToUniversalTime().ToString('o') } Write-Utf8NoBomAtomic $statePath (($newState | ConvertTo-Json -Depth 8) + "`n") return [pscustomobject]@{ CfgPath = $cfgPath CfgBackup = $cfgBackup Model = $resolvedModel TotalModels = $totalModels HasJsonc = (Test-Path -LiteralPath $jsoncPath -PathType Leaf) } } # ---------------------------------------------------------------- No-VPN CLI Binary Installer function Get-WindowsArch { $a = [string]$env:PROCESSOR_ARCHITECTURE $a64 = [string]$env:PROCESSOR_ARCHITEW6432 if ($a -match '(?i)arm64' -or $a64 -match '(?i)arm64') { return 'arm64' } return 'x64' } function Find-OpenCodeBin { $cands = @( (Join-Path $script:Opt.BinDir 'opencode.exe') ) try { foreach ($cmd in @(Get-Command opencode -All -ErrorAction SilentlyContinue)) { if ($cmd.Source) { $cands += [string]$cmd.Source } } } catch { } foreach ($c in $cands) { if ($c -and (Test-Path -LiteralPath $c -PathType Leaf)) { return $c } } return '' } function Install-CliFromMirror { $arch = Get-WindowsArch $fname = 'opencode-windows-' + $arch + '.zip' $url = $script:Opt.AuthOrigin + '/downloads/v' + $script:OpenCodeVersion + '/' + $fname Say-Step ((U '\u4ece\u56fd\u5185\u514d VPN \u955c\u50cf\u4e0b\u8f7d\u5b98\u65b9 OpenCode CLI v') + $script:OpenCodeVersion + ' (windows-' + $arch + ')') Say ((U '\u4e0b\u8f7d\u5730\u5740: ') + $url) $tmpDir = Join-Path ([IO.Path]::GetTempPath()) ('opencode-dl-' + [Guid]::NewGuid().ToString('N')) $zipPath = Join-Path $tmpDir $fname $extDir = Join-Path $tmpDir 'extract' New-Item -ItemType Directory -Path $extDir -Force | Out-Null New-Item -ItemType Directory -Path $script:Opt.BinDir -Force | Out-Null try { $prevProg = $ProgressPreference $ProgressPreference = 'SilentlyContinue' try { Invoke-WebRequest -Uri $url -OutFile $zipPath -UseBasicParsing -TimeoutSec 300 } finally { $ProgressPreference = $prevProg } # Best-effort SHA-256 verification try { $manifest = Invoke-RestMethod -Method Get -Uri ($script:Opt.AuthOrigin + '/downloads/manifest.json') -TimeoutSec 10 if ($manifest -and $manifest.files -and $manifest.files.PSObject.Properties[$fname]) { $expectedSha = [string]$manifest.files.PSObject.Properties[$fname].Value.sha256 if ($expectedSha) { $actualSha = Get-FileSha256Hex $zipPath if ($actualSha -ine $expectedSha) { Fail ((U '\u5b89\u88c5\u5305 SHA-256 \u6821\u9a8c\u5931\u8d25 (\u671f\u671b ') + $expectedSha + ', ' + $actualSha + ')') } Say-Ok ((U 'SHA-256 \u5b8c\u6574\u6027\u6821\u9a8c\u901a\u8fc7 (') + $actualSha.Substring(0, 12) + '...)') } } } catch { } Expand-Archive -LiteralPath $zipPath -DestinationPath $extDir -Force $exeHit = Get-ChildItem -LiteralPath $extDir -Filter 'opencode.exe' -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $exeHit) { Fail (U '\u538b\u7f29\u5305\u5185\u672a\u627e\u5230 opencode.exe\u3002') } $dstExe = Join-Path $script:Opt.BinDir 'opencode.exe' Copy-Item -LiteralPath $exeHit.FullName -Destination $dstExe -Force Say-Ok ((U '\u5df2\u5b89\u88c5 OpenCode CLI \u5230 ') + $dstExe) if (-not $script:Opt.NoPath) { $userPath = [string][Environment]::GetEnvironmentVariable('Path', 'User') $parts = @($userPath -split ';' | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) $hasBin = $false foreach ($p in $parts) { if ($p.TrimEnd('\') -ieq $script:Opt.BinDir.TrimEnd('\')) { $hasBin = $true; break } } if (-not $hasBin) { $newPath = ($parts + @($script:Opt.BinDir)) -join ';' [Environment]::SetEnvironmentVariable('Path', $newPath, 'User') $env:Path = $script:Opt.BinDir + ';' + $env:Path Say-Ok ((U '\u5df2\u5c06 ') + $script:Opt.BinDir + (U ' \u52a0\u5165\u7528\u6237 PATH\uff08\u65b0\u5f00 PowerShell \u7a97\u53e3\u5373\u53ef\u76f4\u63a5\u8fd0\u884c opencode\uff09')) } } } finally { try { Remove-Item -LiteralPath $tmpDir -Recurse -Force -ErrorAction SilentlyContinue } catch { } } } # ---------------------------------------------------------------- Browser Auth & Network function Acquire-KeyViaBrowser { Say-Step ((U '\u53d1\u8d77\u6d4f\u89c8\u5668\u8bbe\u5907\u6388\u6743 (') + $script:Opt.AuthOrigin + ')') $devName = ([string]$env:COMPUTERNAME + '-opencode') -replace '[^A-Za-z0-9._-]', '' if ([string]::IsNullOrWhiteSpace($devName)) { $devName = 'windows-opencode' } if ($devName.Length -gt 40) { $devName = $devName.Substring(0, 40) } $startBody = (@{ device_name = $devName device_id = [Guid]::NewGuid().ToString() platform = 'Windows ' + (Get-WindowsArch) client = $script:Opt.Client } | ConvertTo-Json -Compress) $startResp = $null try { $startResp = Invoke-RestMethod -Method Post -Uri ($script:Opt.AuthOrigin + '/cli/auth/start') -ContentType 'application/json' -Body $startBody -TimeoutSec 15 } catch { Fail ((U '\u65e0\u6cd5\u8fde\u63a5\u6388\u6743\u670d\u52a1: ') + $_.Exception.Message) } $userCode = [string]$startResp.user_code $pollToken = [string]$startResp.poll_token $authUrl = [string]$startResp.authorize_url if (-not $userCode -or -not $pollToken) { Fail (U '\u6388\u6743\u4f1a\u8bdd\u521d\u59cb\u5316\u5931\u8d25\u3002') } if (-not $authUrl) { $authUrl = $script:Opt.AuthOrigin + '/cli-auth?code=' + $userCode + '&client=' + $script:Opt.Client } Write-Host '' Write-Host ' +------------------------------------------------------+' -ForegroundColor Cyan Write-Host ((U ' | \u7ec8\u7aef\u8bbe\u5907\u7801: ') + $userCode) -ForegroundColor White Write-Host ((U ' | \u6388\u6743\u9875\u9762: ') + $authUrl) -ForegroundColor Cyan Write-Host ' +------------------------------------------------------+' -ForegroundColor Cyan Write-Host '' if (Open-ChuhaiUrl $authUrl) { Say-Ok (U '\u5df2\u81ea\u52a8\u6253\u5f00\u6d4f\u89c8\u5668\uff0c\u8bf7\u6838\u5bf9\u8bbe\u5907\u7801\u5e76\u70b9\u51fb\u300c\u6388\u6743\u6b64\u8bbe\u5907\u300d...') } else { Say-Warn (U '\u672a\u80fd\u81ea\u52a8\u6253\u5f00\u6d4f\u89c8\u5668\uff0c\u8bf7\u624b\u52a8\u590d\u5236\u4e0a\u65b9\u94fe\u63a5\u5728\u6d4f\u89c8\u5668\u4e2d\u6253\u5f00\u5e76\u70b9\u300c\u6388\u6743\u6b64\u8bbe\u5907\u300d...') } $pollBody = (@{ poll_token = $pollToken } | ConvertTo-Json -Compress) for ($attempt = 1; $attempt -le 300; $attempt++) { Start-Sleep -Seconds 2 $pr = $null try { $pr = Invoke-RestMethod -Method Post -Uri ($script:Opt.AuthOrigin + '/cli/auth/poll') -ContentType 'application/json' -Body $pollBody -TimeoutSec 15 } catch { continue } $st = [string]$pr.status if ($st -eq 'approved') { $script:Opt.ApiKey = [string]$pr.key if (-not $script:Opt.ModelExplicit -and $pr.model) { $script:Opt.Model = [string]$pr.model } if (-not $script:Opt.BaseExplicit -and $pr.base_url) { $script:Opt.BaseUrl = Normalize-BaseUrl ([string]$pr.base_url) } if (-not $script:Opt.KeepFreeExplicit -and $pr.keep_free_models) { $script:Opt.KeepFree = $true } if (-not $script:Opt.ApiKey) { Fail (U '\u6388\u6743\u54cd\u5e94\u7f3a\u5c11\u5bc6\u94a5\u3002') } Say-Ok ((U '\u6d4f\u89c8\u5668\u6388\u6743\u6210\u529f\uff0c\u5df2\u5b89\u5168\u53d6\u56de\u4e00\u6b21\u6027\u5bc6\u94a5 (') + (Mask-Secret $script:Opt.ApiKey) + ')!') return } elseif ($st -eq 'denied') { Fail (U '\u4f60\u5df2\u5728\u6d4f\u89c8\u5668\u53d6\u6d88\u672c\u6b21\u8bbe\u5907\u6388\u6743\u3002') } elseif ($st -eq 'expired') { Fail (U '\u8bbe\u5907\u7801\u5df2\u8fc7\u671f\uff0c\u8bf7\u91cd\u65b0\u8fd0\u884c\u4e00\u952e\u63a5\u5165\u547d\u4ee4\u3002') } elseif (($attempt % 10) -eq 0) { Say ((U '\u7b49\u5f85\u6d4f\u89c8\u5668\u70b9\u51fb\u300c\u6388\u6743\u6b64\u8bbe\u5907\u300d... (\u8bbe\u5907\u7801: ') + $userCode + ')') } } Fail (U '\u7b49\u5f85\u6388\u6743\u8d85\u65f6\uff0810 \u5206\u949f\uff09\uff0c\u8bf7\u91cd\u65b0\u8fd0\u884c\u4e00\u952e\u63a5\u5165\u547d\u4ee4\u3002') } function Acquire-KeyFromConsole { Say-Step (U '\u8bf7\u8f93\u5165\u4f60\u7684\u51fa\u6d77365 API \u5bc6\u94a5 (https://api.chuhai365.cc)') $raw = Read-Host (U ' \u7c98\u8d34 sk-... \u5bc6\u94a5\u5e76\u56de\u8f66') $script:Opt.ApiKey = ([string]$raw).Trim().Trim('"', "'") -replace '\s+', '' if ([string]::IsNullOrWhiteSpace($script:Opt.ApiKey)) { Fail (U '\u672a\u8f93\u5165\u5bc6\u94a5\uff0c\u5df2\u53d6\u6d88\u3002') } } function Inspect-ProxyAndEnv([bool]$FixMode = $false) { $issues = 0 foreach ($scope in @('Process', 'User', 'Machine')) { foreach ($v in @('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY')) { $val = '' try { $val = [Environment]::GetEnvironmentVariable($v, $scope) } catch { $val = '' } if ([string]::IsNullOrWhiteSpace($val)) { continue } if ($val -match '^(?:https?|socks5?)://(?:[^@]+@)?(127\.0\.0\.1|localhost):(\d+)') { $h = $Matches[1]; $port = [int]$Matches[2] if (-not (Test-TcpPort $h $port 700)) { Say-Warn ((U '\u68c0\u6d4b\u5230\u6b7b\u4ee3\u7406\u73af\u5883\u53d8\u91cf [') + $scope + '] ' + $v + '=' + $val) $issues++ if ($FixMode -and ($scope -eq 'Process' -or $scope -eq 'User')) { try { [Environment]::SetEnvironmentVariable($v, $null, $scope) Say-Ok ((U '\u5df2\u6e05\u7406\u6b7b\u4ee3\u7406 [') + $scope + '] ' + $v) } catch { } } } } } } if ($FixMode) { Say-Step ((U '\u6d4b\u8bd5\u76f4\u8fde\u51fa\u6d77365 API \u7f51\u5173: ') + $script:Opt.BaseUrl) try { $req = [Net.HttpWebRequest]::Create($script:Opt.BaseUrl + '/models') $req.Method = 'GET'; $req.Timeout = 10000; $req.Proxy = $null $code = 0 try { $resp = $req.GetResponse(); $code = [int]$resp.StatusCode; $resp.Close() } catch [Net.WebException] { if ($_.Exception.Response) { $code = [int]$_.Exception.Response.StatusCode } } if ($code -eq 200 -or $code -eq 401 -or $code -eq 403) { Say-Ok ((U '\u76f4\u8fde api.chuhai365.cc \u6b63\u5e38 (HTTP ') + $code + ')') } else { Say-Err ((U '\u76f4\u8fde api.chuhai365.cc \u5931\u8d25 (HTTP ') + $code + ')') } } catch { Say-Err ((U '\u7f51\u7edc\u63a2\u6d4b\u5f02\u5e38: ') + $_.Exception.Message) } if ($issues -eq 0) { Say-Ok (U '\u672a\u53d1\u73b0\u6b7b\u4ee3\u7406\u73af\u5883\u53d8\u91cf\u3002') } } } # ---------------------------------------------------------------- Check & Uninstall Modes function Invoke-CheckMode { Say-Step ((U '\u51fa\u6d77365 OpenCode \u63a5\u5165\u4f53\u68c0 (\u53ea\u8bfb\u6a21\u5f0f \u00b7 v') + $script:ScriptVersion + ')') Say ((U '\u914d\u7f6e\u76ee\u5f55: ') + $script:Opt.ConfigDir) $cfgPath = Join-Path $script:Opt.ConfigDir 'opencode.json' $jsoncPath = Join-Path $script:Opt.ConfigDir 'opencode.jsonc' if (Test-Path -LiteralPath $cfgPath -PathType Leaf) { try { $d = ConvertTo-OrderedMap ((Read-Utf8NoBom $cfgPath) | ConvertFrom-Json) $provs = if ($d.Contains('providers')) { ConvertTo-OrderedMap $d['providers'] } else { [ordered]@{} } $found = @() foreach ($mp in $script:ManagedProviders) { if ($provs.Contains($mp)) { $pm = ConvertTo-OrderedMap $provs[$mp] $cnt = if ($pm.Contains('models')) { (ConvertTo-OrderedMap $pm['models']).Count } else { 0 } $found += ($mp + ':' + $cnt) } } if ($found.Count -gt 0) { Say-Ok (U 'opencode.json \u5df2\u63a5\u5165\u51fa\u6d77365 API') Say ((U ' \u9ed8\u8ba4\u6a21\u578b: ') + [string]$d['model']) Say ((U ' \u5df2\u6302\u8f7d\u5382\u5546: ') + ($found -join ', ')) } else { Say-Warn (U 'opencode.json \u5b58\u5728\u4f46\u672a\u5305\u542b\u51fa\u6d77365\u5382\u5546\u914d\u7f6e') } } catch { Say-Warn (U 'opencode.json \u89e3\u6790\u5931\u8d25') } } else { Say-Warn ((U '\u672a\u627e\u5230 ') + $cfgPath) } if (Test-Path -LiteralPath $jsoncPath -PathType Leaf) { Say-Warn (U '\u68c0\u6d4b\u5230\u540c\u76ee\u5f55\u5b58\u5728 opencode.jsonc\uff0c\u5176\u4f18\u5148\u7ea7\u9ad8\u4e8e opencode.json\u3002') } $ocBin = Find-OpenCodeBin if ($ocBin) { Say-Ok ((U '\u5df2\u5b89\u88c5 OpenCode CLI: ') + $ocBin) } else { Say (U '\u672a\u68c0\u6d4b\u5230 CLI \u4e8c\u8fdb\u5236\uff08\u684c\u9762\u7248\u7528\u6237\u53ef\u5ffd\u7565\uff0c\u9700\u8981 CLI \u53ef\u52a0 -InstallCli \u514d VPN \u81ea\u52a8\u5b89\u88c5\uff09') } Inspect-ProxyAndEnv $false } function Invoke-UninstallMode { Say-Step (U '\u5378\u8f7d\u51fa\u6d77365 OpenCode \u63a5\u5165\u5e76\u7cbe\u51c6\u8fd8\u539f\u914d\u7f6e') $cfgPath = Join-Path $script:Opt.ConfigDir 'opencode.json' $statePath = Join-Path $script:Opt.ConfigDir '.chuhai365-opencode-state.json' $ts = (Get-Date).ToString('yyyyMMdd-HHmmss') $state = [ordered]@{} if (Test-Path -LiteralPath $statePath -PathType Leaf) { try { $state = ConvertTo-OrderedMap ((Read-Utf8NoBom $statePath) | ConvertFrom-Json) } catch { $state = [ordered]@{} } } $changed = $false if (Test-Path -LiteralPath $cfgPath -PathType Leaf) { Copy-Item -LiteralPath $cfgPath -Destination ($cfgPath + '.bak.pre-uninstall.' + $ts) -Force try { $cfg = ConvertTo-OrderedMap ((Read-Utf8NoBom $cfgPath) | ConvertFrom-Json) if ($cfg.Contains('providers') -and $null -ne $cfg['providers']) { $provs = ConvertTo-OrderedMap $cfg['providers'] foreach ($mp in $script:ManagedProviders) { if ($provs.Contains($mp)) { $provs.Remove($mp); $changed = $true } } if ($provs.Count -gt 0) { $cfg['providers'] = $provs } else { $cfg.Remove('providers') } } if ($cfg.Contains('model') -and ([string]$cfg['model']).StartsWith('chuhai365-')) { if ($state.Contains('had_prev_model') -and [bool]$state['had_prev_model']) { $cfg['model'] = $state['prev_model'] } else { $cfg.Remove('model') } $changed = $true } if ($state.Contains('had_prev_update') -and [bool]$state['had_prev_update']) { $cfg['update'] = $state['prev_update'] } elseif ($state.Contains('had_prev_update') -and $cfg.Contains('update') -and $cfg['update'] -eq 'disable') { $cfg.Remove('update') } if ($state.Contains('free_policy_managed') -and [bool]$state['free_policy_managed'] -and $cfg.Contains('policies')) { $kept = @() foreach ($item in @($cfg['policies'])) { if (-not (Test-SameFreePolicy $item)) { $kept += $item } else { $changed = $true } } if ($kept.Count -gt 0) { $cfg['policies'] = $kept } else { $cfg.Remove('policies') } } $nonSchema = @($cfg.Keys | Where-Object { $_ -ne '$schema' }) if ($nonSchema.Count -eq 0) { Remove-Item -LiteralPath $cfgPath -Force -ErrorAction SilentlyContinue } else { Write-Utf8NoBomAtomic $cfgPath (($cfg | ConvertTo-Json -Depth 16) + "`n") } } catch { } } if (Test-Path -LiteralPath $statePath -PathType Leaf) { Remove-Item -LiteralPath $statePath -Force -ErrorAction SilentlyContinue } if ($changed) { Say-Ok (U '\u5df2\u79fb\u9664\u51fa\u6d77365\u5382\u5546\u914d\u7f6e\u5e76\u7cbe\u51c6\u8fd8\u539f\u539f\u914d\u7f6e\uff08\u5df2\u4fdd\u7559\u5907\u4efd .bak.pre-uninstall.*\uff09\u3002') } else { Say (U '\u672a\u53d1\u73b0\u9700\u8981\u79fb\u9664\u7684\u51fa\u6d77365\u914d\u7f6e\u3002') } Say-Ok (U '\u5378\u8f7d\u5b8c\u6210\uff0c\u4f60\u7684 MCP\u3001\u5176\u4ed6\u5382\u5546\u3001\u6280\u80fd\u4e0e\u5386\u53f2\u4f1a\u8bdd\u5747\u5b8c\u597d\u65e0\u635f\u3002') } # ---------------------------------------------------------------- Main function Invoke-Main([object[]]$RawArgs) { Parse-CliArgs $RawArgs if ($script:Opt.Help) { Show-Usage; return } if ($script:Opt.BadArgs.Count -gt 0) { Fail ((U '\u672a\u77e5\u53c2\u6570: ') + ($script:Opt.BadArgs -join ', ') + (U '\uff08\u8fd0\u884c -Help \u67e5\u770b\u7528\u6cd5\uff09')) } $modeCount = ([int]$script:Opt.Check) + ([int]$script:Opt.FixProxy) + ([int]$script:Opt.Uninstall) if ($modeCount -gt 1) { Fail (U '-Check / -FixProxy / -Uninstall \u4e00\u6b21\u53ea\u80fd\u9009\u62e9\u4e00\u4e2a\u3002') } if ($script:Opt.Check) { Invoke-CheckMode; return } if ($script:Opt.FixProxy) { Inspect-ProxyAndEnv $true; return } if ($script:Opt.Uninstall) { Invoke-UninstallMode; return } Say-Step ((U '\u51fa\u6d77365 API \u00b7 \u5b98\u65b9 OpenCode v') + $script:OpenCodeVersion + (U ' \u4e00\u952e\u63a5\u5165 (v') + $script:ScriptVersion + ')') Say ((U '\u7f51\u5173\u5730\u5740: ') + $script:Opt.BaseUrl) Say ((U '\u914d\u7f6e\u76ee\u5f55: ') + $script:Opt.ConfigDir) if ($script:Opt.InstallCli) { Install-CliFromMirror } if ([string]::IsNullOrWhiteSpace($script:Opt.ApiKey)) { if ($script:Opt.Paste) { Acquire-KeyFromConsole } else { Acquire-KeyViaBrowser } } else { $script:Opt.ApiKey = $script:Opt.ApiKey.Trim().Trim('"', "'") -replace '\s+', '' Say-Ok ((U '\u5df2\u8bfb\u53d6 API \u5bc6\u94a5 (') + (Mask-Secret $script:Opt.ApiKey) + ')') } if (-not $script:Opt.ApiKey.StartsWith('sk-')) { Fail (U '\u5bc6\u94a5\u683c\u5f0f\u4e0d\u6b63\u786e\uff0c\u5e94\u4ee5 sk- \u5f00\u5934\uff0c\u8bf7\u68c0\u67e5\u540e\u91cd\u8bd5\u3002') } $discoveredModels = @() if (-not $script:Opt.NoVerify) { Say-Step (U '\u8fde\u63a5 api.chuhai365.cc \u9a8c\u8bc1\u5bc6\u94a5\u5e76\u540c\u6b65\u53ef\u7528\u6a21\u578b\u5217\u8868') try { $resp = Invoke-RestMethod -Method Get -Uri ($script:Opt.BaseUrl + '/models') -Headers @{ Authorization = ('Bearer ' + $script:Opt.ApiKey); Accept = 'application/json' } -TimeoutSec 20 if ($resp -and $resp.data) { foreach ($item in @($resp.data)) { if ($item -and $item.id) { $mid = ([string]$item.id).Trim() if (Classify-Model $mid) { $discoveredModels += $mid } } } } Say-Ok (U '\u5bc6\u94a5\u9a8c\u8bc1\u901a\u8fc7\uff0c\u5df2\u62c9\u53d6\u4f60\u5f53\u524d\u5bc6\u94a5\u7684\u5168\u90e8\u53ef\u7528\u5bf9\u8bdd/\u7f16\u7a0b\u6a21\u578b\u3002') } catch { $status = 0 try { if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode } } catch { } if ($status -eq 401 -or $status -eq 403) { Fail ((U 'API \u5bc6\u94a5\u65e0\u6548\u3001\u5df2\u88ab\u7981\u7528\u6216\u5df2\u8fc7\u671f (HTTP ') + $status + (U ')\uff0c\u8bf7\u524d\u5f80 https://api.chuhai365.cc \u6838\u5bf9\u5bc6\u94a5\u3002')) } Fail ((U '\u65e0\u6cd5\u8fde\u63a5\u51fa\u6d77365\u7f51\u5173: ') + $_.Exception.Message + (U '\u3002\u8bf7\u8fd0\u884c -FixProxy \u6392\u67e5\u4ee3\u7406\u6216\u7f51\u7edc\u3002')) } } else { Say-Warn (U '\u79bb\u7ebf\u6a21\u5f0f (-NoVerify)\uff1a\u5c06\u5199\u5165\u6807\u51c6\u5168\u7cfb\u6a21\u578b\u6e05\u5355\u3002') } Say-Step ((U '\u5199\u5165 OpenCode V2 \u5168\u5c40\u914d\u7f6e (') + (Join-Path $script:Opt.ConfigDir 'opencode.json') + ')') $res = Apply-OpenCodeConfig $script:Opt.ConfigDir $script:Opt.BaseUrl $script:Opt.Model $script:Opt.KeepFree $script:Opt.ApiKey $discoveredModels Say-Ok ((U '\u914d\u7f6e\u5199\u5165\u5b8c\u6210\uff1a\u5171\u914d\u7f6e ') + $res.TotalModels + (U ' \u4e2a\u6a21\u578b\uff0c\u9ed8\u8ba4\u6a21\u578b ') + $res.Model) if ($res.CfgBackup) { Say ((U '\u539f\u914d\u7f6e\u5df2\u81ea\u52a8\u5907\u4efd\u81f3: ') + $res.CfgBackup) } if ($res.HasJsonc) { Say-Warn (U '\u6ce8\u610f\uff1a\u68c0\u6d4b\u5230\u540c\u76ee\u5f55\u5b58\u5728 opencode.jsonc\uff0c\u5176\u4f18\u5148\u7ea7\u9ad8\u4e8e opencode.json\u3002') } $ocBin = Find-OpenCodeBin if ($ocBin) { try { $p = Start-Process -FilePath $ocBin -ArgumentList 'service','restart' -NoNewWindow -Wait -PassThru -ErrorAction SilentlyContinue if ($p -and $p.ExitCode -eq 0) { Say-Ok (U '\u5df2\u81ea\u52a8\u5237\u65b0 OpenCode \u540e\u53f0\u670d\u52a1\u914d\u7f6e\u3002') } } catch { } } Inspect-ProxyAndEnv $false Write-Host '' Write-Host '========================================================' -ForegroundColor Green Write-Host (U ' [OK] OpenCode \u63a5\u5165\u51fa\u6d77365 API \u5b8c\u6210\uff01') -ForegroundColor Green Write-Host ((U ' \u9ed8\u8ba4\u6a21\u578b: ') + $res.Model) Write-Host ((U ' \u914d\u7f6e\u6587\u4ef6: ') + $res.CfgPath) Write-Host '========================================================' -ForegroundColor Green Write-Host '' if ($script:Opt.Client -eq 'cli') { Say (U '\u4e0b\u4e00\u6b65\uff1a') Say (U '1. \u91cd\u65b0\u6253\u5f00\u4e00\u4e2a PowerShell \u7a97\u53e3\uff08\u4f7f PATH \u751f\u6548\uff09\u3002') Say (U '2. \u8fdb\u5165\u4efb\u610f\u9879\u76ee\u76ee\u5f55\u8fd0\u884c: opencode') Say (U '3. \u8f93\u5165 /models \u53ef\u968f\u65f6\u5728 Claude / GPT / Gemini / Grok \u4e4b\u95f4\u5207\u6362\u3002') } else { Say (U '\u4e0b\u4e00\u6b65\uff1a') Say (U '1. \u6253\u5f00\uff08\u6216\u91cd\u542f\uff09OpenCode \u684c\u9762 App\uff0c\u65e0\u9700\u767b\u5f55 OpenCode \u8d26\u53f7\u3002') Say (U '2. \u76f4\u63a5\u5f00\u59cb\u5bf9\u8bdd\u6216\u5199\u4ee3\u7801\uff0c\u6a21\u578b\u83dc\u5355\u5df2\u81ea\u52a8\u52a0\u8f7d\u4f60\u7684\u5168\u90e8\u53ef\u7528\u6a21\u578b\u3002') Say (U '3. \u5982\u9700\u540c\u65f6\u4f7f\u7528\u7ec8\u7aef\u7248\uff0c\u53ef\u52a0 -InstallCli \u53c2\u6570\u514d VPN \u81ea\u52a8\u5b89\u88c5 CLI\u3002') } Write-Host '' } try { Invoke-Main $args } catch { $msg = [string]$_.Exception.Message if ($msg.StartsWith('CHUHAI_FAIL::')) { Say-Err $msg.Substring(13) } else { Say-Err $msg } exit 1 }