# 5laoban AI gateway: one-step Codex client setup for Windows (PowerShell 5.1 or later). # macOS / Linux: use codex-setup.sh in the same folder. # # Usage, in Command Prompt or PowerShell: # powershell -c "irm https://ai.5lb.cn/helper/codex-setup.ps1 | iex" # or save this file, then run: powershell -ExecutionPolicy Bypass -File codex-setup.ps1 # A bare "irm ... | iex" only works inside PowerShell; Command Prompt answers that irm is not a # command, and members often open Command Prompt. Going through powershell.exe works in both. # # What it does: # 1. Asks for the key the administrator gave you (if this computer is already set up for the gateway, # pressing Enter keeps the key it has) and checks it against the gateway; an invalid key changes nothing. # 2. Writes the gateway into %USERPROFILE%\.codex\config.toml (other settings are kept) # and stores the key in %USERPROFILE%\.codex\auth.json. Both files are backed up first. # 3. If the Codex CLI is missing and npm is available, installs it from the China npm mirror; # when that is not possible, lists manual downloads of the desktop app and Node.js # (a China mirror and the official one for each). # 4. If PowerShell would refuse to run the installed codex command, offers to allow local # scripts for your account, and only changes it when you agree. # 5. If the Codex CLI is 0.162.1 or later, also adds the gateway's model catalog, so the model # picker only lists the models the gateway serves (TASK-011). Windows only checks the CLI. # 6. Image generation is on by default (S5): Codex only offers its image tool when the provider has # requires_openai_auth = false, experimental_bearer_token and the x-openai-actor-authorization # header, so the key is also written into config.toml, readable by the current user only. Set # CODEX_SETUP_NO_IMAGE=1 to keep the old way (requires_openai_auth = true, key only in auth.json). # The provider table is rewritten every run, so switching either way leaves nothing behind. # Every file is written to a temporary file in the same folder and then swapped in. When a # validator is available (codex 0.162.1 or later, or a Python with tomllib), the new config is # checked before it replaces the old one. The script contains no key. # # Optional environment variables: # WULAOBAN_API_KEY pass the key without typing it # CODEX_SETUP_MODEL default model (otherwise $DefaultModel below) # CODEX_SETUP_SKIP_INSTALL set to 1 to skip installing the Codex CLI # CODEX_SETUP_YES set to 1 to replace an existing ChatGPT login without asking # CODEX_SETUP_NO_CATALOG set to 1 to skip the gateway's model catalog (step 5) # CODEX_SETUP_NO_IMAGE set to 1 to leave image generation off (step 6) # # This file is ASCII only on purpose. Windows PowerShell 5.1 misreads UTF-8 files that have no # BOM, and "irm | iex" depends on the server's charset header, so every Chinese message is # written as \uXXXX escapes and decoded at run time by the U function. To change a message, # edit the escapes (any "native2ascii" style converter produces them). # # The rules match codex-setup.sh step for step; public-access/tests/test_codex_setup_cases.md # lists the shared cases. function Invoke-WulaobanCodexSetup { $BaseUrl = 'https://ai.5lb.cn/v1' # The gateway's model catalog: Codex adds its client_version and gets a Codex-format catalog. $CatalogUrl = "$BaseUrl/models" # Lowest Codex that gets the catalog: 0.162.1 is the version that was tested. $MinCodex = [version]'0.162.1' $ProviderId = 'wulaoban' $ProviderName = U '\u65e0\u8001\u677fAI' $DefaultModel = 'gpt-6.2-sol' $ReasoningEffort = 'medium' $NpmRegistry = 'https://registry.npmmirror.com' $NodeMirror = 'https://npmmirror.com/mirrors/node' # The desktop app mirror republishes the official packages unchanged (github.com/Wangnov/codex-app-mirror). $AppMirror = 'https://codexapp.agentsmirror.com/latest' $AppStore = 'https://apps.microsoft.com/detail/9plm9xgg6vks' $CodexDir = Join-Path $HOME '.codex' if ($env:CODEX_HOME) { $CodexDir = $env:CODEX_HOME } $ConfigFile = Join-Path $CodexDir 'config.toml' $AuthFile = Join-Path $CodexDir 'auth.json' $Model = $DefaultModel if ($env:CODEX_SETUP_MODEL) { $Model = $env:CODEX_SETUP_MODEL } $Stamp = Get-Date -Format 'yyyyMMdd-HHmmss' $Utf8NoBom = New-Object System.Text.UTF8Encoding($false) # Shared state for the helper functions (a hashtable is passed by reference). $S = @{ Model = $Model; ProviderId = $ProviderId; ProviderName = $ProviderName; BaseUrl = $BaseUrl; CatalogUrl = $CatalogUrl; ReasoningEffort = $ReasoningEffort; MinCodex = $MinCodex; CodexOk = $null; CodexOkVersion = ''; CodexAllOk = $false; CodexFound = ''; TomlPython = $null; Work = $null; Utf8 = $Utf8NoBom; Image = ($env:CODEX_SETUP_NO_IMAGE -ne '1'); ApiKey = $null } # The gateway only accepts TLS 1.2; older Windows PowerShell does not enable it by default. try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { } Write-Host (U '=== \u65e0\u8001\u677fAI\uff1aCodex \u5ba2\u6237\u7aef\u914d\u7f6e ===') -ForegroundColor Green Write-Host ((U '\u7f51\u5173\u5730\u5740\uff1a{0}') -f $BaseUrl) Write-Host '' # 1. Read the key. Already set up for the gateway: pressing Enter keeps the key it has. $ApiKey = $env:WULAOBAN_API_KEY $OldKey = $null $Reused = $false if (-not $ApiKey) { $OldKey = Get-ExistingKey $ConfigFile $AuthFile $ProviderId if ($OldKey) { Write-Host ((U '\u8fd9\u53f0\u7535\u8111\u5df2\u7ecf\u914d\u7f6e\u8fc7\u65e0\u8001\u677fAI \u7684\u5bc6\u94a5\uff08\u7ed3\u5c3e ****{0}\uff09\u3002') -f $OldKey.Substring($OldKey.Length - 4)) $prompt = U '\u76f4\u63a5\u56de\u8f66\u6cbf\u7528\u8fd9\u628a\u5bc6\u94a5\uff1b\u8981\u6362\u5bc6\u94a5\u5c31\u7c98\u8d34\u65b0\u7684\uff08\u7c98\u8d34\u65f6\u5c4f\u5e55\u4e0a\u4e0d\u663e\u793a\uff09\uff0c\u7136\u540e\u56de\u8f66' } else { $prompt = U '\u8bf7\u7c98\u8d34\u7ba1\u7406\u5458\u53d1\u7ed9\u4f60\u7684\u5bc6\u94a5\uff08\u4ee5 sk- \u5f00\u5934\uff0c\u7c98\u8d34\u65f6\u5c4f\u5e55\u4e0a\u4e0d\u663e\u793a\uff09\uff0c\u7136\u540e\u56de\u8f66' } $secure = Read-Host -Prompt $prompt -AsSecureString if ($secure) { $ApiKey = (New-Object System.Net.NetworkCredential('', $secure)).Password } } if ($ApiKey) { $ApiKey = $ApiKey -replace '\s', '' } if (-not $ApiKey -and $OldKey) { $ApiKey = $OldKey $Reused = $true Write-Host (U '\u6cbf\u7528\u539f\u6765\u7684\u5bc6\u94a5\u3002') } if (-not $ApiKey) { Write-Host (U '\u9519\u8bef\uff1a\u5bc6\u94a5\u4e0d\u80fd\u4e3a\u7a7a\u3002') -ForegroundColor Red return } if ($ApiKey -notmatch '^[A-Za-z0-9_-]+$') { Write-Host (U '\u9519\u8bef\uff1a\u5bc6\u94a5\u91cc\u6709\u4e0d\u8be5\u51fa\u73b0\u7684\u5b57\u7b26\uff0c\u8bf7\u91cd\u65b0\u590d\u5236\u4e00\u6b21\uff08\u53ea\u5e94\u5305\u542b\u5b57\u6bcd\u3001\u6570\u5b57\u3001- \u548c _\uff09\u3002') -ForegroundColor Red return } $S.ApiKey = $ApiKey if ($ApiKey -cnotmatch '^sk-') { Write-Host (U '\u63d0\u793a\uff1a\u5bc6\u94a5\u901a\u5e38\u4ee5 sk- \u5f00\u5934\uff0c\u8bf7\u786e\u8ba4\u590d\u5236\u5b8c\u6574\u3002') -ForegroundColor Yellow } # 2. Check the key against the gateway and fetch the model list Write-Host (U '\u6b63\u5728\u5411\u7f51\u5173\u6821\u9a8c\u5bc6\u94a5\u2026\u2026') $Models = @() try { $resp = Invoke-WebRequest -UseBasicParsing -Uri "$BaseUrl/models" -Headers @{ Authorization = "Bearer $ApiKey" } -TimeoutSec 20 try { $Models = @((ConvertFrom-Json $resp.Content).data | ForEach-Object { $_.id } | Sort-Object -Unique) } catch { } } catch { $code = 0 try { $code = [int]$_.Exception.Response.StatusCode } catch { } if ($code -eq 401 -and $Reused) { Write-Host (U '\u9519\u8bef\uff1a\u7f51\u5173\u4e0d\u8ba4\u539f\u6765\u7684\u5bc6\u94a5\uff08401\uff09\uff0c\u5b83\u53ef\u80fd\u5df2\u7ecf\u505c\u7528\u3002\u8bf7\u5230 https://ai.5lb.cn/me/ \u67e5\u770b\u6216\u627e\u7ba1\u7406\u5458\u8981\u65b0\u5bc6\u94a5\uff0c\u91cd\u65b0\u8fd0\u884c\u65f6\u7c98\u8d34\u3002\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -ForegroundColor Red } elseif ($code -eq 401) { Write-Host (U '\u9519\u8bef\uff1a\u7f51\u5173\u4e0d\u8ba4\u8fd9\u4e2a\u5bc6\u94a5\uff08401\uff09\u3002\u8bf7\u786e\u8ba4\u590d\u5236\u5b8c\u6574\uff0c\u6216\u627e\u7ba1\u7406\u5458\u91cd\u65b0\u8981\u4e00\u4e2a\u3002\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -ForegroundColor Red } elseif ($code -eq 0) { Write-ConnectFailure $S $_.Exception } else { Write-Host ((U '\u9519\u8bef\uff1a\u7f51\u5173\u8fd4\u56de\u4e86 {0}\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5\u6216\u8054\u7cfb\u7ba1\u7406\u5458\u3002\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $code) -ForegroundColor Red } return } if ($Models.Count -gt 0) { Write-Host ((U '\u5bc6\u94a5\u6709\u6548\u3002\u53ef\u7528\u6a21\u578b\uff1a{0}') -f ($Models -join ' ')) -ForegroundColor Green if ($Models -cnotcontains $Model) { Write-Host ((U '\u63d0\u793a\uff1a\u9ed8\u8ba4\u6a21\u578b {0} \u4e0d\u5728\u4e0a\u9762\u7684\u5217\u8868\u91cc\uff0c\u542f\u52a8\u65f6\u7528 codex -m \u6a21\u578b\u540d \u6307\u5b9a\u4e00\u4e2a\u5217\u8868\u91cc\u7684\u3002') -f $Model) -ForegroundColor Yellow } } else { Write-Host (U '\u5bc6\u94a5\u6709\u6548\u3002') -ForegroundColor Green } # 3. An existing ChatGPT login is only replaced after asking if (Test-Path -LiteralPath $AuthFile -PathType Leaf) { $oldAuth = [IO.File]::ReadAllText($AuthFile) # Deliberately case-insensitive: it only decides whether to ask first, and asking more is the safe side. if ($oldAuth -match '"(tokens|refresh_token|id_token)"') { Write-Host (U '\u8fd9\u53f0\u7535\u8111\u7684 Codex \u73b0\u5728\u767b\u5f55\u7740 ChatGPT \u8d26\u53f7\u3002\u7ee7\u7eed\u7684\u8bdd\u4f1a\u6539\u6210\u7528\u65e0\u8001\u677fAI \u7684\u5bc6\u94a5\uff0c') -ForegroundColor Yellow Write-Host ((U '\u539f\u6765\u7684\u767b\u5f55\u4fe1\u606f\u4f1a\u5907\u4efd\u5230 {0} \u3002\u60f3\u6362\u56de ChatGPT \u8d26\u53f7\u65f6\u8fd0\u884c\uff1a') -f "$AuthFile.bak-$Stamp") -ForegroundColor Yellow Write-Host ' powershell -c "irm https://ai.5lb.cn/helper/codex-restore.ps1 | iex"' -ForegroundColor Yellow Write-Host (U '\u4e4b\u524d\u7528 ChatGPT \u8d26\u53f7\u5f00\u7684\u5bf9\u8bdd\uff0c\u63a5\u7f51\u5173\u540e\u63a5\u7740\u804a\u4f1a\u62a5 invalid_api_key\uff0c\u5728\u684c\u9762\u5e94\u7528\u91cc\u5bf9\u5b83\u70b9\u300c\u5206\u652f\u300d\u6216\u8005\u65b0\u5f00\u4e00\u4e2a\u4f1a\u8bdd\u5373\u53ef\u3002') -ForegroundColor Yellow if ($env:CODEX_SETUP_YES -ne '1') { $answer = Read-Host -Prompt (U '\u7ee7\u7eed\u5417\uff1f(y/N)') if ($answer -notmatch '^[Yy]') { Write-Host (U '\u5df2\u53d6\u6d88\uff0c\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') return } } } } # 4. Phase one: config.toml and auth.json. Both candidates are written next to the real files and # checked when a validator is available; only then are they swapped in, config first. If auth # cannot be swapped in, config goes back to exactly what it was (or away, if there was none). if (-not (Test-Path -LiteralPath $CodexDir)) { New-Item -ItemType Directory -Path $CodexDir -Force | Out-Null } if ((Test-Path -LiteralPath $ConfigFile -PathType Container) -or (Test-Path -LiteralPath $AuthFile -PathType Container)) { Write-Host ((U '\u9519\u8bef\uff1a{0} \u6216 {1} \u662f\u4e2a\u76ee\u5f55\uff0c\u811a\u672c\u4e0d\u5904\u7406\u3002\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $ConfigFile, $AuthFile) -ForegroundColor Red return } $S.Work = Join-Path ([IO.Path]::GetTempPath()) ('codex-setup-' + [guid]::NewGuid().ToString('N')) try { New-Item -ItemType Directory -Path $S.Work -ErrorAction Stop | Out-Null } catch { Write-Host ((U '\u9519\u8bef\uff1a\u5efa\u4e0d\u4e86\u4e34\u65f6\u76ee\u5f55\uff08{0}\uff09\uff0c\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $_.Exception.Message) -ForegroundColor Red return } $CfgNew = $null $AuthNew = $null try { Find-Codex $S Find-TomlPython $S $HadConfig = Test-Path -LiteralPath $ConfigFile -PathType Leaf $OldLines = $null if ($HadConfig) { $OldLines = [IO.File]::ReadAllLines($ConfigFile, $Utf8NoBom) } $CfgNew = New-SiblingTemp $ConfigFile $AuthNew = New-SiblingTemp $AuthFile try { [IO.File]::WriteAllLines($CfgNew, (Build-Config $S $OldLines $false 'none'), $Utf8NoBom) $authText = "{`n `"auth_mode`": `"apikey`",`n `"OPENAI_API_KEY`": `"$ApiKey`"`n}`n" [IO.File]::WriteAllText($AuthNew, $authText, $Utf8NoBom) [void](Protect-File $CfgNew) [void](Protect-File $AuthNew) } catch { Write-Host ((U '\u9519\u8bef\uff1a\u5199\u4e0d\u4e86\u4e34\u65f6\u6587\u4ef6\uff08{0}\uff09\uff0c\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $_.Exception.Message) -ForegroundColor Red return } $Checked = '' if ($S.CodexOk -or $S.TomlPython) { $err = Test-Candidate $S $CfgNew $false if ($err) { Write-Host ((U '\u9519\u8bef\uff1a\u751f\u6210\u7684 config.toml \u6ca1\u901a\u8fc7\u6821\u9a8c\uff08{0}\uff09\u3002\u539f\u6765\u7684\u914d\u7f6e\u53ef\u80fd\u6709\u683c\u5f0f\u9519\u8bef\uff0c\u6216\u8005\u7528\u4e86\u811a\u672c\u4e0d\u8ba4\u8bc6\u7684\u5199\u6cd5\uff0c\u8bf7\u5148\u4fee\u597d\u3002\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $err) -ForegroundColor Red return } if ($S.CodexOk) { $Checked = 'codex ' + $S.CodexOkVersion } if ($S.TomlPython) { if ($Checked) { $Checked += (U '\u3001') }; $Checked += 'Python tomllib' } } # Both backups must exist and match byte for byte before the first swap. Copy-Item errors are # non-terminating under the default ErrorActionPreference, so -ErrorAction Stop turns them into # exceptions the catch below sees. try { if ($HadConfig) { Copy-Item -LiteralPath $ConfigFile -Destination "$ConfigFile.bak-$Stamp" -Force -ErrorAction Stop if (-not (Test-SameBytes $ConfigFile "$ConfigFile.bak-$Stamp")) { throw "$ConfigFile.bak-$Stamp" } [void](Protect-File "$ConfigFile.bak-$Stamp") Write-Host ((U '\u539f\u914d\u7f6e\u5df2\u5907\u4efd\uff1a{0}') -f "$ConfigFile.bak-$Stamp") } if (Test-Path -LiteralPath $AuthFile -PathType Leaf) { Copy-Item -LiteralPath $AuthFile -Destination "$AuthFile.bak-$Stamp" -Force -ErrorAction Stop if (-not (Test-SameBytes $AuthFile "$AuthFile.bak-$Stamp")) { throw "$AuthFile.bak-$Stamp" } [void](Protect-File "$AuthFile.bak-$Stamp") Write-Host ((U '\u539f\u767b\u5f55\u4fe1\u606f\u5df2\u5907\u4efd\uff1a{0}') -f "$AuthFile.bak-$Stamp") } } catch { Write-Host ((U '\u9519\u8bef\uff1a\u5907\u4efd\u539f\u6587\u4ef6\u5931\u8d25\uff08{0}\uff09\uff0c\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $_.Exception.Message) -ForegroundColor Red return } if (-not (Move-Into $CfgNew $ConfigFile)) { Write-Host ((U '\u9519\u8bef\uff1a\u5199\u4e0d\u8fdb {0}\u3002\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $ConfigFile) -ForegroundColor Red return } $CfgNew = $null if (-not (Move-Into $AuthNew $AuthFile)) { if (Restore-Config $HadConfig "$ConfigFile.bak-$Stamp" $ConfigFile) { Write-Host ((U '\u9519\u8bef\uff1a\u5199\u4e0d\u8fdb {0}\uff0cconfig.toml \u5df2\u6362\u56de\u539f\u72b6\u3002\u6ca1\u6709\u5b8c\u6210\u914d\u7f6e\u3002') -f $AuthFile) -ForegroundColor Red } else { Write-Host ((U '\u9519\u8bef\uff1a\u5199\u4e0d\u8fdb {0}\uff0cconfig.toml \u4e5f\u6ca1\u80fd\u6362\u56de\u53bb\uff1a\u8bf7\u628a {1} \u6539\u56de config.toml\uff08\u539f\u6765\u6ca1\u6709\u8fd9\u4e2a\u6587\u4ef6\u7684\uff0c\u5220\u6389 config.toml\uff09\u3002') -f $AuthFile, "$ConfigFile.bak-$Stamp") -ForegroundColor Red } return } $AuthNew = $null # File.Replace keeps the ACL of the file it replaces, so the final files are restricted again here. if (-not ((Protect-File $ConfigFile) -and (Protect-File $AuthFile))) { Write-Host ((U '\u63d0\u793a\uff1a\u6ca1\u80fd\u628a {0} \u548c {1} \u8bbe\u6210\u53ea\u6709\u4f60\u80fd\u8bfb\uff0c\u8bf7\u81ea\u5df1\u68c0\u67e5\u8fd9\u4e24\u4e2a\u6587\u4ef6\u7684\u6743\u9650\uff08\u91cc\u9762\u6709\u5bc6\u94a5\uff09\u3002') -f $ConfigFile, $AuthFile) -ForegroundColor Yellow } if ($Checked) { Write-Host ((U '\u914d\u7f6e\u5df2\u5199\u5165\uff1a{0}\uff08\u5df2\u7528 {1} \u6821\u9a8c\uff09') -f $ConfigFile, $Checked) -ForegroundColor Green } else { Write-Host ((U '\u914d\u7f6e\u5df2\u5199\u5165\uff1a{0}') -f $ConfigFile) -ForegroundColor Green } Write-Host ((U '\u5bc6\u94a5\u5df2\u4fdd\u5b58\uff1a{0}') -f $AuthFile) -ForegroundColor Green if ($S.Image) { Write-Host (U '\u751f\u56fe\uff1a\u5df2\u5f00\u542f\u3002\u5728 Codex \u91cc\u76f4\u63a5\u8bf4\u300c\u753b\u4e00\u5f20\u2026\u2026\u300d\u5373\u53ef\uff0c\u6d88\u8017\u8ba2\u9605\u53f7\u7684\u751f\u56fe\u989d\u5ea6\u3002') -ForegroundColor Green Write-Host (U ' \u4e3a\u4e86\u8ba9 Codex \u63d0\u4f9b\u751f\u56fe\u5de5\u5177\uff0c\u5bc6\u94a5\u4e5f\u5199\u5728\u4e86 config.toml \u7684\u7f51\u5173\u6bb5\u91cc\uff08\u6587\u4ef6\u53ea\u6709\u4f60\u80fd\u8bfb\uff09\uff1b\u4e0d\u60f3\u8981\u5c31\u5148\u8bbe CODEX_SETUP_NO_IMAGE=1 \u518d\u91cd\u65b0\u8fd0\u884c\u3002') } else { Write-Host (U '\u751f\u56fe\uff1a\u6ca1\u6709\u5f00\u542f\uff08CODEX_SETUP_NO_IMAGE=1\uff09\u3002\u5bc6\u94a5\u53ea\u5728 auth.json \u91cc\uff1b\u60f3\u5f00\u5c31\u4e0d\u8bbe\u8fd9\u4e2a\u53d8\u91cf\u91cd\u65b0\u8fd0\u884c\u3002') } Write-Host '' # 6. Install the Codex CLI when it is missing and npm is available $ShowManual = $false $ShowNode = $false $HasCli = $false $Codex = Find-Shim 'codex' $Npm = Find-Shim 'npm' if ($Codex) { $HasCli = $true $ver = '' try { $ver = (& $Codex --version 2>$null | Select-Object -First 1) } catch { } Write-Host ((U '\u5df2\u5b89\u88c5 Codex \u547d\u4ee4\u884c\uff1a{0}') -f $ver) } elseif ($env:CODEX_SETUP_SKIP_INSTALL -eq '1') { Write-Host (U '\u6309\u8981\u6c42\u8df3\u8fc7\u4e86 Codex \u547d\u4ee4\u884c\u7684\u5b89\u88c5\u3002') } elseif ($Npm) { Write-Host (U '\u6ca1\u6709\u68c0\u6d4b\u5230 Codex \u547d\u4ee4\u884c\uff0c\u6b63\u5728\u7528 npm \u4ece\u56fd\u5185\u955c\u50cf\u5b89\u88c5\uff08\u5b89\u88c5\u5305\u4e00\u767e\u591a MB\uff0c\u8bf7\u7a0d\u7b49\uff09\u2026\u2026') & $Npm install -g '@openai/codex' "--registry=$NpmRegistry" if ($LASTEXITCODE -eq 0) { $HasCli = $true Write-Host (U '\u5b89\u88c5\u5b8c\u6210\u3002\u5f53\u524d\u7a97\u53e3\u627e\u4e0d\u5230 codex \u547d\u4ee4\u7684\u8bdd\uff0c\u5173\u6389\u7a97\u53e3\u91cd\u65b0\u6253\u5f00\u4e00\u4e2a\u3002') -ForegroundColor Green } else { Write-Host (U '\u81ea\u52a8\u5b89\u88c5\u6ca1\u6709\u6210\u529f\u3002\u53ef\u4ee5\u7528\u7ba1\u7406\u5458\u8eab\u4efd\u6253\u5f00\u547d\u4ee4\u63d0\u793a\u7b26\u540e\u624b\u52a8\u6267\u884c\uff1a') -ForegroundColor Yellow Write-Host " npm install -g @openai/codex --registry=$NpmRegistry" -ForegroundColor Yellow $ShowManual = $true } } else { Write-Host (U '\u6ca1\u6709\u68c0\u6d4b\u5230 Codex \u547d\u4ee4\u884c\uff0c\u4e5f\u6ca1\u6709 npm\uff0c\u6ca1\u6cd5\u81ea\u52a8\u5b89\u88c5\u3002\u53ef\u4ee5\u624b\u52a8\u4e0b\u8f7d\u5b89\u88c5\uff1a') -ForegroundColor Yellow $ShowManual = $true $ShowNode = $true } # When the CLI could not be installed, list manual downloads. The desktop app needs no # Node.js and reads the same config; the Microsoft Store comes first because it opens from # China and keeps the app updated, and the mirrored MSIX needs administrator rights. if ($ShowManual) { $Arm64 = ($env:PROCESSOR_ARCHITECTURE -eq 'ARM64') try { $Arm64 = ([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture -eq 'Arm64') } catch { } $appArch = 'win-x64' if ($Arm64) { $appArch = 'win-arm64' } Write-Host (U '\u684c\u9762\u5e94\u7528\uff08\u4e0d\u7528 Node.js\uff0c\u5b89\u88c5\u5305\u8fd1 1 GB\uff0c\u88c5\u597d\u540e\u5e94\u7528\u540d\u53eb ChatGPT\uff09\uff1a') -ForegroundColor Yellow Write-Host ((U ' \u5fae\u8f6f\u5546\u5e97\uff1a{0}') -f $AppStore) -ForegroundColor Yellow Write-Host ((U ' \u56fd\u5185\u955c\u50cf\uff1a{0} \uff08\u53cc\u51fb\u5b89\u88c5\uff0c\u9700\u8981\u7ba1\u7406\u5458\u6743\u9650\uff09') -f "$AppMirror/$appArch") -ForegroundColor Yellow if ($ShowNode) { # The newest LTS release on the mirror, e.g. v24.22.0; left empty when the index cannot be read. $NodeVersion = $null try { $index = ConvertFrom-Json (Invoke-WebRequest -UseBasicParsing -Uri "$NodeMirror/index.json" -TimeoutSec 15).Content foreach ($release in $index) { if ($release.lts) { $NodeVersion = $release.version; break } } } catch { } $nodeArch = 'x64' if ($Arm64) { $nodeArch = 'arm64' } Write-Host (U '\u547d\u4ee4\u884c\u7248\uff1a\u5148\u5b89\u88c5 Node.js \u957f\u671f\u652f\u6301\u7248\uff0c\u518d\u91cd\u65b0\u8fd0\u884c\u672c\u811a\u672c\uff1a') -ForegroundColor Yellow if ($NodeVersion) { Write-Host ((U ' \u56fd\u5185\u955c\u50cf\uff1a{0}') -f "$NodeMirror/$NodeVersion/node-$NodeVersion-$nodeArch.msi") -ForegroundColor Yellow } Write-Host (U ' \u5b98\u65b9\u4e0b\u8f7d\uff1ahttps://nodejs.org/zh-cn/download') -ForegroundColor Yellow } Write-Host (U '\u914d\u7f6e\u5df2\u7ecf\u5199\u597d\uff0c\u88c5\u4e0a\u5c31\u80fd\u7528\u3002\u5df2\u7ecf\u5728\u7528 VS Code \u63d2\u4ef6\u6216\u684c\u9762\u5e94\u7528\u7684\u4e0d\u7528\u518d\u88c5\uff0c\u91cd\u542f\u5b83\u4eec\u5373\u53ef\u3002') -ForegroundColor Yellow } # In PowerShell, "codex" runs npm's codex.ps1 shim, which the default execution policy blocks; # Command Prompt runs codex.cmd and is unaffected. Offer RemoteSigned for the current user and # change it only when the user agrees. A policy set by Group Policy cannot be changed from here. $Lasting = $null if ($HasCli) { try { $Lasting = Get-LastingExecutionPolicy } catch { } } if ($Lasting -and (@('Restricted', 'AllSigned') -contains $Lasting[1])) { Write-Host '' Write-Host (U '\u8fd9\u53f0\u7535\u8111\u7684 PowerShell \u4e0d\u8ba9\u8fd0\u884c\u811a\u672c\uff0c\u5728 PowerShell \u91cc\u76f4\u63a5\u8f93\u5165 codex \u4f1a\u63d0\u793a\u300c\u7981\u6b62\u8fd0\u884c\u811a\u672c\u300d\uff0c\u547d\u4ee4\u63d0\u793a\u7b26\u91cc\u4e0d\u53d7\u5f71\u54cd\u3002') -ForegroundColor Yellow if ($Lasting[0] -like '*Policy') { Write-Host (U '\u8fd9\u9879\u8bbe\u7f6e\u7531\u516c\u53f8\u7684\u7ec4\u7b56\u7565\u7ba1\u7740\uff0c\u8fd9\u91cc\u6539\u4e0d\u4e86\uff1a\u5728 PowerShell \u91cc\u6539\u8f93\u5165 codex.cmd\uff0c\u6216\u8005\u5728\u547d\u4ee4\u63d0\u793a\u7b26\u91cc\u4f7f\u7528\u3002') -ForegroundColor Yellow } else { Write-Host (U '\u53ef\u4ee5\u6539\u6210\u5141\u8bb8\u8fd0\u884c\u672c\u673a\u7684\u811a\u672c\uff08\u4ece\u7f51\u4e0a\u4e0b\u8f7d\u7684\u811a\u672c\u4ecd\u8981\u6709\u7b7e\u540d\uff09\uff0c\u53ea\u6539\u4f60\u81ea\u5df1\u7684\u8d26\u53f7\u3002') $answer = Read-Host -Prompt (U '\u73b0\u5728\u6539\u5417\uff1f(y/N)') $Fixed = $false if ($answer -match '^[Yy]') { # Started with -ExecutionPolicy Bypass, the change is saved but reported as overridden, so check the result instead. try { Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force -ErrorAction SilentlyContinue } catch { } try { $Fixed = ([string](Get-ExecutionPolicy -Scope CurrentUser) -eq 'RemoteSigned') } catch { } } if ($Fixed) { Write-Host (U '\u5df2\u6539\u597d\uff0c\u91cd\u65b0\u6253\u5f00 PowerShell \u540e\u53ef\u4ee5\u76f4\u63a5\u8f93\u5165 codex\u3002') -ForegroundColor Green } else { Write-Host (U '\u6ca1\u6709\u6539\u3002\u5728 PowerShell \u91cc\u53ef\u4ee5\u6539\u8f93\u5165 codex.cmd\uff1b\u4ee5\u540e\u60f3\u6539\uff0c\u5728 PowerShell \u91cc\u8fd0\u884c\u4e00\u6b21\u4e0b\u9762\u8fd9\u884c\uff1a') -ForegroundColor Yellow Write-Host ' Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force' -ForegroundColor Yellow } } } # 7. Phase two, after the install: check the codex version again and add the catalog only when # it is new enough. There is always a codex to validate with here; any failure keeps phase one. Write-Host '' Add-Catalog $S $ConfigFile } finally { foreach ($f in @($CfgNew, $AuthNew)) { if ($f -and (Test-Path -LiteralPath $f)) { Remove-Item -LiteralPath $f -Force -ErrorAction SilentlyContinue } } if ($S.Work -and (Test-Path -LiteralPath $S.Work)) { Remove-Item -LiteralPath $S.Work -Recurse -Force -ErrorAction SilentlyContinue } } Write-Host '' Write-Host (U '\u5b8c\u6210\u3002\u7528\u6cd5\uff1a\u5728\u547d\u4ee4\u63d0\u793a\u7b26\u6216 PowerShell \u91cc\u8fdb\u5165\u4f60\u7684\u9879\u76ee\u76ee\u5f55\uff0c\u8fd0\u884c codex\u3002') -ForegroundColor Green Write-Host (U 'VS Code \u63d2\u4ef6\u548c\u684c\u9762\u5e94\u7528\u8bfb\u7684\u662f\u540c\u4e00\u4efd\u914d\u7f6e\uff0c\u91cd\u542f\u540e\u751f\u6548\u3002') Write-Host (U '\u8981\u6362\u5bc6\u94a5\u6216\u6362\u6a21\u578b\uff0c\u91cd\u65b0\u8fd0\u884c\u672c\u811a\u672c\u5373\u53ef\u3002') } # Decodes the \uXXXX escapes used for every Chinese message in this file. function U([string]$Text) { return [regex]::Unescape($Text) } # The key from an earlier run of this script, or $null: config.toml has the gateway section, auth.json is # not a ChatGPT login and holds a well-formed key. function Get-ExistingKey([string]$ConfigFile, [string]$AuthFile, [string]$ProviderId) { try { if (-not (Test-Path -LiteralPath $ConfigFile -PathType Leaf) -or -not (Test-Path -LiteralPath $AuthFile -PathType Leaf)) { return $null } $section = '(?m)^[ \t]*\[model_providers\.' + [regex]::Escape($ProviderId) + '\][ \t]*(#.*)?\r?$' if ([IO.File]::ReadAllText($ConfigFile) -cnotmatch $section) { return $null } $auth = [IO.File]::ReadAllText($AuthFile) if ($auth -match '"(refresh_token|id_token)"') { return $null } $m = [regex]::Match($auth, '"OPENAI_API_KEY"\s*:\s*"([A-Za-z0-9_-]{8,})"') if ($m.Success) { return $m.Groups[1].Value } } catch { } return $null } # B-056: what kind of network failure the gateway check hit, from the exception chain: Windows PowerShell 5.1 # throws a WebException with a Status, PowerShell 7 an HttpRequestException with an HttpRequestError (.NET 8 # and later), and a cancellation when -TimeoutSec runs out. Returns '' when it cannot tell. function Get-ConnectKind($Err) { $e = $Err while ($e) { $kind = '' if ($e -is [System.Net.WebException]) { $kind = [string]$e.Status } if (-not $kind) { try { $kind = [string]$e.HttpRequestError } catch { } } if (-not $kind -and ($e -is [System.TimeoutException] -or $e -is [System.OperationCanceledException])) { $kind = 'Timeout' } switch ($kind) { 'NameResolutionFailure' { return 'dns' } 'NameResolutionError' { return 'dns' } 'ProxyNameResolutionFailure' { return 'proxy' } 'ProxyTunnelError' { return 'proxy' } 'ConnectFailure' { return 'connect' } 'ConnectionError' { return 'connect' } 'Timeout' { return 'timeout' } 'SecureChannelFailure' { return 'tls' } 'SecureConnectionError' { return 'tls' } 'TrustFailure' { return 'cert' } 'ReceiveFailure' { return 'cut' } 'SendFailure' { return 'cut' } 'ConnectionClosed' { return 'cut' } 'KeepAliveFailure' { return 'cut' } 'ResponseEnded' { return 'cut' } } if ($e -is [System.Security.Authentication.AuthenticationException]) { return 'tls' } $e = $e.InnerException } return '' } # Which Windows proxy settings are on (Internet Options, which Invoke-WebRequest follows): 'proxy' for a # proxy server, 'pac' for an automatic configuration script. Nothing outside Windows. function Get-SystemProxy { $found = @() try { $p = Get-ItemProperty -LiteralPath 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -ErrorAction Stop if ($p.ProxyEnable -eq 1) { $found += 'proxy' } if ($p.AutoConfigURL) { $found += 'pac' } } catch { } return $found } # B-056: the gateway could not be reached at all (no HTTP status). Says why (Get-ConnectKind), then one line the # member can pass on: the exception type and its WebException.Status or HttpRequestError name, never the message. # Messages can carry the proxy's address and port ("actively refused it. (127.0.0.1:1)") or the whole proxy # string with its password, and the proxy can come from the Windows setting as well as the variables, so no # text filter is trusted (code review C1-2, rereview R2). Then whether a proxy is set: environment variables or # the Windows setting, by name only, never the address. function Write-ConnectFailure($S, $Err) { $hostName = ([Uri]$S.BaseUrl).Host $reason = '' switch (Get-ConnectKind $Err) { 'dns' { $reason = (U '\u89e3\u6790\u4e0d\u4e86\u57df\u540d {0}\uff0cDNS \u4e0d\u901a\u6216\u8005\u7f51\u7edc\u6ca1\u8fde\u4e0a') -f $hostName } 'proxy' { $reason = U '\u89e3\u6790\u4e0d\u4e86\u4ee3\u7406\u670d\u52a1\u5668\u7684\u5730\u5740\u6216\u8005\u8fde\u4e0d\u4e0a\u4ee3\u7406\uff0c\u4ee3\u7406\u8bbe\u7f6e\u53ef\u80fd\u6709\u8bef' } 'connect' { $reason = U '\u8fde\u63a5\u88ab\u62d2\u7edd\u6216\u8005\u7f51\u7edc\u4e0d\u901a' } 'timeout' { $reason = U '\u8fde\u63a5\u8d85\u65f6' } 'tls' { $reason = U '\u52a0\u5bc6\u8fde\u63a5\uff08TLS\uff09\u63e1\u624b\u5931\u8d25\uff0c\u5e38\u89c1\u539f\u56e0\u662f\u4ee3\u7406\u6216\u52a0\u901f\u5668\u62e6\u4e0b\u4e86\u8fd9\u4e2a\u7f51\u7ad9' } 'cert' { $reason = U '\u8bc1\u4e66\u6821\u9a8c\u5931\u8d25\uff0c\u53ef\u80fd\u6709\u4ee3\u7406\u6216\u5b89\u5168\u8f6f\u4ef6\u5728\u62e6\u622a\u52a0\u5bc6\u8fde\u63a5' } 'cut' { $reason = U '\u8fde\u63a5\u88ab\u4e2d\u9014\u65ad\u5f00' } } if ($reason) { Write-Host ((U '\u9519\u8bef\uff1a\u8fde\u4e0d\u4e0a {0}\uff1a{1}\u3002\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $S.BaseUrl, $reason) -ForegroundColor Red } else { Write-Host ((U '\u9519\u8bef\uff1a\u8fde\u4e0d\u4e0a {0}\u3002\u6ca1\u6709\u6539\u52a8\u4efb\u4f55\u6587\u4ef6\u3002') -f $S.BaseUrl) -ForegroundColor Red } $kind = '' $e = $Err while ($e -and -not $kind) { if ($e -is [System.Net.WebException]) { $kind = [string]$e.Status } if (-not $kind) { try { $kind = [string]$e.HttpRequestError } catch { } } $e = $e.InnerException } $label = $Err.GetType().FullName if ($kind) { $label = $label + ' / ' + $kind } Write-Host ((U '\u62a5\u9519\u7c7b\u578b\uff08\u627e\u7ba1\u7406\u5458\u65f6\u628a\u8fd9\u4e00\u884c\u53d1\u8fc7\u53bb\uff09\uff1a{0}') -f $label) # Windows treats variable names case-insensitively; -notcontains does too, so each one is listed once. $names = @() foreach ($n in 'HTTPS_PROXY', 'https_proxy', 'ALL_PROXY', 'all_proxy', 'HTTP_PROXY', 'http_proxy') { if ([Environment]::GetEnvironmentVariable($n) -and ($names -notcontains $n)) { $names += $n } } $sys = @() foreach ($k in @(Get-SystemProxy)) { if ($k -eq 'proxy') { $sys += (U '\u4ee3\u7406\u670d\u52a1\u5668') } elseif ($k -eq 'pac') { $sys += (U '\u81ea\u52a8\u4ee3\u7406\uff08PAC\uff09') } } $list = U '\u3001' if ($names.Count -gt 0 -or $sys.Count -gt 0) { $parts = @() if ($names.Count -gt 0) { $parts += ((U '\u73af\u5883\u53d8\u91cf {0}') -f ($names -join $list)) } if ($sys.Count -gt 0) { $parts += ((U '\u7cfb\u7edf\u8bbe\u7f6e\u91cc\u5f00\u7740{0}') -f ($sys -join $list)) } Write-Host ((U '\u68c0\u6d4b\u5230\u4ee3\u7406\uff1a{0}\u3002') -f ($parts -join (U '\uff1b'))) Write-Host ((U '\u5982\u679c\u5f00\u7740 Clash \u7b49\u4ee3\u7406\u6216\u52a0\u901f\u5668\uff0c\u5148\u5173\u6389\u518d\u8fd0\u884c\uff0c\u6216\u8005\u628a {0} \u8bbe\u6210\u76f4\u8fde\u3002') -f $hostName) } else { Write-Host ((U '\u8bf7\u68c0\u67e5\u7f51\u7edc\uff1b\u7528\u4e86\u4ee3\u7406\u6216\u52a0\u901f\u5668\u7684\u8bdd\uff0c\u5148\u5173\u6389\u518d\u8fd0\u884c\uff0c\u6216\u8005\u628a {0} \u8bbe\u6210\u76f4\u8fde\u3002') -f $hostName) } } # npm puts a .ps1 shim next to each .cmd one, and PowerShell picks the .ps1 first, which the default # execution policy (Restricted) refuses to run. The .cmd shim runs under any policy. function Find-Shim([string]$Name) { $found = Get-Command "$Name.cmd" -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $found) { $found = Get-Command $Name -ErrorAction SilentlyContinue | Select-Object -First 1 } return $found } # The policy a PowerShell window opened later will use, as (scope, policy). The Process scope is # skipped because it only lasts for this run; nothing set anywhere means Restricted on Windows desktops. function Get-LastingExecutionPolicy { foreach ($scope in 'MachinePolicy', 'UserPolicy', 'CurrentUser', 'LocalMachine') { $policy = [string](Get-ExecutionPolicy -Scope $scope) if ($policy -ne 'Undefined') { return @($scope, $policy) } } return @('Default', 'Restricted') } # ---- Model catalog helpers (same rules as codex-setup.sh) ---- # A temporary file next to the target, so the final swap is a rename on the same volume. function New-SiblingTemp([string]$Target) { $dir = Split-Path -Parent $Target $name = '.' + (Split-Path -Leaf $Target) + '.' + [guid]::NewGuid().ToString('N').Substring(0, 8) return (Join-Path $dir $name) } # Lets only the current user read and write the file (the key may be in it): on Windows an ACL with just # the current user and no inherited entries; elsewhere (PowerShell 7 on macOS / Linux, used by the tests) # mode 600. Returns $false when that could not be done. function Protect-File([string]$Path) { try { if ($env:OS -eq 'Windows_NT') { $acl = New-Object System.Security.AccessControl.FileSecurity $acl.SetAccessRuleProtection($true, $false) $me = [System.Security.Principal.WindowsIdentity]::GetCurrent().User $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($me, 'FullControl', 'Allow'))) Set-Acl -LiteralPath $Path -AclObject $acl -ErrorAction Stop } else { [IO.File]::SetUnixFileMode($Path, [IO.UnixFileMode]'UserRead, UserWrite') } return $true } catch { return $false } } # Swaps $Src in for $Dst: File.Replace when $Dst exists (one rename on NTFS), File.Move otherwise. function Move-Into([string]$Src, [string]$Dst) { try { if (Test-Path -LiteralPath $Dst -PathType Leaf) { [IO.File]::Replace($Src, $Dst, [NullString]::Value) } else { [IO.File]::Move($Src, $Dst) } return $true } catch { return $false } } # True when both files exist and have the same bytes: same length, then byte by byte. (Comparing # Base64 strings with -eq would be wrong: -eq ignores case, Base64 does not.) function Test-SameBytes([string]$A, [string]$B) { try { $x = [IO.File]::ReadAllBytes($A) $y = [IO.File]::ReadAllBytes($B) } catch { return $false } if ($x.Length -ne $y.Length) { return $false } for ($i = 0; $i -lt $x.Length; $i++) { if ($x[$i] -ne $y[$i]) { return $false } } return $true } # Puts config.toml back after a failed auth.json swap: byte for byte from the backup just made, or # removed when there was no config before. Returns $true only when the result was checked: the # target equals the backup, or the target is gone. Copy/Remove errors are made terminating so a # failure cannot be reported as a successful restore. function Restore-Config([bool]$Had, [string]$Backup, [string]$Target) { $t = $null try { if ($Had) { $t = New-SiblingTemp $Target Copy-Item -LiteralPath $Backup -Destination $t -Force -ErrorAction Stop if (-not (Move-Into $t $Target)) { return $false } return (Test-SameBytes $Backup $Target) } if (Test-Path -LiteralPath $Target) { Remove-Item -LiteralPath $Target -Force -ErrorAction Stop } return (-not (Test-Path -LiteralPath $Target)) } catch { return $false } finally { if ($t -and (Test-Path -LiteralPath $t)) { Remove-Item -LiteralPath $t -Force -ErrorAction SilentlyContinue } } } # The codex CLI version as "X.Y.Z" taken from "codex-cli X.Y.Z"; suffixes such as -alpha.N are ignored. function Get-CodexVersion($Cmd) { $raw = '' try { $raw = [string](& $Cmd --version 2>$null | Select-Object -First 1) } catch { } if ($raw -cmatch '^codex-cli (\d+)\.(\d+)\.(\d+)') { $shown = ($raw -split ' ')[1] return @([version]("{0}.{1}.{2}" -f $Matches[1], $Matches[2], $Matches[3]), $shown) } return $null } # Finds the codex CLI (on PATH, or in npm's global folder right after installing it) and reads its # version. Windows only checks the CLI. Sets CodexOk (validator), CodexAllOk and CodexFound in $S. function Find-Codex($S) { $S.CodexOk = $null; $S.CodexOkVersion = ''; $S.CodexAllOk = $false; $S.CodexFound = '' $path = $null $cli = Find-Shim 'codex' if ($cli) { $path = $cli.Path } if (-not $path) { $npm = Find-Shim 'npm' if ($npm) { $prefix = '' try { $prefix = [string](& $npm.Path prefix -g 2>$null | Select-Object -First 1) } catch { } if ($prefix) { $cand = Join-Path $prefix.Trim() 'codex.cmd' if (Test-Path -LiteralPath $cand) { $path = $cand } } } } if (-not $path) { $S.CodexFound = (U '\u6ca1\u6709\u627e\u5230 codex'); return } $v = Get-CodexVersion $path if (-not $v) { $S.CodexFound = (U '\u547d\u4ee4\u884c codex \u8bfb\u4e0d\u51fa\u7248\u672c'); return } if ($v[0] -ge $S.MinCodex) { $S.CodexOk = $path; $S.CodexOkVersion = $v[1]; $S.CodexAllOk = $true $S.CodexFound = (U '\u547d\u4ee4\u884c codex {0}') -f $v[1] } else { $S.CodexFound = (U '\u547d\u4ee4\u884c codex {0}\uff08\u4f4e\u4e8e {1}\uff09') -f $v[1], $S.MinCodex } } # A Python with tomllib (3.11 or later) adds a full parse. The python.exe / python3.exe aliases in # WindowsApps open the Microsoft Store instead of running, so they are skipped. function Find-TomlPython($S) { $S.TomlPython = $null foreach ($name in 'python', 'python3') { $found = Get-Command $name -CommandType Application -ErrorAction SilentlyContinue | Where-Object { $_.Path -notlike '*\WindowsApps\*' } | Select-Object -First 1 if (-not $found) { continue } try { & $found.Path -c 'import tomllib' 2>$null | Out-Null } catch { continue } if ($LASTEXITCODE -eq 0) { $S.TomlPython = $found.Path; return } } } # The full-parse check, run as a file (passing it with -c would lose its quotes in PowerShell 5.1). # Exit codes: 2 not valid TOML (the message is printed), 3 discovery not true, 4 wrong catalog url, # 5 a top-level model_catalog_json, 6 image settings incomplete, 7 image settings left behind. # The key is never passed on the command line; only whether image generation is on. $script:TomlCheck = @' import sys, tomllib path, need, url, pid, image = sys.argv[1:6] try: with open(path, "rb") as f: data = tomllib.load(f) except (OSError, ValueError) as e: print(e) sys.exit(2) provider = data.get("model_providers", {}).get(pid, {}) headers = provider.get("http_headers") if image == "1": token = provider.get("experimental_bearer_token") if (provider.get("requires_openai_auth") is not False or not isinstance(token, str) or not token or not isinstance(headers, dict) or headers.get("x-openai-actor-authorization") != "local-image-extension"): sys.exit(6) elif provider.get("requires_openai_auth") is not True or "experimental_bearer_token" in provider or headers is not None: sys.exit(7) if need == "1": features = data.get("features") provider = data.get("model_providers", {}).get(pid, {}) if not isinstance(features, dict) or features.get("api_key_model_discovery") is not True: sys.exit(3) if provider.get("model_catalog_url") != url: sys.exit(4) if "model_catalog_json" in data: sys.exit(5) '@ # Validates a candidate config; returns $null when it passes, otherwise the reason. # codex: "codex features list" loads the whole config ("codex debug models --bundled" does not read it). # CODEX_HOME is a temporary folder holding only the candidate config.toml (no auth.json), and so # is the working folder. Exit code 0 is required; with the catalog, it must list # api_key_model_discovery as true. # tomllib: when a Python with tomllib is available, a full parse as well. function Test-Candidate($S, [string]$Candidate, [bool]$NeedCatalog) { if ($S.CodexOk) { $vdir = Join-Path $S.Work ('validate-' + [guid]::NewGuid().ToString('N')) try { New-Item -ItemType Directory -Path $vdir -ErrorAction Stop | Out-Null Copy-Item -LiteralPath $Candidate -Destination (Join-Path $vdir 'config.toml') -ErrorAction Stop } catch { return ((U '\u51c6\u5907\u6821\u9a8c\u7528\u7684\u4e34\u65f6\u76ee\u5f55\u5931\u8d25\uff1a{0}') -f $_.Exception.Message) } $oldHome = $env:CODEX_HOME $out = '' $rc = 1 Push-Location -LiteralPath $vdir try { $env:CODEX_HOME = $vdir $out = (& $S.CodexOk features list 2>&1 | Out-String) $rc = $LASTEXITCODE } catch { $out = [string]$_ } finally { $env:CODEX_HOME = $oldHome Pop-Location Remove-Item -LiteralPath $vdir -Recurse -Force -ErrorAction SilentlyContinue } if ($rc -ne 0) { $first = (($out -split "`n") | Where-Object { $_.Trim() } | Select-Object -First 2) -join ' ' return ((U 'codex {0} \u8bfb\u8fd9\u4efd\u914d\u7f6e\u51fa\u9519\uff1a{1}') -f $S.CodexOkVersion, $first) } if ($NeedCatalog) { $ok = $false foreach ($line in ($out -split "`n")) { $f = @($line.Trim() -split '\s+') if ($f.Count -ge 2 -and $f[0] -ceq 'api_key_model_discovery' -and $f[$f.Count - 1] -ceq 'true') { $ok = $true } } if (-not $ok) { return ((U 'codex {0} \u8bfb\u51fa\u6765\u7684 api_key_model_discovery \u4e0d\u662f true') -f $S.CodexOkVersion) } } } if ($S.TomlPython) { $check = Join-Path $S.Work 'toml-check.py' [IO.File]::WriteAllText($check, $script:TomlCheck, $S.Utf8) $need = '0' if ($NeedCatalog) { $need = '1' } $image = '0' if ($S.Image) { $image = '1' } $out = (& $S.TomlPython -I $check $Candidate $need $S.CatalogUrl $S.ProviderId $image 2>&1 | Out-String) switch ($LASTEXITCODE) { 0 { } 2 { return ((U 'TOML \u89e3\u6790\u51fa\u9519\uff1a{0}') -f $out.Trim()) } 3 { return (U 'features.api_key_model_discovery \u4e0d\u662f true') } 4 { return (U 'model_catalog_url \u4e0d\u5bf9') } 5 { return (U '\u9876\u5c42\u6709 model_catalog_json') } 6 { return (U '\u7f51\u5173\u6bb5\u7684\u751f\u56fe\u8bbe\u7f6e\u4e0d\u5bf9') } 7 { return (U '\u7f51\u5173\u6bb5\u8fd8\u7559\u7740\u751f\u56fe\u7684\u8bbe\u7f6e') } default { return ((U 'TOML \u68c0\u67e5\u6ca1\u6709\u8fd0\u884c\u6210\u529f\uff1a{0}') -f $out.Trim()) } } } return $null } # How many times $Delim occurs in $Line (left to right, no overlap). function Get-Count([string]$Line, [string]$Delim) { return ([regex]::Matches($Line, [regex]::Escape($Delim))).Count } # The multi-line string delimiter this line leaves open ('"""' or "'''"), or ''. Called outside strings only. function Get-OpenDelim([string]$Line) { $i = $Line.IndexOf('"""') $j = $Line.IndexOf("'''") if ($i -lt 0 -and $j -lt 0) { return '' } $d = "'''" if ($j -lt 0 -or ($i -ge 0 -and $i -lt $j)) { $d = '"""' } if ((Get-Count $Line $d) % 2 -eq 1) { return $d } return '' } $script:WordPattern = '[^A-Za-z0-9_-](features|api_key_model_discovery|model_catalog_json)[^A-Za-z0-9_-]' $script:SimpleHeader = '^\s*\[\s*features\s*\]\s*(#.*)?$' $script:SimpleKey = '^\s*api_key_model_discovery\s*=\s*(true|false)\s*(#.*)?$' # How the old config (except this script's own provider table) writes features. One word, as in the sh: # none / single (one unquoted [features] header, at most a plain api_key_model_discovery = true|false) / # localcatalog (a top-level model_catalog_json) / complex (any other form, or several headers). # Case-sensitive like TOML keys. Comments and multi-line strings are not definitions. function Get-FeaturesKind($S, [string[]]$Lines) { $ownTable = '^\s*\[model_providers\.' + [regex]::Escape($S.ProviderId) + '(\]|\.)' $table = ''; $own = $false; $ml = ''; $headers = 0; $complex = $false; $localCatalog = $false foreach ($line in $Lines) { if ($ml) { if ((Get-Count $line $ml) % 2 -eq 1) { $ml = '' }; continue } $ml = Get-OpenDelim $line if ($line -cmatch '^\s*(#|$)') { continue } if ($line -cmatch '^\s*\[') { $own = ($line -cmatch $ownTable) if ($own) { continue } if ($line -cmatch $script:SimpleHeader) { $headers++; $table = 'features'; continue } $table = 'other' if ((" $line ") -cmatch $script:WordPattern) { $complex = $true } continue } if ($own) { continue } if ($table -eq 'features' -and $line -cmatch $script:SimpleKey) { continue } if ($table -eq '' -and $line -cmatch '^\s*model_catalog_json\s*=') { $localCatalog = $true; continue } if ((" $line ") -cmatch $script:WordPattern) { $complex = $true } } if ($localCatalog) { return 'localcatalog' } if ($complex -or $headers -gt 1) { return 'complex' } if ($headers -eq 1) { return 'single' } return 'none' } # Adds api_key_model_discovery = true: under the single [features] header (dropping the plain lines # already there), or as a new [features] table at the end. function Add-FeaturesLine([string[]]$Lines, [string]$Kind) { $out = New-Object System.Collections.Generic.List[string] $ml = ''; $inside = $false foreach ($line in $Lines) { if ($ml) { if ((Get-Count $line $ml) % 2 -eq 1) { $ml = '' }; $out.Add($line); continue } $ml = Get-OpenDelim $line if ($line -cmatch '^\s*\[') { $inside = $false if ($Kind -eq 'single' -and $line -cmatch $script:SimpleHeader) { $out.Add($line) $out.Add('api_key_model_discovery = true') $inside = $true continue } } elseif ($inside -and $line -cmatch $script:SimpleKey) { continue } $out.Add($line) } if ($Kind -eq 'none') { $out.Add(''); $out.Add('[features]'); $out.Add('api_key_model_discovery = true') } return ,$out.ToArray() } # The whole config.toml as lines: this script's three top-level keys, the rest of the old config # (without the keys it replaces and without its own provider table, trailing blank lines removed so # they do not pile up), then the provider table; with $Catalog also the two catalog settings. function Build-Config($S, $OldLines, [bool]$Catalog, [string]$Kind) { $rest = New-Object System.Collections.Generic.List[string] if ($OldLines) { $top = $true $skip = $false $ownTable = '^\s*\[model_providers\.' + [regex]::Escape($S.ProviderId) + '(\]|\.)' foreach ($line in $OldLines) { # TOML keys are case-sensitive: MODEL or [model_providers.WULAOBAN] belong to the user (-cmatch, as in the sh). if ($line -match '^\s*\[') { $top = $false $skip = ($line -cmatch $ownTable) } if ($skip) { continue } if ($top -and ($line -cmatch '^\s*(model|model_provider|model_reasoning_effort)\s*=')) { continue } $rest.Add($line) } while ($rest.Count -gt 0 -and $rest[$rest.Count - 1] -match '^\s*$') { $rest.RemoveAt($rest.Count - 1) } } $restLines = $rest.ToArray() if ($Catalog) { $restLines = Add-FeaturesLine $restLines $Kind } $lines = New-Object System.Collections.Generic.List[string] $lines.Add("model = `"$($S.Model)`"") $lines.Add("model_provider = `"$($S.ProviderId)`"") $lines.Add("model_reasoning_effort = `"$($S.ReasoningEffort)`"") foreach ($line in $restLines) { $lines.Add($line) } $lines.Add('') $lines.Add("[model_providers.$($S.ProviderId)]") $lines.Add("name = `"$($S.ProviderName)`"") $lines.Add("base_url = `"$($S.BaseUrl)`"") $lines.Add('wire_api = "responses"') if ($S.Image) { # Image generation: Codex only offers image_gen without OpenAI auth and with this header. $lines.Add('requires_openai_auth = false') $lines.Add("experimental_bearer_token = `"$($S.ApiKey)`"") $lines.Add('http_headers = { "x-openai-actor-authorization" = "local-image-extension" }') } else { $lines.Add('requires_openai_auth = true') } if ($Catalog) { $lines.Add("model_catalog_url = `"$($S.CatalogUrl)`"") } return ,$lines.ToArray() } # Phase two: add the model catalog to the config phase one wrote. Only when the codex found is new # enough, so there is always a codex to validate with; any failure keeps phase one and only warns. function Add-Catalog($S, [string]$ConfigFile) { if ($env:CODEX_SETUP_NO_CATALOG -eq '1') { Write-Host (U '\u6309 CODEX_SETUP_NO_CATALOG=1 \u8df3\u8fc7\u4e86\u7f51\u5173\u7684\u6a21\u578b\u76ee\u5f55\u3002') return } Find-Codex $S if (-not $S.CodexAllOk) { Write-Host ((U '\u6ca1\u6709\u52a0\u7f51\u5173\u7684\u6a21\u578b\u76ee\u5f55\uff1a{0}\u3002') -f $S.CodexFound) -ForegroundColor Yellow if ($S.CodexFound -ceq (U '\u6ca1\u6709\u627e\u5230 codex')) { Write-Host ((U '\u88c5\u597d Codex\uff08{0} \u4ee5\u4e0a\uff09\u540e\u91cd\u65b0\u8fd0\u884c\u672c\u811a\u672c\uff0c\u6a21\u578b\u9009\u5355\u624d\u4f1a\u53ea\u663e\u793a\u7f51\u5173\u5f00\u653e\u7684\u6a21\u578b\u3002') -f $S.MinCodex) -ForegroundColor Yellow } else { Write-Host ((U '\u5347\u7ea7\u5230 {0} \u4ee5\u4e0a\u540e\u91cd\u65b0\u8fd0\u884c\u672c\u811a\u672c\uff0c\u6a21\u578b\u9009\u5355\u624d\u4f1a\u53ea\u663e\u793a\u7f51\u5173\u5f00\u653e\u7684\u6a21\u578b\u3002') -f $S.MinCodex) -ForegroundColor Yellow } return } $lines = [IO.File]::ReadAllLines($ConfigFile, $S.Utf8) $kind = Get-FeaturesKind $S $lines if ($kind -eq 'localcatalog') { Write-Host (U '\u6ca1\u6709\u52a0\u7f51\u5173\u7684\u6a21\u578b\u76ee\u5f55\uff1aconfig.toml \u9876\u5c42\u6709 model_catalog_json\uff08\u672c\u5730\u7684\u6a21\u578b\u76ee\u5f55\u6587\u4ef6\uff09\uff0c\u5b83\u6bd4\u7f51\u5173\u7684\u76ee\u5f55\u4f18\u5148\uff0c\u7f51\u5173\u76ee\u5f55\u4e0d\u4f1a\u751f\u6548\u3002') -ForegroundColor Yellow Write-Host (U '\u811a\u672c\u4e0d\u52a8\u4f60\u7684\u8fd9\u9879\u8bbe\u7f6e\uff1b\u60f3\u7528\u7f51\u5173\u7684\u76ee\u5f55\uff0c\u5220\u6389\u8fd9\u4e00\u884c\u540e\u91cd\u65b0\u8fd0\u884c\u672c\u811a\u672c\u3002') -ForegroundColor Yellow return } if ($kind -eq 'complex') { Write-Host (U '\u6ca1\u6709\u52a0\u7f51\u5173\u7684\u6a21\u578b\u76ee\u5f55\uff1aconfig.toml \u91cc features \u7684\u5199\u6cd5\u811a\u672c\u4e0d\u81ea\u52a8\u6539\uff08\u70b9\u952e\u3001\u5185\u8054\u8868\u3001\u5b50\u8868\u3001\u5e26\u5f15\u53f7\u6216\u8005\u591a\u5904\u5b9a\u4e49\uff09\u3002') -ForegroundColor Yellow Write-Host (U '\u628a features \u6539\u6210\u5355\u72ec\u4e00\u6bb5 [features] \u7684\u666e\u901a\u5199\u6cd5\u540e\u91cd\u65b0\u8fd0\u884c\u672c\u811a\u672c\uff1b\u6216\u8005\u81ea\u5df1\u5728 features \u91cc\u52a0 api_key_model_discovery = true\u3002') -ForegroundColor Yellow return } $cfg2 = New-SiblingTemp $ConfigFile try { [IO.File]::WriteAllLines($cfg2, (Build-Config $S $lines $true $kind), $S.Utf8) [void](Protect-File $cfg2) $err = Test-Candidate $S $cfg2 $true if ($err) { Write-Host ((U '\u6ca1\u6709\u52a0\u7f51\u5173\u7684\u6a21\u578b\u76ee\u5f55\uff1a\u52a0\u4e0a\u4ee5\u540e\u6ca1\u901a\u8fc7\u6821\u9a8c\uff08{0}\uff09\u3002\u4fdd\u7559\u4e86\u521a\u624d\u5199\u597d\u7684\u57fa\u672c\u914d\u7f6e\u3002') -f $err) -ForegroundColor Yellow return } if (-not (Move-Into $cfg2 $ConfigFile)) { Write-Host ((U '\u6ca1\u6709\u52a0\u7f51\u5173\u7684\u6a21\u578b\u76ee\u5f55\uff1a\u5199\u5165 {0} \u5931\u8d25\u3002\u4fdd\u7559\u4e86\u521a\u624d\u5199\u597d\u7684\u57fa\u672c\u914d\u7f6e\u3002') -f $ConfigFile) -ForegroundColor Yellow return } [void](Protect-File $ConfigFile) Write-Host ((U '\u5df2\u52a0\u4e0a\u7f51\u5173\u7684\u6a21\u578b\u76ee\u5f55\uff08{0}\uff09\uff1a\u91cd\u542f Codex \u540e\uff0c\u6a21\u578b\u9009\u5355\u53ea\u663e\u793a\u7f51\u5173\u5f00\u653e\u7684\u6a21\u578b\u3002') -f $S.CodexFound) -ForegroundColor Green } catch { Write-Host ((U '\u6ca1\u6709\u52a0\u7f51\u5173\u7684\u6a21\u578b\u76ee\u5f55\uff1a{0}\u3002\u4fdd\u7559\u4e86\u521a\u624d\u5199\u597d\u7684\u57fa\u672c\u914d\u7f6e\u3002') -f $_.Exception.Message) -ForegroundColor Yellow } finally { if (Test-Path -LiteralPath $cfg2) { Remove-Item -LiteralPath $cfg2 -Force -ErrorAction SilentlyContinue } } } Invoke-WulaobanCodexSetup