# Novaferry:把 Codex 会话记录里生成的图片取出来存成文件(Windows PowerShell 5.1 / 7 都能用) # # 为什么需要:通过第三方 API(包括 Novaferry)使用 Codex 时,模型生成的图片会完整传回 Codex、存在会话记录里, # 但 Codex 不会把它保存成图片文件,也不显示。这个脚本只读取本机的会话记录,不联网、不改任何文件, # 把图片另存到 用户目录\Codex-images\。 # # 用法:irm https://novaferry.com/tools/codex-images.ps1 | iex # 默认只找最近 7 天的会话;要找更早的,先设置 $NfDays = 30 再运行上面那行。 $ErrorActionPreference = 'Stop' $days = if ($NfDays) { [int]$NfDays } else { 7 } $codexHome = if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $HOME '.codex' } $outDir = Join-Path $HOME 'Codex-images' $since = (Get-Date).AddDays(-$days) $dirs = @('sessions', 'archived_sessions') | ForEach-Object { Join-Path $codexHome $_ } | Where-Object { Test-Path $_ } if (-not $dirs) { Write-Host "没找到 Codex 会话记录($codexHome\sessions)。"; return } $files = Get-ChildItem -Path $dirs -Recurse -Filter '*.jsonl' | Where-Object { $_.LastWriteTime -ge $since } $saved = 0; $skipped = 0 $unreadable = 0 foreach ($f in $files) { # Codex 运行时会占着正在写的会话文件:用「只读 + 允许别的程序同时读写」打开,打不开就跳过 try { $fs = [System.IO.File]::Open($f.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite -bor [System.IO.FileShare]::Delete) } catch { $unreadable++; continue } $reader = New-Object System.IO.StreamReader($fs, [System.Text.Encoding]::UTF8) try { while ($null -ne ($line = $reader.ReadLine())) { if ($line -notmatch '"type"\s*:\s*"image_generation_call"') { continue } $m = [regex]::Match($line, '"result"\s*:\s*"([A-Za-z0-9+/=]{100,})"') if (-not $m.Success) { continue } $b64 = $m.Groups[1].Value $id = [regex]::Match($line, '"id"\s*:\s*"([^"]+)"').Groups[1].Value $ts = [regex]::Match($line, '"timestamp"\s*:\s*"([0-9T:\-]+)').Groups[1].Value $ext = if ($b64.StartsWith('/9j/')) { 'jpg' } elseif ($b64.StartsWith('UklGR')) { 'webp' } else { 'png' } $stamp = ($ts -replace '[T:]', '-') if ($stamp.Length -gt 16) { $stamp = $stamp.Substring(0, 16) } $short = if ($id.Length -gt 8) { $id.Substring($id.Length - 8) } else { $id } [void][System.IO.Directory]::CreateDirectory($outDir) $path = Join-Path $outDir "$stamp-$short.$ext" if (Test-Path $path) { $skipped++; continue } [System.IO.File]::WriteAllBytes($path, [Convert]::FromBase64String($b64)) $saved++ Write-Host "已保存 $path" } } finally { $reader.Dispose(); $fs.Dispose() } } if ($unreadable -gt 0) { Write-Host "有 $unreadable 个会话文件打不开,已跳过;关掉 Codex 后再运行一次即可。" } if ($saved -eq 0 -and $skipped -eq 0) { Write-Host "最近 $days 天的 Codex 会话里没有找到生成的图片。" } else { Write-Host "完成:新保存 $saved 张,之前已保存过 $skipped 张。图片在 $outDir" if ($saved -gt 0) { Invoke-Item $outDir } }