# Official OpenAI Codex Universal Installer for Chuhai365 API (Windows) # Portal: https://gpt.chuhai365.cc # Gateway: https://api.chuhai365.cc/v1 # Supports: Windows PowerShell 5.1 & PowerShell 7 (x64 / ARM64) # Supports: remote "irm https://gpt.chuhai365.cc/install.ps1 | iex" and local -File # # Quick usage: # irm https://gpt.chuhai365.cc/install.ps1 | iex # $env:NEWAPI_API_KEY='sk-xxx'; irm https://gpt.chuhai365.cc/install.ps1 | iex # & ([scriptblock]::Create((irm https://gpt.chuhai365.cc/install.ps1))) -Check # & ([scriptblock]::Create((irm https://gpt.chuhai365.cc/install.ps1))) -FixProxy # & ([scriptblock]::Create((irm https://gpt.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:DefaultAuthOrigin = 'https://gpt.chuhai365.cc' $script:DefaultBaseUrl = 'https://api.chuhai365.cc/v1' $script:DefaultModel = 'gpt-6.2-sol' $script:DefaultEffort = 'high' $script:StartMark = '# >>> chuhai365-codex >>>' $script:EndMark = '# <<< chuhai365-codex <<<' $script:OwnedRootKeys = @( 'model_provider', 'openai_base_url', 'model', 'review_model', 'model_reasoning_effort', 'forced_login_method', 'cli_auth_credentials_store', 'disable_response_storage' ) $script:OAuthAuthKeys = @('tokens', 'last_refresh', 'access_token', 'refresh_token', 'id_token') 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:DefaultCodexHome = Join-Path $script:UserHome '.codex' $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 } Effort = if ($env:CHUHAI_EFFORT) { [string]$env:CHUHAI_EFFORT } else { $script:DefaultEffort } CodexHome = if ($env:CODEX_HOME) { [string]$env:CODEX_HOME } else { $script:DefaultCodexHome } ModelExplicit = [bool]$env:CHUHAI_MODEL EffortExplicit = [bool]$env:CHUHAI_EFFORT BaseExplicit = [bool]$env:NEWAPI_BASE_URL Paste = $false Check = $false FixProxy = $false Uninstall = $false NoVerify = $false NoProbe = $false NoKill = $false Help = $false BadArgs = @() } foreach ($ev in @($env:NEWAPI_API_KEY, $env:CHUHAI_API_KEY, $env:CODEX_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)(Effort|ReasoningEffort)$' { if ($null -ne $inlineVal) { $script:Opt.Effort = $inlineVal.ToLowerInvariant(); $script:Opt.EffortExplicit = $true } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.Effort = ([string]$RawArgs[$i]).ToLowerInvariant(); $script:Opt.EffortExplicit = $true } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)CodexHome$' { if ($null -ne $inlineVal) { $script:Opt.CodexHome = $inlineVal } elseif (($i + 1) -lt $RawArgs.Count) { $i++; $script:Opt.CodexHome = [string]$RawArgs[$i] } else { $script:Opt.BadArgs += ($arg + ' (missing value)') } } '^--?(?i)Paste$' { $script:Opt.Paste = $true } '^--?(?i)(Check|Status)$' { $script:Opt.Check = $true } '^--?(?i)(FixProxy|Doctor)$' { $script:Opt.FixProxy = $true } '^--?(?i)Uninstall$' { $script:Opt.Uninstall = $true } '^--?(?i)(NoVerify|Offline)$' { $script:Opt.NoVerify = $true } '^--?(?i)(NoProbe|SkipProbe)$' { $script:Opt.NoProbe = $true } '^--?(?i)NoKill$' { $script:Opt.NoKill = $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 Codex \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 + ' (' + $script:DefaultEffort + ')') Write-Host '' Write-Host (U '\u5e38\u7528\u7528\u6cd5:') -ForegroundColor Yellow Write-Host ' 1) irm https://gpt.chuhai365.cc/install.ps1 | iex' Write-Host ' 2) $env:NEWAPI_API_KEY=''sk-xxx''; irm https://gpt.chuhai365.cc/install.ps1 | iex' Write-Host ' 3) & ([scriptblock]::Create((irm https://gpt.chuhai365.cc/install.ps1))) -Check' Write-Host ' 4) & ([scriptblock]::Create((irm https://gpt.chuhai365.cc/install.ps1))) -FixProxy' Write-Host ' 5) & ([scriptblock]::Create((irm https://gpt.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 (gpt-6.2-sol / gpt-6.2-astra / o3)' Write-Host ' -Effort low | medium | high | xhigh' Write-Host ' -BaseUrl Gateway URL (default https://api.chuhai365.cc/v1)' Write-Host ' -CodexHome Custom CODEX_HOME directory' 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 / conflicting env vars' Write-Host ' -Uninstall Remove managed block and restore backup' Write-Host ' -NoProbe / -NoVerify Skip /v1/responses probe or all network checks' } # ---------------------------------------------------------------- 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 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-Hashtable($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 { } } } # ---------------------------------------------------------------- Browser Opener (Windows 10/11 safe) 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 } } # ---------------------------------------------------------------- TOML & Auth Management function Strip-ManagedBlock([string]$Text) { $lines = $Text -split "\r?\n" $out = New-Object System.Collections.Generic.List[string] $inside = $false foreach ($ln in $lines) { $s = $ln.Trim() if ($s -eq $script:StartMark) { $inside = $true; continue } if ($s -eq $script:EndMark) { $inside = $false; continue } if (-not $inside) { [void]$out.Add($ln) } } return ($out -join "`n") } function Strip-ProviderTable([string]$TablesText) { if ([string]::IsNullOrEmpty($TablesText)) { return '' } $lines = $TablesText -split "\r?\n" $out = New-Object System.Collections.Generic.List[string] $skip = $false foreach ($ln in $lines) { if ($ln -match '^\s*\[') { $skip = ($ln -match '^\s*\[model_providers\.chuhai365(?:\.|\])') } if (-not $skip) { [void]$out.Add($ln) } } return ($out -join "`n") } function Split-Toml([string]$Text) { $lines = @($Text -split "\r?\n") for ($i = 0; $i -lt $lines.Count; $i++) { if ($lines[$i] -match '^\s*\[') { $root = if ($i -gt 0) { @($lines[0..($i - 1)]) } else { @() } $tbl = ($lines[$i..($lines.Count - 1)] -join "`n") return [pscustomobject]@{ Root = $root; Tables = $tbl } } } return [pscustomobject]@{ Root = $lines; Tables = '' } } function Build-ManagedBlock([string]$BaseUrl, [string]$Model, [string]$Effort) { return (@( $script:StartMark 'model_provider = "chuhai365"' ('openai_base_url = "' + $BaseUrl + '"') ('model = "' + $Model + '"') ('review_model = "' + $Model + '"') ('model_reasoning_effort = "' + $Effort + '"') 'forced_login_method = "api"' 'cli_auth_credentials_store = "file"' 'disable_response_storage = true' '' '[model_providers.chuhai365]' 'name = "Chuhai365"' ('base_url = "' + $BaseUrl + '"') 'wire_api = "responses"' 'requires_openai_auth = true' $script:EndMark ) -join "`n") } function Apply-CodexConfig([string]$CodexHome, [string]$BaseUrl, [string]$Model, [string]$Effort, [string]$ApiKey) { if (-not (Test-Path -LiteralPath $CodexHome)) { New-Item -ItemType Directory -Path $CodexHome -Force | Out-Null } $cfgPath = Join-Path $CodexHome 'config.toml' $authPath = Join-Path $CodexHome 'auth.json' $statePath = Join-Path $CodexHome '.chuhai365-codex-state.json' $ts = (Get-Date).ToString('yyyyMMdd-HHmmss') $prevState = $null if (Test-Path -LiteralPath $statePath -PathType Leaf) { try { $prevState = (Read-Utf8NoBom $statePath) | ConvertFrom-Json } catch { $prevState = $null } } $cfgBackup = '' $rawCfg = '' if (Test-Path -LiteralPath $cfgPath -PathType Leaf) { $cfgBackup = $cfgPath + '.bak.chuhai365.' + $ts Copy-Item -LiteralPath $cfgPath -Destination $cfgBackup -Force $rawCfg = Read-Utf8NoBom $cfgPath } $cleaned = Strip-ManagedBlock $rawCfg $split = Split-Toml $cleaned $tblText = Strip-ProviderTable $split.Tables $keptRoot = New-Object System.Collections.Generic.List[string] $removedRoot = New-Object System.Collections.Generic.List[string] foreach ($ln in @($split.Root)) { if ($ln -match '^\s*([A-Za-z0-9_-]+)\s*=' -and ($script:OwnedRootKeys -contains $Matches[1])) { [void]$removedRoot.Add($ln) } else { [void]$keptRoot.Add($ln) } } while ($keptRoot.Count -gt 0 -and [string]::IsNullOrWhiteSpace($keptRoot[$keptRoot.Count - 1])) { $keptRoot.RemoveAt($keptRoot.Count - 1) } $parts = New-Object System.Collections.Generic.List[string] if ($keptRoot.Count -gt 0) { [void]$parts.Add(($keptRoot -join "`n")) } [void]$parts.Add((Build-ManagedBlock $BaseUrl $Model $Effort)) $tblTrim = $tblText.Trim("`r", "`n") if (-not [string]::IsNullOrEmpty($tblTrim)) { [void]$parts.Add($tblTrim) } Write-Utf8NoBomAtomic $cfgPath (($parts -join "`n`n") + "`n") $authBackup = '' $authHt = [ordered]@{} if (Test-Path -LiteralPath $authPath -PathType Leaf) { $authBackup = $authPath + '.bak.chuhai365.' + $ts Copy-Item -LiteralPath $authPath -Destination $authBackup -Force try { $parsedAuth = (Read-Utf8NoBom $authPath) | ConvertFrom-Json $authHt = ConvertTo-Hashtable $parsedAuth } catch { $authHt = [ordered]@{} } } $stripped = @() foreach ($ok in $script:OAuthAuthKeys) { if ($authHt.Contains($ok)) { $stripped += $ok $authHt.Remove($ok) } } $authHt['OPENAI_API_KEY'] = $ApiKey $authHt['auth_mode'] = 'apikey' $authJson = ($authHt | ConvertTo-Json -Depth 10) + "`n" Write-Utf8NoBomAtomic $authPath $authJson $savedPrevLines = @($removedRoot.ToArray()) if ($null -ne $prevState -and $null -ne $prevState.PSObject.Properties['previous_root_lines']) { $savedPrevLines = @($prevState.previous_root_lines) } $stateObj = [ordered]@{ schema_version = 1 provider = 'chuhai365' base_url = $BaseUrl model = $Model reasoning_effort = $Effort installed_key_sha256 = (Get-Sha256Hex $ApiKey) previous_root_lines = $savedPrevLines updated_at = (Get-Date).ToUniversalTime().ToString('o') } Write-Utf8NoBomAtomic $statePath (($stateObj | ConvertTo-Json -Depth 6) + "`n") return [pscustomobject]@{ CfgBackup = $cfgBackup AuthBackup = $authBackup StrippedOAuth = $stripped } } # ---------------------------------------------------------------- Codex Binary Discovery & Execution function Invoke-CodexExec([string]$BinPath, [string[]]$ExecArgs, [string]$CodexHome, [string]$StdinText = $null) { $psi = New-Object System.Diagnostics.ProcessStartInfo $ext = [IO.Path]::GetExtension($BinPath) if ($ext -match '^(?i)\.(cmd|bat)$') { $escapedArgs = ($ExecArgs | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' ' $psi.FileName = 'cmd.exe' $psi.Arguments = '/d /s /c ""' + $BinPath + '" ' + $escapedArgs + '"' } else { $psi.FileName = $BinPath $psi.Arguments = (($ExecArgs | ForEach-Object { if ($_ -match '\s|"') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' ') } $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true if ($null -ne $StdinText) { $psi.RedirectStandardInput = $true } $psi.EnvironmentVariables['CODEX_HOME'] = $CodexHome $proc = New-Object System.Diagnostics.Process $proc.StartInfo = $psi [void]$proc.Start() if ($null -ne $StdinText) { $proc.StandardInput.WriteLine($StdinText) $proc.StandardInput.Close() } $stdout = $proc.StandardOutput.ReadToEnd() $stderr = $proc.StandardError.ReadToEnd() $exited = $proc.WaitForExit(20000) if (-not $exited) { try { $proc.Kill() } catch { } } return [pscustomobject]@{ ExitCode = if ($exited) { $proc.ExitCode } else { -1 } StdOut = [string]$stdout StdErr = [string]$stderr } } function Test-CodexCandidate([string]$Path, [string]$CodexHome) { if ([string]::IsNullOrWhiteSpace($Path)) { return $false } if ($Path -match '(?i)\\WindowsApps\\') { return $false } if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $false } try { $fi = Get-Item -LiteralPath $Path -ErrorAction Stop if ($fi.Length -le 0) { return $false } } catch { return $false } try { $r = Invoke-CodexExec $Path @('login', '--help') $CodexHome return (($r.StdOut + $r.StdErr) -match '--with-api-key') } catch { return $false } } function Find-CodexBin([string]$CodexHome) { $cands = New-Object System.Collections.Generic.List[string] if ($env:CHUHAI_CODEX_BIN) { [void]$cands.Add([string]$env:CHUHAI_CODEX_BIN) } $localApp = [Environment]::GetFolderPath('LocalApplicationData') $roamApp = [Environment]::GetFolderPath('ApplicationData') if ($localApp) { 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' )) { [void]$cands.Add((Join-Path $localApp $rel)) } } [void]$cands.Add((Join-Path $script:UserHome '.codex\bin\codex.exe')) $relRoot = Join-Path $script:UserHome '.codex\packages\standalone\releases' if (Test-Path -LiteralPath $relRoot -PathType Container) { foreach ($hit in @(Get-ChildItem -LiteralPath $relRoot -Filter 'codex.exe' -Recurse -ErrorAction SilentlyContinue)) { [void]$cands.Add([string]$hit.FullName) } } if ($roamApp) { [void]$cands.Add((Join-Path $roamApp 'npm\codex.cmd')) [void]$cands.Add((Join-Path $roamApp 'npm\codex.exe')) } try { $pkgs = @(Get-AppxPackage -ErrorAction Stop | Where-Object { $_.Name -match '(?i)(Codex|ChatGPT|OpenAI)' }) foreach ($pkg in $pkgs) { if (-not $pkg.InstallLocation) { continue } foreach ($rel in @('app\resources\codex.exe', 'app\bin\codex.exe', 'app\codex.exe', 'resources\codex.exe')) { [void]$cands.Add((Join-Path $pkg.InstallLocation $rel)) } $appSub = Join-Path $pkg.InstallLocation 'app' if (Test-Path -LiteralPath $appSub -PathType Container) { foreach ($hit in @(Get-ChildItem -LiteralPath $appSub -Filter 'codex.exe' -Recurse -ErrorAction SilentlyContinue | Select-Object -First 3)) { [void]$cands.Add([string]$hit.FullName) } } } } catch { } try { foreach ($cmd in @(Get-Command codex -All -ErrorAction SilentlyContinue)) { if ($cmd.Source) { [void]$cands.Add([string]$cmd.Source) } } } catch { } $seen = @{} foreach ($c in $cands) { if ([string]::IsNullOrWhiteSpace($c)) { continue } $key = $c.ToLowerInvariant() if ($seen.ContainsKey($key)) { continue } $seen[$key] = $true if (Test-CodexCandidate $c $CodexHome) { return $c } } return '' } function Stop-DesktopApps { if ($script:Opt.NoKill) { return } if ($script:Opt.CodexHome.TrimEnd('\') -ine $script:DefaultCodexHome.TrimEnd('\')) { return } $procs = @(Get-Process -Name 'Codex', 'ChatGPT' -ErrorAction SilentlyContinue) if ($procs.Count -eq 0) { return } Say-Step (U '\u6b63\u5728\u5173\u95ed\u8fd0\u884c\u4e2d\u7684 Codex / ChatGPT \u684c\u9762 App\uff08\u9632\u6b62\u65e7\u8fdb\u7a0b\u8986\u76d6\u767b\u5f55\u6001\uff09') foreach ($p in $procs) { try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch { } } for ($i = 0; $i -lt 10; $i++) { if (@(Get-Process -Name 'Codex', 'ChatGPT' -ErrorAction SilentlyContinue).Count -eq 0) { break } Start-Sleep -Milliseconds 500 } Say-Ok (U '\u684c\u9762 App \u8fdb\u7a0b\u5df2\u5b89\u5168\u9000\u51fa\u3002') } # ---------------------------------------------------------------- Proxy & Conflict Env Diagnostics function Inspect-ProxyAndEnv([bool]$FixMode = $false) { $issues = 0 $scopes = @('Process', 'User', 'Machine') $proxyVars = @('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY') $conflictVars = @('OPENAI_BASE_URL', 'OPENAI_API_KEY') foreach ($scope in $scopes) { foreach ($v in $proxyVars) { $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 { } } } } } foreach ($cv in $conflictVars) { $cval = '' try { $cval = [Environment]::GetEnvironmentVariable($cv, $scope) } catch { $cval = '' } if ([string]::IsNullOrWhiteSpace($cval)) { continue } if ($cv -eq 'OPENAI_BASE_URL' -and ($cval.TrimEnd('/') -ieq $script:Opt.BaseUrl.TrimEnd('/'))) { continue } Say-Warn ((U '\u68c0\u6d4b\u5230\u51b2\u7a81\u73af\u5883\u53d8\u91cf [') + $scope + '] ' + $cv + (U '\uff08\u53ef\u80fd\u8986\u76d6 ~/.codex \u914d\u7f6e\uff09')) $issues++ } } if ($FixMode) { Say-Step ((U '\u6d4b\u8bd5\u8fde\u901a\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\u6216\u51b2\u7a81\u73af\u5883\u53d8\u91cf\u3002') } } } # ---------------------------------------------------------------- Browser Device Auth function Acquire-KeyViaBrowser { Say-Step ((U '\u53d1\u8d77\u6d4f\u89c8\u5668\u8bbe\u5907\u6388\u6743 (') + $script:Opt.AuthOrigin + ')') $devName = ([string]$env:COMPUTERNAME + '-codex') -replace '[^A-Za-z0-9._-]', '' if ([string]::IsNullOrWhiteSpace($devName)) { $devName = 'windows-codex' } if ($devName.Length -gt 40) { $devName = $devName.Substring(0, 40) } $startBody = (@{ device_name = $devName device_id = [Guid]::NewGuid().ToString() platform = 'Windows ' + [Environment]::GetEnvironmentVariable('PROCESSOR_ARCHITECTURE') client = 'codex' } | 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=codex' } 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.EffortExplicit -and $pr.reasoning_effort) { $script:Opt.Effort = [string]$pr.reasoning_effort } if (-not $script:Opt.BaseExplicit -and $pr.base_url) { $script:Opt.BaseUrl = Normalize-BaseUrl ([string]$pr.base_url) } 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') } } # ---------------------------------------------------------------- Modes: Check / Uninstall function Invoke-CheckMode { Say-Step ((U '\u51fa\u6d77365 Codex \u63a5\u5165\u4f53\u68c0 (\u53ea\u8bfb\u6a21\u5f0f \u00b7 v') + $script:ScriptVersion + ')') Say ((U '\u914d\u7f6e\u76ee\u5f55: ') + $script:Opt.CodexHome) $cfgPath = Join-Path $script:Opt.CodexHome 'config.toml' $authPath = Join-Path $script:Opt.CodexHome 'auth.json' if (Test-Path -LiteralPath $cfgPath -PathType Leaf) { $txt = Read-Utf8NoBom $cfgPath $managed = ($txt.Contains($script:StartMark) -and $txt.Contains($script:EndMark)) if ($managed) { Say-Ok (U 'config.toml \u5df2\u7531\u51fa\u6d77365\u6258\u7ba1') } else { Say-Warn (U 'config.toml \u5b58\u5728\u4f46\u672a\u5305\u542b\u51fa\u6d77365\u6258\u7ba1\u5757') } foreach ($ln in ($txt -split "\r?\n")) { if ($ln -match '^\s*\[') { break } if ($ln -match '^\s*(model_provider|openai_base_url|model|model_reasoning_effort|forced_login_method)\s*=') { Say (' ' + $ln.Trim()) } } } else { Say-Warn ((U '\u672a\u627e\u5230 ') + $cfgPath) } if (Test-Path -LiteralPath $authPath -PathType Leaf) { try { $a = ConvertTo-Hashtable ((Read-Utf8NoBom $authPath) | ConvertFrom-Json) if ($a.Contains('OPENAI_API_KEY') -and $a['OPENAI_API_KEY']) { Say-Ok ((U 'auth.json \u5df2\u914d\u7f6e API Key (auth_mode=') + [string]$a['auth_mode'] + ')') } else { Say-Warn (U 'auth.json \u672a\u5199\u5165 OPENAI_API_KEY') } $hasOauth = $false foreach ($ok in $script:OAuthAuthKeys) { if ($a.Contains($ok)) { $hasOauth = $true } } if ($hasOauth) { Say-Warn (U 'auth.json \u4e2d\u4ecd\u6b8b\u7559 ChatGPT OAuth \u5b57\u6bb5\uff0c\u5efa\u8bae\u91cd\u8dd1\u5b89\u88c5\u547d\u4ee4\u6e05\u7406\u3002') } } catch { Say-Warn (U 'auth.json \u89e3\u6790\u5931\u8d25') } } else { Say-Warn ((U '\u672a\u627e\u5230 ') + $authPath) } $cbin = Find-CodexBin $script:Opt.CodexHome if ($cbin) { Say-Ok ((U '\u5df2\u5b9a\u4f4d\u5b98\u65b9 codex \u4e8c\u8fdb\u5236: ') + $cbin) $ls = Invoke-CodexExec $cbin @('login', 'status') $script:Opt.CodexHome $lsOut = ($ls.StdOut + ' ' + $ls.StdErr).Trim() if ($lsOut) { Say ('codex login status: ' + $lsOut) } } else { Say-Warn (U '\u672a\u68c0\u6d4b\u5230\u5b98\u65b9 Codex App / CLI \u4e8c\u8fdb\u5236\uff08\u8bf7\u524d\u5f80 https://chatgpt.com/codex \u6216 npm i -g @openai/codex \u5b89\u88c5\uff09') } Inspect-ProxyAndEnv $false } function Invoke-UninstallMode { Say-Step (U '\u5378\u8f7d\u51fa\u6d77365 Codex \u63a5\u5165\u5e76\u7cbe\u51c6\u8fd8\u539f\u914d\u7f6e') Stop-DesktopApps $cfgPath = Join-Path $script:Opt.CodexHome 'config.toml' $authPath = Join-Path $script:Opt.CodexHome 'auth.json' $statePath = Join-Path $script:Opt.CodexHome '.chuhai365-codex-state.json' $ts = (Get-Date).ToString('yyyyMMdd-HHmmss') $state = $null if (Test-Path -LiteralPath $statePath -PathType Leaf) { try { $state = (Read-Utf8NoBom $statePath) | ConvertFrom-Json } catch { $state = $null } } if (Test-Path -LiteralPath $cfgPath -PathType Leaf) { $raw = Read-Utf8NoBom $cfgPath if ($raw.Contains($script:StartMark) -or $raw.Contains('[model_providers.chuhai365]')) { Copy-Item -LiteralPath $cfgPath -Destination ($cfgPath + '.bak.pre-uninstall.' + $ts) -Force $cleaned = Strip-ManagedBlock $raw $split = Split-Toml $cleaned $tbl = Strip-ProviderTable $split.Tables $root = New-Object System.Collections.Generic.List[string] $existingKeys = @{} foreach ($ln in @($split.Root)) { [void]$root.Add($ln) if ($ln -match '^\s*([A-Za-z0-9_-]+)\s*=') { $existingKeys[$Matches[1]] = $true } } while ($root.Count -gt 0 -and [string]::IsNullOrWhiteSpace($root[$root.Count - 1])) { $root.RemoveAt($root.Count - 1) } $restored = New-Object System.Collections.Generic.List[string] if ($null -ne $state -and $null -ne $state.PSObject.Properties['previous_root_lines']) { foreach ($pl in @($state.previous_root_lines)) { $pls = [string]$pl if ($pls -match '^\s*([A-Za-z0-9_-]+)\s*=' -and $existingKeys.ContainsKey($Matches[1])) { continue } if (-not [string]::IsNullOrWhiteSpace($pls)) { [void]$restored.Add($pls) } } } $parts = New-Object System.Collections.Generic.List[string] if ($root.Count -gt 0) { [void]$parts.Add(($root -join "`n")) } if ($restored.Count -gt 0) { [void]$parts.Add(($restored -join "`n")) } $tblTrim = $tbl.Trim("`r", "`n") if (-not [string]::IsNullOrEmpty($tblTrim)) { [void]$parts.Add($tblTrim) } if ($parts.Count -gt 0) { Write-Utf8NoBomAtomic $cfgPath (($parts -join "`n`n") + "`n") } else { Remove-Item -LiteralPath $cfgPath -Force -ErrorAction SilentlyContinue } Say-Ok (U '\u5df2\u79fb\u9664 config.toml \u6258\u7ba1\u5757\u5e76\u8fd8\u539f\u539f\u6709\u914d\u7f6e\u3002') } else { Say (U 'config.toml \u4e2d\u672a\u53d1\u73b0\u51fa\u6d77365\u6258\u7ba1\u5757\uff0c\u65e0\u9700\u6539\u52a8\u3002') } } $keyMatched = $false if (Test-Path -LiteralPath $authPath -PathType Leaf) { try { $a = ConvertTo-Hashtable ((Read-Utf8NoBom $authPath) | ConvertFrom-Json) if ($a.Contains('OPENAI_API_KEY') -and $a['OPENAI_API_KEY']) { $instHash = if ($null -ne $state -and $null -ne $state.PSObject.Properties['installed_key_sha256']) { [string]$state.installed_key_sha256 } else { '' } $curHash = Get-Sha256Hex ([string]$a['OPENAI_API_KEY']) if (-not $instHash -or $instHash -eq $curHash) { Copy-Item -LiteralPath $authPath -Destination ($authPath + '.bak.pre-uninstall.' + $ts) -Force $a.Remove('OPENAI_API_KEY') if ($a.Contains('auth_mode') -and ([string]$a['auth_mode'] -eq 'apikey')) { $a.Remove('auth_mode') } if ($a.Count -gt 0) { Write-Utf8NoBomAtomic $authPath (($a | ConvertTo-Json -Depth 10) + "`n") } else { Remove-Item -LiteralPath $authPath -Force -ErrorAction SilentlyContinue } $keyMatched = $true Say-Ok (U '\u5df2\u6e05\u9664 auth.json \u4e2d\u7531\u51fa\u6d77365\u5199\u5165\u7684\u5bc6\u94a5\u3002') } } } catch { } } if (Test-Path -LiteralPath $statePath -PathType Leaf) { Remove-Item -LiteralPath $statePath -Force -ErrorAction SilentlyContinue } if ($keyMatched) { $cbin = Find-CodexBin $script:Opt.CodexHome if ($cbin) { [void](Invoke-CodexExec $cbin @('logout') $script:Opt.CodexHome) Say-Ok (U '\u5df2\u540c\u6b65\u6267\u884c codex logout \u6e05\u7406\u767b\u5f55\u6001\u3002') } } Say-Ok (U '\u5378\u8f7d\u8fd8\u539f\u5b8c\u6210\u3002') } # ---------------------------------------------------------------- Entry Point try { Parse-CliArgs $args if ($script:Opt.Help) { Show-Usage; return } if ($script:Opt.BadArgs.Count -gt 0) { Fail ((U '\u672a\u77e5\u53c2\u6570: ') + ($script:Opt.BadArgs -join ', ')) } if (@('low', 'medium', 'high', 'xhigh') -notcontains $script:Opt.Effort) { Fail ((U '\u4e0d\u652f\u6301\u7684\u63a8\u7406\u5f3a\u5ea6: ') + $script:Opt.Effort) } if ($script:Opt.Check) { Invoke-CheckMode; return } if ($script:Opt.FixProxy) { Say-Step ((U '\u51fa\u6d77365 Codex \u4ee3\u7406\u4e0e\u7f51\u7edc\u81ea\u68c0\u4fee\u590d (v') + $script:ScriptVersion + ')') Inspect-ProxyAndEnv $true Invoke-CheckMode return } if ($script:Opt.Uninstall) { Invoke-UninstallMode; return } Write-Host '' Write-Host ((U '\u51fa\u6d77365 API \u00b7 \u5b98\u65b9 Codex \u4e00\u952e\u63a5\u5165 v') + $script:ScriptVersion) -ForegroundColor Cyan Say ((U '\u7f51\u5173\u5730\u5740: ') + $script:Opt.BaseUrl) Say ((U '\u914d\u7f6e\u76ee\u5f55: ') + $script:Opt.CodexHome) $script:Opt.ApiKey = ([string]$script:Opt.ApiKey).Trim().Trim('"', "'") -replace '\s+', '' if ([string]::IsNullOrWhiteSpace($script:Opt.ApiKey)) { if ($script:Opt.Paste) { Acquire-KeyFromConsole } else { Acquire-KeyViaBrowser } } else { Say-Ok ((U '\u68c0\u6d4b\u5230\u5df2\u4f20\u5165 API \u5bc6\u94a5 (') + (Mask-Secret $script:Opt.ApiKey) + (U ')\uff0c\u8df3\u8fc7\u6d4f\u89c8\u5668\u6388\u6743\u76f4\u63a5\u914d\u7f6e\u3002')) } if (-not $script:Opt.NoVerify) { Say-Step (U '\u6821\u9a8c\u5bc6\u94a5\u4e0e\u51fa\u6d77365\u7f51\u5173\u8fde\u901a\u6027') $headers = @{ Authorization = ('Bearer ' + $script:Opt.ApiKey) } try { $modelsResp = Invoke-RestMethod -Method Get -Uri ($script:Opt.BaseUrl + '/models') -Headers $headers -TimeoutSec 15 $gptIds = @() if ($modelsResp -and $modelsResp.data) { foreach ($item in @($modelsResp.data)) { $mid = [string]$item.id if ($mid -match '(?i)(image|dall-e|whisper|tts|embedding|rerank|moderation|sora|audio|realtime|transcribe)') { continue } if ($mid -match '(?i)(^|/)(gpt-|codex|o[134]($|[-._])|chatgpt-)' -or $mid -match '(?i)codex') { $gptIds += $mid } } } Say-Ok (U '\u5bc6\u94a5\u6821\u9a8c\u901a\u8fc7 (HTTP 200)') if ($gptIds.Count -gt 0) { Say ((U '\u53ef\u7528 GPT / Codex \u6a21\u578b: ') + ($gptIds -join ', ')) } } catch [Net.WebException] { $sc = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } if ($sc -eq 401 -or $sc -eq 403) { Fail ((U 'API \u5bc6\u94a5\u65e0\u6548\u3001\u5df2\u88ab\u7981\u7528\u6216\u5df2\u8fc7\u671f (HTTP ') + $sc + ')') } Say-Warn ((U '\u62c9\u53d6 /v1/models \u8fd4\u56de\u5f02\u5e38 (HTTP ') + $sc + (U ')\uff0c\u5c06\u7ee7\u7eed\u5199\u5165\u914d\u7f6e\u3002')) } catch { Say-Warn ((U '\u6821\u9a8c /v1/models \u5931\u8d25: ') + $_.Exception.Message) } if (-not $script:Opt.NoProbe) { try { $pBody = (@{ model = $script:Opt.Model; input = 'ping'; max_output_tokens = 16; store = $false } | ConvertTo-Json -Compress) $null = Invoke-RestMethod -Method Post -Uri ($script:Opt.BaseUrl + '/responses') -Headers $headers -ContentType 'application/json' -Body $pBody -TimeoutSec 25 Say-Ok ((U 'Responses \u534f\u8bae (/v1/responses \u00b7 ') + $script:Opt.Model + (U ') \u5b9e\u6d4b\u901a\u8fc7')) } catch { Say-Warn ((U 'Responses \u63a2\u9488\u672a\u8fd4\u56de 200\uff08\u53ef\u5728 App \u5185\u5207\u6362\u6a21\u578b\uff09: ') + $_.Exception.Message) } } } Inspect-ProxyAndEnv $false Stop-DesktopApps Say-Step ((U '\u5199\u5165 ') + $script:Opt.CodexHome + '\config.toml ' + (U '\u4e0e auth.json')) $res = Apply-CodexConfig $script:Opt.CodexHome $script:Opt.BaseUrl $script:Opt.Model $script:Opt.Effort $script:Opt.ApiKey if ($res.CfgBackup) { Say ((U '\u5df2\u5907\u4efd\u539f config.toml -> ') + $res.CfgBackup) } if ($res.StrippedOAuth.Count -gt 0) { Say ((U '\u5df2\u6e05\u7406\u65e7 ChatGPT OAuth \u5b57\u6bb5: ') + ($res.StrippedOAuth -join ', ')) } Say-Ok ((U '\u5df2\u5199\u5165\u6258\u7ba1\u914d\u7f6e (model=') + $script:Opt.Model + ', effort=' + $script:Opt.Effort + ', wire_api=responses)') Say-Step (U '\u540c\u6b65\u5b98\u65b9 Codex \u684c\u9762 App / CLI \u767b\u5f55\u6001') $cbin = Find-CodexBin $script:Opt.CodexHome if ($cbin) { Say ((U '\u68c0\u6d4b\u5230\u5b98\u65b9 codex: ') + $cbin) [void](Invoke-CodexExec $cbin @('logout') $script:Opt.CodexHome) [void](Invoke-CodexExec $cbin @('-c', 'cli_auth_credentials_store="auto"', 'logout') $script:Opt.CodexHome) $loginRes = Invoke-CodexExec $cbin @('login', '--with-api-key') $script:Opt.CodexHome $script:Opt.ApiKey if ($loginRes.ExitCode -eq 0) { Say-Ok (U '\u5df2\u6267\u884c codex login --with-api-key \u6ce8\u518c\u684c\u9762 App \u767b\u5f55\u6001') $stRes = Invoke-CodexExec $cbin @('login', 'status') $script:Opt.CodexHome $stTxt = ($stRes.StdOut + ' ' + $stRes.StdErr).Trim() if ($stTxt) { Say-Ok ((U '\u767b\u5f55\u6001\u9a8c\u8bc1: ') + $stTxt) } } else { Say-Warn (U 'codex login --with-api-key \u8fd4\u56de\u975e\u96f6\u72b6\u6001\uff0cauth.json \u5df2\u5199\u5165\uff0c\u91cd\u542f App \u540e\u5982\u4ecd\u63d0\u793a\u767b\u5f55\u8bf7\u5148\u5f7b\u5e95\u9000\u51fa App \u518d\u91cd\u8dd1\u3002') } } else { Say-Warn (U '\u5f53\u524d\u673a\u5668\u672a\u68c0\u6d4b\u5230\u5df2\u5b89\u88c5\u7684\u5b98\u65b9 Codex App / CLI \u4e8c\u8fdb\u5236\u3002') Say (U '\u5df2\u63d0\u524d\u5199\u597d .codex \u914d\u7f6e\uff1b\u5b89\u88c5\u5b98\u65b9 Codex (https://chatgpt.com/codex \u6216 npm i -g @openai/codex) \u540e\u5efa\u8bae\u518d\u8dd1\u4e00\u6b21\u672c\u547d\u4ee4\u3002') } Write-Host '' Write-Host (U '[OK] \u63a5\u5165\u5b8c\u6210\uff01') -ForegroundColor Green Say (U '1. \u82e5\u4f7f\u7528\u5b98\u65b9 Codex \u684c\u9762 App\uff1a\u8bf7\u5b8c\u5168\u9000\u51fa\uff08\u53f3\u952e\u6258\u76d8\u56fe\u6807 Quit\uff09\u540e\u91cd\u65b0\u6253\u5f00\u3002') Say (U '2. \u70b9\u51fb\u300c\u65b0\u5efa\u4f1a\u8bdd\u300d\u76f4\u63a5\u5f00\u804a \u2014\u2014 \u4e0d\u8981\u70b9\u300c\u7528 ChatGPT \u767b\u5f55\u300d\uff0c\u4e0d\u8981\u586b\u624b\u673a\u53f7\u3002') Say (U '3. \u7ec8\u7aef CLI \u76f4\u63a5\u8fd0\u884c codex\uff1bVS Code / Cursor \u6269\u5c55\u91cd\u8f7d\u7a97\u53e3\u5373\u81ea\u52a8\u5171\u4eab\u672c\u914d\u7f6e\u3002') Say (U '4. \u5982\u9700\u6392\u67e5\u72b6\u6001\u6216\u5378\u8f7d\u8fd8\u539f\uff0c\u53ef\u968f\u65f6\u8bbf\u95ee https://gpt.chuhai365.cc/') } catch { $msg = [string]$_.Exception.Message if ($msg.StartsWith('CHUHAI_FAIL::')) { Say-Err $msg.Substring(13) } else { Say-Err $msg } exit 1 }