Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

127
scripts/asciicheck.py Executable 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())

16
scripts/build_codex_package.py Executable file
View File

@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Build a canonical Codex package directory and optional archive."""
from pathlib import Path
import sys
# Some developer environments set PYTHONSAFEPATH=1, which prevents Python from
# adding the script directory to sys.path. Add it explicitly so the local helper
# package remains importable when this executable is launched from any cwd.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from codex_package.cli import main
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,37 @@
"""Adapt an extracted signed Windows package to WinGet's existing root filenames."""
import argparse
import json
import shutil
from pathlib import Path
def prepare_winget_package(package: Path) -> None:
metadata_path = package / "codex-package.json"
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
target = metadata["target"]
if target not in ("x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"):
raise ValueError("WinGet requires a Windows package")
if metadata["entrypoint"] != "bin/codex.exe":
raise ValueError("WinGet requires the canonical Codex entrypoint")
entrypoint = f"codex-{target}.exe"
manifest_path = package / "codex-resources/voice/manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
manifest["sha256"][entrypoint] = manifest["sha256"].pop("bin/codex.exe")
(package / "bin/codex.exe").rename(package / entrypoint)
(package / "bin/codex-code-mode-host.exe").rename(
package / "codex-code-mode-host.exe"
)
# Keep resources in place for package-aware discovery and provide the root
# filenames declared by the existing WinGet portable installer manifest.
for helper in ("codex-command-runner.exe", "codex-windows-sandbox-setup.exe"):
shutil.copy2(package / "codex-resources" / helper, package / helper)
metadata["entrypoint"] = entrypoint
for path, value in ((metadata_path, metadata), (manifest_path, manifest)):
path.write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("package", type=Path)
prepare_winget_package(parser.parse_args().package)

View File

@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if ! "${repo_root}/.github/scripts/run_bazel_with_buildbuddy.py" mod deps --lockfile_mode=error; then
echo "Unable to verify MODULE.bazel.lock; see the Bazel error above."
echo "If Bazel reports an out-of-date lockfile, run 'just bazel-lock-update' and commit the updated lockfile."
exit 1
fi

201
scripts/check_blob_size.py Executable file
View File

@@ -0,0 +1,201 @@
#!/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())

View File

@@ -0,0 +1,106 @@
# Codex package builder
This package contains the implementation behind `scripts/build_codex_package.py`.
The top-level script is the stable executable entry point; these modules keep the
package-building logic split by responsibility.
Run the builder through `just`:
```bash
just assemble-codex-package --help
just assemble-codex-package --variant codex-app-server
just assemble-codex-package --target x86_64-unknown-linux-gnu
```
The builder creates a canonical Codex package directory:
```text
.
├── codex-package.json
├── bin
│ ├── <entrypoint>[.exe]
│ ├── codex-code-mode-host[.exe]
│ └── codex-exec-server[.exe]
├── codex-resources
│ ├── bwrap # Linux only
│ ├── codex-command-runner.exe # Windows only
│ └── codex-windows-sandbox-setup.exe # Windows only
└── codex-path
└── rg[.exe]
```
The package directory is the primary artifact. Archive formats such as
`.tar.gz`, `.tar.zst`, and `.zip` are serializations of that directory.
The `execServer` field in `codex-package.json` advertises the packaged executor.
Installers use its presence to repair a missing executor while accepting older
packages that predate the standalone binary.
If `--target` is omitted, the builder uses the release target for the current
host platform. On Linux, that default is a musl target to match Codex release
artifacts; pass a GNU Linux target explicitly for native glibc local builds. If
`--package-dir` is omitted, the builder creates a new temporary directory and
prints its path after the package is built.
The `--variant` flag selects the package entrypoint. Supported variants are
`codex` and `codex-app-server`. The `--package-version` flag sets the version in
`codex-package.json`; it defaults to `[workspace.package].version` in
`codex-rs/Cargo.toml`.
## Source-built artifacts
Artifacts built from this repository are built by the package builder in one
grouped `cargo build` command per package when they are needed and no prebuilt
override was provided:
- all targets: the selected entrypoint, unless `--entrypoint-bin` is provided
- all targets: `codex-code-mode-host`, unless `--code-mode-host-bin` is provided
- all targets: `codex-exec-server`, unless `--exec-server-bin` is provided
- Linux targets: `bwrap`, unless `--bwrap-bin` is provided
- Windows targets: `codex-command-runner` and `codex-windows-sandbox-setup`,
unless the corresponding prebuilt helper flags are provided
The default cargo profile is `dev-small` because local iteration should favor
fast, small builds. Release jobs should pass `--cargo-profile release` and an
explicit target. Release jobs that already built and signed/notarized the
entrypoint should pass `--entrypoint-bin` so the package contains that exact
binary instead of rebuilding it.
Release jobs should likewise pass `--code-mode-host-bin` and `--exec-server-bin`
so the package preserves the signed host and executor beside the entrypoint.
On Linux and macOS, the builder strips symbols from the **package copies** of
source-built release-profile entrypoint, code-mode host, and executor binaries. Cargo outputs
retain their symbols for debugging. The default `--strip auto` also preserves
development/profiling builds and prebuilt inputs
byte-for-byte, including signatures. Use `--strip all` to also strip prebuilt
first-party executable copies, or `--strip none` to keep symbols in every package copy.
Strip before production signing; `--strip all` is not appropriate for inputs
whose release signatures must be preserved. Windows MSVC symbols are separate
PDB files and are not included in the package.
macOS uses `xcrun strip -S -x`, matching the release pipeline and preserving
executable ad-hoc signatures. Linux uses `llvm-strip`, a target-prefixed GNU
strip, or native GNU strip when the host architecture matches. For cross builds,
install `llvm-strip` or pass `--strip-tool /path/to/target-strip`. Missing tools
or strip failures fail the build; use `--strip none` to deliberately opt out.
Third-party resources are copied unchanged. In particular, never strip `bwrap`
after its integrity digest has been embedded in Codex.
Release jobs that already built package resource binaries should also pass the
corresponding resource flags: `--bwrap-bin` for Linux packages, and
`--codex-command-runner-bin` plus `--codex-windows-sandbox-setup-bin` for
Windows packages. This keeps package archive creation as a pure staging step
after signing instead of rebuilding resources.
When the builder source-builds an entrypoint for a Darwin or Linux target, it
downloads and verifies the matching Codex-built V8 release pair before invoking
Cargo and sets `RUSTY_V8_ARCHIVE` plus `RUSTY_V8_SRC_BINDING_PATH` for that
build. Windows targets keep Cargo's release-build MSVC artifact path. Explicit
overrides remain authoritative when both variables are already set. Set
`V8_FROM_SOURCE=1` to leave the build with the `v8` crate source-build path.
`rg` is not built from this repository, so the builder fetches it from the
DotSlash manifest at `scripts/codex_package/rg`. Downloaded archives are cached
under `$TMPDIR/codex-package/<target>-rg` and are reused only after the recorded
size and SHA-256 digest have been verified. Pass `--rg-bin` to use a local
ripgrep executable instead.

View File

@@ -0,0 +1 @@
"""Helpers for building canonical Codex package archives."""

View File

@@ -0,0 +1,118 @@
"""Archive writers for canonical Codex package directories."""
import shutil
import subprocess
import tarfile
import tempfile
import zipfile
from collections.abc import Callable
from pathlib import Path
from .targets import REPO_ROOT
ZSTD_DOTSLASH = REPO_ROOT / ".github" / "workflows" / "zstd"
def write_archive(package_dir: Path, archive_path: Path, *, force: bool) -> None:
if is_relative_to(archive_path, package_dir):
raise RuntimeError(
f"Archive output must be outside the package directory: {archive_path}"
)
archive_path.parent.mkdir(parents=True, exist_ok=True)
if archive_path.exists():
if not force:
raise RuntimeError(f"Archive output already exists: {archive_path}")
archive_path.unlink()
archive_format = archive_format_for_path(archive_path)
if archive_format == "tar.gz":
write_tar_archive(package_dir, archive_path, mode="w:gz")
elif archive_format == "tar.zst":
write_tar_zst_archive(package_dir, archive_path)
elif archive_format == "zip":
write_zip_archive(package_dir, archive_path)
else:
raise AssertionError(f"unexpected archive format: {archive_format}")
def is_relative_to(path: Path, parent: Path) -> bool:
try:
path.relative_to(parent)
return True
except ValueError:
return False
def archive_format_for_path(path: Path) -> str:
suffixes = path.suffixes
if suffixes[-2:] == [".tar", ".gz"] or path.suffix == ".tgz":
return "tar.gz"
if suffixes[-2:] == [".tar", ".zst"]:
return "tar.zst"
if path.suffix == ".zip":
return "zip"
raise RuntimeError(
f"Unsupported archive suffix for {path}. Use .tar.gz, .tgz, .tar.zst, or .zip."
)
def write_tar_archive(package_dir: Path, archive_path: Path, *, mode: str) -> None:
options = {"compresslevel": 6} if mode == "w:gz" else {}
with tarfile.open(archive_path, mode, **options) as archive:
for path in package_entries(package_dir):
archive.add(
path,
arcname=path.relative_to(package_dir),
recursive=False,
)
def write_tar_zst_archive(package_dir: Path, archive_path: Path) -> None:
zstd_command = resolve_zstd_command()
with tempfile.TemporaryDirectory(prefix="codex-package-archive-") as temp_dir_str:
tar_path = Path(temp_dir_str) / "package.tar"
write_tar_archive(package_dir, tar_path, mode="w")
subprocess.check_call(
[*zstd_command, "-T0", "-19", "-f", str(tar_path), "-o", str(archive_path)]
)
def resolve_zstd_command(
*,
dotslash_manifest: Path = ZSTD_DOTSLASH,
which: Callable[[str], str | None] = shutil.which,
) -> list[str]:
zstd = which("zstd")
if zstd is not None:
return [zstd]
dotslash = which("dotslash")
if dotslash is not None and dotslash_manifest.is_file():
return [dotslash, str(dotslash_manifest)]
raise RuntimeError(
"zstd is required to write .tar.zst archives. Install zstd, or install "
f"DotSlash so the repository wrapper can run: {dotslash_manifest}"
)
def write_zip_archive(package_dir: Path, archive_path: Path) -> None:
with zipfile.ZipFile(
archive_path, "w", compression=zipfile.ZIP_DEFLATED
) as archive:
for path in package_entries(package_dir):
relative_path = path.relative_to(package_dir)
if path.is_dir():
archive.write(path, f"{relative_path}/")
else:
archive.write(path, relative_path)
def package_entries(package_dir: Path) -> list[Path]:
return sorted(
package_dir.rglob("*"),
key=lambda path: path.relative_to(package_dir).as_posix(),
)

View File

@@ -0,0 +1,210 @@
"""Cargo builds for source-built Codex package artifacts."""
import os
import subprocess
from dataclasses import dataclass
from pathlib import Path
from .targets import REPO_ROOT
from .targets import PackageVariant
from .targets import TargetSpec
from .v8 import resolve_codex_v8_cargo_env
CODEX_RS_ROOT = REPO_ROOT / "codex-rs"
@dataclass(frozen=True)
class SourceBuildOutputs:
entrypoint_bin: Path
code_mode_host_bin: Path
exec_server_bin: Path
bwrap_bin: Path | None
codex_command_runner_bin: Path | None
codex_windows_sandbox_setup_bin: Path | None
def build_source_binaries(
spec: TargetSpec,
variant: PackageVariant,
*,
cargo: str,
profile: str,
entrypoint_bin: Path | None,
code_mode_host_bin: Path | None,
exec_server_bin: Path | None,
bwrap_bin: Path | None,
codex_command_runner_bin: Path | None,
codex_windows_sandbox_setup_bin: Path | None,
) -> SourceBuildOutputs:
validate_prebuilt_resource_inputs(
spec,
bwrap_bin=bwrap_bin,
codex_command_runner_bin=codex_command_runner_bin,
codex_windows_sandbox_setup_bin=codex_windows_sandbox_setup_bin,
)
binaries = source_binaries_for_target(
spec,
variant,
build_entrypoint=entrypoint_bin is None,
build_code_mode_host=code_mode_host_bin is None,
build_exec_server=exec_server_bin is None,
build_bwrap=spec.is_linux and bwrap_bin is None,
build_codex_command_runner=spec.is_windows and codex_command_runner_bin is None,
build_codex_windows_sandbox_setup=spec.is_windows
and codex_windows_sandbox_setup_bin is None,
)
if binaries:
cmd = [
cargo,
"build",
"--target",
spec.target,
"--profile",
profile,
]
for binary in binaries:
cmd.extend(["--bin", binary])
cargo_env = None
if (
entrypoint_bin is None
or code_mode_host_bin is None
or exec_server_bin is None
):
codex_v8_env = resolve_codex_v8_cargo_env(spec)
if codex_v8_env:
cargo_env = {**os.environ, **codex_v8_env}
print("+", " ".join(cmd))
subprocess.run(
cmd,
cwd=CODEX_RS_ROOT,
check=True,
env=cargo_env,
)
output_dir = cargo_profile_output_dir(spec, profile)
outputs = SourceBuildOutputs(
entrypoint_bin=resolve_output_path(
entrypoint_bin,
output_dir / variant.entrypoint_name(spec),
),
code_mode_host_bin=(
code_mode_host_bin.resolve()
if code_mode_host_bin is not None
else output_dir / f"codex-code-mode-host{spec.exe_suffix}"
),
exec_server_bin=(
exec_server_bin.resolve()
if exec_server_bin is not None
else output_dir / f"codex-exec-server{spec.exe_suffix}"
),
bwrap_bin=resolve_output_path(
bwrap_bin,
output_dir / "bwrap" if spec.is_linux else None,
),
codex_command_runner_bin=resolve_output_path(
codex_command_runner_bin,
output_dir / "codex-command-runner.exe" if spec.is_windows else None,
),
codex_windows_sandbox_setup_bin=resolve_output_path(
codex_windows_sandbox_setup_bin,
output_dir / "codex-windows-sandbox-setup.exe" if spec.is_windows else None,
),
)
validate_source_outputs(outputs)
return outputs
def source_binaries_for_target(
spec: TargetSpec,
variant: PackageVariant,
*,
build_entrypoint: bool,
build_code_mode_host: bool,
build_exec_server: bool,
build_bwrap: bool,
build_codex_command_runner: bool,
build_codex_windows_sandbox_setup: bool,
) -> list[str]:
binaries = []
if build_entrypoint:
binaries.append(variant.cargo_bin)
if build_code_mode_host:
binaries.append("codex-code-mode-host")
if build_exec_server:
binaries.append("codex-exec-server")
if build_bwrap:
binaries.append("bwrap")
if build_codex_command_runner:
binaries.append("codex-command-runner")
if build_codex_windows_sandbox_setup:
binaries.append("codex-windows-sandbox-setup")
return binaries
def validate_prebuilt_resource_inputs(
spec: TargetSpec,
*,
bwrap_bin: Path | None,
codex_command_runner_bin: Path | None,
codex_windows_sandbox_setup_bin: Path | None,
) -> None:
if bwrap_bin is not None and not spec.is_linux:
raise RuntimeError("--bwrap-bin is only supported for Linux targets.")
if codex_command_runner_bin is not None and not spec.is_windows:
raise RuntimeError(
"--codex-command-runner-bin is only supported for Windows targets."
)
if codex_windows_sandbox_setup_bin is not None and not spec.is_windows:
raise RuntimeError(
"--codex-windows-sandbox-setup-bin is only supported for Windows targets."
)
def resolve_output_path(
explicit_path: Path | None, default_path: Path | None
) -> Path | None:
if explicit_path is not None:
return explicit_path.resolve()
return default_path
def cargo_profile_output_dir(spec: TargetSpec, profile: str) -> Path:
target_dir = cargo_target_dir()
return target_dir / spec.target / cargo_profile_dirname(profile)
def cargo_target_dir() -> Path:
target_dir = os.environ.get("CARGO_TARGET_DIR")
if target_dir is None:
return CODEX_RS_ROOT / "target"
path = Path(target_dir)
if path.is_absolute():
return path
return CODEX_RS_ROOT / path
def cargo_profile_dirname(profile: str) -> str:
if profile == "dev":
return "debug"
if profile == "release":
return "release"
return profile
def validate_source_outputs(outputs: SourceBuildOutputs) -> None:
for path in [
outputs.entrypoint_bin,
outputs.code_mode_host_bin,
outputs.exec_server_bin,
outputs.bwrap_bin,
outputs.codex_command_runner_bin,
outputs.codex_windows_sandbox_setup_bin,
]:
if path is not None and not path.is_file():
raise RuntimeError(f"cargo build did not produce expected binary: {path}")

View File

@@ -0,0 +1,282 @@
"""Command-line interface for building Codex package directories."""
import argparse
import re
import tempfile
from pathlib import Path
from .archive import write_archive
from .cargo import build_source_binaries
from .layout import build_package_dir
from .layout import prepare_package_dir
from .layout import validate_package_dir
from .ripgrep import resolve_rg_bin
from .symbols import strip_binary
from .targets import PACKAGE_VARIANTS
from .targets import TARGET_SPECS
from .targets import PackageInputs
from .targets import default_target
from .targets import resolve_input_path
from .version import read_workspace_version
# Release pipelines run this builder with system Python, so avoid new dependencies.
SEMVER_PATTERN = re.compile(
r"(?P<major>0|[1-9][0-9]*)\."
r"(?P<minor>0|[1-9][0-9]*)\."
r"(?P<patch>0|[1-9][0-9]*)"
r"(?:-(?P<prerelease>[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?"
r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
)
def parse_package_version(value: str) -> str:
match = SEMVER_PATTERN.fullmatch(value)
if match is not None:
components = (match.group(name) for name in ("major", "minor", "patch"))
prerelease = match.group("prerelease") or ""
if all(int(component) <= 2**64 - 1 for component in components) and all(
not (part.isdigit() and len(part) > 1 and part.startswith("0"))
for part in prerelease.split(".")
):
return value
raise argparse.ArgumentTypeError(f"invalid semantic version: {value!r}")
def parse_args() -> argparse.Namespace:
return create_parser().parse_args()
def create_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Build a canonical Codex package directory and optional archive.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--target",
default=argparse.SUPPRESS,
choices=sorted(TARGET_SPECS),
help=(
"Rust target triple for the package. Defaults to the release target "
"for this host platform."
),
)
parser.add_argument(
"--variant",
choices=sorted(PACKAGE_VARIANTS),
default="codex",
help="Package variant to build.",
)
parser.add_argument(
"--package-version",
type=parse_package_version,
default=read_workspace_version(),
help="Semantic version to record in codex-package.json.",
)
parser.add_argument(
"--package-dir",
type=Path,
default=argparse.SUPPRESS,
help=(
"Output directory to create as the package root. Defaults to a new temporary directory."
),
)
parser.add_argument(
"--archive-output",
type=Path,
action="append",
default=[],
help=(
"Optional archive output path. May be repeated. Supported suffixes: "
".tar.gz, .tgz, .tar.zst, .zip."
),
)
parser.add_argument(
"--force",
action="store_true",
help="Replace an existing package directory or archive output.",
)
parser.add_argument(
"--cargo",
default="cargo",
help="Cargo executable to use for source-built package artifacts.",
)
parser.add_argument(
"--cargo-profile",
default="dev-small",
help=(
"Cargo profile for source-built package artifacts. Use release for release packages."
),
)
parser.add_argument(
"--strip",
choices=("auto", "all", "none"),
default="auto",
help=(
"Strip Unix first-party package binaries: auto strips source-built "
"release-profile inputs, all also strips other profiles and prebuilt "
"inputs, none preserves symbols. "
"Original inputs and third-party resources are never modified."
),
)
parser.add_argument(
"--strip-tool",
help="Target-compatible strip executable override, for example llvm-strip.",
)
parser.add_argument(
"--entrypoint-bin",
type=Path,
help=(
"Optional prebuilt entrypoint executable for the selected package "
"variant. If omitted, the entrypoint is built with Cargo."
),
)
parser.add_argument(
"--code-mode-host-bin",
type=Path,
help=(
"Optional prebuilt codex-code-mode-host executable. If omitted, "
"the host is built with Cargo."
),
)
parser.add_argument(
"--exec-server-bin",
type=Path,
help="Optional prebuilt codex-exec-server executable. If omitted, build it with Cargo.",
)
parser.add_argument(
"--bwrap-bin",
type=Path,
help=(
"Optional prebuilt Linux bwrap executable. If omitted for Linux "
"targets, bwrap is built with Cargo."
),
)
parser.add_argument(
"--codex-command-runner-bin",
type=Path,
help=(
"Optional prebuilt Windows codex-command-runner.exe executable. "
"If omitted for Windows targets, codex-command-runner is built "
"with Cargo."
),
)
parser.add_argument(
"--codex-windows-sandbox-setup-bin",
type=Path,
help=(
"Optional prebuilt Windows codex-windows-sandbox-setup.exe "
"executable. If omitted for Windows targets, "
"codex-windows-sandbox-setup is built with Cargo."
),
)
parser.add_argument(
"--rg-bin",
type=Path,
help=(
"Optional local ripgrep executable override instead of fetching from "
"scripts/codex_package/rg."
),
)
return parser
def main() -> int:
args = parse_args()
package_dir = assemble_package(args)
archive_package(package_dir, args)
return 0
def assemble_package(args: argparse.Namespace) -> Path:
"""Build the directory before optional downstream additions and archiving."""
spec = TARGET_SPECS[getattr(args, "target", None) or default_target()]
variant = PACKAGE_VARIANTS[args.variant]
package_dir_arg = getattr(args, "package_dir", None)
package_dir = (
package_dir_arg.resolve()
if package_dir_arg is not None
else Path(tempfile.mkdtemp(prefix="codex-package-")).resolve()
)
source_outputs = build_source_binaries(
spec,
variant,
cargo=args.cargo,
profile=args.cargo_profile,
entrypoint_bin=resolve_optional_input_path(
args.entrypoint_bin,
"prebuilt entrypoint executable",
"--entrypoint-bin",
),
code_mode_host_bin=resolve_optional_input_path(
args.code_mode_host_bin,
"prebuilt code-mode host executable",
"--code-mode-host-bin",
),
exec_server_bin=resolve_optional_input_path(
args.exec_server_bin,
"prebuilt executor executable",
"--exec-server-bin",
),
bwrap_bin=resolve_optional_input_path(
args.bwrap_bin,
"prebuilt Linux bwrap executable",
"--bwrap-bin",
),
codex_command_runner_bin=resolve_optional_input_path(
args.codex_command_runner_bin,
"prebuilt Windows codex-command-runner.exe executable",
"--codex-command-runner-bin",
),
codex_windows_sandbox_setup_bin=resolve_optional_input_path(
args.codex_windows_sandbox_setup_bin,
"prebuilt Windows codex-windows-sandbox-setup.exe executable",
"--codex-windows-sandbox-setup-bin",
),
)
inputs = PackageInputs(
entrypoint_bin=source_outputs.entrypoint_bin,
code_mode_host_bin=source_outputs.code_mode_host_bin,
exec_server_bin=source_outputs.exec_server_bin,
rg_bin=resolve_rg_bin(spec, args.rg_bin),
bwrap_bin=source_outputs.bwrap_bin,
codex_command_runner_bin=source_outputs.codex_command_runner_bin,
codex_windows_sandbox_setup_bin=source_outputs.codex_windows_sandbox_setup_bin,
)
prepare_package_dir(package_dir, force=args.force)
build_package_dir(package_dir, args.package_version, variant, spec, inputs)
for filename, prebuilt in (
(variant.entrypoint_name(spec), args.entrypoint_bin),
(f"codex-code-mode-host{spec.exe_suffix}", args.code_mode_host_bin),
(f"codex-exec-server{spec.exe_suffix}", args.exec_server_bin),
):
if args.strip == "all" or (
args.strip == "auto"
and args.cargo_profile == "release"
and prebuilt is None
):
strip_binary(package_dir / "bin" / filename, spec, tool=args.strip_tool)
validate_package_dir(package_dir, variant, spec)
return package_dir
def archive_package(package_dir: Path, args: argparse.Namespace) -> None:
for archive_output in args.archive_output:
archive_path = archive_output.resolve()
write_archive(package_dir, archive_path, force=args.force)
print(f"Built Codex package archive at {archive_path}")
print(f"Built Codex package directory at {package_dir}")
def resolve_optional_input_path(
explicit_path: Path | None,
description: str,
flag_name: str,
) -> Path | None:
if explicit_path is None:
return None
return resolve_input_path(explicit_path, description, flag_name)

View File

