# Cài / cập nhật Codex dùng codex.fosta.app, kèm vẽ ảnh qua Images API của fosta (Windows). # PowerShell: irm https://codex.fosta.app/install.ps1 | iex # hoặc bấm đúp "Cai-Codex-Fosta-Windows.bat" # Hỏi key và model. Chạy lại bất cứ lúc nào để đổi key hoặc model: script chỉ thay đúng # các khối "fosta" nó đã ghi, phần cấu hình khác của bạn được giữ nguyên. # Chạy qua "irm | iex" nên không được thoát cả tiến trình (sẽ đóng cửa sổ PowerShell của người # dùng): mọi thứ nằm trong hàm Install-FostaCodex và dừng bằng return. function Install-FostaCodex { $ErrorActionPreference = 'Stop' try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch {} [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 Add-Type -AssemblyName System.Net.Http $CodexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' } $BaseUrl = 'https://codex.fosta.app/v1' $Model = $env:FOSTA_MODEL $Utf8 = New-Object Text.UTF8Encoding $false # config.toml, AGENTS.md: UTF-8 không BOM $Utf8Bom = New-Object Text.UTF8Encoding $true # file .ps1: có BOM để PowerShell 5 đọc đúng tiếng Việt Write-Host '== Cài Codex dùng codex.fosta.app ==' Write-Host 'Chưa có key? Mua trong bot Telegram @mmo_api_codex_bot.' Write-Host '' $Key = $env:FOSTA_KEY if (-not $Key) { $sec = Read-Host 'Dán key fosta rồi bấm Enter (key không hiện ra màn hình)' -AsSecureString $Key = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($sec)) } # Chỉ giữ ký tự in được ASCII: xóa khoảng trắng LẪN ký tự ẩn/điều khiển (zero-width, # BOM, DEL...) hay dính khi copy key — nếu không, header Authorization sẽ lỗi 400. $Key = ($Key -replace '[^\x21-\x7E]', '') if (-not $Key) { Write-Host 'Chưa nhập key, dừng.'; return } if (-not $Model) { Write-Host '' Write-Host 'Chọn model mặc định:' Write-Host ' 1) gpt-6.2-astra (trừ token x2)' Write-Host ' 2) gpt-6.2-sol (trừ token x1)' $choice = Read-Host 'Nhập 1 hoặc 2 [1]' $Model = if ($choice -eq '2') { 'gpt-6.2-sol' } else { 'gpt-6.2-astra' } } Write-Host 'Kiểm tra key...' $http = New-Object Net.Http.HttpClient $http.Timeout = [TimeSpan]::FromSeconds(30) $http.DefaultRequestHeaders.Authorization = New-Object Net.Http.Headers.AuthenticationHeaderValue('Bearer', $Key) try { $code = [int]$http.GetAsync("$BaseUrl/models").Result.StatusCode } catch { $code = 0 } if ($code -eq 401 -or $code -eq 403) { Write-Host "Key sai hoặc đã bị khoá (mã $code)."; return } if ($code -ne 200) { Write-Host "Không gọi được codex.fosta.app (mã $code). Kiểm tra mạng rồi chạy lại."; return } New-Item -ItemType Directory -Force -Path (Join-Path $CodexHome 'fosta') | Out-Null $cfg = Join-Path $CodexHome 'config.toml' if (-not (Test-Path $cfg)) { [IO.File]::WriteAllText($cfg, '', $Utf8) } $stamp = Get-Date -Format 'yyyyMMdd-HHmmss' Copy-Item $cfg "$cfg.bak-fosta-$stamp" # 1. config.toml: provider RIÊNG "fosta" (không đụng provider openai gốc hay auth.json của # bạn — OpenAI/ChatGPT thật của bạn được giữ nguyên). Chỉ đổi model_provider mặc định sang # fosta; bỏ các khối fosta của bản cài cũ. Provider riêng (thay vì openai built-in) để Codex # đi HTTP, tránh lỗi websocket 405 ở /v1/responses. $kept = New-Object Collections.Generic.List[string] $skip = $false; $inTable = $false; $drop = $false foreach ($line in [IO.File]::ReadAllLines($cfg)) { if ($line -match '^# >>> fosta') { $skip = $true; continue } if ($line -match '^# <<< fosta') { $skip = $false; continue } if ($skip) { continue } if ($line -match '^\s*\[') { $inTable = $true; $drop = ($line -match '^\s*\[model_providers\.fosta\]') } if ($drop) { continue } if (-not $inTable -and $line -match '^\s*(model|model_provider)\s*=') { continue } if (-not $inTable -and $line -match '^\s*(openai_base_url|model_catalog_json)\s*=.*fosta') { continue } $kept.Add($line) } $top = @( '# >>> fosta (script cài fosta ghi; chạy lại script sẽ thay khối này)', 'model_provider = "fosta"', "model = `"$Model`"", '# <<< fosta' ) $bottom = @( '', '# >>> fosta', '[model_providers.fosta]', 'name = "codex.fosta.app"', "base_url = `"$BaseUrl`"", 'wire_api = "responses"', "experimental_bearer_token = `"$Key`"", '# <<< fosta' ) [IO.File]::WriteAllText($cfg, (($top + $kept + $bottom) -join "`n") + "`n", $Utf8) # 2. Công cụ vẽ: đọc key và địa chỉ từ provider fosta trong config.toml, gọi Images API. $imagegen = @' # Vẽ hoặc sửa ảnh qua codex.fosta.app. # powershell -NoProfile -ExecutionPolicy Bypass -File imagegen.ps1 -Prompt "mô tả" -Out out.png # [-Size 1024x1024|1536x1024|1024x1536] [-Quality low|medium|high] [-Ref "a.png,b.png"] # Có -Ref thì gửi ảnh mẫu (sửa ảnh / giữ nhân vật), không có thì vẽ mới. param( [Parameter(Mandatory = $true)][string]$Prompt, [Parameter(Mandatory = $true)][string]$Out, [string]$Size = '1024x1024', [string]$Quality = '', [string[]]$Ref = @() ) $ErrorActionPreference = 'Stop' try { [Console]::OutputEncoding = [Text.Encoding]::UTF8 } catch {} [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 Add-Type -AssemblyName System.Net.Http $cfg = Join-Path $PSScriptRoot '..\config.toml' $base = $null; $key = $null; $in = $false foreach ($line in [IO.File]::ReadAllLines($cfg)) { if ($line -match '^\[model_providers\.fosta\]') { $in = $true; continue } if ($line -match '^\[') { $in = $false } if ($in -and $line -match '^\s*base_url\s*=\s*"([^"]+)"') { $base = $Matches[1] } if ($in -and $line -match '^\s*experimental_bearer_token\s*=\s*"([^"]+)"') { $key = $Matches[1] } } if (-not $key -or -not $base) { [Console]::Error.WriteLine("Không thấy key fosta trong $cfg, chạy lại file cài."); exit 1 } # "-Ref a.png,b.png" qua -File đến dưới dạng một chuỗi: tách theo dấu phẩy. $refs = @($Ref | ForEach-Object { $_ -split ',' } | Where-Object { $_ } | ForEach-Object { (Resolve-Path $_.Trim()).Path }) $outPath = if ([IO.Path]::IsPathRooted($Out)) { $Out } else { [IO.Path]::GetFullPath((Join-Path (Get-Location) $Out)) } New-Item -ItemType Directory -Force -Path (Split-Path $outPath) | Out-Null $http = New-Object Net.Http.HttpClient $http.Timeout = [TimeSpan]::FromSeconds(300) $http.DefaultRequestHeaders.Authorization = New-Object Net.Http.Headers.AuthenticationHeaderValue('Bearer', $key) function Esc([string]$s) { $sb = New-Object Text.StringBuilder foreach ($c in $s.ToCharArray()) { switch ($c) { '"' { [void]$sb.Append('\"') } '\' { [void]$sb.Append('\\') } "`n" { [void]$sb.Append('\n') } "`r" { [void]$sb.Append('\r') } "`t" { [void]$sb.Append('\t') } default { if ([int]$c -lt 32) { [void]$sb.Append(('\u{0:x4}' -f [int]$c)) } else { [void]$sb.Append($c) } } } } $sb.ToString() } $ok = $false for ($attempt = 1; $attempt -le 6; $attempt++) { $code = 0; $text = ''; $blocked = $false try { if ($refs.Count -gt 0) { $form = New-Object Net.Http.MultipartFormDataContent $form.Add((New-Object Net.Http.StringContent('gpt-image-2')), 'model') $form.Add((New-Object Net.Http.StringContent($Prompt, [Text.Encoding]::UTF8)), 'prompt') $form.Add((New-Object Net.Http.StringContent($Size)), 'size') if ($Quality) { $form.Add((New-Object Net.Http.StringContent($Quality)), 'quality') } foreach ($r in $refs) { $fc = New-Object Net.Http.ByteArrayContent(, [IO.File]::ReadAllBytes($r)) $fc.Headers.ContentType = New-Object Net.Http.Headers.MediaTypeHeaderValue('image/png') $form.Add($fc, 'image[]', [IO.Path]::GetFileName($r)) } $resp = $http.PostAsync("$base/images/edits", $form).GetAwaiter().GetResult() } else { $json = '{"model":"gpt-image-2","prompt":"' + (Esc $Prompt) + '","size":"' + $Size + '","n":1' if ($Quality) { $json += ',"quality":"' + $Quality + '"' } $json += '}' $body = New-Object Net.Http.StringContent($json, [Text.Encoding]::UTF8, 'application/json') $resp = $http.PostAsync("$base/images/generations", $body).GetAwaiter().GetResult() } $code = [int]$resp.StatusCode $text = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() } catch { # .Result tren task loi tra ve null (PS 5.1 nuot loi) nen dung GetResult() de thay loi that. $ex = $_.Exception.GetBaseException() $text = $ex.Message if ($ex -is [Threading.Tasks.TaskCanceledException]) { $text = 'Het thoi gian cho may chu (300s).' } if ($ex -is [Net.Sockets.SocketException] -and $ex.NativeErrorCode -eq 10013) { $blocked = $true } } if ($code -eq 200) { $m = [regex]::Match($text, '"b64_json"\s*:\s*"([^"]+)"') if ($m.Success) { $bytes = [Convert]::FromBase64String($m.Groups[1].Value.Replace('\/', '/')) if ($bytes.Length -gt 8 -and $bytes[1] -eq 0x50 -and $bytes[2] -eq 0x4E -and $bytes[3] -eq 0x47) { [IO.File]::WriteAllBytes($outPath, $bytes); $ok = $true; break } } [Console]::Error.WriteLine("Lần ${attempt}: máy chủ trả 200 nhưng không có ảnh: " + $text.Substring(0, [Math]::Min(120, $text.Length))) } else { [Console]::Error.WriteLine("Lần ${attempt} lỗi (mã $code): " + $text.Substring(0, [Math]::Min(200, $text.Length))) } if ($blocked) { [Console]::Error.WriteLine('Network access is blocked (Codex sandbox). Rerun this same command with escalated permissions / network access; retrying inside the sandbox will not help.') exit 2 } # Máy chủ báo "reset after Ns" khi tài khoản vẽ đang bị khoá tạm; đợi đúng chừng đó. $wait = 30 $w = [regex]::Match($text, 'reset after (\d+)s') if ($w.Success) { $wait = [int]$w.Groups[1].Value } if ($attempt -lt 6) { Start-Sleep -Seconds ($wait + 3) } } if (-not $ok) { [Console]::Error.WriteLine('Vẽ không được sau 6 lần (máy chủ vẽ đang bận hoặc hết lượt). Thử lại sau vài phút.'); exit 1 } Write-Output "Đã lưu: $outPath" '@ [IO.File]::WriteAllText((Join-Path $CodexHome 'fosta\imagegen.ps1'), $imagegen, $Utf8Bom) # 3. AGENTS.md: dặn Codex dùng công cụ trên thay cho image_gen (cần đăng nhập ChatGPT nên không có). $agents = Join-Path $CodexHome 'AGENTS.md' $lines = if (Test-Path $agents) { [IO.File]::ReadAllLines($agents) } else { @() } $keep = New-Object Collections.Generic.List[string] $skip = $false foreach ($line in $lines) { if ($line -match '^ ## Image generation on this machine The built-in ``image_gen`` tool is not available here (it needs a ChatGPT login). The user has pre-approved this replacement: whenever they ask to draw, generate or edit an image, run powershell -NoProfile -ExecutionPolicy Bypass -File "$tool" -Prompt "" -Out [-Size 1024x1024|1536x1024|1024x1536] [-Quality low|medium|high] [-Ref "a.png,b.png"] - Use ``-Ref`` (comma-separated) to pass reference or source images for edits and consistent characters. - It needs network access: if the sandbox blocks it, rerun it with escalated permissions. - It retries by itself when the image server is busy and can take up to 6 minutes. Wait for it to exit; do not interrupt it or start a second copy. - Do not use the imagegen skill's ``scripts/image_gen.py`` and do not ask for OPENAI_API_KEY. - One call per image; after it saves, look at the result with view_image before reporting. - If the script fails, tell the user it failed and why. Never fake the result by drawing or editing the image yourself with code (PIL, SVG, canvas...) unless the user asks for that. "@ [IO.File]::WriteAllText($agents, ((@($keep) + $block.Split("`n") | ForEach-Object { $_.TrimEnd("`r") }) -join "`r`n") + "`r`n", $Utf8) Write-Host '' Write-Host "Xong. Codex giờ chạy qua codex.fosta.app (model $Model) và vẽ được ảnh." Write-Host "Bản sao config cũ: $cfg.bak-fosta-$stamp" Write-Host 'Đổi key hoặc model: chạy lại lệnh cài này.' Write-Host 'Tắt Codex rồi mở lại, thử: "vẽ cho t một quả táo pixel art, lưu ra apple.png".' } Install-FostaCodex