Vendor Codex and land Phase 1 Epiphany state slice

This commit is contained in:
Meta Vens 2026-04-23 23:20:16 +01:00
commit 2042687e30
3959 changed files with 953751 additions and 7 deletions

127
vendor/codex/scripts/asciicheck.py vendored Normal file
View file

@ -0,0 +1,127 @@
#!/usr/bin/env python3
import argparse
import sys
from pathlib import Path
"""
Utility script that takes a list of files and returns non-zero if any of them
contain non-ASCII characters other than those in the allowed list.
If --fix is used, it will attempt to replace non-ASCII characters with ASCII
equivalents.
The motivation behind this script is that characters like U+00A0 (non-breaking
space) can cause regexes not to match and can result in surprising anchor
values for headings when GitHub renders Markdown as HTML.
"""
"""
When --fix is used, perform the following substitutions.
"""
substitutions: dict[int, str] = {
0x00A0: " ", # non-breaking space
0x2011: "-", # non-breaking hyphen
0x2013: "-", # en dash
0x2014: "-", # em dash
0x2018: "'", # left single quote
0x2019: "'", # right single quote
0x201C: '"', # left double quote
0x201D: '"', # right double quote
0x2026: "...", # ellipsis
0x202F: " ", # narrow non-breaking space
}
"""
Unicode codepoints that are allowed in addition to ASCII.
Be conservative with this list.
Note that it is always an option to use the hex HTML representation
instead of the character itself so the source code is ASCII-only.
For example, U+2728 (sparkles) can be written as `✨`.
"""
allowed_unicode_codepoints = {
0x2728, # sparkles
}
def main() -> int:
parser = argparse.ArgumentParser(
description="Check for non-ASCII characters in files."
)
parser.add_argument(
"--fix",
action="store_true",
help="Rewrite files, replacing non-ASCII characters with ASCII equivalents, where possible.",
)
parser.add_argument(
"files",
nargs="+",
help="Files to check for non-ASCII characters.",
)
args = parser.parse_args()
has_errors = False
for filename in args.files:
path = Path(filename)
has_errors |= lint_utf8_ascii(path, fix=args.fix)
return 1 if has_errors else 0
def lint_utf8_ascii(filename: Path, fix: bool) -> bool:
"""Returns True if an error was printed."""
try:
with open(filename, "rb") as f:
raw = f.read()
text = raw.decode("utf-8")
except UnicodeDecodeError as e:
print("UTF-8 decoding error:")
print(f" byte offset: {e.start}")
print(f" reason: {e.reason}")
# Attempt to find line/column
partial = raw[: e.start]
line = partial.count(b"\n") + 1
col = e.start - (partial.rfind(b"\n") if b"\n" in partial else -1)
print(f" location: line {line}, column {col}")
return True
errors = []
for lineno, line in enumerate(text.splitlines(keepends=True), 1):
for colno, char in enumerate(line, 1):
codepoint = ord(char)
if char == "\n":
continue
if (
not (0x20 <= codepoint <= 0x7E)
and codepoint not in allowed_unicode_codepoints
):
errors.append((lineno, colno, char, codepoint))
if errors:
for lineno, colno, char, codepoint in errors:
safe_char = repr(char)[1:-1] # nicely escape things like \u202f
print(
f"Invalid character at line {lineno}, column {colno}: U+{codepoint:04X} ({safe_char})"
)
if errors and fix:
print(f"Attempting to fix {filename}...")
num_replacements = 0
new_contents = ""
for char in text:
codepoint = ord(char)
if codepoint in substitutions:
num_replacements += 1
new_contents += substitutions[codepoint]
else:
new_contents += char
with open(filename, "w", encoding="utf-8") as f:
f.write(new_contents)
print(f"Fixed {num_replacements} of {len(errors)} errors in {filename}.")
return bool(errors)
if __name__ == "__main__":
sys.exit(main())

View file

@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
if ! bazel mod deps --lockfile_mode=error; then
echo "MODULE.bazel.lock is out of date."
echo "Run 'just bazel-lock-update' and commit the updated lockfile."
exit 1
fi

193
vendor/codex/scripts/check_blob_size.py vendored Normal file
View file

@ -0,0 +1,193 @@
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import os
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
DEFAULT_MAX_BYTES = 500 * 1024
@dataclass(frozen=True)
class ChangedBlob:
path: str
size_bytes: int
is_allowlisted: bool
is_binary: bool
def run_git(*args: str) -> str:
result = subprocess.run(
["git", *args],
check=True,
capture_output=True,
text=True,
)
return result.stdout
def load_allowlist(path: Path) -> set[str]:
allowlist: set[str] = set()
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.split("#", 1)[0].strip()
if line:
allowlist.add(line)
return allowlist
def get_changed_paths(base: str, head: str) -> list[str]:
output = run_git(
"diff",
"--name-only",
"--diff-filter=AM",
"--no-renames",
"-z",
base,
head,
)
return [path for path in output.split("\0") if path]
def is_binary_change(base: str, head: str, path: str) -> bool:
output = run_git(
"diff",
"--numstat",
"--diff-filter=AM",
"--no-renames",
base,
head,
"--",
path,
).strip()
if not output:
return False
added, deleted, _ = output.split("\t", 2)
return added == "-" and deleted == "-"
def blob_size(commit: str, path: str) -> int:
return int(run_git("cat-file", "-s", f"{commit}:{path}").strip())
def collect_changed_blobs(base: str, head: str, allowlist: set[str]) -> list[ChangedBlob]:
blobs: list[ChangedBlob] = []
for path in get_changed_paths(base, head):
blobs.append(
ChangedBlob(
path=path,
size_bytes=blob_size(head, path),
is_allowlisted=path in allowlist,
is_binary=is_binary_change(base, head, path),
)
)
return blobs
def format_kib(size_bytes: int) -> str:
return f"{size_bytes / 1024:.1f} KiB"
def write_step_summary(
max_bytes: int,
blobs: list[ChangedBlob],
violations: list[ChangedBlob],
) -> None:
summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
if not summary_path:
return
lines = [
"## Blob Size Policy",
"",
f"Default max: `{max_bytes}` bytes ({format_kib(max_bytes)})",
f"Changed files checked: `{len(blobs)}`",
f"Violations: `{len(violations)}`",
"",
]
if blobs:
lines.extend(
[
"| Path | Kind | Size | Status |",
"| --- | --- | ---: | --- |",
]
)
for blob in blobs:
status = "allowlisted" if blob.is_allowlisted else "ok"
if blob in violations:
status = "blocked"
kind = "binary" if blob.is_binary else "non-binary"
lines.append(
f"| `{blob.path}` | {kind} | `{blob.size_bytes}` bytes ({format_kib(blob.size_bytes)}) | {status} |"
)
else:
lines.append("No changed files were detected.")
lines.append("")
Path(summary_path).write_text("\n".join(lines), encoding="utf-8")
def main() -> int:
parser = argparse.ArgumentParser(
description="Fail if changed blobs exceed the configured size budget."
)
parser.add_argument("--base", required=True, help="Base git revision to diff against.")
parser.add_argument("--head", required=True, help="Head git revision to inspect.")
parser.add_argument(
"--max-bytes",
type=int,
default=DEFAULT_MAX_BYTES,
help=f"Maximum allowed blob size in bytes. Default: {DEFAULT_MAX_BYTES}.",
)
parser.add_argument(
"--allowlist",
type=Path,
required=True,
help="Path to the newline-delimited allowlist file.",
)
args = parser.parse_args()
allowlist = load_allowlist(args.allowlist)
blobs = collect_changed_blobs(args.base, args.head, allowlist)
violations = [
blob for blob in blobs if blob.size_bytes > args.max_bytes and not blob.is_allowlisted
]
write_step_summary(args.max_bytes, blobs, violations)
if not blobs:
print("No changed files were detected.")
return 0
print(f"Checked {len(blobs)} changed file(s) against the {args.max_bytes}-byte limit.")
for blob in blobs:
status = "allowlisted" if blob.is_allowlisted else "ok"
if blob in violations:
status = "blocked"
kind = "binary" if blob.is_binary else "non-binary"
print(
f"- {blob.path}: {blob.size_bytes} bytes ({format_kib(blob.size_bytes)}) [{kind}, {status}]"
)
if violations:
print("\nFile(s) exceed the configured limit:")
for blob in violations:
print(f"- {blob.path}: {blob.size_bytes} bytes > {args.max_bytes} bytes")
print(
"\nIf one of these is a real checked-in asset we want to keep, add its "
"repo-relative path to .github/blob-size-allowlist.txt. Otherwise, "
"shrink it or keep it out of git."
)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

10
vendor/codex/scripts/debug-codex.sh vendored Normal file
View file

@ -0,0 +1,10 @@
#!/bin/bash
# Set "chatgpt.cliExecutable": "/Users/<USERNAME>/code/codex/scripts/debug-codex.sh" in VSCode settings to always get the
# latest codex-rs binary when debugging Codex Extension.
set -euo pipefail
CODEX_RS_DIR=$(realpath "$(dirname "$0")/../codex-rs")
(cd "$CODEX_RS_DIR" && cargo run --quiet --bin codex -- "$@")

750
vendor/codex/scripts/install/install.ps1 vendored Normal file
View file

