From fbc51f2040cf295dda3a4aad16c86af9811113c3 Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Thu, 30 Jul 2026 11:30:35 +0800 Subject: [PATCH 1/9] feat: add multiplatform Alpha release support --- .github/workflows/ci.yml | 30 ++- .github/workflows/release.yml | 271 ++++++++++++++-------- .github/workflows/sync-fork-channel.yml | 2 +- README.en.md | 66 ++++-- README.md | 66 ++++-- docs/i18n/mvp-usage.md | 4 +- docs/macos-testing.md | 78 +++++++ install.ps1 | 7 +- install.sh | 141 +++++++++++ package-lock.json | 6 +- package.json | 4 +- scripts/build-executor.mjs | 2 +- scripts/download-fork-release.mjs | 5 +- scripts/package-release.mjs | 224 ++++++++++++++++++ scripts/package-release.ps1 | 2 +- scripts/verify-release-artifacts.mjs | 88 +++++++ src/config/constants.mjs | 55 ++--- src/discovery/official-codex.mjs | 220 ++++++++++-------- src/installer/bin.mjs | 48 +++- src/installer/install.mjs | 93 +++++--- src/installer/path.mjs | 23 ++ src/installer/posix-path.mjs | 109 +++++++++ src/launcher/main.mjs | 27 ++- src/launcher/select-target.mjs | 136 ++++++----- src/manage-main.mjs | 65 +++++- src/notices/once.mjs | 10 +- src/platform/runtime.mjs | 176 ++++++++++++++ src/release/ccu-update-manifest.mjs | 28 ++- src/release/ccu-version.mjs | 4 +- src/release/fork-manifest.mjs | 27 ++- src/release/github-fork.mjs | 43 +++- src/release/github-version.mjs | 31 ++- src/state/schema.mjs | 99 ++++---- src/update/check.mjs | 40 +++- src/update/upgrade.mjs | 86 +++++-- src/version.mjs | 2 +- test/install-script.test.mjs | 29 +++ test/installer/posix-path.test.mjs | 62 +++++ test/platform.test.mjs | 216 +++++++++++++++++ test/release/ccu-update-manifest.test.mjs | 9 + test/release/ccu-version.test.mjs | 1 + test/release/fork-manifest.test.mjs | 67 +++++- test/release/github-version.test.mjs | 8 + test/update-upgrade.test.mjs | 70 +++++- test/workflow-sync-channel.test.mjs | 31 ++- tui/src/main.rs | 119 +++++++++- uninstall.sh | 27 +++ 47 files changed, 2457 insertions(+), 500 deletions(-) create mode 100644 docs/macos-testing.md create mode 100644 install.sh create mode 100644 scripts/package-release.mjs create mode 100644 scripts/verify-release-artifacts.mjs create mode 100644 src/installer/path.mjs create mode 100644 src/installer/posix-path.mjs create mode 100644 src/platform/runtime.mjs create mode 100644 test/installer/posix-path.test.mjs create mode 100644 test/platform.test.mjs create mode 100644 uninstall.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index efb31ee..b186e36 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd - uses: actions/setup-node@v4 with: - node-version: "24" + node-version: "22.19.0" cache: npm - uses: dtolnay/rust-toolchain@stable with: @@ -40,3 +40,31 @@ jobs: cargo fmt --all -- --check cargo test --locked cargo build --release --locked + + unix: + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + - macos-latest + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + - uses: actions/setup-node@v4 + with: + node-version: "22.19.0" + cache: npm + - uses: dtolnay/rust-toolchain@stable + with: + toolchain: "1.96.1" + - run: npm ci + - name: Verify cross-platform runtime contracts + run: node --test test/platform.test.mjs test/installer/posix-path.test.mjs test/install-script.test.mjs test/update-upgrade.test.mjs + - run: npm run build + - name: Verify Rust manager TUI + working-directory: tui + run: | + cargo fmt --all -- --check + cargo test --locked + cargo build --release --locked diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6b8eeee..dba0a49 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,12 +4,17 @@ on: push: tags: - "v*" + - "!v*-alpha.*" workflow_dispatch: inputs: tag: description: Existing v-prefixed tag to publish required: true type: string + fork_tag: + description: Optional exact fork Release tag; required for Alpha builds + required: false + type: string permissions: contents: write @@ -19,117 +24,199 @@ concurrency: cancel-in-progress: false jobs: - windows: - runs-on: windows-latest + metadata: + runs-on: ubuntu-24.04 + outputs: + tag: ${{ steps.release.outputs.tag }} + version: ${{ steps.release.outputs.version }} + fork_tag: ${{ steps.release.outputs.fork_tag }} + prerelease: ${{ steps.release.outputs.prerelease }} + steps: + - name: Validate release channel + id: release + shell: bash + env: + RELEASE_TAG: ${{ inputs.tag || github.ref_name }} + FORK_TAG: ${{ inputs.fork_tag }} + run: | + set -euo pipefail + prerelease=false + if [[ "$RELEASE_TAG" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then + version="${BASH_REMATCH[1]}" + if [[ -n "$FORK_TAG" && ! "$FORK_TAG" =~ ^ccu-rust-v[0-9]+\.[0-9]+\.[0-9]+-r[1-9][0-9]*$ ]]; then + echo "Stable CCU releases require a stable fork tag" >&2 + exit 1 + fi + elif [[ "$RELEASE_TAG" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)-alpha\.([1-9][0-9]*)$ ]]; then + version="${BASH_REMATCH[1]}-alpha.${BASH_REMATCH[2]}" + prerelease=true + [[ "$FORK_TAG" =~ ^ccu-rust-v[0-9]+\.[0-9]+\.[0-9]+-r[1-9][0-9]*-alpha\.[1-9][0-9]*$ ]] || { + echo "Alpha CCU releases require an exact Alpha fork tag" >&2 + exit 1 + } + else + echo "invalid release tag: $RELEASE_TAG" >&2 + exit 1 + fi + { + echo "tag=$RELEASE_TAG" + echo "version=$version" + echo "fork_tag=$FORK_TAG" + echo "prerelease=$prerelease" + } >> "$GITHUB_OUTPUT" + + build: + needs: metadata + name: Build ${{ matrix.platform }} + strategy: + fail-fast: false + matrix: + include: + - platform: windows-x64 + os: windows-latest + node-platform: win32 + node-arch: x64 + update-manifest: ccu-update-manifest.json + - platform: linux-x64 + os: ubuntu-24.04 + node-platform: linux + node-arch: x64 + update-manifest: ccu-update-manifest-linux-x64.json + - platform: linux-arm64 + os: ubuntu-24.04-arm + node-platform: linux + node-arch: arm64 + update-manifest: ccu-update-manifest-linux-arm64.json + - platform: macos-x64 + os: macos-15-intel + node-platform: darwin + node-arch: x64 + update-manifest: ccu-update-manifest-macos-x64.json + - platform: macos-arm64 + os: macos-15 + node-platform: darwin + node-arch: arm64 + update-manifest: ccu-update-manifest-macos-arm64.json + runs-on: ${{ matrix.os }} + timeout-minutes: 90 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd with: ref: ${{ inputs.tag || github.ref }} - uses: actions/setup-node@v4 with: - node-version: "24" + node-version: "22.19.0" cache: npm - uses: dtolnay/rust-toolchain@stable with: toolchain: "1.96.1" - run: npm ci - - run: npm test - - name: Download and verify latest fork Release - shell: pwsh + - name: Verify runner architecture + shell: bash + env: + EXPECTED_PLATFORM: ${{ matrix.node-platform }} + EXPECTED_ARCH: ${{ matrix.node-arch }} + run: | + node -e 'if (process.platform !== process.env.EXPECTED_PLATFORM || process.arch !== process.env.EXPECTED_ARCH) { throw new Error(`runner is ${process.platform}-${process.arch}, expected ${process.env.EXPECTED_PLATFORM}-${process.env.EXPECTED_ARCH}`); }' + - name: Run full Windows regression + if: matrix.node-platform == 'win32' + run: npm test + - name: Run Unix platform contracts + if: matrix.node-platform != 'win32' + run: node --test test/platform.test.mjs test/installer/posix-path.test.mjs test/install-script.test.mjs test/update-upgrade.test.mjs + - name: Download and verify latest platform fork Release env: GITHUB_TOKEN: ${{ github.token }} - run: node scripts/download-fork-release.mjs --output artifacts/fork-release - - name: Build release package - shell: pwsh + run: node scripts/download-fork-release.mjs --output artifacts/fork-release --tag "${{ needs.metadata.outputs.fork_tag }}" + - name: Build self-contained platform package + shell: bash + env: + RELEASE_VERSION: ${{ needs.metadata.outputs.version }} run: | - $tag = '${{ inputs.tag || github.ref_name }}' - if ($tag -notmatch '^v(.+)$') { throw "invalid release tag: $tag" } - .\scripts\package-release.ps1 ` - -Version $Matches[1] ` - -OutputDirectory artifacts ` - -ForkReleaseDir artifacts/fork-release + node scripts/package-release.mjs \ + --version "$RELEASE_VERSION" \ + --output artifacts \ + --fork-release-dir artifacts/fork-release + node scripts/verify-release-artifacts.mjs \ + --directory artifacts \ + --version "$RELEASE_VERSION" \ + --platform "${{ matrix.platform }}" - uses: actions/upload-artifact@v4 with: - name: codex-cli-ultra-windows + name: ccu-release-${{ matrix.platform }} path: | - artifacts/*.zip* - artifacts/ccu-update-manifest.json + artifacts/codex-cli-ultra-v*-${{ matrix.platform }}.zip + artifacts/codex-cli-ultra-v*-${{ matrix.platform }}.zip.sha256 + artifacts/${{ matrix.update-manifest }} if-no-files-found: error + + publish: + needs: + - metadata + - build + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + ref: ${{ inputs.tag || github.ref }} + - uses: actions/setup-node@v4 + with: + node-version: "22.19.0" + - uses: actions/download-artifact@v4 + with: + pattern: ccu-release-* + path: artifacts + merge-multiple: true + - name: Verify complete release set + shell: bash + env: + RELEASE_VERSION: ${{ needs.metadata.outputs.version }} + run: | + node scripts/verify-release-artifacts.mjs \ + --directory artifacts \ + --version "$RELEASE_VERSION" - name: Publish GitHub Release - shell: pwsh + shell: bash env: GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ needs.metadata.outputs.tag }} + PRERELEASE: ${{ needs.metadata.outputs.prerelease }} run: | - $tag = '${{ inputs.tag || github.ref_name }}' - if ($tag -notmatch '^v[0-9]+\.[0-9]+\.[0-9]+$') { - throw "invalid release tag: $tag" - } - - $zipFiles = @(Get-ChildItem -LiteralPath artifacts -Filter '*.zip' -File) - if ($zipFiles.Count -ne 1) { - throw "expected exactly one release ZIP; found $($zipFiles.Count)" - } - $zip = $zipFiles[0] - $sidecar = Get-Item -LiteralPath "$($zip.FullName).sha256" - $updateManifestFile = Get-Item -LiteralPath 'artifacts/ccu-update-manifest.json' - $updateManifest = Get-Content -LiteralPath $updateManifestFile.FullName -Raw | ConvertFrom-Json - if ( - $updateManifest.releaseTag -ne $tag -or - $updateManifest.ccuVersion -ne $tag.Substring(1) -or - $updateManifest.asset.name -ne $zip.Name -or - [long]$updateManifest.asset.size -ne $zip.Length - ) { - throw "CCU update manifest does not match the release package" - } - $sidecarLine = (Get-Content -LiteralPath $sidecar.FullName -Raw).Trim() - if ($sidecarLine -notmatch '^([0-9a-fA-F]{64})\s{2}(.+)$') { - throw "invalid SHA256 sidecar: $($sidecar.Name)" - } - if ($Matches[2] -ne $zip.Name) { - throw "SHA256 sidecar names '$($Matches[2])', expected '$($zip.Name)'" - } - $actualHash = (Get-FileHash -LiteralPath $zip.FullName -Algorithm SHA256).Hash.ToLowerInvariant() - if ($actualHash -ne $Matches[1].ToLowerInvariant()) { - throw "local release ZIP SHA256 mismatch" - } - - gh release view $tag --repo $env:GITHUB_REPOSITORY *> $null - if ($LASTEXITCODE -ne 0) { - gh release create $tag $zip.FullName $sidecar.FullName $updateManifestFile.FullName ` - --repo $env:GITHUB_REPOSITORY ` - --verify-tag ` - --title "Codex CLI Ultra $tag" ` - --notes "自包含 Windows 安装包:内置已验证的 CCU i18n fork、1396 条简体中文 FTL 和 Hermes 状态栏;新版管理器支持后台任务进度、本地 fork Release 安装与二次确认卸载,并同步显示 CCU、CCU-I18N 和 OpenAI Codex 三路版本。安装器在网络失败时提供直接下载指引。" ` - --latest - } - - $release = gh release view $tag --repo $env:GITHUB_REPOSITORY ` - --json isDraft,isPrerelease,assets | ConvertFrom-Json - if ($release.isDraft -or $release.isPrerelease) { - throw "published release must be stable and non-draft" - } - $assetNames = @($release.assets | ForEach-Object name) - foreach ($expected in @($zip.Name, $sidecar.Name, $updateManifestFile.Name)) { - if ($expected -notin $assetNames) { - throw "published release is missing asset: $expected" - } - } - - $verifyDir = Join-Path $env:RUNNER_TEMP 'ccu-release-verify' - New-Item -ItemType Directory -Path $verifyDir -Force | Out-Null - gh release download $tag --repo $env:GITHUB_REPOSITORY ` - --pattern $zip.Name ` - --pattern $sidecar.Name ` - --pattern $updateManifestFile.Name ` - --dir $verifyDir ` - --clobber - $remoteZip = Join-Path $verifyDir $zip.Name - $remoteSidecar = Join-Path $verifyDir $sidecar.Name - $remoteLine = (Get-Content -LiteralPath $remoteSidecar -Raw).Trim() - if ($remoteLine -notmatch '^([0-9a-fA-F]{64})\s{2}(.+)$') { - throw "downloaded SHA256 sidecar is invalid" - } - $remoteHash = (Get-FileHash -LiteralPath $remoteZip -Algorithm SHA256).Hash.ToLowerInvariant() - if ($remoteHash -ne $Matches[1].ToLowerInvariant() -or $Matches[2] -ne $zip.Name) { - throw "downloaded release asset failed SHA256 verification" - } + set -euo pipefail + release_tier="Alpha test build" + release_flags=(--prerelease) + if [[ "$PRERELEASE" != "true" ]]; then + release_tier="Stable build" + release_flags=(--latest) + fi + if gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + gh release upload "$RELEASE_TAG" artifacts/* \ + --repo "$GITHUB_REPOSITORY" \ + --clobber + else + gh release create "$RELEASE_TAG" artifacts/* \ + --repo "$GITHUB_REPOSITORY" \ + --verify-tag \ + --title "Codex CLI Ultra $RELEASE_TAG" \ + --notes "$release_tier. Self-contained packages for Windows x64, Linux x64/ARM64, and macOS Intel/Apple Silicon. Each package includes the matching verified CCU i18n fork, Simplified Chinese FTL, Hermes status line, and the CCU Manager." \ + "${release_flags[@]}" + fi + actual_prerelease="$(gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json isPrerelease --jq .isPrerelease)" + if [[ "$actual_prerelease" != "$PRERELEASE" ]]; then + echo "Release prerelease state is $actual_prerelease, expected $PRERELEASE" >&2 + exit 1 + fi + - name: Download and verify published assets + shell: bash + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ needs.metadata.outputs.tag }} + RELEASE_VERSION: ${{ needs.metadata.outputs.version }} + run: | + mkdir remote-assets + gh release download "$RELEASE_TAG" \ + --repo "$GITHUB_REPOSITORY" \ + --dir remote-assets + node scripts/verify-release-artifacts.mjs \ + --directory remote-assets \ + --version "$RELEASE_VERSION" diff --git a/.github/workflows/sync-fork-channel.yml b/.github/workflows/sync-fork-channel.yml index 9379539..b7aa866 100644 --- a/.github/workflows/sync-fork-channel.yml +++ b/.github/workflows/sync-fork-channel.yml @@ -22,7 +22,7 @@ jobs: fetch-depth: 0 - uses: actions/setup-node@v4 with: - node-version: "24" + node-version: "22.19.0" cache: npm - run: npm ci - name: Recover a pending CCU Release before syncing a newer fork diff --git a/README.en.md b/README.en.md index 84dca0a..593f520 100644 --- a/README.en.md +++ b/README.en.md @@ -4,9 +4,11 @@ [![Release](https://img.shields.io/github/v/release/Cec1c/codex-cli-ultra?display_name=tag&style=flat-square)](https://github.com/Cec1c/codex-cli-ultra/releases/latest) ![Windows x64](https://img.shields.io/badge/Windows-x64-0078D4?style=flat-square&logo=windows11&logoColor=white) +![Linux x64 / ARM64](https://img.shields.io/badge/Linux-x64%20%2F%20ARM64-FCC624?style=flat-square&logo=linux&logoColor=black) +![macOS Intel / Apple Silicon](https://img.shields.io/badge/macOS-Intel%20%2F%20Apple%20Silicon-000000?style=flat-square&logo=apple&logoColor=white) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg?style=flat-square)](LICENSE) -Codex-Cli-Ultra (CCU) provides external FTL language packs, Windows installation management, and optional interface extensions for Codex CLI. Simplified Chinese is the current reference implementation. +Codex-Cli-Ultra (CCU) provides external FTL language packs, cross-platform installation management, and optional interface extensions for Codex CLI. Simplified Chinese is the current reference implementation. [Latest Release](https://github.com/Cec1c/codex-cli-ultra/releases/latest) · [Contributing](CONTRIBUTING.md) · [Codex i18n fork](https://github.com/Cec1c/codex) @@ -37,10 +39,10 @@ The terminal background, font, and colors are provided by a separate terminal co ### Requirements -- Windows x64 -- PowerShell 7 -- Node.js 24 or newer +- Windows x64, Linux x64/ARM64, or macOS Intel/Apple Silicon +- Node.js 22.19.0 or newer - Official Codex installed through npm +- PowerShell 7 on Windows; Bash on Linux and macOS ```powershell npm install -g @openai/codex @@ -48,9 +50,9 @@ npm install -g @openai/codex ### Release installation (recommended) -1. Download `codex-cli-ultra-v*-windows-x64.zip` and its `.sha256` from [Releases](https://github.com/Cec1c/codex-cli-ultra/releases/latest). +1. Download the ZIP for your platform and its `.sha256` from [Releases](https://github.com/Cec1c/codex-cli-ultra/releases/latest). 2. Verify the SHA256 and extract the ZIP. -3. Run `install.cmd`. +3. Run `install.cmd` on Windows or `./install.sh` on Linux/macOS. 4. Open a new terminal and verify the installation: ```powershell @@ -61,11 +63,31 @@ codex --yolo The Release ZIP includes a fork binary verified against its manifest, file size, and SHA256. +| System | Release suffix | Installer | +| --- | --- | --- | +| Windows x64 | `windows-x64.zip` | `install.cmd` | +| Linux x64 | `linux-x64.zip` | `./install.sh` | +| Linux ARM64 | `linux-arm64.zip` | `./install.sh` | +| macOS Intel | `macos-x64.zip` | `./install.sh` | +| macOS Apple Silicon | `macos-arm64.zip` | `./install.sh` | + +Linux/macOS example: + +```bash +sha256sum -c codex-cli-ultra-v*-linux-x64.zip.sha256 # use shasum -a 256 -c on macOS +unzip codex-cli-ultra-v*-linux-x64.zip +cd codex-cli-ultra-v*-linux-x64 +./install.sh +source ~/.bashrc # use source ~/.zshrc for zsh +``` + +The multi-platform Release pipeline is being landed. If the latest Release does not yet contain your Unix asset, use the source installation below rather than another platform's binary. + To remove CCU and return to the official English build: ```powershell codex-ultra uninstall -# or run uninstall.cmd from the Release package +# or run uninstall.cmd / ./uninstall.sh from the Release package ``` ### Source installation @@ -79,11 +101,20 @@ npm ci .\install.ps1 ``` +Linux/macOS: + +```bash +git clone https://github.com/Cec1c/codex-cli-ultra.git +cd codex-cli-ultra +npm ci +./install.sh +``` + This repository builds the CCU manager, not the complete Codex Rust project. CCU-I18N still requires a fork binary that follows the Release manifest contract. The installer resolves the fork Release in this order: -1. A directory passed through `-ForkReleaseDir`; +1. A directory passed through `-ForkReleaseDir` on Windows or `--fork-release-dir` on Linux/macOS; 2. `fork-release/` in the repository root; 3. The latest stable asset from [`Cec1c/codex` Releases](https://github.com/Cec1c/codex/releases). @@ -104,6 +135,7 @@ Use [`Cec1c/codex`](https://github.com/Cec1c/codex) when building the fork from | `i` | Install a detected local fork Release | | `u` | Update CCU-I18N | | `f` | Synchronize language and theme content | +| `o` | Open the CCU Release page in a browser | | `x` | Remove CCU after confirmation | | `q` | Exit | @@ -156,8 +188,8 @@ codex-cli-ultra/ ├── templates/languages/ # English FTL template ├── test/ # Node.js tests ├── tui/ # Rust Ratatui manager -├── install.ps1 / install.cmd -└── uninstall.ps1 / uninstall.cmd +├── install.ps1 / install.cmd / install.sh +└── uninstall.ps1 / uninstall.cmd / uninstall.sh ``` `dist/`, `tui/target/`, and `artifacts/` are generated build outputs rather than maintenance entry points for languages or themes. @@ -196,9 +228,9 @@ node src/cli.mjs language validate ` | Channel | Current example | Updated when | | --- | --- | --- | -| CCU | `v0.1.7` | Installer, manager, content, or documentation changes | -| CCU-I18N fork | `0.144.6-ccu.i18n.2` | Codex source or the i18n interface changes | -| OpenAI Codex | `0.144.6` | A new official stable version is released | +| CCU | `v0.1.8-alpha.1` | Installer, manager, content, or documentation changes | +| CCU-I18N fork | `v0.145.0-CCU.R2` (Alpha) | Codex source or the i18n interface changes | +| OpenAI Codex | `0.145.0` | A new official stable version is released | Automation checks upstream stable Releases every six hours. A CCU-only update does not rebuild the fork; a new fork Release is created only when fork code must change. @@ -206,14 +238,16 @@ Automation checks upstream stable Releases every six hours. A CCU-only update do | Item | Status | | --- | --- | -| Supported platform | Windows x64 | -| CCU | `v0.1.7` | -| CCU-I18N | `0.144.6-ccu.i18n.2` | +| Supported platforms | Windows x64; Linux x64/ARM64; macOS Intel/Apple Silicon | +| CCU | `v0.1.8-alpha.1` | +| CCU-I18N | `v0.145.0-CCU.R2` (Alpha) | | Reference locale | Simplified Chinese (`zh-CN`) | | FTL coverage | 1,396 actively used message keys | | Fallback | Built-in English per message | | Customization | Optional Hermes status line; additional theme work is in progress | +Windows x64 regression and a real Linux x64 install/remove smoke test have passed. Linux ARM64 and both macOS architectures are wired into the build matrix; macOS still requires real-device acceptance using the [macOS test checklist](docs/macos-testing.md). + ## Contributing New language packs, translation corrections, compatibility reports, and interface extensions are welcome. Contributors for other locales can use the English template, English Issues, and English pull requests without referring to the Chinese pack. diff --git a/README.md b/README.md index 4483582..bd6060f 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,11 @@ [![Release](https://img.shields.io/github/v/release/Cec1c/codex-cli-ultra?display_name=tag&style=flat-square)](https://github.com/Cec1c/codex-cli-ultra/releases/latest) ![Windows x64](https://img.shields.io/badge/Windows-x64-0078D4?style=flat-square&logo=windows11&logoColor=white) +![Linux x64 / ARM64](https://img.shields.io/badge/Linux-x64%20%2F%20ARM64-FCC624?style=flat-square&logo=linux&logoColor=black) +![macOS Intel / Apple Silicon](https://img.shields.io/badge/macOS-Intel%20%2F%20Apple%20Silicon-000000?style=flat-square&logo=apple&logoColor=white) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg?style=flat-square)](LICENSE) -Codex-Cli-Ultra(CCU)为 Codex CLI 提供外部 FTL 语言包、Windows 安装管理和可选的界面扩展。当前参考实现为简体中文。 +Codex-Cli-Ultra(CCU)为 Codex CLI 提供外部 FTL 语言包、跨平台安装管理和可选的界面扩展。当前参考实现为简体中文。 [最新 Release](https://github.com/Cec1c/codex-cli-ultra/releases/latest) · [贡献指南](CONTRIBUTING.md) · [Codex i18n fork](https://github.com/Cec1c/codex) · [LinuxDo](https://linux.do) @@ -37,10 +39,10 @@ Codex-Cli-Ultra(CCU)为 Codex CLI 提供外部 FTL 语言包、Windows 安 ### 环境要求 -- Windows x64 -- PowerShell 7 -- Node.js 24 或更高版本 +- Windows x64、Linux x64/ARM64,或 macOS Intel/Apple Silicon +- Node.js 22.19.0 或更高版本 - 通过 npm 安装的官方 Codex +- Windows 安装需要 PowerShell 7;Linux/macOS 安装需要 Bash ```powershell npm install -g @openai/codex @@ -48,9 +50,9 @@ npm install -g @openai/codex ### Release 安装(推荐) -1. 从 [Releases](https://github.com/Cec1c/codex-cli-ultra/releases/latest) 下载 `codex-cli-ultra-v*-windows-x64.zip` 和对应的 `.sha256`。 +1. 从 [Releases](https://github.com/Cec1c/codex-cli-ultra/releases/latest) 下载当前系统对应的 ZIP 和 `.sha256`。 2. 校验 SHA256 并解压 ZIP。 -3. 运行 `install.cmd`。 +3. Windows 运行 `install.cmd`;Linux/macOS 运行 `./install.sh`。 4. 打开新终端并验证: ```powershell @@ -61,11 +63,31 @@ codex --yolo Release ZIP 已内置经过 manifest、文件大小和 SHA256 校验的 fork 二进制。 +| 系统 | Release 文件后缀 | 安装入口 | +| --- | --- | --- | +| Windows x64 | `windows-x64.zip` | `install.cmd` | +| Linux x64 | `linux-x64.zip` | `./install.sh` | +| Linux ARM64 | `linux-arm64.zip` | `./install.sh` | +| macOS Intel | `macos-x64.zip` | `./install.sh` | +| macOS Apple Silicon | `macos-arm64.zip` | `./install.sh` | + +Linux/macOS 示例: + +```bash +sha256sum -c codex-cli-ultra-v*-linux-x64.zip.sha256 # macOS 可用 shasum -a 256 -c +unzip codex-cli-ultra-v*-linux-x64.zip +cd codex-cli-ultra-v*-linux-x64 +./install.sh +source ~/.bashrc # zsh 使用 source ~/.zshrc +``` + +多平台 Release 流水线正在落地;若最新 Release 尚无对应 Unix 资产,请使用下面的源码安装方式,不要下载其他平台的二进制。 + 卸载 CCU 并恢复官方英文版: ```powershell codex-ultra uninstall -# 或运行 Release 包中的 uninstall.cmd +# 或运行 Release 包中的 uninstall.cmd / ./uninstall.sh ``` ### 我非要源码安装 @@ -79,11 +101,20 @@ npm ci .\install.ps1 ``` +Linux/macOS: + +```bash +git clone https://github.com/Cec1c/codex-cli-ultra.git +cd codex-cli-ultra +npm ci +./install.sh +``` + 本仓库只编译 CCU 管理器,不编译完整的 Codex Rust 项目。运行 CCU-I18N 仍需要符合发布 manifest 的 fork 二进制。 安装器按以下顺序查找 fork Release: -1. `-ForkReleaseDir` 指定的目录; +1. `-ForkReleaseDir`(Windows)或 `--fork-release-dir`(Linux/macOS)指定的目录; 2. 仓库根目录的 `fork-release/`; 3. [`Cec1c/codex` Releases](https://github.com/Cec1c/codex/releases) 中的最新稳定版本。 @@ -104,6 +135,7 @@ npm ci | `i` | 安装检测到的本地 fork Release | | `u` | 更新 CCU-I18N | | `f` | 同步语言包和主题 | +| `o` | 在浏览器中打开 CCU Release 页面 | | `x` | 二次确认卸载 | | `q` | 退出 | @@ -158,8 +190,8 @@ codex-cli-ultra/ ├── templates/languages/ # 英文 FTL 模板 ├── test/ # Node.js 测试 ├── tui/ # Rust Ratatui 管理器 -├── install.ps1 / install.cmd -└── uninstall.ps1 / uninstall.cmd +├── install.ps1 / install.cmd / install.sh +└── uninstall.ps1 / uninstall.cmd / uninstall.sh ``` `dist/`、`tui/target/` 和 `artifacts/` 为构建产物,不是语言包或主题的维护入口。 @@ -198,9 +230,9 @@ node src/cli.mjs language validate ` | 通道 | 当前版本示例 | 更新条件 | | --- | --- | --- | -| CCU | `v0.1.7` | 安装器、管理器、内容包或文档发生变化 | -| CCU-I18N fork | `0.144.6-ccu.i18n.2` | Codex 源码或 i18n 接口发生变化 | -| OpenAI Codex | `0.144.6` | 官方发布新的稳定版本 | +| CCU | `v0.1.8-alpha.1` | 安装器、管理器、内容包或文档发生变化 | +| CCU-I18N fork | `v0.145.0-CCU.R2`(Alpha) | Codex 源码或 i18n 接口发生变化 | +| OpenAI Codex | `0.145.0` | 官方发布新的稳定版本 | 自动化每 6 小时检查上游稳定 Release。CCU 的独立更新不会触发 fork 重新编译;只有 fork 代码需要变化时才创建新的 fork Release。 @@ -208,15 +240,15 @@ node src/cli.mjs language validate ` | 项目 | 状态 | | --- | --- | -| 支持平台 | Windows x64 | -| CCU | `v0.1.7` | -| CCU-I18N | `0.144.6-ccu.i18n.2` | +| 支持平台 | Windows x64;Linux x64/ARM64;macOS Intel/Apple Silicon | +| CCU | `v0.1.8-alpha.1` | +| CCU-I18N | `v0.145.0-CCU.R2`(Alpha) | | 参考语言包 | 简体中文 `zh-CN` | | FTL 覆盖 | 1,396 个实际使用的消息键 | | 回退机制 | 按消息回退到内置英文 | | 个性化 | 可选 Hermes 状态栏;其他主题能力仍在开发中 | -Mac 和 Linux也许以后会做,主要是我手上没有Mac +当前 Windows x64 回归与 Linux x64 真环境安装/卸载冒烟已通过。Linux ARM64 和两种 macOS 架构已接入构建矩阵;macOS 仍需真人实机验收,详见 [macOS 验收清单](docs/macos-testing.md)。 ## 贡献指南 diff --git a/docs/i18n/mvp-usage.md b/docs/i18n/mvp-usage.md index 7133938..b048891 100644 --- a/docs/i18n/mvp-usage.md +++ b/docs/i18n/mvp-usage.md @@ -29,12 +29,12 @@ ## 2. 环境要求 / Requirements - Windows 11 与 PowerShell 7。 -- Node.js 24 或更高版本,以及 npm。 +- Node.js 22.19.0 或更高版本,以及 npm。 - Git,以及包含固定提交的 `openai/codex` 源码仓库。 - 上游 `rust-toolchain.toml` 指定的 Rust/Cargo 1.95.0。 - Windows 11 and PowerShell 7. -- Node.js 24 or newer, plus npm. +- Node.js 22.19.0 or newer, plus npm. - Git and an `openai/codex` source repository containing the pinned commit. - Rust/Cargo 1.95.0 selected by the upstream `rust-toolchain.toml`. diff --git a/docs/macos-testing.md b/docs/macos-testing.md new file mode 100644 index 0000000..b6f09c6 --- /dev/null +++ b/docs/macos-testing.md @@ -0,0 +1,78 @@ +# macOS 实机验收清单 + +这份清单用于 CCU 的 macOS 真人验收。代码和 CI 同时覆盖 Apple Silicon(`macos-arm64`)与 Intel(`macos-x64`),但不能替代 Gatekeeper、终端配置和浏览器联动的真实设备测试。 + +## 测试信息 + +记录以下信息后再开始: + +- Mac 型号、CPU 架构和 macOS 版本; +- `node --version`、`npm --version`、`codex --version`; +- 下载的 CCU ZIP 文件名和 SHA256; +- 默认 shell(通常为 zsh)及所用终端(Terminal、iTerm2 或 VS Code)。 + +Apple Silicon 和 Intel 各完成一次为完整验收;只有一类设备时,应明确记录另一类仍由 CI 覆盖、未做实机验证。 + +## 安装与 Gatekeeper + +1. 安装官方 npm Codex,确认安装 CCU 前 `codex --version` 正常。 +2. 下载与 CPU 匹配的 ZIP 和 `.sha256`,运行: + + ```bash + shasum -a 256 -c codex-cli-ultra-v*-macos-*.zip.sha256 + unzip codex-cli-ultra-v*-macos-*.zip + cd codex-cli-ultra-v*-macos-* + xattr -lr . | grep -i quarantine || true + ./install.sh + ``` + +3. 如果 Gatekeeper 拦截,保留完整提示和截图。确认文件来自本项目 Release 且 SHA256 已通过后,才可对解压目录执行: + + ```bash + xattr -dr com.apple.quarantine . + ./install.sh + ``` + +4. 确认 `~/.zshrc` 中只有一组 CCU PATH 标记;重新运行安装器不应重复追加。 +5. 打开全新终端,确认 `command -v codex` 指向 CCU 安装目录。 + +## 功能验收 + +依次验证: + +```bash +codex --version +codex --i18n-self-check +codex-ultra status --json +ccu-manager +``` + +在 CCU Manager 中: + +- `r` 能刷新本地状态; +- `c` 能查询三个版本通道; +- `o` 能使用默认浏览器打开 `https://github.com/Cec1c/codex-cli-ultra/releases`; +- 状态栏开关、内容同步和 TUI 中英文显示正常; +- 若有比当前版本更新的测试 Release,执行一次 CCU 自动更新,确认 Manager 退出后完成切换并重新打开。 + +再启动一次 `codex --yolo`,确认中文界面、键盘输入、窗口缩放和退出均正常。 + +## 卸载与官方回退 + +运行: + +```bash +codex-ultra uninstall +exec zsh -l +command -v codex +codex --version +``` + +验收标准: + +- CCU 安装目录已删除; +- `~/.zshrc`、`~/.zprofile` 中没有残留 CCU PATH 标记; +- `codex` 回到安装前的官方 npm 版本; +- 原有 Codex 登录和配置仍可用。 + +报告失败时,请附上失败命令、完整 stderr、`codex-ultra status --json` 输出,以及是否经过 Gatekeeper/quarantine 处理;不要包含 API key、token 或其他凭据。 diff --git a/install.ps1 b/install.ps1 index 982314a..da836f7 100644 --- a/install.ps1 +++ b/install.ps1 @@ -155,14 +155,15 @@ function Assert-ChildPath { $sourceRoot = $PSScriptRoot $packaged = Test-Path -LiteralPath (Join-Path $sourceRoot 'bin\codex-ultra.mjs') -PathType Leaf -$nodePath = Resolve-ApplicationPath -Name 'node' -InstallHint 'Install Node.js 24 or newer and retry.' +$nodePath = Resolve-ApplicationPath -Name 'node' -InstallHint 'Install Node.js 22.19.0 or newer and retry.' $nodeVersionText = (& $nodePath --version).Trim().TrimStart('v') if ($LASTEXITCODE -ne 0) { throw "Unable to read the Node.js version (exit code $LASTEXITCODE)." } $nodeVersion = $null -if (-not [version]::TryParse($nodeVersionText, [ref]$nodeVersion) -or $nodeVersion.Major -lt 24) { - throw "Node.js 24 or newer is required; found $nodeVersionText." +$minimumNodeVersion = [version]'22.19.0' +if (-not [version]::TryParse($nodeVersionText, [ref]$nodeVersion) -or $nodeVersion -lt $minimumNodeVersion) { + throw "Node.js 22.19.0 or newer is required; found $nodeVersionText." } Write-Host '' Write-Host 'Codex CLI Ultra 中文版安装程序' -ForegroundColor Green diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..a470ab8 --- /dev/null +++ b/install.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +set -euo pipefail + +source_root=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +install_root=${CODEX_ULTRA_HOME:-} +fork_release_dir="" +skip_build=false +non_interactive=false +preserve_statusline=false +statusline_mode="" + +while (($#)); do + case "$1" in + --install-root) + install_root=${2:?--install-root requires a path} + shift 2 + ;; + --fork-release-dir) + fork_release_dir=${2:?--fork-release-dir requires a path} + shift 2 + ;; + --skip-build) + skip_build=true + shift + ;; + --non-interactive) + non_interactive=true + shift + ;; + --preserve-statusline) + preserve_statusline=true + shift + ;; + --enable-statusline|--disable-statusline) + if [[ -n "$statusline_mode" ]]; then + echo "choose only one status-line mode" >&2 + exit 2 + fi + statusline_mode=$1 + shift + ;; + *) + echo "unknown option: $1" >&2 + exit 2 + ;; + esac +done + +if [[ -z "$install_root" ]]; then + if [[ $(uname -s) == Darwin ]]; then + install_root="$HOME/Library/Application Support/codex-cli-ultra" + else + install_root="${XDG_DATA_HOME:-$HOME/.local/share}/codex-cli-ultra" + fi +fi + +command -v node >/dev/null 2>&1 || { + echo "Node.js 22.19.0 or newer is required." >&2 + exit 1 +} +node -e 'const [major, minor] = process.versions.node.split(".").map(Number); if (major < 22 || (major === 22 && minor < 19)) process.exit(1)' || { + echo "Node.js 22.19.0 or newer is required; found $(node --version)." >&2 + exit 1 +} + +source_root=$(node -e 'process.stdout.write(require("node:fs").realpathSync(process.argv[1]))' "$source_root") +install_root=$(node -e 'process.stdout.write(require("node:path").resolve(process.argv[1]))' "$install_root") +if [[ -e "$install_root" ]]; then + install_root=$(node -e 'process.stdout.write(require("node:fs").realpathSync(process.argv[1]))' "$install_root") +fi +if [[ "$install_root" == "$source_root" ]]; then + echo "Install root must not be the installer source directory." >&2 + exit 1 +fi + +packaged=false +if [[ -f "$source_root/bin/codex-ultra.mjs" ]]; then + packaged=true +fi + +if [[ $packaged == false && $skip_build == false ]]; then + command -v npm >/dev/null 2>&1 || { echo "npm is required for a source install." >&2; exit 1; } + command -v cargo >/dev/null 2>&1 || { echo "Cargo is required for a source install." >&2; exit 1; } + ( + cd "$source_root" + npm ci + npm run build + cd tui + cargo build --release --locked + ) +fi + +if [[ $packaged == true ]]; then + manager_entry="$source_root/bin/codex-ultra.mjs" + manager_executable="$source_root/bin/ccu-manager" + content_root="$source_root/content" +else + manager_entry="$source_root/dist/codex-ultra.mjs" + manager_executable="$source_root/tui/target/release/ccu-manager" + content_root="$source_root" +fi + +for required in "$manager_entry" "$manager_executable"; do + [[ -f "$required" ]] || { echo "required build output is missing: $required" >&2; exit 1; } +done +chmod 755 "$manager_executable" + +if [[ -z "$fork_release_dir" && -d "$source_root/fork-release" ]]; then + if compgen -G "$source_root/fork-release/ccu-fork-manifest*.json" >/dev/null; then + fork_release_dir="$source_root/fork-release" + fi +fi + +if [[ -z "$statusline_mode" && $preserve_statusline == false && $non_interactive == false ]]; then + read -r -p "Enable the optional CCU Hermes status line? [y/N] " answer + if [[ $answer =~ ^([yY]|[yY][eE][sS])$ ]]; then + statusline_mode="--enable-statusline" + else + statusline_mode="--disable-statusline" + fi +fi + +export CODEX_ULTRA_HOME="$install_root" +export CODEX_CCU_CONTENT_ROOT="$content_root" +arguments=("$manager_entry" install) +if [[ -n "$fork_release_dir" ]]; then + arguments+=(--release-dir "$fork_release_dir") +fi +if [[ -n "$statusline_mode" ]]; then + arguments+=("$statusline_mode") +fi + +echo "Installing Codex CLI Ultra into $install_root" +node "${arguments[@]}" +mkdir -p "$install_root/bin" +install -m 755 "$manager_executable" "$install_root/bin/ccu-manager" + +echo +echo "Codex CLI Ultra installation completed." +echo "Open a new terminal, then run: codex --version" +echo "If the command is not found yet, source your shell profile or add $install_root/bin to PATH." diff --git a/package-lock.json b/package-lock.json index becb12f..87d76ea 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codex-cli-ultra", - "version": "0.1.7", + "version": "0.1.8-alpha.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codex-cli-ultra", - "version": "0.1.7", + "version": "0.1.8-alpha.1", "dependencies": { "@fluent/bundle": "0.19.1", "@fluent/syntax": "0.19.0", @@ -18,7 +18,7 @@ "yazl": "3.3.1" }, "engines": { - "node": ">=24" + "node": ">=22.19.0" } }, "node_modules/@esbuild/aix-ppc64": { diff --git a/package.json b/package.json index 8c5805d..d561970 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "codex-cli-ultra", - "version": "0.1.7", + "version": "0.1.8-alpha.1", "private": true, "type": "module", "packageManager": "npm@11.12.1", "engines": { - "node": ">=24" + "node": ">=22.19.0" }, "scripts": { "build": "node scripts/build-executor.mjs", diff --git a/scripts/build-executor.mjs b/scripts/build-executor.mjs index 6babf0c..aa2c06a 100644 --- a/scripts/build-executor.mjs +++ b/scripts/build-executor.mjs @@ -19,7 +19,7 @@ export async function buildExecutors(options = {}) { outExtension: { ".js": ".mjs" }, platform: "node", format: "esm", - target: "node24", + target: "node22.19", bundle: true, banner: { js: 'import { createRequire as __ccuCreateRequire } from "node:module"; const require = __ccuCreateRequire(import.meta.url);' diff --git a/scripts/download-fork-release.mjs b/scripts/download-fork-release.mjs index 16a7a37..dc6a912 100644 --- a/scripts/download-fork-release.mjs +++ b/scripts/download-fork-release.mjs @@ -14,8 +14,11 @@ function optionValue(args, name) { const output = resolve( optionValue(process.argv.slice(2), "--output") ?? "artifacts/fork-release" ); +const releaseTag = + optionValue(process.argv.slice(2), "--tag")?.trim() || undefined; const latest = await resolveLatestForkRelease({ - token: process.env.GITHUB_TOKEN + token: process.env.GITHUB_TOKEN, + releaseTag }); await mkdir(output, { recursive: true }); const manifestPath = resolve(output, FORK_MANIFEST_NAME); diff --git a/scripts/package-release.mjs b/scripts/package-release.mjs new file mode 100644 index 0000000..eaf015b --- /dev/null +++ b/scripts/package-release.mjs @@ -0,0 +1,224 @@ +import { spawnSync } from "node:child_process"; +import { createWriteStream } from "node:fs"; +import { + cp, + mkdir, + readdir, + readFile, + rm, + stat, + writeFile +} from "node:fs/promises"; +import { basename, join, relative, resolve, sep } from "node:path"; + +import yazl from "yazl"; + +import { RUNTIME_PLATFORM } from "../src/config/constants.mjs"; +import { + ccuUpdateManifestName, + validateCcuUpdateManifest +} from "../src/release/ccu-update-manifest.mjs"; +import { + forkManifestName, + validateForkManifest +} from "../src/release/fork-manifest.mjs"; +import { sha256File } from "../src/release/hash.mjs"; + +const root = resolve(import.meta.dirname, ".."); + +function option(name, fallback = undefined) { + const index = process.argv.indexOf(name); + if (index === -1) return fallback; + if (index === process.argv.length - 1 || process.argv[index + 1].startsWith("--")) { + throw new Error(`${name} requires a value`); + } + return process.argv[index + 1]; +} + +function assertChild(parent, candidate, label) { + const rootPath = resolve(parent); + const target = resolve(candidate); + const relation = relative(rootPath, target); + if (!relation || relation === ".." || relation.startsWith(`..${sep}`)) { + throw new Error(`${label} must stay inside the output directory`); + } + return target; +} + +function run(command, args, cwd = root) { + const result = spawnSync(command, args, { cwd, stdio: "inherit", shell: false }); + if (result.error) throw result.error; + if (result.status !== 0) { + throw new Error(`${command} ${args.join(" ")} failed with exit code ${result.status}`); + } +} + +async function copy(source, destination, mode = undefined) { + await cp(source, destination, { recursive: true, force: true }); + if (mode !== undefined && !RUNTIME_PLATFORM.isWindows) { + const { chmod } = await import("node:fs/promises"); + await chmod(destination, mode); + } +} + +async function listFiles(directory, prefix = "") { + const files = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name; + const absolutePath = join(directory, entry.name); + if (entry.isSymbolicLink()) { + throw new Error(`release staging contains a symbolic link: ${relativePath}`); + } + if (entry.isDirectory()) { + files.push(...await listFiles(absolutePath, relativePath)); + } else if (entry.isFile()) { + files.push({ absolutePath, relativePath }); + } else { + throw new Error(`release staging contains an unsupported entry: ${relativePath}`); + } + } + return files; +} + +async function createZip(sourceDirectory, destination) { + const zip = new yazl.ZipFile(); + const rootName = basename(sourceDirectory); + for (const file of await listFiles(sourceDirectory)) { + const metadata = await stat(file.absolutePath); + zip.addFile(file.absolutePath, `${rootName}/${file.relativePath}`, { + mode: metadata.mode + }); + } + await new Promise((resolvePromise, reject) => { + zip.outputStream + .pipe(createWriteStream(destination, { flags: "wx" })) + .once("close", resolvePromise) + .once("error", reject); + zip.end(); + }); +} + +const packageJson = JSON.parse(await readFile(join(root, "package.json"), "utf8")); +const version = option("--version", packageJson.version); +if (!/^\d+\.\d+\.\d+(?:-alpha\.[1-9]\d*)?$/.test(version)) { + throw new Error("--version must be x.y.z or x.y.z-alpha.N"); +} +const output = resolve(option("--output", join(root, "artifacts"))); +const forkReleaseOption = option("--fork-release-dir"); +if (!forkReleaseOption) throw new Error("--fork-release-dir is required"); +const forkReleaseDir = resolve(forkReleaseOption); +const skipBuild = process.argv.includes("--skip-build"); +await mkdir(output, { recursive: true }); + +const manifestName = forkManifestName(RUNTIME_PLATFORM); +const forkManifestPath = join(forkReleaseDir, manifestName); +const forkManifest = validateForkManifest( + JSON.parse(await readFile(forkManifestPath, "utf8")), + { platform: RUNTIME_PLATFORM.target } +); +const forkAssetPath = join(forkReleaseDir, forkManifest.asset.name); +const forkHash = await sha256File(forkAssetPath); +if ( + forkHash.size !== forkManifest.asset.size || + forkHash.sha256 !== forkManifest.asset.sha256 +) { + throw new Error("bundled fork asset size or SHA-256 does not match its manifest"); +} + +if (!skipBuild) { + run(RUNTIME_PLATFORM.isWindows ? "npm.cmd" : "npm", ["run", "build"]); + run("cargo", ["build", "--release", "--locked"], join(root, "tui")); +} + +const name = `codex-cli-ultra-v${version}-${RUNTIME_PLATFORM.id}`; +const stage = assertChild(output, join(output, name), "release staging directory"); +const zipPath = assertChild(output, join(output, `${name}.zip`), "release ZIP"); +const updateManifestPath = assertChild( + output, + join(output, ccuUpdateManifestName(RUNTIME_PLATFORM)), + "CCU update manifest" +); +await rm(stage, { recursive: true, force: true }); +await rm(zipPath, { force: true }); +await rm(`${zipPath}.sha256`, { force: true }); +await mkdir(join(stage, "bin"), { recursive: true }); +await mkdir(join(stage, "content", "languages"), { recursive: true }); +await mkdir(join(stage, "content", "themes"), { recursive: true }); +await mkdir(join(stage, "content", "catalog"), { recursive: true }); +await mkdir(join(stage, "fork-release"), { recursive: true }); + +await copy(join(root, "dist", "codex-ultra.mjs"), join(stage, "bin", "codex-ultra.mjs")); +await copy(join(root, "dist", "launcher.mjs"), join(stage, "bin", "launcher.mjs")); +await copy( + join(root, "tui", "target", "release", RUNTIME_PLATFORM.managerName), + join(stage, "bin", RUNTIME_PLATFORM.managerName), + 0o755 +); +await copy( + join(root, "packages", "languages", "zh-CN"), + join(stage, "content", "languages", "zh-CN") +); +await copy( + join(root, "packages", "themes", "ccu-hermes"), + join(stage, "content", "themes", "ccu-hermes") +); +await copy( + join(root, "research", "codex-0.144.5", "tui-messages.jsonl"), + join(stage, "content", "catalog", "tui-messages.jsonl") +); +await copy( + join(root, "templates", "languages", "messages.en-US.ftl"), + join(stage, "content", "catalog", "messages.en-US.ftl") +); +await copy(join(root, "packages", "quota.example.json"), join(stage, "content", "quota.example.json")); +await copy(forkManifestPath, join(stage, "fork-release", manifestName)); +await copy(forkAssetPath, join(stage, "fork-release", forkManifest.asset.name)); + +if (RUNTIME_PLATFORM.isWindows) { + for (const name of ["install.ps1", "install.cmd", "uninstall.ps1", "uninstall.cmd"]) { + await copy(join(root, name), join(stage, name)); + } +} else { + await copy(join(root, "install.sh"), join(stage, "install.sh"), 0o755); + await copy(join(root, "uninstall.sh"), join(stage, "uninstall.sh"), 0o755); +} +for (const name of ["README.md", "README.en.md", "LICENSE"]) { + await copy(join(root, name), join(stage, name)); +} + +await createZip(stage, zipPath); +const packageHash = await sha256File(zipPath); +await writeFile( + `${zipPath}.sha256`, + `${packageHash.sha256.slice("sha256:".length)} ${basename(zipPath)}\n`, + "ascii" +); +const updateManifest = validateCcuUpdateManifest({ + schemaVersion: 1, + type: "codex-cli-ultra-update", + ccuVersion: version, + releaseTag: `v${version}`, + platform: RUNTIME_PLATFORM.id, + minimumManagerVersion: "0.1.5", + bundledFork: { + releaseTag: forkManifest.releaseTag, + displayVersion: forkManifest.displayVersion, + upstreamVersion: forkManifest.upstreamVersion, + i18nApiVersion: forkManifest.i18nApiVersion + }, + asset: { + name: basename(zipPath), + size: packageHash.size, + sha256: packageHash.sha256 + } +}); +await writeFile(updateManifestPath, `${JSON.stringify(updateManifest, null, 2)}\n`, "utf8"); + +process.stdout.write(`${JSON.stringify({ + version, + platform: RUNTIME_PLATFORM.id, + package: stage, + zip: zipPath, + sha256: packageHash.sha256.slice("sha256:".length), + updateManifest: updateManifestPath +})}\n`); diff --git a/scripts/package-release.ps1 b/scripts/package-release.ps1 index 828a020..d48b79a 100644 --- a/scripts/package-release.ps1 +++ b/scripts/package-release.ps1 @@ -1,6 +1,6 @@ [CmdletBinding()] param( - [string]$Version = '0.1.7', + [string]$Version = '0.1.8-alpha.1', [string]$MinimumManagerVersion = '0.1.5', [string]$OutputDirectory = $(Join-Path (Split-Path -Parent $PSScriptRoot) 'artifacts'), [string]$ForkReleaseDir = $env:CCU_FORK_RELEASE_DIR diff --git a/scripts/verify-release-artifacts.mjs b/scripts/verify-release-artifacts.mjs new file mode 100644 index 0000000..24b09d3 --- /dev/null +++ b/scripts/verify-release-artifacts.mjs @@ -0,0 +1,88 @@ +import { readFile, stat } from "node:fs/promises"; +import { basename, join, resolve } from "node:path"; + +import { validateCcuUpdateManifest } from "../src/release/ccu-update-manifest.mjs"; +import { sha256File } from "../src/release/hash.mjs"; + +const SUPPORTED_PLATFORMS = Object.freeze([ + "windows-x64", + "linux-x64", + "linux-arm64", + "macos-x64", + "macos-arm64" +]); + +function option(name, fallback = undefined) { + const index = process.argv.indexOf(name); + if (index === -1) return fallback; + if (index === process.argv.length - 1 || process.argv[index + 1].startsWith("--")) { + throw new Error(`${name} requires a value`); + } + return process.argv[index + 1]; +} + +function options(name) { + const values = []; + for (let index = 0; index < process.argv.length; index += 1) { + if (process.argv[index] !== name) continue; + if (index === process.argv.length - 1 || process.argv[index + 1].startsWith("--")) { + throw new Error(`${name} requires a value`); + } + values.push(process.argv[index + 1]); + } + return values; +} + +const directory = resolve(option("--directory", "artifacts")); +const version = option("--version"); +if (!/^\d+\.\d+\.\d+(?:-alpha\.[1-9]\d*)?$/.test(version ?? "")) { + throw new Error("--version must be x.y.z or x.y.z-alpha.N"); +} +const requested = options("--platform"); +const platforms = requested.length === 0 ? SUPPORTED_PLATFORMS : requested; +if (new Set(platforms).size !== platforms.length) { + throw new Error("--platform values must be unique"); +} +for (const platform of platforms) { + if (!SUPPORTED_PLATFORMS.includes(platform)) { + throw new Error(`unsupported release platform: ${platform}`); + } +} + +const verified = []; +for (const platform of platforms) { + const zipName = `codex-cli-ultra-v${version}-${platform}.zip`; + const manifestName = platform === "windows-x64" + ? "ccu-update-manifest.json" + : `ccu-update-manifest-${platform}.json`; + const zipPath = join(directory, zipName); + const manifestPath = join(directory, manifestName); + const sidecarPath = `${zipPath}.sha256`; + const manifest = validateCcuUpdateManifest( + JSON.parse(await readFile(manifestPath, "utf8")), + { releaseTag: `v${version}`, platform } + ); + const [archive, metadata, sidecar] = await Promise.all([ + sha256File(zipPath), + stat(zipPath), + readFile(sidecarPath, "ascii") + ]); + if ( + manifest.asset.name !== zipName || + manifest.asset.size !== metadata.size || + manifest.asset.sha256 !== archive.sha256 + ) { + throw new Error(`${platform} update manifest does not match its archive`); + } + const match = sidecar.trim().match(/^([a-f0-9]{64}) (.+)$/); + if ( + match === null || + match[1] !== archive.sha256.slice("sha256:".length) || + match[2] !== basename(zipPath) + ) { + throw new Error(`${platform} SHA-256 sidecar does not match its archive`); + } + verified.push({ platform, zip: zipName, manifest: manifestName, sha256: match[1] }); +} + +process.stdout.write(`${JSON.stringify({ version, directory, verified }, null, 2)}\n`); diff --git a/src/config/constants.mjs b/src/config/constants.mjs index be83a13..452e4b1 100644 --- a/src/config/constants.mjs +++ b/src/config/constants.mjs @@ -1,11 +1,22 @@ -import { join, resolve, win32 } from "node:path"; +import { win32 } from "node:path"; + +import { + RUNTIME_PLATFORM, + isAbsoluteLocalPath, + isPathInside, + pathIdentity, + pathsEqual, + resolvePlatformInstallRoot, + resolveRuntimePlatform +} from "../platform/runtime.mjs"; export const STATE_SCHEMA_VERSION = 1; export const RELEASE_MANIFEST_SCHEMA_VERSION = 1; export const LANGUAGE_SCHEMA_VERSION = 1; export const I18N_API_VERSION = 1; export const CATALOG_VERSION = 1; -export const PLATFORM = "x86_64-pc-windows-msvc"; +export const PLATFORM = RUNTIME_PLATFORM.target; +export { RUNTIME_PLATFORM, isAbsoluteLocalPath, isPathInside, pathsEqual }; export function isAbsoluteLocalWindowsPath(value) { return ( @@ -17,38 +28,28 @@ export function isAbsoluteLocalWindowsPath(value) { } export function windowsPathIdentity(value) { - return win32.resolve(value).toLowerCase(); + return pathIdentity( + value, + resolveRuntimePlatform({ platform: "win32", arch: "x64" }) + ); } export function windowsPathsEqual(left, right) { - return windowsPathIdentity(left) === windowsPathIdentity(right); + return pathsEqual( + left, + right, + resolveRuntimePlatform({ platform: "win32", arch: "x64" }) + ); } export function isWindowsPathInside(root, candidate) { - const relation = win32.relative( - win32.resolve(root), - win32.resolve(candidate) - ); - return ( - relation === "" || - (relation !== ".." && - !relation.startsWith("..\\") && - !win32.isAbsolute(relation)) + return isPathInside( + root, + candidate, + resolveRuntimePlatform({ platform: "win32", arch: "x64" }) ); } -export function resolveInstallRoot(env = process.env) { - let root; - if (env.CODEX_ULTRA_HOME) { - root = resolve(env.CODEX_ULTRA_HOME); - } else { - if (!env.LOCALAPPDATA) { - throw new Error("LOCALAPPDATA is required on Windows"); - } - root = join(env.LOCALAPPDATA, "codex-cli-ultra"); - } - if (!isAbsoluteLocalWindowsPath(root)) { - throw new Error("install root must be on a local Windows drive"); - } - return root; +export function resolveInstallRoot(env = process.env, runtime = RUNTIME_PLATFORM) { + return resolvePlatformInstallRoot(env, runtime); } diff --git a/src/discovery/official-codex.mjs b/src/discovery/official-codex.mjs index 5aa5e7a..b4386f9 100644 --- a/src/discovery/official-codex.mjs +++ b/src/discovery/official-codex.mjs @@ -1,23 +1,15 @@ import { execFile as execFileCallback } from "node:child_process"; import { readFile, realpath, stat } from "node:fs/promises"; import { - delimiter, - dirname, - join, - resolve -} from "node:path"; -import { promisify } from "node:util"; - -import { - isAbsoluteLocalWindowsPath, - isWindowsPathInside, + RUNTIME_PLATFORM, + isAbsoluteLocalPath, + isPathInside, resolveInstallRoot } from "../config/constants.mjs"; +import { pathApiFor } from "../platform/runtime.mjs"; +import { promisify } from "node:util"; const execFilePromise = promisify(execFileCallback); -const PLATFORM_PACKAGE = "@openai/codex-win32-x64"; -const PLATFORM_SUFFIX = "win32-x64"; -const TARGET = "x86_64-pc-windows-msvc"; function parsePackageJson(source, label) { let value; @@ -35,45 +27,57 @@ function parsePackageJson(source, label) { return value; } -function assertOutsideInstallRoot(installRoot, candidate) { - if (isWindowsPathInside(installRoot, candidate)) { +function assertOutsideInstallRoot(installRoot, candidate, runtime) { + if (isPathInside(installRoot, candidate, runtime)) { throw new Error( `official Codex path is inside the Codex Ultra install root: ${candidate}` ); } } -async function resolveExistingFile(path, label, realpathFile) { +async function resolveExistingFile(path, label, realpathFile, runtime) { + const pathApi = pathApiFor(runtime); let canonical; try { - canonical = resolve(await realpathFile(path)); + canonical = pathApi.resolve(await realpathFile(path)); } catch (error) { throw new Error(`${label} is unavailable`, { cause: error }); } - if (!isAbsoluteLocalWindowsPath(canonical)) { - throw new Error(`${label} resolved outside a local Windows drive`); + if (!isAbsoluteLocalPath(canonical, runtime)) { + throw new Error( + runtime.isWindows + ? `${label} resolved outside a local Windows drive` + : `${label} resolved outside an absolute local path` + ); } return canonical; } -async function canonicalizeInstallRoot(path, realpathFile) { - const resolved = resolve(path); +async function canonicalizeInstallRoot(path, realpathFile, runtime) { + const pathApi = pathApiFor(runtime); + const resolved = pathApi.resolve(path); let canonical; try { - canonical = resolve(await realpathFile(resolved)); + canonical = pathApi.resolve(await realpathFile(resolved)); } catch (error) { if (error?.code === "ENOENT") { return resolved; } throw new Error("Codex Ultra install root is unsafe", { cause: error }); } - if (!isAbsoluteLocalWindowsPath(canonical)) { - throw new Error("Codex Ultra install root resolved outside a local Windows drive"); + if (!isAbsoluteLocalPath(canonical, runtime)) { + throw new Error( + runtime.isWindows + ? "Codex Ultra install root resolved outside a local Windows drive" + : "Codex Ultra install root resolved outside an absolute local path" + ); } return canonical; } -function sanitizeExecEnvironment(env, installRoot) { +function sanitizeExecEnvironment(env, installRoot, runtime) { + const pathApi = pathApiFor(runtime); + const delimiter = runtime.isWindows ? ";" : ":"; const result = {}; let pathValue; for (const [key, value] of Object.entries(env)) { @@ -90,19 +94,19 @@ function sanitizeExecEnvironment(env, installRoot) { .map((entry) => entry.trim().replace(/^"(.*)"$/, "$1")) .filter((entry) => { if ( - !isAbsoluteLocalWindowsPath(entry) || - isWindowsPathInside(installRoot, entry) + !isAbsoluteLocalPath(entry, runtime) || + isPathInside(installRoot, entry, runtime) ) { return false; } - const identity = entry.toLowerCase(); + const identity = runtime.isWindows ? entry.toLowerCase() : entry; if (seen.has(identity)) { return false; } seen.add(identity); return true; }) - .map((entry) => resolve(entry)); + .map((entry) => pathApi.resolve(entry)); result.PATH = localEntries.join(delimiter); } return result; @@ -112,46 +116,52 @@ async function resolveTrustedNpmCommand({ env, installRoot, realpathFile, - statFile + statFile, + runtime }) { + const pathApi = pathApiFor(runtime); + const delimiter = runtime.isWindows ? ";" : ":"; const pathValue = env.PATH ?? ""; for (const directory of pathValue.split(delimiter)) { if (!directory) continue; - const candidate = join(directory, "npm.cmd"); + const candidate = pathApi.join(directory, runtime.isWindows ? "npm.cmd" : "npm"); if (/[%!^&|<>"\r\n]/.test(candidate)) continue; let npmCommand; let nodePath; let npmCliPath; try { - npmCommand = resolve(await realpathFile(candidate)); + npmCommand = pathApi.resolve(await realpathFile(candidate)); if ( - !isAbsoluteLocalWindowsPath(npmCommand) || - isWindowsPathInside(installRoot, npmCommand) + !isAbsoluteLocalPath(npmCommand, runtime) || + isPathInside(installRoot, npmCommand, runtime) ) { continue; } - const npmDirectory = dirname(npmCommand); - nodePath = resolve(await realpathFile(join(npmDirectory, "node.exe"))); - npmCliPath = resolve( - await realpathFile( - join(npmDirectory, "node_modules", "npm", "bin", "npm-cli.js") - ) - ); - if ( - !isAbsoluteLocalWindowsPath(nodePath) || - !isAbsoluteLocalWindowsPath(npmCliPath) || - isWindowsPathInside(installRoot, nodePath) || - isWindowsPathInside(installRoot, npmCliPath) - ) { - continue; + if (runtime.isWindows) { + const npmDirectory = pathApi.dirname(npmCommand); + nodePath = pathApi.resolve( + await realpathFile(pathApi.join(npmDirectory, "node.exe")) + ); + npmCliPath = pathApi.resolve( + await realpathFile( + pathApi.join(npmDirectory, "node_modules", "npm", "bin", "npm-cli.js") + ) + ); + if ( + !isAbsoluteLocalPath(nodePath, runtime) || + !isAbsoluteLocalPath(npmCliPath, runtime) || + isPathInside(installRoot, nodePath, runtime) || + isPathInside(installRoot, npmCliPath, runtime) + ) { + continue; + } } - const [npmStats, nodeStats, cliStats] = await Promise.all([ - statFile(npmCommand), - statFile(nodePath), - statFile(npmCliPath) - ]); + const paths = runtime.isWindows + ? [npmCommand, nodePath, npmCliPath] + : [npmCommand]; + const metadataList = await Promise.all(paths.map((path) => statFile(path))); if ( - [npmStats, nodeStats, cliStats].some( + metadataList.some( (metadata) => !metadata || (typeof metadata.isFile === "function" && !metadata.isFile()) || @@ -165,7 +175,11 @@ async function resolveTrustedNpmCommand({ } return { npmCommand, nodePath, npmCliPath }; } - throw new Error("no trusted npm.cmd found on the local PATH"); + throw new Error( + runtime.isWindows + ? "no trusted npm.cmd found on the local PATH" + : "no trusted npm found on PATH" + ); } async function resolveNpmRoot({ @@ -174,68 +188,80 @@ async function resolveNpmRoot({ env, installRoot, realpathFile, - statFile + statFile, + runtime }) { + const pathApi = pathApiFor(runtime); if (npmRoot !== undefined) { - return resolve(npmRoot); + return pathApi.resolve(npmRoot); } const npm = await resolveTrustedNpmCommand({ env, installRoot, realpathFile, - statFile + statFile, + runtime }); - const execEnv = { ...env, PATH: dirname(npm.nodePath) }; + const executable = runtime.isWindows ? npm.nodePath : npm.npmCommand; + const args = runtime.isWindows ? [npm.npmCliPath, "root", "-g"] : ["root", "-g"]; + const execEnv = runtime.isWindows + ? { ...env, PATH: pathApi.dirname(npm.nodePath) } + : env; const result = await execFile( - npm.nodePath, - [npm.npmCliPath, "root", "-g"], + executable, + args, { env: execEnv, encoding: "utf8", - windowsHide: true + windowsHide: runtime.isWindows } ); const stdout = typeof result === "string" ? result : String(result?.stdout ?? ""); const discovered = stdout.trim(); if (!discovered) { - throw new Error("npm.cmd root -g returned an empty path"); + throw new Error("npm root -g returned an empty path"); } - return resolve(discovered); + return pathApi.resolve(discovered); } export async function discoverOfficialCodex(options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; + const pathApi = pathApiFor(runtime); const env = options.env ?? process.env; const runExecFile = options.execFile ?? execFilePromise; const readFileImpl = options.readFile ?? readFile; const realpathImpl = options.realpath ?? realpath; const statImpl = options.stat ?? stat; const installRoot = await canonicalizeInstallRoot( - options.installRoot ?? resolveInstallRoot(env), - realpathImpl + options.installRoot ?? resolveInstallRoot(env, runtime), + realpathImpl, + runtime ); const npmRoot = await resolveNpmRoot({ npmRoot: options.npmRoot, execFile: runExecFile, - env: sanitizeExecEnvironment(env, installRoot), + env: sanitizeExecEnvironment(env, installRoot, runtime), installRoot, realpathFile: realpathImpl, - statFile: statImpl + statFile: statImpl, + runtime }); - if (!isAbsoluteLocalWindowsPath(installRoot)) { - throw new Error("install root must be on a local Windows drive"); + if (!isAbsoluteLocalPath(installRoot, runtime)) { + throw new Error("install root must be an absolute local path"); } - if (!isAbsoluteLocalWindowsPath(npmRoot)) { - throw new Error("npm root must be on a local Windows drive"); + if (!isAbsoluteLocalPath(npmRoot, runtime)) { + throw new Error("npm root must be an absolute local path"); } const packageJsonPath = await resolveExistingFile( - join(npmRoot, "@openai", "codex", "package.json"), + pathApi.join(npmRoot, "@openai", "codex", "package.json"), "official Codex package.json", - realpathImpl + realpathImpl, + runtime ); - assertOutsideInstallRoot(installRoot, packageJsonPath); + assertOutsideInstallRoot(installRoot, packageJsonPath, runtime); const manifest = parsePackageJson( await readFileImpl(packageJsonPath, "utf8"), "official Codex package.json" @@ -243,50 +269,52 @@ export async function discoverOfficialCodex(options = {}) { if (manifest.name !== "@openai/codex") { throw new Error("official Codex package has an unexpected name"); } - const expectedPlatformVersion = `${manifest.version}-${PLATFORM_SUFFIX}`; + const expectedPlatformVersion = `${manifest.version}-${runtime.npmSuffix}`; const expectedDependency = `npm:@openai/codex@${expectedPlatformVersion}`; - if (manifest.optionalDependencies?.[PLATFORM_PACKAGE] !== expectedDependency) { + if (manifest.optionalDependencies?.[runtime.npmPackage] !== expectedDependency) { throw new Error( - "official package does not declare the exact Windows platform dependency" + runtime.isWindows + ? "official package does not declare the exact Windows platform dependency" + : `official package does not declare the exact ${runtime.id} platform dependency` ); } const platformPackageJsonPath = await resolveExistingFile( - join( - dirname(packageJsonPath), + pathApi.join( + pathApi.dirname(packageJsonPath), "node_modules", - "@openai", - "codex-win32-x64", + ...runtime.npmPackage.split("/"), "package.json" ), - "official Windows platform package.json", - realpathImpl + `official ${runtime.id} platform package.json`, + realpathImpl, + runtime ); - assertOutsideInstallRoot(installRoot, platformPackageJsonPath); + assertOutsideInstallRoot(installRoot, platformPackageJsonPath, runtime); const platformManifest = parsePackageJson( await readFileImpl(platformPackageJsonPath, "utf8"), - "official Windows platform package.json" + `official ${runtime.id} platform package.json` ); if (platformManifest.name !== "@openai/codex") { - throw new Error("official Windows platform package has an unexpected name"); + throw new Error(`official ${runtime.id} platform package has an unexpected name`); } if (platformManifest.version !== expectedPlatformVersion) { - throw new Error("official Windows platform package version does not match"); + throw new Error(`official ${runtime.id} platform package version does not match`); } - const expectedBinaryPath = join( - dirname(platformPackageJsonPath), + const expectedBinaryPath = pathApi.join( + pathApi.dirname(platformPackageJsonPath), "vendor", - TARGET, + runtime.target, "bin", - "codex.exe" + runtime.binaryName ); let binaryPath; let binaryStats; try { - binaryPath = resolve(await realpathImpl(expectedBinaryPath)); - if (!isAbsoluteLocalWindowsPath(binaryPath)) { - throw new Error("binary resolved outside a local Windows drive"); + binaryPath = pathApi.resolve(await realpathImpl(expectedBinaryPath)); + if (!isAbsoluteLocalPath(binaryPath, runtime)) { + throw new Error("binary resolved outside an absolute local path"); } binaryStats = await statImpl(binaryPath); } catch (error) { @@ -299,7 +327,7 @@ export async function discoverOfficialCodex(options = {}) { ) { throw new Error("official Codex binary is missing"); } - assertOutsideInstallRoot(installRoot, binaryPath); + assertOutsideInstallRoot(installRoot, binaryPath, runtime); return { version: manifest.version, diff --git a/src/installer/bin.mjs b/src/installer/bin.mjs index bcdad41..3ff1556 100644 --- a/src/installer/bin.mjs +++ b/src/installer/bin.mjs @@ -2,20 +2,41 @@ import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; -const WRAPPERS = Object.freeze({ +import { + RUNTIME_PLATFORM, + pathsEqual +} from "../config/constants.mjs"; + +const WINDOWS_WRAPPERS = Object.freeze({ "codex.cmd": '@echo off\r\nnode "%~dp0launcher.mjs" %*\r\nexit /b %ERRORLEVEL%\r\n', "codex.ps1": "#!/usr/bin/env pwsh\n& node (Join-Path $PSScriptRoot 'launcher.mjs') @args\nexit $LASTEXITCODE\n", "codex-ultra.cmd": '@echo off\r\nset "NODE_USE_ENV_PROXY=1"\r\nset "CODEX_CCU_CONTENT_ROOT=%~dp0..\\content"\r\nnode "%~dp0codex-ultra.mjs" %*\r\nexit /b %ERRORLEVEL%\r\n', "codex-ultra.ps1": "#!/usr/bin/env pwsh\n$env:NODE_USE_ENV_PROXY = '1'\n$env:CODEX_CCU_CONTENT_ROOT = Join-Path $PSScriptRoot '..\\content'\n& node (Join-Path $PSScriptRoot 'codex-ultra.mjs') @args\nexit $LASTEXITCODE\n" }); -async function replaceFileAtomic(path, bytes, fsOps = {}) { +const POSIX_WRAPPERS = Object.freeze({ + codex: `#!/bin/sh +set -eu +script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +exec node "$script_dir/launcher.mjs" "$@" +`, + "codex-ultra": `#!/bin/sh +set -eu +script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +default_content_root=$(CDPATH= cd -- "$script_dir/../content" && pwd) +export NODE_USE_ENV_PROXY=1 +export CODEX_CCU_CONTENT_ROOT="\${CODEX_CCU_CONTENT_ROOT:-$default_content_root}" +exec node "$script_dir/codex-ultra.mjs" "$@" +` +}); + +async function replaceFileAtomic(path, bytes, fsOps = {}, mode = 0o644) { const write = fsOps.writeFile ?? writeFile; const move = fsOps.rename ?? rename; const remove = fsOps.rm ?? rm; const temporary = `${path}.tmp-${randomUUID()}`; try { - await write(temporary, bytes, { flag: "wx" }); + await write(temporary, bytes, { flag: "wx", mode }); await move(temporary, path); } catch (error) { await remove(temporary, { force: true }).catch(() => {}); @@ -23,8 +44,8 @@ async function replaceFileAtomic(path, bytes, fsOps = {}) { } } -async function copyBundle(source, destination, fsOps) { - if (resolve(source).toLowerCase() === resolve(destination).toLowerCase()) { +async function copyBundle(source, destination, fsOps, runtime) { + if (pathsEqual(resolve(source), resolve(destination), runtime)) { return; } const read = fsOps.readFile ?? readFile; @@ -35,20 +56,29 @@ export async function installManagementBin(options) { if (!options?.binDirectory) throw new Error("binDirectory is required"); if (!options.managerSource) throw new Error("managerSource is required"); if (!options.launcherSource) throw new Error("launcherSource is required"); + const runtime = options.runtime ?? RUNTIME_PLATFORM; const fsOps = options.fsOps ?? {}; await (fsOps.mkdir ?? mkdir)(options.binDirectory, { recursive: true }); await copyBundle( options.managerSource, join(options.binDirectory, "codex-ultra.mjs"), - fsOps + fsOps, + runtime ); await copyBundle( options.launcherSource, join(options.binDirectory, "launcher.mjs"), - fsOps + fsOps, + runtime ); - for (const [name, source] of Object.entries(WRAPPERS)) { - await replaceFileAtomic(join(options.binDirectory, name), source, fsOps); + const wrappers = runtime.isWindows ? WINDOWS_WRAPPERS : POSIX_WRAPPERS; + for (const [name, source] of Object.entries(wrappers)) { + await replaceFileAtomic( + join(options.binDirectory, name), + source, + fsOps, + runtime.isWindows ? 0o644 : 0o755 + ); } return { binDirectory: options.binDirectory }; } diff --git a/src/installer/install.mjs b/src/installer/install.mjs index c8d220e..452214b 100644 --- a/src/installer/install.mjs +++ b/src/installer/install.mjs @@ -1,6 +1,7 @@ import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; import { + chmod, lstat, mkdir, open, @@ -11,16 +12,17 @@ import { stat, writeFile } from "node:fs/promises"; -import { dirname, join, resolve } from "node:path"; +import { dirname, join } from "node:path"; import { MESSAGE_SPECS } from "../catalog/message-specs.mjs"; import { - PLATFORM, + RUNTIME_PLATFORM, STATE_SCHEMA_VERSION, - isAbsoluteLocalWindowsPath, + isAbsoluteLocalPath, + pathsEqual, resolveInstallRoot, - windowsPathsEqual } from "../config/constants.mjs"; +import { pathApiFor } from "../platform/runtime.mjs"; import { discoverOfficialCodex } from "../discovery/official-codex.mjs"; import { validateLanguagePack } from "../language/validate.mjs"; import { buildLaunchEnvironment } from "../launcher/select-target.mjs"; @@ -100,7 +102,11 @@ const RECOVERABLE_ROOT_FILES = new Set([ ]); const CCU_RELEASE_ID = /^\d+\.\d+\.\d+-ccu\.i18n\.\d+$/; -async function isRecoverableCcuInstallRoot(installRoot, entries) { +async function isRecoverableCcuInstallRoot( + installRoot, + entries, + runtime = RUNTIME_PLATFORM +) { let releasesEntry = null; for (const entry of entries) { if (entry.isSymbolicLink()) return false; @@ -133,10 +139,10 @@ async function isRecoverableCcuInstallRoot(installRoot, entries) { installRoot, "releases", release.name, - PLATFORM, + runtime.target, "package", "bin", - "codex.exe" + runtime.binaryName ); const metadata = await pathExists(binaryPath); if (!metadata?.isFile() || metadata.isSymbolicLink()) return false; @@ -337,7 +343,8 @@ export async function readOptionalState(path, readStateImpl) { } } -export async function ensureOwnershipMarker(installRoot) { +export async function ensureOwnershipMarker(installRoot, options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; let rootMetadata = await pathExists(installRoot); if (rootMetadata) { if (!rootMetadata.isDirectory() || rootMetadata.isSymbolicLink()) { @@ -361,7 +368,7 @@ export async function ensureOwnershipMarker(installRoot) { if ( existing?.schemaVersion !== 1 || typeof existing.root !== "string" || - !windowsPathsEqual(existing.root, installRoot) || + !pathsEqual(existing.root, installRoot, runtime) || Reflect.ownKeys(existing).length !== 2 ) { throw new Error("Codex Ultra ownership marker does not match install root"); @@ -371,7 +378,7 @@ export async function ensureOwnershipMarker(installRoot) { const rootEntries = await readdir(installRoot, { withFileTypes: true }); if ( rootEntries.length !== 0 && - !(await isRecoverableCcuInstallRoot(installRoot, rootEntries)) + !(await isRecoverableCcuInstallRoot(installRoot, rootEntries, runtime)) ) { throw new Error("install root is not empty and has no ownership marker"); } @@ -492,12 +499,14 @@ export function statesEqual(left, right) { export async function installFromProvider(options) { if (!options?.provider) throw new Error("provider is required"); if (!options.catalogPath) throw new Error("catalogPath is required"); + const runtime = options.runtime ?? RUNTIME_PLATFORM; + const pathApi = pathApiFor(runtime); const env = options.env ?? process.env; - const installRoot = resolve( - options.installRoot ?? resolveInstallRoot(env) + const installRoot = pathApi.resolve( + options.installRoot ?? resolveInstallRoot(env, runtime) ); - if (!isAbsoluteLocalWindowsPath(installRoot)) { - throw new Error("installRoot must be on a local Windows drive"); + if (!isAbsoluteLocalPath(installRoot, runtime)) { + throw new Error("installRoot must be an absolute local path"); } const statePath = join(installRoot, "state.json"); const discover = options.discoverOfficialCodex ?? discoverOfficialCodex; @@ -513,7 +522,7 @@ export async function installFromProvider(options) { }); const removePathEntry = options.removePathEntry ?? (async () => ({ changed: false })); - const official = await discover({ installRoot, env }); + const official = await discover({ installRoot, env, runtime }); const oldState = await readOptionalState(statePath, readStateImpl); let stagingRoot = null; let pathAdded = false; @@ -526,10 +535,10 @@ export async function installFromProvider(options) { upstreamVersion: official.version, upstreamTag: options.expectedUpstreamTag ?? `rust-v${official.version}`, upstreamCommit: expectedCommit, - platform: PLATFORM + platform: runtime.target }); - await ensureOwnershipMarker(installRoot); + await ensureOwnershipMarker(installRoot, { runtime }); stagingRoot = join(installRoot, "cache", `install-${randomUUID()}`); await mkdir(stagingRoot, { recursive: true }); const ultraZip = join(stagingRoot, manifest.asset.name); @@ -562,7 +571,15 @@ export async function installFromProvider(options) { throw new Error("language pack locale does not match the Release manifest"); } - const stagedBinary = join(extractedRelease, "package", "bin", "codex.exe"); + const stagedBinary = join( + extractedRelease, + "package", + "bin", + runtime.binaryName + ); + if (!runtime.isWindows) { + await (options.chmod ?? chmod)(stagedBinary, 0o755); + } const stagedResource = join(extractedLanguage, "messages.ftl"); await runStage(options, "smoke-version", () => smoke({ binaryPath: stagedBinary, @@ -629,7 +646,12 @@ export async function installFromProvider(options) { }) ); - const finalBinary = join(finalRelease, "package", "bin", "codex.exe"); + const finalBinary = join( + finalRelease, + "package", + "bin", + runtime.binaryName + ); const finalResource = join(finalLanguage, "messages.ftl"); const finalManifest = join(finalLanguage, "manifest.json"); const [binaryHash, binaryStat, resourceHash, resourceStat] = await Promise.all([ @@ -718,12 +740,14 @@ export async function updateFromProvider(options) { export async function installForkFromProvider(options) { if (!options?.provider) throw new Error("provider is required"); + const runtime = options.runtime ?? RUNTIME_PLATFORM; + const pathApi = pathApiFor(runtime); const env = options.env ?? process.env; - const installRoot = resolve( - options.installRoot ?? resolveInstallRoot(env) + const installRoot = pathApi.resolve( + options.installRoot ?? resolveInstallRoot(env, runtime) ); - if (!isAbsoluteLocalWindowsPath(installRoot)) { - throw new Error("installRoot must be on a local Windows drive"); + if (!isAbsoluteLocalPath(installRoot, runtime)) { + throw new Error("installRoot must be an absolute local path"); } const statePath = join(installRoot, "state.json"); @@ -742,7 +766,7 @@ export async function installForkFromProvider(options) { }); const removePathEntry = options.removePathEntry ?? (async () => ({ changed: false })); - const official = await discover({ installRoot, env }); + const official = await discover({ installRoot, env, runtime }); const oldState = await readOptionalState(statePath, readStateImpl); let stagingRoot = null; let pathAdded = false; @@ -753,9 +777,9 @@ export async function installForkFromProvider(options) { "manifest", () => options.provider.readManifest() ); - const manifest = validateManifest(rawManifest, { platform: PLATFORM }); + const manifest = validateManifest(rawManifest, { platform: runtime.target }); - await ensureOwnershipMarker(installRoot); + await ensureOwnershipMarker(installRoot, { runtime }); const recoveredReleases = oldState === null ? await quarantineOrphanedCcuReleases(installRoot, options) : []; @@ -780,7 +804,15 @@ export async function installForkFromProvider(options) { extractZip(forkZip, extractedRelease) ); - const stagedBinary = join(extractedRelease, "package", "bin", "codex.exe"); + const stagedBinary = join( + extractedRelease, + "package", + "bin", + runtime.binaryName + ); + if (!runtime.isWindows) { + await (options.chmod ?? chmod)(stagedBinary, 0o755); + } await runStage(options, "smoke-version", () => smoke({ binaryPath: stagedBinary, binaryArgsPrefix: options.binaryArgsPrefix, @@ -813,7 +845,12 @@ export async function installForkFromProvider(options) { }) ); - const finalBinary = join(finalRelease, "package", "bin", "codex.exe"); + const finalBinary = join( + finalRelease, + "package", + "bin", + runtime.binaryName + ); const [binaryHash, binaryStat] = await Promise.all([ hashFile(finalBinary), stat(finalBinary) diff --git a/src/installer/path.mjs b/src/installer/path.mjs new file mode 100644 index 0000000..6844438 --- /dev/null +++ b/src/installer/path.mjs @@ -0,0 +1,23 @@ +import { RUNTIME_PLATFORM } from "../config/constants.mjs"; +import { + addPosixUserPathEntry, + removePosixUserPathEntry +} from "./posix-path.mjs"; +import { + addUserPathEntry as addWindowsUserPathEntry, + removeUserPathEntry as removeWindowsUserPathEntry +} from "./windows-path.mjs"; + +export async function addUserPathEntry(entry, options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; + return runtime.isWindows + ? await addWindowsUserPathEntry(entry, options) + : await addPosixUserPathEntry(entry, options); +} + +export async function removeUserPathEntry(entry, options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; + return runtime.isWindows + ? await removeWindowsUserPathEntry(entry, options) + : await removePosixUserPathEntry(entry, options); +} diff --git a/src/installer/posix-path.mjs b/src/installer/posix-path.mjs new file mode 100644 index 0000000..f994d98 --- /dev/null +++ b/src/installer/posix-path.mjs @@ -0,0 +1,109 @@ +import { randomUUID } from "node:crypto"; +import { lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; +import { posix } from "node:path"; + +const START_MARKER = "# >>> codex-cli-ultra >>>"; +const END_MARKER = "# <<< codex-cli-ultra <<<"; +const BLOCK_PATTERN = new RegExp( + `(?:^|\\n)${START_MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\n[\\s\\S]*?\\n${END_MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=\\n|$)`, + "g" +); + +function shellQuote(value) { + if (typeof value !== "string" || !posix.isAbsolute(value) || /[\0\r\n]/.test(value)) { + throw new Error("POSIX PATH entry must be an absolute single-line path"); + } + return `'${value.replaceAll("'", `'"'"'`)}'`; +} + +function selectedProfile(env, explicit) { + if (explicit) return explicit; + if (!env.HOME || !posix.isAbsolute(env.HOME)) { + throw new Error("HOME must be an absolute path for POSIX PATH setup"); + } + const shell = posix.basename(env.SHELL ?? ""); + const profile = shell === "zsh" + ? ".zshrc" + : shell === "bash" + ? ".bashrc" + : ".profile"; + return posix.join(env.HOME, profile); +} + +async function readProfile(path, fsOps) { + const inspect = fsOps.lstat ?? lstat; + try { + const metadata = await inspect(path); + if (metadata.isSymbolicLink() || !metadata.isFile()) { + throw new Error(`shell profile must be a regular file: ${path}`); + } + return await (fsOps.readFile ?? readFile)(path, "utf8"); + } catch (error) { + if (error?.code === "ENOENT") return ""; + throw error; + } +} + +function withoutManagedBlock(source) { + return source.replace(BLOCK_PATTERN, "").replace(/^\n+|\n+$/g, ""); +} + +async function writeProfileAtomic(path, source, fsOps) { + const temporary = `${path}.tmp-${randomUUID()}`; + await (fsOps.mkdir ?? mkdir)(posix.dirname(path), { recursive: true }); + try { + await (fsOps.writeFile ?? writeFile)(temporary, source, { + encoding: "utf8", + flag: "wx", + mode: 0o600 + }); + await (fsOps.rename ?? rename)(temporary, path); + } catch (error) { + await (fsOps.rm ?? rm)(temporary, { force: true }).catch(() => {}); + throw error; + } +} + +export async function addPosixUserPathEntry(entry, options = {}) { + const env = options.env ?? process.env; + const normalized = posix.resolve(entry); + const profilePath = selectedProfile(env, options.profilePath); + const source = await readProfile(profilePath, options.fsOps ?? {}); + const base = withoutManagedBlock(source); + const block = [ + START_MARKER, + `export PATH=${shellQuote(normalized)}:"$PATH"`, + END_MARKER + ].join("\n"); + const next = `${base ? `${base}\n\n` : ""}${block}\n`; + if (source === next) { + return { changed: false, entry: normalized, profilePath }; + } + await writeProfileAtomic(profilePath, next, options.fsOps ?? {}); + return { changed: true, entry: normalized, profilePath }; +} + +export async function removePosixUserPathEntry(entry, options = {}) { + const env = options.env ?? process.env; + const normalized = posix.resolve(entry); + const profiles = options.profilePath + ? [options.profilePath] + : [".profile", ".bash_profile", ".bashrc", ".zprofile", ".zshrc"].map((name) => { + if (!env.HOME || !posix.isAbsolute(env.HOME)) { + throw new Error("HOME must be an absolute path for POSIX PATH cleanup"); + } + return posix.join(env.HOME, name); + }); + let changed = false; + const changedProfiles = []; + for (const profilePath of new Set(profiles)) { + const source = await readProfile(profilePath, options.fsOps ?? {}); + const base = withoutManagedBlock(source); + const next = base ? `${base}\n` : ""; + if (source === next) continue; + await writeProfileAtomic(profilePath, next, options.fsOps ?? {}); + changed = true; + changedProfiles.push(profilePath); + } + return { changed, entry: normalized, profilePaths: changedProfiles }; +} diff --git a/src/launcher/main.mjs b/src/launcher/main.mjs index 8caf68a..d895657 100644 --- a/src/launcher/main.mjs +++ b/src/launcher/main.mjs @@ -2,7 +2,10 @@ import { spawn } from "node:child_process"; import { join, resolve } from "node:path"; import { pathToFileURL } from "node:url"; -import { resolveInstallRoot } from "../config/constants.mjs"; +import { + RUNTIME_PLATFORM, + resolveInstallRoot +} from "../config/constants.mjs"; import { discoverOfficialCodex } from "../discovery/official-codex.mjs"; import { writeNoticeOnce } from "../notices/once.mjs"; import { readState } from "../state/store.mjs"; @@ -11,6 +14,7 @@ import { runSelectedTarget } from "./process.mjs"; import { selectLaunchTarget } from "./select-target.mjs"; function prepareManagedUpdateEnvironment(options) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; const managerPath = join(options.installRoot, "bin", "codex-ultra.mjs"); const spawnDetached = options.spawnDetached ?? spawn; try { @@ -32,7 +36,11 @@ function prepareManagedUpdateEnvironment(options) { } catch {} return { CODEX_CCU_MANAGED: "1", - CODEX_CCU_MANAGER_PATH: join(options.installRoot, "bin", "ccu-manager.exe"), + CODEX_CCU_MANAGER_PATH: join( + options.installRoot, + "bin", + runtime.managerName + ), CODEX_CCU_MANAGER_VERSION: CCU_VERSION, CODEX_CCU_UPDATE_CACHE_PATH: join(options.installRoot, "update-cache.json"), CODEX_CCU_UPDATE_DISMISSALS_DIR: join(options.installRoot, "update-dismissals") @@ -40,10 +48,11 @@ function prepareManagedUpdateEnvironment(options) { } export async function launcherMain(options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; const env = options.env ?? process.env; const args = options.args ?? process.argv.slice(2); const stderr = options.stderr ?? process.stderr; - const installRoot = options.installRoot ?? resolveInstallRoot(env); + const installRoot = options.installRoot ?? resolveInstallRoot(env, runtime); const statePath = options.statePath ?? join(installRoot, "state.json"); const readStateImpl = options.readState ?? readState; @@ -66,7 +75,8 @@ export async function launcherMain(options = {}) { recoveredOfficial = await discoverOfficialImpl({ ...options.discoveryOptions, env, - installRoot + installRoot, + runtime }); } catch { recoveredOfficial = null; @@ -78,7 +88,8 @@ export async function launcherMain(options = {}) { state, recoveredOfficial, installRoot, - env + env, + runtime }); if (selection.kind === "ultra") { @@ -88,7 +99,8 @@ export async function launcherMain(options = {}) { ...prepareManagedUpdateEnvironment({ ...options, env, - installRoot + installRoot, + runtime }) }; } catch {} @@ -101,7 +113,8 @@ export async function launcherMain(options = {}) { ...options.noticeOptions, installRoot, reason: selection.reason, - detail: selection.notice + detail: selection.notice, + runtime }); } catch { firstNotice = false; diff --git a/src/launcher/select-target.mjs b/src/launcher/select-target.mjs index e5138c8..e2ff350 100644 --- a/src/launcher/select-target.mjs +++ b/src/launcher/select-target.mjs @@ -1,12 +1,12 @@ import { readFile, realpath, stat } from "node:fs/promises"; -import { win32 } from "node:path"; import { - isAbsoluteLocalWindowsPath, - isWindowsPathInside, - PLATFORM, - windowsPathsEqual + RUNTIME_PLATFORM, + isAbsoluteLocalPath, + isPathInside, + pathsEqual } from "../config/constants.mjs"; +import { pathApiFor } from "../platform/runtime.mjs"; import { validateState } from "../state/schema.mjs"; const MANAGED_ENV_KEYS = new Set([ @@ -88,8 +88,9 @@ async function readFileStat(path, statFile) { } } -async function canonicalizeLocalPath(path, realpathFile) { - if (!isAbsoluteLocalWindowsPath(path)) { +async function canonicalizeLocalPath(path, realpathFile, runtime) { + const pathApi = pathApiFor(runtime); + if (!isAbsoluteLocalPath(path, runtime)) { return { kind: "untrusted", path: null }; } let canonical; @@ -98,51 +99,52 @@ async function canonicalizeLocalPath(path, realpathFile) { } catch { return { kind: "missing", path: null }; } - if (!isAbsoluteLocalWindowsPath(canonical)) { + if (!isAbsoluteLocalPath(canonical, runtime)) { return { kind: "untrusted", path: null }; } - return { kind: "ok", path: win32.resolve(canonical) }; + return { kind: "ok", path: pathApi.resolve(canonical) }; } -async function canonicalizeInstallRoot(path, realpathFile) { - if (!isAbsoluteLocalWindowsPath(path)) { +async function canonicalizeInstallRoot(path, realpathFile, runtime) { + const pathApi = pathApiFor(runtime); + if (!isAbsoluteLocalPath(path, runtime)) { return { kind: "untrusted", path: null }; } try { const canonical = await realpathFile(path); - if (!isAbsoluteLocalWindowsPath(canonical)) { + if (!isAbsoluteLocalPath(canonical, runtime)) { return { kind: "untrusted", path: null }; } - return { kind: "ok", path: win32.resolve(canonical) }; + return { kind: "ok", path: pathApi.resolve(canonical) }; } catch (error) { if (error?.code === "ENOENT") { - return { kind: "missing", path: win32.resolve(path) }; + return { kind: "missing", path: pathApi.resolve(path) }; } return { kind: "untrusted", path: null }; } } -function expectedOfficialPaths(packageJsonPath) { - const platformPackageJsonPath = win32.join( - win32.dirname(packageJsonPath), +function expectedOfficialPaths(packageJsonPath, runtime) { + const pathApi = pathApiFor(runtime); + const platformPackageJsonPath = pathApi.join( + pathApi.dirname(packageJsonPath), "node_modules", - "@openai", - "codex-win32-x64", + ...runtime.npmPackage.split("/"), "package.json" ); return { platformPackageJsonPath, - binaryPath: win32.join( - win32.dirname(platformPackageJsonPath), + binaryPath: pathApi.join( + pathApi.dirname(platformPackageJsonPath), "vendor", - PLATFORM, + runtime.target, "bin", - "codex.exe" + runtime.binaryName ) }; } -function officialLayoutIsSafe(official, installRoot) { +function officialLayoutIsSafe(official, installRoot, runtime) { if (!official || typeof official !== "object") { return false; } @@ -152,18 +154,19 @@ function officialLayoutIsSafe(official, installRoot) { official.binaryPath ]) { if ( - !isAbsoluteLocalWindowsPath(path) || - isWindowsPathInside(installRoot, path) + !isAbsoluteLocalPath(path, runtime) || + isPathInside(installRoot, path, runtime) ) { return false; } } - const expected = expectedOfficialPaths(official.packageJsonPath); + const expected = expectedOfficialPaths(official.packageJsonPath, runtime); return ( - windowsPathsEqual( + pathsEqual( official.platformPackageJsonPath, - expected.platformPackageJsonPath - ) && windowsPathsEqual(official.binaryPath, expected.binaryPath) + expected.platformPackageJsonPath, + runtime + ) && pathsEqual(official.binaryPath, expected.binaryPath, runtime) ); } @@ -172,9 +175,10 @@ async function inspectOfficial({ installRoot, readPackageVersion, realpathFile, - statFile + statFile, + runtime }) { - if (!officialLayoutIsSafe(official, installRoot)) { + if (!officialLayoutIsSafe(official, installRoot, runtime)) { return { rootVersion: null, platformVersion: null, @@ -185,11 +189,12 @@ async function inspectOfficial({ const packagePath = await canonicalizeLocalPath( official.packageJsonPath, - realpathFile + realpathFile, + runtime ); if ( packagePath.kind !== "ok" || - isWindowsPathInside(installRoot, packagePath.path) + isPathInside(installRoot, packagePath.path, runtime) ) { return { rootVersion: null, @@ -213,18 +218,20 @@ async function inspectOfficial({ const platformPath = await canonicalizeLocalPath( official.platformPackageJsonPath, - realpathFile + realpathFile, + runtime ); if (platformPath.kind !== "ok") { return { rootVersion, platformVersion: null, trusted: false, path: null }; } - const canonicalExpected = expectedOfficialPaths(packagePath.path); + const canonicalExpected = expectedOfficialPaths(packagePath.path, runtime); if ( - !windowsPathsEqual( + !pathsEqual( platformPath.path, - canonicalExpected.platformPackageJsonPath + canonicalExpected.platformPackageJsonPath, + runtime ) || - isWindowsPathInside(installRoot, platformPath.path) + isPathInside(installRoot, platformPath.path, runtime) ) { return { rootVersion, platformVersion: null, trusted: false, path: null }; } @@ -235,18 +242,19 @@ async function inspectOfficial({ if (platformVersion === null) { return { rootVersion, platformVersion: null, trusted: false, path: null }; } - if (platformVersion !== `${rootVersion}-win32-x64`) { + if (platformVersion !== `${rootVersion}-${runtime.npmSuffix}`) { return { rootVersion, platformVersion, trusted: false, path: null }; } const binaryPath = await canonicalizeLocalPath( official.binaryPath, - realpathFile + realpathFile, + runtime ); if ( binaryPath.kind !== "ok" || - !windowsPathsEqual(binaryPath.path, canonicalExpected.binaryPath) || - isWindowsPathInside(installRoot, binaryPath.path) + !pathsEqual(binaryPath.path, canonicalExpected.binaryPath, runtime) || + isPathInside(installRoot, binaryPath.path, runtime) ) { return { rootVersion, platformVersion, trusted: false, path: null }; } @@ -259,30 +267,32 @@ async function inspectOfficial({ }; } -async function inspectUltra(active, installRoot, realpathFile, statFile) { - const expectedPath = win32.join( +async function inspectUltra(active, installRoot, realpathFile, statFile, runtime) { + const pathApi = pathApiFor(runtime); + const expectedPath = pathApi.join( installRoot, "releases", active.releaseId, active.platform, "package", "bin", - "codex.exe" + runtime.binaryName ); - if (!windowsPathsEqual(active.binaryPath, expectedPath)) { + if (!pathsEqual(active.binaryPath, expectedPath, runtime)) { return { valid: false, reason: "ultra-path-untrusted" }; } const binaryPath = await canonicalizeLocalPath( active.binaryPath, - realpathFile + realpathFile, + runtime ); if (binaryPath.kind === "missing") { return { valid: false, reason: "ultra-missing" }; } if ( binaryPath.kind !== "ok" || - !windowsPathsEqual(binaryPath.path, expectedPath) || - !isWindowsPathInside(installRoot, binaryPath.path) + !pathsEqual(binaryPath.path, expectedPath, runtime) || + !isPathInside(installRoot, binaryPath.path, runtime) ) { return { valid: false, reason: "ultra-path-untrusted" }; } @@ -309,19 +319,21 @@ function combineNotices(primary, secondary) { return `${primary} ${secondary.replace(/^Codex Ultra:\s*/, "")}`; } -async function selectLanguageEnvironment({ installRoot }) { +async function selectLanguageEnvironment({ installRoot, runtime }) { + const pathApi = pathApiFor(runtime); return { env: { - CODEX_CCU_LANGUAGE_PACK_ROOT: win32.join(installRoot, "languages"), - CODEX_CCU_THEME_PACK_ROOT: win32.join(installRoot, "themes"), - CODEX_CCU_QUOTA_PATH: win32.join(installRoot, "quota.json") + CODEX_CCU_LANGUAGE_PACK_ROOT: pathApi.join(installRoot, "languages"), + CODEX_CCU_THEME_PACK_ROOT: pathApi.join(installRoot, "themes"), + CODEX_CCU_QUOTA_PATH: pathApi.join(installRoot, "quota.json") }, notice: null }; } export async function selectLaunchTarget(options = {}) { - if (!isAbsoluteLocalWindowsPath(options.installRoot)) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; + if (!isAbsoluteLocalPath(options.installRoot, runtime)) { return result( "error", null, @@ -332,7 +344,8 @@ export async function selectLaunchTarget(options = {}) { const realpathFile = options.realpathFile ?? realpath; const canonicalRoot = await canonicalizeInstallRoot( options.installRoot, - realpathFile + realpathFile, + runtime ); if (canonicalRoot.kind === "untrusted") { return result( @@ -347,7 +360,7 @@ export async function selectLaunchTarget(options = {}) { let state = null; if (options.state !== null && options.state !== undefined) { try { - state = validateState(options.state); + state = validateState(options.state, { runtime }); } catch { state = null; } @@ -362,7 +375,8 @@ export async function selectLaunchTarget(options = {}) { installRoot, readPackageVersion, realpathFile, - statFile + statFile, + runtime }); if (state === null) { @@ -404,7 +418,8 @@ export async function selectLaunchTarget(options = {}) { active, installRoot, realpathFile, - statFile + statFile, + runtime ); if (ultra.valid) { const language = await selectLanguageEnvironment({ @@ -412,7 +427,8 @@ export async function selectLaunchTarget(options = {}) { installRoot, env: options.env ?? process.env, realpathFile, - statFile + statFile, + runtime }); const officialUnavailable = !official.trusted; const officialVersionChanged = diff --git a/src/manage-main.mjs b/src/manage-main.mjs index bb43a83..202139c 100644 --- a/src/manage-main.mjs +++ b/src/manage-main.mjs @@ -6,7 +6,10 @@ import { dirname, join, resolve } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { pathToFileURL } from "node:url"; -import { resolveInstallRoot } from "./config/constants.mjs"; +import { + RUNTIME_PLATFORM, + resolveInstallRoot +} from "./config/constants.mjs"; import { syncBundledContent } from "./content/sync.mjs"; import { discoverOfficialCodex } from "./discovery/official-codex.mjs"; import { installManagementBin } from "./installer/bin.mjs"; @@ -17,7 +20,7 @@ import { import { addUserPathEntry, removeUserPathEntry -} from "./installer/windows-path.mjs"; +} from "./installer/path.mjs"; import { uninstallCcu } from "./installer/uninstall.mjs"; import { FORK_MANIFEST_NAME, @@ -26,6 +29,7 @@ import { } from "./release/fork-manifest.mjs"; import { resolveLatestForkRelease } from "./release/github-fork.mjs"; import { + compareCcuVersions, compareStableVersions, resolveLatestCcuRelease, resolveLatestUpstreamRelease @@ -215,6 +219,7 @@ exit 1 `; function scheduleInstallRootCleanup(options) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; const spawnDetached = options.spawnDetached ?? spawn; const tombstoneRoot = join( dirname(options.installRoot), @@ -235,6 +240,28 @@ function scheduleInstallRootCleanup(options) { return true; } catch {} } + if (!runtime.isWindows) { + const child = spawnDetached( + options.execPath ?? process.execPath, + [ + "--input-type=module", + "--eval", + "import { renameSync, rmSync } from 'node:fs'; setTimeout(() => { let target = process.env.CCU_INSTALL_ROOT; try { renameSync(target, process.env.CCU_TOMBSTONE_ROOT); target = process.env.CCU_TOMBSTONE_ROOT; } catch {} try { rmSync(target, { recursive: true, force: true }); } catch { process.exitCode = 1; } }, 250);" + ], + { + detached: true, + stdio: "ignore", + env: { + ...options.env, + CCU_INSTALL_ROOT: options.installRoot, + CCU_TOMBSTONE_ROOT: tombstoneRoot + } + } + ); + child.once?.("error", () => {}); + child.unref?.(); + return Number.isInteger(child.pid) && child.pid > 0; + } const child = spawnDetached( options.pwshExecutable ?? options.env?.CODEX_CCU_PWSH_EXECUTABLE ?? @@ -298,7 +325,8 @@ async function collectStatus(options) { try { official = await (options.discoverOfficialCodex ?? discoverOfficialCodex)({ installRoot, - env: options.env + env: options.env, + runtime: options.runtime }); } catch { official = null; @@ -363,7 +391,8 @@ async function collectRemoteStatus(status, options) { const network = options.networkClient ?? createNetworkClient(settings, options); const remoteOptions = { fetchImpl: network.fetch, - token: options.githubToken + token: options.githubToken, + runtime: options.runtime }; try { const [forkResult, ccuResult, upstreamResult] = await Promise.allSettled([ @@ -384,7 +413,7 @@ async function collectRemoteStatus(status, options) { if (ccuResult.status === "fulfilled") { status.latestCcu = ccuResult.value; status.ccuUpdateAvailable = - compareStableVersions(CCU_VERSION, ccuResult.value.version) < 0; + compareCcuVersions(CCU_VERSION, ccuResult.value.version) < 0; } else { status.onlineErrors.push(remoteError("ccu", ccuResult)); } @@ -477,7 +506,8 @@ async function resolveProvider(args, options) { } const latest = await (options.resolveLatestForkRelease ?? resolveLatestForkRelease)({ fetchImpl: options.fetchImpl, - token: options.githubToken + token: options.githubToken, + runtime: options.runtime }); return { ...latest, @@ -494,8 +524,9 @@ export async function manageMain(options = {}) { const stdout = options.stdout ?? process.stdout; const stderr = options.stderr ?? process.stderr; const env = options.env ?? process.env; + const runtime = options.runtime ?? RUNTIME_PLATFORM; const cwd = options.cwd ?? process.cwd(); - const installRoot = options.installRoot ?? resolveInstallRoot(env); + const installRoot = options.installRoot ?? resolveInstallRoot(env, runtime); const command = args[0]; const json = args.includes("--json"); const eventMode = args.includes("--events") @@ -508,6 +539,7 @@ export async function manageMain(options = {}) { ...options, cwd, env, + runtime, installRoot, githubToken: options.githubToken ?? env.GITHUB_TOKEN }; @@ -588,7 +620,7 @@ export async function manageMain(options = {}) { currentVersion: CCU_VERSION, latestVersion: checked.latest.version, updateAvailable: - compareStableVersions(CCU_VERSION, checked.latest.version) < 0, + compareCcuVersions(CCU_VERSION, checked.latest.version) < 0, releaseUrl: checked.latest.url, packageReady: checked.manifest !== null, cache: checked.cache @@ -673,7 +705,10 @@ export async function manageMain(options = {}) { const result = await (options.uninstallCcu ?? uninstallCcu)({ installRoot, env, - removePathEntry: options.removePathEntry ?? removeUserPathEntry + runtime, + removePathEntry: + options.removePathEntry ?? + ((entry) => removeUserPathEntry(entry, { env, runtime })) }); const schedule = options.scheduleInstallRootCleanup ?? scheduleInstallRootCleanup; @@ -721,7 +756,8 @@ export async function manageMain(options = {}) { installManagementBin({ binDirectory, managerSource, - launcherSource + launcherSource, + runtime })); const contentRoot = resolve( options.contentRoot ?? @@ -763,9 +799,14 @@ export async function manageMain(options = {}) { provider: release.provider, installRoot, env, + runtime, discoverOfficialCodex: options.discoverOfficialCodex, - addPathEntry: options.addPathEntry ?? addUserPathEntry, - removePathEntry: options.removePathEntry ?? removeUserPathEntry, + addPathEntry: + options.addPathEntry ?? + ((entry) => addUserPathEntry(entry, { env, runtime })), + removePathEntry: + options.removePathEntry ?? + ((entry) => removeUserPathEntry(entry, { env, runtime })), prepareBin, onStage: options.onStage ?? diff --git a/src/notices/once.mjs b/src/notices/once.mjs index 8394ae0..e4bb938 100644 --- a/src/notices/once.mjs +++ b/src/notices/once.mjs @@ -2,7 +2,10 @@ import { createHash } from "node:crypto"; import { mkdir, open } from "node:fs/promises"; import { join } from "node:path"; -import { isAbsoluteLocalWindowsPath } from "../config/constants.mjs"; +import { + RUNTIME_PLATFORM, + isAbsoluteLocalPath +} from "../config/constants.mjs"; export async function writeNoticeOnce(options = {}) { try { @@ -10,7 +13,10 @@ export async function writeNoticeOnce(options = {}) { const detail = String(options.detail ?? ""); const noticesDirectory = options.noticesDirectory ?? join(options.installRoot, "notices"); - if (!isAbsoluteLocalWindowsPath(noticesDirectory)) { + if (!isAbsoluteLocalPath( + noticesDirectory, + options.runtime ?? RUNTIME_PLATFORM + )) { return false; } const hash = createHash("sha256") diff --git a/src/platform/runtime.mjs b/src/platform/runtime.mjs new file mode 100644 index 0000000..c3b785a --- /dev/null +++ b/src/platform/runtime.mjs @@ -0,0 +1,176 @@ +import { posix, win32 } from "node:path"; + +const DEFINITIONS = new Map([ + [ + "win32:x64", + { + id: "windows-x64", + nodePlatform: "win32", + arch: "x64", + target: "x86_64-pc-windows-msvc", + npmPackage: "@openai/codex-win32-x64", + npmSuffix: "win32-x64", + binaryName: "codex.exe", + managerName: "ccu-manager.exe", + installerName: "install.ps1", + uninstallerName: "uninstall.ps1", + isWindows: true + } + ], + [ + "linux:x64", + { + id: "linux-x64", + nodePlatform: "linux", + arch: "x64", + target: "x86_64-unknown-linux-musl", + npmPackage: "@openai/codex-linux-x64", + npmSuffix: "linux-x64", + binaryName: "codex", + managerName: "ccu-manager", + installerName: "install.sh", + uninstallerName: "uninstall.sh", + isWindows: false + } + ], + [ + "linux:arm64", + { + id: "linux-arm64", + nodePlatform: "linux", + arch: "arm64", + target: "aarch64-unknown-linux-musl", + npmPackage: "@openai/codex-linux-arm64", + npmSuffix: "linux-arm64", + binaryName: "codex", + managerName: "ccu-manager", + installerName: "install.sh", + uninstallerName: "uninstall.sh", + isWindows: false + } + ], + [ + "darwin:x64", + { + id: "macos-x64", + nodePlatform: "darwin", + arch: "x64", + target: "x86_64-apple-darwin", + npmPackage: "@openai/codex-darwin-x64", + npmSuffix: "darwin-x64", + binaryName: "codex", + managerName: "ccu-manager", + installerName: "install.sh", + uninstallerName: "uninstall.sh", + isWindows: false + } + ], + [ + "darwin:arm64", + { + id: "macos-arm64", + nodePlatform: "darwin", + arch: "arm64", + target: "aarch64-apple-darwin", + npmPackage: "@openai/codex-darwin-arm64", + npmSuffix: "darwin-arm64", + binaryName: "codex", + managerName: "ccu-manager", + installerName: "install.sh", + uninstallerName: "uninstall.sh", + isWindows: false + } + ] +]); + +export function resolveRuntimePlatform(options = {}) { + const nodePlatform = options.platform ?? process.platform; + const arch = options.arch ?? process.arch; + const definition = DEFINITIONS.get(`${nodePlatform}:${arch}`); + if (!definition) { + throw new Error(`unsupported platform: ${nodePlatform} (${arch})`); + } + return Object.freeze({ ...definition }); +} + +export const RUNTIME_PLATFORM = resolveRuntimePlatform(); + +export function pathApiFor(runtime = RUNTIME_PLATFORM) { + return runtime.isWindows ? win32 : posix; +} + +export function isAbsoluteLocalPath(value, runtime = RUNTIME_PLATFORM) { + if (typeof value !== "string" || value.includes("\0")) return false; + if (runtime.isWindows) { + return /^[A-Za-z]:[\\/]/.test(value) && win32.isAbsolute(value); + } + return posix.isAbsolute(value); +} + +export function pathIdentity(value, runtime = RUNTIME_PLATFORM) { + const identity = pathApiFor(runtime).resolve(value); + return runtime.isWindows ? identity.toLowerCase() : identity; +} + +export function pathsEqual(left, right, runtime = RUNTIME_PLATFORM) { + return pathIdentity(left, runtime) === pathIdentity(right, runtime); +} + +export function isPathInside(root, candidate, runtime = RUNTIME_PLATFORM) { + const pathApi = pathApiFor(runtime); + const relation = pathApi.relative( + pathApi.resolve(root), + pathApi.resolve(candidate) + ); + return ( + relation === "" || + (relation !== ".." && + !relation.startsWith(`..${pathApi.sep}`) && + !pathApi.isAbsolute(relation)) + ); +} + +function requireHome(env, runtime) { + const home = env.HOME; + if (!isAbsoluteLocalPath(home, runtime)) { + throw new Error("HOME must be an absolute local path"); + } + return pathApiFor(runtime).resolve(home); +} + +export function resolvePlatformInstallRoot( + env = process.env, + runtime = RUNTIME_PLATFORM +) { + const pathApi = pathApiFor(runtime); + let root; + if (env.CODEX_ULTRA_HOME) { + root = pathApi.resolve(env.CODEX_ULTRA_HOME); + } else if (runtime.isWindows) { + if (!env.LOCALAPPDATA) { + throw new Error("LOCALAPPDATA is required on Windows"); + } + root = pathApi.join(env.LOCALAPPDATA, "codex-cli-ultra"); + } else if (runtime.nodePlatform === "darwin") { + root = pathApi.join( + requireHome(env, runtime), + "Library", + "Application Support", + "codex-cli-ultra" + ); + } else { + const dataHome = env.XDG_DATA_HOME; + const base = dataHome + ? pathApi.resolve(dataHome) + : pathApi.join(requireHome(env, runtime), ".local", "share"); + root = pathApi.join(base, "codex-cli-ultra"); + } + if (!isAbsoluteLocalPath(root, runtime)) { + throw new Error( + runtime.isWindows + ? "install root must be on a local Windows drive" + : "install root must be an absolute local path" + ); + } + return pathApi.resolve(root); +} diff --git a/src/release/ccu-update-manifest.mjs b/src/release/ccu-update-manifest.mjs index 4ed62c5..c15e50b 100644 --- a/src/release/ccu-update-manifest.mjs +++ b/src/release/ccu-update-manifest.mjs @@ -1,7 +1,16 @@ -import { compareStableVersions } from "./github-version.mjs"; +import { RUNTIME_PLATFORM } from "../config/constants.mjs"; +import { compareCcuVersions } from "./github-version.mjs"; -export const CCU_UPDATE_MANIFEST_NAME = "ccu-update-manifest.json"; -const VERSION_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+$/; +export function ccuUpdateManifestName(runtime = RUNTIME_PLATFORM) { + return runtime.isWindows + ? "ccu-update-manifest.json" + : `ccu-update-manifest-${runtime.id}.json`; +} + +export const CCU_UPDATE_MANIFEST_NAME = ccuUpdateManifestName(); +const CCU_VERSION_PATTERN = + /^[0-9]+\.[0-9]+\.[0-9]+(?:-alpha\.[1-9][0-9]*)?$/; +const STABLE_VERSION_PATTERN = /^[0-9]+\.[0-9]+\.[0-9]+$/; const SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/; function record(value, label) { @@ -27,13 +36,14 @@ function safeName(value, label) { } export function validateCcuUpdateManifest(value, expected = {}) { + const platform = expected.platform ?? RUNTIME_PLATFORM.id; record(value, "CCU update manifest"); if (value.schemaVersion !== 1 || value.type !== "codex-cli-ultra-update") { throw new Error("unsupported CCU update manifest"); } const ccuVersion = string(value.ccuVersion, "ccuVersion"); - if (!VERSION_PATTERN.test(ccuVersion)) { - throw new Error("ccuVersion must be a stable x.y.z version"); + if (!CCU_VERSION_PATTERN.test(ccuVersion)) { + throw new Error("ccuVersion must be x.y.z or x.y.z-alpha.N"); } const releaseTag = string(value.releaseTag, "releaseTag"); if (releaseTag !== `v${ccuVersion}`) { @@ -42,14 +52,14 @@ export function validateCcuUpdateManifest(value, expected = {}) { if (expected.releaseTag && expected.releaseTag !== releaseTag) { throw new Error("manifest releaseTag does not match GitHub Release"); } - if (value.platform !== "windows-x64") { + if (value.platform !== platform) { throw new Error("unsupported CCU update platform"); } const minimumManagerVersion = string( value.minimumManagerVersion, "minimumManagerVersion" ); - if (!VERSION_PATTERN.test(minimumManagerVersion)) { + if (!STABLE_VERSION_PATTERN.test(minimumManagerVersion)) { throw new Error("minimumManagerVersion must be a stable version"); } const fork = record(value.bundledFork, "bundledFork"); @@ -67,7 +77,7 @@ export function validateCcuUpdateManifest(value, expected = {}) { type: "codex-cli-ultra-update", ccuVersion, releaseTag, - platform: "windows-x64", + platform, minimumManagerVersion, bundledFork: { releaseTag: string(fork.releaseTag, "bundledFork.releaseTag"), @@ -88,5 +98,5 @@ export function validateCcuUpdateManifest(value, expected = {}) { export function managerCanApplyUpdate(currentVersion, manifest) { const value = validateCcuUpdateManifest(manifest); - return compareStableVersions(currentVersion, value.minimumManagerVersion) >= 0; + return compareCcuVersions(currentVersion, value.minimumManagerVersion) >= 0; } diff --git a/src/release/ccu-version.mjs b/src/release/ccu-version.mjs index ad7b41e..c8a8db3 100644 --- a/src/release/ccu-version.mjs +++ b/src/release/ccu-version.mjs @@ -1,12 +1,12 @@ import { readFile, writeFile } from "node:fs/promises"; import { resolve } from "node:path"; -const VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/; +const VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)(?:-alpha\.[1-9]\d*)?$/; function parseVersion(version) { const match = VERSION_PATTERN.exec(version); if (!match) throw new Error(`invalid CCU version: ${version}`); - return match.slice(1).map(Number); + return match.slice(1, 4).map(Number); } export function nextPatchVersion(version) { diff --git a/src/release/fork-manifest.mjs b/src/release/fork-manifest.mjs index ede23a1..5e28389 100644 --- a/src/release/fork-manifest.mjs +++ b/src/release/fork-manifest.mjs @@ -1,6 +1,16 @@ -import { I18N_API_VERSION, PLATFORM } from "../config/constants.mjs"; +import { + I18N_API_VERSION, + PLATFORM, + RUNTIME_PLATFORM +} from "../config/constants.mjs"; -export const FORK_MANIFEST_NAME = "ccu-fork-manifest.json"; +export function forkManifestName(runtime = RUNTIME_PLATFORM) { + return runtime.isWindows + ? "ccu-fork-manifest.json" + : `ccu-fork-manifest-${runtime.id}.json`; +} + +export const FORK_MANIFEST_NAME = forkManifestName(); const COMMIT_PATTERN = /^[a-f0-9]{40}$/; const SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/; @@ -102,10 +112,19 @@ export function validateForkManifest(value, expected = {}) { if (upstreamTag !== `rust-v${upstreamVersion}`) { throw new Error("upstreamTag does not match upstreamVersion"); } - if (releaseTag !== `ccu-rust-v${upstreamVersion}-r${ultraRevision}`) { + const stableReleaseTag = `ccu-rust-v${upstreamVersion}-r${ultraRevision}`; + const alphaReleasePattern = new RegExp( + `^${stableReleaseTag.replaceAll(".", "\\.")}-alpha\\.[1-9][0-9]*$` + ); + if (releaseTag !== stableReleaseTag && !alphaReleasePattern.test(releaseTag)) { throw new Error("releaseTag does not match the CCU release contract"); } - if (displayVersion !== `${upstreamVersion}-ccu.i18n.${ultraRevision}`) { + const currentDisplayVersion = `v${upstreamVersion}-CCU.R${ultraRevision}`; + const legacyDisplayVersion = `${upstreamVersion}-ccu.i18n.${ultraRevision}`; + if ( + displayVersion !== currentDisplayVersion && + displayVersion !== legacyDisplayVersion + ) { throw new Error("displayVersion does not match the CCU version contract"); } diff --git a/src/release/github-fork.mjs b/src/release/github-fork.mjs index 7cde547..e7ea07c 100644 --- a/src/release/github-fork.mjs +++ b/src/release/github-fork.mjs @@ -1,11 +1,14 @@ import { - FORK_MANIFEST_NAME, + forkManifestName, validateForkManifest } from "./fork-manifest.mjs"; +import { RUNTIME_PLATFORM } from "../config/constants.mjs"; import { HttpReleaseProvider } from "./provider.mjs"; const DEFAULT_REPOSITORY = "Cec1c/codex"; const MAX_RELEASE_RESPONSE_BYTES = 1024 * 1024; +const RELEASE_TAG_PATTERN = + /^ccu-rust-v[0-9]+\.[0-9]+\.[0-9]+-r[1-9][0-9]*(?:-alpha\.[1-9][0-9]*)?$/; async function readLimitedJson(response) { const declaredLength = Number(response.headers.get("content-length")); @@ -28,15 +31,24 @@ async function readLimitedJson(response) { } } -function releaseApiUrl(repository) { +function releaseApiUrl(repository, releaseTag) { if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) { throw new Error("fork repository must use owner/name syntax"); } + if (releaseTag !== undefined) { + if (!RELEASE_TAG_PATTERN.test(releaseTag)) { + throw new Error("fork release tag does not match the CCU release contract"); + } + return `https://api.github.com/repos/${repository}/releases/tags/${encodeURIComponent(releaseTag)}`; + } return `https://api.github.com/repos/${repository}/releases/latest`; } export async function resolveLatestForkRelease(options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; + const manifestName = options.manifestName ?? forkManifestName(runtime); const repository = options.repository ?? DEFAULT_REPOSITORY; + const requestedReleaseTag = options.releaseTag; const headers = new Headers({ Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", @@ -46,7 +58,7 @@ export async function resolveLatestForkRelease(options = {}) { headers.set("Authorization", `Bearer ${options.token}`); } const response = await (options.fetchImpl ?? fetch)( - releaseApiUrl(repository), + releaseApiUrl(repository, requestedReleaseTag), { method: "GET", headers, @@ -55,22 +67,36 @@ export async function resolveLatestForkRelease(options = {}) { } ); if (!response.ok) { - throw new Error(`GitHub latest release request failed with HTTP ${response.status}`); + throw new Error(`GitHub fork release request failed with HTTP ${response.status}`); } const release = await readLimitedJson(response); if ( release?.draft === true || - release?.prerelease === true || typeof release?.tag_name !== "string" || !Array.isArray(release?.assets) ) { + throw new Error("GitHub fork release metadata is invalid"); + } + if (requestedReleaseTag === undefined && release.prerelease === true) { throw new Error("GitHub latest release is not a stable CCU fork release"); } + if ( + requestedReleaseTag !== undefined && + release.tag_name !== requestedReleaseTag + ) { + throw new Error("GitHub fork release tag does not match the requested tag"); + } + if (requestedReleaseTag !== undefined) { + const expectedPrerelease = requestedReleaseTag.includes("-alpha."); + if (release.prerelease !== expectedPrerelease) { + throw new Error("GitHub fork release prerelease state does not match its tag"); + } + } const manifestAsset = release.assets.find( - (asset) => asset?.name === FORK_MANIFEST_NAME + (asset) => asset?.name === manifestName ); if (typeof manifestAsset?.browser_download_url !== "string") { - throw new Error(`GitHub Release has no ${FORK_MANIFEST_NAME} asset`); + throw new Error(`GitHub Release has no ${manifestName} asset`); } const provider = new HttpReleaseProvider({ manifestUrl: manifestAsset.browser_download_url, @@ -78,7 +104,8 @@ export async function resolveLatestForkRelease(options = {}) { headers }); const manifest = validateForkManifest(await provider.readManifest(), { - releaseTag: release.tag_name + releaseTag: release.tag_name, + platform: runtime.target }); return { repository, diff --git a/src/release/github-version.mjs b/src/release/github-version.mjs index 1a0b287..034faf1 100644 --- a/src/release/github-version.mjs +++ b/src/release/github-version.mjs @@ -1,3 +1,6 @@ +import { RUNTIME_PLATFORM } from "../config/constants.mjs"; +import { ccuUpdateManifestName } from "./ccu-update-manifest.mjs"; + const MAX_RELEASE_RESPONSE_BYTES = 1024 * 1024; async function readLimitedJson(response) { @@ -75,13 +78,14 @@ async function resolveLatestVersion(options) { } export async function resolveLatestCcuRelease(options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; const result = await resolveLatestVersion({ ...options, repository: options.repository ?? "Cec1c/codex-cli-ultra", tagPattern: /^v([0-9]+\.[0-9]+\.[0-9]+)$/ }); const updateManifest = result.assets.find( - (asset) => asset?.name === "ccu-update-manifest.json" + (asset) => asset?.name === ccuUpdateManifestName(runtime) ); return { repository: result.repository, @@ -117,3 +121,28 @@ export function compareStableVersions(left, right) { } return 0; } + +export function compareCcuVersions(left, right) { + const parse = (value) => { + if (typeof value !== "string") { + throw new Error(`invalid CCU version: ${value}`); + } + const match = /^(\d+)\.(\d+)\.(\d+)(?:-alpha\.([1-9]\d*))?$/.exec(value); + if (!match) throw new Error(`invalid CCU version: ${value}`); + return { + core: match.slice(1, 4).map(Number), + alpha: match[4] === undefined ? null : Number(match[4]) + }; + }; + const a = parse(left); + const b = parse(right); + for (let index = 0; index < 3; index += 1) { + if (a.core[index] !== b.core[index]) { + return a.core[index] < b.core[index] ? -1 : 1; + } + } + if (a.alpha === b.alpha) return 0; + if (a.alpha === null) return 1; + if (b.alpha === null) return -1; + return a.alpha < b.alpha ? -1 : 1; +} diff --git a/src/state/schema.mjs b/src/state/schema.mjs index 1f186e6..73b2bd6 100644 --- a/src/state/schema.mjs +++ b/src/state/schema.mjs @@ -1,11 +1,10 @@ -import { win32 } from "node:path"; - import { - isAbsoluteLocalWindowsPath, - PLATFORM, + RUNTIME_PLATFORM, STATE_SCHEMA_VERSION, - windowsPathsEqual + isAbsoluteLocalPath, + pathsEqual } from "../config/constants.mjs"; +import { pathApiFor } from "../platform/runtime.mjs"; const SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/; @@ -39,7 +38,7 @@ function validateNonEmptyString(value, label) { return value; } -function validateWindowsPathSegment(value, label) { +function validatePathSegment(value, label, runtime) { const segment = validateNonEmptyString(value, label); if ( !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(segment) || @@ -47,17 +46,21 @@ function validateWindowsPathSegment(value, label) { segment === "." || segment === ".." ) { - throw new Error(`${label} must be a safe Windows path segment`); + throw new Error( + `${label} must be a safe ${runtime.isWindows ? "Windows " : ""}path segment` + ); } return segment; } -function validateAbsolutePath(value, label) { +function validateAbsolutePath(value, label, runtime) { if ( typeof value !== "string" || - !isAbsoluteLocalWindowsPath(value) + !isAbsoluteLocalPath(value, runtime) ) { - throw new Error(`${label} must be an absolute local Windows drive path`); + throw new Error( + `${label} must be an absolute local ${runtime.isWindows ? "Windows drive " : ""}path` + ); } return value; } @@ -97,7 +100,7 @@ function validateLocaleId(value, label) { return id; } -function validateOfficial(value) { +function validateOfficial(value, runtime) { assertRecord(value, "official"); assertExactKeys( value, @@ -114,7 +117,8 @@ function validateOfficial(value) { version: validateNonEmptyString(value.version, "official.version"), packageJsonPath: validateAbsolutePath( value.packageJsonPath, - "official.packageJsonPath" + "official.packageJsonPath", + runtime ), platformPackageVersion: validateNonEmptyString( value.platformPackageVersion, @@ -122,44 +126,47 @@ function validateOfficial(value) { ), platformPackageJsonPath: validateAbsolutePath( value.platformPackageJsonPath, - "official.platformPackageJsonPath" + "official.platformPackageJsonPath", + runtime ), binaryPath: validateAbsolutePath( value.binaryPath, - "official.binaryPath" + "official.binaryPath", + runtime ) }; - const expectedPlatformPackageJsonPath = win32.join( - win32.dirname(official.packageJsonPath), + const pathApi = pathApiFor(runtime); + const expectedPlatformPackageJsonPath = pathApi.join( + pathApi.dirname(official.packageJsonPath), "node_modules", - "@openai", - "codex-win32-x64", + ...runtime.npmPackage.split("/"), "package.json" ); if ( - !windowsPathsEqual( + !pathsEqual( official.platformPackageJsonPath, - expectedPlatformPackageJsonPath + expectedPlatformPackageJsonPath, + runtime ) ) { throw new Error( "official.platformPackageJsonPath must match the official package layout" ); } - const expectedBinaryPath = win32.join( - win32.dirname(official.platformPackageJsonPath), + const expectedBinaryPath = pathApi.join( + pathApi.dirname(official.platformPackageJsonPath), "vendor", - PLATFORM, + runtime.target, "bin", - "codex.exe" + runtime.binaryName ); - if (!windowsPathsEqual(official.binaryPath, expectedBinaryPath)) { + if (!pathsEqual(official.binaryPath, expectedBinaryPath, runtime)) { throw new Error("official.binaryPath must match the official package layout"); } return official; } -function validateBuild(value, label) { +function validateBuild(value, label, runtime) { assertRecord(value, label); assertExactKeys( value, @@ -175,13 +182,14 @@ function validateBuild(value, label) { ], label ); - if (value.platform !== PLATFORM) { - throw new Error(`${label}.platform must equal ${PLATFORM}`); + if (value.platform !== runtime.target) { + throw new Error(`${label}.platform must equal ${runtime.target}`); } return { - releaseId: validateWindowsPathSegment( + releaseId: validatePathSegment( value.releaseId, - `${label}.releaseId` + `${label}.releaseId`, + runtime ), upstreamVersion: validateNonEmptyString( value.upstreamVersion, @@ -191,10 +199,11 @@ function validateBuild(value, label) { value.ultraRevision, `${label}.ultraRevision` ), - platform: PLATFORM, + platform: runtime.target, binaryPath: validateAbsolutePath( value.binaryPath, - `${label}.binaryPath` + `${label}.binaryPath`, + runtime ), size: validatePositiveSafeInteger(value.size, `${label}.size`), mtimeMs: validateMtime(value.mtimeMs, `${label}.mtimeMs`), @@ -202,7 +211,7 @@ function validateBuild(value, label) { }; } -function validateLocale(value, label = "locale") { +function validateLocale(value, runtime, label = "locale") { assertRecord(value, label); assertExactKeys( value, @@ -213,11 +222,13 @@ function validateLocale(value, label = "locale") { id: validateLocaleId(value.id, `${label}.id`), manifestPath: validateAbsolutePath( value.manifestPath, - `${label}.manifestPath` + `${label}.manifestPath`, + runtime ), resourcePath: validateAbsolutePath( value.resourcePath, - `${label}.resourcePath` + `${label}.resourcePath`, + runtime ), size: validatePositiveSafeInteger(value.size, `${label}.size`), mtimeMs: validateMtime(value.mtimeMs, `${label}.mtimeMs`), @@ -225,19 +236,20 @@ function validateLocale(value, label = "locale") { }; } -function validateLastKnownGood(value) { +function validateLastKnownGood(value, runtime) { assertRecord(value, "lastKnownGood"); assertExactKeys(value, ["build", "locale"], "lastKnownGood"); return { - build: validateBuild(value.build, "lastKnownGood.build"), + build: validateBuild(value.build, "lastKnownGood.build", runtime), locale: value.locale === null ? null - : validateLocale(value.locale, "lastKnownGood.locale") + : validateLocale(value.locale, runtime, "lastKnownGood.locale") }; } -export function validateState(value) { +export function validateState(value, options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; assertRecord(value, "state"); assertExactKeys( value, @@ -249,12 +261,13 @@ export function validateState(value) { } return { schemaVersion: STATE_SCHEMA_VERSION, - official: validateOfficial(value.official), - active: value.active === null ? null : validateBuild(value.active, "active"), - locale: value.locale === null ? null : validateLocale(value.locale), + official: validateOfficial(value.official, runtime), + active: + value.active === null ? null : validateBuild(value.active, "active", runtime), + locale: value.locale === null ? null : validateLocale(value.locale, runtime), lastKnownGood: value.lastKnownGood === null ? null - : validateLastKnownGood(value.lastKnownGood) + : validateLastKnownGood(value.lastKnownGood, runtime) }; } diff --git a/src/update/check.mjs b/src/update/check.mjs index f8d579d..98c4b37 100644 --- a/src/update/check.mjs +++ b/src/update/check.mjs @@ -1,8 +1,9 @@ import { createNetworkClient } from "../network/client.mjs"; import { - CCU_UPDATE_MANIFEST_NAME, + ccuUpdateManifestName, validateCcuUpdateManifest } from "../release/ccu-update-manifest.mjs"; +import { RUNTIME_PLATFORM } from "../config/constants.mjs"; import { resolveLatestCcuRelease } from "../release/github-version.mjs"; import { HttpReleaseProvider } from "../release/provider.mjs"; import { readSettings } from "../settings/store.mjs"; @@ -10,23 +11,31 @@ import { writeUpdateCacheAtomic } from "./cache.mjs"; const CCU_RELEASES_URL = "https://github.com/Cec1c/codex-cli-ultra/releases"; -function manifestProvider(manifestUrl, options, network) { +function manifestProvider(manifestUrl, options, network, manifestName) { return new HttpReleaseProvider({ manifestUrl, fetchImpl: network.fetch, headers: options.githubToken ? { Authorization: `Bearer ${options.githubToken}` } : {}, - manifestName: CCU_UPDATE_MANIFEST_NAME + manifestName }); } async function readUpdateManifest(manifestUrl, options, network, expected = {}) { - const provider = manifestProvider(manifestUrl, options, network); + const runtime = options.runtime ?? RUNTIME_PLATFORM; + const provider = manifestProvider( + manifestUrl, + options, + network, + ccuUpdateManifestName(runtime) + ); return validateCcuUpdateManifest(await provider.readManifest(), expected); } export async function checkForCcuUpdate(options = {}) { + const runtime = options.runtime ?? RUNTIME_PLATFORM; + const manifestName = ccuUpdateManifestName(runtime); const settings = options.settings ?? await (options.readSettings ?? readSettings)(options.installRoot); @@ -37,14 +46,20 @@ export async function checkForCcuUpdate(options = {}) { try { latest = await (options.resolveLatestCcuRelease ?? resolveLatestCcuRelease)({ fetchImpl: network.fetch, - token: options.githubToken + token: options.githubToken, + runtime }); } catch (apiError) { const manifestUrl = options.latestManifestUrl ?? - `${CCU_RELEASES_URL}/latest/download/${CCU_UPDATE_MANIFEST_NAME}`; + `${CCU_RELEASES_URL}/latest/download/${manifestName}`; try { - manifest = await readUpdateManifest(manifestUrl, options, network); + manifest = await readUpdateManifest( + manifestUrl, + options, + network, + { platform: runtime.id } + ); } catch (manifestError) { throw new Error( `GitHub API update check failed: ${apiError.message}; public manifest fallback failed: ${manifestError.message}`, @@ -64,7 +79,7 @@ export async function checkForCcuUpdate(options = {}) { latest.updateManifestUrl, options, network, - { releaseTag: latest.tag } + { releaseTag: latest.tag, platform: runtime.id } ); } const cache = await (options.writeUpdateCacheAtomic ?? writeUpdateCacheAtomic)( @@ -97,14 +112,19 @@ export async function resolveCcuUpdatePackage(options = {}) { } if (!checked.latest.updateManifestUrl || !checked.manifest) { throw new Error( - `CCU ${checked.latest.version} does not provide ${CCU_UPDATE_MANIFEST_NAME}` + `CCU ${checked.latest.version} does not provide ${ccuUpdateManifestName(options.runtime ?? RUNTIME_PLATFORM)}` ); } const settings = checked.settings; const network = options.networkClient ?? createNetworkClient(settings, options); return { ...checked, - provider: manifestProvider(checked.latest.updateManifestUrl, options, network), + provider: manifestProvider( + checked.latest.updateManifestUrl, + options, + network, + ccuUpdateManifestName(options.runtime ?? RUNTIME_PLATFORM) + ), networkClient: network, ownsNetworkClient: !options.networkClient }; diff --git a/src/update/upgrade.mjs b/src/update/upgrade.mjs index fdfcf79..7022338 100644 --- a/src/update/upgrade.mjs +++ b/src/update/upgrade.mjs @@ -1,15 +1,17 @@ import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; import { mkdir, readdir, rm, writeFile } from "node:fs/promises"; -import { basename, join } from "node:path"; +import { join } from "node:path"; +import { RUNTIME_PLATFORM } from "../config/constants.mjs"; +import { pathApiFor } from "../platform/runtime.mjs"; import { extractZipSecure } from "../release/archive.mjs"; import { managerCanApplyUpdate, validateCcuUpdateManifest } from "../release/ccu-update-manifest.mjs"; import { sha256File } from "../release/hash.mjs"; -import { compareStableVersions } from "../release/github-version.mjs"; +import { compareCcuVersions } from "../release/github-version.mjs"; import { CCU_VERSION } from "../version.mjs"; import { resolveCcuUpdatePackage } from "./check.mjs"; @@ -48,6 +50,25 @@ catch { } `; +const POSIX_APPLY_SCRIPT = String.raw`#!/bin/sh +set -u +manager_pid="\${CCU_MANAGER_PID:-0}" +if [ "$manager_pid" -gt 0 ] 2>/dev/null; then + while kill -0 "$manager_pid" 2>/dev/null; do sleep 1; done +fi +if bash "$CCU_INSTALL_SCRIPT" --non-interactive --preserve-statusline; then + printf '{"schemaVersion":1,"status":"succeeded","targetVersion":"%s","message":"CCU upgrade completed"}\n' "$CCU_TARGET_VERSION" > "$CCU_JOB_RESULT" + if [ -x "$CCU_INSTALLED_MANAGER" ]; then + (cd "$CCU_INSTALL_ROOT" && nohup "$CCU_INSTALLED_MANAGER" >/dev/null 2>&1 &) + fi + rm -f -- "$CCU_DOWNLOAD_PATH" + rm -rf -- "$CCU_STAGE_ROOT" + exit 0 +fi +printf '{"schemaVersion":1,"status":"failed","targetVersion":"%s","message":"CCU installer failed"}\n' "$CCU_TARGET_VERSION" > "$CCU_JOB_RESULT" +exit 1 +`; + async function findPackageRoot(stagingRoot, fsOps = {}) { const readDirectory = fsOps.readdir ?? readdir; const entries = await readDirectory(stagingRoot, { withFileTypes: true }); @@ -64,6 +85,8 @@ function emitStage(options, stage, detail = null) { export async function stageCcuUpgrade(options = {}) { if (!options.installRoot) throw new Error("installRoot is required"); + const runtime = options.runtime ?? RUNTIME_PLATFORM; + const pathApi = pathApiFor(runtime); const targetVersion = options.targetVersion ? options.targetVersion.replace(/^v/, "") : undefined; @@ -73,7 +96,8 @@ export async function stageCcuUpgrade(options = {}) { }); try { const manifest = validateCcuUpdateManifest(resolved.manifest, { - releaseTag: resolved.latest.tag + releaseTag: resolved.latest.tag, + platform: runtime.id }); if (!managerCanApplyUpdate(options.currentVersion ?? CCU_VERSION, manifest)) { throw new Error( @@ -81,7 +105,7 @@ export async function stageCcuUpgrade(options = {}) { ); } if ( - compareStableVersions(options.currentVersion ?? CCU_VERSION, manifest.ccuVersion) >= 0 + compareCcuVersions(options.currentVersion ?? CCU_VERSION, manifest.ccuVersion) >= 0 ) { return { changed: false, @@ -91,10 +115,10 @@ export async function stageCcuUpgrade(options = {}) { }; } - const cacheRoot = join(options.installRoot, "cache", "updates"); + const cacheRoot = pathApi.join(options.installRoot, "cache", "updates"); await (options.mkdir ?? mkdir)(cacheRoot, { recursive: true }); - const downloadPath = join(cacheRoot, `${manifest.asset.name}.part`); - const stagingRoot = join(cacheRoot, `stage-${randomUUID()}`); + const downloadPath = pathApi.join(cacheRoot, `${manifest.asset.name}.part`); + const stagingRoot = pathApi.join(cacheRoot, `stage-${randomUUID()}`); await (options.mkdir ?? mkdir)(stagingRoot, { recursive: true }); try { @@ -123,7 +147,7 @@ export async function stageCcuUpgrade(options = {}) { stagingRoot, options.fsOps ); - const installScript = join(packageRoot, "install.ps1"); + const installScript = pathApi.join(packageRoot, runtime.installerName); emitStage(options, "ready", packageRoot); return { changed: true, @@ -148,22 +172,34 @@ export async function stageCcuUpgrade(options = {}) { export async function scheduleCcuUpgradeApply(staged, options = {}) { if (!staged.changed) return { scheduled: false, reason: staged.message }; - const jobsRoot = join(options.installRoot, "cache", "update-jobs"); + const runtime = options.runtime ?? RUNTIME_PLATFORM; + const pathApi = pathApiFor(runtime); + const jobsRoot = pathApi.join(options.installRoot, "cache", "update-jobs"); await (options.mkdir ?? mkdir)(jobsRoot, { recursive: true }); const jobId = randomUUID(); - const scriptPath = join(jobsRoot, `${jobId}.ps1`); - const resultPath = join(jobsRoot, `${jobId}.json`); - await (options.writeFile ?? writeFile)(scriptPath, APPLY_SCRIPT, "utf8"); + const scriptPath = pathApi.join(jobsRoot, `${jobId}.${runtime.isWindows ? "ps1" : "sh"}`); + const resultPath = pathApi.join(jobsRoot, `${jobId}.json`); + await (options.writeFile ?? writeFile)( + scriptPath, + runtime.isWindows ? APPLY_SCRIPT : POSIX_APPLY_SCRIPT, + runtime.isWindows ? "utf8" : { encoding: "utf8", mode: 0o700 } + ); const spawnProcess = options.spawn ?? spawn; - const child = spawnProcess(options.pwshExecutable ?? "pwsh.exe", [ - "-NoLogo", - "-NoProfile", - "-NonInteractive", - "-WindowStyle", - "Hidden", - "-File", - scriptPath - ], { + const executable = runtime.isWindows + ? options.pwshExecutable ?? "pwsh.exe" + : options.shellExecutable ?? "sh"; + const args = runtime.isWindows + ? [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-WindowStyle", + "Hidden", + "-File", + scriptPath + ] + : [scriptPath]; + const child = spawnProcess(executable, args, { detached: true, windowsHide: true, stdio: "ignore", @@ -173,7 +209,11 @@ export async function scheduleCcuUpgradeApply(staged, options = {}) { CCU_MANAGER_PID: String(options.managerPid ?? 0), CCU_INSTALL_SCRIPT: staged.installScript, CCU_INSTALL_ROOT: options.installRoot, - CCU_INSTALLED_MANAGER: join(options.installRoot, "bin", "ccu-manager.exe"), + CCU_INSTALLED_MANAGER: pathApi.join( + options.installRoot, + "bin", + runtime.managerName + ), CCU_JOB_RESULT: resultPath, CCU_DOWNLOAD_PATH: staged.downloadPath, CCU_STAGE_ROOT: staged.stagingRoot @@ -186,7 +226,7 @@ export async function scheduleCcuUpgradeApply(staged, options = {}) { jobId, resultPath, targetVersion: staged.manifest.ccuVersion, - assetName: basename(staged.downloadPath).replace(/\.part$/, "") + assetName: pathApi.basename(staged.downloadPath).replace(/\.part$/, "") }; } diff --git a/src/version.mjs b/src/version.mjs index a08f154..ab194ce 100644 --- a/src/version.mjs +++ b/src/version.mjs @@ -1 +1 @@ -export const CCU_VERSION = "0.1.7"; +export const CCU_VERSION = "0.1.8-alpha.1"; diff --git a/test/install-script.test.mjs b/test/install-script.test.mjs index 78cb21e..1ead733 100644 --- a/test/install-script.test.mjs +++ b/test/install-script.test.mjs @@ -9,6 +9,7 @@ const execFileAsync = promisify(execFile); const projectRoot = dirname(dirname(fileURLToPath(import.meta.url))); const installScript = join(projectRoot, "install.ps1"); const windowsOnly = { skip: process.platform !== "win32" }; +const unixOnly = { skip: process.platform === "win32" }; async function runInstallerPreflight(statusLineArguments) { try { @@ -61,6 +62,34 @@ test( } ); +test( + "Unix installer rejects the source directory as its install root", + unixOnly, + async () => { + await assert.rejects( + execFileAsync( + "bash", + [ + installScript.replace(/install\.ps1$/, "install.sh"), + "--install-root", + projectRoot, + "--skip-build", + "--non-interactive" + ], + { cwd: projectRoot } + ), + (error) => { + assert.equal(error.code, 1); + assert.match( + `${error.stdout ?? ""}\n${error.stderr ?? ""}`, + /Install root must not be the installer source directory\./ + ); + return true; + } + ); + } +); + test( "PowerShell installer rejects conflicting status-line modes", windowsOnly, diff --git a/test/installer/posix-path.test.mjs b/test/installer/posix-path.test.mjs new file mode 100644 index 0000000..42d1cdc --- /dev/null +++ b/test/installer/posix-path.test.mjs @@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +import { + addPosixUserPathEntry, + removePosixUserPathEntry +} from "../../src/installer/posix-path.mjs"; + +test("POSIX PATH profile block is reversible and idempotent", async () => { + const root = await mkdtemp(join(tmpdir(), "ccu-posix-profile-")); + const profilePath = join(root, ".profile"); + try { + await writeFile(profilePath, "export EDITOR=vim\n", "utf8"); + const first = await addPosixUserPathEntry("/opt/ccu/bin", { + profilePath, + env: { HOME: "/home/alice", SHELL: "/bin/bash" } + }); + assert.equal(first.changed, true); + const installed = await readFile(profilePath, "utf8"); + assert.match(installed, /# >>> codex-cli-ultra >>>/); + assert.match(installed, /export PATH='\/opt\/ccu\/bin':"\$PATH"/); + + const second = await addPosixUserPathEntry("/opt/ccu/bin", { + profilePath, + env: { HOME: "/home/alice", SHELL: "/bin/bash" } + }); + assert.equal(second.changed, false); + + const removed = await removePosixUserPathEntry("/opt/ccu/bin", { + profilePath, + env: { HOME: "/home/alice", SHELL: "/bin/bash" } + }); + assert.equal(removed.changed, true); + assert.equal(await readFile(profilePath, "utf8"), "export EDITOR=vim\n"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("POSIX PATH setup targets the active interactive shell profile", async () => { + const missing = Object.assign(new Error("missing"), { code: "ENOENT" }); + const fsOps = { + lstat: async () => { throw missing; }, + mkdir: async () => {}, + writeFile: async () => {}, + rename: async () => {}, + rm: async () => {} + }; + const bash = await addPosixUserPathEntry("/opt/ccu/bin", { + env: { HOME: "/home/alice", SHELL: "/bin/bash" }, + fsOps + }); + const zsh = await addPosixUserPathEntry("/opt/ccu/bin", { + env: { HOME: "/home/alice", SHELL: "/bin/zsh" }, + fsOps + }); + assert.equal(bash.profilePath, "/home/alice/.bashrc"); + assert.equal(zsh.profilePath, "/home/alice/.zshrc"); +}); diff --git a/test/platform.test.mjs b/test/platform.test.mjs new file mode 100644 index 0000000..27b1e74 --- /dev/null +++ b/test/platform.test.mjs @@ -0,0 +1,216 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { execFile } from "node:child_process"; +import test from "node:test"; + +import { discoverOfficialCodex } from "../src/discovery/official-codex.mjs"; +import { installManagementBin } from "../src/installer/bin.mjs"; +import { selectLaunchTarget } from "../src/launcher/select-target.mjs"; +import { + isPathInside, + pathsEqual, + resolvePlatformInstallRoot, + resolveRuntimePlatform +} from "../src/platform/runtime.mjs"; + +const LINUX = resolveRuntimePlatform({ platform: "linux", arch: "x64" }); +const MAC_ARM = resolveRuntimePlatform({ platform: "darwin", arch: "arm64" }); +const execFileAsync = promisify(execFile); + +test("runtime platform descriptors cover Linux and both macOS architectures", () => { + assert.deepEqual( + { + id: LINUX.id, + target: LINUX.target, + npmPackage: LINUX.npmPackage, + binaryName: LINUX.binaryName + }, + { + id: "linux-x64", + target: "x86_64-unknown-linux-musl", + npmPackage: "@openai/codex-linux-x64", + binaryName: "codex" + } + ); + assert.equal(MAC_ARM.id, "macos-arm64"); + assert.equal(MAC_ARM.target, "aarch64-apple-darwin"); + assert.equal( + resolveRuntimePlatform({ platform: "darwin", arch: "x64" }).target, + "x86_64-apple-darwin" + ); +}); + +test("platform install roots follow XDG and macOS user conventions", () => { + assert.equal( + resolvePlatformInstallRoot({ HOME: "/home/alice" }, LINUX), + "/home/alice/.local/share/codex-cli-ultra" + ); + assert.equal( + resolvePlatformInstallRoot( + { HOME: "/home/alice", XDG_DATA_HOME: "/data/alice" }, + LINUX + ), + "/data/alice/codex-cli-ultra" + ); + assert.equal( + resolvePlatformInstallRoot({ HOME: "/Users/alice" }, MAC_ARM), + "/Users/alice/Library/Application Support/codex-cli-ultra" + ); + assert.throws( + () => resolvePlatformInstallRoot({ HOME: "relative" }, LINUX), + /HOME must be an absolute local path/ + ); +}); + +test("POSIX path identity remains case-sensitive and child-safe", () => { + assert.equal(pathsEqual("/opt/CCU", "/opt/ccu", LINUX), false); + assert.equal(isPathInside("/opt/ccu", "/opt/ccu/bin/codex", LINUX), true); + assert.equal(isPathInside("/opt/ccu", "/opt/ccu-other/bin", LINUX), false); +}); + +test("official Codex discovery validates the Linux npm package layout", async () => { + const installRoot = "/home/alice/.local/share/codex-cli-ultra"; + const npmRoot = "/opt/node/lib/node_modules"; + const packageJsonPath = `${npmRoot}/@openai/codex/package.json`; + const platformPackageJsonPath = `${npmRoot}/@openai/codex/node_modules/@openai/codex-linux-x64/package.json`; + const binaryPath = `${npmRoot}/@openai/codex/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex`; + const files = new Map([ + [ + packageJsonPath, + JSON.stringify({ + name: "@openai/codex", + version: "0.145.0", + optionalDependencies: { + "@openai/codex-linux-x64": "npm:@openai/codex@0.145.0-linux-x64" + } + }) + ], + [ + platformPackageJsonPath, + JSON.stringify({ name: "@openai/codex", version: "0.145.0-linux-x64" }) + ] + ]); + const result = await discoverOfficialCodex({ + runtime: LINUX, + installRoot, + npmRoot, + realpath: async (path) => path, + readFile: async (path) => files.get(path), + stat: async () => ({ isFile: () => true, size: 1 }) + }); + assert.deepEqual(result, { + version: "0.145.0", + packageJsonPath, + platformPackageVersion: "0.145.0-linux-x64", + platformPackageJsonPath, + binaryPath + }); +}); + +test("Linux launch selection accepts only the platform-specific installed layout", async () => { + const installRoot = "/home/alice/.local/share/codex-cli-ultra"; + const packageJsonPath = "/opt/node/lib/node_modules/@openai/codex/package.json"; + const platformPackageJsonPath = "/opt/node/lib/node_modules/@openai/codex/node_modules/@openai/codex-linux-x64/package.json"; + const officialBinary = "/opt/node/lib/node_modules/@openai/codex/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex"; + const ultraBinary = `${installRoot}/releases/0.145.0-ccu.i18n.2/x86_64-unknown-linux-musl/package/bin/codex`; + const state = { + schemaVersion: 1, + official: { + version: "0.145.0", + packageJsonPath, + platformPackageVersion: "0.145.0-linux-x64", + platformPackageJsonPath, + binaryPath: officialBinary + }, + active: { + releaseId: "0.145.0-ccu.i18n.2", + upstreamVersion: "0.145.0", + ultraRevision: 2, + platform: LINUX.target, + binaryPath: ultraBinary, + size: 10, + mtimeMs: 20, + sha256: `sha256:${"a".repeat(64)}` + }, + locale: null, + lastKnownGood: null + }; + const selection = await selectLaunchTarget({ + runtime: LINUX, + installRoot, + state, + realpathFile: async (path) => path, + readPackageVersion: async (path) => + path === packageJsonPath ? "0.145.0" : "0.145.0-linux-x64", + statFile: async (path) => ({ + isFile: () => true, + size: path === ultraBinary ? 10 : 1, + mtimeMs: path === ultraBinary ? 20 : 1 + }) + }); + assert.equal(selection.kind, "ultra"); + assert.equal(selection.path, ultraBinary); + assert.equal( + selection.env.CODEX_CCU_LANGUAGE_PACK_ROOT, + `${installRoot}/languages` + ); +}); + +test("POSIX management wrappers are executable and forward arguments", async () => { + const root = await mkdtemp(join(tmpdir(), "ccu-posix-bin-")); + try { + const managerSource = join(root, "manager-source.mjs"); + const launcherSource = join(root, "launcher-source.mjs"); + const binDirectory = join(root, "bin"); + await mkdir(join(root, "content")); + await writeFile( + managerSource, + "process.stdout.write(JSON.stringify({kind: 'manager', args: process.argv.slice(2), content: process.env.CODEX_CCU_CONTENT_ROOT}));\n" + ); + await writeFile( + launcherSource, + "process.stdout.write(JSON.stringify({kind: 'launcher', args: process.argv.slice(2)}));\n" + ); + await installManagementBin({ + runtime: LINUX, + binDirectory, + managerSource, + launcherSource + }); + const wrapper = await readFile(join(binDirectory, "codex"), "utf8"); + assert.match(wrapper, /^#!\/bin\/sh/); + assert.match(wrapper, /"\$@"/); + if (process.platform !== "win32") { + assert.equal((await stat(join(binDirectory, "codex"))).mode & 0o111, 0o111); + } + const managerWrapper = await readFile( + join(binDirectory, "codex-ultra"), + "utf8" + ); + assert.match(managerWrapper, /CODEX_CCU_CONTENT_ROOT/); + if (process.platform !== "win32") { + const launcherRun = await execFileAsync(join(binDirectory, "codex"), [ + "--model", + "值 with spaces" + ]); + assert.deepEqual(JSON.parse(launcherRun.stdout), { + kind: "launcher", + args: ["--model", "值 with spaces"] + }); + const managerRun = await execFileAsync(join(binDirectory, "codex-ultra"), [ + "status", + "--json" + ]); + assert.deepEqual(JSON.parse(managerRun.stdout), { + kind: "manager", + args: ["status", "--json"], + content: join(binDirectory, "../content") + }); + } + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/test/release/ccu-update-manifest.test.mjs b/test/release/ccu-update-manifest.test.mjs index 88c938b..51e9e97 100644 --- a/test/release/ccu-update-manifest.test.mjs +++ b/test/release/ccu-update-manifest.test.mjs @@ -40,3 +40,12 @@ test("CCU update manifest rejects a mismatched release tag", () => { value.releaseTag = "v0.1.6"; assert.throws(() => validateCcuUpdateManifest(value), /does not match/); }); + +test("CCU update manifest accepts a canonical Alpha release", () => { + const value = manifest(); + value.ccuVersion = "0.1.8-alpha.1"; + value.releaseTag = "v0.1.8-alpha.1"; + value.asset.name = "codex-cli-ultra-v0.1.8-alpha.1-windows-x64.zip"; + assert.deepEqual(validateCcuUpdateManifest(value), value); + assert.equal(managerCanApplyUpdate("0.1.8-alpha.1", value), true); +}); diff --git a/test/release/ccu-version.test.mjs b/test/release/ccu-version.test.mjs index 3f5463e..a58b23b 100644 --- a/test/release/ccu-version.test.mjs +++ b/test/release/ccu-version.test.mjs @@ -12,6 +12,7 @@ import { test("nextPatchVersion increments only the patch component", () => { assert.equal(nextPatchVersion("0.1.3"), "0.1.4"); assert.equal(nextPatchVersion("2.9.99"), "2.9.100"); + assert.equal(nextPatchVersion("0.1.8-alpha.1"), "0.1.9"); }); test("repository release version surfaces match package.json", async () => { diff --git a/test/release/fork-manifest.test.mjs b/test/release/fork-manifest.test.mjs index 124fd4f..dd8af31 100644 --- a/test/release/fork-manifest.test.mjs +++ b/test/release/fork-manifest.test.mjs @@ -7,12 +7,17 @@ import { } from "../../src/release/fork-manifest.mjs"; import { resolveLatestForkRelease } from "../../src/release/github-fork.mjs"; -function manifest(revision = 1, version = "0.144.5") { +function manifest(revision = 1, version = "0.144.5", options = {}) { + const releaseTag = `ccu-rust-v${version}-r${revision}${ + options.alpha === undefined ? "" : `-alpha.${options.alpha}` + }`; return { schemaVersion: 1, type: "codex-ccu-i18n-build", - releaseTag: `ccu-rust-v${version}-r${revision}`, - displayVersion: `${version}-ccu.i18n.${revision}`, + releaseTag, + displayVersion: options.legacy + ? `${version}-ccu.i18n.${revision}` + : `v${version}-CCU.R${revision}`, upstreamVersion: version, upstreamTag: `rust-v${version}`, upstreamCommit: "a".repeat(40), @@ -49,6 +54,20 @@ test("fork manifest validates the release, display, upstream, and asset contract } }); +test("fork manifest accepts legacy stable installs and canonical Alpha tags", () => { + const legacy = manifest(2, "0.145.0", { legacy: true }); + const alpha = manifest(2, "0.145.0", { alpha: 1 }); + assert.deepEqual(validateForkManifest(legacy), legacy); + assert.deepEqual( + validateForkManifest(alpha, { releaseTag: alpha.releaseTag }), + alpha + ); + assert.throws( + () => validateForkManifest({ ...alpha, releaseTag: "ccu-rust-v0.145.0-r2-alpha.0" }), + /release contract/ + ); +}); + test("fork release ordering handles a new upstream and same-upstream revisions", () => { assert.equal(compareForkReleases(manifest(1), manifest(2)), -1); assert.equal(compareForkReleases(manifest(2), manifest(1)), 1); @@ -85,3 +104,45 @@ test("latest fork release resolves the manifest asset and checks the GitHub tag" assert.equal(calls.length, 2); assert.match(calls[0], /api\.github\.com\/repos\/Cec1c\/codex\/releases\/latest/); }); + +test("an exact fork Alpha tag resolves its prerelease assets", async () => { + const value = manifest(2, "0.145.0", { alpha: 1 }); + const calls = []; + const fetchImpl = async (url) => { + calls.push(String(url)); + if (calls.length === 1) { + return new Response(JSON.stringify({ + draft: false, + prerelease: true, + tag_name: value.releaseTag, + html_url: `https://github.com/Cec1c/codex/releases/tag/${value.releaseTag}`, + assets: [{ + name: "ccu-fork-manifest.json", + browser_download_url: + `https://github.com/Cec1c/codex/releases/download/${value.releaseTag}/ccu-fork-manifest.json` + }] + }), { status: 200 }); + } + return new Response(JSON.stringify(value), { status: 200 }); + }; + + const alpha = await resolveLatestForkRelease({ + fetchImpl, + releaseTag: value.releaseTag + }); + assert.deepEqual(alpha.manifest, value); + assert.match(calls[0], /releases\/tags\/ccu-rust-v0\.145\.0-r2-alpha\.1$/); + + await assert.rejects( + resolveLatestForkRelease({ + releaseTag: value.releaseTag, + fetchImpl: async () => new Response(JSON.stringify({ + draft: false, + prerelease: false, + tag_name: value.releaseTag, + assets: [] + }), { status: 200 }) + }), + /prerelease state/ + ); +}); diff --git a/test/release/github-version.test.mjs b/test/release/github-version.test.mjs index 4ed1921..2f4b8a1 100644 --- a/test/release/github-version.test.mjs +++ b/test/release/github-version.test.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { + compareCcuVersions, compareStableVersions, resolveLatestCcuRelease, resolveLatestUpstreamRelease @@ -58,3 +59,10 @@ test("stable version comparison is numeric", () => { assert.equal(compareStableVersions("0.144.6", "0.144.6"), 0); assert.equal(compareStableVersions("1.0.0", "0.999.999"), 1); }); + +test("CCU version comparison orders Alpha builds without downgrading them", () => { + assert.equal(compareCcuVersions("0.1.8-alpha.1", "0.1.8-alpha.2"), -1); + assert.equal(compareCcuVersions("0.1.8-alpha.2", "0.1.8"), -1); + assert.equal(compareCcuVersions("0.1.8-alpha.1", "0.1.7"), 1); + assert.equal(compareCcuVersions("0.1.8", "0.1.8"), 0); +}); diff --git a/test/update-upgrade.test.mjs b/test/update-upgrade.test.mjs index f2ea032..c89da47 100644 --- a/test/update-upgrade.test.mjs +++ b/test/update-upgrade.test.mjs @@ -4,9 +4,15 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; -import { stageCcuUpgrade } from "../src/update/upgrade.mjs"; +import { + scheduleCcuUpgradeApply, + stageCcuUpgrade +} from "../src/update/upgrade.mjs"; +import { resolveRuntimePlatform } from "../src/platform/runtime.mjs"; const SHA256 = `sha256:${"a".repeat(64)}`; +const LINUX = resolveRuntimePlatform({ platform: "linux", arch: "x64" }); +const RUNTIME = resolveRuntimePlatform(); function updateManifest() { return { @@ -14,7 +20,7 @@ function updateManifest() { type: "codex-cli-ultra-update", ccuVersion: "0.1.6", releaseTag: "v0.1.6", - platform: "windows-x64", + platform: RUNTIME.id, minimumManagerVersion: "0.1.5", bundledFork: { releaseTag: "ccu-rust-v0.146.0-r1", @@ -23,7 +29,7 @@ function updateManifest() { i18nApiVersion: 1 }, asset: { - name: "codex-cli-ultra-v0.1.6-windows-x64.zip", + name: `codex-cli-ultra-v0.1.6-${RUNTIME.id}.zip`, size: 4, sha256: SHA256 } @@ -39,6 +45,20 @@ function resolvedPackage(provider) { }; } +test("an Alpha manager does not downgrade itself to an older stable release", async () => { + const report = await stageCcuUpgrade({ + installRoot: "/tmp/ccu-alpha-version-check", + currentVersion: "0.1.8-alpha.1", + resolveCcuUpdatePackage: async () => resolvedPackage({ + async materializeAsset() { + assert.fail("an older stable package must not be downloaded"); + } + }) + }); + assert.equal(report.changed, false); + assert.equal(report.message, "CCU is already current or newer"); +}); + test("CCU upgrade forwards real progress through verify and extract stages", async () => { const installRoot = await mkdtemp(join(tmpdir(), "ccu-upgrade-stage-")); const stages = []; @@ -69,7 +89,7 @@ test("CCU upgrade forwards real progress through verify and extract stages", asy assert.equal(report.changed, true); assert.deepEqual(stages, ["download", "verify", "extract", "ready"]); assert.deepEqual(progress.map((event) => event.percent), [100]); - assert.match(report.installScript, /package[\\/]install\.ps1$/); + assert.equal(report.installScript.split(/[\\/]/).at(-1), RUNTIME.installerName); await rm(installRoot, { recursive: true, force: true }); }); @@ -79,7 +99,7 @@ test("CCU upgrade removes a corrupt completed partial before retry", async () => installRoot, "cache", "updates", - "codex-cli-ultra-v0.1.6-windows-x64.zip.part" + `codex-cli-ultra-v0.1.6-${RUNTIME.id}.zip.part` ); await assert.rejects( stageCcuUpgrade({ @@ -100,3 +120,43 @@ test("CCU upgrade removes a corrupt completed partial before retry", async () => await assert.rejects(access(downloadPath), { code: "ENOENT" }); await rm(installRoot, { recursive: true, force: true }); }); + +test("POSIX CCU upgrade handoff uses a private shell script and preserves installer flags", async () => { + const writes = []; + const spawns = []; + const staged = { + changed: true, + manifest: { ccuVersion: "0.1.6" }, + installScript: "/tmp/ccu stage/package/install.sh", + downloadPath: "/home/alice/.local/share/codex-cli-ultra/cache/update.zip.part", + stagingRoot: "/home/alice/.local/share/codex-cli-ultra/cache/stage-1" + }; + const report = await scheduleCcuUpgradeApply(staged, { + runtime: LINUX, + installRoot: "/home/alice/.local/share/codex-cli-ultra", + managerPid: 42, + env: { HOME: "/home/alice", PATH: "/usr/bin" }, + mkdir: async () => {}, + writeFile: async (...args) => writes.push(args), + spawn: (...args) => { + spawns.push(args); + return { pid: 123, once() {}, unref() {} }; + } + }); + + assert.equal(report.scheduled, true); + assert.equal(writes.length, 1); + assert.match(writes[0][0], /cache[\\/]update-jobs[\\/].+\.sh$/); + assert.match(writes[0][1], /bash "\$CCU_INSTALL_SCRIPT" --non-interactive --preserve-statusline/); + assert.deepEqual(writes[0][2], { encoding: "utf8", mode: 0o700 }); + assert.equal(spawns.length, 1); + assert.equal(spawns[0][0], "sh"); + assert.deepEqual(spawns[0][1], [writes[0][0]]); + assert.equal(spawns[0][2].detached, true); + assert.equal(spawns[0][2].env.CCU_MANAGER_PID, "42"); + assert.equal(spawns[0][2].env.CCU_INSTALL_SCRIPT, staged.installScript); + assert.equal( + spawns[0][2].env.CCU_INSTALLED_MANAGER, + "/home/alice/.local/share/codex-cli-ultra/bin/ccu-manager" + ); +}); diff --git a/test/workflow-sync-channel.test.mjs b/test/workflow-sync-channel.test.mjs index 034a15a..40d8aeb 100644 --- a/test/workflow-sync-channel.test.mjs +++ b/test/workflow-sync-channel.test.mjs @@ -26,13 +26,32 @@ test("stable channel workflow commits a newly created untracked manifest", async }); test("release workflow verifies the published ZIP and SHA256 sidecar", async () => { - const workflow = await readFile( - new URL("../.github/workflows/release.yml", import.meta.url), - "utf8" - ); + const [workflow, verifier] = await Promise.all([ + readFile( + new URL("../.github/workflows/release.yml", import.meta.url), + "utf8" + ), + readFile( + new URL("../scripts/verify-release-artifacts.mjs", import.meta.url), + "utf8" + ) + ]); assert.match(workflow, /gh release create[\s\S]*--verify-tag/); + assert.match(workflow, /!v\*-alpha\.\*/); + assert.match(workflow, /Alpha CCU releases require an exact Alpha fork tag/); + assert.match(workflow, /--prerelease/); assert.match(workflow, /gh release download/); - assert.match(workflow, /Get-FileHash[\s\S]*SHA256/); - assert.match(workflow, /downloaded release asset failed SHA256 verification/); + assert.match(workflow, /verify-release-artifacts\.mjs/); + for (const platform of [ + "windows-x64", + "linux-x64", + "linux-arm64", + "macos-x64", + "macos-arm64" + ]) { + assert.match(workflow, new RegExp(platform)); + } + assert.match(verifier, /sha256File/); + assert.match(verifier, /SHA-256 sidecar does not match its archive/); }); diff --git a/tui/src/main.rs b/tui/src/main.rs index 3c19cd1..b4b792a 100644 --- a/tui/src/main.rs +++ b/tui/src/main.rs @@ -126,6 +126,8 @@ struct ForkManifest { #[derive(Debug, Clone, Deserialize, Serialize, Default)] struct RemoteVersion { version: String, + #[serde(default)] + url: Option, } #[derive(Debug, Clone, Deserialize, Serialize, Default)] @@ -331,6 +333,25 @@ impl App { ); } + fn open_release_page(&mut self) { + let url = trusted_release_url( + self.status + .latest_ccu + .as_ref() + .and_then(|release| release.url.as_deref()), + ); + match open_url(url) { + Ok(()) => { + self.notice = format!("已在默认浏览器中打开 {url}"); + self.failed = false; + } + Err(error) => { + self.notice = format!("无法自动打开浏览器:{error};请访问 {url}"); + self.failed = true; + } + } + } + fn refresh_now(&mut self, online: bool) { let args = if online { vec![ @@ -757,6 +778,81 @@ fn friendly_error(source: &str) -> String { source.trim().to_string() } +fn trusted_release_url(candidate: Option<&str>) -> &str { + candidate + .filter(|url| { + *url == RELEASES_URL + || url + .strip_prefix(RELEASES_URL) + .is_some_and(|suffix| suffix.starts_with("/tag/v")) + }) + .unwrap_or(RELEASES_URL) +} + +fn fork_manifest_name() -> &'static str { + if cfg!(target_os = "windows") { + "ccu-fork-manifest.json" + } else if cfg!(all(target_os = "linux", target_arch = "x86_64")) { + "ccu-fork-manifest-linux-x64.json" + } else if cfg!(all(target_os = "linux", target_arch = "aarch64")) { + "ccu-fork-manifest-linux-arm64.json" + } else if cfg!(all(target_os = "macos", target_arch = "x86_64")) { + "ccu-fork-manifest-macos-x64.json" + } else if cfg!(all(target_os = "macos", target_arch = "aarch64")) { + "ccu-fork-manifest-macos-arm64.json" + } else { + "ccu-fork-manifest.json" + } +} + +fn open_url(url: &str) -> Result<()> { + #[cfg(target_os = "windows")] + { + let status = Command::new("cmd") + .args(["/C", "start", "", url]) + .status() + .context("无法调用 Windows 默认浏览器")?; + if !status.success() { + bail!("Windows 默认浏览器命令返回 {status}"); + } + return Ok(()); + } + #[cfg(target_os = "macos")] + { + let status = Command::new("open") + .arg(url) + .status() + .context("无法调用 macOS open")?; + if !status.success() { + bail!("macOS open 返回 {status}"); + } + return Ok(()); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + for program in ["xdg-open", "wslview"] { + if Command::new(program) + .arg(url) + .status() + .is_ok_and(|status| status.success()) + { + return Ok(()); + } + } + if std::env::var_os("WSL_DISTRO_NAME").is_some() + && Command::new("cmd.exe") + .args(["/C", "start", "", url]) + .status() + .is_ok_and(|status| status.success()) + { + return Ok(()); + } + bail!("未找到 xdg-open、wslview 或 WSL 浏览器桥接") + } + #[cfg(not(any(target_os = "windows", target_os = "macos", unix)))] + bail!("当前平台不支持自动打开浏览器") +} + fn format_online_errors(errors: &[OnlineError]) -> String { let channels = errors .iter() @@ -788,7 +884,7 @@ fn discover_local_release( } } for root in candidates { - let manifest_path = root.join("ccu-fork-manifest.json"); + let manifest_path = root.join(fork_manifest_name()); let Ok(source) = fs::read_to_string(&manifest_path) else { continue; }; @@ -905,6 +1001,7 @@ fn run(terminal: &mut Terminal>, app: &mut App) -> ), KeyCode::Char('i') => app.install_local(), KeyCode::Char('u') => app.start_ccu_upgrade(), + KeyCode::Char('o') => app.open_release_page(), KeyCode::Char('P') => app.begin_proxy_edit(), KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::SHIFT) => { app.begin_proxy_edit(); @@ -1003,7 +1100,7 @@ fn draw(frame: &mut ratatui::Frame, app: &App) { ), ]), Line::from(Span::styled( - "Tab/1-3 切换 r 刷新 c 检查版本 u 升级完整CCU p 代理开关 Shift+P 配置 q 退出", + "Tab/1-3 切换 r 刷新 c 检查版本 u 升级完整CCU o 打开Release p 代理开关 Shift+P 配置 q 退出", Style::default().fg(MUTED), )), ]) @@ -1270,7 +1367,7 @@ fn draw_status(frame: &mut ratatui::Frame, area: ratatui::layout::Rect, app: &Ap ), Line::from(""), Line::from(Span::styled( - "c 同步三路远程版本;u 下载、校验并升级完整 CCU,完成后 Manager 会自动接力安装。", + "c 同步三路远程版本;u 下载并升级完整 CCU;o 在默认浏览器打开对应 Release。", Style::default().fg(MUTED), )), Line::from(Span::styled( @@ -1422,6 +1519,20 @@ mod tests { assert!(message.contains("本地后按 i 安装")); } + #[test] + fn release_page_accepts_only_the_ccu_repository() { + assert_eq!( + trusted_release_url(Some( + "https://github.com/Cec1c/codex-cli-ultra/releases/tag/v0.1.7" + )), + "https://github.com/Cec1c/codex-cli-ultra/releases/tag/v0.1.7" + ); + assert_eq!( + trusted_release_url(Some("https://example.com/fake-release")), + RELEASES_URL + ); + } + #[test] fn discovers_a_complete_local_fork_release() { let root = @@ -1429,7 +1540,7 @@ mod tests { let _ = fs::remove_dir_all(&root); fs::create_dir_all(&root).unwrap(); fs::write( - root.join("ccu-fork-manifest.json"), + root.join(fork_manifest_name()), r#"{"displayVersion":"0.144.6-ccu.i18n.2","upstreamVersion":"0.144.6","asset":{"name":"fork.zip"}}"#, ) .unwrap(); diff --git a/uninstall.sh b/uninstall.sh new file mode 100644 index 0000000..727bc9b --- /dev/null +++ b/uninstall.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail + +install_root=${CODEX_ULTRA_HOME:-} +if [[ ${1:-} == --install-root ]]; then + install_root=${2:?--install-root requires a path} +elif (($#)); then + echo "usage: uninstall.sh [--install-root PATH]" >&2 + exit 2 +fi + +if [[ -z "$install_root" ]]; then + if [[ $(uname -s) == Darwin ]]; then + install_root="$HOME/Library/Application Support/codex-cli-ultra" + else + install_root="${XDG_DATA_HOME:-$HOME/.local/share}/codex-cli-ultra" + fi +fi + +manager="$install_root/bin/codex-ultra.mjs" +if [[ ! -f "$manager" ]]; then + echo "Codex CLI Ultra is not installed at $install_root" + exit 0 +fi + +export CODEX_ULTRA_HOME="$install_root" +node "$manager" uninstall From a8d7297384924e2f9fe14f45d6ce89c927cdced6 Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Thu, 30 Jul 2026 11:30:51 +0800 Subject: [PATCH 2/9] chore: mark POSIX installers executable --- install.sh | 0 uninstall.sh | 0 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 install.sh mode change 100644 => 100755 uninstall.sh diff --git a/install.sh b/install.sh old mode 100644 new mode 100755 diff --git a/uninstall.sh b/uninstall.sh old mode 100644 new mode 100755 From 0274303c28e1622e64f588d764cad572949de45f Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Thu, 30 Jul 2026 11:39:10 +0800 Subject: [PATCH 3/9] fix(release): use GNU target for Linux ARM64 --- src/platform/runtime.mjs | 2 +- test/platform.test.mjs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/platform/runtime.mjs b/src/platform/runtime.mjs index c3b785a..ef2c5d6 100644 --- a/src/platform/runtime.mjs +++ b/src/platform/runtime.mjs @@ -39,7 +39,7 @@ const DEFINITIONS = new Map([ id: "linux-arm64", nodePlatform: "linux", arch: "arm64", - target: "aarch64-unknown-linux-musl", + target: "aarch64-unknown-linux-gnu", npmPackage: "@openai/codex-linux-arm64", npmSuffix: "linux-arm64", binaryName: "codex", diff --git a/test/platform.test.mjs b/test/platform.test.mjs index 27b1e74..d0d5639 100644 --- a/test/platform.test.mjs +++ b/test/platform.test.mjs @@ -17,6 +17,7 @@ import { } from "../src/platform/runtime.mjs"; const LINUX = resolveRuntimePlatform({ platform: "linux", arch: "x64" }); +const LINUX_ARM = resolveRuntimePlatform({ platform: "linux", arch: "arm64" }); const MAC_ARM = resolveRuntimePlatform({ platform: "darwin", arch: "arm64" }); const execFileAsync = promisify(execFile); @@ -36,6 +37,7 @@ test("runtime platform descriptors cover Linux and both macOS architectures", () } ); assert.equal(MAC_ARM.id, "macos-arm64"); + assert.equal(LINUX_ARM.target, "aarch64-unknown-linux-gnu"); assert.equal(MAC_ARM.target, "aarch64-apple-darwin"); assert.equal( resolveRuntimePlatform({ platform: "darwin", arch: "x64" }).target, From 33cb1afb9141f6c5795e57c08e19e5664da15ede Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Thu, 30 Jul 2026 11:41:46 +0800 Subject: [PATCH 4/9] fix(release): separate Linux fork and npm targets --- src/discovery/official-codex.mjs | 2 +- src/launcher/select-target.mjs | 2 +- src/platform/runtime.mjs | 7 ++++++- src/state/schema.mjs | 2 +- test/platform.test.mjs | 6 ++++-- 5 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/discovery/official-codex.mjs b/src/discovery/official-codex.mjs index b4386f9..169b196 100644 --- a/src/discovery/official-codex.mjs +++ b/src/discovery/official-codex.mjs @@ -305,7 +305,7 @@ export async function discoverOfficialCodex(options = {}) { const expectedBinaryPath = pathApi.join( pathApi.dirname(platformPackageJsonPath), "vendor", - runtime.target, + runtime.officialTarget, "bin", runtime.binaryName ); diff --git a/src/launcher/select-target.mjs b/src/launcher/select-target.mjs index e2ff350..8af70c4 100644 --- a/src/launcher/select-target.mjs +++ b/src/launcher/select-target.mjs @@ -137,7 +137,7 @@ function expectedOfficialPaths(packageJsonPath, runtime) { binaryPath: pathApi.join( pathApi.dirname(platformPackageJsonPath), "vendor", - runtime.target, + runtime.officialTarget, "bin", runtime.binaryName ) diff --git a/src/platform/runtime.mjs b/src/platform/runtime.mjs index ef2c5d6..4cb53cc 100644 --- a/src/platform/runtime.mjs +++ b/src/platform/runtime.mjs @@ -8,6 +8,7 @@ const DEFINITIONS = new Map([ nodePlatform: "win32", arch: "x64", target: "x86_64-pc-windows-msvc", + officialTarget: "x86_64-pc-windows-msvc", npmPackage: "@openai/codex-win32-x64", npmSuffix: "win32-x64", binaryName: "codex.exe", @@ -23,7 +24,8 @@ const DEFINITIONS = new Map([ id: "linux-x64", nodePlatform: "linux", arch: "x64", - target: "x86_64-unknown-linux-musl", + target: "x86_64-unknown-linux-gnu", + officialTarget: "x86_64-unknown-linux-musl", npmPackage: "@openai/codex-linux-x64", npmSuffix: "linux-x64", binaryName: "codex", @@ -40,6 +42,7 @@ const DEFINITIONS = new Map([ nodePlatform: "linux", arch: "arm64", target: "aarch64-unknown-linux-gnu", + officialTarget: "aarch64-unknown-linux-musl", npmPackage: "@openai/codex-linux-arm64", npmSuffix: "linux-arm64", binaryName: "codex", @@ -56,6 +59,7 @@ const DEFINITIONS = new Map([ nodePlatform: "darwin", arch: "x64", target: "x86_64-apple-darwin", + officialTarget: "x86_64-apple-darwin", npmPackage: "@openai/codex-darwin-x64", npmSuffix: "darwin-x64", binaryName: "codex", @@ -72,6 +76,7 @@ const DEFINITIONS = new Map([ nodePlatform: "darwin", arch: "arm64", target: "aarch64-apple-darwin", + officialTarget: "aarch64-apple-darwin", npmPackage: "@openai/codex-darwin-arm64", npmSuffix: "darwin-arm64", binaryName: "codex", diff --git a/src/state/schema.mjs b/src/state/schema.mjs index 73b2bd6..187764f 100644 --- a/src/state/schema.mjs +++ b/src/state/schema.mjs @@ -156,7 +156,7 @@ function validateOfficial(value, runtime) { const expectedBinaryPath = pathApi.join( pathApi.dirname(official.platformPackageJsonPath), "vendor", - runtime.target, + runtime.officialTarget, "bin", runtime.binaryName ); diff --git a/test/platform.test.mjs b/test/platform.test.mjs index d0d5639..7fc0e2d 100644 --- a/test/platform.test.mjs +++ b/test/platform.test.mjs @@ -26,12 +26,14 @@ test("runtime platform descriptors cover Linux and both macOS architectures", () { id: LINUX.id, target: LINUX.target, + officialTarget: LINUX.officialTarget, npmPackage: LINUX.npmPackage, binaryName: LINUX.binaryName }, { id: "linux-x64", - target: "x86_64-unknown-linux-musl", + target: "x86_64-unknown-linux-gnu", + officialTarget: "x86_64-unknown-linux-musl", npmPackage: "@openai/codex-linux-x64", binaryName: "codex" } @@ -117,7 +119,7 @@ test("Linux launch selection accepts only the platform-specific installed layout const packageJsonPath = "/opt/node/lib/node_modules/@openai/codex/package.json"; const platformPackageJsonPath = "/opt/node/lib/node_modules/@openai/codex/node_modules/@openai/codex-linux-x64/package.json"; const officialBinary = "/opt/node/lib/node_modules/@openai/codex/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex"; - const ultraBinary = `${installRoot}/releases/0.145.0-ccu.i18n.2/x86_64-unknown-linux-musl/package/bin/codex`; + const ultraBinary = `${installRoot}/releases/0.145.0-ccu.i18n.2/${LINUX.target}/package/bin/codex`; const state = { schemaVersion: 1, official: { From 85477533e1ae9bedd722f4044306ec4983989f04 Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Thu, 30 Jul 2026 14:56:46 +0800 Subject: [PATCH 5/9] fix(release): make Windows alpha packaging portable --- README.en.md | 4 ++-- README.md | 4 ++-- package-lock.json | 4 ++-- package.json | 2 +- scripts/package-release.mjs | 2 +- scripts/package-release.ps1 | 2 +- src/version.mjs | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.en.md b/README.en.md index 593f520..0707752 100644 --- a/README.en.md +++ b/README.en.md @@ -228,7 +228,7 @@ node src/cli.mjs language validate ` | Channel | Current example | Updated when | | --- | --- | --- | -| CCU | `v0.1.8-alpha.1` | Installer, manager, content, or documentation changes | +| CCU | `v0.1.8-alpha.2` | Installer, manager, content, or documentation changes | | CCU-I18N fork | `v0.145.0-CCU.R2` (Alpha) | Codex source or the i18n interface changes | | OpenAI Codex | `0.145.0` | A new official stable version is released | @@ -239,7 +239,7 @@ Automation checks upstream stable Releases every six hours. A CCU-only update do | Item | Status | | --- | --- | | Supported platforms | Windows x64; Linux x64/ARM64; macOS Intel/Apple Silicon | -| CCU | `v0.1.8-alpha.1` | +| CCU | `v0.1.8-alpha.2` | | CCU-I18N | `v0.145.0-CCU.R2` (Alpha) | | Reference locale | Simplified Chinese (`zh-CN`) | | FTL coverage | 1,396 actively used message keys | diff --git a/README.md b/README.md index bd6060f..e32d216 100644 --- a/README.md +++ b/README.md @@ -230,7 +230,7 @@ node src/cli.mjs language validate ` | 通道 | 当前版本示例 | 更新条件 | | --- | --- | --- | -| CCU | `v0.1.8-alpha.1` | 安装器、管理器、内容包或文档发生变化 | +| CCU | `v0.1.8-alpha.2` | 安装器、管理器、内容包或文档发生变化 | | CCU-I18N fork | `v0.145.0-CCU.R2`(Alpha) | Codex 源码或 i18n 接口发生变化 | | OpenAI Codex | `0.145.0` | 官方发布新的稳定版本 | @@ -241,7 +241,7 @@ node src/cli.mjs language validate ` | 项目 | 状态 | | --- | --- | | 支持平台 | Windows x64;Linux x64/ARM64;macOS Intel/Apple Silicon | -| CCU | `v0.1.8-alpha.1` | +| CCU | `v0.1.8-alpha.2` | | CCU-I18N | `v0.145.0-CCU.R2`(Alpha) | | 参考语言包 | 简体中文 `zh-CN` | | FTL 覆盖 | 1,396 个实际使用的消息键 | diff --git a/package-lock.json b/package-lock.json index 87d76ea..8b1bacd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codex-cli-ultra", - "version": "0.1.8-alpha.1", + "version": "0.1.8-alpha.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codex-cli-ultra", - "version": "0.1.8-alpha.1", + "version": "0.1.8-alpha.2", "dependencies": { "@fluent/bundle": "0.19.1", "@fluent/syntax": "0.19.0", diff --git a/package.json b/package.json index d561970..6b42a7d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codex-cli-ultra", - "version": "0.1.8-alpha.1", + "version": "0.1.8-alpha.2", "private": true, "type": "module", "packageManager": "npm@11.12.1", diff --git a/scripts/package-release.mjs b/scripts/package-release.mjs index eaf015b..1fca8fa 100644 --- a/scripts/package-release.mjs +++ b/scripts/package-release.mjs @@ -126,7 +126,7 @@ if ( } if (!skipBuild) { - run(RUNTIME_PLATFORM.isWindows ? "npm.cmd" : "npm", ["run", "build"]); + run(process.execPath, ["scripts/build-executor.mjs"]); run("cargo", ["build", "--release", "--locked"], join(root, "tui")); } diff --git a/scripts/package-release.ps1 b/scripts/package-release.ps1 index d48b79a..cb17527 100644 --- a/scripts/package-release.ps1 +++ b/scripts/package-release.ps1 @@ -1,6 +1,6 @@ [CmdletBinding()] param( - [string]$Version = '0.1.8-alpha.1', + [string]$Version = '0.1.8-alpha.2', [string]$MinimumManagerVersion = '0.1.5', [string]$OutputDirectory = $(Join-Path (Split-Path -Parent $PSScriptRoot) 'artifacts'), [string]$ForkReleaseDir = $env:CCU_FORK_RELEASE_DIR diff --git a/src/version.mjs b/src/version.mjs index ab194ce..d5f747e 100644 --- a/src/version.mjs +++ b/src/version.mjs @@ -1 +1 @@ -export const CCU_VERSION = "0.1.8-alpha.1"; +export const CCU_VERSION = "0.1.8-alpha.2"; From 1f27d8dc277fcf1875e25d7b887dba98b23f890a Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Thu, 30 Jul 2026 16:16:48 +0800 Subject: [PATCH 6/9] feat(installer): allow standalone CCU installs --- README.en.md | 10 ++++--- README.md | 10 ++++--- docs/CCU_I18N_FORK_PLAN.md | 12 ++++----- docs/PLAN2_PROGRESS.md | 2 +- docs/macos-testing.md | 8 +++--- install.ps1 | 6 ++--- package-lock.json | 4 +-- package.json | 2 +- scripts/package-release.ps1 | 2 +- src/discovery/official-codex.mjs | 38 ++++++++++++++++++++------- src/installer/install.mjs | 8 ++++-- src/launcher/select-target.mjs | 27 +++++++++++-------- src/manage-main.mjs | 6 ++++- src/state/schema.mjs | 3 ++- src/version.mjs | 2 +- test/installer/fork-install.test.mjs | 25 ++++++++++++++++++ test/installer/state.test.mjs | 4 ++- test/installer/uninstall.test.mjs | 39 ++++++++++++++++++++++++++++ test/launcher/discovery.test.mjs | 38 ++++++++++++++++++++++++++- test/launcher/select-target.test.mjs | 11 ++++++++ test/manage-main.test.mjs | 22 ++++++++++++++++ uninstall.ps1 | 4 +-- 22 files changed, 228 insertions(+), 55 deletions(-) diff --git a/README.en.md b/README.en.md index 0707752..70a41bb 100644 --- a/README.en.md +++ b/README.en.md @@ -41,9 +41,11 @@ The terminal background, font, and colors are provided by a separate terminal co - Windows x64, Linux x64/ARM64, or macOS Intel/Apple Silicon - Node.js 22.19.0 or newer -- Official Codex installed through npm +- Official Codex is optional; when present, CCU records it as a failure fallback - PowerShell 7 on Windows; Bash on Linux and macOS +Optional: install official Codex first if you want to retain it as a fallback: + ```powershell npm install -g @openai/codex ``` @@ -160,7 +162,7 @@ CCU-I18N fork ── i18n API + built-in English fallback CCU manager ── install / update / uninstall / sync ``` -The official npm Codex remains installed as an English fallback. The launcher selects the verified fork from local state and falls back to the official binary when that state is invalid. +Official npm Codex is an optional fallback. Without it, CCU installs in standalone mode and launches the verified fork directly. The launcher falls back to an official binary only when one was recorded and the fork state is invalid. ## Repository structure @@ -228,7 +230,7 @@ node src/cli.mjs language validate ` | Channel | Current example | Updated when | | --- | --- | --- | -| CCU | `v0.1.8-alpha.2` | Installer, manager, content, or documentation changes | +| CCU | `v0.1.8-alpha.3` | Installer, manager, content, or documentation changes | | CCU-I18N fork | `v0.145.0-CCU.R2` (Alpha) | Codex source or the i18n interface changes | | OpenAI Codex | `0.145.0` | A new official stable version is released | @@ -239,7 +241,7 @@ Automation checks upstream stable Releases every six hours. A CCU-only update do | Item | Status | | --- | --- | | Supported platforms | Windows x64; Linux x64/ARM64; macOS Intel/Apple Silicon | -| CCU | `v0.1.8-alpha.2` | +| CCU | `v0.1.8-alpha.3` | | CCU-I18N | `v0.145.0-CCU.R2` (Alpha) | | Reference locale | Simplified Chinese (`zh-CN`) | | FTL coverage | 1,396 actively used message keys | diff --git a/README.md b/README.md index e32d216..c3e8942 100644 --- a/README.md +++ b/README.md @@ -41,9 +41,11 @@ Codex-Cli-Ultra(CCU)为 Codex CLI 提供外部 FTL 语言包、跨平台安 - Windows x64、Linux x64/ARM64,或 macOS Intel/Apple Silicon - Node.js 22.19.0 或更高版本 -- 通过 npm 安装的官方 Codex +- 官方 Codex 可选;若已安装,CCU 会登记它作为故障回退目标 - Windows 安装需要 PowerShell 7;Linux/macOS 安装需要 Bash +可选:若希望保留官方 Codex 作为回退目标,可先安装: + ```powershell npm install -g @openai/codex ``` @@ -160,7 +162,7 @@ CCU-I18N fork ── i18n API + built-in English fallback CCU manager ── install / update / uninstall / sync ``` -安装后保留官方 npm Codex 作为英文回退版本。CCU 启动器根据已校验的安装状态选择当前 fork;本地状态无效时回退到官方二进制。 +官方 npm Codex 是可选回退目标;没有官方版时,CCU 以 standalone 状态安装并直接启动已校验的 fork。若已登记官方版且 fork 状态无效,启动器才回退到官方二进制。 是的,这么追着codex的更新其实很累很低效,但相关维护人员暂时并没有理会我的关于添加i18n接口的issues,尽管我当时提交了一版示范 @@ -230,7 +232,7 @@ node src/cli.mjs language validate ` | 通道 | 当前版本示例 | 更新条件 | | --- | --- | --- | -| CCU | `v0.1.8-alpha.2` | 安装器、管理器、内容包或文档发生变化 | +| CCU | `v0.1.8-alpha.3` | 安装器、管理器、内容包或文档发生变化 | | CCU-I18N fork | `v0.145.0-CCU.R2`(Alpha) | Codex 源码或 i18n 接口发生变化 | | OpenAI Codex | `0.145.0` | 官方发布新的稳定版本 | @@ -241,7 +243,7 @@ node src/cli.mjs language validate ` | 项目 | 状态 | | --- | --- | | 支持平台 | Windows x64;Linux x64/ARM64;macOS Intel/Apple Silicon | -| CCU | `v0.1.8-alpha.2` | +| CCU | `v0.1.8-alpha.3` | | CCU-I18N | `v0.145.0-CCU.R2`(Alpha) | | 参考语言包 | 简体中文 `zh-CN` | | FTL 覆盖 | 1,396 个实际使用的消息键 | diff --git a/docs/CCU_I18N_FORK_PLAN.md b/docs/CCU_I18N_FORK_PLAN.md index 6de587b..b319d62 100644 --- a/docs/CCU_I18N_FORK_PLAN.md +++ b/docs/CCU_I18N_FORK_PLAN.md @@ -73,24 +73,24 @@ CODEX_CCU_LANGUAGE_PACK_ROOT - `/language` 本身不访问网络,也不负责安装或更新语言包。 - 整包加载失败时使用英文;单个键或参数格式失败时只对该条消息回退英文。 -## 5. 官方版与二开版共存 +## 5. 可选官方版与二开版共存 -CCU 不覆盖或修改官方 Codex 安装目录,而是登记两个独立目标: +CCU 不要求预装官方 Codex,也不覆盖或修改其安装目录。存在官方版时登记两个独立目标;不存在时以 `official = null` 的 standalone 状态管理 fork: ```text -official -> OpenAI 官方 codex +official -> OpenAI 官方 codex(可选) fork -> Cec1c/codex 的 CCU i18n 构建 ``` JS 执行器负责: -1. 发现已有官方 Codex。 +1. 尝试发现已有官方 Codex;未安装时继续 standalone 安装。 2. 下载并校验 fork release 中对应平台的二进制。 3. 保存活动目标和上一已知可用目标。 4. 通过 CCU 自己的 shim/launcher 决定默认 `codex` 指向。 -5. 支持显式启动官方版、二开版、回滚和 doctor 检查。 +5. 官方版存在时支持故障回退;无官方版时直接保持已校验 fork 可用。 -因此“默认使用二开”不等于替换官方安装,升级失败也不会破坏官方 Codex。 +因此“默认使用二开”不等于替换官方安装;官方版存在时升级失败不会破坏它,不存在时也不会阻止 CCU 首次安装。 ## 6. fork 自动跟踪与发布 diff --git a/docs/PLAN2_PROGRESS.md b/docs/PLAN2_PROGRESS.md index e151a6f..d5c07f5 100644 --- a/docs/PLAN2_PROGRESS.md +++ b/docs/PLAN2_PROGRESS.md @@ -49,7 +49,7 @@ - 已创建 GitHub fork `https://github.com/Cec1c/codex`;本地部分克隆位于 `.upstream/codex`,由 Ultra 的 `.gitignore` 默认排除。`origin` 指向个人 fork,`upstream` 指向 `openai/codex`。 - 官方 Codex 版本变化时,完整性正常的 Ultra 可进入 `optimistic coexistence` 模式继续运行,同时明确提示不宣称与新版官方 Codex 功能对齐。 - installer 使用 fork Release manifest 与 i18n API 合同,支持同上游 revision 更新和跨上游版本更新。 -- 仅保留官方 npm 英文备份与一个当前 CCU Release;launcher PATH 优先级保证 `codex` 默认进入 CCU。 +- 官方 npm Codex 改为可选回退目标;没有官方版时使用 `official = null` 的 standalone 状态,并只保留一个当前 CCU Release。launcher PATH 优先级保证 `codex` 默认进入 CCU。 - Rust 管理器提供状态、语言包、主题包页面;内容同步会把历史 `zh-Hans` 偏好迁移为 `zh-CN`。 ## FTL 模板与中文包收口 diff --git a/docs/macos-testing.md b/docs/macos-testing.md index b6f09c6..42799d2 100644 --- a/docs/macos-testing.md +++ b/docs/macos-testing.md @@ -7,7 +7,7 @@ 记录以下信息后再开始: - Mac 型号、CPU 架构和 macOS 版本; -- `node --version`、`npm --version`、`codex --version`; +- `node --version`、`npm --version`,以及安装前是否能找到 `codex`; - 下载的 CCU ZIP 文件名和 SHA256; - 默认 shell(通常为 zsh)及所用终端(Terminal、iTerm2 或 VS Code)。 @@ -15,7 +15,7 @@ Apple Silicon 和 Intel 各完成一次为完整验收;只有一类设备时 ## 安装与 Gatekeeper -1. 安装官方 npm Codex,确认安装 CCU 前 `codex --version` 正常。 +1. 确认 Node.js 不低于 22.19.0。优先在没有官方 Codex 的环境验证 standalone 安装,并记录 `command -v codex || true`;若设备已有官方版,不需要卸载,只需记录其版本。 2. 下载与 CPU 匹配的 ZIP 和 `.sha256`,运行: ```bash @@ -57,7 +57,7 @@ ccu-manager 再启动一次 `codex --yolo`,确认中文界面、键盘输入、窗口缩放和退出均正常。 -## 卸载与官方回退 +## 卸载与可选官方回退 运行: @@ -72,7 +72,7 @@ codex --version - CCU 安装目录已删除; - `~/.zshrc`、`~/.zprofile` 中没有残留 CCU PATH 标记; -- `codex` 回到安装前的官方 npm 版本; +- 安装前有官方版时,`codex` 回到该 npm 版本;安装前没有时,`command -v codex` 不再指向 CCU; - 原有 Codex 登录和配置仍可用。 报告失败时,请附上失败命令、完整 stderr、`codex-ultra status --json` 输出,以及是否经过 Gatekeeper/quarantine 处理;不要包含 API key、token 或其他凭据。 diff --git a/install.ps1 b/install.ps1 index da836f7..85115cb 100644 --- a/install.ps1 +++ b/install.ps1 @@ -167,7 +167,7 @@ if (-not [version]::TryParse($nodeVersionText, [ref]$nodeVersion) -or $nodeVersi } Write-Host '' Write-Host 'Codex CLI Ultra 中文版安装程序' -ForegroundColor Green -Write-Host '不会结束当前 Codex;官方 npm Codex 会保留为英文回退版本。' -ForegroundColor DarkGray +Write-Host '不会结束当前 Codex;官方 npm Codex 如已安装会保留为可选回退,未安装也可继续。' -ForegroundColor DarkGray Write-InstallStep -Number 1 -Total 5 -Message '检查安装包与本机环境' if (-not $packaged -and -not $SkipBuild) { $npmPath = Resolve-ApplicationPath -Name 'npm' -InstallHint 'Reinstall Node.js with npm and retry.' @@ -311,6 +311,6 @@ Write-InstallStep -Number 4 -Total 5 -Message '更新当前终端命令优先级 $env:Path = "$bin;$env:Path" Write-InstallStep -Number 5 -Total 5 -Message '安装完成' Write-Host "CCU 命令目录:$bin" -ForegroundColor Green -Write-Host '新终端中的 codex 会启动中文版本;官方英文版仍保留用于一键回退。' -ForegroundColor Green +Write-Host '新终端中的 codex 会启动中文版本;若已安装官方版,CCU 会保留它作为故障回退。' -ForegroundColor Green Write-Host '验证命令:codex --version;codex --i18n-self-check;codex --yolo' -ForegroundColor Cyan -Write-Host '卸载回退:运行安装包中的 uninstall.cmd,或执行 codex-ultra uninstall。' -ForegroundColor Cyan +Write-Host '卸载 CCU:运行安装包中的 uninstall.cmd,或执行 codex-ultra uninstall。' -ForegroundColor Cyan diff --git a/package-lock.json b/package-lock.json index 8b1bacd..c165955 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codex-cli-ultra", - "version": "0.1.8-alpha.2", + "version": "0.1.8-alpha.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codex-cli-ultra", - "version": "0.1.8-alpha.2", + "version": "0.1.8-alpha.3", "dependencies": { "@fluent/bundle": "0.19.1", "@fluent/syntax": "0.19.0", diff --git a/package.json b/package.json index 6b42a7d..8b6cc99 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codex-cli-ultra", - "version": "0.1.8-alpha.2", + "version": "0.1.8-alpha.3", "private": true, "type": "module", "packageManager": "npm@11.12.1", diff --git a/scripts/package-release.ps1 b/scripts/package-release.ps1 index cb17527..21fc047 100644 --- a/scripts/package-release.ps1 +++ b/scripts/package-release.ps1 @@ -1,6 +1,6 @@ [CmdletBinding()] param( - [string]$Version = '0.1.8-alpha.2', + [string]$Version = '0.1.8-alpha.3', [string]$MinimumManagerVersion = '0.1.5', [string]$OutputDirectory = $(Join-Path (Split-Path -Parent $PSScriptRoot) 'artifacts'), [string]$ForkReleaseDir = $env:CCU_FORK_RELEASE_DIR diff --git a/src/discovery/official-codex.mjs b/src/discovery/official-codex.mjs index 169b196..b4029c3 100644 --- a/src/discovery/official-codex.mjs +++ b/src/discovery/official-codex.mjs @@ -115,6 +115,7 @@ function sanitizeExecEnvironment(env, installRoot, runtime) { async function resolveTrustedNpmCommand({ env, installRoot, + allowMissing, realpathFile, statFile, runtime @@ -175,6 +176,7 @@ async function resolveTrustedNpmCommand({ } return { npmCommand, nodePath, npmCliPath }; } + if (allowMissing) return null; throw new Error( runtime.isWindows ? "no trusted npm.cmd found on the local PATH" @@ -187,6 +189,7 @@ async function resolveNpmRoot({ execFile, env, installRoot, + allowMissing, realpathFile, statFile, runtime @@ -198,10 +201,12 @@ async function resolveNpmRoot({ const npm = await resolveTrustedNpmCommand({ env, installRoot, + allowMissing, realpathFile, statFile, runtime }); + if (npm === null) return null; const executable = runtime.isWindows ? npm.nodePath : npm.npmCommand; const args = runtime.isWindows ? [npm.npmCliPath, "root", "-g"] : ["root", "-g"]; const execEnv = runtime.isWindows @@ -238,29 +243,40 @@ export async function discoverOfficialCodex(options = {}) { realpathImpl, runtime ); + if (!isAbsoluteLocalPath(installRoot, runtime)) { + throw new Error("install root must be an absolute local path"); + } const npmRoot = await resolveNpmRoot({ npmRoot: options.npmRoot, execFile: runExecFile, env: sanitizeExecEnvironment(env, installRoot, runtime), installRoot, + allowMissing: options.allowMissing === true, realpathFile: realpathImpl, statFile: statImpl, runtime }); - if (!isAbsoluteLocalPath(installRoot, runtime)) { - throw new Error("install root must be an absolute local path"); - } + if (npmRoot === null) return null; + if (!isAbsoluteLocalPath(npmRoot, runtime)) { throw new Error("npm root must be an absolute local path"); } - const packageJsonPath = await resolveExistingFile( - pathApi.join(npmRoot, "@openai", "codex", "package.json"), - "official Codex package.json", - realpathImpl, - runtime - ); + let packageJsonPath; + try { + packageJsonPath = await resolveExistingFile( + pathApi.join(npmRoot, "@openai", "codex", "package.json"), + "official Codex package.json", + realpathImpl, + runtime + ); + } catch (error) { + if (options.allowMissing === true && error?.cause?.code === "ENOENT") { + return null; + } + throw error; + } assertOutsideInstallRoot(installRoot, packageJsonPath, runtime); const manifest = parsePackageJson( await readFileImpl(packageJsonPath, "utf8"), @@ -337,3 +353,7 @@ export async function discoverOfficialCodex(options = {}) { binaryPath }; } + +export async function discoverOptionalOfficialCodex(options = {}) { + return await discoverOfficialCodex({ ...options, allowMissing: true }); +} diff --git a/src/installer/install.mjs b/src/installer/install.mjs index 452214b..29c07e6 100644 --- a/src/installer/install.mjs +++ b/src/installer/install.mjs @@ -23,7 +23,10 @@ import { resolveInstallRoot, } from "../config/constants.mjs"; import { pathApiFor } from "../platform/runtime.mjs"; -import { discoverOfficialCodex } from "../discovery/official-codex.mjs"; +import { + discoverOfficialCodex, + discoverOptionalOfficialCodex +} from "../discovery/official-codex.mjs"; import { validateLanguagePack } from "../language/validate.mjs"; import { buildLaunchEnvironment } from "../launcher/select-target.mjs"; import { extractZipSecure } from "../release/archive.mjs"; @@ -751,7 +754,8 @@ export async function installForkFromProvider(options) { } const statePath = join(installRoot, "state.json"); - const discover = options.discoverOfficialCodex ?? discoverOfficialCodex; + const discover = + options.discoverOfficialCodex ?? discoverOptionalOfficialCodex; const validateManifest = options.validateForkManifest ?? validateForkManifest; const hashFile = options.sha256File ?? sha256File; const extractZip = options.extractZipSecure ?? extractZipSecure; diff --git a/src/launcher/select-target.mjs b/src/launcher/select-target.mjs index 8af70c4..e5e1f83 100644 --- a/src/launcher/select-target.mjs +++ b/src/launcher/select-target.mjs @@ -430,23 +430,28 @@ export async function selectLaunchTarget(options = {}) { statFile, runtime }); - const officialUnavailable = !official.trusted; + const officialNotConfigured = officialCandidate === null; + const officialUnavailable = !officialNotConfigured && !official.trusted; const officialVersionChanged = official.rootVersion !== null && official.rootVersion !== active.upstreamVersion; - const officialNotice = officialUnavailable - ? `Codex Ultra: official Codex is unavailable while using ${active.releaseId}; run codex-ultra doctor.` - : officialVersionChanged - ? `Codex Ultra: ${active.releaseId} is based on Codex ${active.upstreamVersion} while official Codex ${official.rootVersion} is installed; continuing in optimistic coexistence mode without claiming feature parity.` - : null; + const officialNotice = officialNotConfigured + ? null + : officialUnavailable + ? `Codex Ultra: official Codex is unavailable while using ${active.releaseId}; run codex-ultra doctor.` + : officialVersionChanged + ? `Codex Ultra: ${active.releaseId} is based on Codex ${active.upstreamVersion} while official Codex ${official.rootVersion} is installed; continuing in optimistic coexistence mode without claiming feature parity.` + : null; return result( "ultra", ultra.path, - officialUnavailable - ? "official-unavailable-ultra-valid" - : officialVersionChanged - ? "ultra-optimistic-coexistence" - : "ultra-exact-match", + officialNotConfigured + ? "ultra-standalone" + : officialUnavailable + ? "official-unavailable-ultra-valid" + : officialVersionChanged + ? "ultra-optimistic-coexistence" + : "ultra-exact-match", combineNotices(officialNotice, language.notice), language.env ); diff --git a/src/manage-main.mjs b/src/manage-main.mjs index 202139c..b63eb65 100644 --- a/src/manage-main.mjs +++ b/src/manage-main.mjs @@ -721,7 +721,11 @@ export async function manageMain(options = {}) { const report = { ...result, cleanupScheduled }; if (json) writeJson(stdout, report); else { - stdout.write("已从用户 PATH 移除 CCU,codex 将回退到官方英文版。\n"); + stdout.write( + result.official === null + ? "已从用户 PATH 移除 CCU;未配置官方 Codex 回退。\n" + : "已从用户 PATH 移除 CCU,codex 将回退到官方英文版。\n" + ); stdout.write( cleanupScheduled ? "CCU 文件将在当前命令退出后自动删除。\n" diff --git a/src/state/schema.mjs b/src/state/schema.mjs index 187764f..fab0691 100644 --- a/src/state/schema.mjs +++ b/src/state/schema.mjs @@ -261,7 +261,8 @@ export function validateState(value, options = {}) { } return { schemaVersion: STATE_SCHEMA_VERSION, - official: validateOfficial(value.official, runtime), + official: + value.official === null ? null : validateOfficial(value.official, runtime), active: value.active === null ? null : validateBuild(value.active, "active", runtime), locale: value.locale === null ? null : validateLocale(value.locale, runtime), diff --git a/src/version.mjs b/src/version.mjs index d5f747e..4c32d40 100644 --- a/src/version.mjs +++ b/src/version.mjs @@ -1 +1 @@ -export const CCU_VERSION = "0.1.8-alpha.2"; +export const CCU_VERSION = "0.1.8-alpha.3"; diff --git a/test/installer/fork-install.test.mjs b/test/installer/fork-install.test.mjs index d6c6b7f..09a8a06 100644 --- a/test/installer/fork-install.test.mjs +++ b/test/installer/fork-install.test.mjs @@ -104,6 +104,31 @@ test("fork install keeps only the active CCU release beside the official backup" assert.equal(stored.lastKnownGood, null); }); +test("fork install supports a standalone state without official Codex", async (t) => { + const installRoot = await mkdtemp(join(tmpdir(), "ccu-fork-standalone-")); + t.after(() => rm(installRoot, { recursive: true, force: true })); + const installed = await installRevision(installRoot, 1, { + discoverOfficialCodex: undefined, + env: { PATH: "C:\\Windows\\System32" } + }); + + assert.equal(installed.result.state.official, null); + assert.equal( + installed.result.state.active.releaseId, + "0.144.5-ccu.i18n.1" + ); + const stored = await readState(join(installRoot, "state.json")); + assert.equal(stored.official, null); + assert.equal(stored.active.releaseId, "0.144.5-ccu.i18n.1"); + + const updated = await installRevision(installRoot, 2, { + discoverOfficialCodex: undefined, + env: { PATH: "C:\\Windows\\System32" } + }); + assert.equal(updated.result.state.official, null); + assert.equal(updated.result.state.active.releaseId, "0.144.5-ccu.i18n.2"); +}); + test("fork install defers cleanup when the running Codex locks the old release", async () => { const installRoot = await mkdtemp(join(tmpdir(), "ccu-fork-install-locked-")); await installRevision(installRoot, 1); diff --git a/test/installer/state.test.mjs b/test/installer/state.test.mjs index 5879b6b..427c4d7 100644 --- a/test/installer/state.test.mjs +++ b/test/installer/state.test.mjs @@ -103,12 +103,14 @@ test("valid state preserves only launch-stable facts in a deep clone", () => { assert.equal(validState.active.releaseId, "0.144.4-ultra.1"); }); -test("nullable active and locale plus an exact last-known-good pair are accepted", () => { +test("nullable official, active, and locale plus an exact last-known-good pair are accepted", () => { const inactive = validateState({ ...cloneState(), + official: null, active: null, locale: null }); + assert.equal(inactive.official, null); assert.equal(inactive.active, null); assert.equal(inactive.locale, null); diff --git a/test/installer/uninstall.test.mjs b/test/installer/uninstall.test.mjs index 66b62b5..5825cd5 100644 --- a/test/installer/uninstall.test.mjs +++ b/test/installer/uninstall.test.mjs @@ -105,3 +105,42 @@ test("uninstall preserves preferences not owned by CCU", async (t) => { "my.custom.theme\n" ); }); + +test("standalone uninstall preserves a null official target", async (t) => { + const installRoot = await mkdtemp(join(tmpdir(), "ccu-uninstall-standalone-")); + t.after(() => rm(installRoot, { recursive: true, force: true })); + const statePath = join(installRoot, "state.json"); + await writeStateAtomic(statePath, { + schemaVersion: 1, + official: null, + active: { + releaseId: "0.144.6-ccu.i18n.1", + upstreamVersion: "0.144.6", + ultraRevision: 1, + platform: "x86_64-pc-windows-msvc", + binaryPath: join( + installRoot, + "releases", + "0.144.6-ccu.i18n.1", + "x86_64-pc-windows-msvc", + "package", + "bin", + "codex.exe" + ), + size: 1, + mtimeMs: 1, + sha256: `sha256:${"a".repeat(64)}` + }, + locale: null, + lastKnownGood: null + }); + + const result = await uninstallCcu({ + installRoot, + removePathEntry: async () => ({ changed: true }) + }); + const stored = await readState(statePath); + assert.equal(result.official, null); + assert.equal(stored.official, null); + assert.equal(stored.active, null); +}); diff --git a/test/launcher/discovery.test.mjs b/test/launcher/discovery.test.mjs index 60a16e2..e8c5a46 100644 --- a/test/launcher/discovery.test.mjs +++ b/test/launcher/discovery.test.mjs @@ -11,7 +11,10 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test from "node:test"; -import { discoverOfficialCodex } from "../../src/discovery/official-codex.mjs"; +import { + discoverOfficialCodex, + discoverOptionalOfficialCodex +} from "../../src/discovery/official-codex.mjs"; const PLATFORM_PACKAGE = "@openai/codex-win32-x64"; const TARGET = "x86_64-pc-windows-msvc"; @@ -166,6 +169,32 @@ test("refuses to execute npm from relative or network PATH entries", async () => assert.equal(execCalled, false); }); +test("optional discovery accepts a missing npm command or official package", async () => { + const root = await mkdtemp(join(tmpdir(), "codex-ultra-optional-official-")); + const installRoot = join(root, "ultra"); + assert.equal( + await discoverOptionalOfficialCodex({ + installRoot, + env: { PATH: "C:\\Windows\\System32" } + }), + null + ); + + const npmRoot = join(root, "node_modules"); + await mkdir(npmRoot, { recursive: true }); + assert.equal( + await discoverOptionalOfficialCodex({ npmRoot, installRoot }), + null + ); + await assert.rejects( + discoverOptionalOfficialCodex({ + installRoot: "\\\\server\\share\\ultra", + env: { PATH: "C:\\Windows\\System32" } + }), + /Codex Ultra install root is unsafe|install root must be an absolute local path/ + ); +}); + test("rejects canonical package or install paths that resolve to a network share", async () => { const root = await mkdtemp(join(tmpdir(), "codex-ultra-network-realpath-")); const fixture = await createOfficialFixture({ root }); @@ -278,6 +307,13 @@ test("rejects package manifests that do not identify official Codex", async () = }), /official Codex package has an unexpected name/ ); + await assert.rejects( + discoverOptionalOfficialCodex({ + npmRoot: fixture.npmRoot, + installRoot: join(root, "ultra") + }), + /official Codex package has an unexpected name/ + ); }); test("rejects any discovered official path inside the Ultra install root", async () => { diff --git a/test/launcher/select-target.test.mjs b/test/launcher/select-target.test.mjs index fd6eee9..5729a02 100644 --- a/test/launcher/select-target.test.mjs +++ b/test/launcher/select-target.test.mjs @@ -204,6 +204,17 @@ test("selection checks local version sources before Ultra metadata", async () => ]); }); +test("standalone state launches Ultra without an official-missing warning", async () => { + const state = { ...structuredClone(exactState), official: null }; + const { result, calls } = await select({ state }); + + assert.equal(result.kind, "ultra"); + assert.equal(result.reason, "ultra-standalone"); + assert.equal(result.path, exactState.active.binaryPath); + assert.equal(result.notice, null); + assert.deepEqual(calls, [`stat:${exactState.active.binaryPath}`]); +}); + test("an incomplete official upgrade keeps a verified Ultra available", async () => { const readers = createReaders({ officialVersion: "0.145.0", diff --git a/test/manage-main.test.mjs b/test/manage-main.test.mjs index b876c6b..c137344 100644 --- a/test/manage-main.test.mjs +++ b/test/manage-main.test.mjs @@ -403,6 +403,28 @@ test("uninstall removes an unlocked install root without a background process", assert.equal(JSON.parse(output).cleanupScheduled, true); }); +test("standalone uninstall does not claim an official fallback", async () => { + let output = ""; + const code = await manageMain({ + args: ["uninstall"], + installRoot, + uninstallCcu: async () => ({ + changed: true, + installRoot, + official: null, + pathRemoved: true, + stateChanged: true, + removedPreferences: [] + }), + scheduleInstallRootCleanup: () => false, + stdout: { write(chunk) { output += chunk; } } + }); + + assert.equal(code, 0); + assert.match(output, /未配置官方 Codex 回退/); + assert.doesNotMatch(output, /回退到官方英文版/); +}); + test("uninstall reports cleanup as unscheduled when the helper has no pid", async () => { let output = ""; const code = await manageMain({ diff --git a/uninstall.ps1 b/uninstall.ps1 index 1cae388..1760d7d 100644 --- a/uninstall.ps1 +++ b/uninstall.ps1 @@ -13,7 +13,7 @@ $installRoot = [System.IO.Path]::GetFullPath($InstallRoot) $manager = Join-Path $installRoot 'bin\codex-ultra.mjs' Write-Host '' Write-Host 'Codex CLI Ultra 一键卸载' -ForegroundColor Yellow -Write-Host '不会结束当前 Codex;新命令会立即回退到官方英文版。' -ForegroundColor DarkGray +Write-Host '不会结束当前 Codex;若安装前存在官方版,新命令会回到该版本。' -ForegroundColor DarkGray if (-not (Test-Path -LiteralPath $manager -PathType Leaf)) { Write-Host "未找到已安装的 CCU 管理器:$manager" -ForegroundColor Yellow @@ -29,4 +29,4 @@ if ($LASTEXITCODE -ne 0) { throw "codex-ultra uninstall failed with exit code $LASTEXITCODE" } -Write-Host '卸载指令已完成。请打开新终端运行 codex --version 验证英文原版。' -ForegroundColor Green +Write-Host '卸载指令已完成。请打开新终端检查 command -v/where codex;安装前有官方版时再运行 codex --version。' -ForegroundColor Green From 4e11b25168d53f51f2af0ae4d1df5221948b0c39 Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Wed, 19 Aug 2026 10:53:11 +0800 Subject: [PATCH 7/9] fix(theme): migrate legacy ice preferences to rainbow --- src/content/sync.mjs | 20 ++++++++++++++++---- test/content-sync.test.mjs | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/content/sync.mjs b/src/content/sync.mjs index 53d069d..81e712e 100644 --- a/src/content/sync.mjs +++ b/src/content/sync.mjs @@ -22,8 +22,18 @@ const PRIMARY_THEME_DIRECTORY = "rainbow_color"; const HERMES_THEME_ID = "ccu.hermes"; const HERMES_THEME_DIRECTORY = "ccu-hermes"; const LEGACY_THEME_ID = "ccu.deepseek"; -const PREVIOUS_THEME_IDS = new Set([HERMES_THEME_ID, LEGACY_THEME_ID]); -const OWNED_THEME_IDS = new Set([PRIMARY_THEME_ID, HERMES_THEME_ID, LEGACY_THEME_ID]); +const LEGACY_ICE_THEME_ID = "ccu.ice-banner"; +const PREVIOUS_THEME_IDS = new Set([ + HERMES_THEME_ID, + LEGACY_THEME_ID, + LEGACY_ICE_THEME_ID +]); +const OWNED_THEME_IDS = new Set([ + PRIMARY_THEME_ID, + HERMES_THEME_ID, + LEGACY_THEME_ID, + LEGACY_ICE_THEME_ID +]); async function exists(path, lstatImpl = lstat) { try { @@ -238,7 +248,8 @@ export async function syncBundledContent(options) { const currentTheme = themePreferenceExists ? (await read(themePreference, "utf8")).trim() : null; - if (!themePreferenceExists || PREVIOUS_THEME_IDS.has(currentTheme)) { + const migratingPreviousTheme = PREVIOUS_THEME_IDS.has(currentTheme); + if (!themePreferenceExists || migratingPreviousTheme) { await write(themePreference, `${theme.id}\n`, "utf8"); } const requestedStatusLinePreset = @@ -267,7 +278,8 @@ export async function syncBundledContent(options) { } } else if ( requestedStatusLinePreset === undefined && - PREVIOUS_THEME_IDS.has(currentStatusLinePreset) + (PREVIOUS_THEME_IDS.has(currentStatusLinePreset) || + (!statusLinePreferenceExists && migratingPreviousTheme)) ) { await write(statusLinePreference, `${theme.id}\n`, "utf8"); } diff --git a/test/content-sync.test.mjs b/test/content-sync.test.mjs index 928f805..a75a324 100644 --- a/test/content-sync.test.mjs +++ b/test/content-sync.test.mjs @@ -194,6 +194,40 @@ test("content sync migrates the legacy DeepSeek preset and applies rainbow confi ); }); +test("content sync migrates the owned ice theme and enables the rainbow status line", async (t) => { + const root = await mkdtemp(join(tmpdir(), "ccu-content-ice-theme-")); + t.after(() => rm(root, { recursive: true, force: true })); + const codexHome = join(root, "codex-home"); + const installRoot = join(root, "install"); + await writeFile(join(root, "placeholder"), "", "utf8"); + await syncBundledContent({ + contentRoot: projectRoot, + installRoot, + env: { CODEX_HOME: codexHome } + }); + await Promise.all([ + writeFile(join(codexHome, "ui-theme"), "ccu.ice-banner\n", "utf8"), + writeFile(join(codexHome, "config.toml"), "[tui]\nstatus_line = []\n", "utf8") + ]); + + const result = await syncBundledContent({ + contentRoot: join(installRoot, "content"), + installRoot, + env: { CODEX_HOME: codexHome } + }); + + assert.equal(await readFile(join(codexHome, "ui-theme"), "utf8"), "rainbow_color\n"); + assert.equal( + await readFile(join(codexHome, "ui-statusline-preset"), "utf8"), + "rainbow_color\n" + ); + assert.equal(result.theme.statusLinePresetEnabled, true); + assert.match( + await readFile(join(codexHome, "config.toml"), "utf8"), + /"context-progress"/ + ); +}); + test("PowerShell installer lets the core claim ownership before copying local payloads", async () => { const source = await readFile(join(projectRoot, "install.ps1"), "utf8"); const installCall = source.lastIndexOf("Invoke-CcuInstall"); From 8c9576619ccc0f0771471cb992cdec6c5b893263 Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Wed, 19 Aug 2026 12:30:58 +0800 Subject: [PATCH 8/9] fix(launcher): unify Codex home across shells --- src/installer/bin.mjs | 10 ++++++---- test/platform.test.mjs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/installer/bin.mjs b/src/installer/bin.mjs index 3ff1556..b57da52 100644 --- a/src/installer/bin.mjs +++ b/src/installer/bin.mjs @@ -8,22 +8,24 @@ import { } from "../config/constants.mjs"; const WINDOWS_WRAPPERS = Object.freeze({ - "codex.cmd": '@echo off\r\nnode "%~dp0launcher.mjs" %*\r\nexit /b %ERRORLEVEL%\r\n', - "codex.ps1": "#!/usr/bin/env pwsh\n& node (Join-Path $PSScriptRoot 'launcher.mjs') @args\nexit $LASTEXITCODE\n", - "codex-ultra.cmd": '@echo off\r\nset "NODE_USE_ENV_PROXY=1"\r\nset "CODEX_CCU_CONTENT_ROOT=%~dp0..\\content"\r\nnode "%~dp0codex-ultra.mjs" %*\r\nexit /b %ERRORLEVEL%\r\n', - "codex-ultra.ps1": "#!/usr/bin/env pwsh\n$env:NODE_USE_ENV_PROXY = '1'\n$env:CODEX_CCU_CONTENT_ROOT = Join-Path $PSScriptRoot '..\\content'\n& node (Join-Path $PSScriptRoot 'codex-ultra.mjs') @args\nexit $LASTEXITCODE\n" + "codex.cmd": '@echo off\r\nif not defined CODEX_HOME set "CODEX_HOME=%USERPROFILE%\\.codex"\r\nnode "%~dp0launcher.mjs" %*\r\nexit /b %ERRORLEVEL%\r\n', + "codex.ps1": "#!/usr/bin/env pwsh\nif (-not $env:CODEX_HOME -and $env:USERPROFILE) { $env:CODEX_HOME = Join-Path $env:USERPROFILE '.codex' }\n& node (Join-Path $PSScriptRoot 'launcher.mjs') @args\nexit $LASTEXITCODE\n", + "codex-ultra.cmd": '@echo off\r\nif not defined CODEX_HOME set "CODEX_HOME=%USERPROFILE%\\.codex"\r\nset "NODE_USE_ENV_PROXY=1"\r\nset "CODEX_CCU_CONTENT_ROOT=%~dp0..\\content"\r\nnode "%~dp0codex-ultra.mjs" %*\r\nexit /b %ERRORLEVEL%\r\n', + "codex-ultra.ps1": "#!/usr/bin/env pwsh\nif (-not $env:CODEX_HOME -and $env:USERPROFILE) { $env:CODEX_HOME = Join-Path $env:USERPROFILE '.codex' }\n$env:NODE_USE_ENV_PROXY = '1'\n$env:CODEX_CCU_CONTENT_ROOT = Join-Path $PSScriptRoot '..\\content'\n& node (Join-Path $PSScriptRoot 'codex-ultra.mjs') @args\nexit $LASTEXITCODE\n" }); const POSIX_WRAPPERS = Object.freeze({ codex: `#!/bin/sh set -eu script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +export CODEX_HOME="\${CODEX_HOME:-$HOME/.codex}" exec node "$script_dir/launcher.mjs" "$@" `, "codex-ultra": `#!/bin/sh set -eu script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) default_content_root=$(CDPATH= cd -- "$script_dir/../content" && pwd) +export CODEX_HOME="\${CODEX_HOME:-$HOME/.codex}" export NODE_USE_ENV_PROXY=1 export CODEX_CCU_CONTENT_ROOT="\${CODEX_CCU_CONTENT_ROOT:-$default_content_root}" exec node "$script_dir/codex-ultra.mjs" "$@" diff --git a/test/platform.test.mjs b/test/platform.test.mjs index 7fc0e2d..e9d5260 100644 --- a/test/platform.test.mjs +++ b/test/platform.test.mjs @@ -19,6 +19,7 @@ import { const LINUX = resolveRuntimePlatform({ platform: "linux", arch: "x64" }); const LINUX_ARM = resolveRuntimePlatform({ platform: "linux", arch: "arm64" }); const MAC_ARM = resolveRuntimePlatform({ platform: "darwin", arch: "arm64" }); +const WINDOWS = resolveRuntimePlatform({ platform: "win32", arch: "x64" }); const execFileAsync = promisify(execFile); test("runtime platform descriptors cover Linux and both macOS architectures", () => { @@ -163,6 +164,38 @@ test("Linux launch selection accepts only the platform-specific installed layout ); }); +test("Windows wrappers default every CCU entry point to one Codex home", async () => { + const root = await mkdtemp(join(tmpdir(), "ccu-windows-bin-")); + try { + const managerSource = join(root, "manager-source.mjs"); + const launcherSource = join(root, "launcher-source.mjs"); + const binDirectory = join(root, "bin"); + await Promise.all([ + writeFile(managerSource, ""), + writeFile(launcherSource, "") + ]); + await installManagementBin({ + runtime: WINDOWS, + binDirectory, + managerSource, + launcherSource + }); + + for (const name of ["codex.cmd", "codex-ultra.cmd"]) { + const wrapper = await readFile(join(binDirectory, name), "utf8"); + assert.match(wrapper, /if not defined CODEX_HOME/); + assert.match(wrapper, /%USERPROFILE%\\\.codex/); + } + for (const name of ["codex.ps1", "codex-ultra.ps1"]) { + const wrapper = await readFile(join(binDirectory, name), "utf8"); + assert.match(wrapper, /-not \$env:CODEX_HOME/); + assert.match(wrapper, /Join-Path \$env:USERPROFILE '\.codex'/); + } + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + test("POSIX management wrappers are executable and forward arguments", async () => { const root = await mkdtemp(join(tmpdir(), "ccu-posix-bin-")); try { @@ -187,6 +220,7 @@ test("POSIX management wrappers are executable and forward arguments", async () const wrapper = await readFile(join(binDirectory, "codex"), "utf8"); assert.match(wrapper, /^#!\/bin\/sh/); assert.match(wrapper, /"\$@"/); + assert.match(wrapper, /CODEX_HOME=/); if (process.platform !== "win32") { assert.equal((await stat(join(binDirectory, "codex"))).mode & 0o111, 0o111); } @@ -194,6 +228,7 @@ test("POSIX management wrappers are executable and forward arguments", async () join(binDirectory, "codex-ultra"), "utf8" ); + assert.match(managerWrapper, /CODEX_HOME=/); assert.match(managerWrapper, /CODEX_CCU_CONTENT_ROOT/); if (process.platform !== "win32") { const launcherRun = await execFileAsync(join(binDirectory, "codex"), [ From 61a97acb2f8557567514c488a76841603e3841a8 Mon Sep 17 00:00:00 2001 From: Cecic <1518585189@qq.com> Date: Tue, 25 Aug 2026 15:39:08 +0800 Subject: [PATCH 9/9] fix(ci): install rustfmt on unix runners --- .github/workflows/ci.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 074ce8f..6d4dcff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: toolchain: "1.96.1" + components: rustfmt - run: npm ci - name: Verify stable multiplatform Release contract run: node --test test/workflow-sync-channel.test.mjs @@ -60,6 +61,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: toolchain: "1.96.1" + components: rustfmt - run: npm ci - name: Verify cross-platform runtime contracts run: node --test test/platform.test.mjs test/installer/posix-path.test.mjs test/install-script.test.mjs test/update-upgrade.test.mjs