@@ -0,0 +1,229 @@
"""Fetch executable artifacts from checked-in DotSlash manifests."""
import gzip
import hashlib
import json
import shutil
import stat
import tarfile
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import urlparse
from urllib.request import Request, urlopen
from .targets import TargetSpec
DOWNLOAD_TIMEOUT_SECS = 60
@dataclass(frozen=True)
class DotSlashArtifact:
size: int
digest: str
archive_format: str
archive_member: str
url: str
def fetch_dotslash_executable(
spec: TargetSpec,
*,
manifest_path: Path,
artifact_label: str,
cache_key: str,
dest_name: str,
missing_ok: bool = False,
) -> Path | None:
artifact = artifact_for_target(
spec,
manifest_path,
artifact_label=artifact_label,
missing_ok=missing_ok,
)
if artifact is None:
return None
cache_dir = default_cache_root() / cache_key
archive_path = cache_dir / archive_filename(artifact.url)
if not archive_is_valid(archive_path, artifact, artifact_label):
download_archive(artifact.url, archive_path)
try:
verify_archive(archive_path, artifact, artifact_label)
except RuntimeError:
archive_path.unlink(missing_ok=True)
raise
dest = cache_dir / dest_name
extract_archive_member(archive_path, artifact, dest, artifact_label)
if not spec.is_windows:
mode = dest.stat().st_mode
dest.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
return dest
def artifact_for_target(
spec: TargetSpec,
manifest_path: Path,
*,
artifact_label: str,
missing_ok: bool = False,
) -> DotSlashArtifact | None:
manifest = load_manifest(manifest_path)
platform_info = manifest.get("platforms", {}).get(spec.dotslash_platform)
if platform_info is None:
if missing_ok:
return None
raise RuntimeError(
f"{artifact_label} manifest {manifest_path} is missing platform "
f"{spec.dotslash_platform!r}"
)
providers = platform_info.get("providers")
if not providers:
raise RuntimeError(
f"{artifact_label} manifest {manifest_path} has no providers for "
f"{spec.dotslash_platform!r}"
)
hash_name = platform_info.get("hash")
if hash_name != "sha256":
raise RuntimeError(
f"Unsupported {artifact_label} hash {hash_name!r} for "
f"{spec.dotslash_platform!r}; expected sha256"
)
return DotSlashArtifact(
size=int(platform_info["size"]),
digest=str(platform_info["digest"]),
archive_format=str(platform_info["format"]),
archive_member=str(platform_info["path"]),
url=str(providers[0]["url"]),
)
def load_manifest(manifest_path: Path) -> dict:
text = manifest_path.read_text(encoding="utf-8")
if text.startswith("#!"):
text = "\n".join(text.splitlines()[1:])
return json.loads(text)
def default_cache_root() -> Path:
return Path(tempfile.gettempdir()) / "codex-package"
def archive_filename(url: str) -> str:
filename = Path(urlparse(url).path).name
if not filename:
raise RuntimeError(f"Unable to determine archive filename from {url}")
return filename
def archive_is_valid(
archive_path: Path,
artifact: DotSlashArtifact,
artifact_label: str,
) -> bool:
if not archive_path.is_file():
return False
try:
verify_archive(archive_path, artifact, artifact_label)
except RuntimeError:
archive_path.unlink(missing_ok=True)
return False
return True
def verify_archive(
archive_path: Path,
artifact: DotSlashArtifact,
artifact_label: str,
) -> None:
actual_size = archive_path.stat().st_size
if actual_size != artifact.size:
raise RuntimeError(
f"{artifact_label} archive {archive_path} has size {actual_size}, "
f"expected {artifact.size}"
)
digest = hashlib.sha256()
with open(archive_path, "rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
digest.update(chunk)
actual_digest = digest.hexdigest()
if actual_digest != artifact.digest:
raise RuntimeError(
f"{artifact_label} archive {archive_path} has sha256 {actual_digest}, "
f"expected {artifact.digest}"
)
def download_archive(url: str, archive_path: Path) -> None:
archive_path.parent.mkdir(parents=True, exist_ok=True)
temp_path = archive_path.with_suffix(f"{archive_path.suffix}.tmp")
temp_path.unlink(missing_ok=True)
try:
request = Request(url, headers={"User-Agent": "codex-package"})
with urlopen(request, timeout=DOWNLOAD_TIMEOUT_SECS) as response:
with open(temp_path, "wb") as out:
shutil.copyfileobj(response, out)
temp_path.replace(archive_path)
finally:
temp_path.unlink(missing_ok=True)
def extract_archive_member(
archive_path: Path,
artifact: DotSlashArtifact,
dest: Path,
artifact_label: str,
) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
dest.unlink(missing_ok=True)
if artifact.archive_format == "gz":
with gzip.open(archive_path, "rb") as extracted, open(dest, "wb") as out:
shutil.copyfileobj(extracted, out)
return
if artifact.archive_format == "tar.gz":
with tarfile.open(archive_path, "r:gz") as archive:
try:
member = archive.getmember(artifact.archive_member)
except KeyError as exc:
raise RuntimeError(
f"{artifact_label} archive {archive_path} is missing "
f"{artifact.archive_member!r}"
) from exc
extracted = archive.extractfile(member)
if extracted is None:
raise RuntimeError(
f"{artifact_label} archive member {artifact.archive_member!r} is not a file"
)
with extracted, open(dest, "wb") as out:
shutil.copyfileobj(extracted, out)
return
if artifact.archive_format == "zip":
with zipfile.ZipFile(archive_path) as archive:
try:
with archive.open(artifact.archive_member) as extracted:
with open(dest, "wb") as out:
shutil.copyfileobj(extracted, out)
except KeyError as exc:
raise RuntimeError(
f"{artifact_label} archive {archive_path} is missing "
f"{artifact.archive_member!r}"
) from exc
return
raise RuntimeError(
f"Unsupported {artifact_label} archive format {artifact.archive_format!r}; "
"expected gz, tar.gz or zip"
)

View File

@@ -0,0 +1,180 @@
"""Canonical Codex package directory layout."""
import json
import shutil
import stat
from pathlib import Path
from .targets import PackageInputs
from .targets import PackageVariant
from .targets import TargetSpec
LAYOUT_VERSION = 1
def prepare_package_dir(package_dir: Path, *, force: bool) -> None:
if package_dir.exists():
if not package_dir.is_dir():
raise RuntimeError(
f"Package output exists and is not a directory: {package_dir}"
)
if any(package_dir.iterdir()):
if not force:
raise RuntimeError(
f"Package output directory is not empty: {package_dir}. "
"Pass --force to replace it."
)
shutil.rmtree(package_dir)
package_dir.mkdir(parents=True, exist_ok=True)
def build_package_dir(
package_dir: Path,
version: str,
variant: PackageVariant,
spec: TargetSpec,
inputs: PackageInputs,
) -> None:
bin_dir = package_dir / "bin"
resources_dir = package_dir / "codex-resources"
path_dir = package_dir / "codex-path"
bin_dir.mkdir()
resources_dir.mkdir()
path_dir.mkdir()
entrypoint_name = variant.entrypoint_name(spec)
copy_executable(
inputs.entrypoint_bin,
bin_dir / entrypoint_name,
is_windows=spec.is_windows,
)
copy_executable(
inputs.code_mode_host_bin,
bin_dir / f"codex-code-mode-host{spec.exe_suffix}",
is_windows=spec.is_windows,
)
copy_executable(
inputs.exec_server_bin,
bin_dir / f"codex-exec-server{spec.exe_suffix}",
is_windows=spec.is_windows,
)
copy_executable(inputs.rg_bin, path_dir / spec.rg_name, is_windows=spec.is_windows)
if inputs.bwrap_bin is not None:
copy_executable(inputs.bwrap_bin, resources_dir / "bwrap", is_windows=False)
if inputs.codex_command_runner_bin is not None:
copy_executable(
inputs.codex_command_runner_bin,
resources_dir / "codex-command-runner.exe",
is_windows=True,
)
if inputs.codex_windows_sandbox_setup_bin is not None:
copy_executable(
inputs.codex_windows_sandbox_setup_bin,
resources_dir / "codex-windows-sandbox-setup.exe",
is_windows=True,
)
metadata = {
"layoutVersion": LAYOUT_VERSION,
"version": version,
"target": spec.target,
"variant": variant.name,
"entrypoint": f"bin/{entrypoint_name}",
"execServer": f"bin/codex-exec-server{spec.exe_suffix}",
"resourcesDir": "codex-resources",
"pathDir": "codex-path",
}
write_json(package_dir / "codex-package.json", metadata)
def validate_package_dir(
package_dir: Path,
variant: PackageVariant,
spec: TargetSpec,
) -> None:
required_dirs = [
Path("bin"),
Path("codex-resources"),
Path("codex-path"),
]
for relative_dir in required_dirs:
path = package_dir / relative_dir
if not path.is_dir():
raise RuntimeError(f"Missing package directory: {relative_dir}")
metadata_path = package_dir / "codex-package.json"
if not metadata_path.is_file():
raise RuntimeError("Missing package metadata: codex-package.json")
with open(metadata_path, encoding="utf-8") as fh:
metadata = json.load(fh)
expected_metadata = {
"layoutVersion": LAYOUT_VERSION,
"target": spec.target,
"variant": variant.name,
"entrypoint": f"bin/{variant.entrypoint_name(spec)}",
"execServer": f"bin/codex-exec-server{spec.exe_suffix}",
"resourcesDir": "codex-resources",
"pathDir": "codex-path",
}
for key, expected in expected_metadata.items():
actual = metadata.get(key)
if actual != expected:
raise RuntimeError(
f"Invalid package metadata field {key!r}: expected {expected!r}, got {actual!r}"
)
required_files = [
Path("bin") / variant.entrypoint_name(spec),
Path("bin") / f"codex-code-mode-host{spec.exe_suffix}",
Path("bin") / f"codex-exec-server{spec.exe_suffix}",
Path("codex-path") / spec.rg_name,
]
executable_files = list(required_files)
if spec.is_linux:
required_files.append(Path("codex-resources") / "bwrap")
executable_files.append(Path("codex-resources") / "bwrap")
if spec.is_windows:
required_files.extend(
[
Path("codex-resources") / "codex-command-runner.exe",
Path("codex-resources") / "codex-windows-sandbox-setup.exe",
]
)
for relative_file in required_files:
path = package_dir / relative_file
if not path.is_file():
raise RuntimeError(f"Missing package file: {relative_file}")
if not spec.is_windows:
for relative_file in executable_files:
path = package_dir / relative_file
if not is_executable(path):
raise RuntimeError(f"Package file is not executable: {relative_file}")
def copy_executable(src: Path, dest: Path, *, is_windows: bool) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(src, dest)
if not is_windows:
mode = dest.stat().st_mode
dest.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
def write_json(path: Path, value: object) -> None:
with open(path, "w", encoding="utf-8") as out:
json.dump(value, out, indent=2)
out.write("\n")
def is_executable(path: Path) -> bool:
return bool(path.stat().st_mode & stat.S_IXUSR)

79
scripts/codex_package/rg Executable file
View File

@@ -0,0 +1,79 @@
#!/usr/bin/env dotslash
{
"name": "rg",
"platforms": {
"macos-aarch64": {
"size": 1764284,
"hash": "sha256",
"digest": "3750b2e93f37e0c692657da574d7019a101c0084da05a790c83fd335bad973e4",
"format": "tar.gz",
"path": "ripgrep-15.2.0-aarch64-apple-darwin/rg",
"providers": [
{
"url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-apple-darwin.tar.gz"
}
]
},
"linux-aarch64": {
"size": 1854661,
"hash": "sha256",
"digest": "a740b91c82eaf9914cfedd353572f2791cbe0162c84101ee0951058f4dcbc90d",
"format": "tar.gz",
"path": "ripgrep-15.2.0-aarch64-unknown-linux-gnu/rg",
"providers": [
{
"url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-unknown-linux-gnu.tar.gz"
}
]
},
"macos-x86_64": {
"size": 1878284,
"hash": "sha256",
"digest": "af7825fcc69a2afc7a7aea55fc9af90e26421d8f20fe59df32e233c0b8a231c1",
"format": "tar.gz",
"path": "ripgrep-15.2.0-x86_64-apple-darwin/rg",
"providers": [
{
"url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-apple-darwin.tar.gz"
}
]
},
"linux-x86_64": {
"size": 2265718,
"hash": "sha256",
"digest": "33e15bcf1624b25cdd2a55813a47a2f95dbe126268203e76aa6a585d1e7b149c",
"format": "tar.gz",
"path": "ripgrep-15.2.0-x86_64-unknown-linux-musl/rg",
"providers": [
{
"url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-unknown-linux-musl.tar.gz"
}
]
},
"windows-x86_64": {
"size": 1789611,
"hash": "sha256",
"digest": "71b2fef860abe467217a538ff31de02f5258807c0129f771846f87bd029aafc5",
"format": "zip",
"path": "ripgrep-15.2.0-x86_64-pc-windows-msvc/rg.exe",
"providers": [
{
"url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-pc-windows-msvc.zip"
}
]
},
"windows-aarch64": {
"size": 1640124,
"hash": "sha256",
"digest": "e4abca10c3a64ebea742667dd7009449d49403db5460dd6873e389fa2945360f",
"format": "zip",
"path": "ripgrep-15.2.0-aarch64-pc-windows-msvc/rg.exe",
"providers": [
{
"url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-pc-windows-msvc.zip"
}
]
}
}
}

View File

@@ -0,0 +1,32 @@
"""Fetch ripgrep from the DotSlash manifest used by the package builder."""
from pathlib import Path
from .dotslash import fetch_dotslash_executable
from .targets import TargetSpec, resolve_input_path
RG_MANIFEST = Path(__file__).with_name("rg")
def resolve_rg_bin(spec: TargetSpec, rg_bin: Path | None) -> Path:
if rg_bin is not None:
return resolve_input_path(rg_bin, "ripgrep executable", "--rg-bin")
return fetch_rg(spec)
def fetch_rg(
spec: TargetSpec,
*,
manifest_path: Path = RG_MANIFEST,
) -> Path:
rg_bin = fetch_dotslash_executable(
spec,
manifest_path=manifest_path,
artifact_label="ripgrep",
cache_key=f"{spec.target}-rg",
dest_name=spec.rg_name,
)
if rg_bin is None:
raise AssertionError("ripgrep is required for all package targets")
return rg_bin

View File

@@ -0,0 +1,39 @@
from pathlib import Path
import pytest
from fixtures import code_mode_host_debug_symbols, package, responses_server
__all__ = ["code_mode_host_debug_symbols", "package", "responses_server"]
def pytest_addoption(parser: pytest.Parser) -> None:
group = parser.getgroup("Codex package smoke")
group.addoption(
"--compression",
choices=("gzip", "zstd"),
required=True,
help="Compression format of the supplied package archives.",
)
group.addoption(
"--package-target",
required=True,
help="Rust target triple for the assembled release packages.",
)
group.addoption(
"--cli-archive",
type=Path,
required=True,
help="Assembled Codex CLI package archive in the selected format.",
)
group.addoption(
"--app-server-archive",
type=Path,
required=True,
help="Assembled app-server package archive in the selected format.",
)
group.addoption(
"--symbols-archive",
type=Path,
required=True,
help="Gzip archive containing symbols for all packaged binaries.",
)

View File

@@ -0,0 +1,252 @@
import gzip
import json
import os
import platform
import subprocess
import tarfile
from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Self
import pytest
import zstandard
from app_server_harness import MockResponsesServer
@dataclass(frozen=True)
class SmokePackage:
target: str
cli: Path
cli_root: Path
cli_path_dir: Path
app_server: Path
app_server_root: Path
app_server_path_dir: Path
directory: Path
environment: dict[str, str]
@classmethod
def from_archives(
cls,
directory: Path,
target: str,
cli_archive: Path,
app_server_archive: Path,
compression: str,
) -> Self:
config_dir = directory / "codex-config"
config_dir.mkdir()
environment = dict(os.environ)
# Preserve host proxies while routing the fake localhost model directly.
inherited_bypass = (
environment.get("NO_PROXY") or environment.get("no_proxy") or ""
).split(",")
environment["NO_PROXY"] = ",".join(
dict.fromkeys(
host.strip()
for host in [*inherited_bypass, "127.0.0.1", "localhost"]
if host.strip()
)
)
# Isolate package configuration and state from the user's Codex setup.
environment["CODEX_HOME"] = str(config_dir)
# Shell startup files can replace PATH and hide the packaged ripgrep.
environment.pop("BASH_ENV", None)
environment["ZDOTDIR"] = str(directory)
extracted_packages = []
for index, archive_path in enumerate((cli_archive, app_server_archive)):
extracted = directory / f"package-{index}"
extracted.mkdir()
decompress = zstandard.open if compression == "zstd" else gzip.open
with (
decompress(archive_path, "rb") as source,
tarfile.open(fileobj=source, mode="r|") as archive,
):
archive.extractall(extracted, filter="data")
manifest = json.loads((extracted / "codex-package.json").read_text())
extracted_packages.append(
(
extracted,
extracted / manifest["entrypoint"],
extracted / manifest["pathDir"],
)
)
cli_root, cli, cli_path_dir = extracted_packages[0]
app_server_root, app_server, app_server_path_dir = extracted_packages[1]
(config_dir / "config.toml").write_text(
"""approval_policy = "never"
sandbox_mode = "workspace-write"
suppress_unstable_features_warning = true
[sandbox_workspace_write]
network_access = true
writable_roots = []
[features]
code_mode_only = true
code_mode_host = true
memories = false
apps = false
plugins = false
[analytics]
enabled = false
[otel]
exporter = "none"
trace_exporter = "none"
metrics_exporter = "none"
"""
)
return cls(
target=target,
cli=cli,
cli_root=cli_root,
cli_path_dir=cli_path_dir,
app_server=app_server,
app_server_root=app_server_root,
app_server_path_dir=app_server_path_dir,
directory=directory,
environment=environment,
)
def run(
self,
*arguments: str,
stdin: str | None = None,
) -> subprocess.CompletedProcess[str]:
return subprocess.run(
[str(self.cli), *arguments],
cwd=self.directory,
env=self.environment,
input=stdin,
check=True,
text=True,
capture_output=True,
timeout=45,
)
@pytest.fixture(scope="session")
def package(
request: pytest.FixtureRequest,
tmp_path_factory: pytest.TempPathFactory,
) -> SmokePackage:
compression = request.config.getoption("compression")
target = request.config.getoption("package_target")
directory = tmp_path_factory.mktemp(f"codex-package-smoke-{compression}")
if "windows" in target:
# pytest's 0700 directories have protected ACLs, so restricted-token
# sandboxes need read/execute access to reach the packaged binaries.
for path in (directory.parent, directory):
subprocess.run(
["icacls", str(path), "/grant", "*S-1-1-0:(OI)(CI)(RX)"],
check=True,
capture_output=True,
text=True,
)
package = SmokePackage.from_archives(
directory,
target,
request.config.getoption("cli_archive"),
request.config.getoption("app_server_archive"),
compression,
)
if target == "x86_64-apple-darwin" and platform.machine() == "arm64":
# Freshly extracted Intel binaries need cold Rosetta translation before
# the command and SDK startup deadlines begin. Keep startup bounded and
# fail setup if either packaged entrypoint cannot run.
for executable in (package.cli, package.app_server):
subprocess.run(
[str(executable), "--help"],
cwd=package.directory,
env=package.environment,
check=True,
text=True,
capture_output=True,
timeout=180,
)
return package
@pytest.fixture
def responses_server(package: SmokePackage) -> Iterator[MockResponsesServer]:
config_path = Path(package.environment["CODEX_HOME"]) / "config.toml"
original_config = config_path.read_text()
with MockResponsesServer() as server:
# Direct CLI commands and SDK-launched servers must share a provider;
# CodexConfig only controls how the SDK launches its server process.
config_path.write_text(
f"""model = "package-smoke"
model_provider = "package_smoke"
{original_config}
[model_providers.package_smoke]
name = "package smoke"
base_url = "{server.url}/v1"
wire_api = "responses"
request_max_retries = 0
stream_max_retries = 0
"""
)
try:
yield server
finally:
config_path.write_text(original_config)
@pytest.fixture(scope="session")
def code_mode_host_debug_symbols(
pytestconfig: pytest.Config,
tmp_path_factory: pytest.TempPathFactory,
) -> Path:
target = pytestconfig.getoption("package_target")
binaries = {
"codex",
"codex-app-server",
"codex-code-mode-host",
"codex-exec-server",
}
if "windows" in target:
binaries.update({"codex-command-runner", "codex-windows-sandbox-setup"})
if "apple-darwin" in target:
markers = {
binary: f"/{binary}.dSYM/Contents/Resources/DWARF/" for binary in binaries
}
else:
extension = "pdb" if "windows" in target else "debug"
markers = {binary: f"/{binary}.{extension}" for binary in binaries}
destination = tmp_path_factory.mktemp("codex-debug-symbols")
found: set[str] = set()
symbol_path = None
with tarfile.open(pytestconfig.getoption("symbols_archive"), "r|gz") as archive:
for member in archive:
if not member.isfile():
continue
for binary, marker in markers.items():
if "apple-darwin" in target:
_, found_marker, dwarf_name = member.name.partition(marker)
matches = bool(
found_marker and dwarf_name and "/" not in dwarf_name
)
else:
matches = member.name.endswith(marker)
if not matches:
continue
found.add(binary)
if binary == "codex-code-mode-host":
archive.extract(member, destination, filter="data")
symbol_path = destination / member.name
break
assert found == binaries, found
assert symbol_path is not None
return symbol_path

View File

@@ -0,0 +1,12 @@
[project]
name = "codex-package-smoke-tests"
version = "0.0.0"
requires-python = ">=3.12"
dependencies = [
"pydantic>=2.12,<3",
"pytest>=8.0",
"zstandard>=0.23",
]
[tool.uv]
package = false

View File

@@ -0,0 +1,557 @@
"""Exercise each assembled package in the order its shipped files appear.
ROOT_OF_EXTRACTED_PACKAGE
├── bin
│ ├── codex[.exe] # CLI package only
│ ├── codex-app-server[.exe] # app-server package only
│ ├── codex-code-mode-host[.exe]
│ └── codex-exec-server[.exe]
├── codex-package.json
├── codex-path
│ └── rg[.exe]
└── codex-resources
├── bwrap # Linux only
├── codex-command-runner.exe # Windows only
├── codex-windows-sandbox-setup.exe # Windows only
Debug symbols for all shipped binaries arrive in a separate companion archive.
Each package contains one entrypoint, not both codex and codex-app-server.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import tomllib
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from pathlib import Path
import pytest
from app_server_harness import (
MockResponsesServer,
ev_completed,
ev_response_created,
sse,
)
from openai_codex import ApprovalMode, Codex, CodexConfig, Sandbox
from fixtures import SmokePackage
@pytest.mark.parametrize(
("arguments", "expected"),
[
pytest.param(("--help",), "Usage:", id="help"),
pytest.param(("features", "list"), "code_mode", id="features"),
pytest.param(("completion", "bash"), "codex", id="completion"),
],
)
def test_cli_public_commands(
package: SmokePackage,
arguments: tuple[str, ...],
expected: str,
) -> None:
"""Packaged CLI remains usable for discovery, features, and completions."""
output = package.run(*arguments).stdout
assert expected in output
def test_cli_version_matches_release_sources(package: SmokePackage) -> None:
"""Verify the compiled banner against the sources used to package the release."""
root = next(
parent
for parent in Path(__file__).resolve().parents
if (parent / "codex-rs/Cargo.toml").is_file()
)
manifest = tomllib.loads((root / "codex-rs/Cargo.toml").read_text())
version = manifest["workspace"]["package"]["version"]
assert package.run("--version").stdout == f"codex-cli {version}\n"
@pytest.mark.parametrize("variant", ["cli_root", "app_server_root"])
def test_packaged_executor_initializes_and_enforces_sandbox(
package: SmokePackage, variant: str
) -> None:
"""Each package re-enters its executor helpers and enforces filesystem/process policy."""
root = getattr(package, variant)
windows = "windows" in package.target
suffix = ".exe" if windows else ""
executor = root / "bin" / f"codex-exec-server{suffix}"
directory = package.directory / f"{variant}-executor-sandbox"
directory.mkdir()
workspace = directory / "workspace"
workspace.mkdir()
home = directory / "home"
home.mkdir()
blocked = directory / "blocked.txt"
blocked.write_text("unchanged")
environment = {**package.environment, "CODEX_HOME": str(home)}
if windows:
# Elevated mode must discover the setup/runner in this package's resources.
# Exclude build outputs and host Codex installations from helper fallback.
environment["PATH"] = str(Path(os.environ["SystemRoot"]) / "System32")
sandbox = {
"permissions": {
"type": "managed",
"file_system": {
"type": "restricted",
"entries": [
{
"path": {"type": "special", "value": {"kind": "root"}},
"access": "read",
},
{
"path": {"type": "path", "path": workspace.as_uri()},
"access": "write",
},
],
},
"network": "restricted",
},
"cwd": workspace.as_uri(),
"windowsSandboxLevel": "elevated" if windows else "disabled",
}
version = (
subprocess.check_output(
[str(executor), "--version"], env=package.environment, text=True, timeout=45
)
.strip()
.split()[-1]
)
assert version == package.run("--version").stdout.strip().split()[-1]
with (
ThreadPoolExecutor(max_workers=1) as reader,
subprocess.Popen(
[str(executor), "--listen", "stdio"],
cwd=package.directory,
env=environment,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
text=True,
) as process,
):
assert process.stdin is not None and process.stdout is not None
try:
process.stdin.write(
json.dumps(
{
"id": 1,
"method": "initialize",
"params": {"clientName": "package-smoke"},
}
)
+ "\n"
)
process.stdin.flush()
initialized = json.loads(
reader.submit(process.stdout.readline).result(timeout=45)
)
assert initialized["id"] == 1
assert initialized["result"]["sessionId"]
reported_environment = initialized["result"]["environmentInfo"]
metadata = json.loads((root / "codex-package.json").read_text())
assert reported_environment["executorVersion"] == metadata["version"]
process.stdin.write('{"method":"initialized","params":{}}\n')
def file_request(
request_id: int,
method: str,
path: Path,
*,
timeout: int = 45,
**params: str,
) -> dict:
process.stdin.write(
json.dumps(
{
"id": request_id,
"method": method,
"params": {
"path": path.as_uri(),
"sandbox": sandbox,
**params,
},
}
)
+ "\n"
)
process.stdin.flush()
return json.loads(
reader.submit(process.stdout.readline).result(timeout=timeout)
)
if windows:
# Resolving the inner helper creates today's log. The first ACL scan must see it.
log_dir = home / ".sandbox"
log_dir.mkdir(exist_ok=True)
sibling = log_dir / "allowed.txt"
sibling.write_bytes(b"ok")
day = datetime.now(UTC).date()
log = log_dir / f"sandbox.{day}.log"
assert not log.exists()
sandbox["permissions"]["file_system"]["entries"].append(
{
"path": {
"type": "glob_pattern",
"pattern": (log_dir / "*.log").as_posix(),
},
"access": "deny",
}
)
# The first Windows helper can provision sandbox accounts before replying.
denied = file_request(5, "fs/readFile", log, timeout=180)
if not log.exists() and day != datetime.now(UTC).date():
# The helper crossed UTC midnight before creating its log.
log = next(log_dir.glob("sandbox.*.log"))
denied = file_request(7, "fs/readFile", log)
assert "Access is denied" in denied.get("error", {}).get("message", "")
assert log.is_file()
assert file_request(6, "fs/readFile", sibling) == {
"id": 6,
"result": {"dataBase64": "b2s="},
}
# Restricted writes always launch the filesystem helper, even when allowed.
for request_id, path in [(2, workspace / "allowed.txt"), (3, blocked)]:
response = file_request(
request_id, "fs/writeFile", path, dataBase64="b2s="
)
if request_id == 2:
assert response == {"id": 2, "result": {}}, response
assert path.read_text() == "ok"
else:
assert response["id"] == 3 and "error" in response, response
assert blocked.read_text() == "unchanged"
command = (
[
str(Path(os.environ["SystemRoot"]) / "System32" / "cmd.exe"),
"/D",
"/S",
"/C",
r"echo process>process.txt & echo forbidden>..\blocked.txt & exit /b 0",
]
if windows
else [
"/bin/sh",
"-c",
"printf process >process.txt; printf forbidden >../blocked.txt; exit 0",
]
)
process.stdin.write(
json.dumps(
{
"id": 4,
"method": "process/start",
"params": {
"processId": "package-sandbox",
"argv": command,
"cwd": workspace.as_uri(),
"env": {
key: value
for key, value in environment.items()
if key.casefold() in {"path", "systemroot"}
},
"sandbox": sandbox,
"tty": False,
"pipeStdin": False,
"arg0": None,
},
}
)
+ "\n"
)
process.stdin.flush()
started = False
exit_code = None
notifications = []
while not started or exit_code is None:
response = json.loads(
reader.submit(process.stdout.readline).result(timeout=45)
)
notifications.append(response)
if response.get("id") == 4:
expected_type = (
"windowsRestrictedToken"
if windows
else "macosSeatbelt"
if "apple-darwin" in package.target
else "linuxSeccomp"
)
assert response["result"]["sandboxType"] == expected_type, response
started = True
if response.get("method") == "process/exited":
exit_code = response["params"]["exitCode"]
assert exit_code == 0, notifications
assert (workspace / "process.txt").is_file(), notifications
assert (workspace / "process.txt").read_text().strip() == "process"
assert blocked.read_text() == "unchanged"
process.stdin.close()
assert process.wait(timeout=45) == 0
finally:
if process.poll() is None:
process.kill()
def test_packaged_executor_matches_subcommand_startup(
package: SmokePackage,
tmp_path: Path,
) -> None:
"""Both binaries reject the same invalid executor arguments and config."""
home = tmp_path / "home"
temporary = tmp_path / "tmp"
home.mkdir()
temporary.mkdir()
(home / "config.toml").write_text("unknown_executor_option = true\n")
# Release builds require the helper directory to live outside their temp root.
environment = {
**package.environment,
"CODEX_HOME": str(home),
"TMPDIR": str(temporary),
"TEMP": str(temporary),
"TMP": str(temporary),
}
suffix = ".exe" if "windows" in package.target else ""
executor = package.cli_root / "bin" / f"codex-exec-server{suffix}"
for arguments in [
["--strict-config", "--listen", "stdio"],
["-c", "unknown_executor_option=true", "--strict-config", "--listen", "stdio"],
["--listen", "http://127.0.0.1:0"],
["--concurrent-requests", "0"],
[
"--aws-sigv4",
"--remote",
"https://example.openai.com",
"--environment-id",
"env-1",
],
["--remote-transport", "direct"],
["forward", "--connect", "ws://127.0.0.1:0"],
[
"-c",
"unknown_executor_option=true",
"forward",
"-c",
"analytics.enabled=false",
"--strict-config",
"--connect",
"ws://127.0.0.1:0",
"--remote",
"https://example.openai.com",
"--environment-id",
"env-1",
],
]:
outputs = []
for command in ([str(package.cli), "exec-server"], [str(executor)]):
result = subprocess.run(
[*command, *arguments],
cwd=tmp_path,
env=environment,
capture_output=True,
text=True,
timeout=45,
)
assert result.returncode != 0, arguments
outputs.append(
(
result.returncode,
result.stdout,
result.stderr.replace("codex exec-server", "codex-exec-server"),
)
)
assert outputs[0] == outputs[1], arguments
@pytest.mark.parametrize("entrypoint", ["codex", "codex-app-server"])
def test_app_server_runs_code_mode_through_python_sdk(
package: SmokePackage,
responses_server: MockResponsesServer,
entrypoint: str,
) -> None:
"""Both packages run their own ripgrep through sandboxed SDK code mode."""
windows = "windows" in package.target
sandbox_config = ("--config", 'windows.sandbox="unelevated"') if windows else ()
if entrypoint == "codex":
executable = package.cli
package_root = package.cli_root
package_path_dir = package.cli_path_dir
config = CodexConfig(
codex_bin=str(executable),
config_overrides=sandbox_config[1:],
cwd=str(package.directory),
env=package.environment,
)
else:
executable = package.app_server
package_root = package.app_server_root
package_path_dir = package.app_server_path_dir
config = CodexConfig(
launch_args_override=(str(executable), *sandbox_config),
cwd=str(package.directory),
env=package.environment,
)
if windows:
# TODO(anp): Assert resolved rg paths once Windows sandbox PATH finds them.
ripgrep = str(package_path_dir / "rg.exe").replace("'", "''")
command = (
f"$rg = '{ripgrep}'; Write-Output $rg; & $rg --version; "
"if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }"
)
else:
command = "command -v rg && rg --version"
exec_arguments = {"cmd": command, "login": False, "yield_time_ms": 10_000}
responses_server.enqueue_sse(
sse(
[
ev_response_created("code-mode"),
{
"type": "response.output_item.done",
"item": {
"type": "custom_tool_call",
"call_id": "package-smoke",
"name": "exec",
"input": (
"text(JSON.stringify(await tools.exec_command("
f"{json.dumps(exec_arguments)})))"
),
},
},
ev_completed("code-mode"),
]
)
)
responses_server.enqueue_assistant_message("Done", response_id="code-mode-done")
with Codex(config=config) as client:
turn = client.thread_start(
ephemeral=True,
approval_mode=ApprovalMode.deny_all,
sandbox=Sandbox.workspace_write,
).run("run package smoke")
assert turn.final_response == "Done", turn
# The mock also records analytics POSTs, which have no Responses input list.
output = next(
item
for request in responses_server.requests()
if request.path == "/v1/responses"
for item in request.input()
if item.get("type") == "custom_tool_call_output"
and item.get("call_id") == "package-smoke"
)["output"]
if not isinstance(output, str):
output = next(
item["text"] for item in output if item.get("text", "").startswith("{")
)
execution = json.loads(output)
execution_output = execution["output"]
assert execution["exit_code"] == 0, execution_output
assert "ripgrep" in execution_output, execution_output
# Each entrypoint must execute the ripgrep bundled in its own package.
reported_ripgrep_path = Path(execution_output.splitlines()[0].strip())
assert reported_ripgrep_path.is_relative_to(package_root), execution_output
def _code_mode_host_symbol_address(
package: SmokePackage,
symbols: Path,
*arguments: str,
) -> str:
symbol_output = subprocess.run(
["nm", "-C", *arguments, str(symbols)],
cwd=package.directory,
env=package.environment,
capture_output=True,
text=True,
check=True,
timeout=45,
).stdout
# Rust v0 symbols can name this crate only as the instantiating crate of
# a dependency's generic function. Match the demangled entrypoint instead.
return next(
parts[0]
for line in symbol_output.splitlines()
if len(parts := line.split(maxsplit=2)) == 3
and parts[1].lower() == "t"
and re.fullmatch(r"codex_code_mode_host::main(?:::h[0-9a-f]{16})?", parts[2])
)
@pytest.mark.skipif(sys.platform != "linux", reason="requires Linux debug symbols")
def test_linux_debug_symbols_resolve_packaged_code(
package: SmokePackage,
code_mode_host_debug_symbols: Path,
) -> None:
"""Linux host symbols resolve a packaged function and its source location."""
address = _code_mode_host_symbol_address(
package, code_mode_host_debug_symbols, "--defined-only"
)
resolved = subprocess.run(
[
"addr2line",
"-e",
str(code_mode_host_debug_symbols),
"-f",
"-C",
f"0x{address}",
],
cwd=package.directory,
env=package.environment,
capture_output=True,
text=True,
check=True,
timeout=45,
).stdout
assert "codex_code_mode_host" in resolved, resolved
source = resolved.splitlines()[-1]
assert source != "??:?" and source.rsplit(":", 1)[-1].isdigit(), source
@pytest.mark.skipif(sys.platform != "darwin", reason="requires macOS debug symbols")
def test_macos_debug_symbols_resolve_packaged_code(
package: SmokePackage,
code_mode_host_debug_symbols: Path,
) -> None:
"""macOS host symbols resolve a packaged function."""
address = _code_mode_host_symbol_address(package, code_mode_host_debug_symbols)
resolved = subprocess.run(
["atos", "-o", str(code_mode_host_debug_symbols), f"0x{address}"],
cwd=package.directory,
env=package.environment,
capture_output=True,
text=True,
check=True,
timeout=45,
).stdout
assert "codex_code_mode_host" in resolved, resolved
@pytest.mark.skipif(sys.platform != "win32", reason="requires Windows debug symbols")
def test_windows_debug_symbols_resolve_packaged_code(
package: SmokePackage,
code_mode_host_debug_symbols: Path,
) -> None:
"""Windows host symbols match the packaged executable's debug signature."""
# Cargo embeds an underscored PDB name; Bazel uses the binary's name.
# Offer the archived PDB under both names so dumpbin still verifies that
# its signature matches the packaged executable, regardless of builder.
cargo_symbols = code_mode_host_debug_symbols.with_name("codex_code_mode_host.pdb")
shutil.copy2(code_mode_host_debug_symbols, cargo_symbols)
symbols = (code_mode_host_debug_symbols, cargo_symbols)
host = code_mode_host_debug_symbols.with_suffix(".exe")
shutil.copy2(package.cli.with_name("codex-code-mode-host.exe"), host)
result = subprocess.run(
["dumpbin", "/PDBPATH", str(host)],
cwd=package.directory,
env=package.environment,
capture_output=True,
text=True,
check=True,
timeout=45,
)
assert any(str(path).casefold() in result.stdout.casefold() for path in symbols), (
result.stdout
)

258
scripts/codex_package/smoke_tests/uv.lock generated Normal file
View File

@@ -0,0 +1,258 @@
version = 1
revision = 3
requires-python = ">=3.12"
[[package]]
name = "annotated-types"
version = "0.8.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" },
]
[[package]]
name = "codex-package-smoke-tests"
version = "0.0.0"
source = { virtual = "." }
dependencies = [
{ name = "pydantic" },
{ name = "pytest" },
{ name = "zstandard" },
]
[package.metadata]
requires-dist = [
{ name = "pydantic", specifier = ">=2.12,<3" },
{ name = "pytest", specifier = ">=8.0" },
{ name = "zstandard", specifier = ">=0.23" },
]
[[package]]
name = "colorama"
version = "0.4.6"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
]
[[package]]
name = "iniconfig"
version = "2.3.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
]
[[package]]
name = "packaging"
version = "26.3"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
]
[[package]]
name = "pydantic"
version = "2.13.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "annotated-types" },
{ name = "pydantic-core" },
{ name = "typing-extensions" },
{ name = "typing-inspection" },
]
sdist = { url = "https://files.pythonhosted.org/packages/18/a5/b60d21ac674192f8ab0ba4e9fd860690f9b4a6e51ca5df118733b487d8d6/pydantic-2.13.4.tar.gz", hash = "sha256:c40756b57adaa8b1efeeced5c196f3f3b7c435f90e84ea7f443901bec8099ef6", size = 844775, upload-time = "2026-05-06T13:43:05.343Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/fd/7b/122376b1fd3c62c1ed9dc80c931ace4844b3c55407b6fb2d199377c9736f/pydantic-2.13.4-py3-none-any.whl", hash = "sha256:45a282cde31d808236fd7ea9d919b128653c8b38b393d1c4ab335c62924d9aba", size = 472262, upload-time = "2026-05-06T13:43:02.641Z" },
]
[[package]]
name = "pydantic-core"
version = "2.46.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/9d/56/921726b776ace8d8f5db44c4ef961006580d91dc52b803c489fafd1aa249/pydantic_core-2.46.4.tar.gz", hash = "sha256:62f875393d7f270851f20523dd2e29f082bcc82292d66db2b64ea71f64b6e1c1", size = 471464, upload-time = "2026-05-06T13:37:06.98Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/ce/8c/af022f0af448d7747c5154288d46b5f2bc5f17366eaa0e23e9aa04d59f3b/pydantic_core-2.46.4-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:3245406455a5d98187ec35530fd772b1d799b26667980872c8d4614991e2c4a2", size = 2106158, upload-time = "2026-05-06T13:38:57.215Z" },
{ url = "https://files.pythonhosted.org/packages/19/95/6195171e385007300f0f5574592e467c568becce2d937a0b6804f218bc49/pydantic_core-2.46.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:962ccbab7b642487b1d8b7df90ef677e03134cf1fd8880bf698649b22a69371f", size = 1951724, upload-time = "2026-05-06T13:37:02.697Z" },
{ url = "https://files.pythonhosted.org/packages/8e/bc/f47d1ff9cbb1620e1b5b697eef06010035735f07820180e74178226b27b3/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8233f2947cf85404441fd7e0085f53b10c93e0ee78611099b5c7237e36aacbf7", size = 1975742, upload-time = "2026-05-06T13:37:09.448Z" },
{ url = "https://files.pythonhosted.org/packages/5b/11/9b9a5b0306345664a2da6410877af6e8082481b5884b3ddd78d47c6013ce/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3a233125ac121aa3ffba9a2b59edfc4a985a76092dc8279586ab4b71390875e7", size = 2052418, upload-time = "2026-05-06T13:37:38.234Z" },
{ url = "https://files.pythonhosted.org/packages/f1/b7/a65fec226f5d78fc39f4a13c4cc0c768c22b113438f60c14adc9d2865038/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5b712b53160b79a5850310b912a5ef8e57e56947c8ad690c227f5c9d7e561712", size = 2232274, upload-time = "2026-05-06T13:38:27.753Z" },
{ url = "https://files.pythonhosted.org/packages/68/f0/92039db98b907ef49269a8271f67db9cb78ae2fc68062ef7e4e77adb5f61/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9401557acd873c3a7f3eb9383edef8ac4968f9510e340f4808d427e75667e7b4", size = 2309940, upload-time = "2026-05-06T13:38:05.353Z" },
{ url = "https://files.pythonhosted.org/packages/5f/97/2aab507d3d00ca626e8e57c1eac6a79e4e5fbcc63eb99733ff55d1717f65/pydantic_core-2.46.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:926c9541b14b12b1681dca8a0b75feb510b06c6341b70a8e500c2fdcff837cce", size = 2094516, upload-time = "2026-05-06T13:39:10.577Z" },
{ url = "https://files.pythonhosted.org/packages/22/37/a8aca44d40d737dde2bc05b3c6c07dff0de07ce6f82e9f3167aeaf4d5dea/pydantic_core-2.46.4-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:56cb4851bcaf3d117eddcef4fe66afd750a50274b0da8e22be256d10e5611987", size = 2136854, upload-time = "2026-05-06T13:40:22.59Z" },
{ url = "https://files.pythonhosted.org/packages/24/99/fcef1b79238c06a8cbec70819ac722ba76e02bc8ada9b0fd66eba40da01b/pydantic_core-2.46.4-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:c68fcd102d71ea85c5b2dfac3f4f8476eff42a9e078fd5faefff6d145063536b", size = 2180306, upload-time = "2026-05-06T13:40:10.666Z" },
{ url = "https://files.pythonhosted.org/packages/ae/6c/fc44000918855b42779d007ae63b0532794739027b2f417321cddbc44f6a/pydantic_core-2.46.4-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:b2f69dec1725e79a012d920df1707de5caf7ed5e08f3be4435e25803efc47458", size = 2190044, upload-time = "2026-05-06T13:40:43.231Z" },
{ url = "https://files.pythonhosted.org/packages/6b/65/d9cadc9f1920d7a127ad2edba16c1db7916e59719285cd6c94600b0080ba/pydantic_core-2.46.4-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:8d0820e8192167f80d88d64038e609c31452eeca865b4e1d9950a27a4609b00b", size = 2329133, upload-time = "2026-05-06T13:39:57.365Z" },
{ url = "https://files.pythonhosted.org/packages/d0/cf/c873d91679f3a30bcf5e7ac280ce5573483e72295307685120d0d5ad3416/pydantic_core-2.46.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:fbdb89b3e1c94a30cc5edfce477c6e6a5dc4d8f84665b455c27582f211a1c72c", size = 2374464, upload-time = "2026-05-06T13:38:06.976Z" },
{ url = "https://files.pythonhosted.org/packages/47/bd/6f2fc8188f31bf10590f1e98e7b306336161fac930a8c514cd7bd828c7dc/pydantic_core-2.46.4-cp312-cp312-win32.whl", hash = "sha256:9aa768456404a8bf48a4406685ac2bec8e72b62c69313734fa3b73cf33b3a894", size = 1974823, upload-time = "2026-05-06T13:40:47.985Z" },
{ url = "https://files.pythonhosted.org/packages/40/8c/985c1d41ea1107c2534abd9870e4ed5c8e7669b5c308297835c001e7a1c4/pydantic_core-2.46.4-cp312-cp312-win_amd64.whl", hash = "sha256:e9c26f834c65f5752f3f06cb08cb86a913ceb7274d0db6e267808a708b46bc89", size = 2072919, upload-time = "2026-05-06T13:39:21.153Z" },
{ url = "https://files.pythonhosted.org/packages/c4/ba/f463d006e0c47373ca7ec5e1a261c59dc01ef4d62b2657af925fb0deee3a/pydantic_core-2.46.4-cp312-cp312-win_arm64.whl", hash = "sha256:4fc73cb559bdb54b1134a706a2802a4cddd27a0633f5abb7e53056268751ac6a", size = 2027604, upload-time = "2026-05-06T13:39:03.753Z" },
{ url = "https://files.pythonhosted.org/packages/51/a2/5d30b469c5267a17b39dec53208222f76a8d351dfac4af661888c5aee77d/pydantic_core-2.46.4-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:5d5902252db0d3cedf8d4a1bc68f70eeb430f7e4c7104c8c476753519b423008", size = 2106306, upload-time = "2026-05-06T13:37:48.029Z" },
{ url = "https://files.pythonhosted.org/packages/c1/81/4fa520eaffa8bd7d1525e644cd6d39e7d60b1592bc5b516693c7340b50f1/pydantic_core-2.46.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:c94f0688e7b8d0a67abf40e57a7eaaecd17cc9586706a31b76c031f63df052b4", size = 1951906, upload-time = "2026-05-06T13:37:17.012Z" },
{ url = "https://files.pythonhosted.org/packages/03/d5/fd02da45b659668b05923b17ba3a0100a0a3d5541e3bd8fcc4ecb711309e/pydantic_core-2.46.4-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f027324c56cd5406ca49c124b0db10e56c69064fec039acc571c29020cc87c76", size = 1976802, upload-time = "2026-05-06T13:37:35.113Z" },
{ url = "https://files.pythonhosted.org/packages/21/f2/95727e1368be3d3ed485eaab7adbd7dda408f33f7a36e8b48e0144002b91/pydantic_core-2.46.4-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e739fee756ba1010f8bcccb534252e85a35fe45ae92c295a06059ce58b74ccd3", size = 2052446, upload-time = "2026-05-06T13:37:12.313Z" },
{ url = "https://files.pythonhosted.org/packages/9c/86/5d99feea3f77c7234b8718075b23db11532773c1a0dbd9b9490215dc2eeb/pydantic_core-2.46.4-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9d56801be94b86a9da183e5f3766e6310752b99ff647e38b09a9500d88e46e76", size = 2232757, upload-time = "2026-05-06T13:39:01.149Z" },
{ url = "https://files.pythonhosted.org/packages/d2/3a/508ac615935ef7588cf6d9e9b91309fdc2da751af865e02a9098de88258c/pydantic_core-2.46.4-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2412e734dcb48da14d4e4006b82b46b74f2518b8a26ee7e58c6844a6cd6d03c4", size = 2309275, upload-time = "2026-05-06T13:37:41.406Z" },
{ url = "https://files.pythonhosted.org/packages/07/f8/41db9de19d7987d6b04715a02b3b40aea467000275d9d758ffaa31af7d50/pydantic_core-2.46.4-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9551187363ffc0de2a00b2e47c25aeaeb1020b69b668762966df15fc5659dd5a", size = 2094467, upload-time = "2026-05-06T13:39:18.847Z" },
{ url = "https://files.pythonhosted.org/packages/2c/e2/f35033184cb11d0052daf4416e8e10a502ea2ac006fc4f459aee872727d1/pydantic_core-2.46.4-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:0186750b482eefa11d7f435892b09c5c606193ef3375bcf94aa00ae6bfb66262", size = 2134417, upload-time = "2026-05-06T13:40:17.944Z" },
{ url = "https://files.pythonhosted.org/packages/7e/7b/6ceeb1cc90e193862f444ebe373d8fdf613f0a82572dde03fb10734c6c71/pydantic_core-2.46.4-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5855698a4856556d86e8e6cd8434bc3ac0314ee8e12089ae0e143f64c6256e4e", size = 2179782, upload-time = "2026-05-06T13:40:32.618Z" },
{ url = "https://files.pythonhosted.org/packages/5a/f2/c8d7773ede6af08036423a00ae0ceffce266c3c52a096c435d68c896083f/pydantic_core-2.46.4-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:cbaf13819775b7f769bf4a1f066cb6df7a28d4480081a589828ef190226881cd", size = 2188782, upload-time = "2026-05-06T13:36:51.018Z" },
{ url = "https://files.pythonhosted.org/packages/59/31/0c864784e31f09f05cdd87606f08923b9c9e7f6e51dd27f20f62f975ce9f/pydantic_core-2.46.4-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:633147d34cf4550417f12e2b1a0383973bdf5cdfde212cb09e9a581cf10820be", size = 2328334, upload-time = "2026-05-06T13:40:37.764Z" },
{ url = "https://files.pythonhosted.org/packages/c2/eb/4f6c8a41efa30baa755590f4141abf3a8c370fab610915733e74134a7270/pydantic_core-2.46.4-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:82cf5301172168103724d49a1444d3378cb20cdee30b116a1bd6031236298a5d", size = 2372986, upload-time = "2026-05-06T13:39:34.152Z" },
{ url = "https://files.pythonhosted.org/packages/5b/24/b375a480d53113860c299764bfe9f349a3dc9108b3adc0d7f0d786492ebf/pydantic_core-2.46.4-cp313-cp313-win32.whl", hash = "sha256:9fa8ae11da9e2b3126c6426f147e0fba88d96d65921799bb30c6abd1cb2c97fb", size = 1973693, upload-time = "2026-05-06T13:37:55.072Z" },
{ url = "https://files.pythonhosted.org/packages/7e/e8/cff247591966f2d22ec8c003cd7587e27b7ba7b81ab2fb888e3ab75dc285/pydantic_core-2.46.4-cp313-cp313-win_amd64.whl", hash = "sha256:6b3ace8194b0e5204818c92802dcdca7fc6d88aabbb799d7c795540d9cd6d292", size = 2071819, upload-time = "2026-05-06T13:38:49.139Z" },
{ url = "https://files.pythonhosted.org/packages/c6/1a/f4aee670d5670e9e148e0c82c7db98d780be566c6e6a97ee8035528ca0b3/pydantic_core-2.46.4-cp313-cp313-win_arm64.whl", hash = "sha256:184c081504d17f1c1066e430e117142b2c77d9448a97f7b65c6ac9fd9aee238d", size = 2027411, upload-time = "2026-05-06T13:40:45.796Z" },
{ url = "https://files.pythonhosted.org/packages/8d/74/228a26ddad29c6672b805d9fd78e8d251cd04004fa7eed0e622096cd0250/pydantic_core-2.46.4-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:428e04521a40150c85216fc8b85e8d39fece235a9cf5e383761238c7fa9b96fb", size = 2102079, upload-time = "2026-05-06T13:38:41.019Z" },
{ url = "https://files.pythonhosted.org/packages/ad/1f/8970b150a4b4365623ae00fc88603491f763c627311ae8031e3111356d6e/pydantic_core-2.46.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:23ace664830ee0bfe014a0c7bc248b1f7f25ed7ad103852c317624a1083af462", size = 1952179, upload-time = "2026-05-06T13:36:59.812Z" },
{ url = "https://files.pythonhosted.org/packages/95/30/5211a831ae054928054b2f79731661087a2bc5c01e825c672b3a4a8f1b3e/pydantic_core-2.46.4-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ce5c1d2a8b27468f433ca974829c44060b8097eedc39933e3c206a90ee49c4a9", size = 1978926, upload-time = "2026-05-06T13:37:39.933Z" },
{ url = "https://files.pythonhosted.org/packages/57/e9/689668733b1eb67adeef047db3c2e8788fcf65a7fd9c9e2b46b7744fe245/pydantic_core-2.46.4-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:7283d57845ecf5a163403eb0702dfc220cc4fbdd18919cb5ccea4f95ee1cdab4", size = 2046785, upload-time = "2026-05-06T13:38:01.995Z" },
{ url = "https://files.pythonhosted.org/packages/60/d9/6715260422ff50a2109878fd24d948a6c3446bb2664f34ee78cd972b3acd/pydantic_core-2.46.4-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8daafc69c93ee8a0204506a3b6b30f586ef54028f52aeeeb5c4cfc5184fd5914", size = 2228733, upload-time = "2026-05-06T13:40:50.371Z" },
{ url = "https://files.pythonhosted.org/packages/18/ae/fdb2f64316afca925640f8e70bb1a564b0ec2721c1389e25b8eb4bf9a299/pydantic_core-2.46.4-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cd2213145bcc2ba85884d0ac63d222fece9209678f77b9b4d76f054c561adb28", size = 2307534, upload-time = "2026-05-06T13:37:21.531Z" },
{ url = "https://files.pythonhosted.org/packages/89/1d/8eff589b45bb8190a9d12c49cfad0f176a5cbd1534908a6b5125e2886239/pydantic_core-2.46.4-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7a5f930472650a82629163023e630d160863fce524c616f4e5186e5de9d9a49b", size = 2099732, upload-time = "2026-05-06T13:39:31.942Z" },
{ url = "https://files.pythonhosted.org/packages/06/d5/ee5a3366637fee41dee51a1fc91562dcf12ddbc68fda34e6b253da2324bb/pydantic_core-2.46.4-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:c1b3f518abeca3aa13c712fd202306e145abf59a18b094a6bafb2d2bbf59192c", size = 2129627, upload-time = "2026-05-06T13:37:25.033Z" },
{ url = "https://files.pythonhosted.org/packages/94/33/2414be571d2c6a6c4d08be21f9292b6d3fdb08949a97b6dfe985017821db/pydantic_core-2.46.4-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1a7dd0b3ee80d90150e3495a3a13ac34dbcbfd4f012996a6a1d8900e91b5c0fb", size = 2179141, upload-time = "2026-05-06T13:37:14.046Z" },
{ url = "https://files.pythonhosted.org/packages/7b/79/7daa95be995be0eecc4cf75064cb33f9bbbfe3fe0158caf2f0d4a996a5c7/pydantic_core-2.46.4-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:3fb702cd90b0446a3a1c5e470bfa0dd23c0233b676a9099ddcc964fa6ca13898", size = 2184325, upload-time = "2026-05-06T13:36:53.615Z" },
{ url = "https://files.pythonhosted.org/packages/9f/cb/d0a382f5c0de8a222dc61c65348e0ce831b1f68e0a018450d31c2cace3a5/pydantic_core-2.46.4-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:b8458003118a712e66286df6a707db01c52c0f52f7db8e4a38f0da1d3b94fc4e", size = 2323990, upload-time = "2026-05-06T13:40:29.971Z" },
{ url = "https://files.pythonhosted.org/packages/05/db/d9ba624cc4a5aced1598e88c04fdbd8310c8a69b9d38b9a3d39ce3a61ed7/pydantic_core-2.46.4-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:372429a130e469c9cd698925ce5fc50940b7a1336b0d82038e63d5bbc4edc519", size = 2369978, upload-time = "2026-05-06T13:37:23.027Z" },
{ url = "https://files.pythonhosted.org/packages/f2/20/d15df15ba918c423461905802bfd2981c3af0bfa0e40d05e13edbfa48bc3/pydantic_core-2.46.4-cp314-cp314-win32.whl", hash = "sha256:85bb3611ff1802f3ee7fdd7dbff26b56f343fb432d57a4728fdd49b6ef35e2f4", size = 1966354, upload-time = "2026-05-06T13:38:03.499Z" },
{ url = "https://files.pythonhosted.org/packages/fc/b6/6b8de4c0a7d7ab3004c439c80c5c1e0a3e8d78bbae19379b01960383d9e5/pydantic_core-2.46.4-cp314-cp314-win_amd64.whl", hash = "sha256:811ff8e9c313ab425368bcbb36e5c4ebd7108c2bbf4e4089cfbb0b01eff63fac", size = 2072238, upload-time = "2026-05-06T13:39:40.807Z" },
{ url = "https://files.pythonhosted.org/packages/32/36/51eb763beec1f4cf59b1db243a7dcc39cbb41230f050a09b9d69faaf0a48/pydantic_core-2.46.4-cp314-cp314-win_arm64.whl", hash = "sha256:bfec22eab3c8cc2ceec0248aec886624116dc079afa027ecc8ad4a7e62010f8a", size = 2018251, upload-time = "2026-05-06T13:37:26.72Z" },
{ url = "https://files.pythonhosted.org/packages/e8/91/855af51d625b23aa987116a19e231d2aaef9c4a415273ddc189b79a45fee/pydantic_core-2.46.4-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:af8244b2bef6aaad6d92cda81372de7f8c8d36c9f0c3ea36e827c60e7d9467a0", size = 2099593, upload-time = "2026-05-06T13:39:47.682Z" },
{ url = "https://files.pythonhosted.org/packages/fb/1b/8784a54c65edb5f49f0a14d6977cf1b209bba85a4c77445b255c2de58ab3/pydantic_core-2.46.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:5a4330cdbc57162e4b3aa303f588ba752257694c9c9be3e7ebb11b4aca659b5d", size = 1935226, upload-time = "2026-05-06T13:40:40.428Z" },
{ url = "https://files.pythonhosted.org/packages/e8/e7/1955d28d1afc56dd4b3ad7cc0cf39df1b9852964cf16e5d13912756d6d6b/pydantic_core-2.46.4-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:29c61fc04a3d840155ff08e475a04809278972fe6aef51e2720554e96367e34b", size = 1974605, upload-time = "2026-05-06T13:37:32.029Z" },
{ url = "https://files.pythonhosted.org/packages/93/e2/3fedbf0ba7a22850e6e9fd78117f1c0f10f950182344d8a6c535d468fdd8/pydantic_core-2.46.4-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c50f2528cf200c5eed56faf3f4e22fcd5f38c157a8b78576e6ba3168ec35f000", size = 2030777, upload-time = "2026-05-06T13:38:55.239Z" },
{ url = "https://files.pythonhosted.org/packages/f8/61/46be275fcaaba0b4f5b9669dd852267ce1ff616592dccf7a7845588df091/pydantic_core-2.46.4-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0cbe8b01f948de4286c74cdd6c667aceb38f5c1e26f0693b3983d9d74887c65e", size = 2236641, upload-time = "2026-05-06T13:37:08.096Z" },
{ url = "https://files.pythonhosted.org/packages/60/db/12e93e46a8bac9988be3c016860f83293daea8c716c029c9ace279036f2f/pydantic_core-2.46.4-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:617d7e2ca7dcb8c5cf6bcb8c59b8832c94b36196bbf1cbd1bfb56ed341905edd", size = 2286404, upload-time = "2026-05-06T13:40:20.221Z" },
{ url = "https://files.pythonhosted.org/packages/e2/4a/4d8b19008f38d31c53b8219cfedc2e3d5de5fe99d90076b7e767de29274f/pydantic_core-2.46.4-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7027560ee92211647d0d34e3f7cd6f50da56399d26a9c8ad0da286d3869a53f3", size = 2109219, upload-time = "2026-05-06T13:38:12.153Z" },
{ url = "https://files.pythonhosted.org/packages/88/70/3cbc40978fefb7bb09c6708d40d4ad1a5d70fd7213c3d17f971de868ec1f/pydantic_core-2.46.4-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:f99626688942fb746e545232e7726926f3be91b5975f8b55327665fafda991c7", size = 2110594, upload-time = "2026-05-06T13:40:02.971Z" },
{ url = "https://files.pythonhosted.org/packages/9d/20/b8d36736216e29491125531685b2f9e61aa5b4b2599893f8268551da3338/pydantic_core-2.46.4-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fc3e9034a63de20e15e8ade85358bc6efc614008cab72898b4b4952bea0509ff", size = 2159542, upload-time = "2026-05-06T13:39:27.506Z" },
{ url = "https://files.pythonhosted.org/packages/1d/a2/367df868eb584dacf6bf82a389272406d7178e301c4ac82545ab98bc2dd9/pydantic_core-2.46.4-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:97e7cf2be5c77b7d1a9713a05605d49460d02c6078d38d8bef3cbe323c548424", size = 2168146, upload-time = "2026-05-06T13:38:31.93Z" },
{ url = "https://files.pythonhosted.org/packages/c1/b8/4460f77f7e201893f649a29ab355dddd3beee8a97bcb1a320db414f9a06e/pydantic_core-2.46.4-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:3bf92c5d0e00fefaab325a4d27828fe6b6e2a21848686b5b60d2d9eeb09d76c6", size = 2306309, upload-time = "2026-05-06T13:37:44.717Z" },
{ url = "https://files.pythonhosted.org/packages/64/c4/be2639293acd87dc8ddbcec41a73cee9b2ebf996fe6d892a1a74e88ad3f7/pydantic_core-2.46.4-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:3ecbc122d18468d06ca279dc26a8c2e2d5acb10943bb35e36ae92096dc3b5565", size = 2369736, upload-time = "2026-05-06T13:37:05.645Z" },
{ url = "https://files.pythonhosted.org/packages/30/a6/9f9f380dbb301f67023bf8f707aaa75daadf84f7152d95c410fd7e81d994/pydantic_core-2.46.4-cp314-cp314t-win32.whl", hash = "sha256:e846ae7835bf0703ae43f534ab79a867146dadd59dc9ca5c8b53d5c8f7c9ef02", size = 1955575, upload-time = "2026-05-06T13:38:51.116Z" },
{ url = "https://files.pythonhosted.org/packages/40/1f/f1eb9eb350e795d1af8586289746f5c5677d16043040d63710e22abc43c9/pydantic_core-2.46.4-cp314-cp314t-win_amd64.whl", hash = "sha256:2108ba5c1c1eca18030634489dc544844144ee36357f2f9f780b93e7ddbb44b5", size = 2051624, upload-time = "2026-05-06T13:38:21.672Z" },
{ url = "https://files.pythonhosted.org/packages/f6/d2/42dd53d0a85c27606f316d3aa5d2869c4e8470a5ed6dec30e4a1abe19192/pydantic_core-2.46.4-cp314-cp314t-win_arm64.whl", hash = "sha256:4fcbe087dbc2068af7eda3aa87634eba216dbda64d1ae73c8684b621d33f6596", size = 2017325, upload-time = "2026-05-06T13:40:52.723Z" },
{ url = "https://files.pythonhosted.org/packages/9d/1d/8987ad40f65ae1432753072f214fb5c74fe47ffbd0698bb9cbbb585664f8/pydantic_core-2.46.4-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:1d8ba486450b14f3b1d63bc521d410ec7565e52f887b9fb671791886436a42f7", size = 2095527, upload-time = "2026-05-06T13:39:52.283Z" },
{ url = "https://files.pythonhosted.org/packages/64/d3/84c282a7eee1d3ac4c0377546ef5a1ea436ce26840d9ac3b7ed54a377507/pydantic_core-2.46.4-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:3009f12e4e90b7f88b4f9adb1b0c4a3d58fe7820f3238c190047209d148026df", size = 1936024, upload-time = "2026-05-06T13:40:15.671Z" },
{ url = "https://files.pythonhosted.org/packages/d7/ca/eac61596cdeb4d7e174d3dc0bd8a6238f14f75f97a24e7b7db4c7e7340a0/pydantic_core-2.46.4-graalpy312-graalpy250_312_native-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ad785e92e6dc634c21555edc8bd6b64957ab844541bcb96a1366c202951ae526", size = 1990696, upload-time = "2026-05-06T13:38:34.717Z" },
{ url = "https://files.pythonhosted.org/packages/fa/c3/7c8b240552251faf6b3a957db200fcfbbcec36763c050428b601e0c9b83b/pydantic_core-2.46.4-graalpy312-graalpy250_312_native-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:00c603d540afdd6b80eb39f078f33ebd46211f02f33e34a32d9f053bba711de0", size = 2147590, upload-time = "2026-05-06T13:39:29.883Z" },
]
[[package]]
name = "pygments"
version = "2.20.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
]
[[package]]
name = "pytest"
version = "9.1.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "colorama", marker = "sys_platform == 'win32'" },
{ name = "iniconfig" },
{ name = "packaging" },
{ name = "pluggy" },
{ name = "pygments" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" },
]
[[package]]
name = "typing-extensions"
version = "4.16.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" },
]
[[package]]
name = "typing-inspection"
version = "0.4.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" },
]
[[package]]
name = "zstandard"
version = "0.25.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/fd/aa/3e0508d5a5dd96529cdc5a97011299056e14c6505b678fd58938792794b1/zstandard-0.25.0.tar.gz", hash = "sha256:7713e1179d162cf5c7906da876ec2ccb9c3a9dcbdffef0cc7f70c3667a205f0b", size = 711513, upload-time = "2025-09-14T22:15:54.002Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/82/fc/f26eb6ef91ae723a03e16eddb198abcfce2bc5a42e224d44cc8b6765e57e/zstandard-0.25.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7b3c3a3ab9daa3eed242d6ecceead93aebbb8f5f84318d82cee643e019c4b73b", size = 795738, upload-time = "2025-09-14T22:16:56.237Z" },
{ url = "https://files.pythonhosted.org/packages/aa/1c/d920d64b22f8dd028a8b90e2d756e431a5d86194caa78e3819c7bf53b4b3/zstandard-0.25.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:913cbd31a400febff93b564a23e17c3ed2d56c064006f54efec210d586171c00", size = 640436, upload-time = "2025-09-14T22:16:57.774Z" },
{ url = "https://files.pythonhosted.org/packages/53/6c/288c3f0bd9fcfe9ca41e2c2fbfd17b2097f6af57b62a81161941f09afa76/zstandard-0.25.0-cp312-cp312-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:011d388c76b11a0c165374ce660ce2c8efa8e5d87f34996aa80f9c0816698b64", size = 5343019, upload-time = "2025-09-14T22:16:59.302Z" },
{ url = "https://files.pythonhosted.org/packages/1e/15/efef5a2f204a64bdb5571e6161d49f7ef0fffdbca953a615efbec045f60f/zstandard-0.25.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dffecc361d079bb48d7caef5d673c88c8988d3d33fb74ab95b7ee6da42652ea", size = 5063012, upload-time = "2025-09-14T22:17:01.156Z" },
{ url = "https://files.pythonhosted.org/packages/b7/37/a6ce629ffdb43959e92e87ebdaeebb5ac81c944b6a75c9c47e300f85abdf/zstandard-0.25.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7149623bba7fdf7e7f24312953bcf73cae103db8cae49f8154dd1eadc8a29ecb", size = 5394148, upload-time = "2025-09-14T22:17:03.091Z" },
{ url = "https://files.pythonhosted.org/packages/e3/79/2bf870b3abeb5c070fe2d670a5a8d1057a8270f125ef7676d29ea900f496/zstandard-0.25.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6a573a35693e03cf1d67799fd01b50ff578515a8aeadd4595d2a7fa9f3ec002a", size = 5451652, upload-time = "2025-09-14T22:17:04.979Z" },
{ url = "https://files.pythonhosted.org/packages/53/60/7be26e610767316c028a2cbedb9a3beabdbe33e2182c373f71a1c0b88f36/zstandard-0.25.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5a56ba0db2d244117ed744dfa8f6f5b366e14148e00de44723413b2f3938a902", size = 5546993, upload-time = "2025-09-14T22:17:06.781Z" },
{ url = "https://files.pythonhosted.org/packages/85/c7/3483ad9ff0662623f3648479b0380d2de5510abf00990468c286c6b04017/zstandard-0.25.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:10ef2a79ab8e2974e2075fb984e5b9806c64134810fac21576f0668e7ea19f8f", size = 5046806, upload-time = "2025-09-14T22:17:08.415Z" },
{ url = "https://files.pythonhosted.org/packages/08/b3/206883dd25b8d1591a1caa44b54c2aad84badccf2f1de9e2d60a446f9a25/zstandard-0.25.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aaf21ba8fb76d102b696781bddaa0954b782536446083ae3fdaa6f16b25a1c4b", size = 5576659, upload-time = "2025-09-14T22:17:10.164Z" },
{ url = "https://files.pythonhosted.org/packages/9d/31/76c0779101453e6c117b0ff22565865c54f48f8bd807df2b00c2c404b8e0/zstandard-0.25.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:1869da9571d5e94a85a5e8d57e4e8807b175c9e4a6294e3b66fa4efb074d90f6", size = 4953933, upload-time = "2025-09-14T22:17:11.857Z" },
{ url = "https://files.pythonhosted.org/packages/18/e1/97680c664a1bf9a247a280a053d98e251424af51f1b196c6d52f117c9720/zstandard-0.25.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:809c5bcb2c67cd0ed81e9229d227d4ca28f82d0f778fc5fea624a9def3963f91", size = 5268008, upload-time = "2025-09-14T22:17:13.627Z" },
{ url = "https://files.pythonhosted.org/packages/1e/73/316e4010de585ac798e154e88fd81bb16afc5c5cb1a72eeb16dd37e8024a/zstandard-0.25.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f27662e4f7dbf9f9c12391cb37b4c4c3cb90ffbd3b1fb9284dadbbb8935fa708", size = 5433517, upload-time = "2025-09-14T22:17:16.103Z" },
{ url = "https://files.pythonhosted.org/packages/5b/60/dd0f8cfa8129c5a0ce3ea6b7f70be5b33d2618013a161e1ff26c2b39787c/zstandard-0.25.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:99c0c846e6e61718715a3c9437ccc625de26593fea60189567f0118dc9db7512", size = 5814292, upload-time = "2025-09-14T22:17:17.827Z" },
{ url = "https://files.pythonhosted.org/packages/fc/5f/75aafd4b9d11b5407b641b8e41a57864097663699f23e9ad4dbb91dc6bfe/zstandard-0.25.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:474d2596a2dbc241a556e965fb76002c1ce655445e4e3bf38e5477d413165ffa", size = 5360237, upload-time = "2025-09-14T22:17:19.954Z" },
{ url = "https://files.pythonhosted.org/packages/ff/8d/0309daffea4fcac7981021dbf21cdb2e3427a9e76bafbcdbdf5392ff99a4/zstandard-0.25.0-cp312-cp312-win32.whl", hash = "sha256:23ebc8f17a03133b4426bcc04aabd68f8236eb78c3760f12783385171b0fd8bd", size = 436922, upload-time = "2025-09-14T22:17:24.398Z" },
{ url = "https://files.pythonhosted.org/packages/79/3b/fa54d9015f945330510cb5d0b0501e8253c127cca7ebe8ba46a965df18c5/zstandard-0.25.0-cp312-cp312-win_amd64.whl", hash = "sha256:ffef5a74088f1e09947aecf91011136665152e0b4b359c42be3373897fb39b01", size = 506276, upload-time = "2025-09-14T22:17:21.429Z" },
{ url = "https://files.pythonhosted.org/packages/ea/6b/8b51697e5319b1f9ac71087b0af9a40d8a6288ff8025c36486e0c12abcc4/zstandard-0.25.0-cp312-cp312-win_arm64.whl", hash = "sha256:181eb40e0b6a29b3cd2849f825e0fa34397f649170673d385f3598ae17cca2e9", size = 462679, upload-time = "2025-09-14T22:17:23.147Z" },
{ url = "https://files.pythonhosted.org/packages/35/0b/8df9c4ad06af91d39e94fa96cc010a24ac4ef1378d3efab9223cc8593d40/zstandard-0.25.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ec996f12524f88e151c339688c3897194821d7f03081ab35d31d1e12ec975e94", size = 795735, upload-time = "2025-09-14T22:17:26.042Z" },
{ url = "https://files.pythonhosted.org/packages/3f/06/9ae96a3e5dcfd119377ba33d4c42a7d89da1efabd5cb3e366b156c45ff4d/zstandard-0.25.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a1a4ae2dec3993a32247995bdfe367fc3266da832d82f8438c8570f989753de1", size = 640440, upload-time = "2025-09-14T22:17:27.366Z" },
{ url = "https://files.pythonhosted.org/packages/d9/14/933d27204c2bd404229c69f445862454dcc101cd69ef8c6068f15aaec12c/zstandard-0.25.0-cp313-cp313-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:e96594a5537722fdfb79951672a2a63aec5ebfb823e7560586f7484819f2a08f", size = 5343070, upload-time = "2025-09-14T22:17:28.896Z" },
{ url = "https://files.pythonhosted.org/packages/6d/db/ddb11011826ed7db9d0e485d13df79b58586bfdec56e5c84a928a9a78c1c/zstandard-0.25.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:bfc4e20784722098822e3eee42b8e576b379ed72cca4a7cb856ae733e62192ea", size = 5063001, upload-time = "2025-09-14T22:17:31.044Z" },
{ url = "https://files.pythonhosted.org/packages/db/00/87466ea3f99599d02a5238498b87bf84a6348290c19571051839ca943777/zstandard-0.25.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:457ed498fc58cdc12fc48f7950e02740d4f7ae9493dd4ab2168a47c93c31298e", size = 5394120, upload-time = "2025-09-14T22:17:32.711Z" },
{ url = "https://files.pythonhosted.org/packages/2b/95/fc5531d9c618a679a20ff6c29e2b3ef1d1f4ad66c5e161ae6ff847d102a9/zstandard-0.25.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:fd7a5004eb1980d3cefe26b2685bcb0b17989901a70a1040d1ac86f1d898c551", size = 5451230, upload-time = "2025-09-14T22:17:34.41Z" },
{ url = "https://files.pythonhosted.org/packages/63/4b/e3678b4e776db00f9f7b2fe58e547e8928ef32727d7a1ff01dea010f3f13/zstandard-0.25.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8e735494da3db08694d26480f1493ad2cf86e99bdd53e8e9771b2752a5c0246a", size = 5547173, upload-time = "2025-09-14T22:17:36.084Z" },
{ url = "https://files.pythonhosted.org/packages/4e/d5/ba05ed95c6b8ec30bd468dfeab20589f2cf709b5c940483e31d991f2ca58/zstandard-0.25.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3a39c94ad7866160a4a46d772e43311a743c316942037671beb264e395bdd611", size = 5046736, upload-time = "2025-09-14T22:17:37.891Z" },
{ url = "https://files.pythonhosted.org/packages/50/d5/870aa06b3a76c73eced65c044b92286a3c4e00554005ff51962deef28e28/zstandard-0.25.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:172de1f06947577d3a3005416977cce6168f2261284c02080e7ad0185faeced3", size = 5576368, upload-time = "2025-09-14T22:17:40.206Z" },
{ url = "https://files.pythonhosted.org/packages/5d/35/398dc2ffc89d304d59bc12f0fdd931b4ce455bddf7038a0a67733a25f550/zstandard-0.25.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3c83b0188c852a47cd13ef3bf9209fb0a77fa5374958b8c53aaa699398c6bd7b", size = 4954022, upload-time = "2025-09-14T22:17:41.879Z" },
{ url = "https://files.pythonhosted.org/packages/9a/5c/36ba1e5507d56d2213202ec2b05e8541734af5f2ce378c5d1ceaf4d88dc4/zstandard-0.25.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:1673b7199bbe763365b81a4f3252b8e80f44c9e323fc42940dc8843bfeaf9851", size = 5267889, upload-time = "2025-09-14T22:17:43.577Z" },
{ url = "https://files.pythonhosted.org/packages/70/e8/2ec6b6fb7358b2ec0113ae202647ca7c0e9d15b61c005ae5225ad0995df5/zstandard-0.25.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:0be7622c37c183406f3dbf0cba104118eb16a4ea7359eeb5752f0794882fc250", size = 5433952, upload-time = "2025-09-14T22:17:45.271Z" },
{ url = "https://files.pythonhosted.org/packages/7b/01/b5f4d4dbc59ef193e870495c6f1275f5b2928e01ff5a81fecb22a06e22fb/zstandard-0.25.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:5f5e4c2a23ca271c218ac025bd7d635597048b366d6f31f420aaeb715239fc98", size = 5814054, upload-time = "2025-09-14T22:17:47.08Z" },
{ url = "https://files.pythonhosted.org/packages/b2/e5/fbd822d5c6f427cf158316d012c5a12f233473c2f9c5fe5ab1ae5d21f3d8/zstandard-0.25.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4f187a0bb61b35119d1926aee039524d1f93aaf38a9916b8c4b78ac8514a0aaf", size = 5360113, upload-time = "2025-09-14T22:17:48.893Z" },
{ url = "https://files.pythonhosted.org/packages/8e/e0/69a553d2047f9a2c7347caa225bb3a63b6d7704ad74610cb7823baa08ed7/zstandard-0.25.0-cp313-cp313-win32.whl", hash = "sha256:7030defa83eef3e51ff26f0b7bfb229f0204b66fe18e04359ce3474ac33cbc09", size = 436936, upload-time = "2025-09-14T22:17:52.658Z" },
{ url = "https://files.pythonhosted.org/packages/d9/82/b9c06c870f3bd8767c201f1edbdf9e8dc34be5b0fbc5682c4f80fe948475/zstandard-0.25.0-cp313-cp313-win_amd64.whl", hash = "sha256:1f830a0dac88719af0ae43b8b2d6aef487d437036468ef3c2ea59c51f9d55fd5", size = 506232, upload-time = "2025-09-14T22:17:50.402Z" },
{ url = "https://files.pythonhosted.org/packages/d4/57/60c3c01243bb81d381c9916e2a6d9e149ab8627c0c7d7abb2d73384b3c0c/zstandard-0.25.0-cp313-cp313-win_arm64.whl", hash = "sha256:85304a43f4d513f5464ceb938aa02c1e78c2943b29f44a750b48b25ac999a049", size = 462671, upload-time = "2025-09-14T22:17:51.533Z" },
{ url = "https://files.pythonhosted.org/packages/3d/5c/f8923b595b55fe49e30612987ad8bf053aef555c14f05bb659dd5dbe3e8a/zstandard-0.25.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:e29f0cf06974c899b2c188ef7f783607dbef36da4c242eb6c82dcd8b512855e3", size = 795887, upload-time = "2025-09-14T22:17:54.198Z" },
{ url = "https://files.pythonhosted.org/packages/8d/09/d0a2a14fc3439c5f874042dca72a79c70a532090b7ba0003be73fee37ae2/zstandard-0.25.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:05df5136bc5a011f33cd25bc9f506e7426c0c9b3f9954f056831ce68f3b6689f", size = 640658, upload-time = "2025-09-14T22:17:55.423Z" },
{ url = "https://files.pythonhosted.org/packages/5d/7c/8b6b71b1ddd517f68ffb55e10834388d4f793c49c6b83effaaa05785b0b4/zstandard-0.25.0-cp314-cp314-manylinux2010_i686.manylinux_2_12_i686.manylinux_2_28_i686.whl", hash = "sha256:f604efd28f239cc21b3adb53eb061e2a205dc164be408e553b41ba2ffe0ca15c", size = 5379849, upload-time = "2025-09-14T22:17:57.372Z" },
{ url = "https://files.pythonhosted.org/packages/a4/86/a48e56320d0a17189ab7a42645387334fba2200e904ee47fc5a26c1fd8ca/zstandard-0.25.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:223415140608d0f0da010499eaa8ccdb9af210a543fac54bce15babbcfc78439", size = 5058095, upload-time = "2025-09-14T22:17:59.498Z" },
{ url = "https://files.pythonhosted.org/packages/f8/ad/eb659984ee2c0a779f9d06dbfe45e2dc39d99ff40a319895df2d3d9a48e5/zstandard-0.25.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2e54296a283f3ab5a26fc9b8b5d4978ea0532f37b231644f367aa588930aa043", size = 5551751, upload-time = "2025-09-14T22:18:01.618Z" },
{ url = "https://files.pythonhosted.org/packages/61/b3/b637faea43677eb7bd42ab204dfb7053bd5c4582bfe6b1baefa80ac0c47b/zstandard-0.25.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ca54090275939dc8ec5dea2d2afb400e0f83444b2fc24e07df7fdef677110859", size = 6364818, upload-time = "2025-09-14T22:18:03.769Z" },
{ url = "https://files.pythonhosted.org/packages/31/dc/cc50210e11e465c975462439a492516a73300ab8caa8f5e0902544fd748b/zstandard-0.25.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e09bb6252b6476d8d56100e8147b803befa9a12cea144bbe629dd508800d1ad0", size = 5560402, upload-time = "2025-09-14T22:18:05.954Z" },
{ url = "https://files.pythonhosted.org/packages/c9/ae/56523ae9c142f0c08efd5e868a6da613ae76614eca1305259c3bf6a0ed43/zstandard-0.25.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a9ec8c642d1ec73287ae3e726792dd86c96f5681eb8df274a757bf62b750eae7", size = 4955108, upload-time = "2025-09-14T22:18:07.68Z" },
{ url = "https://files.pythonhosted.org/packages/98/cf/c899f2d6df0840d5e384cf4c4121458c72802e8bda19691f3b16619f51e9/zstandard-0.25.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:a4089a10e598eae6393756b036e0f419e8c1d60f44a831520f9af41c14216cf2", size = 5269248, upload-time = "2025-09-14T22:18:09.753Z" },
{ url = "https://files.pythonhosted.org/packages/1b/c0/59e912a531d91e1c192d3085fc0f6fb2852753c301a812d856d857ea03c6/zstandard-0.25.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:f67e8f1a324a900e75b5e28ffb152bcac9fbed1cc7b43f99cd90f395c4375344", size = 5430330, upload-time = "2025-09-14T22:18:11.966Z" },
{ url = "https://files.pythonhosted.org/packages/a0/1d/7e31db1240de2df22a58e2ea9a93fc6e38cc29353e660c0272b6735d6669/zstandard-0.25.0-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:9654dbc012d8b06fc3d19cc825af3f7bf8ae242226df5f83936cb39f5fdc846c", size = 5811123, upload-time = "2025-09-14T22:18:13.907Z" },
{ url = "https://files.pythonhosted.org/packages/f6/49/fac46df5ad353d50535e118d6983069df68ca5908d4d65b8c466150a4ff1/zstandard-0.25.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4203ce3b31aec23012d3a4cf4a2ed64d12fea5269c49aed5e4c3611b938e4088", size = 5359591, upload-time = "2025-09-14T22:18:16.465Z" },
{ url = "https://files.pythonhosted.org/packages/c2/38/f249a2050ad1eea0bb364046153942e34abba95dd5520af199aed86fbb49/zstandard-0.25.0-cp314-cp314-win32.whl", hash = "sha256:da469dc041701583e34de852d8634703550348d5822e66a0c827d39b05365b12", size = 444513, upload-time = "2025-09-14T22:18:20.61Z" },
{ url = "https://files.pythonhosted.org/packages/3a/43/241f9615bcf8ba8903b3f0432da069e857fc4fd1783bd26183db53c4804b/zstandard-0.25.0-cp314-cp314-win_amd64.whl", hash = "sha256:c19bcdd826e95671065f8692b5a4aa95c52dc7a02a4c5a0cac46deb879a017a2", size = 516118, upload-time = "2025-09-14T22:18:17.849Z" },
{ url = "https://files.pythonhosted.org/packages/f0/ef/da163ce2450ed4febf6467d77ccb4cd52c4c30ab45624bad26ca0a27260c/zstandard-0.25.0-cp314-cp314-win_arm64.whl", hash = "sha256:d7541afd73985c630bafcd6338d2518ae96060075f9463d7dc14cfb33514383d", size = 476940, upload-time = "2025-09-14T22:18:19.088Z" },
]