@ -0,0 +1,750 @@
param(
[string]$Release = "latest"
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
function Write-Step {
param(
[string]$Message
)
Write-Host "==> $Message"
}
function Write-WarningStep {
param(
[string]$Message
)
Write-Warning $Message
}
function Prompt-YesNo {
param(
[string]$Prompt
)
if ([Console]::IsInputRedirected -or [Console]::IsOutputRedirected) {
return $false
}
$choice = Read-Host "$Prompt [y/N]"
return $choice -match "^(?i:y(?:es)?)$"
}
function Normalize-Version {
param(
[string]$RawVersion
)
if ([string]::IsNullOrWhiteSpace($RawVersion) -or $RawVersion -eq "latest") {
return "latest"
}
if ($RawVersion.StartsWith("rust-v")) {
return $RawVersion.Substring(6)
}
if ($RawVersion.StartsWith("v")) {
return $RawVersion.Substring(1)
}
return $RawVersion
}
function Get-ReleaseAssetMetadata {
param(
[string]$AssetName,
[string]$ResolvedVersion
)
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/openai/codex/releases/tags/rust-v$ResolvedVersion"
$asset = $release.assets | Where-Object { $_.name -eq $AssetName } | Select-Object -First 1
if ($null -eq $asset) {
throw "Could not find release asset $AssetName for Codex $ResolvedVersion."
}
$digestMatch = [regex]::Match([string]$asset.digest, "^sha256:([0-9a-fA-F]{64})$")
if (-not $digestMatch.Success) {
throw "Could not find SHA-256 digest for release asset $AssetName."
}
return [PSCustomObject]@{
Url = $asset.browser_download_url
Sha256 = $digestMatch.Groups[1].Value.ToLowerInvariant()
}
}
function Test-ArchiveDigest {
param(
[string]$ArchivePath,
[string]$ExpectedDigest
)
$actualDigest = (Get-FileHash -LiteralPath $ArchivePath -Algorithm SHA256).Hash.ToLowerInvariant()
if ($actualDigest -ne $ExpectedDigest) {
throw "Downloaded Codex archive checksum did not match release metadata. Expected $ExpectedDigest but got $actualDigest."
}
}
function Path-Contains {
param(
[string]$PathValue,
[string]$Entry
)
if ([string]::IsNullOrWhiteSpace($PathValue)) {
return $false
}
$needle = $Entry.TrimEnd("\")
foreach ($segment in $PathValue.Split(";", [System.StringSplitOptions]::RemoveEmptyEntries)) {
if ($segment.TrimEnd("\") -ieq $needle) {
return $true
}
}
return $false
}
function Invoke-WithInstallLock {
param(
[string]$LockPath,
[scriptblock]$Script
)
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $LockPath) | Out-Null
$lock = $null
while ($null -eq $lock) {
try {
$lock = [System.IO.File]::Open(
$LockPath,
[System.IO.FileMode]::OpenOrCreate,
[System.IO.FileAccess]::ReadWrite,
[System.IO.FileShare]::None
)
} catch [System.IO.IOException] {
Start-Sleep -Milliseconds 250
}
}
try {
& $Script
} finally {
$lock.Dispose()
}
}
function Remove-StaleInstallArtifacts {
param(
[string]$ReleasesDir
)
if (Test-Path -LiteralPath $ReleasesDir -PathType Container) {
Get-ChildItem -LiteralPath $ReleasesDir -Force -Directory -Filter ".staging.*" -ErrorAction SilentlyContinue |
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
}
}
function Resolve-Version {
$normalizedVersion = Normalize-Version -RawVersion $Release
if ($normalizedVersion -ne "latest") {
return $normalizedVersion
}
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/openai/codex/releases/latest"
if (-not $release.tag_name) {
Write-Error "Failed to resolve the latest Codex release version."
exit 1
}
return (Normalize-Version -RawVersion $release.tag_name)
}
function Get-VersionFromBinary {
param(
[string]$CodexPath
)
if (-not (Test-Path -LiteralPath $CodexPath -PathType Leaf)) {
return $null
}
try {
$versionOutput = & $CodexPath --version 2>$null
} catch {
return $null
}
if ($versionOutput -match '([0-9][0-9A-Za-z.+-]*)$') {
return $matches[1]
}
return $null
}
function Get-CurrentInstalledVersion {
param(
[string]$StandaloneCurrentDir
)
$standaloneVersion = Get-VersionFromBinary -CodexPath (Join-Path $StandaloneCurrentDir "codex.exe")
if (-not [string]::IsNullOrWhiteSpace($standaloneVersion)) {
return $standaloneVersion
}
return $null
}
function Test-OldStandaloneBinLayout {
param(
[string]$VisibleBinDir,
[string]$DefaultVisibleBinDir
)
if (-not $VisibleBinDir.Equals($DefaultVisibleBinDir, [System.StringComparison]::OrdinalIgnoreCase)) {
return $false
}
if (-not (Test-Path -LiteralPath $VisibleBinDir -PathType Container)) {
return $false
}
$item = Get-Item -LiteralPath $VisibleBinDir -Force
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
return $false
}
$requiredFiles = @("codex.exe", "rg.exe")
foreach ($fileName in $requiredFiles) {
if (-not (Test-Path -LiteralPath (Join-Path $VisibleBinDir $fileName) -PathType Leaf)) {
return $false
}
}
$knownFiles = @(
"codex.exe",
"rg.exe",
"codex-command-runner.exe",
"codex-windows-sandbox.exe",
"codex-windows-sandbox-setup.exe"
)
foreach ($child in Get-ChildItem -LiteralPath $VisibleBinDir -Force) {
if ($child.PSIsContainer) {
return $false
}
if ($knownFiles -notcontains $child.Name) {
return $false
}
}
return $true
}
function Move-OldStandaloneBinIfApproved {
param(
[string]$VisibleBinDir,
[string]$DefaultVisibleBinDir
)
if (-not (Test-OldStandaloneBinLayout -VisibleBinDir $VisibleBinDir -DefaultVisibleBinDir $DefaultVisibleBinDir)) {
return $null
}
Write-Step "We found an older Codex install at $VisibleBinDir"
Write-WarningStep "To continue, Codex needs to update the install at this path."
if (-not (Prompt-YesNo "Replace it with the current Codex setup now?")) {
throw "Cannot replace older standalone install without confirmation: $VisibleBinDir"
}
$backupDir = "$VisibleBinDir.backup.$([DateTimeOffset]::UtcNow.ToUnixTimeSeconds()).$PID"
Write-Step "Moving older standalone install to $backupDir"
Move-Item -LiteralPath $VisibleBinDir -Destination $backupDir
return $backupDir
}
function Add-JunctionSupportType {
if (([System.Management.Automation.PSTypeName]'CodexInstaller.Junction').Type) {
return
}
Add-Type -TypeDefinition @"
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace CodexInstaller
{
public static class Junction
{
private const uint GENERIC_WRITE = 0x40000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint FILE_SHARE_DELETE = 0x00000004;
private const uint OPEN_EXISTING = 3;
private const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
private const uint FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;
private const uint FSCTL_SET_REPARSE_POINT = 0x000900A4;
private const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003;
private const int HeaderLength = 20;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFileW(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
byte[] lpInBuffer,
int nInBufferSize,
IntPtr lpOutBuffer,
int nOutBufferSize,
out int lpBytesReturned,
IntPtr lpOverlapped);
public static void SetTarget(string linkPath, string targetPath)
{
string substituteName = "\\??\\" + Path.GetFullPath(targetPath);
byte[] substituteNameBytes = Encoding.Unicode.GetBytes(substituteName);
if (substituteNameBytes.Length > ushort.MaxValue - HeaderLength) {
throw new ArgumentException("Junction target path is too long.", "targetPath");
}
byte[] reparseBuffer = new byte[substituteNameBytes.Length + HeaderLength];
WriteUInt32(reparseBuffer, 0, IO_REPARSE_TAG_MOUNT_POINT);
WriteUInt16(reparseBuffer, 4, checked((ushort)(substituteNameBytes.Length + 12)));
WriteUInt16(reparseBuffer, 8, 0);
WriteUInt16(reparseBuffer, 10, checked((ushort)substituteNameBytes.Length));
WriteUInt16(reparseBuffer, 12, checked((ushort)(substituteNameBytes.Length + 2)));
WriteUInt16(reparseBuffer, 14, 0);
Buffer.BlockCopy(substituteNameBytes, 0, reparseBuffer, 16, substituteNameBytes.Length);
using (SafeFileHandle handle = CreateFileW(
linkPath,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
IntPtr.Zero,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
IntPtr.Zero))
{
if (handle.IsInvalid) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
int bytesReturned;
if (!DeviceIoControl(
handle,
FSCTL_SET_REPARSE_POINT,
reparseBuffer,
reparseBuffer.Length,
IntPtr.Zero,
0,
out bytesReturned,
IntPtr.Zero))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
private static void WriteUInt16(byte[] buffer, int offset, ushort value)
{
buffer[offset] = (byte)value;
buffer[offset + 1] = (byte)(value >> 8);
}
private static void WriteUInt32(byte[] buffer, int offset, uint value)
{
buffer[offset] = (byte)value;
buffer[offset + 1] = (byte)(value >> 8);
buffer[offset + 2] = (byte)(value >> 16);
buffer[offset + 3] = (byte)(value >> 24);
}
}
}
"@
}
function Set-JunctionTarget {
param(
[string]$LinkPath,
[string]$TargetPath
)
Add-JunctionSupportType
[CodexInstaller.Junction]::SetTarget($LinkPath, $TargetPath)
}
function Test-IsJunction {
param(
[string]$Path
)
if (-not (Test-Path -LiteralPath $Path)) {
return $false
}
$item = Get-Item -LiteralPath $Path -Force
return ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -and $item.LinkType -eq "Junction"
}
function Ensure-Junction {
param(
[string]$LinkPath,
[string]$TargetPath,
[string]$InstallerOwnedTargetPrefix
)
if (-not (Test-Path -LiteralPath $LinkPath)) {
New-Item -ItemType Junction -Path $LinkPath -Target $TargetPath | Out-Null
return
}
$item = Get-Item -LiteralPath $LinkPath -Force
if (Test-IsJunction -Path $LinkPath) {
$existingTarget = [string]$item.Target
if (-not [string]::IsNullOrWhiteSpace($InstallerOwnedTargetPrefix)) {
$ownedTargetPrefix = $InstallerOwnedTargetPrefix.TrimEnd("\\")
if (-not $existingTarget.StartsWith($ownedTargetPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Refusing to retarget junction at $LinkPath because it is not managed by this installer."
}
}
if ($existingTarget.Equals($TargetPath, [System.StringComparison]::OrdinalIgnoreCase)) {
return
}
# Keep the path itself in place and only retarget the junction. That
# avoids a gap where current or the visible bin path disappears during
# an update.
Set-JunctionTarget -LinkPath $LinkPath -TargetPath $TargetPath
return
}
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
throw "Refusing to replace non-junction reparse point at $LinkPath."
}
if ($item.PSIsContainer) {
if ((Get-ChildItem -LiteralPath $LinkPath -Force | Select-Object -First 1) -ne $null) {
throw "Refusing to replace non-empty directory at $LinkPath with a junction."
}
Remove-Item -LiteralPath $LinkPath -Force
New-Item -ItemType Junction -Path $LinkPath -Target $TargetPath | Out-Null
return
}
throw "Refusing to replace file at $LinkPath with a junction."
}
function Test-ReleaseIsComplete {
param(
[string]$ReleaseDir,
[string]$ExpectedVersion,
[string]$ExpectedTarget
)
if (-not (Test-Path -LiteralPath $ReleaseDir -PathType Container)) {
return $false
}
$expectedFiles = @(
"codex.exe",
"codex-resources\codex-command-runner.exe",
"codex-resources\codex-windows-sandbox-setup.exe",
"codex-resources\rg.exe"
)
foreach ($name in $expectedFiles) {
if (-not (Test-Path -LiteralPath (Join-Path $ReleaseDir $name) -PathType Leaf)) {
return $false
}
}
return (Split-Path -Leaf $ReleaseDir) -eq "$ExpectedVersion-$ExpectedTarget"
}
function Get-ExistingCodexCommand {
$existing = Get-Command codex -ErrorAction SilentlyContinue
if ($null -eq $existing) {
return $null
}
return $existing.Source
}
function Get-ExistingCodexManager {
param(
[string]$ExistingPath,
[string]$VisibleBinDir
)
if ([string]::IsNullOrWhiteSpace($ExistingPath)) {
return $null
}
if ($ExistingPath.StartsWith($VisibleBinDir, [System.StringComparison]::OrdinalIgnoreCase)) {
return $null
}
if ($ExistingPath -match "\\.bun\\") {
return "bun"
}
if ($ExistingPath -match "node_modules" -or $ExistingPath -match "\\npm\\") {
return "npm"
}
return $null
}
function Get-ConflictingInstall {
param(
[string]$VisibleBinDir
)
$existingPath = Get-ExistingCodexCommand
$manager = Get-ExistingCodexManager -ExistingPath $existingPath -VisibleBinDir $VisibleBinDir
if ($null -eq $manager) {
return $null
}
Write-Step "Detected existing $manager-managed Codex at $existingPath"
Write-WarningStep "Multiple managed Codex installs can be ambiguous because PATH order decides which one runs."
return [PSCustomObject]@{
Manager = $manager
Path = $existingPath
}
}
function Maybe-HandleConflictingInstall {
param(
[object]$Conflict
)
if ($null -eq $Conflict) {
return
}
$manager = $Conflict.Manager
$uninstallArgs = if ($manager -eq "bun") {
@("remove", "-g", "@openai/codex")
} else {
@("uninstall", "-g", "@openai/codex")
}
$uninstallCommand = if ($manager -eq "bun") { "bun" } else { "npm" }
if (Prompt-YesNo "Uninstall the existing $manager-managed Codex now?") {
Write-Step "Running: $uninstallCommand $($uninstallArgs -join ' ')"
try {
& $uninstallCommand @uninstallArgs
} catch {
Write-WarningStep "Failed to uninstall the existing $manager-managed Codex. Continuing with the standalone install."
}
} else {
Write-WarningStep "Leaving the existing $manager-managed Codex installed. PATH order will determine which codex runs."
}
}
function Test-VisibleCodexCommand {
param(
[string]$VisibleBinDir
)
$codexCommand = Join-Path $VisibleBinDir "codex.exe"
& $codexCommand --version *> $null
if ($LASTEXITCODE -ne 0) {
throw "Installed Codex command failed verification: $codexCommand --version"
}
}
if ($env:OS -ne "Windows_NT") {
Write-Error "install.ps1 supports Windows only. Use install.sh on macOS or Linux."
exit 1
}
if (-not [Environment]::Is64BitOperatingSystem) {
Write-Error "Codex requires a 64-bit version of Windows."
exit 1
}
$architecture = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture
$target = $null
$platformLabel = $null
$npmTag = $null
switch ($architecture) {
"Arm64" {
$target = "aarch64-pc-windows-msvc"
$platformLabel = "Windows (ARM64)"
$npmTag = "win32-arm64"
}
"X64" {
$target = "x86_64-pc-windows-msvc"
$platformLabel = "Windows (x64)"
$npmTag = "win32-x64"
}
default {
Write-Error "Unsupported architecture: $architecture"
exit 1
}
}
$codexHome = if ([string]::IsNullOrWhiteSpace($env:CODEX_HOME)) {
Join-Path $env:USERPROFILE ".codex"
} else {
$env:CODEX_HOME
}
$standaloneRoot = Join-Path $codexHome "packages\standalone"
$releasesDir = Join-Path $standaloneRoot "releases"
$currentDir = Join-Path $standaloneRoot "current"
$lockPath = Join-Path $standaloneRoot "install.lock"
$defaultVisibleBinDir = Join-Path $env:LOCALAPPDATA "Programs\OpenAI\Codex\bin"
if ([string]::IsNullOrWhiteSpace($env:CODEX_INSTALL_DIR)) {
$visibleBinDir = $defaultVisibleBinDir
} else {
$visibleBinDir = $env:CODEX_INSTALL_DIR
}
$currentVersion = Get-CurrentInstalledVersion -StandaloneCurrentDir $currentDir
$resolvedVersion = Resolve-Version
$releaseName = "$resolvedVersion-$target"
$releaseDir = Join-Path $releasesDir $releaseName
if (-not [string]::IsNullOrWhiteSpace($currentVersion) -and $currentVersion -ne $resolvedVersion) {
Write-Step "Updating Codex CLI from $currentVersion to $resolvedVersion"
} elseif (-not [string]::IsNullOrWhiteSpace($currentVersion)) {
Write-Step "Updating Codex CLI"
} else {
Write-Step "Installing Codex CLI"
}
Write-Step "Detected platform: $platformLabel"
Write-Step "Resolved version: $resolvedVersion"
$conflictingInstall = Get-ConflictingInstall -VisibleBinDir $visibleBinDir
$oldStandaloneBackup = $null
$packageAsset = "codex-npm-$npmTag-$resolvedVersion.tgz"
$tempDir = Join-Path ([System.IO.Path]::GetTempPath()) ("codex-install-" + [System.Guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Force -Path $tempDir | Out-Null
try {
Invoke-WithInstallLock -LockPath $lockPath -Script {
Remove-StaleInstallArtifacts -ReleasesDir $releasesDir
if (-not (Test-ReleaseIsComplete -ReleaseDir $releaseDir -ExpectedVersion $resolvedVersion -ExpectedTarget $target)) {
if (Test-Path -LiteralPath $releaseDir) {
Write-WarningStep "Found incomplete existing release at $releaseDir. Reinstalling."
}
$archivePath = Join-Path $tempDir $packageAsset
$extractDir = Join-Path $tempDir "extract"
$stagingDir = Join-Path $releasesDir ".staging.$releaseName.$PID"
$assetMetadata = Get-ReleaseAssetMetadata -AssetName $packageAsset -ResolvedVersion $resolvedVersion
Write-Step "Downloading Codex CLI"
Invoke-WebRequest -Uri $assetMetadata.Url -OutFile $archivePath
Test-ArchiveDigest -ArchivePath $archivePath -ExpectedDigest $assetMetadata.Sha256
New-Item -ItemType Directory -Force -Path $extractDir | Out-Null
New-Item -ItemType Directory -Force -Path $releasesDir | Out-Null
if (Test-Path -LiteralPath $stagingDir) {
Remove-Item -LiteralPath $stagingDir -Recurse -Force
}
New-Item -ItemType Directory -Force -Path $stagingDir | Out-Null
tar -xzf $archivePath -C $extractDir
$vendorRoot = Join-Path $extractDir "package/vendor/$target"
$resourcesDir = Join-Path $stagingDir "codex-resources"
New-Item -ItemType Directory -Force -Path $resourcesDir | Out-Null
$copyMap = @{
"codex/codex.exe" = "codex.exe"
"codex/codex-command-runner.exe" = "codex-resources\codex-command-runner.exe"
"codex/codex-windows-sandbox-setup.exe" = "codex-resources\codex-windows-sandbox-setup.exe"
"path/rg.exe" = "codex-resources\rg.exe"
}
foreach ($relativeSource in $copyMap.Keys) {
Copy-Item -LiteralPath (Join-Path $vendorRoot $relativeSource) -Destination (Join-Path $stagingDir $copyMap[$relativeSource])
}
if (Test-Path -LiteralPath $releaseDir) {
Remove-Item -LiteralPath $releaseDir -Recurse -Force
}
Move-Item -LiteralPath $stagingDir -Destination $releaseDir
}
New-Item -ItemType Directory -Force -Path $standaloneRoot | Out-Null
Ensure-Junction -LinkPath $currentDir -TargetPath $releaseDir -InstallerOwnedTargetPrefix $releasesDir
$visibleParent = Split-Path -Parent $visibleBinDir
New-Item -ItemType Directory -Force -Path $visibleParent | Out-Null
$oldStandaloneBackup = Move-OldStandaloneBinIfApproved -VisibleBinDir $visibleBinDir -DefaultVisibleBinDir $defaultVisibleBinDir
try {
Ensure-Junction -LinkPath $visibleBinDir -TargetPath $currentDir -InstallerOwnedTargetPrefix $standaloneRoot
Test-VisibleCodexCommand -VisibleBinDir $visibleBinDir
} catch {
if ($null -ne $oldStandaloneBackup -and (Test-Path -LiteralPath $oldStandaloneBackup)) {
if (Test-Path -LiteralPath $visibleBinDir) {
Remove-Item -LiteralPath $visibleBinDir -Recurse -Force
}
Move-Item -LiteralPath $oldStandaloneBackup -Destination $visibleBinDir
}
throw
}
if ($null -ne $oldStandaloneBackup) {
Remove-Item -LiteralPath $oldStandaloneBackup -Recurse -Force
}
}
} finally {
Remove-Item -Recurse -Force $tempDir -ErrorAction SilentlyContinue
}
Maybe-HandleConflictingInstall -Conflict $conflictingInstall
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
if (-not (Path-Contains -PathValue $userPath -Entry $visibleBinDir)) {
if ([string]::IsNullOrWhiteSpace($userPath)) {
$newUserPath = $visibleBinDir
} else {
$newUserPath = "$visibleBinDir;$userPath"
}
[Environment]::SetEnvironmentVariable("Path", $newUserPath, "User")
Write-Step "PATH updated for future PowerShell sessions."
} elseif (Path-Contains -PathValue $env:Path -Entry $visibleBinDir) {
Write-Step "$visibleBinDir is already on PATH."
} else {
Write-Step "PATH is already configured for future PowerShell sessions."
}
if (-not (Path-Contains -PathValue $env:Path -Entry $visibleBinDir)) {
if ([string]::IsNullOrWhiteSpace($env:Path)) {
$env:Path = $visibleBinDir
} else {
$env:Path = "$visibleBinDir;$env:Path"
}
}
Write-Step "Current PowerShell session: codex"
Write-Step "Future PowerShell windows: open a new PowerShell window and run: codex"
Write-Host "Codex CLI $resolvedVersion installed successfully."
$codexCommand = Join-Path $visibleBinDir "codex.exe"
if (Prompt-YesNo "Start Codex now?") {
Write-Step "Launching Codex"
& $codexCommand
}

768
vendor/codex/scripts/install/install.sh vendored Normal file
View file

@ -0,0 +1,768 @@
#!/bin/sh
set -eu
RELEASE="latest"
BIN_DIR="${CODEX_INSTALL_DIR:-$HOME/.local/bin}"
BIN_PATH="$BIN_DIR/codex"
CODEX_HOME_DIR="${CODEX_HOME:-$HOME/.codex}"
STANDALONE_ROOT="$CODEX_HOME_DIR/packages/standalone"
RELEASES_DIR="$STANDALONE_ROOT/releases"
CURRENT_LINK="$STANDALONE_ROOT/current"
LOCK_FILE="$STANDALONE_ROOT/install.lock"
LOCK_DIR="$STANDALONE_ROOT/install.lock.d"
LOCK_STALE_AFTER_SECS=600
path_action="already"
path_profile=""
conflict_manager=""
conflict_path=""
lock_kind=""
tmp_dir=""
step() {
printf '==> %s\n' "$1"
}
warn() {
printf 'WARNING: %s\n' "$1" >&2
}
normalize_version() {
case "$1" in
"" | latest)
printf 'latest\n'
;;
rust-v*)
printf '%s\n' "${1#rust-v}"
;;
v*)
printf '%s\n' "${1#v}"
;;
*)
printf '%s\n' "$1"
;;
esac
}
parse_args() {
while [ "$#" -gt 0 ]; do
case "$1" in
--release)
if [ "$#" -lt 2 ]; then
echo "--release requires a value." >&2
exit 1
fi
RELEASE="$2"
shift
;;
--help | -h)
cat <<EOF
Usage: install.sh [--release VERSION]
EOF
exit 0
;;
*)
echo "Unknown argument: $1" >&2
exit 1
;;
esac
shift
done
}
download_file() {
url="$1"
output="$2"
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$url" -o "$output"
return
fi
if command -v wget >/dev/null 2>&1; then
wget -q -O "$output" "$url"
return
fi
echo "curl or wget is required to install Codex." >&2
exit 1
}
download_text() {
url="$1"
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$url"
return
fi
if command -v wget >/dev/null 2>&1; then
wget -q -O - "$url"
return
fi
echo "curl or wget is required to install Codex." >&2
exit 1
}
release_url_for_asset() {
asset="$1"
resolved_version="$2"
printf 'https://github.com/openai/codex/releases/download/rust-v%s/%s\n' "$resolved_version" "$asset"
}
release_metadata_url() {
resolved_version="$1"
printf 'https://api.github.com/repos/openai/codex/releases/tags/rust-v%s\n' "$resolved_version"
}
release_asset_digest() {
asset="$1"
resolved_version="$2"
release_json="$(download_text "$(release_metadata_url "$resolved_version")")"
digest="$(printf '%s\n' "$release_json" | awk -v asset="$asset" '
{
if ($0 ~ "\"name\":[[:space:]]*\"" asset "\"") {
in_asset = 1
asset_depth = depth
}
if (in_asset && /"digest":[[:space:]]*"[^"]+"/) {
sub(/^.*"digest":[[:space:]]*"/, "")
sub(/".*$/, "")
digest = $0
}
line = $0
opens = gsub(/\{/, "{", line)
closes = gsub(/\}/, "}", line)
depth += opens - closes
if (in_asset && depth < asset_depth) {
in_asset = 0
}
}
END {
if (digest != "") {
print digest
}
}
')"
case "$digest" in
sha256:????????????????????????????????????????????????????????????????)
printf '%s\n' "${digest#sha256:}"
;;
*)
echo "Could not find SHA-256 digest for release asset $asset." >&2
exit 1
;;
esac
}
file_sha256() {
path="$1"
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "$path" | awk '{print $1}'
return
fi
if command -v shasum >/dev/null 2>&1; then
shasum -a 256 "$path" | awk '{print $1}'
return
fi
if command -v openssl >/dev/null 2>&1; then
openssl dgst -sha256 "$path" | sed 's/^.*= //'
return
fi
echo "sha256sum, shasum, or openssl is required to verify the Codex download." >&2
exit 1
}
verify_archive_digest() {
archive_path="$1"
expected_digest="$2"
actual_digest="$(file_sha256 "$archive_path")"
if [ "$actual_digest" != "$expected_digest" ]; then
echo "Downloaded Codex archive checksum did not match release metadata." >&2
echo "expected: $expected_digest" >&2
echo "actual: $actual_digest" >&2
exit 1
fi
}
require_command() {
if ! command -v "$1" >/dev/null 2>&1; then
echo "$1 is required to install Codex." >&2
exit 1
fi
}
resolve_version() {
normalized_version="$(normalize_version "$RELEASE")"
if [ "$normalized_version" != "latest" ]; then
printf '%s\n' "$normalized_version"
return
fi
release_json="$(download_text "https://api.github.com/repos/openai/codex/releases/latest")"
resolved="$(printf '%s\n' "$release_json" | sed -n 's/.*"tag_name":[[:space:]]*"rust-v\([^"]*\)".*/\1/p' | head -n 1)"
if [ -z "$resolved" ]; then
echo "Failed to resolve the latest Codex release version." >&2
exit 1
fi
printf '%s\n' "$resolved"
}
pick_profile() {
# Use the same shell-specific split Homebrew documents because there is no
# universal startup file across macOS/Linux login and interactive shells.
case "$os:${SHELL:-}" in
darwin:*/zsh)
printf '%s\n' "$HOME/.zprofile"
;;
darwin:*/bash)
printf '%s\n' "$HOME/.bash_profile"
;;
linux:*/zsh)
printf '%s\n' "$HOME/.zshrc"
;;
linux:*/bash)
printf '%s\n' "$HOME/.bashrc"
;;
*)
printf '%s\n' "$HOME/.profile"
;;
esac
}
add_to_path() {
path_action="already"
path_profile=""
case ":$PATH:" in
*":$BIN_DIR:"*)
return
;;
esac
profile="$(pick_profile)"
path_profile="$profile"
begin_marker="# >>> Codex installer >>>"
end_marker="# <<< Codex installer <<<"
path_line="export PATH=\"$BIN_DIR:\$PATH\""
if [ -f "$profile" ] && grep -F "$begin_marker" "$profile" >/dev/null 2>&1; then
if grep -F "$path_line" "$profile" >/dev/null 2>&1; then
path_action="configured"
return
fi
if grep -F "$end_marker" "$profile" >/dev/null 2>&1; then
rewrite_path_block "$profile" "$begin_marker" "$end_marker" "$path_line"
path_action="updated"
return
fi
fi
append_path_block "$profile" "$begin_marker" "$end_marker" "$path_line"
path_action="added"
}
append_path_block() {
profile="$1"
begin_marker="$2"
end_marker="$3"
path_line="$4"
{
printf '\n%s\n' "$begin_marker"
printf '%s\n' "$path_line"
printf '%s\n' "$end_marker"
} >>"$profile"
}
rewrite_path_block() {
profile="$1"
begin_marker="$2"
end_marker="$3"
path_line="$4"
tmp_profile="$tmp_dir/profile.$$.tmp"
awk -v begin="$begin_marker" -v end="$end_marker" -v line="$path_line" '
BEGIN {
in_block = 0
replaced = 0
}
$0 == begin {
if (!replaced) {
print begin
print line
print end
replaced = 1
}
in_block = 1
next
}
in_block {
if ($0 == end) {
in_block = 0
}
next
}
{
print
}
END {
if (in_block != 0) {
exit 1
}
}
' "$profile" >"$tmp_profile"
mv "$tmp_profile" "$profile"
}
mkdir_lock_is_stale() {
[ -d "$LOCK_DIR" ] || return 1
pid="$(cat "$LOCK_DIR/pid" 2>/dev/null || true)"
started_at="$(cat "$LOCK_DIR/started_at" 2>/dev/null || true)"
now="$(date +%s 2>/dev/null || printf '0')"
case "$started_at" in
''|*[!0-9]*)
started_at=0
;;
esac
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
return 1
fi
if [ "$started_at" -eq 0 ] || [ "$now" -eq 0 ]; then
return 0
fi
[ $((now - started_at)) -ge "$LOCK_STALE_AFTER_SECS" ]
}
acquire_install_lock() {
mkdir -p "$STANDALONE_ROOT"
if [ "$os" = "darwin" ] && command -v lockf >/dev/null 2>&1; then
: >>"$LOCK_FILE"
exec 9<>"$LOCK_FILE"
lockf 9
lock_kind="lockf"
return
fi
if command -v flock >/dev/null 2>&1; then
exec 9>"$LOCK_FILE"
flock 9
lock_kind="flock"
return
fi
while ! mkdir "$LOCK_DIR" 2>/dev/null; do
if mkdir_lock_is_stale; then
warn "Removing stale installer lock at $LOCK_DIR"
rm -rf "$LOCK_DIR"
continue
fi
sleep 1
done
printf '%s\n' "$$" >"$LOCK_DIR/pid"
date +%s >"$LOCK_DIR/started_at" 2>/dev/null || true
lock_kind="mkdir"
}
release_install_lock() {
if [ "$lock_kind" = "mkdir" ]; then
rm -rf "$LOCK_DIR" 2>/dev/null || true
elif [ "$lock_kind" = "flock" ] || [ "$lock_kind" = "lockf" ]; then
exec 9>&- 2>/dev/null || true
fi
lock_kind=""
}
cleanup_stale_install_artifacts() {
mkdir -p "$RELEASES_DIR" "$STANDALONE_ROOT"
find "$RELEASES_DIR" -mindepth 1 -maxdepth 1 -name '.staging.*' -exec rm -rf {} +
find "$STANDALONE_ROOT" -mindepth 1 -maxdepth 1 -name '.current.*' -exec rm -f {} +
if [ -d "$BIN_DIR" ]; then
find "$BIN_DIR" -mindepth 1 -maxdepth 1 -name '.codex.*' -exec rm -f {} +
fi
}
replace_path_with_symlink() {
link_path="$1"
link_target="$2"
tmp_link="$3"
rm -f "$tmp_link"
ln -s "$link_target" "$tmp_link"
if mv -Tf "$tmp_link" "$link_path" 2>/dev/null; then
return
fi
if mv -hf "$tmp_link" "$link_path" 2>/dev/null; then
return
fi
rm -f "$link_path"
mv -f "$tmp_link" "$link_path"
}
version_from_binary() {
codex_path="$1"
if [ ! -x "$codex_path" ]; then
return 1
fi
"$codex_path" --version 2>/dev/null | sed -n 's/.* \([0-9][0-9A-Za-z.+-]*\)$/\1/p' | head -n 1
}
current_installed_version() {
version="$(version_from_binary "$CURRENT_LINK/codex" || true)"
if [ -n "$version" ]; then
printf '%s\n' "$version"
return 0
fi
return 0
}
resolve_existing_codex() {
command -v codex 2>/dev/null || true
}
classify_existing_codex() {
existing_path="$1"
if [ -z "$existing_path" ] || [ "$existing_path" = "$BIN_PATH" ]; then
return 1
fi
case "$existing_path" in
/opt/homebrew/* | /usr/local/*)
if [ "$os" = "darwin" ]; then
printf 'brew\n'
return 0
fi
;;
esac
if [ -f "$existing_path" ] && grep -F "#!/usr/bin/env node" "$existing_path" >/dev/null 2>&1; then
case "$existing_path" in
*".bun"*)
printf 'bun\n'
;;
*)
printf 'npm\n'
;;
esac
return 0
fi
return 1
}
prompt_yes_no() {
prompt="$1"
if ( : </dev/tty ) 2>/dev/null; then
printf '%s [y/N] ' "$prompt" >/dev/tty
if ! IFS= read -r answer </dev/tty; then
return 1
fi
elif [ -t 0 ]; then
printf '%s [y/N] ' "$prompt"
if ! IFS= read -r answer; then
return 1
fi
else
return 1
fi
case "$answer" in
y | Y | yes | YES)
return 0
;;
*)
return 1
;;
esac
}
print_launch_instructions() {
case "$path_action" in
added)
step "Current terminal: export PATH=\"$BIN_DIR:\$PATH\" && codex"
step "Future terminals: open a new terminal and run: codex"
step "PATH was added to $path_profile"
;;
updated)
step "Current terminal: export PATH=\"$BIN_DIR:\$PATH\" && codex"
step "Future terminals: open a new terminal and run: codex"
step "PATH was updated in $path_profile"
;;
configured)
step "Current terminal: export PATH=\"$BIN_DIR:\$PATH\" && codex"
step "Future terminals: open a new terminal and run: codex"
step "PATH is already configured in $path_profile"
;;
*)
step "Current terminal: codex"
step "Future terminals: open a new terminal and run: codex"
;;
esac
}
maybe_launch_codex_now() {
if prompt_yes_no "Start Codex now?"; then
step "Launching Codex"
"$BIN_PATH"
fi
}
detect_conflicting_install() {
existing_path="$(resolve_existing_codex)"
manager="$(classify_existing_codex "$existing_path" || true)"
if [ -z "$manager" ]; then
return
fi
conflict_manager="$manager"
conflict_path="$existing_path"
step "Detected existing $manager-managed Codex at $existing_path"
warn "Multiple managed Codex installs can be ambiguous because PATH order decides which one runs."
}
handle_conflicting_install() {
if [ -z "$conflict_manager" ]; then
return
fi
case "$conflict_manager" in
brew)
uninstall_cmd="brew uninstall --cask codex"
;;
bun)
uninstall_cmd="bun remove -g @openai/codex"
;;
*)
uninstall_cmd="npm uninstall -g @openai/codex"
;;
esac
if prompt_yes_no "Uninstall the existing $conflict_manager-managed Codex now?"; then
step "Running: $uninstall_cmd"
if ! sh -c "$uninstall_cmd"; then
warn "Failed to uninstall the existing $conflict_manager-managed Codex. Continuing with the standalone install."
fi
else
warn "Leaving the existing $conflict_manager-managed Codex installed. PATH order will determine which codex runs."
fi
}
install_release() {
release_dir="$1"
vendor_root="$2"
stage_release="$RELEASES_DIR/.staging.$(basename "$release_dir").$$"
mkdir -p "$RELEASES_DIR"
rm -rf "$stage_release"
mkdir -p "$stage_release/codex-resources"
cp "$vendor_root/codex/codex" "$stage_release/codex"
cp "$vendor_root/path/rg" "$stage_release/codex-resources/rg"
chmod 0755 "$stage_release/codex"
chmod 0755 "$stage_release/codex-resources/rg"
if [ -e "$release_dir" ] || [ -L "$release_dir" ]; then
rm -rf "$release_dir"
fi
mv "$stage_release" "$release_dir"
}
release_dir_is_complete() {
release_dir="$1"
expected_version="$2"
expected_target="$3"
[ -d "$release_dir" ] &&
[ -x "$release_dir/codex" ] &&
[ -x "$release_dir/codex-resources/rg" ] &&
[ "$(basename "$release_dir")" = "$expected_version-$expected_target" ]
}
update_current_link() {
release_dir="$1"
tmp_link="$STANDALONE_ROOT/.current.$$"
replace_path_with_symlink "$CURRENT_LINK" "$release_dir" "$tmp_link"
}
update_visible_command() {
mkdir -p "$BIN_DIR"
tmp_link="$BIN_DIR/.codex.$$"
replace_path_with_symlink "$BIN_PATH" "$CURRENT_LINK/codex" "$tmp_link"
}
verify_visible_command() {
"$BIN_PATH" --version >/dev/null
}
parse_args "$@"
require_command mktemp
require_command tar
case "$(uname -s)" in
Darwin)
os="darwin"
;;
Linux)
os="linux"
;;
*)
echo "install.sh supports macOS and Linux. Use install.ps1 on Windows." >&2
exit 1
;;
esac
case "$(uname -m)" in
x86_64 | amd64)
arch="x86_64"
;;
arm64 | aarch64)
arch="aarch64"
;;
*)
echo "Unsupported architecture: $(uname -m)" >&2
exit 1
;;
esac
if [ "$os" = "darwin" ] && [ "$arch" = "x86_64" ]; then
if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || true)" = "1" ]; then
arch="aarch64"
fi
fi
if [ "$os" = "darwin" ]; then
if [ "$arch" = "aarch64" ]; then
npm_tag="darwin-arm64"
vendor_target="aarch64-apple-darwin"
platform_label="macOS (Apple Silicon)"
else
npm_tag="darwin-x64"
vendor_target="x86_64-apple-darwin"
platform_label="macOS (Intel)"
fi
else
if [ "$arch" = "aarch64" ]; then
npm_tag="linux-arm64"
vendor_target="aarch64-unknown-linux-musl"
platform_label="Linux (ARM64)"
else
npm_tag="linux-x64"
vendor_target="x86_64-unknown-linux-musl"
platform_label="Linux (x64)"
fi
fi
resolved_version="$(resolve_version)"
asset="codex-npm-$npm_tag-$resolved_version.tgz"
download_url="$(release_url_for_asset "$asset" "$resolved_version")"
release_name="$resolved_version-$vendor_target"
release_dir="$RELEASES_DIR/$release_name"
current_version="$(current_installed_version)"
if [ -n "$current_version" ] && [ "$current_version" != "$resolved_version" ]; then
step "Updating Codex CLI from $current_version to $resolved_version"
elif [ -n "$current_version" ]; then
step "Updating Codex CLI"
else
step "Installing Codex CLI"
fi
step "Detected platform: $platform_label"
step "Resolved version: $resolved_version"
detect_conflicting_install
tmp_dir="$(mktemp -d)"
cleanup() {
release_install_lock
if [ -n "$tmp_dir" ]; then
rm -rf "$tmp_dir"
fi
}
trap cleanup EXIT INT TERM
acquire_install_lock
cleanup_stale_install_artifacts
if ! release_dir_is_complete "$release_dir" "$resolved_version" "$vendor_target"; then
if [ -e "$release_dir" ] || [ -L "$release_dir" ]; then
warn "Found incomplete existing release at $release_dir; reinstalling."
fi
archive_path="$tmp_dir/$asset"
extract_dir="$tmp_dir/extract"
step "Downloading Codex CLI"
expected_digest="$(release_asset_digest "$asset" "$resolved_version")"
download_file "$download_url" "$archive_path"
verify_archive_digest "$archive_path" "$expected_digest"
mkdir -p "$extract_dir"
tar -xzf "$archive_path" -C "$extract_dir"
step "Installing standalone package to $release_dir"
install_release "$release_dir" "$extract_dir/package/vendor/$vendor_target"
fi
update_current_link "$release_dir"
update_visible_command
add_to_path
verify_visible_command
release_install_lock
handle_conflicting_install
case "$path_action" in
added)
print_launch_instructions
;;
updated)
print_launch_instructions
;;
configured)
print_launch_instructions
;;
*)
step "$BIN_DIR is already on PATH"
print_launch_instructions
;;
esac
printf 'Codex CLI %s installed successfully.\n' "$resolved_version"
maybe_launch_codex_now

View file

@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${repo_root}"
# Resolve the dynamic targets before printing anything so callers do not
# continue with a partial list if `bazel query` fails.
manual_rust_test_targets="$(bazel query 'kind("rust_test rule", attr(tags, "manual", //codex-rs/... except //codex-rs/v8-poc/...))')"
printf '%s\n' \
"//codex-rs/..." \
"-//codex-rs/v8-poc:all"
# `--config=clippy` on the `workspace_root_test` wrappers does not lint the
# underlying `rust_test` binaries. Add the internal manual `*-unit-tests-bin`
# targets explicitly so inline `#[cfg(test)]` code is linted like
# `cargo clippy --tests`.
printf '%s\n' "${manual_rust_test_targets}"

View file

@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${repo_root}"
# Keep this list focused on first-party Rust targets whose compile surface can
# differ when `cfg(not(debug_assertions))` becomes active.
#
# Exclude the experimental `v8-poc` target because it pulls in expensive V8
# build machinery that is unrelated to the release-only Rust regression this
# workflow is meant to catch.
printf '%s\n' \
"//codex-rs/..." \
"-//codex-rs/v8-poc:all"

View file

@ -0,0 +1,195 @@
#!/usr/bin/env python3
import argparse
import asyncio
import datetime as dt
import json
import sys
from typing import Any
import websockets
HOST = "127.0.0.1"
DEFAULT_PORT = 8765
PATH = "/v1/responses"
CALL_ID = "shell-command-call"
FUNCTION_NAME = "shell_command"
FUNCTION_ARGS_JSON = json.dumps({"command": "echo websocket"}, separators=(",", ":"))
ASSISTANT_TEXT = "done"
def _utc_iso() -> str:
return dt.datetime.now(tz=dt.timezone.utc).isoformat(timespec="milliseconds")
def _default_usage() -> dict[str, Any]:
return {
"input_tokens": 0,
"input_tokens_details": None,
"output_tokens": 0,
"output_tokens_details": None,
"total_tokens": 0,
}
def _event_response_created(response_id: str) -> dict[str, Any]:
return {"type": "response.created", "response": {"id": response_id}}
def _event_response_done() -> dict[str, Any]:
return {"type": "response.done", "response": {"usage": _default_usage()}}
def _event_response_completed(response_id: str) -> dict[str, Any]:
return {"type": "response.completed", "response": {"id": response_id, "usage": _default_usage()}}
def _event_function_call(call_id: str, name: str, arguments_json: str) -> dict[str, Any]:
return {
"type": "response.output_item.done",
"item": {"type": "function_call", "call_id": call_id, "name": name, "arguments": arguments_json},
}
def _event_assistant_message(message_id: str, text: str) -> dict[str, Any]:
return {
"type": "response.output_item.done",
"item": {
"type": "message",
"role": "assistant",
"id": message_id,
"content": [{"type": "output_text", "text": text}],
},
}
def _dump_json(payload: Any) -> str:
return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
def _print_request(prefix: str, payload: Any) -> None:
pretty = json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True)
sys.stdout.write(f"{prefix} {_utc_iso()}\n{pretty}\n")
sys.stdout.flush()
async def _handle_connection(
websocket: Any,
*,
expected_path: str = PATH,
) -> None:
# websockets v15 exposes the request path here.
path = getattr(getattr(websocket, "request", None), "path", None)
if path is None:
# Older handler signatures could pass `path` separately; accept if unavailable.
path = "(unknown)"
sys.stdout.write(f"[conn] {_utc_iso()} connected path={path}\n")
sys.stdout.flush()
path_no_qs = path.split("?", 1)[0] if path != "(unknown)" else path
if path_no_qs != "(unknown)" and path_no_qs != expected_path:
sys.stdout.write(f"[conn] {_utc_iso()} rejecting unexpected path (expected {expected_path})\n")
sys.stdout.flush()
await websocket.close(code=1008, reason="unexpected websocket path")
return
async def recv_json(label: str) -> Any:
msg = await websocket.recv()
if isinstance(msg, bytes):
payload = json.loads(msg.decode("utf-8"))
else:
payload = json.loads(msg)
_print_request(f"[{label}] recv", payload)
return payload
async def send_event(ev: dict[str, Any]) -> None:
sys.stdout.write(f"[conn] {_utc_iso()} send {_dump_json(ev)}\n")
await websocket.send(_dump_json(ev))
# Request 1: provoke a function call (mirrors `codex-rs/core/tests/suite/agent_websocket.rs`).
await recv_json("req1")
await send_event(_event_response_created("resp-1"))
await send_event(_event_function_call(CALL_ID, FUNCTION_NAME, FUNCTION_ARGS_JSON))
await send_event(_event_response_done())
# Request 2: expect appended tool output; send final assistant message.
await recv_json("req2")
await send_event(_event_response_created("resp-2"))
await send_event(_event_assistant_message("msg-1", ASSISTANT_TEXT))
await send_event(_event_response_completed("resp-2"))
sys.stdout.write(f"[conn] {_utc_iso()} closing\n")
sys.stdout.flush()
await websocket.close()
async def _serve(port: int) -> int:
async def handler(ws: Any) -> None:
try:
await _handle_connection(ws, expected_path=PATH)
except websockets.exceptions.ConnectionClosedOK:
return
try:
server = await websockets.serve(handler, HOST, port)
except OSError as err:
sys.stderr.write(f"[server] failed to bind ws://{HOST}:{port}: {err}\n")
return 2
bound_port = server.sockets[0].getsockname()[1]
ws_uri = f"ws://{HOST}:{bound_port}"
sys.stdout.write("[server] mock Responses WebSocket server running\n")
sys.stdout.write(f"""Add this to your config.toml:
[model_providers.localapi_ws]
base_url = "{ws_uri}/v1"
name = "localapi_ws"
wire_api = "responses_websocket"
env_key = "OPENAI_API_KEY_STAGING"
[profiles.localapi_ws]
model = "gpt-5.2"
model_provider = "localapi_ws"
model_reasoning_effort = "medium"
start codex with `codex --profile localapi_ws`
""")
sys.stdout.flush()
try:
await asyncio.Future()
finally:
server.close()
await server.wait_closed()
return 0
def main() -> int:
parser = argparse.ArgumentParser(
description=(
"Mock a minimal Responses API WebSocket endpoint for the `test_codex` flow.\n"
f"Binds to {HOST}:{DEFAULT_PORT} by default and logs incoming JSON requests to stdout."
),
formatter_class=argparse.RawTextHelpFormatter,
)
parser.add_argument(
"--port",
type=int,
default=DEFAULT_PORT,
help=f"Bind port (default: {DEFAULT_PORT}; use 0 for random free port).",
)
args = parser.parse_args()
try:
return asyncio.run(_serve(args.port))
except KeyboardInterrupt:
return 0
if __name__ == "__main__":
raise SystemExit(main())

120
vendor/codex/scripts/readme_toc.py vendored Normal file
View file

@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""
Utility script to verify (and optionally fix) the Table of Contents in a
Markdown file. By default, it checks that the ToC between `<!-- Begin ToC -->`
and `<!-- End ToC -->` matches the headings in the file. With --fix, it
rewrites the file to update the ToC.
"""
import argparse
import sys
import re
import difflib
from pathlib import Path
from typing import List
# Markers for the Table of Contents section
BEGIN_TOC: str = "<!-- Begin ToC -->"
END_TOC: str = "<!-- End ToC -->"
def main() -> int:
parser = argparse.ArgumentParser(
description="Check and optionally fix the README.md Table of Contents."
)
parser.add_argument(
"file", nargs="?", default="README.md", help="Markdown file to process"
)
parser.add_argument(
"--fix", action="store_true", help="Rewrite file with updated ToC"
)
args = parser.parse_args()
path = Path(args.file)
return check_or_fix(path, args.fix)
def generate_toc_lines(content: str) -> List[str]:
"""
Generate markdown list lines for headings (## to ######) in content.
"""
lines = content.splitlines()
headings = []
in_code = False
for line in lines:
if line.strip().startswith("```"):
in_code = not in_code
continue
if in_code:
continue
m = re.match(r"^(#{2,6})\s+(.*)$", line)
if not m:
continue
level = len(m.group(1))
text = m.group(2).strip()
headings.append((level, text))
toc = []
for level, text in headings:
indent = " " * (level - 2)
slug = text.lower()
# normalize spaces and dashes
slug = slug.replace("\u00a0", " ")
slug = slug.replace("\u2011", "-").replace("\u2013", "-").replace("\u2014", "-")
# drop other punctuation
slug = re.sub(r"[^0-9a-z\s-]", "", slug)
slug = slug.strip().replace(" ", "-")
toc.append(f"{indent}- [{text}](#{slug})")
return toc
def check_or_fix(readme_path: Path, fix: bool) -> int:
if not readme_path.is_file():
print(f"Error: file not found: {readme_path}", file=sys.stderr)
return 1
content = readme_path.read_text(encoding="utf-8")
lines = content.splitlines()
# locate ToC markers
try:
begin_idx = next(i for i, l in enumerate(lines) if l.strip() == BEGIN_TOC)
end_idx = next(i for i, l in enumerate(lines) if l.strip() == END_TOC)
except StopIteration:
# No ToC markers found; treat as a no-op so repos without a ToC don't fail CI
print(
f"Note: Skipping ToC check; no markers found in {readme_path}.",
)
return 0
# extract current ToC list items
current_block = lines[begin_idx + 1 : end_idx]
current = [l for l in current_block if l.lstrip().startswith("- [")]
# generate expected ToC from content without current ToC
toc_content = lines[:begin_idx] + lines[end_idx+1:]
expected = generate_toc_lines("\n".join(toc_content))
if current == expected:
return 0
if not fix:
print(
"ERROR: README ToC is out of date. Diff between existing and generated ToC:"
)
# Show full unified diff of current vs expected
diff = difflib.unified_diff(
current,
expected,
fromfile="existing ToC",
tofile="generated ToC",
lineterm="",
)
for line in diff:
print(line)
return 1
# rebuild file with updated ToC
prefix = lines[: begin_idx + 1]
suffix = lines[end_idx+1:]
new_lines = prefix + [""] + expected + [""] + suffix
readme_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
print(f"Updated ToC in {readme_path}.")
return 0
if __name__ == "__main__":
sys.exit(main())

View file

@ -0,0 +1,61 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cargo_root="$repo_root/codex-rs"
listen_url="${CODEX_EXEC_SERVER_LISTEN_URL:-ws://127.0.0.1:0}"
start_timeout_seconds="${CODEX_EXEC_SERVER_START_TIMEOUT_SECONDS:-120}"
tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/codex-tui-with-exec-server.XXXXXX")"
stdout_log="$tmp_dir/exec-server.stdout"
stderr_log="$tmp_dir/exec-server.stderr"
server_pid=""
exec_server_url=""
cleanup() {
if [[ -n "$server_pid" ]]; then
kill "$server_pid" >/dev/null 2>&1 || true
wait "$server_pid" >/dev/null 2>&1 || true
fi
rm -rf "$tmp_dir"
}
trap cleanup EXIT INT TERM HUP
(
cd "$cargo_root"
cargo run -p codex-cli --bin codex -- exec-server --listen "$listen_url"
) >"$stdout_log" 2>"$stderr_log" &
server_pid="$!"
# Wait for the server to print its bound websocket URL before launching the TUI.
for _ in $(seq 1 "$((start_timeout_seconds * 20))"); do
if [[ -s "$stdout_log" ]]; then
exec_server_url="$(head -n 1 "$stdout_log" | tr -d '\r')"
if [[ "$exec_server_url" == ws://* ]]; then
break
fi
fi
if ! kill -0 "$server_pid" >/dev/null 2>&1; then
cat "$stderr_log" >&2 || true
cat "$stdout_log" >&2 || true
echo "failed to start codex exec-server" >&2
exit 1
fi
sleep 0.05
done
if [[ -z "$exec_server_url" ]]; then
cat "$stderr_log" >&2 || true
cat "$stdout_log" >&2 || true
echo "timed out waiting ${start_timeout_seconds}s for codex exec-server to report its websocket URL" >&2
exit 1
fi
export CODEX_EXEC_SERVER_URL="$exec_server_url"
echo "Starting codex-tui with CODEX_EXEC_SERVER_URL=$CODEX_EXEC_SERVER_URL" >&2
cd "$cargo_root"
cargo run -p codex-tui --bin codex-tui -- -c mcp_oauth_credentials_store=file "$@"

View file

@ -0,0 +1,206 @@
#!/usr/bin/env python3
"""Stage one or more Codex npm packages for release."""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
BUILD_SCRIPT = REPO_ROOT / "codex-cli" / "scripts" / "build_npm_package.py"
INSTALL_NATIVE_DEPS = REPO_ROOT / "codex-cli" / "scripts" / "install_native_deps.py"
WORKFLOW_NAME = ".github/workflows/rust-release.yml"
GITHUB_REPO = "openai/codex"
_SPEC = importlib.util.spec_from_file_location("codex_build_npm_package", BUILD_SCRIPT)
if _SPEC is None or _SPEC.loader is None:
raise RuntimeError(f"Unable to load module from {BUILD_SCRIPT}")
_BUILD_MODULE = importlib.util.module_from_spec(_SPEC)
_SPEC.loader.exec_module(_BUILD_MODULE)
PACKAGE_NATIVE_COMPONENTS = getattr(_BUILD_MODULE, "PACKAGE_NATIVE_COMPONENTS", {})
PACKAGE_EXPANSIONS = getattr(_BUILD_MODULE, "PACKAGE_EXPANSIONS", {})
CODEX_PLATFORM_PACKAGES = getattr(_BUILD_MODULE, "CODEX_PLATFORM_PACKAGES", {})
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--release-version",
required=True,
help="Version to stage (e.g. 0.1.0 or 0.1.0-alpha.1).",
)
parser.add_argument(
"--package",
dest="packages",
action="append",
required=True,
help="Package name to stage. May be provided multiple times.",
)
parser.add_argument(
"--workflow-url",
help="Optional workflow URL to reuse for native artifacts.",
)
parser.add_argument(
"--output-dir",
type=Path,
default=None,
help="Directory where npm tarballs should be written (default: dist/npm).",
)
parser.add_argument(
"--keep-staging-dirs",
action="store_true",
help="Retain temporary staging directories instead of deleting them.",
)
return parser.parse_args()
def collect_native_components(packages: list[str]) -> set[str]:
components: set[str] = set()
for package in packages:
components.update(PACKAGE_NATIVE_COMPONENTS.get(package, []))
return components
def expand_packages(packages: list[str]) -> list[str]:
expanded: list[str] = []
for package in packages:
for expanded_package in PACKAGE_EXPANSIONS.get(package, [package]):
if expanded_package in expanded:
continue
expanded.append(expanded_package)
return expanded
def resolve_release_workflow(version: str) -> dict:
stdout = subprocess.check_output(
[
"gh",
"run",
"list",
"--branch",
f"rust-v{version}",
"--json",
"workflowName,url,headSha",
"--workflow",
WORKFLOW_NAME,
"--jq",
"first(.[])",
],
cwd=REPO_ROOT,
text=True,
)
workflow = json.loads(stdout or "null")
if not workflow:
raise RuntimeError(f"Unable to find rust-release workflow for version {version}.")
return workflow
def resolve_workflow_url(version: str, override: str | None) -> tuple[str, str | None]:
if override:
return override, None
workflow = resolve_release_workflow(version)
return workflow["url"], workflow.get("headSha")
def install_native_components(
workflow_url: str,
components: set[str],
vendor_root: Path,
) -> None:
if not components:
return
cmd = [str(INSTALL_NATIVE_DEPS), "--workflow-url", workflow_url]
for component in sorted(components):
cmd.extend(["--component", component])
cmd.append(str(vendor_root))
run_command(cmd)
def run_command(cmd: list[str]) -> None:
print("+", " ".join(cmd))
subprocess.run(cmd, cwd=REPO_ROOT, check=True)
def tarball_name_for_package(package: str, version: str) -> str:
if package in CODEX_PLATFORM_PACKAGES:
platform = package.removeprefix("codex-")
return f"codex-npm-{platform}-{version}.tgz"
return f"{package}-npm-{version}.tgz"
def main() -> int:
args = parse_args()
output_dir = args.output_dir or (REPO_ROOT / "dist" / "npm")
output_dir.mkdir(parents=True, exist_ok=True)
runner_temp = Path(os.environ.get("RUNNER_TEMP", tempfile.gettempdir()))
packages = expand_packages(list(args.packages))
native_components = collect_native_components(packages)
vendor_temp_root: Path | None = None
vendor_src: Path | None = None
resolved_head_sha: str | None = None
final_messages = []
try:
if native_components:
workflow_url, resolved_head_sha = resolve_workflow_url(
args.release_version, args.workflow_url
)
vendor_temp_root = Path(tempfile.mkdtemp(prefix="npm-native-", dir=runner_temp))
install_native_components(workflow_url, native_components, vendor_temp_root)
vendor_src = vendor_temp_root / "vendor"
if resolved_head_sha:
print(f"should `git checkout {resolved_head_sha}`")
for package in packages:
staging_dir = Path(tempfile.mkdtemp(prefix=f"npm-stage-{package}-", dir=runner_temp))
pack_output = output_dir / tarball_name_for_package(package, args.release_version)
cmd = [
str(BUILD_SCRIPT),
"--package",
package,
"--release-version",
args.release_version,
"--staging-dir",
str(staging_dir),
"--pack-output",
str(pack_output),
]
if vendor_src is not None:
cmd.extend(["--vendor-src", str(vendor_src)])
try:
run_command(cmd)
finally:
if not args.keep_staging_dirs:
shutil.rmtree(staging_dir, ignore_errors=True)
final_messages.append(f"Staged {package} at {pack_output}")
finally:
if vendor_temp_root is not None and not args.keep_staging_dirs:
shutil.rmtree(vendor_temp_root, ignore_errors=True)
for msg in final_messages:
print(msg)
return 0
if __name__ == "__main__":
raise SystemExit(main())

185
vendor/codex/scripts/start-codex-exec.sh vendored Normal file
View file

@ -0,0 +1,185 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 HOST [RSYNC_OPTION]..." >&2
}
if [[ $# -lt 1 ]]; then
usage
exit 2
fi
case "$1" in
-h|--help)
usage
exit 0
;;
esac
remote_host="$1"
shift
remote_path='~/code/codex-sync'
local_exec_server_port="${CODEX_REMOTE_EXEC_SERVER_LOCAL_PORT:-8765}"
remote_exec_server_start_timeout_seconds="${CODEX_REMOTE_EXEC_SERVER_START_TIMEOUT_SECONDS:-15}"
remote_exec_server_pid=''
remote_exec_server_log_path=''
remote_exec_server_pid_path=''
remote_repo_root=''
cleanup() {
local exit_code=$?
trap - EXIT INT TERM
if [[ -n "${remote_exec_server_pid_path}" ]]; then
ssh "${remote_host}" \
"if [[ -f '${remote_exec_server_pid_path}' ]]; then kill \$(cat '${remote_exec_server_pid_path}') >/dev/null 2>&1 || true; fi; rm -f '${remote_exec_server_pid_path}' '${remote_exec_server_log_path}'" \
>/dev/null 2>&1 || true
fi
exit "${exit_code}"
}
trap cleanup EXIT INT TERM
if ! command -v git >/dev/null 2>&1; then
echo "git is required" >&2
exit 1
fi
if ! command -v ssh >/dev/null 2>&1; then
echo "ssh is required" >&2
exit 1
fi
if ! command -v rsync >/dev/null 2>&1; then
echo "local rsync is required" >&2
exit 1
fi
repo_root="$(git rev-parse --show-toplevel 2>/dev/null)" || {
echo "run this script from inside a git repository" >&2
exit 1
}
ssh "${remote_host}" "mkdir -p ${remote_path}"
ssh "${remote_host}" -C "sudo apt-get install rsync libcap-dev"
sync_instance_id="$(date +%s)-$$"
rsync \
--archive \
--compress \
--human-readable \
--itemize-changes \
--exclude '.git/' \
--exclude 'codex-rs/target/' \
--filter=':- .gitignore' \
"$@" \
"${repo_root}/" \
"${remote_host}:${remote_path}/" \
>&2
remote_exec_server_log_path="/tmp/codex-exec-server-${sync_instance_id}.log"
remote_exec_server_pid_path="/tmp/codex-exec-server-${sync_instance_id}.pid"
remote_start_output="$(
ssh "${remote_host}" bash -s -- \
"${remote_exec_server_log_path}" \
"${remote_exec_server_pid_path}" \
"${remote_exec_server_start_timeout_seconds}" <<'EOF'
set -euo pipefail
remote_exec_server_log_path="$1"
remote_exec_server_pid_path="$2"
remote_exec_server_start_timeout_seconds="$3"
remote_repo_root="$HOME/code/codex-sync"
remote_codex_rs="$remote_repo_root/codex-rs"
cd "${remote_codex_rs}"
cargo build -p codex-cli --bin codex
rm -f "${remote_exec_server_log_path}" "${remote_exec_server_pid_path}"
nohup ./target/debug/codex exec-server --listen ws://127.0.0.1:0 \
>"${remote_exec_server_log_path}" 2>&1 &
remote_exec_server_pid="$!"
echo "${remote_exec_server_pid}" >"${remote_exec_server_pid_path}"
deadline=$((SECONDS + remote_exec_server_start_timeout_seconds))
while (( SECONDS < deadline )); do
if [[ -s "${remote_exec_server_log_path}" ]]; then
listen_url="$(head -n 1 "${remote_exec_server_log_path}" || true)"
if [[ "${listen_url}" == ws://* ]]; then
printf 'remote_exec_server_pid=%s\n' "${remote_exec_server_pid}"
printf 'remote_exec_server_log_path=%s\n' "${remote_exec_server_log_path}"
printf 'remote_repo_root=%s\n' "${remote_repo_root}"
printf 'listen_url=%s\n' "${listen_url}"
exit 0
fi
fi
if ! kill -0 "${remote_exec_server_pid}" >/dev/null 2>&1; then
cat "${remote_exec_server_log_path}" >&2 || true
echo "remote exec server exited before reporting a listen URL" >&2
exit 1
fi
sleep 0.1
done
cat "${remote_exec_server_log_path}" >&2 || true
echo "timed out waiting for remote exec server listen URL" >&2
exit 1
EOF
)"
listen_url=''
while IFS='=' read -r key value; do
case "${key}" in
remote_exec_server_pid)
remote_exec_server_pid="${value}"
;;
remote_exec_server_log_path)
remote_exec_server_log_path="${value}"
;;
remote_repo_root)
remote_repo_root="${value}"
;;
listen_url)
listen_url="${value}"
;;
esac
done <<< "${remote_start_output}"
if [[ -z "${remote_exec_server_pid}" || -z "${listen_url}" || -z "${remote_repo_root}" ]]; then
echo "failed to parse remote exec server startup output" >&2
exit 1
fi
remote_exec_server_port="${listen_url##*:}"
if [[ -z "${remote_exec_server_port}" || "${remote_exec_server_port}" == "${listen_url}" ]]; then
echo "failed to parse remote exec server port from ${listen_url}" >&2
exit 1
fi
echo "Remote exec server: ${listen_url}"
echo "Remote exec server log: ${remote_exec_server_log_path}"
echo "Press Ctrl-C to stop the SSH tunnel and remote exec server."
echo "Start codex via: "
printf ' CODEX_EXEC_SERVER_URL=ws://127.0.0.1:%s codex -C %q\n' \
"${local_exec_server_port}" \
"${remote_repo_root}"
ssh \
-nNT \
-o ControlMaster=no \
-o ControlPath=none \
-o ExitOnForwardFailure=yes \
-o ServerAliveInterval=30 \
-o ServerAliveCountMax=3 \
-L "${local_exec_server_port}:127.0.0.1:${remote_exec_server_port}" \
"${remote_host}"

137
vendor/codex/scripts/test-remote-env.sh vendored Normal file
View file

@ -0,0 +1,137 @@
#!/usr/bin/env bash
# Remote-env setup script for codex-rs integration tests.
#
# Usage (source-only):
# source scripts/test-remote-env.sh
# cd codex-rs
# cargo test -p codex-core --test all remote_env_connects_creates_temp_dir_and_runs_sample_script
# codex_remote_env_cleanup
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
is_sourced() {
[[ "${BASH_SOURCE[0]}" != "$0" ]]
}
setup_remote_env() {
local container_name
local codex_binary_path
local container_ip
local remote_codex_path
local remote_exec_server_pid
local remote_exec_server_port
local remote_exec_server_stdout_path
container_name="${CODEX_TEST_REMOTE_ENV_CONTAINER_NAME:-codex-remote-test-env-local-$(date +%s)-${RANDOM}}"
codex_binary_path="${REPO_ROOT}/codex-rs/target/debug/codex"
if ! command -v docker >/dev/null 2>&1; then
echo "docker is required (Colima or Docker Desktop)" >&2
return 1
fi
if ! docker info >/dev/null 2>&1; then
echo "docker daemon is not reachable; for Colima run: colima start" >&2
return 1
fi
if ! command -v cargo >/dev/null 2>&1; then
echo "cargo is required to build codex" >&2
return 1
fi
(
cd "${REPO_ROOT}/codex-rs"
cargo build -p codex-cli --bin codex
)
if [[ ! -f "${codex_binary_path}" ]]; then
echo "codex binary not found at ${codex_binary_path}" >&2
return 1
fi
docker rm -f "${container_name}" >/dev/null 2>&1 || true
# bubblewrap needs mount propagation inside the remote test container.
docker run -d \
--name "${container_name}" \
--privileged \
--security-opt seccomp=unconfined \
ubuntu:24.04 sleep infinity >/dev/null
if ! docker exec "${container_name}" sh -lc "apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y python3 zsh"; then
docker rm -f "${container_name}" >/dev/null 2>&1 || true
return 1
fi
if [[ -z "${CODEX_TEST_REMOTE_EXEC_SERVER_URL:-}" ]]; then
remote_codex_path="/tmp/codex-remote-env/codex"
remote_exec_server_port="31987"
remote_exec_server_stdout_path="/tmp/codex-remote-env/exec-server.stdout"
docker exec "${container_name}" sh -lc "mkdir -p /tmp/codex-remote-env"
docker cp "${codex_binary_path}" "${container_name}:${remote_codex_path}"
docker exec "${container_name}" chmod +x "${remote_codex_path}"
remote_exec_server_pid="$(
docker exec "${container_name}" sh -lc \
"rm -f ${remote_exec_server_stdout_path}; nohup ${remote_codex_path} exec-server --listen ws://0.0.0.0:${remote_exec_server_port} > ${remote_exec_server_stdout_path} 2>&1 & echo \$!"
)"
wait_for_remote_exec_server_port "${container_name}" "${remote_exec_server_port}" "${remote_exec_server_stdout_path}"
container_ip="$(
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "${container_name}"
)"
if [[ -z "${container_ip}" ]]; then
echo "container ${container_name} has no IP address" >&2
docker rm -f "${container_name}" >/dev/null 2>&1 || true
return 1
fi
export CODEX_TEST_REMOTE_EXEC_SERVER_PID="${remote_exec_server_pid}"
export CODEX_TEST_REMOTE_EXEC_SERVER_URL="ws://${container_ip}:${remote_exec_server_port}"
fi
export CODEX_TEST_REMOTE_ENV="${container_name}"
}
wait_for_remote_exec_server_port() {
local container_name="$1"
local port="$2"
local stdout_path="$3"
local deadline=$((SECONDS + 5))
while (( SECONDS < deadline )); do
if docker exec "${container_name}" python3 -c "import socket; socket.create_connection(('127.0.0.1', ${port}), timeout=0.2).close()" >/dev/null 2>&1; then
return 0
fi
sleep 0.025
done
echo "timed out waiting for remote exec-server on ${container_name}:${port}" >&2
docker exec "${container_name}" sh -lc "cat ${stdout_path} 2>/dev/null || true" >&2 || true
return 1
}
codex_remote_env_cleanup() {
if [[ -n "${CODEX_TEST_REMOTE_ENV:-}" ]]; then
docker rm -f "${CODEX_TEST_REMOTE_ENV}" >/dev/null 2>&1 || true
unset CODEX_TEST_REMOTE_ENV
fi
unset CODEX_TEST_REMOTE_EXEC_SERVER_PID
unset CODEX_TEST_REMOTE_EXEC_SERVER_URL
}
if ! is_sourced; then
echo "source this script instead of executing it: source scripts/test-remote-env.sh" >&2
exit 1
fi
old_shell_options="$(set +o)"
set -euo pipefail
if setup_remote_env; then
status=0
echo "CODEX_TEST_REMOTE_ENV=${CODEX_TEST_REMOTE_ENV}"
echo "CODEX_TEST_REMOTE_EXEC_SERVER_URL=${CODEX_TEST_REMOTE_EXEC_SERVER_URL}"
echo "Remote env ready. Run your command, then call: codex_remote_env_cleanup"
else
status=$?
fi
eval "${old_shell_options}"
return "${status}"