# OpusCodex 一键接入(Windows PowerShell 5.1+) # irm https://gpt.opusapi.xyz/install.ps1 | iex # 或: .\install.ps1 -Key 'sk-xxx' # # Windows 桌面要进 API 网关模式,必须找到官方 Codex CLI 并跑 # `codex login --with-api-key`。只写 auth.json 不够:Electron 仍会走 ChatGPT 验证码。 param( [string]$Key = $env:OPUSCODEX_API_KEY, [string]$BaseUrl = "https://gpt.opusapi.xyz", [switch]$Check, [switch]$Uninstall ) $ErrorActionPreference = "Stop" try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072 } catch {} $Site = $BaseUrl.TrimEnd("/") switch ($Site) { "https://gpt.opusapi.xyz" { } "https://opusapi.xyz" { } "https://india.opusapi.xyz" { } default { throw "不允许的 BaseUrl: $Site(OpusCodex 只用 gpt.opusapi.xyz;备用 opusapi.xyz / india.opusapi.xyz)" } } $ApiBase = if ($env:OPUSCODEX_API_BASE) { $env:OPUSCODEX_API_BASE.TrimEnd("/") } else { "https://api.opusapi.xyz/v1" } switch ($ApiBase) { "https://api.opusapi.xyz/v1" { } "https://gpt.opusapi.xyz/v1" { } "https://opusapi.xyz/v1" { } "https://india.opusapi.xyz/v1" { } default { throw "不允许的 ApiBase: $ApiBase" } } $ConfigDir = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME ".codex" } $ConfigFile = Join-Path $ConfigDir "config.toml" $AuthFile = Join-Path $ConfigDir "auth.json" $MarkBegin = "# >>> opuscodex-codex >>>" $MarkEnd = "# <<< opuscodex-codex <<<" $DefaultCodexHome = Join-Path $HOME ".codex" $ChatgptAuthKeys = @("tokens", "last_refresh", "access_token", "refresh_token", "id_token") $OwnedRootKeys = @( "model_provider", "openai_base_url", "model", "review_model", "model_reasoning_effort", "forced_login_method", "cli_auth_credentials_store", "disable_response_storage" ) function Write-Utf8NoBom([string]$Path, [string]$Content) { $encoding = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($Path, $Content, $encoding) } function Escape-Toml([string]$Value) { return (($Value -replace '\\', '\\') -replace '"', '\"') } function Test-OpusCodexUrl([string]$Url) { return ($Url -match '^https://(gpt\.|api\.|india\.)?opusapi\.xyz(/|\?|$)') } # ShellExecute of https:// fails in elevated/system32 and Win11 empty https open\command. # Do not throw: device-flow poll must continue; URL is printed. function Open-OpusCodexUrl([string]$Url) { if (-not (Test-OpusCodexUrl $Url)) { return } $prev = $ErrorActionPreference $ErrorActionPreference = "Continue" try { $exes = @() $progId = "" foreach ($choiceKey in @( "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoiceLatest\ProgId", "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice" )) { try { $progId = [string](Get-ItemProperty -LiteralPath $choiceKey -ErrorAction Stop).ProgId if ($progId) { break } } catch {} } if ($progId) { foreach ($rk in @( "HKCU:\Software\Classes\$progId\shell\open\command", "HKLM:\SOFTWARE\Classes\$progId\shell\open\command" )) { try { $raw = [string](Get-ItemProperty -LiteralPath $rk -ErrorAction Stop)."(default)" $candidate = $null if ($raw -match '"([^"]+\.exe)"') { $candidate = $Matches[1] } elseif ($raw -match '(?i)([a-z]:\\[^"]*?\.exe)') { $candidate = $Matches[1] } if (-not $candidate) { continue } $candidate = [Environment]::ExpandEnvironmentVariables($candidate) if ($candidate -match '^[a-zA-Z]:\\' -and $candidate -notmatch '(?i)[\\/](explorer|rundll32|LaunchWinApp)\.exe$' -and (Test-Path -LiteralPath $candidate)) { $exes += $candidate } } catch {} } } foreach ($n in @("msedge.exe", "chrome.exe", "firefox.exe")) { try { $p = [string](Get-ItemProperty -LiteralPath "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\$n" -ErrorAction Stop)."(default)" if ($p) { $p = [Environment]::ExpandEnvironmentVariables($p.Trim().Trim('"')) } if ($p -and $p -match '^[a-zA-Z]:\\' -and (Test-Path -LiteralPath $p)) { $exes += $p } } catch {} } $seen = @{} foreach ($exe in $exes) { $k = $exe.ToLowerInvariant() if ($seen.ContainsKey($k)) { continue } $seen[$k] = $true try { $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $exe $psi.Arguments = $Url $psi.UseShellExecute = $false [void][System.Diagnostics.Process]::Start($psi) return } catch {} } } catch {} finally { $ErrorActionPreference = $prev } } function Stop-CodexApps { if ($ConfigDir -ne $DefaultCodexHome) { return } $running = Get-Process -Name ChatGPT,Codex -ErrorAction SilentlyContinue if (-not $running) { return } Write-Host "退出正在运行的 Codex / ChatGPT 桌面端,避免它把 ChatGPT 登录态写回" $running | Stop-Process -Force -ErrorAction SilentlyContinue $n = 0 while ($n -lt 20) { if (-not (Get-Process -Name ChatGPT,Codex -ErrorAction SilentlyContinue)) { return } Start-Sleep -Milliseconds 250 $n++ } } function Strip-Managed([string]$Text) { $pattern = [regex]::Escape($MarkBegin) + ".*?" + [regex]::Escape($MarkEnd) + "\r?\n?" return [regex]::Replace( $Text, $pattern, "", [System.Text.RegularExpressions.RegexOptions]::Singleline ) } function Remove-OwnedRootKeys([string]$Text) { $out = New-Object System.Collections.Generic.List[string] $inRoot = $true foreach ($line in [regex]::Split($Text, "(?<=\n)")) { $trimmed = $line.Trim() if ($trimmed.StartsWith("[")) { $inRoot = $false } if ($inRoot -and $trimmed.Contains("=") -and -not $trimmed.StartsWith("#")) { $name = ($trimmed -split "=", 2)[0].Trim() if ($OwnedRootKeys -contains $name) { continue } } $out.Add($line) } return -join $out } function Remove-ProviderTable([string]$Text, [string]$Name) { $pattern = '(?m)^\[model_providers\.' + [regex]::Escape($Name) + '\][^\[]*' return [regex]::Replace($Text, $pattern, "") } function Normalize-Text([string]$Text) { if ([string]::IsNullOrWhiteSpace($Text)) { return "" } $value = [regex]::Replace($Text, "(\r?\n){3,}", "`n`n").Trim() return $value + "`n" } function Split-ConfigSections([string]$Text) { $match = [regex]::Match($Text, '(?m)^[ \t]*\[') if (-not $match.Success) { return [pscustomobject]@{ Root = $Text; Tables = "" } } return [pscustomobject]@{ Root = $Text.Substring(0, $match.Index) Tables = $Text.Substring($match.Index) } } function Test-CodexApiLogin([string]$Bin) { if (-not $Bin) { return $false } if (-not (Test-Path -LiteralPath $Bin)) { return $false } try { $item = Get-Item -LiteralPath $Bin -ErrorAction Stop if ($item.Length -eq 0) { return $false } } catch { return $false } try { $help = & $Bin login --help 2>&1 | Out-String return ($help -match "--with-api-key") } catch { return $false } } function Add-CodexCandidate([System.Collections.Generic.List[string]]$List, [string]$Path) { if (-not $Path) { return } if ($List.Contains($Path)) { return } $List.Add($Path) } function Find-CodexBin { $candidates = New-Object System.Collections.Generic.List[string] if ($env:OPUSCODEX_CODEX_BIN) { Add-CodexCandidate $candidates $env:OPUSCODEX_CODEX_BIN } $la = [string]$env:LOCALAPPDATA $up = [string]$env:USERPROFILE $ad = [string]$env:APPDATA if ($la) { foreach ($rel in @( "Programs\OpenAI\Codex\bin\codex.exe", "Programs\OpenAI\ChatGPT\bin\codex.exe", "Programs\ChatGPT\resources\codex.exe", "ChatGPT\resources\codex.exe", "Programs\Codex\resources\codex.exe", "Programs\Codex\bin\codex.exe", "Programs\codex\codex.exe" )) { Add-CodexCandidate $candidates (Join-Path $la $rel) } } if ($up) { Add-CodexCandidate $candidates (Join-Path $up ".codex\bin\codex.exe") $releaseRoot = Join-Path $up ".codex\packages\standalone\releases" if (Test-Path -LiteralPath $releaseRoot) { Get-ChildItem -LiteralPath $releaseRoot -Filter "codex.exe" -Recurse -ErrorAction SilentlyContinue | Select-Object -First 8 | ForEach-Object { Add-CodexCandidate $candidates $_.FullName } } } if ($ad) { Add-CodexCandidate $candidates (Join-Path $ad "npm\codex.cmd") Add-CodexCandidate $candidates (Join-Path $ad "npm\codex.exe") } try { foreach ($n in @("*Codex*", "*ChatGPT*", "*OpenAI*")) { foreach ($pkg in @(Get-AppxPackage -Name $n -ErrorAction SilentlyContinue)) { $root = [string]$pkg.InstallLocation if (-not $root) { continue } foreach ($rel in @( "app\resources\codex.exe", "app\bin\codex.exe", "app\codex.exe", "resources\codex.exe" )) { Add-CodexCandidate $candidates (Join-Path $root $rel) } $appDir = Join-Path $root "app" if (Test-Path -LiteralPath $appDir) { Get-ChildItem -LiteralPath $appDir -Filter "codex.exe" -Recurse -Depth 3 -ErrorAction SilentlyContinue | Select-Object -First 8 | ForEach-Object { Add-CodexCandidate $candidates $_.FullName } } } } } catch {} $cmd = Get-Command codex -ErrorAction SilentlyContinue if ($cmd -and $cmd.Source) { $src = [string]$cmd.Source if ($src -notmatch '\\WindowsApps\\[^\\]+$') { Add-CodexCandidate $candidates $src } } foreach ($p in $candidates) { if (Test-CodexApiLogin $p) { return $p } } return $null } function Start-CodexCli([string]$Bin, [string]$Arguments, [string]$Stdin) { $psi = New-Object System.Diagnostics.ProcessStartInfo if ($Bin -match '\.(cmd|bat)$') { $psi.FileName = $env:ComSpec $psi.Arguments = "/d /s /c `" `"$Bin`" $Arguments `"" } else { $psi.FileName = $Bin $psi.Arguments = $Arguments } $psi.UseShellExecute = $false $psi.RedirectStandardInput = $true $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.CreateNoWindow = $true $psi.WorkingDirectory = $ConfigDir if ($psi.EnvironmentVariables.ContainsKey("CODEX_HOME")) { $psi.EnvironmentVariables["CODEX_HOME"] = $ConfigDir } else { $psi.EnvironmentVariables.Add("CODEX_HOME", $ConfigDir) } $proc = [System.Diagnostics.Process]::Start($psi) if ($null -ne $Stdin) { $proc.StandardInput.Write($Stdin) } $proc.StandardInput.Close() $stdout = $proc.StandardOutput.ReadToEnd() $stderr = $proc.StandardError.ReadToEnd() if (-not $proc.WaitForExit(120000)) { try { $proc.Kill() } catch {} return [pscustomobject]@{ ExitCode = -1; Output = "timeout" } } return [pscustomobject]@{ ExitCode = $proc.ExitCode Output = "$stdout`n$stderr" } } function Invoke-CodexApiLogin([string]$ApiKey) { $bin = Find-CodexBin if (-not $bin) { Write-Host "warn: 没找到 Codex CLI(2026 桌面版通常在 %LOCALAPPDATA%\Programs\OpenAI\Codex\bin\codex.exe)。配置已写入,但桌面仍会走 ChatGPT 验证码登录。装好官方 App 后请重跑本脚本。" return } Write-Host "向 Codex 注册 API 登录态…" $env:CODEX_HOME = $ConfigDir $null = Start-CodexCli $bin "logout" $null $null = Start-CodexCli $bin '-c cli_auth_credentials_store="auto" logout' $null $login = Start-CodexCli $bin "login --with-api-key" $ApiKey if ($login.ExitCode -ne 0) { Write-Host "warn: codex login --with-api-key 失败(exit $($login.ExitCode))。桌面可能仍要验证码登录。" return } $status = Start-CodexCli $bin "login status" $null if ($status.Output -match "API key") { Write-Host "已注册 API 登录(不要再点 ChatGPT / 不要填手机号)" } else { Write-Host "warn: Codex 登录态不是 API key,桌面可能仍走验证码。请完全退出 App 后重跑安装。" } } function Write-CodexConfig([string]$apiKey, [string]$base) { New-Item -ItemType Directory -Force -Path $ConfigDir | Out-Null if (Test-Path -LiteralPath $ConfigFile) { Copy-Item -LiteralPath $ConfigFile -Destination "$ConfigFile.bak.opuscodex.$(Get-Date -Format yyyyMMddHHmmss)" -Force } $raw = if (Test-Path -LiteralPath $ConfigFile) { Get-Content -LiteralPath $ConfigFile -Raw -Encoding UTF8 } else { "" } $raw = Remove-ProviderTable (Remove-ProviderTable (Strip-Managed $raw) "custom") "opuscodex" $raw = Remove-OwnedRootKeys $raw $sections = Split-ConfigSections $raw $sections.Root = Normalize-Text $sections.Root if ($sections.Root) { $sections.Root += "`n" } $sections.Tables = Normalize-Text $sections.Tables $escKey = Escape-Toml $apiKey $escBase = Escape-Toml $base $managed = @" $MarkBegin # managed by OpusCodex install.ps1 model_provider = "custom" openai_base_url = "$escBase" model = "gpt-6.1-sol" review_model = "gpt-6.1-sol" forced_login_method = "api" cli_auth_credentials_store = "file" disable_response_storage = true [model_providers.custom] name = "OpusCodex" base_url = "$escBase" wire_api = "responses" requires_openai_auth = true experimental_bearer_token = "$escKey" $MarkEnd "@ Write-Utf8NoBom $ConfigFile ($sections.Root + $managed + $sections.Tables) $old = $null if (Test-Path -LiteralPath $AuthFile) { try { $old = Get-Content -LiteralPath $AuthFile -Raw -Encoding UTF8 | ConvertFrom-Json } catch { $old = $null } } $auth = [ordered]@{ OPENAI_API_KEY = $apiKey auth_mode = "apikey" } if ($old) { foreach ($prop in $old.PSObject.Properties) { if ($ChatgptAuthKeys -contains $prop.Name) { continue } if ($prop.Name -eq "OPENAI_API_KEY" -or $prop.Name -eq "auth_mode") { continue } $auth[$prop.Name] = $prop.Value } } Write-Utf8NoBom $AuthFile (($auth | ConvertTo-Json -Depth 20) + "`n") Write-Host "wrote $ConfigFile" Write-Host "wrote $AuthFile" } function Start-DeviceFlow { $dname = "$env:COMPUTERNAME-codex" $did = [guid]::NewGuid().ToString() $start = Invoke-RestMethod -Method Post -Uri "$Site/cli/auth/start" -ContentType "application/json" -Body (@{ device_name = $dname; device_id = $did } | ConvertTo-Json) $uc = $start.user_code $pt = $start.poll_token if (-not $uc -or -not $pt) { throw "设备流启动失败" } $url = "$Site/cli-auth?code=$uc&client=codex" Write-Host "" Write-Host " 设备码 $uc" Write-Host " 浏览器 $url" Write-Host "" Open-OpusCodexUrl $url Write-Host "等待授权…" for ($i = 0; $i -lt 300; $i++) { Start-Sleep -Seconds 2 try { $r = Invoke-RestMethod -Method Post -Uri "$Site/cli/auth/poll" -ContentType "application/json" -Body (@{ poll_token = $pt } | ConvertTo-Json) } catch { continue } if ($r.status -eq "approved") { if (-not $r.key) { throw "授权成功但无 key" } return $r.key } if ($r.status -eq "expired" -or $r.status -eq "denied") { throw "授权 $($r.status)" } } throw "授权超时" } if ($Uninstall) { if (Test-Path -LiteralPath $ConfigFile) { $raw = Get-Content -LiteralPath $ConfigFile -Raw -Encoding UTF8 $raw = Strip-Managed $raw Write-Utf8NoBom $ConfigFile $raw } Write-Host "已尝试清除 managed 块" exit 0 } if ($Check) { Write-Host "config: $ConfigFile exists=$([bool](Test-Path -LiteralPath $ConfigFile))" if (Test-Path -LiteralPath $ConfigFile) { Select-String -Path $ConfigFile -Pattern "openai_base_url|model_provider|forced_login_method|OpusCodex" | ForEach-Object { $_.Line } } $bin = Find-CodexBin Write-Host "codex_bin: $(if ($bin) { $bin } else { 'missing' })" exit 0 } Write-Host "" Write-Host "OpusCodex · 一键接入 Codex App" Write-Host "" if (-not $Key) { $Key = Start-DeviceFlow } else { $Key = ($Key -replace '\s','').Trim("'").Trim('"') } Stop-CodexApps Write-CodexConfig -apiKey $Key -base $ApiBase Invoke-CodexApiLogin -ApiKey $Key Write-Host "" Write-Host "完成。请打开 Codex App → 不要点 ChatGPT 登录、不要填手机号 → 新建会话。" Write-Host "若仍出现验证码登录:完全退出 App 后重跑本脚本(必须能找到 codex.exe 并显示「已注册 API 登录」)。" Write-Host ""