View File

@@ -0,0 +1,54 @@
"""Strip packaged Unix executables without modifying their build outputs.
Call only on package copies of first-party binaries. Prebuilt release inputs
may already be signed, and resources such as bwrap have integrity hashes that
must survive staging. Windows MSVC symbols live in separate PDB files.
"""
import platform
import shutil
import subprocess
from pathlib import Path
from .targets import TargetSpec
from .targets import normalize_machine
def strip_binary(binary: Path, spec: TargetSpec, *, tool: str | None = None) -> None:
if spec.is_windows:
return
if spec.is_linux:
# A host GNU strip may not understand a cross-compiled ELF architecture.
# LLVM supports both packaged Linux architectures from any host.
machine = spec.target.split("-", 1)[0]
command = (
tool
or shutil.which("llvm-strip")
or shutil.which(f"{machine}-linux-gnu-strip")
)
if (
command is None
and platform.system() == "Linux"
and normalize_machine(platform.machine()) == machine
):
command = shutil.which("strip")
if command is None:
raise RuntimeError(
f"No strip tool for {spec.target}; install llvm-strip or pass "
"--strip-tool /path/to/target-strip (or --strip none to keep symbols)"
)
args = [command, "--strip-debug", "--strip-unneeded"]
else:
if tool is None and platform.system() != "Darwin":
raise RuntimeError(
"Stripping a macOS binary requires a Mach-O strip tool; pass "
"--strip-tool /path/to/strip (or --strip none to keep symbols)"
)
# Match the release pipeline. Apple's strip also updates the ad-hoc
# code signature on Cargo-built ARM64 executables so they remain runnable.
args = [tool] if tool is not None else ["xcrun", "strip"]
args.extend(("-S", "-x"))
print(f"Stripping package executable {binary}")
subprocess.run([*args, str(binary)], check=True)

View File

@@ -0,0 +1,170 @@
"""Supported package targets and default binary discovery."""
import os
import platform
import stat
from dataclasses import dataclass
from pathlib import Path
_repo_root = os.environ.get("CODEX_REPO_ROOT")
if _repo_root is None:
raise RuntimeError(
"CODEX_REPO_ROOT must point to the repository root; "
"run `just assemble-codex-package` to set it automatically"
)
REPO_ROOT = Path(_repo_root)
@dataclass(frozen=True)
class TargetSpec:
target: str
is_windows: bool
is_linux: bool
dotslash_platform: str
@property
def exe_suffix(self) -> str:
return ".exe" if self.is_windows else ""
@property
def rg_name(self) -> str:
return f"rg{self.exe_suffix}"
@dataclass(frozen=True)
class PackageVariant:
name: str
cargo_bin: str
executable_stem: str
def entrypoint_name(self, spec: TargetSpec) -> str:
return f"{self.executable_stem}{spec.exe_suffix}"
@dataclass(frozen=True)
class PackageInputs:
entrypoint_bin: Path
code_mode_host_bin: Path
exec_server_bin: Path
rg_bin: Path
bwrap_bin: Path | None
codex_command_runner_bin: Path | None
codex_windows_sandbox_setup_bin: Path | None
PACKAGE_VARIANTS: dict[str, PackageVariant] = {
"codex": PackageVariant(
name="codex",
cargo_bin="codex",
executable_stem="codex",
),
"codex-app-server": PackageVariant(
name="codex-app-server",
cargo_bin="codex-app-server",
executable_stem="codex-app-server",
),
}
TARGET_SPECS: dict[str, TargetSpec] = {
"x86_64-unknown-linux-gnu": TargetSpec(
target="x86_64-unknown-linux-gnu",
is_windows=False,
is_linux=True,
dotslash_platform="linux-x86_64",
),
"x86_64-unknown-linux-musl": TargetSpec(
target="x86_64-unknown-linux-musl",
is_windows=False,
is_linux=True,
dotslash_platform="linux-x86_64",
),
"aarch64-unknown-linux-gnu": TargetSpec(
target="aarch64-unknown-linux-gnu",
is_windows=False,
is_linux=True,
dotslash_platform="linux-aarch64",
),
"aarch64-unknown-linux-musl": TargetSpec(
target="aarch64-unknown-linux-musl",
is_windows=False,
is_linux=True,
dotslash_platform="linux-aarch64",
),
"x86_64-apple-darwin": TargetSpec(
target="x86_64-apple-darwin",
is_windows=False,
is_linux=False,
dotslash_platform="macos-x86_64",
),
"aarch64-apple-darwin": TargetSpec(
target="aarch64-apple-darwin",
is_windows=False,
is_linux=False,
dotslash_platform="macos-aarch64",
),
"x86_64-pc-windows-msvc": TargetSpec(
target="x86_64-pc-windows-msvc",
is_windows=True,
is_linux=False,
dotslash_platform="windows-x86_64",
),
"aarch64-pc-windows-msvc": TargetSpec(
target="aarch64-pc-windows-msvc",
is_windows=True,
is_linux=False,
dotslash_platform="windows-aarch64",
),
}
HOST_RELEASE_TARGETS: dict[tuple[str, str], str] = {
("darwin", "aarch64"): "aarch64-apple-darwin",
("darwin", "x86_64"): "x86_64-apple-darwin",
("linux", "aarch64"): "aarch64-unknown-linux-musl",
("linux", "x86_64"): "x86_64-unknown-linux-musl",
("windows", "aarch64"): "aarch64-pc-windows-msvc",
("windows", "x86_64"): "x86_64-pc-windows-msvc",
}
def default_target() -> str:
system = platform.system().lower()
machine = normalize_machine(platform.machine())
target = HOST_RELEASE_TARGETS.get((system, machine))
if target is None:
supported = ", ".join(sorted(TARGET_SPECS))
raise RuntimeError(
f"Unsupported host platform {platform.system()}/{platform.machine()}. "
f"Pass --target explicitly. Supported targets: {supported}"
)
return target
def resolve_input_path(
explicit_path: Path | None,
description: str,
flag_name: str,
) -> Path:
if explicit_path is not None:
path = explicit_path.resolve()
if not path.is_file():
raise RuntimeError(f"{description} does not exist: {path}")
if not is_executable(path):
raise RuntimeError(f"{description} is not executable: {path}")
return path
raise RuntimeError(f"Must specify {flag_name} for {description}.")
def is_executable(path: Path) -> bool:
return bool(path.stat().st_mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))
def normalize_machine(machine: str) -> str:
machine = machine.lower()
if machine in ("amd64", "x86_64"):
return "x86_64"
if machine in ("aarch64", "arm64"):
return "aarch64"
return machine

View File

@@ -0,0 +1,45 @@
#!/usr/bin/env python3
from pathlib import Path
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from codex_package.archive import resolve_zstd_command
class ResolveZstdCommandTest(unittest.TestCase):
def test_prefers_zstd_from_path(self) -> None:
def which(name: str) -> str | None:
return {"zstd": "/usr/bin/zstd", "dotslash": "/usr/bin/dotslash"}.get(name)
self.assertEqual(resolve_zstd_command(which=which), ["/usr/bin/zstd"])
def test_falls_back_to_dotslash_manifest(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
manifest = Path(temp_dir) / "zstd"
manifest.write_text("#!/usr/bin/env dotslash\n{}\n", encoding="utf-8")
def which(name: str) -> str | None:
return {"dotslash": "/usr/bin/dotslash"}.get(name)
self.assertEqual(
resolve_zstd_command(dotslash_manifest=manifest, which=which),
["/usr/bin/dotslash", str(manifest)],
)
def test_errors_when_no_zstd_or_dotslash_manifest_is_available(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
missing_manifest = Path(temp_dir) / "zstd"
with self.assertRaisesRegex(RuntimeError, "zstd is required"):
resolve_zstd_command(
dotslash_manifest=missing_manifest,
which=lambda _name: None,
)
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,129 @@
#!/usr/bin/env python3
from pathlib import Path
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from codex_package.cargo import build_source_binaries
from codex_package.cargo import source_binaries_for_target
from codex_package.targets import PACKAGE_VARIANTS
from codex_package.targets import TARGET_SPECS
class SourceBinariesForTargetTest(unittest.TestCase):
def test_macos_package_with_prebuilt_entrypoint_builds_nothing(self) -> None:
self.assertEqual(
source_binaries_for_target(
TARGET_SPECS["aarch64-apple-darwin"],
PACKAGE_VARIANTS["codex"],
build_entrypoint=False,
build_code_mode_host=False,
build_exec_server=False,
build_bwrap=False,
build_codex_command_runner=False,
build_codex_windows_sandbox_setup=False,
),
[],
)
def test_linux_package_with_prebuilt_entrypoint_and_bwrap_builds_nothing(
self,
) -> None:
self.assertEqual(
source_binaries_for_target(
TARGET_SPECS["x86_64-unknown-linux-musl"],
PACKAGE_VARIANTS["codex"],
build_entrypoint=False,
build_code_mode_host=False,
build_exec_server=False,
build_bwrap=False,
build_codex_command_runner=False,
build_codex_windows_sandbox_setup=False,
),
[],
)
def test_windows_package_with_prebuilt_entrypoint_and_helpers_builds_nothing(
self,
) -> None:
self.assertEqual(
source_binaries_for_target(
TARGET_SPECS["x86_64-pc-windows-msvc"],
PACKAGE_VARIANTS["codex"],
build_entrypoint=False,
build_code_mode_host=False,
build_exec_server=False,
build_bwrap=False,
build_codex_command_runner=False,
build_codex_windows_sandbox_setup=False,
),
[],
)
def test_missing_windows_helpers_are_built(self) -> None:
self.assertEqual(
source_binaries_for_target(
TARGET_SPECS["x86_64-pc-windows-msvc"],
PACKAGE_VARIANTS["codex"],
build_entrypoint=False,
build_code_mode_host=False,
build_exec_server=False,
build_bwrap=False,
build_codex_command_runner=True,
build_codex_windows_sandbox_setup=True,
),
["codex-command-runner", "codex-windows-sandbox-setup"],
)
def test_missing_code_mode_host_is_built_for_app_server(self) -> None:
self.assertEqual(
source_binaries_for_target(
TARGET_SPECS["aarch64-apple-darwin"],
PACKAGE_VARIANTS["codex-app-server"],
build_entrypoint=False,
build_code_mode_host=True,
build_exec_server=True,
build_bwrap=False,
build_codex_command_runner=False,
build_codex_windows_sandbox_setup=False,
),
["codex-code-mode-host", "codex-exec-server"],
)
def test_build_uses_prebuilt_windows_helpers_without_running_cargo(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
root = Path(temp_dir)
entrypoint = touch_file(root / "codex.exe")
code_mode_host = touch_file(root / "codex-code-mode-host.exe")
command_runner = touch_file(root / "codex-command-runner.exe")
sandbox_setup = touch_file(root / "codex-windows-sandbox-setup.exe")
outputs = build_source_binaries(
TARGET_SPECS["x86_64-pc-windows-msvc"],
PACKAGE_VARIANTS["codex"],
cargo=str(root / "cargo-that-should-not-run"),
profile="release",
entrypoint_bin=entrypoint,
code_mode_host_bin=code_mode_host,
exec_server_bin=code_mode_host,
bwrap_bin=None,
codex_command_runner_bin=command_runner,
codex_windows_sandbox_setup_bin=sandbox_setup,
)
self.assertEqual(outputs.entrypoint_bin, entrypoint)
self.assertEqual(outputs.code_mode_host_bin, code_mode_host)
self.assertEqual(outputs.codex_command_runner_bin, command_runner)
self.assertEqual(outputs.codex_windows_sandbox_setup_bin, sandbox_setup)
def touch_file(path: Path) -> Path:
path.write_text("", encoding="utf-8")
return path.resolve()
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,48 @@
#!/usr/bin/env python3
import argparse
from pathlib import Path
import sys
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from codex_package.cli import parse_package_version
class PackageVersionTest(unittest.TestCase):
def test_accepts_release_prerelease_and_build_versions(self) -> None:
for version in (
"0.0.0",
"1.2.3",
"0.0.0-internal.deadbeef",
"1.2.3-alpha.1+build.01",
"18446744073709551615.0.0",
):
with self.subTest(version=version):
self.assertEqual(parse_package_version(version), version)
def test_rejects_versions_the_runtime_cannot_parse(self) -> None:
for version in (
"",
"1",
"1.2",
"1.2.3.4",
"v1.2.3",
"01.2.3",
"1.02.3",
"1.2.03",
"1.2.3-",
"1.2.3-alpha..1",
"1.2.3-01",
"1.2.3+",
"1.2.3+build..1",
"18446744073709551616.0.0",
):
with self.subTest(version=version):
with self.assertRaises(argparse.ArgumentTypeError):
parse_package_version(version)
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,264 @@
#!/usr/bin/env python3
from pathlib import Path
import hashlib
import io
import tarfile
import json
import shutil
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from build_winget_package import prepare_winget_package
from codex_package.archive import write_archive, resolve_zstd_command
from codex_package.layout import build_package_dir
from codex_package.layout import validate_package_dir
from codex_package.targets import PACKAGE_VARIANTS
from codex_package.targets import PackageInputs
from codex_package.targets import TARGET_SPECS
from codex_package.targets import default_target
class PackageLayoutTest(unittest.TestCase):
@unittest.skipIf(sys.platform == "win32", "MSVC symbols are separate PDB files")
def test_strip_policy_preserves_inputs_and_runs_packaged_executables(self) -> None:
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
source = root / "input-executable"
# System executables may already be stripped. Compile with debug
# information so a no-op strip cannot pass this regression test.
subprocess.run(
["cc", "-g", "-O0", "-x", "c", "-", "-o", str(source)],
input=r"""#include <stdio.h>
int main(void) {
fputs("package-ok", stdout);
return 0;
}
""",
text=True,
check=True,
capture_output=True,
)
original = source.read_bytes()
target = default_target()
for mode in ("auto", "all", "none"):
with self.subTest(mode=mode):
package = root / mode
command = [
sys.executable,
str(
Path(__file__).resolve().parents[1]
/ "build_codex_package.py"
),
"--target",
target,
"--cargo-profile",
"release",
"--package-dir",
str(package),
"--strip",
mode,
]
flags = [
"--entrypoint-bin",
"--code-mode-host-bin",
"--exec-server-bin",
"--rg-bin",
]
if "linux" in target:
flags.append("--bwrap-bin")
for flag in flags:
command.extend((flag, str(source)))
if mode != "all":
# Preserved prebuilt inputs must not even need a strip tool.
command.extend(("--strip-tool", str(root / "absent-strip")))
subprocess.run(command, check=True, capture_output=True)
for name in ("codex", "codex-code-mode-host", "codex-exec-server"):
executable = package / "bin" / name
self.assertEqual(
subprocess.check_output([str(executable)]),
b"package-ok",
)
if mode != "all":
self.assertEqual(executable.read_bytes(), original)
else:
self.assertLess(executable.stat().st_size, len(original))
self.assertEqual(source.read_bytes(), original)
self.assertEqual((package / "codex-path/rg").read_bytes(), original)
if "linux" in target:
self.assertEqual(
(package / "codex-resources/bwrap").read_bytes(), original
)
def test_winget_preserves_signed_files_and_voice_hashes(self) -> None:
for target in ("x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"):
with self.subTest(target=target), tempfile.TemporaryDirectory() as temp:
package = Path(temp)
files = {
"bin/codex.exe": b"signed CLI",
"bin/codex-code-mode-host.exe": b"signed code mode host",
"bin/codex-exec-server.exe": b"signed executor",
"codex-resources/codex-command-runner.exe": b"signed runner",
"codex-resources/codex-windows-sandbox-setup.exe": b"signed setup",
"codex-resources/voice/bin/codex-voice-host.exe": b"signed voice host",
"codex-resources/voice/bin/gstreamer-1.0-0.dll": b"signed audio DLL",
"codex-resources/voice/NOTICE.md": b"license notices",
"codex-path/rg.exe": b"ripgrep",
}
for name, contents in files.items():
path = package / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(contents)
metadata = {
"layoutVersion": 1,
"target": target,
"entrypoint": "bin/codex.exe",
}
(package / "codex-package.json").write_text(json.dumps(metadata))
manifest = {
"schemaVersion": 1,
"sha256": {
name: hashlib.sha256(contents).hexdigest()
for name, contents in files.items()
if name == "bin/codex.exe"
or name.startswith("codex-resources/voice/")
},
}
manifest_path = package / "codex-resources/voice/manifest.json"
manifest_path.write_text(json.dumps(manifest))
prepare_winget_package(package)
entrypoint = f"codex-{target}.exe"
files[entrypoint] = files.pop("bin/codex.exe")
files["codex-code-mode-host.exe"] = files.pop(
"bin/codex-code-mode-host.exe"
)
for helper in (
"codex-command-runner.exe",
"codex-windows-sandbox-setup.exe",
):
files[helper] = files[f"codex-resources/{helper}"]
actual = {
str(path.relative_to(package)).replace("\\", "/"): path.read_bytes()
for path in package.rglob("*")
if path.is_file()
}
actual_metadata = json.loads(actual.pop("codex-package.json"))
actual_manifest = json.loads(
actual.pop("codex-resources/voice/manifest.json")
)
self.assertEqual(actual, files)
metadata["entrypoint"] = entrypoint
self.assertEqual(actual_metadata, metadata)
manifest["sha256"][entrypoint] = manifest["sha256"].pop("bin/codex.exe")
self.assertEqual(actual_manifest, manifest)
for name, digest in actual_manifest["sha256"].items():
self.assertEqual(hashlib.sha256(actual[name]).hexdigest(), digest)
def test_macos_package_preserves_prebuilt_resource_binaries(self) -> None:
for variant_name in ("codex", "codex-app-server"):
for target in ("aarch64-apple-darwin", "x86_64-apple-darwin"):
with self.subTest(variant=variant_name, target=target):
with tempfile.TemporaryDirectory() as temp_dir:
root = Path(temp_dir)
package_dir = root / "package"
package_dir.mkdir()
rg_bin = touch_executable(root / "signed-rg")
rg_bin.write_bytes(b"signed ripgrep binary")
variant = PACKAGE_VARIANTS[variant_name]
spec = TARGET_SPECS[target]
inputs = PackageInputs(
entrypoint_bin=touch_executable(
root / variant.executable_stem
),
code_mode_host_bin=touch_executable(
root / "codex-code-mode-host"
),
exec_server_bin=rg_bin,
rg_bin=rg_bin,
bwrap_bin=None,
codex_command_runner_bin=None,
codex_windows_sandbox_setup_bin=None,
)
build_package_dir(package_dir, "1.2.3", variant, spec, inputs)
validate_package_dir(package_dir, variant, spec)
for suffix in (".tar.gz", ".tar.zst"):
archive_path = root / f"package{suffix}"
write_archive(package_dir, archive_path, force=False)
data = (
subprocess.check_output(
[
*resolve_zstd_command(),
"-d",
"--stdout",
str(archive_path),
]
)
if suffix == ".tar.zst"
else archive_path.read_bytes()
)
with tarfile.open(
fileobj=io.BytesIO(data), mode="r:*"
) as archive:
member = archive.getmember("bin/codex-exec-server")
self.assertTrue(member.mode & 0o111)
self.assertEqual(
archive.extractfile(member).read(),
rg_bin.read_bytes(),
)
self.assertEqual(
{
"rg": (package_dir / "codex-path" / "rg").read_bytes(),
"executor": (
package_dir / "bin/codex-exec-server"
).read_bytes(),
},
{
"rg": b"signed ripgrep binary",
"executor": b"signed ripgrep binary",
},
)
def test_app_server_package_places_code_mode_host_beside_entrypoint(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
root = Path(temp_dir)
package_dir = root / "package"
package_dir.mkdir()
inputs = PackageInputs(
entrypoint_bin=touch_executable(root / "codex-app-server"),
code_mode_host_bin=touch_executable(root / "codex-code-mode-host"),
exec_server_bin=touch_executable(root / "codex-exec-server"),
rg_bin=touch_executable(root / "rg"),
bwrap_bin=touch_executable(root / "bwrap"),
codex_command_runner_bin=None,
codex_windows_sandbox_setup_bin=None,
)
build_package_dir(
package_dir,
"1.2.3",
PACKAGE_VARIANTS["codex-app-server"],
TARGET_SPECS["x86_64-unknown-linux-musl"],
inputs,
)
validate_package_dir(
package_dir,
PACKAGE_VARIANTS["codex-app-server"],
TARGET_SPECS["x86_64-unknown-linux-musl"],
)
self.assertTrue((package_dir / "bin" / "codex-code-mode-host").is_file())
def touch_executable(path: Path) -> Path:
path.touch(mode=0o755)
return path
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,312 @@
import hashlib
import io
import sys
import tempfile
import unittest
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from unittest.mock import MagicMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from codex_package import v8
from codex_package.targets import TARGET_SPECS, TargetSpec
class FetchCodexV8ArtifactsTest(unittest.TestCase):
version = "152.2.0"
def setUp(self) -> None:
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
@contextmanager
def release(
self,
target: str,
*,
line_ending: bytes = b"\n",
trusted_digest: str | None = None,
trusted_name: str | None = None,
create_pins: bool = True,
) -> Iterator[tuple[TargetSpec, MagicMock, str]]:
spec = TARGET_SPECS[target]
profile = v8.V8_ARTIFACT_PROFILE
archive_name = (
f"rusty_v8_{profile}_{target}.lib.gz"
if spec.is_windows
else f"librusty_v8_{profile}_{target}.a.gz"
)
binding_name = f"src_binding_{profile}_{target}.rs"
manifest_name = f"rusty_v8_{profile}_{target}.sha256"
archive = b"trusted V8 archive"
binding = b"trusted V8 binding"
manifest = (
line_ending.join(
(
f"{hashlib.sha256(archive).hexdigest()} {archive_name}".encode(),
f"{hashlib.sha256(binding).hexdigest()} {binding_name}".encode(),
)
)
+ line_ending
)
payloads = {
manifest_name: manifest,
archive_name: archive,
binding_name: binding,
}
if create_pins:
pins = (
self.root / "third_party/v8/rusty_v8_152_2_0_release_manifests.sha256"
)
pins.parent.mkdir(parents=True)
digest = trusted_digest or hashlib.sha256(manifest).hexdigest()
name = trusted_name or manifest_name
pins.write_bytes(f"{digest} {name}".encode() + line_ending)
def download(_url: str, destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(payloads[destination.name])
with (
patch.object(v8, "REPO_ROOT", self.root),
patch.object(v8, "download_file", side_effect=download) as download_file,
):
yield spec, download_file, manifest_name
def test_fetches_artifacts_after_authenticating_manifest(self) -> None:
with self.release("x86_64-unknown-linux-gnu") as (
spec,
download,
manifest_name,
):
artifacts = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
self.assertEqual(artifacts.archive.read_bytes(), b"trusted V8 archive")
self.assertEqual(artifacts.binding.read_bytes(), b"trusted V8 binding")
self.assertEqual(download.call_args_list[0].args[1].name, manifest_name)
self.assertEqual(download.call_count, 3)
def test_authenticates_windows_manifest_with_crlf(self) -> None:
with self.release("x86_64-pc-windows-msvc", line_ending=b"\r\n") as (
spec,
download,
_manifest_name,
):
artifacts = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
self.assertEqual(artifacts.archive.read_bytes(), b"trusted V8 archive")
self.assertEqual(artifacts.binding.read_bytes(), b"trusted V8 binding")
self.assertEqual(download.call_count, 3)
def test_rejects_tampered_manifest_before_downloading_artifacts(self) -> None:
with self.release("x86_64-unknown-linux-gnu", trusted_digest="0" * 64) as (
spec,
download,
manifest_name,
):
with self.assertRaisesRegex(
RuntimeError, "does not match its trusted SHA-256"
):
v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
download.assert_called_once()
self.assertEqual(download.call_args.args[1].name, manifest_name)
def test_rejects_missing_manifest_pin_before_downloading_artifacts(self) -> None:
with self.release(
"x86_64-unknown-linux-gnu", trusted_name="another-target.sha256"
) as (spec, download, manifest_name):
with self.assertRaisesRegex(RuntimeError, "has no trusted SHA-256"):
v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
download.assert_called_once()
self.assertEqual(download.call_args.args[1].name, manifest_name)
def test_rejects_missing_pin_file_before_downloading_artifacts(self) -> None:
with self.release("x86_64-unknown-linux-gnu", create_pins=False) as (
spec,
download,
manifest_name,
):
with self.assertRaises(FileNotFoundError):
v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
download.assert_called_once()
self.assertEqual(download.call_args.args[1].name, manifest_name)
def test_verified_cache_needs_no_network(self) -> None:
with self.release("x86_64-unknown-linux-gnu") as (spec, download, _):
first = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
download.reset_mock()
download.side_effect = AssertionError("unexpected network request")
second = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
self.assertEqual(second, first)
download.assert_not_called()
def test_missing_or_corrupt_manifest_refresh_retains_valid_artifacts(self) -> None:
with self.release("x86_64-unknown-linux-gnu") as (spec, download, name):
artifacts = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
manifest = artifacts.archive.parent / name
expected = manifest.read_bytes()
for contents in (None, b"corrupt"):
with self.subTest(contents=contents):
if contents is None:
manifest.unlink()
else:
manifest.write_bytes(contents)
download.reset_mock()
refreshed = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
self.assertEqual(refreshed, artifacts)
self.assertEqual(manifest.read_bytes(), expected)
download.assert_called_once()
self.assertEqual(download.call_args.args[1], manifest)
def test_cached_manifest_still_authenticates_both_artifacts(self) -> None:
with self.release("x86_64-unknown-linux-gnu") as (spec, download, _):
artifacts = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
artifacts.archive.write_bytes(b"corrupt archive")
artifacts.binding.write_bytes(b"corrupt binding")
download.reset_mock()
repaired = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
self.assertEqual(repaired, artifacts)
self.assertEqual(
(repaired.archive.read_bytes(), repaired.binding.read_bytes()),
(b"trusted V8 archive", b"trusted V8 binding"),
)
self.assertEqual(
[call.args[1] for call in download.call_args_list],
[artifacts.archive, artifacts.binding],
)
def test_changed_repository_pin_rejects_old_cache_and_bad_refresh(self) -> None:
with self.release("x86_64-unknown-linux-gnu") as (spec, download, name):
artifacts = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
pins = (
self.root / "third_party/v8/rusty_v8_152_2_0_release_manifests.sha256"
)
pins.write_text(f"{'0' * 64} {name}\n")
download.reset_mock()
with self.assertRaisesRegex(
RuntimeError, "does not match its trusted SHA-256"
):
v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
download.assert_called_once()
self.assertEqual(
download.call_args.args[1], artifacts.archive.parent / name
)
self.assertFalse((artifacts.archive.parent / name).exists())
self.assertEqual(artifacts.archive.read_bytes(), b"trusted V8 archive")
self.assertEqual(artifacts.binding.read_bytes(), b"trusted V8 binding")
@unittest.skipIf(sys.platform == "win32", "requires unprivileged symlinks")
def test_symlink_manifest_is_replaced_without_writing_through_link(self) -> None:
actual_download = v8.download_file
with self.release("x86_64-unknown-linux-gnu") as (spec, download, name):
artifacts = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
manifest = artifacts.archive.parent / name
expected = manifest.read_bytes()
backing = manifest.with_suffix(".original")
manifest.rename(backing)
manifest.symlink_to(backing)
download.reset_mock()
download.side_effect = actual_download
with patch.object(v8, "urlopen", return_value=io.BytesIO(expected)):
refreshed = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
self.assertEqual(refreshed, artifacts)
self.assertFalse(manifest.is_symlink())
self.assertEqual(
(manifest.read_bytes(), backing.read_bytes()), (expected, expected)
)
download.assert_called_once()
def test_interrupted_refresh_preserves_cache(self) -> None:
actual_download = v8.download_file
class InterruptedResponse(io.BytesIO):
def read(self, size=-1):
if self.tell():
raise OSError("interrupted download")
return super().read(size)
with self.release("x86_64-unknown-linux-gnu") as (spec, download, name):
artifacts = v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
manifest = artifacts.archive.parent / name
manifest.write_bytes(b"stale manifest")
download.reset_mock()
download.side_effect = actual_download
with (
patch.object(
v8, "urlopen", return_value=InterruptedResponse(b"partial")
),
self.assertRaisesRegex(OSError, "interrupted download"),
):
v8.fetch_codex_v8_artifacts(
spec, version=self.version, cache_root=self.root / "cache"
)
self.assertEqual(manifest.read_bytes(), b"stale manifest")
self.assertEqual(artifacts.archive.read_bytes(), b"trusted V8 archive")
self.assertEqual(artifacts.binding.read_bytes(), b"trusted V8 binding")
self.assertFalse(list(manifest.parent.glob("*.tmp")))
def test_source_and_paired_overrides_do_not_touch_cache(self) -> None:
spec = TARGET_SPECS["x86_64-unknown-linux-gnu"]
for environ in (
{"V8_FROM_SOURCE": "1"},
{
"RUSTY_V8_ARCHIVE": "archive.a",
"RUSTY_V8_SRC_BINDING_PATH": "binding.rs",
},
):
with (
self.subTest(environ=environ),
patch.object(
v8,
"fetch_codex_v8_artifacts",
side_effect=AssertionError("unexpected fetch"),
) as fetch,
):
self.assertEqual(
v8.resolve_codex_v8_cargo_env(spec, environ=environ), {}
)
fetch.assert_not_called()
if __name__ == "__main__":
unittest.main()

221
scripts/codex_package/v8.py Normal file
View File

@@ -0,0 +1,221 @@
"""Codex-built V8 artifact overrides for package Cargo builds."""
from __future__ import annotations
import hashlib
import os
import shutil
import tempfile
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from urllib.request import urlopen
from .targets import REPO_ROOT, TargetSpec
DOWNLOAD_TIMEOUT_SECS = 120
V8_ARTIFACT_PROFILE = "ptrcomp_sandbox_release"
@dataclass(frozen=True)
class RustyV8ArtifactPair:
archive: Path
binding: Path
def resolve_codex_v8_cargo_env(
spec: TargetSpec,
*,
environ: Mapping[str, str] | None = None,
cache_root: Path | None = None,
) -> dict[str, str]:
environ = os.environ if environ is None else environ
if environ.get("V8_FROM_SOURCE") in {"true", "1", "yes"}:
return {}
archive_override = environ.get("RUSTY_V8_ARCHIVE")
binding_override = environ.get("RUSTY_V8_SRC_BINDING_PATH")
if archive_override and binding_override:
return {}
if archive_override or binding_override:
raise RuntimeError(
"Cargo package builds need RUSTY_V8_ARCHIVE and RUSTY_V8_SRC_BINDING_PATH set together."
)
artifacts = fetch_codex_v8_artifacts(spec, cache_root=cache_root)
return {
"RUSTY_V8_ARCHIVE": str(artifacts.archive),
"RUSTY_V8_SRC_BINDING_PATH": str(artifacts.binding),
}
def fetch_codex_v8_artifacts(
spec: TargetSpec,
*,
version: str | None = None,
cache_root: Path | None = None,
) -> RustyV8ArtifactPair:
version = version or resolved_v8_crate_version()
release_url = (
f"https://github.com/openai/codex/releases/download/rusty-v8-v{version}"
)
target = spec.target
cache_dir = (cache_root or default_cache_root()) / f"rusty-v8-{version}-{target}"
if spec.is_windows:
archive_name = f"rusty_v8_{V8_ARTIFACT_PROFILE}_{target}.lib.gz"
else:
archive_name = f"librusty_v8_{V8_ARTIFACT_PROFILE}_{target}.a.gz"
binding_name = f"src_binding_{V8_ARTIFACT_PROFILE}_{target}.rs"
checksums_name = f"rusty_v8_{V8_ARTIFACT_PROFILE}_{target}.sha256"
archive = cache_dir / archive_name
binding = cache_dir / binding_name
checksums = cache_dir / checksums_name
# A cached manifest is sufficient only while it matches this checkout's
# release pin. Probe without deleting it in case refresh is unavailable.
cached_manifest_valid = False
try:
if not checksums.is_symlink():
verify_release_checksum_manifest(
checksums, version=version, remove_invalid=False
)
cached_manifest_valid = True
except (OSError, RuntimeError, ValueError):
pass
if not cached_manifest_valid:
download_file(f"{release_url}/{checksums.name}", checksums)
verify_release_checksum_manifest(checksums, version=version)
expected_checksums = load_checksums(checksums, {archive.name, binding.name})
for artifact in [archive, binding]:
ensure_valid_artifact(
artifact,
expected_checksums[artifact.name],
f"{release_url}/{artifact.name}",
)
return RustyV8ArtifactPair(archive=archive, binding=binding)
def resolved_v8_crate_version() -> str:
import tomllib
cargo_lock = tomllib.loads((REPO_ROOT / "codex-rs" / "Cargo.lock").read_text())
versions = sorted(
{
package["version"]
for package in cargo_lock["package"]
if package["name"] == "v8"
}
)
if len(versions) != 1:
raise RuntimeError(
f"Expected exactly one resolved v8 version, found: {versions}"
)
return versions[0]
def default_cache_root() -> Path:
return Path(tempfile.gettempdir()) / "codex-package"
def verify_release_checksum_manifest(
checksums_path: Path, *, version: str, remove_invalid: bool = True
) -> None:
version_suffix = version.replace(".", "_")
trusted_checksums = (
REPO_ROOT
/ "third_party"
/ "v8"
/ f"rusty_v8_{version_suffix}_release_manifests.sha256"
)
for line in trusted_checksums.read_text(encoding="utf-8").splitlines():
digest, artifact_name = line.split(maxsplit=1)
if artifact_name != checksums_path.name:
continue
if has_checksum(checksums_path, digest):
return
if remove_invalid:
checksums_path.unlink(missing_ok=True)
raise RuntimeError(
f"V8 checksum manifest {checksums_path} does not match its trusted SHA-256."
)
raise RuntimeError(
f"V8 checksum manifest {checksums_path.name} has no trusted SHA-256 for {version}."
)
def load_checksums(checksums_path: Path, artifact_names: set[str]) -> dict[str, str]:
checksums: dict[str, str] = {}
lines = checksums_path.read_text(encoding="utf-8").splitlines()
if len(lines) != len(artifact_names):
raise RuntimeError(
f"Expected {len(artifact_names)} V8 checksums in {checksums_path}, found {len(lines)}."
)
for line in lines:
parts = line.split(maxsplit=1)
if len(parts) != 2:
raise RuntimeError(
f"Invalid V8 checksum line in {checksums_path}: {line!r}"
)
digest, artifact_name = parts[0], parts[1].strip()
if len(digest) != 64 or any(char not in "0123456789abcdef" for char in digest):
raise RuntimeError(
f"Invalid V8 checksum digest in {checksums_path}: {digest}"
)
if artifact_name not in artifact_names:
raise RuntimeError(
f"Unexpected V8 checksum artifact in {checksums_path}: {artifact_name}"
)
checksums[artifact_name] = digest
if checksums.keys() != artifact_names:
raise RuntimeError(
f"V8 checksum manifest {checksums_path} does not cover {artifact_names}."
)
return checksums
def ensure_valid_artifact(artifact: Path, checksum: str, url: str) -> None:
if has_checksum(artifact, checksum):
return
artifact.unlink(missing_ok=True)
download_file(url, artifact)
if has_checksum(artifact, checksum):
return
artifact.unlink(missing_ok=True)
raise RuntimeError(
f"Codex-built V8 artifact {artifact} failed checksum validation."
)
def has_checksum(path: Path, expected: str) -> bool:
if not path.is_file():
return False
digest = hashlib.sha256()
with path.open("rb") as artifact:
for chunk in iter(lambda: artifact.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest() == expected
def download_file(url: str, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
temp_path = dest.with_suffix(f"{dest.suffix}.tmp")
temp_path.unlink(missing_ok=True)
try:
with urlopen(url, timeout=DOWNLOAD_TIMEOUT_SECS) as response:
with temp_path.open("wb") as output:
shutil.copyfileobj(response, output)
temp_path.replace(dest)
finally:
temp_path.unlink(missing_ok=True)

View File

@@ -0,0 +1,29 @@
"""Version discovery for Codex packages."""
import re
from .targets import REPO_ROOT
WORKSPACE_VERSION_PATTERN = re.compile(r'^version\s*=\s*"([^"]+)"')
def read_workspace_version() -> str:
cargo_toml = REPO_ROOT / "codex-rs" / "Cargo.toml"
in_workspace_package = False
with open(cargo_toml, encoding="utf-8") as fh:
for line in fh:
stripped = line.strip()
if stripped == "[workspace.package]":
in_workspace_package = True
continue
if in_workspace_package and stripped.startswith("["):
break
if in_workspace_package:
match = WORKSPACE_VERSION_PATTERN.match(stripped)
if match is not None:
return match.group(1)
raise RuntimeError(f"Could not find [workspace.package].version in {cargo_toml}")

10
scripts/debug-codex.sh Executable 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 -- "$@")

221
scripts/format.py Normal file
View File

@@ -0,0 +1,221 @@
#!/usr/bin/env python3
"""Format repository sources or check that they are already formatted."""
import argparse
import os
import shlex
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
@dataclass(frozen=True)
class Command:
args: tuple[str, ...]
cwd: Path = REPO_ROOT
@dataclass(frozen=True)
class FormatterGroup:
name: str
commands: tuple[Command, ...]
@dataclass(frozen=True)
class FormatterResult:
name: str
output: str
returncode: int
def just_formatter_group(*, check: bool) -> FormatterGroup:
args = ["just", "--unstable", "--fmt"]
if check:
args.append("--check")
return FormatterGroup("Just", (Command(tuple(args)),))
def rust_formatter_group(*, check: bool) -> FormatterGroup:
rust_workspace = REPO_ROOT / "codex-rs"
repository_files = subprocess.check_output(
[
"git",
"ls-files",
"-z",
"--cached",
"--others",
"--exclude-standard",
"--",
"*.rs",
],
cwd=REPO_ROOT,
).split(b"\0")
rust_files = sorted(
os.path.relpath(REPO_ROOT / os.fsdecode(encoded_path), rust_workspace)
for encoded_path in repository_files
if encoded_path and (REPO_ROOT / os.fsdecode(encoded_path)).is_file()
)
# Git supplies every source file, including files Cargo cannot discover.
# Do not recursively format child modules again or include ignored files.
args = [
"rustfmt",
"--edition",
"2024",
"--config-path",
str(rust_workspace / "rustfmt.toml"),
"--config",
"imports_granularity=Item,skip_children=true",
]
if check:
args.append("--check")
# Batch relative paths to stay below Windows command-line limits.
commands = tuple(
Command(tuple(args + rust_files[start : start + 64]), rust_workspace)
for start in range(0, len(rust_files), 64)
)
return FormatterGroup("Rust", commands)
def buildifier_formatter_group(*, check: bool) -> FormatterGroup:
repository_files = subprocess.check_output(
["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
cwd=REPO_ROOT,
).split(b"\0")
buildifier_files: list[str] = []
for encoded_path in repository_files:
if not encoded_path:
continue
path = Path(os.fsdecode(encoded_path))
name = path.name
if (
name in {"BUILD", "WORKSPACE", "MODULE.bazel"}
or name.startswith(("BUILD.", "WORKSPACE."))
or name.endswith((".BUILD.bazel", ".MODULE.bazel", ".bzl", ".sky"))
or ".bzl." in name
or ".sky." in name
):
buildifier_files.append(path.as_posix())
buildifier_files.sort()
# Invoke DotSlash explicitly because Windows does not honor shebangs.
buildifier_args = [
"dotslash",
str(REPO_ROOT / "tools" / "buildifier"),
"-mode=check" if check else "-mode=fix",
"-lint=off",
*buildifier_files,
]
return FormatterGroup("Bazel/Starlark", (Command(tuple(buildifier_args)),))
def python_sdk_formatter_group(*, check: bool) -> FormatterGroup:
# Each `--project` retains its local dependency and Ruff configuration context.
uv_run_args = [
"uv",
"run",
"--frozen",
"--project",
"sdk/python",
"--only-group",
"format",
]
format_args = [
*uv_run_args,
"ruff",
"format",
]
if check:
format_args.append("--check")
# `ruff check --diff` reports lint-driven rewrites without changing files.
# It is the check-mode counterpart of `--fix --fix-only`, not a full lint gate.
lint_args = ["ruff", "check", "--diff"]
else:
# Ruff's lint fixer and formatter are separate passes: the first applies
# fixable lint rewrites, while the second formats source layout.
lint_args = ["ruff", "check", "--fix", "--fix-only"]
return FormatterGroup(
"Python SDK",
(
Command((*uv_run_args, *lint_args, "sdk/python")),
Command((*format_args, "sdk/python")),
),
)
def python_scripts_formatter_group(*, check: bool) -> FormatterGroup:
args = ["uv", "run", "--frozen", "--project", "scripts", "ruff", "format"]
if check:
args.append("--check")
args.append(".")
return FormatterGroup("Python scripts", (Command(tuple(args)),))
def formatter_groups(*, check: bool) -> tuple[FormatterGroup, ...]:
return (
just_formatter_group(check=check),
rust_formatter_group(check=check),
buildifier_formatter_group(check=check),
python_sdk_formatter_group(check=check),
python_scripts_formatter_group(check=check),
)
def run_formatter_group(group: FormatterGroup) -> FormatterResult:
"""Run one formatter group sequentially and return its buffered output."""
for command in group.commands:
try:
process = subprocess.run(
command.args,
cwd=command.cwd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
check=False,
)
except OSError as error:
output = f"$ {shlex.join(command.args)}\n{error}\n"
return FormatterResult(group.name, output, 1)
if process.returncode != 0:
output = f"$ {shlex.join(command.args)}\n{process.stdout}"
if process.stdout and not process.stdout.endswith("\n"):
output += "\n"
return FormatterResult(group.name, output, process.returncode)
return FormatterResult(group.name, "", 0)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"--check",
action="store_true",
help="check formatting without modifying files",
)
args = parser.parse_args()
groups = formatter_groups(check=args.check)
failures: list[str] = []
with ThreadPoolExecutor(max_workers=len(groups)) as executor:
futures = [executor.submit(run_formatter_group, group) for group in groups]
for future in as_completed(futures):
result = future.result()
if result.returncode != 0:
failures.append(result.name)
print(f"==> {result.name} formatter failed", file=sys.stderr)
print(result.output, end="", file=sys.stderr)
if failures:
print(f"Formatting failed: {', '.join(failures)}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())

1266
scripts/install/install.ps1 Normal file

File diff suppressed because it is too large Load Diff

1500
scripts/install/install.sh Executable file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

72
scripts/just-shell.py Normal file
View File

@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Cross-platform shell launcher for `just` recipes.
This keeps recipe bodies as normal shell snippets while giving the justfile one
portable placeholder, `{args}`, for forwarding variadic recipe arguments.
"""
from __future__ import annotations
import os
import shutil
import subprocess
import sys
ARGS_TOKEN = "{args}"
STDERR_NULL_TOKEN = "{stderr-null}"
POWERSHELL_ARGS = "@($args | Select-Object -Skip 1)"
POWERSHELL_STDERR_NULL = "2>$null; exit $LASTEXITCODE"
SH_ARGS = '"$@"'
SH_STDERR_NULL = "2>/dev/null"
def main() -> int:
if len(sys.argv) < 2:
print("just shell adapter expected a recipe command.", file=sys.stderr)
return 1
command = sys.argv[1]
recipe_name = sys.argv[2] if len(sys.argv) > 2 else ""
recipe_args = sys.argv[3:]
if os.name == "nt":
return run_powershell(command, recipe_name, recipe_args)
else:
return run_sh(command, recipe_name, recipe_args)
def run_sh(command: str, recipe_name: str, recipe_args: list[str]) -> int:
command = command.replace(ARGS_TOKEN, SH_ARGS)
command = command.replace(STDERR_NULL_TOKEN, SH_STDERR_NULL)
os.execvp("sh", ["sh", "-cu", command, recipe_name, *recipe_args])
def run_powershell(command: str, recipe_name: str, recipe_args: list[str]) -> int:
pwsh = shutil.which("pwsh.exe") or shutil.which("pwsh")
if pwsh is None:
print(
"PowerShell ('pwsh') is required for Windows just recipes. "
"Run 'just install' to install it.",
file=sys.stderr,
)
return 1
command = command.replace(ARGS_TOKEN, POWERSHELL_ARGS)
command = command.replace(STDERR_NULL_TOKEN, POWERSHELL_STDERR_NULL)
return subprocess.run(
[
pwsh,
"-NoLogo",
"-NoProfile",
"-CommandWithArgs",
command,
recipe_name,
*recipe_args,
],
check=False,
).returncode
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,52 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${repo_root}"
windows_cross_compile=0
while [[ $# -gt 0 ]]; do
case "$1" in
--windows-cross-compile)
windows_cross_compile=1
shift
;;
*)
echo "Usage: $0 [--windows-cross-compile]" >&2
exit 1
;;
esac
done
# Resolve the dynamic targets before printing anything so callers do not
# continue with a partial list if `bazel query` fails. Target discovery is
# local on all platforms.
manual_rust_test_targets="$(
./.github/scripts/run-bazel-query-ci.sh \
--output=label \
-- 'kind("rust_test rule", attr(tags, "manual", //codex-rs/... except //codex-rs/v8-poc/...))'
)"
if [[ "${RUNNER_OS:-}" != "Windows" ]]; then
# Non-Windows clippy jobs lint the native test binaries; the
# Windows-cross binaries exist only for the fast Windows test leg.
manual_rust_test_targets="$(printf '%s\n' "${manual_rust_test_targets}" | grep -v -- '-windows-cross-bin$' || true)"
elif [[ $windows_cross_compile -eq 1 ]]; then
# `bazel query` is intentionally pre-analysis and does not remove targets
# made incompatible by `target_compatible_with`. Sharded integration tests
# add native-only manual helpers such as `core-all-test-bin`, plus separate
# `core-all-test-windows-cross-bin` helpers for the Windows cross leg. Keep
# the Windows helpers and unit-test helpers, but do not pass the native-only
# sharded integration helpers as explicit clippy targets.
manual_rust_test_targets="$(printf '%s\n' "${manual_rust_test_targets}" | grep -v -- '-test-bin$' || true)"
fi
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,19 @@
#!/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.
# The normal test job covers the Wine smoke test; omit its downloaded runtime
# and cross-compile from this build-only release sweep.
printf '%s\n' \
"//codex-rs/..." \
"-//codex-rs/core/tests/remote_env_windows:smoke-test" \
"-//codex-rs/v8-poc:all"

View File

@@ -0,0 +1,121 @@
# MCP client conformance
This directory tests the actual Codex executable against the official Model
Context Protocol client conformance suite. It exercises the shipping legacy,
intermediate `2025-11-25`, and modern `2026-07-28` protocols, localhost HTTP,
stdio, OAuth, and additional transport and security regression fixtures.
The official upstream suite is pinned to
`modelcontextprotocol/conformance@49103de6ed70804e940637bf3e9e29e4a3f54e64`.
Use the Node.js version in the repository's `.nvmrc` and Python 3.10 or later.
## Run the conformance gate
First install the frozen workspace dependencies and build Codex:
```bash
pnpm install --frozen-lockfile
cargo build --locked --manifest-path codex-rs/Cargo.toml -p codex-cli --bin codex
```
From a published Codex checkout, run:
```bash
python3 scripts/mcp_conformance/run_codex_compliance.py \
codex-rs/target/debug/codex \
--conformance-cli node_modules/@modelcontextprotocol/conformance/dist/index.js \
--baseline-report scripts/mcp_conformance/regression-baseline-v1.json \
--report /tmp/codex-mcp-conformance.json
```
The positional executable can also point to an already built Codex binary.
`--conformance-cli` selects the exact, lockfile-installed upstream JavaScript
runner instead of downloading a moving version during a test.
## What the baseline means
`regression-baseline-v1.json` is a compact, reviewed snapshot of the upstream
revision, required protocol versions, HTTP and stdio transports, enabled modern
feature, OAuth coverage, and individual passing and failing check identities.
The gate exits successfully only when:
- The upstream suite and modern feature match the committed baseline.
- The shipping legacy, intermediate, and modern protocols are actually tested.
- The required HTTP, stdio, and authentication scenarios are actually run.
- Every previously passing check still passes.
- No additional check fails.
Existing known failures remain visible in the complete JSON report. In
particular, `success` describes complete upstream conformance and
`regressionGate.success` describes the no-new-regressions merge gate; the gate
does not relabel an existing failure as a pass.
Create a compact baseline from a reviewed complete report without contacting
the upstream suite again:
```bash
python3 scripts/mcp_conformance/run_codex_compliance.py \
/absolute/path/to/codex \
--baseline-report /absolute/path/to/full-conformance-report.json \
--extract-baseline /tmp/mcp-conformance-regression-baseline-v1.json
```
Alternatively, add `--write-baseline /tmp/mcp-conformance-regression-baseline-v1.json`
to a complete conformance run. Review every baseline change; do not regenerate
it to conceal a regression.
## Run the production reviewer regression gate
The separate reviewer gate tests the real Codex app-server across all three
shipping, legacy, and modern protocol modes. It covers stdio and localhost
HTTP, exact-integer tool and elicitation schemas, bounded multi-round requests,
malformed discovery response IDs, repeated pagination cursors, SSE framing and
keepalives, and catalog boundaries. In a published Codex checkout, run:
```bash
python3 scripts/mcp_conformance/review_regressions.py \
/absolute/path/to/codex \
--mode all \
--baseline-report scripts/mcp_conformance/review-regression-baseline-v1.json \
--report /tmp/codex-mcp-review-regressions.json
```
A complete, main-derived baseline records all 186 real check identities and all
21 required cases. Existing failures remain explicitly visible in the complete
report; `regressionGate.success: true` means there are no newly failing or
missing checks. Improvements are recorded under `fixedChecks`. The gate never
classifies an existing failure as a passing check.
Extract a compact deterministic reviewer baseline from a reviewed complete
production report without rerunning the client:
```bash
python3 scripts/mcp_conformance/review_regressions.py \
/absolute/path/to/codex \
--baseline-report /absolute/path/to/full-review-regressions.json \
--extract-baseline /tmp/review-regression-baseline-v1.json
```
Review every baseline update. Do not regenerate a baseline to hide a regression.
## Run the fixture self-tests
```bash
env PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 \
python3 -m pytest -q scripts/mcp_conformance
```
## Run the required SDK integration
The existing required SDK workflow runs the complete Python fixture self-tests.
Its TypeScript job builds the actual Codex executable, sets `CODEX_EXEC_PATH`,
installs the pinned upstream conformance runner, and runs both the official
authenticated suite and the separate production reviewer regression matrix.
Neither gate can be skipped. To reproduce the focused integration locally:
```bash
CODEX_EXEC_PATH=/absolute/path/to/codex \
pnpm --filter @openai/codex-sdk test -- \
--runInBand tests/mcpConformance.test.ts
```

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,518 @@
"""Driver for the upstream MCP client conformance suite.
The upstream suite owns the localhost HTTP server and the wire-level checks.
This module deliberately invokes one scenario at a time because the upstream
parallel suite path does not currently propagate the client adapter result.
"""
import json
import os
import re
import shlex
import signal
import subprocess
import sys
import tempfile
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Mapping, Sequence
SHIPPING_LEGACY_VERSION = "2025-06-18"
LEGACY_VERSION = "2025-11-25"
MODERN_VERSION = "2026-07-28"
# Reviewed on 2026-07-29. Pinning a commit instead of an npm prerelease keeps
# the scenario definitions and result semantics reproducible.
OFFICIAL_CONFORMANCE_GIT_REF = "49103de6ed70804e940637bf3e9e29e4a3f54e64"
OFFICIAL_CONFORMANCE_REPOSITORY = "modelcontextprotocol/conformance"
OFFICIAL_NON_AUTH_SCENARIOS: Mapping[str, tuple[str, ...]] = {
SHIPPING_LEGACY_VERSION: (
"initialize",
"tools_call",
),
LEGACY_VERSION: (
"initialize",
"tools_call",
"elicitation-sep1034-client-defaults",
"sse-retry",
),
MODERN_VERSION: (
"tools_call",
"request-metadata",
"sep-2322-client-request-state",
"http-standard-headers",
"http-custom-headers",
"http-invalid-tool-headers",
"json-schema-ref-no-deref",
),
}
OFFICIAL_AUTH_SCENARIOS: Mapping[str, tuple[str, ...]] = {
SHIPPING_LEGACY_VERSION: (
"auth/token-endpoint-auth-basic",
"auth/token-endpoint-auth-post",
"auth/token-endpoint-auth-none",
),
LEGACY_VERSION: (
"auth/metadata-default",
"auth/metadata-var1",
"auth/metadata-var2",
"auth/metadata-var3",
"auth/basic-cimd",
"auth/scope-from-www-authenticate",
"auth/scope-from-scopes-supported",
"auth/scope-omitted-when-undefined",
"auth/scope-step-up",
"auth/scope-retry-limit",
"auth/token-endpoint-auth-basic",
"auth/token-endpoint-auth-post",
"auth/token-endpoint-auth-none",
"auth/pre-registration",
),
MODERN_VERSION: (
"auth/metadata-default",
"auth/metadata-var1",
"auth/metadata-var2",
"auth/metadata-var3",
"auth/basic-cimd",
"auth/scope-from-www-authenticate",
"auth/scope-from-scopes-supported",
"auth/scope-omitted-when-undefined",
"auth/scope-step-up",
"auth/scope-retry-limit",
"auth/token-endpoint-auth-basic",
"auth/token-endpoint-auth-post",
"auth/token-endpoint-auth-none",
"auth/pre-registration",
"auth/resource-mismatch",
"auth/offline-access-scope",
"auth/offline-access-not-supported",
"auth/authorization-server-migration",
"auth/iss-supported",
"auth/iss-not-advertised",
"auth/iss-supported-missing",
"auth/iss-wrong-issuer",
"auth/iss-unexpected",
"auth/iss-normalized",
"auth/metadata-issuer-mismatch",
),
}
# These scenarios cover separately negotiated protocol extensions rather than
# either dated release. Keep them visible for future adapters, but do not mix
# them into versioned release conformance percentages.
OFFICIAL_AUTH_EXTENSION_SCENARIOS: tuple[str, ...] = (
"auth/client-credentials-jwt",
"auth/client-credentials-basic",
"auth/enterprise-managed-authorization",
"auth/dpop",
"auth/dpop-nonce",
"auth/wif-jwt-bearer",
)
_SENSITIVE_JSON_FIELD = re.compile(
r'("(?:client_secret|private_key_pem|valid_jwt|wrong_audience_jwt|'
r'expired_jwt|idp_id_token)"\s*:\s*)"(?:\\.|[^"\\])*"'
)
_SENSITIVE_ESCAPED_JSON_FIELD = re.compile(
r'(\\"(?:client_secret|private_key_pem|valid_jwt|wrong_audience_jwt|'
r'expired_jwt|idp_id_token)\\"\s*:\s*)\\"(?:\\\\.|[^"\\])*\\"'
)
_SENSITIVE_URL_PARAMETER = re.compile(
r"([?&](?:code|state|code_challenge|code_verifier|access_token|"
r"""refresh_token|client_secret)=)[^&\s"'\\<>]+""",
re.IGNORECASE,
)
_BEARER_TOKEN = re.compile(r"(\bBearer\s+)[A-Za-z0-9._~+/=-]+", re.IGNORECASE)
def redact_sensitive_text(value: str) -> str:
value = _SENSITIVE_JSON_FIELD.sub(r'\1"[REDACTED]"', value)
value = _SENSITIVE_ESCAPED_JSON_FIELD.sub(r'\1\\"[REDACTED]\\"', value)
value = _SENSITIVE_URL_PARAMETER.sub(r"\1[REDACTED]", value)
return _BEARER_TOKEN.sub(r"\1[REDACTED]", value)
def _scrub_retained_artifacts(scenario_dir: Path) -> None:
for name in ("stdout.txt", "stderr.txt"):
for path in scenario_dir.rglob(name):
try:
original = path.read_text(encoding="utf-8")
redacted = redact_sensitive_text(original)
if redacted != original:
path.write_text(redacted, encoding="utf-8")
except OSError:
continue
for path in scenario_dir.rglob(".credentials.json"):
try:
path.unlink(missing_ok=True)
except OSError:
continue
@dataclass(frozen=True)
class OfficialCheck:
scenario: str
check_id: str
name: str
status: str
description: str
error_message: str | None = None
@dataclass
class OfficialScenarioResult:
scenario: str
success: bool
checks: list[OfficialCheck] = field(default_factory=list)
adapter_success: bool = False
adapter_detail: str = ""
runner_detail: str = ""
def default_conformance_command() -> list[str]:
return [
"npx",
"--yes",
(f"github:{OFFICIAL_CONFORMANCE_REPOSITORY}#{OFFICIAL_CONFORMANCE_GIT_REF}"),
]
def scenarios_for_mode(
mode: str,
requested: Sequence[str] | None = None,
*,
include_auth: bool = True,
) -> tuple[str, ...]:
non_auth = OFFICIAL_NON_AUTH_SCENARIOS.get(mode)
auth = OFFICIAL_AUTH_SCENARIOS.get(mode)
if non_auth is None or auth is None:
raise ValueError(f"unsupported MCP protocol version: {mode}")
available = non_auth + (auth if include_auth else ())
if not requested:
return available
all_scenarios = {
scenario
for scenario_map in (
OFFICIAL_NON_AUTH_SCENARIOS,
OFFICIAL_AUTH_SCENARIOS,
)
for mode_scenarios in scenario_map.values()
for scenario in mode_scenarios
}
unknown = sorted(set(requested) - all_scenarios)
if unknown:
raise ValueError(
"scenarios are not part of the pinned versioned client suite: "
+ ", ".join(unknown)
)
disabled = sorted(
set(requested)
& {
scenario
for mode_scenarios in OFFICIAL_AUTH_SCENARIOS.values()
for scenario in mode_scenarios
}
if not include_auth
else ()
)
if disabled:
raise ValueError(
"authentication scenarios require auth coverage to be enabled: "
+ ", ".join(disabled)
)
requested_set = set(requested)
selected = tuple(scenario for scenario in available if scenario in requested_set)
if not selected:
raise ValueError(
f"requested scenarios are unavailable for MCP protocol version {mode}: "
+ ", ".join(sorted(requested_set))
)
return selected
def _safe_scenario_name(scenario: str) -> str:
return re.sub(r"[^A-Za-z0-9_.-]+", "-", scenario)
def _make_adapter_launcher(
adapter_script: Path,
*,
require_automatic_auth: bool = False,
) -> Path:
# The official runner currently splits --command on spaces before spawning
# it. Put a one-token launcher in the system temp directory so arbitrary
# checkout paths (including paths with spaces) remain supported.
launcher_dir = Path(tempfile.mkdtemp(prefix="mcp-conformance-adapter-"))
automatic_auth = "1" if require_automatic_auth else "0"
if sys.platform == "win32":
launcher = launcher_dir / "client.cmd"
adapter_command = subprocess.list2cmdline([sys.executable, str(adapter_script)])
launcher.write_text(
"@echo off\n"
f'set "CODEX_CONFORMANCE_REQUIRE_AUTOMATIC_AUTH={automatic_auth}"\n'
f"{adapter_command} %*\n",
encoding="utf-8",
)
else:
launcher = launcher_dir / "client"
launcher.write_text(
"#!/bin/sh\n"
f"export CODEX_CONFORMANCE_REQUIRE_AUTOMATIC_AUTH={automatic_auth}\n"
f'exec {shlex.quote(sys.executable)} {shlex.quote(str(adapter_script))} "$@"\n',
encoding="utf-8",
)
launcher.chmod(0o755)
return launcher
def _terminate_process_group(
process: subprocess.Popen[str],
*,
force: bool = False,
) -> None:
if sys.platform == "win32":
command = ["taskkill", "/T", "/PID", str(process.pid)]
if force:
command.insert(1, "/F")
try:
result = subprocess.run(
command,
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if result.returncode == 0:
return
except OSError:
pass
try:
if force:
process.kill()
else:
process.terminate()
except (OSError, ProcessLookupError):
pass
return
try:
os.killpg(process.pid, signal.SIGKILL if force else signal.SIGTERM)
except (OSError, ProcessLookupError):
pass
def _load_checks(result_dir: Path, scenario: str) -> list[OfficialCheck]:
check_files = sorted(result_dir.rglob("checks.json"))
if len(check_files) != 1:
return []
try:
decoded = json.loads(check_files[0].read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return []
if not isinstance(decoded, list):
return []
checks: list[OfficialCheck] = []
for index, raw in enumerate(decoded, start=1):
if not isinstance(raw, dict):
continue
check_id = str(raw.get("id") or f"unnamed-{index}")
name = str(raw.get("name") or check_id)
status = str(raw.get("status") or "FAILURE").upper()
# INFO entries are the suite's HTTP trace, not conformance assertions.
# They remain available in the retained upstream checks.json artifact.
if status == "INFO":
continue
checks.append(
OfficialCheck(
scenario=scenario,
check_id=check_id,
name=name,
status=status,
description=str(raw.get("description") or name),
error_message=(
redact_sensitive_text(str(raw["errorMessage"]))
if raw.get("errorMessage") is not None
else None
),
)
)
return checks
def _load_adapter_report(report_path: Path) -> tuple[bool, str]:
try:
decoded = json.loads(report_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
return False, f"Codex adapter did not write a valid report: {exc}"
if not isinstance(decoded, dict):
return False, "Codex adapter report was not an object"
success = decoded.get("success") is True
steps = decoded.get("steps")
failed_steps: list[str] = []
if isinstance(steps, list):
for step in steps:
if isinstance(step, dict) and step.get("success") is not True:
failed_steps.append(
f"{step.get('name')}: {step.get('detail', 'failed')}"
)
if success:
return True, "Codex adapter completed the scenario"
if failed_steps:
return False, redact_sensitive_text("; ".join(failed_steps))[-4_000:]
return False, redact_sensitive_text(
str(decoded.get("error") or "Codex adapter failed")
)[-4_000:]
def _run_scenario(
*,
conformance_command: Sequence[str],
adapter_launcher: Path,
codex_binary: Path,
mode: str,
scenario: str,
output_dir: Path,
timeout_seconds: float,
base_env: Mapping[str, str],
process_grace_seconds: float = 15,
) -> OfficialScenarioResult:
scenario_dir = output_dir / _safe_scenario_name(scenario)
scenario_dir.mkdir(parents=True, exist_ok=True)
adapter_report = scenario_dir / "codex-adapter.json"
adapter_home = scenario_dir / "codex-home"
adapter_home.mkdir()
env = dict(base_env)
env.update(
{
"CODEX_CONFORMANCE_BINARY": str(codex_binary),
"CODEX_CONFORMANCE_HOME": str(adapter_home),
"CODEX_CONFORMANCE_ADAPTER_REPORT": str(adapter_report),
}
)
command = [
*conformance_command,
"client",
"--command",
str(adapter_launcher),
"--scenario",
scenario,
"--spec-version",
mode,
"--timeout",
str(round(timeout_seconds * 1_000)),
"--output-dir",
str(scenario_dir),
]
process: subprocess.Popen[str] | None = None
try:
process = subprocess.Popen(
command,
env=env,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
start_new_session=sys.platform != "win32",
creationflags=(
getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
if sys.platform == "win32"
else 0
),
)
try:
process_timeout = timeout_seconds + process_grace_seconds
stdout, stderr = process.communicate(timeout=process_timeout)
runner_detail = redact_sensitive_text((stderr or stdout).strip())[-8_000:]
returncode = process.returncode
except subprocess.TimeoutExpired:
_terminate_process_group(process)
try:
stdout, stderr = process.communicate(timeout=3)
except subprocess.TimeoutExpired:
_terminate_process_group(process, force=True)
stdout, stderr = process.communicate()
runner_detail = redact_sensitive_text(
(stderr or stdout)
+ f"\nofficial scenario timed out after {process_timeout:g}s"
).strip()[-8_000:]
returncode = 124
except OSError as exc:
runner_detail = redact_sensitive_text(str(exc))
returncode = 127
# A crashing upstream runner can exit before its still-running adapter has
# atomically written the diagnostic report. Give that report a short grace
# period so an upstream fixture crash is not mislabeled as an adapter
# failure, then terminate any orphaned descendants in the runner's process
# group.
if returncode != 0 and not adapter_report.is_file():
report_deadline = time.monotonic() + min(process_grace_seconds, 10)
while time.monotonic() < report_deadline and not adapter_report.is_file():
time.sleep(0.05)
if returncode != 0 and process is not None:
_terminate_process_group(process)
_scrub_retained_artifacts(scenario_dir)
checks = _load_checks(scenario_dir, scenario)
adapter_success, adapter_detail = _load_adapter_report(adapter_report)
official_failure = any(check.status in {"FAILURE", "WARNING"} for check in checks)
success = (
returncode == 0 and bool(checks) and adapter_success and not official_failure
)
if not checks:
runner_detail = (
"official runner did not produce exactly one checks.json; " + runner_detail
).strip()
elif returncode != 0 and not official_failure and adapter_success:
runner_detail = (
f"official runner exited with code {returncode}; " + runner_detail
).strip()
return OfficialScenarioResult(
scenario=scenario,
success=success,
checks=checks,
adapter_success=adapter_success,
adapter_detail=adapter_detail,
runner_detail=runner_detail,
)
def run_official_mode(
*,
conformance_command: Sequence[str],
adapter_script: Path,
codex_binary: Path,
mode: str,
scenarios: Sequence[str],
output_dir: Path,
timeout_seconds: float,
base_env: Mapping[str, str],
) -> list[OfficialScenarioResult]:
launcher = _make_adapter_launcher(
adapter_script,
require_automatic_auth=base_env.get("CODEX_CONFORMANCE_REQUIRE_AUTOMATIC_AUTH")
== "1",
)
try:
return [
_run_scenario(
conformance_command=conformance_command,
adapter_launcher=launcher,
codex_binary=codex_binary,
mode=mode,
scenario=scenario,
output_dir=output_dir,
timeout_seconds=timeout_seconds,
base_env=base_env,
)
for scenario in scenarios
]
finally:
try:
launcher.unlink()
launcher.parent.rmdir()
except OSError:
pass

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,697 @@
import json
import subprocess
import sys
import urllib.parse
from pathlib import Path
import codex_conformance_adapter
import official_conformance
import pytest
import run_codex_compliance
from codex_conformance_adapter import (
CIMD_CLIENT_METADATA_URL,
CLIENT_REGISTRATION_OVERRIDE_ENV_VAR,
AdapterFailure,
_client_registration_override,
_exercise_auth_scenario,
_oauth_client_id,
_validate_oauth_secret_not_persisted,
_validated_callback_url,
_write_auth_registration,
)
from official_conformance import (
LEGACY_VERSION,
MODERN_VERSION,
OFFICIAL_CONFORMANCE_GIT_REF,
SHIPPING_LEGACY_VERSION,
_make_adapter_launcher,
_run_scenario,
_scrub_retained_artifacts,
_terminate_process_group,
default_conformance_command,
redact_sensitive_text,
run_official_mode,
scenarios_for_mode,
)
def _authorization_url(redirect_uri: str, state: str = "test-state") -> str:
return "http://127.0.0.1:8765/authorize?" + urllib.parse.urlencode(
{
"client_id": "test-client",
"redirect_uri": redirect_uri,
"state": state,
}
)
def test_auth_adapter_only_accepts_exact_loopback_callback() -> None:
redirect_uri = "http://127.0.0.1:32123/callback"
authorization_url = _authorization_url(redirect_uri)
callback_url = redirect_uri + "?code=test-code&state=test-state"
assert _validated_callback_url(authorization_url, callback_url) == callback_url
with pytest.raises(AdapterFailure, match="exact loopback"):
_validated_callback_url(
authorization_url,
"http://127.0.0.1:32124/callback?code=test-code&state=test-state",
)
with pytest.raises(AdapterFailure, match="preserve OAuth state"):
_validated_callback_url(
authorization_url,
redirect_uri + "?code=test-code&state=wrong-state",
)
with pytest.raises(AdapterFailure, match="safe loopback"):
_validated_callback_url(
_authorization_url("https://example.com/callback"),
"https://example.com/callback?code=test-code&state=test-state",
)
@pytest.mark.parametrize(
("query", "message"),
[
("code=first&code=second&state=test-state", "exactly one nonempty code"),
("code=&state=test-state", "exactly one nonempty code"),
("error=first&error=second&state=test-state", "exactly one nonempty error"),
("error=&state=test-state", "exactly one nonempty error"),
("code=test-code&error=access_denied&state=test-state", "exactly one of"),
("code=test-code&state=test-state&state=test-state", "preserve OAuth state"),
(
"code=test-code&state=test-state&iss=first&iss=second",
"exactly one nonempty iss",
),
("code=test-code&state=test-state&iss=", "exactly one nonempty iss"),
("state=test-state", "exactly one of"),
],
)
def test_auth_adapter_rejects_ambiguous_oauth_callback_parameters(
query: str,
message: str,
) -> None:
redirect_uri = "http://127.0.0.1:32123/callback"
with pytest.raises(AdapterFailure, match=message):
_validated_callback_url(
_authorization_url(redirect_uri),
f"{redirect_uri}?{query}",
)
def test_auth_adapter_allows_a_single_error_callback_for_client_validation() -> None:
redirect_uri = "http://127.0.0.1:32123/callback"
callback_url = redirect_uri + "?error=access_denied&state=test-state&iss=issuer"
assert (
_validated_callback_url(_authorization_url(redirect_uri), callback_url)
== callback_url
)
def test_official_runner_is_pinned_instead_of_using_npm_latest() -> None:
command = default_conformance_command()
assert OFFICIAL_CONFORMANCE_GIT_REF in command[-1]
assert "@latest" not in command[-1]
def test_official_adapter_launcher_preserves_strict_production_auth_mode(
tmp_path: Path,
) -> None:
adapter = tmp_path / "show_automatic_auth.py"
adapter.write_text(
'import os\nprint(os.environ.get("CODEX_CONFORMANCE_REQUIRE_AUTOMATIC_AUTH", ""))\n',
encoding="utf-8",
)
launcher = _make_adapter_launcher(adapter, require_automatic_auth=True)
try:
result = subprocess.run(
[str(launcher)],
capture_output=True,
check=True,
text=True,
)
finally:
launcher.unlink()
launcher.parent.rmdir()
assert result.stdout.strip() == "1"
@pytest.mark.parametrize("require_automatic_auth", [False, True])
def test_windows_official_adapter_launcher_quotes_checkout_paths(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
require_automatic_auth: bool,
) -> None:
adapter = tmp_path / "checkout with spaces" / "adapter script.py"
adapter.parent.mkdir()
adapter.write_text("raise AssertionError('launcher generation only')\n")
monkeypatch.setattr(official_conformance.sys, "platform", "win32")
launcher = _make_adapter_launcher(
adapter,
require_automatic_auth=require_automatic_auth,
)
try:
contents = launcher.read_text(encoding="utf-8")
finally:
launcher.unlink()
launcher.parent.rmdir()
expected_auth = "1" if require_automatic_auth else "0"
assert launcher.name == "client.cmd"
assert contents.startswith("@echo off\n")
assert (
f'set "CODEX_CONFORMANCE_REQUIRE_AUTOMATIC_AUTH={expected_auth}"\n' in contents
)
assert subprocess.list2cmdline([sys.executable, str(adapter)]) + " %*\n" in contents
@pytest.mark.parametrize(
("force", "expected_command"),
[
(False, ["taskkill", "/T", "/PID", "417"]),
(True, ["taskkill", "/F", "/T", "/PID", "417"]),
],
)
def test_windows_official_timeout_terminates_the_entire_process_tree(
monkeypatch: pytest.MonkeyPatch,
force: bool,
expected_command: list[str],
) -> None:
observed: list[list[str]] = []
class FakeProcess:
pid = 417
def terminate(self) -> None:
raise AssertionError("successful taskkill must own tree termination")
def kill(self) -> None:
raise AssertionError("successful taskkill must own tree termination")
def fake_run(
command: list[str],
*,
check: bool,
stdout: int,
stderr: int,
) -> subprocess.CompletedProcess[str]:
observed.append(command)
assert check is False
assert stdout == subprocess.DEVNULL
assert stderr == subprocess.DEVNULL
return subprocess.CompletedProcess(command, 0)
monkeypatch.setattr(official_conformance.sys, "platform", "win32")
monkeypatch.setattr(official_conformance.subprocess, "run", fake_run)
_terminate_process_group(
FakeProcess(), # type: ignore[arg-type] - validate the Popen process contract.
force=force,
)
assert observed == [expected_command]
@pytest.mark.parametrize(
"scenario",
["auth/scope-step-up", "auth/authorization-server-migration"],
)
def test_strict_auth_does_not_inject_a_second_login(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
scenario: str,
) -> None:
manual_reauthorizations: list[object] = []
monkeypatch.setattr(
codex_conformance_adapter,
"_oauth_login",
lambda _client, **_kwargs: (True, None),
)
monkeypatch.setattr(codex_conformance_adapter, "_reload_mcp", lambda _client: None)
monkeypatch.setattr(
codex_conformance_adapter, "_auth_inventory", lambda _client: {}
)
def fail_tool_call(_client: object, _workspace: Path) -> None:
raise AdapterFailure("reauthorization is required")
monkeypatch.setattr(codex_conformance_adapter, "_auth_tool_call", fail_tool_call)
monkeypatch.setattr(
codex_conformance_adapter,
"_login_reload_and_call",
lambda *args, **kwargs: manual_reauthorizations.append((args, kwargs)),
)
with pytest.raises(AdapterFailure, match="reauthorization is required"):
_exercise_auth_scenario(
object(), # type: ignore[arg-type]
scenario=scenario,
workspace=tmp_path,
timeout_seconds=1,
require_automatic_auth=True,
)
assert manual_reauthorizations == []
@pytest.mark.parametrize(
"scenario",
["auth/scope-step-up", "auth/authorization-server-migration"],
)
def test_strict_auth_accepts_product_owned_reauthentication(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
scenario: str,
) -> None:
tool_calls: list[Path] = []
manual_reauthorizations: list[object] = []
monkeypatch.setattr(
codex_conformance_adapter,
"_oauth_login",
lambda _client, **_kwargs: (True, None),
)
monkeypatch.setattr(codex_conformance_adapter, "_reload_mcp", lambda _client: None)
monkeypatch.setattr(
codex_conformance_adapter, "_auth_inventory", lambda _client: {}
)
monkeypatch.setattr(
codex_conformance_adapter,
"_auth_tool_call",
lambda _client, workspace: tool_calls.append(workspace),
)
monkeypatch.setattr(
codex_conformance_adapter,
"_login_reload_and_call",
lambda *args, **kwargs: manual_reauthorizations.append((args, kwargs)),
)
detail = _exercise_auth_scenario(
object(), # type: ignore[arg-type]
scenario=scenario,
workspace=tmp_path,
timeout_seconds=1,
require_automatic_auth=True,
)
assert "automatically" in detail
assert tool_calls == [tmp_path]
assert manual_reauthorizations == []
@pytest.mark.parametrize("filename", ["config.toml", ".credentials.json"])
def test_oauth_client_secret_persistence_is_detected_without_disclosing_it(
tmp_path: Path,
filename: str,
) -> None:
secret = "reviewer-confidential-client-secret"
(tmp_path / filename).write_text(
json.dumps({"client_secret": secret}),
encoding="utf-8",
)
with pytest.raises(AdapterFailure, match="client secret was persisted") as error:
_validate_oauth_secret_not_persisted(tmp_path, secret)
assert filename in str(error.value)
assert secret not in str(error.value)
def test_oauth_client_secret_environment_reference_is_not_a_persisted_secret(
tmp_path: Path,
) -> None:
(tmp_path / "config.toml").write_text(
'client_secret_env_var = "MCP_CONFORMANCE_CLIENT_SECRET"\n',
encoding="utf-8",
)
_validate_oauth_secret_not_persisted(
tmp_path, "reviewer-confidential-client-secret"
)
def test_auth_adapter_selects_only_scenario_provided_client_ids() -> None:
assert _oauth_client_id("auth/basic-cimd", {}) == CIMD_CLIENT_METADATA_URL
assert (
_oauth_client_id(
"auth/pre-registration",
{"client_id": "pre-registered", "client_secret": "do-not-log"},
)
== "pre-registered"
)
assert _oauth_client_id("auth/metadata-default", {}) is None
with pytest.raises(AdapterFailure, match="client_id"):
_oauth_client_id("auth/pre-registration", {})
@pytest.mark.parametrize(
("scenario", "require_automatic_auth", "override", "expected"),
[
("auth/offline-access-not-supported", False, None, None),
("auth/offline-access-scope", False, None, "dcr"),
("auth/offline-access-scope", True, None, None),
("auth/offline-access-scope", False, "cimd", "cimd"),
],
)
def test_auth_adapter_scopes_client_registration_overrides(
monkeypatch: pytest.MonkeyPatch,
scenario: str,
require_automatic_auth: bool,
override: str | None,
expected: str | None,
) -> None:
if override is None:
monkeypatch.delenv(CLIENT_REGISTRATION_OVERRIDE_ENV_VAR, raising=False)
else:
monkeypatch.setenv(CLIENT_REGISTRATION_OVERRIDE_ENV_VAR, override)
assert (
_client_registration_override(
scenario,
require_automatic_auth=require_automatic_auth,
)
== expected
)
def test_auth_registration_does_not_persist_context_secret(tmp_path: Path) -> None:
config_path = tmp_path / "config.toml"
config_path.write_text('mcp_oauth_credentials_store = "file"\n', encoding="utf-8")
_write_auth_registration(
config_path,
server_url="http://127.0.0.1:8765/mcp",
oauth_client_id="pre-registered-client",
oauth_client_secret_env_var="MCP_CONFORMANCE_CLIENT_SECRET",
)
config = config_path.read_text(encoding="utf-8")
assert 'url = "http://127.0.0.1:8765/mcp"' in config
assert 'client_id = "pre-registered-client"' in config
assert 'client_secret_env_var = "MCP_CONFORMANCE_CLIENT_SECRET"' in config
assert "do-not-log" not in config
assert "client_secret =" not in config
def test_official_diagnostics_redact_oauth_secrets() -> None:
diagnostic = (
'With context: {"client_id":"visible","client_secret":"secret-value",'
'"private_key_pem":"private-value"}\n'
"Authorize at http://localhost/authorize?state=state-value&code_challenge=pkce-value\n"
"Authorization: Bearer token-value"
)
redacted = redact_sensitive_text(diagnostic)
assert '"client_id":"visible"' in redacted
assert '"client_secret":"[REDACTED]"' in redacted
assert '"private_key_pem":"[REDACTED]"' in redacted
assert "state=[REDACTED]" in redacted
assert "code_challenge=[REDACTED]" in redacted
assert "Bearer [REDACTED]" in redacted
serialized = redact_sensitive_text(json.dumps({"diagnostic": diagnostic}))
assert json.loads(serialized)["diagnostic"]
for secret in (
"secret-value",
"private-value",
"state-value",
"pkce-value",
"token-value",
):
assert secret not in redacted
assert secret not in serialized
def test_retained_artifacts_remove_oauth_credential_store(tmp_path: Path) -> None:
codex_home = tmp_path / "codex-home"
codex_home.mkdir()
credentials = codex_home / ".credentials.json"
credentials.write_text('{"client_secret":"do-not-retain"}', encoding="utf-8")
stdout = tmp_path / "stdout.txt"
stdout.write_text("Bearer token-value", encoding="utf-8")
_scrub_retained_artifacts(tmp_path)
assert not credentials.exists()
assert stdout.read_text(encoding="utf-8") == "Bearer [REDACTED]"
def test_pinned_full_scenarios_are_selected_by_protocol_version() -> None:
shipping_legacy = scenarios_for_mode(SHIPPING_LEGACY_VERSION)
legacy = scenarios_for_mode(LEGACY_VERSION)
modern = scenarios_for_mode(MODERN_VERSION)
assert shipping_legacy == (
"initialize",
"tools_call",
"auth/token-endpoint-auth-basic",
"auth/token-endpoint-auth-post",
"auth/token-endpoint-auth-none",
)
assert scenarios_for_mode(SHIPPING_LEGACY_VERSION, include_auth=False) == (
"initialize",
"tools_call",
)
assert legacy[:4] == (
"initialize",
"tools_call",
"elicitation-sep1034-client-defaults",
"sse-retry",
)
assert len(legacy) == 18
assert len([scenario for scenario in legacy if scenario.startswith("auth/")]) == 14
assert "auth/pre-registration" in legacy
assert modern[:7] == (
"tools_call",
"request-metadata",
"sep-2322-client-request-state",
"http-standard-headers",
"http-custom-headers",
"http-invalid-tool-headers",
"json-schema-ref-no-deref",
)
assert len(modern) == 32
assert len([scenario for scenario in modern if scenario.startswith("auth/")]) == 25
assert "auth/resource-mismatch" in modern
assert "auth/metadata-issuer-mismatch" in modern
assert scenarios_for_mode(LEGACY_VERSION, include_auth=False) == legacy[:4]
assert scenarios_for_mode(MODERN_VERSION, include_auth=False) == modern[:7]
assert scenarios_for_mode(
MODERN_VERSION,
["tools_call", "http-custom-headers"],
) == ("tools_call", "http-custom-headers")
assert len(OFFICIAL_CONFORMANCE_GIT_REF) == 40
@pytest.mark.parametrize(
("mode", "scenario"),
[
(SHIPPING_LEGACY_VERSION, "request-metadata"),
(LEGACY_VERSION, "http-standard-headers"),
(MODERN_VERSION, "elicitation-sep1034-client-defaults"),
],
)
def test_versioned_scenario_selection_rejects_an_incompatible_protocol(
mode: str, scenario: str
) -> None:
with pytest.raises(
ValueError,
match=rf"unavailable for MCP protocol version {mode}.*{scenario}",
):
scenarios_for_mode(mode, [scenario], include_auth=False)
def test_cross_version_auth_subset_remains_available_to_every_mode() -> None:
requested = (
"auth/token-endpoint-auth-basic",
"auth/resource-mismatch",
"auth/authorization-server-migration",
)
assert scenarios_for_mode(SHIPPING_LEGACY_VERSION, requested) == (
"auth/token-endpoint-auth-basic",
)
assert scenarios_for_mode(LEGACY_VERSION, requested) == (
"auth/token-endpoint-auth-basic",
)
assert scenarios_for_mode(MODERN_VERSION, requested) == requested
def test_official_cli_rejects_an_empty_versioned_scenario_run(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
def unexpected_run(*_args: object, **_kwargs: object) -> None:
raise AssertionError("an incompatible selection must not execute conformance")
monkeypatch.setattr(run_codex_compliance, "run_compliance", unexpected_run)
exit_code = run_codex_compliance.main(
[
sys.executable,
"--mode",
SHIPPING_LEGACY_VERSION,
"--transport",
"http",
"--official-scenario",
"request-metadata",
"--no-auth",
"--conformance-cli",
sys.executable,
]
)
assert exit_code == 2
assert (
"requested scenarios are unavailable for MCP protocol version 2025-06-18: "
"request-metadata"
) in capsys.readouterr().err
def test_official_driver_reads_checks_and_adapter_report(tmp_path: Path) -> None:
fake_cli = tmp_path / "fake_conformance.py"
fake_cli.write_text(
"""
import json
import os
import pathlib
import sys
args = sys.argv[1:]
scenario = args[args.index("--scenario") + 1]
output = pathlib.Path(args[args.index("--output-dir") + 1])
result_dir = output / f"{scenario}-timestamp"
result_dir.mkdir(parents=True)
(result_dir / "checks.json").write_text(json.dumps([
{
"id": "request-trace",
"name": "RequestTrace",
"description": "not a conformance assertion",
"status": "INFO",
},
{
"id": "official-check",
"name": "OfficialCheck",
"description": "observed",
"status": "SUCCESS",
},
]))
pathlib.Path(os.environ["CODEX_CONFORMANCE_ADAPTER_REPORT"]).write_text(
json.dumps({"success": True, "steps": []})
)
""".lstrip(),
encoding="utf-8",
)
adapter = tmp_path / "adapter.py"
adapter.write_text("raise AssertionError('fake CLI should not run adapter')\n")
results = run_official_mode(
conformance_command=[sys.executable, str(fake_cli)],
adapter_script=adapter,
codex_binary=Path("/opt/codex"),
mode=MODERN_VERSION,
scenarios=["tools_call"],
output_dir=tmp_path / "results",
timeout_seconds=1,
base_env={},
)
assert len(results) == 1
assert results[0].success
assert results[0].adapter_success
assert len(results[0].checks) == 1
assert results[0].checks[0].check_id == "official-check"
def test_official_driver_terminates_timed_out_process_group(tmp_path: Path) -> None:
fake_cli = tmp_path / "hanging_conformance.py"
fake_cli.write_text(
"""
import subprocess
import sys
import time
subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
time.sleep(60)
""".lstrip(),
encoding="utf-8",
)
adapter = tmp_path / "adapter.py"
adapter.write_text("raise AssertionError('not reached')\n", encoding="utf-8")
launcher = _make_adapter_launcher(adapter)
try:
result = _run_scenario(
conformance_command=[sys.executable, str(fake_cli)],
adapter_launcher=launcher,
codex_binary=Path("/opt/codex"),
mode=MODERN_VERSION,
scenario="tools_call",
output_dir=tmp_path / "results",
timeout_seconds=0.05,
process_grace_seconds=0.05,
base_env={},
)
finally:
launcher.unlink()
launcher.parent.rmdir()
assert not result.success
assert "timed out" in result.runner_detail
def test_official_driver_does_not_mislabel_runner_crash_as_adapter_failure(
tmp_path: Path,
) -> None:
fake_cli = tmp_path / "crashing_conformance.py"
fake_cli.write_text(
"""
import os
import subprocess
import sys
script = '''
import json
import os
import pathlib
import time
time.sleep(0.1)
pathlib.Path(os.environ["CODEX_CONFORMANCE_ADAPTER_REPORT"]).write_text(
json.dumps({"success": True, "steps": []})
)
'''
subprocess.Popen([sys.executable, "-c", script], env=os.environ)
sys.exit(1)
""".lstrip(),
encoding="utf-8",
)
adapter = tmp_path / "adapter.py"
adapter.write_text("raise AssertionError('not reached')\n", encoding="utf-8")
launcher = _make_adapter_launcher(adapter)
try:
result = _run_scenario(
conformance_command=[sys.executable, str(fake_cli)],
adapter_launcher=launcher,
codex_binary=Path("/opt/codex"),
mode=MODERN_VERSION,
scenario="request-metadata",
output_dir=tmp_path / "results",
timeout_seconds=1,
process_grace_seconds=1,
base_env={},
)
finally:
launcher.unlink()
launcher.parent.rmdir()
assert not result.success
assert result.adapter_success
assert "did not produce exactly one checks.json" in result.runner_detail

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,208 @@
#!/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 = "exec-command-call"
FUNCTION_NAME = "exec_command"
FUNCTION_ARGS_JSON = json.dumps({"cmd": "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())

9
scripts/pyproject.toml Normal file
View File

@@ -0,0 +1,9 @@
[project]
name = "codex-scripts"
version = "0.0.0"
requires-python = ">=3.10"
dependencies = ["ruff>=0.15.8"]
[tool.uv]
exclude-newer = "7 days"
index-strategy = "first-index"

120
scripts/readme_toc.py Executable 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 "$@"

632
scripts/stage_npm_packages.py Executable file
View File

@@ -0,0 +1,632 @@
#!/usr/bin/env python3
"""Stage one or more Codex npm packages for release."""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextlib import contextmanager
from dataclasses import dataclass
import importlib.util
import json
import os
import shutil
import subprocess
import tarfile
import tempfile
from pathlib import Path
from typing import Sequence
REPO_ROOT = Path(__file__).resolve().parent.parent
BUILD_SCRIPT = REPO_ROOT / "codex-cli" / "scripts" / "build_npm_package.py"
WORKFLOW_NAME = ".github/workflows/rust-release.yml"
GITHUB_REPO = "openai/codex"
BINARY_TARGETS = (
"x86_64-unknown-linux-musl",
"aarch64-unknown-linux-musl",
"x86_64-apple-darwin",
"aarch64-apple-darwin",
"x86_64-pc-windows-msvc",
"aarch64-pc-windows-msvc",
)
_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", {})
CODEX_PACKAGE_COMPONENT = getattr(
_BUILD_MODULE, "CODEX_PACKAGE_COMPONENT", "codex-package"
)
@dataclass(frozen=True)
class BinaryComponent:
artifact_prefix: str
dest_dir: str
binary_basename: str
@dataclass(frozen=True)
class WorkflowArtifact:
name: str
size_in_bytes: int
BINARY_COMPONENTS = {
"codex-responses-api-proxy": BinaryComponent(
artifact_prefix="codex-responses-api-proxy",
dest_dir="codex-responses-api-proxy",
binary_basename="codex-responses-api-proxy",
),
}
def _gha_enabled() -> bool:
return os.environ.get("GITHUB_ACTIONS") == "true"
def _gha_escape(value: str) -> str:
return value.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
@contextmanager
def _gha_group(title: str):
if _gha_enabled():
print(f"::group::{_gha_escape(title)}", flush=True)
try:
yield
finally:
if _gha_enabled():
print("::endgroup::", flush=True)
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(
"--artifacts-dir",
type=Path,
help="Directory containing previously downloaded workflow 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 native_components_for_package(package: str) -> tuple[str, ...]:
return tuple(sorted(PACKAGE_NATIVE_COMPONENTS.get(package, [])))
def collect_native_component_sets(packages: list[str]) -> list[tuple[str, ...]]:
component_sets: list[tuple[str, ...]] = []
seen: set[tuple[str, ...]] = set()
for package in packages:
components = native_components_for_package(package)
if not components or components in seen:
continue
seen.add(components)
component_sets.append(components)
return component_sets
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 | None,
components: set[str],
vendor_root: Path,
artifacts_dir: Path,
) -> None:
if not components:
return
vendor_dir = vendor_root / "vendor"
vendor_dir.mkdir(parents=True, exist_ok=True)
if workflow_url is None:
with _gha_group("Install downloaded native artifacts"):
install_from_downloaded_artifacts(
artifacts_dir, sorted(components), vendor_dir
)
else:
workflow_id = workflow_url.rstrip("/").split("/")[-1]
print(
f"Downloading native artifacts from workflow {workflow_id}...", flush=True
)
with _gha_group(f"Download native artifacts from workflow {workflow_id}"):
artifacts_dir.mkdir(parents=True, exist_ok=True)
install_from_workflow_artifacts(
workflow_id,
artifacts_dir,
sorted(components),
vendor_dir,
)
print(f"Installed native dependencies into {vendor_dir}", flush=True)
def install_from_workflow_artifacts(
workflow_id: str,
artifacts_dir: Path,
components: Sequence[str],
vendor_dir: Path,
) -> None:
artifacts = select_target_artifacts(workflow_id, components)
download_artifacts(workflow_id, artifacts_dir, artifacts)
install_from_downloaded_artifacts(artifacts_dir, components, vendor_dir)
def install_from_downloaded_artifacts(
artifacts_dir: Path,
components: Sequence[str],
vendor_dir: Path,
) -> None:
if CODEX_PACKAGE_COMPONENT in components:
install_codex_package_archives(artifacts_dir, vendor_dir, BINARY_TARGETS)
install_binary_components(
artifacts_dir,
vendor_dir,
[BINARY_COMPONENTS[name] for name in components if name in BINARY_COMPONENTS],
)
def select_target_artifacts(
workflow_id: str,
components: Sequence[str],
) -> list[WorkflowArtifact]:
needs_target_artifacts = CODEX_PACKAGE_COMPONENT in components or any(
component in BINARY_COMPONENTS for component in components
)
if not needs_target_artifacts:
return []
artifacts_by_name = {
artifact.name: artifact for artifact in list_workflow_artifacts(workflow_id)
}
selected_artifacts: list[WorkflowArtifact] = []
for target in BINARY_TARGETS:
for artifact_name in [target, f"{target}-unsigned"]:
artifact = artifacts_by_name.get(artifact_name)
if artifact is not None:
selected_artifacts.append(artifact)
break
else:
raise FileNotFoundError(
f"Expected workflow artifact not found for target {target}"
)
return selected_artifacts
def list_workflow_artifacts(workflow_id: str) -> list[WorkflowArtifact]:
stdout = subprocess.check_output(
[
"gh",
"api",
f"repos/{GITHUB_REPO}/actions/runs/{workflow_id}/artifacts",
"--paginate",
"--jq",
".artifacts[] | [.name, .size_in_bytes] | @tsv",
],
text=True,
)
artifacts: list[WorkflowArtifact] = []
for line in stdout.splitlines():
name, size_in_bytes = line.split("\t", 1)
artifacts.append(WorkflowArtifact(name=name, size_in_bytes=int(size_in_bytes)))
return artifacts
def download_artifacts(
workflow_id: str,
dest_dir: Path,
artifacts: Sequence[WorkflowArtifact],
) -> None:
total_bytes = sum(artifact.size_in_bytes for artifact in artifacts)
print(
f"Downloading {len(artifacts)} artifacts ({format_bytes(total_bytes)})",
flush=True,
)
for artifact in artifacts:
artifact_dir = dest_dir / artifact.name
if artifact_dir.is_dir() and any(artifact_dir.iterdir()):
print(
f" using cached {artifact.name} ({format_bytes(artifact.size_in_bytes)})",
flush=True,
)
continue
artifact_dir.mkdir(parents=True, exist_ok=True)
print(
f" downloading {artifact.name} ({format_bytes(artifact.size_in_bytes)})",
flush=True,
)
subprocess.check_call(
[
"gh",
"run",
"download",
"--name",
artifact.name,
"--dir",
str(artifact_dir),
"--repo",
GITHUB_REPO,
workflow_id,
]
)
def install_codex_package_archives(
artifacts_dir: Path,
vendor_dir: Path,
targets: Sequence[str],
) -> None:
if not targets:
return
print(
"Installing Codex package archives for targets: " + ", ".join(targets),
flush=True,
)
max_workers = min(len(targets), max(1, (os.cpu_count() or 1)))
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(
install_single_codex_package_archive,
artifacts_dir,
vendor_dir,
target,
): target
for target in targets
}
for future in as_completed(futures):
installed_path = future.result()
print(f" installed {installed_path}", flush=True)
def install_single_codex_package_archive(
artifacts_dir: Path,
vendor_dir: Path,
target: str,
) -> Path:
artifact_subdir = artifact_dir_for_target(artifacts_dir, target)
archive_path = artifact_subdir / f"codex-package-{target}.tar.gz"
if not archive_path.exists():
raise FileNotFoundError(f"Expected package archive not found: {archive_path}")
dest_dir = vendor_dir / target
if dest_dir.exists():
shutil.rmtree(dest_dir)
dest_dir.mkdir(parents=True, exist_ok=True)
with tarfile.open(archive_path, "r:gz") as archive:
archive.extractall(dest_dir, filter="data")
return dest_dir
def install_binary_components(
artifacts_dir: Path,
vendor_dir: Path,
selected_components: Sequence[BinaryComponent],
) -> None:
for component in selected_components:
component_targets = list(BINARY_TARGETS)
print(
f"Installing {component.binary_basename} binaries for targets: "
+ ", ".join(component_targets),
flush=True,
)
max_workers = min(len(component_targets), max(1, (os.cpu_count() or 1)))
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(
install_single_binary,
artifacts_dir,
vendor_dir,
target,
component,
): target
for target in component_targets
}
for future in as_completed(futures):
installed_path = future.result()
print(f" installed {installed_path}", flush=True)
def install_single_binary(
artifacts_dir: Path,
vendor_dir: Path,
target: str,
component: BinaryComponent,
) -> Path:
artifact_subdir = artifact_dir_for_target(artifacts_dir, target)
archive_path = binary_archive_path(
artifact_subdir, component.artifact_prefix, target
)
dest_dir = vendor_dir / target / component.dest_dir
dest_dir.mkdir(parents=True, exist_ok=True)
binary_name = (
f"{component.binary_basename}.exe"
if "windows" in target
else component.binary_basename
)
dest = dest_dir / binary_name
dest.unlink(missing_ok=True)
extract_zstd_archive(archive_path, dest)
if "windows" not in target:
dest.chmod(0o755)
return dest
def binary_archive_path(artifact_dir: Path, artifact_prefix: str, target: str) -> Path:
archive_names = [archive_name_for_target(artifact_prefix, target)]
if artifact_dir.name == f"{target}-unsigned":
archive_names.append(
archive_name_for_target(artifact_prefix, f"{target}-unsigned")
)
for archive_name in archive_names:
archive_path = artifact_dir / archive_name
if archive_path.exists():
return archive_path
raise FileNotFoundError(
f"Expected artifact not found: {artifact_dir / archive_names[0]}"
)
def archive_name_for_target(artifact_prefix: str, target: str) -> str:
if "windows" in target:
return f"{artifact_prefix}-{target}.exe.zst"
return f"{artifact_prefix}-{target}.zst"
def artifact_dir_for_target(artifacts_dir: Path, target: str) -> Path:
for artifact_name in [target, f"{target}-unsigned"]:
artifact_dir = artifacts_dir / artifact_name
if artifact_dir.is_dir():
return artifact_dir
return artifacts_dir / target
def extract_zstd_archive(archive_path: Path, dest: Path) -> None:
dest.parent.mkdir(parents=True, exist_ok=True)
output_path = archive_path.parent / dest.name
subprocess.check_call(
["zstd", "-f", "-d", str(archive_path), "-o", str(output_path)]
)
shutil.move(str(output_path), dest)
def format_bytes(size_in_bytes: int) -> str:
value = float(size_in_bytes)
for unit in ["B", "KiB", "MiB"]:
if value < 1024:
return f"{value:.1f} {unit}"
value /= 1024
return f"{value:.1f} GiB"
def run_command(cmd: list[str]) -> None:
print("+", " ".join(cmd), flush=True)
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_component_sets = collect_native_component_sets(packages)
print("Expanded packages: " + ", ".join(packages), flush=True)
if native_component_sets:
component_sets = [
"(" + ", ".join(components) + ")" for components in native_component_sets
]
print(
"Native component sets: " + ", ".join(component_sets),
flush=True,
)
vendor_temp_roots: list[Path] = []
vendor_src_by_components: dict[tuple[str, ...], Path] = {}
artifacts_temp_root: Path | None = None
remove_artifacts_temp_root = False
resolved_head_sha: str | None = None
staging_jobs: list[tuple[Path, list[str], str]] = []
try:
if native_component_sets:
if args.artifacts_dir is not None:
artifacts_temp_root = args.artifacts_dir.resolve()
artifacts_temp_root.mkdir(parents=True, exist_ok=True)
else:
artifacts_temp_root = Path(
tempfile.mkdtemp(prefix="npm-native-artifacts-", dir=runner_temp)
)
remove_artifacts_temp_root = True
target_artifact_dirs = [
artifact_dir_for_target(artifacts_temp_root, target)
for target in BINARY_TARGETS
]
if args.artifacts_dir is not None and all(
artifact_dir.is_dir() and any(artifact_dir.iterdir())
for artifact_dir in target_artifact_dirs
):
workflow_url = None
else:
workflow_url, resolved_head_sha = resolve_workflow_url(
args.release_version, args.workflow_url
)
print(f"Using native artifacts from {workflow_url}", flush=True)
print(f"Using artifact cache at {artifacts_temp_root}", flush=True)
for components in native_component_sets:
vendor_temp_root = Path(
tempfile.mkdtemp(prefix="npm-native-", dir=runner_temp)
)
vendor_temp_roots.append(vendor_temp_root)
print(
"Installing native components "
+ ", ".join(components)
+ f" into {vendor_temp_root}",
flush=True,
)
install_native_components(
workflow_url,
set(components),
vendor_temp_root,
artifacts_temp_root,
)
vendor_src_by_components[components] = vendor_temp_root / "vendor"
if resolved_head_sha:
print(f"should `git checkout {resolved_head_sha}`", flush=True)
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
)
print(f"Staging {package} in {staging_dir}", flush=True)
cmd = [
str(BUILD_SCRIPT),
"--package",
package,
"--release-version",
args.release_version,
"--staging-dir",
str(staging_dir),
"--pack-output",
str(pack_output),
]
vendor_src = vendor_src_by_components.get(
native_components_for_package(package)
)
if vendor_src is not None:
cmd.extend(["--vendor-src", str(vendor_src)])
staging_jobs.append(
(staging_dir, cmd, f"Staged {package} at {pack_output}")
)
max_workers = min(len(staging_jobs), os.cpu_count() or 1)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(run_command, cmd): staging_dir
for staging_dir, cmd, _message in staging_jobs
}
for future in as_completed(futures):
try:
future.result()
finally:
if not args.keep_staging_dirs:
shutil.rmtree(futures[future], ignore_errors=True)
finally:
if not args.keep_staging_dirs:
for staging_dir, _cmd, _message in staging_jobs:
shutil.rmtree(staging_dir, ignore_errors=True)
for vendor_temp_root in vendor_temp_roots:
shutil.rmtree(vendor_temp_root, ignore_errors=True)
if remove_artifacts_temp_root and artifacts_temp_root is not None:
shutil.rmtree(artifacts_temp_root, ignore_errors=True)
for _staging_dir, _cmd, message in staging_jobs:
print(message, flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())

185
scripts/start-codex-exec.sh Executable 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}"

142
scripts/test-remote-env.sh Executable file
View File

@@ -0,0 +1,142 @@
#!/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
# just test -p codex-core --test all remote_test_env_can_connect_and_use_filesystem
# 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="${CARGO_TARGET_DIR:-${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 bubblewrap git"; 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}"
export CODEX_TEST_REMOTE_ENV_CONTAINER_NAME="${container_name}"
export CODEX_TEST_ENVIRONMENT="docker"
}
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_ENV_CONTAINER_NAME
unset CODEX_TEST_REMOTE_EXEC_SERVER_PID
unset CODEX_TEST_REMOTE_EXEC_SERVER_URL
unset CODEX_TEST_ENVIRONMENT
}
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_ENVIRONMENT=${CODEX_TEST_ENVIRONMENT}"
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}"

43
scripts/uv.lock generated Normal file
View File

@@ -0,0 +1,43 @@
version = 1
revision = 3
requires-python = ">=3.10"
[options]
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P7D"
[[package]]
name = "codex-scripts"
version = "0.0.0"
source = { virtual = "." }
dependencies = [
{ name = "ruff" },
]
[package.metadata]
requires-dist = [{ name = "ruff", specifier = ">=0.15.8" }]
[[package]]
name = "ruff"
version = "0.15.13"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/24/21/a7d5c126d5b557715ef81098f3db2fe20f622a039ff2e626af28d674ab80/ruff-0.15.13.tar.gz", hash = "sha256:f9d89f17f7ba7fb2ed42921f0df75da797a9a5d71bc39049e2c687cf2baf44b7", size = 4678180, upload-time = "2026-05-14T13:44:37.869Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c6/61/11d458dc6ac22504fd8e237b29dfd40504c7fbbcc8930402cfe51a8e63ed/ruff-0.15.13-py3-none-linux_armv6l.whl", hash = "sha256:444b580fc72fd6887e650acd3e575e18cdc79dbcf42fb4030b491057921f61f8", size = 10738279, upload-time = "2026-05-14T13:44:18.7Z" },
{ url = "https://files.pythonhosted.org/packages/86/ca/caa871ee7be718c45256fada4e16a218ee3e33f0c4a46b729a60a24912e6/ruff-0.15.13-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:6590d009e7cb7ebf36f83dbdd44a3fa48a0994ff6f1cdc1b08006abe58f98dc7", size = 11124798, upload-time = "2026-05-14T13:44:06.427Z" },
{ url = "https://files.pythonhosted.org/packages/d3/19/43f5f2e568dddde567fc41f8471f9432c09563e19d3e617a48cfa52f8f0a/ruff-0.15.13-py3-none-macosx_11_0_arm64.whl", hash = "sha256:1c26d2f66163deeb6e08d8b39fbbe983ce3c71cea06a6d7591cfd1421793c629", size = 10460761, upload-time = "2026-05-14T13:44:04.375Z" },
{ url = "https://files.pythonhosted.org/packages/99/df/cf938cd6de3003178f03ad7c1ea2a6c099468c03a35037985070b37e76be/ruff-0.15.13-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9dbd6f94b434f896308e4d57fb7bfde0d02b99f7a64b3bdab0fdfa6a864203a5", size = 10804451, upload-time = "2026-05-14T13:44:25.221Z" },
{ url = "https://files.pythonhosted.org/packages/c7/7d/5d0973129b154ded2225729169d7068f26b467760b146493fde138415f23/ruff-0.15.13-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bf3259f3be4d181bda591da5db2571aed6853c6a048157756448020bc6c5cd22", size = 10534285, upload-time = "2026-05-14T13:44:08.888Z" },
{ url = "https://files.pythonhosted.org/packages/1f/e3/6b999bbc66cd51e5f073842bc2a3995e99c5e0e72e16b15e7261f7abf57a/ruff-0.15.13-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ae9c17e5eb4430c154e76abc25d79a318190f5a997f38fb6b114416c5319ffc9", size = 11312063, upload-time = "2026-05-14T13:44:11.274Z" },
{ url = "https://files.pythonhosted.org/packages/af/5a/642639e9f5db04f1e97fbd6e091c6fd20725bdf072fb114d00eefb9e6eb8/ruff-0.15.13-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2e2e39bff6c341f4b577a21b801326fab0b11847f48fcaa83f00a113c9b3cb55", size = 12183079, upload-time = "2026-05-14T13:44:01.634Z" },
{ url = "https://files.pythonhosted.org/packages/19/4c/7585735f6b53b0f12de13618b2f7d250a844f018822efc899df2e7b8295f/ruff-0.15.13-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e8d9a8e08013542e94d3220bc5b62cc3e5ef87c5f74bff367d3fac14fab013e6", size = 11440833, upload-time = "2026-05-14T13:43:59.043Z" },
{ url = "https://files.pythonhosted.org/packages/e8/31/bf1a0803d077e679cfeee5f2f67290a0fa79c7385b5d9a8c17b9db2c48f0/ruff-0.15.13-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cc411dfebe5eebe55ce041c6ae080eb7668955e866daa2fbb16692a784f1c4ca", size = 11434486, upload-time = "2026-05-14T13:44:27.761Z" },
{ url = "https://files.pythonhosted.org/packages/e1/4e/62c9b999875d4f14db80f277c030578f5e249c9852d65b7ac7ad0b43c041/ruff-0.15.13-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:768494eb08b9cee54e2fd27969966f74db5a57f6eaa7a90fcb3306af34dfc4bd", size = 11385189, upload-time = "2026-05-14T13:44:13.704Z" },
{ url = "https://files.pythonhosted.org/packages/fc/89/7e959047a104df3eb12863447c110140191fc5b6c4f379ea2e803fcdb0e4/ruff-0.15.13-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:fb75f9a3a7e42ffe117d734494e6c5e5cb3565d66e12612cb63d0e572a41a5b6", size = 10781380, upload-time = "2026-05-14T13:43:56.734Z" },
{ url = "https://files.pythonhosted.org/packages/ff/52/5fd18f3b88cab63e88aa11516b3b4e1e5f720e5c330f8dbe5c26210f41f8/ruff-0.15.13-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:8cb74dd33bb2f6613faf7fc03b660053b5ac4f80e706d5788c6335e2a8048d51", size = 10540605, upload-time = "2026-05-14T13:44:20.748Z" },
{ url = "https://files.pythonhosted.org/packages/e8/e0/9e35f338990d3e41a82875ff7053ffe97541dae81c9d02143177f381d572/ruff-0.15.13-py3-none-musllinux_1_2_i686.whl", hash = "sha256:7ef823f817fcd191dc934e984be9cf4094f808effa16f2542ad8e821ba02bbf2", size = 11036554, upload-time = "2026-05-14T13:44:16.256Z" },
{ url = "https://files.pythonhosted.org/packages/c2/13/070fb048c24080fba188f66371e2a92785be257ad02242066dc7255ac6e9/ruff-0.15.13-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:f345a13937bd7f09f6f5d19fa0721b0c103e00e7f62bc67089a8e5e037719e0b", size = 11528133, upload-time = "2026-05-14T13:44:22.808Z" },
{ url = "https://files.pythonhosted.org/packages/6b/8c/b1e1666aef7fc6555094d73ae6cd981701781ae85b97ceefc0eebd0b4668/ruff-0.15.13-py3-none-win32.whl", hash = "sha256:4044f94208b3b05ba0fc4a4abd0558cf4d6459bd18325eead7fd8cc66f909b41", size = 10721455, upload-time = "2026-05-14T13:44:35.697Z" },
{ url = "https://files.pythonhosted.org/packages/ab/a6/870a3e8a50590bb92be184ad928c2922f088b00d9dc5c5ec7b924ee08c22/ruff-0.15.13-py3-none-win_amd64.whl", hash = "sha256:7064884d442b7d477b4e7473d12da7f08851d2b1982763c5d3f388a19468a1a4", size = 11900409, upload-time = "2026-05-14T13:44:30.389Z" },
{ url = "https://files.pythonhosted.org/packages/9b/36/9c015cd052fca743dae8cb2aeb16b551444787467db42ceab0fc968865af/ruff-0.15.13-py3-none-win_arm64.whl", hash = "sha256:2471da9bd1068c8c064b5fd9c0c4b6dddffd6369cb1cd68b29993b1709ff1b21", size = 11179336, upload-time = "2026-05-14T13:44:33.026Z" },
]

View File

@@ -0,0 +1,20 @@
@echo off
setlocal
if defined STABLE_GIT_COMMIT (
echo STABLE_GIT_COMMIT %STABLE_GIT_COMMIT%
exit /b 0
)
for /f "delims=" %%I in ('git rev-parse --verify HEAD 2^>nul') do set "BUILD_COMMIT=%%I"
if defined BUILD_COMMIT (
echo STABLE_GIT_COMMIT %BUILD_COMMIT%
exit /b 0
)
if defined GITHUB_SHA (
echo STABLE_GIT_COMMIT %GITHUB_SHA%
exit /b 0
)
echo STABLE_GIT_COMMIT unknown

15
scripts/workspace-status.sh Executable file
View File

@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${STABLE_GIT_COMMIT:-}" ]]; then
build_commit="${STABLE_GIT_COMMIT}"
elif build_commit="$(git rev-parse --verify HEAD 2>/dev/null)"; then
:
elif [[ -n "${GITHUB_SHA:-}" ]]; then
build_commit="${GITHUB_SHA}"
else
build_commit="unknown"
fi
printf 'STABLE_GIT_COMMIT %s\n' "${build_commit}"